Example usage for org.joda.time.format DateTimeFormatter print

List of usage examples for org.joda.time.format DateTimeFormatter print

Introduction

In this page you can find the example usage for org.joda.time.format DateTimeFormatter print.

Prototype

public String print(ReadablePartial partial) 

Source Link

Document

Prints a ReadablePartial to a new String.

Usage

From source file:com.github.flawedbliss.dicebotr4.MySqlManager.java

License:Open Source License

/**
 * // w w w  .j  ava  2 s .co m
 * @param code The primary key (code) where the used column used should be updated
 * @param uid Unique Id of the user who used the code
 * @throws DicebotException 
 */
public void setCodeUsed(String code, String uid) throws DicebotException {
    String sql = "UPDATE premium SET used=1, used_by=?, date_used=? WHERE code=?";
    DateTimeFormatter dtf = DateTimeFormat.forPattern("yyyy-MM-dd HH:mm:ss");
    try (Connection connect = cp.getConnection();
            PreparedStatement statement = connect.prepareStatement(sql);) {
        statement.setString(0, uid);
        statement.setString(1, dtf.print(new DateTime(new Date())));
        statement.setString(2, code);
        statement.executeUpdate();
    } catch (SQLException ex) {
        if (ex.getMessage() != null) {
            throw new DicebotException("Unable to set code used for code " + code + "\n" + ex.getMessage());
        } else {
            throw new DicebotException("Unable to set code used for " + code + ". No further information.");
        }
    }
}

From source file:com.github.pockethub.android.util.TimeUtils.java

License:Apache License

public static String dateToString(Date value) {
    DateTimeFormatter formats = DateTimeFormat.forPattern("yyyy-MM-dd'T'HH:mm:ss'Z'");
    return formats.print(value.getTime());
}

From source file:com.github.rinde.datgen.pdptw.DatasetGenerator.java

License:Apache License

static void writePropertiesFile(Scenario scen, GeneratorSettings settings, double actualDyn, long seed,
        String fileName) {// w w  w .  j  ava2s. co  m
    final DateTimeFormatter formatter = ISODateTimeFormat.dateHourMinuteSecondMillis();

    final VanLon15ProblemClass pc = (VanLon15ProblemClass) scen.getProblemClass();
    final ImmutableMap.Builder<String, Object> properties = ImmutableMap.<String, Object>builder()
            .put("problem_class", pc.getId()).put("id", scen.getProblemInstanceId())
            .put("dynamism_bin", pc.getDynamism()).put("dynamism_actual", actualDyn)
            .put("urgency", pc.getUrgency()).put("scale", pc.getScale()).put("random_seed", seed)
            .put("creation_date", formatter.print(System.currentTimeMillis()))
            .put("creator", System.getProperty("user.name")).put("day_length", settings.getDayLength())
            .put("office_opening_hours", settings.getOfficeHours());

    properties.putAll(settings.getProperties());

    final ImmutableMultiset<Class<?>> eventTypes = Metrics.getEventTypeCounts(scen);
    for (final Multiset.Entry<Class<?>> en : eventTypes.entrySet()) {
        properties.put(en.getElement().getSimpleName(), en.getCount());
    }

    try {
        Files.write(Paths.get(fileName + ".properties"),
                asList(Joiner.on("\n").withKeyValueSeparator(" = ").join(properties.build())), Charsets.UTF_8);
    } catch (final IOException e) {
        throw new IllegalStateException(e);
    }
}

From source file:com.github.rinde.dynurg.Generator.java

License:Apache License

static void writePropertiesFile(Scenario scen, StatisticalSummary urgency, double dynamism,
        String problemClassId, String instanceId, GeneratorSettings settings, String fileName) {
    final DateTimeFormatter formatter = ISODateTimeFormat.dateHourMinuteSecondMillis();

    final ImmutableMap.Builder<String, Object> properties = ImmutableMap.<String, Object>builder()
            .put("problem_class", problemClassId).put("id", instanceId).put("dynamism", dynamism)
            .put("urgency_mean", urgency.getMean()).put("urgency_sd", urgency.getStandardDeviation())
            .put("creation_date", formatter.print(System.currentTimeMillis()))
            .put("creator", System.getProperty("user.name")).put("day_length", settings.dayLength)
            .put("office_opening_hours", settings.officeHours);

    properties.putAll(settings.properties);

    final ImmutableMultiset<Enum<?>> eventTypes = Metrics.getEventTypeCounts(scen);
    for (final Multiset.Entry<Enum<?>> en : eventTypes.entrySet()) {
        properties.put(en.getElement().name(), en.getCount());
    }//  www.  j a  v  a  2s.  c o m

    try {
        Files.write(Joiner.on("\n").withKeyValueSeparator(" = ").join(properties.build()),
                new File(fileName + ".properties"), Charsets.UTF_8);
    } catch (final IOException e) {
        throw new IllegalStateException(e);
    }
}

From source file:com.gooddata.util.ResultSetHelperService.java

License:Apache License

private String handleDate(ResultSet rs, int columnIndex) throws SQLException {
    java.sql.Date date = rs.getDate(columnIndex);
    String value = null;/* www.j  a va  2 s .  com*/
    if (date != null) {
        DateTimeFormatter dateFormat = DateTimeFormat.forPattern("dd-MMM-yyyy");
        value = dateFormat.print(new DateTime(date));
    }
    return value;
}

From source file:com.gooddata.util.ResultSetHelperService.java

License:Apache License

private String handleTimestamp(Timestamp timestamp) {
    DateTimeFormatter timeFormat = DateTimeFormat.forPattern("dd-MMM-yyyy HH:mm:ss");
    return timestamp == null ? null : timeFormat.print(new DateTime(timestamp));
}

From source file:com.goodhuddle.huddle.web.site.handlebars.helper.DateTimeHelper.java

License:Open Source License

private String format(ReadableInstant value, Options options, DateTimeFormatter defaultFormat) {
    DateTimeFormatter formatter = defaultFormat;
    String pattern = options.param(0, null);
    if (pattern != null) {
        formatter = DateTimeFormat.forPattern(pattern);
    }//  ww  w  . j  av  a  2 s  . c om
    return formatter.print(value);
}

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) {/*ww  w  . j  a  va  2 s  .  c om*/
        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.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 a va2s  .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.portfolio.calendar.service.CalendarWritePlatformServiceJpaRepositoryImpl.java

License:Apache License

@Override
public CommandProcessingResult createCalendar(final JsonCommand command) {

    this.fromApiJsonDeserializer.validateForCreate(command.json());
    Long entityId = null;/* ww w  . j  av a 2  s .co  m*/
    CalendarEntityType entityType = CalendarEntityType.INVALID;
    LocalDate entityActivationDate = null;
    Group centerOrGroup = null;
    if (command.getGroupId() != null) {
        centerOrGroup = this.groupRepository.findOneWithNotFoundDetection(command.getGroupId());
        entityActivationDate = centerOrGroup.getActivationLocalDate();
        entityType = centerOrGroup.isCenter() ? CalendarEntityType.CENTERS : CalendarEntityType.GROUPS;
        entityId = command.getGroupId();
    } else if (command.getLoanId() != null) {
        final Loan loan = this.loanRepositoryWrapper.findOneWithNotFoundDetection(command.getLoanId(), true);
        entityActivationDate = (loan.getApprovedOnDate() == null) ? loan.getSubmittedOnDate()
                : loan.getApprovedOnDate();
        entityType = CalendarEntityType.LOANS;
        entityId = command.getLoanId();
    } else if (command.getClientId() != null) {
        final Client client = this.clientRepository.findOneWithNotFoundDetection(command.getClientId());
        entityActivationDate = client.getActivationLocalDate();
        entityType = CalendarEntityType.CLIENTS;
        entityId = command.getClientId();
    }

    final Integer entityTypeId = entityType.getValue();
    final Calendar newCalendar = Calendar.fromJson(command);

    final List<ApiParameterError> dataValidationErrors = new ArrayList<>();
    final DataValidatorBuilder baseDataValidator = new DataValidatorBuilder(dataValidationErrors)
            .resource("calendar");
    if (entityActivationDate == null || newCalendar.getStartDateLocalDate().isBefore(entityActivationDate)) {
        final DateTimeFormatter formatter = DateTimeFormat.forPattern(command.dateFormat())
                .withLocale(command.extractLocale());
        String dateAsString = "";
        if (entityActivationDate != null)
            dateAsString = formatter.print(entityActivationDate);

        final String errorMessage = "cannot.be.before." + entityType.name().toLowerCase() + ".activation.date";
        baseDataValidator.reset().parameter(CALENDAR_SUPPORTED_PARAMETERS.START_DATE.getValue())
                .value(dateAsString).failWithCodeNoParameterAddedToErrorCode(errorMessage);
    }

    if (centerOrGroup != null) {
        Long centerOrGroupId = centerOrGroup.getId();
        Integer centerOrGroupEntityTypeId = entityType.getValue();

        final Group parent = centerOrGroup.getParent();
        if (parent != null) {
            centerOrGroupId = parent.getId();
            centerOrGroupEntityTypeId = CalendarEntityType.CENTERS.getValue();
        }

        final CalendarInstance collectionCalendarInstance = this.calendarInstanceRepository
                .findByEntityIdAndEntityTypeIdAndCalendarTypeId(centerOrGroupId, centerOrGroupEntityTypeId,
                        CalendarType.COLLECTION.getValue());
        if (collectionCalendarInstance != null) {
            final String errorMessage = "multiple.collection.calendar.not.supported";
            baseDataValidator.reset().failWithCodeNoParameterAddedToErrorCode(errorMessage);
        }
    }

    if (!dataValidationErrors.isEmpty()) {
        throw new PlatformApiDataValidationException(dataValidationErrors);
    }

    this.calendarRepository.save(newCalendar);

    final CalendarInstance newCalendarInstance = CalendarInstance.from(newCalendar, entityId, entityTypeId);
    this.calendarInstanceRepository.save(newCalendarInstance);

    return new CommandProcessingResultBuilder() //
            .withCommandId(command.commandId()) //
            .withEntityId(newCalendar.getId()) //
            .withClientId(command.getClientId()) //
            .withGroupId(command.getGroupId()) //
            .withLoanId(command.getLoanId()) //
            .build();

}