Example usage for org.apache.commons.lang.time DateUtils isSameDay

List of usage examples for org.apache.commons.lang.time DateUtils isSameDay

Introduction

In this page you can find the example usage for org.apache.commons.lang.time DateUtils isSameDay.

Prototype

public static boolean isSameDay(Calendar cal1, Calendar cal2) 

Source Link

Document

Checks if two calendar objects are on the same day ignoring time.

28 Mar 2002 13:45 and 28 Mar 2002 06:01 would return true.

Usage

From source file:de.hybris.platform.b2bacceleratorfacades.order.impl.DefaultB2BCheckoutFacade.java

@Override
public ScheduledCartData scheduleOrder(final TriggerData trigger) {
    final CartModel cartModel = getCart();
    cartModel.setSite(getBaseSiteService().getCurrentBaseSite());
    cartModel.setStore(getBaseStoreService().getCurrentBaseStore());
    getModelService().save(cartModel);//from   ww  w . j  a  v  a  2 s. co m

    final AddressModel deliveryAddress = cartModel.getDeliveryAddress();
    final AddressModel paymentAddress = cartModel.getPaymentAddress();
    final PaymentInfoModel paymentInfo = cartModel.getPaymentInfo();
    final TriggerModel triggerModel = getModelService().create(TriggerModel.class);
    getTriggerPopulator().populate(trigger, triggerModel);

    // If Trigger is not relative, reset activeDate to next expected runtime
    if (BooleanUtils.isFalse(triggerModel.getRelative())) {
        // getNextTime(relavtiveDate) will skip the date, to avoid skipping the activation date, go back 1 day to test.
        final Calendar priorDayCalendar = Calendar.getInstance();
        priorDayCalendar.setTime(DateUtils.addDays(triggerModel.getActivationTime(), -1));

        final Date nextPotentialFire = triggerService.getNextTime(triggerModel, priorDayCalendar).getTime();

        if (!DateUtils.isSameDay(nextPotentialFire, triggerModel.getActivationTime())) {
            // Adjust activation time to next scheduled vis a vis the cron expression
            triggerModel.setActivationTime(nextPotentialFire);
        }
    }
    // schedule cart
    final CartToOrderCronJobModel scheduledCart = getScheduleOrderService().createOrderFromCartCronJob(
            cartModel, deliveryAddress, paymentAddress, paymentInfo, Collections.singletonList(triggerModel));

    ScheduledCartData scheduledCartData = null;
    if (scheduledCart != null) {
        scheduledCartData = getScheduledCartConverter().convert(scheduledCart);
        getCartService().removeSessionCart();
        // trigger an email.
        getEventService().publishEvent(initializeReplenishmentPlacedEvent(scheduledCart));
    }

    return scheduledCartData;
}

From source file:com.gumtreescraper.scraper.GumtreeScraper.java

private boolean needToScrapeNextPage(String dateStr) {
    Date today = new Date();
    if (DateUtils.isSameDay(today, lastEditedDate)) { // check why lastEditedDate is null
        if (dateStr.toLowerCase().contains("minutes") || dateStr.toLowerCase().contains("hours")) {
            return true;
        }/* w  w  w.ja va  2 s . co m*/

        if (dateStr.toLowerCase().contains("yesterday")) {
            return false;
        }
    }

    Calendar cal = Calendar.getInstance();
    cal.setTime(today);
    cal.add(Calendar.DAY_OF_YEAR, -1);
    Date yesterday = cal.getTime();

    if (DateUtils.isSameDay(yesterday, lastEditedDate)) {
        if (dateStr.toLowerCase().contains("yesterday")) {
            return true;
        }
    }

    Date d = GumtreeUtils.convertStringToDate(dateStr);
    if (d == null) {
        return false;
    }

    return DateUtils.isSameDay(d, lastEditedDate);

    //        return true;
}

From source file:de.hybris.platform.b2b.services.impl.B2BMerchantCheckTest.java

@Test
@Ignore("breaks in https://bamboo.hybris.com/download/HYBRISACCELERATORR-B2BACCELERATOR-BUILD, the test needs to be refactored.")
public void shouldTriggerCreditAlertOnceForTimePeriod() throws Exception {
    /**// w  w w.java 2s.  co  m
     * Create and order between 8000 - 10000 EUR for unit GC Sales DE Alert should be created for GC Sales Rep
     */

    login("GC Sales DE Boss");

    final OrderModel order = createOrder("GC Sales DE Boss", 900, OrderStatus.CREATED);
    b2bCartService.removeSessionCart();
    Assert.assertNotNull(order);

    //Set up credit limit data for test - should not have alert sent date
    final B2BUnitModel unitLoggedIn = b2bUnitService.getUnitForUid("GC Sales DE");
    final B2BCreditLimitModel creditLimit = unitLoggedIn.getCreditLimit();
    creditLimit.setActive(Boolean.TRUE);
    creditLimit.setDateRange(B2BPeriodRange.DAY);
    creditLimit.setAmount(BigDecimal.valueOf(10000D));
    creditLimit.setAlertThreshold(BigDecimal.valueOf(8000D));
    creditLimit.setDatePeriod(null);
    creditLimit.setAlertSentDate(null);
    modelService.save(creditLimit);

    final B2BApprovalProcessModel b2bApprovalProcessModel = getB2BApprovalProcessModelForOrder(order);
    this.waitForProcessToEnd(b2bApprovalProcessModel.getCode(), 20000);
    this.modelService.refresh(order);
    this.modelService.refresh(b2bApprovalProcessModel);
    Assert.assertEquals(OrderStatus.APPROVED, order.getStatus());
    Assert.assertEquals(ProcessState.SUCCEEDED, b2bApprovalProcessModel.getProcessState());
    //Check Alert Sent Date exist now
    modelService.refresh(creditLimit);
    Assert.assertNotNull("AlertSendDate should have been set", creditLimit.getAlertSentDate());

    // create a second order 100 total against the same cost center which makes the orders total of 9010 for the credit limit
    //the order still  exceeds Alert Limit (8000) but the total of all orders is below credit limit (1000)

    final OrderModel order2 = createOrder("GC Sales DE Boss", 10, OrderStatus.CREATED);
    Assert.assertNotNull(order2);

    final B2BApprovalProcessModel b2bApprovalProcessModel2 = getB2BApprovalProcessModelForOrder(order2);
    this.waitForProcessToEnd(b2bApprovalProcessModel2.getCode(), 20000);
    this.modelService.refresh(order2);
    this.modelService.refresh(b2bApprovalProcessModel2);
    Assert.assertEquals(OrderStatus.APPROVED, order2.getStatus());
    Assert.assertEquals(ProcessState.SUCCEEDED, b2bApprovalProcessModel2.getProcessState());

    //Alert Sent Date was in past, so it's updated with Current Date
    modelService.refresh(creditLimit);

    Assert.assertNotNull("AlertSentDate should not be null", creditLimit.getAlertSentDate());
    Assert.assertTrue(String.format("AlertSentDate %s shold be in the same day as %s",
            creditLimit.getAlertSentDate(), new Date()),
            DateUtils.isSameDay(creditLimit.getAlertSentDate(), new Date()));

}

From source file:ch.algotrader.service.CalendarServiceImpl.java

/**
 * gets the holiday for this date/*from ww w  . j  a va2s  . com*/
 */
private Holiday getHoliday(final Exchange exchange, final Date dateTime) {

    Validate.notNull(exchange, "exchange not found");
    Validate.notNull(dateTime, "dateTime is null");

    final Date date = DateUtils.truncate(dateTime, Calendar.DATE);

    return CollectionUtils.find(exchange.getHolidays(), new Predicate<Holiday>() {

        @Override
        public boolean evaluate(Holiday holiday) {
            return DateUtils.isSameDay(holiday.getDate(), date);
        }
    });
}

From source file:net.audumla.climate.bom.BOMSimpleHistoricalClimateObserver.java

public boolean supportsDate(Date date) {
    return !invalidMonths.contains(Time.getMonthAndYear(date))
            && (date.before(Time.getToday()) || DateUtils.isSameDay(date, Time.getToday()));
}

From source file:com.cubusmail.gwtui.server.services.MailboxService.java

public GWTMessageList retrieveMessages(String folderId, int start, int pageSize, String sortField, String dir,
        String[][] params) throws Exception {

    if (folderId != null) {
        IMailbox mailbox = SessionManager.get().getMailbox();
        UserAccount account = SessionManager.get().getUserAccount();
        log.debug("retrieving messages from " + folderId + " ...");

        try {/*from  www .  jav  a2  s . c o  m*/
            IMailFolder currentFolder = mailbox.getMailFolderById(folderId);
            mailbox.setCurrentFolder(currentFolder);

            Message[] msgs = currentFolder.retrieveMessages(sortField);

            String quickSearchFields = MessageUtils.getParamValue(params, "fields");
            String extendedSearchFields = MessageUtils.getParamValue(params,
                    GWTMailConstants.EXTENDED_SEARCH_FIELDS);

            // all messages with only header data

            // quick search params
            if (quickSearchFields != null) {
                String quickSearchText = MessageUtils.getParamValue(params, "query");
                msgs = MessageUtils.quickFilterMessages(msgs, quickSearchFields, quickSearchText);
            } else if (extendedSearchFields != null) {
                msgs = MessageUtils.filterMessages(currentFolder, msgs, extendedSearchFields, params);
            }

            boolean ascending = "ASC".equals(dir);
            MessageUtils.sortMessages(msgs, sortField, ascending);

            if (msgs != null && msgs.length > 0) {
                log.debug("Building Array objects...");
                long time = System.currentTimeMillis();

                int total_count = msgs.length;
                start = Math.min(total_count - 1, start == -1 ? 0 : start);
                pageSize = pageSize == -1 ? account.getPreferences().getPageCount() : pageSize;
                pageSize = Math.min(pageSize, total_count - start);

                Message[] pagedMessages = new Message[pageSize];
                int pagedIndex = 0;
                for (int msgIndex = start; msgIndex < start + pageSize; msgIndex++) {
                    pagedMessages[pagedIndex++] = msgs[msgIndex];
                }
                FetchProfile completeProfile = MessageUtils.createFetchProfile(true, null);
                currentFolder.fetch(pagedMessages, completeProfile);

                String[][] messageStringArray = new String[pageSize][MessageListFields.values().length];
                Preferences preferences = SessionManager.get().getPreferences();

                // get date formats for message list date
                Locale locale = SessionManager.get().getLocale();
                TimeZone timezone = SessionManager.get().getTimeZone();
                String datePattern = this.applicationContext
                        .getMessage(CubusConstants.MESSAGELIST_DATE_FORMAT_PATTERN, null, locale);
                String timePattern = this.applicationContext
                        .getMessage(CubusConstants.MESSAGELIST_TIME_FORMAT_PATTERN, null, locale);

                NumberFormat sizeFormat = MessageUtils.createSizeFormat(locale);

                DateFormat dateFormat = null;
                DateFormat timeFormat = null;
                if (preferences.isShortTimeFormat()) {
                    dateFormat = new SimpleDateFormat(datePattern, locale);
                    timeFormat = new SimpleDateFormat(timePattern, locale);
                    timeFormat.setTimeZone(timezone);
                } else {
                    dateFormat = new SimpleDateFormat(datePattern + " " + timePattern, locale);
                }
                dateFormat.setTimeZone(timezone);
                Date today = Calendar.getInstance(timezone).getTime();

                for (int i = 0; i < pageSize; i++) {
                    if (preferences.isShortTimeFormat()
                            && DateUtils.isSameDay(today, pagedMessages[i].getSentDate())) {
                        // show only time
                        ConvertUtil.convertToStringArray(currentFolder, pagedMessages[i], messageStringArray[i],
                                timeFormat, sizeFormat);
                    } else {
                        ConvertUtil.convertToStringArray(currentFolder, pagedMessages[i], messageStringArray[i],
                                dateFormat, sizeFormat);
                    }
                }
                log.debug("..finish. Time for building Array: " + (System.currentTimeMillis() - time));

                return new GWTMessageList(messageStringArray, msgs.length);
            }

            return null;
        } catch (MessagingException e) {
            log.error(e.getMessage(), e);
            throw new GWTMessageException(e.getMessage());
        }
    } else {
        return null;
    }
}

From source file:com.cubusmail.mail.util.MessageUtils.java

/**
 * Filter the messages.//  w  w  w.  j  a  v  a 2s.  c om
 * 
 * @param msgs
 * @param searchFields
 * @param searchText
 * @return
 */
public static Message[] quickFilterMessages(Message[] msgs, String searchFields, String searchText) {

    if (!StringUtils.isEmpty(searchFields) && !StringUtils.isEmpty(searchText)) {
        searchFields = StringUtils.remove(searchFields, '[');
        searchFields = StringUtils.remove(searchFields, ']');
        searchFields = StringUtils.remove(searchFields, '\"');
        String[] fields = StringUtils.split(searchFields, ',');
        List<Message> filteredMsgs = new ArrayList<Message>();

        Date searchDate = null;
        try {
            searchDate = DateUtils.parseDate(searchText, new String[] { "dd.MM.yyyy" });
        } catch (Exception e) {
            // do nothing
        }

        try {
            for (Message message : msgs) {
                boolean contains = false;
                for (String searchField : fields) {
                    if (MessageListFields.SUBJECT.name().equals(searchField)) {
                        String subject = message.getSubject();
                        contains = StringUtils.containsIgnoreCase(subject, searchText);
                    } else if (MessageListFields.FROM.name().equals(searchField)) {
                        String from = MessageUtils.getMailAdressString(message.getFrom(),
                                AddressStringType.COMPLETE);
                        contains = StringUtils.containsIgnoreCase(from, searchText) || contains;
                    } else if (searchDate != null && MessageListFields.DATE.name().equals(searchField)) {
                        Date sendDate = message.getSentDate();
                        contains = (sendDate != null && DateUtils.isSameDay(searchDate, sendDate)) || contains;
                    }
                }
                if (contains) {
                    filteredMsgs.add(message);
                }
            }
        } catch (MessagingException ex) {
            log.warn(ex.getMessage(), ex);
        }

        return filteredMsgs.toArray(new Message[0]);
    }

    return msgs;
}

From source file:gov.nih.nci.firebird.service.protocol.ProtocolServiceBeanTest.java

@Test
public void testApproveRegistration() throws CredentialAlreadyExistsException {
    InvestigatorRegistration registration = RegistrationFactory.getInstance().createInvestigatorRegistration();
    registration.setStatus(RegistrationStatus.ACCEPTED);
    SubInvestigatorRegistration subInvestigatorRegistration = createSubinvestigatorRegistration(registration,
            RegistrationStatus.ACCEPTED);
    bean.approvePacket(registration);/*www  . ja v a2s. c om*/
    assertEquals(RegistrationStatus.APPROVED, registration.getStatus());
    assertEquals(RegistrationStatus.APPROVED, subInvestigatorRegistration.getStatus());
    assertTrue(
            DateUtils.isSameDay(registration.getApprovalDate(), subInvestigatorRegistration.getApprovalDate()));
    checkFormStatuses(registration, APPROVED);
    checkFormStatuses(subInvestigatorRegistration, APPROVED);
    verify(mockSponsorNotificationService).notifyInvestigatorsOfApproval(registration);
}

From source file:com.seajas.search.attender.service.attender.dao.ProfileDAO.java

/**
 * Find all notifiable subscribers from the given profile.
 * //  www .  ja  v  a2  s  .c  om
 * @param calendar
 * @param profile
 * @return List<ProfileSubscriber>
 */
public List<ProfileSubscriber> findNotifiableSubscribers(final Calendar calendar,
        final List<ProfileSubscriber> subscribers) {
    if (!calendar.getTimeZone().getID().equals("UTC"))
        throw new IllegalArgumentException(
                "The given calendar must have a UTC timezone (has " + calendar.getTimeZone().getID() + ")");

    // Calculate the current time in UTC

    Integer currentHour = calendar.get(Calendar.HOUR_OF_DAY), currentMinute = calendar.get(Calendar.MINUTE),
            currentDay = calendar.get(Calendar.DAY_OF_WEEK);
    Date currentTime = new Date(calendar.getTimeInMillis());

    // Return a list of all applicable subscribers for this profile

    List<ProfileSubscriber> result = new ArrayList<ProfileSubscriber>();

    // Find all active profiles' confirmed subscribers whose notification preference fall within the current day and whose time
    // values are greater than or equal to the current hour / minute; then take 7 days for weekly updates, 1 for daily updates,
    // and 1 for weekdays where Saturday / Sunday are excluded

    for (ProfileSubscriber subscriber : subscribers) {
        Integer subscriberDay = subscriber.getNotificationDay(),
                subscriberHour = subscriber.getNotificationHour(),
                subscriberMinute = subscriber.getNotificationMinute();
        Date lastNotification = subscriber.getLastNotification();
        NotificationType subscriberType = subscriber.getNotificationType();

        // Correct for the user-specific timezone

        TimeZone timeZone = TimeZone.getTimeZone(subscriber.getTimeZone());

        // Take leap seconds into account, although we're not so precise to really care

        if (subscriberMinute != null) {
            subscriberMinute -= (int) ((timeZone.getOffset(calendar.getTimeInMillis()) % MILLISECONDS_PER_HOUR)
                    / MILLISECONDS_PER_MINUTE);

            if (subscriberMinute < 0) {
                subscriberMinute += 60;
                subscriberHour--;
            } else if (subscriberMinute > 59) {
                subscriberMinute -= 60;
                subscriberHour++;
            }
        }

        if (subscriberHour != null) {
            subscriberHour -= (int) (timeZone.getOffset(calendar.getTimeInMillis()) / MILLISECONDS_PER_HOUR);

            if (subscriberHour < 0) {
                subscriberHour += 24;

                if (subscriberDay != null)
                    subscriberDay--;
            } else if (subscriberHour > 23) {
                subscriberHour -= 24;

                if (subscriberDay != null)
                    subscriberDay++;
            }
        }

        if (subscriberDay == -1)
            subscriberDay = 6;
        else if (subscriberDay == 7)
            subscriberDay = 0;

        // Now determine the actual applicability (last_notification is stored as a UTC date, so does not need to be converted)

        if (subscriber.getIsConfirmed() && ((subscriberType.equals(NotificationType.Weekly)
                && subscriberDay.equals(currentDay) && subscriberHour <= currentHour
                && subscriberMinute <= currentMinute && dateDifference(lastNotification, currentTime) >= 6)
                || (subscriberType.equals(NotificationType.Weekdays) && currentDay != Calendar.SATURDAY
                        && currentDay != Calendar.SUNDAY && subscriberHour <= currentHour
                        && subscriberMinute <= currentMinute
                        && !DateUtils.isSameDay(lastNotification, currentTime))
                || (subscriberType.equals(NotificationType.Daily) && subscriberHour <= currentHour
                        && subscriberMinute <= currentMinute
                        && !DateUtils.isSameDay(lastNotification, currentTime)))) {
            if (logger.isInfoEnabled())
                logger.info("Adding subscriber '" + subscriber.getUniqueId() + "' with e-mail '"
                        + subscriber.getEmail() + "' to be notified");

            result.add(subscriber);
        } else if (logger.isDebugEnabled()) {
            if (!subscriber.getIsConfirmed())
                logger.debug("Not adding subscriber '" + subscriber.getUniqueId() + "' with e-mail '"
                        + subscriber.getEmail() + "' - not confirmed");
            else if (subscriberType.equals(NotificationType.Direct))
                logger.debug("Not adding subscriber '" + subscriber.getUniqueId() + "' with e-mail '"
                        + subscriber.getEmail()
                        + "' - direct notifications are handled by search-enricher instances");
            else if (subscriberType.equals(NotificationType.Weekly)) {
                if (!subscriberDay.equals(currentDay))
                    logger.debug("Not adding subscriber '" + subscriber.getUniqueId() + "' with e-mail '"
                            + subscriber.getEmail() + "' - weekly notification does not fall on current day");
                if (!(subscriberHour <= currentHour && subscriberMinute <= currentMinute))
                    logger.debug("Not adding subscriber '" + subscriber.getUniqueId() + "' with e-mail '"
                            + subscriber.getEmail() + "' - weekly notification falls outside of current time");
                if (!(dateDifference(lastNotification, currentTime) >= 6))
                    logger.debug("Not adding subscriber '" + subscriber.getUniqueId() + "' with e-mail '"
                            + subscriber.getEmail()
                            + "' - weekly notification difference (in days) smaller than 7");
            } else if (subscriberType.equals(NotificationType.Weekdays)) {
                if (!(currentDay != Calendar.SATURDAY && currentDay != Calendar.SUNDAY))
                    logger.debug("Not adding subscriber '" + subscriber.getUniqueId() + "' with e-mail '"
                            + subscriber.getEmail() + "' - weekday notification does not fall on weekday");
                if (!(subscriberHour <= currentHour && subscriberMinute <= currentMinute))
                    logger.debug("Not adding subscriber '" + subscriber.getUniqueId() + "' with e-mail '"
                            + subscriber.getEmail() + "' - weekday notification falls outside of current time");
                if (DateUtils.isSameDay(lastNotification, currentTime))
                    logger.debug("Not adding subscriber '" + subscriber.getUniqueId() + "' with e-mail '"
                            + subscriber.getEmail()
                            + "' - weekday notification difference indicates a notification has already gone out today");
            } else if (subscriberType.equals(NotificationType.Daily)) {
                if (!(subscriberHour <= currentHour && subscriberMinute <= currentMinute))
                    logger.debug("Not adding subscriber '" + subscriber.getUniqueId() + "' with e-mail '"
                            + subscriber.getEmail() + "' - daily notification falls outside of current time");
                if (DateUtils.isSameDay(lastNotification, currentTime))
                    logger.debug("Not adding subscriber '" + subscriber.getUniqueId() + "' with e-mail '"
                            + subscriber.getEmail()
                            + "' - daily notification difference indicates a notification has already gone out today");
            }
        }
    }

    return result;
}

From source file:fi.vm.sade.organisaatio.business.impl.OrganisaatioBusinessServiceImpl.java

@Override
public void changeOrganisaatioParent(Organisaatio organisaatio, Organisaatio newParent, Date date) {
    // Organisaatiota ei saa siirt nykyisen parentin alle
    if (organisaatio.getParent().getOid().equals(newParent.getOid())) {
        throw new OrganisaatioMoveException("organisation.move.parent.invalid");
    }//from  www.  j  a  va 2s . c  o  m

    // Organisaatiota ei saa siirt vrll hierarkiatasolla olevaan organisaatioon
    checker.checkParentChildHierarchy(organisaatio, newParent);

    // Organisaatiota ei saa siirt lakkautettuun tai poistettuun organisaatioon
    if (newParent.isOrganisaatioPoistettu() != false || OrganisaatioUtil.isPassive(newParent)) {
        throw new OrganisaatioMoveException("organisation.move.parent.invalid");
    }

    OrganisaatioSuhde currentParentRelationship = organisaatioSuhdeDAO.findParentTo(organisaatio.getId(), null);
    currentParentRelationship.setLoppuPvm(date);
    organisaatioSuhdeDAO.update(currentParentRelationship);

    // Luodaan uusi suhde
    // HUOM! Tss pit laittaa organisaatiosuhde "organisaation kautta --> nin parent laskenta pysyy mukana"
    OrganisaatioSuhde parentRelation = new OrganisaatioSuhde();
    parentRelation.setSuhdeTyyppi(OrganisaatioSuhde.OrganisaatioSuhdeTyyppi.HISTORIA);
    parentRelation.setAlkuPvm(date);
    parentRelation.setLoppuPvm(null);
    parentRelation.setChild(organisaatio);
    parentRelation.setParent(newParent);

    // Asetetaan uusi parentsuhde
    organisaatio.getParentSuhteet().add(parentRelation);

    // Organisaatiolla on uusi parent, toimipisteen tapauksessa ollaan uuden oppilaitoksen alla.
    // Lasketaan toimipisteelle uusi opetuspisteen jrjestysnumero ja asetetaan toimipistekoodi.
    // Mahdollinen vanha toimipistekoodi pit lakkauttaa ja luoda uusi koodiston koodi.
    if (OrganisaatioUtil.isToimipiste(organisaatio)) {
        // Vanha toimipistekoodi tarvitaan pit lakkauttaa
        String oldToimipistekoodi = organisaatio.getToimipisteKoodi();

        String opJarjNro = generateOpetuspisteenJarjNro(organisaatio);
        organisaatio.setOpetuspisteenJarjNro(opJarjNro);
        organisaatio.setToimipisteKoodi(calculateToimipisteKoodi(organisaatio));
        parentRelation.setOpetuspisteenJarjNro(opJarjNro);

        Calendar previousDay = Calendar.getInstance();
        previousDay.setTime(date);
        previousDay.add(Calendar.DAY_OF_MONTH, -1);

        // Lakkautetaan vanha opetuspistekoodi (opetuspiste pistetn lakkaamaan piv ennen)
        organisaatioKoodisto.lakkautaKoodi(OrganisaatioKoodisto.KoodistoUri.TOIMIPISTE.uri(),
                oldToimipistekoodi, previousDay.getTime(), true);

        // Pivitetn uusi opetuspistekoodi koodistoon.
        organisaatioKoodisto.paivitaKoodisto(organisaatio, true);
    }

    // Pivitetn suhteet ja indeksointi, jos uusi parent on jo voimassa (date == tnn / aiemmin)
    Date today = new Date();
    if (date.before(today) || DateUtils.isSameDay(date, today)) {
        setParentPath(organisaatio, newParent.getOid());
        organisaatioDAO.update(organisaatio);
        solrIndexer.index(organisaatio);

        updateChildrenRecursive(organisaatio);
    }
}