List of usage examples for java.util Calendar DAY_OF_YEAR
int DAY_OF_YEAR
To view the source code for java.util Calendar DAY_OF_YEAR.
Click Source Link
get
and set
indicating the day number within the current year. From source file:org.tsm.concharto.dao.UserTagDaoHib.java
public List<TagCloudEntry> getTagCounts(int daysBack) { //calculate the date of days back Calendar cal = Calendar.getInstance(); Date end = cal.getTime();//from ww w. ja v a 2 s.com cal.add(Calendar.DAY_OF_YEAR, -daysBack); Date start = cal.getTime(); return getTagCounts(new TimeRange(start, end)); }
From source file:eu.cloudscale.showcase.generate.GenerateMongo.java
@Override public void populateOrdersAndCC_XACTSTable() { GregorianCalendar cal;//from www . j a v a 2s .com String[] credit_cards = { "VISA", "MASTERCARD", "DISCOVER", "AMEX", "DINERS" }; int num_card_types = 5; String[] ship_types = { "AIR", "UPS", "FEDEX", "SHIP", "COURIER", "MAIL" }; int num_ship_types = 6; String[] status_types = { "PROCESSING", "SHIPPED", "PENDING", "DENIED" }; int num_status_types = 4; // Order variables int O_C_ID; java.sql.Timestamp O_DATE; double O_SUB_TOTAL; double O_TAX; double O_TOTAL; String O_SHIP_TYPE; java.sql.Timestamp O_SHIP_DATE; int O_BILL_ADDR_ID, O_SHIP_ADDR_ID; String O_STATUS; String CX_TYPE; int CX_NUM; String CX_NAME; java.sql.Date CX_EXPIRY; String CX_AUTH_ID; int CX_CO_ID; System.out.println("Populating ORDERS, ORDER_LINES, CC_XACTS with " + NUM_ORDERS + " orders"); System.out.print("Complete (in 10,000's): "); for (int i = 1; i <= NUM_ORDERS; i++) { if (i % 10000 == 0) System.out.print(i / 10000 + " "); int num_items = getRandomInt(1, 5); O_C_ID = getRandomInt(1, NUM_CUSTOMERS); cal = new GregorianCalendar(); cal.add(Calendar.DAY_OF_YEAR, -1 * getRandomInt(1, 60)); O_DATE = new java.sql.Timestamp(cal.getTime().getTime()); O_SUB_TOTAL = (double) getRandomInt(1000, 999999) / 100; O_TAX = O_SUB_TOTAL * 0.0825; O_TOTAL = O_SUB_TOTAL + O_TAX + 3.00 + num_items; O_SHIP_TYPE = ship_types[getRandomInt(0, num_ship_types - 1)]; cal.add(Calendar.DAY_OF_YEAR, getRandomInt(0, 7)); O_SHIP_DATE = new java.sql.Timestamp(cal.getTime().getTime()); O_BILL_ADDR_ID = getRandomInt(1, 2 * NUM_CUSTOMERS); O_SHIP_ADDR_ID = getRandomInt(1, 2 * NUM_CUSTOMERS); O_STATUS = status_types[getRandomInt(0, num_status_types - 1)]; Orders order = new Orders(); // Set parameter order.setOId(i); order.setCustomer(customerDao.findById(O_C_ID)); order.setODate(new Date(O_DATE.getTime())); order.setOSubTotal(O_SUB_TOTAL); order.setOTax(O_TAX); order.setOTotal(O_TOTAL); order.setOShipType(O_SHIP_TYPE); order.setOShipDate(O_SHIP_DATE); order.setAddressByOBillAddrId(addressDao.findById(O_BILL_ADDR_ID)); order.setAddressByOShipAddrId(addressDao.findById(O_SHIP_ADDR_ID)); order.setOStatus(O_STATUS); order.setCcXactses(new HashSet<ICcXacts>()); order.setOrderLines(new HashSet<IOrderLine>()); for (int j = 1; j <= num_items; j++) { int OL_ID = j; int OL_O_ID = i; int OL_I_ID = getRandomInt(1, NUM_ITEMS); int OL_QTY = getRandomInt(1, 300); double OL_DISCOUNT = (double) getRandomInt(0, 30) / 100; String OL_COMMENTS = getRandomAString(20, 100); OrderLine orderLine = new OrderLine(); orderLine.setOlId(OL_ID); orderLine.setItem(itemDao.findById(OL_I_ID)); orderLine.setOlQty(OL_QTY); orderLine.setOlDiscount(OL_DISCOUNT); orderLine.setOlComment(OL_COMMENTS); orderLine.setOrders(order); orderLineDao.shrani(orderLine); HashSet<IOrderLine> set = new HashSet<IOrderLine>(); set.add(orderLine); set.addAll(order.getOrderLines()); order.setOrderLines(set); ordersDao.shrani(order); } CX_TYPE = credit_cards[getRandomInt(0, num_card_types - 1)]; CX_NUM = getRandomNString(16); CX_NAME = getRandomAString(14, 30); cal = new GregorianCalendar(); cal.add(Calendar.DAY_OF_YEAR, getRandomInt(10, 730)); CX_EXPIRY = new java.sql.Date(cal.getTime().getTime()); CX_AUTH_ID = getRandomAString(15); CX_CO_ID = getRandomInt(1, 92); CcXacts ccXacts = new CcXacts(); ccXacts.setId(i); ccXacts.setCountry(countryDao.findById(CX_CO_ID)); ccXacts.setCxType(CX_TYPE); ccXacts.setCxNum(CX_NUM); ccXacts.setCxName(CX_NAME); ccXacts.setCxExpiry(CX_EXPIRY); ccXacts.setCxAuthId(CX_AUTH_ID); ccXacts.setCxXactAmt(O_TOTAL); ccXacts.setCxXactDate(O_SHIP_DATE); ccXacts.setOrders(order); ccXactsDao.shrani(ccXacts); HashSet<ICcXacts> set = new HashSet<ICcXacts>(); set.add(ccXacts); set.addAll(order.getCcXactses()); order.setCcXactses(set); ordersDao.shrani(order); } System.out.println(""); }
From source file:ch.silviowangler.dox.LoadIntegrationTest.java
@Before public void setUp() throws Exception { loginAsTestRoot();// www .ja va2 s. c o m Calendar calendar = new GregorianCalendar(2013, Calendar.JANUARY, 1); Map<String, SortedSet<Attribute>> cache = new HashMap<>(); for (int i = 1; i <= TOTAL_AMOUNT_OF_FILES; i++) { Map<TranslatableKey, DescriptiveIndex> indices = new HashMap<>(); SortedSet<Attribute> attributes; if (!cache.containsKey("INVOICE")) { attributes = documentService.findAttributes(new DocumentClass("INVOICE")); cache.put("INVOICE", attributes); } else { attributes = cache.get("INVOICE"); } for (Attribute attribute : attributes) { if (!attribute.isOptional()) { Object o; switch (attribute.getDataType()) { case SHORT: case LONG: case DOUBLE: case STRING: case INTEGER: o = Integer.toString(i); break; case BOOLEAN: o = (i % 2 == 0); break; case DATE: calendar.add(Calendar.DAY_OF_YEAR, 1); o = calendar.getTime(); break; case CURRENCY: o = "CHF " + i; break; default: throw new IllegalArgumentException("Unknown attribute type: " + attribute.getDataType()); } indices.put(new TranslatableKey(attribute.getShortName()), new DescriptiveIndex(o)); } } importFile(i + ".txt", Integer.toString(i), "INVOICE", indices); } loginAsTestRoot(); }
From source file:gov.nasa.arc.spife.ui.table.days.Day.java
private static TemporalExtent computeDayExtent(Date start) { Date end;/* ww w. ja v a 2s . com*/ synchronized (CALENDAR) { CALENDAR.setTime(start); CALENDAR.add(Calendar.DAY_OF_YEAR, 1); CALENDAR.add(Calendar.MILLISECOND, -1); end = CALENDAR.getTime(); } return new TemporalExtent(start, end); }
From source file:com.gatf.executor.core.GatfFunctionHandler.java
public static String handleFunction(String function) { if (function.equals(BOOLEAN)) { Random rand = new Random(); return String.valueOf(rand.nextBoolean()); } else if (function.matches(DT_FMT_REGEX)) { Matcher match = datePattern.matcher(function); match.matches();/* w ww .j a v a 2s.c o m*/ SimpleDateFormat format = new SimpleDateFormat(match.group(1)); return format.format(new Date()); } else if (function.matches(DT_FUNC_FMT_REGEX)) { Matcher match = specialDatePattern.matcher(function); match.matches(); String formatStr = match.group(1); String operation = match.group(2); int value = Integer.valueOf(match.group(3)); String unit = match.group(4); SimpleDateFormat format = new SimpleDateFormat(formatStr); try { Date dt = format.parse(format.format(new Date())); Calendar cal = Calendar.getInstance(); cal.setTime(dt); value = (operation.equals(MINUS) ? -value : value); if (unit.equals(YEAR)) { cal.add(Calendar.YEAR, value); } else if (unit.equals(MONTH)) { cal.add(Calendar.MONTH, value); } else if (unit.equals(DAY)) { cal.add(Calendar.DAY_OF_YEAR, value); } else if (unit.equals(HOUR)) { cal.add(Calendar.HOUR_OF_DAY, value); } else if (unit.equals(MINUITE)) { cal.add(Calendar.MINUTE, value); } else if (unit.equals(SECOND)) { cal.add(Calendar.SECOND, value); } else if (unit.equals(MILLISECOND)) { cal.add(Calendar.MILLISECOND, value); } return format.format(cal.getTime()); } catch (Exception e) { throw new AssertionError("Invalid date format specified - " + formatStr); } } else if (function.equals(FLOAT)) { Random rand = new Random(12345678L); return String.valueOf(rand.nextFloat()); } else if (function.equals(ALPHA)) { return RandomStringUtils.randomAlphabetic(10); } else if (function.equals(ALPHANUM)) { return RandomStringUtils.randomAlphanumeric(10); } else if (function.equals(NUMBER_PLUS)) { Random rand = new Random(); return String.valueOf(rand.nextInt(1234567)); } else if (function.equals(NUMBER_MINUS)) { Random rand = new Random(); return String.valueOf(-rand.nextInt(1234567)); } else if (function.equals(NUMBER)) { Random rand = new Random(); boolean bool = rand.nextBoolean(); return bool ? String.valueOf(rand.nextInt(1234567)) : String.valueOf(-rand.nextInt(1234567)); } else if (function.matches(RANDOM_RANGE_REGEX)) { Matcher match = randRangeNum.matcher(function); match.matches(); String min = match.group(1); String max = match.group(2); try { int nmin = Integer.parseInt(min); int nmax = Integer.parseInt(max); return String.valueOf(nmin + (int) (Math.random() * ((nmax - nmin) + 1))); } catch (Exception e) { e.printStackTrace(); } } return null; }
From source file:nz.net.orcon.kanban.tools.DateInterpreterTest.java
@Test public void testConversion_futureDate() throws Exception { final Calendar calFutureDate = Calendar.getInstance(); calFutureDate.add(Calendar.DAY_OF_YEAR, 4); int dayOfMonth = calFutureDate.get(Calendar.DAY_OF_MONTH); int month = calFutureDate.get(Calendar.MONTH); int year = calFutureDate.get(Calendar.YEAR); final Date interpretDate = dateInterpreter.interpretDateFormula("today+4days"); Calendar calInterpreted = Calendar.getInstance(); calInterpreted.setTime(interpretDate); Assert.assertEquals(dayOfMonth, calInterpreted.get(Calendar.DAY_OF_MONTH)); Assert.assertEquals(month, calInterpreted.get(Calendar.MONTH)); Assert.assertEquals(year, calInterpreted.get(Calendar.YEAR)); }
From source file:jerry.c2c.action.UploadProductAction.java
public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { String target = "result"; String resultPageTitle = "error"; String msgTitle = "error"; String msgContent = "error"; NewProductForm productForm = (NewProductForm) form; HttpSession session = request.getSession(); Item item = new Item(); try {//from w ww.j a v a2s . com BeanUtils.copyProperties(item, productForm); item.setCreateTime(DateTimeUtil.getCurrentTimestamp()); Timestamp createTime = DateTimeUtil.getCurrentTimestamp(); Calendar calendar = Calendar.getInstance(); calendar.add(Calendar.DAY_OF_YEAR, productForm.getDays()); Timestamp endTime = new Timestamp(calendar.getTimeInMillis()); item.setBelongTo((Shop) session.getAttribute("user_shop")); item.setCreateTime(createTime); item.setEndTime(endTime); Category category = categoryService.getById(productForm.getCategoryId()); item.setCategory(category); itemService.save(item); this.handleUploadImage(productForm.getImageFile(), item.getBelongTo().getName(), item.getId()); resultPageTitle = "??"; msgTitle = "??"; msgContent = "?(" + item.getName() + ")?"; } catch (IllegalAccessException e) { itemService.delete(item); resultPageTitle = "?"; msgTitle = "?"; msgContent = "?,?:" + e.getMessage(); } catch (InvocationTargetException e) { itemService.delete(item); resultPageTitle = "?"; msgTitle = "?"; msgContent = "?,?:" + e.getMessage(); } catch (IOException e) { itemService.delete(item); e.printStackTrace(); resultPageTitle = "?"; msgTitle = "?"; msgContent = "?,?:" + e.getMessage(); } catch (BusinessException e) { itemService.delete(item); e.printStackTrace(); resultPageTitle = "?"; msgTitle = "?"; msgContent = "?,?:" + e.getMessage(); } finally { request.setAttribute("title", resultPageTitle); request.setAttribute("message_title", msgTitle); request.setAttribute("message_content", msgContent); } return mapping.findForward(target); }
From source file:io.omatic.event.service.EventMaintainanceService.java
/** * Maintenance method used to keep the number of {@link Event} records in the database * at a manageable level. /*from www . j a v a 2 s . co m*/ * * Note that this method can be scheduled. To do so specify a value for the externalised * property eventomatic.maintenance.cronSchedule. The value must be in crontab format. For more information see * <a href="http://docs.spring.io/spring/docs/current/javadoc-api/org/springframework/scheduling/support/CronSequenceGenerator.html">here</a> */ @Transactional @Scheduled(cron = "${eventomatic.maintenance.cronSchedule}") public void maintainPoll() { // Firstly delete any events that are older than they should be, this will stop historic data clogging up the system. 0 disable if (applicationConfiguration.getMaintenance().getMaxAge() < 0) { Calendar cal = Calendar.getInstance(); cal.add(Calendar.DAY_OF_YEAR, applicationConfiguration.getMaintenance().getMaxAge().intValue()); Date maxAge = cal.getTime(); long countOldEvents = eventRepository.countByRecievedDateBefore(maxAge); log.info("Checking for mesages older than {} and found {}", maxAge, countOldEvents); if (countOldEvents > 0) { log.info("Deleting {} events from before {}", countOldEvents, maxAge); eventRepository.deleteByRecievedDateBefore(maxAge); log.info("Deletion complete"); } } else { log.info("Age based housekeeping disabled"); } // Secondly, if the max events has exceeded the specified limit then trim the database. 0 or -1 will disable. if (applicationConfiguration.getMaintenance().getEventLimit() > 0) { long countTotalEvents = eventRepository.count(); Long overrun = countTotalEvents - applicationConfiguration.getMaintenance().getEventLimit(); log.info("Checking for event count of greather than {} and found {}", applicationConfiguration.getMaintenance().getEventLimit(), countTotalEvents); if (overrun > 0) { Page<Event> events = eventRepository .findAll(new PageRequest(0, overrun.intValue(), new Sort(Direction.ASC, "recievedDate"))); eventRepository.deleteInBatch(events); log.info("Deleted {} of {} events.", overrun, countTotalEvents); } } else { log.info("Event limit based housekeeping disabled"); } }
From source file:com.criticalblue.android.astropiks.PhotoRequester.java
/** * Requests a photo.// w w w . j a v a 2 s. c o m * * @throws IOException if all else fails. */ public void getPhoto() throws IOException { // grab the current calendar date and back up one day for next request final String date = mDateFormat.format(mCalendar.getTime()); mCalendar.add(Calendar.DAY_OF_YEAR, -1); // build and call the request String urlRequest = mContext.getString(R.string.api_url) + BASE_PATH + DATE_PARAMETER + date; final Request request = new Request.Builder().url(urlRequest).build(); mLoadingData = true; mClient.newCall(request).enqueue(new Callback() { @Override public void onFailure(Call call, IOException e) { // network failure Log.e("PhotoRequester", "network failure " + e.toString()); Photo photo = new Photo(); photo.setUrl(null); photo.setTitle("Network Failure"); photo.setDesc("Unable to complete network request."); photo.setDate(null); mResponseListener.receivedPhoto(photo); mLoadingData = false; } @Override public void onResponse(Call call, Response response) throws IOException { // network response if (response.code() == 500) { // skip this poto and try again getPhoto(); } else if (response.code() != 200) { // unsuccessful response Photo photo = new Photo(); photo.setUrl(null); photo.setTitle("Unauthorized"); photo.setDesc("You are not authorized to access this information."); photo.setDate(null); mResponseListener.receivedPhoto(photo); mLoadingData = false; return; } try { JSONObject photoJSON = new JSONObject(response.body().string()); if (photoJSON.has("error")) { // bad photo data, likely a rate limit error Photo photo = new Photo(); String code = photoJSON.getJSONObject("error").getString("code"); String msg = photoJSON.getJSONObject("error").getString("message"); photo.setUrl(null); photo.setTitle(code); photo.setDesc(msg); photo.setDate(null); mResponseListener.receivedPhoto(photo); mLoadingData = false; } else if (!photoJSON.getString(MEDIA_TYPE_KEY).equals(MEDIA_TYPE_VIDEO_VALUE)) { // is an image, grab it Photo photo = new Photo(); String url = null; String title = null; String desc = null; String date = null; try { url = photoJSON.getString("url"); title = photoJSON.getString("title"); desc = photoJSON.getString("explanation"); date = photoJSON.getString("date"); } catch (JSONException e) { } SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd"); Date day = null; try { day = dateFormat.parse(date); } catch (ParseException e) { e.printStackTrace(); } photo.setUrl(url); photo.setTitle(title); photo.setDesc(desc); photo.setDate(day); mResponseListener.receivedPhoto(photo); mLoadingData = false; } else { // probably a video, try again getPhoto(); } } catch (JSONException e) { // response body not expected JSON Photo photo = new Photo(); photo.setUrl(null); photo.setTitle("Invalid Photo"); photo.setDesc("Unexpected error when requesting photo."); photo.setDate(null); mResponseListener.receivedPhoto(photo); mLoadingData = false; } } }); }
From source file:edu.wisc.my.stats.web.filter.RelativeDateQueryFilter.java
/** * @see javax.servlet.Filter#doFilter(javax.servlet.ServletRequest, javax.servlet.ServletResponse, javax.servlet.FilterChain) *///from w ww. j av a 2 s .co m public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { if (!(request instanceof HttpServletRequest)) { throw new ClassCastException("RelativeDateQueryFilter can only filter HttpServletRequests"); } boolean useWrapper = false; final WritableHttpServletRequestWrapper wrappedRequestWrapper = new WritableHttpServletRequestWrapper( (HttpServletRequest) request); for (final String dateParameter : this.dateParameters) { final String value = request.getParameter(dateParameter); if (StringUtils.isBlank(value)) { continue; } try { final int dayOffset = Integer.parseInt(value); final Calendar now = Calendar.getInstance(); now.add(Calendar.DAY_OF_YEAR, -1 * dayOffset); final String newValue = this.dateFormat.format(now.getTime()); useWrapper = true; wrappedRequestWrapper.putParameter(dateParameter, newValue); } catch (NumberFormatException nfe) { //Isn't a single number, assume it is a valid Date and just ignore it. } } if (useWrapper) { chain.doFilter(wrappedRequestWrapper, response); } else { chain.doFilter(request, response); } }