Example usage for java.time LocalDateTime now

List of usage examples for java.time LocalDateTime now

Introduction

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

Prototype

public static LocalDateTime now() 

Source Link

Document

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

Usage

From source file:org.kitodo.production.forms.IndexingForm.java

/**
 * Return the progress in percent of the currently running indexing process. If
 * the list of entries to be indexed is empty, this will return "0".
 *
 * @param currentType/* w  w  w  . j  ava  2 s .  c o  m*/
 *            the ObjectType for which the progress will be determined
 * @return the progress of the current indexing process in percent
 */
public int getProgress(ObjectType currentType) {
    long numberOfObjects = countDatabaseObjects.get(currentType);
    long nrOfIndexedObjects = getNumberOfIndexedObjects(currentType);
    int progress = numberOfObjects > 0 ? (int) ((nrOfIndexedObjects / (float) numberOfObjects) * 100) : 0;
    if (Objects.equals(currentIndexState, currentType) && (numberOfObjects == 0 || progress == 100)) {
        lastIndexed.put(currentIndexState, LocalDateTime.now());
        currentIndexState = ObjectType.NONE;
        if (numberOfObjects == 0) {
            objectIndexingStates.put(currentType, IndexingStates.NO_STATE);
        } else {
            objectIndexingStates.put(currentType, IndexingStates.INDEXING_SUCCESSFUL);
        }
        indexerThread.interrupt();
        pollingChannel.send(INDEXING_FINISHED_MESSAGE + currentType + "!");
    }
    return progress;
}

From source file:org.sakaiproject.rubrics.logic.RubricsServiceImpl.java

/**
 * call the rubrics-service to save the binding between assignment and rubric
 * @param params A hashmap with all the rbcs params comming from the component. The tool should generate it.
 * @param tool the tool id, something like "sakai.assignment"
 * @param id the id of the element to// w  w  w  .ja v a 2s  . c om
 */
public void saveRubricAssociation(String tool, String id, Map<String, String> params) {

    String associationHref = null;
    String created = "";
    String owner = "";
    String ownerType = "";
    String creatorId = "";
    Long oldRubricId = null;
    Map<String, Boolean> oldParams = new HashMap<>();

    try {
        Optional<Resource<ToolItemRubricAssociation>> associationResource = getRubricAssociationResource(tool,
                id, null);
        ToolItemRubricAssociation association = null;
        if (associationResource.isPresent()) {
            associationHref = associationResource.get().getLink(Link.REL_SELF).getHref();
            association = associationResource.get().getContent();
            created = association.getMetadata().getCreated().toString();
            owner = association.getMetadata().getOwnerId();
            ownerType = association.getMetadata().getOwnerType();
            creatorId = association.getMetadata().getCreatorId();
            oldParams = association.getParameters();
            oldRubricId = association.getRubricId();
        }

        //we will create a new one or update if the parameter rbcs-associate is true
        String nowTime = LocalDateTime.now().toString();
        if (params.get(RubricsConstants.RBCS_ASSOCIATE).equals("1")) {

            if (associationHref == null) { // create a new one.
                String input = "{\"toolId\" : \"" + tool + "\",\"itemId\" : \"" + id + "\",\"rubricId\" : "
                        + params.get(RubricsConstants.RBCS_LIST) + ",\"metadata\" : {\"created\" : \"" + nowTime
                        + /*"\",\"modified\" : \"" + nowTime +*/ "\",\"ownerId\" : \""
                        + userDirectoryService.getCurrentUser().getId() + "\"},\"parameters\" : {"
                        + setConfigurationParameters(params, oldParams) + "}}";
                log.debug("New association " + input);
                String query = serverConfigurationService.getServerUrl() + RBCS_SERVICE_URL_PREFIX
                        + "rubric-associations/";
                String resultPost = postRubricResource(query, input, tool, null);
                log.debug("resultPost: " + resultPost);
            } else {
                String input = "{\"toolId\" : \"" + tool + "\",\"itemId\" : \"" + id + "\",\"rubricId\" : "
                        + params.get(RubricsConstants.RBCS_LIST) + ",\"metadata\" : {\"created\" : \"" + created
                        + /*"\",\"modified\" : \"" + nowTime +*/ "\",\"ownerId\" : \"" + owner
                        + "\",\"ownerType\" : \"" + ownerType + "\",\"creatorId\" : \"" + creatorId
                        + "\"},\"parameters\" : {" + setConfigurationParameters(params, oldParams) + "}}";
                log.debug("Existing association update " + input);
                if (Long.valueOf(params.get(RubricsConstants.RBCS_LIST)) != oldRubricId) {
                    deleteRubricEvaluationsForAssociation(associationHref, tool);
                }
                String resultPut = putRubricResource(associationHref, input, tool);
                //update the actual one.
                log.debug("resultPUT: " + resultPut);
            }
        } else {
            // We delete the association
            if (associationHref != null) {
                deleteRubricEvaluationsForAssociation(associationHref, tool);
                deleteRubricResource(associationHref, tool, null);
                if (association != null) {
                    hasAssociatedRubricCache.remove(association.getToolId() + "#" + association.getItemId());
                }
            }
        }

    } catch (Exception e) {
        //TODO If we have an error here, maybe we should return say something to the user
    }
}

From source file:ch.bfh.abcvote.util.controllers.CommunicationController.java

/**
 * Gets a List of ElectionHeaders from the Bulletin Board and returns it. Fetched list depends on the given ElectionFilterTyp
 * @param filter//www .ja  va2  s. c o  m
 * The filter can be set to All, Open or Closed
 * @return returns a list of election headers
 */
public List<ElectionHeader> getElectionHeaders(ElectionFilterTyp filter) {
    List<ElectionHeader> electionHeaderlist = new ArrayList<ElectionHeader>();

    DateTimeFormatter format = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
    LocalDateTime actualDateTime = LocalDateTime.now();
    String dateTimeString = actualDateTime.format(format);

    URL url = null;
    //depending on the filter a different request is sent to the bulletin board
    switch (filter) {
    // if the filter is set to ALL, all the electionheaders on the bulletin board are requested
    case ALL: {
        try {
            url = new URL(bulletinBoardUrl + "/elections");
        } catch (MalformedURLException ex) {
            Logger.getLogger(CommunicationController.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
        break;

    // if the filter is set to OPEN only ElectionHeaders where the VotingPeriod is still going are requested from the bulletin board
    case OPEN: {
        try {
            url = new URL(bulletinBoardUrl + "/elections/open?date="
                    + URLEncoder.encode(dateTimeString, "UTF-8").replace("+", "%20"));
        } catch (UnsupportedEncodingException | MalformedURLException ex) {
            System.err.println(ex);
        }
    }
        break;
    // if the filter is set to CLOSED only ElectionHeaders where the VotingPeriod is already over are requested from the bulletin board
    case CLOSED: {
        try {
            url = new URL(bulletinBoardUrl + "/elections/closed?date="
                    + URLEncoder.encode(dateTimeString, "UTF-8").replace("+", "%20"));
        } catch (UnsupportedEncodingException | MalformedURLException ex) {
            System.err.println(ex);
        }
    }
        break;
    }

    try {

        InputStream urlInputStream = url.openStream();
        JsonReader jsonReader = Json.createReader(urlInputStream);
        JsonArray obj = jsonReader.readArray();
        //Recieved Json String is transformed into a list of ElectionHeader objects
        for (JsonObject result : obj.getValuesAs(JsonObject.class)) {

            int id = Integer.parseInt(result.getString("id"));
            String title = result.getString("electionTitle");
            LocalDateTime beginDate = LocalDateTime.parse(result.getString("beginDate"), format);
            LocalDateTime endDate = LocalDateTime.parse(result.getString("endDate"), format);

            ElectionHeader electionHeader = new ElectionHeader(id, title, beginDate, endDate);
            electionHeaderlist.add(electionHeader);
        }
    } catch (IOException x) {
        System.err.println(x);
    }

    return electionHeaderlist;
}

From source file:com.swcguild.capstoneproject.dao.BlogDaoDbImplTest.java

/**
 * Test of getActiveTags method, of class BlogDaoDbImpl.
 *///from  w  w w  .  j a va2s  . c  o m
@Test
public void testGetActiveTags() {
    System.out.println("getActiveTags");
    Post post1 = new Post("Supergirl", "Clark Kent", "hot new cousin saves city", "super, girl",
            LocalDateTime.now().toString(), "2015-12-20");
    Post post2 = new Post("Super", "Kent", "cousin saves city", "super", LocalDateTime.now().toString(),
            "2015-12-20");
    Post post3 = new Post("girl", "Clar", "new cousin saves city", "girl", LocalDateTime.now().toString(),
            "2015-12-20");
    post1.setStatus(1);
    post2.setStatus(1);
    post3.setStatus(1);
    dao.addPost(post1);
    dao.addPost(post2);
    dao.addPost(post3);
    List<Tag> result = dao.getActiveTags();
    String expT = "supergirl";
    String resT = "";
    for (Tag t : result) {
        resT += t.getTag();
    }
    assertEquals(expT, resT);
}

From source file:com.example.bot.spring.KitchenSinkController.java

private static DownloadedContent createTempFile(String ext) {
    String fileName = LocalDateTime.now().toString() + '-' + UUID.randomUUID().toString() + '.' + ext;
    Path tempFile = KitchenSinkApplication.downloadedContentDir.resolve(fileName);
    tempFile.toFile().deleteOnExit();//www . j  av  a 2s .  co  m
    return new DownloadedContent(tempFile, createUri("/downloaded/" + tempFile.getFileName()));
}

From source file:net.sf.gazpachoquest.dbpopulator.DBPopulator.java

public void populateForDemo(Set<UserDTO> respondents) {
    QuestionnaireDefinitionDTO questionnaireDefinition = sampleQuizCreator.create();
    asignDefaultMailTemplate(questionnaireDefinition);
    questionnaireDefinitionEditorFacade.confirm(questionnaireDefinition);
    Set<QuestionnaireDefinitionDTO> questionnairDefinitions = new HashSet<>();
    questionnairDefinitions.add(questionnaireDefinition);

    ResearchDTO research = ResearchDTO.with().type(ResearchAccessType.BY_INVITATION)
            .name("New Quiz" + questionnaireDefinition.getLanguageSettings().getTitle() + " started")
            .startDate(LocalDateTime.now()).expirationDate(LocalDateTime.of(2015, 12, 31, 12, 0, 0)).build();
    research.setQuestionnaireDefinition(questionnaireDefinition);

    research = researchFacade.save(research);

    Integer researchId = research.getId();

    for (UserDTO respondent : respondents) {
        researchFacade.addRespondent(researchId, respondent);
    }/* ww w  .j  a v  a  2s. com*/
    researchFacade.changeStatus(researchId, EntityStatus.CONFIRMED);

    research = ResearchDTO.with().type(ResearchAccessType.OPEN_ACCESS)
            .name("Anonymous New Quiz" + questionnaireDefinition.getLanguageSettings().getTitle() + " started")
            .startDate(LocalDateTime.now()).expirationDate(LocalDateTime.of(2015, 12, 31, 12, 0, 0)).build();
    research.setQuestionnaireDefinition(questionnaireDefinition);

    research = researchFacade.save(research);

    researchId = research.getId();

    for (UserDTO respondent : respondents) {
        researchFacade.addRespondent(researchId, respondent);
    }
    researchFacade.changeStatus(researchId, EntityStatus.CONFIRMED);

    questionnaireDefinition = fastFoodSurveyCreator.create();
    asignDefaultMailTemplate(questionnaireDefinition);
    questionnaireDefinitionEditorFacade.confirm(questionnaireDefinition);
    questionnairDefinitions = new HashSet<>();
    questionnairDefinitions.add(questionnaireDefinition);

    research = ResearchDTO.with().type(ResearchAccessType.OPEN_ACCESS)
            .name("New customer satisfation survey " + questionnaireDefinition.getLanguageSettings().getTitle()
                    + " started")
            .startDate(LocalDateTime.now()).expirationDate(LocalDateTime.of(2015, 12, 31, 12, 0, 0)).build();
    research.setQuestionnaireDefinition(questionnaireDefinition);
    researchFacade.save(research);
}

From source file:nc.noumea.mairie.appock.services.impl.CommandeServiceImpl.java

@Override
public Commande passeCommande(Commande commande) {
    AppUser appUser = authHelper.getCurrentUser();
    commande.setEtatCommande(EtatCommande.EN_ATTENTE_RECEPTION_COMMANDE);
    commande.setDatePassageCommande(LocalDateTime.now());
    commande.setPassageUser(appUser.getNomComplet());

    List<ArticleDemande> listeArticleDemandeQuantiteAgrege = construitListeArticleDemandeQuantiteAgrege(
            commande.getListeDemande());
    Map<Service, List<ArticleCommande>> mapServiceArticleCommande = new HashMap<>();
    for (ArticleDemande articleDemande : listeArticleDemandeQuantiteAgrege) {
        ArticleCommande articleCommande = new ArticleCommande();
        articleCommande.setArticleCatalogue(articleDemande.getArticleCatalogue());
        articleCommande.setQuantiteCommande(articleDemande.getQuantiteCommande());
        articleCommande.setQuantiteRecu(articleDemande.getQuantiteCommande());

        Service service = articleDemande.getDemande().getService();
        if (mapServiceArticleCommande.get(service) != null) {
            mapServiceArticleCommande.get(service).add(articleCommande);
        } else {//from w  w w  .j av  a  2 s. c  om
            List<ArticleCommande> listeArticleCommande = new ArrayList<>();
            listeArticleCommande.add(articleCommande);
            mapServiceArticleCommande.put(service, listeArticleCommande);
        }
    }

    for (Service service : mapServiceArticleCommande.keySet()) {
        CommandeService commandeService = new CommandeService();
        commandeService.setCommande(commande);
        commandeService.setService(service);
        List<ArticleCommande> listeArticleCommande = mapServiceArticleCommande.get(service);
        for (ArticleCommande articleCommande : listeArticleCommande) {
            articleCommande.setCommandeService(commandeService);
        }
        commandeService.setListeArticleCommande(listeArticleCommande);
        commande.getListeCommandeService().add(commandeService);
    }

    for (Demande demande : commande.getListeDemande()) {
        demande.setEtatDemande(EtatDemande.EN_ATTENTE_RECEPTION);
        demandeRepository.save(demande);
    }

    return commandeRepository.save(commande);
}

From source file:kitt.site.controller.mobile.UserController.java

/**
 * ? - ??//from ww  w . j av a2  s .  c  o m
 * @param newPhone                   ?
 * @param code                       ??
 * @param user
 */
@RequestMapping(value = "/account/changePhone", method = RequestMethod.POST)
@LoginRequired
@ResponseBody
public Object changePhone(String newPhone, String code, @CurrentUser User user, BindResult bindResult) {
    Phonevalidator phonevalidator = validMapper.findVerifyCode(newPhone, code,
            ValidateType.updatePhoneNumWeixin);
    User newUser = userMapper.getUserByPhone(newPhone);
    if (newUser != null) {
        bindResult.addError("userIsExists", "??!");
    } else if (StringUtils.isBlank(code)) {
        bindResult.addError("verifyCode", "???!");
    } else if (phonevalidator == null) {
        bindResult.addError("verifyCode", "??!");
    } else if (phonevalidator.getExpiretime().isBefore(LocalDateTime.now())) {
        bindResult.addError("verifyCode", "??!");
    } else {
        validMapper.modifyValidatedAndTime(newPhone, code);
        userMapper.modifyPhone(newPhone, user.getId());
        user.setSecurephone(newPhone);
    }
    return json(bindResult);
}

From source file:com.swcguild.capstoneproject.dao.BlogDaoDbImplTest.java

/**
 * Test of addPinPost method, of class BlogDaoDbImpl.
 *///  ww w .  j  a  va2s.  com
@Test
public void testAddPinPost() {
    System.out.println("addPinPost");
    PinPost pinPost = new PinPost("Cali", "Shawn", "Won by 14", LocalDateTime.now().toString(), "2016-01-01");

    dao.addPinPost(pinPost);
    assertEquals(1, dao.getAllPinPosts().size());
}

From source file:alfio.manager.WaitingQueueManagerIntegrationTest.java

@Test
public void testAssignTicketToWaitingQueueBoundedCategory() {
    LocalDateTime start = LocalDateTime.now().minusMinutes(2);
    LocalDateTime end = LocalDateTime.now().plusMinutes(20);
    List<TicketCategoryModification> categories = Collections.singletonList(new TicketCategoryModification(null,
            "default", AVAILABLE_SEATS, new DateTimeModification(start.toLocalDate(), start.toLocalTime()),
            new DateTimeModification(end.toLocalDate(), end.toLocalTime()), DESCRIPTION, BigDecimal.TEN, false,
            "", true, null, null, null, null, null));

    configurationManager.saveSystemConfiguration(ConfigurationKeys.ENABLE_WAITING_QUEUE, "true");

    Event event = initEvent(categories, organizationRepository, userManager, eventManager, eventRepository)
            .getKey();//from  w ww  .j  ava2 s .co  m

    TicketCategory bounded = ticketCategoryRepository.findByEventId(event.getId()).get(0);

    TicketReservationModification tr = new TicketReservationModification();
    tr.setAmount(AVAILABLE_SEATS - 1);
    tr.setTicketCategoryId(bounded.getId());

    TicketReservationModification tr2 = new TicketReservationModification();
    tr2.setAmount(1);
    tr2.setTicketCategoryId(bounded.getId());

    TicketReservationWithOptionalCodeModification multi = new TicketReservationWithOptionalCodeModification(tr,
            Optional.empty());
    TicketReservationWithOptionalCodeModification single = new TicketReservationWithOptionalCodeModification(
            tr2, Optional.empty());

    String reservationId = ticketReservationManager.createTicketReservation(event,
            Collections.singletonList(multi), Collections.emptyList(), DateUtils.addDays(new Date(), 1),
            Optional.empty(), Optional.empty(), Locale.ENGLISH, false);
    TotalPrice reservationCost = ticketReservationManager.totalReservationCostWithVAT(reservationId);
    PaymentResult result = ticketReservationManager.confirm("", null, event, reservationId, "test@test.ch",
            new CustomerName("Full Name", "Full", "Name", event), Locale.ENGLISH, "", reservationCost,
            Optional.empty(), Optional.of(PaymentProxy.OFFLINE), false, null, null, null);
    assertTrue(result.isSuccessful());

    String reservationIdSingle = ticketReservationManager.createTicketReservation(event,
            Collections.singletonList(single), Collections.emptyList(), DateUtils.addDays(new Date(), 1),
            Optional.empty(), Optional.empty(), Locale.ENGLISH, false);
    TotalPrice reservationCostSingle = ticketReservationManager
            .totalReservationCostWithVAT(reservationIdSingle);
    PaymentResult resultSingle = ticketReservationManager.confirm("", null, event, reservationIdSingle,
            "test@test.ch", new CustomerName("Full Name", "Full", "Name", event), Locale.ENGLISH, "",
            reservationCostSingle, Optional.empty(), Optional.of(PaymentProxy.OFFLINE), false, null, null,
            null);
    assertTrue(resultSingle.isSuccessful());

    assertEquals(0, eventRepository.findStatisticsFor(event.getId()).getDynamicAllocation());

    assertTrue(
            waitingQueueManager.subscribe(event, customerJohnDoe(event), "john@doe.com", null, Locale.ENGLISH));

    ticketReservationManager.deleteOfflinePayment(event, reservationIdSingle, false);

    List<Triple<WaitingQueueSubscription, TicketReservationWithOptionalCodeModification, ZonedDateTime>> subscriptions = waitingQueueManager
            .distributeSeats(event).collect(Collectors.toList());
    assertEquals(1, subscriptions.size());
    Triple<WaitingQueueSubscription, TicketReservationWithOptionalCodeModification, ZonedDateTime> subscriptionDetail = subscriptions
            .get(0);
    assertEquals("john@doe.com", subscriptionDetail.getLeft().getEmailAddress());
    TicketReservationWithOptionalCodeModification reservation = subscriptionDetail.getMiddle();
    assertEquals(Integer.valueOf(bounded.getId()), reservation.getTicketCategoryId());
    assertEquals(Integer.valueOf(1), reservation.getAmount());
    assertTrue(subscriptionDetail.getRight().isAfter(ZonedDateTime.now()));
}