use of org.joda.time.format.PeriodFormatterBuilder in project presto by prestodb.
the class DateTimeUtils method cretePeriodFormatter.
private static PeriodFormatter cretePeriodFormatter(IntervalField startField, IntervalField endField) {
if (endField == null) {
endField = startField;
}
List<PeriodParser> parsers = new ArrayList<>();
PeriodFormatterBuilder builder = new PeriodFormatterBuilder();
switch(startField) {
case YEAR:
builder.appendYears();
parsers.add(builder.toParser());
if (endField == IntervalField.YEAR) {
break;
}
builder.appendLiteral("-");
case MONTH:
builder.appendMonths();
parsers.add(builder.toParser());
if (endField != IntervalField.MONTH) {
throw new IllegalArgumentException("Invalid interval qualifier: " + startField + " to " + endField);
}
break;
case DAY:
builder.appendDays();
parsers.add(builder.toParser());
if (endField == IntervalField.DAY) {
break;
}
builder.appendLiteral(" ");
case HOUR:
builder.appendHours();
parsers.add(builder.toParser());
if (endField == IntervalField.HOUR) {
break;
}
builder.appendLiteral(":");
case MINUTE:
builder.appendMinutes();
parsers.add(builder.toParser());
if (endField == IntervalField.MINUTE) {
break;
}
builder.appendLiteral(":");
case SECOND:
builder.appendSecondsWithOptionalMillis();
parsers.add(builder.toParser());
break;
}
return new PeriodFormatter(builder.toPrinter(), new OrderedPeriodParser(parsers));
}
use of org.joda.time.format.PeriodFormatterBuilder in project beam by apache.
the class DurationUtils method parseDuration.
/**
* Parses a duration from a period formatted string. Values are accepted in the following formats:
*
* <p>Formats Ns - Seconds. Example: 5s<br>
* Nm - Minutes. Example: 13m<br>
* Nh - Hours. Example: 2h
*
* <pre>
* parseDuration(null) = NullPointerException()
* parseDuration("") = Duration.standardSeconds(0)
* parseDuration("2s") = Duration.standardSeconds(2)
* parseDuration("5m") = Duration.standardMinutes(5)
* parseDuration("3h") = Duration.standardHours(3)
* </pre>
*
* @param value The period value to parse.
* @return The {@link Duration} parsed from the supplied period string.
*/
public static Duration parseDuration(String value) {
checkNotNull(value, "The specified duration must be a non-null value!");
PeriodParser parser = new PeriodFormatterBuilder().appendSeconds().appendSuffix("s").appendMinutes().appendSuffix("m").appendHours().appendSuffix("h").toParser();
MutablePeriod period = new MutablePeriod();
parser.parseInto(period, value, 0, Locale.getDefault());
Duration duration = period.toDurationFrom(new DateTime(0));
checkArgument(duration.getMillis() > 0, "The window duration must be greater than 0!");
return duration;
}
use of org.joda.time.format.PeriodFormatterBuilder in project OpenClinica by OpenClinica.
the class RuleController method create.
@RequestMapping(value = "/studies/{study}/validateAndTestRule", method = RequestMethod.POST)
@ResponseBody
public org.openclinica.ns.rules_test.v31.RulesTest create(@RequestBody org.openclinica.ns.rules_test.v31.RulesTest ruleTest, Model model, HttpSession session, @PathVariable("study") String studyOid) throws Exception {
ResourceBundleProvider.updateLocale(new Locale("en_US"));
RulesPostImportContainer rpic = mapRulesToRulesPostImportContainer(ruleTest.getRules());
StudyDAO studyDao = new StudyDAO(dataSource);
StudyBean currentStudy = studyDao.findByOid(studyOid);
UserAccountBean userAccount = getUserAccount();
mayProceed(userAccount, currentStudy);
getRulePostImportContainerService(currentStudy, userAccount);
rpic = getRulePostImportContainerService(currentStudy, userAccount).validateRuleDefs(rpic);
rpic = getRulePostImportContainerService(currentStudy, userAccount).validateRuleSetDefs(rpic);
Response response = new Response();
response.setValid(Boolean.TRUE);
if (rpic.getInValidRuleDefs().size() > 0 || rpic.getInValidRuleSetDefs().size() > 0) {
response.setValid(Boolean.FALSE);
for (AuditableBeanWrapper<RuleBean> beanWrapper : rpic.getInValidRuleDefs()) {
for (String error : beanWrapper.getImportErrors()) {
org.openclinica.ns.response.v31.MessagesType messageType = new MessagesType();
messageType.setMessage(error);
response.getMessages().add(messageType);
}
}
for (AuditableBeanWrapper<RuleSetBean> beanWrapper : rpic.getInValidRuleSetDefs()) {
for (String error : beanWrapper.getImportErrors()) {
org.openclinica.ns.response.v31.MessagesType messageType = new MessagesType();
messageType.setMessage(error);
response.getMessages().add(messageType);
}
}
}
HashMap<String, String> p = new HashMap<String, String>();
for (ParameterType parameterType : ruleTest.getParameters()) {
p.put(parameterType.getKey(), parameterType.getValue());
}
ExpressionObjectWrapper eow = new ExpressionObjectWrapper(dataSource, currentStudy, rpic.getRuleDefs().get(0).getExpression(), rpic.getRuleSets().get(0));
ExpressionProcessor ep = ExpressionProcessorFactory.createExpressionProcessor(eow);
// Run expression with populated HashMap
DateTime start = new DateTime();
HashMap<String, String> result = ep.testEvaluateExpression(p);
DateTime end = new DateTime();
Duration dur = new Duration(start, end);
PeriodFormatter yearsAndMonths = new PeriodFormatterBuilder().printZeroAlways().appendSecondsWithMillis().appendSuffix(" second", " seconds").toFormatter();
yearsAndMonths.print(dur.toPeriod());
// Run expression with empty HashMap to check rule validity, because
// using illegal test values will cause invalidity
HashMap<String, String> k = new HashMap<String, String>();
HashMap<String, String> theResult = ep.testEvaluateExpression(k);
ruleTest.getParameters().clear();
for (Map.Entry<String, String> entry : result.entrySet()) {
ParameterType parameterType = new ParameterType();
parameterType.setKey(entry.getKey());
parameterType.setValue(entry.getValue());
ruleTest.getParameters().add(parameterType);
}
// if (theResult.get("ruleValidation").equals("rule_valid") && result.get("ruleValidation").equals("rule_invalid")) {
// result.put("ruleValidation", "rule_valid");
// result.put("ruleEvaluatesTo", resword.getString("test_rules_rule_fail") + " " +
// result.get("ruleValidationFailMessage"));
// result.remove("ruleValidationFailMessage");
// }
// Put on screen
// request.setAttribute("duration", yearsAndMonths.print(dur.toPeriod()));
RulesTestMessagesType messageType = new RulesTestMessagesType();
messageType.setKey("duration");
messageType.setValue(yearsAndMonths.print(dur.toPeriod()));
ruleTest.getRulesTestMessages().add(messageType);
return ruleTest;
}
use of org.joda.time.format.PeriodFormatterBuilder in project OpenClinica by OpenClinica.
the class TestRuleServlet method validate.
private HashMap<String, String> validate(Validator v) throws ParseException {
FormProcessor fp = new FormProcessor(request);
String targetString = fp.getString("target");
String ruleString = fp.getString("rule");
ruleString = ruleString.trim().replaceAll("(\n|\t|\r)", " ");
targetString = targetString.trim().replaceAll("(\n|\t|\r)", "");
HashMap<String, String> p = session.getAttribute("testValues") != null ? (HashMap<String, String>) session.getAttribute("testValues") : new HashMap<String, String>();
if (p != null) {
for (Map.Entry<String, String> entry : p.entrySet()) {
entry.setValue(fp.getString(entry.getKey()));
if (entry.getKey().startsWith(ExpressionService.STUDY_EVENT_OID_START_KEY) && (entry.getKey().endsWith(ExpressionService.STATUS) || entry.getKey().endsWith(ExpressionService.STARTDATE))) {
StudyEventDefinitionBean sed = getExpressionService().getStudyEventDefinitionFromExpressionForEvents(entry.getKey(), currentStudy);
if (entry.getKey().endsWith(ExpressionService.STATUS)) {
// TODO add the logic for status
} else if (entry.getKey().endsWith(ExpressionService.STARTDATE)) {
try {
v.addValidation(entry.getKey(), Validator.IS_A_DATE);
SimpleDateFormat sdf = new SimpleDateFormat(resformat.getString("date_format_string"));
SimpleDateFormat sdf2 = new SimpleDateFormat("yyyy-MM-dd");
if (!entry.getValue().isEmpty()) {
java.util.Date date = sdf2.parse(entry.getValue());
entry.setValue(sdf.format(date));
}
} catch (Exception e) {
logger.error(e.toString());
// TODO: handle exception
}
}
} else {
ItemBean item = getExpressionService().getItemBeanFromExpression(entry.getKey());
List<ItemFormMetadataBean> itemFormMetadataBeans = getItemFormMetadataDAO().findAllByItemId(item.getId());
ItemFormMetadataBean itemFormMetadataBean = itemFormMetadataBeans.size() > 0 ? itemFormMetadataBeans.get(0) : null;
if (!entry.getValue().equals("") && NullValue.getByName(entry.getValue()) == NullValue.INVALID) {
if (itemFormMetadataBean != null) {
if (itemFormMetadataBean.getResponseSet().getResponseType() == ResponseType.SELECTMULTI || itemFormMetadataBean.getResponseSet().getResponseType() == ResponseType.CHECKBOX) {
v.addValidation(entry.getKey(), Validator.IN_RESPONSE_SET_COMMA_SEPERATED, itemFormMetadataBean.getResponseSet());
}
if (itemFormMetadataBean.getResponseSet().getResponseType() == ResponseType.SELECT || itemFormMetadataBean.getResponseSet().getResponseType() == ResponseType.RADIO) {
v.addValidation(entry.getKey(), Validator.IN_RESPONSE_SET_SINGLE_VALUE, itemFormMetadataBean.getResponseSet());
} else {
itemDataTypeToValidatorId(entry.getKey(), item, v);
}
}
}
if (item.getItemDataTypeId() == 9) {
try {
SimpleDateFormat sdf = new SimpleDateFormat(resformat.getString("date_format_string"));
SimpleDateFormat sdf2 = new SimpleDateFormat("yyyy-MM-dd");
if (!entry.getValue().isEmpty()) {
java.util.Date date = sdf.parse(entry.getValue());
entry.setValue(sdf2.format(date));
}
} catch (Exception e) {
// TODO: handle exception
}
}
}
}
}
List<RuleActionBean> actions = session.getAttribute("testRuleActions") != null ? (List<RuleActionBean>) session.getAttribute("testRuleActions") : new ArrayList<RuleActionBean>();
if (actions != null) {
for (int i = 0; i < actions.size(); i++) {
actions.get(i).setExpressionEvaluatesTo(fp.getBoolean("actions" + i));
}
}
// Check Target if not valid report and return
try {
getExpressionService().ruleSetExpressionChecker(targetString);
} catch (OpenClinicaSystemException e) {
HashMap<String, String> result = new HashMap<String, String>();
MessageFormat mf = new MessageFormat("");
mf.applyPattern(respage.getString(e.getErrorCode()));
Object[] arguments = e.getErrorParams();
result.put("ruleValidation", "target_invalid");
result.put("ruleValidationFailMessage", e.getErrorCode() + " : " + mf.format(arguments));
result.put("ruleEvaluatesTo", "");
request.setAttribute("targetFail", "on");
return result;
}
// Auto update itemName & itemDefinition based on target
ItemBean item = getExpressionService().getItemBeanFromExpression(targetString);
StudyEventDefinitionBean sed = null;
if (item != null) {
request.setAttribute("itemName", item.getName());
request.setAttribute("itemDefinition", item.getDescription());
} else {
sed = getExpressionService().getStudyEventDefinitionFromExpressionForEvents(targetString, currentStudy);
if (sed != null) {
request.setAttribute("itemName", sed.getName());
request.setAttribute("itemDefinition", sed.getDescription());
}
}
RuleSetBean ruleSet = new RuleSetBean();
ExpressionBean target = new ExpressionBean();
target.setContext(Context.OC_RULES_V1);
target.setValue(targetString);
ruleSet.setTarget(target);
RuleSetBean persistentRuleSet = getRuleSetDao().findByExpressionAndStudy(ruleSet, currentStudy.getId());
if (persistentRuleSet != null) {
if (item != null)
request.setAttribute("ruleSetId", item.getId());
else
request.setAttribute("ruleSetId", sed.getId());
}
ExpressionBean rule = new ExpressionBean();
rule.setContext(Context.OC_RULES_V1);
rule.setValue(ruleString);
ExpressionObjectWrapper eow = new ExpressionObjectWrapper(sm.getDataSource(), currentStudy, rule, ruleSet);
ExpressionProcessor ep = ExpressionProcessorFactory.createExpressionProcessor(eow);
ep.setRespage(respage);
// Run expression with populated HashMap
DateTime start = new DateTime();
HashMap<String, String> result = ep.testEvaluateExpression(p);
DateTime end = new DateTime();
Duration dur = new Duration(start, end);
PeriodFormatter yearsAndMonths = new PeriodFormatterBuilder().printZeroAlways().appendSecondsWithMillis().appendSuffix(" second", " seconds").toFormatter();
yearsAndMonths.print(dur.toPeriod());
// Run expression with empty HashMap to check rule validity, because
// using illegal test values will cause invalidity
HashMap<String, String> k = new HashMap<String, String>();
HashMap<String, String> theResult = ep.testEvaluateExpression(k);
if (theResult.get("ruleValidation").equals("rule_valid") && result.get("ruleValidation").equals("rule_invalid")) {
result.put("ruleValidation", "rule_valid");
result.put("ruleEvaluatesTo", resword.getString("test_rules_rule_fail") + " " + result.get("ruleValidationFailMessage"));
result.remove("ruleValidationFailMessage");
}
// Put on screen
request.setAttribute("duration", yearsAndMonths.print(dur.toPeriod()));
return result;
}
use of org.joda.time.format.PeriodFormatterBuilder in project FlareBot by FlareBot.
the class UpdateCommand method onCommand.
@Override
public void onCommand(User sender, GuildWrapper guild, TextChannel channel, Message message, String[] args, Member member) {
if (PerGuildPermissions.isCreator(sender)) {
if (args.length == 0) {
update(false, channel);
} else if (args.length == 1) {
if (args[0].equalsIgnoreCase("force")) {
update(true, channel);
} else if (args[0].equalsIgnoreCase("no-active-channels")) {
channel.sendMessage("I will now update to the latest version when no channels are playing music!").queue();
if (Getters.getConnectedVoiceChannels() == 0) {
update(true, channel);
} else {
if (!queued.getAndSet(true)) {
FlareBot.NOVOICE_UPDATING.set(true);
} else
channel.sendMessage("There is already an update queued!").queue();
}
} else if (args[0].equalsIgnoreCase("schedule")) {
if (!queued.getAndSet(true)) {
FlareBot.instance().scheduleUpdate();
MessageUtils.sendSuccessMessage("Update scheduled for 12PM GMT!", channel);
} else {
MessageUtils.sendErrorMessage("There is already an update queued!", channel);
}
} else if (args[0].equalsIgnoreCase("cancel")) {
if (!queued.getAndSet(true)) {
MessageUtils.sendErrorMessage("There is no update queued!", channel);
} else {
if (Scheduler.cancelTask("Scheduled-Update")) {
MessageUtils.sendSuccessMessage("Cancelled Update!", channel);
} else {
MessageUtils.sendErrorMessage("Could not cancel update!", channel);
}
}
} else {
if (!queued.getAndSet(true)) {
Period p;
try {
PeriodFormatter formatter = new PeriodFormatterBuilder().appendDays().appendSuffix("d").appendHours().appendSuffix("h").appendMinutes().appendSuffix("m").appendSeconds().appendSuffix("s").toFormatter();
p = formatter.parsePeriod(args[0]);
new FlareBotTask("Scheduled-Update") {
@Override
public void run() {
update(true, channel);
}
}.delay(TimeUnit.SECONDS.toMillis(p.toStandardSeconds().getSeconds()));
} catch (IllegalArgumentException e) {
channel.sendMessage("That is an invalid time option!").queue();
return;
}
channel.sendMessage("I will now update to the latest version in " + p.toStandardSeconds().getSeconds() + " seconds.").queue();
} else {
channel.sendMessage("There is already an update queued!").queue();
}
}
}
}
}
Aggregations