コード例 #1
0
 /**
  * 处理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;
   }
 }
コード例 #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";
    }
  }
コード例 #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);
  }
コード例 #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()));
 }
コード例 #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);
  }
コード例 #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()));
 }
コード例 #7
0
  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;
  }
コード例 #8
0
 /**
  * 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);
 }
コード例 #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;
  }
コード例 #10
0
ファイル: Dispatcher.java プロジェクト: faithyee/Struts2
  /**
   * 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
    }
  }
コード例 #11
0
ファイル: TranslationServlet.java プロジェクト: Eljah/jamwiki
 /**
  * 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;
 }
コード例 #12
0
ファイル: GmailMailer.java プロジェクト: ulisseslima/ptah
  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;
  }
コード例 #13
0
  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;
  }
コード例 #14
0
ファイル: GmailMailer.java プロジェクト: ulisseslima/ptah
 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;
 }
コード例 #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);
   }
 }
コード例 #16
0
ファイル: EditServlet.java プロジェクト: Eljah/jamwiki
 /** 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");
 }
コード例 #17
0
ファイル: Dispatcher.java プロジェクト: phani6292/struts
  /**
   * 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
    }
  }
コード例 #18
0
  @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());
  }
コード例 #19
0
ファイル: SignupController.java プロジェクト: hotmob/passport
 @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";
   }
 }
コード例 #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);
    }
  }
コード例 #21
0
ファイル: UIUtil.java プロジェクト: divinoirj/DSpaceOSUKB
  /**
   * 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;
  }
コード例 #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;
 }
コード例 #23
0
  /**
   * @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;
  }
コード例 #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());
 }
コード例 #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());
 }
コード例 #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());
 }
コード例 #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());
 }
コード例 #28
0
 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);
   }
 }
コード例 #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;
    }
  }
コード例 #30
0
ファイル: PaginationTag.java プロジェクト: Eljah/jamwiki
 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;
 }