List of usage examples for java.util Calendar after
public boolean after(Object when)
Calendar
represents a time after the time represented by the specified Object
. From source file:nl.strohalm.cyclos.services.accounts.guarantees.GuaranteeServiceImpl.java
private void updateAssociatedPaymentObligations(final Guarantee guarantee) { final Calendar today = DateHelper.truncateNextDay(Calendar.getInstance()); for (final PaymentObligation paymentObligation : guarantee.getPaymentObligations()) { final Calendar expirationDate = paymentObligation.getExpirationDate(); final Calendar maxPublishDate = paymentObligation.getMaxPublishDate(); final Element by = LoggedUser.element(); PaymentObligationLog log = null; if (today.after(expirationDate)) { log = paymentObligation.changeStatus(PaymentObligation.Status.EXPIRED, by); } else if (today.after(maxPublishDate)) { log = paymentObligation.changeStatus(PaymentObligation.Status.REGISTERED, by); paymentObligation.setMaxPublishDate(null); } else {//from w w w. ja v a2 s . com log = paymentObligation.changeStatus(PaymentObligation.Status.PUBLISHED, by); } paymentObligation.setGuarantee(null); paymentObligationService.saveLog(log); paymentObligationService.save(paymentObligation, false); } }
From source file:cs.umass.edu.prepare.view.activities.CalendarActivity.java
/** * Allows the user to set time for adherence data where the time is unknown. * @param medication the medication for which the adherence is being modified. * @param index the index of the adherence being modified, i.e. AM or PM. *//*from w w w . j av a 2 s .c o m*/ private void setTimeTaken(final Medication medication, final Calendar dateKey, final int index) { final Dialog dialog = new Dialog(this); dialog.setContentView(R.layout.dialog_set_time); final TimePicker timePicker = (TimePicker) dialog.findViewById(R.id.time_picker); Button cancelButton = (Button) dialog.findViewById(R.id.btn_time_cancel); cancelButton.setOnClickListener(v -> dialog.dismiss()); Button saveButton = (Button) dialog.findViewById(R.id.btn_time_save); saveButton.setOnClickListener(v -> { Calendar time = Utils.getTimeNoInterval(timePicker); // TODO: Store times taken Map<Medication, Adherence[]> dailyAdherence = adherenceData.get(dateKey); Adherence[] adherence = dailyAdherence.get(medication); adherence[index].setTimeTaken(time); Calendar[] schedule = dailySchedule.get(medication); Calendar timeToTake = (Calendar) time.clone(); timeToTake.set(Calendar.HOUR_OF_DAY, schedule[index].get(Calendar.HOUR_OF_DAY)); timeToTake.set(Calendar.MINUTE, schedule[index].get(Calendar.MINUTE)); Calendar upperBound = (Calendar) timeToTake.clone(); upperBound.add(Calendar.HOUR_OF_DAY, 1); Calendar lowerBound = (Calendar) timeToTake.clone(); lowerBound.add(Calendar.HOUR_OF_DAY, -1); if (time.after(upperBound) || time.before(lowerBound)) { adherence[index].setAdherenceType(Adherence.AdherenceType.TAKEN_EARLY_OR_LATE); } else { adherence[index].setAdherenceType(Adherence.AdherenceType.TAKEN); } dialog.dismiss(); refresh(); DataIO preferences = DataIO.getInstance(CalendarActivity.this); preferences.setAdherenceData(this, adherenceData); }); dialog.show(); }
From source file:uk.org.openeyes.BiometryFunctions.java
/** * * * @return OphinbiometryImportedEvents// w w w . j a va 2 s .co m */ private OphinbiometryImportedEvents processImportedEvent() { OphinbiometryImportedEvents importedEvent = null; DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); Criteria currentEvent = session.createCriteria(OphinbiometryImportedEvents.class); // For IOL Master 700 we can use the Device Serial Number and Acquisition Datetime fields to check if it's the same study if (eventStudy.getDeviceType().equals("IOLM700")) { currentEvent.add(Restrictions.eq("deviceSerialNumber", eventStudy.getDeviceSerial())); currentEvent.add(Restrictions.eq("acquisitionDatetime", eventStudy.getAcquisitionDateTime())); currentEvent.add(Restrictions.sqlRestriction( "event_id = (SELECT max(event_id) FROM ophinbiometry_imported_events WHERE device_serial_number='" + eventStudy.getDeviceSerial() + "' AND acquisition_datetime='" + eventStudy.getAcquisitionDateTime() + "')")); } else if (eventStudy.getDeviceType().equals("IOLM500")) { currentEvent.add(Restrictions.eq("studyId", eventStudy.getStudyInstanceID())); currentEvent.add(Restrictions.eq("seriesId", eventStudy.getSeriesInstanceID())); currentEvent.add(Restrictions.eq("surgeonName", eventStudy.getSurgeonName())); currentEvent.add(Restrictions.sqlRestriction( "event_id = (SELECT max(event_id) FROM ophinbiometry_imported_events WHERE study_id='" + eventStudy.getStudyInstanceID() + "' AND series_id='" + eventStudy.getSeriesInstanceID() + "' AND surgeon_name='" + eventStudy.getSurgeonName() + "')")); } // we should check if event is deleted, and we should create a new one if yes if (!currentEvent.list().isEmpty()) { importedEvent = (OphinbiometryImportedEvents) currentEvent.list().get(0); // if the event is in deleted state we cerate a new record if (importedEvent.getEventId().getDeleted() == 0) { dicomLogger.addToRawOutput("StudyID exists in database, merging with existing event..."); isNewEvent = false; // we decide if the imported file content time is newer then the stored content date if (importedEvent.getContentDateTime() != null) { Calendar lastContentDateTime = new GregorianCalendar(); Calendar studyContentDateTime = new GregorianCalendar(); try { lastContentDateTime .setTime(df.parse(getSQLFormattedDate(importedEvent.getContentDateTime()))); studyContentDateTime .setTime(df.parse(getSQLFormattedDate(eventStudy.getContentDateTime().getTime()))); } catch (ParseException ex) { Logger.getLogger(BiometryFunctions.class.getName()).log(Level.SEVERE, null, ex); } if (studyContentDateTime.after(lastContentDateTime)) { try { importedEvent.setContentDateTime( df.parse(getSQLFormattedDate(eventStudy.getContentDateTime().getTime()))); } catch (ParseException ex) { ex.printStackTrace(); } importedEvent.setIsMerged(true); dicomLogger.addToRawOutput( "Event content date and time is newer then the stored values, updating existing measuerements..."); } } } else { isNewEvent = true; } } if (isNewEvent) { Event newEvent = createNewEvent(); importedEvent = createNewImportedEvent(newEvent); } return importedEvent; }
From source file:org.openbravo.advpaymentmngt.ad_actionbutton.Reconciliation.java
private void processReconciliation(HttpServletResponse response, VariablesSecureApp vars, String strTabId, String strFinancialAccountId, String strDifference, String strStatementDate, String strBeginBalance, String strEndBalance, boolean process) throws IOException, ServletException { log4j.debug(/*from w w w.j av a 2 s . c om*/ "Output: Process or Save button pressed on Financial Account || Transaction || Reconciliation manual window"); dao = new AdvPaymentMngtDao(); OBError msg = new OBError(); OBContext.setAdminMode(); try { FIN_FinancialAccount account = OBDal.getInstance().get(FIN_FinancialAccount.class, strFinancialAccountId); FIN_Reconciliation reconciliation = TransactionsDao.getLastReconciliation(account, "N"); FIN_Reconciliation lastProcessedReconciliation = TransactionsDao.getLastReconciliation(account, "Y"); reconciliation.setEndingBalance(new BigDecimal(strEndBalance)); reconciliation.setTransactionDate(FIN_Utility.getDateTime(strStatementDate)); reconciliation.setEndingDate(FIN_Utility.getDateTime(strStatementDate)); reconciliation.setDocumentStatus("DR"); reconciliation.setProcessed(false); reconciliation.setAPRMProcessReconciliation("P"); reconciliation.setAprmProcessRec("P"); OBDal.getInstance().save(reconciliation); OBDal.getInstance().flush(); if (process) { // Validations String strMessage = ""; boolean raiseException = false; if (new BigDecimal(strDifference).compareTo(BigDecimal.ZERO) != 0) { strMessage = "@APRM_ReconciliationDiscrepancy@" + " " + strDifference; raiseException = true; } Calendar calCurrent = Calendar.getInstance(); calCurrent.setTime(FIN_Utility.getDateTime(strStatementDate)); if (lastProcessedReconciliation != null) { Calendar calLast = Calendar.getInstance(); calLast.setTime(lastProcessedReconciliation.getEndingDate()); if (calCurrent.before(calLast)) { strMessage = "@APRM_ReconcileInFutureOrPast@"; raiseException = true; } } Calendar tomorrow = Calendar.getInstance(); tomorrow.add(Calendar.DATE, 1); tomorrow.setTime(DateUtils.truncate(tomorrow.getTime(), Calendar.DATE)); if (calCurrent.after(tomorrow)) { strMessage = "@APRM_ReconcileInFutureOrPast@"; raiseException = true; } if (raiseException) { msg.setType("Error"); msg.setTitle(Utility.messageBD(this, "Error", vars.getLanguage())); msg.setMessage(Utility.parseTranslation(this, vars, vars.getLanguage(), strMessage)); vars.setMessage(strTabId, msg); msg = null; printPageClosePopUpAndRefreshParent(response, vars); return; } boolean orgLegalWithAccounting = FIN_Utility.periodControlOpened(reconciliation.TABLE_NAME, reconciliation.getId(), reconciliation.TABLE_NAME + "_ID", "LE"); boolean documentEnabled = getDocumentConfirmation(this, reconciliation.getId()); if (documentEnabled && !FIN_Utility.isPeriodOpen(reconciliation.getClient().getId(), AcctServer.DOCTYPE_Reconciliation, reconciliation.getOrganization().getId(), strStatementDate) && orgLegalWithAccounting) { msg.setType("Error"); msg.setTitle(Utility.messageBD(this, "Error", vars.getLanguage())); msg.setMessage( Utility.parseTranslation(this, vars, vars.getLanguage(), "@PeriodNotAvailable@")); vars.setMessage(strTabId, msg); msg = null; printPageClosePopUpAndRefreshParent(response, vars); return; } if (documentEnabled && orgLegalWithAccounting) { String identifier = linesInNotAvailablePeriod(reconciliation.getId()); if (!identifier.equalsIgnoreCase("")) { msg.setType("Error"); msg.setTitle(Utility.messageBD(this, "Error", vars.getLanguage())); msg.setMessage(String.format( Utility.messageBD(this, "APRM_PeriodNotAvailableClearedItem", vars.getLanguage()), identifier)); vars.setMessage(strTabId, msg); msg = null; printPageClosePopUpAndRefreshParent(response, vars); return; } } for (APRM_FinaccTransactionV finacctrxv : reconciliation.getAPRMFinaccTransactionVList()) { if (reconciliation.getEndingDate() .compareTo(finacctrxv.getFinancialAccountTransaction().getTransactionDate()) < 0) { FIN_FinaccTransaction trans = finacctrxv.getFinancialAccountTransaction(); // We set processed to false before changing dates to avoid trigger exception boolean posted = "Y".equals(trans.getPosted()); if (posted) { trans.setPosted("N"); OBDal.getInstance().save(trans); OBDal.getInstance().flush(); } trans.setProcessed(false); OBDal.getInstance().save(trans); OBDal.getInstance().flush(); trans.setTransactionDate(reconciliation.getEndingDate()); trans.setDateAcct(reconciliation.getEndingDate()); OBDal.getInstance().save(trans); OBDal.getInstance().flush(); // We set processed to true afterwards trans.setProcessed(true); OBDal.getInstance().save(trans); OBDal.getInstance().flush(); if (posted) { trans.setPosted("Y"); OBDal.getInstance().save(trans); OBDal.getInstance().flush(); } // Changing dates for accounting entries as well TransactionsDao.updateAccountingDate(trans); } Boolean invoicePaidold = false; if (finacctrxv.getPayment() != null) { for (FIN_PaymentDetail pd : finacctrxv.getPayment().getFINPaymentDetailList()) { for (FIN_PaymentScheduleDetail psd : pd.getFINPaymentScheduleDetailList()) { invoicePaidold = psd.isInvoicePaid(); if (!invoicePaidold) { if ((FIN_Utility .invoicePaymentStatus(finacctrxv.getPayment().getPaymentMethod(), reconciliation.getAccount(), finacctrxv.getPayment().isReceipt()) .equals(finacctrxv.getPayment().getStatus()))) { psd.setInvoicePaid(true); } if (psd.isInvoicePaid()) { FIN_Utility.updatePaymentAmounts(psd); } } } FIN_Utility.updateBusinessPartnerCredit(finacctrxv.getPayment()); } } } reconciliation.setDocumentStatus("CO"); reconciliation.setProcessed(true); reconciliation.setAPRMProcessReconciliation("R"); reconciliation.setAprmProcessRec("R"); OBDal.getInstance().save(reconciliation); OBDal.getInstance().flush(); } String strMessage = "@APRM_ReconciliationNo@" + ": " + reconciliation.getDocumentNo(); msg.setType("Success"); msg.setTitle(Utility.messageBD(this, "Success", vars.getLanguage())); msg.setMessage(Utility.parseTranslation(this, vars, vars.getLanguage(), strMessage)); vars.setMessage(strTabId, msg); msg = null; printPageClosePopUpAndRefreshParent(response, vars); } catch (Exception e) { throw new OBException(e); } finally { OBContext.restorePreviousMode(); } }
From source file:nl.strohalm.cyclos.services.ads.AdImportServiceImpl.java
private void importAd(final AdImport adImport, final int lineNumber, final Map<String, AdCategory> existingAdCategoryMap, final Map<String, ImportedAdCategory> importedAdCategoryMap, final Map<String, CustomField> customFieldMap, final LocalSettings localSettings, final List<String> headers, final List<String> values) { final Map<String, String> customFieldValues = new HashMap<String, String>(); final CalendarConverter dateConverter = localSettings.getRawDateConverter(); final NumberConverter<BigDecimal> numberConverter = localSettings.getNumberConverter(); // Insert the ad ImportedAd ad = new ImportedAd(); ad.setLineNumber(lineNumber);//w ww. j ava 2 s . c o m ad.setImport(adImport); ad.setStatus(ImportedAd.Status.SUCCESS); ad = importedAdDao.insert(ad); ad.setPublicationPeriod(new Period()); ad.setExternalPublication(true); try { ad.setCustomValues(new ArrayList<ImportedAdCustomFieldValue>()); // Process each field. Field names are lowercased to ignore case for (int i = 0; i < headers.size() && i < values.size(); i++) { final String field = StringUtils.trimToEmpty(headers.get(i)).toLowerCase(); final String value = StringUtils.trimToNull(values.get(i)); final boolean valueIsTrue = "true".equalsIgnoreCase(value) || "1".equals(value); if ("owner".equals(field)) { if (value != null) { try { final MemberUser user = (MemberUser) elementService.loadUser(value, RelationshipHelper .nested(User.Relationships.ELEMENT, Element.Relationships.GROUP)); ad.setOwner(user.getMember()); } catch (final Exception e) { ad.setStatus(ImportedAd.Status.INVALID_OWNER); ad.setErrorArgument1(value); } } } else if ("title".equals(field)) { ad.setTitle(value); } else if ("description".equals(field)) { ad.setDescription(value); } else if ("html".equals(field)) { ad.setHtml(valueIsTrue); } else if ("publicationstart".equals(field)) { try { ad.getPublicationPeriod().setBegin(dateConverter.valueOf(value)); } catch (final Exception e) { ad.setStatus(ImportedAd.Status.INVALID_PUBLICATION_START); ad.setErrorArgument1(value); break; } } else if ("publicationend".equals(field)) { try { ad.getPublicationPeriod().setEnd(dateConverter.valueOf(value)); } catch (final Exception e) { ad.setStatus(ImportedAd.Status.INVALID_PUBLICATION_END); ad.setErrorArgument1(value); break; } } else if ("tradetype".equals(field)) { // Only search is handled now, as it's the exception. Later, if it's null, offer is implied if ("search".equalsIgnoreCase(value)) { ad.setTradeType(TradeType.SEARCH); } } else if ("external".equals(field)) { ad.setExternalPublication(valueIsTrue); } else if ("price".equals(field)) { try { ad.setPrice(numberConverter.valueOf(value)); if (BigDecimal.ZERO.equals(ad.getPrice())) { ad.setPrice(null); } } catch (final Exception e) { ad.setStatus(ImportedAd.Status.INVALID_PRICE); ad.setErrorArgument1(value); break; } } else if ("category".equals(field)) { final Object category = handleCategory(ad, value, existingAdCategoryMap, importedAdCategoryMap); if (category instanceof AdCategory) { ad.setExistingCategory((AdCategory) category); } else if (category instanceof ImportedAdCategory) { ad.setImportedCategory((ImportedAdCategory) category); } else if (ad.getStatus() != null) { // The handleCategory may have set the status. Set the argument and leave ad.setErrorArgument1(value); break; } } else if (customFieldMap.containsKey(field)) { // Create a custom field value final ImportedAdCustomFieldValue fieldValue = new ImportedAdCustomFieldValue(); fieldValue.setField(customFieldMap.get(field)); fieldValue.setValue(value); ad.getCustomValues().add(fieldValue); customFieldValues.put(field, value); } else { throw new UnknownColumnException(field); } } // When there was an error, stop processing if (ad.getStatus() != ImportedAd.Status.SUCCESS) { return; } // Validate some data if (ad.getOwner() == null) { ad.setStatus(ImportedAd.Status.MISSING_OWNER); return; } if (ad.getExistingCategory() == null && ad.getImportedCategory() == null) { ad.setStatus(ImportedAd.Status.MISSING_CATEGORY); return; } if (ad.getTitle() == null) { ad.setStatus(ImportedAd.Status.MISSING_TITLE); return; } if (ad.getDescription() == null) { ad.setStatus(ImportedAd.Status.MISSING_DESCRIPTION); return; } // Set some default data final MemberGroupSettings groupSettings = ad.getOwner().getMemberGroup().getMemberSettings(); Calendar begin = ad.getPublicationPeriod().getBegin(); if (begin == null) { // When there's no begin, assume today begin = Calendar.getInstance(); ad.getPublicationPeriod().setBegin(begin); } final Calendar end = ad.getPublicationPeriod().getEnd(); if (end == null) { // Without end, it's a permanent ad // Check whether permanent ads are allowed if (!groupSettings.isEnablePermanentAds()) { ad.setStatus(ImportedAd.Status.MISSING_PUBLICATION_PERIOD); return; } ad.setPermanent(true); } else { // Validate the publication period if (begin.after(end)) { ad.setStatus(ImportedAd.Status.PUBLICATION_BEGIN_AFTER_END); return; } else { // Check the max publication time final TimePeriod maxAdPublicationTime = groupSettings.getMaxAdPublicationTime(); if (!end.before(maxAdPublicationTime.add(begin))) { ad.setStatus(ImportedAd.Status.MAX_PUBLICATION_EXCEEDED); return; } } } if (ad.getTradeType() == null) { ad.setTradeType(TradeType.OFFER); } switch (groupSettings.getExternalAdPublication()) { case DISABLED: ad.setExternalPublication(false); break; case ENABLED: ad.setExternalPublication(true); break; } // Save the custom field values try { adCustomFieldService.saveValues(ad); } catch (final Exception e) { ad.setStatus(ImportedAd.Status.INVALID_CUSTOM_FIELD); if (e instanceof ValidationException) { final ValidationException vex = (ValidationException) e; final Map<String, Collection<ValidationError>> errorsByProperty = vex.getErrorsByProperty(); if (MapUtils.isNotEmpty(errorsByProperty)) { final String fieldName = errorsByProperty.keySet().iterator().next(); ad.setErrorArgument1(fieldName); final String fieldValue = StringUtils.trimToNull(customFieldValues.get(fieldName)); if (fieldValue == null) { // When validation failed and the field is null, it's actually missing ad.setStatus(ImportedAd.Status.MISSING_CUSTOM_FIELD); } else { ad.setErrorArgument2(fieldValue); } } } return; } } catch (final UnknownColumnException e) { throw e; } catch (final Exception e) { ad.setStatus(ImportedAd.Status.UNKNOWN_ERROR); ad.setErrorArgument1(e.toString()); } finally { importedAdDao.update(ad); } }
From source file:com.ecofactor.qa.automation.newapp.service.MockDataServiceImpl.java
/** * Gets the current position./* w ww .j av a 2 s .c o m*/ * * @param thermostatId * the thermostat id * @return the current position */ private int getCurrentPosition(Integer thermostatId) { Thermostat thermostat = findBythermostatId(thermostatId); Calendar current = DateUtil.getCurrentTimeZoneCalendar(thermostat.getTimezone()); int currentPosition = 0; int block = 0; int gap = 0; for (MockJobData jobData : jobDataList) { ++block; if (current.after(jobData.getStart())) { ++currentPosition; } if (current.after(jobData.getEnd())) { if (block == mockJobDataConfig.getInt(testName + MockJobDataConfig.TEST_BLOCKS)) { ++currentPosition; } else { if (currentPosition > gap) { ++gap; } } } } if (gap == currentPosition) { currentPosition = gap * 10; } return currentPosition; }
From source file:net.adamcin.recap.impl.RecapSessionImpl.java
private boolean isNewer(Node src, Node dst) { try {/* w ww . j a va 2s. co m*/ Calendar srcDate = null; Calendar dstDate = null; if ((this.allowLastModifiedProperty) && (src.hasProperty(this.options.getLastModifiedProperty())) && (dst.hasProperty(this.options.getLastModifiedProperty()))) { srcDate = src.getProperty(this.options.getLastModifiedProperty()).getDate(); dstDate = dst.getProperty(this.options.getLastModifiedProperty()).getDate(); } else if ((src.hasProperty(JcrConstants.JCR_LASTMODIFIED)) && (dst.hasProperty(JcrConstants.JCR_LASTMODIFIED))) { srcDate = src.getProperty(JcrConstants.JCR_LASTMODIFIED).getDate(); dstDate = dst.getProperty(JcrConstants.JCR_LASTMODIFIED).getDate(); } return (srcDate == null) || (dstDate == null) || (srcDate.after(dstDate)); } catch (RepositoryException e) { LOGGER.error("Unable to compare dates: {}", e.toString()); } return true; }
From source file:org.kuali.kra.s2s.generator.impl.PHS398FellowshipSupplementalV1_1Generator.java
private BudgetDecimal getNumberOfMonths(Date dateStart, Date dateEnd) { BudgetDecimal monthCount = BudgetDecimal.ZERO; int fullMonthCount = 0; Calendar startDate = Calendar.getInstance(); Calendar endDate = Calendar.getInstance(); startDate.setTime(dateStart);//from ww w.j a va 2 s. c o m endDate.setTime(dateEnd); startDate.clear(Calendar.HOUR); startDate.clear(Calendar.MINUTE); startDate.clear(Calendar.SECOND); startDate.clear(Calendar.MILLISECOND); endDate.clear(Calendar.HOUR); endDate.clear(Calendar.MINUTE); endDate.clear(Calendar.SECOND); endDate.clear(Calendar.MILLISECOND); if (startDate.after(endDate)) { return BudgetDecimal.ZERO; } int startMonthDays = startDate.getActualMaximum(Calendar.DATE) - startDate.get(Calendar.DATE); startMonthDays++; int startMonthMaxDays = startDate.getActualMaximum(Calendar.DATE); BudgetDecimal startMonthFraction = new BudgetDecimal(startMonthDays) .divide(new BudgetDecimal(startMonthMaxDays)); int endMonthDays = endDate.get(Calendar.DATE); int endMonthMaxDays = endDate.getActualMaximum(Calendar.DATE); BudgetDecimal endMonthFraction = new BudgetDecimal(endMonthDays).divide(new BudgetDecimal(endMonthMaxDays)); startDate.set(Calendar.DATE, 1); endDate.set(Calendar.DATE, 1); while (startDate.getTimeInMillis() < endDate.getTimeInMillis()) { startDate.set(Calendar.MONTH, startDate.get(Calendar.MONTH) + 1); fullMonthCount++; } fullMonthCount = fullMonthCount - 1; monthCount = monthCount.add(new BudgetDecimal(fullMonthCount)).add(startMonthFraction) .add(endMonthFraction); return monthCount; }
From source file:com.flyhz.avengers.framework.AvengersAppMaster.java
private void initHbase() { LOG.info("init hbase"); HConnection hConnection = null;//from w ww .ja va 2 s . com HBaseAdmin hbaseAdmin = null; // HTable hVersion = null; HTable hPage = null; HTable hDomain = null; try { hConnection = HConnectionManager.createConnection(hbaseConf); hbaseAdmin = new HBaseAdmin(hConnection); if (hbaseAdmin.tableExists("av_page")) { hbaseAdmin.disableTable("av_page"); hbaseAdmin.deleteTable(Bytes.toBytes("av_page")); HTableDescriptor tableDesc = new HTableDescriptor(TableName.valueOf("av_page")); HColumnDescriptor info = new HColumnDescriptor("info"); HColumnDescriptor preference = new HColumnDescriptor("preference"); tableDesc.addFamily(info); tableDesc.addFamily(preference); hbaseAdmin.createTable(tableDesc); } else { HTableDescriptor tableDesc = new HTableDescriptor(TableName.valueOf("av_page")); HColumnDescriptor info = new HColumnDescriptor("info"); HColumnDescriptor preference = new HColumnDescriptor("preference"); tableDesc.addFamily(info); tableDesc.addFamily(preference); hbaseAdmin.createTable(tableDesc); } if (!hbaseAdmin.tableExists("av_domain")) { HTableDescriptor tableDesc = new HTableDescriptor(TableName.valueOf("av_domain")); HColumnDescriptor preference = new HColumnDescriptor("preference"); tableDesc.addFamily(preference); hbaseAdmin.createTable(tableDesc); } if (!hbaseAdmin.tableExists("av_product")) { HTableDescriptor tableDesc = new HTableDescriptor(TableName.valueOf("av_product")); HColumnDescriptor info = new HColumnDescriptor("info"); HColumnDescriptor preference = new HColumnDescriptor("preference"); tableDesc.addFamily(info); tableDesc.addFamily(preference); hbaseAdmin.createTable(tableDesc); } Configuration configuration = HBaseConfiguration.create(hbaseConf); configuration.setLong("hbase.rpc.timeout", 600000); // Scan configuration.setLong("hbase.client.scanner.caching", 1000); long version = System.currentTimeMillis(); this.version = version; this.domainRootForCrawlSet.clear(); Map<String, Object> context = XConfiguration.getAvengersContext(); hDomain = new HTable(hbaseConf, "av_domain"); for (String root : context.keySet()) { @SuppressWarnings("unchecked") Map<String, Object> domainMap = (Map<String, Object>) context.get(root); Get hDomainGet = new Get(Bytes.toBytes(root)); hDomainGet.addColumn(Bytes.toBytes("preference"), Bytes.toBytes("batchId")); Result result = hDomain.get(hDomainGet); LOG.info("root[{}] result.isEmpty -> {}", root, result == null ? null : result.isEmpty()); if (result != null && !result.isEmpty()) { Cell cell = result.rawCells()[0]; Calendar calendar = Calendar.getInstance(); LOG.info("root[{}] av_domain.version -> ", root, Bytes.toLong(cell.getValueArray())); calendar.setTime(new Date(Bytes.toLong(cell.getValueArray()))); // ? Integer period = (Integer) domainMap.get(XConfiguration.CRAWL_PERIOD); calendar.add(Calendar.HOUR_OF_DAY, period.intValue()); LOG.info("root[{}] calendar -> {},current.version -> {}", calendar.getTimeInMillis(), version); if (calendar.after(new Date(version))) { continue; } } Put avDomainPut = new Put(Bytes.toBytes(root)); // ??version?crawl?info? avDomainPut.add(Bytes.toBytes("preference"), Bytes.toBytes("batchId"), Bytes.toBytes(version)); hDomain.put(avDomainPut); domainRootForCrawlSet.add(root); } } catch (IOException e) { LOG.error("", e); } catch (Throwable e) { LOG.error("", e); } finally { if (hPage != null) { try { hPage.close(); } catch (IOException e) { LOG.error("", e); } } if (hbaseAdmin != null) { try { hbaseAdmin.close(); } catch (IOException e) { LOG.error("", e); } } if (hConnection != null) { try { hConnection.close(); } catch (IOException e) { LOG.error("", e); } } } }
From source file:nl.strohalm.cyclos.services.access.AccessServiceImpl.java
private boolean isBlocked(final Calendar date) { return date != null && date.after(Calendar.getInstance()); }