private static String getCommaseparatedStringFromList(List controllIdList) {
    StringBuilder result = new StringBuilder();

    for (int i = 0; i < controllIdList.size(); i++) {
      Map map = (Map) controllIdList.get(i);
      if (map.get("control_ids") != null) {
        result.append(map.get("control_ids"));
        result.append(",");
      }
    }
    return result.length() > 0 ? result.substring(0, result.length() - 1) : "";
  }
Exemple #2
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;
 }
 /**
  * 填充数据
  *
  * @param list 数据库有效数据列表
  * @return 填充的数据
  */
 private <T extends TrendValue> List<T> fulldata(
     List<T> list, DateFormat format, int field, Date start, Date end, Class<T> clazz) {
   Map<String, T> map = tomap(list);
   Calendar calendar = Calendar.getInstance();
   calendar.setTime(start);
   List<T> nlist = new ArrayList<>();
   while (calendar.getTime().before(end)) {
     String keytime = format.format(calendar.getTime());
     T value = map.get(keytime);
     if (value == null) {
       value = AfReflecter.newInstance(clazz);
       value.setEmpty();
       value.setDate(keytime);
       value.setTime(calendar.getTime());
       nlist.add(value);
     } else {
       nlist.add(value);
       map.remove(keytime);
     }
     calendar.add(field, 1);
   }
   for (Map.Entry<String, T> entry : map.entrySet()) {
     nlist.add(entry.getValue());
   }
   return nlist;
 }
 @ModelAttribute("poolSettings")
 public PoolSettings getPoolSettings(
     /*@PathVariable("accountId") Long accountId,
     @PathVariable("poolId") Long poolId */ HttpServletRequest request) {
   //        return getAccountPool( accountId, poolId ).getPoolSettings();
   Map pathVariables =
       (Map)
           request.getAttribute(
               "org.springframework.web.servlet.HandlerMapping.uriTemplateVariables");
   if (pathVariables.containsKey("accountId") && pathVariables.containsKey("poolId")) {
     long accountId = Long.parseLong((String) pathVariables.get("accountId"));
     long poolId = Long.parseLong((String) pathVariables.get("poolId"));
     return poolDao.readPoolByIdAndAccountId(poolId, accountId).getPoolSettings();
   } else {
     return null;
   }
 }
 /*
  * TODO: Refactor this code.
  */
 private byte[] signMethod(Map<String, String> parameters) throws NoSuchAlgorithmException {
   String toHash = "";
   List<String> paramNames = new ArrayList<String>(parameters.keySet());
   Collections.sort(paramNames);
   for (String paramName : paramNames) {
     toHash += paramName + parameters.get(paramName);
   }
   toHash += SECRET;
   byte[] hashMe = toHash.getBytes();
   MessageDigest mg = MessageDigest.getInstance("md5");
   hashMe = mg.digest(hashMe);
   return hashMe;
 }
  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;
  }
 @Scheduled(cron = "${scheduled.cron}")
 public void countTechnicalJobs() {
   jsonConfigRepository
       .getSkillConfig()
       .stream()
       .forEach(
           term -> {
             Map<String, Double> avgSalary =
                 vietnamWorksJobStatisticService.getAverageSalaryBySkill(term, JOB_LEVEL_ALL);
             messagingTemplate.convertAndSend(
                 "/topic/jobs/term/" + term.getKey(),
                 new TechnicalTermResponse.Builder()
                     .withTerm(term.getKey())
                     .withLabel(term.getLabel())
                     .withAverageSalaryMin(avgSalary.get("SALARY_MIN"))
                     .withAverageSalaryMax(avgSalary.get("SALARY_MAX"))
                     .withCount(vietnamWorksJobStatisticService.count(term))
                     .build());
           });
 }
 @SendTo("/topic/jobs/terms")
 @MessageMapping("/jobs/terms")
 public List<TechnicalTermResponse> countTechnicalTerms() {
   List<TechnicalTermResponse> terms = new LinkedList<>();
   jsonConfigRepository
       .getSkillConfig()
       .stream()
       .forEach(
           term -> {
             Map<String, Double> avgSalary =
                 vietnamWorksJobStatisticService.getAverageSalaryBySkill(term, JOB_LEVEL_ALL);
             terms.add(
                 new TechnicalTermResponse.Builder()
                     .withTerm(term.getKey())
                     .withLabel(term.getLabel())
                     .withCount(vietnamWorksJobStatisticService.count(term))
                     .withAverageSalaryMin(avgSalary.get("SALARY_MIN"))
                     .withAverageSalaryMax(avgSalary.get("SALARY_MAX"))
                     .build());
           });
   return terms;
 }
Exemple #9
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;
 }
  /**
   * 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;
  }
Exemple #11
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";
  }
  @RequestMapping("/events/{eventName}/export.csv")
  public void downloadAllTicketsCSV(
      @PathVariable("eventName") String eventName,
      HttpServletRequest request,
      HttpServletResponse response,
      Principal principal)
      throws IOException {
    List<String> fields =
        Arrays.asList(
            Optional.ofNullable(request.getParameterValues("fields")).orElse(new String[] {}));
    Event event = loadEvent(eventName, principal);
    Map<Integer, TicketCategory> categoriesMap =
        eventManager
            .loadTicketCategories(event)
            .stream()
            .collect(Collectors.toMap(TicketCategory::getId, Function.identity()));
    ZoneId eventZoneId = event.getZoneId();

    Predicate<String> contains = FIXED_FIELDS::contains;

    response.setContentType("text/csv;charset=UTF-8");
    response.setHeader("Content-Disposition", "attachment; filename=" + eventName + "-export.csv");

    try (ServletOutputStream out = response.getOutputStream();
        CSVWriter writer = new CSVWriter(new OutputStreamWriter(out))) {

      for (int marker :
          BOM_MARKERS) { // UGLY-MODE_ON: specify that the file is written in UTF-8 with BOM, thanks
                         // to alexr http://stackoverflow.com/a/4192897
        out.write(marker);
      }

      writer.writeNext(fields.toArray(new String[fields.size()]));

      eventManager
          .findAllConfirmedTickets(eventName, principal.getName())
          .stream()
          .map(
              t -> {
                List<String> line = new ArrayList<>();
                if (fields.contains("ID")) {
                  line.add(t.getUuid());
                }
                if (fields.contains("creation")) {
                  line.add(t.getCreation().withZoneSameInstant(eventZoneId).toString());
                }
                if (fields.contains("category")) {
                  line.add(categoriesMap.get(t.getCategoryId()).getName());
                }
                if (fields.contains("event")) {
                  line.add(eventName);
                }
                if (fields.contains("status")) {
                  line.add(t.getStatus().toString());
                }
                if (fields.contains("originalPrice")) {
                  line.add(MonetaryUtil.centsToUnit(t.getSrcPriceCts()).toString());
                }
                if (fields.contains("paidPrice")) {
                  line.add(MonetaryUtil.centsToUnit(t.getFinalPriceCts()).toString());
                }
                if (fields.contains("discount")) {
                  line.add(MonetaryUtil.centsToUnit(t.getDiscountCts()).toString());
                }
                if (fields.contains("vat")) {
                  line.add(MonetaryUtil.centsToUnit(t.getVatCts()).toString());
                }
                if (fields.contains("reservationID")) {
                  line.add(t.getTicketsReservationId());
                }
                if (fields.contains("Full Name")) {
                  line.add(t.getFullName());
                }
                if (fields.contains("First Name")) {
                  line.add(t.getFirstName());
                }
                if (fields.contains("Last Name")) {
                  line.add(t.getLastName());
                }
                if (fields.contains("E-Mail")) {
                  line.add(t.getEmail());
                }
                if (fields.contains("locked")) {
                  line.add(String.valueOf(t.getLockedAssignment()));
                }
                if (fields.contains("Language")) {
                  line.add(String.valueOf(t.getUserLanguage()));
                }

                // obviously not optimized
                Map<String, String> additionalValues =
                    ticketFieldRepository.findAllValuesForTicketId(t.getId());

                fields
                    .stream()
                    .filter(contains.negate())
                    .forEachOrdered(
                        field -> {
                          line.add(additionalValues.getOrDefault(field, "").replaceAll("\"", ""));
                        });

                return line.toArray(new String[line.size()]);
              })
          .forEachOrdered(writer::writeNext);
      writer.flush();
      out.flush();
    }
  }
  /**
   * 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;
  }
  /**
   * 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;
  }