Example usage for org.joda.time.format DateTimeFormat forPattern

List of usage examples for org.joda.time.format DateTimeFormat forPattern

Introduction

In this page you can find the example usage for org.joda.time.format DateTimeFormat forPattern.

Prototype

public static DateTimeFormatter forPattern(String pattern) 

Source Link

Document

Factory to create a formatter from a pattern string.

Usage

From source file:at.gv.egovernment.moa.util.DateTimeUtils.java

License:EUPL

public static String formatPEPSDateToMOADate(String pepsDate) {

    if (StringUtils.isEmpty(pepsDate)) {
        return null;
    }/*from  w w w  .java2  s. c om*/

    DateTimeFormatter fmt = null;

    switch (pepsDate.length()) {
    case 4:
        fmt = DateTimeFormat.forPattern("yyyy");
        break;
    case 6:
        fmt = DateTimeFormat.forPattern("yyyyMM");
        break;
    case 8:
        fmt = DateTimeFormat.forPattern("yyyyMMdd");
        break;
    default:
        fmt = DateTimeFormat.forPattern("yyyy-MM-dd");
        break;
    }

    DateTime dt = fmt.parseDateTime(pepsDate);
    DateTimeFormatter fmt2 = DateTimeFormat.forPattern("yyyy-MM-dd");
    return fmt2.print(dt);

}

From source file:au.edu.ausstage.mobile.GathererManager.java

License:Open Source License

/**
 * Constructor for this class//from  ww  w.jav  a  2  s . c o  m
 *
 * @param database a valid DbManager object
 * @param servletConfig a valid ServletConfig object
 */
public GathererManager(DbManager database, ServletConfig servletConfig) {

    // double check the parameter
    if (database == null || servletConfig == null) {
        throw new IllegalArgumentException("All parameters to this constructor are required");
    }

    // store a reference to the database object locally
    this.database = database;

    // instantiate the email processing objects
    emailOptions = new EmailOptions();
    try {

        // set the options for sending email
        emailOptions.setHost(servletConfig.getServletContext().getInitParameter("mailHost"));

        if (InputUtils.isValid(servletConfig.getServletContext().getInitParameter("mailUser")) == true) {
            emailOptions.setUser(servletConfig.getServletContext().getInitParameter("mailUser"));
            emailOptions.setPassword(servletConfig.getServletContext().getInitParameter("mailPassword"));
        }

        // use security?
        if (InputUtils.isValid(servletConfig.getServletContext().getInitParameter("mailSsl")) == true) {
            // double check the value of this parameter
            if (servletConfig.getServletContext().getInitParameter("mailSsl").equals("yes") == true
                    || servletConfig.getServletContext().getInitParameter("mailSsl").equals("true") == true) {
                emailOptions.setSSL(true);
            } else {
                emailOptions.setSSL(false);
            }
        }

        if (InputUtils.isValid(servletConfig.getServletContext().getInitParameter("mailTls")) == true) {
            // double check the value of this parameter
            if (servletConfig.getServletContext().getInitParameter("mailTls").equals("yes") == true
                    || servletConfig.getServletContext().getInitParameter("mailTls").equals("true") == true) {
                emailOptions.setTLS(true);
            } else {
                emailOptions.setTLS(false);
            }
        }

        emailOptions.setPort(servletConfig.getServletContext().getInitParameter("mailPort"));
        emailOptions.setFromAddress(servletConfig.getServletContext().getInitParameter("mailFrom"));
        emailOptions.setToAddress(servletConfig.getServletContext().getInitParameter("mailTo"));

    } catch (IllegalArgumentException ex) {
        throw new IllegalArgumentException("Unable to construct the email options class", ex);
    }

    // instantiate the email manager class
    emailManager = new EmailManager(emailOptions);

    // instantiate the date time helper variables variables
    dateTimeFormat = DateTimeFormat.forPattern(JODA_DATE_TIME_FORMAT);
    inputDateTimeFormat = DateTimeFormat.forPattern(JODA_INPUT_DATE_TIME_FORMAT);
}

From source file:au.edu.ausstage.tweetgatherer.MessageProcessor.java

License:Open Source License

/**
 * A constructor for this class//w w  w .  java  2s  .co  m
 *
 * @param tweets   a blocking queue used to store new messages
 * @param logDir   the directory to log files to
 * @param manager  a valid DbManager object
 *
 */
public MessageProcessor(LinkedBlockingQueue<STweet> tweets, String logDir, DbManager manager,
        EmailManager emailManager) {

    // check on the parameters
    if (tweets == null) {
        throw new IllegalArgumentException("The tweets parameter cannot be null");
    }

    if (InputUtils.isValid(logDir) == false) {
        throw new IllegalArgumentException("The log directory parameter cannot be null or empty");
    }

    if (FileUtils.doesDirExist(logDir) == false) {
        throw new IllegalArgumentException("The specified log directory is not valid");
    }

    if (manager == null) {
        throw new IllegalArgumentException("The database parameter cannot be null");
    }

    if (emailManager == null) {
        throw new IllegalArgumentException("The EmailManager parameter cannot be null");
    }

    // assign parrameters to local variables
    newTweets = tweets;
    logFiles = logDir;
    database = manager;
    this.emailManager = emailManager;

    // build the dateTimeFormat object
    dateTimeFormat = DateTimeFormat.forPattern(JODA_DATE_TIME_FORMAT);
    inputDateTimeFormat = DateTimeFormat.forPattern(JODA_INPUT_DATE_TIME_FORMAT);

    // build the Extractor object
    extractHashTags = new Extractor();
}

From source file:au.org.scoutmaster.domain.Contact.java

public void setBirthDate(final String fieldValue) {
    final DateTimeParser[] parsers = { DateTimeFormat.forPattern("yyyy-MM-dd").getParser(),
            DateTimeFormat.forPattern("yyyy/MM/dd").getParser() };
    final DateTimeFormatter formatter = new DateTimeFormatterBuilder().append(null, parsers).toFormatter();

    if (fieldValue != null && fieldValue.length() > 0) {
        final DateTime date1 = formatter.parseDateTime(fieldValue);
        setBirthDate(new java.sql.Date(date1.toDate().getTime()));
    }//from  w  ww  . j  a  v  a  2 s.co m
}

From source file:AuditGenerator.SeedData.java

private static void createAudit(String date, String childId, String parentId, int statusIndex, int siteId,
        int referringUrlId) throws SQLException, InterruptedException {
    String sql;/*from   ww  w  . j a v  a2s .com*/
    String currentSeverityId = "1";
    DateTime currentTime = DateTime.now();
    int randomSecond = randomGenerator.nextInt(100000);
    currentTime = currentTime.minusSeconds(randomSecond);

    DateTimeFormatter fmt = DateTimeFormat.forPattern("yyyy-MM-dd HH:mm:ss");
    String due = currentTime.toString(fmt);

    String thisSiteId = "" + siteId;
    if (referringUrlId == -1) {
        if (statusIndex == 0 || statusIndex == 1) {
            System.out.println("statusIndex " + statusIndex);
            sql = "INSERT into " + dbName
                    + ".audits (created_at, updated_at, status, site_id, due_at, published_at,audit_type_id) VALUES ('"
                    + date + "', '" + date + "', 'published', " + thisSiteId + ",'" + due + "', '" + date
                    + "',1)";
        } else {
            sql = "INSERT into " + dbName
                    + ".audits (created_at, updated_at, status, site_id,referral_url_id, due_at,audit_type_id) VALUES ('"
                    + date + "', '" + date + "', 'unaudited', " + thisSiteId + ",'" + due + "',1)";
        }
    } else {
        if (statusIndex == 0 || statusIndex == 1) {
            System.out.println("statusIndex " + statusIndex);
            sql = "INSERT into " + dbName
                    + ".audits (created_at, updated_at, status, site_id, referral_url_id, due_at, published_at,audit_type_id) VALUES ('"
                    + date + "', '" + date + "', 'published', " + thisSiteId + "," + referringUrlId + ",'" + due
                    + "', '" + date + "',1)";
        } else {
            sql = "INSERT into " + dbName
                    + ".audits (created_at, updated_at, status, site_id,referral_url_id, due_at,audit_type_id) VALUES ('"
                    + date + "', '" + date + "', 'unaudited', " + thisSiteId + "," + referringUrlId + ",'" + due
                    + "',1)";
        }
    }

    //Grab audit ID from insert                 
    int auditId = sqlHandler.getSQLResponse(sql);

    String typePMMSQL = "INSERT INTO " + dbName
            + ".audit_audit_types (audit_id, audit_type_id, created_at, updated_at) VALUES (" + auditId
            + ", 1, '" + date + "','" + date + "')";
    sqlHandler.executeStatement(typePMMSQL);
    ArrayList addContent = new ArrayList<String>();
    addContent.add(4);
    Iterator it = addContent.iterator();
    while (it.hasNext()) {
        int nextContent = (int) it.next();
        String sql3 = "INSERT INTO " + dbName
                + ".audit_content_types (audit_id, content_type_id, created_at, updated_at) VALUES (" + auditId
                + ", " + nextContent + ", '" + date + "', '" + date + "')";
        System.out.println(sql3);
        sqlHandler.executeStatement(sql3);
        //severities are related to content type

        String sql4 = "INSERT INTO " + dbName
                + ".audit_client_content_type_severities (audit_id, severity_id, content_type_id, client_organization_id, created_at, updated_at)"
                + "VALUES (" + auditId + ", " + currentSeverityId + "," + nextContent + ", " + childId + ", '"
                + date + "', '" + date + "')";
        System.out.println(sql4);
        sqlHandler.executeStatement(sql4);
        if (parentId != null && statusIndex == 1) {
            String parentContentSQL = "INSERT INTO " + dbName
                    + ".audit_client_content_type_severities (audit_id, severity_id, content_type_id, client_organization_id, created_at, updated_at)"
                    + "VALUES (" + auditId + ", " + currentSeverityId + "," + nextContent + ", " + parentId
                    + ", '" + date + "', '" + date + "')";
            sqlHandler.executeStatement(parentContentSQL);
        }
    }
    if (statusIndex == 1) {
        String thisResolution = "cleared";
        String sql5;
        if ("Under Review".equals(thisResolution)) {
            sql5 = "INSERT INTO " + dbName + ".audit_client_merchant_resolutions "
                    + "(audit_id, severity_id, status, author_organization_id, created_at, updated_at)"
                    + "VALUES (" + auditId + ", " + currentSeverityId + ", '" + thisResolution + "', " + childId
                    + ", '" + date + "', '" + date + "')";
        } else {
            sql5 = "INSERT INTO " + dbName + ".audit_client_merchant_resolutions "
                    + "(audit_id, severity_id, status, author_organization_id, recipient_organization_id, published_at, created_at, updated_at)"
                    + "VALUES (" + auditId + ", " + currentSeverityId + ", '" + thisResolution + "', " + childId
                    + ", " + parentId + ", '" + date + "', '" + date + "', '" + date + "')";
        }
        System.out.println("merchant res sql " + sql5);
        sqlHandler.executeStatement(sql5);
    }
    // create one or more notes  
    Random r = new Random();
    int noteCount = r.nextInt(6 - 1) + 1;
    for (int i = 0; i < noteCount; i++) {
        generateNotes(auditId, i);
    }
    generateAuditChange(auditId);
}

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;/*from  www.j a  v  a 2  s  .c  o m*/
    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:AuditGenerator.SeedData.java

private static void createMultiAudit(String date, String childId, String parentId1, String parentId2,
        int statusIndex, int siteId) {
    String sql;//from  w  w  w.  jav  a2  s.  c  om
    String currentSeverityId = "1";
    DateTime currentTime = DateTime.now();

    int randomSecond = randomGenerator.nextInt(100000);
    currentTime = currentTime.minusSeconds(randomSecond);

    DateTimeFormatter fmt = DateTimeFormat.forPattern("yyyy-MM-dd HH:mm:ss");
    String due = currentTime.toString(fmt);
    String thisSiteId = "" + siteId;
    if (statusIndex == 0 || statusIndex == 1) {
        System.out.println("statusIndex " + statusIndex);
        sql = "INSERT into " + dbName
                + ".audits (created_at, updated_at, status, site_id, due_at, published_at) VALUES ('" + date
                + "', '" + date + "', 'published', " + thisSiteId + ", '" + due + "', '" + date + "')";
    } else {
        sql = "INSERT into " + dbName + ".audits (created_at, updated_at, status, site_id, due_at) VALUES ('"
                + date + "', '" + date + "', 'unaudited', " + thisSiteId + ", '" + due + "')";
    }

    //Grab audit ID from insert                 
    int auditId = sqlHandler.getSQLResponse(sql);
    String typePMMSQL = "INSERT INTO " + dbName
            + ".audit_audit_types (audit_id, audit_type_id, created_at, updated_at) VALUES (" + auditId
            + ", 1, '" + date + "','" + date + "')";

    sqlHandler.executeStatement(typePMMSQL);
    ArrayList addContent = new ArrayList<String>();
    addContent.add(4);
    Iterator it = addContent.iterator();
    while (it.hasNext()) {
        int nextContent = (int) it.next();
        String sql3 = "INSERT INTO " + dbName
                + ".audit_content_types (audit_id, content_type_id, created_at, updated_at) VALUES (" + auditId
                + ", " + nextContent + ", '" + date + "', '" + date + "')";
        System.out.println(sql3);
        sqlHandler.executeStatement(sql3);
        //severities are related to content type

        String sql4 = "INSERT INTO " + dbName
                + ".audit_client_content_type_severities (audit_id, severity_id, content_type_id, client_organization_id, created_at, updated_at)"
                + "VALUES (" + auditId + ", " + currentSeverityId + "," + nextContent + ", " + childId + ", '"
                + date + "', '" + date + "')";
        System.out.println(sql4);
        sqlHandler.executeStatement(sql4);
        if (parentId1 != null && statusIndex == 1) {
            String parentContentSQL = "INSERT INTO " + dbName
                    + ".audit_client_content_type_severities (audit_id, severity_id, content_type_id, client_organization_id, created_at, updated_at)"
                    + "VALUES (" + auditId + ", " + currentSeverityId + "," + nextContent + ", " + parentId1
                    + ", '" + date + "', '" + date + "')";
            String parentContent2SQL = "INSERT INTO " + dbName
                    + ".audit_client_content_type_severities (audit_id, severity_id, content_type_id, client_organization_id, created_at, updated_at)"
                    + "VALUES (" + auditId + ", " + currentSeverityId + "," + nextContent + ", " + parentId2
                    + ", '" + date + "', '" + date + "')";

            sqlHandler.executeStatement(parentContentSQL);
            sqlHandler.executeStatement(parentContent2SQL);
        }
    }
    if (statusIndex == 1) {
        String thisResolution = "cleared";
        String sql5, sql6;
        if ("Under Review".equals(thisResolution)) {
            sql5 = "INSERT INTO " + dbName + ".audit_client_merchant_resolutions "
                    + "(audit_id, severity_id, status, author_organization_id, created_at, updated_at)"
                    + "VALUES (" + auditId + ", " + currentSeverityId + ", '" + thisResolution + "', " + childId
                    + ", '" + date + "', '" + date + "')";
            sql6 = "";

        } else {
            sql5 = "INSERT INTO " + dbName + ".audit_client_merchant_resolutions "
                    + "(audit_id, severity_id, status, author_organization_id, recipient_organization_id, published_at, created_at, updated_at)"
                    + "VALUES (" + auditId + ", " + currentSeverityId + ", '" + thisResolution + "', " + childId
                    + ", " + parentId1 + ", '" + date + "', '" + date + "', '" + date + "')";

            sql6 = "INSERT INTO " + dbName + ".audit_client_merchant_resolutions "
                    + "(audit_id, severity_id, status, author_organization_id, recipient_organization_id, published_at, created_at, updated_at)"
                    + "VALUES (" + auditId + ", " + currentSeverityId + ", '" + thisResolution + "', " + childId
                    + ", " + parentId2 + ", '" + date + "', '" + date + "', '" + date + "')";
        }
        System.out.println("merchant res sql " + sql5);
        sqlHandler.executeStatement(sql5);
        sqlHandler.executeStatement(sql6);
    }
}

From source file:azkaban.app.jmx.JobScheduler.java

License:Apache License

public String scheduleWorkflow(String jobName, boolean ignoreDeps, int hour, int minutes, int seconds,
        String scheduledDate, boolean isRecurring, int period, String periodUnits) {
    String errorMsg = null;//  ww  w.  j a  va2  s. co m
    if (jobName == null || jobName.trim().length() == 0) {
        errorMsg = "You must select at least one job to run.";
        logger.error(errorMsg);
        return errorMsg;
    }
    JobDescriptor descriptor = jobManager.getJobDescriptor(jobName);
    if (descriptor == null) {
        errorMsg = "Job: '" + jobName + "' doesn't exist.";
        logger.error(errorMsg);
        return errorMsg;
    }

    DateTime day = null;
    DateTime time = null;
    try {
        if (scheduledDate == null || scheduledDate.trim().length() == 0) {
            day = new LocalDateTime().toDateTime();
            time = day.withHourOfDay(hour).withMinuteOfHour(minutes).withSecondOfMinute(seconds);
            if (day.isAfter(time)) {
                time = time.plusDays(1);
            }
        } else {
            try {
                day = DateTimeFormat.forPattern("MM-dd-yyyy").parseDateTime(scheduledDate);
            } catch (IllegalArgumentException e) {
                logger.error(e);
                return "Invalid date: '" + scheduledDate + "', \"MM-dd-yyyy\" format is expected.";
            }
            time = day.withHourOfDay(hour).withMinuteOfHour(minutes).withSecondOfMinute(seconds);
        }
    } catch (IllegalFieldValueException e) {
        logger.error(e);
        return "Invalid schedule time (see logs): " + e.getMessage();

    }
    ReadablePeriod thePeriod = null;
    if (isRecurring) {
        if ("d".equals(periodUnits)) {
            thePeriod = Days.days(period);
        } else if ("h".equals(periodUnits)) {
            thePeriod = Hours.hours(period);
        } else if ("m".equals(periodUnits)) {
            thePeriod = Minutes.minutes(period);
        } else if ("s".equals(periodUnits)) {
            thePeriod = Seconds.seconds(period);
        } else {
            errorMsg = "Unknown period unit: " + periodUnits;
            logger.error(errorMsg);
            return errorMsg;
        }
    }
    try {
        if (thePeriod == null) {
            scheduler.schedule(jobName, time, ignoreDeps);
        } else {
            scheduler.schedule(jobName, time, thePeriod, ignoreDeps);
        }
        return "Schedule Successful!";
    } catch (Exception e) {
        logger.error(e);
        return "Schedule Failed (see logs): " + e.getMessage();
    }
}

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();/*  ww  w.ja v a  2s .c o 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.common.web.GuiUtils.java

License:Apache License

public String formatDate(DateTime date, String format) {
    DateTimeFormatter f = DateTimeFormat.forPattern(format);
    return f.print(date);
}