Example usage for org.joda.time LocalDateTime parse

List of usage examples for org.joda.time LocalDateTime parse

Introduction

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

Prototype

public static LocalDateTime parse(String str, DateTimeFormatter formatter) 

Source Link

Document

Parses a LocalDateTime from the specified string using a formatter.

Usage

From source file:com.pinterest.secor.parser.AnalyticsMessageParser.java

License:Apache License

/**
 * Note that this depends on the {@link #jsonObject} state.
 *//*from ww  w.ja  v a  2 s. c  o  m*/
@Override
public String[] extractPartitions(Message message) {
    String result[] = { defaultType, defaultDate };
    String event_type = "";
    String analytics_type = "";

    /**
     * The idea is to store a directory structure that looks like
     * analytics-bucket/27/identify/2015/05/19/27/xxxxxxxxxxxx.json
     *
     *                  ^-- repeat the hour to spread the load among 24 shards
     *
     * analytics payloads may be of type: "track", event:"user_definded_name"
     *                           or type: "identify"
     *                           or type: "page"
     *                           or type: "screen"
     */

    if (jsonObject != null) {
        Object fieldType = jsonObject.get(mConfig.getMessageTypeName()); //type
        Object fieldValue = jsonObject.get(mConfig.getMessageTimestampName()); //timestamp

        if (fieldType != null) {
            analytics_type = fieldType.toString();
            if (analytics_type.equals("track")) {
                Object fieldSecondary = jsonObject.get("event");
                event_type = sanitizePath(fieldSecondary.toString());
            } else {
                event_type = analytics_type;
            }
        }

        if (fieldValue != null) {
            try {
                DateTimeFormatter inputFormatter = ISODateTimeFormat.dateOptionalTimeParser();
                LocalDateTime datetime = LocalDateTime.parse(fieldValue.toString(), inputFormatter);
                result[1] = datetime.toString(mConfig.getMessageTimestampBucketFormat());
            } catch (Exception e) {
                LOG.warn("date = " + fieldValue.toString() + " could not be parsed with ISODateTimeFormat."
                        + " Using date default=" + defaultDate);
            }
        }
    }

    // The hour bucket where the event happened
    String hour = result[1].split("/")[3];
    result[0] = hour + "/" + event_type;

    return result;
}

From source file:com.pinterest.secor.parser.DataLakeMessageParser.java

License:Apache License

@Override
public String[] extractPartitions(Message message) {
    JSONObject jsonObject = (JSONObject) JSONValue.parse(message.getPayload());
    String result[] = { defaultType, defaultDate };

    if (jsonObject != null) {
        Object fieldType = jsonObject.get(mConfig.getMessageTypeName()); //type
        Object fieldValue = jsonObject.get(mConfig.getMessageTimestampName()); //@timestamp
        if (fieldType != null) {
            result[0] = sanitizePath(fieldType.toString());
        }/* w  w w  . j  a v a  2 s . c  om*/
        if (fieldValue != null) {
            try {

                DateTimeFormatter inputFormatter = ISODateTimeFormat.dateOptionalTimeParser();
                LocalDateTime datetime = LocalDateTime.parse(fieldValue.toString(), inputFormatter);
                result[1] = datetime.toString(mConfig.getMessageTimestampBucketFormat());
            } catch (Exception e) {
                LOG.warn("date = " + fieldValue.toString() + " could not be parsed with ISODateTimeFormat."
                        + " Using date default=" + defaultDate);
            }
        }
    }

    return result;
}

From source file:com.sandata.lab.common.utils.data.adapter.CustomLocalDateTimeAdapter.java

License:Open Source License

@Override
public LocalDateTime deserialize(JsonElement json, Type type, JsonDeserializationContext context)
        throws JsonParseException {

    try {/*from   ww  w .  j a  v  a 2s  .  com*/
        LocalDateTime localDateTime = LocalDateTime.parse(json.getAsString(),
                DateTimeFormat.forPattern("yyyy-MM-dd HH:mm"));

        return localDateTime;
    } catch (Exception e) {
        e.printStackTrace();
    }

    return null;
}

From source file:nu.yona.app.utils.DateUtility.java

/**
 * Gets retrive week./*from  w w  w .  j  a  va  2  s  .  c  om*/
 *
 * @param week the week
 * @return the retrive week
 * @throws ParseException the parse exception
 */
public static String getRetriveWeek(String week) throws ParseException {
    String retriveWeek = "";
    DateTime time = new DateTime();
    int thisWeek = time.getWeekOfWeekyear();
    int pastWeek = thisWeek - 1;
    if (week.endsWith("" + thisWeek)) {
        retriveWeek = YonaApplication.getAppContext().getString(R.string.this_week);
    } else if (week.endsWith("" + pastWeek)) {
        retriveWeek = YonaApplication.getAppContext().getString(R.string.last_week);
    } else {
        Calendar calendar = Calendar.getInstance(Locale.getDefault());
        LocalDateTime localDateTime = LocalDateTime.parse(week, DateTimeFormat.forPattern("yyyy-'W'ww"));
        calendar.setTime(new Date(localDateTime.toDate().getTime()));
        calendar.add(Calendar.DAY_OF_WEEK, -1);
        Date startDate = calendar.getTime();
        calendar.add(Calendar.DAY_OF_MONTH, 6);
        Date endDate = calendar.getTime();
        SimpleDateFormat sdf = new SimpleDateFormat("dd MMMM");
        retriveWeek = sdf.format(startDate) + " - " + sdf.format(endDate);
    }
    return retriveWeek.toUpperCase();
}

From source file:nu.yona.app.utils.DateUtility.java

/**
 * Get Current weeks Days List. example:  Sun 21, Mon 22, Tue 23 , Wed 24 ,Thu 25, Fri 26
 *
 * @param currentYearWeek the current year week
 * @return week day// w w w  .j av  a2 s . c o m
 */
public static Map<String, String> getWeekDay(String currentYearWeek) {
    LinkedHashMap<String, String> listOfdates = new LinkedHashMap<>();
    try {
        Calendar calendar = Calendar.getInstance(Locale.getDefault());
        LocalDateTime localDateTime = LocalDateTime.parse(currentYearWeek,
                DateTimeFormat.forPattern("yyyy-'W'ww"));
        calendar.setTime(new Date(localDateTime.toDate().getTime()));
        calendar.add(Calendar.DAY_OF_WEEK, -1);
        for (int i = 0; i < M_NO_OF_DAY_PER_WEEK; i++) {
            listOfdates.put(DAY_FORMAT.format(calendar.getTime()), DAY_NO_FORMAT.format(calendar.getTime()));
            calendar.add(Calendar.DAY_OF_WEEK, 1);
        }
    } catch (Exception e) {
        AppUtils.reportException(DateUtility.class.getSimpleName(), e, Thread.currentThread());
    }

    return listOfdates;

}

From source file:org.apache.fineract.infrastructure.reportmailingjob.data.ReportMailingJobValidator.java

License:Apache License

/** 
 * validate the request to create a new report mailing job 
 * /*from  w  ww . j av  a 2s . c om*/
 * @param jsonCommand -- the JSON command object (instance of the JsonCommand class)
 * @return None
 **/
public void validateCreateRequest(final JsonCommand jsonCommand) {
    final String jsonString = jsonCommand.json();
    final JsonElement jsonElement = jsonCommand.parsedJson();

    if (StringUtils.isBlank(jsonString)) {
        throw new InvalidJsonException();
    }

    final Type typeToken = new TypeToken<Map<String, Object>>() {
    }.getType();
    this.fromJsonHelper.checkForUnsupportedParameters(typeToken, jsonString,
            ReportMailingJobConstants.CREATE_REQUEST_PARAMETERS);

    final List<ApiParameterError> dataValidationErrors = new ArrayList<>();
    final DataValidatorBuilder dataValidatorBuilder = new DataValidatorBuilder(dataValidationErrors)
            .resource(StringUtils.lowerCase(ReportMailingJobConstants.REPORT_MAILING_JOB_ENTITY_NAME));

    final String name = this.fromJsonHelper.extractStringNamed(ReportMailingJobConstants.NAME_PARAM_NAME,
            jsonElement);
    dataValidatorBuilder.reset().parameter(ReportMailingJobConstants.NAME_PARAM_NAME).value(name).notBlank()
            .notExceedingLengthOf(100);

    final String startDateTime = this.fromJsonHelper
            .extractStringNamed(ReportMailingJobConstants.START_DATE_TIME_PARAM_NAME, jsonElement);
    dataValidatorBuilder.reset().parameter(ReportMailingJobConstants.START_DATE_TIME_PARAM_NAME)
            .value(startDateTime).notBlank();

    final Integer stretchyReportId = this.fromJsonHelper.extractIntegerWithLocaleNamed(
            ReportMailingJobConstants.STRETCHY_REPORT_ID_PARAM_NAME, jsonElement);
    dataValidatorBuilder.reset().parameter(ReportMailingJobConstants.STRETCHY_REPORT_ID_PARAM_NAME)
            .value(stretchyReportId).notNull().integerGreaterThanZero();

    final String emailRecipients = this.fromJsonHelper
            .extractStringNamed(ReportMailingJobConstants.EMAIL_RECIPIENTS_PARAM_NAME, jsonElement);
    dataValidatorBuilder.reset().parameter(ReportMailingJobConstants.EMAIL_RECIPIENTS_PARAM_NAME)
            .value(emailRecipients).notBlank();

    final String emailSubject = this.fromJsonHelper
            .extractStringNamed(ReportMailingJobConstants.EMAIL_SUBJECT_PARAM_NAME, jsonElement);
    dataValidatorBuilder.reset().parameter(ReportMailingJobConstants.EMAIL_SUBJECT_PARAM_NAME)
            .value(emailSubject).notBlank().notExceedingLengthOf(100);

    final String emailMessage = this.fromJsonHelper
            .extractStringNamed(ReportMailingJobConstants.EMAIL_MESSAGE_PARAM_NAME, jsonElement);
    dataValidatorBuilder.reset().parameter(ReportMailingJobConstants.EMAIL_MESSAGE_PARAM_NAME)
            .value(emailMessage).notBlank();

    if (this.fromJsonHelper.parameterExists(ReportMailingJobConstants.IS_ACTIVE_PARAM_NAME, jsonElement)) {
        final Boolean isActive = this.fromJsonHelper
                .extractBooleanNamed(ReportMailingJobConstants.IS_ACTIVE_PARAM_NAME, jsonElement);
        dataValidatorBuilder.reset().parameter(ReportMailingJobConstants.IS_ACTIVE_PARAM_NAME).value(isActive)
                .notNull();
    }

    final Integer emailAttachmentFileFormatId = this.fromJsonHelper.extractIntegerSansLocaleNamed(
            ReportMailingJobConstants.EMAIL_ATTACHMENT_FILE_FORMAT_ID_PARAM_NAME, jsonElement);
    dataValidatorBuilder.reset().parameter(ReportMailingJobConstants.EMAIL_ATTACHMENT_FILE_FORMAT_ID_PARAM_NAME)
            .value(emailAttachmentFileFormatId).notNull();

    if (emailAttachmentFileFormatId != null) {
        dataValidatorBuilder.reset()
                .parameter(ReportMailingJobConstants.EMAIL_ATTACHMENT_FILE_FORMAT_ID_PARAM_NAME)
                .value(emailAttachmentFileFormatId)
                .isOneOfTheseValues(ReportMailingJobEmailAttachmentFileFormat.validValues());
    }

    final String dateFormat = jsonCommand.dateFormat();
    dataValidatorBuilder.reset().parameter(ReportMailingJobConstants.DATE_FORMAT_PARAM_NAME).value(dateFormat)
            .notBlank();

    if (StringUtils.isNotEmpty(dateFormat)) {

        try {
            final DateTimeFormatter dateTimeFormatter = DateTimeFormat.forPattern(dateFormat)
                    .withLocale(jsonCommand.extractLocale());

            // try to parse the date time string
            LocalDateTime.parse(startDateTime, dateTimeFormatter);
        }

        catch (IllegalArgumentException ex) {
            dataValidatorBuilder.reset().parameter(ReportMailingJobConstants.DATE_FORMAT_PARAM_NAME)
                    .value(dateFormat).failWithCode("invalid.date.format");
        }
    }

    throwExceptionIfValidationWarningsExist(dataValidationErrors);
}

From source file:org.apache.fineract.infrastructure.reportmailingjob.data.ReportMailingJobValidator.java

License:Apache License

/** 
 * validate the request to update a report mailing job 
 * /*  w w  w .j av  a  2  s.co m*/
 * @param jsonCommand -- the JSON command object (instance of the JsonCommand class)
 * @return None
 **/
public void validateUpdateRequest(final JsonCommand jsonCommand) {
    final String jsonString = jsonCommand.json();
    final JsonElement jsonElement = jsonCommand.parsedJson();

    if (StringUtils.isBlank(jsonString)) {
        throw new InvalidJsonException();
    }

    final Type typeToken = new TypeToken<Map<String, Object>>() {
    }.getType();
    this.fromJsonHelper.checkForUnsupportedParameters(typeToken, jsonString,
            ReportMailingJobConstants.UPDATE_REQUEST_PARAMETERS);

    final List<ApiParameterError> dataValidationErrors = new ArrayList<>();
    final DataValidatorBuilder dataValidatorBuilder = new DataValidatorBuilder(dataValidationErrors)
            .resource(StringUtils.lowerCase(ReportMailingJobConstants.REPORT_MAILING_JOB_ENTITY_NAME));

    if (this.fromJsonHelper.parameterExists(ReportMailingJobConstants.NAME_PARAM_NAME, jsonElement)) {
        final String name = this.fromJsonHelper.extractStringNamed(ReportMailingJobConstants.NAME_PARAM_NAME,
                jsonElement);
        dataValidatorBuilder.reset().parameter(ReportMailingJobConstants.NAME_PARAM_NAME).value(name).notBlank()
                .notExceedingLengthOf(100);
    }

    if (this.fromJsonHelper.parameterExists(ReportMailingJobConstants.STRETCHY_REPORT_ID_PARAM_NAME,
            jsonElement)) {
        final Integer stretchyReportId = this.fromJsonHelper.extractIntegerWithLocaleNamed(
                ReportMailingJobConstants.STRETCHY_REPORT_ID_PARAM_NAME, jsonElement);
        dataValidatorBuilder.reset().parameter(ReportMailingJobConstants.STRETCHY_REPORT_ID_PARAM_NAME)
                .value(stretchyReportId).notNull().integerGreaterThanZero();
    }

    if (this.fromJsonHelper.parameterExists(ReportMailingJobConstants.EMAIL_RECIPIENTS_PARAM_NAME,
            jsonElement)) {
        final String emailRecipients = this.fromJsonHelper
                .extractStringNamed(ReportMailingJobConstants.EMAIL_RECIPIENTS_PARAM_NAME, jsonElement);
        dataValidatorBuilder.reset().parameter(ReportMailingJobConstants.EMAIL_RECIPIENTS_PARAM_NAME)
                .value(emailRecipients).notBlank();
    }

    if (this.fromJsonHelper.parameterExists(ReportMailingJobConstants.EMAIL_SUBJECT_PARAM_NAME, jsonElement)) {
        final String emailSubject = this.fromJsonHelper
                .extractStringNamed(ReportMailingJobConstants.EMAIL_SUBJECT_PARAM_NAME, jsonElement);
        dataValidatorBuilder.reset().parameter(ReportMailingJobConstants.EMAIL_SUBJECT_PARAM_NAME)
                .value(emailSubject).notBlank().notExceedingLengthOf(100);
    }

    if (this.fromJsonHelper.parameterExists(ReportMailingJobConstants.EMAIL_MESSAGE_PARAM_NAME, jsonElement)) {
        final String emailMessage = this.fromJsonHelper
                .extractStringNamed(ReportMailingJobConstants.EMAIL_MESSAGE_PARAM_NAME, jsonElement);
        dataValidatorBuilder.reset().parameter(ReportMailingJobConstants.EMAIL_MESSAGE_PARAM_NAME)
                .value(emailMessage).notBlank();
    }

    if (this.fromJsonHelper.parameterExists(ReportMailingJobConstants.IS_ACTIVE_PARAM_NAME, jsonElement)) {
        final Boolean isActive = this.fromJsonHelper
                .extractBooleanNamed(ReportMailingJobConstants.IS_ACTIVE_PARAM_NAME, jsonElement);
        dataValidatorBuilder.reset().parameter(ReportMailingJobConstants.IS_ACTIVE_PARAM_NAME).value(isActive)
                .notNull();
    }

    if (this.fromJsonHelper.parameterExists(
            ReportMailingJobConstants.EMAIL_ATTACHMENT_FILE_FORMAT_ID_PARAM_NAME, jsonElement)) {
        final Integer emailAttachmentFileFormatId = this.fromJsonHelper.extractIntegerSansLocaleNamed(
                ReportMailingJobConstants.EMAIL_ATTACHMENT_FILE_FORMAT_ID_PARAM_NAME, jsonElement);
        dataValidatorBuilder.reset()
                .parameter(ReportMailingJobConstants.EMAIL_ATTACHMENT_FILE_FORMAT_ID_PARAM_NAME)
                .value(emailAttachmentFileFormatId).notNull();

        if (emailAttachmentFileFormatId != null) {
            dataValidatorBuilder.reset()
                    .parameter(ReportMailingJobConstants.EMAIL_ATTACHMENT_FILE_FORMAT_ID_PARAM_NAME)
                    .value(emailAttachmentFileFormatId)
                    .isOneOfTheseValues(ReportMailingJobEmailAttachmentFileFormat.validValues());
        }
    }

    if (this.fromJsonHelper.parameterExists(ReportMailingJobConstants.START_DATE_TIME_PARAM_NAME,
            jsonElement)) {
        final String dateFormat = jsonCommand.dateFormat();
        dataValidatorBuilder.reset().parameter(ReportMailingJobConstants.DATE_FORMAT_PARAM_NAME)
                .value(dateFormat).notBlank();

        final String startDateTime = this.fromJsonHelper
                .extractStringNamed(ReportMailingJobConstants.START_DATE_TIME_PARAM_NAME, jsonElement);
        dataValidatorBuilder.reset().parameter(ReportMailingJobConstants.START_DATE_TIME_PARAM_NAME)
                .value(startDateTime).notBlank();

        if (StringUtils.isNotEmpty(dateFormat)) {

            try {
                final DateTimeFormatter dateTimeFormatter = DateTimeFormat.forPattern(dateFormat)
                        .withLocale(jsonCommand.extractLocale());

                // try to parse the date time string
                LocalDateTime.parse(startDateTime, dateTimeFormatter);
            }

            catch (IllegalArgumentException ex) {
                dataValidatorBuilder.reset().parameter(ReportMailingJobConstants.DATE_FORMAT_PARAM_NAME)
                        .value(dateFormat).failWithCode("invalid.date.format");
            }
        }
    }

    throwExceptionIfValidationWarningsExist(dataValidationErrors);
}

From source file:org.apache.fineract.infrastructure.scheduledemail.data.EmailDataValidator.java

License:Apache License

/**
 * validate the request to create a new report mailing job
 *
 * @param jsonCommand -- the JSON command object (instance of the JsonCommand class)
 * @return None/* w  w  w  .  j  a va 2 s . c  o  m*/
 **/
public void validateCreateRequest(final JsonCommand jsonCommand) {
    final String jsonString = jsonCommand.json();
    final JsonElement jsonElement = jsonCommand.parsedJson();

    if (StringUtils.isBlank(jsonString)) {
        throw new InvalidJsonException();
    }

    final Type typeToken = new TypeToken<Map<String, Object>>() {
    }.getType();
    this.fromApiJsonHelper.checkForUnsupportedParameters(typeToken, jsonString,
            ScheduledEmailConstants.CREATE_REQUEST_PARAMETERS);

    final List<ApiParameterError> dataValidationErrors = new ArrayList<>();
    final DataValidatorBuilder dataValidatorBuilder = new DataValidatorBuilder(dataValidationErrors)
            .resource(StringUtils.lowerCase(ScheduledEmailConstants.SCHEDULED_EMAIL_ENTITY_NAME));

    final String name = this.fromApiJsonHelper.extractStringNamed(ScheduledEmailConstants.NAME_PARAM_NAME,
            jsonElement);
    dataValidatorBuilder.reset().parameter(ScheduledEmailConstants.NAME_PARAM_NAME).value(name).notBlank()
            .notExceedingLengthOf(100);

    final String startDateTime = this.fromApiJsonHelper
            .extractStringNamed(ScheduledEmailConstants.START_DATE_TIME_PARAM_NAME, jsonElement);
    dataValidatorBuilder.reset().parameter(ScheduledEmailConstants.START_DATE_TIME_PARAM_NAME)
            .value(startDateTime).notBlank();

    final Integer stretchyReportId = this.fromApiJsonHelper
            .extractIntegerWithLocaleNamed(ScheduledEmailConstants.STRETCHY_REPORT_ID_PARAM_NAME, jsonElement);
    dataValidatorBuilder.reset().parameter(ScheduledEmailConstants.STRETCHY_REPORT_ID_PARAM_NAME)
            .value(stretchyReportId).notNull().integerGreaterThanZero();

    final String emailRecipients = this.fromApiJsonHelper
            .extractStringNamed(ScheduledEmailConstants.EMAIL_RECIPIENTS_PARAM_NAME, jsonElement);
    dataValidatorBuilder.reset().parameter(ScheduledEmailConstants.EMAIL_RECIPIENTS_PARAM_NAME)
            .value(emailRecipients).notBlank();

    final String emailSubject = this.fromApiJsonHelper
            .extractStringNamed(ScheduledEmailConstants.EMAIL_SUBJECT_PARAM_NAME, jsonElement);
    dataValidatorBuilder.reset().parameter(ScheduledEmailConstants.EMAIL_SUBJECT_PARAM_NAME).value(emailSubject)
            .notBlank().notExceedingLengthOf(100);

    final String emailMessage = this.fromApiJsonHelper
            .extractStringNamed(ScheduledEmailConstants.EMAIL_MESSAGE_PARAM_NAME, jsonElement);
    dataValidatorBuilder.reset().parameter(ScheduledEmailConstants.EMAIL_MESSAGE_PARAM_NAME).value(emailMessage)
            .notBlank();

    if (this.fromApiJsonHelper.parameterExists(ScheduledEmailConstants.IS_ACTIVE_PARAM_NAME, jsonElement)) {
        final Boolean isActive = this.fromApiJsonHelper
                .extractBooleanNamed(ScheduledEmailConstants.IS_ACTIVE_PARAM_NAME, jsonElement);
        dataValidatorBuilder.reset().parameter(ScheduledEmailConstants.IS_ACTIVE_PARAM_NAME).value(isActive)
                .notNull();
    }

    final Integer emailAttachmentFileFormatId = this.fromApiJsonHelper.extractIntegerSansLocaleNamed(
            ScheduledEmailConstants.EMAIL_ATTACHMENT_FILE_FORMAT_ID_PARAM_NAME, jsonElement);
    dataValidatorBuilder.reset().parameter(ScheduledEmailConstants.EMAIL_ATTACHMENT_FILE_FORMAT_ID_PARAM_NAME)
            .value(emailAttachmentFileFormatId).notNull();

    if (emailAttachmentFileFormatId != null) {
        dataValidatorBuilder.reset()
                .parameter(ScheduledEmailConstants.EMAIL_ATTACHMENT_FILE_FORMAT_ID_PARAM_NAME)
                .value(emailAttachmentFileFormatId)
                .isOneOfTheseValues(ScheduledEmailAttachmentFileFormat.validValues());
    }

    final String dateFormat = jsonCommand.dateFormat();
    dataValidatorBuilder.reset().parameter(ScheduledEmailConstants.DATE_FORMAT_PARAM_NAME).value(dateFormat)
            .notBlank();

    if (StringUtils.isNotEmpty(dateFormat)) {

        try {
            final DateTimeFormatter dateTimeFormatter = DateTimeFormat.forPattern(dateFormat)
                    .withLocale(jsonCommand.extractLocale());

            // try to parse the date time string
            LocalDateTime.parse(startDateTime, dateTimeFormatter);
        }

        catch (IllegalArgumentException ex) {
            dataValidatorBuilder.reset().parameter(ScheduledEmailConstants.DATE_FORMAT_PARAM_NAME)
                    .value(dateFormat).failWithCode("invalid.date.format");
        }
    }

    throwExceptionIfValidationWarningsExist(dataValidationErrors);
}

From source file:org.apache.fineract.infrastructure.scheduledemail.data.EmailDataValidator.java

License:Apache License

/**
 * validate the request to update a report mailing job
 *
 * @param jsonCommand -- the JSON command object (instance of the JsonCommand class)
 * @return None/*from w  w w.  j  av a  2s  .  c om*/
 **/
public void validateUpdateRequest(final JsonCommand jsonCommand) {
    final String jsonString = jsonCommand.json();
    final JsonElement jsonElement = jsonCommand.parsedJson();

    if (StringUtils.isBlank(jsonString)) {
        throw new InvalidJsonException();
    }

    final Type typeToken = new TypeToken<Map<String, Object>>() {
    }.getType();
    this.fromApiJsonHelper.checkForUnsupportedParameters(typeToken, jsonString,
            ScheduledEmailConstants.UPDATE_REQUEST_PARAMETERS);

    final List<ApiParameterError> dataValidationErrors = new ArrayList<>();
    final DataValidatorBuilder dataValidatorBuilder = new DataValidatorBuilder(dataValidationErrors)
            .resource(StringUtils.lowerCase(ScheduledEmailConstants.SCHEDULED_EMAIL_ENTITY_NAME));

    if (this.fromApiJsonHelper.parameterExists(ScheduledEmailConstants.NAME_PARAM_NAME, jsonElement)) {
        final String name = this.fromApiJsonHelper.extractStringNamed(ScheduledEmailConstants.NAME_PARAM_NAME,
                jsonElement);
        dataValidatorBuilder.reset().parameter(ScheduledEmailConstants.NAME_PARAM_NAME).value(name).notBlank()
                .notExceedingLengthOf(100);
    }

    if (this.fromApiJsonHelper.parameterExists(ScheduledEmailConstants.STRETCHY_REPORT_ID_PARAM_NAME,
            jsonElement)) {
        final Integer stretchyReportId = this.fromApiJsonHelper.extractIntegerWithLocaleNamed(
                ScheduledEmailConstants.STRETCHY_REPORT_ID_PARAM_NAME, jsonElement);
        dataValidatorBuilder.reset().parameter(ScheduledEmailConstants.STRETCHY_REPORT_ID_PARAM_NAME)
                .value(stretchyReportId).notNull().integerGreaterThanZero();
    }

    if (this.fromApiJsonHelper.parameterExists(ScheduledEmailConstants.EMAIL_RECIPIENTS_PARAM_NAME,
            jsonElement)) {
        final String emailRecipients = this.fromApiJsonHelper
                .extractStringNamed(ScheduledEmailConstants.EMAIL_RECIPIENTS_PARAM_NAME, jsonElement);
        dataValidatorBuilder.reset().parameter(ScheduledEmailConstants.EMAIL_RECIPIENTS_PARAM_NAME)
                .value(emailRecipients).notBlank();
    }

    if (this.fromApiJsonHelper.parameterExists(ScheduledEmailConstants.EMAIL_SUBJECT_PARAM_NAME, jsonElement)) {
        final String emailSubject = this.fromApiJsonHelper
                .extractStringNamed(ScheduledEmailConstants.EMAIL_SUBJECT_PARAM_NAME, jsonElement);
        dataValidatorBuilder.reset().parameter(ScheduledEmailConstants.EMAIL_SUBJECT_PARAM_NAME)
                .value(emailSubject).notBlank().notExceedingLengthOf(100);
    }

    if (this.fromApiJsonHelper.parameterExists(ScheduledEmailConstants.EMAIL_MESSAGE_PARAM_NAME, jsonElement)) {
        final String emailMessage = this.fromApiJsonHelper
                .extractStringNamed(ScheduledEmailConstants.EMAIL_MESSAGE_PARAM_NAME, jsonElement);
        dataValidatorBuilder.reset().parameter(ScheduledEmailConstants.EMAIL_MESSAGE_PARAM_NAME)
                .value(emailMessage).notBlank();
    }

    if (this.fromApiJsonHelper.parameterExists(ScheduledEmailConstants.IS_ACTIVE_PARAM_NAME, jsonElement)) {
        final Boolean isActive = this.fromApiJsonHelper
                .extractBooleanNamed(ScheduledEmailConstants.IS_ACTIVE_PARAM_NAME, jsonElement);
        dataValidatorBuilder.reset().parameter(ScheduledEmailConstants.IS_ACTIVE_PARAM_NAME).value(isActive)
                .notNull();
    }

    if (this.fromApiJsonHelper
            .parameterExists(ScheduledEmailConstants.EMAIL_ATTACHMENT_FILE_FORMAT_ID_PARAM_NAME, jsonElement)) {
        final Integer emailAttachmentFileFormatId = this.fromApiJsonHelper.extractIntegerSansLocaleNamed(
                ScheduledEmailConstants.EMAIL_ATTACHMENT_FILE_FORMAT_ID_PARAM_NAME, jsonElement);
        dataValidatorBuilder.reset()
                .parameter(ScheduledEmailConstants.EMAIL_ATTACHMENT_FILE_FORMAT_ID_PARAM_NAME)
                .value(emailAttachmentFileFormatId).notNull();

        if (emailAttachmentFileFormatId != null) {
            dataValidatorBuilder.reset()
                    .parameter(ScheduledEmailConstants.EMAIL_ATTACHMENT_FILE_FORMAT_ID_PARAM_NAME)
                    .value(emailAttachmentFileFormatId)
                    .isOneOfTheseValues(ScheduledEmailAttachmentFileFormat.validValues());
        }
    }

    if (this.fromApiJsonHelper.parameterExists(ScheduledEmailConstants.START_DATE_TIME_PARAM_NAME,
            jsonElement)) {
        final String dateFormat = jsonCommand.dateFormat();
        dataValidatorBuilder.reset().parameter(ScheduledEmailConstants.DATE_FORMAT_PARAM_NAME).value(dateFormat)
                .notBlank();

        final String startDateTime = this.fromApiJsonHelper
                .extractStringNamed(ScheduledEmailConstants.START_DATE_TIME_PARAM_NAME, jsonElement);
        dataValidatorBuilder.reset().parameter(ScheduledEmailConstants.START_DATE_TIME_PARAM_NAME)
                .value(startDateTime).notBlank();

        if (StringUtils.isNotEmpty(dateFormat)) {

            try {
                final DateTimeFormatter dateTimeFormatter = DateTimeFormat.forPattern(dateFormat)
                        .withLocale(jsonCommand.extractLocale());

                // try to parse the date time string
                LocalDateTime.parse(startDateTime, dateTimeFormatter);
            }

            catch (IllegalArgumentException ex) {
                dataValidatorBuilder.reset().parameter(ScheduledEmailConstants.DATE_FORMAT_PARAM_NAME)
                        .value(dateFormat).failWithCode("invalid.date.format");
            }
        }
    }

    throwExceptionIfValidationWarningsExist(dataValidationErrors);
}

From source file:org.apache.fineract.infrastructure.scheduledemail.domain.EmailCampaign.java

License:Apache License

public static EmailCampaign instance(final AppUser submittedBy, final Report businessRuleId,
        final Report stretchyReport, final JsonCommand command) {

    final String campaignName = command.stringValueOfParameterNamed(EmailCampaignValidator.campaignName);
    final Long campaignType = command.longValueOfParameterNamed(EmailCampaignValidator.campaignType);

    final String paramValue = command.stringValueOfParameterNamed(EmailCampaignValidator.paramValue);
    final String emailSubject = command.stringValueOfParameterNamed(EmailCampaignValidator.emailSubject);
    final String emailMessage = command.stringValueOfParameterNamed(EmailCampaignValidator.emailMessage);
    final String stretchyReportParamMap = command
            .stringValueOfParameterNamed(ScheduledEmailConstants.STRETCHY_REPORT_PARAM_MAP_PARAM_NAME);
    final Integer emailAttachmentFileFormatId = command
            .integerValueOfParameterNamed(ScheduledEmailConstants.EMAIL_ATTACHMENT_FILE_FORMAT_ID_PARAM_NAME);
    final ScheduledEmailAttachmentFileFormat emailAttachmentFileFormat;
    if (emailAttachmentFileFormatId != null) {
        emailAttachmentFileFormat = ScheduledEmailAttachmentFileFormat.instance(emailAttachmentFileFormatId);
    } else {/*ww w. j  a va2 s.  c  om*/
        emailAttachmentFileFormat = ScheduledEmailAttachmentFileFormat.instance(2);
    }
    LocalDate submittedOnDate = new LocalDate();
    if (command.hasParameter(EmailCampaignValidator.submittedOnDateParamName)) {
        submittedOnDate = command
                .localDateValueOfParameterNamed(EmailCampaignValidator.submittedOnDateParamName);
    }

    final String recurrence = command.stringValueOfParameterNamed(EmailCampaignValidator.recurrenceParamName);
    final Locale locale = command.extractLocale();
    final DateTimeFormatter fmt = DateTimeFormat.forPattern(command.dateFormat()).withLocale(locale);

    LocalDateTime recurrenceStartDate = new LocalDateTime();
    if (EmailCampaignType.fromInt(campaignType.intValue()).isSchedule()) {
        if (command.hasParameter(EmailCampaignValidator.recurrenceStartDate)) {
            recurrenceStartDate = LocalDateTime.parse(
                    command.stringValueOfParameterNamed(EmailCampaignValidator.recurrenceStartDate), fmt);
        }
    } else {
        recurrenceStartDate = null;
    }

    return new EmailCampaign(campaignName, campaignType.intValue(), businessRuleId, paramValue, emailSubject,
            emailMessage, submittedOnDate, submittedBy, stretchyReport, stretchyReportParamMap,
            emailAttachmentFileFormat, recurrence, recurrenceStartDate);
}