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:com.swcguild.capstoneproject.dao.BlogDaoDbImplTest.java

/**
 * Test of publishPost method, of class BlogDaoDbImpl.
 *///  ww  w . j  a  va2 s .co m
@Test
public void testPublishPost() {
    System.out.println("publishPost");
    Post post3 = new Post("girl", "Clar", "new cousin saves city", "girl", LocalDateTime.now().toString(),
            "2015-12-20");
    post3.setStatus(1);
    dao.addPost(post3);
    dao.publishPost(post3.getPostID(), post3);
    assertEquals(1, post3.getStatus());
}

From source file:org.cyberjos.jcconf2016.node.HazelcastHelper.java

/**
 * Creates and runs a new consumer.//from   w  w w .j  av a 2  s.  c  om
 *
 * @param cloudNode the cloud node which runs this new consumer
 */
private void runConsumer(final CloudNode cloudNode) {
    final Thread thread = new Thread(() -> {
        final long serialNumber = HazelcastHelper.getAtomicLong("WORKER_SN").incrementAndGet();
        final String time = LocalDateTime.now().format(NAME_FORMATTER);
        final String workerName = String.format("Worker-%d-%s", serialNumber, time);
        final String nodeName = cloudNode.getName();
        logger.info("[{}] Starting a new consumer thread: {}.", nodeName, workerName);

        while (!this.isMaster(cloudNode)) {
            try {
                logger.debug("[{}] Waiting for incoming task...", workerName);
                final int taskSize = HazelcastHelper.this.getTaskQueue().take();
                logger.debug("[{}] Received task size: {}", workerName, taskSize);
                final IMap<Long, Integer> map = HazelcastHelper.getMap(BIG_DATA);
                final IAtomicLong serial = HazelcastHelper.getAtomicLong(BIG_DATA);
                logger.debug("[{}] Before map size : {}, SN: {}", workerName, map.size(), serial.get());
                for (int i = 0; i < taskSize; i++) {
                    map.put(serial.incrementAndGet(), RandomUtils.nextInt(MIN_VALUE, MAX_VALUE));
                }
                logger.debug("[{}] After map size: {}, SN: {}", workerName, map.size(), serial.get());
                logger.info("[{}] Finished task: {}", workerName, taskSize);
                Thread.sleep(RandomUtils.nextInt(MIN_WAIT_CONSUMER, MAX_WAIT_CONSUMER));
            } catch (final Exception ex) {
                logger.error(String.format("[%s] Exception occurred", workerName), ex);
            }
        }
    });
    thread.start();
}

From source file:demo.admin.controller.UserController.java

@RequestMapping(value = "/user/saveCompanyInfo", method = RequestMethod.POST)
public Object saveCompany(@RequestParam("userid") int userid, @RequestParam("name") String name,
        @RequestParam("address") String address,
        @RequestParam("invoicinginformation") String invoicinginformation,
        @RequestParam("businesslicense") String businesslicense,
        @RequestParam("identificationnumber") String identificationnumber,
        @RequestParam("organizationcode") String organizationcode,
        @RequestParam("operatinglicense") String operatinglicense,
        @RequestParam("openinglicense") String openinglicense,
        @RequestParam("legalpersonname") String legalpersonname, @RequestParam("account") String account,
        @RequestParam("openingbank") String openingbank,
        @RequestParam("identificationnumword") String identificationnumword,
        @RequestParam("zipcode") String zipcode) {
    Company companyc = companyMapper.getCompanyByUserid(userid);
    Company company;/*from  w  w w .  j ava  2  s .com*/
    User user = userMapper.getUserById(userid);
    if (companyc == null) {
        company = new Company(name, address, user.getSecurephone(), null, invoicinginformation, businesslicense,
                identificationnumber, organizationcode, operatinglicense, openinglicense, legalpersonname,
                account, openingbank, userid, identificationnumword, zipcode);
        companyMapper.addCompany(company);
    } else {
        String cname = (StringUtils.isNullOrEmpty(name) == true ? companyc.getName() : name);
        String caddress = (StringUtils.isNullOrEmpty(address) == true ? companyc.getAddress() : address);
        String cinvoicinginformation = (StringUtils.isNullOrEmpty(invoicinginformation) == true
                ? companyc.getInvoicinginformation()
                : invoicinginformation);
        String cbusinesslicense = (StringUtils.isNullOrEmpty(businesslicense) == true
                ? companyc.getBusinesslicense()
                : businesslicense);
        String cidentificationnumber = (StringUtils.isNullOrEmpty(identificationnumber) == true
                ? companyc.getIdentificationnumber()
                : identificationnumber);
        String corganizationcode = (StringUtils.isNullOrEmpty(organizationcode) == true
                ? companyc.getOrganizationcode()
                : organizationcode);
        String coperatinglicense = (StringUtils.isNullOrEmpty(operatinglicense) == true
                ? companyc.getOperatinglicense()
                : operatinglicense);
        String copeninglicense = (StringUtils.isNullOrEmpty(openinglicense) == true
                ? companyc.getOpeninglicense()
                : openinglicense);
        String clegalpersonname = (StringUtils.isNullOrEmpty(legalpersonname) == true
                ? companyc.getLegalpersonname()
                : legalpersonname);
        String caccount = (StringUtils.isNullOrEmpty(account) == true ? companyc.getAccount() : account);
        String copeningbank = (StringUtils.isNullOrEmpty(openingbank) == true ? companyc.getOpeningbank()
                : openingbank);
        String cidentificationnumword = (StringUtils.isNullOrEmpty(identificationnumword) == true
                ? companyc.getIdentificationnumword()
                : identificationnumword);
        String czipcode = (StringUtils.isNullOrEmpty(zipcode) == true ? companyc.getZipcode() : zipcode);
        company = new Company(cname, caddress, companyc.getPhone(), companyc.getFax(), cinvoicinginformation,
                cbusinesslicense, cidentificationnumber, corganizationcode, coperatinglicense, copeninglicense,
                clegalpersonname, caccount, copeningbank, userid, cidentificationnumword, czipcode);
        companyMapper.modifyCompany(company);
    }
    companyMapper.setCompanyStatus("", null, companyMapper.getIdByUserid(userid));
    companyMapper.addCompVerify(
            new CompanyVerify("", LocalDateTime.now(), companyMapper.getIdByUserid(userid), userid));
    userMapper.setUserVerifyStatus("", userid);
    return true;
}

From source file:com.ccserver.digital.controller.AdminControllerTest.java

private CreditCardApplicationDTO getCreditCardApplicationDTO() {
    CreditCardApplicationDTO creditCardApplicationDTO = new CreditCardApplicationDTO();

    // ----- losApplicationId
    ApplicationLOSDTO losDTO = new ApplicationLOSDTO();
    losDTO.setLosApplicationId("123ABC");
    creditCardApplicationDTO.setApplicationLOS(losDTO);

    // ----- cardType

    // ----- DoB/*from   w  w  w .  j a va  2  s. c  o m*/
    creditCardApplicationDTO.setDob(LocalDateTime.now());

    // ----- Name
    creditCardApplicationDTO.setFirstName("LE");
    creditCardApplicationDTO.setMiddleName("Hong");
    creditCardApplicationDTO.setLastName("Thanh");

    // ----- gender
    creditCardApplicationDTO.setGender(Gender.Male);

    // ----- Moblie
    PhoneDTO moblie = new PhoneDTO();
    moblie.setCountryCode("+84");
    moblie.setPhoneNumber("985481179");
    creditCardApplicationDTO.setMobile(moblie);

    // ----- phoneBusiness
    PhoneDTO phoneBusiness = new PhoneDTO();
    phoneBusiness.setCountryCode("+84");
    phoneBusiness.setPhoneNumber("985481179");
    creditCardApplicationDTO.setBusinessPhone(phoneBusiness);

    // ----- email
    creditCardApplicationDTO.setEmail("letuanthuongtin@gmail.com");

    // ----- passportNumber
    creditCardApplicationDTO.setPassportNumber("123456789");

    // ----- dateOfIssue
    creditCardApplicationDTO.setDateOfIssue(LocalDateTime.now());

    // ----- placeOfIssue
    SelectionList selectionListDTO = new SelectionList();
    selectionListDTO.setCategory("plauceOfise");
    selectionListDTO.setCode("11");
    creditCardApplicationDTO.setPlaceOfIssue(selectionListDTO);

    // ----- citizenship
    CountryDTO citizenship = new CountryDTO();
    citizenship.setId(1L);
    citizenship.setCode("VN");
    citizenship.setVi("Viet Nam");
    citizenship.setEn("VietNam");
    creditCardApplicationDTO.setCitizenship(citizenship);

    // ----- haveGreenCard
    creditCardApplicationDTO.setHaveGreenCard(true);

    // ----- isUSResident
    creditCardApplicationDTO.setUSResident(true);

    // ----- education
    // creditCardApplicationDTO.setEducation(EducationQualification.HighShool);

    // ----- maritalStatus
    // creditCardApplicationDTO.setMaritalStatus(MaritalStatus.Single);

    // ----- numberOfChildren
    creditCardApplicationDTO.setNumberOfChildren(4);

    // ----- permanent address---
    // TODO: create province and district for integration test
    AddressDTO permanentAddress = new AddressDTO();
    BaseProvinceDTO province = new BaseProvinceDTO();
    province.setName("Ha Noi");
    province.setId(1L);
    DistrictDTO districtDTO1 = new DistrictDTO();
    districtDTO1.setName("Hai Ba Trung");
    districtDTO1.setId(1L);
    permanentAddress.setDistrict(districtDTO1);
    permanentAddress.setProvince(province);
    permanentAddress.setStreet("LE Thanh NGhi");
    permanentAddress.setAddressDetails("So Nha 18");
    creditCardApplicationDTO.setPermanentAddress(permanentAddress);

    // ----- currentIsPermanent
    creditCardApplicationDTO.setCurrentIsPermanent(true);

    // ----- currentAddress
    creditCardApplicationDTO.setCurrentAddress(permanentAddress);

    // ----- typeOfEmployement
    creditCardApplicationDTO.setTypeOfEmployement(TypeOfEmployment.Business);

    // ----- licenseNumber
    creditCardApplicationDTO.setLicenseNumber("12345");

    // ----- businessStartDate
    creditCardApplicationDTO.setBusinessStartDate(LocalDateTime.now());

    // ----- businessTelephone
    PhoneDTO businessTelephone = new PhoneDTO();
    businessTelephone.setCountryCode("+84");
    businessTelephone.setPhoneNumber("985481179");
    businessTelephone.setExt("01");
    creditCardApplicationDTO.setBusinessTelephone(businessTelephone);

    // ----- businessAddress
    creditCardApplicationDTO.setBusinessAddress(permanentAddress);

    // ----- nameOfEmployer
    CompanyDTO companyDTO = new CompanyDTO();
    companyDTO.setCode("111");
    creditCardApplicationDTO.setNameOfEmployer(companyDTO);

    // ----- occupation
    //creditCardApplicationDTO.setOccupation("Engineer");

    // ----- industry
    // creditCardApplicationDTO.setIndustry("finance");

    // ----- yearsOfWorking
    creditCardApplicationDTO.setYearsOfWorking(1);

    // ----- monthsOfWorking
    creditCardApplicationDTO.setMonthsOfWorking(8);

    // ----- employerAddress
    creditCardApplicationDTO.setEmployerAddress(permanentAddress);

    // ----- monthlyIncome
    creditCardApplicationDTO.setMonthlyIncome(new BigDecimal("10"));

    // ----- monthlyExpenses
    creditCardApplicationDTO.setMonthlyExpenses(new BigDecimal("5"));

    // ----- securityQuestion
    SelectionListDTO securityQuestion = new SelectionListDTO();
    securityQuestion.setId(3L);
    creditCardApplicationDTO.setSecurityQuestion(securityQuestion);

    // ----- securityAnswer
    creditCardApplicationDTO.setSecurityAnswer("Thanh");

    // ----- referenceName
    creditCardApplicationDTO.setReferenceName("LE Tuan");

    // ----- relationshipReference
    SelectionListDTO relationship = new SelectionListDTO();
    relationship.setId(3L);
    creditCardApplicationDTO.setRelationshipReference(relationship);

    // ----- phoneOfReference
    creditCardApplicationDTO.setPhoneOfReference(moblie);

    // ----- branchDelivery
    // creditCardApplicationDTO.setDeliveryCard("Branch 1");

    // ----- isSecondaryCard
    creditCardApplicationDTO.setSecondaryCard(true);

    // ----- isAccurateCommit
    creditCardApplicationDTO.setAccurateCommit(true);

    // ----- agreeTermsConditions
    creditCardApplicationDTO.setAgreeTermsConditions(true);

    return creditCardApplicationDTO;
}

From source file:org.apache.hadoop.yarn.server.resourcemanager.security.TestHopsworksRMAppSecurityActions.java

@Test
public void testConfUpdate() throws Exception {
    LocalDateTime now = LocalDateTime.now();
    Date nbf = DateUtils.localDateTime2Date(now);
    LocalDateTime expiration = now.plus(10, ChronoUnit.MINUTES);
    Date expirationDate = DateUtils.localDateTime2Date(expiration);
    JWTClaimsSet masterClaims = new JWTClaimsSet();
    masterClaims.setSubject("master_token");
    masterClaims.setExpirationTime(expirationDate);
    masterClaims.setNotBeforeTime(nbf);//  w  ww.j  ava  2  s. co  m
    String newMasterToken = jwtIssuer.generate(masterClaims);
    Assert.assertNotNull(newMasterToken);

    String[] newRenewalTokens = new String[5];
    JWTClaimsSet renewClaims = new JWTClaimsSet();
    renewClaims.setSubject("renew_token");
    renewClaims.setExpirationTime(expirationDate);
    renewClaims.setNotBeforeTime(nbf);
    for (int i = 0; i < newRenewalTokens.length; i++) {
        String renewToken = jwtIssuer.generate(renewClaims);
        Assert.assertNotNull(renewToken);
        newRenewalTokens[i] = renewToken;
    }
    RMAppSecurityActions actor = new TestingHopsworksActions(newMasterToken, expirationDate, newRenewalTokens);
    ((Configurable) actor).setConf(conf);
    actor.init();
    TimeUnit.MILLISECONDS.sleep(500);

    // Renewal must have happened, check new values in ssl-server
    Configuration sslConf = new Configuration();
    sslConf.addResource(conf.get(SSLFactory.SSL_SERVER_CONF_KEY));
    String newMasterTokenConf = sslConf.get(YarnConfiguration.RM_JWT_MASTER_TOKEN, "");
    Assert.assertEquals(newMasterToken, newMasterTokenConf);
    for (int i = 0; i < newRenewalTokens.length; i++) {
        String confKey = String.format(YarnConfiguration.RM_JWT_RENEW_TOKEN_PATTERN, i);
        String newRenewalToken = sslConf.get(confKey, "");
        Assert.assertEquals(newRenewalTokens[i], newRenewalToken);
    }

    DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss");
    Assert.assertEquals(expiration.format(formatter),
            ((HopsworksRMAppSecurityActions) actor).getMasterTokenExpiration().format(formatter));
    actor.destroy();
}

From source file:com.bekwam.resignator.ResignatorAppMainViewController.java

@FXML
public void initialize() {

    try {//from   w  w w  .  ja va 2  s  . co  m

        miHelp.setAccelerator(KeyCombination.keyCombination("F1"));

        cbType.getItems().add(SigningArgumentsType.JAR);
        cbType.getItems().add(SigningArgumentsType.FOLDER);

        cbType.getSelectionModel().select(SigningArgumentsType.JAR);

        cbType.setConverter(new StringConverter<SigningArgumentsType>() {

            @Override
            public String toString(SigningArgumentsType type) {
                return StringUtils.capitalize(StringUtils.lowerCase(String.valueOf(type)));
            }

            @Override
            public SigningArgumentsType fromString(String type) {
                return Enum.valueOf(SigningArgumentsType.class, StringUtils.upperCase(type));
            }

        });

        activeConfiguration.activeProfileProperty().bindBidirectional(activeProfile.profileNameProperty());
        tfSourceFile.textProperty().bindBidirectional(activeProfile.sourceFileFileNameProperty());
        tfTargetFile.textProperty().bindBidirectional(activeProfile.targetFileFileNameProperty());
        ckReplace.selectedProperty().bindBidirectional(activeProfile.replaceSignaturesProperty());
        cbType.valueProperty().bindBidirectional(activeProfile.argsTypeProperty());

        miSave.disableProperty().bind(needsSave.not());

        tfSourceFile.textProperty().addListener(new WeakInvalidationListener(needsSaveListener));
        tfTargetFile.textProperty().addListener(new WeakInvalidationListener(needsSaveListener));
        ckReplace.selectedProperty().addListener(new WeakInvalidationListener(needsSaveListener));
        cbType.valueProperty().addListener(new WeakInvalidationListener(needsSaveListener));

        lblSource.setText(SOURCE_LABEL_JAR);
        lblTarget.setText(TARGET_LABEL_JAR);
        cbType.getSelectionModel().selectedItemProperty().addListener((ov, old_v, new_v) -> {
            if (new_v == SigningArgumentsType.FOLDER) {
                if (!lblSource.getText().equalsIgnoreCase(SOURCE_LABEL_FOLDER)) {
                    lblSource.setText(SOURCE_LABEL_FOLDER);
                }
                if (!lblSource.getText().equalsIgnoreCase(TARGET_LABEL_FOLDER)) {
                    lblTarget.setText(TARGET_LABEL_FOLDER);
                }
            } else {
                if (!lblSource.getText().equalsIgnoreCase(SOURCE_LABEL_JAR)) {
                    lblSource.setText(SOURCE_LABEL_JAR);
                }
                if (!lblSource.getText().equalsIgnoreCase(TARGET_LABEL_JAR)) {
                    lblTarget.setText(TARGET_LABEL_JAR);
                }
            }
        });

        lvProfiles.getSelectionModel().selectedItemProperty().addListener((ov, old_v, new_v) -> {

            if (new_v == null) { // coming from clearSelection or sort
                return;
            }

            if (needsSave.getValue()) {

                Alert alert = new Alert(Alert.AlertType.CONFIRMATION, "Discard unsaved profile?");
                alert.setHeaderText("Unsaved profile");
                Optional<ButtonType> response = alert.showAndWait();
                if (!response.isPresent() || response.get() != ButtonType.OK) {
                    if (logger.isDebugEnabled()) {
                        logger.debug("[SELECT] discard canceled");
                    }
                    return;
                }
            }

            if (logger.isDebugEnabled()) {
                logger.debug("[SELECT] nv={}", new_v);
            }
            doLoadProfile(new_v);
        });

        lvProfiles.setCellFactory(TextFieldListCell.forListView());

        Task<Void> t = new Task<Void>() {

            @Override
            protected Void call() throws Exception {

                updateMessage("Loading configuration");
                configurationDS.loadConfiguration();

                if (!configurationDS.isSecured()) {
                    if (logger.isDebugEnabled()) {
                        logger.debug("[CALL] config not secured; getting password");
                    }
                    NewPasswordController npc = newPasswordControllerProvider.get();

                    if (logger.isDebugEnabled()) {
                        logger.debug("[INIT TASK] npc id={}", npc.hashCode());
                    }

                    Platform.runLater(() -> {
                        try {
                            npc.showAndWait();
                        } catch (Exception exc) {
                            logger.error("error showing npc", exc);
                        }
                    });

                    synchronized (npc) {
                        try {
                            npc.wait(MAX_WAIT_TIME); // 10 minutes to enter the password
                        } catch (InterruptedException exc) {
                            logger.error("new password operation interrupted", exc);
                        }
                    }

                    if (logger.isDebugEnabled()) {
                        logger.debug("[INIT TASK] npc={}", npc.getHashedPassword());
                    }

                    if (StringUtils.isNotEmpty(npc.getHashedPassword())) {

                        activeConfiguration.setHashedPassword(npc.getHashedPassword());
                        activeConfiguration.setUnhashedPassword(npc.getUnhashedPassword());
                        activeConfiguration.setLastUpdatedDateTime(LocalDateTime.now());
                        configurationDS.saveConfiguration();

                        configurationDS.loadConfiguration();
                        configurationDS.decrypt(activeConfiguration.getUnhashedPassword());

                    } else {

                        Platform.runLater(() -> {
                            Alert noPassword = new Alert(Alert.AlertType.INFORMATION,
                                    "You'll need to provide a password to save your keystore credentials.");
                            noPassword.showAndWait();
                        });

                        return null;
                    }
                } else {

                    PasswordController pc = passwordControllerProvider.get();

                    Platform.runLater(() -> {
                        try {
                            pc.showAndWait();
                        } catch (Exception exc) {
                            logger.error("error showing pc", exc);
                        }
                    });

                    synchronized (pc) {
                        try {
                            pc.wait(MAX_WAIT_TIME); // 10 minutes to enter the password
                        } catch (InterruptedException exc) {
                            logger.error("password operation interrupted", exc);
                        }
                    }

                    Platform.runLater(() -> {

                        if (pc.getStage().isShowing()) { // ended in timeout timeout
                            pc.getStage().hide();
                        }

                        if (pc.wasCancelled() || pc.wasReset() || !pc.doesPasswordMatch()) {

                            if (logger.isDebugEnabled()) {
                                logger.debug("[INIT TASK] was cancelled or the number of retries was exceeded");
                            }

                            String msg = "";
                            if (pc.wasCancelled()) {
                                msg = "You must provide a password to the datastore. Exitting...";
                            } else if (pc.wasReset()) {
                                msg = "Data file removed. Exitting...";
                            } else {
                                msg = "Exceeded maximum number of retries. Exitting...";
                            }

                            Alert alert = new Alert(Alert.AlertType.WARNING, msg);
                            alert.setOnCloseRequest((evt) -> {
                                Platform.exit();
                                System.exit(1);
                            });
                            alert.showAndWait();

                        } else {

                            //
                            // save password for later decryption ops
                            //

                            activeConfiguration.setUnhashedPassword(pc.getPassword());
                            configurationDS.decrypt(activeConfiguration.getUnhashedPassword());

                            //
                            // init profileBrowser
                            //
                            if (logger.isDebugEnabled()) {
                                logger.debug("[INIT TASK] loading profiles from source");
                            }

                            long startTimeMillis = System.currentTimeMillis();

                            final List<String> profileNames = configurationDS.getProfiles().stream()
                                    .map(Profile::getProfileName).sorted((o1, o2) -> o1.compareToIgnoreCase(o2))
                                    .collect(Collectors.toList());

                            final List<String> recentProfiles = configurationDS.getRecentProfileNames();

                            if (logger.isDebugEnabled()) {
                                logger.debug("[INIT TASK] loading profiles into UI");
                            }

                            lvProfiles.setItems(FXCollections.observableArrayList(profileNames));

                            if (CollectionUtils.isNotEmpty(recentProfiles)) {
                                mRecentProfiles.getItems().clear();
                                mRecentProfiles.getItems().addAll(
                                        FXCollections.observableArrayList(recentProfiles.stream().map((s) -> {
                                            MenuItem mi = new MenuItem(s);
                                            mi.setOnAction(recentProfileLoadHandler);
                                            return mi;
                                        }).collect(Collectors.toList())));
                            }

                            //
                            // #31 preload the last active profile
                            //
                            if (StringUtils.isNotEmpty(activeConfiguration.getActiveProfile())) {

                                if (logger.isDebugEnabled()) {
                                    logger.debug("[INIT TASK] preloading last active profile={}",
                                            activeConfiguration.getActiveProfile());
                                }
                                doLoadProfile(activeConfiguration.getActiveProfile());
                            }

                            long endTimeMillis = System.currentTimeMillis();

                            if (logger.isDebugEnabled()) {
                                logger.debug("[INIT TASK] loading profiles took {} ms",
                                        (endTimeMillis - startTimeMillis));
                            }
                        }
                    });
                }

                return null;
            }

            @Override
            protected void succeeded() {
                super.succeeded();
                updateMessage("");
                lblStatus.textProperty().unbind();
            }

            @Override
            protected void cancelled() {
                super.cancelled();
                logger.error("task cancelled", getException());
                updateMessage("");
                lblStatus.textProperty().unbind();
            }

            @Override
            protected void failed() {
                super.failed();
                logger.error("task failed", getException());
                updateMessage("");
                lblStatus.textProperty().unbind();
            }
        };

        lblStatus.textProperty().bind(t.messageProperty());

        new Thread(t).start();

    } catch (Exception exc) {

        logger.error("can't load configuration", exc);

        String msg = "Verify that the user has access to the directory '" + configFile + "' under "
                + System.getProperty("user.home") + ".";

        Alert alert = new Alert(Alert.AlertType.ERROR, msg);
        alert.setHeaderText("Can't load config file");
        alert.showAndWait();

        Platform.exit();
    }
}

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

/**
 * Test of getTagsById method, of class BlogDaoDbImpl.
 *///from  w  w  w.j  ava 2  s . c o m
@Test
public void testGetTagsById() {
    System.out.println("getTagsById");
    Post p1 = new Post("Supergirl", "Clark Kent", "hot new cousin saves city", "super",
            LocalDateTime.now().toString(), "2015-12-30");
    Post p2 = new Post("Supergirl", "Clark Kent", "hot new cousin saves city", "super1",
            LocalDateTime.now().toString(), "2015-12-30");
    Post p3 = new Post("Supergirl", "Clark Kent", "hot new cousin saves city", "super2",
            LocalDateTime.now().toString(), "2015-12-30");
    dao.addPost(p1);
    dao.addPost(p2);
    dao.addPost(p3);

    int postID = p1.getPostID();
    String expresult = p1.getTags();
    String result = dao.getTagsById(postID);
    assertEquals(expresult, result);
}

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

@CacheEvict(value = WallRideCacheConfiguration.USER_CACHE, allEntries = true)
public List<UserInvitation> inviteUsers(UserInvitationCreateRequest form, BindingResult result,
        AuthorizedUser authorizedUser) throws MessagingException {
    String[] recipients = StringUtils.commaDelimitedListToStringArray(form.getInvitees());

    LocalDateTime now = LocalDateTime.now();

    List<UserInvitation> invitations = new ArrayList<>();
    for (String recipient : recipients) {
        UserInvitation invitation = new UserInvitation();
        invitation.setEmail(recipient);//from w w  w . ja  v  a 2s. c o  m
        invitation.setMessage(form.getMessage());
        invitation.setExpiredAt(now.plusHours(72));
        invitation.setCreatedAt(now);
        invitation.setCreatedBy(authorizedUser.toString());
        invitation.setUpdatedAt(now);
        invitation.setUpdatedBy(authorizedUser.toString());
        invitation = userInvitationRepository.saveAndFlush(invitation);
        invitations.add(invitation);
    }

    Blog blog = blogService.getBlogById(Blog.DEFAULT_ID);
    for (UserInvitation invitation : invitations) {
        String websiteTitle = blog.getTitle(LocaleContextHolder.getLocale().getLanguage());
        String signupLink = ServletUriComponentsBuilder.fromCurrentContextPath().path("/_admin/signup")
                .queryParam("token", invitation.getToken()).buildAndExpand().toString();

        final Context ctx = new Context(LocaleContextHolder.getLocale());
        ctx.setVariable("websiteTitle", websiteTitle);
        ctx.setVariable("authorizedUser", authorizedUser);
        ctx.setVariable("signupLink", signupLink);
        ctx.setVariable("invitation", invitation);

        final MimeMessage mimeMessage = mailSender.createMimeMessage();
        final MimeMessageHelper message = new MimeMessageHelper(mimeMessage, true, "UTF-8"); // true = multipart
        message.setSubject(MessageFormat.format(
                messageSourceAccessor.getMessage("InvitationMessageTitle", LocaleContextHolder.getLocale()),
                authorizedUser.toString(), websiteTitle));
        message.setFrom(authorizedUser.getEmail());
        message.setTo(invitation.getEmail());

        final String htmlContent = templateEngine.process("user-invite", ctx);
        message.setText(htmlContent, true); // true = isHtml

        mailSender.send(mimeMessage);
    }

    return invitations;
}

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

@CacheEvict(value = WallRideCacheConfiguration.ARTICLE_CACHE, allEntries = true)
public Article saveArticle(ArticleUpdateRequest request, AuthorizedUser authorizedUser) {
    postRepository.lock(request.getId());
    Article article = articleRepository.findOneByIdAndLanguage(request.getId(), request.getLanguage());
    LocalDateTime now = LocalDateTime.now();

    String code = request.getCode();
    if (code == null) {
        try {//  w  w w  .  java2 s  .  co  m
            code = new CodeFormatter().parse(request.getTitle(), LocaleContextHolder.getLocale());
        } catch (ParseException e) {
            throw new ServiceException(e);
        }
    }
    if (!StringUtils.hasText(code)) {
        if (!article.getStatus().equals(Post.Status.DRAFT)) {
            throw new EmptyCodeException();
        }
    }
    if (!article.getStatus().equals(Post.Status.DRAFT)) {
        Post duplicate = postRepository.findOneByCodeAndLanguage(code, request.getLanguage());
        if (duplicate != null && !duplicate.equals(article)) {
            throw new DuplicateCodeException(code);
        }
    }

    if (!article.getStatus().equals(Post.Status.DRAFT)) {
        article.setCode(code);
        article.setDraftedCode(null);
    } else {
        article.setCode(null);
        article.setDraftedCode(code);
    }

    Media cover = null;
    if (request.getCoverId() != null) {
        cover = entityManager.getReference(Media.class, request.getCoverId());
    }
    article.setCover(cover);
    article.setTitle(request.getTitle());
    article.setBody(request.getBody());

    //      User author = null;
    //      if (request.getAuthorId() != null) {
    //         author = entityManager.getReference(User.class, request.getAuthorId());
    //      }
    //      article.setAuthor(author);

    LocalDateTime date = request.getDate();
    if (!Post.Status.DRAFT.equals(article.getStatus())) {
        if (date == null) {
            date = now;
        } else if (date.isAfter(now)) {
            article.setStatus(Post.Status.SCHEDULED);
        } else {
            article.setStatus(Post.Status.PUBLISHED);
        }
    }
    article.setDate(date);
    article.setLanguage(request.getLanguage());

    article.getCategories().clear();
    for (long categoryId : request.getCategoryIds()) {
        article.getCategories().add(entityManager.getReference(Category.class, categoryId));
    }

    article.getTags().clear();
    Set<String> tagNames = StringUtils.commaDelimitedListToSet(request.getTags());
    if (!CollectionUtils.isEmpty(tagNames)) {
        for (String tagName : tagNames) {
            Tag tag = tagRepository.findOneForUpdateByNameAndLanguage(tagName, request.getLanguage());
            if (tag == null) {
                tag = new Tag();
                tag.setName(tagName);
                tag.setLanguage(request.getLanguage());
                article.setCreatedAt(now);
                article.setCreatedBy(authorizedUser.toString());
                article.setUpdatedAt(now);
                article.setUpdatedBy(authorizedUser.toString());
                tag = tagRepository.saveAndFlush(tag);
            }
            article.getTags().add(tag);
        }
    }

    article.getRelatedPosts().clear();
    Set<Post> relatedPosts = new HashSet<>();
    for (long relatedId : request.getRelatedPostIds()) {
        relatedPosts.add(entityManager.getReference(Post.class, relatedId));
    }
    article.setRelatedToPosts(relatedPosts);

    Seo seo = new Seo();
    seo.setTitle(request.getSeoTitle());
    seo.setDescription(request.getSeoDescription());
    seo.setKeywords(request.getSeoKeywords());
    article.setSeo(seo);

    List<Media> medias = new ArrayList<>();
    if (StringUtils.hasText(request.getBody())) {
        //         Blog blog = blogService.getBlogById(Blog.DEFAULT_ID);
        String mediaUrlPrefix = wallRideProperties.getMediaUrlPrefix();
        Pattern mediaUrlPattern = Pattern.compile(String.format("%s([0-9a-zA-Z\\-]+)", mediaUrlPrefix));
        Matcher mediaUrlMatcher = mediaUrlPattern.matcher(request.getBody());
        while (mediaUrlMatcher.find()) {
            Media media = mediaRepository.findOneById(mediaUrlMatcher.group(1));
            medias.add(media);
        }
    }
    article.setMedias(medias);

    article.setUpdatedAt(now);
    article.setUpdatedBy(authorizedUser.toString());

    Map<CustomField, CustomFieldValue> valueMap = new LinkedHashMap<>();
    for (CustomFieldValue value : article.getCustomFieldValues()) {
        valueMap.put(value.getCustomField(), value);
    }

    article.getCustomFieldValues().clear();
    if (!CollectionUtils.isEmpty(request.getCustomFieldValues())) {
        for (CustomFieldValueEditForm valueForm : request.getCustomFieldValues()) {
            CustomField customField = entityManager.getReference(CustomField.class,
                    valueForm.getCustomFieldId());
            CustomFieldValue value = valueMap.get(customField);
            if (value == null) {
                value = new CustomFieldValue();
            }
            value.setCustomField(customField);
            value.setPost(article);
            if (valueForm.getFieldType().equals(CustomField.FieldType.CHECKBOX)) {
                if (!ArrayUtils.isEmpty(valueForm.getTextValues())) {
                    value.setTextValue(String.join(",", valueForm.getTextValues()));
                } else {
                    value.setTextValue(null);
                }
            } else {
                value.setTextValue(valueForm.getTextValue());
            }
            value.setStringValue(valueForm.getStringValue());
            value.setNumberValue(valueForm.getNumberValue());
            value.setDateValue(valueForm.getDateValue());
            value.setDatetimeValue(valueForm.getDatetimeValue());
            if (!value.isEmpty()) {
                article.getCustomFieldValues().add(value);
            }
        }
    }

    return articleRepository.save(article);
}

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

@CacheEvict(value = WallRideCacheConfiguration.PAGE_CACHE, allEntries = true)
public Page savePage(PageUpdateRequest request, AuthorizedUser authorizedUser) {
    postRepository.lock(request.getId());
    Page page = pageRepository.findOneByIdAndLanguage(request.getId(), request.getLanguage());
    LocalDateTime now = LocalDateTime.now();

    String code = request.getCode();
    if (code == null) {
        try {/*from  ww  w. j  a  v a2  s.  c o  m*/
            code = new CodeFormatter().parse(request.getTitle(), LocaleContextHolder.getLocale());
        } catch (ParseException e) {
            throw new ServiceException(e);
        }
    }
    if (!StringUtils.hasText(code)) {
        if (!page.getStatus().equals(Post.Status.DRAFT)) {
            throw new EmptyCodeException();
        }
    }
    if (!page.getStatus().equals(Post.Status.DRAFT)) {
        Post duplicate = postRepository.findOneByCodeAndLanguage(code, request.getLanguage());
        if (duplicate != null && !duplicate.equals(page)) {
            throw new DuplicateCodeException(code);
        }
    }

    if (!page.getStatus().equals(Post.Status.DRAFT)) {
        page.setCode(code);
        page.setDraftedCode(null);
    } else {
        page.setCode(null);
        page.setDraftedCode(code);
    }

    Page parent = (request.getParentId() != null)
            ? entityManager.getReference(Page.class, request.getParentId())
            : null;
    if (!(page.getParent() == null && parent == null)
            && !ObjectUtils.nullSafeEquals(page.getParent(), parent)) {
        pageRepository.shiftLftRgt(page.getLft(), page.getRgt());
        pageRepository.shiftRgt(page.getRgt());
        pageRepository.shiftLft(page.getRgt());

        int rgt = 0;
        if (parent == null) {
            rgt = pageRepository.findMaxRgt();
            rgt++;
        } else {
            rgt = parent.getRgt();
            pageRepository.unshiftRgt(rgt);
            pageRepository.unshiftLft(rgt);
        }
        page.setLft(rgt);
        page.setRgt(rgt + 1);
    }

    page.setParent(parent);

    Media cover = null;
    if (request.getCoverId() != null) {
        cover = entityManager.getReference(Media.class, request.getCoverId());
    }
    page.setCover(cover);
    page.setTitle(request.getTitle());
    page.setBody(request.getBody());

    //      User author = null;
    //      if (request.getAuthorId() != null) {
    //         author = entityManager.getReference(User.class, request.getAuthorId());
    //      }
    //      page.setAuthor(author);

    LocalDateTime date = request.getDate();
    if (Post.Status.PUBLISHED.equals(page.getStatus())) {
        if (date == null) {
            date = now.truncatedTo(ChronoUnit.HOURS);
        } else if (date.isAfter(now)) {
            page.setStatus(Post.Status.SCHEDULED);
        }
    }
    page.setDate(date);
    page.setLanguage(request.getLanguage());

    page.getCategories().clear();
    SortedSet<Category> categories = new TreeSet<>();
    for (long categoryId : request.getCategoryIds()) {
        categories.add(entityManager.getReference(Category.class, categoryId));
    }
    page.setCategories(categories);

    page.getTags().clear();
    Set<String> tagNames = StringUtils.commaDelimitedListToSet(request.getTags());
    if (!CollectionUtils.isEmpty(tagNames)) {
        for (String tagName : tagNames) {
            Tag tag = tagRepository.findOneForUpdateByNameAndLanguage(tagName, request.getLanguage());
            if (tag == null) {
                tag = new Tag();
                tag.setName(tagName);
                tag.setLanguage(request.getLanguage());
                page.setCreatedAt(now);
                page.setCreatedBy(authorizedUser.toString());
                page.setUpdatedAt(now);
                page.setUpdatedBy(authorizedUser.toString());
                tag = tagRepository.saveAndFlush(tag);
            }
            page.getTags().add(tag);
        }
    }

    page.getRelatedPosts().clear();
    Set<Post> relatedPosts = new HashSet<>();
    for (long relatedId : request.getRelatedPostIds()) {
        relatedPosts.add(entityManager.getReference(Post.class, relatedId));
    }
    page.setRelatedToPosts(relatedPosts);

    Seo seo = new Seo();
    seo.setTitle(request.getSeoTitle());
    seo.setDescription(request.getSeoDescription());
    seo.setKeywords(request.getSeoKeywords());
    page.setSeo(seo);

    List<Media> medias = new ArrayList<>();
    if (StringUtils.hasText(request.getBody())) {
        //         Blog blog = blogService.getBlogById(Blog.DEFAULT_ID);
        String mediaUrlPrefix = wallRideProperties.getMediaUrlPrefix();
        Pattern mediaUrlPattern = Pattern.compile(String.format("%s([0-9a-zA-Z\\-]+)", mediaUrlPrefix));
        Matcher mediaUrlMatcher = mediaUrlPattern.matcher(request.getBody());
        while (mediaUrlMatcher.find()) {
            Media media = mediaRepository.findOneById(mediaUrlMatcher.group(1));
            medias.add(media);
        }
    }
    page.setMedias(medias);

    page.setUpdatedAt(now);
    page.setUpdatedBy(authorizedUser.toString());

    SortedSet<CustomFieldValue> fieldValues = new TreeSet<>();
    Map<CustomField, CustomFieldValue> valueMap = new LinkedHashMap<>();
    for (CustomFieldValue value : page.getCustomFieldValues()) {
        valueMap.put(value.getCustomField(), value);
    }

    page.getCustomFieldValues().clear();
    if (!CollectionUtils.isEmpty(request.getCustomFieldValues())) {
        for (CustomFieldValueEditForm valueForm : request.getCustomFieldValues()) {
            CustomField customField = entityManager.getReference(CustomField.class,
                    valueForm.getCustomFieldId());
            CustomFieldValue value = valueMap.get(customField);
            if (value == null) {
                value = new CustomFieldValue();
            }
            value.setCustomField(customField);
            value.setPost(page);
            if (valueForm.getFieldType().equals(CustomField.FieldType.CHECKBOX)) {
                if (!ArrayUtils.isEmpty(valueForm.getTextValues())) {
                    value.setTextValue(String.join(",", valueForm.getTextValues()));
                } else {
                    value.setTextValue(null);
                }
            } else {
                value.setTextValue(valueForm.getTextValue());
            }
            value.setStringValue(valueForm.getStringValue());
            value.setNumberValue(valueForm.getNumberValue());
            value.setDateValue(valueForm.getDateValue());
            value.setDatetimeValue(valueForm.getDatetimeValue());
            if (!value.isEmpty()) {
                fieldValues.add(value);
            }
        }
    }
    page.setCustomFieldValues(fieldValues);

    return pageRepository.save(page);
}