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:de.tbuchloh.kiskis.persistence.importer.CSVImport.java
private ModelNode createAccount(final CSVEntry entry) { final NetAccount na = new NetAccount(); String name = entry.get(LABEL); if (StringTools.isBlank(name)) { name = "<unknown>"; }/*from ww w . java2 s . c o m*/ na.setName(name); String password = entry.get(PWD); if (StringTools.isBlank(password)) { password = ""; } final Calendar creaDate = DateUtils.getCurrentDateTime(); final String created = entry.get(CREATED); if (!StringTools.isBlank(created)) { try { creaDate.setTime(ModelConstants.SHORT.parse(created)); } catch (final ParseException e) { _msgListener.showMessage(ERR_PARSE_DATE.format(new Object[] { created })); } } final String expires = entry.get(EXPIRATION); final Calendar expDate = DateUtils.getCurrentDateTime(); if (!StringTools.isBlank(expires)) { try { expDate.setTime(ModelConstants.SHORT.parse(expires)); } catch (final ParseException e) { expDate.add(Calendar.DAY_OF_YEAR, Settings.getDefaultPwdExpiryDays()); na.setExpiresNever(true); _msgListener.showMessage(ERR_PARSE_DATE.format(new Object[] { expires })); } } else { expDate.add(Calendar.DAY_OF_YEAR, Settings.getDefaultPwdExpiryDays()); na.setExpiresNever(true); } na.setCreationDate(creaDate); final Password pwd = new Password(password.toCharArray(), expDate, creaDate); na.setPwd(pwd); final String userName = entry.get(USERNAME); na.setUsername(userName == null ? "" : userName); final String email = entry.get(EMAIL); na.setEmail(email == null ? "" : email); final String url = entry.get(URL); na.setUrl(url == null ? "" : url); final String commentField = entry.get(COMMENT); final StringBuilder comment = new StringBuilder(commentField == null ? "" : commentField); if (comment.length() > 0) { comment.append('\n'); } comment.append(MSG_IMPORTED_ON.format(new Object[] { DateUtils.getCurrentDateTime().getTime() })); na.setComment(comment.toString()); LOG.debug("Created account: " + na); return na; }
From source file:net.solarnetwork.node.weather.nz.metservice.MetserviceDayDatumDataSource.java
@Override public GeneralLocationDatum readCurrentDatum() { // first see if we have cached data GeneralDayDatum result = getDatumCache().get(LAST_DATUM_CACHE_KEY); if (result != null) { Calendar now = Calendar.getInstance(); Calendar datumCal = Calendar.getInstance(); datumCal.setTime(result.getCreated()); if (now.get(Calendar.YEAR) == datumCal.get(Calendar.YEAR) && now.get(Calendar.DAY_OF_YEAR) == datumCal.get(Calendar.DAY_OF_YEAR)) { // cached data is for same date, so return that return result; }// w w w . j a v a 2s. com // invalid cached data, remove now getDatumCache().remove(LAST_DATUM_CACHE_KEY); } final String url = getBaseUrl() + '/' + riseSet; final SimpleDateFormat timeFormat = new SimpleDateFormat(getTimeDateFormat()); final SimpleDateFormat dayFormat = new SimpleDateFormat(getDayDateFormat()); try { URLConnection conn = getURLConnection(url, HTTP_METHOD_GET); JsonNode data = getObjectMapper().readTree(getInputStreamFromURLConnection(conn)); Date day = parseDateAttribute("day", data, dayFormat); Date sunrise = parseDateAttribute("sunRise", data, timeFormat); Date sunset = parseDateAttribute("sunSet", data, timeFormat); if (day != null && sunrise != null && sunset != null) { result = new GeneralDayDatum(); result.setCreated(day); result.setSunrise(new LocalTime(sunrise)); result.setSunset(new LocalTime(sunset)); log.debug("Obtained new DayDatum: {}", result); getDatumCache().put(LAST_DATUM_CACHE_KEY, result); } } catch (IOException e) { log.warn("Error reading MetService URL [{}]: {}", url, e.getMessage()); } return result; }
From source file:Statement.Statement.java
private void loadExpense() { SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd"); Calendar calendar = Calendar.getInstance(); calendar.add(Calendar.DAY_OF_YEAR, 1); Date tomorrow = calendar.getTime(); dateFormat.format(tomorrow);// w w w. ja va 2s.c o m evaluator = new HighlightEvaluator(); evaluator.setStartDate(tomorrow); try { PreparedStatement st = cnn.prepareStatement("SELECT Date FROM Expense where ShopID = ?"); st.setString(1, code); ResultSet rs = st.executeQuery(); while (rs.next()) { evaluator.add(rs.getDate(1)); } } catch (Exception e) { } jc.getDayChooser().addDateEvaluator(evaluator); jc.setCalendar(jc.getCalendar()); }
From source file:org.gots.weather.provider.google.GoogleWeatherTask.java
@Override protected WeatherConditionInterface doInBackground(Object... arg0) { if (force || ws == null) { try {//from w w w . ja v a 2 s . c o m // android.os.Debug.waitForDebugger(); /*************/ HttpClient httpclient = new DefaultHttpClient(); HttpGet httpget = new HttpGet(url.toURI()); // create a response handler ResponseHandler<String> responseHandler = new BasicResponseHandler(); String responseBody = httpclient.execute(httpget, responseHandler); // Log.d(DEBUG_TAG, "response from httpclient:n "+responseBody); ByteArrayInputStream is = new ByteArrayInputStream(responseBody.getBytes()); /* Get a SAXParser from the SAXPArserFactory. */ SAXParserFactory spf = SAXParserFactory.newInstance(); SAXParser sp = spf.newSAXParser(); /* Get the XMLReader of the SAXParser we created. */ XMLReader xr = sp.getXMLReader(); /* Create a new ContentHandler and apply it to the XML-Reader */ GoogleWeatherHandler gwh = new GoogleWeatherHandler(); xr.setContentHandler(gwh); // InputSource is = new InputSource(url.openStream()); /* Parse the xml-data our URL-call returned. */ xr.parse(new InputSource(is)); /* Our Handler now provides the parsed weather-data to us. */ ws = gwh.getWeatherSet(); } catch (Exception e) { Log.e("WeatherManager", "WeatherQueryError", e); } force = false; } Calendar requestCalendar = Calendar.getInstance(); requestCalendar.setTime(requestedDay); if (ws == null) return new WeatherCondition(requestedDay); else if (requestCalendar.get(Calendar.DAY_OF_YEAR) == Calendar.getInstance().get(Calendar.DAY_OF_YEAR)) return ws.getWeatherCurrentCondition(); else if (requestCalendar.get(Calendar.DAY_OF_YEAR) > Calendar.getInstance().get(Calendar.DAY_OF_YEAR)) return ws.getWeatherForecastConditions().get( requestCalendar.get(Calendar.DAY_OF_YEAR) - Calendar.getInstance().get(Calendar.DAY_OF_YEAR)); return new WeatherCondition(requestedDay); }
From source file:it.infn.ct.security.utilities.LDAPCleaner.java
private void followingChecks(int days) { _log.info("Check users who have not extended yet"); Calendar cal = GregorianCalendar.getInstance(); cal.add(Calendar.DAY_OF_YEAR, days); cal.set(Calendar.HOUR_OF_DAY, 0); cal.set(Calendar.MINUTE, 0);//from www. j a va 2 s . com cal.set(Calendar.SECOND, 0); cal.set(Calendar.MILLISECOND, 0); Calendar calEnd = GregorianCalendar.getInstance(); calEnd.setTime(cal.getTime()); calEnd.add(Calendar.DAY_OF_YEAR, 1); Session ses = factory.openSession(); List lstUserUpdates = ses.createCriteria(UserConfirmUpdate.class) .add(Restrictions.between("timelimit", cal.getTime(), calEnd.getTime())) .add(Restrictions.eq("updated", Boolean.FALSE)).list(); for (UserConfirmUpdate ucu : (List<UserConfirmUpdate>) lstUserUpdates) { UserRequest ur = LDAPUtils.getUser(ucu.getUsername()); sendUserRemainder(ur, days); } ses.close(); }
From source file:com.netflix.simianarmy.resources.sniper.SniperMonkeyResource.java
/** * Gets the sniper events. Creates GET /api/v1/sniper api which outputs the sniper events in json. Users can specify * cgi query params to filter the results and use "since" query param to set the start of a timerange. "since" will * number of milliseconds since the epoch. * * @param uriInfo/*from www. j av a 2s .c o m*/ * the uri info * @return the sniper events json response * @throws IOException * Signals that an I/O exception has occurred. */ @GET public Response getSniperEvents(@Context UriInfo uriInfo) throws IOException { Map<String, String> query = new HashMap<String, String>(); Date date = null; for (Map.Entry<String, List<String>> pair : uriInfo.getQueryParameters().entrySet()) { if (pair.getValue().isEmpty()) { continue; } if (pair.getKey().equals("since")) { date = new Date(Long.parseLong(pair.getValue().get(0))); } else { query.put(pair.getKey(), pair.getValue().get(0)); } } // if "since" not set, default to 24 hours ago if (date == null) { Calendar now = monkey.context().calendar().now(); now.add(Calendar.DAY_OF_YEAR, -1); date = now.getTime(); } List<Event> evts = monkey.context().recorder().findEvents(SniperMonkey.Type.SNIPER, SniperMonkey.EventTypes.SNIPER_TERMINATION, query, date); ByteArrayOutputStream baos = new ByteArrayOutputStream(); JsonGenerator gen = JSON_FACTORY.createJsonGenerator(baos, JsonEncoding.UTF8); gen.writeStartArray(); for (Event evt : evts) { gen.writeStartObject(); gen.writeStringField("monkeyType", evt.monkeyType().name()); gen.writeStringField("eventType", evt.eventType().name()); gen.writeNumberField("eventTime", evt.eventTime().getTime()); gen.writeStringField("region", evt.region()); for (Map.Entry<String, String> pair : evt.fields().entrySet()) { gen.writeStringField(pair.getKey(), pair.getValue()); } gen.writeEndObject(); } gen.writeEndArray(); gen.close(); return Response.status(Response.Status.OK).entity(baos.toString("UTF-8")).build(); }
From source file:com.adaptris.core.LogHandlerTest.java
public static List<Long> createLogFiles(File dir, String prefix, int count) throws Exception { ensureDirectory(dir);// w ww. j av a 2 s. c om ArrayList<Long> ages = new ArrayList<Long>(); // Shoudld give us files ranging from 9 days in the past to 1hour in the // past. for (int i = count - 1; i >= 0; i--) { Calendar c = Calendar.getInstance(); c.add(Calendar.DAY_OF_YEAR, 0 - i); c.add(Calendar.MINUTE, -1); ages.add(c.getTimeInMillis()); } for (Long age : ages) { File f = File.createTempFile(prefix, null, dir); f.setLastModified(age); } return ages; }
From source file:edu.eci.pdsw.samples.managedbeans.PagosBean.java
public void aprobar() { try {/* w w w .j a va 2s . c om*/ Servicios.getInstance(base).validarPago(pagoselec.getId_pago()); } catch (PersistenceException ex) { FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_INFO, ex.getMessage(), null)); } Date fecha = new java.sql.Date(java.util.Calendar.getInstance().getTime().getTime()); Calendar calendar = Calendar.getInstance(); calendar.setTime(fecha); calendar.add(Calendar.DAY_OF_YEAR, 183); Date fecha2 = new java.sql.Date(calendar.getTime().getTime()); try { Servicios.getInstance(base).validarUsuario(pagoselec.getUsuario_nombre(), fecha2); } catch (PersistenceException ex) { FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_INFO, ex.getMessage(), null)); } }
From source file:jdchub.module.commands.handlers.BanCommand.java
@Override public String execute(String cmd, String args, AbstractClient commandOwner) { banExpiresDate = new Date(); this.commandOwner = commandOwner; this.nick = null; this.reason = null; LongOpt[] longOpts = new LongOpt[5]; longOpts[0] = new LongOpt("nick", LongOpt.REQUIRED_ARGUMENT, null, 'n'); longOpts[1] = new LongOpt("reason", LongOpt.REQUIRED_ARGUMENT, null, 'r'); longOpts[2] = new LongOpt("time", LongOpt.REQUIRED_ARGUMENT, null, 't'); longOpts[3] = new LongOpt("ip", LongOpt.REQUIRED_ARGUMENT, null, 'i'); longOpts[4] = new LongOpt("mask", LongOpt.REQUIRED_ARGUMENT, null, 'm'); String[] argArray = CommandUtils.strArgToArray(args); Getopt getopt = new Getopt(cmd, argArray, "n:r:t:i:m:", longOpts); if (argArray.length < 1) { showHelp();//from w w w.j a v a 2 s .co m return null; } int c; while ((c = getopt.getopt()) != -1) { switch (c) { case 'n': this.nick = getopt.getOptarg(); break; case 'r': this.reason = getopt.getOptarg(); break; case 'i': this.ip = getopt.getOptarg(); break; case 'm': this.mask = getopt.getOptarg(); break; case 't': // Valid entries for <time> are Ns, Nm, Nh, Nd, Nw, NM, Ny String timeString = getopt.getOptarg(); int timeType = timeString.charAt(timeString.length() - 1); int time; try { time = Integer.parseInt(timeString.substring(0, timeString.length() - 1)); if (time <= 0) { throw new NumberFormatException("Invalid time format : time must be greater than 0"); } } catch (NumberFormatException ex) { showError("Invalid time format."); return "Invalid expires time."; } Calendar calendar = new GregorianCalendar(); calendar.setTime(banExpiresDate); switch (timeType) { case 's': timeType = Calendar.SECOND; break; case 'm': timeType = Calendar.MINUTE; break; case 'h': timeType = Calendar.HOUR; break; case 'd': timeType = Calendar.DAY_OF_YEAR; break; case 'w': timeType = Calendar.WEEK_OF_YEAR; break; case 'M': timeType = Calendar.MONTH; break; case 'Y': timeType = Calendar.YEAR; break; default: showError("Invalid time format."); } calendar.add(timeType, time); this.banExpiresDate = calendar.getTime(); this.banType = Constants.BAN_TEMPORARY; break; case '?': showHelp(); break; default: showHelp(); break; } } return ban(); }
From source file:net.sourceforge.fenixedu.presentationTier.TagLib.sop.examsMapNew.renderers.ExamsMapContentRenderer.java
@Override public StringBuilder renderDayLabel(ExamsMapSlot examsMapSlot, ExamsMap examsMap, String typeUser, PageContext pageContext) {//from w w w . j a va2 s.c om this.examsMap = examsMap; StringBuilder strBuffer = new StringBuilder(); boolean isFirstDayOfSeason = ((examsMapSlot.getDay().get(Calendar.DAY_OF_MONTH) == examsMap .getFirstDayOfSeason().get(Calendar.DAY_OF_MONTH)) && (examsMapSlot.getDay().get(Calendar.MONTH) == examsMap.getFirstDayOfSeason().get(Calendar.MONTH)) && (examsMapSlot.getDay().get(Calendar.YEAR) == examsMap.getFirstDayOfSeason().get(Calendar.YEAR))); boolean isSecondDayOfMonthAndFirstDayWasASunday = (examsMapSlot.getDay().get(Calendar.DAY_OF_MONTH) == 2 && examsMapSlot.getDay().get(Calendar.DAY_OF_WEEK) == 2); if (examsMap.getInfoExecutionDegree() != null && typeUser.equals("sop")) { strBuffer.append("<a href='showExamsManagement.do?method=createByDay" + "&" + PresentationConstants.EXECUTION_DEGREE_OID + "=" + examsMap.getInfoExecutionDegree().getExternalId() + "&" + PresentationConstants.EXECUTION_PERIOD_OID + "=" + examsMap.getInfoExecutionPeriod().getExternalId() + "&" + PresentationConstants.CURRICULAR_YEAR_OID + "=" + examsMap.getCurricularYears().iterator().next() + "&" + PresentationConstants.DAY + "=" + examsMapSlot.getDay().get(Calendar.DAY_OF_MONTH) + "&" + PresentationConstants.MONTH + "=" + (examsMapSlot.getDay().get(Calendar.MONTH) + 1) + "&" + PresentationConstants.YEAR + "=" + examsMapSlot.getDay().get(Calendar.YEAR) + "'>"); } strBuffer.append(examsMapSlot.getDay().get(Calendar.DAY_OF_MONTH)); if ((examsMapSlot.getDay().get(Calendar.DAY_OF_MONTH) == 1) || isFirstDayOfSeason || isSecondDayOfMonthAndFirstDayWasASunday) { strBuffer.append(" "); strBuffer.append(getMessageResource(pageContext, "public.degree.information.label.of")); strBuffer.append(" "); Locale locale = pageContext.getRequest().getLocale(); strBuffer.append(monthToString(examsMapSlot.getDay().get(Calendar.MONTH), locale)); } if (examsMapSlot.getDay().get(Calendar.DAY_OF_YEAR) == 1) { strBuffer.append(getMessageResource(pageContext, "public.degree.information.label.comma")); strBuffer.append(examsMapSlot.getDay().get(Calendar.YEAR)); } if (examsMap.getInfoExecutionDegree() != null && typeUser.equals("sop")) { strBuffer.append("</a>"); } strBuffer.append("<br />"); return strBuffer; }