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:com.drc.wiktionary.ExtendedWikiHelper.java
/** * Get the WOTD for a random date. Note there are only 365 possible * responses for any given day. Random future dates wrap back to the * //from w ww .j av a 2 s. co m * @return Random dictionary word, or null if no valid word was found. * @throws ApiException * If any connection or server error occurs. * @throws ParseException * If there are problems parsing the response. */ public static String getRandomWord(Context context) throws ApiException, ParseException { Resources res = context.getResources(); String[] monthNames = res.getStringArray(R.array.month_names); // Keep trying a few times until we find a valid word int tries = 0; while (tries++ < RANDOM_TRIES) { // pick random day of year, 1-365 int rDoy = RANDOM.nextInt(364) + 1; Calendar c = Calendar.getInstance(); // set cal's day of year to random day of year // the corresponding random month and day of month // are used below to build the page title c.set(Calendar.DAY_OF_YEAR, rDoy); // random month, day, year String rMonth = monthNames[c.get(Calendar.MONTH)]; int rDay = c.get(Calendar.DAY_OF_MONTH); int rYear = c.get(Calendar.YEAR) - RANDOM.nextInt(4); // Build the page title for the archive month, year String pageName = res.getString(R.string.template_wotd_archive_title, rYear, rMonth); String pageContent = null; try { // query for the archive page // archive page contains all words for that year / month SimpleWikiHelper.prepareUserAgent(context); pageContent = SimpleWikiHelper.getPageContent(pageName, false); } catch (ApiException e) { Log.e("WordWidget", "Couldn't contact API", e); } catch (ParseException e) { Log.e("WordWidget", "Couldn't parse API response", e); } Matcher matcher = null; if (pageContent != null) { matcher = Pattern.compile(WordWidget.WOTD_PATTERN).matcher(pageContent); } if (matcher != null) { // iterate to randomly selected day for (int i = 0; i < rDay && matcher.find(); i++) { if (i != rDay - 1) { continue; } String foundWord = matcher.group(1); if (foundWord != null && !sInvalidWord.matcher(foundWord).find()) { return foundWord; } } } } // No valid word found in number of tries, so return null return null; }
From source file:TripServlet.java
public Date getLastYear() { Calendar c = Calendar.getInstance(); c = (Calendar) c.clone();/* w w w . j a v a 2s. c o m*/ c.add(Calendar.YEAR, -1);// last month c.set(Calendar.DAY_OF_YEAR, c.getFirstDayOfWeek()); Date date = c.getTime(); return date; }
From source file:com.cws.esolutions.security.dao.certmgmt.impl.CertificateManagerImpl.java
/** * @see com.cws.esolutions.security.dao.certmgmt.interfaces.ICertificateManager#createCertificateRequest(List, String, int, int) *//*from w w w. ja v a2 s . c o m*/ public synchronized File createCertificateRequest(final List<String> subjectData, final String storePassword, final int validityPeriod, final int keySize) throws CertificateManagementException { final String methodName = ICertificateManager.CNAME + "#createCertificateRequest(final List<String> subjectData, final String storePassword, final int validityPeriod, final int keySize) throws CertificateManagementException"; if (DEBUG) { DEBUGGER.debug(methodName); DEBUGGER.debug("Value: {}", subjectData); DEBUGGER.debug("Value: {}", validityPeriod); DEBUGGER.debug("Value: {}", keySize); } final File rootDirectory = certConfig.getRootDirectory(); final String signatureAlgorithm = certConfig.getSignatureAlgorithm(); final String certificateAlgorithm = certConfig.getCertificateAlgorithm(); final File privateKeyDirectory = FileUtils .getFile(certConfig.getPrivateKeyDirectory() + "/" + subjectData.get(0)); final File publicKeyDirectory = FileUtils .getFile(certConfig.getPublicKeyDirectory() + "/" + subjectData.get(0)); final File csrDirectory = FileUtils.getFile(certConfig.getCsrDirectory() + "/" + subjectData.get(0)); final File storeDirectory = FileUtils.getFile(certConfig.getStoreDirectory() + "/" + subjectData.get(0)); final X500Name x500Name = new X500Name("CN=" + subjectData.get(0) + ",OU=" + subjectData.get(1) + ",O=" + subjectData.get(2) + ",L=" + subjectData.get(3) + ",ST=" + subjectData.get(4) + ",C=" + subjectData.get(5) + ",E=" + subjectData.get(6)); if (DEBUG) { DEBUGGER.debug("rootDirectory: {}", rootDirectory); DEBUGGER.debug("signatureAlgorithm: {}", signatureAlgorithm); DEBUGGER.debug("certificateAlgorithm: {}", certificateAlgorithm); DEBUGGER.debug("privateKeyDirectory: {}", privateKeyDirectory); DEBUGGER.debug("publicKeyDirectory: {}", publicKeyDirectory); DEBUGGER.debug("csrDirectory: {}", csrDirectory); DEBUGGER.debug("storeDirectory: {}", storeDirectory); DEBUGGER.debug("x500Name: {}", x500Name); } File csrFile = null; JcaPEMWriter csrPemWriter = null; JcaPEMWriter publicKeyWriter = null; JcaPEMWriter privateKeyWriter = null; FileOutputStream csrFileStream = null; FileOutputStream keyStoreStream = null; FileOutputStream publicKeyFileStream = null; FileOutputStream privateKeyFileStream = null; OutputStreamWriter csrFileStreamWriter = null; OutputStreamWriter privateKeyStreamWriter = null; OutputStreamWriter publicKeyStreamWriter = null; try { KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType()); keyStore.load(null, storePassword.toCharArray()); if (DEBUG) { DEBUGGER.debug("KeyStore: {}", keyStore); } SecureRandom random = new SecureRandom(); KeyPairGenerator keyGenerator = KeyPairGenerator.getInstance(certificateAlgorithm); keyGenerator.initialize(keySize, random); if (DEBUG) { DEBUGGER.debug("KeyGenerator: {}", keyGenerator); } KeyPair keyPair = keyGenerator.generateKeyPair(); if (DEBUG) { DEBUGGER.debug("KeyPair: {}", keyPair); } if (keyPair != null) { final Signature sig = Signature.getInstance(signatureAlgorithm); final PrivateKey privateKey = keyPair.getPrivate(); final PublicKey publicKey = keyPair.getPublic(); if (DEBUG) { DEBUGGER.debug("Signature: {}", sig); DEBUGGER.debug("PrivateKey: {}", privateKey); DEBUGGER.debug("PublicKey: {}", publicKey); } sig.initSign(privateKey, random); ContentSigner signGen = new JcaContentSignerBuilder(signatureAlgorithm).build(privateKey); if (DEBUG) { DEBUGGER.debug("ContentSigner: {}", signGen); } Calendar expiry = Calendar.getInstance(); expiry.add(Calendar.DAY_OF_YEAR, validityPeriod); if (DEBUG) { DEBUGGER.debug("Calendar: {}", expiry); } CertificateFactory certFactory = CertificateFactory.getInstance(certConfig.getCertificateType()); if (DEBUG) { DEBUGGER.debug("CertificateFactory: {}", certFactory); } X509Certificate[] issuerCert = new X509Certificate[] { (X509Certificate) certFactory .generateCertificate(new FileInputStream(certConfig.getIntermediateCertificateFile())) }; if (DEBUG) { DEBUGGER.debug("X509Certificate[]: {}", (Object) issuerCert); } keyStore.setCertificateEntry(certConfig.getRootCertificateName(), certFactory.generateCertificate( new FileInputStream(FileUtils.getFile(certConfig.getRootCertificateFile())))); keyStore.setCertificateEntry(certConfig.getIntermediateCertificateName(), certFactory.generateCertificate(new FileInputStream( FileUtils.getFile(certConfig.getIntermediateCertificateFile())))); PKCS10CertificationRequestBuilder builder = new JcaPKCS10CertificationRequestBuilder(x500Name, publicKey); if (DEBUG) { DEBUGGER.debug("PKCS10CertificationRequestBuilder: {}", builder); } PKCS10CertificationRequest csr = builder.build(signGen); if (DEBUG) { DEBUGGER.debug("PKCS10CertificationRequest: {}", csr); } // write private key File privateKeyFile = FileUtils.getFile(privateKeyDirectory + "/" + subjectData.get(0) + SecurityServiceConstants.PRIVATEKEY_FILE_EXT); if (DEBUG) { DEBUGGER.debug("privateKeyFile: {}", privateKeyFile); } if (!(privateKeyFile.createNewFile())) { throw new IOException("Failed to store private file"); } privateKeyFileStream = new FileOutputStream(privateKeyFile); privateKeyStreamWriter = new OutputStreamWriter(privateKeyFileStream); if (DEBUG) { DEBUGGER.debug("privateKeyFileStream: {}", privateKeyFileStream); DEBUGGER.debug("privateKeyStreamWriter: {}", privateKeyStreamWriter); } privateKeyWriter = new JcaPEMWriter(privateKeyStreamWriter); privateKeyWriter.writeObject(privateKey); privateKeyWriter.flush(); privateKeyStreamWriter.flush(); privateKeyFileStream.flush(); // write public key File publicKeyFile = FileUtils.getFile(publicKeyDirectory + "/" + subjectData.get(0) + SecurityServiceConstants.PUBLICKEY_FILE_EXT); if (DEBUG) { DEBUGGER.debug("publicKeyFile: {}", publicKeyFile); } if (!(publicKeyFile.createNewFile())) { throw new IOException("Failed to store public key file"); } publicKeyFileStream = new FileOutputStream(publicKeyFile); publicKeyStreamWriter = new OutputStreamWriter(publicKeyFileStream); if (DEBUG) { DEBUGGER.debug("publicKeyFileStream: {}", publicKeyFileStream); DEBUGGER.debug("publicKeyStreamWriter: {}", publicKeyStreamWriter); } publicKeyWriter = new JcaPEMWriter(publicKeyStreamWriter); publicKeyWriter.writeObject(publicKey); publicKeyWriter.flush(); publicKeyStreamWriter.flush(); publicKeyFileStream.flush(); // write csr csrFile = FileUtils .getFile(csrDirectory + "/" + subjectData.get(0) + SecurityServiceConstants.CSR_FILE_EXT); if (DEBUG) { DEBUGGER.debug("csrFile: {}", csrFile); } if (!(csrFile.createNewFile())) { throw new IOException("Failed to store CSR file"); } csrFileStream = new FileOutputStream(csrFile); csrFileStreamWriter = new OutputStreamWriter(csrFileStream); if (DEBUG) { DEBUGGER.debug("publicKeyFileStream: {}", publicKeyFileStream); DEBUGGER.debug("publicKeyStreamWriter: {}", publicKeyStreamWriter); } csrPemWriter = new JcaPEMWriter(csrFileStreamWriter); csrPemWriter.writeObject(csr); csrPemWriter.flush(); csrFileStreamWriter.flush(); csrFileStream.flush(); File keyStoreFile = FileUtils .getFile(storeDirectory + "/" + subjectData.get(0) + "." + KeyStore.getDefaultType()); if (DEBUG) { DEBUGGER.debug("keyStoreFile: {}", keyStoreFile); } keyStoreStream = FileUtils.openOutputStream(keyStoreFile); if (DEBUG) { DEBUGGER.debug("keyStoreStream: {}", keyStoreStream); } keyStore.setKeyEntry(subjectData.get(0), (Key) keyPair.getPrivate(), storePassword.toCharArray(), issuerCert); keyStore.store(keyStoreStream, storePassword.toCharArray()); keyStoreStream.flush(); if (DEBUG) { DEBUGGER.debug("KeyStore: {}", keyStore); } } else { throw new CertificateManagementException("Failed to generate keypair. Cannot continue."); } } catch (FileNotFoundException fnfx) { throw new CertificateManagementException(fnfx.getMessage(), fnfx); } catch (IOException iox) { throw new CertificateManagementException(iox.getMessage(), iox); } catch (NoSuchAlgorithmException nsax) { throw new CertificateManagementException(nsax.getMessage(), nsax); } catch (IllegalStateException isx) { throw new CertificateManagementException(isx.getMessage(), isx); } catch (InvalidKeyException ikx) { throw new CertificateManagementException(ikx.getMessage(), ikx); } catch (OperatorCreationException ocx) { throw new CertificateManagementException(ocx.getMessage(), ocx); } catch (KeyStoreException ksx) { throw new CertificateManagementException(ksx.getMessage(), ksx); } catch (CertificateException cx) { throw new CertificateManagementException(cx.getMessage(), cx); } finally { if (csrFileStreamWriter != null) { IOUtils.closeQuietly(csrFileStreamWriter); } if (csrFileStream != null) { IOUtils.closeQuietly(csrFileStream); } if (csrPemWriter != null) { IOUtils.closeQuietly(csrPemWriter); } if (publicKeyFileStream != null) { IOUtils.closeQuietly(publicKeyFileStream); } if (publicKeyStreamWriter != null) { IOUtils.closeQuietly(publicKeyStreamWriter); } if (publicKeyWriter != null) { IOUtils.closeQuietly(publicKeyWriter); } if (privateKeyFileStream != null) { IOUtils.closeQuietly(privateKeyFileStream); } if (privateKeyStreamWriter != null) { IOUtils.closeQuietly(privateKeyStreamWriter); } if (privateKeyWriter != null) { IOUtils.closeQuietly(privateKeyWriter); } if (keyStoreStream != null) { IOUtils.closeQuietly(keyStoreStream); } } return csrFile; }
From source file:jenkins.branch.DefaultDeadBranchStrategy.java
/** * {@inheritDoc}/*ww w . j a v a2 s. co m*/ */ public <P extends Job<P, R> & TopLevelItem, R extends Run<P, R>> void runDeadBranchCleanup( TaskListener listener, Map<String, P> deadBranches) throws IOException, InterruptedException { final MultiBranchProject<P, R> owner = (MultiBranchProject<P, R>) getOwner(); LOGGER.log(FINE, "Running the dead branch cleanup for " + owner.getFullDisplayName()); if (pruneDeadBranches && (numToKeep != -1 || daysToKeep != -1)) { List<P> candidates = new ArrayList<P>(deadBranches.values()); Collections.sort(candidates, new Comparator<P>() { public int compare(P o1, P o2) { // most recent build first R lb1 = o1.getLastBuild(); R lb2 = o2.getLastBuild(); if (lb1 == null) { if (lb2 == null) { return 0; } return 1; } if (lb2 == null) { return -1; } long ms1 = lb1.getTimeInMillis(); long ms2 = lb2.getTimeInMillis(); return ms1 == ms2 ? 0 : (ms1 > ms2 ? -1 : 1); } }); int count = 0; if (numToKeep != -1) { for (Iterator<P> iterator = candidates.iterator(); iterator.hasNext();) { P project = iterator.next(); count++; // todo keepers if (count <= numToKeep) { continue; } LOGGER.log(FINER, project.getFullDisplayName() + " is to be removed"); project.delete(); owner.onDeleted(project); iterator.remove(); } } if (daysToKeep != -1) { Calendar cal = new GregorianCalendar(); cal.add(Calendar.DAY_OF_YEAR, -daysToKeep); for (Iterator<P> iterator = candidates.iterator(); iterator.hasNext();) { P project = iterator.next(); R r = project.getLastBuild(); // todo keepers if (r != null && !r.getTimestamp().before(cal)) { LOGGER.log(FINER, project.getFullDisplayName() + " is not GC-ed because it's still new"); continue; } LOGGER.log(FINER, project.getFullDisplayName() + " is to be removed"); project.delete(); owner.onDeleted(project); iterator.remove(); } } } }
From source file:edu.harvard.iq.dvn.core.index.IndexServiceBean.java
public void createIndexNotificationTimer() { for (Iterator it = timerService.getTimers().iterator(); it.hasNext();) { Timer timer = (Timer) it.next(); if (timer.getInfo().equals(INDEX_NOTIFICATION_TIMER)) { logger.info("Cannot create IndexNotificationTimer, timer already exists."); logger.info("IndexNotificationTimer next timeout is " + timer.getNextTimeout()); return; }/* w w w. j a va 2 s. co m*/ } Calendar cal = Calendar.getInstance(); cal.add(Calendar.DAY_OF_YEAR, 1); cal.set(Calendar.HOUR_OF_DAY, 15); logger.log(Level.INFO, "Indexer notification timer set for " + cal.getTime()); Date initialExpiration = cal.getTime(); // First timeout is 1:00 AM of next day long intervalDuration = 1000 * 60 * 60 * 24; // repeat every 24 hours timerService.createTimer(initialExpiration, intervalDuration, INDEX_NOTIFICATION_TIMER); }
From source file:de.hshannover.f4.trust.irondetectprocedures.MeanDaily.java
/** * Checks if the two calendar objects refer to the same day. ignores timezones * @param c1/* www. j a va 2s .c om*/ * @param c2 * @return */ private boolean isSameDay(Calendar c1, Calendar c2) { return c1.get(Calendar.YEAR) == c2.get(Calendar.YEAR) && c1.get(Calendar.DAY_OF_YEAR) == c2.get(Calendar.DAY_OF_YEAR); }
From source file:com.discovery.darchrow.date.DateExtensionUtil.java
/** * ? :getWeekDateStringList(6, "yyyy-MM-dd");. * //w w w .j av a 2s . co m * @param week * 1 ?2 3 4 5 6 7, ? {@link Calendar#SUNDAY}, {@link Calendar#MONDAY}, {@link Calendar#TUESDAY}, * {@link Calendar#WEDNESDAY}, {@link Calendar#THURSDAY}, {@link Calendar#FRIDAY}, {@link Calendar#SATURDAY} * @param datePattern * ??? * @return ? * @see org.apache.commons.lang3.time.DateUtils#iterator(Date, int) * @see Calendar#SUNDAY * @see Calendar#MONDAY * @see Calendar#TUESDAY * @see Calendar#WEDNESDAY * @see Calendar#THURSDAY * @see Calendar#FRIDAY * @see Calendar#SATURDAY */ public static List<String> getWeekDateStringList(int week, String datePattern) { Date now = new Date(); Date firstWeekOfSpecifyDateYear = DateUtil.getFirstWeekOfSpecifyDateYear(now, week); //? Calendar calendarEnd = CalendarUtil.resetYearEnd(DateUtil.toCalendar(now)); List<String> list = new ArrayList<String>(); for (Calendar calendar = DateUtil.toCalendar(firstWeekOfSpecifyDateYear); calendar .before(calendarEnd); calendar.add(Calendar.DAY_OF_YEAR, 7)) { list.add(CalendarUtil.toString(calendar, datePattern)); } return list; }
From source file:com.webbfontaine.valuewebb.model.util.Utils.java
public static int diffDays(Date startDate, Date endDate) { int numberOfDays = 0; Calendar startCalDate = Calendar.getInstance(); Calendar endCalDate = Calendar.getInstance(); startCalDate.setTime(startDate);/* w w w . ja va2 s .com*/ endCalDate.setTime(endDate); if (startCalDate.get(Calendar.YEAR) == endCalDate.get(Calendar.YEAR)) { return endCalDate.get(Calendar.DAY_OF_YEAR) - startCalDate.get(Calendar.DAY_OF_YEAR) + 1; } for (int i = startCalDate.get(Calendar.YEAR) + 1; i <= (endCalDate.get(Calendar.YEAR) - 1); i++) { numberOfDays += isLeapYear(i) ? 366 : 365; } numberOfDays += daysNumberFromYearBeginning(endCalDate) + daysNumberUntilYearEnd(startCalDate) + 1; return numberOfDays; }
From source file:de.fhbingen.wbs.wpOverview.tabs.AvailabilityGraph.java
/** * Set the view to YEAR./* ww w. j ava2 s.c o m*/ */ private void setYearView() { actualStart = (GregorianCalendar) actualDay.clone(); actualStart.set(Calendar.DAY_OF_YEAR, actualDay.getActualMinimum(Calendar.DAY_OF_YEAR)); actualStart.set(Calendar.HOUR, 0); actualStart.set(Calendar.MINUTE, 0); actualStart.add(Calendar.DAY_OF_YEAR, -1); actualEnd = (GregorianCalendar) actualDay.clone(); actualEnd.set(Calendar.DAY_OF_YEAR, actualDay.getActualMaximum(Calendar.DAY_OF_YEAR)); actualEnd.set(Calendar.HOUR, 23); actualEnd.set(Calendar.MINUTE, 59); actualView = YEAR; GregorianCalendar helper = (GregorianCalendar) actualEnd.clone(); helper.add(Calendar.DATE, -1); makeChart(new SimpleDateFormat("yyyy").format(helper.getTime())); }
From source file:com.mobileman.projecth.business.DoctorServiceTest.java
/** * /*from w w w . j a v a2s . com*/ * @throws Exception */ @Test public void saveManualKpiValue() throws Exception { Doctor doctor = (Doctor) userService.findUserByLogin("sysuser3"); assertNotNull(doctor); List<PatientKeyPerformanceIndicatorValidation> validations = patientKPIValidationService.findAll(); assertNotNull(validations); assertEquals(0, validations.size()); Patient patient = patientService.findAll().get(0); assertNotNull(patient); assertNotNull(patient.getId()); Disease disease = diseaseService.findByCode("M79.0"); assertNotNull(disease); KeyPerformanceIndicatorType questionaryValidationType = keyPerformanceIndicatorTypeService.find("CDAI", disease.getId()); doctorService.saveValidatedKpiValue(doctor.getId(), patient.getId(), new Date(), questionaryValidationType, new BigDecimal("15")); validations = patientKPIValidationService.findAll(); assertNotNull(validations); assertEquals(1, validations.size()); Calendar calendar = new GregorianCalendar(); calendar.add(Calendar.DAY_OF_YEAR, -1); Date start = calendar.getTime(); calendar.add(Calendar.DAY_OF_YEAR, 2); Date end = calendar.getTime(); List<PatientKeyPerformanceIndicatorValidation> values = patientKPIValidationService .findValidatedValues(patient.getId(), questionaryValidationType.getId(), start, end); assertEquals(1, values.size()); assertEquals(15, values.get(0).getValue().intValue()); values = patientKPIValidationService.findValidatedValues(doctor.getId(), patient.getId(), questionaryValidationType.getId(), start, end); assertEquals(1, values.size()); assertEquals(15, values.get(0).getValue().intValue()); values = patientKPIValidationService.findValidatedValues(patient.getId(), patient.getId(), questionaryValidationType.getId(), start, end); assertEquals(0, values.size()); }