Example #1
0
 @RequestMapping(value = "/productos", params = "term", produces = "application/json")
 public @ResponseBody List<LabelValueBean> productos(
     HttpServletRequest request, @RequestParam("term") String filtro) {
   for (String nombre : request.getParameterMap().keySet()) {
     log.debug("Param: {} : {}", nombre, request.getParameterMap().get(nombre));
   }
   Map<String, Object> params = new HashMap<>();
   params.put("almacen", request.getSession().getAttribute("almacenId"));
   params.put("filtro", filtro);
   params = productoDao.lista(params);
   List<LabelValueBean> valores = new ArrayList<>();
   List<Producto> productos = (List<Producto>) params.get("productos");
   for (Producto producto : productos) {
     StringBuilder sb = new StringBuilder();
     sb.append(producto.getSku());
     sb.append(" | ");
     sb.append(producto.getNombre());
     sb.append(" | ");
     sb.append(producto.getDescripcion());
     sb.append(" | ");
     sb.append(producto.getExistencia()).append(" ").append(producto.getUnidadMedida());
     sb.append(" | ");
     sb.append(producto.getPrecioUnitario());
     valores.add(new LabelValueBean(producto.getId(), sb.toString()));
   }
   return valores;
 }
  /**
   * Handles requests with message handler implementation. Previously sets Http request method as
   * header parameter.
   *
   * @param method
   * @param requestEntity
   * @return
   */
  private ResponseEntity<String> handleRequestInternal(
      HttpMethod method, HttpEntity<String> requestEntity) {
    Map<String, ?> httpRequestHeaders = headerMapper.toHeaders(requestEntity.getHeaders());
    Map<String, String> customHeaders = new HashMap<String, String>();
    for (Entry<String, List<String>> header : requestEntity.getHeaders().entrySet()) {
      if (!httpRequestHeaders.containsKey(header.getKey())) {
        customHeaders.put(
            header.getKey(), StringUtils.collectionToCommaDelimitedString(header.getValue()));
      }
    }

    HttpServletRequest request =
        ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
    UrlPathHelper pathHelper = new UrlPathHelper();

    customHeaders.put(CitrusHttpMessageHeaders.HTTP_REQUEST_URI, pathHelper.getRequestUri(request));
    customHeaders.put(
        CitrusHttpMessageHeaders.HTTP_CONTEXT_PATH, pathHelper.getContextPath(request));

    String queryParams = pathHelper.getOriginatingQueryString(request);
    customHeaders.put(
        CitrusHttpMessageHeaders.HTTP_QUERY_PARAMS, queryParams != null ? queryParams : "");

    customHeaders.put(CitrusHttpMessageHeaders.HTTP_REQUEST_METHOD, method.toString());

    Message<?> response =
        messageHandler.handleMessage(
            MessageBuilder.withPayload(requestEntity.getBody())
                .copyHeaders(convertHeaderTypes(httpRequestHeaders))
                .copyHeaders(customHeaders)
                .build());

    return generateResponse(response);
  }
Example #3
0
 @RequestMapping(value = "/events/{name}", method = GET)
 public Map<String, Object> getSingleEvent(
     @PathVariable("name") String eventName, Principal principal) {
   Map<String, Object> out = new HashMap<>();
   final String username = principal.getName();
   final EventWithStatistics event =
       eventStatisticsManager.getSingleEventWithStatistics(eventName, username);
   out.put("event", event);
   out.put("organization", eventManager.loadOrganizer(event.getEvent(), username));
   return out;
 }
 @RequiresPermissions({"categoryWord-get"})
 @RequestMapping(
     method = RequestMethod.POST,
     value = "/query",
     headers = "Accept=application/json")
 public @ResponseBody Map<String, Object> query(@RequestBody Map<String, String> params) {
   List<CategoryWord> rows = categoryWordService.findLikeAnyWhere(params);
   Map<String, Object> result = new HashMap<String, Object>();
   result.put("total", rows.size());
   result.put("rows", rows);
   return result;
 }
Example #5
0
 @ResponseBody
 @RequestMapping(value = "findJobGroup/{id}", method = RequestMethod.GET)
 public Map<String, String> findJobGroup(@PathVariable("id") Integer id) {
   BLGroup blGroup = groupService.getGroupNodeWithChildNode(id);
   Map<String, String> map = new LinkedHashMap<String, String>();
   map.put(blGroup.getGROUP_ID().toString(), blGroup.getNAME());
   while (blGroup.getPARENT_GROUP_ID() != 0 && !"Jobs".equals(blGroup.getNAME())) {
     blGroup = groupService.getGroupNodeWithChildNode(blGroup.getPARENT_GROUP_ID());
     map.put(blGroup.getGROUP_ID().toString(), blGroup.getNAME());
   }
   return map;
 }
  void Initialize() throws Exception {
    try {

      departamentos = divisionPoliticaService.getAllDepartamentos();
      catClasif = catalogoService.getClasificacionesFinalRotavirus();
      catResp = catalogoService.getRespuesta();
      registroVacunas = catalogoService.getRegistrosVacuna();
      tipoVacunaRotavirus = catalogoService.getTiposVacunasRotavirus();
      caracteristaHeceses = catalogoService.getCaracteristasHeces();
      gradoDeshidratacions = catalogoService.getGradosDeshidratacion();
      condicionEgresos = catalogoService.getCondicionEgreso();
      salaRotaVirusList = catalogoService.getSalasRotaVirus();

      mapModel = new HashMap<>();

      mapModel.put("departamentos", departamentos);
      mapModel.put("catClasif", catClasif);
      mapModel.put("catResp", catResp);
      mapModel.put("registroVacunas", registroVacunas);
      mapModel.put("tipoVacunaRotavirus", tipoVacunaRotavirus);
      mapModel.put("caracteristaHeceses", caracteristaHeceses);
      mapModel.put("gradoDeshidratacions", gradoDeshidratacions);
      mapModel.put("condicionEgresos", condicionEgresos);
      mapModel.put("salas", salaRotaVirusList);

    } catch (Exception ex) {
      ex.printStackTrace();
      throw ex;
    }
  }
Example #7
0
  @ResponseBody
  @RequestMapping(value = "chooseJobs", method = RequestMethod.POST, produces = MediaTypes.JSON)
  public Map<String, Object> chooseJobs(@RequestParam("id") Integer id) {
    /**
     * 根节点下不会直接挂载作业,其他节点下可以挂载子节点和作业
     *
     * <p>如果传入的id是0,代表根节点,此时获取根节点下所有子节点 当点击一个子节点后,判断此节点是否为智能节点,如果是智能节点,则查找smart_group_query表
     * 如果是非智能节点,则获取此节点下的子节点和作业 GROUP_TYPE_ID=9 代表智能节点; GROUP_TYPE_ID=4代表非智能节点
     */
    List<GroupBean> groupBeanList = new ArrayList<GroupBean>();
    if (id == 0) {
      List<GroupBean> firstLevelJobGroupList = groupService.findFirstLevelJobGroup();
      groupBeanList.addAll(firstLevelJobGroupList);
    } else {
      List<GroupBean> childJobGroup = groupService.findChildJobGroup(id);
      groupBeanList.addAll(childJobGroup);

      BLGroup groupNode = groupService.findByGroupId(id);
      if (groupNode.getGROUP_TYPE_ID() == 4) {
        List<GroupBean> staticJobList = groupService.findStaticJob(groupNode);
        groupBeanList.addAll(staticJobList);
      } else {
        List<GroupBean> smartJobList = groupService.findSmartJob(groupNode);
        groupBeanList.addAll(smartJobList);
      }
    }

    Map<String, Object> resultMap = new HashMap<String, Object>();
    resultMap.put("data", groupBeanList);
    return resultMap;
  }
Example #8
0
  /** GET /users/suggestions -> suggest users to follow */
  @RequestMapping(
      value = "/rest/users/suggestions",
      method = RequestMethod.GET,
      produces = "application/json")
  @ResponseBody
  public Collection<User> suggestions() {
    User currentUser = userService.getCurrentUser();
    final String login = currentUser.getLogin();
    if (log.isDebugEnabled()) {
      log.debug("REST request to get the last active tweeters list (except " + login + ").");
    }

    Collection<String> exceptions = userService.getFriendsForUser(login);
    exceptions.add(login);

    Collection<Tweet> tweets = timelineService.getDayline("");
    Map<String, User> users = new HashMap<String, User>();
    for (Tweet tweet : tweets) {
      if (exceptions.contains(tweet.getLogin())) continue;

      users.put(tweet.getLogin(), userService.getUserProfileByLogin(tweet.getLogin()));
      if (users.size() == 3) break; // suggestions list limit
    }
    return users.values();
  }
Example #9
0
  @ResponseBody
  @RequestMapping(
      value = "chooseDeviceBYBBSA",
      method = RequestMethod.POST,
      produces = MediaTypes.JSON)
  public Map<String, Object> chooseDeviceBYBBSA(
      @RequestParam("id") Integer id, HttpServletRequest request) throws SQLException {
    List<GroupBean> groupBeanList = new ArrayList<GroupBean>();
    if (id == 0) {
      List<GroupBean> firstLevelDeviceList = groupService.findFirstLevelDeviceGroup();
      groupBeanList.addAll(firstLevelDeviceList);
    } else {
      List<GroupBean> childDeviceGroup = groupService.findDeviceGroupWithId(id);
      groupBeanList.addAll(childDeviceGroup);

      BLGroup groupNode = groupService.findByGroupId(id);
      if (groupNode.getGROUP_TYPE_ID() == 1) {
        List<GroupBean> staticDeviceList = groupService.findStaticDeviceNode(id);
        groupBeanList.addAll(staticDeviceList);
      } else {
        List<GroupBean> smartDeviceList = groupService.findSmartDeviceNode(id);
        groupBeanList.addAll(smartDeviceList);
      }
    }

    Map<String, Object> resultMap = new HashMap<String, Object>();
    resultMap.put("data", groupBeanList);
    // resultMap.put("data",deviceFilter.deviceFilterRole(groupBeanList,UserNameUtil.getUserNameByRequest(request)) );
    return resultMap;
  }
  /**
   * Checks for collection typed header values and convert them to comma delimited String. We need
   * this for further header processing e.g when forwarding headers to JMS queues.
   *
   * @param headers the http request headers.
   */
  private Map<String, Object> convertHeaderTypes(Map<String, ?> headers) {
    Map<String, Object> convertedHeaders = new HashMap<String, Object>();

    for (Entry<String, ?> header : headers.entrySet()) {
      if (header.getValue() instanceof Collection<?>) {
        Collection<?> value = (Collection<?>) header.getValue();
        convertedHeaders.put(header.getKey(), StringUtils.collectionToCommaDelimitedString(value));
      } else if (header.getValue() instanceof MediaType) {
        convertedHeaders.put(header.getKey(), header.getValue().toString());
      } else {
        convertedHeaders.put(header.getKey(), header.getValue());
      }
    }

    return convertedHeaders;
  }
 /**
  * 把list转为map 方便查找
  *
  * @param list 数据库有效数据列表
  * @return map
  */
 private <T extends TrendValue> Map<String, T> tomap(List<T> list) {
   Map<String, T> map = new LinkedHashMap<>();
   for (T value : list) {
     map.put(value.getDate(), value);
   }
   return map;
 }
  /**
   * Guardar datos de una notificación rotavirus (agregar o actualizar)
   *
   * @param request con los datos de la notificación
   * @param response con el resultado de la acción
   * @throws ServletException
   * @throws IOException
   */
  @RequestMapping(
      value = "save",
      method = RequestMethod.POST,
      consumes = MediaType.APPLICATION_JSON_VALUE,
      produces = "application/json")
  protected void save(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {
    String json = "";
    String resultado = "";
    String idNotificacion = "";
    try {
      logger.debug("Guardando datos de Ficha Rotavirus");
      BufferedReader br =
          new BufferedReader(new InputStreamReader(request.getInputStream(), "UTF8"));
      json = br.readLine();
      FichaRotavirus fichaRotavirus = jSonToFichaRotavirus(json);
      if (fichaRotavirus.getDaNotificacion() == null) {
        DaNotificacion noti = guardarNotificacion(json, request);
        fichaRotavirus.setDaNotificacion(noti);
      } else {
        if (fichaRotavirus.getFechaInicioDiarrea() != null) {
          fichaRotavirus
              .getDaNotificacion()
              .setFechaInicioSintomas(fichaRotavirus.getFechaInicioDiarrea());
          daNotificacionService.updateNotificacion(fichaRotavirus.getDaNotificacion());
        }
      }
      rotaVirusService.saveOrUpdate(fichaRotavirus);
      idNotificacion = fichaRotavirus.getDaNotificacion().getIdNotificacion();
    } catch (Exception ex) {
      logger.error(ex.getMessage(), ex);
      ex.printStackTrace();
      resultado = messageSource.getMessage("msg.error.save.rota", null, null);
      resultado = resultado + ". \n " + ex.getMessage();

    } finally {
      Map<String, String> map = new HashMap<String, String>();
      map.put("mensaje", resultado);
      map.put("idNotificacion", idNotificacion);
      String jsonResponse = new Gson().toJson(map);
      response.getOutputStream().write(jsonResponse.getBytes());
      response.getOutputStream().close();
    }
  }
 @RequiresPermissions({"categoryWord-get"})
 @RequestMapping(
     method = RequestMethod.GET,
     value =
         "/get/EnglishWord/{englishWord}/ChineseWord/{chineseWord}/EsglisgAb/{esglisgAb}/Remark/{remark}",
     headers = "Accept=application/json")
 public @ResponseBody List<CategoryWord> getByParams(
     @PathVariable(value = "englishWord") String englishWord,
     @PathVariable(value = "chineseWord") String chineseWord,
     @PathVariable(value = "esglisgAb") String esglisgAb,
     @PathVariable(value = "remark") String remark) {
   Map<String, String> params = new HashMap<String, String>();
   if (!"isNull".equals(englishWord)) params.put("englishWord", englishWord);
   if (!"isNull".equals(chineseWord)) params.put("chineseWord", chineseWord);
   if (!"isNull".equals(esglisgAb)) params.put("esglisgAb", esglisgAb);
   if (!"isNull".equals(remark)) params.put("remark", remark);
   List<CategoryWord> words = categoryWordService.findBy(params);
   return words;
 }
 public Map<String, String> toParamsMap(JSONObject json) throws JSONException {
   Map<String, String> retMap = new HashMap<String, String>();
   Iterator<String> keysItr = json.keys();
   while (keysItr.hasNext()) {
     String key = keysItr.next();
     String value = (String) json.get(key);
     retMap.put(key, value);
   }
   return retMap;
 }
Example #15
0
 @ResponseBody
 @RequestMapping(value = "searchJobs", method = RequestMethod.POST, produces = MediaTypes.JSON)
 public Map<String, Object> searchJobs(
     @RequestParam("name") String name,
     @RequestParam("value") String value,
     HttpServletRequest request,
     HttpServletResponse response) {
   Map<String, Object> resultMap = new HashMap<String, Object>();
   resultMap.put("data", blGroupService.findJobByQuery(name, value));
   return resultMap;
 }
  @RequestMapping(method = RequestMethod.GET)
  @PreAuthorize(Permission.SECURITY_REPORT_READ)
  public @ResponseBody void getNumberOfEarlyAlertsByReasons(
      final HttpServletResponse response,
      final @RequestParam(required = false) UUID campusId,
      final @RequestParam(required = false) String termCode,
      final @RequestParam(required = false) Date createDateFrom,
      final @RequestParam(required = false) Date createDateTo,
      final @RequestParam(required = false) ObjectStatus objectStatus,
      final @RequestParam(required = false, defaultValue = DEFAULT_REPORT_TYPE) String reportType)
      throws ObjectNotFoundException, IOException {

    final DateTerm dateTerm = new DateTerm(createDateFrom, createDateTo, termCode, termService);
    final Map<String, Object> parameters = Maps.newHashMap();
    final Campus campus = SearchParameters.getCampus(campusId, campusService);

    if (StringUtils.isBlank(termCode)
        || termCode.trim().toLowerCase().equals("not used") && createDateFrom != null) {
      dateTerm.setTerm(null);
    } else if (termCode != null && createDateFrom == null) {
      dateTerm.setStartEndDates(null, null);
    }

    SearchParameters.addCampusToParameters(campus, parameters);
    SearchParameters.addDateTermToMap(dateTerm, parameters);

    List<Triple<String, Long, Long>> reasonTotals =
        earlyAlertService.getEarlyAlertReasonTypeCountByCriteria(
            campus,
            dateTerm.getTermCodeNullPossible(),
            dateTerm.getStartDate(),
            dateTerm.getEndDate(),
            objectStatus);

    List<EarlyAlertReasonCountsTO> results =
        earlyAlertService.getStudentEarlyAlertReasonCountByCriteria(
            dateTerm.getTermCodeNullPossible(),
            dateTerm.getStartDate(),
            dateTerm.getEndDate(),
            campus,
            objectStatus);

    if (results == null) {
      results = new ArrayList<>();
    }

    SearchParameters.addDateTermToMap(dateTerm, parameters);
    parameters.put(REASON_TOTALS, reasonTotals);

    renderReport(response, parameters, results, REPORT_URL, reportType, REPORT_FILE_TITLE);
  }
  /**
   * 类别词chineseWord唯一性验证
   *
   * @param chineseWord
   * @return
   */
  @RequestMapping(
      method = RequestMethod.GET,
      value = "/uniqueValidName",
      headers = "Accept=application/json")
  public @ResponseBody boolean uniqueValidName(String chineseWord) {
    Map<String, String> map = new HashMap<String, String>();
    try {
      chineseWord = URLDecoder.decode(chineseWord, "UTF-8");
    } catch (UnsupportedEncodingException e) {

    }
    map.put("chineseWord", chineseWord);
    return categoryWordService.uniqueValid(map);
  }
Example #18
0
 @RequestMapping(value = "/proveedores", params = "term", produces = "application/json")
 public @ResponseBody List<LabelValueBean> proveedores(
     HttpServletRequest request, @RequestParam("term") String filtro) {
   for (String nombre : request.getParameterMap().keySet()) {
     log.debug("Param: {} : {}", nombre, request.getParameterMap().get(nombre));
   }
   Map<String, Object> params = new HashMap<>();
   params.put("empresa", request.getSession().getAttribute("empresaId"));
   params.put("filtro", filtro);
   params = proveedorDao.lista(params);
   List<LabelValueBean> valores = new ArrayList<>();
   List<Proveedor> proveedores = (List<Proveedor>) params.get("proveedores");
   for (Proveedor proveedor : proveedores) {
     StringBuilder sb = new StringBuilder();
     sb.append(proveedor.getNombre());
     sb.append(" | ");
     sb.append(proveedor.getRfc());
     sb.append(" | ");
     sb.append(proveedor.getNombreCompleto());
     valores.add(new LabelValueBean(proveedor.getId(), sb.toString(), proveedor.getNombre()));
   }
   return valores;
 }
  private List getHederAndValueOfPersonInfo(List infoList) throws ParseException {
    List headerAndValueList = new ArrayList();
    for (int i = 0; i < infoList.size(); i++) {

      Map map = (Map) infoList.get(i);
      Set set = map.keySet();
      for (Object s : set) {
        if (map.get(s) != null
            && !Utils.isEmpty(map.get(s).toString().trim())
            && !("id").equals(s)) {
          Map header = new HashMap();
          header.put("header", WordUtils.capitalize(s.toString().replace("_", " ")));
          // if(Utils.isValidXlsStrToDate(map.get(s).toString()))
          //          header.put("value",Utils.getXlsDateToString(map.get(s).toString()));
          // else
          header.put("value", map.get(s).toString());

          headerAndValueList.add(header);
        }
      }
    }
    return headerAndValueList;
  }
Example #20
0
  @ResponseBody
  @RequestMapping(
      value = "getIPAndPathByGroupID",
      method = RequestMethod.POST,
      produces = MediaTypes.JSON)
  public Map<String, Object> getIPAndPathByGroupID(@RequestParam("groupids") String groupids) {
    List<String> ipAddress = new ArrayList<String>();
    String groupPaths = "";
    String[] groups = groupids.split(",");
    for (String groupid : groups) {
      ipAddress = groupService.getIPAddressByGroupID(Integer.parseInt(groupid), ipAddress);
      groupPaths += groupService.getGroupPathByGroupID(Integer.parseInt(groupid)) + ",";
    }
    String ripAddress = "";
    for (String ip : ipAddress) {
      ripAddress += ip + ",";
    }
    Map<String, Object> resultMap = new HashMap<String, Object>();
    resultMap.put("ipAddress", ripAddress.substring(0, ripAddress.length() - 1));
    resultMap.put("groupPaths", groupPaths.substring(0, groupPaths.length() - 1));

    return resultMap;
  }
Example #21
0
 @ResponseBody
 @RequestMapping(
     value = "searchDeviceBYBBSA",
     method = RequestMethod.POST,
     produces = MediaTypes.JSON)
 public Map<String, Object> searchDeviceBYBBSA(
     @RequestParam("deviceIP") String deviceIP, HttpServletRequest request) {
   List<GroupBean> groupBeanList = new ArrayList<GroupBean>();
   groupBeanList = deviceService.findDeviceByIP(entityManager, deviceIP);
   // groupBeanList=
   // deviceFilter.deviceFilterRole(groupBeanList,UserNameUtil.getUserNameByRequest(request));
   Map<String, Object> resultMap = new HashMap<String, Object>();
   resultMap.put("data", groupBeanList);
   return resultMap;
 }
  /**
   * Only for internal use
   *
   * <p>Count total for each control
   *
   * @param strArray
   * @param adminJdbcService
   * @return
   */
  private static Map countStringOccurences(String[] strArray, AdminJdbcService adminJdbcService) {
    logger.debug("Count String Occurences method found");

    Map<String, Integer> countMap = new TreeMap<String, Integer>();
    Map<String, Integer> controlIdsMap = new TreeMap<String, Integer>();
    Set<String> controlIdsSet = new TreeSet<String>();
    Set<String> keySet = countMap.keySet();
    List list = new ArrayList();

    for (String string : strArray) {
      String control[] = string.split(":");
      if (!Utils.isNullOrEmpty(control[1]) && Integer.parseInt(control[1].trim()) == 2) {
        if (!countMap.containsKey(control[0])) {
          countMap.put(control[0], 1);
        } else {
          Integer count = countMap.get(control[0]);
          count = count + 1;
          countMap.put(control[0], count);
        }
      }
    }

    return countMap;
  }
Example #23
0
  /**
   * 지정한 조건의 파일 처리 이력을 조회한다.
   *
   * <p>auditConditionMap 처리 이력 조건 정보
   *
   * @return 파일 처리 목록
   */
  @RequestMapping(value = "list", method = RequestMethod.GET)
  @ResponseStatus(HttpStatus.OK)
  @ResponseBody
  public Response getAuditHistories(
      @RequestParam String clusterName,
      @RequestParam(defaultValue = "") String startDate,
      @RequestParam(defaultValue = "") String endDate,
      @RequestParam(defaultValue = "") String path,
      @RequestParam(defaultValue = "ALL") String auditType,
      @RequestParam(defaultValue = "0") int nextPage,
      @RequestParam(defaultValue = "10") int limit) {

    EngineService engineService = this.getEngineService(clusterName);
    FileSystemAuditRemoteService service = engineService.getFileSystemAuditRemoteService();
    int level = getSessionUserLevel();
    String username = level == 1 ? "" : getSessionUsername();
    int totalRows =
        service.getTotalCountOfAuditHistories(startDate, endDate, path, auditType, username);

    Map auditConditionMap = new HashMap();

    auditConditionMap.put("level", level);
    auditConditionMap.put("username", username);
    auditConditionMap.put("startDate", startDate);
    auditConditionMap.put("endDate", endDate);
    auditConditionMap.put("path", path);
    auditConditionMap.put("auditType", auditType);
    auditConditionMap.put("nextPage", nextPage);
    auditConditionMap.put("limit", limit);

    List<AuditHistory> auditHistories = service.getAuditHistories(auditConditionMap);

    Response response = new Response();
    response.getList().addAll(auditHistories);
    response.setTotal(totalRows);
    response.setSuccess(true);

    return response;
  }
  /** @return poolConfigurationId => poolStatus map. */
  @RequestMapping(value = "/admin/pools/status", method = RequestMethod.GET)
  @ResponseBody
  public Map<Long, PoolStatus> getPoolsStatus() {
    Map<Long /* poolConfigurationId */, PoolStatus> resultMap = new HashMap<Long, PoolStatus>();
    // get pool status for all pools
    Collection<PoolStatus> poolStatuses = poolManagerApi.listStatuses();
    // map every status found to its pool configuration
    List<PoolConfigurationModel> poolConfigurationModels = poolDao.readPools();
    for (PoolConfigurationModel poolConfiguration : poolConfigurationModels) {
      Long poolConfigurationId = poolConfiguration.getId();

      for (PoolStatus poolStatus : poolStatuses) {
        if (poolStatus.getPoolId().equals(poolConfiguration.getPoolSettings().getUuid())) {
          resultMap.put(poolConfigurationId, poolStatus);
        }
      }
    }

    return resultMap;
  }
Example #25
0
  @RequestMapping
  public String lista(
      HttpServletRequest request,
      HttpServletResponse response,
      @RequestParam(required = false) String filtro,
      @RequestParam(required = false) Long pagina,
      @RequestParam(required = false) String tipo,
      @RequestParam(required = false) String correo,
      @RequestParam(required = false) String order,
      @RequestParam(required = false) String sort,
      Usuario usuario,
      Errors errors,
      Model modelo) {
    log.debug("Mostrando lista de tipos de entradas");
    Map<String, Object> params = new HashMap<>();
    params.put("almacen", request.getSession().getAttribute("almacenId"));
    if (StringUtils.isNotBlank(filtro)) {
      params.put("filtro", filtro);
    }
    if (pagina != null) {
      params.put("pagina", pagina);
      modelo.addAttribute("pagina", pagina);
    } else {
      pagina = 1L;
      modelo.addAttribute("pagina", pagina);
    }
    if (StringUtils.isNotBlank(order)) {
      params.put("order", order);
      params.put("sort", sort);
    }

    if (StringUtils.isNotBlank(tipo)) {
      params.put("reporte", true);
      params = entradaDao.lista(params);
      try {
        generaReporte(tipo, (List<Entrada>) params.get("entradas"), response);
        return null;
      } catch (JRException | IOException e) {
        log.error("No se pudo generar el reporte", e);
        params.remove("reporte");
        errors.reject("error.generar.reporte");
      }
    }

    if (StringUtils.isNotBlank(correo)) {
      params.put("reporte", true);
      params = entradaDao.lista(params);

      params.remove("reporte");
      try {
        enviaCorreo(correo, (List<Entrada>) params.get("entradas"), request);
        modelo.addAttribute("message", "lista.enviada.message");
        modelo.addAttribute(
            "messageAttrs",
            new String[] {
              messageSource.getMessage("entrada.lista.label", null, request.getLocale()),
              ambiente.obtieneUsuario().getUsername()
            });
      } catch (JRException | MessagingException e) {
        log.error("No se pudo enviar el reporte por correo", e);
      }
    }
    params = entradaDao.lista(params);
    modelo.addAttribute("entradas", params.get("entradas"));

    // inicia paginado
    Long cantidad = (Long) params.get("cantidad");
    Integer max = (Integer) params.get("max");
    Long cantidadDePaginas = cantidad / max;
    List<Long> paginas = new ArrayList<>();
    long i = 1;
    do {
      paginas.add(i);
    } while (i++ < cantidadDePaginas);
    List<Entrada> entradas = (List<Entrada>) params.get("entradas");
    Long primero = ((pagina - 1) * max) + 1;
    Long ultimo = primero + (entradas.size() - 1);
    String[] paginacion = new String[] {primero.toString(), ultimo.toString(), cantidad.toString()};
    modelo.addAttribute("paginacion", paginacion);
    modelo.addAttribute("paginas", paginas);
    // termina paginado

    return "inventario/entrada/lista";
  }
  /**
   * control list with applied in no of Project
   *
   * @param request
   * @return
   */
  @RequestMapping(
      value = "/icga/getJASONforProjectWiseControlList.html",
      method = RequestMethod.POST)
  public @ResponseBody JasonBean getProjectWiseControlCountList(HttpServletRequest request) {
    logger.debug("Project Wise Control List Controller ");
    String page = request.getParameter("page") != null ? request.getParameter("page") : "1";
    String rp = request.getParameter("rp") != null ? request.getParameter("rp") : "10";
    String sortname =
        request.getParameter("sortname") != null ? request.getParameter("sortname") : "projectName";
    String sortorder =
        request.getParameter("sortorder") != null ? request.getParameter("sortorder") : "desc";
    String query = request.getParameter("query") != null ? request.getParameter("query") : "false";
    String qtype = request.getParameter("qtype") != null ? request.getParameter("qtype") : "false";
    String controlIdsListAsString =
        request.getParameter("controlId") != null ? request.getParameter("controlId") : "";

    String tableName =
        request.getParameter("tableName") != null ? request.getParameter("tableName") : "";

    List dbColumnList = TransactionSearchController.getDbColumnHeaderList(request, tableName);
    sortname =
        dbColumnList != null
            ? RealTimeMonitoringController.getDbColumnNameByRef(dbColumnList, sortname)
            : null;
    logger.debug("SMN: controlIdsListAsString=" + controlIdsListAsString);

    List dbColumnHeaderList = new ArrayList();
    JasonBean jasonData = new JasonBean();

    int totalItems = 0;
    List<Cell> entry = new ArrayList<Cell>();
    List trxSearchList = new ArrayList<Control>();
    GlobalTransactionSearch globalTransactionSearch = new GlobalTransactionSearch();
    try {

      totalItems =
          adminJdbcService.getProjectWiseCountByControlIds(
              controlIdsListAsString,
              getStringForComparingControls(controlIdsListAsString),
              qtype,
              query,
              sortname,
              sortorder);
      trxSearchList =
          adminJdbcService.getProjectWiseCountListByControlIds(
              controlIdsListAsString,
              getStringForComparingControls(controlIdsListAsString),
              Utils.parseInteger(page),
              "max".equals(rp) ? totalItems : Utils.parseInteger(rp),
              qtype,
              query,
              sortname,
              sortorder);

      logger.debug("TOTAL count---" + totalItems + " page=" + page + " rp=" + rp);
      if ("max".equals(rp)) {
        TransactionSearchController.setTotalListSizeAndListInSession(
            totalItems, trxSearchList, request);
        jasonData.setTotal(totalItems);
      } else {
        if (trxSearchList != null) {
          int count = 0;
          logger.debug("trxSearchList size=" + trxSearchList.size());
          jasonData.setPage(Utils.parseInteger(page));
          for (Object obj : trxSearchList) {
            RealTimeProject realTimeProject = new RealTimeProject();
            Cell cell = new Cell();
            Map map = (Map) obj;

            realTimeProject.setProjectName(
                map.get("project") != null ? map.get("project").toString() : "");
            realTimeProject.setTransactionIds(
                map.get("transaction_ids") != null ? map.get("transaction_ids").toString() : "");
            realTimeProject.setTotal(map.get("total") != null ? map.get("total").toString() : "");
            realTimeProject.setProjectType(
                map.get("projectType") != null ? map.get("projectType").toString() : "");
            realTimeProject.setProjectId(
                map.get("projectId") != null ? map.get("projectId").toString() : "");

            cell.setId(count++);
            cell.setCell(realTimeProject);
            entry.add(cell);
          }

          Map mapForHeader = new HashMap();
          mapForHeader.put(
              "projectName", "project"); // key=flexigrid parameter name, value = dbField Name
          mapForHeader.put("transactionIds", "transaction_ids");
          mapForHeader.put("total", "total");
          mapForHeader.put("projectId", "projectId");
          mapForHeader.put("projectType", "projectType");
          dbColumnHeaderList.add(mapForHeader);
          request.getSession().setAttribute(tableName, dbColumnHeaderList);

          jasonData.setRows(entry);
          jasonData.setTotal(totalItems);
          jasonData.setDbColumnHeader(dbColumnHeaderList);
        } else {
          logger.debug("No Transaction Search List Found");
        }
      }

    } catch (Exception ex) {
      logger.debug("CERROR:Project Wise Control Exception : " + ex);
    }

    return jasonData;
  }
  /**
   * control list with applied in no of transaction
   *
   * @param request
   * @return
   */
  @RequestMapping(value = "/icga/getJASONforExistingControlList.html", method = RequestMethod.POST)
  public @ResponseBody JasonBean getAssignmentList(HttpServletRequest request) {
    logger.debug("Control List Controller ");
    String page = request.getParameter("page") != null ? request.getParameter("page") : "1";
    String rp = request.getParameter("rp") != null ? request.getParameter("rp") : "10";
    String sortname =
        request.getParameter("sortname") != null ? request.getParameter("sortname") : "projectName";
    String sortorder =
        request.getParameter("sortorder") != null ? request.getParameter("sortorder") : "desc";
    String query = request.getParameter("query") != null ? request.getParameter("query") : "false";
    String qtype = request.getParameter("qtype") != null ? request.getParameter("qtype") : "false";

    String controlIds =
        request.getParameter("controlIds") != null ? request.getParameter("controlIds") : "0";
    String tableName =
        request.getParameter("tableName") != null ? request.getParameter("tableName") : "";

    String controlIdsListAsString = "";

    JasonBean jasonData = new JasonBean();
    List dbColumnHeaderList = new ArrayList();
    int totalControl = 0;
    List controlList = new ArrayList();
    List<Cell> entry = new ArrayList<Cell>();
    List allControlList = new ArrayList<Cell>();
    Map<String, Integer> countMap = new TreeMap<String, Integer>();

    try {
      String partSql =
          !"0".equals(controlIds)
              ? InternalControlGapAnalysisController.getStringForComparingControls(controlIds)
              : "";
      allControlList = adminJdbcService.getControlIdList(controlIds, partSql);
      controlIdsListAsString = getCommaseparatedStringFromList(allControlList);
      String[] controllIdsArray =
          !"0".equals(controlIds)
              ? getUsedControlsByControlIds(controlIds, controlIdsListAsString.split(","))
              : controlIdsListAsString.split(",");

      countMap = countStringOccurences(controllIdsArray, adminJdbcService);
      if (countMap != null && countMap.size() > 0) {
        logger.debug("AMLOG:: countMap size: " + countMap.size());
        jasonData.setPage(Utils.parseInteger(page));

        for (String string : countMap.keySet()) {
          Map map = new HashMap();
          Long controlId = !Utils.isEmpty(string) ? Long.parseLong(string) : 0;
          logger.debug("AMLOG:: controlId: " + controlId);
          //                        Control control = new Control();
          Cell cell = new Cell();
          Control control =
              controlId > 0
                  ? (Control) adminService.loadEntityById(controlId, Constants.CONTROL)
                  : new Control();
          /*control.setId(controlId);
          control.setName(controlName);*/
          control.setTotalUsed(countMap.get(string));
          cell.setCell(control);
          entry.add(cell);

          map.put("control_name", control.getName());
          map.put("transaction_type", control.getTransactionType());
          map.put("total", countMap.get(string));
          controlList.add(map);
        }
        int totalItem = controlList != null ? controlList.size() : 0;

        Map mapForHeader = new HashMap();
        mapForHeader.put(
            "name", "control_name"); // key=flexigrid parameter name, value = dbField Name
        mapForHeader.put("transactionType", "transaction_type");
        mapForHeader.put("totalUsed", "total");
        dbColumnHeaderList.add(mapForHeader);
        request.getSession().setAttribute(tableName, dbColumnHeaderList);

        jasonData.setRows(entry);
        jasonData.setTotal(totalItem);
        jasonData.setDbColumnHeader(dbColumnHeaderList);

        if ("max".equals(rp)) {
          logger.debug("SMN LOG: custom controlList size=" + controlList.size());
          TransactionSearchController.setTotalListSizeAndListInSession(
              totalItem, controlList, request);
        }
      }
    } catch (Exception ex) {
      logger.debug("CERROR: Real Time Project exception : " + ex);
    }

    return jasonData;
  }
 private void putInputConstraint(String key, Object defaultValue, Object value) {
   if (!value.equals(defaultValue)) {
     inputConstraints.put(key, value);
   }
 }
  // Get project status
  @RequestMapping(value = "/{userId}/status", method = RequestMethod.GET)
  public String showStatus(@PathVariable Long userId, ModelMap model) throws SQLException {
    User u = (User) userDao.getUserById(userId).get(0);
    Project p = (Project) userDao.getProjectById(userId).get(0);

    if (u.getTenanttype().contentEquals("kanban")) {
      List l = userDao.cardCount(userId);
      List<Object[]> resultList = l;
      Map<String, Integer> resultMap = new HashMap<>(resultList.size());
      int a[] = new int[4];
      int i = 0;

      for (Object[] result : resultList) {
        String name = (String) result[0];
        int count = ((Number) result[1]).intValue();
        a[i] = count;
        i++;
        resultMap.put(name, count);
      }
      model.addAttribute("a", a);
    } else if (u.getTenanttype().contentEquals("scrum")) {

      List<Long> t = userDao.tCount(userId);
      List<Long> r = userDao.rCount(userId);

      Long tr = t.get(0);
      Long rr = r.get(0);

      int tHours = Long.valueOf(tr).intValue();
      int rHours = Long.valueOf(rr).intValue();

      List<Integer> actual = new ArrayList<>();
      List<Integer> initial = new ArrayList<>();

      int burnDown = 2 * 5;

      while (rHours > 0) {
        actual.add(rHours);
        rHours = rHours - burnDown;
      }

      while (tHours > 0) {
        initial.add(tHours);
        tHours = tHours - burnDown;
      }
      int k = 0;
      int l = 1;

      List<Integer[]> dataArray = new ArrayList<>();
      for (int item : actual) {
        Integer[] o = {k, item, initial.get(k)};
        dataArray.add(o);
        k++;
      }

      if (initial.size() > actual.size()) {
        for (int item : initial) {
          if (l > actual.size()) {
            Integer[] o = {l, 0, item};
            dataArray.add(o);
          }
          l++;
        }
        Integer[] o = {l, 0, 0};
        dataArray.add(o);
      } else if (initial.size() < actual.size()) {
        for (int item : initial) {
          if (l > initial.size()) {
            Integer[] o = {l, item, 0};
            dataArray.add(o);
          }
          l++;
        }
        Integer[] o = {l, 0, 0};
        dataArray.add(o);
      } else if (initial.size() == actual.size()) {
        Integer[] o = {k, 0, 0};
        dataArray.add(o);
      }
      model.addAttribute("dataArray", dataArray);
    } else if (u.getTenanttype().contentEquals("waterfall")) {

      List l = userDao.taskCount(userId);
      List<Object[]> resultList = l;
      Map<String, Integer> resultMap = new HashMap<>(resultList.size());
      int a[] = {0, 0, 0};

      for (Object[] result : resultList) {
        String name = (String) result[0];
        int count = ((Number) result[1]).intValue();
        if (name.contentEquals("Requested")) {
          a[0] = count;
        } else if (name.contentEquals("In Progress")) {
          a[1] = count;
        } else if (name.contentEquals("Completed")) {
          a[2] = count;
        }
        resultMap.put(name, count);
      }
      model.addAttribute("a", a);
    }

    model.addAttribute("tenant", u.getTenanttype());
    model.addAttribute("project", p.getProjectname());
    model.addAttribute("userid", userId);

    return "Status";
  }