List of usage examples for java.util Locale forLanguageTag
public static Locale forLanguageTag(String languageTag)
From source file:org.diorite.impl.command.defaults.DevCmd.java
public DevCmd() { // TODO: remove super("dev", Pattern.compile("(dev)(:(?<action>([a-z0-9_]*))|)", Pattern.CASE_INSENSITIVE), CommandPriority.LOW);//from w ww. j a v a 2 s . c om this.setDescription("Debug"); this.setCommandExecutor((sender, command, label, matchedPattern, args) -> { final String action = matchedPattern.group("action"); final IPlayer p = (IPlayer) sender; if (action == null) { p.getNetworkManager() .sendPacket(new PacketPlayClientboundBlockChange( args.readCoordinates(0, p.getLocation().toBlockLocation()), args.asInt(3), args.asInt(4).byteValue())); return; } final IServerManager serverManager = DioriteCore.getInstance().getServerManager(); final PermissionsManager mag = serverManager.getPermissionsManager(); switch (action.toLowerCase()) { case "metadata": { final IEntity entity = p.getNearbyEntities(3, 3, 3, LookupShape.RECTANGLE).iterator().next(); final int index = args.asInt(1); switch (args.asString(0)) { case "flag": { final String s = args.asString(2); for (final String flag : s.split(",")) { entity.getMetadata().setBoolean(index, DioriteMathUtils.asInt(flag), args.asBoolean(3)); } break; } case "int": { entity.getMetadata().setInt(index, args.asInt(2)); break; } case "bool": { entity.getMetadata().setBoolean(index, args.asBoolean(2)); break; } case "float": { entity.getMetadata().setFloat(index, args.asFloat(2)); break; } case "loc": { entity.getMetadata().setBlockLocation(index, args.readCoordinates(2, p.getLocation().toBlockLocation())); break; } } break; } case "mobname": { final IEntity entity = p.getNearbyEntities(3, 3, 3, LookupShape.RECTANGLE).iterator().next(); System.out.println(args.asText()); entity.setCustomName( ChatColor.translateAlternateColorCodesInString(args.asText().replace("%n", "\n"))); entity.setCustomNameVisible(true); break; } case "mob": { final IEntityFactory entityFactory = serverManager.getEntityFactory(); if (args.asString(0).equalsIgnoreCase("creeper")) { final ICreeper creeper = entityFactory.createEntity(ICreeper.class, p.getLocation()); creeper.getMetadata().setBoolean(ICreeper.META_KEY_CREEPER_POWERED, true); p.getWorld().addEntity(creeper); } else if (args.asString(0).equalsIgnoreCase("chickenArmy")) { DioriteCore.getInstance().sync(() -> { for (double x = p.getX() - 10; x <= (p.getX() + 14); x += 1.5) { for (double y = p.getY() - 6; y <= (p.getY() + 5); y += 1.5) { for (double z = p.getZ() - 3; z <= (p.getZ() + 3); z += 1.5) { final IChicken entity = entityFactory.createEntity(IChicken.class, new Location(x, y, z, p.getWorld())); p.getWorld().addEntity(entity); } } } }, p); } else if (args.asString(0).equalsIgnoreCase("zombie")) { final IZombie zombie = entityFactory.createEntity(IZombie.class, p.getLocation()); zombie.setCustomName("Custom name!"); zombie.setCustomNameVisible(true); // zombie.getMetadata().setInt(ILivingEntity.META_KEY_ARROWS_IN_BODY, args.has(1) ? args.asInt(1, 0) : 0); zombie.getMetadata().setInt(ILivingEntity.META_KEY_LIVING_POTION_EFFECT_COLOR, args.has(1) ? Integer.parseInt(args.asString(1), 16) : 0); if (args.has(3)) { String s = args.asString(2); for (final String flag : s.split(",")) { zombie.getMetadata().setBoolean(IEntity.META_KEY_ENTITY_BASIC_FLAGS, DioriteMathUtils.asInt(flag), args.asBoolean(3)); } } zombie.setAir(-5); zombie.setSilent(true); p.getWorld().addEntity(zombie); } else if (args.asString(0).equalsIgnoreCase("area")) { final IAreaEffectCloud entity = entityFactory.createEntity(IAreaEffectCloud.class, p.getLocation()); entity.setColor(Color.AQUA); entity.setRadius(30); p.getWorld().addEntity(entity); } else if (args.asString(0).equalsIgnoreCase("area2")) { final IAreaEffectCloud entity = entityFactory.createEntity(IAreaEffectCloud.class, p.getLocation()); entity.getMetadata().setInt(IAreaEffectCloud.META_KEY_AREA_EFFECT_CLOUD_COLOR, Integer.parseInt(args.asString(3), 16)); entity.getMetadata().setFloat(IAreaEffectCloud.META_KEY_AREA_EFFECT_CLOUD_RADIUS, args.asFloat(2)); entity.getMetadata().setBoolean(IAreaEffectCloud.META_KEY_AREA_EFFECT_CLOUD_IS_POINT, args.asBoolean(1)); if (args.has(4)) { Integer id = args.asInt(4); if (id == null) { id = Particle.getByParticleName(args.asString(4)).getParticleId(); } entity.getMetadata().setInt(IAreaEffectCloud.META_KEY_AREA_EFFECT_CLOUD_PARTICLE_ID, id); } p.getWorld().addEntity(entity); } else if (args.asString(0).equalsIgnoreCase("crystal")) { final IEnderCrystal entity = entityFactory.createEntity(IEnderCrystal.class, p.getLocation()); entity.getMetadata().setBoolean(IEnderCrystal.META_KEY_ENDER_CRYSTAL_SHOW_BOTTOM, args.asBoolean(1)); if (args.has(4)) { entity.getMetadata().setBlockLocation(IEnderCrystal.META_KEY_ENDER_CRYSTAL_TARGET, args.readCoordinates(2, p.getLocation().toBlockLocation())); } p.getWorld().addEntity(entity); } else { final IEntity entity = entityFactory.createEntity(EntityType.getByEnumName(args.asString(0)), p.getLocation()); if (entity != null) { p.getWorld().addEntity(entity); } } break; } case "sound1": { p.getNetworkManager().sendPacket( new PacketPlayClientboundSoundEffect(Sound.getById(args.asInt(0)), p.getLocation(), 2, 63)); break; } case "sound2": { p.getNetworkManager().sendPacket( new PacketPlayClientboundNamedSoundEffect(args.asString(0), p.getLocation(), 2, 63)); break; } case "eq": { // Core break; } case "bookmeta": { final ItemStack item = new BaseItemStack(Material.WRITTEN_BOOK); final BookMeta meta = (BookMeta) item.getItemMeta(); meta.setAuthor("Lel"); meta.setPages("ugh"); p.getInventory().add(item); break; } case "gib": { final ItemStack item = new BaseItemStack(Material.APPLE); item.setAmount(args.has(0) ? args.asInt(0, 1) : 1); final ItemMeta meta = item.getItemMeta(); meta.setDisplayName("Diorite"); p.getInventory().add(item); break; } case "potionmeta": { final ItemStack item = new BaseItemStack( new PotionMat("POTION", 373, "minecraft:potion", 1, "POTION", (short) 8193, 5, 6) { }); final PotionMeta meta = new PotionMetaImpl(null); meta.addCustomEffect(new StatusEffect(StatusEffectType.INVISIBILITY, 3, 300, false, true), false); meta.addCustomEffect(new StatusEffect(StatusEffectType.INVISIBILITY, 3, 30000, false, true), false); item.setItemMeta(meta); p.getInventory().add(item); break; } case "m2": { final ItemMeta meta = p.getInventory().getItemInHand().getItemMeta(); meta.setDisplayName(RandomStringUtils.randomAlphanumeric(16)); break; } case "itemid": { final ItemMetaImpl meta = (ItemMetaImpl) p.getInventory().getItemInHand().getItemMeta(); System.out.println("Meta: " + System.identityHashCode(meta) + ", tag: " + (meta.getRawNbtData() == null ? "NULL" : System.identityHashCode(meta.getRawNbtData()) + "") + ", item: " + (!meta.getItemStack().isPresent() ? "NULL" : System.identityHashCode(meta.getItemStack().get()) + "")); break; } case "skullmeta": { final ItemStack item = new BaseItemStack(SkullMat.SKULL_PLAYER); System.out.println(item.getItemMeta()); final SkullMeta meta = (SkullMeta) item.getItemMeta(); meta.setOwner(args.asString(0)); System.out.println(meta); p.getInventory().add(item); break; } case "itemmeta": { final ItemStack item = new BaseItemStack(Material.STONE); final ItemMeta meta = item.getItemMeta(); meta.setDisplayName("Custom name!"); meta.setLore(Arrays.asList("North to", "gupi nup")); meta.addEnchant(EnchantmentType.AQUA_AFFINITY, 3, true); meta.addAttributeModifier(AttributeModifier.builder().setUuid(new UUID(0, 0)).setName("t") .setValue(2.25D).setType(AttributeType.GENERIC_ATTACK_DAMAGE).build()); meta.addAttributeModifier(AttributeModifier.builder().setUuid(new UUID(0, 1)).setName("t") .setValue(2.25D).setType(AttributeType.GENERIC_MAX_HEALTH).build()); p.getInventory().add(item); break; } case "pextest": { sender.setOp(false); mag.getPermissibleGroups(sender).forEach(g -> mag.removePermissibleFromGroup(sender, g)); sender.sendMessage("Testing permissions: "); sender.sendMessage("foo.bar: " + sender.hasPermission("foo.bar")); // false sender.sendMessage("Your groups: " + mag.getPermissibleGroups(sender).stream() .map(f -> f.getGroup().getName()).collect(Collectors.toList())); // empty final PermissionsGroup group = mag.createGroup("test"); sender.sendMessage("Adding to group (" + group.getName() + "): " + mag.addPermissibleToGroup(sender, group, 1)); // true sender.sendMessage("Your groups: " + mag.getPermissibleGroups(sender).stream() .map(f -> f.getGroup().getName()).collect(Collectors.toList())); // test mag.setPermission(group, "foo.bar", PermissionLevel.TRUE); sender.sendMessage("foo.bar: " + sender.hasPermission("foo.bar")); // true mag.removePermissibleFromGroup(sender, "test"); sender.sendMessage("Your groups: " + mag.getPermissibleGroups(sender).stream() .map(f -> f.getGroup().getName()).collect(Collectors.toList())); // empty sender.sendMessage("foo.bar: " + sender.hasPermission("foo.bar")); // false sender.sendMessage("Adding to group (" + group.getName() + "): " + mag.addPermissibleToGroup(sender, group, 1)); // true mag.setPermission(group, "foo.bar", PermissionLevel.OP); sender.sendMessage("foo.bar: " + sender.hasPermission("foo.bar")); // false sender.setOp(true); sender.sendMessage("foo.bar: " + sender.hasPermission("foo.bar")); // true sender.setOp(false); mag.setPermission(group, "foo.{$-$}", "foo.[-100--10,25-30]", PermissionLevel.TRUE); // from -100 to -10 sender.sendMessage("foo.5: " + sender.hasPermission("foo.5")); // false sender.sendMessage("foo.-10: " + sender.hasPermission("foo.-10")); // true sender.sendMessage("foo.-25: " + sender.hasPermission("foo.-25")); // true sender.sendMessage("foo.25: " + sender.hasPermission("foo.25")); // true mag.removePermissibleFromGroup(sender, "test"); sender.sendMessage("Your groups: " + mag.getPermissibleGroups(sender).stream() .map(f -> f.getGroup().getName()).collect(Collectors.toList())); // empty sender.sendMessage("foo.5: " + sender.hasPermission("foo.5")); // false sender.sendMessage("foo.-10: " + sender.hasPermission("foo.-10")); // false sender.sendMessage("foo.-25: " + sender.hasPermission("foo.-25")); // false sender.sendMessage("foo.25: " + sender.hasPermission("foo.25")); // false sender.setOp(true); sender.sendMessage("foo.5: " + sender.hasPermission("foo.5")); // true sender.sendMessage("foo.-10: " + sender.hasPermission("foo.-10")); // true sender.sendMessage("foo.-25: " + sender.hasPermission("foo.-25")); // true sender.sendMessage("foo.25: " + sender.hasPermission("foo.25")); // true mag.addPermissibleToGroup(sender, mag.createGroup("test"), 1); mag.addPermissibleToGroup(sender, mag.createGroup("a1"), 2); mag.addPermissibleToGroup(sender, mag.createGroup("a2"), 3); mag.addPermissibleToGroup(sender, mag.createGroup("a3"), 4); sender.sendMessage("Your groups: " + mag.getPermissibleGroups(sender).stream() .map(f -> f.getGroup().getName()).collect(Collectors.toList())); // test, a1, a2, a3 mag.setPermission(mag.getGroup("test"), "test.test", PermissionLevel.FALSE); mag.setPermission(mag.getGroup("a3"), "test.test", PermissionLevel.TRUE); sender.sendMessage("test.test: " + sender.hasPermission("test.test")); // true mag.setPermission(sender, "test.test", PermissionLevel.NOT_OP); sender.sendMessage("test.test: " + sender.hasPermission("test.test")); // false mag.setPermission(mag.getGroup("a2"), "test.test2", PermissionLevel.FALSE); mag.setPermission(mag.getGroup("a1"), "test.test2", PermissionLevel.TRUE); sender.sendMessage("test.test2: " + sender.hasPermission("test.test2")); // false break; } case "pex": { if (sender.hasPermission(args.asString(0))) { sender.sendMessage("You have " + args.asString(0) + " permission!"); } else { sender.sendMessage("You don't have " + args.asString(0) + " permission!"); } break; } case "pexaddg": { final PermissionsGroup group = mag.getGroup(args.asString(0)); if (group == null) { sender.sendMessage("No group, " + args.asString(0)); return; } mag.setPermission(group, args.asString(1), args.asString(2).equalsIgnoreCase("null") ? null : PermissionLevel.valueOf(args.asString(2).toUpperCase())); sender.sendMessage("Set permission " + args.asString(1) + ":" + (args.asString(2).equalsIgnoreCase("null") ? null : PermissionLevel.valueOf(args.asString(2).toUpperCase())) + " to group " + group.getName()); break; } case "pexadd": { mag.setPermission(sender, args.asString(0), args.asString(1).equalsIgnoreCase("null") ? null : PermissionLevel.valueOf(args.asString(1).toUpperCase())); sender.sendMessage("Set permission " + args.asString(0) + ":" + (args.asString(1).equalsIgnoreCase("null") ? null : PermissionLevel.valueOf(args.asString(1).toUpperCase())) + " to you"); break; } case "pexaddu": { final boolean added = mag.addPermissibleToGroup(sender, args.asString(0), args.asInt(1)); sender.sendMessage("Added you to " + args.asString(0) + " group: " + added); break; } case "pexreg": { mag.registerPermission(mag.createPermission(args.asString(0), args.asString(0), PermissionLevel.valueOf(args.asString(1).toUpperCase()))); sender.sendMessage("Register permission " + args.asString(0) + ":" + PermissionLevel.valueOf(args.asString(1).toUpperCase()) + " to manager"); break; } case "op": { if (p.isOp()) { p.setOp(false); sender.sendMessage("You are not op anymore..."); } else { p.setOp(true); sender.sendMessage("You are now op!"); } break; } case "pexrg": { final PermissionsGroup group = mag.removeGroup(args.asString(0)); sender.sendMessage("Removed group: " + group); break; } case "pexcg": { final PermissionsGroup group = mag.createGroup(args.asString(0)); sender.sendMessage("Created group: " + group); break; } case "setlocale": { p.setPreferedLocale((args.length() == 0) ? null : Locale.forLanguageTag(args.asText())); System.out.println("Done: " + p.getPreferredLocale()); break; } case "msgr": { DioriteMessages.reload(); System.out.println("Done"); break; } case "msg": { p.setPreferedLocale(Locale.forLanguageTag("pl-PL")); DioriteMessages.broadcastMessage(args.asText(), MessageData.e("player", p), MessageData.e("test", "Meeeh")); break; } case "tc": { final TextComponent tc = ComponentBuilder.start("test <r> ing").color(ChatColor.RED) .event(new ClickEvent(Action.OPEN_URL, "www.diorite.org:<port>")) .appendLegacy("2 costam costam 8<r> dbdjs fdd").create(); sender.sendMessage(tc); System.out.println(tc.toLegacyText()); System.out.println(ComponentSerializer.toString(tc)); sender.sendMessage(tc.duplicate()); System.out.println(tc.duplicate().toLegacyText()); System.out.println(ComponentSerializer.toString(tc.duplicate())); break; } case "rep": { final TextComponent tc = ComponentBuilder.start("test <r> ing").color(ChatColor.RED) .event(new ClickEvent(Action.OPEN_URL, "www.diorite.org:<port>")) .appendLegacy("2 costam costam 8<r> dbdjs fdd").create(); sender.sendMessage(tc.duplicate()); tc.replace("<r>", ComponentBuilder.start("Replaced clickable text") .event(new ClickEvent(Action.SUGGEST_COMMAND, "YeY")).create()); tc.replace("<port>", new TextComponent("8081")); sender.sendMessage(tc); break; } case "inv": { ((InventoryHolder) sender).getInventory().update(); sender.sendMessage("Inventory updated!"); break; } case "gs": { p.getNetworkManager() .sendPacket(new PacketPlayClientboundGameStateChange(args.asInt(0), args.asFloat(1))); sender.sendSimpleColoredMessage("&3Done."); break; } case "cb": { sender.sendSimpleColoredMessage(p.getLocation().toBlockLocation().getBlock().toString()); break; } // case "en": // { // final ItemImpl item = new ItemImpl(UUID.randomUUID(), p.getCore(), IEntity.getNextEntityID(), p.getLocation().addX(3).addY(1)); // item.setItemStack(new BaseItemStack(Material.TNT)); // p.getWorld().addEntity(item); // break; // } case "ep": { for (final IEntity e : p.getNearbyEntities(args.asDouble(0), args.asDouble(0), args.asDouble(0), LookupShape.RECTANGLE)) { sender.sendSimpleColoredMessage("[" + e.getId() + "] " + e.getType() + ": " + e.getLocation()); } break; } default: { sender.sendSimpleColoredMessage("&4No action..."); break; } } }); }
From source file:ru.anr.base.BaseParent.java
/** * @param startDate//from w ww . j a va2 s . c om * Start date * @param endDate * End date * @param locale * Locale * @return formatted period without seconds */ public static String formatPeriodWithoutSeconds(Calendar startDate, Calendar endDate, String locale) { Period period = new Period(startDate.getTimeInMillis(), endDate.getTimeInMillis(), PeriodType.standard().withSecondsRemoved().withMillisRemoved()); String l = locale == null ? Locale.getDefault().toString() : locale; return PeriodFormat.wordBased(Locale.forLanguageTag(l.replaceAll("_", "-"))).print(period); }
From source file:alfio.manager.TicketReservationManager.java
@Transactional(readOnly = true) public Map<String, Object> prepareModelForReservationEmail(Event event, TicketReservation reservation) { Optional<String> vat = getVAT(event); OrderSummary summary = orderSummaryForReservationId(reservation.getId(), event, Locale.forLanguageTag(reservation.getUserLanguage())); return prepareModelForReservationEmail(event, reservation, vat, summary); }
From source file:com.android.server.MountService.java
private void copyLocaleFromMountService() { String systemLocale;/* www .j av a 2s.c o m*/ try { systemLocale = getField(StorageManager.SYSTEM_LOCALE_KEY); } catch (RemoteException e) { return; } if (TextUtils.isEmpty(systemLocale)) { return; } Slog.d(TAG, "Got locale " + systemLocale + " from mount service"); Locale locale = Locale.forLanguageTag(systemLocale); Configuration config = new Configuration(); config.setLocale(locale); try { ActivityManagerNative.getDefault().updateConfiguration(config); } catch (RemoteException e) { Slog.e(TAG, "Error setting system locale from mount service", e); } // Temporary workaround for http://b/17945169. Slog.d(TAG, "Setting system properties to " + systemLocale + " from mount service"); SystemProperties.set("persist.sys.language", locale.getLanguage()); SystemProperties.set("persist.sys.country", locale.getCountry()); }
From source file:alfio.manager.AdminReservationManager.java
private void sendTicketHasBeenRemoved(Event event, Organization organization, Ticket ticket) { Map<String, Object> model = TemplateResource.buildModelForTicketHasBeenCancelled(organization, event, ticket);// w w w. j av a 2 s .c om Locale locale = Locale.forLanguageTag(Optional.ofNullable(ticket.getUserLanguage()).orElse("en")); notificationManager.sendSimpleEmail(event, ticket.getEmail(), messageSource.getMessage("email-ticket-released.subject", new Object[] { event.getDisplayName() }, locale), () -> templateManager.renderTemplate(event, TemplateResource.TICKET_HAS_BEEN_CANCELLED, model, locale)); }
From source file:com.joliciel.talismane.TalismaneConfigImpl.java
public void loadParameters(Map<String, String> args) { try {// www . j a v a2s . c o m if (args.size() == 0) { System.out.println("Talismane usage instructions: "); System.out.println("* indicates optional, + indicates default value"); System.out.println(""); System.out.println( "Usage: command=analyse *startModule=[sentence+|tokenise|postag|parse] *endModule=[sentence|tokenise|postag|parse+] *inFile=[inFilePath, stdin if missing] *outFile=[outFilePath, stdout if missing] *template=[outputTemplatePath]"); System.out.println(""); System.out.println("Additional optional parameters:"); System.out.println( " *encoding=[UTF-8, ...] *includeDetails=[true|false+] posTaggerRules*=[posTaggerRuleFilePath] textFilters*=[regexFilterFilePath] *sentenceModel=[path] *tokeniserModel=[path] *posTaggerModel=[path] *parserModel=[path] *inputPatternFile=[inputPatternFilePath] *posTagSet=[posTagSetPath]"); return; } String logConfigPath = args.get("logConfigFile"); if (logConfigPath != null) { args.remove("logConfigFile"); Properties props = new Properties(); props.load(new FileInputStream(logConfigPath)); PropertyConfigurator.configure(props); } String performanceConifPath = args.get("performanceConfigFile"); if (performanceConifPath != null) { args.remove("performanceConfigFile"); performanceConfigFile = this.getFile(performanceConifPath); } String encoding = null; String inputEncoding = null; String outputEncoding = null; String builtInTemplate = null; String posTagSetPath = null; String externalResourcePath = null; String transitionSystemStr = null; String languagePackPath = null; for (Entry<String, String> arg : args.entrySet()) { String argName = arg.getKey(); String argValue = arg.getValue(); if (argName.equals("command")) { String commandString = argValue; if (commandString.equals("analyze")) commandString = "analyse"; command = Command.valueOf(commandString); } else if (argName.equals("option")) { option = Option.valueOf(argValue); } else if (argName.equals("mode")) { mode = Mode.valueOf(argValue); } else if (argName.equals("module")) { if (argValue.equalsIgnoreCase("sentence") || argValue.equalsIgnoreCase("sentenceDetector")) module = Talismane.Module.SentenceDetector; else if (argValue.equalsIgnoreCase("tokenise") || argValue.equalsIgnoreCase("tokeniser")) module = Talismane.Module.Tokeniser; else if (argValue.equalsIgnoreCase("postag") || argValue.equalsIgnoreCase("posTagger")) module = Talismane.Module.PosTagger; else if (argValue.equalsIgnoreCase("parse") || argValue.equalsIgnoreCase("parser")) module = Talismane.Module.Parser; else if (argValue.equalsIgnoreCase("language") || argValue.equalsIgnoreCase("languageDetector")) module = Talismane.Module.LanguageDetector; else throw new TalismaneException("Unknown module: " + argValue); } else if (argName.equals("startModule")) { if (argValue.equalsIgnoreCase("sentence") || argValue.equalsIgnoreCase("sentenceDetector")) startModule = Talismane.Module.SentenceDetector; else if (argValue.equalsIgnoreCase("tokenise") || argValue.equalsIgnoreCase("tokeniser")) startModule = Talismane.Module.Tokeniser; else if (argValue.equalsIgnoreCase("postag") || argValue.equalsIgnoreCase("posTagger")) startModule = Talismane.Module.PosTagger; else if (argValue.equalsIgnoreCase("parse") || argValue.equalsIgnoreCase("parser")) startModule = Talismane.Module.Parser; else throw new TalismaneException("Unknown startModule: " + argValue); } else if (argName.equals("endModule")) { if (argValue.equalsIgnoreCase("sentence") || argValue.equalsIgnoreCase("sentenceDetector")) endModule = Talismane.Module.SentenceDetector; else if (argValue.equalsIgnoreCase("tokenise") || argValue.equalsIgnoreCase("tokeniser")) endModule = Talismane.Module.Tokeniser; else if (argValue.equalsIgnoreCase("postag") || argValue.equalsIgnoreCase("posTagger")) endModule = Talismane.Module.PosTagger; else if (argValue.equalsIgnoreCase("parse") || argValue.equalsIgnoreCase("parser")) endModule = Talismane.Module.Parser; else throw new TalismaneException("Unknown endModule: " + argValue); } else if (argName.equals("inFile")) inFilePath = argValue; else if (argName.equals("inDir")) inDirPath = argValue; else if (argName.equals("outFile")) outFilePath = argValue; else if (argName.equals("outDir")) outDirPath = argValue; else if (argName.equals("template")) templatePath = argValue; else if (argName.equals("builtInTemplate")) builtInTemplate = argValue; else if (argName.equals("encoding")) { if (inputEncoding != null || outputEncoding != null) throw new TalismaneException( "The parameter 'encoding' cannot be used with 'inputEncoding' or 'outputEncoding'"); encoding = argValue; } else if (argName.equals("inputEncoding")) { if (encoding != null) throw new TalismaneException( "The parameter 'encoding' cannot be used with 'inputEncoding' or 'outputEncoding'"); inputEncoding = argValue; } else if (argName.equals("outputEncoding")) { if (encoding != null) throw new TalismaneException( "The parameter 'encoding' cannot be used with 'inputEncoding' or 'outputEncoding'"); outputEncoding = argValue; } else if (argName.equals("includeDetails")) includeDetails = argValue.equalsIgnoreCase("true"); else if (argName.equals("propagateBeam")) propagateBeam = argValue.equalsIgnoreCase("true"); else if (argName.equals("beamWidth")) beamWidth = Integer.parseInt(argValue); else if (argName.equals("languageModel")) languageModelFilePath = argValue; else if (argName.equals("sentenceModel")) sentenceModelFilePath = argValue; else if (argName.equals("tokeniserModel")) tokeniserModelFilePath = argValue; else if (argName.equals("posTaggerModel")) posTaggerModelFilePath = argValue; else if (argName.equals("parserModel")) parserModelFilePath = argValue; else if (argName.equals("inputPatternFile")) inputPatternFilePath = argValue; else if (argName.equals("inputPattern")) inputRegex = argValue; else if (argName.equals("evaluationPatternFile")) evaluationPatternFilePath = argValue; else if (argName.equals("evaluationPattern")) evaluationRegex = argValue; else if (argName.equals("posTaggerRules")) { if (argValue.startsWith("replace:")) { posTaggerRulesReplace = true; posTaggerRuleFilePath = argValue.substring("replace:".length()); } else { posTaggerRuleFilePath = argValue; } } else if (argName.equals("parserRules")) { if (argValue.startsWith("replace:")) { parserRulesReplace = true; parserRuleFilePath = argValue.substring("replace:".length()); } else { parserRuleFilePath = argValue; } } else if (argName.equals("posTagSet")) posTagSetPath = argValue; else if (argName.equals("textFilters")) { if (argValue.startsWith("replace:")) { textFiltersReplace = true; textFiltersPath = argValue.substring("replace:".length()); } else { textFiltersPath = argValue; } } else if (argName.equals("tokenFilters")) { if (argValue.startsWith("replace:")) { tokenFiltersReplace = true; tokenFiltersPath = argValue.substring("replace:".length()); } else { tokenFiltersPath = argValue; } } else if (argName.equals("tokenSequenceFilters")) { if (argValue.startsWith("replace:")) { tokenSequenceFiltersReplace = true; tokenSequenceFilterPath = argValue.substring("replace:".length()); } else { tokenSequenceFilterPath = argValue; } } else if (argName.equals("posTagSequenceFilters")) posTagSequenceFilterPath = argValue; else if (argName.equals("logStats")) logStats = argValue.equalsIgnoreCase("true"); else if (argName.equals("newline")) newlineMarker = MarkerFilterType.valueOf(argValue); else if (argName.equals("fileName")) fileName = argValue; else if (argName.equals("processByDefault")) processByDefault = argValue.equalsIgnoreCase("true"); else if (argName.equals("maxParseAnalysisTime")) maxParseAnalysisTime = Integer.parseInt(argValue); else if (argName.equals("minFreeMemory")) minFreeMemory = Integer.parseInt(argValue); else if (argName.equals("transitionSystem")) transitionSystemStr = argValue; else if (argName.equals("sentenceCount")) maxSentenceCount = Integer.parseInt(argValue); else if (argName.equals("startSentence")) startSentence = Integer.parseInt(argValue); else if (argName.equals("endBlockCharCode")) endBlockCharacter = (char) Integer.parseInt(argValue); else if (argName.equals("outputGuesses")) outputGuesses = argValue.equalsIgnoreCase("true"); else if (argName.equals("outputGuessCount")) outputGuessCount = Integer.parseInt(argValue); else if (argName.equals("suffix")) suffix = argValue; else if (argName.equals("includeDistanceFScores")) includeDistanceFScores = argValue.equalsIgnoreCase("true"); else if (argName.equals("includeTransitionLog")) includeTransitionLog = argValue.equalsIgnoreCase("true"); else if (argName.equals("evaluationFile")) evaluationFilePath = argValue; else if (argName.equals("labeledEvaluation")) labeledEvaluation = argValue.equalsIgnoreCase("true"); else if (argName.equals("tokeniserBeamWidth")) tokeniserBeamWidth = Integer.parseInt(argValue); else if (argName.equals("posTaggerBeamWidth")) posTaggerBeamWidth = Integer.parseInt(argValue); else if (argName.equals("parserBeamWidth")) parserBeamWidth = Integer.parseInt(argValue); else if (argName.equals("propagateTokeniserBeam")) propagateTokeniserBeam = argValue.equalsIgnoreCase("true"); else if (argName.equals("blockSize")) blockSize = Integer.parseInt(argValue); else if (argName.equals("crossValidationSize")) crossValidationSize = Integer.parseInt(argValue); else if (argName.equals("includeIndex")) includeIndex = Integer.parseInt(argValue); else if (argName.equals("excludeIndex")) excludeIndex = Integer.parseInt(argValue); else if (argName.equals("dynamiseFeatures")) dynamiseFeatures = argValue.equalsIgnoreCase("true"); else if (argName.equals("predictTransitions")) predictTransitions = argValue.equalsIgnoreCase("true"); else if (argName.equals("lexicon")) { if (argValue.startsWith("replace:")) { replaceLexicon = true; lexiconPath = argValue.substring("replace:".length()); } else { lexiconPath = argValue; } } else if (argName.equals("perceptronScoring")) { PerceptronScoring perceptronScoring = PerceptronScoring.valueOf(argValue); MachineLearningSession.setPerceptronScoring(perceptronScoring); } else if (argName.equals("parseComparisonStrategy")) { parseComparisonStrategyType = ParseComparisonStrategyType.valueOf(argValue); } else if (argName.equals("sentenceReader")) { sentenceReaderPath = argValue; } else if (argName.equals("skipLabel")) { skipLabel = argValue; } else if (argName.equals("errorLabels")) { errorLabels = new HashSet<String>(); String[] labels = argValue.split(","); for (String label : labels) { errorLabels.add(label); } } else if (argName.equals("earlyStop")) { earlyStop = argValue.equalsIgnoreCase("true"); } else if (argName.equals("languageFeatures")) { languageFeaturePath = argValue; } else if (argName.equals("sentenceFeatures")) { sentenceFeaturePath = argValue; } else if (argName.equals("tokeniserFeatures")) { tokeniserFeaturePath = argValue; } else if (argName.equals("tokeniserPatterns")) { tokeniserPatternFilePath = argValue; } else if (argName.equals("posTaggerFeatures")) { posTaggerFeaturePath = argValue; } else if (argName.equals("parserFeatures")) { parserFeaturePath = argValue; } else if (argName.equals("externalResources")) { externalResourcePath = argValue; } else if (argName.equals("testWords")) { String[] parts = argValue.split(";"); testWords = new HashSet<String>(); for (String part : parts) testWords.add(part); } else if (argName.equals("includeLexiconCoverage")) { includeLexiconCoverage = argValue.equalsIgnoreCase("true"); } else if (argName.equals("includeUnknownWordResults")) { includeUnknownWordResults = argValue.equalsIgnoreCase("true"); } else if (argName.equals("iterations")) iterations = Integer.parseInt(argValue); else if (argName.equals("cutoff")) cutoff = Integer.parseInt(argValue); else if (argName.equals("dependencyLabels")) dependencyLabelPath = argValue; else if (argName.equals("parsingConstrainer")) parsingConstrainerPath = argValue; else if (argName.equals("algorithm")) algorithm = MachineLearningAlgorithm.valueOf(argValue); else if (argName.equals("linearSVMSolver")) solverType = LinearSVMSolverType.valueOf(argValue); else if (argName.equals("linearSVMCost")) constraintViolationCost = Double.parseDouble(argValue); else if (argName.equals("linearSVMEpsilon")) epsilon = Double.parseDouble(argValue); else if (argName.equals("perceptronTolerance")) perceptronTolerance = Double.parseDouble(argValue); else if (argName.equals("averageAtIntervals")) averageAtIntervals = argValue.equalsIgnoreCase("true"); else if (argName.equals("perceptronObservationPoints")) { String[] points = argValue.split(","); perceptronObservationPoints = new ArrayListNoNulls<Integer>(); for (String point : points) perceptronObservationPoints.add(Integer.parseInt(point)); } else if (argName.equals("tokeniserType")) { tokeniserType = TokeniserType.valueOf(argValue); } else if (argName.equals("patternTokeniser")) patternTokeniserType = PatternTokeniserType.valueOf(argValue); else if (argName.equals("excludeFile")) { excludeFileName = argValue; } else if (argName.equals("port")) { port = Integer.parseInt(argValue); } else if (argName.equals("preloadLexicon")) { preloadLexicon = argValue.equalsIgnoreCase("true"); } else if (argName.equals("locale")) { locale = Locale.forLanguageTag(argValue); } else if (argName.equals("languageCorpusMap")) { languageCorpusMapPath = argValue; } else if (argName.equals("corpusLexicalEntryRegex")) { corpusLexicalEntryRegexPath = argValue; } else if (argName.equals("languagePack")) { languagePackPath = argValue; } else { System.out.println("Unknown argument: " + argName); throw new RuntimeException("Unknown argument: " + argName); } } if (command == null) throw new TalismaneException("No command provided."); if (!(implementation instanceof LanguagePackImplementation) && languagePackPath != null) throw new TalismaneException("The implementation " + implementation.getClass().getSimpleName() + " does not accept language packs"); if (implementation instanceof LanguagePackImplementation) { if (languagePackPath != null) { File languagePackFile = this.getFile(languagePackPath); if (!languagePackFile.exists()) throw new TalismaneException( "languagePack: could not find file: " + languagePackFile.getPath()); LOG.debug("Setting language pack to " + languagePackFile.getPath()); ((LanguagePackImplementation) implementation).setLanguagePack(languagePackFile); } } if (command.equals(Command.evaluate)) { if (outDirPath.length() == 0) throw new TalismaneException("Missing argument: outdir"); } if (startModule == null) startModule = module; if (startModule == null) startModule = Module.SentenceDetector; if (endModule == null) endModule = module; if (endModule == null) endModule = Module.Parser; if (module == null) module = endModule; if (command == Command.train) { if (module == Module.LanguageDetector) { if (languageModelFilePath == null) throw new TalismaneException( "languageModel is required when training a language detector model"); if (languageCorpusMapPath == null) throw new TalismaneException( "languageCorpusMap is required when training a language detector model"); if (languageFeaturePath == null) throw new TalismaneException( "languageFeatures is required when training a language detector model"); } else if (module == Module.SentenceDetector) { if (sentenceModelFilePath == null) throw new TalismaneException( "sentenceModel is required when training a sentence detector model"); if (sentenceFeaturePath == null) throw new TalismaneException( "sentenceFeatures is required when training a sentence detector model"); } else if (module == Module.Tokeniser) { if (tokeniserModelFilePath == null) throw new TalismaneException("tokeniserModel is required when training a tokeniser model"); if (tokeniserFeaturePath == null) throw new TalismaneException( "tokeniserFeatures is required when training a tokeniser model"); } else if (module == Module.PosTagger) { if (posTaggerModelFilePath == null) throw new TalismaneException("posTaggerModel is required when training a posTagger model"); if (posTaggerFeaturePath == null) throw new TalismaneException( "posTaggerFeatures is required when training a posTagger model"); } else if (module == Module.Parser) { this.predictTransitions = true; if (parserModelFilePath == null) throw new TalismaneException("parserModel is required when training a parser model"); if (parserFeaturePath == null) throw new TalismaneException("parserFeatures is required when training a parser model"); } } if (builtInTemplate != null) { if (builtInTemplate.equalsIgnoreCase("with_location")) { tokeniserTemplateName = "tokeniser_template_with_location.ftl"; posTaggerTemplateName = "posTagger_template_with_location.ftl"; parserTemplateName = "parser_conll_template_with_location.ftl"; } else if (builtInTemplate.equalsIgnoreCase("with_prob")) { tokeniserTemplateName = "tokeniser_template_with_prob.ftl"; posTaggerTemplateName = "posTagger_template_with_prob.ftl"; parserTemplateName = "parser_conll_template_with_prob.ftl"; } else if (builtInTemplate.equalsIgnoreCase("with_comments")) { posTaggerTemplateName = "posTagger_template_with_comments.ftl"; parserTemplateName = "parser_conll_template_with_comments.ftl"; } else { throw new TalismaneException("Unknown builtInTemplate: " + builtInTemplate); } } if (posTaggerBeamWidth < 0) posTaggerBeamWidth = beamWidth; if (parserBeamWidth < 0) parserBeamWidth = beamWidth; inputCharset = Charset.defaultCharset(); outputCharset = Charset.defaultCharset(); if (encoding != null) { inputCharset = Charset.forName(encoding); outputCharset = Charset.forName(encoding); } else { if (inputEncoding != null) inputCharset = Charset.forName(inputEncoding); if (outputEncoding != null) outputCharset = Charset.forName(outputEncoding); } if (fileName == null && inFilePath != null) { fileName = inFilePath; } if (posTagSetPath != null) { File posTagSetFile = this.getFile(posTagSetPath); Scanner posTagSetScanner = new Scanner(new BufferedReader( new InputStreamReader(new FileInputStream(posTagSetFile), this.getInputCharset().name()))); PosTagSet posTagSet = this.getPosTaggerService().getPosTagSet(posTagSetScanner); talismaneSession.setPosTagSet(posTagSet); } if (transitionSystemStr != null) { TransitionSystem transitionSystem = null; if (transitionSystemStr.equalsIgnoreCase("ShiftReduce")) { transitionSystem = this.getParserService().getShiftReduceTransitionSystem(); } else if (transitionSystemStr.equalsIgnoreCase("ArcEager")) { transitionSystem = this.getParserService().getArcEagerTransitionSystem(); } else { throw new TalismaneException("Unknown transition system: " + transitionSystemStr); } if (dependencyLabelPath != null) { File dependencyLabelFile = this.getFile(dependencyLabelPath); Scanner depLabelScanner = new Scanner(new BufferedReader( new InputStreamReader(new FileInputStream(dependencyLabelFile), "UTF-8"))); List<String> dependencyLabels = new ArrayListNoNulls<String>(); while (depLabelScanner.hasNextLine()) { String dependencyLabel = depLabelScanner.nextLine(); if (!dependencyLabel.startsWith("#")) dependencyLabels.add(dependencyLabel); } transitionSystem.setDependencyLabels(dependencyLabels); } talismaneSession.setTransitionSystem(transitionSystem); } if (this.lexiconPath != null) { File lexiconFile = this.getFile(lexiconPath); if (!lexiconFile.exists()) throw new TalismaneException("lexicon: File " + lexiconPath + " does not exist"); LexiconDeserializer lexiconDeserializer = new LexiconDeserializer(talismaneSession); List<PosTaggerLexicon> lexicons = lexiconDeserializer.deserializeLexicons(lexiconFile); for (PosTaggerLexicon oneLexicon : lexicons) { talismaneSession.addLexicon(oneLexicon); } if (!replaceLexicon) { List<PosTaggerLexicon> defaultLexicons = this.implementation.getDefaultLexicons(); if (defaultLexicons != null) { for (PosTaggerLexicon oneLexicon : defaultLexicons) { talismaneSession.addLexicon(oneLexicon); } } } } if (externalResourcePath != null) { externalResourceFinder = this.getMachineLearningService().getExternalResourceFinder(); List<String> paths = new ArrayListNoNulls<String>(); if (externalResourcePath != null && externalResourcePath.length() > 0) { LOG.info("externalResourcePath: " + externalResourcePath); String[] parts = externalResourcePath.split(";"); for (String part : parts) paths.add(part); } for (String path : paths) { LOG.info("Reading external resources from " + path); if (path.length() > 0) { File externalResourceFile = this.getFile(path); externalResourceFinder.addExternalResources(externalResourceFile); } } ExternalResourceFinder parserResourceFinder = this.getParserFeatureService() .getExternalResourceFinder(); ExternalResourceFinder posTaggerResourceFinder = this.getPosTaggerFeatureService() .getExternalResourceFinder(); ExternalResourceFinder tokeniserResourceFinder = this.getTokenFeatureService() .getExternalResourceFinder(); ExternalResourceFinder sentenceResourceFinder = this.getSentenceDetectorFeatureService() .getExternalResourceFinder(); for (ExternalResource<?> externalResource : externalResourceFinder.getExternalResources()) { parserResourceFinder.addExternalResource(externalResource); posTaggerResourceFinder.addExternalResource(externalResource); tokeniserResourceFinder.addExternalResource(externalResource); sentenceResourceFinder.addExternalResource(externalResource); } ExternalResourceFinder tokenFilterResourceFinder = this.getTokenFilterService() .getExternalResourceFinder(); for (ExternalWordList externalWordList : externalResourceFinder.getExternalWordLists()) { tokenFilterResourceFinder.addExternalWordList(externalWordList); } } } catch (IOException e) { LogUtils.logError(LOG, e); throw new RuntimeException(e); } }
From source file:alfio.manager.TicketReservationManager.java
private void acquireItems(TicketStatus ticketStatus, AdditionalServiceItemStatus asStatus, PaymentProxy paymentProxy, String reservationId, String email, CustomerName customerName, String userLanguage, String billingAddress, int eventId) { Map<Integer, Ticket> preUpdateTicket = ticketRepository.findTicketsInReservation(reservationId).stream() .collect(toMap(Ticket::getId, Function.identity())); int updatedTickets = ticketRepository.updateTicketsStatusWithReservationId(reservationId, ticketStatus.toString());/*from w w w.j a v a 2s . c o m*/ Map<Integer, Ticket> postUpdateTicket = ticketRepository.findTicketsInReservation(reservationId).stream() .collect(toMap(Ticket::getId, Function.identity())); postUpdateTicket.forEach((id, ticket) -> { auditUpdateTicket(preUpdateTicket.get(id), Collections.emptyMap(), ticket, Collections.emptyMap(), eventId); }); int updatedAS = additionalServiceItemRepository.updateItemsStatusWithReservationUUID(reservationId, asStatus); Validate.isTrue(updatedTickets + updatedAS > 0, "no items have been updated"); specialPriceRepository.updateStatusForReservation(singletonList(reservationId), Status.TAKEN.toString()); ZonedDateTime timestamp = ZonedDateTime.now(ZoneId.of("UTC")); int updatedReservation = ticketReservationRepository.updateTicketReservation(reservationId, TicketReservationStatus.COMPLETE.toString(), email, customerName.getFullName(), customerName.getFirstName(), customerName.getLastName(), userLanguage, billingAddress, timestamp, paymentProxy.toString()); Validate.isTrue(updatedReservation == 1, "expected exactly one updated reservation, got " + updatedReservation); waitingQueueManager.fireReservationConfirmed(reservationId); if (paymentProxy == PaymentProxy.PAYPAL || paymentProxy == PaymentProxy.ADMIN) { //we must notify the plugins about ticket assignment and send them by email Event event = eventRepository.findByReservationId(reservationId); TicketReservation reservation = findById(reservationId).orElseThrow(IllegalStateException::new); findTicketsInReservation(reservationId).stream() .filter(ticket -> StringUtils.isNotBlank(ticket.getFullName()) || StringUtils.isNotBlank(ticket.getFirstName()) || StringUtils.isNotBlank(ticket.getEmail())) .forEach(ticket -> { Locale locale = Locale.forLanguageTag(ticket.getUserLanguage()); if (paymentProxy == PaymentProxy.PAYPAL) { sendTicketByEmail(ticket, locale, event, getTicketEmailGenerator(event, reservation, locale)); } pluginManager.handleTicketAssignment(ticket); extensionManager.handleTicketAssignment(ticket); }); } }
From source file:kolacer.Kolacer.java
private String[] ziskejDatumyPodleDne(String den) { String[] nedele = new String[2]; Date date = new Date(); int style = DateFormat.LONG; DateFormat df = DateFormat.getDateInstance(style, Locale.forLanguageTag("sk")); SimpleDateFormat sdf = new SimpleDateFormat("dd.MM.yyyy"); int pocitadlo = 0; while (!den.equals(df.format(date).split(",")[0])) { date.setTime(date.getTime() - 1000 * 60 * 60 * 24); pocitadlo++;/* w w w .j ava2 s . co m*/ if (pocitadlo == 7) break; } nedele[1] = sdf.format(date); date.setTime(date.getTime() - 14000 * 60 * 60 * 24); nedele[0] = sdf.format(date); return nedele; }
From source file:kobytest.KobyTest.java
public static void pedir_historico(final int id_valor, String symbol, int weeks_ago) throws SQLException, ParseException { System.out.println("Requesting historic data for :" + id_valor); //0 weeks ago is this weekd Calendar cal = Calendar.getInstance(); int current_week = cal.get(Calendar.WEEK_OF_YEAR); int current_day = cal.get(Calendar.DAY_OF_MONTH); int current_month = cal.get(Calendar.MONTH) + 1; int current_year = cal.get(Calendar.YEAR); System.out.println("Current day is " + current_day); System.out.println("Current week is " + current_week); String year = "" + current_year; if (current_month == 1) current_month = 12;//from w w w .j ava2 s. c om String month = "" + current_month; String day = "01"; for (int i = 0; i < weeks_ago; i++) { System.out.println("i = " + i + ". id_valor=" + id_valor + ". valorestabla[id_valor]" + valores_tabla.get(id_valor)); historico_valores.get(valores_tabla.get(id_valor)).put(i, null); } final Contract contract = new Contract(); //contract.m_comboLegs //contract.m_comboLegsDescrip //contract.m_conId = 11; contract.m_currency = "USD"; contract.m_exchange = "SMART"; //contract.m_expiry; contract.m_includeExpired = false; //contract.m_localSymbol = "KO"; //contract.m_multiplier; // contract.m_primaryExch = "NASDAQ"; // contract.m_right = "CALL"; //contract.m_secId; //contract.m_secIdType; contract.m_secType = "STK"; // stock String simbolo = valores_tabla.get(id_valor); contract.m_symbol = simbolo; // symbol //contract.m_tradingClass; //int id, Contract contract, String endDateTime, String durationStr, String barSizeSetting, String whatToShow, int useRTH, int formatDate, List<TagValue> chartOptions //TODO // -semana: buscar el fin de la semana. Calcular a partir de la semana // format yyyymmdd hh:mm:ss tmz, where the time zone is allowed (optionally) after a space at the end. Calendar cal_last_sunday = Calendar.getInstance(); // cal_last_sunday.set(Calendar.WEEK_OF_YEAR, current_week); cal_last_sunday.set(Calendar.WEEK_OF_YEAR, current_week - 1); cal_last_sunday.set(Calendar.DAY_OF_WEEK, Calendar.SUNDAY); // cal_last_sunday.set(Calendar.DAY_OF_WEEK, Calendar.FRIDAY); int last_sunday_day = cal_last_sunday.get(Calendar.DAY_OF_MONTH); int last_sunday_month = cal_last_sunday.get(Calendar.MONTH) + 1; // int last_sunday_month = cal_last_sunday.get(Calendar.MONTH); int last_sunday_year = cal_last_sunday.get(Calendar.YEAR); String last_sunday_year_str = String.valueOf(last_sunday_year); String last_sunday_month_str = String.valueOf(last_sunday_month); if (last_sunday_month < 10) { last_sunday_month_str = "0" + last_sunday_month_str; } String last_sunday_day_str = String.valueOf(last_sunday_day); if (last_sunday_day < 10) { last_sunday_day_str = "0" + last_sunday_day_str; } String semana = last_sunday_year_str + last_sunday_month_str + last_sunday_day_str + " 16:00:00 EST"; // de la primera semana String current_year_str = String.valueOf(current_year); String current_month_str = String.valueOf(current_month); if (current_month < 10) { current_month_str = "0" + current_month_str; } String current_day_str = String.valueOf(current_day); if (current_day < 10) { current_day_str = "0" + current_day_str; } Calendar c = Calendar.getInstance(); Calendar c1 = Calendar.getInstance(); c.add(Calendar.DATE, 0); SimpleDateFormat d = new SimpleDateFormat("yyyyMMdd"); Date date = c.getTime(); Date dateW = c1.getTime(); strSemana = d.format(date); strWeek = d.format(dateW); Calendar calendar = Calendar.getInstance(Locale.forLanguageTag("en-US")); calendar.setTimeZone(TimeZone.getTimeZone("America/New_York")); String hour = calendar.get(Calendar.HOUR_OF_DAY) + ":" + calendar.get(Calendar.MINUTE) + ":00"; //semana = current_year_str + current_month_str + current_day_str + " "+hour+" America/New_York";//EST semana = strSemana + " 09:00:00 EST"; final String semanaTimer = semana; System.out.println("Requestion values for " + strSemana); final String duracion = 1 + " D"; // pedimos todas las semanas final String duracionTimer = 1 + " D"; // pedimos todas las semanas final String barSizeSetting = "1 day"; final String whatToShow = "TRADES"; final int useRTH = 1; //only data that falls within regular trading hours. final int formatDate = 1;//1 - dates applying to bars returned in the format:yyyymmdd{space}{space}hh:mm:dd 2 - dates are returned as a long integer specifying the number of seconds since 1/1/1970 GMT. // List chartOptions = null; final Vector chartOptions = new Vector(); symbol_current = symbol; String fecha = current_year + "-" + current_month + "-" + current_day; // ResultSet exsiste = DDBB.lowHighFecha(fecha); // ResultSet exsisteTicker = DDBB.lowHighFechaName(fecha, symbol);d? count++; HistoricalDataReq historial = new HistoricalDataReq(); peticionesHistorical[count].id = id_valor; peticionesHistorical[count].contract = contract; peticionesHistorical[count].endDateTime = semana; peticionesHistorical[count].durationStr = duracion; peticionesHistorical[count].barSizeSetting = barSizeSetting; peticionesHistorical[count].whatToShow = whatToShow; peticionesHistorical[count].useRTH = useRTH; peticionesHistorical[count].formatDate = formatDate; peticionesHistorical[count].chartOptions = chartOptions; peticionesHistorical[count].ticker = symbol; // peticionesHistorical[count] = historial; System.out.println("--------------------------------------------------------------------------------------" + historial.id + " " + symbol); // connection.reqHistoricalData(id_valor, contract, semanaTimer, duracion, barSizeSetting, whatToShow, useRTH, formatDate, chartOptions); // try { // // Thread t = new Thread(new Runnable() { // // @Override // public void run() { // int num = 1000; // ResultSet dat = DDBB.TickersAll(); // try { // Thread.sleep((int)(Math.random()*((16000*num)-1000+1)+1000)); // } catch (InterruptedException ex) { // Logger.getLogger(KobyTest.class.getName()).log(Level.SEVERE, null, ex); // } // // try { // if(dat.next())num=dat.getInt("id"); // } catch (SQLException ex) { // Logger.getLogger(KobyTest.class.getName()).log(Level.SEVERE, null, ex); // } // Timer timer = new Timer ((int)(Math.random()*((16000*num)-1000+1)+1000), new ActionListener () { // public void actionPerformed(ActionEvent e) // { // connection.reqHistoricalData(id_valor, contract, semanaTimer, duracionTimer, barSizeSetting, whatToShow, useRTH, formatDate, chartOptions); // } // }); // timer.start(); // // } // }); // t.start(); // // } catch (Exception ex) { // Logger.getLogger(Semaforo.class.getName()).log(Level.SEVERE, null, ex); // } // id_ant = id_valor; // connection.reqHistoricalData(id_valor, contract, semana, "300 S", "1 secs", whatToShow, useRTH, formatDate, chartOptions); // if(!exsiste.next()){ System.out.println("eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee"); // DDBB.deleteLowHigh(); // connection.reqHistoricalData(id_valor, contract, semana, duracion, barSizeSetting, whatToShow, useRTH, formatDate, chartOptions); // }else if(newTicker){ // System.out.println("iiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiii"); // connection.reqHistoricalData(id_valor, contract, semana, duracion, barSizeSetting, whatToShow, useRTH, formatDate, chartOptions); // newTicker = false; // }else if(!exsisteTicker.next()){ // System.out.println("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"); // connection.reqHistoricalData(id_valor, contract, semana, duracion, barSizeSetting, whatToShow, useRTH, formatDate, chartOptions); // newTicker = false; // } }
From source file:org.filteredpush.qc.date.DateUtils.java
/** * Given a string that may represent a date or range of dates, or date time or range of date times, * attempt to extract a standard date from that string. * // w ww .j ava 2s . c o m * @param verbatimEventDate a string containing a verbatim event date. * @param yearsBeforeSuspect Dates that parse to a year prior to this year are marked as suspect. * @param assumemmddyyyy if true, assume that dates in the form nn-nn-nnnn are mm-dd-yyyy, if false, assume * that these are dd-mm-yyyy, if null, such dates are tested for ambiguity. * * @return an EventResult with a resultState for the nature of the match and result for the resulting date. */ public static EventResult extractDateFromVerbatimER(String verbatimEventDate, int yearsBeforeSuspect, Boolean assumemmddyyyy) { EventResult result = new EventResult(); String resultDate = null; // Remove some common no data comments if (verbatimEventDate != null && verbatimEventDate.contains("[no date]")) { verbatimEventDate = verbatimEventDate.replace("[no date]", ""); } if (verbatimEventDate != null && verbatimEventDate.contains("[no year]")) { verbatimEventDate = verbatimEventDate.replace("[no year]", ""); } // Strip off leading and trailing [] if (verbatimEventDate != null && verbatimEventDate.startsWith("[") && verbatimEventDate.endsWith("]")) { verbatimEventDate = verbatimEventDate.substring(1); verbatimEventDate = verbatimEventDate.substring(0, verbatimEventDate.length() - 1); } if (verbatimEventDate != null && verbatimEventDate.matches(".*\\[[0-9]+\\].*")) { verbatimEventDate = verbatimEventDate.replace("[", "").replace("]", ""); } // Strip off leading and trailing quotation marks if (verbatimEventDate != null && verbatimEventDate.startsWith("\"") && verbatimEventDate != null && verbatimEventDate.endsWith("\"")) { verbatimEventDate = verbatimEventDate.substring(1, verbatimEventDate.length() - 1); } // strip off leading and trailing whitespace if (verbatimEventDate != null && (verbatimEventDate.startsWith(" ") || verbatimEventDate.endsWith(" "))) { verbatimEventDate = verbatimEventDate.trim(); } // strip off trailing period after number if (verbatimEventDate != null && verbatimEventDate.endsWith(".") && verbatimEventDate.matches(".*[0-9]\\.$")) { verbatimEventDate = verbatimEventDate.substring(0, verbatimEventDate.length() - 1); logger.debug(verbatimEventDate); } // Stop before doing work if provided verbatim string is null. if (isEmpty(verbatimEventDate)) { return result; } if (verbatimEventDate.matches("^[0-9]{4}[-][0-9]{2}[-][0-9]{2}/[0-9]{4}[-][0-9]{2}[-][0-9]{2}$")) { // if verbatim date is a ISO formatted range with identical first and last dates (/), use just one. // Example: 1982-12-11/1982-12-11 changed to 1982-12-11 String[] bits = verbatimEventDate.split("/"); if (bits.length == 2 && bits[0].equals(bits[1])) { verbatimEventDate = bits[0]; } } if (verbatimEventDate.matches("^[0-9]{4}[/][0-9]{2}[/][0-9]{2}-[0-9]{4}[/][0-9]{2}[/][0-9]{2}$")) { // if verbatim date is a range with identical first and last dates (-), use just one. // Example: 1982/12/11-1982/12/11 changed to 1982/12/11 String[] bits = verbatimEventDate.split("-"); if (bits.length == 2 && bits[0].equals(bits[1])) { verbatimEventDate = bits[0]; } } if (verbatimEventDate .matches("^[0-9]{1,2}[-. ][0-9]{1,2}[-. ][0-9]{4}/[0-9]{1,2}[-. ][0-9]{1,2}[-. ][0-9]{4}$")) { // if verbatim date is a range with identical first and last dates (/), use just one. // Example: 12-11-1982/12-11-1982 changed to 12-11-1982 String[] bits = verbatimEventDate.split("/"); if (bits.length == 2 && bits[0].equals(bits[1])) { verbatimEventDate = bits[0]; } } if (verbatimEventDate .matches("^[0-9]{1,2}[./ ][0-9]{1,2}[./ ][0-9]{4}[-][0-9]{1,2}[./ ][0-9]{1,2}[./ ][0-9]{4}$")) { // if verbatim date is a range with identical first and last dates (-), use just one. // Example: 12/11/1982-12/11/1982 changed to 12/11/1982 String[] bits = verbatimEventDate.split("-"); if (bits.length == 2 && bits[0].equals(bits[1])) { verbatimEventDate = bits[0]; } } if (verbatimEventDate.matches("^[0-9]{4}[-]([0-9]{1,2}|[A-Za-z]+)[-][0-9]{1,2}.*")) { // Both separators are the same. // Example 1982-02-05 // Example 1982-Feb-05 // Example 1982-02-05 // Example 1982-02-05T05:03:06 try { DateTimeParser[] parsers = { DateTimeFormat.forPattern("yyyy/MM/dd").getParser(), DateTimeFormat.forPattern("yyyy/MMM/dd").getParser(), DateTimeFormat.forPattern("yyyy-MMM-dd").getParser(), ISODateTimeFormat.dateOptionalTimeParser().getParser() }; DateTimeFormatter formatter = new DateTimeFormatterBuilder().append(null, parsers).toFormatter(); DateMidnight parseDate = LocalDate.parse(verbatimEventDate, formatter).toDateMidnight(); resultDate = parseDate.toString("yyyy-MM-dd"); result.setResultState(EventResult.EventQCResultState.DATE); result.setResult(resultDate); } catch (Exception e) { logger.debug(e.getMessage()); } } if (verbatimEventDate.matches("^[0-9]{4}[/]([0-9]{1,2}|[A-Za-z]+)[/][0-9]{1,2}.*")) { // Both separators are the same. // Example 1982/02/05 // Example 1982/Feb/05 // Example 1982-02-05 // Example 1982/02/05T05:03:06 try { DateTimeParser[] parsers = { DateTimeFormat.forPattern("yyyy/MM/dd").getParser(), DateTimeFormat.forPattern("yyyy/MMM/dd").getParser(), DateTimeFormat.forPattern("yyyy-MMM-dd").getParser(), ISODateTimeFormat.dateOptionalTimeParser().getParser() }; DateTimeFormatter formatter = new DateTimeFormatterBuilder().append(null, parsers).toFormatter(); DateMidnight parseDate = LocalDate.parse(verbatimEventDate, formatter).toDateMidnight(); resultDate = parseDate.toString("yyyy-MM-dd"); result.setResultState(EventResult.EventQCResultState.DATE); result.setResult(resultDate); } catch (Exception e) { logger.debug(e.getMessage()); } } if (verbatimEventDate.matches("^[0-9]{4}[.,][0-9]{1,2}[.,][0-9]{1,2}$")) { // Example 1982.02.05 // Example 1982,02,05 // Cases where the 1-2 digit numbers are both smaller than 12 are treated as ambiguous. String resultDateMD = null; String resultDateDM = null; DateMidnight parseDate1 = null; DateMidnight parseDate2 = null; try { DateTimeParser[] parsers = { DateTimeFormat.forPattern("yyyy.MM.dd").getParser(), DateTimeFormat.forPattern("yyyy,MM,dd").getParser(), DateTimeFormat.forPattern("yyyy,MM.dd").getParser(), DateTimeFormat.forPattern("yyyy.MM,dd").getParser() }; DateTimeFormatter formatter = new DateTimeFormatterBuilder().append(null, parsers).toFormatter(); parseDate1 = LocalDate.parse(verbatimEventDate, formatter).toDateMidnight(); resultDateMD = parseDate1.toString("yyyy-MM-dd"); } catch (Exception e) { logger.debug(e.getMessage()); } try { DateTimeParser[] parsers = { DateTimeFormat.forPattern("yyyy.dd.MM").getParser(), DateTimeFormat.forPattern("yyyy,dd,MM").getParser(), DateTimeFormat.forPattern("yyyy,dd.MM").getParser(), DateTimeFormat.forPattern("yyyy.dd,MM").getParser() }; DateTimeFormatter formatter = new DateTimeFormatterBuilder().append(null, parsers).toFormatter(); parseDate2 = LocalDate.parse(verbatimEventDate, formatter).toDateMidnight(); resultDateDM = parseDate2.toString("yyyy-MM-dd"); } catch (Exception e) { logger.debug(e.getMessage()); } if (resultDateMD != null && resultDateDM == null) { result.setResultState(EventResult.EventQCResultState.DATE); result.setResult(resultDateMD); } else if (resultDateMD == null && resultDateDM != null) { result.setResultState(EventResult.EventQCResultState.DATE); result.setResult(resultDateDM); } else if (resultDateMD != null && resultDateDM != null) { if (resultDateMD.equals(resultDateDM)) { result.setResultState(EventResult.EventQCResultState.DATE); result.setResult(resultDateDM); } else { result.setResultState(EventResult.EventQCResultState.AMBIGUOUS); Interval range = null; if (parseDate1.isBefore(parseDate2)) { result.setResult(resultDateMD + "/" + resultDateDM); } else { result.setResult(resultDateDM + "/" + resultDateMD); } } } } if (verbatimEventDate.matches("^[0-9]{1,2}[-/ ][0-9]{4}")) { // Example 02/1982 try { DateTimeParser[] parsers = { DateTimeFormat.forPattern("MM-yyyy").getParser(), DateTimeFormat.forPattern("MM/yyyy").getParser(), DateTimeFormat.forPattern("MM yyyy").getParser() }; DateTimeFormatter formatter = new DateTimeFormatterBuilder().append(null, parsers).toFormatter(); DateMidnight parseDate = LocalDate.parse(verbatimEventDate, formatter).toDateMidnight(); resultDate = parseDate.toString("yyyy-MM"); result.setResultState(EventResult.EventQCResultState.RANGE); result.setResult(resultDate); } catch (Exception e) { logger.debug(e.getMessage()); } } if (verbatimEventDate.matches("^[0-9]{4}[0-9]{1,2}[0-9]{1,2}[?]$")) { // Example: 19720325 try { DateTimeParser[] parsers = { DateTimeFormat.forPattern("yyyyMMdd").getParser(), DateTimeFormat.forPattern("yyyyMMdd?").getParser(), ISODateTimeFormat.dateOptionalTimeParser().getParser() }; DateTimeFormatter formatter = new DateTimeFormatterBuilder().append(null, parsers).toFormatter() .withLocale(Locale.CHINESE); DateMidnight parseDate = LocalDate.parse(verbatimEventDate, formatter).toDateMidnight(); resultDate = parseDate.toString("yyyy-MM-dd"); result.setResultState(EventResult.EventQCResultState.DATE); result.setResult(resultDate); } catch (Exception e) { logger.debug(e.getMessage()); } } if (verbatimEventDate.matches("^[0-9]{4}[-][0-9]{3}/[0-9]{4}[-][0-9]{3}$")) { // Example: 1982-145 try { String[] bits = verbatimEventDate.split("/"); DateTimeParser[] parsers = { DateTimeFormat.forPattern("yyyy-D").getParser() }; DateTimeFormatter formatter = new DateTimeFormatterBuilder().append(null, parsers).toFormatter(); LocalDate parseStartDate = LocalDate.parse(bits[0], formatter); LocalDate parseEndDate = LocalDate.parse(bits[1], formatter); resultDate = parseStartDate.toString("yyyy-MM-dd") + "/" + parseEndDate.toString("yyyy-MM-dd"); logger.debug(resultDate); result.setResultState(EventResult.EventQCResultState.RANGE); result.setResult(resultDate); } catch (Exception e) { logger.debug(e.getMessage()); } } if (result.getResultState().equals(EventResult.EventQCResultState.NOT_RUN) && verbatimEventDate.matches("^[0-9]{4}0000$")) { // case 19800000 verbatimEventDate = verbatimEventDate.substring(0, 4); } if (result.getResultState().equals(EventResult.EventQCResultState.NOT_RUN) && verbatimEventDate.matches("^[0-9]{4}$")) { // Example: 1962 try { DateTimeParser[] parsers = { DateTimeFormat.forPattern("yyyy").getParser(), }; DateTimeFormatter formatter = new DateTimeFormatterBuilder().append(null, parsers).toFormatter(); DateMidnight parseDate = LocalDate.parse(verbatimEventDate, formatter).toDateMidnight(); resultDate = parseDate.toString("yyyy"); result.setResultState(EventResult.EventQCResultState.RANGE); result.setResult(resultDate); } catch (Exception e) { logger.debug(e.getMessage()); } } if (result.getResultState().equals(EventResult.EventQCResultState.NOT_RUN) && verbatimEventDate.matches("^[12][0-9]{1}00[']{0,1}s$")) { // Example: 1900s try { String verbatimEventDateDelta = verbatimEventDate.replace("'s", "s"); DateTimeParser[] parsers = { DateTimeFormat.forPattern("yyyy's").getParser(), }; DateTimeFormatter formatter = new DateTimeFormatterBuilder().append(null, parsers).toFormatter(); DateMidnight parseDate = LocalDate.parse(verbatimEventDateDelta, formatter).toDateMidnight(); DateMidnight endDate = parseDate.plusYears(100).minusDays(1); resultDate = parseDate.toString("yyyy") + "-01-01/" + endDate.toString("yyyy") + "-12-31"; result.setResultState(EventResult.EventQCResultState.RANGE); result.setResult(resultDate); } catch (Exception e) { logger.debug(e.getMessage()); } } if (result.getResultState().equals(EventResult.EventQCResultState.NOT_RUN) && verbatimEventDate.matches("^[12][0-9]{2}0[']{0,1}s$")) { // Example: 1970s try { String verbatimEventDateDelta = verbatimEventDate.replace("'s", "s"); DateTimeParser[] parsers = { DateTimeFormat.forPattern("yyyy's").getParser(), }; DateTimeFormatter formatter = new DateTimeFormatterBuilder().append(null, parsers).toFormatter(); DateMidnight parseDate = LocalDate.parse(verbatimEventDateDelta, formatter).toDateMidnight(); DateMidnight endDate = parseDate.plusYears(10).minusDays(1); resultDate = parseDate.toString("yyyy") + "-01-01/" + endDate.toString("yyyy") + "-12-31"; result.setResultState(EventResult.EventQCResultState.RANGE); result.setResult(resultDate); } catch (Exception e) { logger.debug(e.getMessage()); } } if (result.getResultState().equals(EventResult.EventQCResultState.NOT_RUN) && verbatimEventDate.matches("^[A-Za-z]{3,9}[.]{0,1}[ ]{0,1}[-/ ][0-9]{4}$")) { // Example: Jan-1980 // Example: Jan./1980 // Example: January 1980 try { DateTimeParser[] parsers = { DateTimeFormat.forPattern("MMM-yyyy").getParser(), DateTimeFormat.forPattern("MMM/yyyy").getParser(), DateTimeFormat.forPattern("MMM /yyyy").getParser(), DateTimeFormat.forPattern("MMM yyyy").getParser() }; DateTimeFormatter formatter = new DateTimeFormatterBuilder().append(null, parsers).toFormatter(); String cleaned = verbatimEventDate.replace(".", ""); DateMidnight parseDate = LocalDate.parse(cleaned, formatter).toDateMidnight(); resultDate = parseDate.toString("yyyy-MM"); result.setResultState(EventResult.EventQCResultState.RANGE); result.setResult(resultDate); } catch (Exception e) { logger.debug(e.getMessage()); } } if (result.getResultState().equals(EventResult.EventQCResultState.NOT_RUN)) { // Example: 04/03/1994 (ambiguous) // Example: 04/20/1994 // Example: 20/04/1994 String resultDateMD = null; String resultDateDM = null; DateMidnight parseDate1 = null; DateMidnight parseDate2 = null; if (assumemmddyyyy == null || assumemmddyyyy) { try { DateTimeParser[] parsers = { DateTimeFormat.forPattern("MM/dd/yyyy").getParser(), DateTimeFormat.forPattern("MM/dd yyyy").getParser(), DateTimeFormat.forPattern("MM/dd-yyyy").getParser(), DateTimeFormat.forPattern("MM/dd, yyyy").getParser(), DateTimeFormat.forPattern("MM/dd,yyyy").getParser(), DateTimeFormat.forPattern("MM dd yyyy").getParser(), DateTimeFormat.forPattern("MM-dd-yyyy").getParser(), DateTimeFormat.forPattern("MM.dd.yyyy").getParser(), DateTimeFormat.forPattern("MM. dd. yyyy").getParser(), DateTimeFormat.forPattern("MM. dd. yyyy.").getParser() }; DateTimeFormatter formatter = new DateTimeFormatterBuilder().append(null, parsers) .toFormatter(); parseDate1 = LocalDate.parse(verbatimEventDate, formatter).toDateMidnight(); resultDateMD = parseDate1.toString("yyyy-MM-dd"); } catch (Exception e) { logger.debug(e.getMessage()); } } if (assumemmddyyyy == null || !assumemmddyyyy) { try { DateTimeParser[] parsers = { DateTimeFormat.forPattern("dd/MM/yyyy").getParser(), DateTimeFormat.forPattern("dd/MM yyyy").getParser(), DateTimeFormat.forPattern("dd/MM-yyyy").getParser(), DateTimeFormat.forPattern("dd/MM, yyyy").getParser(), DateTimeFormat.forPattern("dd/MM,yyyy").getParser(), DateTimeFormat.forPattern("dd MM yyyy").getParser(), DateTimeFormat.forPattern("dd-MM-yyyy").getParser(), DateTimeFormat.forPattern("dd.MM.yyyy").getParser(), DateTimeFormat.forPattern("dd. MM. yyyy").getParser(), DateTimeFormat.forPattern("dd. MM. yyyy.").getParser() }; DateTimeFormatter formatter = new DateTimeFormatterBuilder().append(null, parsers) .toFormatter(); parseDate2 = LocalDate.parse(verbatimEventDate, formatter).toDateMidnight(); resultDateDM = parseDate2.toString("yyyy-MM-dd"); } catch (Exception e) { logger.debug(e.getMessage()); } } if (resultDateMD != null && resultDateDM == null) { result.setResultState(EventResult.EventQCResultState.DATE); result.setResult(resultDateMD); } else if (resultDateMD == null && resultDateDM != null) { result.setResultState(EventResult.EventQCResultState.DATE); result.setResult(resultDateDM); } else if (resultDateMD != null && resultDateDM != null) { if (resultDateMD.equals(resultDateDM)) { result.setResultState(EventResult.EventQCResultState.DATE); result.setResult(resultDateDM); } else { result.setResultState(EventResult.EventQCResultState.AMBIGUOUS); Interval range = null; if (parseDate1.isBefore(parseDate2)) { result.setResult(resultDateMD + "/" + resultDateDM); } else { result.setResult(resultDateDM + "/" + resultDateMD); } } } } if (result.getResultState().equals(EventResult.EventQCResultState.NOT_RUN) && verbatimEventDate.matches("^([0-9]{1,2}|[A-Za-z]+)[-/.]([0-9]{1,2}|[A-Za-z]+)[-/. ][0-9]{4}$")) { // Example: 03/Jan/1982 // Example: Jan-03-1982 try { DateTimeParser[] parsers = { DateTimeFormat.forPattern("MMM/dd/yyyy").getParser(), DateTimeFormat.forPattern("dd/MMM/yyyy").getParser(), DateTimeFormat.forPattern("MMM/dd yyyy").getParser(), DateTimeFormat.forPattern("dd/MMM yyyy").getParser(), DateTimeFormat.forPattern("MMM-dd-yyyy").getParser(), DateTimeFormat.forPattern("dd-MMM-yyyy").getParser(), DateTimeFormat.forPattern("MMM-dd yyyy").getParser(), DateTimeFormat.forPattern("dd-MMM yyyy").getParser(), DateTimeFormat.forPattern("MMM.dd.yyyy").getParser(), DateTimeFormat.forPattern("dd.MMM.yyyy").getParser(), DateTimeFormat.forPattern("MM.dd.yyyy").getParser(), DateTimeFormat.forPattern("dd.MM.yyyy").getParser() }; DateTimeFormatter formatter = new DateTimeFormatterBuilder().append(null, parsers).toFormatter(); DateMidnight parseDate = LocalDate.parse(verbatimEventDate, formatter.withLocale(Locale.ENGLISH)) .toDateMidnight(); resultDate = parseDate.toString("yyyy-MM-dd"); result.setResultState(EventResult.EventQCResultState.DATE); result.setResult(resultDate); } catch (Exception e) { logger.debug(e.getMessage()); } } if (result.getResultState().equals(EventResult.EventQCResultState.NOT_RUN) && verbatimEventDate.matches("^[X*]{2}[-/. ]([0-9]{1,2}|[A-Za-z]+)[-/. ][0-9]{4}$")) { // Example: XX-04-1982 (XX for day) // Example: XX-Jan-1995 try { DateTimeParser[] parsers = { DateTimeFormat.forPattern("MMM/yyyy").getParser(), DateTimeFormat.forPattern("MMM yyyy").getParser(), DateTimeFormat.forPattern("MMM-yyyy").getParser(), DateTimeFormat.forPattern("MMM yyyy").getParser(), DateTimeFormat.forPattern("MMM.yyyy").getParser(), DateTimeFormat.forPattern("MM.yyyy").getParser() }; DateTimeFormatter formatter = new DateTimeFormatterBuilder().append(null, parsers).toFormatter(); DateMidnight parseDate = LocalDate .parse(verbatimEventDate.substring(3), formatter.withLocale(Locale.ENGLISH)) .toDateMidnight(); resultDate = parseDate.toString("yyyy-MM"); result.setResultState(EventResult.EventQCResultState.RANGE); result.setResult(resultDate); } catch (Exception e) { logger.debug(e.getMessage()); } } if (result.getResultState().equals(EventResult.EventQCResultState.NOT_RUN) && verbatimEventDate.matches("^[X*]{2}[-/. ][X*]{2,3}[-/. ][0-9]{4}$")) { // Example: XX-XXX-1995 // Example: **-**-1995 try { DateTimeParser[] parsers = { DateTimeFormat.forPattern("yyyy").getParser(), }; DateTimeFormatter formatter = new DateTimeFormatterBuilder().append(null, parsers).toFormatter(); String yearBit = verbatimEventDate.substring(verbatimEventDate.length() - 4); DateMidnight parseDate = LocalDate.parse(yearBit, formatter.withLocale(Locale.ENGLISH)) .toDateMidnight(); resultDate = parseDate.toString("yyyy"); result.setResultState(EventResult.EventQCResultState.RANGE); result.setResult(resultDate); } catch (Exception e) { logger.debug(e.getMessage()); } } if (verbatimEventDate.matches("^[0-9]{4}[-][0-9]{3}$")) { // Example: 1994-128 (three digits after year = day of year). if (result.getResultState().equals(EventResult.EventQCResultState.NOT_RUN)) { try { DateTimeParser[] parsers = { DateTimeFormat.forPattern("yyyy-D").getParser() }; DateTimeFormatter formatter = new DateTimeFormatterBuilder().append(null, parsers) .toFormatter(); LocalDate parseDate = LocalDate.parse(verbatimEventDate, formatter); resultDate = parseDate.toString("yyyy-MM-dd"); logger.debug(resultDate); result.setResultState(EventResult.EventQCResultState.DATE); result.setResult(resultDate); } catch (Exception e) { logger.debug(e.getMessage()); } } } if (result.getResultState().equals(EventResult.EventQCResultState.NOT_RUN)) { try { // Example: 1983-15 (two digits after year may fall into subsequent blocks). // Example: 1933-Mar DateTimeParser[] parsers = { DateTimeFormat.forPattern("yyyy/M").getParser(), DateTimeFormat.forPattern("yyyy-M").getParser(), DateTimeFormat.forPattern("yyyy-MMM").getParser(), DateTimeFormat.forPattern("yyyy.MMM").getParser(), DateTimeFormat.forPattern("yyyy.MMM.").getParser(), DateTimeFormat.forPattern("yyyy MMM.").getParser(), DateTimeFormat.forPattern("yyyy MMM").getParser(), DateTimeFormat.forPattern("yyyy. MMM.").getParser(), DateTimeFormat.forPattern("yyyy. MMM").getParser(), DateTimeFormat.forPattern("yyyy/MMM").getParser() }; DateTimeFormatter formatter = new DateTimeFormatterBuilder().append(null, parsers).toFormatter(); String cleaned = cleanMonth(verbatimEventDate); LocalDate parseDate = LocalDate.parse(cleaned, formatter.withLocale(Locale.ENGLISH)); resultDate = parseDate.toString("yyyy-MM"); // resultDate = parseDate.dayOfMonth().withMinimumValue() + "/" + parseDate.dayOfMonth().withMaximumValue(); logger.debug(resultDate); if (verbatimEventDate.matches("^[0-9]{4}[-][0-9]{2}$")) { String century = verbatimEventDate.substring(0, 2); String startBit = verbatimEventDate.substring(0, 4); String endBit = verbatimEventDate.substring(5, 7); // 1815-16 won't parse here, passes to next block // 1805-06 could be month or abbreviated year // 1805-03 should to be month if (Integer.parseInt(startBit) >= Integer.parseInt(century + endBit)) { result.setResultState(EventResult.EventQCResultState.RANGE); result.setResult(resultDate); } else { result.setResultState(EventResult.EventQCResultState.SUSPECT); result.setResult(resultDate); } } else { result.setResultState(EventResult.EventQCResultState.RANGE); result.setResult(resultDate); } } catch (Exception e) { logger.debug(e.getMessage()); } } if (result.getResultState().equals(EventResult.EventQCResultState.NOT_RUN) && verbatimEventDate.matches("^[0-9]{4}[-][0-9]{2}$")) { // Example: 1884-85 (two digits look like year later in century). try { String century = verbatimEventDate.substring(0, 2); String startBit = verbatimEventDate.substring(0, 4); String endBit = verbatimEventDate.substring(5, 7); String assembly = startBit + "/" + century + endBit; logger.debug(assembly); Interval parseDate = Interval.parse(assembly); logger.debug(parseDate); resultDate = parseDate.getStart().toString("yyyy") + "/" + parseDate.getEnd().toString("yyyy"); result.setResultState(EventResult.EventQCResultState.RANGE); result.setResult(resultDate); } catch (Exception e) { logger.debug(e.getMessage()); } } if (result.getResultState().equals(EventResult.EventQCResultState.NOT_RUN) && verbatimEventDate.matches("^[0-9]{4}[0-9]{2}[0-9]{2}$") && !verbatimEventDate.endsWith("0000")) { // Example: 19950315 try { DateTimeParser[] parsers = { DateTimeFormat.forPattern("yyyyMMdd").getParser() }; DateTimeFormatter formatter = new DateTimeFormatterBuilder().append(null, parsers).toFormatter(); DateMidnight parseDate = LocalDate.parse(verbatimEventDate, formatter.withLocale(Locale.ENGLISH)) .toDateMidnight(); resultDate = parseDate.toString("yyyy-MM-dd"); result.setResultState(EventResult.EventQCResultState.DATE); result.setResult(resultDate); } catch (Exception e) { logger.debug(e.getMessage()); } } if (result.getResultState().equals(EventResult.EventQCResultState.NOT_RUN)) { // Example: 1845 try { DateTimeParser[] parsers = { DateTimeFormat.forPattern("yyyy").getParser() }; DateTimeFormatter formatter = new DateTimeFormatterBuilder().append(null, parsers).toFormatter(); LocalDate parseDate = LocalDate.parse(verbatimEventDate, formatter); resultDate = parseDate.dayOfYear().withMinimumValue() + "/" + parseDate.dayOfYear().withMaximumValue(); logger.debug(resultDate); result.setResultState(EventResult.EventQCResultState.RANGE); result.setResult(resultDate); } catch (Exception e) { logger.debug(e.getMessage()); } } if (result.getResultState().equals(EventResult.EventQCResultState.NOT_RUN)) { // Multiple yyyy-mmm-ddd, mmm-dd-yyyy, dd-mmm-yyyy patterns. try { DateTimeParser[] parsers = { DateTimeFormat.forPattern("yyyy MMM dd").getParser(), DateTimeFormat.forPattern("yyyy MMM. dd").getParser(), DateTimeFormat.forPattern("yyyy, MMM dd").getParser(), DateTimeFormat.forPattern("yyyy, MMM. dd").getParser(), DateTimeFormat.forPattern("yyyy.MMM.dd").getParser(), DateTimeFormat.forPattern("yyyy.MMM.dd.").getParser(), DateTimeFormat.forPattern("yyyy. MMM. dd").getParser(), DateTimeFormat.forPattern("yyyy. MMM. dd.").getParser(), DateTimeFormat.forPattern("yyyy. MMM dd.").getParser(), DateTimeFormat.forPattern("yyyy. MMM dd").getParser(), DateTimeFormat.forPattern("yyyy MMM. dd.").getParser(), DateTimeFormat.forPattern("yyyy: MMM. dd.").getParser(), DateTimeFormat.forPattern("yyyy: MMM. dd").getParser(), DateTimeFormat.forPattern("yyyy: MMM dd").getParser(), DateTimeFormat.forPattern("yyyy:MMM dd").getParser(), DateTimeFormat.forPattern("yyyy:MMM. dd").getParser(), DateTimeFormat.forPattern("yyyy:MMM.dd").getParser(), DateTimeFormat.forPattern("yyyy MMM dd'st'").getParser(), DateTimeFormat.forPattern("yyyy MMM. dd'st'").getParser(), DateTimeFormat.forPattern("yyyy MMM dd'nd'").getParser(), DateTimeFormat.forPattern("yyyy MMM. dd'nd'").getParser(), DateTimeFormat.forPattern("yyyy MMM dd'rd'").getParser(), DateTimeFormat.forPattern("yyyy MMM. dd'rd'").getParser(), DateTimeFormat.forPattern("yyyy MMM dd'th'").getParser(), DateTimeFormat.forPattern("yyyy MMM. dd'th'").getParser(), DateTimeFormat.forPattern("MMM dd, yyyy").getParser(), DateTimeFormat.forPattern("MMM dd., yyyy").getParser(), DateTimeFormat.forPattern("MMMdd, yyyy").getParser(), DateTimeFormat.forPattern("MMM dd'st', yyyy").getParser(), DateTimeFormat.forPattern("MMM dd'nd', yyyy").getParser(), DateTimeFormat.forPattern("MMM dd'rd', yyyy").getParser(), DateTimeFormat.forPattern("MMM dd'd', yyyy").getParser(), DateTimeFormat.forPattern("MMM dd'th', yyyy").getParser(), DateTimeFormat.forPattern("MMM. dd, yyyy").getParser(), DateTimeFormat.forPattern("MMM.dd, yyyy").getParser(), DateTimeFormat.forPattern("MMM. dd'st', yyyy").getParser(), DateTimeFormat.forPattern("MMM. dd'nd', yyyy").getParser(), DateTimeFormat.forPattern("MMM. dd'rd', yyyy").getParser(), DateTimeFormat.forPattern("MMM. dd'th', yyyy").getParser(), DateTimeFormat.forPattern("MMM.dd,yyyy").getParser(), DateTimeFormat.forPattern("MMM.dd'st',yyyy").getParser(), DateTimeFormat.forPattern("MMM.dd'nd',yyyy").getParser(), DateTimeFormat.forPattern("MMM.dd'rd',yyyy").getParser(), DateTimeFormat.forPattern("MMM.dd'd',yyyy").getParser(), DateTimeFormat.forPattern("MMM.dd'th',yyyy").getParser(), DateTimeFormat.forPattern("MMM.dd.yyyy").getParser(), DateTimeFormat.forPattern("MMM.dd'st'.yyyy").getParser(), DateTimeFormat.forPattern("MMM.dd'nd'.yyyy").getParser(), DateTimeFormat.forPattern("MMM.dd'rd'.yyyy").getParser(), DateTimeFormat.forPattern("MMM.dd'd'.yyyy").getParser(), DateTimeFormat.forPattern("MMM.dd'th'.yyyy").getParser(), DateTimeFormat.forPattern("MMM. dd'st'. yyyy").getParser(), DateTimeFormat.forPattern("MMM. dd'nd'. yyyy").getParser(), DateTimeFormat.forPattern("MMM. dd'rd'. yyyy").getParser(), DateTimeFormat.forPattern("MMM. dd'd'. yyyy").getParser(), DateTimeFormat.forPattern("MMM. dd'th'. yyyy").getParser(), DateTimeFormat.forPattern("MMM dd'st'. yyyy").getParser(), DateTimeFormat.forPattern("MMM dd'nd'. yyyy").getParser(), DateTimeFormat.forPattern("MMM dd'rd'. yyyy").getParser(), DateTimeFormat.forPattern("MMM dd'd'. yyyy").getParser(), DateTimeFormat.forPattern("MMM dd'th'. yyyy").getParser(), DateTimeFormat.forPattern("MMM dd'st'.yyyy").getParser(), DateTimeFormat.forPattern("MMM dd'nd'.yyyy").getParser(), DateTimeFormat.forPattern("MMM dd'rd'.yyyy").getParser(), DateTimeFormat.forPattern("MMM dd'd'.yyyy").getParser(), DateTimeFormat.forPattern("MMM dd'th'.yyyy").getParser(), DateTimeFormat.forPattern("MMM-dd-yyyy").getParser(), DateTimeFormat.forPattern("MMM-dd yyyy").getParser(), DateTimeFormat.forPattern("MMM-dd, yyyy").getParser(), DateTimeFormat.forPattern("dd-MMM-yyyy").getParser(), DateTimeFormat.forPattern("dd.MMM.yyyy").getParser(), DateTimeFormat.forPattern("dd,MMM,yyyy").getParser(), DateTimeFormat.forPattern("dd.MMM.,yyyy").getParser(), DateTimeFormat.forPattern("dd. MMM.,yyyy").getParser(), DateTimeFormat.forPattern("MMM. dd. yyyy").getParser(), DateTimeFormat.forPattern("MMM, dd yyyy").getParser(), DateTimeFormat.forPattern("MMM, dd. yyyy").getParser(), DateTimeFormat.forPattern("MMM, dd, yyyy").getParser(), DateTimeFormat.forPattern("MMM, dd., yyyy").getParser(), DateTimeFormat.forPattern("MMM. dd yyyy").getParser(), DateTimeFormat.forPattern("MMM. dd, yyyy").getParser(), DateTimeFormat.forPattern("MMM. dd/yyyy").getParser(), DateTimeFormat.forPattern("MMM dd,yyyy").getParser(), DateTimeFormat.forPattern("MMM dd, yyyy").getParser(), DateTimeFormat.forPattern("MMM. dd,yyyy").getParser(), DateTimeFormat.forPattern("MMM. dd-yyyy").getParser(), DateTimeFormat.forPattern("MMM.dd-yyyy").getParser(), DateTimeFormat.forPattern("MMM. dd, yyyy").getParser(), DateTimeFormat.forPattern("MMM. dd., yyyy").getParser(), DateTimeFormat.forPattern("MMM., dd, yyyy").getParser(), DateTimeFormat.forPattern("MMM.,dd, yyyy").getParser(), DateTimeFormat.forPattern("MMM. dd yyyy").getParser(), DateTimeFormat.forPattern("MMM. dd'' yyyy").getParser(), DateTimeFormat.forPattern("MMM dd'' yyyy").getParser(), DateTimeFormat.forPattern("dd. MMM. yyyy").getParser(), DateTimeFormat.forPattern("dd. MMM.yyyy").getParser(), DateTimeFormat.forPattern("dd MMM., yyyy").getParser(), DateTimeFormat.forPattern("dd MMM.,yyyy").getParser(), DateTimeFormat.forPattern("dd MMM,.yyyy").getParser(), DateTimeFormat.forPattern("dd MMM,. yyyy").getParser(), DateTimeFormat.forPattern("dd MMM..yyyy").getParser(), DateTimeFormat.forPattern("dd MMM, yyyy").getParser(), DateTimeFormat.forPattern("dd MMM yyyy").getParser(), DateTimeFormat.forPattern("dd MMM,yyyy").getParser(), DateTimeFormat.forPattern("dd MMM.yyyy").getParser(), DateTimeFormat.forPattern("ddMMM.yyyy").getParser(), DateTimeFormat.forPattern("ddMMM. yyyy").getParser(), DateTimeFormat.forPattern("dd.MMM-yyyy").getParser(), DateTimeFormat.forPattern("dd-MMM-yyyy").getParser(), DateTimeFormat.forPattern("dd.MMM yyyy").getParser(), DateTimeFormat.forPattern("dd. MMM yyyy").getParser(), DateTimeFormat.forPattern("dd, MMM, yyyy").getParser(), DateTimeFormat.forPattern("dd, MMM; yyyy").getParser(), DateTimeFormat.forPattern("dd. MMM; yyyy").getParser(), DateTimeFormat.forPattern("dd MMM-yyyy").getParser(), DateTimeFormat.forPattern("dd-MMM yyyy").getParser(), DateTimeFormat.forPattern("ddMMMyyyy").getParser(), DateTimeFormat.forPattern("MMM dd yyyy").getParser(), DateTimeFormat.forPattern("MMM dd/yyyy").getParser(), DateTimeFormat.forPattern("MMM dd'st' yyyy").getParser(), DateTimeFormat.forPattern("MMM dd'nd' yyyy").getParser(), DateTimeFormat.forPattern("MMM dd'rd' yyyy").getParser(), DateTimeFormat.forPattern("MMM dd'd' yyyy").getParser(), DateTimeFormat.forPattern("MMM dd'th' yyyy").getParser(), DateTimeFormat.forPattern("MMM. dd yyyy").getParser(), DateTimeFormat.forPattern("MMM. dd'st' yyyy").getParser(), DateTimeFormat.forPattern("MMM. dd'nd' yyyy").getParser(), DateTimeFormat.forPattern("MMM. dd'rd' yyyy").getParser(), DateTimeFormat.forPattern("MMM. dd'd' yyyy").getParser(), DateTimeFormat.forPattern("MMM. dd'th' yyyy").getParser(), DateTimeFormat.forPattern("MMMdd yyyy").getParser(), DateTimeFormat.forPattern("MMM.dd yyyy").getParser(), DateTimeFormat.forPattern("dd MMM, yyyy").getParser(), DateTimeFormat.forPattern("dd'st' MMM, yyyy").getParser(), DateTimeFormat.forPattern("dd'nd' MMM, yyyy").getParser(), DateTimeFormat.forPattern("dd'rd' MMM, yyyy").getParser(), DateTimeFormat.forPattern("dd'd' MMM, yyyy").getParser(), DateTimeFormat.forPattern("dd'th MMM', yyyy").getParser(), DateTimeFormat.forPattern("dd MMM., yyyy").getParser(), DateTimeFormat.forPattern("dd'st' MMM., yyyy").getParser(), DateTimeFormat.forPattern("dd'nd' MMM., yyyy").getParser(), DateTimeFormat.forPattern("dd'rd' MMM., yyyy").getParser(), DateTimeFormat.forPattern("dd'th' MMM., yyyy").getParser(), DateTimeFormat.forPattern("dd MMM yyyy").getParser(), DateTimeFormat.forPattern("dd'st' MMM yyyy").getParser(), DateTimeFormat.forPattern("dd'nd' MMM yyyy").getParser(), DateTimeFormat.forPattern("dd'rd' MMM yyyy").getParser(), DateTimeFormat.forPattern("dd'd' MMM yyyy").getParser(), DateTimeFormat.forPattern("dd'th' MMM yyyy").getParser(), DateTimeFormat.forPattern("dd MMM. yyyy").getParser(), DateTimeFormat.forPattern("dd'st' MMM. yyyy").getParser(), DateTimeFormat.forPattern("dd'nd' MMM. yyyy").getParser(), DateTimeFormat.forPattern("dd'rd' MMM. yyyy").getParser(), DateTimeFormat.forPattern("dd'd' MMM. yyyy").getParser(), DateTimeFormat.forPattern("dd'th' MMM. yyyy").getParser(), DateTimeFormat.forPattern("dd'st' MMM, yyyy").getParser(), DateTimeFormat.forPattern("dd'nd' MMM, yyyy").getParser(), DateTimeFormat.forPattern("dd'rd' MMM, yyyy").getParser(), DateTimeFormat.forPattern("dd'd' MMM, yyyy").getParser(), DateTimeFormat.forPattern("dd'th' MMM, yyyy").getParser(), DateTimeFormat.forPattern("dd/MMM/yyyy").getParser(), DateTimeFormat.forPattern("dd/MMM yyyy").getParser(), DateTimeFormat.forPattern("MMM/dd yyyy").getParser(), DateTimeFormat.forPattern("MMM/dd/yyyy").getParser(), DateTimeFormat.forPattern("MMM dd. yyyy").getParser(), DateTimeFormat.forPattern("MMM dd'st'. yyyy").getParser(), DateTimeFormat.forPattern("MMM dd'nd'. yyyy").getParser(), DateTimeFormat.forPattern("MMM dd'rd'. yyyy").getParser(), DateTimeFormat.forPattern("MMM dd'th'. yyyy").getParser(), DateTimeFormat.forPattern("MMM. dd. yyyy").getParser(), DateTimeFormat.forPattern("MMM. dd'st'. yyyy").getParser(), DateTimeFormat.forPattern("MMM. dd'nd'. yyyy").getParser(), DateTimeFormat.forPattern("MMM. dd'rd'. yyyy").getParser(), DateTimeFormat.forPattern("MMM. dd'th'. yyyy").getParser(), DateTimeFormat.forPattern("MMM dd.yyyy").getParser(), DateTimeFormat.forPattern("MMM. dd.yyyy").getParser(), DateTimeFormat.forPattern("MMM. dd-yyyy").getParser(), DateTimeFormat.forPattern("MMM. dd'st'-yyyy").getParser(), DateTimeFormat.forPattern("MMM. dd'nd'-yyyy").getParser(), DateTimeFormat.forPattern("MMM. dd'rd'-yyyy").getParser(), DateTimeFormat.forPattern("MMM. dd'th'-yyyy").getParser(), DateTimeFormat.forPattern("MMM dd-yyyy").getParser(), DateTimeFormat.forPattern("MMM dd'st'-yyyy").getParser(), DateTimeFormat.forPattern("MMM dd'nd'-yyyy").getParser(), DateTimeFormat.forPattern("MMM dd'rd'-yyyy").getParser(), DateTimeFormat.forPattern("MMM dd'th'-yyyy").getParser(), DateTimeFormat.forPattern("yyyy-MMM-dd").getParser() }; DateTimeFormatter formatter = new DateTimeFormatterBuilder().append(null, parsers).toFormatter(); String cleaned = cleanMonth(verbatimEventDate); cleaned = cleaned.replace("''", "'"); try { // Specify English locale, or local default will be used LocalDate parseDate = LocalDate.parse(cleaned, formatter.withLocale(Locale.ENGLISH)); resultDate = parseDate.toString("yyyy-MM-dd"); } catch (Exception e) { try { logger.debug(e.getMessage()); LocalDate parseDate = LocalDate.parse(cleaned, formatter.withLocale(Locale.FRENCH)); resultDate = parseDate.toString("yyyy-MM-dd"); } catch (Exception e1) { try { logger.debug(e1.getMessage()); LocalDate parseDate = LocalDate.parse(cleaned, formatter.withLocale(Locale.ITALIAN)); resultDate = parseDate.toString("yyyy-MM-dd"); } catch (Exception e2) { try { logger.debug(e2.getMessage()); LocalDate parseDate = LocalDate.parse(cleaned, formatter.withLocale(Locale.GERMAN)); resultDate = parseDate.toString("yyyy-MM-dd"); } catch (Exception e3) { try { logger.debug(e2.getMessage()); LocalDate parseDate = LocalDate.parse(cleaned, formatter.withLocale(Locale.forLanguageTag("es"))); resultDate = parseDate.toString("yyyy-MM-dd"); } catch (Exception e4) { logger.debug(e2.getMessage()); LocalDate parseDate = LocalDate.parse(cleaned, formatter.withLocale(Locale.forLanguageTag("pt"))); resultDate = parseDate.toString("yyyy-MM-dd"); } } } } } logger.debug(resultDate); result.setResultState(EventResult.EventQCResultState.DATE); result.setResult(resultDate); } catch (Exception e) { logger.debug(e.getMessage()); } } logger.debug(result.getResultState()); if (result.getResultState().equals(EventResult.EventQCResultState.NOT_RUN)) { // Example: jan.-1992 // Example: January 1992 if (verbatimEventDate.matches(".*[0-9]{4}.*")) { try { DateTimeParser[] parsers = { DateTimeFormat.forPattern("MMM, yyyy").getParser(), DateTimeFormat.forPattern("MMM., yyyy").getParser(), DateTimeFormat.forPattern("MMM.,yyyy").getParser(), DateTimeFormat.forPattern("MMM.-yyyy").getParser(), DateTimeFormat.forPattern("MMM.yyyy").getParser(), DateTimeFormat.forPattern("MMM. yyyy").getParser(), DateTimeFormat.forPattern("MMM-yyyy").getParser(), DateTimeFormat.forPattern("MMM -yyyy").getParser(), DateTimeFormat.forPattern("MMM yyyy").getParser(), DateTimeFormat.forPattern("MMM/yyyy").getParser() }; DateTimeFormatter formatter = new DateTimeFormatterBuilder().append(null, parsers) .toFormatter(); String cleaned = cleanMonth(verbatimEventDate); // Strip off a trailing period after a final year if (cleaned.matches("^.*[0-9]{4}[.]$")) { cleaned = cleaned.replaceAll("[.]$", ""); } LocalDate parseDate = LocalDate.parse(cleaned, formatter.withLocale(Locale.ENGLISH)); resultDate = parseDate.toString("yyyy-MM"); logger.debug(resultDate); result.setResultState(EventResult.EventQCResultState.RANGE); result.setResult(resultDate); } catch (Exception e) { logger.debug(e.getMessage()); } } } if (result.getResultState().equals(EventResult.EventQCResultState.NOT_RUN) && verbatimEventDate.matches("^[0-9]{4}([- ]+| to |[/ ]+)[0-9]{4}$")) { // Example: 1882-1995 // Example: 1882 to 1885 // Example: 1882/1885 try { String cleaned = verbatimEventDate.replace(" ", ""); cleaned = cleaned.replace("-", "/"); if (cleaned.matches("^[0-9]{4}to[0-9]{4}$")) { int len = verbatimEventDate.length(); int lastYear = len - 4; cleaned = verbatimEventDate.substring(0, 4) + "/" + verbatimEventDate.substring(lastYear, len); } logger.debug(cleaned); Interval parseDate = Interval.parse(cleaned); logger.debug(parseDate); resultDate = parseDate.getStart().toString("yyyy") + "/" + parseDate.getEnd().toString("yyyy"); result.setResultState(EventResult.EventQCResultState.RANGE); result.setResult(resultDate); } catch (Exception e) { logger.debug(e.getMessage()); } } if (result.getResultState().equals(EventResult.EventQCResultState.NOT_RUN) && verbatimEventDate .matches("^[A-Za-z]+[.]{0,1}( and | to |[-][ ]{0,1}| [-] )[A-Za-z]+[.]{0,1}(, |[/ .])[0-9]{4}$")) { logger.debug(verbatimEventDate); // Example: Jan to Feb 1882 // Example: Jan-Feb/1882 verbatimEventDate = verbatimEventDate.replace(", ", " "); if (verbatimEventDate.matches("^[A-Za-z]+[.]{0,1}[-][A-Za-z]+[.]{0,1}[.][0-9]{4}$")) { // transform case with multiple periods to slash before year. verbatimEventDate = verbatimEventDate.substring(0, verbatimEventDate.length() - 5) + "/" + verbatimEventDate.substring(verbatimEventDate.length() - 4); logger.debug(verbatimEventDate); } if (verbatimEventDate.matches("^[A-Za-z]+[.]{0,1}[ ][-][ ]{1}[A-Za-z]+[.]{0,1}[/ .][0-9]{4}$")) { // remove space around dash. verbatimEventDate = verbatimEventDate.replace(" - ", "-"); logger.debug(verbatimEventDate); } if (verbatimEventDate.matches("^[A-Za-z]+[.]{0,1}[-][ ]{1}[A-Za-z]+[.]{0,1}[/ .][0-9]{4}$")) { // remove space trailing after dash. verbatimEventDate = verbatimEventDate.replace("- ", "-"); logger.debug(verbatimEventDate); } if (verbatimEventDate.matches("^[A-Za-z]+[.]{0,1} and {1}[A-Za-z]+[.]{0,1}[/ .][0-9]{4}$")) { // replace and with dash verbatimEventDate = verbatimEventDate.replace(" and ", "-"); logger.debug(verbatimEventDate); } if (verbatimEventDate.matches("^[A-Za-z]+[.]{0,1} to {1}[A-Za-z]+[.]{0,1}[/ .][0-9]{4}$")) { // replace to with dash verbatimEventDate = verbatimEventDate.replace(" to ", "-"); logger.debug(verbatimEventDate); } try { String[] bits = verbatimEventDate.replace(" ", "/").split("-"); if (bits != null && bits.length == 2) { String year = verbatimEventDate.substring(verbatimEventDate.length() - 4, verbatimEventDate.length()); String startBit = bits[0] + "/" + year; DateTimeParser[] parsers = { DateTimeFormat.forPattern("MMM/yyyy").getParser(), DateTimeFormat.forPattern("MMM./yyyy").getParser() }; DateTimeFormatter formatter = new DateTimeFormatterBuilder().append(null, parsers) .toFormatter(); LocalDate parseStartDate = LocalDate.parse(cleanMonth(startBit), formatter.withLocale(Locale.ENGLISH)); LocalDate parseEndDate = LocalDate.parse(cleanMonth(bits[1]), formatter.withLocale(Locale.ENGLISH)); resultDate = parseStartDate.toString("yyyy-MM") + "/" + parseEndDate.toString("yyyy-MM"); logger.debug(resultDate); result.setResultState(EventResult.EventQCResultState.RANGE); result.setResult(resultDate); } } catch (Exception e) { logger.debug(e.getMessage()); } } if (result.getResultState().equals(EventResult.EventQCResultState.NOT_RUN) && verbatimEventDate.matches( "^[0-9]{1,2}[ /.]{0,1}[A-Za-z]+[.]{0,1}( - |[-])[0-9]{1,2}[ /.]{0,1}[A-Za-z]+[.]{0,1}[/ -.][0-9]{4}$")) { logger.debug(verbatimEventDate); // Example: 05/Jan/1882-03/Feb/1885 if (verbatimEventDate.matches( "^[0-9]{1,2}[ /.]{0,1}[A-Za-z]+[.]{0,1}[-][0-9]{1,2}[ /.]{0,1}[A-Za-z]+[.]{0,1}[-][0-9]{4}$")) { // transform case with multiple dashes to slash before year. verbatimEventDate = verbatimEventDate.substring(0, verbatimEventDate.length() - 5) + "/" + verbatimEventDate.substring(verbatimEventDate.length() - 4); logger.debug(verbatimEventDate); } if (verbatimEventDate.matches( "^[0-9]{1,2}[ /.]{0,1}[A-Za-z]+[.]{0,1}[-][0-9]{1,2}[ /.]{0,1}[A-Za-z]+[.]{0,1}[.][0-9]{4}$")) { // transform case with multiple periods to slash before year. verbatimEventDate = verbatimEventDate.substring(0, verbatimEventDate.length() - 5) + "/" + verbatimEventDate.substring(verbatimEventDate.length() - 4); logger.debug(verbatimEventDate); } try { String[] bits = verbatimEventDate.replace(" - ", "-").replace(" ", "/").split("-"); if (bits != null && bits.length == 2) { String year = verbatimEventDate.substring(verbatimEventDate.length() - 4, verbatimEventDate.length()); String startBit = bits[0] + "/" + year; logger.debug(cleanMonth(startBit)); logger.debug(cleanMonth(bits[1])); DateTimeParser[] parsers = { DateTimeFormat.forPattern("dd MMM/yyyy").getParser(), DateTimeFormat.forPattern("dd.MMM/yyyy").getParser(), DateTimeFormat.forPattern("dd/MMM/yyyy").getParser(), DateTimeFormat.forPattern("ddMMM/yyyy").getParser(), DateTimeFormat.forPattern("dd MMM./yyyy").getParser(), DateTimeFormat.forPattern("dd.MMM./yyyy").getParser(), DateTimeFormat.forPattern("dd/MMM./yyyy").getParser(), DateTimeFormat.forPattern("ddMMM./yyyy").getParser() }; DateTimeFormatter formatter = new DateTimeFormatterBuilder().append(null, parsers) .toFormatter(); LocalDate parseStartDate = LocalDate.parse(cleanMonth(startBit), formatter.withLocale(Locale.ENGLISH)); LocalDate parseEndDate = LocalDate.parse(cleanMonth(bits[1]), formatter.withLocale(Locale.ENGLISH)); resultDate = parseStartDate.toString("yyyy-MM-dd") + "/" + parseEndDate.toString("yyyy-MM-dd"); logger.debug(resultDate); result.setResultState(EventResult.EventQCResultState.RANGE); result.setResult(resultDate); } } catch (Exception e) { logger.debug(e.getMessage()); } } if (result.getResultState().equals(EventResult.EventQCResultState.NOT_RUN) && verbatimEventDate.matches( "^[A-Za-z]+[.]{0,1}[ ]{0,1}[0-9]{1,2}( - |[-]| to | and | et )[A-Za-z]+[.]{0,1}[ ]{0,1}[0-9]{1,2}[/ .,][ ]{0,1}[0-9]{4}$")) { logger.debug(verbatimEventDate); // Example: Aug. 5 - Sept. 8, 1943 try { String[] bits = verbatimEventDate.replace(" to ", "-").replace(" - ", "-").replace(" and ", "-") .replace(" et ", "-").replace(", ", " ").replace(" ", "/").split("-"); if (bits != null && bits.length == 2) { String year = verbatimEventDate.substring(verbatimEventDate.length() - 4, verbatimEventDate.length()); String startBit = bits[0] + "/" + year; logger.debug(cleanMonth(startBit)); logger.debug(cleanMonth(bits[1])); DateTimeParser[] parsers = { DateTimeFormat.forPattern("MMM/dd/yyyy").getParser(), DateTimeFormat.forPattern("MMM./dd/yyyy").getParser(), DateTimeFormat.forPattern("MMM.dd/yyyy").getParser() }; DateTimeFormatter formatter = new DateTimeFormatterBuilder().append(null, parsers) .toFormatter(); LocalDate parseStartDate = LocalDate.parse(cleanMonth(startBit), formatter.withLocale(Locale.ENGLISH)); LocalDate parseEndDate = LocalDate.parse(cleanMonth(bits[1]), formatter.withLocale(Locale.ENGLISH)); resultDate = parseStartDate.toString("yyyy-MM-dd") + "/" + parseEndDate.toString("yyyy-MM-dd"); logger.debug(resultDate); result.setResultState(EventResult.EventQCResultState.RANGE); result.setResult(resultDate); } } catch (Exception e) { logger.debug(e.getMessage()); } } if (result.getResultState().equals(EventResult.EventQCResultState.NOT_RUN) && verbatimEventDate.matches( "^[0-9]{1,2}([ ]{0,1}[-][ ]{0,1}| and | et | to )[0-9]{1,2}[ /.]{0,1}[A-Za-z]+[.]{0,1}[/ -.][0-9]{4}$")) { // Example: 11 et 14 VII 1910 // Example: 05-02 Jan./1992 String toCheck = verbatimEventDate; toCheck = toCheck.replace(" - ", "-").replace(" et ", "-").replace(" and ", "-").replace(" to ", "-"); // Note: "and" has different semantics than "to", may imply that a specimen record // represents two occurrences (e.g. flower on one date, fruit on another) rather than // a range, but dwc:eventDate representation for both forms on one event is a range. if (toCheck.matches("^[0-9]{1,2}[-][0-9]{1,2}[ /.]{0,1}[A-Za-z]+[.]{0,1}[-][0-9]{4}$")) { // transform case with multiple dashes to slash before year. toCheck = toCheck.substring(0, toCheck.length() - 5) + "/" + toCheck.substring(toCheck.length() - 4); logger.debug(toCheck); } if (toCheck.matches("^[0-9]{1,2}[-][0-9]{1,2}[ /.]{0,1}[A-Za-z]+[.]{0,1}[.][0-9]{4}$")) { // transform case with multiple periods to slash before year. toCheck = toCheck.substring(0, toCheck.length() - 5) + "/" + toCheck.substring(toCheck.length() - 4); logger.debug(toCheck); } try { String[] bits = toCheck.replace(" ", "/").split("-"); if (bits != null && bits.length == 2) { String year = toCheck.substring(toCheck.length() - 4, toCheck.length()); logger.debug(cleanMonth(bits[1])); DateTimeParser[] parsers = { DateTimeFormat.forPattern("dd MMM/yyyy").getParser(), DateTimeFormat.forPattern("dd.MMM/yyyy").getParser(), DateTimeFormat.forPattern("dd/MMM/yyyy").getParser(), DateTimeFormat.forPattern("ddMMM/yyyy").getParser(), DateTimeFormat.forPattern("dd MMM./yyyy").getParser(), DateTimeFormat.forPattern("dd.MMM./yyyy").getParser(), DateTimeFormat.forPattern("dd/MMM./yyyy").getParser(), DateTimeFormat.forPattern("ddMMM./yyyy").getParser() }; DateTimeFormatter formatter = new DateTimeFormatterBuilder().append(null, parsers) .toFormatter(); LocalDate parseEndDate = LocalDate.parse(cleanMonth(bits[1]), formatter.withLocale(Locale.ENGLISH)); String startMonthYear = parseEndDate.toString("MMM/yyyy"); String startBit = bits[0] + "/" + startMonthYear; logger.debug(startBit); LocalDate parseStartDate = LocalDate.parse(startBit, formatter.withLocale(Locale.ENGLISH)); resultDate = parseStartDate.toString("yyyy-MM-dd") + "/" + parseEndDate.toString("yyyy-MM-dd"); logger.debug(resultDate); result.setResultState(EventResult.EventQCResultState.RANGE); result.setResult(resultDate); } } catch (Exception e) { logger.debug(e.getMessage()); } } if (result.getResultState().equals(EventResult.EventQCResultState.NOT_RUN) && verbatimEventDate.matches("^[0-9]{2}[-. ]XXX[-. ][0-9]{4}$")) { // Example: 05-XXX-1884 try { String start = verbatimEventDate.substring(verbatimEventDate.length() - 4) + "-01-" + verbatimEventDate.substring(0, 2); String end = verbatimEventDate.substring(verbatimEventDate.length() - 4) + "-12-" + verbatimEventDate.substring(0, 2); EventResult compositeResult = DateUtils.extractDateFromVerbatimER(start + "/" + end, yearsBeforeSuspect, assumemmddyyyy); logger.debug(compositeResult.getResultState()); if (compositeResult.getResultState().equals(EventResult.EventQCResultState.RANGE)) { result.setResultState(EventResult.EventQCResultState.RANGE); result.setResult(compositeResult.getResult()); logger.debug(result.getResult()); } } catch (Exception e) { logger.debug(e.getMessage()); } } if (result.getResultState().equals(EventResult.EventQCResultState.NOT_RUN) && verbatimEventDate.matches("^[0-9]{4}-[0-9]{2}/[0-9]{4}-[0-9]{2}$")) { // Example: 1885-03/1886-04 try { Interval parseDate = Interval.parse(verbatimEventDate); logger.debug(parseDate); resultDate = parseDate.getStart().toString("yyyy-MM") + "/" + parseDate.getEnd().toString("yyyy-MM"); result.setResultState(EventResult.EventQCResultState.RANGE); result.setResult(resultDate); } catch (Exception e) { logger.debug(e.getMessage()); } } if (result.getResultState().equals(EventResult.EventQCResultState.NOT_RUN)) { // Example: 1995-03-05/1996-05-08 try { Interval parseDate = Interval.parse(verbatimEventDate); logger.debug(parseDate); resultDate = parseDate.getStart().toString("yyyy-MM-dd") + "/" + parseDate.getEnd().toString("yyyy-MM-dd"); result.setResultState(EventResult.EventQCResultState.RANGE); result.setResult(resultDate); } catch (Exception e) { logger.debug(e.getMessage()); } } if (result.getResultState().equals(EventResult.EventQCResultState.NOT_RUN)) { // Example: Jan,15-18 1882 // Example: Jan. 17 and 18 1882 String cleaned = verbatimEventDate.trim(); if (verbatimEventDate.matches("^[A-Za-z.]+[ ,]+[0-9]{1,2} and [0-9]{0,2}[ ,]+[0-9]{4}$")) { // Note: "and" has different semantics than "to", may imply that a specimen record // represents two occurrences (e.g. flower on one date, fruit on another) rather than // a range, but dwc:eventDate representation for both forms on one event is a range. cleaned = cleaned.replace(" and ", " to "); } if (verbatimEventDate.matches("^[A-Za-z.]+[ ,]+[0-9]{1,2}-[0-9]{0,2}[ ,]+[0-9]{4}$")) { cleaned = cleaned.replace("-", " to "); } if (cleaned.contains(" to ")) { String[] bits = cleaned.split(" to "); String yearRegex = ".*([0-9]{4}).*"; Matcher yearMatcher = Pattern.compile(yearRegex).matcher(cleaned); String monthRegex = "([A-Za-z.]+).*"; Matcher monthMatcher = Pattern.compile(monthRegex).matcher(cleaned); if (yearMatcher.matches() && monthMatcher.matches()) { String year = yearMatcher.group(1); String month = monthMatcher.group(1); if (bits.length == 2) { if (!bits[0].contains(year)) { bits[0] = bits[0] + " " + year; } if (!bits[1].contains(year)) { bits[1] = bits[1] + " " + year; } if (!bits[1].contains(month)) { bits[1] = month + " " + bits[1]; } Map<String, String> resultBit0 = DateUtils.extractDateFromVerbatim(bits[0]); if (resultBit0.size() > 0 && resultBit0.get("resultState").equals("date")) { Map<String, String> resultBit1 = DateUtils.extractDateFromVerbatim(bits[1]); if (resultBit1.size() > 0 && resultBit1.get("resultState").equals("date")) { result.setResultState(EventResult.EventQCResultState.RANGE); result.setResult(resultBit0.get("result") + "/" + resultBit1.get("result")); } } logger.debug(bits[0]); logger.debug(bits[1]); } } } } // Now test to see if result is sane. if (result != null && !result.getResultState().equals(EventResult.EventQCResultState.NOT_RUN)) { Interval testExtract = DateUtils.extractDateInterval(result.getResult()); if (testExtract == null || testExtract.getStart().getYear() < yearsBeforeSuspect) { result.setResultState(EventResult.EventQCResultState.SUSPECT); logger.debug(result.getResult()); logger.debug(testExtract); } else { logger.debug(result.getResult()); } if (!verbatimEventDate.matches(".*[0-9]{4}.*") && yearsBeforeSuspect > 999) { result = new EventResult(); logger.debug(result.getResult()); } } return result; }