Exemplo n.º 1
0
  /**
   * AJAX Called once user is submitting upload form
   *
   * @param model
   * @param file - Uploaded file
   * @param comment - Comment for uploaded file
   * @return
   */
  @RequestMapping(method = RequestMethod.POST)
  public @ResponseBody JsonResponse uploadAction(
      @Valid @ModelAttribute(value = "image") Image image,
      @RequestParam(value = "captcha_challenge", required = true) String challenge,
      @RequestParam(value = "captcha_response", required = true) String response,
      BindingResult result,
      HttpServletRequest paramHttpServletRequest) {
    JsonResponse jsonResponse = new JsonResponse();
    String remoteAddr = paramHttpServletRequest.getRemoteAddr();
    ReCaptchaResponse reCaptchaResponse = recaptcha.checkAnswer(remoteAddr, challenge, response);
    if (!reCaptchaResponse.isValid()) {
      jsonResponse.setCaptchaError(
          context.getMessage("error.bad.captcha", null, Locale.getDefault()));
      return jsonResponse;
    }

    prepareImage(image);
    (new ImageValidator()).validate(image, result);
    if (!result.hasErrors()) {
      try {
        image.setBytes(image.getFile().getBytes());
        image.setContentType(image.getFile().getContentType());
        image = imageService.saveImage(image);
        jsonResponse.setResponse(paramHttpServletRequest.getRequestURL() + image.getId());
      } catch (Exception e) {
        log.error(e.getMessage());
      }
    } else {
      for (ObjectError error : result.getAllErrors()) {
        jsonResponse.appendError(context.getMessage(error.getCode(), null, Locale.getDefault()));
      }
    }
    return jsonResponse;
  }
Exemplo n.º 2
0
  public static void main(String[] args) {
    ApplicationContext ac = new ClassPathXmlApplicationContext("bean.xml");

    String[] a = {"ЖСеп"};
    Object[] b = {new Date()};

    String hello = ac.getMessage("hello", a, Locale.getDefault());
    String now = ac.getMessage("now", b, Locale.getDefault());

    System.out.println(hello);
    System.out.println(now);
  }
Exemplo n.º 3
0
  @ExceptionHandler(value = {SolrException.class, SolrServerException.class})
  public void handleException(
      Exception ex, HttpServletRequest request, HttpServletResponse response) throws IOException {

    String msg;

    if (ex instanceof SolrException) {
      msg = ex.getLocalizedMessage();
      // Don't send the request as part of error msg
      int requestStart = msg.indexOf("request:");
      if (requestStart > 0) {
        msg = msg.substring(0, requestStart);
      }
    } else if (ex instanceof SolrServerException) {
      msg = appContext.getMessage("oai.solr.unavailable", null, Locale.getDefault());
    } else {
      msg = ex.getLocalizedMessage();
    }

    if (clientXsltHandler != null) {
      clientXsltHandler.sendErrorXml(response, msg, request.getRequestURL().toString());
      ex.printStackTrace();
    } else {
      response.sendError(HttpServletResponse.SC_SERVICE_UNAVAILABLE, msg);
    }
  }
Exemplo n.º 4
0
 private String fmt(String text, Object[] args) {
   String value = "";
   if (text == null) {
     return value;
   }
   Locale locale = m_user.getLocale();
   if (locale == null) {
     locale = Locale.getDefault();
   }
   return m_context.getMessage(text, args, "Not Found", locale);
 }
  /*
   * HuyNDN created on Feb 26, 2016
   */
  @Override
  public void save(PermissionDto permissionDto) {
    PermissionEntity entity = mapper.map(permissionDto, PermissionEntity.class);

    /*
     * Validate
     */
    // These 2 lines of code is to avoid the exception:
    // org.hibernate.TransientPropertyValueException: object references an unsaved transient
    // instance -
    // save the transient instance before flushing :
    // vn.com.splussoftware.sms.model.entity.auth.PermissionEntity.user
    // -> vn.com.splussoftware.sms.model.entity.auth.SMSUserEntity (or SMSGroupEntity).
    if (entity.getGroup().getId() == null) {
      entity.setGroup(null);
    } else {
      // Check if this group exists
      if (!groupRepository.exists(permissionDto.getGroupId())) {
        throw new EntityNotFoundException(
            applicationContext.getMessage(
                GroupServiceImpl.class.getName() + MessagePropertiesConstant.KEY_ENTITY_NOT_FOUND,
                new Object[] {permissionDto.getGroupId()},
                null));
      }
    }

    if (entity.getUser().getId() == null) {
      entity.setUser(null);
    } else {
      // Check if this user exists
      if (!userRepository.exists(permissionDto.getUserId())) {
        throw new EntityNotFoundException(
            applicationContext.getMessage(
                UserServiceImpl.class.getName() + MessagePropertiesConstant.KEY_ENTITY_NOT_FOUND,
                new Object[] {permissionDto.getGroupId()},
                null));
      }
    }

    // Check if there's any same permission exists.
    List<PermissionEntity> ePermissions =
        permissionRepo.findByUserIdAndGroupIdAndTargetTypeAndTargetIdAndPermission(
            permissionDto.getUserId(),
            permissionDto.getGroupId(),
            permissionDto.getTargetType(),
            permissionDto.getTargetId(),
            permissionDto.getPermission());
    if (ePermissions != null && !ePermissions.isEmpty()) {
      throw new EntityExistsException(
          applicationContext.getMessage(
              this.getClass().getName()
                  + MessagePropertiesConstant.KEY_PERMISSION_ALREADY_EXISTS, // Get message from
              // message/messages.properties
              new Object[] {ePermissions.get(0).getId()},
              applicationContext.getMessage(
                  MessagePropertiesConstant.KEY_DEFAULT,
                  null,
                  null), // Get default message from message/messages.properties
              // in case the required message would be not found.
              null));
    }

    permissionRepo.saveAndFlush(entity);
  }
Exemplo n.º 6
0
 protected void addErrorQuery(String errorType, SolrQuery query, Locale locale) {
   query.set(errorType, appContext.getMessage("error." + errorType, null, locale));
 }
Exemplo n.º 7
0
 /**
  * 鏍规嵁key 鏉ユ煡鎵�鍊�
  *
  * @param key
  * @return
  */
 public static String getMsgByKey(String key) {
   if (key == null | key.trim().length() <= 0) {
     return null;
   }
   return applicationContext.getMessage(key, null, Locale.getDefault());
 }
Exemplo n.º 8
0
 public String getMessage(String arg0, Object[] arg1, String arg2, Locale arg3) {
   return applicationContext.getMessage(arg0, arg1, arg2, arg3);
 }
Exemplo n.º 9
0
 public String getMessage(String arg0, Object[] arg1, Locale arg2) throws NoSuchMessageException {
   return applicationContext.getMessage(arg0, arg1, arg2);
 }
Exemplo n.º 10
0
 public String getMessage(MessageSourceResolvable arg0, Locale arg1)
     throws NoSuchMessageException {
   return applicationContext.getMessage(arg0, arg1);
 }
Exemplo n.º 11
0
/*
  /** Stores to persistence layer initial data. */
  @PostConstruct
  public void init() {
    if (roleRepository.findByName("ROLE_ADMIN") == null) {
      Role roleUser = new Role();
      roleUser.setName("ROLE_USER");
      roleRepository.save(roleUser);

      Role roleAdmin = new Role();
      roleAdmin.setName("ROLE_ADMIN");
      roleRepository.save(roleAdmin);

      User user = new User();
      user.setEnabled(true);
      user.setEmail("admin@admin");

      BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();
      user.setPassword(encoder.encode("admin"));
      List<Role> roles = new ArrayList<>();
      roles.add(roleAdmin);
      roles.add(roleUser);
      user.setRoles(roles);
      userRepository.save(user);

      // Create account for wallet
      Account walletAccount = new Account();
      walletAccount.setName(context.getMessage("Name.default.account", null, Locale.ENGLISH));
      walletAccount.setUser(user);
      walletAccount.setAmount(new BigDecimal(0));
      walletAccount.setCurrency(Currency.getInstance("UAH"));
      accountRepository.save(walletAccount);

      Account bankAccount = new Account();
      bankAccount.setName("Bank");
      bankAccount.setUser(user);
      bankAccount.setAmount(new BigDecimal(500));
      bankAccount.setCurrency(Currency.getInstance("UAH"));
      accountRepository.save(bankAccount);

      // Create categories for expenses
      for (int i = 1; i < 6; i++) {
        Category category = new Category();
        category.setName(
            context.getMessage("Name" + i + ".default.category", null, Locale.ENGLISH));
        category.setType(Operation.EXPENSE);
        category.setUser(user);
        categoryRepository.save(category);
      }

      // Create categories for incomes
      for (int i = 6; i < 8; i++) {
        Category category = new Category();
        category.setName(
            context.getMessage("Name" + i + ".default.category", null, Locale.ENGLISH));
        category.setType(Operation.INCOME);
        category.setUser(user);
        categoryRepository.save(category);
      }

      Transaction transaction1 = new Transaction();
      transaction1.setDate(new Date());
      transaction1.setAccount(walletAccount);
      transaction1.setAmount(new BigDecimal(50));
      transaction1.setCurrency(Currency.getInstance("UAH"));
      transaction1.setCategory(categoryRepository.findOne(3));
      transaction1.setType(Operation.EXPENSE);
      transaction1.setComment("McDonalds");
      transaction1.setUser(user);
      transactionRepository.save(transaction1);

      Transaction transaction2 = new Transaction();
      Calendar calendar = new GregorianCalendar();
      calendar.set(Calendar.MONTH, calendar.get(Calendar.MONTH) - 1);
      transaction2.setDate(calendar.getTime());
      transaction2.setAccount(bankAccount);
      transaction2.setAmount(new BigDecimal(45));
      transaction2.setCurrency(Currency.getInstance("UAH"));
      transaction2.setCategory(categoryRepository.findOne(7));
      transaction2.setType(Operation.INCOME);
      transaction2.setComment("Festo");
      transaction2.setUser(user);
      transactionRepository.save(transaction2);

      List<Transaction> transactions = new ArrayList<>();
      transactions.add(transaction1);
      user.setTransactions(transactions);
    }
  }
  /**
   * @see
   *     org.springframework.web.servlet.mvc.ParameterizableViewController#handleRequestInternal(javax.servlet.http.HttpServletRequest,
   *     javax.servlet.http.HttpServletResponse)
   */
  @SuppressWarnings("static-access")
  @Override
  protected ModelAndView handleRequestInternal(
      HttpServletRequest request, HttpServletResponse response) throws Exception {
    ModelAndView mav = new ModelAndView();
    mav.setViewName(getViewName());

    String startDate = "";

    String endDate = "";

    int year = (new Date()).getYear();
    int month = (new Date()).getMonth();

    PmtctService pmtct;
    List<Object> result = new ArrayList<Object>();
    String pageNumber = request.getParameter("page");

    List<Object> res;

    List<Integer> numberOfPages;

    //		config =
    // PMTCTConfiguration.getInstance(request.getRealPath(PMTCTConstants.CONFIGURATION_FILE_LOC));
    //		PMTCTConstants constants = config.getListOfConstants().get(0);
    //		request.getSession().setAttribute("enableModification", "" +
    // config.isModificationEnabled());

    request
        .getSession()
        .setAttribute("pmtctModuleConfigured", "" + PMTCTConfigurationUtils.isConfigured());

    try {
      if (null != request.getParameter("startDate")
          && "" != request.getParameter("startDate").trim()) {
        startDate = request.getParameter("startDate").trim();
      }
      if (null != request.getParameter("endDate") && "" != request.getParameter("endDate").trim()) {
        endDate = request.getParameter("endDate").trim();
      }
      //		}
      //		catch (Exception ex) {
      //			ex.printStackTrace();
      //		}
      //
      //		try {
      if (pageNumber.compareToIgnoreCase("1") == 0 || pageNumber.compareToIgnoreCase("") == 0) {
        pmtct = Context.getService(PmtctService.class);
        //				pmtct.setPMTCTProgrmaId(config.getConstants());
        res = new ArrayList<Object>();

        mav.addObject("monthsList", monthsList);

        if (request.getParameter("category").equalsIgnoreCase("cpn")) {
          if (request.getParameter("type").equalsIgnoreCase("1")) {
            if (startDate.compareTo("") != 0 && endDate.compareTo("") != 0) {
              res = pmtct.getGeneralStatsForPatientsInCPN(startDate, endDate);
              request.getSession().setAttribute("pat_in_cpn_res", res);
            }
            mav.addObject("listHeaderTitle", "pmtct.menu.generalStatsInCPN");
          } else if (request.getParameter("type").equalsIgnoreCase("2")) {
            if (request.getParameter("month") != null
                && request.getParameter("month").trim().compareTo("") != 0)
              month = Integer.parseInt(request.getParameter("month"));
            if (request.getParameter("year") != null
                && request.getParameter("year").trim().compareTo("") != 0)
              year = Integer.parseInt(request.getParameter("year"));

            res = pmtct.getPatientByMoisDeRapportageDPA(month, year);
            request.getSession().setAttribute("pat_in_cpn_res", res);
            mav.addObject(
                "listHeaderTitle", "pmtct.menu.patientWhoMoisDeRapportageDPAIsTheCurrentMois");
          } else if (request.getParameter("type").equalsIgnoreCase("3")) {
            res = pmtct.getCouplesDiscordant();
            request.getSession().setAttribute("pat_in_cpn_res", res);
            mav.addObject("listHeaderTitle", "pmtct.menu.couplesDiscordant");
          }
        }

        for (int i = 0; i < PMTCTConfigurationUtils.getNumberOfRecordPerPage(); i++) {
          if (res.size() == 0) break;
          if (i >= res.size() - 1) {
            result.add(res.get(i));
            break;
          } else result.add(res.get(i));
        }

        // paging
        int n =
            (res.size()
                    == ((int) (res.size() / PMTCTConfigurationUtils.getNumberOfRecordPerPage()))
                        * PMTCTConfigurationUtils.getNumberOfRecordPerPage())
                ? (res.size() / PMTCTConfigurationUtils.getNumberOfRecordPerPage())
                : ((int) (res.size() / PMTCTConfigurationUtils.getNumberOfRecordPerPage())) + 1;
        numberOfPages = new ArrayList<Integer>();
        for (int i = 1; i <= n; i++) {
          numberOfPages.add(i);
        }
        request.getSession().setAttribute("pat_in_cpn_numberOfPages", numberOfPages);
      } else {
        res = (List<Object>) request.getSession().getAttribute("pat_in_cpn_res");
        numberOfPages =
            (List<Integer>) request.getSession().getAttribute("pat_in_cpn_numberOfPages");
        for (int i =
                (PMTCTConfigurationUtils.getNumberOfRecordPerPage()
                    * (Integer.parseInt(pageNumber) - 1));
            i < PMTCTConfigurationUtils.getNumberOfRecordPerPage() * (Integer.parseInt(pageNumber));
            i++) {
          if (i >= res.size()) break;
          else result.add(res.get(i));
        }
      }

      // page infos
      Object[] pagerInfos = new Object[3];
      pagerInfos[0] =
          (res.size() == 0)
              ? 0
              : (PMTCTConfigurationUtils.getNumberOfRecordPerPage()
                      * (Integer.parseInt(pageNumber) - 1))
                  + 1;
      pagerInfos[1] =
          (PMTCTConfigurationUtils.getNumberOfRecordPerPage() * (Integer.parseInt(pageNumber))
                  <= res.size())
              ? PMTCTConfigurationUtils.getNumberOfRecordPerPage() * (Integer.parseInt(pageNumber))
              : res.size();
      pagerInfos[2] = res.size();

      ApplicationContext appContext = ContextProvider.getApplicationContext();

      mav.addObject(
          "pageInfos",
          appContext.getMessage(
              "pmtct.pagingInfo.showingResults", pagerInfos, Context.getUserContext().getLocale()));
      mav.addObject("numberOfPages", numberOfPages);
      mav.addObject("patientList", result);
      mav.addObject("pageSize", PMTCTConfigurationUtils.getNumberOfRecordPerPage());
      mav.addObject("startDate", startDate);
      mav.addObject("endDate", endDate);

      mav.addObject("hivTestResultId", PMTCTConstants.RESULT_OF_HIV_TEST);
      mav.addObject("dpaId", PMTCTConstants.PREGNANT_DUE_DATE);
      mav.addObject("dateOfConfinementId", PMTCTConstants.DATE_OF_CONFINEMENT);
      mav.addObject("positiveId", PMTCTConstants.POSITIVE);

      List<Integer> years = new ArrayList<Integer>();
      for (int yr = 2000; yr < 2016; yr++) years.add(yr);
      mav.addObject("years", years);

      FileExporter fexp = new FileExporter();

      if (request.getParameter("export") != null
          && request.getParameter("export").compareToIgnoreCase("csv") == 0) {
        if (request.getParameter("type").equalsIgnoreCase("1"))
          fexp.exportGeneralStatisticsInCPNToCSVFile(
              request, response, res, "list_of_patients_in_CPN.csv", "List of Patients in CPN");
        else if (request.getParameter("type").equalsIgnoreCase("2")) {
          fexp.exportToCSVFile(
              request,
              response,
              res,
              "list_of_patients_in_CPN_DPA_" + month + "_" + year + ".csv",
              "List of Patients in CPN(DPA=" + month + "-" + year + ")");
        } else if (request.getParameter("type").equalsIgnoreCase("3"))
          fexp.exportToCSVFile(
              request, response, res, "couples_discordants.csv", "Couples discordants");
      }
    } catch (Exception ex) {
      request
          .getSession()
          .setAttribute(
              WebConstants.OPENMRS_ERROR_ATTR,
              "An error occured when trying to load data. Find the error in the log file.");
      log.error("An error occured when trying to load data from database: \n" + ex.getMessage());
      ex.printStackTrace();
    }
    return mav;
  }