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:cz.muni.fi.editor.database.test.NotificationDAOTest.java

@Test
public void markLarge() {
    List<Notification> list = IntStream.rangeClosed(1, 101).mapToObj(i -> {
        Notification n = new Notification();
        n.setMessage("test");
        n.setNotificationDate(LocalDateTime.now());
        n.setNotified(userDAO.getById(1L));

        notificationDAO.create(n);//from www.  j ava2s  . com
        return n;
    }).collect(Collectors.toList());

    notificationDAO.markSeen(list);

}

From source file:fi.todoordelay.gui.GuiMainFrame.java

/**
 * This method is called from within the constructor to initialize the form.
 * WARNING: Do NOT modify this code. The content of this method is always
 * regenerated by the Form Editor./*from   w  w  w.j  a  v  a 2 s.  co m*/
 */
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {

    menuBar = new javax.swing.JMenuBar();
    projectMenu = new javax.swing.JMenu();
    addprojectMenuItem = new javax.swing.JMenuItem();
    saveMenuItem = new javax.swing.JMenuItem();
    saveAsMenuItem = new javax.swing.JMenuItem();
    exitMenuItem = new javax.swing.JMenuItem();
    taskMenu = new javax.swing.JMenu();
    addtaskMenuItem = new javax.swing.JMenuItem();
    copyMenuItem = new javax.swing.JMenuItem();
    pasteMenuItem = new javax.swing.JMenuItem();
    deleteMenuItem = new javax.swing.JMenuItem();
    ownlistMenu = new javax.swing.JMenu();
    addownlistMenuItem = new javax.swing.JMenuItem();
    aboutMenuItem = new javax.swing.JMenuItem();

    projectListModel = new javax.swing.DefaultListModel();
    projectsList = new javax.swing.JList(projectListModel);
    projectsPane = new javax.swing.JScrollPane(projectsList);

    taskListModel = new javax.swing.DefaultListModel();
    tasksList = new javax.swing.JList(taskListModel);
    tasksPane = new javax.swing.JScrollPane(tasksList);

    informationTextArea = new javax.swing.JTextArea();
    informationPane = new javax.swing.JScrollPane(informationTextArea);

    addItemDialog = new javax.swing.JOptionPane();
    editItemDialog = new javax.swing.JOptionPane();

    mainLogic = new fi.todoordelay.logic.LogicMain();

    projectsListMouseListener = new MouseListener() {
        public void mouseClicked(MouseEvent evt) {
            int index = projectsList.locationToIndex(evt.getPoint());
            selectedProject = index;
            selectionGroup = 0;

            if (evt.getButton() == 3) {
                int d = editItemDialog.showConfirmDialog(null,
                        "ARE YOU SURE YOU WANT TO DELETE CHOSEN PROJECT?", "Delete project dialog",
                        editItemDialog.YES_NO_OPTION, editItemDialog.WARNING_MESSAGE);
                if (d == 0) {
                    mainLogic.removeProject(mainLogic.getProjects().get(selectedProject));
                }
                selectedProject = -1;
                updateProjectListModel();
            }

            if (evt.getClickCount() == 2 && selectedProject > -1) {
                List pl = mainLogic.getProjects();
                Project p = (Project) pl.get(index);

                editItemDialog.setWantsInput(true);
                String name = editItemDialog.showInputDialog(null, "New project name (required):",
                        "Edit project dialog", editItemDialog.INFORMATION_MESSAGE);
                String description = editItemDialog.showInputDialog(null, "New project description:",
                        "Edit project dialog", editItemDialog.INFORMATION_MESSAGE);
                String dueString = editItemDialog.showInputDialog(null, "New due date in x day(s):",
                        "Edit project dialog", editItemDialog.INFORMATION_MESSAGE);

                try {
                    if (name.equals("")) {
                        JOptionPane.showMessageDialog(editItemDialog,
                                "Project name cannot be empty (exiting without changes)");
                    } else if (Long.parseLong(dueString) < 0) {
                        JOptionPane.showMessageDialog(editItemDialog, "Due date must be zero or higher");
                    } else {
                        p.setName(name);
                        p.setDescription(description);
                        p.setDuedate(LocalDateTime.now().plusDays(Long.parseLong(dueString)));
                    }
                } catch (Exception e) {
                    JOptionPane.showMessageDialog(editItemDialog, "Due date must be valid number");
                }

            }

            updateProjectListModel();
            mouseClickedOnProjectActionPerformed(evt);

        }

        public void mouseEntered(MouseEvent evt) {
        }

        public void mouseExited(MouseEvent evt) {
        }

        public void mouseReleased(MouseEvent evt) {
        }

        public void mousePressed(MouseEvent evt) {
        }

    };
    projectsList.addMouseListener(projectsListMouseListener);

    tasksListMouseListener = new MouseListener() {
        public void mouseClicked(MouseEvent evt) {
            int index = tasksList.locationToIndex(evt.getPoint());
            selectedTask = index;
            selectionGroup = 1;

            if (evt.getButton() == 3) {
                int d = editItemDialog.showConfirmDialog(null, "ARE YOU SURE YOU WANT TO DELETE CHOSEN TASK?",
                        "Delete task dialog", editItemDialog.YES_NO_OPTION, editItemDialog.WARNING_MESSAGE);
                if (d == 0) {
                    mainLogic.getProjects().get(selectedProject).removeTask(
                            mainLogic.getProjects().get(selectedProject).getTasks().get(selectedTask));
                }
                updateProjectListModel();
            }

            if (evt.getClickCount() == 2 && selectedTask > -1) {
                List tl = mainLogic.getProjects().get(selectedProject).getTasks();
                Task t = (Task) tl.get(index);

                editItemDialog.setWantsInput(true);
                String name = editItemDialog.showInputDialog(null, "New task name (required):",
                        "Edit task dialog", editItemDialog.INFORMATION_MESSAGE);
                String description = editItemDialog.showInputDialog(null, "New task description:",
                        "Edit task dialog", editItemDialog.INFORMATION_MESSAGE);
                String dueString = editItemDialog.showInputDialog(null, "New due date in x day(s):",
                        "Edit task dialog", editItemDialog.INFORMATION_MESSAGE);

                try {
                    if (name.equals("")) {
                        JOptionPane.showMessageDialog(editItemDialog,
                                "Task name cannot be empty (exiting without changes)");
                    } else if (Long.parseLong(dueString) < 0) {
                        JOptionPane.showMessageDialog(editItemDialog, "Due date must be zero or higher");
                    } else {
                        t.setName(name);
                        t.setDescription(description);
                        t.setDuedate(LocalDateTime.now().plusDays(Long.parseLong(dueString)));
                    }
                } catch (Exception e) {
                    JOptionPane.showMessageDialog(editItemDialog, "Due date must be valid number");
                }

            }

            updateProjectListModel();
            mouseClickedOnProjectActionPerformed(evt);

        }

        public void mouseEntered(MouseEvent evt) {
        }

        public void mouseExited(MouseEvent evt) {
        }

        public void mouseReleased(MouseEvent evt) {
        }

        public void mousePressed(MouseEvent evt) {
        }

    };
    tasksList.addMouseListener(tasksListMouseListener);

    setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

    projectsPane.setBorder(javax.swing.BorderFactory.createTitledBorder("Projects"));
    projectsPane.setViewportBorder(null);

    tasksPane.setBorder(javax.swing.BorderFactory.createTitledBorder("Tasks"));
    tasksPane.setViewportBorder(null);

    informationPane.setBorder(javax.swing.BorderFactory.createTitledBorder("Description"));
    projectsPane.setViewportBorder(null);

    projectMenu.setText("Project");
    addprojectMenuItem.setMnemonic('p');
    addprojectMenuItem.setText("Add Project");
    projectMenu.add(addprojectMenuItem);
    addprojectMenuItem.addActionListener(new java.awt.event.ActionListener() {
        public void actionPerformed(java.awt.event.ActionEvent evt) {
            addItemDialog.setWantsInput(true);
            String name = addItemDialog.showInputDialog(null, "Project name (required):", "Add project dialog",
                    addItemDialog.INFORMATION_MESSAGE);
            String description = addItemDialog.showInputDialog(null, "Project description:",
                    "Add project dialog", addItemDialog.INFORMATION_MESSAGE);
            String due_at = addItemDialog.showInputDialog(null, "Due in x day(s):", "Add project dialog",
                    addItemDialog.INFORMATION_MESSAGE);
            Project newProject = new Project(name, description, Long.parseLong(due_at));
            mainLogic.addProject(newProject);
            projectListModel.addElement(name);

            updateProjectListModel();
            addprojectMenuItemActionPerformed(evt);
        }
    });
    menuBar.add(projectMenu);

    taskMenu.setText("Task");
    addtaskMenuItem.setMnemonic('t');
    addtaskMenuItem.setText("Add Task");
    taskMenu.add(addtaskMenuItem);
    addtaskMenuItem.addActionListener(new java.awt.event.ActionListener() {
        public void actionPerformed(java.awt.event.ActionEvent evt) {
            addItemDialog.setWantsInput(true);
            String name = addItemDialog.showInputDialog(null, "Task name (required):", "Add task dialog",
                    addItemDialog.INFORMATION_MESSAGE);
            String description = addItemDialog.showInputDialog(null, "Task description:", "Add task dialog",
                    addItemDialog.INFORMATION_MESSAGE);
            String due_at = addItemDialog.showInputDialog(null, "Due in x day(s):", "Add task dialog",
                    addItemDialog.INFORMATION_MESSAGE);
            Task newTask = new Task(name, description, Long.parseLong(due_at));

            Project s = mainLogic.getProjects().get(selectedProject);

            s.addTask(newTask);
            taskListModel.addElement(name);

            updateProjectListModel();
            addprojectMenuItemActionPerformed(evt);
        }
    });
    menuBar.add(taskMenu);

    setJMenuBar(menuBar);

    javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
    getContentPane().setLayout(layout);
    layout.setHorizontalGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(layout.createSequentialGroup().addContainerGap().addComponent(
                                    projectsPane, javax.swing.GroupLayout.PREFERRED_SIZE, 300,
                                    javax.swing.GroupLayout.PREFERRED_SIZE))
                            .addGroup(
                                    layout.createSequentialGroup().addGap(312, 312, 312).addComponent(tasksPane,
                                            javax.swing.GroupLayout.PREFERRED_SIZE, 300,
                                            javax.swing.GroupLayout.PREFERRED_SIZE))
                            .addGroup(layout.createSequentialGroup().addGap(624, 624, 624).addComponent(
                                    informationPane, javax.swing.GroupLayout.PREFERRED_SIZE, 300,
                                    Short.MAX_VALUE)))

                    .addContainerGap()));
    layout.setVerticalGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING).addGroup(
            javax.swing.GroupLayout.Alignment.TRAILING,
            layout.createSequentialGroup().addContainerGap()
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                            .addComponent(informationPane, javax.swing.GroupLayout.DEFAULT_SIZE, 860,
                                    Short.MAX_VALUE)
                            .addComponent(tasksPane, javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(projectsPane, javax.swing.GroupLayout.Alignment.LEADING))

                    .addContainerGap()));

    pack();
}

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

@Override
public void receptionneCommandeService(CommandeService commandeService)
        throws UnsupportedEncodingException, MessagingException {
    AppUser currentUser = authHelper.getCurrentUser();
    commandeService = commandeServiceRepository.findOne(commandeService.getId());
    commandeService.setEtatCommandeService(EtatCommandeService.RECEPTIONNE);
    commandeService.setDatePassageReception(LocalDateTime.now());
    commandeService.setReceptionUser(currentUser.getNomComplet());
    commandeService.setReceptionLogin(currentUser.getLogin());
    commandeService = commandeServiceRepository.save(commandeService);

    for (Demande demande : commandeService.getCommande().getListeDemande()) {
        demande.setEtatDemande(EtatDemande.TERMINE);
        demandeRepository.save(demande);
    }//from   w w w .jav  a 2  s .  co  m

    mailService.sendMailSuiteReceptionCommandeService(commandeService);
}

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

public List<Comment> bulkUnapproveComment(CommentBulkUnapproveRequest request, AuthorizedUser authorizedUser) {
    if (!authorizedUser.getRoles().contains(User.Role.ADMIN)) {
        throw new ServiceException();
    }/*  ww  w . j av  a  2s.  c  o  m*/

    List<Comment> comments = new ArrayList<>();
    for (long id : request.getIds()) {
        Comment comment = commentRepository.findOneForUpdateById(id);
        if (!comment.isApproved()) {
            continue;
        }

        LocalDateTime now = LocalDateTime.now();
        comment.setApproved(false);
        comment.setUpdatedAt(now);
        comment.setUpdatedBy(authorizedUser.toString());
        comment = commentRepository.saveAndFlush(comment);

        comments.add(comment);
    }
    return comments;
}

From source file:ch.wisv.areafiftylan.integration.TicketRestIntegrationTest.java

@Test
public void testAddTicketType() {
    User admin = createAdmin();//from w  w w  . jav a2  s.c o  m
    TicketType type = new TicketType("testAddType", "Type for adding test", 10, 0,
            LocalDateTime.now().plusDays(1), false);

    //@formatter:off
    given().header(getXAuthTokenHeaderForUser(admin)).when().contentType(ContentType.JSON).body(type)
            .post(TICKETS_ENDPOINT + "/types").then().statusCode(HttpStatus.SC_CREATED);
    //@formatter:on
}

From source file:net.jmhertlein.mcanalytics.api.auth.SSLUtil.java

/**
 * Given a certificate signing request, produce a signed certificate.
 *
 * @param caKey/*from   w  w w .  j  a va 2s.  co  m*/
 * @param caCert
 * @param r
 * @param makeAuthority
 * @return
 */
public static X509Certificate fulfillCertRequest(PrivateKey caKey, X509Certificate caCert,
        PKCS10CertificationRequest r, boolean makeAuthority) {
    X509v3CertificateBuilder b = new JcaX509v3CertificateBuilder(new X500Name(caCert.getSubjectDN().getName()), // the order of O,OU,CN returned is very important
            BigInteger.probablePrime(128, new SecureRandom()), Date.from(Instant.now().minusSeconds(1)),
            Date.from(LocalDateTime.now().plusYears(3).toInstant(ZoneOffset.UTC)), r.getSubject(),
            getPublicKeyFromInfo(r.getSubjectPublicKeyInfo()));

    try {
        b.addExtension(Extension.basicConstraints, true, new BasicConstraints(makeAuthority));
    } catch (CertIOException ex) {
        Logger.getLogger(SSLUtil.class.getName()).log(Level.SEVERE, null, ex);
    }

    try {
        ContentSigner signer = new JcaContentSignerBuilder(SIGNING_ALGORITHM).setProvider("BC").build(caKey);
        X509CertificateHolder build = b.build(signer);
        return new JcaX509CertificateConverter().setProvider("BC").getCertificate(build);
    } catch (OperatorCreationException | CertificateException ex) {
        Logger.getLogger(SSLUtil.class.getName()).log(Level.SEVERE, null, ex);
        return null;
    }
}

From source file:com.ccserver.digital.service.CreditCardApplicationExtractionServiceTest.java

@Test
public void extractByteArrayExcelTest() throws IOException {
    List<CreditCardApplication> applicationList = new ArrayList<>();
    CreditCardApplication creditCardApplication = new CreditCardApplication();
    creditCardApplication.setFirstName("First Name");
    creditCardApplication.setLastName("Last Name");
    creditCardApplication.setPassportNumber("121213");
    creditCardApplication.setEmail("Email");
    creditCardApplication.setCurrentIsPermanent(true);
    creditCardApplication.setHaveGreenCard(false);
    creditCardApplication.setBranchAddress(new Branch());
    creditCardApplication.setBusinessAddress(new Address());
    creditCardApplication.setCitizenship(new Country());
    creditCardApplication.setGender(Gender.Female);
    creditCardApplication.setEducation(new SelectionList());
    applicationList.add(creditCardApplication);
    creditCardApplication.setBusinessStartDate(LocalDateTime.now());
    creditCardApplication.setDateOfIssue(null);
    creditCardApplication.setTypeOfEmployement(TypeOfEmployment.Business);
    creditCardApplication.setBusinessPhone(new Phone());

    Mockito.when(repository.findAll()).thenReturn(applicationList);

    byte[] result = ccAppExtractionService.extractCreditCard(1);
    Assert.assertNotNull(result);//from   w w w.jav  a2  s . c o m

}

From source file:org.apache.geode.management.internal.cli.commands.ExportLogsDUnitTest.java

@Test
public void testExportWithStartAndEndDateTimeFiltering() throws Exception {
    ZonedDateTime cutoffTime = LocalDateTime.now().atZone(ZoneId.systemDefault());

    String messageAfterCutoffTime = "[this message should not show up since it is after cutoffTime]";
    LogLine logLineAfterCutoffTime = new LogLine(messageAfterCutoffTime, "info", true);
    server1.invoke(() -> {/*from  w  ww. java  2  s  .c  o  m*/
        Logger logger = LogService.getLogger();
        logLineAfterCutoffTime.writeLog(logger);
    });

    DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern(FORMAT);
    String cutoffTimeString = dateTimeFormatter.format(cutoffTime);

    CommandStringBuilder commandStringBuilder = new CommandStringBuilder("export logs");
    commandStringBuilder.addOption("start-time", dateTimeFormatter.format(cutoffTime.minusDays(1)));
    commandStringBuilder.addOption("end-time", cutoffTimeString);
    commandStringBuilder.addOption("log-level", "debug");

    gfshConnector.executeAndVerifyCommand(commandStringBuilder.toString());

    expectedMessages.get(server1).add(logLineAfterCutoffTime);
    Set<String> acceptedLogLevels = Stream.of("info", "error", "debug").collect(toSet());
    verifyZipFileContents(acceptedLogLevels);
}

From source file:com.seleniumtests.driver.screenshots.ScreenshotUtil.java

/**
 * Capture a picture//from  ww w .j a  v a  2 s . c om
 * @param target      which picture to take, screen or page.
 * @param exportClass   The type of export to perform (File, ScreenShot, String, BufferedImage)
 * @param allWindows   if true, will take a screenshot for all windows (only available for browser capture)
 * @param force         force capture even if set to false in SeleniumTestContext. This allows PictureElement and ScreenZone to work
 * @return
 */
public <T extends Object> List<T> capture(Target target, Class<T> exportClass, boolean allWindows,
        boolean force) {

    if (!force && (SeleniumTestsContextManager.getThreadContext() == null || getOutputDirectory() == null
            || !SeleniumTestsContextManager.getThreadContext().getCaptureSnapshot())) {
        return new ArrayList<>();
    }

    List<NamedBufferedImage> capturedImages = new ArrayList<>();
    LocalDateTime start = LocalDateTime.now();

    if (target == Target.SCREEN && SeleniumTestsContextManager.isDesktopWebTest()) {
        // capture desktop
        capturedImages.add(new NamedBufferedImage(captureDesktop(), ""));
    } else if (target == Target.PAGE && SeleniumTestsContextManager.isWebTest()) {
        // capture web with scrolling
        removeAlert();
        capturedImages.addAll(captureWebPages(allWindows));
    } else if (target == Target.PAGE && SeleniumTestsContextManager.isAppTest()) {
        capturedImages.add(new NamedBufferedImage(capturePage(-1, -1), ""));
    } else {
        throw new ScenarioException(
                "Capturing page is only possible for web and application tests. Capturing desktop possible for desktop web tests only");
    }

    // back to page top
    try {
        if (target == Target.PAGE) {
            ((CustomEventFiringWebDriver) driver).scrollTop();
        }
    } catch (WebDriverException e) {
        // ignore errors here.
        // com.seleniumtests.it.reporter.TestTestLogging.testManualSteps() with HTMLUnit driver
        // org.openqa.selenium.WebDriverException: Can't execute JavaScript before a page has been loaded!
    }

    List<T> out = new ArrayList<>();
    for (NamedBufferedImage capturedImage : capturedImages) {
        if (capturedImage != null) {
            if (exportClass.equals(File.class)) {
                out.add((T) exportToFile(capturedImage.image));
            } else if (exportClass.equals(ScreenShot.class)) {
                out.add((T) exportToScreenshot(capturedImage.image, capturedImage.prefix,
                        Duration.between(start, LocalDateTime.now()).toMillis()));
            } else if (exportClass.equals(String.class)) {
                try {
                    out.add((T) ImageProcessor.toBase64(capturedImage.image));
                } catch (IOException e) {
                    logger.error("ScreenshotUtil: cannot write image");
                }
            } else if (exportClass.equals(BufferedImage.class)) {
                out.add((T) capturedImage.image);
            }
        }
    }

    return out;
}

From source file:io.stallion.dataAccess.file.TextFilePersister.java

public T fromString(String fileContent, Path fullPath) {
    if (fullPath.toString().endsWith(".html") || fullPath.toString().endsWith(".htm")) {
        return fromHtml(fileContent, fullPath);
    }//from ww  w . j av a  2s. c o  m
    String relativePath = fullPath.toString().replace(getBucketFolderPath(), "");
    Path path = fullPath;

    T item = null;
    try {
        item = getModelClass().newInstance();
    } catch (InstantiationException e) {
        throw new RuntimeException(e);
    } catch (IllegalAccessException e) {
        throw new RuntimeException(e);
    }
    item.setTags(new ArrayList<String>()).setElementById(new HashMap<>()).setElements(new ArrayList<>())
            .setPublishDate(ZonedDateTime.of(LocalDateTime.now(), ZoneId.of("UTC"))).setTitle("")
            .setDraft(false).setTemplate("").setContent("").setSlug("");

    /* Get the id and slug */

    item.setSlug(FilenameUtils.removeExtension(relativePath));
    if (!item.getSlug().startsWith("/")) {
        item.setSlug("/" + item.getSlug());
    }
    if (item.getSlug().endsWith("/index")) {
        item.setSlug(item.getSlug().substring(item.getSlug().length() - 6));
    }

    if (empty(fileContent.trim())) {
        return item;
    }

    /* Parse out toml properties, if found */
    String tomlContent;
    Matcher tomlMatcher = tomlPattern.matcher(fileContent);
    if (tomlMatcher.find()) {
        tomlContent = tomlMatcher.group(1).trim();
        fileContent = tomlMatcher.replaceAll("\n");
        Map tomlMap = new Toml().read(tomlContent).to(HashMap.class);
        for (Object key : tomlMap.keySet()) {
            Object value = tomlMap.get(key);
            setProperty(item, key.toString(), value);
        }
    }

    List<String> allLines = Arrays.asList(fileContent.split("\n"));

    if (allLines.size() == 0) {
        return item;
    }

    if (empty(item.getTitle())) {
        item.setTitle(allLines.get(0));
    }

    String titleLine = "";
    List<String> propertiesSection = list();
    String rawContent = "";
    int propertiesStartAt = 0;
    if (allLines.size() > 1) {
        if (allLines.get(1).startsWith("----") || allLines.get(1).startsWith("====")) {
            titleLine = allLines.get(0);
            propertiesStartAt = 2;
            item.setTitle(titleLine);
        }
    }

    int propertiesEndAt = propertiesStartAt;
    for (; propertiesEndAt < allLines.size(); propertiesEndAt++) {
        String line = allLines.get(propertiesEndAt);
        if (line.trim().equals("---")) {
            continue;
        }
        int colon = line.indexOf(':');
        if (colon == -1) {
            break;
        }
        String key = line.substring(0, colon).trim();
        String value = line.substring(colon + 1, line.length()).trim();
        if ("oldUrls".equals(key)) {
            setProperty(item, key, apply(list(StringUtils.split(value, ";")), (aUrl) -> aUrl.trim()));
        } else {
            setProperty(item, key, value);
        }
    }
    if (propertiesEndAt < allLines.size()) {
        rawContent = StringUtils.join(allLines.subList(propertiesEndAt, allLines.size()), "\n").trim();
    }

    Boolean isMarkdown = false;
    if (path.toString().toLowerCase().endsWith(".txt") || path.toString().toLowerCase().endsWith(".md")) {
        isMarkdown = true;
    }
    item.setElements(StElementParser.parseElements(rawContent, isMarkdown));
    List<StElement> items = item.getElements();
    for (StElement ele : items) {
        item.getElementById().put(ele.getId(), ele);
    }

    String itemContent = StElementParser.removeTags(rawContent).trim();
    item.setOriginalContent(itemContent);

    if (isMarkdown) {
        Log.fine("Parse for page {0} {1} {2}", item.getId(), item.getSlug(), item.getTitle());
        String cacheKey = DigestUtils.md5Hex("markdown-to-html" + Literals.GSEP + itemContent);
        String cached = null;
        if (!"test".equals(Settings.instance().getEnv())) {
            cached = PermaCache.get(cacheKey);
        }
        if (cached == null) {
            itemContent = Markdown.instance().process(itemContent);
            PermaCache.set(cacheKey, itemContent);
        } else {
            itemContent = cached;
        }

        item.setContent(itemContent);
    }

    if (empty(item.getId())) {
        item.setId(makeIdFromFilePath(relativePath));
    }

    Log.fine("Loaded text item: id:{0} slug:{1} title:{2} draft:{3}", item.getId(), item.getSlug(),
            item.getTitle(), item.getDraft());
    return item;
}