Example usage for java.time LocalDateTime atZone

List of usage examples for java.time LocalDateTime atZone

Introduction

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

Prototype

@Override
public ZonedDateTime atZone(ZoneId zone) 

Source Link

Document

Combines this date-time with a time-zone to create a ZonedDateTime .

Usage

From source file:com.cohesionforce.dis.ConvertCSV.java

public void run() {

    int count = 0;

    System.out.println("Opening file to convert: " + inputFile);
    BufferedReader br;//from w  w  w  .  j a v a  2 s  .co  m
    try {
        br = new BufferedReader(new FileReader(inputFile));
    } catch (FileNotFoundException e1) {
        e1.printStackTrace();
        return;
    }

    startWriters();
    marking.setCharacterSet(0);

    dr.setDeadReckoningAlgorithm(2);
    dr.setEntityLinearAcceleration(zeroVector);
    dr.setEntityAngularVelocity(zeroVector);

    System.out.println("Starting to convert PDUs");

    while (done == false) {
        String line = null;
        try {
            line = br.readLine(); // throw away header

            // medallion, hack_license, vendor_id, rate_code,
            // store_and_fwd_flag,pickup_datetime,dropoff_datetime,passenger_count,
            // trip_time_in_secs,trip_distance,pickup_longitude,pickup_latitude,
            // dropoff_longitude,dropoff_latitude
            while ((line = br.readLine()) != null) {
                String[] pieces = line.split(cvsSplitBy);

                String medallion = pieces[0];

                LocalDateTime localTime = LocalDateTime.from(formatter.parse(pieces[5]));
                ZonedDateTime zoneTime = localTime.atZone(ZoneId.of("America/New_York"));
                long ts = zoneTime.toInstant().toEpochMilli();

                EntityStatePdu output = getNewEntityState(medallion);
                output.setTimestamp(ts);

                // Create EntityLocation from string
                double plon = Double.parseDouble(pieces[10]);
                double plat = Double.parseDouble(pieces[11]);
                Vector3Double loc = getLocation(plon, plat);
                output.setEntityLocation(loc);

                logPdu(output, 1);

                if (++count % 100000 == 0) {
                    System.out.println("Converted " + count + " PDUs");
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        done = true;
    } // end
    try {
        br.close();
    } catch (IOException e1) {
        e1.printStackTrace();
    }
    System.out.print("Waiting on writers to clear their queues");

    boolean emptyQueue = false;
    while (!emptyQueue)

    {
        emptyQueue = true;
        for (LogWriter<?> writer : writers) {
            // If any queue is not empty, sleep and check again
            if (!writer.getQueue().isEmpty()) {
                try {
                    emptyQueue = false;
                    System.out.print(".");
                    Thread.sleep(1000);
                    break;
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    System.out.println("");
    System.out.println("PDUs converted: " + count);
    System.out.println("Shutting down logging threads");
    threadGroup.interrupt();

    int tries = 0;
    while (threadGroup.activeCount() > 0 && tries < 10)

    {
        try {
            Thread.sleep(2000);
        } catch (InterruptedException e) {
        }
        ++tries;
    }
    System.out.println("Completed logging threads shutdown");

}

From source file:org.helioviewer.jhv.plugins.hekplugin.HEKPlugin.java

public void dateTimesChanged(int framecount) {
    LocalDateTime startDateTime;
    startDateTime = Plugins.getStartDateTime();
    LocalDateTime endDateTime = Plugins.getEndDateTime();
    if (startDateTime != null && endDateTime != null) {
        Date start = Date.from(startDateTime.atZone(ZoneId.systemDefault()).toInstant());
        Date end = Date.from(endDateTime.atZone(ZoneId.systemDefault()).toInstant());

        Interval<Date> newInterval = new Interval<>(start, end);
        hekPluginPanel.setCurInterval(newInterval);
    }/*from   ww w.  j  av a 2s  .  com*/
}

From source file:co.com.soinsoftware.hotelero.view.JFRoomPayment.java

private Date getFinalDate(final Date initialDate, final int hour) {
    final LocalDate today = LocalDate.now();
    LocalDateTime finalDateTime = null;
    if (DateUtils.isSameDay(initialDate, new Date())) {
        finalDateTime = today.plusDays(1).atTime(LocalTime.of(hour, 0));
    } else {//from w  w  w .j  a  va 2s. com
        finalDateTime = today.atTime(LocalTime.of(hour, 0));
    }
    final ZonedDateTime zdt = finalDateTime.atZone(ZoneId.systemDefault());
    return Date.from(zdt.toInstant());
}

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

@Transactional(propagation = Propagation.NOT_SUPPORTED)
public void updatePostViews() {
    LocalDateTime now = LocalDateTime.now();
    Set<JobExecution> jobExecutions = jobExplorer.findRunningJobExecutions("updatePostViewsJob");
    for (JobExecution jobExecution : jobExecutions) {
        LocalDateTime startTime = LocalDateTime.ofInstant(jobExecution.getStartTime().toInstant(),
                ZoneId.systemDefault());
        Duration d = Duration.between(now, startTime);
        if (Math.abs(d.toMinutes()) == 0) {
            logger.info("Skip processing because the job is running.");
            return;
        }/*  w  w w.  j  av  a 2 s.  c  om*/
    }

    JobParameters params = new JobParametersBuilder()
            .addDate("now", Date.from(now.atZone(ZoneId.systemDefault()).toInstant())).toJobParameters();
    try {
        jobLauncher.run(updatePostViewsJob, params);
    } catch (Exception e) {
        throw new ServiceException(e);
    }
}

From source file:com.seleniumtests.connectors.mails.ImapClient.java

/**
 * get list of all emails in folder// www .  j  ava  2  s . c  o m
 * 
 * @param folderName      folder to read
 * @param firstMessageTime   date from which we should get messages
 * @param firstMessageIndex index of the firste message to find
 * @throws MessagingException
 * @throws IOException
 */
@Override
public List<Email> getEmails(String folderName, int firstMessageIndex, LocalDateTime firstMessageTime)
        throws MessagingException, IOException {

    if (folderName == null) {
        throw new MessagingException("folder ne doit pas tre vide");
    }

    // Get folder
    Folder folder = store.getFolder(folderName);
    folder.open(Folder.READ_ONLY);

    // Get directory
    Message[] messages = folder.getMessages();

    List<Message> preFilteredMessages = new ArrayList<>();

    final LocalDateTime firstTime = firstMessageTime;

    // on filtre les message en fonction du mode de recherche
    if (searchMode == SearchMode.BY_INDEX || firstTime == null) {
        for (int i = firstMessageIndex, n = messages.length; i < n; i++) {
            preFilteredMessages.add(messages[i]);
        }
    } else {
        preFilteredMessages = Arrays.asList(folder.search(new SearchTerm() {
            private static final long serialVersionUID = 1L;

            @Override
            public boolean match(Message msg) {
                try {
                    return !msg.getReceivedDate()
                            .before(Date.from(firstTime.atZone(ZoneId.systemDefault()).toInstant()));
                } catch (MessagingException e) {
                    return false;
                }
            }
        }));

    }

    List<Email> filteredEmails = new ArrayList<>();
    lastMessageIndex = messages.length;

    for (Message message : preFilteredMessages) {

        String contentType = "";
        try {
            contentType = message.getContentType();
        } catch (MessagingException e) {
            MimeMessage msg = (MimeMessage) message;
            message = new MimeMessage(msg);
            contentType = message.getContentType();
        }

        // decode content
        String messageContent = "";
        List<String> attachments = new ArrayList<>();

        if (contentType.toLowerCase().contains("text/html")) {
            messageContent += StringEscapeUtils.unescapeHtml4(message.getContent().toString());
        } else if (contentType.toLowerCase().contains("multipart/")) {
            List<BodyPart> partList = getMessageParts((Multipart) message.getContent());

            // store content in list
            for (BodyPart part : partList) {

                String partContentType = part.getContentType().toLowerCase();
                if (partContentType.contains("text/html")) {
                    messageContent = messageContent
                            .concat(StringEscapeUtils.unescapeHtml4(part.getContent().toString()));

                } else if (partContentType.contains("text/") && !partContentType.contains("vcard")) {
                    messageContent = messageContent.concat((String) part.getContent().toString());

                } else if (partContentType.contains("image") || partContentType.contains("application/")
                        || partContentType.contains("text/x-vcard")) {
                    if (part.getFileName() != null) {
                        attachments.add(part.getFileName());
                    } else {
                        attachments.add(part.getDescription());
                    }
                } else {
                    logger.debug("type: " + part.getContentType());
                }
            }
        }

        // create a new email
        filteredEmails.add(new Email(message.getSubject(), messageContent, "",
                message.getReceivedDate().toInstant().atZone(ZoneId.systemDefault()).toLocalDateTime(),
                attachments));
    }

    folder.close(false);

    return filteredEmails;
}

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

private XMLGregorianCalendar dateToXMLGregorianCalendar(LocalDateTime localDateTime) {
    if (localDateTime == null) {
        return null;
    }//from  ww w .java  2  s . c om
    Date date = Date.from(localDateTime.atZone(ZoneId.systemDefault()).toInstant());
    return dateToXMLGregorianCalendar(date);
}

From source file:org.tightblog.service.WeblogEntryManager.java

/**
 * Find nearest published blog entry before or after a given target date.  Useful for date-based
 * pagination where it is desired to determine the next or previous time period that
 * contains a blog entry./*from   w w  w  .jav a 2s.c  o  m*/
 *
 * @param weblog weblog whose entries to search
 * @param categoryName Category name that entry must belong to or null if entry may belong to any category
 * @param targetDate Earliest (if succeeding = true) or latest (succeeding = false) publish time of blog entry
 * @param succeeding If true, find the first blog entry whose publish time comes after the targetDate, if false, the
 *                   entry closest to but before the targetDate.
 * @return WeblogEntry meeting the above criteria or null if no entry matches
 */
public WeblogEntry findNearestWeblogEntry(Weblog weblog, String categoryName, LocalDateTime targetDate,
        boolean succeeding) {
    WeblogEntry nearestEntry = null;

    WeblogEntrySearchCriteria wesc = new WeblogEntrySearchCriteria();
    wesc.setWeblog(weblog);
    wesc.setCategoryName(categoryName);
    wesc.setStatus(WeblogEntry.PubStatus.PUBLISHED);
    wesc.setMaxResults(1);
    if (succeeding) {
        wesc.setStartDate(targetDate.atZone(ZoneId.systemDefault()).toInstant());
        wesc.setSortOrder(WeblogEntrySearchCriteria.SortOrder.ASCENDING);
    } else {
        wesc.setEndDate(targetDate.atZone(ZoneId.systemDefault()).toInstant());
        wesc.setSortOrder(WeblogEntrySearchCriteria.SortOrder.DESCENDING);
    }
    List entries = getWeblogEntries(wesc);
    if (entries.size() > 0) {
        nearestEntry = (WeblogEntry) entries.get(0);
    }
    return nearestEntry;
}

From source file:edu.usu.sdl.openstorefront.service.UserServiceImpl.java

@Override
public void cleanupOldUserMessages() {
    int maxDays = Convert.toInteger(PropertiesManager.getValue(PropertiesManager.KEY_MESSAGE_KEEP_DAYS, "30"));

    LocalDateTime archiveTime = LocalDateTime.now();
    archiveTime = archiveTime.minusDays(maxDays);
    archiveTime = archiveTime.truncatedTo(ChronoUnit.DAYS);
    String deleteQuery = "updateDts < :maxUpdateDts AND activeStatus = :activeStatusParam";

    ZonedDateTime zdt = archiveTime.atZone(ZoneId.systemDefault());
    Date archiveDts = Date.from(zdt.toInstant());

    Map<String, Object> queryParams = new HashMap<>();
    queryParams.put("maxUpdateDts", archiveDts);
    queryParams.put("activeStatusParam", UserMessage.INACTIVE_STATUS);

    persistenceService.deleteByQuery(UserMessage.class, deleteQuery, queryParams);
}

From source file:com.streamsets.pipeline.stage.origin.jdbc.cdc.oracle.OracleCDCSource.java

private long localDateTimeToEpoch(LocalDateTime date) {
    return date.atZone(zoneId).toEpochSecond();
}

From source file:org.sleuthkit.autopsy.experimental.autoingest.FileExporterSettingsPanel.java

/**
 * Get the artifact condition from the user's input
 *
 * @return the ArtifactCondition, or null if there isn't one.
 *//*  www . j  a v  a  2 s. com*/
ArtifactCondition getArtifactConditionFromInput(Rule rule) throws IllegalArgumentException {
    ArtifactCondition artifactCondition = null;
    if (cbAttributeType.isSelected()) {
        String selectedAttribute = comboBoxAttributeName.getSelectedItem().toString();
        BlackboardAttribute.TSK_BLACKBOARD_ATTRIBUTE_VALUE_TYPE typeFromComboBox = BlackboardAttribute.TSK_BLACKBOARD_ATTRIBUTE_VALUE_TYPE
                .fromLabel(comboBoxValueType.getSelectedItem().toString());
        BlackboardAttribute.TSK_BLACKBOARD_ATTRIBUTE_VALUE_TYPE intrinsicType = attributeTypeMap
                .get(comboBoxAttributeName.getSelectedItem().toString());

        // if we don't have a type in the map, but they have set the combobox, put it in the map
        if (intrinsicType == null && typeFromComboBox != null) {
            intrinsicType = typeFromComboBox;
            attributeTypeMap.put(selectedAttribute, typeFromComboBox);
        }

        if (intrinsicType == BlackboardAttribute.TSK_BLACKBOARD_ATTRIBUTE_VALUE_TYPE.DATETIME) {
            LocalDateTime localDateTime = dateTimePicker.getDateTime();
            if (localDateTime == null) {
                throw new IllegalArgumentException("Bad date/time combination");
            }
            Instant instant = localDateTime.atZone(ZoneId.systemDefault()).toInstant();
            String stringValue = Long.toString(Date.from(instant).getTime());
            artifactCondition = new Rule.ArtifactCondition(comboBoxArtifactName.getSelectedItem().toString(),
                    comboBoxAttributeName.getSelectedItem().toString(), stringValue, intrinsicType,
                    RelationalOp.fromSymbol(comboBoxAttributeComparison.getSelectedItem().toString()));
        } else if (intrinsicType == BlackboardAttribute.TSK_BLACKBOARD_ATTRIBUTE_VALUE_TYPE.BYTE) {
            try {
                String stringValue = tbAttributeValue.getText();
                byte[] hexValue = Hex.decodeHex(stringValue.toCharArray());
                String finalValue = new String(Hex.encodeHex(hexValue));
                artifactCondition = new Rule.ArtifactCondition(
                        comboBoxArtifactName.getSelectedItem().toString(),
                        comboBoxAttributeName.getSelectedItem().toString(), finalValue, intrinsicType,
                        RelationalOp.fromSymbol(comboBoxAttributeComparison.getSelectedItem().toString()));
            } catch (DecoderException ex) {
                throw new IllegalArgumentException(ex);
            }
        } else if (intrinsicType != null) {
            artifactCondition = new Rule.ArtifactCondition(comboBoxArtifactName.getSelectedItem().toString(),
                    comboBoxAttributeName.getSelectedItem().toString(), tbAttributeValue.getText(),
                    intrinsicType,
                    RelationalOp.fromSymbol(comboBoxAttributeComparison.getSelectedItem().toString()));
        } else {
            throw new IllegalArgumentException();
        }
    }
    return artifactCondition;
}