List of usage examples for org.apache.commons.lang3.time DateUtils addSeconds
public static Date addSeconds(final Date date, final int amount)
From source file:eu.ggnet.dwoss.stock.StockTransactionProcessorOperation.java
/** * Bring a list of transactions from prepared into the state in transfer via commission. * <p/>//from www .ja v a2 s . c o m * @param transactions the transaction to commission * @param picker the pricker of units * @param deliverer the transferer. * @throws RuntimeException if the transaction is in some form invalid. */ // TODO: how about some validations. @Override public void commission(List<StockTransaction> transactions, String picker, String deliverer) throws RuntimeException { for (StockTransaction transaction : transactions) { L.info("Commissioning {}", transaction); Set<ConstraintViolation<StockTransaction>> violations = VALIDATOR.validate(transaction); if (!violations.isEmpty()) throw new RuntimeException("Invalid StockTransaction in PRE-Validate: " + ConstraintViolationFormater.toSingleLine(violations)); transaction = stockEm.find(StockTransaction.class, transaction.getId()); Date before = transaction.addStatus(COMMISSIONED, PICKER, picker, DELIVERER, deliverer); transaction.addStatus(DateUtils.addSeconds(before, 1), IN_TRANSFER, DELIVERER, deliverer); violations = VALIDATOR.validate(transaction); if (!violations.isEmpty()) throw new RuntimeException("Invalid StockTransaction in POST-Validate: " + ConstraintViolationFormater.toSingleLine(violations)); for (StockUnit stockUnit : transaction.getUnits()) { stockUnit.setStock(null); } } }
From source file:com.pinterest.rocksplicator.controller.mysql.MySQLTaskQueue.java
@Override public int resetZombieTasks(final int zombieThresholdSeconds) { beginTransaction();/* w w w .j av a2 s. c om*/ List<TaskEntity> runningTasks = getEntityManager().createNamedQuery("task.peekTasksWithState") .setParameter("state", TaskState.RUNNING.intValue()).setLockMode(LockModeType.PESSIMISTIC_WRITE) .getResultList(); List<TaskEntity> zombieTasks = runningTasks.stream() .filter(t -> t.getState() == TaskState.RUNNING.intValue() && DateUtils.addSeconds(t.getLastAliveAt(), zombieThresholdSeconds).before(new Date())) .collect(Collectors.toList()); for (TaskEntity zombieTask : zombieTasks) { getEntityManager().lock(zombieTask.getCluster(), LockModeType.PESSIMISTIC_WRITE); zombieTask.setState(TaskState.PENDING.intValue()); zombieTask.getCluster().setLocks(0); getEntityManager().persist(zombieTask); getEntityManager().persist(zombieTask.getCluster()); } getEntityManager().getTransaction().commit(); return zombieTasks.size(); }
From source file:de.tor.tribes.ui.algo.AttackTimePanel.java
/** * Get the entire timeframe based on the panel settings * * @return TimeFrame The timeframe/*from ww w . j a v a2 s . c om*/ */ public TimeFrame getTimeFrame() { Date correctedArrive = DateUtils.addDays(maxArriveTimeField.getSelectedDate(), 1); correctedArrive = DateUtils.addSeconds(correctedArrive, -1); maxArriveTimeField.setDate(correctedArrive); TimeFrame frame = new TimeFrame(minSendTimeField.getSelectedDate(), minSendTimeField.getSelectedDate(), correctedArrive, correctedArrive); DefaultListModel model = (DefaultListModel) jTimeFrameList.getModel(); for (int i = 0; i < jTimeFrameList.getModel().getSize(); i++) { TimeSpan s = (TimeSpan) model.getElementAt(i); if (s.getDirection().equals(TimeSpan.DIRECTION.SEND)) { frame.addStartTimeSpan(s); } else if (s.getDirection().equals(TimeSpan.DIRECTION.ARRIVE)) { frame.addArriveTimeSpan(s); } } return frame; }
From source file:com.pinterest.rocksplicator.controller.mysql.MySQLTaskQueue.java
@Override public int removeFinishedTasks(final int secondsAgo, final String namespace, final String clusterName, final String taskName) { beginTransaction();//from ww w . ja v a 2 s . c o m List<TaskEntity> finishedTasks; if (Strings.isNullOrEmpty(namespace)) { if (Strings.isNullOrEmpty(taskName)) { finishedTasks = getEntityManager().createNamedQuery("task.peekTasksWithState") .setParameter("state", TaskState.DONE.intValue()) .setLockMode(LockModeType.PESSIMISTIC_WRITE).getResultList(); } else { finishedTasks = getEntityManager().createNamedQuery("task.peekTasksWithStateAndName") .setParameter("state", TaskState.DONE.intValue()).setParameter("name", taskName) .setLockMode(LockModeType.PESSIMISTIC_WRITE).getResultList(); } } else { if (Strings.isNullOrEmpty(clusterName)) { if (Strings.isNullOrEmpty(taskName)) { finishedTasks = getEntityManager().createNamedQuery("task.peekTasksWithStateFromNamespace") .setParameter("state", TaskState.DONE.intValue()).setParameter("namespace", namespace) .setLockMode(LockModeType.PESSIMISTIC_WRITE).getResultList(); } else { finishedTasks = getEntityManager() .createNamedQuery("task.peekTasksWithStateAndNameFromNamespace") .setParameter("state", TaskState.DONE.intValue()).setParameter("namespace", namespace) .setParameter("name", taskName).setLockMode(LockModeType.PESSIMISTIC_WRITE) .getResultList(); } } else { if (Strings.isNullOrEmpty(taskName)) { finishedTasks = getEntityManager().createNamedQuery("task.peekTasksWithStateFromCluster") .setParameter("state", TaskState.DONE.intValue()).setParameter("namespace", namespace) .setParameter("name", clusterName).setLockMode(LockModeType.PESSIMISTIC_WRITE) .getResultList(); } else { finishedTasks = getEntityManager().createNamedQuery("task.peekTasksWithStateAndNameFromCluster") .setParameter("state", TaskState.DONE.intValue()).setParameter("namespace", namespace) .setParameter("name", taskName).setParameter("clusterName", clusterName) .setLockMode(LockModeType.PESSIMISTIC_WRITE).getResultList(); } } } List<TaskEntity> removingTasks = finishedTasks.stream() .filter(t -> DateUtils.addSeconds(t.getCreatedAt(), secondsAgo).before(new Date())) .collect(Collectors.toList()); removingTasks.stream().forEach(t -> getEntityManager().remove(t)); getEntityManager().getTransaction().commit(); return removingTasks.size(); }
From source file:com.feilong.core.date.DateUtil.java
/** * <code>date</code>? ({@link java.util.Calendar#SECOND}?,??),,. * //from ww w . ja v a2s . c o m * <p> * ?<code>date</code>?? * </p> * * <h3>:</h3> * * <blockquote> * * <pre class="code"> * DateUtil.addSecond(2012-10-16 23:22:02,180) =2012-10-16 23:25:02.206 * DateUtil.addSecond(2012-10-16 23:22:02,-180) =2012-10-16 23:19:02.206 * </pre> * * </blockquote> * * @param date * ? * @param second * ?,<span style="color:red">?</span>,??<br> * @return <code>date</code>null, {@link java.lang.IllegalArgumentException} * @see org.apache.commons.lang3.time.DateUtils#addSeconds(Date, int) */ public static Date addSecond(Date date, int second) { return DateUtils.addSeconds(date, second); }
From source file:egovframework.example.sample.web.EgovSampleController.java
@RequestMapping(value = "/cashPay.do", method = RequestMethod.POST) public String cashPay( //? HttpServletRequest request,//from w w w. j a va2 s.c o m @RequestParam("dType") String o_type, // @RequestParam("pPricee") int o_price, // ? @RequestParam("o_name") String o_name, //?? @RequestParam("o_phone") String o_phone, //? @RequestParam("o_adress") String o_adress, //? @RequestParam("o_orderMessage") String o_omessage, // @RequestParam("o_delivMessage") String o_dmessage, // @RequestParam("useCash") int useCash, // ? @RequestParam("cashSum") int cashSum, //? ? Model model, SessionStatus status) throws Exception { if (o_omessage.isEmpty()) { o_omessage = ""; } if (o_dmessage.isEmpty()) { o_dmessage = ""; } //System.out.println("1"+ o_type+"2"+ o_price+"3"+o_name +"4"+o_phone +"5"+ o_adress+"6"+ o_omessage+"7"+o_dmessage +"8"+useCash ); ///// ?// Date orderDate = DateUtils.addDays(new Date(), 0); orderDate = DateUtils.addSeconds(orderDate, 0); Format sdf = FastDateFormat.getInstance("yyyyMMddhhmmss", Locale.getDefault()); String orderDates = sdf.format(orderDate); String code = ""; for (int i = 1; i <= 4; i++) { char ch = (char) ((Math.random() * 26) + 65); code = ch + code; } String orderCode = orderDates + code; //System.out.println("-"+orderCode); //////////////////////////////////////////////////// OrderResult or = new OrderResult(o_omessage, o_dmessage, o_name, o_phone, o_adress, orderCode, o_price, useCash); model.addAttribute("orderList", or); HttpSession hs = request.getSession(); Account loginInfo = (Account) hs.getAttribute("userInfo"); Account acc = new Account(); model.addAttribute("myCash", loginInfo.getA_cash()); //? ? (? - ? +? ?) // loginInfo.getA_cash() - useCash + cashSum //int resultCash = (loginInfo.getA_cash() - useCash) +cashSum; int resultCash = (loginInfo.getA_cash() - useCash); acc.setA_cash(resultCash); acc.setA_id(loginInfo.getA_id()); sampleService.useCash(acc); status.setComplete(); System.out.println("? "); KartVO kart = new KartVO(); kart.setK_id(loginInfo.getA_id()); List<KartVO> kartList = sampleService.kartList(kart); String ol_name = kartList.get(0).getK_name(); model.addAttribute("resultList", kartList); for (int i = 0; i < kartList.size(); i++) { int pSeq = kartList.get(i).getK_seq(); int pEa = kartList.get(i).getK_ea(); String pname = kartList.get(i).getK_name(); //System.out.println(pname); // ? //TODO ? ?(?? ) Product product = new Product(); product.setP_seq(pSeq); Product product2 = sampleService.selectProduct(product); int proEa = product2.getP_ea(); int setEa = proEa - pEa; product.setP_ea(setEa); sampleService.updateEa(product); ///? OrderSeetVO orderVO = new OrderSeetVO(orderCode, loginInfo.getA_id(), o_type, o_name, o_phone, o_adress, o_omessage, o_dmessage, pname, pEa, o_price, pSeq); sampleService.orderSeet(orderVO); status.setComplete(); System.out.println(i + " ? ?"); if (i == kartList.size() - 1) { ol_name = ol_name + " " + i + ""; } } //? OrderSeetListVO oslVO = new OrderSeetListVO(orderCode, loginInfo.getA_id(), " ", ol_name, o_omessage, o_dmessage, o_price); sampleService.orderSeetList(oslVO); System.out.println("? ?"); // sampleService.allDeleteKart(kart); status.setComplete(); System.out.println(" "); ////? refresh ? ///////// Account ac = new Account(); ac.setA_id(loginInfo.getA_id()); Account ac2 = sampleService.getAccount(ac); hs.setAttribute("userInfo", ac2); // hs.setMaxInactiveInterval(1*60*60); ////////////////////////////////////////////// model.addAttribute("login", "loginOK.jsp"); model.addAttribute("main", "orderResult.jsp"); return "sample/home"; }
From source file:org.apache.falcon.lifecycle.engine.oozie.retention.AgeBasedCoordinatorBuilder.java
/** * Builds the coordinator app./*from w w w . j av a 2 s . c o m*/ * @param cluster - cluster to schedule retention on. * @param basePath - Base path to marshal coordinator app. * @param feed - feed for which retention is to be scheduled. * @param wfProp - properties passed from workflow to coordinator e.g. ENTITY_PATH * @return - Properties from creating the coordinator application to be used by Bundle. * @throws FalconException */ public static Properties build(Cluster cluster, Path basePath, Feed feed, Properties wfProp) throws FalconException { org.apache.falcon.entity.v0.feed.Cluster feedCluster = FeedHelper.getCluster(feed, cluster.getName()); if (feedCluster.getValidity().getEnd().before(new Date())) { LOG.warn("Feed Retention is not applicable as Feed's end time for cluster {} is not in the future", cluster.getName()); return null; } COORDINATORAPP coord = new COORDINATORAPP(); String coordName = EntityUtil.getWorkflowName(LifeCycle.EVICTION.getTag(), feed).toString(); coord.setName(coordName); Date endDate = feedCluster.getValidity().getEnd(); if (RuntimeProperties.get().getProperty("falcon.retention.keep.instances.beyond.validity", "true") .equalsIgnoreCase("false")) { int retentionLimitinSecs = FeedHelper.getRetentionLimitInSeconds(feed, cluster.getName()); endDate = DateUtils.addSeconds(endDate, retentionLimitinSecs); } coord.setEnd(SchemaHelper.formatDateUTC(endDate)); coord.setStart(SchemaHelper.formatDateUTC(new Date())); coord.setTimezone(feed.getTimezone().getID()); Frequency retentionFrequency = FeedHelper.getLifecycleRetentionFrequency(feed, cluster.getName()); // set controls long frequencyInMillis = ExpressionHelper.get().evaluate(retentionFrequency.toString(), Long.class); CONTROLS controls = new CONTROLS(); controls.setExecution(ExecutionType.LAST_ONLY.value()); controls.setTimeout(String.valueOf(frequencyInMillis / (1000 * 60))); controls.setConcurrency("1"); controls.setThrottle("1"); coord.setControls(controls); coord.setFrequency("${coord:" + retentionFrequency.toString() + "}"); Path buildPath = OozieBuilderUtils.getBuildPath(basePath, LifeCycle.EVICTION.getTag()); Properties props = OozieBuilderUtils.createCoordDefaultConfiguration(coordName, feed); props.putAll(OozieBuilderUtils.getProperties(buildPath, coordName)); WORKFLOW workflow = new WORKFLOW(); String entityPath = wfProp.getProperty(OozieBuilderUtils.ENTITY_PATH); String storagePath = OozieBuilderUtils.getStoragePath(entityPath); workflow.setAppPath(storagePath); workflow.setConfiguration(OozieBuilderUtils.getCoordinatorConfig(props)); ACTION action = new ACTION(); action.setWorkflow(workflow); coord.setAction(action); Path marshalPath = OozieBuilderUtils.marshalCoordinator(cluster, coord, buildPath); return OozieBuilderUtils.getProperties(marshalPath, coordName); }
From source file:org.apache.falcon.oozie.feed.FeedRetentionCoordinatorBuilder.java
@Override public List<Properties> buildCoords(Cluster cluster, Path buildPath) throws FalconException { org.apache.falcon.entity.v0.feed.Cluster feedCluster = FeedHelper.getCluster(entity, cluster.getName()); if (feedCluster == null) { return null; }// ww w .ja v a 2s. c o m COORDINATORAPP coord = new COORDINATORAPP(); String coordName = getEntityName(); coord.setName(coordName); Date endDate = feedCluster.getValidity().getEnd(); if (RuntimeProperties.get().getProperty("falcon.retention.keep.instances.beyond.validity", "true") .equalsIgnoreCase("false")) { int retentionLimitinSecs = FeedHelper.getRetentionLimitInSeconds(entity, cluster.getName()); endDate = DateUtils.addSeconds(endDate, retentionLimitinSecs); } coord.setEnd(SchemaHelper.formatDateUTC(endDate)); if (feedCluster.getValidity().getEnd().before(new Date())) { Date startDate = DateUtils.addMinutes(endDate, -1); coord.setStart(SchemaHelper.formatDateUTC(startDate)); } else { coord.setStart(SchemaHelper.formatDateUTC(new Date())); } coord.setTimezone(entity.getTimezone().getID()); Frequency entityFrequency = entity.getFrequency(); Frequency defaultFrequency = new Frequency("hours(24)"); if (DateUtil.getFrequencyInMillis(entityFrequency) < DateUtil.getFrequencyInMillis(defaultFrequency)) { coord.setFrequency("${coord:hours(6)}"); } else { coord.setFrequency("${coord:days(1)}"); } Path coordPath = getBuildPath(buildPath); Properties props = createCoordDefaultConfiguration(coordName); WORKFLOW workflow = new WORKFLOW(); Properties wfProps = OozieOrchestrationWorkflowBuilder.get(entity, cluster, Tag.RETENTION).build(cluster, coordPath); workflow.setAppPath(getStoragePath(wfProps.getProperty(OozieEntityBuilder.ENTITY_PATH))); props.putAll(getProperties(coordPath, coordName)); // Add the custom properties set in feed. Else, dryrun won't catch any missing props. props.putAll(EntityUtil.getEntityProperties(entity)); workflow.setConfiguration(getConfig(props)); ACTION action = new ACTION(); action.setWorkflow(workflow); coord.setAction(action); Path marshalPath = marshal(cluster, coord, coordPath); return Arrays.asList(getProperties(marshalPath, coordName)); }
From source file:org.apache.syncope.fit.core.SchedTaskITCase.java
@Test public void deferred() { ImplementationTO taskJobDelegate = implementationService.read(TestSampleJobDelegate.class.getSimpleName()); assertNotNull(taskJobDelegate);// ww w . j a v a 2s .co m SchedTaskTO task = new SchedTaskTO(); task.setActive(true); task.setName("deferred"); task.setJobDelegate(taskJobDelegate.getKey()); Response response = taskService.create(task); task = getObject(response.getLocation(), TaskService.class, SchedTaskTO.class); assertNotNull(task); Date initial = new Date(); Date later = DateUtils.addSeconds(initial, 2); taskService.execute(new ExecuteQuery.Builder().key(task.getKey()).startAt(later).build()); int i = 0; int maxit = 50; // wait for completion (executions incremented) do { try { Thread.sleep(1000); } catch (InterruptedException e) { } task = taskService.read(task.getKey(), true); assertNotNull(task); assertNotNull(task.getExecutions()); i++; } while (task.getExecutions().isEmpty() && i < maxit); PagedResult<ExecTO> execs = taskService.listExecutions(new ExecQuery.Builder().key(task.getKey()).build()); assertEquals(1, execs.getTotalCount()); assertTrue(execs.getResult().get(0).getStart().after(initial)); // round 1 sec for safety assertTrue(DateUtils.addSeconds(execs.getResult().get(0).getStart(), 1).after(later)); }
From source file:org.javabeanstack.security.DigestAuth.java
/** * Elimina todos los objeto de autenticacin que ya fuern utilizados o no * se hiciern referencia en un tiempo definido en el atributo secondsIdle *//* www . j a v a2 s .c om*/ public void purgeResponseAuth() { Date now = DateUtils.addSeconds(Dates.now(), secondsIdle * -1); for (Iterator<Map.Entry<String, ServerAuth>> it = serverAuthMap.entrySet().iterator(); it.hasNext();) { Map.Entry<String, ServerAuth> entry = it.next(); if (entry.getValue().getLastReference().before(now)) { it.remove(); } } }