Ejemplo n.º 1
0
  public CreateJournalEntry(
      TravelLogDAO dao,
      Journal journal,
      BindingResult result,
      boolean preload,
      ModelMap map,
      Logger logger) {

    // If we're preloading the sample, just skip to the preload method
    if (preload) {
      preloadJournal(dao, logger);
    } else {
      if (journal.getTitle().length() == 0) {
        result.reject("title", "Title cannot be blank");
      }

      // check to make sure we don't already have a journal
      if (dao.getJournals().size() > 0) {
        result.reject("title", "Journal already exists.  Please reload page.");
      }

      if (!result.hasErrors()) {
        dao.saveJournal(journal);
      }
    }
  }
  @RequestMapping(method = RequestMethod.POST)
  public String update(
      @PathVariable String language,
      @Validated @ModelAttribute(FORM_MODEL_KEY) GoogleAnalyticsUpdateForm form,
      BindingResult errors,
      @AuthenticationPrincipal AuthorizedUser authorizedUser,
      RedirectAttributes redirectAttributes) {
    redirectAttributes.addFlashAttribute(FORM_MODEL_KEY, form);
    redirectAttributes.addFlashAttribute(ERRORS_MODEL_KEY, errors);

    if (errors.hasErrors()) {
      return "redirect:/_admin/{language}/analytics/edit?step.edit";
    }

    GoogleAnalyticsUpdateRequest request = new GoogleAnalyticsUpdateRequest();
    request.setBlogId(Blog.DEFAULT_ID);
    request.setTrackingId(form.getTrackingId());
    request.setProfileId(form.getProfileId());
    request.setCustomDimensionIndex(form.getCustomDimensionIndex());
    request.setServiceAccountId(form.getServiceAccountId());
    request.setServiceAccountP12File(form.getServiceAccountP12File());

    GoogleAnalytics updatedGoogleAnalytics;
    try {
      updatedGoogleAnalytics = blogService.updateGoogleAnalytics(request);
    } catch (GoogleAnalyticsException e) {
      errors.reject("GoogleAnalytics");
      return "redirect:/_admin/{language}/analytics/edit?step.edit";
    }

    redirectAttributes.getFlashAttributes().clear();
    redirectAttributes.addFlashAttribute("updatedGoogleAnalytics", updatedGoogleAnalytics);
    return "redirect:/_admin/{language}/analytics";
  }
Ejemplo n.º 3
0
  @RequestMapping(value = "/apply", method = RequestMethod.POST)
  public String applyGiftCard(
      HttpServletRequest request,
      HttpServletResponse response,
      Model model,
      @ModelAttribute("orderInfoForm") OrderInfoForm orderInfoForm,
      @ModelAttribute("shippingInfoForm") ShippingInfoForm shippingForm,
      @ModelAttribute("billingInfoForm") BillingInfoForm billingForm,
      @ModelAttribute("giftCardInfoForm") GiftCardInfoForm giftCardInfoForm,
      BindingResult result) {
    Order cart = CartState.getCart();

    giftCardInfoFormValidator.validate(giftCardInfoForm, result);
    if (!result.hasErrors()) {
      result.reject(
          "giftCardNumber",
          "The Gift Card module is not enabled. Please contact us for more information about our AccountCredit Module (http://www.broadleafcommerce.com/contact)");
    }

    if (!(cart instanceof NullOrderImpl)) {
      model.addAttribute(
          "orderMultishipOptions",
          orderMultishipOptionService.getOrGenerateOrderMultishipOptions(cart));
      model.addAttribute("paymentRequestDTO", dtoTranslationService.translateOrder(cart));
    }

    populateModelWithReferenceData(request, model);

    return getCheckoutView();
  }
Ejemplo n.º 4
0
  /**
   * Valida un objeto a partir de un validador concreto. <br>
   * El validador debe extender la clase Validator y soportar (verificado mediante el método
   * supports) el objeto a validar. Si no, lanza una IllegalArgumentException. <br>
   * El validador puede tener anotaciones de dependencias de Spring.
   *
   * @see com.lynxspa.sdm.web.services.validation.Validator
   * @see BindingResult#hasFieldErrors()
   * @param object El objeto a validar
   * @param validator El validador a utilizar.
   * @param BindingResult El resultado de la validación, es un objeto BindingResult de Spring. Para
   *     verificar que no hay errores de validación hay que llamar al método hasFieldErrors.
   * @param result
   */
  public void validate(Object object, Class<? extends Validator> validator, BindingResult result) {
    try {
      Validator v = validator.newInstance();
      ctxService.autowire(v);

      validate(object, v, result);
    } catch (IllegalArgumentException ex) {
      throw ex;
    } catch (Throwable ex) {
      logger.fatal(ex.getMessage(), ex);
      result.reject("unknown.validation.error");
    }
  }
Ejemplo n.º 5
0
 @RequestMapping(method = RequestMethod.POST, params = "bevestigen")
 String create(
     @Validated(Offerte.Stap2.class) Offerte offerte,
     BindingResult bindingResult,
     SessionStatus sessionStatus) {
   if (!offerte.getGazontypes().values().contains(true)) {
     bindingResult.reject("minstensEenGazonType");
   }
   if (bindingResult.hasErrors()) {
     return STAP2_VIEW;
   }
   logger.info("offerte versturen via e-mail");
   sessionStatus.setComplete();
   return REDIRECT_URL_NA_TOEVOEGEN;
 }
Ejemplo n.º 6
0
 @RequestMapping(value = "/login", method = RequestMethod.POST)
 public String login(@Valid @ModelAttribute("login") LoginForm loginForm, BindingResult result)
     throws SQLException, ClassNotFoundException {
   System.out.println("post : I am logging in.");
   if (result.hasErrors()) {
     result.reject("invalidLogin", "Invalid Email/Password. Please try again.");
     return "login";
   }
   if (!loginService.validateLoginForm(loginForm)) {
     return "login";
   }
   try {
     if (loginService.login(loginForm)) {
       return "redirect:successful_login.htm";
     } else {
       result.reject("invalidLogin", "Invalid Email/Password. Please try again.");
       return "login";
     }
   } catch (AuthenticationException e) {
     result.reject(
         "unableToLogin", "Login failed due to internal error. Please try again later. ");
   }
   return "login";
 }
Ejemplo n.º 7
0
  /**
   * 验证失败返回true
   *
   * @param m
   * @param result
   * @return
   */
  @Override
  protected boolean hasError(Sample m, BindingResult result) {
    Assert.notNull(m);

    // 字段错误 前台使用<es:showFieldError commandName="showcase/sample"/> 显示
    if (m.getBirthday() != null && m.getBirthday().after(new Date())) {
      // 前台字段名(前台使用[name=字段名]取得dom对象) 错误消息键。。
      result.rejectValue("birthday", "birthday.past");
    }

    // 全局错误 前台使用<es:showGlobalError commandName="showcase/sample"/> 显示
    if (m.getName().contains("admin")) {
      result.reject("name.must.not.admin");
    }

    return result.hasErrors();
  }
  @RequestMapping(value = "move", method = RequestMethod.POST)
  public String move(
      @Valid MovePhysicalPortCommand command,
      BindingResult result,
      RedirectAttributes redirectAttrs,
      Model model) {
    Optional<NbiPort> newPort = physicalPortService.findNbiPort(command.getNewPhysicalPort());

    Optional<PhysicalPort> oldPort = physicalPortService.find(command.getId());

    if (!newPort.isPresent() || !oldPort.isPresent()) {
      return "redirect:";
    }

    if (result.hasErrors()) {
      return renderMoveForm(oldPort.get(), model, redirectAttrs);
    }

    model.addAttribute("lastEventId", endPoints.getLastEventId());

    try {
      Collection<Reservation> reservations = nocService.movePort(oldPort.get(), newPort.get());

      ElementActionView disabledAction = new ElementActionView(false);

      Collection<ReservationView> reservationViews =
          reservations
              .stream()
              .map(
                  reservation ->
                      new ReservationView(
                          reservation, disabledAction, disabledAction, disabledAction))
              .collect(toList());

      messageManager.addInfoMessage(model, "label_physicalport_port_moved");

      model.addAttribute("list", reservationViews);

      return PAGE_URL + "/moveResult";
    } catch (OverlappingSubportAllocationException e) {
      result.reject(e.getMessage());
      return renderMoveForm(oldPort.get(), model, redirectAttrs);
    }
  }
Ejemplo n.º 9
0
  @RequestMapping(value = "{id}/delete", method = RequestMethod.POST)
  public String deleteSelfAndChildren(
      Model model,
      @ModelAttribute("m") M m,
      BindingResult result,
      RedirectAttributes redirectAttributes) {

    if (permissionList != null) {
      permissionList.assertHasDeletePermission();
    }

    if (m.isRoot()) {
      result.reject("您删除的数据中包含根节点,根节点不能删除");
      return deleteForm(m, model);
    }

    baseService.deleteSelfAndChild(m);
    redirectAttributes.addFlashAttribute(Constants.MESSAGE, "删除成功");
    return redirectToUrl(viewName("success"));
  }
 @PreAuthorize("hasAuthority('ADMIN')")
 @RequestMapping(value = "/admin/media/update", method = RequestMethod.POST)
 public String handleMediaUpdateForm(
     @Valid @ModelAttribute("media") Media media, BindingResult bindingResult) {
   LOGGER.debug("Processing media update form={}, bindingResult={}", media, bindingResult);
   if (bindingResult.hasErrors()) {
     // failed validation
     return "media/mediaupdate";
   }
   try {
     mediaService.update(media);
   } catch (DataIntegrityViolationException e) {
     // probably email already exists - very rare case when multiple admins are adding same user
     // at the same time and form validation has passed for more than one of them.
     LOGGER.warn("Exception occurred when trying to save media", e);
     bindingResult.reject("media.exists", "Media already exists");
     return "media/mediaupdate";
   }
   // ok, redirect
   return "redirect:/admin/media/list/" + media.getPage() + "/" + media.getType();
 }
Ejemplo n.º 11
0
  /**
   * POST method uses the password from the form and the openid from the session to authenticate the
   * user.
   *
   * @param data
   * @param errors
   * @param request
   * @return
   */
  @RequestMapping(method = RequestMethod.POST)
  public ModelAndView doPost(
      @ModelAttribute(LOGIN_COMMAND) OpenidLoginFormBean data,
      BindingResult errors,
      HttpServletRequest request) {

    final HttpSession session = request.getSession();

    // user openid is retrieved from the session
    final String openid =
        (String) request.getSession().getAttribute(OpenidPars.SESSION_ATTRIBUTE_OPENID);
    // user password is bound to the form backing object
    final String password = data.getPassword();
    if (LOG.isDebugEnabled())
      LOG.debug("Attempting authentication with openid=" + openid + " password="******"Authentication succeded");

      // redirect to openid server fir further processing
      final String redirect =
          serverUrl + "?" + OpenidPars.PARAMETER_STATUS + "=" + OpenidPars.PARAMETER_STATUS_VALUE;
      return new ModelAndView(new RedirectView(redirect, true));

    } else {

      // set session-scope authentication flag to FALSE
      session.setAttribute(OpenidPars.SESSION_ATTRIBUTE_AUTHENTICATED, Boolean.FALSE);
      if (LOG.isDebugEnabled()) LOG.debug("Authentication error");

      errors.reject("error.invalid", new Object[] {}, "Invalid OpenID and/or Password combination");
      return new ModelAndView(view);
    }
  }
Ejemplo n.º 12
0
  // page 205
  @RequestMapping(method = RequestMethod.POST)
  public String addSpitterFromForm(
      @Valid Spitter spitter,
      BindingResult bindingResult,
      @RequestParam(value = "image", required = false) // 接收文件上传
          MultipartFile image) {

    if (bindingResult.hasErrors()) {
      return "spitters/edit";
    }
    spitterService.saveSpitter(spitter);

    try {
      if (!image.isEmpty()) {
        validateImage(image);
        saveImage(spitter.getId() + ".jpg", image); // 保存图片文件
      }
    } catch (ImageUploadException e) {
      bindingResult.reject(e.getMessage());
      return "spitters/edit";
    }

    return "redirect:/spitters/" + spitter.getUsername();
  }
  @RequestMapping(method = RequestMethod.POST)
  public String create(
      @Valid CreatePhysicalPortCommand command,
      BindingResult result,
      RedirectAttributes redirectAttributes,
      Model model) {
    PhysicalPort physicalPort = physicalPortService.findByBodPortId(command.getBodPortId());
    if (physicalPort != null) {
      result.rejectValue("bodPortId", "validation.not.unique");
    }

    Optional<NbiPort> maybeNbiPort = physicalPortService.findNbiPort(command.getNmsPortId());
    if (!maybeNbiPort.isPresent()) {
      return "redirect:";
    }

    NbiPort nbiPort = maybeNbiPort.get();

    command.validate(nbiPort, bodEnvironment.getBodTopologyName(), result);

    if (result.hasErrors()) {
      model.addAttribute("interfaceTypes", availableInterfaceTypes(nbiPort));
      model.addAttribute("availableTopologies", physicalPortService.findTopologyNames());
      model.addAttribute("vlanRequired", nbiPort.isVlanRequired());
      model.addAttribute("createPhysicalPortCommand", command);

      return PAGE_URL + CREATE;
    }

    PhysicalPort port;
    switch (command.getInterfaceType()) {
      case E_NNI:
        port = createEnniPort(command, nbiPort);

        messageManager.addInfoFlashMessage(
            redirectAttributes, "info_physicalport_enni_created", port.getNocLabel());

        break;
      case UNI:
        UniPort uniPort = createUniPort(command, nbiPort);

        messageManager.addInfoFlashMessage(
            redirectAttributes,
            "info_physicalport_uni_created",
            uniPort.getNocLabel(),
            uniPort.getPhysicalResourceGroup().getName());

        port = uniPort;
        break;
      default:
        throw new IllegalArgumentException("unknown interface type " + command.getInterfaceType());
    }

    try {
      physicalPortService.save(port);
    } catch (OverlappingSubportAllocationException e) {
      result.reject(e.getMessage());
      model.addAttribute("interfaceTypes", availableInterfaceTypes(nbiPort));
      model.addAttribute("availableTopologies", physicalPortService.findTopologyNames());
      model.addAttribute("vlanRequired", nbiPort.isVlanRequired());
      model.addAttribute("createPhysicalPortCommand", command);

      return PAGE_URL + CREATE;
    }

    return redirectPortListPage(port);
  }
  /**
   * Save obs corresponding to given http servlet request, http servlet response, radiologyOrder,
   * obs, obs, obsErrors
   *
   * @param request the http servlet request with all parameters
   * @param response the http servlet response
   * @param radiologyOrder the corresponding radiology order
   * @param obs the obs
   * @param obsErrors the result of the parameter binding
   * @return ModelAndView populated with obs matching the given criteria
   * @should save obs with given parameters
   * @should return populated model and view if binding errors occur
   * @should return populated model and view if edit reason is empty and obs id not null
   * @should return populated model and view if edit reason is null and obs id not null
   * @should return redirecting model and view for not authenticated user
   * @should edit obs with edit reason and complex concept
   * @should edit obs with edit reason, complex concept and request which is an instance of
   *     multihttpserveletrequest
   * @should edit obs with edit reason concept not complex and request which is an instance of
   *     multihttpserveletrequest
   * @should populate model and view with obs occuring thrown APIException
   */
  @RequestMapping(
      value = "/module/radiology/radiologyObs.form",
      method = RequestMethod.POST,
      params = "saveObs")
  ModelAndView saveObs(
      HttpServletRequest request,
      HttpServletResponse response,
      @RequestParam(value = "editReason", required = false) String editReason,
      @RequestParam(value = "orderId", required = true) RadiologyOrder radiologyOrder,
      @ModelAttribute("obs") Obs obs,
      BindingResult obsErrors) {

    HttpSession httpSession = request.getSession();

    new ObsValidator().validate(obs, obsErrors);

    if (obsErrors.hasErrors()) {
      return populateModelAndView(radiologyOrder, obs);
    }
    if (Context.isAuthenticated()) {

      try {
        // if the user is just editing the obs
        if (obs.getObsId() != null && (editReason == null || editReason.isEmpty())) {
          obsErrors.reject("editReason", "Obs.edit.reason.empty");

          return populateModelAndView(radiologyOrder, obs);
        }

        if (obs.getConcept().isComplex()) {
          if (request instanceof MultipartHttpServletRequest) {
            MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
            MultipartFile complexDataFile = multipartRequest.getFile("complexDataFile");
            if (complexDataFile != null && !complexDataFile.isEmpty()) {
              InputStream complexDataInputStream = complexDataFile.getInputStream();

              ComplexData complexData =
                  new ComplexData(complexDataFile.getOriginalFilename(), complexDataInputStream);

              obs.setComplexData(complexData);

              // the handler on the obs.concept is called
              // with
              // the given complex data
              obsService.saveObs(obs, editReason);
              updateReadingPhysician(radiologyOrder.getStudy());
              complexDataInputStream.close();
            }
          }
        } else {
          obsService.saveObs(obs, editReason);
          updateReadingPhysician(radiologyOrder.getStudy());
        }
        httpSession.setAttribute(WebConstants.OPENMRS_MSG_ATTR, "Obs.saved");
      } catch (APIException e) {
        httpSession.setAttribute(WebConstants.OPENMRS_ERROR_ATTR, e.getMessage());
        return populateModelAndView(radiologyOrder, obs);
      } catch (IOException e) {
        return populateModelAndView(radiologyOrder, obs);
      }
    }
    return new ModelAndView(
        "redirect:"
            + RADIOLOGY_OBS_FORM_URL
            + "orderId="
            + obs.getOrder().getId()
            + "&obsId="
            + obs.getId());
  }