/**
  * 处理Service返回状态
  *
  * @param status
  * @param request
  * @param response
  * @param session
  * @throws IOException
  */
 private void handleStatus(
     int status, HttpServletRequest request, HttpServletResponse response, HttpSession session)
     throws IOException {
   switch (status) {
     case GroupService.OWNER_CAN_NOT_DROP_OUT:
       WebUtils.setResponseMessage(
           response,
           "error",
           "handlegroupmember_owner_not_deleted",
           session.getId(),
           request.getLocale());
       break;
     case GroupService.SUCCESS:
       WebUtils.setResponseBean(response, "success", null, session.getId(), request.getLocale());
       break;
     case GroupService.UID_NOT_OWNER:
       WebUtils.setResponseMessage(
           response, "error", "handlegroupmember_not_owner", session.getId(), request.getLocale());
       break;
     case GroupService.USER_NOT_INT_GROUP:
       WebUtils.setResponseMessage(
           response,
           "error",
           "handlegroupmember_user_not_in_group",
           session.getId(),
           request.getLocale());
       break;
     default:
       break;
   }
 }
Ejemplo n.º 2
0
  @RequestMapping(value = "/roleform.html", method = RequestMethod.POST)
  public String guardarRole(
      @ModelAttribute("role") Role role,
      BindingResult result,
      SessionStatus status,
      HttpServletRequest request,
      Model model) {

    try {

      if (result.hasErrors()) {
        model.addAttribute("role", role);
        return "/admin/roleform";
      }

      roleManager.saveRole(role);
      updateRoleSecurity(role);
      saveMessage(request, getText("roleform.added", role.getName(), request.getLocale()));
      return "redirect:rolelist.html";

    } catch (Exception e) {

      if (role.getId() != null) {
        return "redirect:roleform.html?from=list&id=" + role.getId();
      }
      model.addAttribute("role", role);
      saveError(request, getText("errors.general", request.getLocale()));
      return "redirect:roleform.html";
    }
  }
Ejemplo n.º 3
0
  private void enviaCorreo(String tipo, List<Almacen> almacenes, HttpServletRequest request)
      throws JRException, MessagingException {
    log.debug("Enviando correo {}", tipo);
    byte[] archivo = null;
    String tipoContenido = null;
    switch (tipo) {
      case "PDF":
        archivo = generaPdf(almacenes);
        tipoContenido = "application/pdf";
        break;
      case "CSV":
        archivo = generaCsv(almacenes);
        tipoContenido = "text/csv";
        break;
      case "XLS":
        archivo = generaXls(almacenes);
        tipoContenido = "application/vnd.ms-excel";
    }

    MimeMessage message = mailSender.createMimeMessage();
    MimeMessageHelper helper = new MimeMessageHelper(message, true);
    helper.setTo(ambiente.obtieneUsuario().getUsername());
    String titulo = messageSource.getMessage("almacen.lista.label", null, request.getLocale());
    helper.setSubject(
        messageSource.getMessage(
            "envia.correo.titulo.message", new String[] {titulo}, request.getLocale()));
    helper.setText(
        messageSource.getMessage(
            "envia.correo.contenido.message", new String[] {titulo}, request.getLocale()),
        true);
    helper.addAttachment(titulo + "." + tipo, new ByteArrayDataSource(archivo, tipoContenido));
    mailSender.send(message);
  }
Ejemplo n.º 4
0
 @RequestMapping(value = "/user/resendRegistrationToken", method = RequestMethod.GET)
 @ResponseBody
 public GenericResponse resendRegistrationToken(
     final HttpServletRequest request, @RequestParam("token") final String existingToken) {
   final VerificationToken newToken = userService.generateNewVerificationToken(existingToken);
   final User user = userService.getUser(newToken.getToken());
   mailSender.send(
       constructResendVerificationTokenEmail(
           getAppUrl(request), request.getLocale(), newToken, user));
   return new GenericResponse(
       messages.getMessage("message.resendToken", null, request.getLocale()));
 }
Ejemplo n.º 5
0
  /**
   * メッセージリソースに対してメッセージキーを指定することで エラーメッセージを取得する。
   *
   * @param req HTTPリクエスト
   * @param se SystemException
   * @param resources メッセージリソース
   * @return エラーメッセージ
   */
  private String getErrorMessage(
      HttpServletRequest req, SystemException se, MessageResources resources) {
    String errorCode = se.getErrorCode();
    // メッセージキーが指定されていないとき、nullを返却する。
    if (errorCode == null) {
      return null;
    }

    String[] options = se.getOptions();
    if (options == null) {
      return resources.getMessage(req.getLocale(), errorCode);
    }
    return resources.getMessage(req.getLocale(), errorCode, options);
  }
Ejemplo n.º 6
0
 // Reset password
 @RequestMapping(value = "/user/resetPassword", method = RequestMethod.POST)
 @ResponseBody
 public GenericResponse resetPassword(
     final HttpServletRequest request, @RequestParam("email") final String userEmail) {
   final User user = userService.findUserByEmail(userEmail);
   if (user == null) {
     throw new UserNotFoundException();
   }
   final String token = UUID.randomUUID().toString();
   userService.createPasswordResetTokenForUser(user, token);
   mailSender.send(constructResetTokenEmail(getAppUrl(request), request.getLocale(), token, user));
   return new GenericResponse(
       messages.getMessage("message.resetPasswordEmail", null, request.getLocale()));
 }
  private Map listPermissions(HttpServletRequest request) {
    Map map = new LinkedHashMap();
    map.put(
        new Integer(BasePermission.ADMINISTRATION.getMask()),
        getApplicationContext()
            .getMessage("select.administer", null, "Administer", request.getLocale()));
    map.put(
        new Integer(BasePermission.READ.getMask()),
        getApplicationContext().getMessage("select.read", null, "Read", request.getLocale()));
    map.put(
        new Integer(BasePermission.DELETE.getMask()),
        getApplicationContext().getMessage("select.delete", null, "Delete", request.getLocale()));

    return map;
  }
 /**
  * Handles GET request for the register page.
  *
  * @param message non-null but optional message to show on the page
  */
 private void doRegisterGet(HttpServletRequest req, HttpServletResponse resp, String message)
     throws IOException {
   RobotRegistrationPage.write(
       resp.getWriter(), new GxpContext(req.getLocale()), domain, message, analyticsAccount);
   resp.setContentType("text/html");
   resp.setStatus(HttpServletResponse.SC_OK);
 }
Ejemplo n.º 9
0
  /**
   * Performs a search on the site search index using the current host in the request Sample usage
   * from velocity:
   *
   * <pre>{@code
   * #set($searchresults = $sitesearch.search("dotcms",null,0,10,$request))
   * #set($hitsdetail = $searchresults.getDetails())
   * #set($summaries = $searchresults.getSummaries())
   * #foreach ($i in [0..$math.sub($searchresults.getEnd(),1)])
   *    $hitsdetail.get($i).getValue("title")
   *    $hitsdetail.get($i).getValue("url")
   *    $summaries.get($i).toHtml(true)
   * #end
   * }</pre>
   *
   * @param query String to search for
   * @param sort Property to sort the results
   * @param start Start row
   * @param rows Number of rows to return (10 by default)
   * @param request
   * @return DotSearchResults
   * @throws IOException
   */
  public DotSearchResults search(
      String query, String sort, int start, int rows, HttpServletRequest request)
      throws IOException {

    Host host = null;

    try {
      host = hostWebAPI.getCurrentHost(request);
    } catch (Exception e) {
      Logger.error(this, e.getMessage(), e);
      try {
        Logger.warn(this, "Error getting host from request, trying default host");
        host = hostWebAPI.findDefaultHost(userAPI.getSystemUser(), false);
      } catch (Exception e1) {
        Logger.error(this, e1.getMessage(), e1);
        throw new DotRuntimeException(e.getMessage(), e);
      }
    }

    Locale locale = (Locale) request.getSession().getAttribute(WebKeys.Globals_FRONTEND_LOCALE_KEY);
    String lang = request.getLocale().getLanguage();
    if (locale != null) {
      lang = locale.getLanguage();
    }

    DotSearchResults dsr =
        siteSearchAPI.search(query, sort, start, rows, lang, host.getIdentifier());

    dsr.setHost(host);
    dsr.setLang(lang);
    return dsr;
  }
Ejemplo n.º 10
0
  /**
   * Prepare a request, including setting the encoding and locale.
   *
   * @param request The request
   * @param response The response
   */
  public void prepare(HttpServletRequest request, HttpServletResponse response) {
    String encoding = null;
    if (defaultEncoding != null) {
      encoding = defaultEncoding;
    }
    // check for Ajax request to use UTF-8 encoding strictly
    // http://www.w3.org/TR/XMLHttpRequest/#the-send-method
    if ("XMLHttpRequest".equals(request.getHeader("X-Requested-With"))) {
      encoding = "UTF-8";
    }

    Locale locale = null;
    if (defaultLocale != null) {
      locale = LocalizedTextUtil.localeFromString(defaultLocale, request.getLocale());
    }

    if (encoding != null) {
      applyEncoding(request, encoding);
    }

    if (locale != null) {
      response.setLocale(locale);
    }

    if (paramsWorkaroundEnabled) {
      request.getParameter(
          "foo"); // simply read any parameter (existing or not) to "prime" the request
    }
  }
Ejemplo n.º 11
0
 /**
  * This method handles the request after its parent class receives control.
  *
  * @param request - Standard HttpServletRequest object.
  * @param response - Standard HttpServletResponse object.
  * @return A <code>ModelAndView</code> object to be handled by the rest of the Spring framework.
  */
 public ModelAndView handleRequestInternal(
     HttpServletRequest request, HttpServletResponse response) {
   ModelAndView next = new ModelAndView("wiki");
   try {
     if (!Utilities.isAdmin(request)) {
       String redirect = "Special:Translation";
       next.addObject(
           "errorMessage",
           Utilities.getMessage("admin.message.loginrequired", request.getLocale()));
       viewLogin(request, next, redirect);
       loadDefaults(request, next, this.pageInfo);
       return next;
     }
     String function = request.getParameter("function");
     if (!StringUtils.hasText(function)) {
       view(request, next);
     } else {
       translate(request, next);
     }
     next.addObject("translations", new TreeMap(this.translations));
     next.addObject("codes", this.retrieveTranslationCodes());
     if (request.getParameter("language") != null)
       next.addObject("language", request.getParameter("language"));
   } catch (Exception e) {
     viewError(request, next, e);
   }
   loadDefaults(request, next, this.pageInfo);
   return next;
 }
Ejemplo n.º 12
0
  public String getDefaultMessage(User user, String[] token, HttpServletRequest request)
      throws UnsupportedEncodingException {
    String escapedName = token[0].replace(" ", "+");
    String escapedToken = URLEncoder.encode(token[1], "UTF-8");
    String[] messageKeys = {"mail.welcome.m", "mail.instructions", "mail.end"};
    if (user.getGender().equals("F")) {
      messageKeys[0] = "mail.welcome.f";
    }
    String[] message = I18n.getStringsAsArray(request.getLocale(), messageKeys);
    emailMsgTxt =
        message[0]
            + " "
            + SERVER_NAME
            + ", "
            + user.getName()
            + message[1]
            + DOMAIN
            + "/SignupConfirmation?id="
            + escapedName
            + "@"
            + escapedToken
            + "@"
            + token[2]
            + "&action=confirm"
            + message[2]
            + " "
            + SERVER_NAME;

    return emailMsgTxt;
  }
  private Map<String, Object> discoverAndSetParameters(
      IReportRunnable report, HttpServletRequest request) throws Throwable {

    Map<String, Object> parms = new HashMap<String, Object>();
    IGetParameterDefinitionTask task = birtEngine.createGetParameterDefinitionTask(report);
    @SuppressWarnings("unchecked")
    Collection<IParameterDefnBase> params = task.getParameterDefns(true);
    for (IParameterDefnBase param : params) {
      Assert.isInstanceOf(
          IScalarParameterDefn.class,
          param,
          "the parameter must be assignable to " + IScalarParameterDefn.class.getName());
      IScalarParameterDefn scalar = (IScalarParameterDefn) param;
      if (this.reportParameters != null && this.reportParameters.get(param.getName()) != null) {
        String format = scalar.getDisplayFormat();
        // todo will this step on the Spring MVC converters?
        ReportParameterConverter converter =
            new ReportParameterConverter(format, request.getLocale());

        Object value = this.reportParameters.get(param.getName());
        parms.put(param.getName(), value);

        //                       /* converter.parse(*/  this.reportParameters.get(param.getName()),
        // scalar.getDataType()/*)*/);
      } else if (StringUtils.hasText(getParameter(request, param.getName()))) {
        parms.put(param.getName(), getParamValueObject(request, scalar));
      }
    }
    task.close();
    return parms;
  }
Ejemplo n.º 14
0
 public String getPasswordResetMessage(
     User user, String[] token, String requestInfo, HttpServletRequest request)
     throws UnsupportedEncodingException {
   String escapedName = token[0].replace(" ", "+");
   String escapedToken = URLEncoder.encode(token[1], "UTF-8");
   String[] messageKeys = {
     "user.request.mail.Greeting",
     "user.request.PasswordReset",
     "user.request.passwordReset.Confirm",
     "user.request.mail.End"
   };
   String[] message = I18n.getStringsAsArray(request.getLocale(), messageKeys);
   passwordResetMsg =
       message[0]
           + user.getName()
           + message[1]
           + requestInfo
           + message[2]
           + DOMAIN
           + "/PasswordReset?id="
           + escapedName
           + "@"
           + escapedToken
           + "&action=confirm"
           + message[3]
           + " "
           + SERVER_NAME;
   return passwordResetMsg;
 }
Ejemplo n.º 15
0
 protected void executeLogic(
     ActionMapping mapping,
     ActionForm form,
     HttpServletRequest request,
     HttpServletResponse response)
     throws Exception {
   AccountFB fb = (AccountFB) form;
   UserAccount account =
       (UserAccount) getEnvironment().getEntityFactory().create("gallery-useraccount");
   PropertyUtils.copyProperties(account, fb);
   getEnvironment().getEntityStorageFactory().getStorage("gallery-useraccount").store(account);
   if (account.getStylesheet() != null && account.getStylesheet().length() > 0) {
     request.getSession().setAttribute("stylesheetPB", account.getStylesheet());
   } else {
     request.getSession().removeAttribute("stylesheetPB");
   }
   if (account.getUsername().equals(request.getRemoteUser())) {
     boolean useEnglish =
         !request
             .getLocale()
             .getLanguage()
             .equals(getEnvironment().getConfigurableResources().getParameter("nativelanguage"));
     String title = account.getTitle();
     if (useEnglish && StringUtil.asNull(account.getTitleEnglish()) != null) {
       title = account.getTitleEnglish();
     }
     request.getSession().setAttribute("titlePB", title);
   }
 }
Ejemplo n.º 16
0
 /** Functionality to handle the "Show Changes" button being clicked. */
 private void showChanges(
     HttpServletRequest request,
     ModelAndView next,
     WikiPageInfo pageInfo,
     String virtualWiki,
     String topicName,
     Integer lastTopicVersionId)
     throws Exception {
   String contents1 = request.getParameter("contents");
   String contents2 = "";
   if (!StringUtils.isBlank(request.getParameter("section"))) {
     // editing a section of a topic
     int section = Integer.valueOf(request.getParameter("section"));
     String[] sliceResults =
         ParserUtil.parseSlice(
             request.getContextPath(), request.getLocale(), virtualWiki, topicName, section);
     contents2 = sliceResults[1];
   } else if (lastTopicVersionId != null) {
     // get the full topic version
     TopicVersion lastTopicVersion =
         WikiBase.getDataHandler().lookupTopicVersion(lastTopicVersionId);
     contents2 = lastTopicVersion.getVersionContent();
   }
   this.loadDiff(request, next, pageInfo, contents1, contents2);
   next.addObject("editShowChanges", "true");
 }
Ejemplo n.º 17
0
  /**
   * Prepare a request, including setting the encoding and locale.
   *
   * @param request The request
   * @param response The response
   */
  public void prepare(HttpServletRequest request, HttpServletResponse response) {
    String encoding = null;
    if (defaultEncoding != null) {
      encoding = defaultEncoding;
    }

    Locale locale = null;
    if (defaultLocale != null) {
      locale = LocalizedTextUtil.localeFromString(defaultLocale, request.getLocale());
    }

    if (encoding != null) {
      try {
        request.setCharacterEncoding(encoding);
      } catch (Exception e) {
        LOG.error("Error setting character encoding to '" + encoding + "' - ignoring.", e);
      }
    }

    if (locale != null) {
      response.setLocale(locale);
    }

    if (paramsWorkaroundEnabled) {
      request.getParameter(
          "foo"); // simply read any parameter (existing or not) to "prime" the request
    }
  }
  @Override
  protected ModelAndView onSubmit(
      HttpServletRequest request, HttpServletResponse response, Object object, BindException errors)
      throws Exception {
    AnagraficaObjectDTO anagraficaObjectDTO = (AnagraficaObjectDTO) object;

    if (request.getParameter("cancel") != null) {
      return new ModelAndView(listView);
    }

    EO anagraficaObject;
    List<TP> tipProprieta;
    if (anagraficaObjectDTO.getObjectId() != null) {
      anagraficaObject =
          applicationService.get(clazzAnagraficaObject, anagraficaObjectDTO.getObjectId());
      tipProprieta =
          applicationService.getListTipologieProprietaFirstLevel(clazzTipologiaProprieta);
    } else {
      anagraficaObject = clazzAnagraficaObject.newInstance();
      tipProprieta = applicationService.getTipologiaOnCreation(clazzTipologiaProprieta);
    }

    AnagraficaUtils.reverseDTO(anagraficaObjectDTO, anagraficaObject, tipProprieta);

    anagraficaObject.pulisciAnagrafica();
    applicationService.saveOrUpdate(clazzAnagraficaObject, anagraficaObject);
    saveMessage(request, getText("action.anagrafica.edited", request.getLocale()));

    return new ModelAndView(detailsView, "id", anagraficaObject.getId());
  }
Ejemplo n.º 19
0
 @RequestMapping(
     method = RequestMethod.POST,
     params = {"bind", "step!=1"})
 public String onBindSubmit(
     UserForm userForm,
     BindingResult errors,
     WebRequest webRequest,
     HttpServletRequest request,
     HttpServletResponse response)
     throws Exception {
   try {
     if (StringUtils.hasText(userForm.getConfirmPassword())) { // New User, Signup !
       onSubmit(userForm, errors, request, response);
     } else {
       SecurityContext.addCasSignin(
           centralAuthenticationService,
           ticketGrantingTicketCookieGenerator,
           userForm.getUsername(),
           userForm.getPassword(),
           false,
           false,
           response);
     }
     ProviderSignInUtils.handlePostSignUp(userForm.getUsername(), webRequest);
     return "redirect:/";
   } catch (Exception e) {
     e.fillInStackTrace();
     log.warn(e.getMessage());
     saveError(request, getText("bind.error.signup", request.getLocale()));
     return "signup";
   }
 }
Ejemplo n.º 20
0
  @Override
  protected void doPost(HttpServletRequest req, HttpServletResponse resp)
      throws ServletException, IOException {
    final CreationClientForm form = new CreationClientForm(req);
    req.setAttribute(RequestConstants.FORM_CREATION_CLIENT, form);
    form.validate();

    if (form.hasErrors()) {
      req.setAttribute("msgError", LangUtil.getMessage(req.getLocale(), "error.form"));
      req.getRequestDispatcher("jsp/creerClient.jsp").forward(req, resp);
    } else {
      final ClientDTO client =
          (ClientDTO)
              ConverterFactory.getInstance()
                  .getFormConverter(ClientFormConverter.class.getName())
                  .convertToDTO(form);

      // TODO revoir avec les BDD
      final String idClient = client.getNom();
      Map<String, ClientDTO> mapClients =
          (Map<String, ClientDTO>) req.getSession().getAttribute(SessionConstants.MAP_CLIENTS);
      if (mapClients == null) {
        mapClients = new HashMap<String, ClientDTO>();
        req.getSession().setAttribute(SessionConstants.MAP_CLIENTS, mapClients);
      }
      mapClients.put(idClient, client);

      req.setAttribute(RequestConstants.CURRENT_CLIENT, client);

      req.getRequestDispatcher("jsp/afficherClient.jsp").forward(req, resp);
    }
  }
Ejemplo n.º 21
0
  /**
   * Get the Locale for a session according to the user's language selection or language
   * preferences. Order of selection - language selected via UI - language as set by application -
   * language browser default
   *
   * @param request the request Object
   * @return supportedLocale Locale supported by this DSpace Instance for this request
   */
  public static Locale getSessionLocale(HttpServletRequest request) {

    String paramLocale = request.getParameter("locale");
    Locale sessionLocale = null;
    Locale supportedLocale = null;

    if (!StringUtils.isEmpty(paramLocale)) {
      /* get session locale according to user selection */
      sessionLocale = new Locale(paramLocale);
    }

    if (sessionLocale == null) {
      /* get session locale set by application */
      HttpSession session = request.getSession();
      sessionLocale = (Locale) Config.get(session, Config.FMT_LOCALE);
    }

    /*
     * if session not set by selection or application then default browser
     * locale
     */
    if (sessionLocale == null) {
      sessionLocale = request.getLocale();
    }

    if (sessionLocale == null) {
      sessionLocale = I18nUtil.DEFAULTLOCALE;
    }
    supportedLocale = I18nUtil.getSupportedLocale(sessionLocale);

    return supportedLocale;
  }
Ejemplo n.º 22
0
 /**
  * Determine the default locale for the given request, Called if no locale cookie has been found.
  *
  * <p>The default implementation returns the specified default locale, if any, else falls back to
  * the request's accept-header locale.
  *
  * @param request the request to resolve the locale for
  * @return the default locale (never <code>null</code>)
  * @see #setDefaultLocale
  * @see javax.servlet.http.HttpServletRequest#getLocale()
  */
 protected Locale determineDefaultLocale(HttpServletRequest request) {
   Locale defaultLocale = getDefaultLocale();
   if (defaultLocale == null) {
     defaultLocale = request.getLocale();
   }
   return defaultLocale;
 }
  /**
   * @see
   *     org.springframework.web.servlet.mvc.SimpleFormController#referenceData(javax.servlet.http.HttpServletRequest,
   *     java.lang.Object, org.springframework.validation.Errors)
   */
  protected Map<String, Object> referenceData(HttpServletRequest request, Object obj, Errors errs)
      throws Exception {

    Drug drug = (Drug) obj;

    Map<String, Object> map = new HashMap<String, Object>();
    String defaultVerbose = "false";

    if (Context.isAuthenticated()) {
      if (drug.getConcept() != null)
        map.put("conceptName", drug.getConcept().getName(request.getLocale()));
      defaultVerbose =
          Context.getAuthenticatedUser()
              .getUserProperty(OpenmrsConstants.USER_PROPERTY_SHOW_VERBOSE);
    }

    map.put("defaultVerbose", defaultVerbose.equals("true") ? true : false);

    String editReason = request.getParameter("editReason");
    if (editReason == null) editReason = "";

    map.put("editReason", editReason);

    return map;
  }
Ejemplo n.º 24
0
 @Test
 public void testGetJapanese() {
   when(mockReq.getLocale()).thenReturn(Locale.JAPAN);
   Provider<I18n> p = new I18nProvider(mockReq);
   I18n providedI18n = p.get();
   assertEquals(Locale.JAPAN, providedI18n.getLocale());
 }
Ejemplo n.º 25
0
 @Test
 public void testGetDefault() {
   when(mockReq.getLocale()).thenReturn(null);
   Provider<I18n> p = new I18nProvider(mockReq);
   I18n providedI18n = p.get();
   assertEquals(Locale.US, providedI18n.getLocale());
 }
Ejemplo n.º 26
0
 @Test
 public void testGetFrench() {
   when(mockReq.getLocale()).thenReturn(Locale.FRANCE);
   Provider<I18n> p = new I18nProvider(mockReq);
   I18n providedI18n = p.get();
   assertEquals(Locale.FRANCE, providedI18n.getLocale());
 }
Ejemplo n.º 27
0
 @Inject
 public RequestScopedLocale(
     HttpServletRequest request, @Named("app.locale.default") String language) {
   this.locale = request.getLocale();
   this.defaultLocale = new Locale.Builder().setLanguage(language).build();
   // LOGGER.debug("request locale {} {}", this.locale, this.locale.getLanguage());
 }
 private void initContextHolders(
     HttpServletRequest request, ServletRequestAttributes requestAttributes) {
   LocaleContextHolder.setLocale(request.getLocale(), this.threadContextInheritable);
   RequestContextHolder.setRequestAttributes(requestAttributes, this.threadContextInheritable);
   if (logger.isDebugEnabled()) {
     logger.debug("Bound request context to thread: " + request);
   }
 }
Ejemplo n.º 29
0
  @RequestMapping(value = "/eliminarrole.html")
  public String eliminarRole(
      @RequestParam(value = "id", required = false) Long id,
      HttpServletRequest request,
      Model model) {

    try {

      roleManager.removeRole(id);
      saveMessage(request, getText("roleform.deleted", request.getLocale()));
      return "redirect:rolelist.html";

    } catch (Exception e) {
      saveError(request, getText("errors.general", request.getLocale()));
      return "redirect:roleform.html?from=list&id=" + id;
    }
  }
Ejemplo n.º 30
0
 private StringBuffer nextPage(
     Pagination pagination, String baseUrl, int count, boolean previous) {
   HttpServletRequest request = (HttpServletRequest) this.pageContext.getRequest();
   StringBuffer output = new StringBuffer();
   try {
     Object[] objects = new Object[1];
     objects[0] = new Integer(pagination.getNumResults());
     if (pagination.getOffset() == 0 && previous) {
       output.append(
           Utilities.formatMessage("common.pagination.previous", request.getLocale(), objects));
       return output;
     }
     if (pagination.getNumResults() != count && !previous) {
       output.append(
           Utilities.formatMessage("common.pagination.next", request.getLocale(), objects));
       return output;
     }
     output.append("<a href=\"");
     String virtualWiki = Utilities.getVirtualWikiFromRequest(request);
     WikiLink wikiLink = LinkUtil.parseWikiLink(baseUrl);
     int offset = pagination.getOffset() + pagination.getNumResults();
     if (previous) {
       offset = pagination.getOffset() - pagination.getNumResults();
       if (offset < 0) offset = 0;
     }
     String query =
         LinkUtil.appendQueryParam(
             wikiLink.getQuery(), "num", new Integer(pagination.getNumResults()).toString());
     query += "&amp;offset=" + offset;
     wikiLink.setQuery(query);
     output.append(LinkUtil.buildInternalLinkUrl(request.getContextPath(), virtualWiki, wikiLink));
     output.append("\">");
     if (previous) {
       output.append(
           Utilities.formatMessage("common.pagination.previous", request.getLocale(), objects));
     } else {
       output.append(
           Utilities.formatMessage("common.pagination.next", request.getLocale(), objects));
     }
     output.append("</a>");
   } catch (Exception e) {
     logger.warning("Failure while building pagination element", e);
   }
   return output;
 }