/** 得到日期字符串 默认格式(yyyy-MM-dd) pattern可以为:"yyyy-MM-dd" "HH:mm:ss" "E" */
 public static String formatDate(Date date, Object... pattern) {
   String formatDate = null;
   if (pattern != null && pattern.length > 0) {
     formatDate = DateFormatUtils.format(date, pattern[0].toString());
   } else {
     formatDate = DateFormatUtils.format(date, "yyyy-MM-dd");
   }
   return formatDate;
 }
 /*
  * (non-Javadoc)
  *
  * @see org.talend.dataquality.indicators.impl.FrequencyIndicatorImpl#handle(java.lang.Object)
  */
 @Override
 public boolean handle(Object data) {
   if (data == null) {
     return super.handle(data);
   }
   if (data instanceof Date) {
     // add the quater pattern for each data.
     String monthStr = DateFormatUtils.format((Date) data, monthSign);
     int month = Integer.parseInt(monthStr) / 4 + 1;
     String format = DateFormatUtils.format((Date) data, datePattern + month);
     return super.handle(format);
   }
   return super.handle(data);
 }
Exemple #3
0
  public void addListPolicies(List parent, DSpaceObject dso, Collection owningCollection)
      throws WingException, SQLException {
    if (!isAdvancedFormEnabled) {
      return;
    }
    parent.addLabel(T_head_policies_table);

    java.util.List<ResourcePolicy> resourcePolicies =
        authorizeService.findPoliciesByDSOAndType(context, dso, ResourcePolicy.TYPE_CUSTOM);
    if (resourcePolicies.isEmpty()) {
      parent.addItem(T_no_policies);
      return;
    }

    for (ResourcePolicy rp : resourcePolicies) {
      int id = rp.getID();

      String name = "";
      if (rp.getRpName() != null) name = rp.getRpName();

      String action = resourcePolicyService.getActionText(rp);

      // if it is the default policy for the Submitter don't show it.
      if (dso instanceof org.dspace.content.Item) {
        org.dspace.content.Item item = (org.dspace.content.Item) dso;
        if (rp.getEPerson() != null) {
          if (item.getSubmitter().equals(rp.getEPerson())) continue;
        }
      }

      String group = "";
      if (rp.getGroup() != null) group = rp.getGroup().getName();

      // start
      String startDate = "";
      if (rp.getStartDate() != null) {
        startDate = DateFormatUtils.format(rp.getStartDate(), "yyyy-MM-dd");
      }

      // endDate
      String endDate = "";
      if (rp.getEndDate() != null) {
        endDate = DateFormatUtils.format(rp.getEndDate(), "yyyy-MM-dd");
      }

      parent.addItem(T_policy.parameterize(name, action, group, startDate, endDate));
    }
  }
Exemple #4
0
  /**
   * @param list 数据源
   * @param fieldMap 类的英文属性和Excel中的中文列名的对应关系
   * @param sheetName 工作表的名称
   * @param sheetSize 每个工作表中记录的最大个数
   * @param response 使用response可以导出到浏览器
   * @throws ExcelException @MethodName : listToExcel @Description : 导出Excel(导出到浏览器,可以自定义工作表的大小)
   */
  public static <T> void listToExcel(
      List<T> list,
      LinkedHashMap<String, String> fieldMap,
      String sheetName,
      int sheetSize,
      HttpServletResponse response)
      throws ExcelException {
    // 文件名默认设置为当前时间:年月日时分秒
    String fileName = DateFormatUtils.format(new Date(), "yyyyMMddhhmmss");
    // 设置response头信息
    response.reset();
    response.setContentType("application/vnd.ms-excel");
    response.setHeader("Content-disposition", "attachment;filename=" + fileName + ".xls");

    // 创建工作簿并发送到浏览器
    try {
      OutputStream os = response.getOutputStream();
      listToExcel(list, fieldMap, sheetName, sheetSize, os);
    } catch (Exception e) {
      e.printStackTrace();

      // 如果是ExcelException,则直接抛出
      if (e instanceof ExcelException) {
        throw (ExcelException) e;
      } else {
        // 否则将其他异常包装成ExcelException再抛出
        throw new ExcelException("导出excel失败");
      }
    }
  }
  @GET
  @Path("/patientList")
  @Produces("application/json")
  public AbstractSearchResponse<AdmissionTo1> getPatientList(
      @QueryParam("programNo") String programNo,
      @QueryParam("day") String day,
      @QueryParam("startIndex") Integer startIndex,
      @QueryParam("numToReturn") Integer numToReturn)
      throws Exception {

    AbstractSearchResponse<AdmissionTo1> response = new AbstractSearchResponse<AdmissionTo1>();

    if (day == null) {
      day = DateFormatUtils.format(Calendar.getInstance(), DateUtils.ISO8601_DATE_PATTERN);
    }

    Date d = new SimpleDateFormat(DateUtils.ISO8601_DATE_PATTERN).parse(day);

    if (programNo == null) {
      // get default
      ProgramProvider current = null;
      ProgramProvider pp =
          programManager.getCurrentProgramInDomain(
              getLoggedInInfo(), getLoggedInInfo().getLoggedInProviderNo());
      if (pp != null) {
        current = pp;
      } else {
        List<ProgramProvider> ppList =
            programManager.getProgramDomain(
                getLoggedInInfo(), getLoggedInInfo().getLoggedInProviderNo());
        if (ppList.size() > 0) {
          current = ppList.get(0);
        }
      }
      if (current != null) {
        programNo = String.valueOf(current.getProgramId());
      }
    }

    if (programNo == null) {
      throw new Exception("Can't get a program for this provider to use as default");
    }

    List<AdmissionTo1> transfers =
        new AdmissionConverter()
            .includeDemographic(true)
            .getAllAsTransferObjects(
                getLoggedInInfo(),
                admissionManager.findAdmissionsByProgramAndDate(
                    getLoggedInInfo(), Integer.parseInt(programNo), d, startIndex, numToReturn));

    response.setContent(transfers);
    response.setTotal(
        admissionManager.findAdmissionsByProgramAndDateAsCount(
            getLoggedInInfo(), Integer.parseInt(programNo), d));

    return response;
  }
  public static String[] defaultHeader(
      String programName,
      String reportId,
      String headerLine1,
      String headerLine2,
      String headerLine3) {
    Calendar cal = Calendar.getInstance();
    String date = DateFormatUtils.format(cal, ReportingDefaultConstants.DATE_FORMAT);
    String time = DateFormatUtils.format(cal, ReportingDefaultConstants.TIME_FORMAT);

    String[] header =
        new String[] {
          "DATE:" + date + "~" + headerLine1 + "~PAGE: #",
          "TIME:" + time + "~" + headerLine2 + "~RPT : " + reportId,
          "PRGM:" + programName + "~" + headerLine3 + "~"
        };
    return header;
  }
Exemple #7
0
 public App printHours(String estado, String gmt) {
   System.out.println(" -----------------------------------");
   System.out.println(
       "Em "
           + estado
           + DateFormatUtils.format(
               new Date(), " dd/MM/yyyy HH:mm:ss ", TimeZone.getTimeZone(gmt)));
   System.out.println(" -----------------------------------");
   return this;
 }
  public List<Map<String, Object>> getQrtzTriggers() {
    List<Map<String, Object>> results =
        getJdbcTemplate().queryForList("select * from QRTZ_TRIGGERS order by start_time");
    long val = 0;
    String temp = null;
    for (Map<String, Object> map : results) {
      temp = MapUtils.getString(map, "trigger_name");
      if (StringUtils.indexOf(temp, "&") != -1) {
        map.put("display_name", StringUtils.substringBefore(temp, "&"));
      } else {
        map.put("display_name", temp);
      }

      val = MapUtils.getLongValue(map, "next_fire_time");
      if (val > 0) {
        map.put("next_fire_time", DateFormatUtils.format(val, "yyyy-MM-dd HH:mm:ss"));
      }

      val = MapUtils.getLongValue(map, "prev_fire_time");
      if (val > 0) {
        map.put("prev_fire_time", DateFormatUtils.format(val, "yyyy-MM-dd HH:mm:ss"));
      }

      val = MapUtils.getLongValue(map, "start_time");
      if (val > 0) {
        map.put("start_time", DateFormatUtils.format(val, "yyyy-MM-dd HH:mm:ss"));
      }

      val = MapUtils.getLongValue(map, "end_time");
      if (val > 0) {
        map.put("end_time", DateFormatUtils.format(val, "yyyy-MM-dd HH:mm:ss"));
      }

      map.put("statu", Constant.status.get(MapUtils.getString(map, "trigger_state")));
    }

    return results;
  }
Exemple #9
0
  /**
   * 8、日期
   *
   * @throws ParseException
   */
  @Test
  public void test8() throws ParseException {
    // 生成Date对象
    Date date = DateUtils.parseDate("2010/01/01 11:22:33", new String[] {"yyyy/MM/dd HH:mm:ss"});

    // 10天后
    Date tenDaysAfter = DateUtils.addDays(date, 10); // => 2010/01/11
    // 11:22:33
    System.out.println(DateFormatUtils.format(tenDaysAfter, "yyyy/MM/dd HH:mm:ss"));

    // 前一个月
    Date prevMonth = DateUtils.addMonths(date, -1); // => 2009/12/01
    // 11:22:33
    System.out.println(DateFormatUtils.format(prevMonth, "yyyy/MM/dd HH:mm:ss"));

    // 判断是否是同一天
    Date date1 = DateUtils.parseDate("2010/01/01 11:22:33", new String[] {"yyyy/MM/dd HH:mm:ss"});
    Date date2 = DateUtils.parseDate("2010/01/01 22:33:44", new String[] {"yyyy/MM/dd HH:mm:ss"});
    System.out.println(DateUtils.isSameDay(date1, date2)); // true

    // 日期格式化
    System.out.println(DateFormatUtils.format(new Date(), "yyyy/MM/dd HH:mm:ss"));
  }
  @Override
  @Transactional
  public OrderPayment genOrderPayment(Long buyerId, Long masterOrderId) {

    OrderMasterDTO master = orderService.loadOrderMasterDTO(masterOrderId);
    if (master != null
        && master.getBuyerId().longValue() == buyerId.longValue()
        && master.getPaymentType().intValue() == OrderConstants.PaymentType.ONLINE_PAY.getValue()) {
      if (master.getStatus().intValue() == OrderConstants.OrderMasterStatus.WAIT_PAY.getValue()) {
        OrderPayment query = new OrderPayment();
        query.setMasterOrderId(master.getId());
        query.setBuyerId(buyerId);
        OrderPayment payment = dao.selectOne(query);
        if (payment != null) {
          if (payment.getPayStatus().intValue() == OrderConstants.PaymentStatus.PAYED.getValue()) {
            throw new BizException("order.payment.has.payed");
          }
        } else {
          payment = new OrderPayment();
          payment.setId(null);
          payment.setPayNo("P" + DateFormatUtils.format(new Date(), "yyyyMMddHHmmssSSS"));
          payment.setMasterOrderId(master.getId());
          payment.setMasterOrderNo(master.getMasterOrderNo());
          payment.setTradeNo("");
          payment.setNeedPayAmount(master.getNeedPayAmount());
          payment.setPayedAmount(null);
          payment.setRefundAmount(null);
          payment.setPayStatus(OrderConstants.PaymentStatus.WAITING_PAY.getValue());
          payment.setPaymentType(master.getPaymentType());
          payment.setPayMethod(null);
          //			    payment.setAccountType(accountType);
          //			    payment.setAccountName(accountName);
          //			    payment.setBankCode(bankCode);
          //			    payment.setAccountNo(accountNo);
          payment.setSubmitTime(new Date());
          payment.setPayedTime(null);
          //			    payment.setpayeeId;
          //			    payment.setpayeeName;
          //			    payment.setpayeeTime;
          payment.setBuyerId(buyerId);
          dao.insert(payment);
        }
        return payment;
      } else {
        throw new BizException("order.payment.status.invalid");
      }
    } else {
      throw new BizException("order.payment.parameter.invalid");
    }
  }
Exemple #11
0
 /**
  * 根据身份证号码查询借款申请信息
  *
  * @return
  * @author: huangzlmf
  * @date: 2015年4月21日 10:14:18
  */
 @RequestMapping("/getByIdNoGroup")
 @ResponseBody
 public Map<String, Object> getByIdNoGroup(String idNo) {
   logger.info("----Start:getByIdNoGroup;idNo=" + idNo + ";");
   Map<String, Object> map = new HashMap<String, Object>();
   if (StringUtils.isBlank(idNo)) {
     map.put("error", true);
     map.put("message", "参数有误!");
     logger.info("----End:getByIdNoGroup;idNo=" + idNo + ";message=参数有误!");
     return map;
   }
   LoanDo loanDo = loanApplyService.getByIdNoGroup(idNo);
   if (loanDo == null) {
     map.put("error", true);
     map.put("message", "身份证号码不存在!");
     logger.info("----End:getByIdNoGroup;idNo=" + idNo + ";message=身份证号码不存在!");
     return map;
   }
   map.put("error", false);
   map.put("realName", loanDo.getRealName());
   map.put("loanStatus", loanDo.getLoanStatus());
   map.put("applyDate", DateFormatUtils.format(loanDo.getCreateTime(), "yyyy-MM-dd"));
   if (loanDo.getLoanStatus().equals(LoanStatus.SUBJECTED)
       || loanDo.getLoanStatus().equals(LoanStatus.REPAYING)) {
     map.put("auditDate", DateFormatUtils.format(loanDo.getUpdateTime(), "yyyy-MM-dd"));
   } else {
     map.put("auditDate", "");
   }
   if (loanDo.getLoanStatus().equals(LoanStatus.REPAYING)) {
     map.put("loanDate", DateFormatUtils.format(loanDo.getLoanTime(), "yyyy-MM-dd"));
   } else {
     map.put("loanDate", "");
   }
   logger.info("----End:getByIdNoGroup;idNo=" + idNo + ";");
   return map;
 }
Exemple #12
0
 private File getLogFile(String taskId) {
   String yearMonthString =
       Calendar.getInstance().get(Calendar.YEAR)
           + "-"
           + (Calendar.getInstance().get(Calendar.MONTH) + 1);
   File logsMonthDir = new File(getLogsDir(), yearMonthString);
   logsMonthDir.mkdir();
   File logFile =
       new File(
           logsMonthDir,
           taskId
               + "_"
               + DateFormatUtils.format(new Date(), TimeUtil.LONG_DATE_FORMAT_COMPACT)
               + ".log");
   return logFile;
 }
 @SuppressWarnings("unchecked")
 private void processCommandQueryDescList(ProcessorContext context, DataOutputStream dos)
     throws IOException {
   dos.writeInt(context.getHeadWrapper().getHead());
   dos.writeInt(0); /*result*/
   List<GameRecordDesc> descList = (List<GameRecordDesc>) context.getResult();
   if (descList != null && descList.size() > 0) {
     dos.writeShort(descList.size());
     for (GameRecordDesc desc : descList) {
       dos.writeInt(desc.getRecordId());
       dos.writeInt(desc.getPlayDuration());
       dos.writeInt(desc.getScores());
       dos.writeUTF(desc.getRemark());
       dos.writeUTF(DateFormatUtils.format(desc.getTime(), "yyyy/MM/dd HH:mm:ss"));
     }
   } else {
     dos.writeShort(0);
   }
 }
 public static List<String> getDataList() throws Exception {
   List<String> resList = new ArrayList<String>();
   Queue<String> queue = map.get(RedisCacheThreadLocal.getUuid());
   while (true) {
     String obj = queue.poll();
     if (obj == null || resList.size() > 100) {
       break;
     }
     String[] logArr = obj.split(" ");
     if (logArr != null && logArr.length > 0) {
       try {
         logArr[0] =
             DateFormatUtils.format(
                 new Double(Double.parseDouble(logArr[0]) * 1000).longValue(),
                 "yyyy-MM-dd HH:mm:ss");
       } catch (Exception e) {
       }
     }
     resList.add(StringUtils.join(logArr, " "));
   }
   return resList;
 }
Exemple #15
0
  public void addEmbargoDateSimpleForm(DSpaceObject dso, List form, int errorFlag)
      throws SQLException, WingException {

    String date = null;

    if (dso != null) {
      java.util.List<ResourcePolicy> policies =
          authorizeService.findPoliciesByDSOAndType(context, dso, ResourcePolicy.TYPE_CUSTOM);
      if (policies.size() > 0) {
        ResourcePolicy rp = policies.get(0);
        if (rp.getStartDate() != null) {
          date = DateFormatUtils.format(rp.getStartDate(), "yyyy-MM-dd");
        }
        globalReason = rp.getRpDescription();
      }
    }
    //        CheckBox privateCheckbox = form.addItem().addCheckBox("emabrgo_option");
    //        privateCheckbox.setLabel(T_item_embargoed);
    //        if(date!=null){
    //            privateCheckbox.addOption(true, CB_EMBARGOED, "");
    //        }
    //        else{
    //            privateCheckbox.addOption(false, CB_EMBARGOED, "");
    //        }

    // Date
    Text startDate = form.addItem().addText("embargo_until_date");
    startDate.setLabel(T_item_embargoed);
    if (errorFlag == org.dspace.submit.step.AccessStep.STATUS_ERROR_FORMAT_DATE) {
      startDate.addError(T_error_date_format);
    } else if (errorFlag == org.dspace.submit.step.AccessStep.STATUS_ERROR_MISSING_DATE) {
      startDate.addError(T_error_missing_date);
    }

    if (date != null) {
      startDate.setValue(date);
    }
    startDate.setHelp(T_label_date_help);
  }
 private void processCommandRead(ProcessorContext context, DataOutputStream dos)
     throws IOException {
   dos.writeInt(context.getHeadWrapper().getHead());
   GameRecord record = (GameRecord) context.getResult();
   if (record != null) {
     dos.writeInt(0);
     dos.writeInt(record.getRecordId());
     dos.writeInt(record.getPlayDuration());
     dos.writeInt(record.getScores());
     dos.writeUTF(record.getRemark());
     dos.writeUTF(DateFormatUtils.format(record.getTime(), "yyyy/MM/dd HH:mm:ss"));
     byte[] data = record.getData();
     if (data != null && data.length > 0) {
       dos.writeInt(data.length);
       dos.write(data, 0, data.length);
     } else {
       dos.writeInt(0);
     }
   } else {
     dos.writeInt(Constant.EC_RECORD_NOT_EXIST);
     dos.writeUTF("游戏记录不存在");
   }
 }
Exemple #17
0
 @Override
 public void serialize(Date value, JsonGenerator jgen, SerializerProvider provider)
     throws IOException, JsonProcessingException {
   jgen.writeString(DateFormatUtils.format(value, DATE_FORMAT));
 }
Exemple #18
0
 public static String formatDate(Date date) {
   if (date == null) return "";
   return DateFormatUtils.format(date, "yyyy-MM-dd");
 }
  private void assertKesi(KesiSCM kesi) {

    Assert.assertNotNull(kesi);
    Assert.assertEquals(
        "http://www.alert-project.eu/ontologies/alert_scm.owl#Repository1",
        kesi.getRepositoryUri().trim());

    Assert.assertEquals("1", kesi.getRevisionTag());

    Assert.assertEquals("Sasa Stojanovic", kesi.getAuthor().getName());
    Assert.assertEquals("*****@*****.**", kesi.getAuthor().getId());
    Assert.assertEquals("*****@*****.**", kesi.getAuthor().getEmail());

    Assert.assertEquals("Ivan Obradovic", kesi.getCommitter().getName());
    Assert.assertEquals("*****@*****.**", kesi.getCommitter().getId());
    Assert.assertEquals("*****@*****.**", kesi.getCommitter().getEmail());

    Assert.assertEquals(
        "2012-01-16 16:31", DateFormatUtils.format(kesi.getDate(), "yyyy-MM-dd HH:mm"));

    Assert.assertEquals("comment of commit", kesi.getMessageLog().trim());

    List<KesiSCM.File> files = kesi.getFiles();
    Assert.assertEquals(2, files.size());

    Iterator<KesiSCM.File> iterator = files.iterator();

    KesiSCM.File file1 = iterator.next();

    Assert.assertEquals("Add", file1.getAction());
    Assert.assertEquals("branch1", file1.getBranch());

    List<KesiSCM.File.Module> modules = file1.getModules();
    Assert.assertEquals(2, modules.size(), 0);

    Iterator<KesiSCM.File.Module> fileModules1 = modules.iterator();
    KesiSCM.File.Module next = fileModules1.next();
    Assert.assertEquals("Mod111", next.getName());
    Assert.assertEquals(100, next.getStartLine(), 0);
    Assert.assertEquals(199, next.getEndLine(), 0);

    List<KesiSCM.File.Module.Methods> methods = next.getMethods();

    Iterator<KesiSCM.File.Module.Methods> moduleMethods1 = methods.iterator();
    KesiSCM.File.Module.Methods mm1 = moduleMethods1.next();
    Assert.assertEquals("Meth111", mm1.getName());
    Assert.assertEquals(100, mm1.getStartLine(), 0);
    Assert.assertEquals(149, mm1.getEndLine(), 0);

    KesiSCM.File.Module.Methods mm2 = moduleMethods1.next();
    Assert.assertEquals("Meth112", mm2.getName());
    Assert.assertEquals(150, mm2.getStartLine(), 0);
    Assert.assertEquals(199, mm2.getEndLine(), 0);

    KesiSCM.File file2 = iterator.next();

    Assert.assertEquals("Copy", file2.getAction());
    Assert.assertEquals("branch2", file2.getBranch());

    List<KesiSCM.File.Module> file2Modules = file2.getModules();
    Assert.assertEquals(1, file2Modules.size(), 0);

    Iterator<KesiSCM.File.Module> file2ModulesIterator = file2Modules.iterator();
    KesiSCM.File.Module fm2i1 = file2ModulesIterator.next();

    Assert.assertEquals("Mod2111", fm2i1.getName());
    Assert.assertEquals(300, fm2i1.getStartLine(), 0);
    Assert.assertEquals(399, fm2i1.getEndLine(), 0);

    List<KesiSCM.File.Module.Methods> fm2i1Methods = fm2i1.getMethods();
    Assert.assertEquals(1, fm2i1Methods.size(), 0);

    Iterator<KesiSCM.File.Module.Methods> fm2iMethodsIterator = fm2i1Methods.iterator();

    KesiSCM.File.Module.Methods fm2im1 = fm2iMethodsIterator.next();
    Assert.assertEquals("Meth211", fm2im1.getName());
    Assert.assertEquals(300, fm2im1.getStartLine(), 0);
    Assert.assertEquals(399, fm2im1.getEndLine(), 0);
  }
Exemple #20
0
 public int getDate10() {
   return NumberUtils.toInt(DateFormatUtils.format(addTime, "yyyyMMddHH"));
 }
Exemple #21
0
 /**
  * Formats a timestamp in the format expected by Sentry.
  *
  * @param timestamp timestamp to format
  * @return formatted timestamp
  */
 protected String formatTimestamp(long timestamp) {
   return DateFormatUtils.formatUTC(timestamp, DateFormatUtils.ISO_DATETIME_FORMAT.getPattern());
 }
Exemple #22
0
 public String getModified() {
   return DateFormatUtils.format(project.getModified(), "dd/MM/yy HH:mm");
 }
Exemple #23
0
  /**
   * Try to write response from cache.
   *
   * @param request the specified request
   * @param response the specified response
   * @param chain filter chain
   * @throws IOException io exception
   * @throws ServletException servlet exception
   */
  @Override
  public void doFilter(
      final ServletRequest request, final ServletResponse response, final FilterChain chain)
      throws IOException, ServletException {
    final long startTimeMillis = System.currentTimeMillis();
    request.setAttribute(Keys.HttpRequest.START_TIME_MILLIS, startTimeMillis);

    final HttpServletRequest httpServletRequest = (HttpServletRequest) request;
    final String requestURI = httpServletRequest.getRequestURI();
    LOGGER.log(Level.FINER, "Request URI[{0}]", requestURI);

    if (StaticResources.isStatic(httpServletRequest)) {
      final String path = httpServletRequest.getServletPath() + httpServletRequest.getPathInfo();
      LOGGER.log(Level.FINEST, "Requests a static resource, forwards to servlet[path={0}]", path);
      request.getRequestDispatcher(path).forward(request, response);

      return;
    }

    if (!Latkes.isPageCacheEnabled()) {
      LOGGER.log(Level.FINEST, "Page cache is disabled");
      chain.doFilter(request, response);

      return;
    }

    final String skinDirName = (String) httpServletRequest.getAttribute(Keys.TEMAPLTE_DIR_NAME);
    if ("mobile".equals(skinDirName)) {
      // Mobile request, bypasses page caching
      chain.doFilter(request, response);

      return;
    }

    String pageCacheKey;
    final String queryString = httpServletRequest.getQueryString();
    pageCacheKey = (String) request.getAttribute(Keys.PAGE_CACHE_KEY);
    if (Strings.isEmptyOrNull(pageCacheKey)) {
      pageCacheKey = PageCaches.getPageCacheKey(requestURI, queryString);
      request.setAttribute(Keys.PAGE_CACHE_KEY, pageCacheKey);
    }

    final JSONObject cachedPageContentObject =
        PageCaches.get(pageCacheKey, httpServletRequest, (HttpServletResponse) response);

    if (null == cachedPageContentObject) {
      LOGGER.log(Level.FINER, "Page cache miss for request URI[{0}]", requestURI);
      chain.doFilter(request, response);

      return;
    }

    final String cachedType = cachedPageContentObject.optString(PageCaches.CACHED_TYPE);

    try {
      // If cached an article that has view password, dispatches the password form
      if (langPropsService.get(PageTypes.ARTICLE.getLangeLabel()).equals(cachedType)
          && cachedPageContentObject.has(PageCaches.CACHED_PWD)) {
        JSONObject article = new JSONObject();

        final String articleId = cachedPageContentObject.optString(PageCaches.CACHED_OID);

        article.put(Keys.OBJECT_ID, articleId);
        article.put(
            Article.ARTICLE_VIEW_PWD, cachedPageContentObject.optString(PageCaches.CACHED_PWD));

        if (articles.needViewPwd(httpServletRequest, article)) {
          article = articleRepository.get(articleId); // Loads the article entity

          final HttpServletResponse httpServletResponse = (HttpServletResponse) response;
          try {
            httpServletResponse.sendRedirect(
                Latkes.getServePath()
                    + "/console/article-pwd"
                    + articles.buildArticleViewPwdFormParameters(article));
            return;
          } catch (final Exception e) {
            httpServletResponse.sendError(HttpServletResponse.SC_NOT_FOUND);
            return;
          }
        }
      }
    } catch (final Exception e) {
      LOGGER.log(Level.SEVERE, e.getMessage(), e);
      chain.doFilter(request, response);
    }

    try {
      LOGGER.log(
          Level.FINEST, "Writes resposne for page[pageCacheKey={0}] from cache", pageCacheKey);
      response.setContentType("text/html");
      response.setCharacterEncoding("UTF-8");
      final PrintWriter writer = response.getWriter();
      String cachedPageContent = cachedPageContentObject.getString(PageCaches.CACHED_CONTENT);
      final String topBarHTML =
          TopBars.getTopBarHTML((HttpServletRequest) request, (HttpServletResponse) response);
      cachedPageContent = cachedPageContent.replace(Common.TOP_BAR_REPLACEMENT_FLAG, topBarHTML);

      final String cachedTitle = cachedPageContentObject.getString(PageCaches.CACHED_TITLE);
      LOGGER.log(
          Level.FINEST,
          "Cached value[key={0}, type={1}, title={2}]",
          new Object[] {pageCacheKey, cachedType, cachedTitle});

      statistics.incBlogViewCount((HttpServletRequest) request, (HttpServletResponse) response);

      final long endimeMillis = System.currentTimeMillis();
      final String dateString = DateFormatUtils.format(endimeMillis, "yyyy/MM/dd HH:mm:ss");
      final String msg =
          String.format(
              "<!-- Cached by B3log Solo(%1$d ms), %2$s -->",
              endimeMillis - startTimeMillis, dateString);
      LOGGER.finer(msg);
      cachedPageContent += Strings.LINE_SEPARATOR + msg;
      writer.write(cachedPageContent);
      writer.flush();
      writer.close();
    } catch (final JSONException e) {
      LOGGER.log(Level.SEVERE, e.getMessage(), e);
      chain.doFilter(request, response);
    } catch (final RepositoryException e) {
      LOGGER.log(Level.SEVERE, e.getMessage(), e);
      chain.doFilter(request, response);
    } catch (final ServiceException e) {
      LOGGER.log(Level.SEVERE, e.getMessage(), e);
      chain.doFilter(request, response);
    }
  }
Exemple #24
0
  @Override
  public void action(final Event<JSONObject> event) throws EventException {
    final JSONObject data = event.getData();
    LOGGER.log(
        Level.DEBUG,
        "Processing an event[type={0}, data={1}] in listener[className={2}]",
        new Object[] {event.getType(), data, CommentNotifier.class.getName()});

    try {
      final JSONObject originalArticle = data.getJSONObject(Article.ARTICLE);
      final JSONObject originalComment = data.getJSONObject(Comment.COMMENT);
      final String commentContent = originalComment.optString(Comment.COMMENT_CONTENT);
      final JSONObject commenter =
          userQueryService.getUser(originalComment.optString(Comment.COMMENT_AUTHOR_ID));
      final String commenterName = commenter.optString(User.USER_NAME);

      // 0. Data channel (WebSocket)
      final JSONObject chData = new JSONObject();
      chData.put(Article.ARTICLE_T_ID, originalArticle.optString(Keys.OBJECT_ID));
      chData.put(Comment.COMMENT_T_ID, originalComment.optString(Keys.OBJECT_ID));
      chData.put(Comment.COMMENT_T_AUTHOR_NAME, commenterName);

      final String userEmail = commenter.optString(User.USER_EMAIL);
      chData.put(
          Comment.COMMENT_T_AUTHOR_THUMBNAIL_URL, avatarQueryService.getAvatarURL(userEmail));
      chData.put(Common.THUMBNAIL_UPDATE_TIME, commenter.optLong(UserExt.USER_UPDATE_TIME));

      chData.put(
          Comment.COMMENT_CREATE_TIME,
          DateFormatUtils.format(
              new Date(originalComment.optLong(Comment.COMMENT_CREATE_TIME)), "yyyy-MM-dd HH:mm"));
      String cc = shortLinkQueryService.linkArticle(commentContent);
      cc = shortLinkQueryService.linkTag(cc);
      cc = Emotions.convert(cc);
      cc = Markdowns.toHTML(cc);
      cc = Markdowns.clean(cc, "");
      try {
        final Set<String> userNames = userQueryService.getUserNames(commentContent);
        for (final String userName : userNames) {
          cc =
              cc.replace(
                  '@' + userName,
                  "@<a href='"
                      + Latkes.getServePath()
                      + "/member/"
                      + userName
                      + "'>"
                      + userName
                      + "</a>");
        }
      } catch (final ServiceException e) {
        LOGGER.log(Level.ERROR, "Generates @username home URL for comment content failed", e);
      }
      chData.put(Comment.COMMENT_CONTENT, cc);

      ArticleChannel.notifyComment(chData);

      // + Article Heat
      final JSONObject articleHeat = new JSONObject();
      articleHeat.put(Article.ARTICLE_T_ID, originalArticle.optString(Keys.OBJECT_ID));
      articleHeat.put(Common.OPERATION, "+");
      ArticleListChannel.notifyHeat(articleHeat);

      final boolean isDiscussion =
          originalArticle.optInt(Article.ARTICLE_TYPE) == Article.ARTICLE_TYPE_C_DISCUSSION;

      // Timeline
      if (!isDiscussion) {
        final String articleTitle =
            StringUtils.substring(
                Jsoup.parse(originalArticle.optString(Article.ARTICLE_TITLE)).text(), 0, 28);
        final String articlePermalink =
            Latkes.getServePath() + originalArticle.optString(Article.ARTICLE_PERMALINK);

        final JSONObject timeline = new JSONObject();
        timeline.put(Common.TYPE, Comment.COMMENT);
        String content = langPropsService.get("timelineCommentLabel");
        content =
            content
                .replace(
                    "{user}",
                    "<a target='_blank' rel='nofollow' href='"
                        + Latkes.getServePath()
                        + "/member/"
                        + commenterName
                        + "'>"
                        + commenterName
                        + "</a>")
                .replace(
                    "{article}",
                    "<a target='_blank' rel='nofollow' href='"
                        + articlePermalink
                        + "'>"
                        + articleTitle
                        + "</a>")
                .replace("{comment}", StringUtils.substring(Jsoup.parse(cc).text(), 0, 28));
        timeline.put(Common.CONTENT, content);

        timelineMgmtService.addTimeline(timeline);
      }

      // 1. 'Commented' Notification
      final String articleAuthorId = originalArticle.optString(Article.ARTICLE_AUTHOR_ID);
      final Set<String> atUserNames = userQueryService.getUserNames(commentContent);
      final boolean commenterIsArticleAuthor =
          articleAuthorId.equals(originalComment.optString(Comment.COMMENT_AUTHOR_ID));
      if (commenterIsArticleAuthor && atUserNames.isEmpty()) {
        return;
      }

      atUserNames.remove(commenterName); // Do not notify commenter itself

      if (!commenterIsArticleAuthor) {
        final JSONObject requestJSONObject = new JSONObject();
        requestJSONObject.put(Notification.NOTIFICATION_USER_ID, articleAuthorId);
        requestJSONObject.put(
            Notification.NOTIFICATION_DATA_ID, originalComment.optString(Keys.OBJECT_ID));

        notificationMgmtService.addCommentedNotification(requestJSONObject);
      }

      final String articleContent = originalArticle.optString(Article.ARTICLE_CONTENT);
      final Set<String> articleContentAtUserNames = userQueryService.getUserNames(articleContent);

      // 2. 'At' Notification
      for (final String userName : atUserNames) {
        if (isDiscussion && !articleContentAtUserNames.contains(userName)) {
          continue;
        }

        final JSONObject user = userQueryService.getUserByName(userName);

        if (null == user) {
          LOGGER.log(Level.WARN, "Not found user by name [{0}]", userName);

          continue;
        }

        if (user.optString(Keys.OBJECT_ID).equals(articleAuthorId)) {
          continue; // Has added in step 1
        }

        final JSONObject requestJSONObject = new JSONObject();
        requestJSONObject.put(Notification.NOTIFICATION_USER_ID, user.optString(Keys.OBJECT_ID));
        requestJSONObject.put(
            Notification.NOTIFICATION_DATA_ID, originalComment.optString(Keys.OBJECT_ID));

        notificationMgmtService.addAtNotification(requestJSONObject);
      }
    } catch (final Exception e) {
      LOGGER.log(Level.ERROR, "Sends the comment notification failed", e);
    }
  }
Exemple #25
0
  public String getExitToWorkAndCountVacationDayJson(
      String beginDateString, String endDateString, Integer employeeId, Integer vacationTypeId) {
    final JsonObjectNodeBuilder builder = anObjectBuilder();
    try {
      Employee employee = employeeService.find(employeeId);
      final Timestamp beginDate =
          DateTimeUtil.stringToTimestamp(beginDateString, CreateVacationForm.DATE_FORMAT);
      final Timestamp endDate =
          DateTimeUtil.stringToTimestamp(endDateString, CreateVacationForm.DATE_FORMAT);

      // Получаем день выхода на работу
      com.aplana.timesheet.dao.entity.Calendar endDateCalendar = calendarService.find(endDate);
      com.aplana.timesheet.dao.entity.Calendar nextWorkDay =
          calendarService.getNextWorkDay(endDateCalendar, employee.getRegion());
      String format =
          DateFormatUtils.format(nextWorkDay.getCalDate(), CreateVacationForm.DATE_FORMAT);
      builder.withField("exitDate", aStringBuilder(format));

      // Получаем кол-во дней в отпуске за исключением неучитываемых праздников
      Integer vacationDayCountExCons =
          calendarService.getCountDaysForPeriodForRegionExConsiderHolidays(
              beginDate, endDate, employee.getRegion());
      // Получаем кол-во рабочих дней в отпуске
      Integer vacationWorkCount =
          calendarService.getCountWorkDaysForPeriodForRegion(
              beginDate, endDate, employee.getRegion());

      builder.withField("vacationWorkDayCount", aStringBuilder(vacationWorkCount.toString()));
      builder.withField(
          "vacationDayCount",
          aStringBuilder((vacationDayCountExCons <= 0) ? "0" : vacationDayCountExCons.toString()));

      /*  проверка на необходимость вывода информ сообщения
          о необходимости оформления отпуска по вск
          для отпуска с сохранением содержания
      */
      Calendar calendar = java.util.Calendar.getInstance();

      calendar.setTime(beginDate);
      int beginWeekYear = calendar.get(Calendar.WEEK_OF_YEAR);

      calendar.setTime(endDate);
      int endWeekYear = calendar.get(Calendar.WEEK_OF_YEAR);

      calendar.set(Calendar.DAY_OF_WEEK, calendar.getFirstDayOfWeek());
      Date beginWeekDate = calendar.getTime();

      int endDay = calendar.get(Calendar.DAY_OF_WEEK);
      int leftDays = Calendar.SATURDAY - endDay;
      calendar.add(Calendar.DATE, ++leftDays);
      Date sunday = calendar.getTime();

      // Количество рабочих дней в отпуске, если конец отпуска приходится
      // на следующую неделю то считается с понедельника след недели по дату конца отпуска
      Integer countWorkDaysVacationPeriod =
          calendarService.getCountWorkDaysForPeriodForRegion(
              beginWeekYear != endWeekYear ? beginWeekDate : beginDate,
              endDate,
              employee.getRegion());

      // Количество рабочих дней в неделе приходящихся на конец отпуска
      Integer countWorkDaysWeek =
          calendarService.getCountWorkDaysForPeriodForRegion(
              beginWeekDate, DateUtils.addDays(beginWeekDate, 6), employee.getRegion());

      // Количество учитываемых дней в период с понедельника последней недели отпуска по конец
      // отпуска
      Integer countVacConsiderDaysOnEndWeek =
          calendarService.getCountDaysForPeriodForRegionExConsiderHolidays(
              beginWeekYear != endWeekYear ? beginWeekDate : beginDate,
              endDate,
              employee.getRegion());

      // Количество учитываемых дней в неделе
      Integer countConsiderDaysOnEndWeek =
          calendarService.getCountDaysForPeriodForRegionExConsiderHolidays(
              beginWeekYear != endWeekYear ? beginWeekDate : beginDate,
              sunday,
              employee.getRegion());

      if (vacationTypeId != null
          && vacationTypeId == VacationTypesEnum.WITH_PAY.getId()
          &&
          // проверка что в отпуск попала не вся учитываемая неделя
          !countVacConsiderDaysOnEndWeek.equals(countConsiderDaysOnEndWeek)
          &&
          // и в этот период попадают все рабочие дни
          countWorkDaysVacationPeriod.equals(countWorkDaysWeek)) {
        builder.withField("vacationFridayInform", aStringBuilder("true"));
      }

      return JsonUtil.format(builder);
    } catch (Exception th) {
      logger.error(CANT_GET_EXIT_TO_WORK_EXCEPTION_MESSAGE, th);
      return CANT_GET_EXIT_TO_WORK_EXCEPTION_MESSAGE;
    }
  }
  @Override
  public List<AvailableCoachDto> getAvailableCoach(Date date, String timeslot, String staffType) {
    String partTime = "PT" + staffType;
    String fullTime = "FT" + staffType;
    if (date == null) {
      String allCoachSql =
          "SELECT \n"
              + "    m.user_id as coachId, CONCAT (s.given_name, ' ' ,s.surname) AS nickname, s.portrait_photo as portraitPhoto\n"
              + "FROM\n"
              + "    staff_master m,\n"
              + "    staff_coach_info c\n"
              + "        LEFT JOIN\n"
              + "    user_master u ON (u.user_id = c.user_id)\n"
              + "        LEFT JOIN\n"
              + "    staff_profile s ON (s.user_id = c.user_id)\n"
              + "WHERE\n"
              + "    m.user_id = c.user_id\n"
              + "        AND m.status = 'ACT'\n"
              + "        AND (m.staff_type = ?\n"
              + "        OR m.staff_type = ?)\n";
      return this.getDtoBySql(
          allCoachSql, Arrays.asList(partTime, fullTime), AvailableCoachDto.class);
    } else {
      String[] slot = timeslot.split(",");
      String coachByDateSql =
          "select \n"
              + "    m.user_id as coachId,\n"
              + "    CONCAT (s.given_name, ' ' ,s.surname) AS nickname,\n"
              + "    s.portrait_photo as portraitPhoto\n"
              + "from\n"
              + "    staff_master m,\n"
              + "    staff_coach_info c\n"
              + "        left join\n"
              + "    user_master u on (u.user_id = c.user_id)\n"
              + "        left join\n"
              + "    staff_profile s on (s.user_id = c.user_id)\n"
              + "where\n"
              + "    m.user_id = c.user_id\n"
              + "        and m.STATUS = 'ACT'\n"
              + "        and (m.staff_type = ?\n"
              + "        or m.staff_type = ?)\n"
              + "        and m.user_id not in (select \n"
              + "            coach_user_id\n"
              + "        from\n"
              + "            staff_coach_roster\n"
              + "        where\n"
              + "            begin_time in ("
              + getQuestionMasks(slot)
              + ") and off_duty = 'Y'\n"
              + "                and on_date = ?)\n"
              + "        and m.user_id not in (select \n"
              + "            coach_user_id\n"
              + "        from\n"
              + "            staff_coach_roster\n"
              + "        where\n"
              + "            week_day = ? and off_duty = 'Y'\n"
              + "                and coach_user_id not in (select \n"
              + "                    coach_user_id\n"
              + "                from\n"
              + "                    staff_coach_roster\n"
              + "                where\n"
              + "                    on_date = ?\n"
              + "                        and rate_type is not null))\n"
              + "        and m.user_id not in (select \n"
              + "            staff_user_id\n"
              + "        from\n"
              + "            staff_timeslot\n"
              + "        where\n"
              + "            date_format(begin_datetime, '%Y-%m-%d') = ?\n"
              + "                and date_format(begin_datetime, '%H') in ("
              + getQuestionMasks(slot)
              + "))\n";
      String dateStr = DateFormatUtils.format(date, "yyyy-MM-dd");
      Calendar dateTime = Calendar.getInstance();
      dateTime.setTime(date);

      List<Serializable> params = new ArrayList<Serializable>();
      params.add(partTime);
      params.add(fullTime);
      params.addAll(CollectionUtils.arrayToList(slot));
      params.add(date);
      params.add(dateTime.get(Calendar.DAY_OF_WEEK));
      params.add(date);
      params.add(dateStr);
      params.addAll(CollectionUtils.arrayToList(slot));
      return this.getDtoBySql(coachByDateSql, params, AvailableCoachDto.class);
    }
  }
  public static void checkProjectAndMail(
      Project project,
      String otherAddresses,
      AbstractBuild build,
      BuildListener listener,
      boolean sendAll)
      throws IOException {

    // 参考 org.jenkinsci.plugins.tokenmacro.impl.BuildUrlMacro
    String BUILD_URL =
        new StringBuilder()
            .append(Hudson.getInstance().getRootUrl())
            .append(build.getUrl())
            .toString();
    String PROJECT_NAME = build.getProject().getName();
    String BUILD_NUMBER = String.valueOf(build.getNumber());

    String subject = String.format("%s - Build # %s のタスク", PROJECT_NAME, BUILD_NUMBER);
    String footer = String.format("Check console output at %s to view the results.", BUILD_URL);
    // ///////////////// 以下メール送信系の処理

    String header = null;
    List<PVACEVViewBean> list = null;
    if (!sendAll) {
      list = ViewUtils.getIsCheckPVACEVViewList(project);
      header = "以下、期限が過ぎましたが完了していない要注意タスクです。 ";
    } else {
      list = ViewUtils.getPVACEVViewBeanList(project);
      header = "以下、条件に合致したタスクです。 ";
    }

    if (list.isEmpty()) {
      listener.getLogger().println("[EVM Tools] : 要注意タスクはありませんでした。");
      return;
    }
    StringBuffer messageBuf = new StringBuffer();
    messageBuf.append(header);
    messageBuf.append("\n");
    messageBuf.append("\n");
    messageBuf.append("--------------------");
    messageBuf.append("\n");
    messageBuf.append("担当者\tタスクID\tタスク名\t期限");
    messageBuf.append("\n");
    for (PVACEVViewBean bean : list) {
      Date scheduledEndDate = bean.getScheduledEndDate();
      String endDate = "未設定";
      if (scheduledEndDate != null) {
        endDate = DateFormatUtils.format(scheduledEndDate, "yyyy/MM/dd");
      }
      String personInCharge =
          StringUtils.isEmpty(bean.getPersonInCharge()) ? "未設定" : bean.getPersonInCharge();

      String line =
          String.format(
              "%s\t%s\t%s\t%s", personInCharge, bean.getTaskId(), bean.getTaskName(), endDate);
      messageBuf.append(line);
      messageBuf.append("\n");
    }
    messageBuf.append("--------------------");
    messageBuf.append("\n");
    messageBuf.append("\n");
    messageBuf.append(footer);

    String message = new String(messageBuf);
    listener.getLogger().println("[EVM Tools] : --- 要注意タスク--- ");
    listener.getLogger().println(message);
    listener.getLogger().println("[EVM Tools] : --- 要注意タスク--- ");

    DescriptorImpl descriptor =
        (DescriptorImpl) Jenkins.getInstance().getDescriptor(EVMToolsBuilder.class);

    boolean useMail = !StringUtils.isEmpty(descriptor.getAddresses());
    listener.getLogger().println("[EVM Tools] メール送信する? :" + useMail);
    String address =
        StringUtils.isEmpty(otherAddresses) ? descriptor.getAddresses() : otherAddresses;
    listener.getLogger().println("[EVM Tools] 宛先:" + address);
    listener.getLogger().println("[EVM Tools] 期限切れ以外も通知?:" + sendAll);

    if (useMail && !StringUtils.isEmpty(address)) {
      String[] addresses = Utils.parseCommna(address);
      for (String string : addresses) {
        System.out.printf("[%s]\n", string);
      }
      try {
        if (addresses.length > 0) {
          PMUtils.sendMail(addresses, subject, message);
        } else {
          String errorMsg = "メール送信に失敗しました。宛先の設定がされていません";
          listener.getLogger().println("[EVM Tools] " + errorMsg);
          throw new AbortException(errorMsg);
        }
      } catch (MessagingException e) {
        String errorMsg = "メール送信に失敗しました。「システムの設定」で E-mail 通知 の設定や宛先などを見直してください";
        listener.getLogger().println("[EVM Tools] " + errorMsg);
        throw new AbortException(errorMsg);
      }
    }
  }
 private List<Map<String, Object>> localTransactionResult(List<LocalTransaction> requistionList) {
   List<Map<String, Object>> mappedApplications =
       new ArrayList<Map<String, Object>>(requistionList.size());
   List<PropertyFilter> propertyFilters = new ArrayList<PropertyFilter>();
   List<Application> apps = new ArrayList<Application>();
   List<SecurityDomain> sds = new ArrayList<SecurityDomain>();
   for (LocalTransaction localTransaction : requistionList) {
     propertyFilters.clear();
     apps.clear();
     sds.clear();
     Map<String, Object> mappedLocalTransaction = localTransaction.toMap(null, null);
     String formatValue = "";
     if (localTransaction.getBeginTime() != null) {
       formatValue =
           DateFormatUtils.format(
               (Calendar) localTransaction.getBeginTime(), "yyyy-MM-dd HH:mm:ss");
     }
     mappedLocalTransaction.put("beginTime", formatValue);
     formatValue = "";
     if (localTransaction.getEndTime() != null) {
       formatValue =
           DateFormatUtils.format((Calendar) localTransaction.getEndTime(), "yyyy-MM-dd HH:mm:ss");
     }
     mappedLocalTransaction.put("endTime", formatValue);
     mappedLocalTransaction.put(
         "failMessage",
         localTransaction.getFailMessage() == null ? "" : localTransaction.getFailMessage());
     // propertyFilters.add(new PropertyFilter("aid", MatchType.EQ,
     // PropertyType.S, localTransaction.getAid()));
     if (localTransaction.getProcedureName().equals(Operation.CREATE_SD.toString())
         || localTransaction.getProcedureName().equals(Operation.DELETE_SD.toString())
         || localTransaction.getProcedureName().equals(Operation.LOCK_SD.toString())
         || localTransaction.getProcedureName().equals(Operation.UNLOCK_SD.toString())
         || localTransaction.getProcedureName().equals(Operation.SYNC_CARD_SD.toString())
         || localTransaction.getProcedureName().equals(Operation.UPDATE_KEY.toString())) {
       propertyFilters.add(
           new PropertyFilter("aid", MatchType.EQ, PropertyType.S, localTransaction.getAid()));
       sds = securityDomainManager.find(propertyFilters);
       if (sds != null && sds.size() != 0) {
         mappedLocalTransaction.put("appName", sds.get(0).getSdName());
         mappedLocalTransaction.put("showType", "sd");
       }
     } else if (localTransaction.getProcedureName().equals("LOCK_CARD")
         || localTransaction.getProcedureName().equals("UNLOCK_CARD")) {
       propertyFilters.add(
           new PropertyFilter(
               "mobileNo", MatchType.EQ, PropertyType.S, localTransaction.getMobileNo()));
       List<CustomerCardInfo> ccis = this.customerCardInfoManager.find(propertyFilters);
       CustomerCardInfo cci = null;
       for (CustomerCardInfo _cci : ccis) {
         if (_cci.getCard()
             .getCardNo()
             .equals(localTransaction.getCardNo())) { // 根据卡号和手机号查找CustomerCardInfo,并且列出最新的终端名
           if (cci == null || cci.getId() < _cci.getId()) {
             cci = _cci;
           }
         }
       }
       if (null != cci) {
         mappedLocalTransaction.put("appName", cci.getName());
         mappedLocalTransaction.put("cciIconId", cci.getMobileType().getId());
         mappedLocalTransaction.put("showType", "termial");
       }
     } else {
       propertyFilters.add(
           new PropertyFilter("aid", MatchType.EQ, PropertyType.S, localTransaction.getAid()));
       apps = applicationManager.find(propertyFilters);
       if (apps != null && apps.size() != 0) {
         mappedLocalTransaction.put("appName", apps.get(0).getName());
         mappedLocalTransaction.put("application_id", apps.get(0).getId());
         mappedLocalTransaction.put("showType", "app");
       }
     }
     if (PlatformMessage.SUCCESS.getCode().equals(localTransaction.getResult())) {
       mappedLocalTransaction.put("result", PlatformMessage.SUCCESS.getMessage());
     } else if (PlatformMessage.TRANS_EXCESSIVING.getCode().equals(localTransaction.getResult())) {
       mappedLocalTransaction.put("result", PlatformMessage.TRANS_EXCESSIVING.getMessage());
     } else if (PlatformMessage.TRANS_EXCEPTION_CLOSED
         .getCode()
         .equals(localTransaction.getResult())) {
       mappedLocalTransaction.put("result", PlatformMessage.TRANS_EXCEPTION_CLOSED.getMessage());
     } else {
       //				for (PlatformErrorCode pe : PlatformErrorCode.values()) {
       //					if (pe.getErrorCode().equals(localTransaction.getResult())) {
       //						mappedLocalTransaction.put("result", pe.getDefaultMessage());
       //					}
       //				}
       mappedLocalTransaction.put("result", localTransaction.getFailMessage());
     }
     mappedApplications.add(mappedLocalTransaction);
   }
   return mappedApplications;
 }
Exemple #29
0
  public ActionForward prepareForEdit(
      ActionMapping mapping,
      ActionForm form,
      HttpServletRequest request,
      HttpServletResponse response)
      throws Exception {
    Integer infoExamId = (Integer) request.getAttribute(PresentationConstants.EXAM_OID);
    request.setAttribute(PresentationConstants.EXAM_OID, infoExamId);

    ContextUtils.setCurricularYearsContext(request);

    InfoExam infoExam = (InfoExam) request.getAttribute(PresentationConstants.EXAM);
    List executionCourseList = infoExam.getAssociatedExecutionCourse();
    Iterator iter = executionCourseList.iterator();
    List newExecutionCourseList = new ArrayList();
    while (iter.hasNext()) {
      InfoExecutionCourse element = (InfoExecutionCourse) iter.next();

      InfoExecutionCourse executionCourse;
      try {
        executionCourse =
            ReadExecutionCourseWithAssociatedCurricularCourses.run(element.getIdInternal());
      } catch (Exception ex) {
        throw new Exception(ex);
      }
      newExecutionCourseList.add(executionCourse);
    }

    request.setAttribute(PresentationConstants.EXECUTION_COURSES_LIST, newExecutionCourseList);

    String nextPage = request.getParameter("nextPage");
    request.setAttribute(PresentationConstants.NEXT_PAGE, nextPage);

    List<LabelValueBean> examSeasons = Util.getExamSeasons();
    request.setAttribute(PresentationConstants.LABLELIST_SEASONS, examSeasons);

    DynaValidatorForm createExamForm = (DynaValidatorForm) form;

    String[] executionCourseIDList = new String[executionCourseList.size()];
    for (int i = 0; i < executionCourseList.size(); i++) {
      executionCourseIDList[i] =
          ((InfoExecutionCourse) executionCourseList.get(i)).getIdInternal().toString();
    }
    createExamForm.set("executionCourses", executionCourseIDList);

    List<InfoRoomOccupation> roomsList = infoExam.getWrittenEvaluationSpaceOccupations();
    String[] roomsIDArray = new String[roomsList.size()];
    Object[] infoRoomsArray = new Object[roomsList.size()];
    for (int i = 0; i < roomsList.size(); i++) {
      infoRoomsArray[i] = roomsList.get(i).getInfoRoom();
      roomsIDArray[i] = ((InfoRoom) infoRoomsArray[i]).getIdInternal().toString();
    }
    createExamForm.set("rooms", roomsIDArray);
    request.setAttribute("rooms", infoRoomsArray);

    List scopeList = infoExam.getAssociatedCurricularCourseScope();
    String[] scopeIDArray = new String[scopeList.size()];
    for (int i = 0; i < scopeList.size(); i++) {
      scopeIDArray[i] = ((InfoCurricularCourseScope) scopeList.get(i)).getIdInternal().toString();
    }
    createExamForm.set("scopes", scopeIDArray);

    createExamForm.set("day", DateFormatUtils.format(infoExam.getDay().getTime(), "dd"));
    createExamForm.set("month", DateFormatUtils.format(infoExam.getDay().getTime(), "MM"));
    createExamForm.set("year", DateFormatUtils.format(infoExam.getDay().getTime(), "yyyy"));
    createExamForm.set(
        "beginningHour", DateFormatUtils.format(infoExam.getBeginning().getTime(), "HH"));
    createExamForm.set(
        "beginningMinute", DateFormatUtils.format(infoExam.getBeginning().getTime(), "mm"));
    createExamForm.set("endHour", DateFormatUtils.format(infoExam.getEnd().getTime(), "HH"));
    createExamForm.set("endMinute", DateFormatUtils.format(infoExam.getEnd().getTime(), "mm"));
    createExamForm.set("season", infoExam.getSeason().getSeason().toString());

    return mapping.findForward("showCreateForm");
  }
Exemple #30
0
  public void addTablePolicies(Division parent, DSpaceObject dso, Collection owningCollection)
      throws WingException, SQLException {
    if (!isAdvancedFormEnabled) {
      return;
    }
    Division div = parent.addDivision("access-existing-policies");
    div.setHead(T_head_policies_table);
    div.addPara(T_policies_help.parameterize(owningCollection));

    java.util.List<ResourcePolicy> resourcePolicies =
        authorizeService.findPoliciesByDSOAndType(context, dso, ResourcePolicy.TYPE_CUSTOM);

    if (resourcePolicies.isEmpty()) {
      div.addPara(T_no_policies);
      return;
    }

    int cols = resourcePolicies.size();
    if (cols == 0) cols = 1;
    Table policies = div.addTable("policies", 6, cols);
    Row header = policies.addRow(Row.ROLE_HEADER);

    header.addCellContent(T_column0); // name
    header.addCellContent(T_column1); // action
    header.addCellContent(T_column2); // group
    header.addCellContent(T_column3); // start_date
    header.addCellContent(T_column4); // end_date

    for (ResourcePolicy rp : resourcePolicies) {
      int id = rp.getID();

      String name = "";
      if (rp.getRpName() != null) name = rp.getRpName();

      String action = resourcePolicyService.getActionText(rp);

      // if it is the default policy for the Submitter don't show it.
      if (dso instanceof org.dspace.content.Item) {
        org.dspace.content.Item item = (org.dspace.content.Item) dso;
        if (rp.getEPerson() != null) {
          if (item.getSubmitter().equals(rp.getEPerson())) continue;
        }
      }

      String group = "";
      if (rp.getGroup() != null) group = rp.getGroup().getName();

      Row row = policies.addRow();

      row.addCellContent(name);
      row.addCellContent(action);
      row.addCellContent(group);

      // start
      String startDate = "";
      if (rp.getStartDate() != null) {
        startDate = DateFormatUtils.format(rp.getStartDate(), "yyyy-MM-dd");
      }
      row.addCellContent(startDate);

      // endDate
      String endDate = "";
      if (rp.getEndDate() != null) {
        endDate = DateFormatUtils.format(rp.getEndDate(), "yyyy-MM-dd");
      }
      row.addCellContent(endDate);

      Button edit = row.addCell().addButton("submit_edit_edit_policies_" + id);
      edit.setValue(T_table_submit_edit);

      Button delete = row.addCell().addButton("submit_delete_edit_policies_" + id);
      delete.setValue(T_table_submit_delete);
    }
  }