// 옵션다운로드 페이지에서 옵션값 수정하기
  @RequestMapping(value = "/update_option_01.isnet")
  public ModelAndView update_option_01(
      @RequestParam(value = "customer", required = false) Integer customer,
      @RequestParam(value = "product", required = false) Integer product,
      @RequestParam(value = "param", required = false) String param) {
    logger.debug("[" + getClass().getSimpleName() + "] [update_option_01] start");

    // 조건맵
    Map<String, Object> paramMap = new HashMap<String, Object>();
    paramMap.put("CUSTOMER_NO", customer);
    paramMap.put("PRODUCT_NO", product);
    paramMap.put("PARAM", param);

    ModelAndView mav = new ModelAndView(mappingJacksonJsonView);
    try {
      Map<String, Object> resultMap = optionService.update_option_01(paramMap);
      mav.addAllObjects(resultMap);

    } catch (Exception e) {
      e.printStackTrace();
      logger.error("[" + getClass().getSimpleName() + "] [file_01] 파일 생성중 오류 발생");
    }
    logger.debug("[" + getClass().getSimpleName() + "] [update_option_01] end");
    return mav;
  }
  @Override
  public ModelAndView getReportTemplate() {
    List<MonthlyTraffic> monthlyTrafficReports = monthlyTraffictDAO.getMonthlyTraffic(monthDate);
    HSSFWorkbook workbook = new HSSFWorkbook();
    HSSFSheet sheet = workbook.createSheet("Monthly Traffic Report");

    int rownum = 0;
    Row row0 = sheet.createRow(rownum++);

    row0.createCell(0).setCellValue("Source Country");
    row0.createCell(1).setCellValue("Service");
    row0.createCell(2).setCellValue("Destination Country");
    row0.createCell(3).setCellValue("Total Call Minutes");

    for (MonthlyTraffic mt : monthlyTrafficReports) {
      Row row = sheet.createRow(rownum++);
      row.createCell(0).setCellValue(mt.getFromCountry());
      row.createCell(1).setCellValue(mt.getServiceName());
      row.createCell(2).setCellValue(mt.getToCountry());
      row.createCell(3).setCellValue(mt.getMinutesOfCalls());
    }

    Map<String, HSSFWorkbook> parameterMap = new HashMap<String, HSSFWorkbook>();
    parameterMap.put("excelBook", workbook);
    ModelAndView modelAndView = new ModelAndView();
    modelAndView.addAllObjects(parameterMap);
    return modelAndView;
  }
  /*
   * Return a view sending all params from a request
   *
   * @param request HttpServletRequest to send to the view
   * @param viewname String with the view name to load
   * @return ModelAndView return a view with viewname
   */
  public static ModelAndView buildViewParams(HttpServletRequest request, String viewname) {

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

    ModelAndView mav = new ModelAndView(viewname, map);

    Enumeration<String> parameterNames = request.getParameterNames();

    while (parameterNames.hasMoreElements()) {
      String paramName = parameterNames.nextElement();

      // if the request var is a Array
      if ((request.getParameterValues(paramName).getClass().isArray())
          // if Array size is more than 1
          && (request.getParameterValues(paramName).length > 1)) {
        map.put(paramName, Arrays.toString(request.getParameterValues(paramName)));
      } else
        // if the request var is a simple var
        map.put(paramName, request.getParameter(paramName));
    }

    mav.addAllObjects(map);

    // return view
    return mav;
  }
  @Override
  protected ModelAndView onSubmit(
      HttpServletRequest request,
      HttpServletResponse response,
      Object command,
      BindException errors)
      throws Exception {
    logger.debug("onSubmit - START");
    ModelAndView mav = new ModelAndView(IConstant.FORM_VIEW_MESSAGES);
    Currency currency = (Currency) command;

    Locale locale = RequestContextUtils.getLocale(request);
    ArrayList<String> errorMessages = new ArrayList<String>();
    ArrayList<String> infoMessages = new ArrayList<String>();

    // check if the currency has a currencyId
    if (currency.getCurrencyId() != -1) {
      // if I have currencyId, it means that I have "update" action
      logger.debug("onSubmit - handleUpdate");
      mav = handleUpdate(currency, request, locale, errorMessages, infoMessages);
    } else {
      // if I don't have currency, it means that I have "add" action
      logger.debug("onSubmit - handleAdd");
      mav = handleAdd(currency, request, locale, errorMessages, infoMessages);
    }

    setErrors(request, errorMessages);
    setMessages(request, infoMessages);

    mav.addAllObjects(referenceData(request, currency, errors));
    logger.debug("onSubmit - END");
    return mav;
  }
Example #5
0
  @SuppressWarnings("unchecked")
  public ModelAndView sgisCodeList(HttpServletRequest request, HttpServletResponse response) {
    ModelAndView mav = null;

    try {
      mav = new ModelAndView();
      HashMap map = WebUtil.parseRequestMap(request);

      HashMap adminMap =
          (HashMap)
              request
                  .getSession()
                  .getAttribute(SGConfigManager.getString("common.session.admin.name"));
      mav.addObject("admin_id", (String) adminMap.get("ADMIN_ID"));
      mav.addObject("admin_nm", (String) adminMap.get("ADMIN_NM"));
      mav.addObject("sabun", (String) adminMap.get("SABUN"));

      mav.setViewName("/com/code/sgisCodeList");

      mav.addObject("pMap", map);
      mav.addAllObjects(map);

    } catch (Exception e) {
      logger.error("::" + this.getClass() + "\n<sgis코드관리 목록 에러>::::\n" + e.getMessage());
    }
    return mav;
  }
Example #6
0
 /*----------------------------------------------------------------------------------------------------*/
 public ModelAndView getModelAndView() {
   ModelAndView returnView = new ModelAndView(getView());
   if (parameterMap != null) {
     returnView.addAllObjects(parameterMap);
   }
   return returnView;
 }
  @Override
  protected ModelAndView onSubmit(
      HttpServletRequest request,
      HttpServletResponse response,
      Object command,
      BindException errors)
      throws Exception {
    logger.debug("onSubmit - START");
    // used as a container for info/error messages
    ArrayList<String> infoMessages = new ArrayList<String>();
    ArrayList<String> errorMessages = new ArrayList<String>();

    ModelAndView mav = new ModelAndView(IConstant.FORM_VIEW_MESSAGES);

    try {
      boolean isDeleteAction = false;

      // check if i have deleteAll action
      if (request.getParameter(ACTION) != null && DELETEALL.equals(request.getParameter(ACTION))) {
        handleDeleteAll(request, command, infoMessages, errorMessages);
        isDeleteAction = true;
      }
      if (request.getParameter(ACTION) != null && PAGINATION.equals(request.getParameter(ACTION))) {
        mav = handlePagination(request, errorMessages, command);
      } else {
        mav = handleSearch(request, command, errorMessages, isDeleteAction);
      }
    } catch (BusinessException bexc) {
      logger.error(bexc.getMessage(), bexc);
      errorMessages.add(
          messageSource.getMessage(
              SEARCH_ERROR,
              new Object[] {
                bexc.getCode(), ControllerUtils.getInstance().getFormattedCurrentTime()
              },
              RequestContextUtils.getLocale(request)));
    } catch (Exception e) {
      logger.error("", e);
      errorMessages.add(
          messageSource.getMessage(
              SEARCH_EXCEPTION_ERROR,
              new Object[] {ControllerUtils.getInstance().getFormattedCurrentTime()},
              RequestContextUtils.getLocale(request)));
    }

    // setting all messages on response
    setErrors(request, errorMessages);
    setMessages(request, infoMessages);

    mav.addAllObjects(referenceData(request, command, errors));
    logger.debug("onSubmit - END");
    return mav;
  }
 @Override
 protected ModelAndView onSubmit(
     HttpServletRequest request,
     HttpServletResponse response,
     Object command,
     BindException errors)
     throws Exception {
   ModelAndView mav = new ModelAndView(getSuccessView());
   mav.addObject("reportSearchFilter", command);
   mav.addAllObjects(referenceData(request, command, errors));
   return mav;
 }
  @RequestMapping(value = "/option_compare.isnet")
  public ModelAndView option_compare(
      @RequestParam(value = "product", required = false) int product,
      @RequestParam(value = "fileChk", required = false) int[] file,
      @RequestParam(value = "customer_no1", required = false) String customer_no1,
      @RequestParam(value = "customer_no2", required = false) String customer_no2,
      @RequestParam(value = "customer_no3", required = false) String customer_no3,
      @RequestParam(value = "customer_no4", required = false) String customer_no4) {

    logger.debug("[" + getClass().getSimpleName() + "] [list_02] start");
    logger.info("[" + getClass().getSimpleName() + "] product [" + product + "]");
    logger.info("[" + getClass().getSimpleName() + "] file [" + file.length + "]");
    logger.info("[" + getClass().getSimpleName() + "] customer1 [" + customer_no1 + "]");
    logger.info("[" + getClass().getSimpleName() + "] customer2 [" + customer_no2 + "]");
    logger.info("[" + getClass().getSimpleName() + "] customer3 [" + customer_no3 + "]");
    logger.info("[" + getClass().getSimpleName() + "] customer4 [" + customer_no4 + "]");

    String file_query = " AND OPTION_FILE_NO IN (";
    for (int i = 0; i < file.length; i++) {
      if (i != file.length - 1) file_query += file[i] + ",";
      else file_query += file[i] + ") ";
    }
    logger.info("[" + getClass().getSimpleName() + "] file [" + file_query + "]");

    ModelAndView mav = new ModelAndView();
    mav.setView(mappingJacksonJsonView);

    Map<String, Object> paramMap = new HashMap<String, Object>();
    paramMap.put("PRODUCT_NO", product);
    paramMap.put("OPTION_FILE_QUERY", file_query);
    paramMap.put("CUSTOMER_NO1", customer_no1);
    paramMap.put("CUSTOMER_NO2", customer_no2);
    paramMap.put("CUSTOMER_NO3", customer_no3);
    paramMap.put("CUSTOMER_NO4", customer_no4);

    try {

      Map<String, Object> resultMap = optionService.getForthOptionList(paramMap);
      mav.addAllObjects(resultMap);

    } catch (Exception e) {
      e.printStackTrace();
      logger.error("[" + getClass().getSimpleName() + "] [list_02] 조회 오류");
      mav.addObject("error_msg", "옵션 조회중  오류가 발생하였습니다.");
      mav.setViewName("error");
    } finally {
      logger.debug("[" + getClass().getSimpleName() + "] [list_02] end");
    }

    return mav;
  }
Example #10
0
  public static ModelAndView createModelAndView(String viewName, Object... models) {
    ModelAndView mv = new ModelAndView(viewName);
    //		mv.getModel().put(UrlHelper.MODEL_KEY, getUrlMeta());
    if (LangUtils.isEmpty(models)) {
      return mv;
    }

    if (models.length == 1) {
      if (Map.class.isInstance(models[0])) {
        mv.addAllObjects((Map<String, ?>) models[0]);

      } else if (DataWrapper.class.isInstance(models[0])) {
        mv.addObject(models[0]);

      } else if (ModelAttr.class.isInstance(models[0])) {
        ModelAttr attr = (ModelAttr) models[0];
        mv.addObject(attr.getName(), attr.getValue());

      } else {
        mv.addObject(models[0]);
        //				mv.addObject(JsonWrapper.wrap(models[0]));
        //				mv.addObject(SINGLE_MODEL_FLAG_KEY, true);
      }
    } else {
      /*Map<String, ?> modelMap = LangUtils.asMap(models);
      mv.addAllObjects(modelMap);*/

      for (int i = 0; i < models.length; i++) {
        if (DataWrapper.class.isInstance(models[i])) {
          mv.addObject(models[i]);

        } else if (ModelAttr.class.isInstance(models[i])) {
          ModelAttr attr = (ModelAttr) models[i];
          mv.addObject(attr.getName(), attr.getValue());

        } else {
          Object name = models[i];
          if (!String.class.isInstance(name)) {
            throw new BaseException("model key must be a string, but is : " + name);
          }
          i++;
          if (i >= models.length) {
            throw new BaseException("no value for model key : " + name);
          }
          mv.addObject(name.toString(), models[i]);
        }
      }
    }
    return mv;
  }
  @RequestMapping(value = "/adminpage", method = RequestMethod.GET)
  public ModelAndView home() {
    ModelAndView mav = new ModelAndView("home");
    List<Employee> list = employeeService.findAll();

    Gson gson = new Gson();
    String emGson = gson.toJson(list);

    Map<String, Object> map = new HashMap<String, Object>();
    map.put("emGson", emGson);
    map.put("emList", list);
    mav.addAllObjects(map);

    System.out.println(emGson);
    System.out.println(list.toString());

    return mav;
  }
  @RequestMapping(value = "/timesheet", method = RequestMethod.GET)
  public ModelAndView showMainForm(
      @RequestParam(value = "date", required = false) String date,
      @RequestParam(value = "id", required = false) Integer id) {
    logger.info(">>>>>>>>>>>>>>>>>>>>>>>>>>>>");
    logger.info("Showing Time Sheet main page!");
    ModelAndView mav = new ModelAndView();
    mav.setViewName("timesheet");

    TimeSheetForm tsForm = new TimeSheetForm();

    TimeSheetUser securityUser = securityService.getSecurityPrincipal();

    if (id != null) {
      tsForm.setDivisionId(employeeService.find(id).getDivision().getId());
      tsForm.setEmployeeId(id);
    } else if (securityUser != null) {
      tsForm.setDivisionId(securityUser.getEmployee().getDivision().getId());
      tsForm.setEmployeeId(securityUser.getEmployee().getId());
    }

    if (date != null) {
      tsForm.setCalDate(date);
      mav.addObject(
          "selectedCalDateJson", getSelectedCalDateJson(tsForm)); // выставляем дату для DateTextBox
    } else {
      mav.addObject("selectedCalDateJson", "''");
    }
    mav.addObject("timeSheetForm", tsForm); // command object
    mav.addObject("selectedProjectRolesJson", "[{row:'0', role:''}]");
    mav.addObject("selectedProjectTasksJson", "[{row:'0', task:''}]");
    mav.addObject("selectedProjectsJson", "[{row:'0', project:''}]");
    mav.addObject("selectedWorkplaceJson", "[{row:'0', workplace:''}]");
    mav.addObject("selectedActCategoriesJson", "[{row:'0', actCat:''}]");
    mav.addObject("selectedLongVacationIllnessJson", getSelectedLongVacationIllnessJson(tsForm));
    mav.addObject("getDateByDefault", getDateByDefault(tsForm.getEmployeeId()));
    mav.addObject("getFirstWorkDate", getEmployeeFirstWorkDay(tsForm.getEmployeeId()));

    mav.addAllObjects(getListsToMAV());
    return mav;
  }
  @RequestMapping(
      value = "index",
      method = {RequestMethod.GET})
  public ModelAndView index() {
    // 상품목록정보 취득
    List<Item> itemList = this.itemService.getItemList();
    // 모델 생성
    Map<String, Object> model = new HashMap<String, Object>();
    model.put("itemList", itemList);
    // logger.info("dataResult=>" + itemList.toString());
    // 반환값이 되는 ModelAndView 인스턴스를 생성

    logger.info("@@@@@@@@@@@@@@@@@@=>" + this.hibernateItemService.getClass().getName());

    logger.info(
        "#########################=>" + this.hibernateItemService.getItemList("findItemByID"));

    ModelAndView modelAndView = new ModelAndView("index");
    modelAndView.addAllObjects(model);
    logger.info("ItemController index 메서드 실행");
    return modelAndView;
  }
  @RequestMapping(value = "/timesheet", method = RequestMethod.POST)
  public ModelAndView sendTimeSheet(
      @ModelAttribute("timeSheetForm") TimeSheetForm tsForm, BindingResult result) {
    logger.info(
        "Processing form validation for employee {} ({}).",
        tsForm.getEmployeeId(),
        tsForm.getCalDate());
    tsFormValidator.validate(tsForm, result);
    if (result.hasErrors()) {
      logger.info(
          "TimeSheetForm for employee {} has errors. Form not validated.", tsForm.getEmployeeId());
      ModelAndView mavWithErrors = new ModelAndView("timesheet");
      mavWithErrors.addObject("timeSheetForm", tsForm);
      mavWithErrors.addObject("errors", result.getAllErrors());
      mavWithErrors.addObject("selectedProjectsJson", getSelectedProjectsJson(tsForm));
      mavWithErrors.addObject("selectedProjectRolesJson", getSelectedProjectRolesJson(tsForm));
      mavWithErrors.addObject("selectedProjectTasksJson", getSelectedProjectTasksJson(tsForm));
      mavWithErrors.addObject("selectedWorkplaceJson", getSelectedWorkplaceJson(tsForm));
      mavWithErrors.addObject("selectedActCategoriesJson", getSelectedActCategoriesJson(tsForm));
      mavWithErrors.addObject(
          "selectedLongVacationIllnessJson", getSelectedLongVacationIllnessJson(tsForm));
      mavWithErrors.addObject("selectedCalDateJson", getSelectedCalDateJson(tsForm));
      mavWithErrors.addObject("getDateByDefault", getDateByDefault(tsForm.getEmployeeId()));
      mavWithErrors.addObject("getFirstWorkDate", getEmployeeFirstWorkDay(tsForm.getEmployeeId()));
      mavWithErrors.addAllObjects(getListsToMAV());

      return mavWithErrors;
    }
    TimeSheet timeSheet = timeSheetService.storeTimeSheet(tsForm);
    overtimeCauseService.store(timeSheet, tsForm);
    sendMailService.performMailing(tsForm);

    ModelAndView mav = new ModelAndView("selected");
    mav.addObject("timeSheetForm", tsForm);
    logger.info("<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<");

    return mav;
  }
  // Пользователь списывает занятость за продолжительные отпуск или болезнь.
  @RequestMapping(value = "/timesheetLong", method = RequestMethod.POST)
  public ModelAndView sendTimeSheetLong(
      @ModelAttribute("timeSheetForm") TimeSheetForm tsForm, BindingResult result) {
    logger.info(
        "Processing form validation for employee {} ({}) (long).",
        tsForm.getEmployeeId(),
        tsForm.getCalDate());
    tsFormValidator.validate(tsForm, result);
    if (result.hasErrors()) {
      logger.info(
          "TimeSheetForm for employee {} has errors. Form not validated (long).",
          tsForm.getEmployeeId());
      ModelAndView mavWithErrors = new ModelAndView("timesheet");
      mavWithErrors.addObject("timeSheetForm", tsForm);
      mavWithErrors.addObject("errors", result.getAllErrors());
      mavWithErrors.addObject("selectedProjectRolesJson", "[{row:'0', role:''}]");
      mavWithErrors.addObject("selectedProjectTasksJson", "[{row:'0', task:''}]");
      mavWithErrors.addObject("selectedProjectsJson", "[{row:'0', project:''}]");
      mavWithErrors.addObject("selectedActCategoriesJson", "[{row:'0', actCat:''}]");
      mavWithErrors.addObject("selectedWorkplace", "[{row:'0', workplace:''}]");
      mavWithErrors.addObject("selectedCalDateJson", "''");
      mavWithErrors.addObject(
          "selectedLongVacationIllnessJson", getSelectedLongVacationIllnessJson(tsForm));
      mavWithErrors.addAllObjects(getListsToMAV());

      return mavWithErrors;
    }
    timeSheetService.storeTimeSheetLong(tsForm);
    sendMailService.performMailing(tsForm);

    ModelAndView mav = new ModelAndView("selected");
    mav.addObject("timeSheetForm", tsForm);
    logger.info("<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<");

    return mav;
  }
  /**
   * Custom handler to create a new one.
   *
   * @param idPerson the ID of the person
   * @return a ModelMap with the model attributes for the respective view
   */
  @RequestMapping("new/{idPerson}")
  public ModelAndView newFicha(@PathVariable("idPerson") long idPerson, HttpServletRequest request)
      throws Exception {
    String urlValidacion = "";
    try {
      urlValidacion = seguridadService.validarLogin(request);
      // si la url esta vacia significa que la validaci�n del login fue exitosa
      if (urlValidacion.isEmpty())
        urlValidacion =
            seguridadService.validarAutorizacionUsuario(
                request, ConstantsSecurity.SYSTEM_CODE, true);
    } catch (Exception e) {
      e.printStackTrace();
      urlValidacion = "404";
    }
    ModelAndView mav = new ModelAndView();
    if (urlValidacion.isEmpty()) {
      boolean autorizado = true;
      FichaRotavirus fichaRotavirus = new FichaRotavirus();
      DaNotificacion noti = new DaNotificacion();
      Initialize();
      SisPersona persona = personaService.getPersona(idPerson);

      long idUsuario = seguridadService.obtenerIdUsuario(request);
      // Si es usuario a nivel central se cargan todas las unidades asociados al SILAIS y municipio
      if (seguridadService.esUsuarioNivelCentral(idUsuario, ConstantsSecurity.SYSTEM_CODE)) {
        entidades = entidadAdmonService.getAllEntidadesAdtvas();
      } else {
        entidades =
            seguridadService.obtenerEntidadesPorUsuario(
                (int) idUsuario, ConstantsSecurity.SYSTEM_CODE);
      }

      if (persona != null) {
        noti.setPersona(persona);
        fichaRotavirus.setDaNotificacion(noti);
        Divisionpolitica departamentoProce =
            divisionPoliticaService.getDepartamentoByMunicipi(
                fichaRotavirus
                    .getDaNotificacion()
                    .getPersona()
                    .getMunicipioResidencia()
                    .getCodigoNacional());
        List<Divisionpolitica> municipiosResi =
            divisionPoliticaService.getMunicipiosFromDepartamento(
                departamentoProce.getCodigoNacional());
        List<Comunidades> comunidades =
            comunidadesService.getComunidades(
                fichaRotavirus
                    .getDaNotificacion()
                    .getPersona()
                    .getMunicipioResidencia()
                    .getCodigoNacional());

        mav.addObject("entidades", entidades);
        mav.addObject("autorizado", autorizado);
        mav.addObject("departamentoProce", departamentoProce);
        mav.addObject("municipiosResi", municipiosResi);
        mav.addObject("comunidades", comunidades);
        mav.addObject("fichaRotavirus", fichaRotavirus);
        mav.addAllObjects(mapModel);
        mav.setViewName("rotavirus/create");
      } else {
        mav.setViewName("404");
      }

    } else {
      mav.setViewName(urlValidacion);
    }

    return mav;
  }
  /**
   * * Obetener la información de una notificación y cargarla en pantalla para su edición
   *
   * @param idNotificacion a cargar
   * @param request con datos de autenticación
   * @return ModelAndView
   * @throws Exception
   */
  @RequestMapping("edit/{idNotificacion}")
  public ModelAndView editIrag(
      @PathVariable("idNotificacion") String idNotificacion, HttpServletRequest request)
      throws Exception {
    String urlValidacion = "";
    boolean autorizado = true;
    try {
      urlValidacion = seguridadService.validarLogin(request);
      // si la url esta vacia significa que la validaci�n del login fue exitosa
      if (urlValidacion.isEmpty())
        urlValidacion =
            seguridadService.validarAutorizacionUsuario(
                request, ConstantsSecurity.SYSTEM_CODE, true);
    } catch (Exception e) {
      e.printStackTrace();
      urlValidacion = "404";
    }

    ModelAndView mav = new ModelAndView();
    if (urlValidacion.isEmpty()) {

      if (idNotificacion != null) {
        FichaRotavirus fichaRotavirus = rotaVirusService.getFichaById(idNotificacion);

        if (fichaRotavirus != null) {
          Initialize();

          long idUsuario = seguridadService.obtenerIdUsuario(request);
          // irag.setUsuario(usuarioService.getUsuarioById((int) idUsuario));
          if (idUsuario != 0) {
            autorizado =
                seguridadService.esUsuarioNivelCentral(idUsuario, ConstantsSecurity.SYSTEM_CODE)
                    || ((fichaRotavirus.getDaNotificacion().getCodSilaisAtencion() != null
                            && fichaRotavirus.getDaNotificacion().getCodUnidadAtencion() != null)
                        && seguridadService.esUsuarioAutorizadoEntidad(
                            (int) idUsuario,
                            ConstantsSecurity.SYSTEM_CODE,
                            fichaRotavirus.getDaNotificacion().getCodSilaisAtencion().getCodigo())
                        && seguridadService.esUsuarioAutorizadoUnidad(
                            (int) idUsuario,
                            ConstantsSecurity.SYSTEM_CODE,
                            fichaRotavirus.getDaNotificacion().getCodUnidadAtencion().getCodigo()));
          }

          entidades =
              seguridadService.obtenerEntidadesPorUsuario(
                  (int) idUsuario, ConstantsSecurity.SYSTEM_CODE);

          if (entidades.size() <= 0) {
            entidades.add(fichaRotavirus.getDaNotificacion().getCodSilaisAtencion());
          }

          Divisionpolitica municipio =
              divisionPoliticaService.getMunicipiosByUnidadSalud(
                  fichaRotavirus
                      .getDaNotificacion()
                      .getCodUnidadAtencion()
                      .getMunicipio()
                      .getCodigoNacional());
          List<Divisionpolitica> munic =
              divisionPoliticaService.getMunicipiosBySilais(
                  fichaRotavirus.getDaNotificacion().getCodSilaisAtencion().getCodigo());

          List<Unidades> uni = null;
          if (seguridadService.esUsuarioNivelCentral(idUsuario, ConstantsSecurity.SYSTEM_CODE)) {
            if (fichaRotavirus.getDaNotificacion().getCodSilaisAtencion() != null
                && fichaRotavirus.getDaNotificacion().getCodUnidadAtencion() != null) {
              uni =
                  seguridadService.obtenerUnidadesPorUsuarioEntidadMunicipio(
                      (int) idUsuario,
                      fichaRotavirus.getDaNotificacion().getCodSilaisAtencion().getCodigo(),
                      fichaRotavirus
                          .getDaNotificacion()
                          .getCodUnidadAtencion()
                          .getMunicipio()
                          .getCodigoNacional(),
                      ConstantsSecurity.SYSTEM_CODE,
                      HealthUnitType.UnidadesPrimHosp.getDiscriminator());
            }
          } else {
            if (fichaRotavirus.getDaNotificacion().getCodSilaisAtencion() != null
                && fichaRotavirus.getDaNotificacion().getCodUnidadAtencion() != null) {
              uni =
                  seguridadService.obtenerUnidadesPorUsuarioEntidadMunicipio(
                      (int) idUsuario,
                      fichaRotavirus.getDaNotificacion().getCodSilaisAtencion().getCodigo(),
                      fichaRotavirus
                          .getDaNotificacion()
                          .getCodUnidadAtencion()
                          .getMunicipio()
                          .getCodigoNacional(),
                      ConstantsSecurity.SYSTEM_CODE,
                      HealthUnitType.UnidadesPrimHosp.getDiscriminator());
              if (!uni.contains(fichaRotavirus.getDaNotificacion().getCodUnidadAtencion())) {
                uni.add(fichaRotavirus.getDaNotificacion().getCodUnidadAtencion());
              }
            }
          }

          // datos persona
          Divisionpolitica departamentoProce;
          List<Divisionpolitica> municipiosResi = null;
          List<Comunidades> comunidades = null;

          if (fichaRotavirus.getDaNotificacion().getPersona().getMunicipioResidencia() != null) {
            String municipioResidencia =
                fichaRotavirus
                    .getDaNotificacion()
                    .getPersona()
                    .getMunicipioResidencia()
                    .getCodigoNacional();
            departamentoProce =
                divisionPoliticaService.getDepartamentoByMunicipi(municipioResidencia);
            municipiosResi =
                divisionPoliticaService.getMunicipiosFromDepartamento(
                    departamentoProce.getCodigoNacional());
            String comu =
                fichaRotavirus
                    .getDaNotificacion()
                    .getPersona()
                    .getMunicipioResidencia()
                    .getCodigoNacional();
            comunidades = comunidadesService.getComunidades(comu);
          }

          mav.addObject("fichaRotavirus", fichaRotavirus);
          mav.addObject("autorizado", autorizado);
          mav.addObject("entidades", entidades);
          mav.addObject("munic", munic);
          mav.addObject("municipiosResi", municipiosResi);
          mav.addObject("comunidades", comunidades);
          mav.addObject("uni", uni);
          mav.addObject("municipio", municipio);
          mav.addAllObjects(mapModel);

          mav.setViewName("rotavirus/create");
        } else {
          mav.setViewName("404");
        }
      } else {
        mav.setViewName("404");
      }

    } else {
      mav.setViewName(urlValidacion);
    }

    return mav;
  }
Example #18
0
  @RolesAllowed({Role.USER, Role.POWERUSER, Role.SUPERVISOR, Role.ADMIN})
  @RequestMapping(value = "/bdrs/user/atlas.htm", method = RequestMethod.GET)
  public ModelAndView addRecord(
      HttpServletRequest request,
      HttpServletResponse response,
      @RequestParam(value = "surveyId", required = true) int surveyId,
      @RequestParam(value = "taxonSearch", required = false) String taxonSearch,
      @RequestParam(value = "recordId", required = false, defaultValue = "0") int recordId,
      @RequestParam(value = "guid", required = false) String guid) {

    Survey survey = surveyDAO.getSurvey(surveyId);
    Record record = recordDAO.getRecord(recordId);

    record = record == null ? new Record() : record;

    IndicatorSpecies species = null;

    if (guid != null && !guid.isEmpty()) {
      species = taxaDAO.getIndicatorSpeciesByGuid(guid);
    }
    if (species == null && taxonSearch != null && !taxonSearch.isEmpty()) {
      List<IndicatorSpecies> speciesList =
          surveyDAO.getSpeciesForSurveySearch(surveyId, taxonSearch);
      if (speciesList.isEmpty()) {
        species = null;
      } else if (speciesList.size() == 1) {
        species = speciesList.get(0);
      } else {
        log.warn(
            "Multiple species found for survey "
                + surveyId
                + " and taxon search \""
                + taxonSearch
                + "\". Using the first.");
        species = speciesList.get(0);
      }
    }
    if (species == null && record.getSpecies() != null) {
      species = record.getSpecies();
    }

    ModelAndView mv;
    if (species == null) {
      InputStreamReader reader = null;
      try {
        Preference p = preferenceDAO.getPreferenceByKey("ala.species.short.url");
        URL url;
        if (p != null) {
          url = new URL(p.getValue() + "/" + guid + ".json");
        } else {
          url =
              new URL(
                  "http://bie.ala.org.au/species/shortProfile/"
                      + guid
                      + ".json"); // fallback to the BIE
        }

        URLConnection conn = url.openConnection();
        reader = new InputStreamReader(conn.getInputStream());
        StringBuffer buff = new StringBuffer();
        int c;
        while ((c = reader.read()) != -1) {
          buff.append((char) c);
        }
        JSONObject ob = JSONObject.fromObject(buff.toString());
        IndicatorSpecies taxon = new IndicatorSpecies();

        log.debug("Found species information from the atlas : ");
        log.debug(buff.toString());
        // Scientific Name
        taxon.setScientificName(ob.getString("scientificName"));
        taxon.setAuthor(ob.getString("author"));
        taxon.setScientificNameAndAuthor(
            ob.getString("scientificName") + " " + ob.getString("scientificNameAuthorship"));
        taxon.setYear(ob.getString("year"));
        Metadata md = new Metadata();
        md.setKey(Metadata.SCIENTIFIC_NAME_SOURCE_DATA_ID);
        md.setValue(guid);
        metadataDAO.save(md);
        taxon.getMetadata().add(md);

        // Rank
        TaxonRank rank = TaxonRank.findByIdentifier(ob.getString("rank"));
        taxon.setTaxonRank(rank);

        // Common Name
        taxon.setCommonName(ob.getString("commonName"));
        md = new Metadata();
        md.setKey(Metadata.COMMON_NAME_SOURCE_DATA_ID);
        md.setValue(ob.getString("commonNameGUID"));
        metadataDAO.save(md);
        taxon.getMetadata().add(md);

        // Group
        String family = ob.getString("family");
        if (family != null) {
          TaxonGroup g = taxaDAO.getTaxonGroup(family);
          if (g == null) {
            g = taxaDAO.createTaxonGroup(family, false, false, false, false, false, true);
          }
          taxon.setTaxonGroup(g);
        } else {
          TaxonGroup g = taxaDAO.createTaxonGroup("Other", false, false, false, false, false, true);
          taxon.setTaxonGroup(g);
        }

        // Images.
        // Thumbnail
        if (ob.containsKey("thumbnail")) {
          SpeciesProfile sp = new SpeciesProfile();
          sp.setType(
              SpeciesProfile
                  .SPECIES_PROFILE_THUMBNAIL); // this is a 100x100 image, might resize for the
                                               // other ones.
          sp.setHeader("Thumbnail");
          sp.setDescription("Thumbnail for " + taxon.getScientificName());
          String filename = ob.getString("thumbnail");
          String ext = getExtension(filename);
          ManagedFile mf = new ManagedFile();
          mf.setContentType("");
          mf.setCredit("");
          mf.setLicense("");
          mf.setDescription(taxon.getScientificName() + " - " + taxon.getCommonName());
          mf.setFilename(mf.getUuid() + ext);
          mf = managedFileDAO.save(mf);
          fileService.createFile(
              mf.getClass(), mf.getId(), mf.getFilename(), downloadFile(new URL(filename)));
          mf.setContentType(fileService.getFile(mf, mf.getFilename()).getContentType());
          managedFileDAO.save(mf);
          sp.setContent(mf.getUuid());
          speciesProfileDAO.save(sp);
          taxon.getInfoItems().add(sp);

          // Now thumbnail the thumbnail...
          BufferedImage fortyXforty =
              imageService.resizeImage(
                  fileService.getFile(mf, mf.getFilename()).getInputStream(), 40, 40);
          ByteArrayOutputStream baos = new ByteArrayOutputStream();
          ImageIO.write(fortyXforty, "png", baos);
          baos.flush();
          byte[] data = baos.toByteArray();
          baos.close();

          sp = new SpeciesProfile();
          sp.setType(
              SpeciesProfile
                  .SPECIES_PROFILE_IMAGE_40x40); // this is a 100x100 image, might resize for the
                                                 // other ones.
          sp.setHeader("40x40 Thumbnail");
          sp.setDescription("40x40 Thumbnail for " + taxon.getScientificName());

          mf = new ManagedFile();
          mf.setContentType("");
          mf.setCredit("");
          mf.setLicense("");
          mf.setDescription(taxon.getScientificName() + " - " + taxon.getCommonName());
          mf.setFilename(mf.getUuid() + ".png");
          mf = managedFileDAO.save(mf);
          fileService.createFile(mf.getClass(), mf.getId(), mf.getFilename(), data);
          mf.setContentType(fileService.getFile(mf, mf.getFilename()).getContentType());
          managedFileDAO.save(mf);
          sp.setContent(mf.getUuid());
          speciesProfileDAO.save(sp);
          taxon.getInfoItems().add(sp);
        }

        // Main Image
        if (ob.containsKey("imageURL")) {
          SpeciesProfile sp = new SpeciesProfile();
          sp.setType(SpeciesProfile.SPECIES_PROFILE_IMAGE);
          sp.setHeader("Image");
          sp.setDescription("Image for " + taxon.getScientificName());
          String filename = ob.getString("imageURL");
          String ext = getExtension(filename);
          ManagedFile mf = new ManagedFile();
          mf.setContentType("");
          mf.setCredit("");
          mf.setLicense("");
          mf.setDescription(taxon.getScientificName() + " - " + taxon.getCommonName());
          mf.setFilename(mf.getUuid() + ext);
          mf = managedFileDAO.save(mf);
          fileService.createFile(
              mf.getClass(), mf.getId(), mf.getFilename(), downloadFile(new URL(filename)));
          mf.setContentType(fileService.getFile(mf, mf.getFilename()).getContentType());
          managedFileDAO.save(mf);
          sp.setContent(mf.getUuid());
          speciesProfileDAO.save(sp);
          taxon.getInfoItems().add(sp);
        }

        // Save the Taxon
        species = taxaDAO.save(taxon);
      } catch (IOException ioe) {
        log.error("Could not retrieve species profile from the Atlas", ioe);
        species = null;
      } finally {
        if (reader != null) {
          try {
            reader.close();
          } catch (IOException ioe) {
            log.error("Error closing stream from Atlas webservice, possible network error", ioe);
          }
        }
      }
    }

    if (species == null) {
      log.debug("Could not determine species, reverting to tracker form");
      // The atlas form relies upon a preconfigured species.
      // If we do not have one, fall back to the tracker form.
      mv = new ModelAndView(new RedirectView("tracker.htm"));
      mv.addAllObjects(request.getParameterMap());
      mv.addObject("surveyId", surveyId);
      return mv;
    } else {
      // Add all attribute form fields
      Map<String, FormField> formFieldMap = new HashMap<String, FormField>();

      // Add all property form fields
      for (String propertyName : RECORD_PROPERTY_NAMES) {
        formFieldMap.put(
            propertyName,
            formFieldFactory.createRecordFormField(
                survey, record, propertyName, species, Taxonomic.TAXONOMIC));
      }

      // Determine the file attribute to use for the form (if there is one)
      // Sort the list of survey attributes by weight so that we can
      // correctly select the first file attribute.
      List<Attribute> attributeList = survey.getAttributes();
      Collections.sort(attributeList, new ComparePersistentImplByWeight());

      // Retrieve the first file attribute and if present, the associated
      // record attribute.
      Attribute fileAttr = null;
      AttributeValue fileRecAttr = null;
      for (Attribute attr : attributeList) {
        if (fileAttr == null && AttributeType.FILE.equals(attr.getType())) {
          // Attribute found.
          fileAttr = attr;
          // Try to locate matching record attribute
          for (AttributeValue recAttr : record.getAttributes()) {
            if (fileRecAttr == null && fileAttr.equals(recAttr.getAttribute())) {
              fileRecAttr = recAttr;
            }
          }
        }
      }

      // Map all the existing file attributes to record attributes.
      Map<Attribute, AttributeValue> fileAttrToRecAttrMap =
          new HashMap<Attribute, AttributeValue>();

      FormField fileFormField =
          formFieldFactory.createRecordFormField(survey, record, fileAttr, fileRecAttr);

      Map<String, String> errorMap =
          (Map<String, String>) getRequestContext().getSessionAttribute("errorMap");
      getRequestContext().removeSessionAttribute("errorMap");
      Map<String, String> valueMap =
          (Map<String, String>) getRequestContext().getSessionAttribute("valueMap");
      getRequestContext().removeSessionAttribute("valueMap");

      Metadata predefinedLocationsMD = survey.getMetadataByKey(Metadata.PREDEFINED_LOCATIONS_ONLY);
      boolean predefinedLocationsOnly =
          predefinedLocationsMD != null && Boolean.parseBoolean(predefinedLocationsMD.getValue());

      Set<Location> locations = new TreeSet<Location>(new LocationNameComparator());
      locations.addAll(survey.getLocations());
      if (!predefinedLocationsOnly) {
        locations.addAll(locationDAO.getUserLocations(getRequestContext().getUser()));
      }

      Metadata defaultLocId =
          getRequestContext().getUser().getMetadataObj(Metadata.DEFAULT_LOCATION_ID);
      Location defaultLocation;
      if (defaultLocId == null) {
        defaultLocation = null;
      } else {
        int defaultLocPk = Integer.parseInt(defaultLocId.getValue());
        defaultLocation = locationDAO.getLocation(defaultLocPk);
      }

      mv = new ModelAndView("atlas");
      mv.addObject("record", record);
      mv.addObject("taxon", species);
      mv.addObject("survey", survey);
      mv.addObject("locations", locations);
      mv.addObject("formFieldMap", formFieldMap);
      mv.addObject("fileFormField", fileFormField);
      mv.addObject("preview", request.getParameter("preview") != null);
      mv.addObject("defaultLocation", defaultLocation);

      mv.addObject("errorMap", errorMap);
      mv.addObject("valueMap", valueMap);
    }

    return mv;
  }
  // 옵션 리스트를 조회합니다.
  @RequestMapping(value = "/option_list_01.isnet")
  public ModelAndView option_list_01(
      @RequestParam(value = "page", defaultValue = "1") int page,
      @RequestParam(value = "rows", defaultValue = "10") int rows,
      @RequestParam(value = "sidx", required = false) String sidx,
      @RequestParam(value = "sord", required = false) String sord,
      @RequestParam(value = "_search", required = false, defaultValue = "false") boolean _search,
      @RequestParam(value = "searchField", required = false) String searchField,
      @RequestParam(value = "searchString", required = false) String searchString,
      @RequestParam(value = "searchOper", required = false) String searchOper,
      @RequestParam(value = "product", required = false) String product,
      @RequestParam(value = "optionfile", required = false) String file,
      @RequestParam(value = "optioonApp", required = false) String app) {

    logger.debug("[" + getClass().getSimpleName() + "] [option_list_01] start");

    logger.info("[" + getClass().getSimpleName() + "] [option_list_01] product [" + product + "]");
    logger.info("[" + getClass().getSimpleName() + "] [option_list_01] file [" + file + "]");
    logger.info("[" + getClass().getSimpleName() + "] [option_list_01] app [" + app + "]");

    logger.info("[" + getClass().getSimpleName() + "] [option_list_01] page [" + page + "]");
    logger.info("[" + getClass().getSimpleName() + "] [option_list_01] rows [" + rows + "]");
    logger.info("[" + getClass().getSimpleName() + "] [option_list_01] sidx [" + sidx + "]");
    logger.info("[" + getClass().getSimpleName() + "] [option_list_01] sord [" + sord + "]");
    logger.info("[" + getClass().getSimpleName() + "] [option_list_01] _search [" + _search + "]");

    // 조건맵
    Map<String, Object> paramMap = new HashMap<String, Object>();
    paramMap.put("PRODUCT_NO", product);
    paramMap.put("OPTION_FILE_NO", product);
    paramMap.put("OPTION_APP_NO", file);

    paramMap.put("PRODUCT_NO", app);
    paramMap.put("PAGE", page);
    paramMap.put("ROWS", rows);
    paramMap.put("SIDX", sidx);
    paramMap.put("SORD", sord);
    paramMap.put("_SEARCH", _search);

    ModelAndView mav = new ModelAndView();
    mav.setView(mappingJacksonJsonView);

    if (_search) {

      logger.info("searchField [" + searchField + "]");
      logger.info("searchString [" + searchString + "]");
      logger.info("searchOper [" + searchOper + "]");

      paramMap.put("SEARCH_FIELD", searchField);
      paramMap.put("SEARCH_STRING", searchString);
      paramMap.put("SEARCH_OPER", searchOper);
    }

    try {
      Map<String, Object> resultMap = optionService.getFullOptionList(paramMap);
      mav.addAllObjects(resultMap);

    } catch (Exception e) {
      e.printStackTrace();
      logger.error("[" + getClass().getSimpleName() + "] [option_list_01] 옵션 리스트 조회 오류");
    }
    logger.debug("[" + getClass().getSimpleName() + "] [option_list_01] end");

    return mav;
  }