Example #1
1
 @Override
 public boolean validateOptions(Map<String, String> options) {
   if (super.validateOptions(options) == false) return false;
   boolean hasStart = false;
   boolean hasEnd = false;
   try {
     if (options.containsKey(START)) {
       hasStart = true;
       String s = options.get(START);
       if (s.startsWith(LONG_PREFIX)) Long.valueOf(s.substring(LONG_PREFIX.length()));
       else dateParser.parse(s);
     }
     if (options.containsKey(END)) {
       hasEnd = true;
       String s = options.get(END);
       if (s.startsWith(LONG_PREFIX)) Long.valueOf(s.substring(LONG_PREFIX.length()));
       else dateParser.parse(s);
     }
     if (!hasStart && !hasEnd)
       throw new IllegalArgumentException(START + " or " + END + " must be specified");
     if (options.get(START_INCL) != null) Boolean.parseBoolean(options.get(START_INCL));
     if (options.get(END_INCL) != null) Boolean.parseBoolean(options.get(END_INCL));
   } catch (Exception e) {
     throw new IllegalArgumentException("invalid options", e);
   }
   return true;
 }
  public void calcularComissao() throws ParseException {
    SimpleDateFormat df = new SimpleDateFormat("dd/MM/yyyy");

    try {
      Date data1 = dateInicio.getDate();
      Date data2 = dateFim.getDate();
      if (CalcularData.TirarDiferenca(data1, data2) < 0) {
        JOptionPane.showMessageDialog(
            null, "As datas devem ser iguais ou a data final ser superior a data inicial!");
      } else {
        objPed =
            pedDao.comissaoTotalPedido(
                Integer.parseInt(textField.getText()),
                df.parse(dateInicio.getEditor().getText()),
                df.parse(dateFim.getEditor().getText()));
        total = objPed.getTotalPedido();
        porCentCom = Double.parseDouble(textField_2.getText());
        totalCom = (total * porCentCom) / 100;
        JOptionPane.showMessageDialog(null, "Comissão calculada!" + "\nR$ " + totalCom);
        textField_2.setText(String.valueOf(totalCom));
      }
    } catch (NumberFormatException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    } catch (DaoException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }
  }
Example #3
0
 /**
  * 根据微吼url创建直播信息
  *
  * @param url
  * @param groupList
  * @return
  * @throws Exception
  */
 private Live createVhLive(String url, List<JSONObject> groupList, User user) throws Exception {
   int i = url.lastIndexOf("/");
   String num = url.substring(i + 1);
   if (!StringUtil.isBlank(num)) {
     Pattern p = Pattern.compile("^\\d{9}$");
     if (p.matcher(num).matches()) {
       VhallWebinar vh = vhallWebinarService.getVhLiveInfo(num);
       if (vh != null) {
         //					2015-07-11 13:30:00
         SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
         Date start = sdf.parse(vh.getT_start());
         Date end = sdf.parse(vh.getT_end());
         String image = getVhPicUrl(url);
         List<Images> images = this.changePicUrlToImage(image);
         return liveRepo.save(
             new Live(
                 vh.getSubject(),
                 start.getTime(),
                 end.getTime(),
                 Config.LIVE_TYPE_VH,
                 vh.getWebinar_desc(),
                 images,
                 groupList,
                 num,
                 url,
                 user.getId(),
                 user.getNickName(),
                 user.getLogoURL()));
       }
     }
   }
   throw new Exception("创建直播失败");
 }
Example #4
0
  @SuppressWarnings("deprecation")
  private String getDisplayTime(String datetime) {

    try {
      SimpleDateFormat sourceFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
      sourceFormat.setTimeZone(TimeZone.getTimeZone("UTC"));
      Date parsed = sourceFormat.parse(datetime); // => Date is in UTC now

      TimeZone tz = TimeZone.getDefault();
      SimpleDateFormat destFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
      destFormat.setTimeZone(tz);

      String result = destFormat.format(parsed);

      Date dt = sdf.parse(result);
      if (now.getYear() == dt.getYear()
          && now.getMonth() == dt.getMonth()
          && now.getDate() == dt.getDate()) {
        return tformat.format(dt);
      }
      return dformat.format(dt);
    } catch (Exception e) {
    }
    return "";
  }
Example #5
0
  @Check("isAdmin")
  public static void add(String startDate, String endDate, String idAgence) {
    String dateDebut = formatDateToDisplay(startDate);
    String dateFin = formatDateToDisplay(endDate);
    Agence agence = Agence.getAgenceById(Long.parseLong(idAgence));
    SimpleDateFormat dateFormat = new SimpleDateFormat("ddMMyyyyHHmm");
    try {
      Date sDate = dateFormat.parse(startDate);
      Date eDate = dateFormat.parse(endDate);
      List<Employe> listEmployes = Employe.getAvailableEmployes(sDate, eDate);
      List<Vehicule> listVehicules = Vehicule.getAvailableVehiculesByAgence(sDate, eDate, agence);
      boolean isAvailableCircuit = Circuit.isAvailableCircuitByAgence(sDate, eDate, agence);
      List<ProduitType> listProduitTypes = Arrays.asList(ProduitType.values());

      render(
          dateDebut,
          dateFin,
          listEmployes,
          listVehicules,
          isAvailableCircuit,
          agence,
          listProduitTypes);
    } catch (ParseException ex) {
      Logger.getLogger(Sessions.class.getName()).log(Level.SEVERE, null, ex);
    }
  }
  /**
   * Adds the date range values to the search template.
   *
   * <pre>{@code
   * - _date-start
   * - _date-end
   *
   * }</pre>
   *
   * If there is no 'start' and 'end' request parameter, then the current day is used. A day starts
   * at 00:00 and ends the next day at 00:00
   *
   * @param request The request that has been done on the search node.
   * @param propertiesMap The map where the key-values should be added to.
   */
  protected void addStartEnd(SlingHttpServletRequest request, Map<String, String> propertiesMap) {
    try {
      // Default is today
      Calendar cStart = getDayCalendar();
      Calendar cEnd = getDayCalendar();
      cEnd.add(Calendar.DAY_OF_MONTH, 1);

      // If a parameter is specified, we try to parse it and use that one.
      RequestParameter startParam = request.getRequestParameter(START_DAY_PARAM);
      RequestParameter endParam = request.getRequestParameter(END_DAY_PARAM);
      if (startParam != null && endParam != null) {
        String start = startParam.getString("UTF-8");
        String end = endParam.getString("UTF-8");
        cStart.setTime(format.parse(start));
        cEnd.setTime(format.parse(end));
      }

      // Calculate the beginning and the end date.
      String beginning = DateUtils.iso8601jcr(cStart);
      String end = DateUtils.iso8601jcr(cEnd);

      // Add to map.
      propertiesMap.put("_date-start", ClientUtils.escapeQueryChars(beginning));
      propertiesMap.put("_date-end", ClientUtils.escapeQueryChars(end));
    } catch (UnsupportedEncodingException e) {
      LOGGER.error(
          "Caught an UnsupportedEncodingException when trying to provide properties for the calendar search templates.",
          e);
    } catch (ParseException e) {
      LOGGER.error(
          "Caught a ParseException when trying to provide properties for the calendar search templates.",
          e);
    }
  }
Example #7
0
  public static synchronized void create(String array[]) {

    SimpleDateFormat format = new SimpleDateFormat("dd/MM/yyyy", Locale.ENGLISH);
    Date date;
    Person person;

    for (int i = 1; i < array.length; i++) {
      if (array[i].equals("м")) {
        try {
          date = format.parse(array[++i]);
          --i;
          person = Person.createMale(array[--i], date);
          ++i;
          allPeople.add(person);
          System.out.println(allPeople.indexOf(person));
        } catch (ParseException e) {
        }
      }
      if (array[i].equals("ж")) {
        try {
          date = format.parse(array[++i]);
          --i;
          person = Person.createFemale(array[--i], date);
          ++i;
          allPeople.add(person);
          System.out.println(allPeople.indexOf(person));
        } catch (ParseException e) {
        }
      }
    }
  }
Example #8
0
  public Date getHistoryEndDate() {
    if (m_customEnd != null) {
      try {
        if (m_customEnd.length() == 8) {
          return m_dayFormat.parse(m_customEnd);
        } else if (m_customEnd.length() == 10) {
          return m_hourlyFormat.parse(m_customEnd);
        }
      } catch (ParseException e) {
      }
    }

    long temp = 0;
    Calendar cal = Calendar.getInstance();
    cal.setTimeInMillis(m_date);
    if ("month".equals(m_reportType)) {
      int maxDay = cal.getActualMaximum(Calendar.DAY_OF_MONTH);
      temp = m_date + maxDay * (TimeHelper.ONE_HOUR * 24);
    } else if ("week".equals(m_reportType)) {
      temp = m_date + 7 * (TimeHelper.ONE_HOUR * 24);
    } else {
      temp = m_date + (TimeHelper.ONE_HOUR * 24);
    }
    cal.setTimeInMillis(temp);
    return cal.getTime();
  }
Example #9
0
  /**
   * Generates some test tasks. - 6 tasks where kermit is a candidate - 1 tasks where gonzo is
   * assignee - 2 tasks assigned to management group - 2 tasks assigned to accountancy group - 1
   * task assigned to both the management and accountancy group
   */
  private List<String> generateTestTasks() throws Exception {
    List<String> ids = new ArrayList<String>();

    SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy hh:mm:ss.SSS");
    // 6 tasks for kermit
    ClockUtil.setCurrentTime(sdf.parse("01/01/2001 01:01:01.000"));
    for (int i = 0; i < 6; i++) {
      Task task = taskService.newTask();
      task.setName("testTask");
      task.setDescription("testTask description");
      task.setPriority(3);
      taskService.saveTask(task);
      ids.add(task.getId());
      taskService.addCandidateUser(task.getId(), "kermit");
    }

    ClockUtil.setCurrentTime(sdf.parse("02/02/2002 02:02:02.000"));
    // 1 task for gonzo
    Task task = taskService.newTask();
    task.setName("gonzoTask");
    task.setDescription("gonzo description");
    task.setPriority(4);
    taskService.saveTask(task);
    taskService.setAssignee(task.getId(), "gonzo");
    taskService.setVariable(task.getId(), "testVar", "someVariable");
    ids.add(task.getId());

    ClockUtil.setCurrentTime(sdf.parse("03/03/2003 03:03:03.000"));
    // 2 tasks for management group
    for (int i = 0; i < 2; i++) {
      task = taskService.newTask();
      task.setName("managementTask");
      task.setPriority(10);
      taskService.saveTask(task);
      taskService.addCandidateGroup(task.getId(), "management");
      ids.add(task.getId());
    }

    ClockUtil.setCurrentTime(sdf.parse("04/04/2004 04:04:04.000"));
    // 2 tasks for accountancy group
    for (int i = 0; i < 2; i++) {
      task = taskService.newTask();
      task.setName("accountancyTask");
      task.setName("accountancy description");
      taskService.saveTask(task);
      taskService.addCandidateGroup(task.getId(), "accountancy");
      ids.add(task.getId());
    }

    ClockUtil.setCurrentTime(sdf.parse("05/05/2005 05:05:05.000"));
    // 1 task assigned to management and accountancy group
    task = taskService.newTask();
    task.setName("managementAndAccountancyTask");
    taskService.saveTask(task);
    taskService.addCandidateGroup(task.getId(), "management");
    taskService.addCandidateGroup(task.getId(), "accountancy");
    ids.add(task.getId());

    return ids;
  }
 @Override
 public List<TrackGps> viewTrack(String vehicleId, String startTime, String endTime) {
   if (vehicleId == null || vehicleId.trim().equals("") || startTime == null || endTime == null) {
     return null;
   }
   try {
     SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
     sdf.parse(startTime.trim());
     sdf.parse(endTime.trim());
   } catch (ParseException e) {
     throw new ParamValidationServiceException(
         "The param [startTime,endTime] is error.  [startDate,endDate] need to matche 'yyyy-MM-dd HH:mm:ss' .");
   }
   List<GpsHistory> gpsList =
       dao.getGpsListByHcVehicleId(
           vehicleId, DateUtil.string2DateTime(startTime), DateUtil.string2DateTime(endTime));
   this.calculate(RawDataProtocol.TRUCK_HS, gpsList);
   List<TrackGps> trackList = new ArrayList<TrackGps>();
   for (int i = 0; i < gpsList.size(); i++) {
     GpsHistory gps = gpsList.get(i);
     if (!gps.getEnableGps() || gps.getLatitude() < 0.1 || gps.getLongitude() < 0.1) {
       continue;
     }
     TrackGps trackGps = convertEntityGpsToTrackGps(gps);
     if (trackGps != null) {
       trackList.add(trackGps);
     }
   }
   return trackList;
 }
  public void handleAction(String jsonStr, MTMeanMetric rMetric) throws ParseException {
    try {
      JSONObject jsonObj = new JSONObject(jsonStr);

      if (!"getRecommendByDeal".equals(jsonObj.getString("action"))) {
        return;
      }

      JSONObject result = new JSONObject();
      String gid = "app_dataapp_gid_" + jsonObj.getString("gid");
      for (String colname : colnames) {
        result.put(colname, jsonObj.get(colname));
      }

      // 更新监控时间
      String createTime = jsonObj.getString("createTime");
      String currentTime = Utils.getCurrentTime("yyyy-MM-dd HH:mm:ss");
      SimpleDateFormat sd = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
      Date beginDate = sd.parse(createTime);
      Date endDate = sd.parse(currentTime);
      long time = (endDate.getTime() - beginDate.getTime()) / 1000;
      rMetric.update(time);

      result.put("currentTime", currentTime);
      jedisCluster.setex(gid, 3600, result.toString());

      // logger.info(result.toString());
    } catch (JSONException e) {
      return;
    }
  }
Example #12
0
 public static Cleaning buildFromElement(Element e, List<Item> items) throws ParseException {
   SimpleDateFormat sdf = new SimpleDateFormat(CleaningApplication.DATE_FORMAT);
   Cleaning cleaning = new Cleaning();
   cleaning.setName(e.getAttribute("name"));
   cleaning.setPlanedDate(sdf.parse(e.getAttribute("planedDate")));
   String doneDate = e.getAttribute("doneDate");
   if (!doneDate.isEmpty()) {
     cleaning.setDoneDate(sdf.parse(doneDate));
   }
   NodeList itemsList = e.getChildNodes();
   for (int i = 0; i < itemsList.getLength(); i++) {
     Node childNode = itemsList.item(i);
     if (childNode.getNodeType() == Node.ELEMENT_NODE) {
       if (childNode.getNodeName().equalsIgnoreCase("itemClening")) {
         Element child = (Element) childNode;
         Integer idItem = new Integer(child.getAttribute("idItem"));
         for (Item item : items) {
           if (item.getIdItem() == idItem) {
             cleaning.items.add(item);
             break;
           }
         }
       } else if (childNode.getNodeName().equalsIgnoreCase("tasks")) {
         Element child = (Element) childNode;
         cleaning.getTasks().add(Task.TaskBuilder.buildFromElement(child, items));
       }
     }
   }
   return cleaning;
 }
Example #13
0
  public static List<StopTime> getStopTimes(String data) throws JSONException {
    List<StopTime> stopTimes = new ArrayList<StopTime>();

    JSONArray jsonArray = new JSONArray(data);

    SimpleDateFormat currentDateFormat = new SimpleDateFormat("hh:mm:ss");
    SimpleDateFormat newDateFormat = new SimpleDateFormat("hh:mm aa");

    for (int i = 0; i < jsonArray.length(); ++i) {
      JSONObject jsonObject = jsonArray.getJSONObject(i);

      try {
        stopTimes.add(
            new StopTime(
                jsonObject.getString("TripId"),
                newDateFormat.format(currentDateFormat.parse(jsonObject.getString("ArrivalTime"))),
                newDateFormat.format(
                    currentDateFormat.parse(jsonObject.getString("DepartureTime"))),
                jsonObject.getString("StopId"),
                jsonObject.getString("StopHeadsign"),
                jsonObject.getInt("PickupType"),
                jsonObject.getInt("DropOffType"),
                jsonObject.getInt("StopSequence"),
                jsonObject.getString("StartStopId"),
                jsonObject.getString("FinalStopId")));
      } catch (Exception e) {
        Log.e("GTFSParser:getStopTimes", "" + e.getMessage());
        e.printStackTrace();
      }
    }
    return stopTimes;
  }
  /**
   * 计算天数差值
   *
   * @param startTime
   * @param endTime
   * @return
   * @throws ParseException
   */
  private int dayCha(String startTime, String endTime) {
    SimpleDateFormat ft = new SimpleDateFormat("yyyy-MM-dd");
    int days = 0;
    try {
      Date date1 = ft.parse(startTime);
      Date date2 = ft.parse(endTime);
      Calendar d1 = new GregorianCalendar();
      d1.setTime(date1);
      Calendar d2 = new GregorianCalendar();
      d2.setTime(date2);
      days = d2.get(Calendar.DAY_OF_YEAR) - d1.get(Calendar.DAY_OF_YEAR);
      int y2 = d2.get(Calendar.YEAR);
      if (d1.get(Calendar.YEAR) != y2) {
        d1 = (Calendar) d1.clone();
        do {
          days += d1.getActualMaximum(Calendar.DAY_OF_YEAR); // 得到当年的实际天数
          d1.add(Calendar.YEAR, 1);
        } while (d1.get(Calendar.YEAR) != y2);
      }
    } catch (ParseException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }

    return days;
  }
Example #15
0
  /**
   * 根据 日期(时间)字符串 解析日期(时间)
   *
   * @param strTime 字符串形式的日期(时间),格式为:
   *     <p>(1)yyyyMMdd (2) yyyy-MM-dd (3)yyyyMMddHHmmss (4) yyyy-MM-dd HH:mm:ss
   * @return Date 如果解析成功,则返回Date类型的对象,否则为 null
   */
  private static Date parseDate(final String strTime) {
    if (strTime == null || strTime.trim().length() < 6) // 日期时间的最小长度必须大于等于6
    {
      log.error("DateTimeUtil.parseDate()日期时间字符串 [" + strTime + "] 不符合系统格式要求!");
      //			LogUtil.writeRunLog("DateTimeUtil_" + LogUtil.getDate("yyyyMMdd")
      //					+ ".err", "日期时间字符串 [" + strTime + "] 不符合系统格式要求!",
      //					"parseDate");
      return null;
    }

    try {
      if (strTime.indexOf('-') >= 0) // yyyy-MM-dd HH:mm:ss
      {
        if (strTime.length() > 10) // 包括时间
        return timeFormat2.parse(strTime);
        else return dateFormat2.parse(strTime);
      } else
      // yyyyMMddHHmmss
      {
        if (strTime.length() > 8) // 包括时间
        return timeFormat1.parse(strTime);
        else return dateFormat1.parse(strTime);
      }
    } catch (ParseException e) {
      e.printStackTrace();
      return null;
    }
  }
  /**
   * Checa a data e a hora
   *
   * @param data A data
   * @param hora A hora
   * @throws InvalidAttributeValueException
   */
  public static void checaDataHora(String data, String hora) throws InvalidAttributeValueException {
    if (data == null) throw new InvalidAttributeValueException("Data inválida");
    if (hora == null) throw new InvalidAttributeValueException("Hora inválida");
    SimpleDateFormat format = null;
    String dataHora = data + " " + hora;
    Date date = null;

    format = new SimpleDateFormat("dd/MM/yyyy");
    format.setLenient(false);
    try {
      date = format.parse(data);
    } catch (Exception e) {
      throw new InvalidAttributeValueException("Data inválida");
    }

    format = new SimpleDateFormat("HH:mm");
    format.setLenient(false);
    try {
      date = format.parse(hora);
    } catch (Exception e) {
      throw new InvalidAttributeValueException("Hora inválida");
    }

    format = new SimpleDateFormat("dd/MM/yyyy HH:mm");
    format.setLenient(false);
    try {
      date = format.parse(dataHora);
    } catch (ParseException e) {
      e.printStackTrace();
    }
    if (date.before(new Date())) throw new InvalidAttributeValueException("Data inválida");
  }
  private Date getValidDate(Object raw) {

    if (raw instanceof String) {
      try {
        try {
          return formatter1.parse((String) raw);
        } catch (ParseException e) {
          // try w/o hours
        }
        return formatter2.parse((String) raw);
      } catch (ParseException e) {
        getLogger()
            .error(
                Messages.getInstance()
                    .getString(
                        "TimeSeriesCollectionChartDefinition.ERROR_0001_INVALID_DATE", //$NON-NLS-1$
                        (String) raw),
                e);
        return null;
      }
    } else {
      // This was the original code; if we have an unknown object
      // it will throw an exception, but would anyway.
      // It's a small atempt to make MDX queries work here
      return (Date) raw;
    }
  }
Example #18
0
  public ArrayList<FIncomePO> findByTime(String time1, String time2)
      throws RemoteException, IOException {
    ArrayList<FIncomePO> income = new ArrayList<FIncomePO>();
    ObjectInputStream os = null;

    SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
    try {
      Date date1 = formatter.parse(time1);
      Date date2 = formatter.parse(time2);

      FileInputStream fs = new FileInputStream(file);
      os = new ObjectInputStream(fs);
      FIncomePO po = (FIncomePO) os.readObject();

      while (fs.available() > 0) {
        byte[] buf = new byte[4];
        fs.read(buf);
        FIncomePO incomepo = (FIncomePO) os.readObject();

        if (formatter.parse(incomepo.getTime()).after(date1)
            && formatter.parse(incomepo.getTime()).before(date2)) {

          income.add(incomepo);
        }
      }

      return income;
    } catch (Exception e) {
      return null;
    } finally {
      os.close();
    }
  }
  public static List<PernottamentoEntity> searchByCityDate(
      String city, String checkInDateStr, String checkOutDateStr) {

    List<PernottamentoEntity> pernottamentoList;
    java.util.Date checkInDate, checkOutDate;

    SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
    SimpleDateFormat sdfSQL = new SimpleDateFormat("yyyy/MM/dd");
    try {
      checkInDate = sdf.parse(checkInDateStr);
      checkInDateStr = sdfSQL.format(checkInDate);

      checkOutDate = sdf.parse(checkOutDateStr);
      checkOutDateStr = sdfSQL.format(checkOutDate);
    } catch (ParseException e) {
      e.printStackTrace();
    }

    String query =
        "where città like '"
            + city
            + "' AND "
            + "data_inizio < '"
            + checkOutDateStr
            + " 00:00:00' AND "
            + "data_finale > '"
            + checkInDateStr
            + " 00:00:00'";
    DAO dao = PernottamentoDaoHibernate.instance();
    DBManager.initHibernate();
    pernottamentoList = (List<PernottamentoEntity>) dao.getByCriteria(query);
    DBManager.shutdown();

    return pernottamentoList;
  }
Example #20
0
 public boolean insertPersonJoinBrh(PersonJoinBrhBean t) throws Exception {
   SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd");
   if (t.getWorkBegin() == null || t.getWorkBegin().equals("")) {
     throw new RuntimeException("从业开始时间不能为空!");
   } else {
     try {
       sf.parse(t.getWorkBegin());
     } catch (ParseException e) {
       throw new RuntimeException("从业开始时间格式不正确!");
     }
   }
   if (t.getInsYears() == null || t.getInsYears().equals("")) {
     throw new RuntimeException("保险从业年限不能为空!");
   }
   if (t.getRecruitFrom() == null || t.getRecruitFrom().equals("")) {
     throw new RuntimeException("招募来源不能为空!");
   }
   if (t.getWorkDate() == null || t.getWorkDate().equals("")) {
     throw new RuntimeException("入司日期不能为空!");
   } else {
     try {
       sf.parse(t.getWorkDate());
     } catch (ParseException e) {
       throw new RuntimeException("入司日期格式不正确!");
     }
   }
   if (t.getRecruitType() == null || t.getRecruitType().equals("")) {
     throw new RuntimeException("招募类型不能为空!");
   }
   if (t.getLocalAttr() == null || t.getLocalAttr().equals("")) {
     throw new RuntimeException("地域属性不能为空!");
   }
   return dao.insertPersonJoinBrh(t);
 }
Example #21
0
 /**
  * Performs the Basic Access Control protocol.
  *
  * @param docNumber the document number
  * @param dateOfBirth card holder's birth date
  * @param dateOfExpiry document's expiry date
  * @throws CardServiceException if authentication failed
  * @throws ParseException if at least one of the dates could not be parsed
  */
 public void doBac(String docNumber, String dateOfBirth, String dateOfExpiry)
     throws CardServiceException, ParseException {
   if (activateTerminal()) {
     _activePassportService.doBAC(
         new BACKeySpec(docNumber, SDF.parse(dateOfBirth), SDF.parse(dateOfExpiry)));
   }
 }
Example #22
0
 /**
  * 将字符串解析为时间缀
  *
  * @param timestamp
  * @return Timestamp
  * @throws ParseException
  */
 public static Timestamp parseTimestamp(String timestamp) throws ParseException {
   try {
     return new Timestamp(DATE_TIME_FORMAT.parse(timestamp).getTime());
   } catch (ParseException e) {
     return new Timestamp(SHORT_DATE_TIME_FORMAT.parse(timestamp).getTime());
   }
 }
Example #23
0
  /**
   * 获取两个日期之间的间隔日期
   *
   * @author modi
   * @version 1.0.0
   */
  public static int getDaysBetween(final String beginDate, final String endDate) {

    try {
      final SimpleDateFormat format = new SimpleDateFormat("yyyyMMdd", Locale.SIMPLIFIED_CHINESE);
      final Date bDate = format.parse(beginDate);
      final Date eDate = format.parse(endDate);
      Calendar d1 = new GregorianCalendar();
      d1.setTime(bDate);
      final Calendar d2 = new GregorianCalendar();
      d2.setTime(eDate);

      if (d1.after(d2)) {
        return 0;
      }

      int days = d2.get(Calendar.DAY_OF_YEAR) - d1.get(Calendar.DAY_OF_YEAR);
      final int y2 = d2.get(Calendar.YEAR);
      if (d1.get(Calendar.YEAR) != y2) {
        d1 = (Calendar) d1.clone();
        do {
          days += d1.getActualMaximum(Calendar.DAY_OF_YEAR); // 得到当年的实际天数
          d1.add(Calendar.YEAR, 1);
        } while (d1.get(Calendar.YEAR) != y2);
      }
      return days;
    } catch (ParseException e) {
      return 0;
    }
  }
    /** add a label and values in */
    public void add(String label, String[] values) throws Exception {
      if (label.equals("from")) {
        fromDate = true;
        SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yy HH:mm");
        Date d = sdf.parse(values[0] + " 00:00");
        fromDateValue = d.getTime();

      } else if (label.equals("to")) {
        toDate = true;
        SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yy HH:mm");
        Date d = sdf.parse(values[0] + " 23:59");
        toDateValue = d.getTime();

      } else if (label.equals("request")) {
        request = true;
        requestValues = values;
      } else if (label.equals("response")) {
        response = true;
        responseValues = values;
      } else if (label.equals("person")) {
        person = true;
        personValue = values[0];
      } else if (label.equals("role")) {
        role = true;
        roleValues = values;
      } else {
        throw new Exception("Invalid label");
      }
    }
 @Function("public")
 public void doQuery(
     Context context, @Param(name = "from") String from, @Param(name = "to") String to) {
   try {
     Date start = new Date();
     Date end = new Date();
     if (from == null || to == null) {
       end = new Date();
       Calendar calendar = Calendar.getInstance();
       calendar.setTime(end);
       calendar.add(Calendar.DATE, -1); // 得到前一天
       start = calendar.getTime();
     } else {
       SimpleDateFormat fmt = new SimpleDateFormat("MM/dd/yyyy");
       start = fmt.parse(from);
       end = fmt.parse(to);
     }
     EucaConsoleMessage message = eucaAC.genVolumeReport(start, end);
     JSONObject object = (JSONObject) message.getData();
     JSONArray resluts = object.getJSONArray("reports");
     context.put("json", resluts);
   } catch (Exception e) {
     logger.error(e.getMessage(), e);
   }
 }
Example #26
0
  public static int dateTimeDifferenceGeneric(String start_time, String mask) {
    SimpleDateFormat sdf = new SimpleDateFormat(mask);

    DateFormat df = DateFormat.getDateTimeInstance();
    df.setTimeZone(TimeZone.getTimeZone("UTC"));
    String gmtTime = df.format(new Date());

    SimpleDateFormat localsdf = new SimpleDateFormat("MMM d, yyyy hh:mm:ss aaa");
    SimpleDateFormat localsdf24 = new SimpleDateFormat("MMM d, yyyy hh:mm:ss");
    Date staart = new Date();
    Date end = new Date();

    try {
      staart = sdf.parse(start_time);
      end = localsdf.parse(gmtTime);
    } catch (ParseException e) {
      try {
        end = localsdf24.parse(gmtTime);
      } catch (ParseException e1) {
        e1.printStackTrace();
      }
    }
    //        Date hoy = new Date();
    long diff = end.getTime() - staart.getTime();
    long diffMinutes = diff / (60 * 1000); // % 60;

    Log.e("chuy time:", String.valueOf(Math.round(diffMinutes)));
    return Math.round(diffMinutes);
  }
  /**
   * Generates some test tasks. - 2 tasks where kermit is a candidate and 1 task where gonzo is
   * assignee
   */
  private List<String> generateTestTasks() throws Exception {
    List<String> ids = new ArrayList<String>();

    SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy hh:mm:ss.SSS");
    // 2 tasks for kermit
    ClockUtil.setCurrentTime(sdf.parse("01/01/2001 01:01:01.000"));
    for (int i = 0; i < 2; i++) {
      Task task = taskService.newTask();
      task.setName("testTask");
      task.setDescription("testTask description");
      task.setPriority(3);
      taskService.saveTask(task);
      ids.add(task.getId());
      taskService.setVariableLocal(task.getId(), "test", "test");
      taskService.addCandidateUser(task.getId(), "kermit");
    }

    ClockUtil.setCurrentTime(sdf.parse("02/02/2002 02:02:02.000"));
    // 1 task for gonzo
    Task task = taskService.newTask();
    task.setName("gonzoTask");
    task.setDescription("gonzo description");
    task.setPriority(4);
    taskService.saveTask(task);
    taskService.setAssignee(task.getId(), "gonzo");
    taskService.setVariableLocal(task.getId(), "testVar", "someVariable");
    taskService.setVariableLocal(task.getId(), "testVar2", 123);
    ids.add(task.getId());

    return ids;
  }
  @SuppressWarnings("unused")
  // called by reflection
  private List<String> testLeftJoinCube2() throws Exception {
    SimpleDateFormat f = new SimpleDateFormat("yyyy-MM-dd");
    f.setTimeZone(TimeZone.getTimeZone("GMT"));
    List<String> result = Lists.newArrayList();
    final String cubeName = "test_kylin_cube_without_slr_left_join_empty";
    // this cube's start date is 0, end date is 20120601000000
    long dateStart =
        cubeManager
            .getCube(cubeName)
            .getDescriptor()
            .getModel()
            .getPartitionDesc()
            .getPartitionDateStart();
    long dateEnd = f.parse("2012-06-01").getTime();

    clearSegment(cubeName);
    result.add(buildSegment(cubeName, dateStart, dateEnd));

    // then submit an append job, start date is 20120601000000, end
    // date is 20220101000000
    dateStart = f.parse("2012-06-01").getTime();
    dateEnd = f.parse("2022-01-01").getTime();
    result.add(buildSegment(cubeName, dateStart, dateEnd));
    return result;
  }
Example #29
0
  public static String convertISOToSimpleDateFormat(String dateStr) {
    SimpleDateFormat formatter, simpleDateFormatter;
    String simpleDateStr = "";
    formatter = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'");
    IConfig config = SefCoreServiceResolver.getConfigService();
    String simpleDateFromat = config.getValue("GLOBAL", "dateFormat");
    Date date = null;
    try {
      date = formatter.parse(dateStr.substring(0, 24));
      simpleDateFormatter = new SimpleDateFormat(simpleDateFromat);
      simpleDateStr = simpleDateFormatter.format(date);
    } catch (Exception ps) {
      try {
        date = formatter.parse(dateStr.substring(0, 23));
      } catch (Exception e) {
      }
      try {
        simpleDateFormatter = new SimpleDateFormat(simpleDateFromat);
        simpleDateStr = simpleDateFormatter.format(date);
      } catch (Exception e) {

        logger.error("Exception captured.@ convertISOToSimpleDateFormat..", e);
      }
    }
    return simpleDateStr;
  }
Example #30
0
  public List<Evento> findEventoAll() {
    SQLiteDatabase banco = bancoHelper.getWritableDatabase();
    Cursor c =
        banco.query(
            TabelaEventoUtils.TABLENAME, null, null, null, null, null, TabelaEventoUtils.EVENTO_ID);

    List<Evento> listaEventos = new ArrayList<>();

    while (c.moveToNext()) {
      try {
        Evento evento = new Evento();
        SimpleDateFormat formato = new SimpleDateFormat("dd/MM/yyyy - hh:mm:ss");

        evento.set_id(c.getInt(c.getColumnIndex(TabelaEventoUtils.EVENTO_ID)));
        evento.setNome(c.getString(c.getColumnIndex(TabelaEventoUtils.EVENTO_NOME)));
        evento.setLocal(c.getString(c.getColumnIndex(TabelaEventoUtils.EVENTO_LOCAL)));
        evento.setDescricao(c.getString(c.getColumnIndex(TabelaEventoUtils.EVENTO_DESCRICAO)));
        evento.setDataInicio(
            formato.parse(c.getString(c.getColumnIndex(TabelaEventoUtils.EVENTO_DATA_INICIO))));
        evento.setDataTermino(
            formato.parse(c.getString(c.getColumnIndex(TabelaEventoUtils.EVENTO_DATA_TERMINO))));
        evento.setLatitude(
            Double.parseDouble(c.getString(c.getColumnIndex(TabelaEventoUtils.EVENTO_LATITUDE))));
        evento.setLongitude(
            Double.parseDouble(c.getString(c.getColumnIndex(TabelaEventoUtils.EVENTO_LONGITUDE))));

        listaEventos.add(evento);

      } catch (ParseException ex) {
        ex.printStackTrace();
      }
    }

    return listaEventos;
  }