Example usage for org.joda.time DateTime DateTime

List of usage examples for org.joda.time DateTime DateTime

Introduction

In this page you can find the example usage for org.joda.time DateTime DateTime.

Prototype

public DateTime() 

Source Link

Document

Constructs an instance set to the current system millisecond time using ISOChronology in the default time zone.

Usage

From source file:at.tfr.securefs.client.SecurefsFileServiceClient.java

License:Open Source License

public void run() {
    DateTime start = new DateTime();
    try {//from w  w w . j a  v  a2  s .  c om
        FileService svc = new FileService(new URL(fileServiceUrl));
        BindingProvider binding = (BindingProvider) svc.getFileServicePort();
        binding.getRequestContext().put(BindingProvider.USERNAME_PROPERTY, username);
        binding.getRequestContext().put(BindingProvider.PASSWORD_PROPERTY, password);

        for (Path path : files) {

            if (write) {
                if (!path.toFile().exists()) {
                    System.err.println(Thread.currentThread() + ": NoSuchFile: " + path + " currentWorkdir="
                            + Paths.get("./").toAbsolutePath());
                    continue;
                }

                System.out.println(Thread.currentThread() + ": Sending file: " + start + " : " + path);
                svc.getFileServicePort().write(path.toString(),
                        IOUtils.toByteArray(Files.newInputStream(path)));
            }

            Path out = path.resolveSibling(
                    path.getFileName() + (asyncTest ? "." + Thread.currentThread().getId() : "") + ".out");

            if (read) {
                System.out.println(Thread.currentThread() + ": Reading file: " + new DateTime() + " : " + out);
                if (out.getParent() != null) {
                    Files.createDirectories(out.getParent());
                }

                byte[] arr = svc.getFileServicePort().read(path.toString());
                IOUtils.write(arr, Files.newOutputStream(out));
            }

            if (write && read) {
                long inputChk = FileUtils.checksumCRC32(path.toFile());
                long outputChk = FileUtils.checksumCRC32(out.toFile());
                if (inputChk != outputChk) {
                    throw new IOException(Thread.currentThread()
                            + ": Checksum Failed: failure to write/read: in=" + path + ", out=" + out);
                }
                System.out.println(Thread.currentThread() + ": Checked Checksums: " + new DateTime() + " : "
                        + inputChk + " / " + outputChk);
            }

            if (delete) {
                boolean deleted = svc.getFileServicePort().delete(path.toString());
                if (!deleted) {
                    throw new IOException(
                            Thread.currentThread() + ": Delete Failed: failure to delete: in=" + path);
                } else {
                    System.out.println(Thread.currentThread() + ": Deleted File: in=" + path);
                }
            }
        }
    } catch (Throwable t) {
        t.printStackTrace();
        throw new RuntimeException(t);
    }
}

From source file:au.com.scds.chats.dom.activity.Activities.java

License:Apache License

@Action(semantics = SemanticsOf.SAFE)
@ActionLayout(bookmarking = BookmarkPolicy.NEVER)
@MemberOrder(sequence = "6")
public List<ActivityEvent> listAllFutureActivities() {
    return container.allMatches(new QueryDefault<>(ActivityEvent.class, "findAllFutureActivities",
            "currentDateTime", new DateTime()));
}

From source file:au.com.scds.chats.dom.activity.Activities.java

License:Apache License

@Programmatic
public List<ActivityEvent> listAllPastActivities() {
    return container.allMatches(new QueryDefault<>(ActivityEvent.class, "findAllPastActivities",
            "currentDateTime", new DateTime()));
}

From source file:au.edu.uq.cmm.paul.servlet.WebUIController.java

License:Open Source License

private Date determineCutoff(Model model, String olderThan, String age) {

    if (olderThan.isEmpty() && age.isEmpty()) {
        model.addAttribute("message", "Either an expiry date or an age must be supplied");
        return null;
    }/*from  w  ww .  ja v a2s.c o m*/
    String[] parts = age.split("\\s", 2);
    DateTime cutoff;
    if (olderThan.isEmpty()) {
        int value;
        try {
            value = Integer.parseInt(parts[0]);
        } catch (NumberFormatException ex) {
            model.addAttribute("message", "Age quantity is not an integer");
            return null;
        }
        BaseSingleFieldPeriod p;
        switch (parts.length == 1 ? "" : parts[1]) {
        case "minute":
        case "minutes":
            p = Minutes.minutes(value);
            break;
        case "hour":
        case "hours":
            p = Hours.hours(value);
            break;
        case "day":
        case "days":
            p = Days.days(value);
            break;
        case "week":
        case "weeks":
            p = Weeks.weeks(value);
            break;
        case "month":
        case "months":
            p = Months.months(value);
            break;
        case "year":
        case "years":
            p = Years.years(value);
            break;
        default:
            model.addAttribute("message", "Unrecognized age time-unit");
            return null;
        }
        cutoff = DateTime.now().minus(p);
    } else {
        cutoff = parseTimestamp(olderThan);
        if (cutoff == null) {
            model.addAttribute("message", "Unrecognizable expiry date");
            return null;
        }
    }
    if (cutoff.isAfter(new DateTime())) {
        model.addAttribute("message", "Supplied or computed expiry date is in the future!");
        return null;
    }
    model.addAttribute("computedDate", FORMATS[0].print(cutoff));
    return cutoff.toDate();
}

From source file:au.id.hazelwood.xmltvguidebuilder.runner.App.java

License:Apache License

public void run(File configFile, File outFile) throws InvalidConfigException, JAXBException, IOException {
    LOGGER.info("Running XMLTV Guide Builder");
    StopWatch watch = new StopWatch();
    watch.start();/*  w  w  w .  java2 s .c o m*/

    LOGGER.info("Reading config file '{}'", configFile.getCanonicalPath());
    Config config = configFactory.create(configFile);
    DateTime today = new DateTime().withTimeAtStartOfDay();
    DateTime from = today.plusDays(config.getOffset());
    DateTime to = from.plusDays(config.getDays());

    LOGGER.info("Getting listing from foxtel grabber between {} and {}", toISODateTime(from),
            toISODateTime(to));
    ChannelListings channelListings = grabber.getListing(config, from, to, config.getChannelConfigs());

    LOGGER.info("Verifying listings for all channels between {} and {}",
            new Object[] { toISODateTime(from), toISODateTime(to) });
    DateTime subsetTo = from.plusDays(7).isBefore(to) ? from.plusDays(7) : to;
    listingVerifier.verifyListing(channelListings, from, to, subsetTo);

    LOGGER.info("Backup old output files");
    backupOldOutputFiles(outFile);

    LOGGER.info("Writing result to {}", outFile.getCanonicalPath());
    Writer writer = new BufferedWriter(new FileWriterWithEncoding(outFile, "UTF-8"));
    bindingService.marshal(xmltvMapper.toXmltv(channelListings), writer);
    IOUtils.closeQuietly(writer);

    watch.stop();
    LOGGER.info("XMLTV Guide Builder successful in {}", formatDurationWords(watch.getTime()));
}

From source file:au.org.scoutmaster.views.ContactView.java

private void backgroundTab() {
    // Background tab
    final SMMultiColumnFormLayout<Contact> background = new SMMultiColumnFormLayout<Contact>(2,
            this.fieldGroup);
    background.setColumnLabelWidth(0, 120);
    this.tabs.addTab(background, "Background");
    background.setMargin(true);//ww  w  .  j a va 2  s . co m

    background.colspan(2);
    background.bindTextAreaField("Hobbies", Contact_.hobbies, 4);
    background.newLine();
    background.colspan(2);
    background.bindDateField("Affiliated Since", Contact_.affiliatedSince, "yyyy-MM-dd", Resolution.DAY);
    background.newLine();
    background.colspan(2);
    background.bindTextField("Current Employer", Contact_.currentEmployer);
    background.newLine();
    background.colspan(2);
    background.bindTextField("Job Title", Contact_.jobTitle);
    background.newLine();
    background.bindBooleanField("License", Contact_.hasLicense);
    background.newLine();
    background.bindBooleanField("Has WWC", Contact_.hasWWC);
    final DateField wwcExpiryDate = background.bindDateField("WWC Expiry", Contact_.wwcExpiry, "yyyy-MM-dd",
            Resolution.DAY);
    // WWC expiry is five years.
    wwcExpiryDate.setValue(new DateTime().plusYears(5).toDate());
    background.bindTextField("WWC No.", Contact_.wwcNo);
    background.newLine();
    background.bindBooleanField("Has Police Check", Contact_.hasPoliceCheck);
    final DateField policeCheckExpiry = background.bindDateField("Police Check Expiry",
            Contact_.policeCheckExpiry, "yyyy-MM-dd", Resolution.DAY);
    policeCheckExpiry.setValue(new DateTime().plusYears(5).toDate());
    background.newLine();
    background.bindBooleanField("Has Food Handling", Contact_.hasFoodHandlingCertificate);
    background.bindBooleanField("Has First Aid Certificate", Contact_.hasFirstAidCertificate);
}

From source file:AuditGenerator.SeedData.java

private static void generateAudits() throws SQLException, InterruptedException {
    //generate 10 audits for Acq1
    DateTime thisDateTime = new DateTime();
    DateTimeFormatter fmt = DateTimeFormat.forPattern("yyyy-MM-dd HH:mm:ss");
    String sqlDate = thisDateTime.toString(fmt);

    String orgId = "227";
    String parentId = "229";
    Integer siteId = 201;//  w  w  w  . ja v a2 s. c om
    for (int i = 1; i < 50; i++) {
        siteId++;
        createAudit(sqlDate, orgId, parentId, 1, siteId, i + 300);
    }
    String a2Id = "228";
    //generate 10 audits for acq 2
    for (int i = 1; i < 50; i++) {
        siteId++;
        createAudit(sqlDate, a2Id, parentId, 1, siteId, -1);
    }
    //generate 10 audits for solo org
    String soloId = "230";
    for (int i = 1; i < 50; i++) {
        siteId++;
        createAudit(sqlDate, soloId, null, 1, siteId, -1);
    }
    //generate 19 audits for vcm 1
    String vcmId = "231";
    for (int i = 1; i < 60; i++) {
        createMultiAudit(sqlDate, vcmId, "227", "228", 1, i);

    }
    //generate 10 non-published audits for vcm1
    String vcmId1 = "231";
    for (int i = 1; i < 11; i++) {
        createAudit(sqlDate, vcmId1, "0", 0, i, -1);
    }
    //generate violations for audit 31 (site 1) for vcms 2-51
    int baseVCM = 231;

    for (int i = 0; i < 50; i++) {
        int vcm = baseVCM + i;
        generateContent(vcm + "");
    }
}

From source file:awslabs.lab21.StudentCode.java

License:Open Source License

/**
 * Create and return a pre-signed URL for the specified item. Set the URL to expire one hour from the 
 * moment it was generated.//from  www .  ja va 2  s.c  o m
 * Hint: Use the generatePresignedUrl() method of the client object.
 * 
 * @param s3Client    The S3 client object.   
 * @param bucketName The name of the bucket containing the object.
 * @param key    The key used to identify the object.
 * @return        The pre-signed URL for the object.
 */
@Override
public String generatePreSignedUrl(AmazonS3 s3Client, String bucketName, String key) {
    //TODO: Replace this call to the super class with your own implementation of the method.
    DateTime dt = new DateTime();
    URL preSignedURL = s3Client.generatePresignedUrl(bucketName, key, dt.plusMinutes(30).toDate());
    System.out.println(preSignedURL);
    return preSignedURL.toString();
}

From source file:azkaban.app.LoggingJob.java

License:Apache License

@Override
public void run() {
    String jobName = getInnerJob().getId();
    Utils.makePaths(new File(_logDir));
    File jobLogDir = new File(_logDir + File.separator + jobName);
    jobLogDir.mkdir();//from w w  w .  j  a  v  a2s  .co m
    String date = DateTimeFormat.forPattern("MM-dd-yyyy.HH.mm.ss.SSS").print(new DateTime());
    File runLogDir = new File(jobLogDir, date);
    runLogDir.mkdir();
    String logName = new File(runLogDir, jobName + "." + date + ".log").getAbsolutePath();
    Appender jobAppender = null;
    try {
        jobAppender = new FileAppender(loggerLayout, logName, false);
        _logger.addAppender(jobAppender);
    } catch (IOException e) {
        _logger.error("Could not open log file in " + _logDir, e);
    }

    boolean succeeded = false;
    boolean jobNotStaleException = false;
    long start = System.currentTimeMillis();
    try {
        MonitorImpl.getInternalMonitorInterface().jobEvent(getInnerJob(), System.currentTimeMillis(),
                JobAction.START_WORKFLOW_JOB, JobState.NOP);

        getInnerJob().run();
        succeeded = true;

        MonitorImpl.getInternalMonitorInterface().jobEvent(getInnerJob(), System.currentTimeMillis(),
                JobAction.END_WORKFLOW_JOB, JobState.SUCCESSFUL);
    } catch (Exception e) {
        _logger.error("Fatal error occurred while running job '" + jobName + "':", e);
        MonitorImpl.getInternalMonitorInterface().jobEvent(getInnerJob(), System.currentTimeMillis(),
                JobAction.END_WORKFLOW_JOB, getInnerJob().isCanceled() ? JobState.CANCELED : JobState.FAILED);
        if (e instanceof RuntimeException)
            throw (RuntimeException) e;
        else
            throw new RuntimeException(e);
    } finally {
        long end = System.currentTimeMillis();
        Props props = new Props();
        props.put("start", Long.toString(start));
        props.put("end", Long.toString(end));
        props.put("succeeded", Boolean.toString(succeeded));
        props.put("jobNotStaleException", Boolean.toString(jobNotStaleException));
        try {
            props.storeLocal(new File(runLogDir, "run.properties"));
        } catch (IOException e) {
            _logger.warn(String.format("IOException when storing props to local dir[%s]", runLogDir), e);
            throw new RuntimeException(e);
        }

        if (jobAppender != null) {
            _logger.removeAppender(jobAppender);
            jobAppender.close();
        }

    }
}

From source file:azkaban.app.PropsUtils.java

License:Apache License

public static Props produceParentProperties(final ExecutableFlow flow) {
    Props parentProps = new Props();

    parentProps.put("azkaban.flow.id", flow.getId());
    parentProps.put("azkaban.flow.uuid", UUID.randomUUID().toString());

    DateTime loadTime = new DateTime();

    parentProps.put("azkaban.flow.start.timestamp", loadTime.toString());
    parentProps.put("azkaban.flow.start.year", loadTime.toString("yyyy"));
    parentProps.put("azkaban.flow.start.month", loadTime.toString("MM"));
    parentProps.put("azkaban.flow.start.day", loadTime.toString("dd"));
    parentProps.put("azkaban.flow.start.hour", loadTime.toString("HH"));
    parentProps.put("azkaban.flow.start.minute", loadTime.toString("mm"));
    parentProps.put("azkaban.flow.start.seconds", loadTime.toString("ss"));
    parentProps.put("azkaban.flow.start.milliseconds", loadTime.toString("SSS"));
    parentProps.put("azkaban.flow.start.timezone", loadTime.toString("ZZZZ"));
    return parentProps;
}