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:example.app.core.mapping.json.jackson.serialization.JsonToObjectMappingIntegrationTests.java

protected int ageFor(LocalDate birthDate) {
    return Period.between(birthDate, LocalDate.now()).getYears();
}

From source file:org.wallride.service.BlogService.java

@CacheEvict(value = WallRideCacheConfiguration.BLOG_CACHE, allEntries = true)
public GoogleAnalytics updateGoogleAnalytics(GoogleAnalyticsUpdateRequest request) {
    byte[] p12;/*  w  ww . ja v  a 2s  . c  o  m*/
    try {
        p12 = request.getServiceAccountP12File().getBytes();
    } catch (IOException e) {
        throw new ServiceException(e);
    }

    try {
        PrivateKey privateKey = SecurityUtils.loadPrivateKeyFromKeyStore(SecurityUtils.getPkcs12KeyStore(),
                new ByteArrayInputStream(p12), "notasecret", "privatekey", "notasecret");

        HttpTransport httpTransport = GoogleNetHttpTransport.newTrustedTransport();
        JsonFactory jsonFactory = JacksonFactory.getDefaultInstance();

        // Build service account credential.
        Set<String> scopes = new HashSet<>();
        scopes.add(AnalyticsScopes.ANALYTICS_READONLY);

        GoogleCredential credential = new GoogleCredential.Builder().setTransport(httpTransport)
                .setJsonFactory(jsonFactory).setServiceAccountId(request.getServiceAccountId())
                .setServiceAccountScopes(scopes).setServiceAccountPrivateKey(privateKey).build();

        Analytics analytics = new Analytics.Builder(httpTransport, jsonFactory, credential)
                .setApplicationName("WallRide").build();

        GaData gaData = analytics.data().ga()
                .get(request.getProfileId(), "2005-01-01",
                        LocalDate.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd")), "ga:pageviews")
                .setDimensions(String.format("ga:dimension%d", request.getCustomDimensionIndex()))
                .setMaxResults(1).execute();
        logger.debug("GaData: {}", gaData);
    } catch (GeneralSecurityException e) {
        throw new GoogleAnalyticsException(e);
    } catch (IOException e) {
        throw new GoogleAnalyticsException(e);
    }

    GoogleAnalytics googleAnalytics = new GoogleAnalytics();
    googleAnalytics.setTrackingId(request.getTrackingId());
    googleAnalytics.setProfileId(request.getProfileId());
    googleAnalytics.setCustomDimensionIndex(request.getCustomDimensionIndex());
    googleAnalytics.setServiceAccountId(request.getServiceAccountId());
    googleAnalytics.setServiceAccountP12FileName(request.getServiceAccountP12File().getOriginalFilename());
    googleAnalytics.setServiceAccountP12FileContent(p12);

    Blog blog = blogRepository.findOneForUpdateById(request.getBlogId());
    blog.setGoogleAnalytics(googleAnalytics);

    blog = blogRepository.saveAndFlush(blog);
    return blog.getGoogleAnalytics();
}

From source file:org.jboss.jbossset.JiraReporterTest.java

@Test(expected = ParseException.class)
public void testInvalidadStartDate() throws ParseException {
    String cmd = "-u user1 -s " + LocalDate.now().plusDays(1);
    new CommandLineParser(cmd.split(" ")).parse();
}

From source file:example.app.core.mapping.json.jackson.serialization.JsonToObjectMappingIntegrationTests.java

protected LocalDate birthDateFor(int age) {
    return LocalDate.now().minusYears(age);
}

From source file:com.gnadenheimer.mg3.controller.admin.AdminConfigController.java

/**
 * Initializes the controller class./*from  w w  w  .ja v a2 s . c  o  m*/
 */
@Override
public void initialize(URL url, ResourceBundle rb) {
    try {
        cboTransferencias.getItems().addAll("Normal", "Triplicado");
        cboFacturasFormato.getItems().addAll("Preimpreso con rejilla", "Preimpreso sin rejilla",
                "Preimpreso con rejilla modelo especial Bethel Theodor");
        cboPeriodoFiscal.getItems().addAll(2016, 2017);
        txtIP.setText(Preferences.userRoot().node("MG").get("DatabaseIP", "127.000.000.001"));
        txtDataDir.setText(Preferences.userRoot().node("MG").get("Datadir",
                System.getProperty("user.dir") + File.separator + "javadb"));
        rbServidor.setSelected(Boolean.parseBoolean(Preferences.userRoot().node("MG").get("isServer", "true")));
        rbCliente.setSelected(
                !Boolean.parseBoolean(Preferences.userRoot().node("MG").get("isServer", "truemaster   1")));
        cboTransferencias.getSelectionModel()
                .select(Preferences.userRoot().node("MG").get("modoImpresion", "Normal"));
        cboFacturasFormato.getSelectionModel()
                .select(Preferences.userRoot().node("MG").get("formatoFactura", "Preimpreso sin rejilla"));
        rbAyCPorMes
                .setSelected(Boolean.parseBoolean(Preferences.userRoot().node("MG").get("cobrarAC", "true")));
        cboPeriodoFiscal.getSelectionModel().select(Integer
                .valueOf(Preferences.userRoot().node("MG").getInt("PeriodoFiscal", LocalDate.now().getYear())));

        txtDataDir.visibleProperty().bind(rbServidor.selectedProperty());
    } catch (Exception ex) {
        App.showException(this.getClass().getName(), ex.getMessage(), ex);
    }
}

From source file:ca.phon.session.io.xml.v12.XMLSessionWriter_v12.java

/**
 * Create a new jaxb version of the session
 * //  w  w w .  j  a v a  2 s  .  co m
 * @param session
 * @return an version of the session use-able by jaxb 
 */
private JAXBElement<SessionType> toSessionType(Session session) throws IOException {
    final ObjectFactory factory = new ObjectFactory();
    final SessionType retVal = factory.createSessionType();

    // header data
    retVal.setVersion("PB1.2");
    retVal.setId(session.getName());
    retVal.setCorpus(session.getCorpus());

    final HeaderType headerData = factory.createHeaderType();
    if (session.getMediaLocation() != null && session.getMediaLocation().length() > 0) {
        headerData.setMedia(session.getMediaLocation());
    }
    final LocalDate date = (session.getDate() == null ? LocalDate.now() : session.getDate());
    try {
        final DatatypeFactory df = DatatypeFactory.newInstance();
        final XMLGregorianCalendar cal = df
                .newXMLGregorianCalendar(GregorianCalendar.from(date.atStartOfDay(ZoneId.systemDefault())));
        cal.setTimezone(DatatypeConstants.FIELD_UNDEFINED);
        headerData.setDate(cal);
    } catch (DatatypeConfigurationException e) {
        LOGGER.log(Level.WARNING, e.getMessage(), e);
    }
    final String lang = session.getLanguage();
    if (lang != null && lang.length() > 0) {
        final String langs[] = lang.split("\\p{Space}");
        for (String l : langs) {
            headerData.getLanguage().add(l);
        }
    }
    retVal.setHeader(headerData);

    final TranscriptType transcript = factory.createTranscriptType();
    // commets
    for (int i = 0; i < session.getMetadata().getNumberOfComments(); i++) {
        final Comment c = session.getMetadata().getComment(i);
        final CommentType ct = copyComment(factory, c);
        transcript.getUOrComment().add(ct);
    }

    // participants
    final ParticipantsType parts = factory.createParticipantsType();
    for (int i = 0; i < session.getParticipantCount(); i++) {
        final Participant part = session.getParticipant(i);
        final ParticipantType pt = copyParticipant(factory, part);
        parts.getParticipant().add(pt);
    }
    retVal.setParticipants(parts);

    // transcribers
    final TranscribersType tt = factory.createTranscribersType();
    for (int i = 0; i < session.getTranscriberCount(); i++) {
        final Transcriber tr = session.getTranscriber(i);
        final TranscriberType trt = copyTranscriber(factory, tr);
        tt.getTranscriber().add(trt);
    }
    retVal.setTranscribers(tt);

    // tier info/ordering
    final UserTiersType utt = factory.createUserTiersType();
    for (int i = 0; i < session.getUserTierCount(); i++) {
        final TierDescription td = session.getUserTier(i);
        final UserTierType tierType = copyTierDescription(factory, td);
        utt.getUserTier().add(tierType);
    }
    retVal.setUserTiers(utt);

    final TierOrderType tot = factory.createTierOrderType();
    for (TierViewItem tvi : session.getTierView()) {
        final TvType tvt = copyTierViewItem(factory, tvi);
        tot.getTier().add(tvt);
    }
    retVal.setTierOrder(tot);

    // session data
    for (int i = 0; i < session.getRecordCount(); i++) {
        final Record record = session.getRecord(i);

        // insert comments first
        for (int j = 0; j < record.getNumberOfComments(); j++) {
            final Comment com = record.getComment(j);
            final CommentType ct = copyComment(factory, com);
            transcript.getUOrComment().add(ct);
        }

        // copy record data
        final RecordType rt = copyRecord(factory, retVal, record);

        rt.setId(record.getUuid().toString());

        if (record.isExcludeFromSearches())
            rt.setExcludeFromSearches(record.isExcludeFromSearches());

        // setup participant
        if (record.getSpeaker() != null) {
            for (ParticipantType pt : parts.getParticipant()) {
                if (pt.getId().equals(record.getSpeaker().getId())) {
                    rt.setSpeaker(pt);
                    break;
                }
            }
        }

        transcript.getUOrComment().add(rt);
    }
    retVal.setTranscript(transcript);

    return factory.createSession(retVal);
}

From source file:com.romeikat.datamessie.core.statistics.app.shared.LocalStatisticsManager.java

@Override
public StatisticsDto getStatistics(final long projectId, final Integer numberOfDays) {
    final StatisticsDto dto = new StatisticsDto();

    final HibernateSessionProvider sessionProvider = new HibernateSessionProvider(sessionFactory);
    final Collection<Long> sourceIds = sourceDao.getIds(sessionProvider.getStatelessSession(), projectId,
            (Boolean) null);//from   w w w . ja  va 2  s .  c  om

    LocalDate to;
    LocalDate from;
    to = LocalDate.now();
    from = to.minusDays(ObjectUtils.defaultIfNull(numberOfDays, 0) - 1);

    final Function<LocalDate, LocalDate> transformDateFunction = Functions.identity();

    final StatisticsSparseTable baseStatistics = getBaseStatistics(sessionProvider.getStatelessSession(),
            sourceIds, from, to);

    // All documents
    DocumentProcessingState[] states = DocumentProcessingState
            .getWithout(DocumentProcessingState.TECHNICAL_ERROR, DocumentProcessingState.TO_BE_DELETED);
    GetNumberOfDocumentsFunction getNumberOfDocumentsFunction = new GetNumberOfDocumentsFunction(states);
    final SparseSingleTable<Long, LocalDate, Long> allDocumentsStatistics = statisticsService.getStatistics(
            baseStatistics, sourceIds, from, to, transformDateFunction, getNumberOfDocumentsFunction);
    final Function<Pair<Long, Long>, Long> mergeFunction = new Function<Pair<Long, Long>, Long>() {
        @Override
        public Long apply(final Pair<Long, Long> from) {
            return from.getLeft() + from.getRight();
        }
    };
    final Long allDocuments = allDocumentsStatistics.mergeAllValues(mergeFunction);
    dto.setAllDocuments(allDocuments);

    // Downloaded documents
    states = DocumentProcessingState.getWithout(DocumentProcessingState.DOWNLOAD_ERROR,
            DocumentProcessingState.REDIRECTING_ERROR, DocumentProcessingState.TECHNICAL_ERROR);
    getNumberOfDocumentsFunction = new GetNumberOfDocumentsFunction(states);
    final SparseSingleTable<Long, LocalDate, Long> downloadedDocumentsStatistics = statisticsService
            .getStatistics(baseStatistics, sourceIds, from, to, transformDateFunction,
                    getNumberOfDocumentsFunction);
    final Long downloadedDocuments = downloadedDocumentsStatistics.mergeAllValues(mergeFunction);
    dto.setDownloadedDocuments(downloadedDocuments);

    // Preprocessed documents
    getNumberOfDocumentsFunction = new GetNumberOfDocumentsFunction(
            DocumentProcessingState.getWith(DocumentProcessingState.STEMMED));
    final SparseSingleTable<Long, LocalDate, Long> preprocessedDocumentsStatistics = statisticsService
            .getStatistics(baseStatistics, sourceIds, from, to, transformDateFunction,
                    getNumberOfDocumentsFunction);
    final Long preprocessedDocuments = preprocessedDocumentsStatistics.mergeAllValues(mergeFunction);
    dto.setPreprocessedDocuments(preprocessedDocuments);

    // Download success
    final Double downloadSuccess;
    if (downloadedDocuments == null || allDocuments == null || allDocuments == 0) {
        downloadSuccess = null;
    } else {
        downloadSuccess = (double) downloadedDocuments / (double) allDocuments;
    }
    dto.setDownloadSuccess(downloadSuccess);

    // Preprocessing success
    getNumberOfDocumentsFunction = new GetNumberOfDocumentsFunction(
            DocumentProcessingState.getWith(DocumentProcessingState.CLEANED,
                    DocumentProcessingState.CLEANING_ERROR, DocumentProcessingState.STEMMED));
    final SparseSingleTable<Long, LocalDate, Long> preprocessingAttemtedDocumentsStatistics = statisticsService
            .getStatistics(baseStatistics, sourceIds, from, to, transformDateFunction,
                    getNumberOfDocumentsFunction);
    final Long preprocessingAttemtedDocuments = preprocessingAttemtedDocumentsStatistics
            .mergeAllValues(mergeFunction);

    final Double preprocessingSuccess;
    if (preprocessedDocuments == null || preprocessingAttemtedDocuments == null
            || preprocessingAttemtedDocuments == 0) {
        preprocessingSuccess = null;
    } else {
        preprocessingSuccess = (double) preprocessedDocuments / (double) preprocessingAttemtedDocuments;
    }
    dto.setPreprocessingSuccess(preprocessingSuccess);

    // Documents to be preprocessed
    getNumberOfDocumentsFunction = new GetNumberOfDocumentsFunction(
            DocumentProcessingState.getWith(DocumentProcessingState.DOWNLOADED,
                    DocumentProcessingState.REDIRECTED, DocumentProcessingState.CLEANED));
    final SparseSingleTable<Long, LocalDate, Long> documentsToBePreprocessedStatistics = statisticsService
            .getStatistics(baseStatistics, sourceIds, from, to, transformDateFunction,
                    getNumberOfDocumentsFunction);
    final Long documentsToBePreprocessed = documentsToBePreprocessedStatistics.mergeAllValues(mergeFunction);
    dto.setDocumentsToBePreprocessed(documentsToBePreprocessed);

    // Done
    sessionProvider.closeStatelessSession();
    return dto;
}

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

/**
 * Initializes the controller class./*from ww  w .j a va 2s. com*/
 */
@Override
public void initialize(URL url, ResourceBundle rb) {
    dc_date.setValue(LocalDate.now());

    material_name.setCellValueFactory(new PropertyValueFactory<DCItem, String>("name"));
    brand_name.setCellValueFactory(new PropertyValueFactory<DCItem, String>("brand"));
    model_code.setCellValueFactory(new PropertyValueFactory<DCItem, String>("model"));
    quantity.setCellValueFactory(new PropertyValueFactory<DCItem, Integer>("quantity"));
    units.setCellValueFactory(new PropertyValueFactory<DCItem, String>("units"));
    amount.setCellValueFactory(new PropertyValueFactory<DCItem, Integer>("amount"));

    dcDetail.getColumns().setAll(material_name, brand_name, model_code, quantity, units, amount);
    // TODO

    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_name.setUserData(item.getId());
            txt_brand.setText(item.getBrand());
            txt_model.setText(item.getBrand()); // item doesn't have this field. add??
            txt_rate.setText(String.valueOf(item.getRate()));
            txt_units.setText(item.getUnit());
            txt_qty.setText("");
            txt_amount.setText("");
            txt_qty.requestFocus();
        }
    });

    AutoCompletionBinding<Project> bindForProject = 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();
                }
            });

    txt_qty.focusedProperty().addListener(new ChangeListener<Boolean>() {
        @Override
        public void changed(ObservableValue<? extends Boolean> observable, Boolean oldValue, Boolean newValue) {
            if (!newValue) {
                calcAmount();
            }
        }
    });
}

From source file:pw.spn.mptg.service.impl.ProjectServiceImpl.java

private void createLicense(Path workingDir, License license, String developerName) {
    int year = LocalDate.now().getYear();
    Map<String, Object> context = new HashMap<>();
    context.put("year", year);
    context.put("name", developerName);
    byte[] content = templateService.executeTemplate("license_" + license.name().toLowerCase(), context);
    fileService.writeToFile(workingDir, "LICENSE", content);
}

From source file:me.rkfg.xmpp.bot.plugins.FaggotOfTheDayPlugin.java

private Date getFirstTime() {
    final LocalTime midnight = LocalTime.MIDNIGHT;
    final LocalDate today = LocalDate.now();
    final LocalDateTime todayMidnight = LocalDateTime.of(today, midnight);
    return Date.from(todayMidnight.atZone(ZoneId.systemDefault()).toInstant());
}