<commit_before>/*
 * Copyright 2014 jmrozanec
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * http://www.apache.org/licenses/LICENSE-2.0
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.cronutils.model.time;

import com.cronutils.mapper.WeekDay;
import com.cronutils.model.definition.CronDefinition;
import com.cronutils.model.field.CronField;
import com.cronutils.model.field.CronFieldName;
import com.cronutils.model.field.constraint.FieldConstraintsBuilder;
import com.cronutils.model.field.definition.DayOfWeekFieldDefinition;
import com.cronutils.model.field.expression.Always;
import com.cronutils.model.field.expression.QuestionMark;
import com.cronutils.model.time.generator.FieldValueGenerator;
import com.cronutils.model.time.generator.FieldValueGeneratorFactory;
import com.cronutils.model.time.generator.NoSuchValueException;
import com.cronutils.utils.Preconditions;
import com.cronutils.utils.VisibleForTesting;

import java.time.*;
import java.time.temporal.ChronoField;
import java.time.temporal.ChronoUnit;
import java.time.temporal.TemporalField;
import java.time.temporal.TemporalUnit;
import java.util.HashSet;
import java.util.List;
import java.util.Optional;
import java.util.Set;
import java.util.stream.Collectors;
import java.util.stream.Stream;

import static com.cronutils.model.field.CronFieldName.*;
import static com.cronutils.model.field.value.SpecialChar.QUESTION_MARK;
import static com.cronutils.model.time.generator.FieldValueGeneratorFactory.*;
import static com.cronutils.utils.Predicates.not;
import static java.time.temporal.ChronoUnit.DAYS;
import static java.time.temporal.ChronoUnit.SECONDS;
import static java.time.temporal.TemporalAdjusters.lastDayOfMonth;

/**
 * Calculates execution time given a cron pattern.
 */
public class SingleExecutionTime implements ExecutionTime {
    private static final int MAX_ITERATIONS = 100_000;

    private static final LocalTime MAX_SECONDS = LocalTime.MAX.truncatedTo(SECONDS);

    private final CronDefinition cronDefinition;
    private final FieldValueGenerator yearsValueGenerator;
    private final CronField daysOfWeekCronField;
    private final CronField daysOfMonthCronField;
    private final CronField daysOfYearCronField;

    private final TimeNode months;
    private final TimeNode hours;
    private final TimeNode minutes;
    private final TimeNode seconds;

    @VisibleForTesting
    SingleExecutionTime(final CronDefinition cronDefinition, final CronField yearsValueCronField, final CronField daysOfWeekCronField,
            final CronField daysOfMonthCronField, final CronField daysOfYearCronField, final TimeNode months, final TimeNode hours,
            final TimeNode minutes, final TimeNode seconds) {
        this.cronDefinition = Preconditions.checkNotNull(cronDefinition);
        if(cronDefinition.containsFieldDefinition(CronFieldName.YEAR)){
            if(!cronDefinition.getFieldDefinition(CronFieldName.YEAR).isOptional()){
                Preconditions.checkNotNull(yearsValueCronField);
            }
            this.yearsValueGenerator = (yearsValueCronField == null)
                    ? FieldValueGeneratorFactory.forCronField(new CronField(CronFieldName.YEAR, Always.always(),
                    cronDefinition.getFieldDefinition(CronFieldName.YEAR).getConstraints()))
                    : createYearValueGeneratorInstance(yearsValueCronField);
        } else {
            this.yearsValueGenerator = FieldValueGeneratorFactory.forCronField(new CronField(CronFieldName.YEAR, Always.always(),
                    FieldConstraintsBuilder.instance().createConstraintsInstance()));
        }
        this.daysOfWeekCronField = Preconditions.checkNotNull(daysOfWeekCronField);
        this.daysOfMonthCronField = Preconditions.checkNotNull(daysOfMonthCronField);
        this.daysOfYearCronField = daysOfYearCronField;
        this.months = Preconditions.checkNotNull(months);
        this.hours = Preconditions.checkNotNull(hours);
        this.minutes = Preconditions.checkNotNull(minutes);
        this.seconds = Preconditions.checkNotNull(seconds);
    }

    /**
     * Provide nearest date for next execution.
     *
     * @param date - ZonedDateTime instance. If null, a NullPointerException will be raised.
     * @return Optional ZonedDateTime instance, never null. Contains next execution time or empty.
     */
    public Optional<ZonedDateTime> nextExecution(final ZonedDateTime date) {
        Preconditions.checkNotNull(date);
        try {
            ZonedDateTime nextMatch = nextClosestMatch(date);
            if (nextMatch.equals(date)) {
                nextMatch = nextClosestMatch(date.plusSeconds(1));

                if (nextMatch.getOffset().compareTo(date.getOffset()) > 0) {
                    // daylight saving time overlap case: issue #446
                    ZonedDateTime nextNextExecution = nextClosestMatch(nextMatch.plusSeconds(1));

                    boolean lessFrequentThan1Hour = (Duration.between(nextMatch, nextNextExecution).toHours() > 1);
                    if (lessFrequentThan1Hour) {
                        // Avoid duplicate execution during DST overlap
                        nextMatch = nextClosestMatch(date.plusSeconds(1).plusHours(1));
                    }
                }
            }
            return Optional.of(nextMatch);
        } catch (final NoSuchValueException e) {
            return Optional.empty();
        }
    }

    /**
     * If date is not match, will return next closest match.
     * If date is match, will return this date.
     *
     * @param date - reference ZonedDateTime instance - never null;
     * @return ZonedDateTime instance, never null. Value obeys logic specified above.
     * @throws NoSuchValueException if there is no potential next year
     */
    private ZonedDateTime nextClosestMatch(final ZonedDateTime date) throws NoSuchValueException {
        ExecutionTimeResult result = new ExecutionTimeResult(date, false);<commit_msg>fixed #503 - DST overlap check iff next next execution exists<commit_after>/*
 * Copyright 2014 jmrozanec
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * http://www.apache.org/licenses/LICENSE-2.0
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.cronutils.model.time;

import com.cronutils.mapper.WeekDay;
import com.cronutils.model.definition.CronDefinition;
import com.cronutils.model.field.CronField;
import com.cronutils.model.field.CronFieldName;
import com.cronutils.model.field.constraint.FieldConstraintsBuilder;
import com.cronutils.model.field.definition.DayOfWeekFieldDefinition;
import com.cronutils.model.field.expression.Always;
import com.cronutils.model.field.expression.QuestionMark;
import com.cronutils.model.time.generator.FieldValueGenerator;
import com.cronutils.model.time.generator.FieldValueGeneratorFactory;
import com.cronutils.model.time.generator.NoSuchValueException;
import com.cronutils.utils.Preconditions;
import com.cronutils.utils.VisibleForTesting;

import java.time.*;
import java.time.temporal.ChronoField;
import java.time.temporal.ChronoUnit;
import java.time.temporal.TemporalField;
import java.time.temporal.TemporalUnit;
import java.util.HashSet;
import java.util.List;
import java.util.Optional;
import java.util.Set;
import java.util.stream.Collectors;
import java.util.stream.Stream;

import static com.cronutils.model.field.CronFieldName.*;
import static com.cronutils.model.field.value.SpecialChar.QUESTION_MARK;
import static com.cronutils.model.time.generator.FieldValueGeneratorFactory.*;
import static com.cronutils.utils.Predicates.not;
import static java.time.temporal.ChronoUnit.DAYS;
import static java.time.temporal.ChronoUnit.SECONDS;
import static java.time.temporal.TemporalAdjusters.lastDayOfMonth;

/**
 * Calculates execution time given a cron pattern.
 */
public class SingleExecutionTime implements ExecutionTime {
    private static final int MAX_ITERATIONS = 100_000;

    private static final LocalTime MAX_SECONDS = LocalTime.MAX.truncatedTo(SECONDS);

    private final CronDefinition cronDefinition;
    private final FieldValueGenerator yearsValueGenerator;
    private final CronField daysOfWeekCronField;
    private final CronField daysOfMonthCronField;
    private final CronField daysOfYearCronField;

    private final TimeNode months;
    private final TimeNode hours;
    private final TimeNode minutes;
    private final TimeNode seconds;

    @VisibleForTesting
    SingleExecutionTime(final CronDefinition cronDefinition, final CronField yearsValueCronField, final CronField daysOfWeekCronField,
            final CronField daysOfMonthCronField, final CronField daysOfYearCronField, final TimeNode months, final TimeNode hours,
            final TimeNode minutes, final TimeNode seconds) {
        this.cronDefinition = Preconditions.checkNotNull(cronDefinition);
        if(cronDefinition.containsFieldDefinition(CronFieldName.YEAR)){
            if(!cronDefinition.getFieldDefinition(CronFieldName.YEAR).isOptional()){
                Preconditions.checkNotNull(yearsValueCronField);
            }
            this.yearsValueGenerator = (yearsValueCronField == null)
                    ? FieldValueGeneratorFactory.forCronField(new CronField(CronFieldName.YEAR, Always.always(),
                    cronDefinition.getFieldDefinition(CronFieldName.YEAR).getConstraints()))
                    : createYearValueGeneratorInstance(yearsValueCronField);
        } else {
            this.yearsValueGenerator = FieldValueGeneratorFactory.forCronField(new CronField(CronFieldName.YEAR, Always.always(),
                    FieldConstraintsBuilder.instance().createConstraintsInstance()));
        }
        this.daysOfWeekCronField = Preconditions.checkNotNull(daysOfWeekCronField);
        this.daysOfMonthCronField = Preconditions.checkNotNull(daysOfMonthCronField);
        this.daysOfYearCronField = daysOfYearCronField;
        this.months = Preconditions.checkNotNull(months);
        this.hours = Preconditions.checkNotNull(hours);
        this.minutes = Preconditions.checkNotNull(minutes);
        this.seconds = Preconditions.checkNotNull(seconds);
    }

    /**
     * Provide nearest date for next execution.
     *
     * @param date - ZonedDateTime instance. If null, a NullPointerException will be raised.
     * @return Optional ZonedDateTime instance, never null. Contains next execution time or empty.
     */
    public Optional<ZonedDateTime> nextExecution(final ZonedDateTime date) {
        Preconditions.checkNotNull(date);
        try {
            ZonedDateTime nextMatch = nextClosestMatch(date);
            if (nextMatch.equals(date)) {
                nextMatch = nextClosestMatch(date.plusSeconds(1));

                if (nextMatch.getOffset().compareTo(date.getOffset()) > 0) {
                    // daylight saving time overlap case: issue #446
                    Optional<ZonedDateTime> nextNextExecution = Optional.empty();
                    try {
                        nextNextExecution = Optional.of(nextClosestMatch(nextMatch.plusSeconds(1)));
                    }
                    catch (final NoSuchValueException canBeIgnored) {}

                    if (nextNextExecution.isPresent()) {
                        final boolean lessFrequentThan1Hour = (Duration.between(nextMatch, nextNextExecution.get()).toHours() > 1);
                        if (lessFrequentThan1Hour) {
                            // Avoid duplicate execution during DST overlap
                            nextMatch = nextClosestMatch(date.plusSeconds(1).plusHours(1));
                        }
                    }
                }
            }
            return Optional.of(nextMatch);
        }
        catch (final NoSuchValueException e) {
            return Optional.empty();
        }
    }

    /**
     * If date is not match, will return next closest match.
     * If date is match, will return this date.
     *
     * @param date - reference ZonedDateTime instance - never null;
     * @return ZonedDateTime instance, never null. Value obeys logic specified above.
     * @throws NoSuchValueException if there is no potential next year
     */
    private ZonedDateTime nextClosestMatch(final ZonedDateTime date) throws NoSuchValueException {
        ExecutionTimeResult result = new ExecutionTimeResult(date, false);
{'fraction_non_alphanumeric': 0.07819274359169393, 'fraction_numerical': 0.004031337947820795, 'mean_word_length': 3.394385026737968, 'pattern_counts': {'":': 0, '<': 6, '<?xml version=': 0, '>': 10, 'https://': 0, 'lorem ipsum': 0, 'www.': 2, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '6035669', 'n_tokens_mistral': 3563, 'n_tokens_neox': 3381, 'n_words': 836}