Example usage for java.time ZoneId systemDefault

List of usage examples for java.time ZoneId systemDefault

Introduction

In this page you can find the example usage for java.time ZoneId systemDefault.

Prototype

public static ZoneId systemDefault() 

Source Link

Document

Gets the system default time-zone.

Usage

From source file:org.silverpeas.core.webapi.reminder.ReminderResource.java

/**
 * Gets the identifier list of possible of durations.
 * <p>// ww  w.j a  v  a  2s.c o m
 * An identifier of a duration is the concatenation about the duration value and the duration
 * unit ({@link TimeUnit}).<br>
 * {@code 15MINUTE} for example.
 * </p>
 * @return a filled list if any, or an empty one if no trigger can be scheduled.
 * @see WebProcess#execute()
 */
@Path("possibledurations/{property}")
@GET
@Produces(MediaType.APPLICATION_JSON)
@SuppressWarnings("ConstantConditions")
public List<String> getPossibleDurations(@PathParam("property") final String contributionProperty) {
    if (getSessionVolatileResourceCacheService().contains(localId, componentInstanceId)) {
        return getPossibleReminders().map(DURATION_IDS).collect(Collectors.toList());
    }
    final ContributionModel model = getContribution().getModel();
    final ZoneId userZoneId = getUserPreferences().getZoneId();
    final ZoneId platformZoneId = ZoneId.systemDefault();
    final Mutable<Boolean> lastMatchOk = Mutable.of(true);
    return getPossibleReminders().filter(r -> {
        if (lastMatchOk.is(false)) {
            return false;
        }
        final ZonedDateTime from = ZonedDateTime.now(userZoneId).plus(r.getLeft(), r.getRight().toChronoUnit());
        final ZonedDateTime dateReference = model.filterByType(contributionProperty, from)
                .matchFirst(Date.class::isAssignableFrom,
                        d -> ZonedDateTime.ofInstant(((Date) d).toInstant(), platformZoneId))
                .matchFirst(OffsetDateTime.class::equals,
                        d -> ((OffsetDateTime) d).atZoneSameInstant(platformZoneId))
                .matchFirst(LocalDate.class::equals,
                        d -> ((LocalDate) d).atStartOfDay(userZoneId).withZoneSameInstant(platformZoneId))
                .matchFirst(LocalDateTime.class::equals, d -> ((LocalDateTime) d).atZone(platformZoneId))
                .matchFirst(ZonedDateTime.class::equals,
                        d -> ((ZonedDateTime) d).withZoneSameInstant(platformZoneId))
                .result().orElse(null);
        lastMatchOk.set(dateReference != null);
        return lastMatchOk.get();
    }).map(DURATION_IDS).collect(Collectors.toList());
}

From source file:org.silverpeas.core.reminder.ContributionReminderUserNotificationTest.java

@SuppressWarnings("unchecked")
@BeforeEach// w  w  w  .java2  s  . c  o m
public void setup(@TestManagedMock ContributionManager contributionManager,
        @TestManagedMock ComponentInstanceRoutingMapProviderByInstance routingMap,
        @TestManagedMock ComponentInstanceRoutingMapProvider routingMapProvider,
        @TestManagedMock ComponentInstanceRoutingMap instanceRoutingMap,
        @TestManagedMock SilverpeasComponentInstanceProvider instanceProvider,
        @Mock SilverpeasComponentInstance componentInstance, @Mock Contribution contribution) {

    when(componentInstance.getName()).thenReturn(COMPONENT_NAME);
    when(instanceProvider.getById(INSTANCE_ID)).thenReturn(Optional.of(componentInstance));
    when(instanceProvider.getComponentName(INSTANCE_ID)).thenReturn(COMPONENT_NAME);

    when(routingMap.getByInstanceId(INSTANCE_ID)).thenReturn(routingMapProvider);
    when(routingMapProvider.absolute()).thenReturn(instanceRoutingMap);
    when(instanceRoutingMap.getPermalink(CONTRIBUTION_IDENTIFIER)).thenReturn(UriBuilder.fromPath("").build());

    UserPreferences userPreferences = new UserPreferences("26", "fr", ZoneId.systemDefault(), null, null, false,
            false, false, UserMenuDisplay.DEFAULT);
    when(receiver.getId()).thenReturn("26");
    when(receiver.getUserPreferences()).thenReturn(userPreferences);

    when(contribution.getContributionId()).thenReturn(CONTRIBUTION_IDENTIFIER);
    when(contribution.getTitle()).thenReturn("super test");
    when(contributionManager.getById(CONTRIBUTION_IDENTIFIER)).thenReturn(Optional.of(contribution));

    when(UserProvider.get().getUser(receiver.getId())).thenReturn(receiver);
    mocker.setField(DisplayI18NHelper.class, Locale.getDefault().getLanguage(), "defaultLanguage");
}

From source file:org.caratarse.auth.model.dao.UserAttributesTest.java

@Test
public void birthdateUserAttribute() {
    User user = retrieveUserWithAttributes();
    Attribute attribute = user.getUserAttributes().get("birthdate");
    assertTrue(attribute instanceof DateAttribute);
    assertThat(attribute.getName(), is("birthdate"));
    final Date value = new Date(((Date) attribute.getValue()).getTime());
    ZonedDateTime v = value.toInstant().atZone(ZoneId.systemDefault());
    assertThat(v.getDayOfMonth(), is(5));
    assertThat(v.getMonthValue(), is(7));
    assertThat(v.getYear(), is(1980));/*from w w  w  . j  a va2s  . c o m*/
}

From source file:alfio.manager.system.DataMigratorIntegrationTest.java

private Pair<Event, String> initEvent(List<TicketCategoryModification> categories, String displayName) {
    String organizationName = UUID.randomUUID().toString();
    String username = UUID.randomUUID().toString();
    String eventName = UUID.randomUUID().toString();

    organizationRepository.create(organizationName, "org", "email@example.com");
    Organization organization = organizationRepository.findByName(organizationName).get();
    userManager.insertUser(organization.getId(), username, "test", "test", "test@example.com", Role.OPERATOR,
            User.Type.INTERNAL);

    Map<String, String> desc = new HashMap<>();
    desc.put("en", "muh description");
    desc.put("it", "muh description");
    desc.put("de", "muh description");

    EventModification em = new EventModification(null, Event.EventType.INTERNAL, "url", "url", "url", null,
            null, eventName, displayName, organization.getId(), "muh location", "0.0", "0.0",
            ZoneId.systemDefault().getId(), desc,
            new DateTimeModification(LocalDate.now().plusDays(5), LocalTime.now()),
            new DateTimeModification(LocalDate.now().plusDays(5), LocalTime.now().plusHours(1)), BigDecimal.TEN,
            "CHF", AVAILABLE_SEATS, BigDecimal.ONE, true, null, categories, false,
            new LocationDescriptor("", "", "", ""), 7, null, null);
    eventManager.createEvent(em);/*from w w w . ja  v  a 2 s.c  o m*/
    return Pair.of(eventManager.getSingleEvent(eventName, username), username);
}

From source file:org.apache.geode.management.internal.cli.commands.ExportLogsDUnitTest.java

@Test
public void testExportWithStartAndEndDateTimeFiltering() throws Exception {
    ZonedDateTime cutoffTime = LocalDateTime.now().atZone(ZoneId.systemDefault());

    String messageAfterCutoffTime = "[this message should not show up since it is after cutoffTime]";
    LogLine logLineAfterCutoffTime = new LogLine(messageAfterCutoffTime, "info", true);
    server1.invoke(() -> {//from  w  w w  .  j ava2 s .com
        Logger logger = LogService.getLogger();
        logLineAfterCutoffTime.writeLog(logger);
    });

    DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern(FORMAT);
    String cutoffTimeString = dateTimeFormatter.format(cutoffTime);

    CommandStringBuilder commandStringBuilder = new CommandStringBuilder("export logs");
    commandStringBuilder.addOption("start-time", dateTimeFormatter.format(cutoffTime.minusDays(1)));
    commandStringBuilder.addOption("end-time", cutoffTimeString);
    commandStringBuilder.addOption("log-level", "debug");

    gfshConnector.executeAndVerifyCommand(commandStringBuilder.toString());

    expectedMessages.get(server1).add(logLineAfterCutoffTime);
    Set<String> acceptedLogLevels = Stream.of("info", "error", "debug").collect(toSet());
    verifyZipFileContents(acceptedLogLevels);
}

From source file:com.seleniumtests.connectors.mails.ImapClient.java

/**
 * get list of all emails in folder//from  ww  w  .  j a  v  a  2s. c  o m
 * 
 * @param folderName      folder to read
 * @param firstMessageTime   date from which we should get messages
 * @param firstMessageIndex index of the firste message to find
 * @throws MessagingException
 * @throws IOException
 */
@Override
public List<Email> getEmails(String folderName, int firstMessageIndex, LocalDateTime firstMessageTime)
        throws MessagingException, IOException {

    if (folderName == null) {
        throw new MessagingException("folder ne doit pas tre vide");
    }

    // Get folder
    Folder folder = store.getFolder(folderName);
    folder.open(Folder.READ_ONLY);

    // Get directory
    Message[] messages = folder.getMessages();

    List<Message> preFilteredMessages = new ArrayList<>();

    final LocalDateTime firstTime = firstMessageTime;

    // on filtre les message en fonction du mode de recherche
    if (searchMode == SearchMode.BY_INDEX || firstTime == null) {
        for (int i = firstMessageIndex, n = messages.length; i < n; i++) {
            preFilteredMessages.add(messages[i]);
        }
    } else {
        preFilteredMessages = Arrays.asList(folder.search(new SearchTerm() {
            private static final long serialVersionUID = 1L;

            @Override
            public boolean match(Message msg) {
                try {
                    return !msg.getReceivedDate()
                            .before(Date.from(firstTime.atZone(ZoneId.systemDefault()).toInstant()));
                } catch (MessagingException e) {
                    return false;
                }
            }
        }));

    }

    List<Email> filteredEmails = new ArrayList<>();
    lastMessageIndex = messages.length;

    for (Message message : preFilteredMessages) {

        String contentType = "";
        try {
            contentType = message.getContentType();
        } catch (MessagingException e) {
            MimeMessage msg = (MimeMessage) message;
            message = new MimeMessage(msg);
            contentType = message.getContentType();
        }

        // decode content
        String messageContent = "";
        List<String> attachments = new ArrayList<>();

        if (contentType.toLowerCase().contains("text/html")) {
            messageContent += StringEscapeUtils.unescapeHtml4(message.getContent().toString());
        } else if (contentType.toLowerCase().contains("multipart/")) {
            List<BodyPart> partList = getMessageParts((Multipart) message.getContent());

            // store content in list
            for (BodyPart part : partList) {

                String partContentType = part.getContentType().toLowerCase();
                if (partContentType.contains("text/html")) {
                    messageContent = messageContent
                            .concat(StringEscapeUtils.unescapeHtml4(part.getContent().toString()));

                } else if (partContentType.contains("text/") && !partContentType.contains("vcard")) {
                    messageContent = messageContent.concat((String) part.getContent().toString());

                } else if (partContentType.contains("image") || partContentType.contains("application/")
                        || partContentType.contains("text/x-vcard")) {
                    if (part.getFileName() != null) {
                        attachments.add(part.getFileName());
                    } else {
                        attachments.add(part.getDescription());
                    }
                } else {
                    logger.debug("type: " + part.getContentType());
                }
            }
        }

        // create a new email
        filteredEmails.add(new Email(message.getSubject(), messageContent, "",
                message.getReceivedDate().toInstant().atZone(ZoneId.systemDefault()).toLocalDateTime(),
                attachments));
    }

    folder.close(false);

    return filteredEmails;
}

From source file:com.buffalokiwi.api.APIDate.java

/**
 * Create a new APIDate set to now.
 * This will use the local system offset
 */
public APIDate() {
    this(Instant.now().atZone(ZoneId.systemDefault()));
}

From source file:com.onyxscheduler.OnyxSchedulerIT.java

private Date toDate(LocalDateTime localDateTime) {
    return Date.from(localDateTime.atZone(ZoneId.systemDefault()).toInstant());
}

From source file:fr.lepellerin.ecole.service.internal.CantineServiceImpl.java

@Override
@Transactional(readOnly = false)/*from   w  w w. j a  v a 2 s .  c  om*/
public String reserver(final LocalDate date, final int individuId, final Famille famille, final Boolean reserve)
        throws FunctionalException, TechnicalException {
    final LocalDateTime heureResa = this.getLimiteResaCantine(date);
    if (!heureResa.isAfter(LocalDateTime.now())) {
        throw new ActNonModifiableException("activite non reservable");
    }
    final Date d = Date.from(Instant.from(date.atStartOfDay(ZoneId.systemDefault())));
    final Activite activite = getCantineActivite();
    final List<Inscription> icts = this.ictRepository.findByActiviteAndFamille(activite, famille);
    final Inscription ict = icts.stream().filter(i -> individuId == i.getIndividu().getId()).findFirst().get();
    final List<Consommation> consos = this.consommationRepository.findByInscriptionActiviteUniteDate(ict,
            activite, ict.getGroupe(), d);
    final Unite unite = this.uniteRepository.findOneByActiviteAndType(ict.getActivite(), "Unitaire");
    if ((reserve == null && consos != null && !consos.isEmpty())
            || (reserve != null && reserve == false && consos != null && !consos.isEmpty())) {
        consos.forEach(c -> this.consommationRepository.delete(c));
        return "libre";
        // on supprime la conso
    } else if ((reserve == null && (consos == null || consos.isEmpty()))
            || (reserve == true && (consos == null || consos.isEmpty()))) {
        // cree la conso
        final Consommation conso = new Consommation();
        conso.setActivite(activite);
        conso.setDate(d);
        conso.setDateSaisie(new Date());
        conso.setEtat("reservation");
        conso.setGroupe(ict.getGroupe());
        conso.setIndividu(ict.getIndividu());
        conso.setInscription(ict);
        conso.setComptePayeur(ict.getComptePayeur());
        conso.setCategorieTarif(ict.getCategorieTarif());
        conso.setUnite(unite);
        conso.setHeureDebut(unite.getHeureDebut());
        conso.setHeureFin(unite.getHeureFin());

        this.consommationRepository.save(conso);
        return "reserve";
    }
    return "rien";

}

From source file:com.orange.clara.cloud.servicedbdumper.task.job.JobFactory.java

@Transactional
public void purgeErroredJobs() {
    LocalDateTime whenRemoveDateTime;
    List<Job> jobs = jobRepo.findByJobEventOrderByUpdatedAtDesc(JobEvent.ERRORED);
    for (Job job : jobs) {
        whenRemoveDateTime = LocalDateTime.from(job.getUpdatedAt().toInstant().atZone(ZoneId.systemDefault()))
                .plusDays(this.jobErroredDeleteExpirationDays);
        if (LocalDateTime.from(Calendar.getInstance().toInstant().atZone(ZoneId.systemDefault()))
                .isBefore(whenRemoveDateTime)) {
            continue;
        }//  www.  j  av  a 2  s .co m
        this.jobRepo.delete(job);
    }
}