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:com.google.sampling.experiential.model.Event.java

License:Open Source License

public String[] toCSV(List<String> columnNames, boolean anon) {
    DateTimeFormatter jodaTimeFormatter = DateTimeFormat.forPattern(TimeUtil.DATETIME_FORMAT);
    int csvIndex = 0;
    String[] parts = new String[10 + columnNames.size()];
    if (anon) {/*from ww  w. j  ava 2  s  .  c o m*/
        parts[csvIndex++] = Event.getAnonymousId(who + SALT);
    } else {
        parts[csvIndex++] = who;
    }
    parts[csvIndex++] = jodaTimeFormatter.print(new DateTime(when.getTime()));
    parts[csvIndex++] = appId;
    parts[csvIndex++] = pacoVersion;
    parts[csvIndex++] = experimentId;
    parts[csvIndex++] = experimentName;
    parts[csvIndex++] = experimentVersion != null ? Integer.toString(experimentVersion) : "0";

    parts[csvIndex++] = responseTime != null ? jodaTimeFormatter.print(getResponseTimeWithTimeZone(null))
            : null;
    parts[csvIndex++] = scheduledTime != null ? jodaTimeFormatter.print(getScheduledTimeWithTimeZone(null))
            : null;
    parts[csvIndex++] = timeZone;

    Map<String, String> whatMap = getWhatMap();
    for (String key : columnNames) {
        String value = whatMap.get(key);
        parts[csvIndex++] = value;
    }
    return parts;
}

From source file:com.google.sampling.experiential.server.migration.MigrationBackendServlet.java

License:Open Source License

@Override
protected void doGet(final HttpServletRequest req, HttpServletResponse resp)
        throws ServletException, IOException {
    log.info("MIGRATE BACKEND");
    final String requestorEmail = getRequestorEmail(req);
    final String migrationJobName = HttpUtil.getParam(req, "migrationName");
    final String useTaskQueue = HttpUtil.getParam(req, "queue");
    final String cursor = HttpUtil.getParam(req, "cursor");
    final String sTime = HttpUtil.getParam(req, "startTime");
    final String eTime = HttpUtil.getParam(req, "endTime");

    final String jobId = migrationJobName + "_"
            + DigestUtils.md5Hex(requestorEmail + Long.toString(System.currentTimeMillis()));
    log.info("In migrate backend for job: " + jobId);

    final ReportJobStatusManager statusMgr = new ReportJobStatusManager();
    statusMgr.startReport(requestorEmail, jobId);

    final ClassLoader cl = getClass().getClassLoader();
    final Thread thread2 = ThreadManager.createBackgroundThread(new Runnable() {
        @Override/*from   www .  j  av a 2  s . co m*/
        public void run() {

            log.info("MigrationBackend running");
            Thread.currentThread().setContextClassLoader(cl);
            try {
                DateTime startTime = null;
                DateTime endTime = null;
                if (sTime != null && eTime != null) {
                    startTime = DateTimeFormat.forPattern("yyyy-MM-dd'T'HH:mm:ss.sssZ").parseDateTime(sTime);
                    endTime = DateTimeFormat.forPattern("yyyy-MM-dd'T'HH:mm:ss.sssZ").parseDateTime(eTime);
                }
                if (doMigration(migrationJobName, cursor, startTime, endTime)) {
                    statusMgr.completeReport(requestorEmail, jobId, Constants.LOCATION_NA);
                } else {
                    statusMgr.failReport(requestorEmail, jobId, "Check server logs for stacktrace");
                }
            } catch (Throwable e) {
                final String fullStack = getStackTraceAsString(e);
                final String string = fullStack.length() > 700 ? fullStack.substring(0, 700) : fullStack;
                statusMgr.failReport(requestorEmail, jobId,
                        e.getClass() + "." + e.getMessage() + "\n" + string);
                log.severe("Could not run migration job: " + e.getMessage());

                log.severe("stacktrace: " + fullStack);
            }
        }
    });
    thread2.start();
    log.info("Leaving migration backend");
    resp.setContentType("text/plain;charset=UTF-8");
    resp.getWriter().println(jobId);
}

From source file:com.google.sampling.experiential.server.migration.MigrationFrontendServlet.java

License:Open Source License

@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

    resp.setContentType("application/json;charset=UTF-8");

    User user = AuthUtil.getWhoFromLogin();
    if (user == null) {
        AuthUtil.redirectUserToLogin(req, resp);
    } else if (AuthUtil.isUserAdmin()) {
        String cursor = null;// www  .  j av  a2  s.  c om
        DateTime stDate = null;
        DateTime endDate = null;
        cursor = req.getParameter("cursor");
        String jobName = req.getParameter("name");
        String startTime = req.getParameter("startTime");
        String endTime = req.getParameter("endTime");
        try {
            DateTimeFormatter formatter = DateTimeFormat.forPattern(TimeUtil.DATE_TIME_WITH_NO_TZ);
            if (startTime != null && endTime != null) {
                stDate = formatter.parseDateTime(startTime);
                endDate = formatter.parseDateTime(endTime);
            }
        } catch (IllegalArgumentException e) {
            resp.sendError(HttpServletResponse.SC_BAD_REQUEST);
        }
        String jobId = sendMigrateRequestToBackend(req, jobName, cursor, stDate, endDate);
        String redirectUrl = null;
        // On dev local, when we kick off job from backend module - migration with correct port number, 
        // the job status which is defined in default module is getting searched in migration module.
        // In other environments, the request gets routed through dispatch xml.
        if (EnvironmentUtil.isDevInstance()) {
            redirectUrl = "http://"
                    + ModulesServiceFactory.getModulesService().getVersionHostname("default", null)
                    + "/jobStatus?jobId=" + jobId;
        } else {
            redirectUrl = "/jobStatus?jobId=" + jobId;
        }
        resp.sendRedirect(redirectUrl);
    } else {
        resp.sendError(403);
    }
}

From source file:com.google.testing.junit.runner.BazelTestRunner.java

License:Open Source License

/**
 * Takes as arguments the classes or packages to test.
 *
 * <p>To help just run one test or method in a suite, the test suite
 * may be passed in via system properties (-Dbazel.test_suite).
 * An empty args parameter means to run all tests in the suite.
 * A non-empty args parameter means to run only the specified tests/methods.
 *
 * <p>Return codes:/*w  w w.j  av a 2s. c om*/
 * <ul>
 * <li>Test runner failure, bad arguments, etc.: exit code of 2</li>
 * <li>Normal test failure: exit code of 1</li>
 * <li>All tests pass: exit code of 0</li>
 * </ul>
 */
public static void main(String args[]) {
    PrintStream stderr = System.err;

    String suiteClassName = System.getProperty(TEST_SUITE_PROPERTY_NAME);

    if (!checkTestSuiteProperty(suiteClassName)) {
        System.exit(2);
    }

    int exitCode = runTestsInSuite(suiteClassName, args);

    System.err.printf("%nBazelTestRunner exiting with a return value of %d%n", exitCode);
    System.err.println("JVM shutdown hooks (if any) will run now.");
    System.err.println("The JVM will exit once they complete.");
    System.err.println();

    printStackTracesIfJvmExitHangs(stderr);

    DateTimeFormatter formatter = DateTimeFormat.forPattern("yyyy-MM-dd HH:mm:ss");
    DateTime shutdownTime = new DateTime();
    String formattedShutdownTime = formatter.print(shutdownTime);
    System.err.printf("-- JVM shutdown starting at %s --%n%n", formattedShutdownTime);
    System.exit(exitCode);
}

From source file:com.gst.infrastructure.campaigns.sms.domain.SmsCampaign.java

License:Apache License

public static SmsCampaign instance(final AppUser submittedBy, final Report report, final JsonCommand command) {

    final String campaignName = command.stringValueOfParameterNamed(SmsCampaignValidator.campaignName);
    final Long campaignType = command.longValueOfParameterNamed(SmsCampaignValidator.campaignType);
    final Long triggerType = command.longValueOfParameterNamed(SmsCampaignValidator.triggerType);
    final Long providerId = command.longValueOfParameterNamed(SmsCampaignValidator.providerId);
    final String paramValue = command.jsonFragment(SmsCampaignValidator.paramValue);

    final String message = command.stringValueOfParameterNamed(SmsCampaignValidator.message);
    LocalDate submittedOnDate = new LocalDate();
    if (command.hasParameter(SmsCampaignValidator.submittedOnDateParamName)) {
        submittedOnDate = command.localDateValueOfParameterNamed(SmsCampaignValidator.submittedOnDateParamName);
    }//from  w  ww .  j av  a  2  s  . co m
    String recurrence = null;

    LocalDateTime recurrenceStartDate = new LocalDateTime();
    if (SmsCampaignTriggerType.fromInt(triggerType.intValue()).isSchedule()) {
        final Locale locale = command.extractLocale();
        String dateTimeFormat = null;
        if (command.hasParameter(SmsCampaignValidator.dateTimeFormat)) {
            dateTimeFormat = command.stringValueOfParameterNamed(SmsCampaignValidator.dateTimeFormat);
            final DateTimeFormatter fmt = DateTimeFormat.forPattern(dateTimeFormat).withLocale(locale);
            if (command.hasParameter(SmsCampaignValidator.recurrenceStartDate)) {
                recurrenceStartDate = LocalDateTime.parse(
                        command.stringValueOfParameterNamed(SmsCampaignValidator.recurrenceStartDate), fmt);
            }
            recurrence = constructRecurrence(command);
        }
    } else {
        recurrenceStartDate = null;
    }

    return new SmsCampaign(campaignName, campaignType.intValue(), triggerType.intValue(), report, providerId,
            paramValue, message, submittedOnDate, submittedBy, recurrence, recurrenceStartDate);
}

From source file:com.gst.infrastructure.campaigns.sms.domain.SmsCampaign.java

License:Apache License

public Map<String, Object> update(JsonCommand command) {

    final Map<String, Object> actualChanges = new LinkedHashMap<>(5);

    if (command.isChangeInStringParameterNamed(SmsCampaignValidator.campaignName, this.campaignName)) {
        final String newValue = command.stringValueOfParameterNamed(SmsCampaignValidator.campaignName);
        actualChanges.put(SmsCampaignValidator.campaignName, newValue);
        this.campaignName = StringUtils.defaultIfEmpty(newValue, null);
    }// w w  w.  j a v a  2s  .  com
    if (command.isChangeInStringParameterNamed(SmsCampaignValidator.message, this.message)) {
        final String newValue = command.stringValueOfParameterNamed(SmsCampaignValidator.message);
        actualChanges.put(SmsCampaignValidator.message, newValue);
        this.message = StringUtils.defaultIfEmpty(newValue, null);
    }
    if (command.isChangeInStringParameterNamed(SmsCampaignValidator.paramValue, this.paramValue)) {
        final String newValue = command.jsonFragment(SmsCampaignValidator.paramValue);
        actualChanges.put(SmsCampaignValidator.paramValue, newValue);
        this.paramValue = StringUtils.defaultIfEmpty(newValue, null);
    }
    if (command.isChangeInIntegerParameterNamed(SmsCampaignValidator.campaignType, this.campaignType)) {
        final Integer newValue = command.integerValueOfParameterNamed(SmsCampaignValidator.campaignType);
        actualChanges.put(SmsCampaignValidator.campaignType, CampaignType.fromInt(newValue));
        this.campaignType = CampaignType.fromInt(newValue).getValue();
    }

    if (command.isChangeInIntegerParameterNamed(SmsCampaignValidator.triggerType, this.triggerType)) {
        final Integer newValue = command.integerValueOfParameterNamed(SmsCampaignValidator.triggerType);
        actualChanges.put(SmsCampaignValidator.triggerType, SmsCampaignTriggerType.fromInt(newValue));
        this.triggerType = SmsCampaignTriggerType.fromInt(newValue).getValue();
    }

    if (command.isChangeInLongParameterNamed(SmsCampaignValidator.runReportId,
            (this.businessRuleId != null) ? this.businessRuleId.getId() : null)) {
        final String newValue = command.stringValueOfParameterNamed(SmsCampaignValidator.runReportId);
        actualChanges.put(SmsCampaignValidator.runReportId, newValue);
    }
    if (command.isChangeInStringParameterNamed(SmsCampaignValidator.recurrenceParamName, this.recurrence)) {
        final String newValue = command.stringValueOfParameterNamed(SmsCampaignValidator.recurrenceParamName);
        actualChanges.put(SmsCampaignValidator.recurrenceParamName, newValue);
        this.recurrence = StringUtils.defaultIfEmpty(newValue, null);
    }
    if (command.isChangeInLongParameterNamed(SmsCampaignValidator.providerId, this.providerId)) {
        final Long newValue = command.longValueOfParameterNamed(SmsCampaignValidator.providerId);
        actualChanges.put(SmsCampaignValidator.providerId, newValue);
    }

    if (SmsCampaignTriggerType.fromInt(this.triggerType).isSchedule()) {
        final String dateFormatAsInput = command.dateFormat();
        final String dateTimeFormatAsInput = command
                .stringValueOfParameterNamed(SmsCampaignValidator.dateTimeFormat);
        final String localeAsInput = command.locale();
        final Locale locale = command.extractLocale();
        final DateTimeFormatter fmt = DateTimeFormat.forPattern(dateTimeFormatAsInput).withLocale(locale);
        final String valueAsInput = command
                .stringValueOfParameterNamed(SmsCampaignValidator.recurrenceStartDate);
        actualChanges.put(SmsCampaignValidator.recurrenceStartDate, valueAsInput);
        actualChanges.put(SmsCampaignValidator.dateFormatParamName, dateFormatAsInput);
        actualChanges.put(SmsCampaignValidator.dateTimeFormat, dateTimeFormatAsInput);
        actualChanges.put(SmsCampaignValidator.localeParamName, localeAsInput);

        final LocalDateTime newValue = LocalDateTime.parse(valueAsInput, fmt);

        this.recurrenceStartDate = newValue.toDate();
    }

    return actualChanges;
}

From source file:com.gst.infrastructure.campaigns.sms.service.SmsCampaignDomainServiceImpl.java

License:Apache License

private HashMap<String, Object> processRepaymentDataForSms(final LoanTransaction loanTransaction,
        Client groupClient) {//from   ww  w . j ava 2s.com

    HashMap<String, Object> smsParams = new HashMap<String, Object>();
    Loan loan = loanTransaction.getLoan();
    final Client client;
    if (loan.isGroupLoan() && groupClient != null) {
        client = groupClient;
    } else if (loan.isIndividualLoan()) {
        client = loan.getClient();
    } else {
        throw new InvalidParameterException("");
    }

    DateTimeFormatter timeFormatter = DateTimeFormat.forPattern("HH:mm");
    DateTimeFormatter dateFormatter = DateTimeFormat.forPattern("MMM:d:yyyy");

    smsParams.put("id", loanTransaction.getLoan().getClientId());
    smsParams.put("firstname", client.getFirstname());
    smsParams.put("middlename", client.getMiddlename());
    smsParams.put("lastname", client.getLastname());
    smsParams.put("FullName", client.getDisplayName());
    smsParams.put("mobileNo", client.mobileNo());
    smsParams.put("LoanAmount", loan.getPrincpal());
    smsParams.put("LoanOutstanding", loanTransaction.getOutstandingLoanBalance());
    smsParams.put("loanId", loan.getId());
    smsParams.put("LoanAccountId", loan.getAccountNumber());
    smsParams.put("officeId", client.getOffice().getId());

    if (client.getStaff() != null) {
        smsParams.put("loanOfficerId", client.getStaff().getId());
    } else {
        smsParams.put("loanOfficerId", -1);
    }

    smsParams.put("repaymentAmount", loanTransaction.getAmount(loan.getCurrency()));
    smsParams.put("RepaymentDate", loanTransaction.getCreatedDateTime().toLocalDate().toString(dateFormatter));
    smsParams.put("RepaymentTime", loanTransaction.getCreatedDateTime().toLocalTime().toString(timeFormatter));

    if (loanTransaction.getPaymentDetail() != null) {
        smsParams.put("receiptNumber", loanTransaction.getPaymentDetail().getReceiptNumber());
    } else {
        smsParams.put("receiptNumber", -1);
    }
    return smsParams;
}

From source file:com.gst.infrastructure.campaigns.sms.service.SmsCampaignDomainServiceImpl.java

License:Apache License

private HashMap<String, Object> processSavingsTransactionDataForSms(
        final SavingsAccountTransaction savingsAccountTransaction, Client client) {

    // {{savingsId}} {{id}} {{firstname}} {{middlename}} {{lastname}} {{FullName}} {{mobileNo}} {{savingsAccountId}} {{depositAmount}} {{balance}}

    //transactionDate
    HashMap<String, Object> smsParams = new HashMap<String, Object>();
    SavingsAccount savingsAccount = savingsAccountTransaction.getSavingsAccount();
    DateTimeFormatter dateFormatter = DateTimeFormat.forPattern("MMM:d:yyyy");
    smsParams.put("clientId", client.getId());
    smsParams.put("firstname", client.getFirstname());
    smsParams.put("middlename", client.getMiddlename());
    smsParams.put("lastname", client.getLastname());
    smsParams.put("FullName", client.getDisplayName());
    smsParams.put("mobileNo", client.mobileNo());
    smsParams.put("savingsId", savingsAccount.getId());
    smsParams.put("savingsAccountNo", savingsAccount.getAccountNumber());
    smsParams.put("withdrawAmount", savingsAccountTransaction.getAmount(savingsAccount.getCurrency()));
    smsParams.put("depositAmount", savingsAccountTransaction.getAmount(savingsAccount.getCurrency()));
    smsParams.put("balance", savingsAccount.getWithdrawableBalance());
    smsParams.put("officeId", client.getOffice().getId());
    smsParams.put("transactionDate",
            savingsAccountTransaction.getTransactionLocalDate().toString(dateFormatter));
    smsParams.put("savingsTransactionId", savingsAccountTransaction.getId());

    if (client.getStaff() != null) {
        smsParams.put("loanOfficerId", client.getStaff().getId());
    } else {/*from  ww  w  .j a  v a  2s.  c  om*/
        smsParams.put("loanOfficerId", -1);
    }

    if (savingsAccountTransaction.getPaymentDetail() != null) {
        smsParams.put("receiptNumber", savingsAccountTransaction.getPaymentDetail().getReceiptNumber());
    } else {
        smsParams.put("receiptNumber", -1);
    }
    return smsParams;
}

From source file:com.gst.infrastructure.campaigns.sms.service.SmsCampaignWritePlatformServiceJpaImpl.java

License:Apache License

private void updateTriggerDates(Long campaignId) {
    final SmsCampaign smsCampaign = this.smsCampaignRepository.findOne(campaignId);
    if (smsCampaign == null) {
        throw new SmsCampaignNotFound(campaignId);
    }//from ww  w  .j  a v a 2 s . c  o m
    LocalDateTime nextTriggerDate = smsCampaign.getNextTriggerDate();
    smsCampaign.setLastTriggerDate(nextTriggerDate.toDate());
    // calculate new trigger date and insert into next trigger date

    /**
     * next run time has to be in the future if not calculate a new future
     * date
     */
    LocalDate nextRuntime = CalendarUtils.getNextRecurringDate(smsCampaign.getRecurrence(),
            smsCampaign.getNextTriggerDate().toLocalDate(), nextTriggerDate.toLocalDate());
    if (nextRuntime.isBefore(DateUtils.getLocalDateOfTenant())) { // means
                                                                  // next
                                                                  // run
                                                                  // time is
                                                                  // in the
                                                                  // past
                                                                  // calculate
                                                                  // a new
                                                                  // future
                                                                  // date
        nextRuntime = CalendarUtils.getNextRecurringDate(smsCampaign.getRecurrence(),
                smsCampaign.getNextTriggerDate().toLocalDate(), DateUtils.getLocalDateOfTenant());
    }
    final LocalDateTime getTime = smsCampaign.getRecurrenceStartDateTime();
    final String dateString = nextRuntime.toString() + " " + getTime.getHourOfDay() + ":"
            + getTime.getMinuteOfHour() + ":" + getTime.getSecondOfMinute();
    final DateTimeFormatter simpleDateFormat = DateTimeFormat.forPattern("yyyy-MM-dd HH:mm:ss");
    final LocalDateTime newTriggerDateWithTime = LocalDateTime.parse(dateString, simpleDateFormat);

    smsCampaign.setNextTriggerDate(newTriggerDateWithTime.toDate());
    this.smsCampaignRepository.saveAndFlush(smsCampaign);
}

From source file:com.gst.infrastructure.campaigns.sms.service.SmsCampaignWritePlatformServiceJpaImpl.java

License:Apache License

@Transactional
@Override/* ww  w . ja  va  2 s  .co m*/
public CommandProcessingResult activateSmsCampaign(Long campaignId, JsonCommand command) {
    final AppUser currentUser = this.context.authenticatedUser();

    this.smsCampaignValidator.validateActivation(command.json());

    final SmsCampaign smsCampaign = this.smsCampaignRepository.findOne(campaignId);

    if (smsCampaign == null) {
        throw new SmsCampaignNotFound(campaignId);
    }

    final Locale locale = command.extractLocale();
    final DateTimeFormatter fmt = DateTimeFormat.forPattern(command.dateFormat()).withLocale(locale);
    final LocalDate activationDate = command.localDateValueOfParameterNamed("activationDate");

    smsCampaign.activate(currentUser, fmt, activationDate);

    this.smsCampaignRepository.saveAndFlush(smsCampaign);

    if (smsCampaign.isDirect()) {
        insertDirectCampaignIntoSmsOutboundTable(smsCampaign);
    } else if (smsCampaign.isSchedule()) {

        /**
         * if recurrence start date is in the future calculate next trigger
         * date if not use recurrence start date us next trigger date when
         * activating
         */
        LocalDate nextTriggerDate = null;
        if (smsCampaign.getRecurrenceStartDateTime().isBefore(tenantDateTime())) {
            nextTriggerDate = CalendarUtils.getNextRecurringDate(smsCampaign.getRecurrence(),
                    smsCampaign.getRecurrenceStartDate(), DateUtils.getLocalDateOfTenant());
        } else {
            nextTriggerDate = smsCampaign.getRecurrenceStartDate();
        }
        // to get time of tenant
        final LocalDateTime getTime = smsCampaign.getRecurrenceStartDateTime();

        final String dateString = nextTriggerDate.toString() + " " + getTime.getHourOfDay() + ":"
                + getTime.getMinuteOfHour() + ":" + getTime.getSecondOfMinute();
        final DateTimeFormatter simpleDateFormat = DateTimeFormat.forPattern("yyyy-MM-dd HH:mm:ss");
        final LocalDateTime nextTriggerDateWithTime = LocalDateTime.parse(dateString, simpleDateFormat);

        smsCampaign.setNextTriggerDate(nextTriggerDateWithTime.toDate());
        this.smsCampaignRepository.saveAndFlush(smsCampaign);
    }

    /*
     * if campaign is direct insert campaign message into sms outbound table
     * else if its a schedule create a job process for it
     */
    return new CommandProcessingResultBuilder() //
            .withCommandId(command.commandId()) //
            .withEntityId(smsCampaign.getId()) //
            .build();
}