Example usage for java.time LocalDate now

List of usage examples for java.time LocalDate now

Introduction

In this page you can find the example usage for java.time LocalDate now.

Prototype

public static LocalDate now() 

Source Link

Document

Obtains the current date from the system clock in the default time-zone.

Usage

From source file:com.realdolmen.rdfleet.service.EmployeeService.java

/**
 * Assigns an order of a car to an employee. The RdEmployee and the order cannot be null. The car of the order also cannot be null.
 *
 * @param rdEmployee the employee found from the database
 * @param order      the order that should be linked to the employee
 *//*from   w w w. jav  a2 s .  com*/
public void assignOrderToEmployee(RdEmployee rdEmployee, Order order) {
    if (rdEmployee == null)
        throw new IllegalArgumentException("The employee to assign and order to cannot be null.");
    if (rdEmployee.getId() == null)
        throw new IllegalArgumentException(
                String.format("The id of employee %s %s is null so it did not originate out of the database.",
                        rdEmployee.getFirstName(), rdEmployee.getLastName()));
    if (order == null)
        throw new IllegalArgumentException("The order to be assigned to an employee cannot be null.");
    if (order.getOrderedCar() == null)
        throw new IllegalArgumentException("The order should have a car assigned to it.");

    if ((order.getOrderedCar().getSelectedCar().getFunctionalLevel() > rdEmployee.getFunctionalLevel() + 1
            || order.getOrderedCar().getSelectedCar().getFunctionalLevel() < rdEmployee.getFunctionalLevel()
                    - 1)
            && order.getOrderedCar().getCarStatus() != CarStatus.NOT_USED)
        throw new IllegalArgumentException(
                "The ordered car differs more than 1 functional level from the employee's functional level.");

    if (rdEmployee.getCurrentOrder() != null)
        setEmployeeCarRemoved(rdEmployee);

    order.getOrderedCar().setCarStatus(CarStatus.PENDING);
    order.setDateOrdered(LocalDate.now());
    rdEmployee.setCurrentOrder(order);
    rdEmployeeRepository.save(rdEmployee);
}

From source file:com.epam.ta.reportportal.database.search.FilterRules.java

public static Predicate<String> timeStamp() {
    return value -> {
        if (value == null) {
            return false;
        }//w  ww .  j ava  2 s  .co m
        try {
            long offset = Long.parseLong(value);
            LocalDateTime.of(LocalDate.now(), LocalTime.of(0, 0)).plusMinutes(offset);
        } catch (NumberFormatException | DateTimeException e) {
            return false;
        }
        return true;
    };
}

From source file:software.reinvent.dependency.parser.service.CsvWriter.java

/**
 * Creates the csv files/*  w  ww  .  ja  v a 2s . c o  m*/
 * <ul>
 * <li>Internal_{date}.csv</li>
 * <li>External_{date}.csv</li>
 * <li>Artifacts_{date}.csv</li>
 * </ul>
 * with all important information's about the {@link Artifact}s and their {@link ArtifactDependency}'s.
 *
 * @param internalGroupId the internal maven group id
 * @param resultDir       the dir where the CSV files will be written
 * @param prefix          any optional prefix for the CSV files
 *
 * @throws IOException
 */
public void writeDependencies(final String internalGroupId, final File resultDir, final String prefix)
        throws IOException {
    final Set<ArtifactDependency> allDependencies = artifacts.stream().map(Artifact::getDependencies)
            .flatMap(Collection::stream).collect(Collectors.toSet());
    final Set<ArtifactDependency> internalDependencies = allDependencies.stream()
            .filter(isInternalPredicate(internalGroupId))
            .sorted(Comparator.comparing(ArtifactDependency::getGroupId)).collect(toSet());
    final Set<ArtifactDependency> externalDependencies = Sets
            .newHashSet(CollectionUtils.subtract(allDependencies, internalDependencies));

    final Multimap<ArtifactDependency, Artifact> dependencyToArtifact = HashMultimap.create();
    allDependencies.forEach(
            dependency -> artifacts.stream().filter(artifact -> artifact.getDependencies().contains(dependency))
                    .forEach(x -> dependencyToArtifact.put(dependency, x)));

    CSVWriter internalWriter = null;
    CSVWriter externalWriter = null;
    CSVWriter artifactWriter = null;
    try {
        resultDir.mkdirs();
        final File internalResultFile = new File(resultDir,
                prefix + "Internal_" + LocalDate.now().toString() + ".csv");
        final File externalResultFile = new File(resultDir,
                prefix + "External_" + LocalDate.now().toString() + ".csv");
        final File artifactResultFile = new File(resultDir,
                prefix + "Artifacts_" + LocalDate.now().toString() + ".csv");
        logger.info("Will write results to {} and {}.", internalResultFile, externalResultFile);
        internalWriter = new CSVWriter(new FileWriter(internalResultFile), separator);
        writeDependencyHeader(internalWriter);
        externalWriter = new CSVWriter(new FileWriter(externalResultFile), separator);
        writeDependencyHeader(externalWriter);
        artifactWriter = new CSVWriter(new FileWriter(artifactResultFile), separator);
        artifactWriter
                .writeNext(("groupId#artifactId#version#package#internalDependencies" + "#externalDependencies")
                        .split("#"));
        final CSVWriter finalInternalWriter = internalWriter;
        final CSVWriter finalExternalWriter = externalWriter;
        dependencyToArtifact.keySet().stream().sorted(Comparator.comparing(ArtifactDependency::getGroupId)
                .thenComparing(ArtifactDependency::getArtifactId)).forEach(dependency -> {
                    final List<String> dependentArtifacts = dependencyToArtifact.get(dependency).stream()
                            .map(Artifact::getArtifactId).sorted().collect(toList());
                    final String artifactLicenses = defaultIfBlank(
                            Joiner.on("\n").join(dependency.getArtifactLicenses()), "n/a in pom");

                    final ArrayList<String> newLine = Lists.newArrayList(dependency.getGroupId(),
                            dependency.getArtifactId(), Joiner.on("\n").join(dependency.getVersions()),
                            artifactLicenses, dependency.getDescription(),
                            Joiner.on("\n").join(dependentArtifacts));
                    final String[] csvLine = Iterables.toArray(newLine, String.class);
                    if (isInternal(internalGroupId, dependency)) {
                        finalInternalWriter.writeNext(csvLine);
                    } else {
                        finalExternalWriter.writeNext(csvLine);
                    }
                });
        final CSVWriter finalArtifactWriter = artifactWriter;
        artifacts.stream()
                .sorted(Comparator.comparing(Artifact::getGroupId).thenComparing(Artifact::getArtifactId))
                .forEachOrdered(artifact -> {
                    final String intDependencies = getDependencyColumn(artifact, internalDependencies,
                            ArtifactDependency::getArtifactId);
                    final String extDependencies = getDependencyColumn(artifact, externalDependencies,
                            ArtifactDependency::toString);
                    final ArrayList<String> newLine = Lists.newArrayList(artifact.getGroupId(),
                            artifact.getArtifactId(), Joiner.on(",").join(artifact.getVersions()),
                            defaultString(artifact.getPackaging()),

                            intDependencies, extDependencies);
                    final String[] csvLine = Iterables.toArray(newLine, String.class);
                    finalArtifactWriter.writeNext(csvLine);
                });
    } catch (IOException e)

    {
        logger.error("Could not write csv.", e);
    } finally

    {
        if (internalWriter != null) {
            internalWriter.close();
        }
        if (externalWriter != null) {
            externalWriter.close();
        }
        if (artifactWriter != null) {
            artifactWriter.close();
        }
    }

    logger.info("Found {} dependencies. {} internal and {} external", allDependencies.size(),
            internalDependencies.size(), externalDependencies.size());
}

From source file:fr.lepellerin.ecole.web.controller.cantine.ReservationRepasAnneeController.java

/**
 * initialise le form./*from   ww w. jav a2 s.c o m*/
 *
 * @return <code>DetaillerReservationRepasForm</code>
 * @throws TechnicalException 
 */
@ModelAttribute("command")
public ReserverRepasForm addCommand() throws TechnicalException {
    final CurrentUser user = (CurrentUser) SecurityContextHolder.getContext().getAuthentication()
            .getPrincipal();
    final ReserverRepasForm form = new ReserverRepasForm();
    final List<DayOfWeek> jours = this.cantineService.getJourOuvertCantine(LocalDate.now(),
            user.getUser().getFamille());
    jours.forEach(j -> {
        switch (j) {
        case MONDAY:
            form.setPresLundi(true);
            break;
        case TUESDAY:
            form.setPresMardi(true);
            break;
        case WEDNESDAY:
            form.setPresMercredi(true);
            break;
        case THURSDAY:
            form.setPresJeudi(true);
            break;
        case FRIDAY:
            form.setPresVendredi(true);
            break;
        case SATURDAY:
            form.setPresSamedi(true);
            break;
        case SUNDAY:
            form.setPresDimanche(true);
            break;
        default:
            break;
        }
    });
    return form;
}

From source file:example.app.model.Person.java

@Transient
@SuppressWarnings("all")
public int getAge() {
    LocalDate birthDate = getBirthDate();
    Assert.state(birthDate != null, String.format("birth date of person [%s] is unknown", getName()));
    Period period = Period.between(birthDate, LocalDate.now());
    return period.getYears();
}

From source file:curly.artifactory.SpringBootTest.java

public Artifact createArtifact(MongoTemplate mongoTemplate) {
    Artifact artifact = new Artifact();
    Set<Language> languages = new HashSet<>(0);
    Set<Type> types = new HashSet<>(0);
    types.add(new Type("document"));
    types.add(new Type("nosql"));
    languages.add(new Language("java"));
    languages.add(new Language("groovy"));
    languages.add(new Language("ruby"));
    artifact.setName("A lovers project");
    artifact.setAuthor("joaoevangelista");
    artifact.setCategory(new Category("database"));
    artifact.setHomePage("http://example.com");
    artifact.setIncubation(LocalDate.now().toString());
    artifact.setLanguages(languages);//from  w w w.ja v a 2  s.co  m
    artifact.setTypes(types);
    mongoTemplate.insert(artifact);
    return artifact;
}

From source file:serposcope.controllers.HomeController.java

public Result home(Context context) {

    String diskUsage = dbSizeUtils.getDbUsageFormatted();
    String diskFree = dbSizeUtils.getDiskFreeFormatted();

    String display = context.getParameter("display", baseDB.config.getConfig().getDisplayHome());
    if (!Config.VALID_DISPLAY_HOME.contains(display)) {
        display = Config.DEFAULT_DISPLAY_HOME;
    }//from   ww  w  . j a v  a 2s  .co m

    List<Group> groups = (List<Group>) context.getAttribute("groups");
    Run currentRun = baseDB.run.findLast(Module.GOOGLE, RunDB.STATUSES_RUNNING, null);
    Run lastRun = baseDB.run.findLast(Module.GOOGLE, RunDB.STATUSES_DONE, null);
    if (lastRun == null) {
        return Results.ok().template("/serposcope/views/HomeController/" + display + ".ftl.html")
                .render("display", display).render("summaries", Collections.EMPTY_LIST)
                .render("currentRun", currentRun).render("lastRun", lastRun).render("groups", groups)
                .render("lastlog", LocalDate.now().toString() + ".log").render("diskUsage", diskUsage)
                .render("diskFree", diskFree);
    }

    List<TargetHomeEntry> summaries = new ArrayList<>();

    Map<Integer, GoogleTargetSummary> summariesByTarget = googleDB.targetSummary
            .list(lastRun.getId(), "table".equals(display)).stream()
            .collect(Collectors.toMap(GoogleTargetSummary::getTargetId, Function.identity()));

    List<GoogleTarget> targets = googleDB.target
            .list(groups.stream().map(Group::getId).collect(Collectors.toList()));

    Map<Integer, Group> groupById = groups.stream()
            .collect(Collectors.toMap(Group::getId, Function.identity()));

    for (GoogleTarget target : targets) {
        GoogleTargetSummary summary = summariesByTarget.get(target.getId());
        if (summary != null) {
            List<Integer> scoreHistory = googleDB.targetSummary.listScoreHistory(target.getGroupId(),
                    target.getId(), 30);
            int missingScore = 30 - scoreHistory.size();
            for (int i = 0; i < missingScore; i++) {
                scoreHistory.add(0, 0);
            }
            summaries.add(new TargetHomeEntry(groupById.get(target.getGroupId()).getName(), target, summary,
                    scoreHistory));
        }
    }

    Set<Integer> searchIds = new HashSet<>();
    for (TargetHomeEntry homeEntry : summaries) {
        homeEntry.summary.visitReferencedSearchId(searchIds);
    }

    return Results.ok().template("/serposcope/views/HomeController/" + display + ".ftl.html")
            .render("display", display).render("groups", context.getAttribute("groups"))
            .render("currentRun", currentRun).render("lastRun", lastRun)
            .render("lastRuns", baseDB.run.listByStatus(null, 7l, 0l))
            .render("hasTarget", googleDB.target.hasTarget()).render("summaries", summaries)
            .render("searches", googleDB.search.mapBySearchId(searchIds))
            .render("lastlog", LocalDate.now().toString() + ".log").render("diskUsage", diskUsage)
            .render("diskFree", diskFree);
}

From source file:com.github.drbookings.LocalDates.java

public static boolean isLastThreeMonths(final LocalDate date) {
    final Month month = LocalDate.now().getMonth().minus(1);
    if (date.getMonth().equals(month) && (date.getYear() == LocalDate.now().getYear()
            || date.getYear() == LocalDate.now().getYear() - 1)) {
        return true;
    }/* www  . ja va 2 s. c  om*/
    if (date.getMonth().equals(month.minus(1)) && (date.getYear() == LocalDate.now().getYear()
            || date.getYear() == LocalDate.now().getYear() - 1)) {
        return true;
    }
    return date.getMonth().equals(month.minus(2))
            && (date.getYear() == LocalDate.now().getYear() || date.getYear() == LocalDate.now().getYear() - 1);
}

From source file:retsys.client.controller.PurchaseOrderController.java

/**
 * Initializes the controller class./*w  ww. ja v a  2 s . c  om*/
 */
@Override
public void initialize(URL url, ResourceBundle rb) {
    po_date.setValue(LocalDate.now());

    loc_of_material.setCellValueFactory(new PropertyValueFactory<POItem, String>("location"));
    material_name.setCellValueFactory(new PropertyValueFactory<POItem, String>("name"));
    brand_name.setCellValueFactory(new PropertyValueFactory<POItem, String>("brand"));
    model_code.setCellValueFactory(new PropertyValueFactory<POItem, String>("model"));
    quantity.setCellValueFactory(new PropertyValueFactory<POItem, Integer>("quantity"));

    poDetail.getColumns().setAll(loc_of_material, material_name, brand_name, model_code, quantity);

    AutoCompletionBinding<Item> bindForTxt_name = TextFields.bindAutoCompletion(txt_name,
            new Callback<AutoCompletionBinding.ISuggestionRequest, Collection<Item>>() {

                @Override
                public Collection<Item> call(AutoCompletionBinding.ISuggestionRequest param) {
                    List<Item> list = null;
                    try {
                        LovHandler lovHandler = new LovHandler("items", "name");
                        String response = lovHandler.getSuggestions(param.getUserText());
                        list = (List<Item>) new JsonHelper().convertJsonStringToObject(response,
                                new TypeReference<List<Item>>() {
                                });
                    } catch (IOException ex) {
                        Logger.getLogger(ProjectController.class.getName()).log(Level.SEVERE, null, ex);
                    }

                    return list;
                }
            }, new StringConverter<Item>() {

                @Override
                public String toString(Item object) {
                    System.out.println("here..." + object);
                    return object.getName() + " (ID:" + object.getId() + ")";
                }

                @Override
                public Item fromString(String string) {
                    throw new UnsupportedOperationException();
                }
            });
    //event handler for setting other item fields with values from selected Item object
    //fires after autocompletion
    bindForTxt_name.setOnAutoCompleted(new EventHandler<AutoCompletionBinding.AutoCompletionEvent<Item>>() {

        @Override
        public void handle(AutoCompletionBinding.AutoCompletionEvent<Item> event) {
            Item item = event.getCompletion();
            //fill other item related fields
            txt_brand.setText(item.getBrand());
            txt_location.setUserData(item.getId());
            txt_model.setText(null); // item doesn't have this field. add??
        }
    });

    TextFields.bindAutoCompletion(project,
            new Callback<AutoCompletionBinding.ISuggestionRequest, Collection<Project>>() {

                @Override
                public Collection<Project> call(AutoCompletionBinding.ISuggestionRequest param) {
                    List<Project> list = null;
                    try {
                        LovHandler lovHandler = new LovHandler("projects", "name");
                        String response = lovHandler.getSuggestions(param.getUserText());
                        list = (List<Project>) new JsonHelper().convertJsonStringToObject(response,
                                new TypeReference<List<Project>>() {
                                });
                    } catch (IOException ex) {
                        Logger.getLogger(ProjectController.class.getName()).log(Level.SEVERE, null, ex);
                    }

                    return list;
                }
            }, new StringConverter<Project>() {

                @Override
                public String toString(Project object) {
                    return object.getName() + " (ID:" + object.getId() + ")";
                }

                @Override
                public Project fromString(String string) {
                    throw new UnsupportedOperationException();
                }
            });

    TextFields.bindAutoCompletion(vendor,
            new Callback<AutoCompletionBinding.ISuggestionRequest, Collection<Vendor>>() {

                @Override
                public Collection<Vendor> call(AutoCompletionBinding.ISuggestionRequest param) {
                    List<Vendor> list = null;
                    try {
                        LovHandler lovHandler = new LovHandler("vendors", "name");
                        String response = lovHandler.getSuggestions(param.getUserText());
                        list = (List<Vendor>) new JsonHelper().convertJsonStringToObject(response,
                                new TypeReference<List<Vendor>>() {
                                });
                    } catch (IOException ex) {
                        Logger.getLogger(ProjectController.class.getName()).log(Level.SEVERE, null, ex);
                    }

                    return list;
                }
            }, new StringConverter<Vendor>() {

                @Override
                public String toString(Vendor object) {
                    return object.getName() + " (ID:" + object.getId() + ")";
                }

                @Override
                public Vendor fromString(String string) {
                    throw new UnsupportedOperationException();
                }
            });
}

From source file:bzzAgent.BiteSizedBzzDaoJpa.java

@Override
public List<BiteSizedActivityEntity> search(BiteSizedActivitySearchParams params) {
    final LocalDate today = LocalDate.now();

    String activeQuery;/*from   w  w w  .j  a va2s.c  o m*/
    if (params.isActive() != null) {
        if (params.isActive()) {
            activeQuery = "where bsae.endDate >= ? " + " or bsae.phaseInt < 6 "; //Launch(6, "General Launch")

        } else {
            activeQuery = "where bsae.endDate < ? " + " and bsae.phaseInt = 6 ";
        }
    } else {
        activeQuery = "";
    }

    String sql = "from BiteSizedActivityEntity bsae " + " left outer join fetch bsae.incentives incentive "
            + activeQuery + " order by bsae.startDate ASC";

    //sql += "order by ma.mam.id asc";
    TypedQuery<BiteSizedActivityEntity> query2 = em.createQuery(sql, BiteSizedActivityEntity.class)
            .setFirstResult(params.getOffset())
    //.setMaxResults(params.getLimit())
    ;
    if (params.isActive() != null) {
        query2.setParameter(1, today);
    }
    return query2.getResultList();
}