List of usage examples for java.util Date after
public boolean after(Date when)
From source file:eionet.cr.harvest.PullHarvest.java
/** * Returns the {@link Date} to which the source's last harvest time should be set in case of temporary harvest error. It should * be set to "now - harvest_interval + max(harvest_interval*0,1, 120 min)". The "now" is given as method input. * * @param now As indicated above./*w ww . j av a 2s . c o m*/ * @return The calculated last harvest date as indicated above. */ private Date temporaryErrorLastHarvest(Date now) { // The source's harvesting interval in minutes. int intervalMinutes = getContextSourceDTO().getIntervalMinutes(); // The new last harvest will be "now - interval + interval*0,1", but at least two hours (i.e. 120 minutes). // So here we calculate the value that we shall add to the "now - interval". int increaseMinutes = Math.max((intervalMinutes * 10) / 100, 120); // Get calendar instance, set it to now. Calendar cal = Calendar.getInstance(); cal.setTime(now); // Subtract interval and add the above-calculated increase. cal.add(Calendar.MINUTE, -1 * intervalMinutes); cal.add(Calendar.MINUTE, increaseMinutes); // Just make it 100% sure that the calculated time will not be after now, though the business logic should exclude it. Date resultingTime = cal.getTime(); if (resultingTime.after(now)) { resultingTime = now; } return resultingTime; }
From source file:com.painiu.webapp.upload.UploadProcessor.java
private void readJpegMetadata(Photo photo, File file) { try {/*ww w .ja va 2 s . c o m*/ JpegSegmentData data = MetadataUtils.readSegments(file); Metadata metadata = MetadataUtils.extractMetadataFromSegmentData(data); if (log.isDebugEnabled()) { log.debug("********* Metadata of uploaded photo *********"); // iterate over the exif data and print it Iterator directories = metadata.getDirectoryIterator(); while (directories.hasNext()) { Directory directory = (Directory) directories.next(); Iterator tagsIterator = directory.getTagIterator(); while (tagsIterator.hasNext()) { Tag tag = (Tag) tagsIterator.next(); log.debug(tag); } if (directory.hasErrors()) { Iterator errors = directory.getErrors(); while (errors.hasNext()) { log.debug("ERROR: " + errors.next()); } } } } Directory exifDirectory = metadata.getDirectory(ExifDirectory.class); Date takenDate = null; if (exifDirectory.containsTag(ExifDirectory.TAG_DATETIME_ORIGINAL)) { takenDate = exifDirectory.getDate(ExifDirectory.TAG_DATETIME_ORIGINAL); } else if (exifDirectory.containsTag(ExifDirectory.TAG_DATETIME_DIGITIZED)) { takenDate = exifDirectory.getDate(ExifDirectory.TAG_DATETIME_DIGITIZED); } else if (exifDirectory.containsTag(ExifDirectory.TAG_DATETIME)) { takenDate = exifDirectory.getDate(ExifDirectory.TAG_DATETIME); } if (takenDate != null && takenDate.after(MIN_TAKEN_DATE)) { photo.setTakenDate(takenDate); } if (photo.getTitle() == null) { String titleFromMeta = extractTitleFromMetadata(metadata); if (titleFromMeta != null) { photo.setTitle(titleFromMeta); } } if (photo.getDescription() == null) { photo.setDescription(extractDescFromMetadata(metadata)); } if (exifDirectory.containsTag(ExifDirectory.TAG_MODEL)) { String cameraModel = exifDirectory.getString(ExifDirectory.TAG_MODEL); photo.setCameraModel(cameraModel); // save metadata as file File localFile = new File(file.getAbsolutePath() + ".meta"); MetadataUtils.toFile(localFile, data); // PNFS testing ----------------------------------- /*MetaFile metaFile = new MetaFile( photo.getAddress().getUsername(), photo.getAddress().getFileKey(), localFile); try { metaFile.store(); } catch (YPFSException e) { log.error("YPFSException: " + e); photo.setCameraModel(null); } finally { localFile.delete(); }*/ // PNFS } // we dont save any metadata, if there have no camera tag } catch (JpegProcessingException e) { log.warn("JpegProcessingException: ", e); } catch (MetadataException e) { log.warn("MetadataException: ", e); } catch (IOException e) { log.warn("IOException: ", e); } }
From source file:net.solarnetwork.node.settings.ca.CASettingsService.java
@Override public SettingsBackup backupSettings() { final Date mrd = settingDao.getMostRecentModificationDate(); final SimpleDateFormat sdf = new SimpleDateFormat(BACKUP_DATE_FORMAT); final String lastBackupDateStr = settingDao.getSetting(SETTING_LAST_BACKUP_DATE); final Date lastBackupDate; try {//from w w w . j a v a 2s. co m lastBackupDate = (lastBackupDateStr == null ? null : sdf.parse(lastBackupDateStr)); } catch (ParseException e) { throw new RuntimeException("Unable to parse backup last date: " + e.getMessage()); } if (mrd == null || (lastBackupDate != null && lastBackupDate.after(mrd))) { log.debug("Settings unchanged since last backup on {}", lastBackupDateStr); return null; } final Date backupDate = new Date(); final String backupDateKey = sdf.format(backupDate); final File dir = new File(backupDestinationPath); if (!dir.exists()) { dir.mkdirs(); } final File f = new File(dir, BACKUP_FILENAME_PREFIX + backupDateKey + '.' + BACKUP_FILENAME_EXT); log.info("Backing up settings to {}", f.getPath()); Writer writer = null; try { writer = new BufferedWriter(new FileWriter(f)); exportSettingsCSV(writer); settingDao.storeSetting(new Setting(SETTING_LAST_BACKUP_DATE, null, backupDateKey, EnumSet.of(SettingFlag.IgnoreModificationDate))); } catch (IOException e) { log.error("Unable to create settings backup {}: {}", f.getPath(), e.getMessage()); } finally { try { writer.flush(); writer.close(); } catch (IOException e) { // ignore } } // clean out older backups File[] files = dir.listFiles(new RegexFileFilter(BACKUP_FILENAME_PATTERN)); if (files != null && files.length > backupMaxCount) { // sort array Arrays.sort(files, new FilenameReverseComparator()); for (int i = backupMaxCount; i < files.length; i++) { if (!files[i].delete()) { log.warn("Unable to delete old settings backup file {}", files[i]); } } } return new SettingsBackup(backupDateKey, backupDate); }
From source file:com.surevine.alfresco.repo.delete.SiteNameBasedManagedDeletionService.java
@Override public NodeArchivalDetails getArchivalDetails(NodeRef nodeRef) { if (_logger.isDebugEnabled()) { _logger.debug("Getting archive details for " + nodeRef); }//from w w w . java 2 s.c om boolean isMarkedForDelete = _nodeService.hasAspect(nodeRef, ManagedDeletionModel.ASPECT_MARKED_FOR_DELETION); boolean isPerishable = _nodeService.hasAspect(nodeRef, ManagedDeletionModel.ASPECT_PERISHABLE); Date perishDate = (Date) _nodeService.getProperty(nodeRef, ManagedDeletionModel.PROP_PERISH_DUE); Date deleteDate = (Date) _nodeService.getProperty(nodeRef, ManagedDeletionModel.PROP_ARCHIVE_DUE_DATETIME); if (isMarkedForDelete && isPerishable) { if (perishDate.after(deleteDate)) { isPerishable = false; // We will use the delete date } else { isMarkedForDelete = false; // We will use the perish date } } if (isMarkedForDelete) { return new NodeArchivalDetails(ArchivalStatus.MARKED_FOR_DELETE, deleteDate, (String) _nodeService.getProperty(nodeRef, ManagedDeletionModel.PROP_DELETED_BY), null); } if (isPerishable) { return new NodeArchivalDetails(ArchivalStatus.PERISHABLE, perishDate, (String) _nodeService.getProperty(nodeRef, ManagedDeletionModel.PROP_PERISH_REQUESTED_BY), (String) _nodeService.getProperty(nodeRef, ManagedDeletionModel.PROP_PERISH_REASON)); } if (_nodeService.hasAspect(nodeRef, ManagedDeletionModel.ASPECT_DELETED)) { return new NodeArchivalDetails(ArchivalStatus.DELETED, null, null, null); } return new NodeArchivalDetails(ArchivalStatus.UNMARKED, null, null, null); }
From source file:com.aurel.track.fieldType.runtime.matchers.run.DateMatcherRT.java
/** * Whether the value matches or not/* w ww . ja va 2 s .c o m*/ * @param attributeValue * @return */ @Override public boolean match(Object attributeValue) { Boolean nullMatch = nullMatcher(attributeValue); if (nullMatch != null) { return nullMatch.booleanValue(); } if (attributeValue == null) { return false; } //probably no value specified if (dayBegin == null && dayEnd == null) { return true; } Date attributeValueDate = null; try { attributeValueDate = (Date) attributeValue; } catch (Exception e) { LOGGER.error("Converting the attribute value " + attributeValue + " of type " + attributeValue.getClass().getName() + " to Date failed with " + e.getMessage()); LOGGER.debug(ExceptionUtils.getStackTrace(e)); return false; } switch (relation) { case MatchRelations.EQUAL_DATE: case MatchRelations.THIS_WEEK: case MatchRelations.THIS_MONTH: case MatchRelations.LAST_WEEK: case MatchRelations.LAST_MONTH: //for dates without time value (for ex. startDate, endDate) the equality should be also tested return (attributeValueDate.getTime() == dayBegin.getTime() || attributeValueDate.after(dayBegin)) && attributeValueDate.before(dayEnd); case MatchRelations.NOT_EQUAL_DATE: //dayEnd is already the next day so the equality should be also tested return attributeValueDate.before(dayBegin) || attributeValueDate.after(dayEnd) || attributeValueDate.getTime() == dayEnd.getTime(); case MatchRelations.GREATHER_THAN_DATE: case MatchRelations.IN_MORE_THAN_DAYS: return attributeValueDate.after(dayEnd) || attributeValueDate.getTime() == dayEnd.getTime(); case MatchRelations.LESS_THAN_DAYS_AGO: return (attributeValueDate.after(dayEnd) || attributeValueDate.getTime() == dayEnd.getTime()) && attributeValueDate.before(new Date()); case MatchRelations.GREATHER_THAN_EQUAL_DATE: case MatchRelations.LESS_THAN_EQUAL_DAYS_AGO: case MatchRelations.IN_MORE_THAN_EQUAL_DAYS: return attributeValueDate.after(dayBegin) || attributeValueDate.getTime() == dayBegin.getTime(); case MatchRelations.LESS_THAN_DATE: case MatchRelations.MORE_THAN_DAYS_AGO: return attributeValueDate.before(dayBegin); case MatchRelations.IN_LESS_THAN_DAYS: return (attributeValueDate.before(dayBegin) || attributeValueDate.getTime() == dayBegin.getTime()) && attributeValueDate.after(new Date()); case MatchRelations.LESS_THAN_EQUAL_DATE: case MatchRelations.MORE_THAN_EQUAL_DAYS_AGO: case MatchRelations.IN_LESS_THAN_EQUAL_DAYS: return attributeValueDate.before(dayEnd); case MatchRelations.LATER_AS_LASTLOGIN: if (dayBegin == null) { //the very first logging return true; } return attributeValueDate.after(dayBegin); default: return false; } }
From source file:com.example.app.profile.ui.user.ProfileMembershipManagement.java
void doDatesEdit(@Nullable Membership membership) { if (membership == null) return;//from ww w . ja v a2 s .c om final MembershipType membershipType = membership.getMembershipType(); assert membershipType != null; Label heading = new Label(createText(EDIT_DATES_UI_HEADING_FORMAT(), membership.getUser().getName(), membershipType.getName())); heading.setHTMLElement(HTMLElement.h3); MessageContainer messages = new MessageContainer(35_000L); PushButton saveButton = CommonActions.SAVE.push(); PushButton cancelButton = CommonActions.CANCEL.push(); RelativeOffsetRange range = new RelativeOffsetRange(5, 2); CalendarValueEditor startDateEditor = new CalendarValueEditor(START_DATE(), membership.getStartDate(), range); CalendarValueEditor endDateEditor = new CalendarValueEditor(END_DATE(), membership.getEndDate(), range); Container ui = of("edit-membership prop-wrapper prop-editor", messages, heading, of("prop-body", startDateEditor, endDateEditor), of("actions persistence-actions bottom", saveButton, cancelButton)); ActionListener closer = ev -> ui.close(); saveButton.addActionListener(ev -> { if (((Supplier<Boolean>) () -> { final Date startDate = startDateEditor.commitValue(); final Date endDate = endDateEditor.commitValue(); membership.setStartDate( convertForPersistence(toZonedDateTime(startDate, getSession().getTimeZone()))); ZonedDateTime endDateTime = toZonedDateTime(endDate, getSession().getTimeZone()); membership.setEndDate( convertForPersistence(endDateTime != null ? endDateTime.minus(1, ChronoUnit.DAYS) : null)); if (startDate != null && endDate != null && startDate.after(endDate)) { messages.sendNotification(NotificationImpl.error(ERROR_START_DATE_AFTER_END_DATE())); return false; } return true; }).get()) { closer.actionPerformed(ev); showHideConstraints(); } }); cancelButton.addActionListener(closer); getHistory().add(new HistoryElement(ui)); navigateBackOnClose(ui); }
From source file:com.emc.vipr.sync.target.AtmosTarget.java
@Override public void filter(final SyncObject<?> obj) { // skip the root namespace since it obviously exists if ("/".equals(destNamespace + obj.getRelativePath())) { l4j.debug("Target namespace is root"); return;//from w ww . j av a 2s.co m } timeOperationStart(OPERATION_TOTAL); try { // some sync objects lazy-load their metadata (i.e. AtmosSyncObject) // since this may be a timed operation, ensure it loads outside of other timed operations final Map<String, Metadata> umeta = AtmosUtil.getAtmosUserMetadata(obj.getMetadata()); if (destNamespace != null) { // Determine a name for the object. ObjectPath destPath; if (!destNamespace.endsWith("/")) { // A specific file was mentioned. destPath = new ObjectPath(destNamespace); } else { String path = destNamespace + obj.getRelativePath(); if (obj.isDirectory() && !path.endsWith("/")) path += "/"; destPath = new ObjectPath(path); } final ObjectPath fDestPath = destPath; obj.setTargetIdentifier(destPath.toString()); // See if the target exists if (destPath.isDirectory()) { Map<String, Metadata> smeta = getSystemMetadata(destPath); if (smeta != null) { // See if a metadata update is required Date srcCtime = getCTime(obj.getMetadata()); Date dstCtime = parseDate(smeta.get("ctime")); if ((srcCtime != null && dstCtime != null && srcCtime.after(dstCtime)) || force) { if (umeta != null && umeta.size() > 0) { LogMF.debug(l4j, "Updating metadata on {0}", destPath); time(new Timeable<Void>() { @Override public Void call() { atmos.setUserMetadata(fDestPath, umeta.values().toArray(new Metadata[umeta.size()])); return null; } }, OPERATION_SET_USER_META); } final Acl acl = getAtmosAcl(obj.getMetadata()); if (acl != null) { LogMF.debug(l4j, "Updating ACL on {0}", destPath); time(new Timeable<Void>() { @Override public Void call() { atmos.setAcl(fDestPath, acl); return null; } }, OPERATION_SET_ACL); } } else { LogMF.debug(l4j, "No changes from source {0} to dest {1}", obj.getSourceIdentifier(), obj.getTargetIdentifier()); return; } } else { // Directory does not exist on target time(new Timeable<ObjectId>() { @Override public ObjectId call() { return atmos.createDirectory(fDestPath, getAtmosAcl(obj.getMetadata()), umeta.values().toArray(new Metadata[umeta.size()])); } }, OPERATION_CREATE_OBJECT_ON_PATH); } } else { // File, not directory ObjectMetadata destMeta = getMetadata(destPath); if (destMeta == null) { // Target does not exist. InputStream in = null; try { in = obj.getInputStream(); ObjectId id = null; if (in == null) { // Create an empty object final CreateObjectRequest request = new CreateObjectRequest(); request.identifier(destPath).acl(getAtmosAcl(obj.getMetadata())); request.setUserMetadata(umeta.values()); request.contentType(obj.getMetadata().getContentType()); id = time(new Timeable<ObjectId>() { @Override public ObjectId call() { return atmos.createObject(request).getObjectId(); } }, OPERATION_CREATE_OBJECT_ON_PATH); } else { if (checksum != null) { final RunningChecksum ck = new RunningChecksum( ChecksumAlgorithm.valueOf(checksum)); byte[] buffer = new byte[1024 * 1024]; long read = 0; int c; while ((c = in.read(buffer)) != -1) { final BufferSegment bs = new BufferSegment(buffer, 0, c); if (read == 0) { // Create ck.update(bs.getBuffer(), bs.getOffset(), bs.getSize()); final CreateObjectRequest request = new CreateObjectRequest(); request.identifier(destPath).acl(getAtmosAcl(obj.getMetadata())) .content(bs); request.setUserMetadata(umeta.values()); request.contentType(obj.getMetadata().getContentType()).wsChecksum(ck); id = time(new Timeable<ObjectId>() { @Override public ObjectId call() { return atmos.createObject(request).getObjectId(); } }, OPERATION_CREATE_OBJECT_FROM_SEGMENT_ON_PATH); } else { // Append ck.update(bs.getBuffer(), bs.getOffset(), bs.getSize()); Range r = new Range(read, read + c - 1); final UpdateObjectRequest request = new UpdateObjectRequest(); request.identifier(id).content(bs).range(r).wsChecksum(ck); request.contentType(obj.getMetadata().getContentType()); time(new Timeable<Object>() { @Override public Object call() { atmos.updateObject(request); return null; } }, OPERATION_UPDATE_OBJECT_FROM_SEGMENT); } read += c; } } else { final CreateObjectRequest request = new CreateObjectRequest(); request.identifier(destPath).acl(getAtmosAcl(obj.getMetadata())).content(in); request.setUserMetadata(umeta.values()); request.contentLength(obj.getMetadata().getSize()) .contentType(obj.getMetadata().getContentType()); id = time(new Timeable<ObjectId>() { @Override public ObjectId call() { return atmos.createObject(request).getObjectId(); } }, OPERATION_CREATE_OBJECT_FROM_STREAM_ON_PATH); } } updateRetentionExpiration(obj, id); } finally { if (in != null) { in.close(); } } } else { checkUpdate(obj, destPath, destMeta); } } } else { // Object Space // don't create directories in objectspace // TODO: is this a valid use-case (should we create these objects)? if (obj.isDirectory()) { LogMF.debug(l4j, "Source {0} is a directory, but target is in objectspace, ignoring", obj.getSourceIdentifier()); return; } InputStream in = null; try { ObjectId id = null; // Check and see if a target ID was alredy computed String targetId = obj.getTargetIdentifier(); if (targetId != null) { id = new ObjectId(targetId); } if (id != null) { ObjectMetadata destMeta = getMetadata(id); if (destMeta == null) { // Target ID not found! throw new RuntimeException("The target object ID " + id + " was not found!"); } obj.setTargetIdentifier(id.toString()); checkUpdate(obj, id, destMeta); } else { in = obj.getInputStream(); if (in == null) { // Usually some sort of directory final CreateObjectRequest request = new CreateObjectRequest(); request.acl(getAtmosAcl(obj.getMetadata())) .contentType(obj.getMetadata().getContentType()); request.setUserMetadata(umeta.values()); id = time(new Timeable<ObjectId>() { @Override public ObjectId call() { return atmos.createObject(request).getObjectId(); } }, OPERATION_CREATE_OBJECT); } else { if (checksum != null) { final RunningChecksum ck = new RunningChecksum(ChecksumAlgorithm.valueOf(checksum)); byte[] buffer = new byte[1024 * 1024]; long read = 0; int c; while ((c = in.read(buffer)) != -1) { final BufferSegment bs = new BufferSegment(buffer, 0, c); if (read == 0) { // Create ck.update(bs.getBuffer(), bs.getOffset(), bs.getSize()); final CreateObjectRequest request = new CreateObjectRequest(); request.acl(getAtmosAcl(obj.getMetadata())).content(bs); request.setUserMetadata(umeta.values()); request.contentType(obj.getMetadata().getContentType()).wsChecksum(ck); id = time(new Timeable<ObjectId>() { @Override public ObjectId call() { return atmos.createObject(request).getObjectId(); } }, OPERATION_CREATE_OBJECT_FROM_SEGMENT); } else { // Append ck.update(bs.getBuffer(), bs.getOffset(), bs.getSize()); Range r = new Range(read, read + c - 1); final UpdateObjectRequest request = new UpdateObjectRequest(); request.identifier(id).content(bs).range(r).wsChecksum(ck); request.contentType(obj.getMetadata().getContentType()); time(new Timeable<Void>() { @Override public Void call() { atmos.updateObject(request); return null; } }, OPERATION_UPDATE_OBJECT_FROM_SEGMENT); } read += c; } } else { final CreateObjectRequest request = new CreateObjectRequest(); request.acl(getAtmosAcl(obj.getMetadata())).content(in); request.setUserMetadata(umeta.values()); request.contentLength(obj.getMetadata().getSize()) .contentType(obj.getMetadata().getContentType()); id = time(new Timeable<ObjectId>() { @Override public ObjectId call() { return atmos.createObject(request).getObjectId(); } }, OPERATION_CREATE_OBJECT_FROM_STREAM); } } updateRetentionExpiration(obj, id); obj.setTargetIdentifier(id == null ? null : id.toString()); } } finally { try { if (in != null) { in.close(); } } catch (IOException e) { // Ignore } } } LogMF.debug(l4j, "Wrote source {0} to dest {1}", obj.getSourceIdentifier(), obj.getTargetIdentifier()); timeOperationComplete(OPERATION_TOTAL); } catch (Exception e) { timeOperationFailed(OPERATION_TOTAL); throw new RuntimeException("Failed to store object: " + e.getMessage(), e); } }
From source file:com.autodomum.core.event.EventComponent.java
/** * Update the event context with correct parameters *//*from ww w . j a v a 2 s . c o m*/ public void updateEventContext() { final Date now = this.getNow(); final Calendar tomorrowCalendar = this.getCalendar(); tomorrowCalendar.setTime(now); this.eventContext.setHoliday(holiday.isHoliday(tomorrowCalendar)); this.eventContext.setHour(tomorrowCalendar.get(Calendar.HOUR_OF_DAY)); this.eventContext.setMinute(tomorrowCalendar.get(Calendar.MINUTE)); tomorrowCalendar.add(Calendar.DATE, 1); final Date tomorrow = tomorrowCalendar.getTime(); final Date sunrise = this.daylight.sunrise(eventContext.getCoordinate(), now); final Date sunset = this.daylight.sunset(eventContext.getCoordinate(), now); final Date sunriseTomorrow = this.daylight.sunrise(eventContext.getCoordinate(), tomorrow); final Date sunsetTomorrow = this.daylight.sunset(eventContext.getCoordinate(), tomorrow); boolean newDaylight = false; if (now.after(sunset)) { newDaylight = false; this.eventContext.setNextSunrise(sunriseTomorrow.getTime()); this.eventContext.setNextSunset(sunsetTomorrow.getTime()); } else if (now.after(sunrise)) { newDaylight = true; this.eventContext.setNextSunrise(sunriseTomorrow.getTime()); this.eventContext.setNextSunset(sunset.getTime()); } else { this.eventContext.setNextSunrise(sunrise.getTime()); this.eventContext.setNextSunset(sunset.getTime()); } if (newDaylight != this.eventContext.isDaylight()) { this.eventContext.setDaylight(newDaylight); if (newDaylight) { this.publish(new SunriseEvent()); } else { this.publish(new SunsetEvent()); } } }
From source file:gov.nasa.arc.spife.core.plan.advisor.resources.ProfileConstraintPlanAdvisor.java
private TemporalExtent getExtent(ProfileConstraint c) { EPlanElement pe = getPlanElement(c); TemporalExtent extent = pe.getMember(TemporalMember.class).getExtent(); if (extent == null) { return null; }//w ww. j av a 2 s. co m TemporalOffset startOffset = c.getStartOffset(); Date start = startOffset == null ? extent.getStart() : startOffset.getDate(extent); TemporalOffset endOffset = c.getEndOffset(); Date end = endOffset == null ? extent.getEnd() : endOffset.getDate(extent); if (start.after(end)) { LogUtil.warn("Profile Constraint " + c.getProfileKey() + " yielded a start that was after its end when applied to element " + pe.getName()); return null; } return new TemporalExtent(start, end); }