Example usage for java.util Date from

List of usage examples for java.util Date from

Introduction

In this page you can find the example usage for java.util Date from.

Prototype

public static Date from(Instant instant) 

Source Link

Document

Obtains an instance of Date from an Instant object.

Usage

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

@Override
@Transactional(readOnly = false)//from w ww  .ja  va 2s.  c o m
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:software.coolstuff.springframework.owncloud.service.impl.rest.OwncloudRestResourceServiceTest.java

private DavResource createDavResourceFrom(OwncloudTestResourceImpl owncloudResource, Locale locale) {
    URI prefixedHref = resolveAsFileURI(owncloudResource.getHref());
    String contentLanguage = Optional.ofNullable(locale).map(loc -> loc.getLanguage()).orElse(null);
    String name = owncloudResource.getBackendName();
    String eTag = owncloudResource.getBackendETag();
    Date davResourceDate = new Date();
    if (owncloudResource.getLastModifiedAt() != null) {
        davResourceDate = Date
                .from(owncloudResource.getLastModifiedAt().atZone(ZoneId.systemDefault()).toInstant());
    }// w ww  .  j a v  a 2s . c o  m
    if (isRoot(owncloudResource.getHref())) {
        eTag = null;
    }
    try {
        return new OwncloudDavResource(prefixedHref.getPath(), davResourceDate, davResourceDate,
                owncloudResource.getMediaType().toString(),
                owncloudResource instanceof OwncloudFileResource
                        ? ((OwncloudFileResource) owncloudResource).getContentLength()
                        : null,
                eTag, name, contentLanguage);
    } catch (URISyntaxException e) {
        throw new IllegalArgumentException("DavResource couldn't be built by OwncloudResource", e);
    }
}

From source file:com.vmware.photon.controller.api.client.resource.ClusterApiTest.java

@Test
public void testResizeAsync() throws IOException, InterruptedException {
    final Task responseTask = new Task();
    responseTask.setId("12345");
    responseTask.setState("QUEUED");
    responseTask.setQueuedTime(Date.from(Instant.now()));

    ObjectMapper mapper = new ObjectMapper();
    String serializedTask = mapper.writeValueAsString(responseTask);

    setupMocks(serializedTask, HttpStatus.SC_CREATED);

    ClusterApi clusterApi = new ClusterApi(restClient);

    final CountDownLatch latch = new CountDownLatch(1);

    clusterApi.resizeAsync("dummy-cluster-id", 100, new FutureCallback<Task>() {
        @Override/*from ww w  .  j a v a2 s  .  c o m*/
        public void onSuccess(Task result) {
            assertEquals(result, responseTask);
            latch.countDown();
        }

        @Override
        public void onFailure(Throwable t) {
            fail(t.toString());
            latch.countDown();
        }
    });

    assertThat(latch.await(COUNTDOWNLATCH_AWAIT_TIMEOUT, TimeUnit.SECONDS), is(true));
}

From source file:com.vmware.photon.controller.api.client.resource.ClusterRestApiTest.java

@Test
public void testResizeAsync() throws IOException, InterruptedException {
    final Task responseTask = new Task();
    responseTask.setId("12345");
    responseTask.setState("QUEUED");
    responseTask.setQueuedTime(Date.from(Instant.now()));

    ObjectMapper mapper = new ObjectMapper();
    String serializedTask = mapper.writeValueAsString(responseTask);

    setupMocks(serializedTask, HttpStatus.SC_CREATED);

    ClusterApi clusterApi = new ClusterRestApi(restClient);

    final CountDownLatch latch = new CountDownLatch(1);

    clusterApi.resizeAsync("dummy-cluster-id", 100, new FutureCallback<Task>() {
        @Override/*  w  w  w . j  a v  a 2 s. c  o  m*/
        public void onSuccess(Task result) {
            assertEquals(result, responseTask);
            latch.countDown();
        }

        @Override
        public void onFailure(Throwable t) {
            fail(t.toString());
            latch.countDown();
        }
    });

    assertThat(latch.await(COUNTDOWNLATCH_AWAIT_TIMEOUT, TimeUnit.SECONDS), is(true));
}

From source file:com.epam.reportportal.auth.integration.github.GitHubUserReplicator.java

/**
 * Replicates GitHub user to internal database (if does NOT exist). Creates personal project for that user
 *
 * @param userInfo     GitHub user to be replicated
 * @param gitHubClient Configured github client
 * @return Internal User representation/*from  w  ww .j  a v a 2  s .  c o  m*/
 */
public User replicateUser(UserResource userInfo, GitHubClient gitHubClient) {
    String login = EntityUtils.normalizeUsername(userInfo.login);
    User user = userRepository.findOne(login);
    if (null == user) {
        user = new User();
        user.setLogin(login);

        String email = userInfo.email;
        if (Strings.isNullOrEmpty(email)) {
            email = gitHubClient.getUserEmails().stream().filter(EmailResource::isVerified)
                    .filter(EmailResource::isPrimary).findAny().get().getEmail();
        }
        if (userRepository.exists(Filter.builder().withTarget(User.class)
                .withCondition(builder().eq("email", email).build()).build())) {
            throw new UserSynchronizationException("User with email '" + email + "' already exists");
        }
        user.setEmail(EntityUtils.normalizeEmail(email));

        if (!Strings.isNullOrEmpty(userInfo.name)) {
            user.setFullName(userInfo.name);
        }

        User.MetaInfo metaInfo = new User.MetaInfo();
        Date now = Date.from(ZonedDateTime.now().toInstant());
        metaInfo.setLastLogin(now);
        metaInfo.setSynchronizationDate(now);
        user.setMetaInfo(metaInfo);

        user.setType(UserType.GITHUB);
        user.setRole(UserRole.USER);
        Object avatarUrl = userInfo.avatarUrl;
        user.setPhotoId(uploadAvatar(gitHubClient, login, avatarUrl));

        user.setIsExpired(false);

        user.setDefaultProject(generatePersonalProject(user).getId());
        userRepository.save(user);

    } else if (!UserType.GITHUB.equals(user.getType())) {
        //if user with such login exists, but it's not GitHub user than throw an exception
        throw new UserSynchronizationException("User with login '" + user.getId() + "' already exists");
    }
    return user;
}

From source file:org.openmrs.module.operationtheater.api.impl.OperationTheaterServiceImpl.java

@Override
public Interval getLocationAvailableTime(Location location, LocalDate date) {
    Date date1 = Date.from(date.atStartOfDay(ZoneId.systemDefault()).toInstant());
    Date date2 = Date.from(date.plusDays(1).atStartOfDay(ZoneId.systemDefault()).toInstant());
    List<AppointmentBlock> blocks = appointmentService.getAppointmentBlocks(date1, date2,
            location.getId() + ",", null, null);
    //      List<AppointmentBlock> blocks = new ArrayList<AppointmentBlock>();

    if (blocks.size() == 1) {
        //         return new Interval(new DateTime(blocks.get(0).getStartDate()), new DateTime(blocks.get(0).getEndDate()));
        Instant startInstant = LocalDateTime.from(blocks.get(0).getStartDate().toInstant())
                .toInstant(ZoneOffset.UTC);
        Instant endInstant = LocalDateTime.from(blocks.get(0).getEndDate().toInstant())
                .toInstant(ZoneOffset.UTC);
        return Interval.of(startInstant, endInstant);
    } else if (blocks.size() > 1) {
        throw new APIException("There shouldn't be multiple appointment blocks per location and date");
    }/*from  ww  w.java2  s.  c  o m*/

    DateTimeFormatter timeFormatter = OTMetadata.AVAILABLE_TIME_FORMATTER;
    LocalDateTime availableStart = null;
    LocalDateTime availableEnd = null;
    for (LocationAttribute attribute : location.getAttributes()) {
        if (attribute.getAttributeType().getUuid().equals(OTMetadata.DEFAULT_AVAILABLE_TIME_BEGIN_UUID)) {
            LocalTime beginTime = LocalTime.parse((String) attribute.getValue(), timeFormatter);
            //            availableStart = date.withTime(beginTime.getHourOfDay(), beginTime.getMinuteOfHour(), 0, 0);
            availableStart = date.atTime(beginTime.getHour(), beginTime.getMinute());
        } else if (attribute.getAttributeType().getUuid().equals(OTMetadata.DEFAULT_AVAILABLE_TIME_END_UUID)) {
            LocalTime endTime = LocalTime.parse((String) attribute.getValue(), timeFormatter);
            //            availableEnd = date.withTime(endTime.getHourOfDay(), endTime.getMinuteOfHour(), 0, 0);
            availableEnd = date.atTime(endTime.getHour(), endTime.getMinute());
        }
    }

    if (availableStart != null && availableEnd != null) {
        return Interval.of(availableStart.toInstant(ZoneOffset.UTC), availableEnd.toInstant(ZoneOffset.UTC));
    }

    throw new APIException("Available times not defined. please make sure that the attributes "
            + "'default available time begin' and 'default available time end' for the location "
            + location.getName() + " are defined");

}

From source file:org.ng200.openolympus.controller.task.TaskViewController.java

@RequestMapping(method = RequestMethod.POST)
public String submitSolution(final HttpServletRequest request, final Model model, final Locale locale,
        @PathVariable("task") final Task task, final Principal principal, @Valid final SolutionDto solutionDto,
        final BindingResult bindingResult) throws IllegalStateException, IOException, ArchiveException {
    Assertions.resourceExists(task);//w  ww. j  av a 2  s.  com

    this.assertSuperuserOrTaskAllowed(principal, task);

    final User user = this.userRepository.findByUsername(principal.getName());

    this.solutionDtoValidator.validate(solutionDto, bindingResult);
    if (bindingResult.hasErrors()) {
        model.addAttribute("taskDescriptionUUID", task.getDescriptionFile());
        model.addAttribute("taskDescriptionURI", MessageFormat
                .format(TaskViewController.TASK_DESCRIPTION_PATH_TEMPLATE, task.getDescriptionFile()));
        model.addAttribute("localisedDescriptionFragment", "taskDescription_" + locale.getLanguage());
        model.addAttribute("task", task);
        return "tasks/task";
    }

    final UUID uuid = UUID.randomUUID();
    final String solutionPath = MessageFormat.format(TaskViewController.SOLUTION_PATH_TEMPLATE,
            StorageSpace.STORAGE_PREFIX, uuid.toString(),
            solutionDto.getTaskFile().getOriginalFilename().replaceAll("[^a-zA-Z0-9-\\._]", ""));

    final File solutionFile = new File(solutionPath);
    solutionFile.getParentFile().mkdirs();

    solutionDto.getTaskFile().transferTo(solutionFile);

    Solution solution = new Solution(task, user, solutionFile.getAbsolutePath(), Date.from(Instant.now()));
    solution = this.solutionRepository.save(solution);
    this.testingService.testSolutionOnAllTests(solution);

    return MessageFormat.format("redirect:/solution?id={0}", Long.toString(solution.getId()));
}

From source file:alfio.util.EventUtil.java

public static Optional<byte[]> getIcalForEvent(Event event, TicketCategory ticketCategory, String description) {
    ICalendar ical = new ICalendar();
    VEvent vEvent = new VEvent();
    vEvent.setSummary(event.getDisplayName());
    vEvent.setDescription(description);/*from  www.java2  s. com*/
    vEvent.setLocation(StringUtils.replacePattern(event.getLocation(), "[\n\r\t]+", " "));
    ZonedDateTime begin = Optional.ofNullable(ticketCategory)
            .map(tc -> tc.getTicketValidityStart(event.getZoneId())).orElse(event.getBegin());
    ZonedDateTime end = Optional.ofNullable(ticketCategory)
            .map(tc -> tc.getTicketValidityEnd(event.getZoneId())).orElse(event.getEnd());
    vEvent.setDateStart(Date.from(begin.toInstant()));
    vEvent.setDateEnd(Date.from(end.toInstant()));
    vEvent.setUrl(event.getWebsiteUrl());
    ical.addEvent(vEvent);
    StringWriter strWriter = new StringWriter();
    try (ICalWriter writer = new ICalWriter(strWriter, ICalVersion.V2_0)) {
        writer.write(ical);
        return Optional.of(strWriter.toString().getBytes(StandardCharsets.UTF_8));
    } catch (IOException e) {
        log.warn("was not able to generate iCal for event " + event.getShortName(), e);
        return Optional.empty();
    }
}

From source file:org.opendatakit.briefcase.util.ExportAction.java

public static List<String> export(BriefcaseFormDefinition formDefinition, ExportConfiguration configuration,
        TerminationFuture terminationFuture) {
    List<String> errors = new ArrayList<>();
    Optional<File> pemFile = configuration.mapPemFile(Path::toFile).filter(File::exists);
    if ((formDefinition.isFileEncryptedForm() || formDefinition.isFieldEncryptedForm()) && !pemFile.isPresent())
        errors.add(formDefinition.getFormName() + " form is encrypted");
    else/*from   ww  w. j a  v a  2s  .c o m*/
        try {
            export(configuration.mapExportDir(Path::toFile)
                    .orElseThrow(() -> new RuntimeException("Wrong export configuration")), ExportType.CSV,
                    formDefinition, pemFile.orElse(null), terminationFuture,
                    configuration.mapStartDate(
                            (LocalDate ld) -> Date.from(ld.atStartOfDay(ZoneId.systemDefault()).toInstant()))
                            .orElse(null),
                    configuration.mapEndDate(
                            (LocalDate ld) -> Date.from(ld.atStartOfDay(ZoneId.systemDefault()).toInstant()))
                            .orElse(null));
        } catch (IOException ex) {
            errors.add("Export of form " + formDefinition.getFormName() + " has failed: " + ex.getMessage());
        }
    return errors;
}

From source file:de.sainth.recipe.backend.security.AuthFilter.java

private Cookie createCookie(RecipeManagerAuthenticationToken authentication, boolean secure) {
    String newToken = Jwts.builder()
            //        .compressWith(new GzipCompressionCodec())
            .setSubject(authentication.getPrincipal().toString())
            .setExpiration(// w  ww .ja  v  a 2s  . c om
                    Date.from(LocalDateTime.now().plusMinutes(30).atZone(ZoneId.systemDefault()).toInstant()))
            .claim(TOKEN_ROLE, authentication.getAuthorities().get(0).getAuthority()).setIssuedAt(new Date())
            .signWith(SignatureAlgorithm.HS256, key).compact();
    Cookie cookie = new Cookie(COOKIE_NAME, newToken);
    cookie.setSecure(secure);
    cookie.setHttpOnly(true);
    cookie.setMaxAge(30 * 60);
    return cookie;
}