List of usage examples for java.time LocalDate format
@Override
public String format(DateTimeFormatter formatter)
From source file:com.axelor.apps.account.service.MoveLineExportService.java
/** * Mthode ralisant l'export SI - Agresso des en-ttes pour les journaux de type achat * @param mlr// ww w . j a va2s . com * @param replay * @throws AxelorException * @throws IOException */ @SuppressWarnings("unchecked") @Transactional(rollbackOn = { AxelorException.class, Exception.class }) public void exportMoveLineTypeSelect1009FILE1(MoveLineReport moveLineReport, boolean replay) throws AxelorException, IOException { log.info("In export service 1009 FILE 1:"); Company company = moveLineReport.getCompany(); String dateQueryStr = String.format(" WHERE self.company = %s", company.getId()); JournalType journalType = moveLineReportService.getJournalType(moveLineReport); if (moveLineReport.getJournal() != null) { dateQueryStr += String.format(" AND self.journal = %s", moveLineReport.getJournal().getId()); } else { dateQueryStr += String.format(" AND self.journal.type = %s", journalType.getId()); } if (moveLineReport.getPeriod() != null) { dateQueryStr += String.format(" AND self.period = %s", moveLineReport.getPeriod().getId()); } if (replay) { dateQueryStr += String.format(" AND self.accountingOk = true AND self.moveLineReport = %s", moveLineReport.getId()); } else { dateQueryStr += " AND self.accountingOk = false "; } dateQueryStr += " AND self.ignoreInAccountingOk = false AND self.journal.notExportOk = false "; dateQueryStr += String.format(" AND self.statusSelect = %s ", MoveRepository.STATUS_VALIDATED); Query dateQuery = JPA.em().createQuery( "SELECT self.date from Move self" + dateQueryStr + "group by self.date order by self.date"); List<LocalDate> allDates = new ArrayList<LocalDate>(); allDates = dateQuery.getResultList(); log.debug("allDates : {}", allDates); List<String[]> allMoveData = new ArrayList<String[]>(); String companyCode = ""; String reference = ""; String moveQueryStr = ""; String moveLineQueryStr = ""; if (moveLineReport.getRef() != null) { reference = moveLineReport.getRef(); } if (company != null) { companyCode = company.getCode(); moveQueryStr += String.format(" AND self.company = %s", company.getId()); } if (moveLineReport.getPeriod() != null) { moveQueryStr += String.format(" AND self.period = %s", moveLineReport.getPeriod().getId()); } if (moveLineReport.getDateFrom() != null) { moveLineQueryStr += String.format(" AND self.date >= '%s'", moveLineReport.getDateFrom().toString()); } if (moveLineReport.getDateTo() != null) { moveLineQueryStr += String.format(" AND self.date <= '%s'", moveLineReport.getDateTo().toString()); } if (moveLineReport.getDate() != null) { moveLineQueryStr += String.format(" AND self.date <= '%s'", moveLineReport.getDate().toString()); } if (replay) { moveQueryStr += String.format(" AND self.accountingOk = true AND self.moveLineReport = %s", moveLineReport.getId()); } else { moveQueryStr += " AND self.accountingOk = false "; } moveQueryStr += String.format(" AND self.statusSelect = %s ", MoveRepository.STATUS_VALIDATED); LocalDate interfaceDate = moveLineReport.getDate(); for (LocalDate dt : allDates) { List<Journal> journalList = journalRepo.all() .filter("self.type = ?1 AND self.notExportOk = false", journalType).fetch(); if (moveLineReport.getJournal() != null) { journalList = new ArrayList<Journal>(); journalList.add(moveLineReport.getJournal()); } for (Journal journal : journalList) { List<Move> moveList = moveRepo.all().filter( "self.date = ?1 AND self.ignoreInAccountingOk = false AND self.journal.notExportOk = false AND self.journal = ?2" + moveQueryStr, dt, journal).fetch(); String journalCode = journal.getExportCode(); int moveListSize = moveList.size(); if (moveListSize > 0) { int i = 0; for (Move move : moveList) { List<MoveLine> moveLineList = moveLineRepo.all().filter( "self.account.reconcileOk = true AND self.credit != 0.00 AND self.move in ?1" + moveLineQueryStr, moveList).fetch(); if (moveLineList.size() > 0) { String exportNumber = this.getPurchaseExportNumber(company); String periodCode = move.getPeriod().getFromDate().format(MONTH_FORMAT); BigDecimal totalCredit = this.getSumCredit(moveLineList); String invoiceId = ""; String dueDate = ""; if (move.getInvoice() != null) { invoiceId = move.getInvoice().getInvoiceId(); dueDate = move.getInvoice().getDueDate().toString(); } MoveLine firstMoveLine = moveLineList.get(0); String items[] = new String[11]; items[0] = companyCode; items[1] = journalCode; items[2] = exportNumber; items[3] = interfaceDate.format(DATE_FORMAT); items[4] = invoiceId; items[5] = dueDate; items[6] = firstMoveLine.getAccount().getCode(); items[7] = totalCredit.toString(); items[8] = reference; items[9] = dt.format(DATE_FORMAT); items[10] = periodCode; allMoveData.add(items); this.updateMove(move, moveLineReport, interfaceDate, exportNumber); if (i % 10 == 0) { JPA.clear(); } if (i++ % 100 == 0) { log.debug("Process : {} / {}", i, moveListSize); } } } } } } String fileName = "entete" + todayTime.format(DATE_TIME_FORMAT) + "achats.dat"; String filePath = accountConfigService.getExportPath(accountConfigService.getAccountConfig(company)); new File(filePath).mkdirs(); log.debug("Full path to export : {}{}", filePath, fileName); CsvTool.csvWriter(filePath, fileName, '|', null, allMoveData); // Utilis pour le debuggage // CsvTool.csvWriter(filePath, fileName, '|', this.createHeaderForHeaderFile(mlr.getTypeSelect()), allMoveData); }
From source file:net.tradelib.apps.StrategyBacktest.java
public static void run(Strategy strategy) throws Exception { // Setup the logging System.setProperty("java.util.logging.SimpleFormatter.format", "%1$tY-%1$tm-%1$td %1$tH:%1$tM:%1$tS: %4$s: %5$s%n%6$s%n"); LogManager.getLogManager().reset(); Logger rootLogger = Logger.getLogger(""); if (Boolean.parseBoolean(BacktestCfg.instance().getProperty("file.log", "true"))) { FileHandler logHandler = new FileHandler("diag.out", 8 * 1024 * 1024, 2, true); logHandler.setFormatter(new SimpleFormatter()); logHandler.setLevel(Level.FINEST); rootLogger.addHandler(logHandler); }//from w w w .jav a 2s . c o m if (Boolean.parseBoolean(BacktestCfg.instance().getProperty("console.log", "true"))) { ConsoleHandler consoleHandler = new ConsoleHandler(); consoleHandler.setFormatter(new SimpleFormatter()); consoleHandler.setLevel(Level.INFO); rootLogger.addHandler(consoleHandler); } rootLogger.setLevel(Level.INFO); // Setup Hibernate // Configuration configuration = new Configuration(); // StandardServiceRegistryBuilder builder = new StandardServiceRegistryBuilder().applySettings(configuration.getProperties()); // SessionFactory factory = configuration.buildSessionFactory(builder.build()); Context context = new Context(); context.dbUrl = BacktestCfg.instance().getProperty("db.url"); HistoricalDataFeed hdf = new SQLDataFeed(context); hdf.configure(BacktestCfg.instance().getProperty("datafeed.config", "config/datafeed.properties")); context.historicalDataFeed = hdf; HistoricalReplay hr = new HistoricalReplay(context); context.broker = hr; strategy.initialize(context); strategy.cleanupDb(); long start = System.nanoTime(); strategy.start(); long elapsedTime = System.nanoTime() - start; System.out.println("backtest took " + String.format("%.2f secs", (double) elapsedTime / 1e9)); start = System.nanoTime(); strategy.updateEndEquity(); strategy.writeExecutionsAndTrades(); strategy.writeEquity(); elapsedTime = System.nanoTime() - start; System.out .println("writing to the database took " + String.format("%.2f secs", (double) elapsedTime / 1e9)); System.out.println(); // Write the strategy totals to the database strategy.totalTradeStats(); // Write the strategy report to the database and obtain the JSON // for writing it to the console. JsonObject report = strategy.writeStrategyReport(); JsonArray asa = report.getAsJsonArray("annual_stats"); String csvPath = BacktestCfg.instance().getProperty("positions.csv.prefix"); if (!Strings.isNullOrEmpty(csvPath)) { csvPath += "-" + strategy.getLastTimestamp().toLocalDate().format(DateTimeFormatter.BASIC_ISO_DATE) + ".csv"; } String ordersCsvPath = BacktestCfg.instance().getProperty("orders.csv.suffix"); if (!Strings.isNullOrEmpty(ordersCsvPath)) { ordersCsvPath = strategy.getLastTimestamp().toLocalDate().format(DateTimeFormatter.BASIC_ISO_DATE) + "-" + strategy.getName() + ordersCsvPath; } String actionsPath = BacktestCfg.instance().getProperty("actions.file.suffix"); if (!Strings.isNullOrEmpty(actionsPath)) { actionsPath = strategy.getLastTimestamp().toLocalDate().format(DateTimeFormatter.BASIC_ISO_DATE) + "-" + strategy.getName() + actionsPath; } // If emails are being send out String signalText = StrategyText.build(context.dbUrl, strategy.getName(), strategy.getLastTimestamp().toLocalDate(), " ", csvPath, '|'); System.out.println(signalText); System.out.println(); if (!Strings.isNullOrEmpty(ordersCsvPath)) { StrategyText.buildOrdersCsv(context.dbUrl, strategy.getName(), strategy.getLastTimestamp().toLocalDate(), ordersCsvPath); } File actionsFile = Strings.isNullOrEmpty(actionsPath) ? null : new File(actionsPath); if (actionsFile != null) { FileUtils.writeStringToFile(actionsFile, signalText + System.getProperty("line.separator") + System.getProperty("line.separator")); } String message = ""; if (asa.size() > 0) { // Sort the array TreeMap<Integer, Integer> map = new TreeMap<Integer, Integer>(); for (int ii = 0; ii < asa.size(); ++ii) { int year = asa.get(ii).getAsJsonObject().get("year").getAsInt(); map.put(year, ii); } for (int id : map.values()) { JsonObject jo = asa.get(id).getAsJsonObject(); String yearStr = String.valueOf(jo.get("year").getAsInt()); String pnlStr = String.format("$%,d", jo.get("pnl").getAsInt()); String pnlPctStr = String.format("%.2f%%", jo.get("pnl_pct").getAsDouble()); String endEqStr = String.format("$%,d", jo.get("end_equity").getAsInt()); String ddStr = String.format("$%,d", jo.get("maxdd").getAsInt()); String ddPctStr = String.format("%.2f%%", jo.get("maxdd_pct").getAsDouble()); String str = yearStr + " PnL: " + pnlStr + ", PnL Pct: " + pnlPctStr + ", End Equity: " + endEqStr + ", MaxDD: " + ddStr + ", Pct MaxDD: " + ddPctStr; message += str + "\n"; } String pnlStr = String.format("$%,d", report.get("pnl").getAsInt()); String pnlPctStr = String.format("%.2f%%", report.get("pnl_pct").getAsDouble()); String ddStr = String.format("$%,d", report.get("avgdd").getAsInt()); String ddPctStr = String.format("%.2f%%", report.get("avgdd_pct").getAsDouble()); String gainToPainStr = String.format("%.4f", report.get("gain_to_pain").getAsDouble()); String str = "\nAvg PnL: " + pnlStr + ", Pct Avg PnL: " + pnlPctStr + ", Avg DD: " + ddStr + ", Pct Avg DD: " + ddPctStr + ", Gain to Pain: " + gainToPainStr; message += str + "\n"; } else { message += "\n"; } // Global statistics JsonObject jo = report.getAsJsonObject("total_peak"); String dateStr = jo.get("date").getAsString(); int maxEndEq = jo.get("equity").getAsInt(); jo = report.getAsJsonObject("total_maxdd"); double cash = jo.get("cash").getAsDouble(); double pct = jo.get("pct").getAsDouble(); message += "\n" + "Total equity peak [" + dateStr + "]: " + String.format("$%,d", maxEndEq) + "\n" + String.format("Current Drawdown: $%,d [%.2f%%]", Math.round(cash), pct) + "\n"; if (report.has("latest_peak") && report.has("latest_maxdd")) { jo = report.getAsJsonObject("latest_peak"); LocalDate ld = LocalDate.parse(jo.get("date").getAsString(), DateTimeFormatter.ISO_DATE); maxEndEq = jo.get("equity").getAsInt(); jo = report.getAsJsonObject("latest_maxdd"); cash = jo.get("cash").getAsDouble(); pct = jo.get("pct").getAsDouble(); message += "\n" + Integer.toString(ld.getYear()) + " equity peak [" + ld.format(DateTimeFormatter.ISO_DATE) + "]: " + String.format("$%,d", maxEndEq) + "\n" + String.format("Current Drawdown: $%,d [%.2f%%]", Math.round(cash), pct) + "\n"; } message += "\n" + "Avg Trade PnL: " + String.format("$%,d", Math.round(report.get("avg_trade_pnl").getAsDouble())) + ", Max DD: " + String.format("$%,d", Math.round(report.get("maxdd").getAsDouble())) + ", Max DD Pct: " + String.format("%.2f%%", report.get("maxdd_pct").getAsDouble()) + ", Num Trades: " + Integer.toString(report.get("num_trades").getAsInt()); System.out.println(message); if (actionsFile != null) { FileUtils.writeStringToFile(actionsFile, message + System.getProperty("line.separator"), true); } if (Boolean.parseBoolean(BacktestCfg.instance().getProperty("email.enabled", "false"))) { Properties props = new Properties(); props.put("mail.smtp.auth", "true"); props.put("mail.smtp.starttls.enable", "true"); props.put("mail.smtp.host", "smtp.sendgrid.net"); props.put("mail.smtp.port", "587"); String user = BacktestCfg.instance().getProperty("email.user"); String pass = BacktestCfg.instance().getProperty("email.pass"); Session session = Session.getInstance(props, new javax.mail.Authenticator() { protected PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication(user, pass); } }); MimeMessage msg = new MimeMessage(session); try { msg.setFrom(new InternetAddress(BacktestCfg.instance().getProperty("email.from"))); msg.addRecipients(RecipientType.TO, BacktestCfg.instance().getProperty("email.recipients")); msg.setSubject(strategy.getName() + " Report [" + strategy.getLastTimestamp().format(DateTimeFormatter.ISO_LOCAL_DATE) + "]"); msg.setText("Positions & Signals\n" + signalText + "\n\nStatistics\n" + message); Transport.send(msg); } catch (Exception ee) { Logger.getLogger("").warning(ee.getMessage()); } } if (Boolean.parseBoolean(BacktestCfg.instance().getProperty("sftp.enabled", "false"))) { HashMap<String, String> fileMap = new HashMap<String, String>(); if (!Strings.isNullOrEmpty(actionsPath)) fileMap.put(actionsPath, actionsPath); if (!Strings.isNullOrEmpty(ordersCsvPath)) fileMap.put(ordersCsvPath, ordersCsvPath); String user = BacktestCfg.instance().getProperty("sftp.user"); String pass = BacktestCfg.instance().getProperty("sftp.pass"); String host = BacktestCfg.instance().getProperty("sftp.host"); SftpUploader sftp = new SftpUploader(host, user, pass); sftp.upload(fileMap); } }
From source file:objective.taskboard.followup.FollowUpDataRepositoryByFileTest.java
private Path createProjectZip(String projectKey, LocalDate date, String file) { try {//ww w. j a v a2 s.c o m Path pathProject = dataPath.resolve(projectKey); createDirectories(pathProject); Path pathInputJSON = Paths.get(getClass().getResource(file).toURI()); Path pathOutputJSON = pathProject.resolve(date.format(FILE_NAME_FORMATTER) + EXTENSION_JSON); copy(pathInputJSON, pathOutputJSON); Path zipFile = Paths.get(pathOutputJSON.toString() + EXTENSION_ZIP); zip(pathOutputJSON, zipFile); return pathProject; } catch (Exception e) { throw new RuntimeException(e); } }
From source file:org.apache.nifi.processors.solr.SolrUtils.java
private static void writeValue(final SolrInputDocument inputDocument, final Object value, final String fieldName, final DataType dataType, final List<String> fieldsToIndex) throws IOException { final DataType chosenDataType = dataType.getFieldType() == RecordFieldType.CHOICE ? DataTypeUtils.chooseDataType(value, (ChoiceDataType) dataType) : dataType;/*from w w w .jav a 2 s .c om*/ final Object coercedValue = DataTypeUtils.convertType(value, chosenDataType, fieldName); if (coercedValue == null) { return; } switch (chosenDataType.getFieldType()) { case DATE: { final String stringValue = DataTypeUtils.toString(coercedValue, () -> DataTypeUtils.getDateFormat(RecordFieldType.DATE.getDefaultFormat())); if (DataTypeUtils.isLongTypeCompatible(stringValue)) { LocalDate localDate = getLocalDateFromEpochTime(fieldName, coercedValue); addFieldToSolrDocument(inputDocument, fieldName, localDate.format(DateTimeFormatter.ISO_LOCAL_DATE_TIME) + 'Z', fieldsToIndex); } else { addFieldToSolrDocument(inputDocument, fieldName, LocalDate.parse(stringValue).format(DateTimeFormatter.ISO_LOCAL_DATE_TIME) + 'Z', fieldsToIndex); } break; } case TIMESTAMP: { final String stringValue = DataTypeUtils.toString(coercedValue, () -> DataTypeUtils.getDateFormat(RecordFieldType.TIMESTAMP.getDefaultFormat())); if (DataTypeUtils.isLongTypeCompatible(stringValue)) { LocalDateTime localDateTime = getLocalDateTimeFromEpochTime(fieldName, coercedValue); addFieldToSolrDocument(inputDocument, fieldName, localDateTime.format(DateTimeFormatter.ISO_LOCAL_DATE_TIME) + 'Z', fieldsToIndex); } else { addFieldToSolrDocument(inputDocument, fieldName, LocalDateTime.parse(stringValue).format(DateTimeFormatter.ISO_LOCAL_DATE_TIME) + 'Z', fieldsToIndex); } break; } case DOUBLE: addFieldToSolrDocument(inputDocument, fieldName, DataTypeUtils.toDouble(coercedValue, fieldName), fieldsToIndex); break; case FLOAT: addFieldToSolrDocument(inputDocument, fieldName, DataTypeUtils.toFloat(coercedValue, fieldName), fieldsToIndex); break; case LONG: addFieldToSolrDocument(inputDocument, fieldName, DataTypeUtils.toLong(coercedValue, fieldName), fieldsToIndex); break; case INT: case BYTE: case SHORT: addFieldToSolrDocument(inputDocument, fieldName, DataTypeUtils.toInteger(coercedValue, fieldName), fieldsToIndex); break; case CHAR: case STRING: addFieldToSolrDocument(inputDocument, fieldName, coercedValue.toString(), fieldsToIndex); break; case BIGINT: if (coercedValue instanceof Long) { addFieldToSolrDocument(inputDocument, fieldName, (Long) coercedValue, fieldsToIndex); } else { addFieldToSolrDocument(inputDocument, fieldName, (BigInteger) coercedValue, fieldsToIndex); } break; case BOOLEAN: final String stringValue = coercedValue.toString(); if ("true".equalsIgnoreCase(stringValue)) { addFieldToSolrDocument(inputDocument, fieldName, true, fieldsToIndex); } else if ("false".equalsIgnoreCase(stringValue)) { addFieldToSolrDocument(inputDocument, fieldName, false, fieldsToIndex); } else { addFieldToSolrDocument(inputDocument, fieldName, stringValue, fieldsToIndex); } break; case RECORD: { final Record record = (Record) coercedValue; writeRecord(record, inputDocument, fieldsToIndex, fieldName); break; } case ARRAY: default: if (coercedValue instanceof Object[]) { final Object[] values = (Object[]) coercedValue; for (Object element : values) { if (element instanceof Record) { writeRecord((Record) element, inputDocument, fieldsToIndex, fieldName); } else { addFieldToSolrDocument(inputDocument, fieldName, coercedValue.toString(), fieldsToIndex); } } } else { addFieldToSolrDocument(inputDocument, fieldName, coercedValue.toString(), fieldsToIndex); } break; } }
From source file:org.ojbc.adapters.analyticaldatastore.personid.IndexedPersonIdentifierStrategyTest.java
private Object makeDate(int year, int monthOfYear, int dayOfMonth) { LocalDate today = LocalDate.of(year, monthOfYear, dayOfMonth); DateTimeFormatter dtf = DateTimeFormatter.ofPattern("uuuu-MM-dd"); String dateTimeStamp = today.format(dtf); return dateTimeStamp; }
From source file:org.openlmis.converter.DirectDateTypeConverter.java
private String parseDate(String value) { LocalDate date = null; for (String format : DATE_FORMATS) { try {/* w ww .j a v a 2 s . c om*/ date = LocalDate.parse(value, DateTimeFormatter.ofPattern(format)); break; } catch (DateTimeParseException exp) { date = null; logger.debug("Can't parse date {} with format {}", value, format, exp); } } return null == date ? null : date.format(DateTimeFormatter.ISO_DATE); }
From source file:org.silverpeas.core.util.DateUtil.java
public static String getInputDate(LocalDate date, String language) { if (date == null) { return ""; }//from w w w . j a v a 2 s. c o m return date.format(getLocalDateInputFormat(language)); }
From source file:org.symphonyoss.simplebot.LunchBoxBot.java
private void processMessage(Message message) { username = message.getFromUserId().toString(); String messageString = message.getMessage(); if (StringUtils.isNotEmpty(messageString) && StringUtils.isNotBlank(messageString)) { MlMessageParser messageParser = new MlMessageParser(); try {//from w w w .j av a2s. c om messageParser.parseMessage(messageString); String text = messageParser.getText(); if (isFeedback == true) { processFeedback(text); isFeedback = false; } if (StringUtils.startsWithIgnoreCase(text, "/lunchbox")) { LunchBotCommand cmd = getLunchBotCommand(text); switch (cmd) { case MENU: HashMap lunch = parseLunchMenu(todayDateString); sendMessage("#######" + lunch.get("title") + "#######" + "\n\n" + lunch.get("body")); break; case FEEDBACK: isFeedback = true; break; case TOMORROW: LocalDate tomorrowDate = LocalDate.from(todayDate.toInstant().atZone(ZoneId.of("UTC"))) .plusDays(1); DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy,MM,dd"); String tomorrowString = tomorrowDate.format(formatter); lunch = parseLunchMenu(tomorrowString); sendMessage("#######" + lunch.get("title") + "#######" + "\n\n" + lunch.get("body")); break; case FORMAT: sendMessage( "- For feedback on individual items on the menu, <item number> -> <number of stars (out of 5)>\n- For feedback on lunch as a whole, <overall> -> <number of stars (out of 5)>, comments (optional)\n\n\nP.S: Please provide complete feedback in a single message with each section separated by a comma"); break; case OPTIONS: sendMessage( "For today's menu: '/lunchbox menu' OR '/lunchbox today's menu'\nFor tomorrow's menu: '/lunchbox tomorrow' OR '/lunchbox tomorrow's menu'\nFor tips on format for feedback: '/lunchbox format'\nFor feedback: '/lunchbox feedback' <hit enter and then provide feedback all in one message>\nFor options: '/lunchbox help'\n\n\nP.S: All commands should be typed without quotes"); break; case UNKNOWN: break; } } } catch (Exception e) { e.printStackTrace(); } } }
From source file:rapture.dp.invocable.calendar.steps.CalendarLookupStep.java
@Override public String invoke(CallingContext ctx) { DecisionApi decision = Kernel.getDecision(); try {//from w w w. j av a 2 s. c o m decision.setContextLiteral(ctx, getWorkerURI(), "STEPNAME", getStepName()); String dateStr = StringUtils.stripToNull(decision.getContextValue(ctx, getWorkerURI(), "DATE")); String calendar = StringUtils.stripToNull(decision.getContextValue(ctx, getWorkerURI(), "CALENDAR")); String translator = StringUtils .stripToNull(decision.getContextValue(ctx, getWorkerURI(), "TRANSLATOR")); if (translator == null) translator = StringUtils .stripToNull(decision.getContextValue(ctx, getWorkerURI(), "DEFAULT_TRANSLATOR")); LocalDate date = (dateStr == null) ? LocalDate.now() : LocalDate.parse(dateStr); // Translate the date to a name - eg Good Friday, Yom Kippur, Thanksgiving // Expected format is a map of dates (with or without years) to names or lists of names // Example: // { // "31Dec" : ["New Tear's Eve", "Hogmanay"] , // "05Sep2016" : "Labor Day", // "04Sep2017" : "Labor Day" // "2015-01-01" : "New Year's Day" // } Map<String, Object> calendarTable = new HashMap<>(); if (calendar != null) { String calendarJson = StringUtils.stripToNull(Kernel.getDoc().getDoc(ctx, calendar)); if (calendarJson != null) { calendarTable = JacksonUtil.getMapFromJson(calendarJson); } } // Translate the date to a name - eg Good Friday, Yom Kippur, Thanksgiving Map<String, Object> translationTable = new HashMap<>(); if (translator != null) { String translationJson = StringUtils.stripToNull(Kernel.getDoc().getDoc(ctx, translator)); if (translationJson != null) { translationTable = JacksonUtil.getMapFromJson(translationJson); } } List<String> lookup = new ArrayList<>(); String languageTag = StringUtils.stripToNull(decision.getContextValue(ctx, getWorkerURI(), "LOCALE")); Locale locale = (languageTag == null) ? Locale.getDefault() : Locale.forLanguageTag(languageTag); for (DateTimeFormatter formatter : ImmutableList.of(DateTimeFormatter.ISO_LOCAL_DATE, DateTimeFormatter.ofPattern("ddMMMuuuu", locale), DateTimeFormatter.ofPattern("ddMMM", locale), DateTimeFormatter.ofPattern("MMMdduuuu", locale), DateTimeFormatter.ofPattern("MMMdd", locale), DateTimeFormatter.ofPattern("uuuuMMMdd", locale))) { String formattedDate = date.format(formatter); Object transList = translationTable.get(formattedDate); if (transList != null) { if (transList instanceof Iterable) { for (Object o : (Iterable) transList) { lookup.add(o.toString()); } } else lookup.add(transList.toString()); } lookup.add(formattedDate); } lookup.add(DayOfWeek.from(date).getDisplayName(TextStyle.FULL, locale)); decision.setContextLiteral(ctx, getWorkerURI(), "DATE_TRANSLATIONS", JacksonUtil.jsonFromObject(lookup)); // Calendar table defines the priority. getMapFromJson returns a LinkedHashMap so order is preserved. for (Entry<String, Object> calEntry : calendarTable.entrySet()) { if (lookup.contains(calEntry.getKey())) { decision.setContextLiteral(ctx, getWorkerURI(), "CALENDAR_LOOKUP_ENTRY", JacksonUtil.jsonFromObject(calEntry)); decision.writeWorkflowAuditEntry(ctx, getWorkerURI(), calEntry.getKey() + " matched as " + calEntry.getValue().toString(), false); return calEntry.getValue().toString(); } } decision.writeWorkflowAuditEntry(ctx, getWorkerURI(), getStepName() + ": No matches for " + DateTimeFormatter.ISO_LOCAL_DATE.format(date) + " found in calendar", false); return getNextTransition(); } catch (Exception e) { decision.setContextLiteral(ctx, getWorkerURI(), getStepName(), "Unable to access the calendar : " + e.getLocalizedMessage()); decision.setContextLiteral(ctx, getWorkerURI(), getStepName() + "Error", ExceptionToString.summary(e)); decision.writeWorkflowAuditEntry(ctx, getWorkerURI(), "Problem in " + getStepName() + ": " + ExceptionToString.getRootCause(e).getLocalizedMessage(), true); return getErrorTransition(); } }