Search in sources :

Example 21 with DayOfWeek

use of java.time.DayOfWeek in project jdk8u_jdk by JetBrains.

the class TestIsoChronoImpl method test_DayOfWeek_IsoChronology_vsCalendar.

//-----------------------------------------------------------------------
// Verify  ISO Calendar matches java.util.Calendar
// DayOfWeek, WeekOfMonth, WeekOfYear for range
//-----------------------------------------------------------------------
@Test(dataProvider = "RangeVersusCalendar")
public void test_DayOfWeek_IsoChronology_vsCalendar(LocalDate isoStartDate, LocalDate isoEndDate) {
    GregorianCalendar cal = new GregorianCalendar();
    assertEquals(cal.getCalendarType(), "gregory", "Unexpected calendar type");
    LocalDate isoDate = IsoChronology.INSTANCE.date(isoStartDate);
    for (DayOfWeek firstDayOfWeek : DayOfWeek.values()) {
        for (int minDays = 1; minDays <= 7; minDays++) {
            WeekFields weekDef = WeekFields.of(firstDayOfWeek, minDays);
            cal.setFirstDayOfWeek(Math.floorMod(firstDayOfWeek.getValue(), 7) + 1);
            cal.setMinimalDaysInFirstWeek(minDays);
            cal.setTimeZone(TimeZone.getTimeZone("GMT+00"));
            cal.set(Calendar.YEAR, isoDate.get(YEAR));
            cal.set(Calendar.MONTH, isoDate.get(MONTH_OF_YEAR) - 1);
            cal.set(Calendar.DAY_OF_MONTH, isoDate.get(DAY_OF_MONTH));
            // For every date in the range
            while (isoDate.isBefore(isoEndDate)) {
                assertEquals(isoDate.get(DAY_OF_MONTH), cal.get(Calendar.DAY_OF_MONTH), "Day mismatch in " + isoDate + ";  cal: " + cal);
                assertEquals(isoDate.get(MONTH_OF_YEAR), cal.get(Calendar.MONTH) + 1, "Month mismatch in " + isoDate);
                assertEquals(isoDate.get(YEAR_OF_ERA), cal.get(Calendar.YEAR), "Year mismatch in " + isoDate);
                int jdow = Math.floorMod(cal.get(Calendar.DAY_OF_WEEK) - 2, 7) + 1;
                int dow = isoDate.get(weekDef.dayOfWeek());
                assertEquals(jdow, dow, "Calendar DayOfWeek does not match ISO DayOfWeek");
                int jweekOfMonth = cal.get(Calendar.WEEK_OF_MONTH);
                int isoWeekOfMonth = isoDate.get(weekDef.weekOfMonth());
                assertEquals(jweekOfMonth, isoWeekOfMonth, "Calendar WeekOfMonth does not match ISO WeekOfMonth");
                int jweekOfYear = cal.get(Calendar.WEEK_OF_YEAR);
                int weekOfYear = isoDate.get(weekDef.weekOfWeekBasedYear());
                assertEquals(jweekOfYear, weekOfYear, "GregorianCalendar WeekOfYear does not match WeekOfWeekBasedYear");
                int jWeekYear = cal.getWeekYear();
                int weekBasedYear = isoDate.get(weekDef.weekBasedYear());
                assertEquals(jWeekYear, weekBasedYear, "GregorianCalendar getWeekYear does not match YearOfWeekBasedYear");
                int jweeksInWeekyear = cal.getWeeksInWeekYear();
                int weeksInWeekBasedYear = (int) isoDate.range(weekDef.weekOfWeekBasedYear()).getMaximum();
                assertEquals(jweeksInWeekyear, weeksInWeekBasedYear, "length of weekBasedYear");
                isoDate = isoDate.plus(1, ChronoUnit.DAYS);
                cal.add(Calendar.DAY_OF_MONTH, 1);
            }
        }
    }
}
Also used : DayOfWeek(java.time.DayOfWeek) GregorianCalendar(java.util.GregorianCalendar) WeekFields(java.time.temporal.WeekFields) LocalDate(java.time.LocalDate) Test(org.testng.annotations.Test)

Example 22 with DayOfWeek

use of java.time.DayOfWeek in project jgnash by ccavanaugh.

the class UpdateFactory method shouldAutomaticUpdateOccur.

/**
     * Determines if an automatic update is recommended.
     * <p>
     * The current approach is to avoid multiple updates on Saturday or Sunday if one has already occurred.
     * This could be expanded to understand locale rules.
     *
     * @param lastUpdate the last known timestamp for an update to have occurred
     * @return true if an update is recommended
     */
public static boolean shouldAutomaticUpdateOccur(final LocalDateTime lastUpdate) {
    boolean result = true;
    final LocalDate lastDate = LocalDate.from(lastUpdate);
    final DayOfWeek lastDayOfWeek = lastDate.getDayOfWeek();
    if (lastDayOfWeek == DayOfWeek.SATURDAY || lastDayOfWeek == DayOfWeek.SUNDAY) {
        if (LocalDate.now().equals(lastDate) || (LocalDate.now().minusDays(1).equals(lastDate)) && lastDayOfWeek == DayOfWeek.SATURDAY) {
            result = false;
        }
    }
    if (result && LocalDate.now().equals(lastDate)) {
        // check for an after hours update
        switch(Locale.getDefault().getCountry()) {
            case "AU":
            case "CA":
            case "HK":
            case "US":
                final ZonedDateTime zdtUS = lastUpdate.atZone(ZoneId.of("UTC").normalized());
                if (zdtUS.getHour() >= 21 && zdtUS.getMinute() > 25) {
                    // 4:25 EST for delayed online sources
                    result = false;
                }
                break;
            case // UK
            "GB":
                final ZonedDateTime zdtUK = lastUpdate.atZone(ZoneId.of("UTC").normalized());
                if (zdtUK.getHour() >= 21 && zdtUK.getMinute() > 55) {
                    // 4:55 EST for delayed online sources
                    result = false;
                }
                break;
            case // India
            "IN":
                final ZonedDateTime zdtIN = lastUpdate.atZone(ZoneId.of("UTC").normalized());
                if (zdtIN.getHour() >= 20 && zdtIN.getMinute() > 55) {
                    // 3:55 EST for delayed online sources
                    result = false;
                }
                break;
            default:
                break;
        }
    }
    return result;
}
Also used : DayOfWeek(java.time.DayOfWeek) ZonedDateTime(java.time.ZonedDateTime) LocalDate(java.time.LocalDate)

Example 23 with DayOfWeek

use of java.time.DayOfWeek in project openremote by openremote.

the class AbstractManagerSetup method addDemoApartmentSceneEnableDisableTimer.

protected void addDemoApartmentSceneEnableDisableTimer(ServerAsset apartment, ServerAsset agent, Scene[] scenes) {
    AssetAttribute enableAllMacro = initProtocolConfiguration(new AssetAttribute("enableSceneTimer"), MacroProtocol.PROTOCOL_NAME).addMeta(new MetaItem(LABEL, Values.create("Enable scene timer")));
    for (Scene scene : scenes) {
        for (DayOfWeek dayOfWeek : DayOfWeek.values()) {
            String sceneAttributeName = scene.attributeName + "Enabled" + dayOfWeek;
            enableAllMacro.getMeta().add(new MacroAction(new AttributeState(new AttributeRef(apartment.getId(), sceneAttributeName), Values.create(true))).toMetaItem());
        }
    }
    enableAllMacro.getMeta().add(new MacroAction(new AttributeState(new AttributeRef(apartment.getId(), "sceneTimerEnabled"), Values.create(true))).toMetaItem());
    agent.addAttributes(enableAllMacro);
    AssetAttribute disableAllMacro = initProtocolConfiguration(new AssetAttribute("disableSceneTimer"), MacroProtocol.PROTOCOL_NAME).addMeta(new MetaItem(LABEL, Values.create("Disable scene timer")));
    for (Scene scene : scenes) {
        for (DayOfWeek dayOfWeek : DayOfWeek.values()) {
            String sceneAttributeName = scene.attributeName + "Enabled" + dayOfWeek;
            disableAllMacro.getMeta().add(new MacroAction(new AttributeState(new AttributeRef(apartment.getId(), sceneAttributeName), Values.create(false))).toMetaItem());
        }
    }
    disableAllMacro.getMeta().add(new MacroAction(new AttributeState(new AttributeRef(apartment.getId(), "sceneTimerEnabled"), Values.create(false))).toMetaItem());
    agent.addAttributes(disableAllMacro);
}
Also used : MacroAction(org.openremote.agent.protocol.macro.MacroAction) DayOfWeek(java.time.DayOfWeek) AssetAttribute(org.openremote.model.asset.AssetAttribute)

Example 24 with DayOfWeek

use of java.time.DayOfWeek in project openremote by openremote.

the class AbstractManagerSetup method linkDemoApartmentWithSceneAgent.

protected void linkDemoApartmentWithSceneAgent(ServerAsset apartment, ServerAsset agent, Scene[] scenes) {
    for (Scene scene : scenes) {
        apartment.addAttributes(new AssetAttribute(scene.attributeName, AttributeType.STRING, Values.create(AttributeExecuteStatus.READY.name())).setMeta(new MetaItem(LABEL, Values.create(scene.attributeLabel)), new MetaItem(ACCESS_RESTRICTED_WRITE, Values.create(true)), new MetaItem(ACCESS_RESTRICTED_READ, Values.create(true)), new MetaItem(EXECUTABLE, Values.create(true)), new MetaItem(AGENT_LINK, new AttributeRef(agent.getId(), scene.attributeName).toArrayValue())), new AssetAttribute(scene.attributeName + "AlarmEnabled", AttributeType.BOOLEAN).setMeta(new MetaItem(LABEL, Values.create(scene.attributeLabel + " alarm enabled")), new MetaItem(ACCESS_RESTRICTED_WRITE, Values.create(true)), new MetaItem(ACCESS_RESTRICTED_READ, Values.create(true)), new MetaItem(META_MACRO_ACTION_INDEX, Values.create(0)), new MetaItem(AGENT_LINK, new AttributeRef(agent.getId(), scene.attributeName).toArrayValue())), new AssetAttribute(scene.attributeName + "TargetTemperature", AttributeType.NUMBER).setMeta(new MetaItem(LABEL, Values.create(scene.attributeLabel + " target temperature")), new MetaItem(ACCESS_RESTRICTED_WRITE, Values.create(true)), new MetaItem(ACCESS_RESTRICTED_READ, Values.create(true)), new MetaItem(META_MACRO_ACTION_INDEX, Values.create(1)), new MetaItem(AGENT_LINK, new AttributeRef(agent.getId(), scene.attributeName).toArrayValue())));
        for (DayOfWeek dayOfWeek : DayOfWeek.values()) {
            // "MONDAY" => "Monday"
            String dayOfWeekLabel = dayOfWeek.name().substring(0, 1) + dayOfWeek.name().substring(1).toLowerCase(Locale.ROOT);
            apartment.addAttributes(new AssetAttribute(scene.attributeName + "Time" + dayOfWeek.name(), AttributeType.STRING).setMeta(new MetaItem(LABEL, Values.create(scene.attributeLabel + " time " + dayOfWeekLabel)), new MetaItem(ACCESS_RESTRICTED_READ, Values.create(true)), new MetaItem(ACCESS_RESTRICTED_WRITE, Values.create(true)), new MetaItem(RULE_STATE, Values.create(true)), new MetaItem(META_TIMER_VALUE_LINK, Values.create(TimerValue.TIME.toString())), new MetaItem(AGENT_LINK, new AttributeRef(agent.getId(), scene.attributeName + dayOfWeek.name()).toArrayValue())), new AssetAttribute(scene.attributeName + "Enabled" + dayOfWeek.name(), AttributeType.BOOLEAN).setMeta(new MetaItem(LABEL, Values.create(scene.attributeLabel + " enabled " + dayOfWeekLabel)), new MetaItem(ACCESS_RESTRICTED_READ, Values.create(true)), new MetaItem(ACCESS_RESTRICTED_WRITE, Values.create(true)), new MetaItem(META_TIMER_VALUE_LINK, Values.create(TimerValue.ENABLED.toString())), new MetaItem(AGENT_LINK, new AttributeRef(agent.getId(), scene.attributeName + dayOfWeek.name()).toArrayValue())));
        }
    }
    apartment.addAttributes(// The scene timer is enabled when the timer protocol starts
    new AssetAttribute("sceneTimerEnabled", AttributeType.BOOLEAN, Values.create(true)).setMeta(new MetaItem(LABEL, Values.create("Scene timer enabled")), new MetaItem(ACCESS_RESTRICTED_READ, Values.create(true)), new MetaItem(SHOW_ON_DASHBOARD, Values.create(true)), new MetaItem(READ_ONLY, Values.create(true))), new AssetAttribute("enableSceneTimer", AttributeType.STRING).setMeta(new MetaItem(LABEL, Values.create("Enable scene timer")), new MetaItem(ACCESS_RESTRICTED_READ, Values.create(true)), new MetaItem(ACCESS_RESTRICTED_WRITE, Values.create(true)), new MetaItem(EXECUTABLE, Values.create(true)), new MetaItem(AGENT_LINK, new AttributeRef(agent.getId(), "enableSceneTimer").toArrayValue())), new AssetAttribute("disableSceneTimer", AttributeType.STRING).setMeta(new MetaItem(LABEL, Values.create("Disable scene timer")), new MetaItem(ACCESS_RESTRICTED_READ, Values.create(true)), new MetaItem(ACCESS_RESTRICTED_WRITE, Values.create(true)), new MetaItem(EXECUTABLE, Values.create(true)), new MetaItem(AGENT_LINK, new AttributeRef(agent.getId(), "disableSceneTimer").toArrayValue())));
}
Also used : DayOfWeek(java.time.DayOfWeek) AssetAttribute(org.openremote.model.asset.AssetAttribute)

Example 25 with DayOfWeek

use of java.time.DayOfWeek in project scylla by bptlab.

the class DateTimeUtils method getTaskTerminationTime.

/**
 * Calculates the relative end time of a task. Consideres timetables of resources instances. If any resource
 * instance is idle, the duration is extended by the idle time.
 *
 * @param timeSpan
 *            the original duration of the task without any interruptions
 * @param presentTime
 *            current simulation time
 * @param tuple
 *            resource instances assigned to the task
 * @param event
 *            source event (for logging purposes)
 * @return the end time of the task
 */
public static TimeInstant getTaskTerminationTime(TimeSpan timeSpan, TimeInstant presentTime, ResourceObjectTuple tuple, ScyllaEvent event) {
    SimulationModel model = (SimulationModel) event.getModel();
    ProcessInstance processInstance = event.getProcessInstance();
    ProcessModel processModel = processInstance.getProcessModel();
    String source = event.getSource();
    String taskName = event.getDisplayName();
    int nodeId = event.getNodeId();
    String processScopeNodeId = SimulationUtils.getProcessScopeNodeId(processModel, nodeId);
    Set<String> resources = new HashSet<String>();
    Set<ResourceObject> resourceObjects = tuple.getResourceObjects();
    for (ResourceObject res : resourceObjects) {
        String resourceName = res.getResourceType() + "_" + res.getId();
        resources.add(resourceName);
    }
    // start
    long duration = timeSpan.getTimeRounded(timeUnit);
    if (duration == 0) {
        return presentTime;
    }
    ZonedDateTime dateTime = DateTimeUtils.getDateTime(presentTime);
    List<TimetableItem> timetable = tuple.getSharedTimetable();
    if (timetable == null) {
        return new TimeInstant(presentTime.getTimeRounded(timeUnit) + duration);
    }
    Integer index = null;
    for (int i = 0; i < timetable.size(); i++) {
        TimetableItem item = timetable.get(i);
        if (isWithin(dateTime, item)) {
            index = i;
            break;
        }
    }
    long timePassed = 0;
    while (timePassed < duration) {
        TimetableItem item = timetable.get(index);
        DayOfWeek untilWeekday = item.getWeekdayTo();
        LocalTime untilTime = item.getEndTime();
        ZonedDateTime dateTimeUntilEnd = getNextOrSameZonedDateTime(dateTime, untilWeekday, untilTime);
        long durationUntilEnd = chronoUnit.between(dateTime, dateTimeUntilEnd);
        long amountToAdd;
        if (timePassed + durationUntilEnd >= duration) {
            // task completes in current timetable item
            amountToAdd = duration - timePassed;
        } else {
            // until end of timetable item
            amountToAdd = durationUntilEnd;
        }
        timePassed += amountToAdd;
        dateTime = dateTime.plus(amountToAdd, chronoUnit);
        if (timePassed + durationUntilEnd < duration) {
            // task is not completed in current timetable item, so jump to the start of the next timetable item
            if (model.isOutputLoggingOn()) {
                // log idle during use
                ResourceStatus status = ResourceStatus.IN_USE_IDLE;
                long timeRelativeToStart = getTimeInstant(dateTime).getTimeRounded(timeUnit);
                ResourceInfo info = new ResourceInfo(timeRelativeToStart, status, processInstance, nodeId);
                for (ResourceObject obj : tuple.getResourceObjects()) {
                    String resourceType = obj.getResourceType();
                    String resourceId = obj.getId();
                    model.addResourceInfo(resourceType, resourceId, info);
                }
                ProcessNodeTransitionType transition = ProcessNodeTransitionType.PAUSE;
                ProcessNodeInfo nodeInfo = new ProcessNodeInfo(nodeId, processScopeNodeId, source, timeRelativeToStart, taskName, resources, transition);
                model.addNodeInfo(processModel, processInstance, nodeInfo);
            }
            index++;
            if (index == timetable.size()) {
                index = 0;
            }
            TimetableItem nextItem = timetable.get(index);
            untilWeekday = nextItem.getWeekdayFrom();
            untilTime = nextItem.getBeginTime();
            dateTime = getNextZonedDateTime(dateTime, untilWeekday, untilTime);
            if (model.isOutputLoggingOn()) {
                // log back to work
                ResourceStatus status = ResourceStatus.IN_USE;
                long timeRelativeToStart = getTimeInstant(dateTime).getTimeRounded(timeUnit);
                ResourceInfo info = new ResourceInfo(timeRelativeToStart, status, processInstance, nodeId);
                for (ResourceObject obj : tuple.getResourceObjects()) {
                    String resourceType = obj.getResourceType();
                    String resourceId = obj.getId();
                    model.addResourceInfo(resourceType, resourceId, info);
                }
                ProcessNodeTransitionType transition = ProcessNodeTransitionType.RESUME;
                ProcessNodeInfo nodeInfo = new ProcessNodeInfo(nodeId, processScopeNodeId, source, timeRelativeToStart, taskName, resources, transition);
                model.addNodeInfo(processModel, processInstance, nodeInfo);
            }
        }
    }
    TimeInstant timeInstant = getTimeInstant(dateTime);
    return timeInstant;
}
Also used : ProcessModel(de.hpi.bpt.scylla.model.process.ProcessModel) ResourceObject(de.hpi.bpt.scylla.simulation.ResourceObject) DayOfWeek(java.time.DayOfWeek) ResourceInfo(de.hpi.bpt.scylla.logger.ResourceInfo) LocalTime(java.time.LocalTime) ProcessNodeInfo(de.hpi.bpt.scylla.logger.ProcessNodeInfo) ZonedDateTime(java.time.ZonedDateTime) ProcessNodeTransitionType(de.hpi.bpt.scylla.logger.ProcessNodeTransitionType) ResourceStatus(de.hpi.bpt.scylla.logger.ResourceStatus) ProcessInstance(de.hpi.bpt.scylla.simulation.ProcessInstance) TimetableItem(de.hpi.bpt.scylla.model.global.resource.TimetableItem) SimulationModel(de.hpi.bpt.scylla.simulation.SimulationModel) TimeInstant(desmoj.core.simulator.TimeInstant) HashSet(java.util.HashSet)

Aggregations

DayOfWeek (java.time.DayOfWeek)27 LocalDate (java.time.LocalDate)10 Test (org.testng.annotations.Test)9 Month (java.time.Month)8 LocalTime (java.time.LocalTime)7 TimetableItem (de.hpi.bpt.scylla.model.global.resource.TimetableItem)5 ZonedDateTime (java.time.ZonedDateTime)4 LocalDateTime (java.time.LocalDateTime)3 DateTimeFormatter (java.time.format.DateTimeFormatter)2 WeekFields (java.time.temporal.WeekFields)2 ArrayList (java.util.ArrayList)2 List (java.util.List)2 Locale (java.util.Locale)2 Map (java.util.Map)2 TimeUnit (java.util.concurrent.TimeUnit)2 AssetAttribute (org.openremote.model.asset.AssetAttribute)2 ScyllaValidationException (de.hpi.bpt.scylla.exception.ScyllaValidationException)1 ProcessNodeInfo (de.hpi.bpt.scylla.logger.ProcessNodeInfo)1 ProcessNodeTransitionType (de.hpi.bpt.scylla.logger.ProcessNodeTransitionType)1 ResourceInfo (de.hpi.bpt.scylla.logger.ResourceInfo)1