List of usage examples for java.util GregorianCalendar setTime
public final void setTime(Date date)
Date
. From source file:es.tid.fiware.rss.expenditureLimit.processing.test.ProcessingLimitServiceTest.java
/** * Update periods and check amounts./* w w w .j a v a 2s . c om*/ */ @Test @Transactional(propagation = Propagation.SUPPORTS) public void checkControls() { DbeTransaction tx = ProcessingLimitServiceTest.generateTransaction(); tx.setTxEndUserId("userIdUpdate"); try { List<DbeExpendControl> controlsBefore = controlService.getExpendDataForUserAppProvCurrencyObCountry( tx.getTxEndUserId(), tx.getBmService(), tx.getTxAppProvider(), tx.getBmCurrency(), tx.getBmObMop().getBmObCountry()); Assert.assertNotNull(controlsBefore); // Reset dates to current date--> if not test fail GregorianCalendar cal = (GregorianCalendar) Calendar.getInstance(); cal.setTime(new Date()); cal.add(Calendar.DAY_OF_MONTH, 1); DefaultTransactionDefinition def = new DefaultTransactionDefinition(); def.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW); TransactionStatus status = transactionManager.getTransaction(def); for (DbeExpendControl control : controlsBefore) { control.setDtNextPeriodStart(cal.getTime()); controlService.createOrUpdate(control); } transactionManager.commit(status); limitService.proccesLimit(tx); List<DbeExpendControl> controlsAfter = controlService.getExpendDataForUserAppProvCurrencyObCountry( tx.getTxEndUserId(), tx.getBmService(), tx.getTxAppProvider(), tx.getBmCurrency(), tx.getBmObMop().getBmObCountry()); ProcessingLimitServiceTest.logger.debug("Controls:" + controlsAfter.size()); for (DbeExpendControl controlInit : controlsBefore) { for (DbeExpendControl controlEnd : controlsAfter) { if (controlInit.getId().getTxElType().equalsIgnoreCase(controlEnd.getId().getTxElType())) { // All the values without modification Assert.assertTrue( controlInit.getFtExpensedAmount().compareTo(controlEnd.getFtExpensedAmount()) == 0); break; } } } } catch (RSSException e) { ProcessingLimitServiceTest.logger.debug("Error: " + e.getMessage()); Assert.fail("Exception not expected"); } // check error try { tx.setFtChargedTotalAmount(null); tx.setFtInternalTotalAmount(new BigDecimal(1000)); limitService.proccesLimit(tx); Assert.fail("Exception expected"); } catch (RSSException e) { ProcessingLimitServiceTest.logger.debug("Exception received: " + e.getMessage()); // "SVC3705", Assert.assertTrue(e.getMessage().contains("Insufficient payment method balance")); } // check that try { tx.setFtChargedTotalAmount(null); tx.setFtInternalTotalAmount(new BigDecimal(30)); List<DbeExpendControl> controlsBefore = controlService.getExpendDataForUserAppProvCurrencyObCountry( tx.getTxEndUserId(), tx.getBmService(), tx.getTxAppProvider(), tx.getBmCurrency(), tx.getBmObMop().getBmObCountry()); // Reset period DbeExpendControl control = controlsBefore.get(0); GregorianCalendar cal = (GregorianCalendar) Calendar.getInstance(); cal.setTime(new Date()); cal.add(Calendar.MONTH, -1); control.setDtNextPeriodStart(cal.getTime()); DefaultTransactionDefinition def = new DefaultTransactionDefinition(); def.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW); TransactionStatus status = transactionManager.getTransaction(def); controlService.update(control); transactionManager.commit(status); limitService.proccesLimit(tx); List<DbeExpendControl> controlsAfter = controlService.getExpendDataForUserAppProvCurrencyObCountry( tx.getTxEndUserId(), tx.getBmService(), tx.getTxAppProvider(), tx.getBmCurrency(), tx.getBmObMop().getBmObCountry()); boolean finded = false; for (DbeExpendControl checkControl : controlsAfter) { if (checkControl.getFtExpensedAmount().compareTo(new BigDecimal(0)) == 0) { finded = true; break; } } // reset control found Assert.assertTrue(finded); } catch (RSSException e) { ProcessingLimitServiceTest.logger.debug("Exception received: " + e.getMessage()); Assert.fail("Exception expected"); } }
From source file:org.miloss.fgsms.common.Utility.java
/** * Parses the date/time stamp from a given input parameter using one of the * following formats<br> <ul> <li>mm/dd/yyyy</li> <li>mm/dd/yyyy * hh:mm:ss</li> <li>EEE MMM dd HH:mm:ss zzz yyyy - this is the standard * output from the unix date command</li> <li>EEE mm/dd/yyyy HH:mm:ss.ms - * this is the standard output from the windows command echo %date% * %time%</li> <li>yyyy-MM-ddThh:mm:ss.zzzzzzz</li> <li>Epoch time (ms)</li> * <li>PnYnMnDTnHnMnS - XML lexical representation</li> </ul> * * @param s the input string/*from www.j ava 2 s .c om*/ * @return a non-null instance of Calendar matching the interpreted date. * @throws Exception if the date cannot be parsed */ public static Calendar parseDateTime(String s) throws Exception { //this is what the calendar widget gives us SimpleDateFormat f1 = new SimpleDateFormat("MM/dd/yyyy"); SimpleDateFormat f2 = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss"); //std unix date format SimpleDateFormat f3 = new SimpleDateFormat("EEE MMM dd HH:mm:ss zzz yyyy"); //std windows date format SimpleDateFormat f4 = new SimpleDateFormat("EEE MM/dd/yyyy HH:mm:ss.ms"); SimpleDateFormat f5 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.zzzzzzz"); Date d = null; try { d = f1.parse(s, new ParsePosition(0)); } catch (Exception ex) { } if (d == null) { try { d = f2.parse(s, new ParsePosition(0)); } catch (Exception ex) { } } if (d == null) { try { d = f3.parse(s, new ParsePosition(0)); } catch (Exception ex) { } } if (d == null) { try { d = f4.parse(s, new ParsePosition(0)); } catch (Exception ex) { } } if (d == null) { try { d = f5.parse(s, new ParsePosition(0)); } catch (Exception ex) { } } if (d != null) { GregorianCalendar gcal = new GregorianCalendar(); gcal.setTime(d); return (gcal); } try { long timestamp = Long.parseLong(s); GregorianCalendar gcal = new GregorianCalendar(); gcal.setTimeInMillis(timestamp); return (gcal); } catch (Exception x) { } throw new Exception("Unable to parse the date, see documentation for correct usage"); }
From source file:com.sapienter.jbilling.server.process.AgeingBL.java
/** * Goes over all the users that are not active, and calls age on them. * This doesn't discriminate over entities. *///w w w . ja v a2 s. co m public void reviewAll(Date today) throws NamingException, SessionInternalError, SQLException { // go over all the users already in the ageing system for (UserDTO userRow : new UserDAS().findAgeing()) { age(userRow, today); } // now go over the active users with payable invoices UserBL user = new UserBL(); CachedRowSet usersSql; try { usersSql = user.findActiveWithOpenInvoices(); } catch (Exception e) { // avoid further problems LOG.error("Exception finding users to age", e); return; } InvoiceBL invoiceBL = new InvoiceBL(); while (usersSql.next()) { Integer userId = new Integer(usersSql.getInt(1)); user.set(userId); UserDTO userRow = user.getEntity(); // get the grace period for the entity of this user PreferenceBL prefs = new PreferenceBL(); prefs.set(userRow.getEntity().getId(), Constants.PREFERENCE_GRACE_PERIOD); int gracePeriod = prefs.getInt(); LOG.debug("Reviewing invoices of user:" + userRow.getUserId() + " grace: " + gracePeriod); // now go over this user's pending invoices for (Iterator it2 = invoiceBL.getHome().findProccesableByUser(userRow).iterator(); it2.hasNext();) { InvoiceDTO invoice = (InvoiceDTO) it2.next(); GregorianCalendar cal = new GregorianCalendar(); cal.setTime(invoice.getDueDate()); if (gracePeriod > 0) { cal.add(Calendar.DATE, gracePeriod); } if (userRow.getUserId().intValue() == 17) { LOG.debug("invoice " + invoice.getId() + " due+grace=" + cal.getTime() + " today=" + today + " compare=" + (cal.getTime().compareTo(today))); } if (cal.getTime().compareTo(today) < 0) { // ok, this user has an overdue invoice age(userRow, today); break; } } } }
From source file:com.esd.ps.LoginController.java
/** * ,//w w w . ja v a 2s. c o m * @return */ @RequestMapping(value = "/moneyList", method = RequestMethod.POST) @ResponseBody public Map<String, Object> moneyListPost() { Map<String, Object> map = new HashMap<String, Object>(); // Calendar cal = Calendar.getInstance(); cal.setTime(new Date()); int week = cal.get(Calendar.DAY_OF_WEEK); // if (week == 7) { week = 0; } //logger.debug("week:{}",week); // SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd"); // ()? GregorianCalendar gc = new GregorianCalendar(); // ?? gc.setTime(new Date()); // ?? gc.add(5, -week); // String beginDate = sdf.format(gc.getTime()); String endDate = sdf.format(new Date()); SimpleDateFormat sdf1 = new SimpleDateFormat("MMdd"); String beginDate1 = sdf1.format(gc.getTime()); String endDate1 = sdf1.format(new Date()); //logger.debug("beginDate:{},endDate:{}",beginDate,endDate); manager manager = managerService.selectByPrimaryKey(1); List<Map<String, Object>> monthList = salaryService.getMoneyList("", "", endDate); List<Map<String, Object>> weekList = salaryService.getMoneyList(beginDate, endDate, ""); List<Map<String, Object>> totleList = salaryService.getMoneyList("", "", ""); map.put("salary", manager.getSalary()); map.put("monthList", monthList); map.put("weekList", weekList); map.put("totleList", totleList); map.put("weekDate", beginDate1 + "-" + endDate1); return map; }
From source file:es.logongas.encuestas.presentacion.controller.EncuestaController.java
private Curso getCursoFromDate(Date date) { GregorianCalendar gc = new GregorianCalendar(); gc.setTime(date); int anyoInicioCurso; int anyoActual = gc.get(GregorianCalendar.YEAR); int mesActual = gc.get(GregorianCalendar.MONTH); //A partir de Mayo estamos en el nuevo curso a efectos de las encuestas de matricula if (mesActual >= Calendar.MAY) { anyoInicioCurso = anyoActual;//from w w w .j a v a 2s . c o m } else { anyoInicioCurso = anyoActual - 1; } CursoDAO cursoDAO = (CursoDAO) daoFactory.getDAO(Curso.class); Curso curso = cursoDAO.getByAnyoInicio(anyoInicioCurso); if (curso == null) { //Creamos un nuevo curso para este ao throw new RuntimeException("No existe el curso que empieza en el ao:" + anyoInicioCurso); } return curso; }
From source file:es.tid.fiware.rss.controller.SettlementController.java
/** * Do settlement.// w w w .ja va2 s.c o m * * @param dateFrom * @param dateTo * @param aggregatorId * @param model * @return the model and view */ @RequestMapping(value = "/doSettlement", headers = "Accept=*/*", produces = "application/json") @ResponseBody public JsonResponse doSettlement(@QueryParam("dateFrom") String dateFrom, @QueryParam("dateTo") String dateTo, @QueryParam("aggregatorId") String aggregatorId, @QueryParam("providerId") String providerId, ModelMap model) { try { logger.debug("doSettlement - Provider: {} , aggregator: {}", providerId, aggregatorId); logger.debug("doSettlement - Start: Init" + dateFrom + ",End:" + dateTo); SimpleDateFormat format = new SimpleDateFormat("yyyy-MM"); SimpleDateFormat getDate = new SimpleDateFormat("MM/yyyy"); String initDate = ""; String endDate = ""; if (dateFrom != null && !"".equalsIgnoreCase(dateFrom) && dateTo != null && !"".equalsIgnoreCase(dateTo)) { Date from = getDate.parse(dateFrom); Date to = getDate.parse(dateTo); initDate = format.format(from); endDate = format.format(to); } else { // By default use the current month GregorianCalendar cal = (GregorianCalendar) Calendar.getInstance(); cal.setTime(new Date()); cal.set(Calendar.DAY_OF_MONTH, 1); initDate = format.format(cal.getTime()); cal.add(Calendar.MONTH, 1); endDate = format.format(cal.getTime()); } // Calculate settlement. settlementManager.runSettlement(initDate, endDate, aggregatorId, providerId); JsonResponse response = new JsonResponse(); response.setMessage("Settlement proccess launched correctly."); response.setSuccess(true); return response; } catch (Exception e) { logger.error(e.getMessage(), e); JsonResponse response = new JsonResponse(); response.setMessage(e.getMessage()); response.setSuccess(false); return response; } }
From source file:name.persistent.behaviours.RemoteGraphSupport.java
private void store(String type, HttpResponse resp, String... origins) throws Exception { ObjectConnection con = getObjectConnection(); con.addDesignation(this, RemoteGraph.class); String via = getHeader(resp, "Via"); if (via == null) { String url = getResource().stringValue(); String authority = new ParsedURI(url).getAuthority(); setPurlVia(PROTOCOL + " " + authority); } else {//from w ww.j a v a2s .c o m setPurlVia(via); } setPurlContentType(type); setPurlEtag(getHeader(resp, "ETag")); setPurlCacheControl(getHeader(resp, "Cache-Control")); DatatypeFactory df = DatatypeFactory.newInstance(); GregorianCalendar gc = new GregorianCalendar(); setPurlLastValidated(df.newXMLGregorianCalendar(gc)); gc.setTime(getDateHeader(resp, "Last-Modified")); setPurlLastModified(df.newXMLGregorianCalendar(gc)); if (origins != null) { ObjectFactory of = con.getObjectFactory(); for (String origin : origins) { if (origin != null) { Domain o = of.createObject(origin, Domain.class); getPurlAllowedOrigins().add(o); } } } for (Header hd : resp.getHeaders("Warning")) { if (hd.getValue().contains("111")) { // 111 "Revalidation failed" con.addDesignation(this, Unresolvable.class); } } }
From source file:com.handywedge.binarystore.store.azure.BinaryStoreManagerImpl.java
private BinaryInfo createReturnBinaryInfo(CloudBlockBlob blob) throws StoreException { BinaryInfo binary = new BinaryInfo(); try {//ww w .j av a 2 s.com if (blob.exists()) { long milliSeconds = Long.parseLong(PropertiesUtil.get("abs.presignedurl.expiration")); binary.setBucketName(blob.getContainer().getName()); binary.setFileName(blob.getName()); binary.setContentType(blob.getProperties().getContentType()); binary.setSize(blob.getProperties().getLength()); binary.setUrl(blob.getUri().toString()); // Policy SharedAccessBlobPolicy itemPolicy = new SharedAccessBlobPolicy(); GregorianCalendar calendar = new GregorianCalendar(TimeZone.getTimeZone("UTC")); calendar.setTime(new Date()); itemPolicy.setSharedAccessStartTime(calendar.getTime()); calendar.add(Calendar.SECOND, (int) (milliSeconds / 1000)); itemPolicy.setSharedAccessExpiryTime(calendar.getTime()); itemPolicy.setPermissions( EnumSet.of(SharedAccessBlobPermissions.LIST, SharedAccessBlobPermissions.READ)); String sasToken = blob.generateSharedAccessSignature(itemPolicy, null); Thread.sleep(1500); String sasUri = String.format("%s?%s", blob.getUri().toString(), sasToken); binary.setPresignedUrl(sasUri); logger.debug(" ????URL: {}", binary.getUrl()); logger.debug(" ????URL: {}", binary.getPresignedUrl()); } else { binary = null; } } catch (URISyntaxException ue) { throw new StoreException(HttpStatus.SC_INTERNAL_SERVER_ERROR, ErrorClassification.CREATE_BINARY_FAIL, ue, blob.getName()); } catch (NumberFormatException ne) { throw new StoreException(HttpStatus.SC_INTERNAL_SERVER_ERROR, ErrorClassification.CREATE_BINARY_FAIL, ne, blob.getName()); } catch (InvalidKeyException ie) { throw new StoreException(HttpStatus.SC_INTERNAL_SERVER_ERROR, ErrorClassification.CREATE_BINARY_FAIL, ie, blob.getName()); } catch (InterruptedException ite) { throw new StoreException(HttpStatus.SC_INTERNAL_SERVER_ERROR, ErrorClassification.CREATE_BINARY_FAIL, ite, blob.getName()); } catch (StorageException se) { throw new StoreException(HttpStatus.SC_INTERNAL_SERVER_ERROR, ErrorClassification.CREATE_BINARY_FAIL, se, blob.getName()); } return binary; }
From source file:org.opennms.netmgt.provision.persist.requisition.Requisition.java
public void setDate(final Date date) { final GregorianCalendar calendar = new GregorianCalendar(); calendar.setTime(date); try {// w ww . ja va 2 s .c o m setDateStamp(DatatypeFactory.newInstance().newXMLGregorianCalendar(calendar)); } catch (final DatatypeConfigurationException e) { LOG.warn("Failed to turn {} into an XML date.", date); } }
From source file:com.silverpeas.ical.ImportIcalManager.java
/** * IMPORT SilverpeasCalendar in Ical format * @param file/*ww w . j a v a 2s . c om*/ * @return * @throws Exception */ public String importIcalAgenda(File file) throws Exception { SilverTrace.debug("agenda", "ImportIcalManager.importIcalAgenda()", "root.MSG_GEN_ENTER_METHOD"); String returnCode = AgendaSessionController.IMPORT_FAILED; InputStreamReader inputStream = null; XmlReader xr = null; try { String charsetUsed = agendaSessionController.getSettings().getString("defaultCharset"); if (StringUtil.isDefined(charset)) { charsetUsed = charset; } // File Encoding detection xr = new XmlReader(file); SilverTrace.debug("agenda", "ImportIcalManager.importIcalAgenda()", "Encoding = " + xr.getEncoding()); if (StringUtil.isDefined(xr.getEncoding())) { charsetUsed = xr.getEncoding(); } inputStream = new InputStreamReader(new FileInputStream(file), charsetUsed); CalendarBuilder builder = new CalendarBuilder(); Calendar calendar = builder.build(inputStream); // Get all EVENTS for (Object o : calendar.getComponents(Component.VEVENT)) { VEvent eventIcal = (VEvent) o; String name = getFieldEvent(eventIcal.getProperty(Property.SUMMARY)); String description = null; if (StringUtil.isDefined(getFieldEvent(eventIcal.getProperty(Property.DESCRIPTION)))) { description = getFieldEvent(eventIcal.getProperty(Property.DESCRIPTION)); } // Name is mandatory in the Silverpeas Agenda if (!StringUtil.isDefined(name)) { if (StringUtil.isDefined(description)) { name = description; } else { name = " "; } } String priority = getFieldEvent(eventIcal.getProperty(Property.PRIORITY)); if (!StringUtil.isDefined(priority)) { priority = Priority.UNDEFINED.getValue(); } String classification = getFieldEvent(eventIcal.getProperty(Property.CLASS)); String startDate = getFieldEvent(eventIcal.getProperty(Property.DTSTART)); String endDate = getFieldEvent(eventIcal.getProperty(Property.DTEND)); Date startDay = getDay(startDate); String startHour = getHour(startDate); Date endDay = getDay(endDate); String endHour = getHour(endDate); // Duration of the event long duration = endDay.getTime() - startDay.getTime(); boolean allDay = false; // All day case // I don't know why ?? if (("00:00".equals(startHour) && "00:00".equals(endHour)) || (!StringUtil.isDefined(startHour) && !StringUtil.isDefined(endHour))) { // For complete Day startHour = ""; endHour = ""; allDay = true; } // Get reccurrent dates Collection reccurenceDates = getRecurrenceDates(eventIcal); // No reccurent dates if (reccurenceDates == null) { String idEvent = isExist(eventIcal); // update if event already exists, create if does not exist if (StringUtil.isDefined(idEvent)) { agendaSessionController.updateJournal(idEvent, name, description, priority, classification, startDay, startHour, endDay, endHour); } else { idEvent = agendaSessionController.addJournal(name, description, priority, classification, startDay, startHour, endDay, endHour); } // Get Categories processCategories(eventIcal, idEvent); } else { for (Object reccurenceDate : reccurenceDates) { // Reccurent event startDate startDay = (DateTime) reccurenceDate; // Reccurent event endDate long newEndDay = startDay.getTime() + duration; endDay = new DateTime(newEndDay); if (allDay) { // So we have to convert this date to agenda format date GregorianCalendar gregCalendar = new GregorianCalendar(); gregCalendar.setTime(endDay); gregCalendar.add(GregorianCalendar.DATE, -1); endDay = new Date(gregCalendar.getTime()); } String idEvent = isExist(eventIcal, startDay, endDay, startHour); // update if event already exists, create if does not exist if (StringUtil.isDefined(idEvent)) { SilverTrace.debug("agenda", "ImportIcalManager.importIcalAgenda()", "root.MSG_GEN_PARAM_VALUE" + "Update event: " + DateUtil.date2SQLDate(startDay) + " " + startHour + " to " + DateUtil.date2SQLDate(endDay) + " " + endHour); agendaSessionController.updateJournal(idEvent, name, description, priority, classification, startDay, startHour, endDay, endHour); } else { SilverTrace.debug("agenda", "ImportIcalManager.importIcalAgenda()", "root.MSG_GEN_PARAM_VALUE" + "Create event: " + DateUtil.date2SQLDate(startDay) + " " + startHour + " to " + DateUtil.date2SQLDate(endDay) + " " + endHour); idEvent = agendaSessionController.addJournal(name, description, priority, classification, startDay, startHour, endDay, endHour); } // Get Categories processCategories(eventIcal, idEvent); } } } returnCode = AgendaSessionController.IMPORT_SUCCEEDED; } catch (Exception e) { SilverTrace.error("agenda", "ImportIcalManager.importIcalAgenda()", e.getCause().toString()); returnCode = AgendaSessionController.IMPORT_FAILED; } finally { IOUtils.closeQuietly(inputStream); IOUtils.closeQuietly(xr); } SilverTrace.debug("agenda", "ImportIcalManager.importIcalAgenda()", "root.MSG_GEN_EXIT_METHOD"); return returnCode; }