@EventSubscriber public void onMessageReceived(final MessageReceivedEvent e) { final String msg = e.getMessage().getContent(); if (msg.startsWith("!eew")) { final String[] args = msg.split(" "); if (args.length<=1) Command.reply(e, "引数が不足しています"); else { final Command command = EnumUtils.getEnum(Command.class, args[1]); if (command!=null) if (!EEWBot.instance.getConfig().isEnablePermission()||userHasPermission(e.getAuthor().getLongID(), command)) if (args.length-2>=command.getMinArgLength()) command.onCommand(e, ArrayUtils.subarray(args, 2, args.length+1)); else Command.reply(e, "引数が不足しています"); else Command.reply(e, "権限がありません!"); else Command.reply(e, "コマンドが存在しません\nコマンド一覧は`help`コマンドで確認出来ます"); } } }
/** * Build a described {@link Vm} bean from a XML VMRecord entry. */ private VCloudVm toVm(final Element record) { final VCloudVm result = new VCloudVm(); result.setId(StringUtils.removeStart(record.getAttribute("id"), "urn:vcloud:vm:")); result.setName(record.getAttribute("name")); result.setOs(record.getAttribute("guestOs")); // Optional attributes result.setStorageProfileName(record.getAttribute("storageProfileName")); result.setStatus(EnumUtils.getEnum(VmStatus.class, record.getAttribute("status"))); result.setCpu(NumberUtils.toInt(StringUtils.trimToNull(record.getAttribute("numberOfCpus")))); result.setBusy(Boolean.parseBoolean(ObjectUtils.defaultIfNull(StringUtils.trimToNull(record.getAttribute("isBusy")), "false"))); result.setVApp(StringUtils.trimToNull(record.getAttribute("containerName"))); result.setVAppId(StringUtils.trimToNull(StringUtils.removeStart(record.getAttribute("container"), "urn:vcloud:vapp:"))); result.setRam(NumberUtils.toInt(StringUtils.trimToNull(record.getAttribute("memoryMB")))); result.setDeployed( Boolean.parseBoolean(ObjectUtils.defaultIfNull(StringUtils.trimToNull(record.getAttribute("isDeployed")), "false"))); return result; }
/** * Get {@link Enum} value from the string raw data. Accept lower and upper case for the match. */ @SuppressWarnings("unchecked") private static <Y extends Enum<Y>> Enum<Y> toEnum(final String data, final Expression<Y> expression) { if (StringUtils.isNumeric(data)) { // Get Enum value by its ordinal return expression.getJavaType().getEnumConstants()[Integer.parseInt(data)]; } // Get Enum value by its exact name Enum<Y> fromName = EnumUtils.getEnum((Class<Y>) expression.getJavaType(), data); // Get Enum value by its upper case name if (fromName == null) { fromName = Enum.valueOf((Class<Y>) expression.getJavaType(), data.toUpperCase(Locale.ENGLISH)); } return fromName; }
/** * Manage simple value. * * @param bean * the target bean. * @param property * the bean property to set. * @param rawValue * the raw value to set. * @param <E> * Enumeration type. */ @SuppressWarnings("unchecked") protected <E extends Enum<E>> void setSimpleRawProperty(final T bean, final String property, final String rawValue) throws IllegalAccessException, InvocationTargetException { final Field field = getField(clazz, property); // Update the property if (field.getAnnotation(GeneratedValue.class) == null) { if (field.getType().isEnum()) { // Ignore case of Enum name final Class<E> enumClass = (Class<E>) field.getType(); beanUtilsBean.setProperty(bean, property, Enum.valueOf(enumClass, EnumUtils.getEnumMap(enumClass).keySet().stream().filter(rawValue::equalsIgnoreCase).findFirst().orElse(rawValue))); } else { beanUtilsBean.setProperty(bean, property, rawValue); } } }
public static <T extends Enum<T>> Set<T> valuesOf(Class<T> enumClass, String[] enumNameArray, T[] defaultEnumArray) { final Set<T> enumSet = new LinkedHashSet<T>(); if (ArrayUtils.isNotEmpty(enumNameArray)) { for (final String enumName : enumNameArray) { final T enumValue = EnumUtils.getEnum(enumClass, enumName); if (null != enumValue) { enumSet.add(enumValue); } } } if (CollectionUtils.isEmpty(enumSet) && ArrayUtils.isNotEmpty(defaultEnumArray)) { Collections.addAll(enumSet, defaultEnumArray); } return enumSet; }
public SummonerQueryForwardPage(PageParameters parameters) { super(parameters, "Summoner Search", null); // get summoner name and region sent by the form String summonerName = parameters.get("summonerName").toString(""); String regionName = parameters.get("region").toString("").toUpperCase(); // insert data to error page add(new Label("summoner_name", summonerName)); add(new Label("region", regionName)); // check if summoner name and region are valid, if not return to show error page if (summonerName == null || summonerName.length() == 0) return; if (!EnumUtils.isValidEnum(RiotEndpoint.class, regionName)) return; // convert region name to RiotEndpoint object RiotEndpoint region = RiotEndpoint.valueOf(regionName); // generate the summoners statistic Pair<String, SummonerStatisticItem> summonerStatistic = PageDataProvider.generateSummonerStatistic(summonerName, region); // if statistic generation failed, return to show error page if (summonerStatistic == null) return; // forward to single summoner page with region and summoner key name throw new RestartResponseAtInterceptPageException(SingleSummonerPage.class, new PageParameters() .set(0, regionName).set(1, summonerStatistic.getKey())); }
private By parseBy(String locator) { if (StringUtils.isBlank(locator)) { return new ByFocus(); } Pair<String, String> prefixAndSelector = this.fitnesseMarkup.cleanAndParseKeyValue(locator, FitnesseMarkup.KEY_VALUE_SEPARATOR); String prefix = prefixAndSelector.getKey(); String selector = prefixAndSelector.getValue(); LocatorType selectorType = EnumUtils.getEnum(LocatorType.class, prefix); if (selectorType == null) { selector = locator; selectorType = LocatorType.xpath; } try { return selectorType.byClass.getConstructor(String.class).newInstance(selector); } catch (ReflectiveOperationException e) { throw new IllegalStateException("Unexpected failure instantiating selector: " + prefix, e); } }
/** * Creates a new Morph that is stored statically in the class. * * isSynth is a true/false field * @param input String[] {name, morphType, description, implants, aptitudeMaxStr, durability, woundThreshold, CP, creditCost, effects, notes} */ public static void CreateInternalMorph(String[] parts) { if (parts.length != 11 || !Utils.isInteger(parts[5]) || !Utils.isInteger(parts[6]) || !Utils.isInteger(parts[7])) { throw new IllegalArgumentException("Invalidly formatted Morph string[] : " + StringUtils.join(parts,",")); } int cnt = 0; String name = parts[cnt++]; MorphType morphType = EnumUtils.getEnum(MorphType.class, parts[cnt++].toUpperCase()); String description = parts[cnt++]; String implants = parts[cnt++]; String aptitudeMaxStr = parts[cnt++]; int durability = Integer.parseInt(parts[cnt++]); int woundThreshold = Integer.parseInt(parts[cnt++]); int CP = Integer.parseInt(parts[cnt++]); String creditCost = parts[cnt++]; String effects = parts[cnt++]; String notes = parts[cnt++]; Morph temp = new Morph(name,morphType,description,implants,aptitudeMaxStr,durability,woundThreshold,CP,creditCost,effects,notes); Morph.morphList.add(temp); }
/** * Creates a new sleight that is stored statically in the class * @param input String[] of format SleightType;IsExsurgent;SleightName;ActivePassive;ActionType;Range;Duration;StrainMod;skillUsed;Description */ public static void CreateInternalsleight(String[] input) { if (input.length != 10 ) { throw new IllegalArgumentException("Array for Sleight must have 10 parts"); } int cnt = 0; SleightType sleightType = EnumUtils.getEnum(SleightType.class,input[cnt++]); Boolean isExsurgent = Boolean.parseBoolean(input[cnt++]); String sleightName = input[cnt++]; UsageType activePassive = EnumUtils.getEnum(UsageType.class,input[cnt++].toUpperCase()); ActionType actionType = EnumUtils.getEnum(ActionType.class,input[cnt++].toUpperCase()); Range range = EnumUtils.getEnum(Range.class,input[cnt++].toUpperCase()); Duration duration = EnumUtils.getEnum(Duration.class,input[cnt++].toUpperCase()); String strainMod = input[cnt++]; String skillUsed = input[cnt++]; String description = input[cnt++]; Sleight temp = new Sleight(sleightType, isExsurgent, sleightName,activePassive, actionType, range, duration, strainMod, skillUsed, description); Sleight.sleightList.put(temp.getName(),temp); }
@Authenticated(value = {LoggedIn.class, HasRole.class}) @Authorized(value = {"moderator", "admin"}) @Transactional public Result disableModule(long forumId, String forumModule) throws ForumNotFoundException { Forum forum = forumService.findForumById(forumId); if (!EnumUtils.isValidEnum(ForumModules.class, forumModule)) { return redirect(routes.ForumController.editForumModuleConfig(forum.getId())); } ForumModules forumModuleType = ForumModules.valueOf(forumModule); if (forum.getModulesSet().containsAll(ForumModuleUtils.getDependedModules(forumModuleType)) && !ForumModuleUtils.getDependedModules(forumModuleType).isEmpty()) { flashError(Messages.get("forum.module.disable.error.dependencies", ForumModuleUtils.getDependedModules(forumModuleType).toString())); return redirect(routes.ForumController.editForumModuleConfig(forum.getId())); } forumModuleService.disableModule(forum.getJid(), ForumModules.valueOf(forumModule)); return redirect(routes.ForumController.editForumModuleConfig(forum.getId())); }
@Override public void initGui() { buttonList.add(new GuiButton(0, width - 105, height - 25, 100, 20, "Apply and continue")); super.initGui(); namefield = new GuiTextField(1, fontRendererObj, 55, 110, 100, 10); surnamefield = new GuiTextField(2, fontRendererObj, 55, 125, 100, 10); namefield.setCanLoseFocus(true); surnamefield.setCanLoseFocus(true); genderGroup = new GuiRadioGroup(surnamefield.xPosition, surnamefield.yPosition + surnamefield.height + 5); jobMenu = new GuiDropdownMenu(5, genderGroup.yPos + 20, surnamefield.getWidth() + 10, "Job: "); genderGroup.buttonList.clear(); genderGroup.horizontal = true; genderGroup.addButton(new GuiRadiobutton(0, 0, 0, 10, 10, "Male")); genderGroup.addButton(new GuiRadiobutton(1, 0, 0, 10, 10, "Female")); genderGroup.singleChoice = true; jobMenu.setMaxHeight(4); int enumid = 0; for (EnumJob job : EnumUtils.getEnumList(EnumJob.class)) { jobMenu.contents.add(new GuiMenuItem(jobMenu, enumid, job.name())); enumid++; } }
@Authenticated(value = {LoggedIn.class, HasRole.class}) @Transactional public Result enableModule(long contestId, String contestModule) throws ContestNotFoundException { Contest contest = contestService.findContestById(contestId); if (contest.isLocked() || !EnumUtils.isValidEnum(ContestModules.class, contestModule) || !ContestControllerUtils.getInstance().isAllowedToManageContest(contest, IdentityUtils.getUserJid())) { return redirect(org.iatoki.judgels.uriel.contest.routes.ContestController.editContestModuleConfig(contest.getId())); } ContestModules contestModuleType = ContestModules.valueOf(contestModule); if (!ContestModuleUtils.getModuleContradiction(contestModuleType).isEmpty() && contest.getModulesSet().containsAll(ContestModuleUtils.getModuleContradiction(contestModuleType))) { flashError(Messages.get("contest.module.enable.error.contradiction", ContestModuleUtils.getModuleContradiction(contestModuleType).toString())); return redirect(org.iatoki.judgels.uriel.contest.routes.ContestController.editContestModuleConfig(contest.getId())); } if (!contest.getModulesSet().containsAll(ContestModuleUtils.getModuleDependencies(contestModuleType))) { flashError(Messages.get("contest.module.enable.error.dependencies", ContestModuleUtils.getModuleDependencies(contestModuleType).toString())); return redirect(org.iatoki.judgels.uriel.contest.routes.ContestController.editContestModuleConfig(contest.getId())); } contestModuleService.enableModule(contest.getJid(), contestModuleType, IdentityUtils.getUserJid(), IdentityUtils.getIpAddress()); return redirect(org.iatoki.judgels.uriel.contest.routes.ContestController.editContestModuleConfig(contest.getId())); }
@Authenticated(value = {LoggedIn.class, HasRole.class}) @Transactional public Result disableModule(long contestId, String contestModule) throws ContestNotFoundException { Contest contest = contestService.findContestById(contestId); if (contest.isLocked() || !EnumUtils.isValidEnum(ContestModules.class, contestModule) || !ContestControllerUtils.getInstance().isAllowedToManageContest(contest, IdentityUtils.getUserJid())) { return redirect(org.iatoki.judgels.uriel.contest.routes.ContestController.editContestModuleConfig(contest.getId())); } ContestModules contestModuleType = ContestModules.valueOf(contestModule); if (contest.getModulesSet().containsAll(ContestModuleUtils.getDependedModules(contestModuleType)) && !ContestModuleUtils.getDependedModules(contestModuleType).isEmpty()) { flashError(Messages.get("contest.module.disable.error.dependencies", ContestModuleUtils.getDependedModules(contestModuleType).toString())); return redirect(org.iatoki.judgels.uriel.contest.routes.ContestController.editContestModuleConfig(contest.getId())); } contestModuleService.disableModule(contest.getJid(), contestModuleType, IdentityUtils.getUserJid(), IdentityUtils.getIpAddress()); return redirect(org.iatoki.judgels.uriel.contest.routes.ContestController.editContestModuleConfig(contest.getId())); }
private static void logNumOfVarByTypes(final List<VariantContext> variants, final Logger logger) { logger.info("Discovered " + variants.size() + " variants."); final Map<String, Long> variantsCountByType = variants.stream() .collect(Collectors.groupingBy(vc -> (String) vc.getAttribute(GATKSVVCFConstants.SVTYPE), Collectors.counting())); variantsCountByType.forEach((key, value) -> logger.info(key + ": " + value)); final Set<String> knownTypes = new HashSet<>( EnumUtils.getEnumMap(SimpleSVType.TYPES.class).keySet() ); knownTypes.add(BreakEndVariantType.InvSuspectBND.INV33_BND); knownTypes.add(BreakEndVariantType.InvSuspectBND.INV55_BND); knownTypes.add(BreakEndVariantType.TransLocBND.STRANDSWITCHLESS_BND); knownTypes.add(GATKSVVCFConstants.CPX_SV_SYB_ALT_ALLELE_STR); Sets.difference(knownTypes, variantsCountByType.keySet()).forEach(key -> logger.info(key + ": " + 0)); }
@Override public void readFromNBT(NBTTagCompound nbt) { // read breed name and convert it to the corresponding breed object String breedName = nbt.getString(NBT_BREED); EnumDragonBreed breed = EnumUtils.getEnum(EnumDragonBreed.class, breedName.toUpperCase()); if (breed == null) { breed = EnumDragonBreed.DEFAULT; L.warn("Dragon {} loaded with invalid breed type {}, using {} instead", dragon.getEntityId(), breedName, breed); } setBreedType(breed); // read breed points NBTTagCompound breedPointTag = nbt.getCompoundTag(NBT_BREED_POINTS); breedPoints.forEach((type, points) -> { points.set(breedPointTag.getInteger(type.getName())); }); }
public JooqProcessRecord(ProcessInstanceRecord record) { this.processInstance = record; id = record.getId(); accountId = record.getAccountId(); clusterId = record.getClusterId(); data = new HashMap<>(record.getData()); endTime = toTimestamp(record.getEndTime()); executionCount = record.getExecutionCount(); exitReason = EnumUtils.getEnum(ExitReason.class, record.getExitReason()); priority = record.getPriority(); processLog = new ProcessLog(); processName = record.getProcessName(); resourceId = record.getResourceId(); resourceType = record.getResourceType(); result = EnumUtils.getEnum(ProcessResult.class, record.getResult()); runAfter = record.getRunAfter(); runningProcessServerId = record.getRunningProcessServerId(); startProcessServerId = record.getStartProcessServerId(); startTime = toTimestamp(record.getStartTime()); }
@Override public Reply parse(Push push) { if (!(push instanceof EventPush)) { return null; } EventPush eventPush = (EventPush) push; String event = eventPush.getEvent(); EventPushType eventPushType = EnumUtils.getEnum(EventPushType.class, StringUtils.upperCase(event)); Validate.notNull(eventPushType, "don't-support-%s-event-push", event); // TODO please custom it. if (eventPushType == EventPushType.SUBSCRIBE) { Reply reply = ReplyUtil.parseReplyDetailWarpper(ReplyUtil.getDummyTextReplyDetailWarpper()); return ReplyUtil.buildReply(reply, eventPush); } return null; }
public static Reply parseReplyDetailWarpper(ReplyDetailWarpper replyDetailWarpper) { if (replyDetailWarpper == null) { return null; } String replyType = replyDetailWarpper.getReplyType(); ReplyEnumFactory replyEnumFactory = EnumUtils.getEnum(ReplyEnumFactory.class, StringUtils.upperCase(replyType)); if (replyEnumFactory == null) { return null; } Reply buildReply = replyEnumFactory.buildReply(replyDetailWarpper.getReplyDetails()); if (buildReply != null) { buildReply.setFuncFlag(replyDetailWarpper.getFuncFlag()); return buildReply; } return null; }
public static void main(String[] args) throws Exception { File parent = new File(PushTest.class.getClassLoader().getResource("push").toURI()); for (File pushFile : parent.listFiles()) { // if (!StringUtils.startsWithIgnoreCase(pushFile.getName(), "event")) { // continue; // } // String message = FileUtils.readFileToString(pushFile, "utf-8"); String messageType = getMsgType(message); PushEnumFactory pushEnum = EnumUtils.getEnum(PushEnumFactory.class, StringUtils.upperCase(messageType)); Push push = pushEnum.convert(message); System.out.println(pushFile + "\n" + message + "\n" + push + "\n"); } }
private static <T> T convertScalarEntity(ScalarEntity scalarEntity, ToscaKey<T> key) { String value = scalarEntity.getValue(); Class targetType = key.getType(); if (String.class.isAssignableFrom(targetType)) { return (T) value; } else if (Integer.class.isAssignableFrom(targetType)) { return (T) Integer.valueOf(value); } else if (Boolean.class.isAssignableFrom(targetType)) { return (T) Boolean.valueOf(value); // TODO handle values besides true/false (later, when doing error handling) } else if (targetType.isEnum()) { Map<String, T> enumMap = EnumUtils.getEnumMap(targetType); Optional<T> result = enumMap.entrySet().stream() .filter(entry -> value.equalsIgnoreCase(entry.getKey())) .map(Map.Entry::getValue) .findAny(); return result.orElseThrow(() -> new NoSuchElementException( String.format("No value with name '%s' in enum '%s'", value, targetType.getSimpleName()))); } else if (OperationVariable.class.isAssignableFrom(targetType)) { return (T) new OperationVariable(scalarEntity); } else if (SizeUnit.class.isAssignableFrom(targetType)) { SizeUnit.Unit fromDefaultUnit = (SizeUnit.Unit) key.getDirectives().get(SizeUnit.FROM); SizeUnit.Unit toUnit = (SizeUnit.Unit) key.getDirectives().get(SizeUnit.TO); if (fromDefaultUnit == null || toUnit == null) { throw new IllegalStateException( "ToscaKey defining a SizeUnit is illegal: No directive set for source and target units"); } return (T) SizeUnit.convert(value, fromDefaultUnit, toUnit); } else { throw new UnsupportedOperationException(String.format( "Cannot convert value of type %s: currently unsupported", targetType.getSimpleName())); } }
public WebDriverProperties validate() { // validate CAPABILITY_BROWSER when testing in local if(isEmpty(getRemote())) { DriverType browserType = EnumUtils.getEnum(DriverType.class, getBrowser().toUpperCase()); checkArgument(DriverType.local.contains(browserType), String.format("Invalid [capabilities.browser, capabilities.browserName, browser] " + "= [%s] not in %s", getBrowser(), DriverType.local.toString())); } // validate CAPABILITY_BROWSER_SIZE if(isNotEmpty(getBrowserSize())) { checkArgument(getBrowserSize().matches("\\d+[x]\\d+"), String.format("Invalid [capabilities.browserSize] = [%s] " + "not in the format 123x456", getBrowserSize())); } // validate CAPABILITY_VIEWPORT_SIZE if(isNotEmpty(getViewportSize())) { checkArgument(getViewportSize().matches("\\d+[x]\\d+"), String.format("Invalid [capabilities.viewportSize] = [%s] " + "not in the format 123x456", getViewportSize())); } // validate CAPABILITY_DEVICE_NAME over CAPABILITY_USER_AGENT if(isNotEmpty(getDeviceName()) && isNotEmpty(getUserAgent())) { throw new IllegalArgumentException( "Invalid capabilities setup:" + " [capabilities.deviceName] and [capabilities.userAgent] cannot coexist."); } // validate CAPABILITY_REMOTE if(isNotEmpty(getRemote())) { try { new URL(getRemote()); } catch (MalformedURLException e) { throw new IllegalArgumentException( "Invalid 'capabilities.remote' parameter: " + getRemote(), e); } } // all the properties are valid return this; }
public static boolean userHasPermission(final long userid, final Command command) { return EEWBot.instance.getPermissions().values().stream() .filter(permission -> permission.getUserid().stream() .anyMatch(id -> id==userid)) .findAny().orElse(EEWBot.instance.getPermissions().getOrDefault("everyone", Permission.DEFAULT_EVERYONE)) .getCommand().stream() .map(str -> EnumUtils.getEnum(Command.class, str)) .anyMatch(cmd -> cmd==command); }
/** * Converte um LancamentoDto para uma entidade Lancamento. * * @param lancamentoDto * @param result * @return Lancamento * @throws ParseException */ private Lancamento converterDtoParaLancamento(LancamentoDto lancamentoDto, BindingResult result) throws ParseException { Lancamento lancamento = new Lancamento(); if (lancamentoDto.getId().isPresent()) { Optional<Lancamento> lanc = this.lancamentoService.buscarPorId(lancamentoDto.getId().get()); if (lanc.isPresent()) { lancamento = lanc.get(); } else { result.addError(new ObjectError("lancamento", "Lançamento não encontrado.")); } } else { lancamento.setFuncionario(new Funcionario()); lancamento.getFuncionario().setId(lancamentoDto.getFuncionarioId()); } lancamento.setDescricao(lancamentoDto.getDescricao()); lancamento.setLocalizacao(lancamentoDto.getLocalizacao()); lancamento.setData(this.dateFormat.parse(lancamentoDto.getData())); if (EnumUtils.isValidEnum(TipoEnum.class, lancamentoDto.getTipo())) { lancamento.setTipo(TipoEnum.valueOf(lancamentoDto.getTipo())); } else { result.addError(new ObjectError("tipo", "Tipo inválido.")); } return lancamento; }
/** * Validates Protocol with Enum value. * * @param inputProtocol * @return HTTP by default */ private SiteToSiteTransportProtocol validateSiteToSiteProtocol(String inputProtocol) { if (EnumUtils.isValidEnum(SiteToSiteTransportProtocol.class, inputProtocol)) { return SiteToSiteTransportProtocol.valueOf(inputProtocol); } else { // Protocol not validaed. Using HTTP by default return SiteToSiteTransportProtocol.HTTP; } }
@Override public boolean setBossBarStyle(BarStyle style, BarColor colour) { try { Field fieldBossBattleServer = EnderDragonBattle.class.getDeclaredField("c"); fieldBossBattleServer.setAccessible(true); BossBattleServer battleServer = (BossBattleServer) fieldBossBattleServer.get(battle); if (battleServer == null) return false; if (style != null) { String nmsStyle = style.name().contains("SEGMENTED") ? style.name().replace("SEGMENTED", "NOTCHED") : "PROGRESS"; if (EnumUtils.isValidEnum(BossBattle.BarStyle.class, nmsStyle)) { battleServer.style = BossBattle.BarStyle.valueOf(nmsStyle); } } if (colour != null) { battleServer.color = BossBattle.BarColor.valueOf(colour.name()); } battleServer.sendUpdate(PacketPlayOutBoss.Action.UPDATE_STYLE); fieldBossBattleServer.setAccessible(false); } catch (NoSuchFieldException | IllegalArgumentException | IllegalAccessException e) { e.printStackTrace(); return false; } return true; }
private void validateImageAndInstanceTypeCompatibility(InstanceType type, String rootDeviceType) { AssertUtil.assertTrue( EnumUtils.isValidEnum(AWSConstants.AWSInstanceStoreTypes.class, type.storageType), String.format("%s does not support instance-store volumes", type.id)); if (!rootDeviceType.equals(AWSStorageType.EBS.name().toLowerCase())) { AssertUtil.assertFalse( type.storageType.equals(AWSConstants.AWSInstanceStoreTypes.NVMe_SSD.name()), String.format( "%s supports only NVMe_SSD instance-store disks and NVMe disks cannot be " + "attached to %s AMI", type.id, rootDeviceType)); } }
@Override public Object createInstance(String typeName) { Class clazz = resolveType(typeName); if (clazz.getSimpleName().contains("Enum")) { return EnumUtils.getEnumList(clazz).get(0); } try { return clazz.newInstance(); } catch (InstantiationException | IllegalAccessException e) { throw new IllegalArgumentException(String.format("Could not create an instance of class %s.", clazz.getName())); } }
/** * Checks the mode string * * @throws IllegalArgumentException If not valid */ private void checkMode() { val mode = config.getString("mode"); if (!EnumUtils.isValidEnum(MovieHandler.Type.class, mode)) { throw new IllegalArgumentException("mode is not valid!"); } }
public boolean select(WebDriverHelper driverHelper, String locator) { return driverHelper.doWhenAvailable(locator, (driver, parsedLocator) -> { Pair<String, String> keyValue = this.fitnesseMarkup.cleanAndParseKeyValue(parsedLocator.getOriginalSelector(), FitnesseMarkup.KEY_VALUE_SEPARATOR); FrameSelectorType frameSelector = EnumUtils.getEnum(FrameSelectorType.class, keyValue.getKey()); if (frameSelector == null) { driver.switchTo().frame(driver.findElement(parsedLocator.getBy())); return; } frameSelector.selector.accept(driver, keyValue.getValue()); }); }
private Pair<OptionSelectorType, String> parseOptionLocator(String optionLocator) { Pair<String, String> keyValue = this.fitnesseMarkup.cleanAndParseKeyValue(optionLocator, FitnesseMarkup.KEY_VALUE_SEPARATOR); // if no type is informed value will be parsed as prefix String prefix = keyValue.getKey(); String value = StringUtils.defaultIfBlank(keyValue.getValue(), prefix); return Pair.of(Optional.ofNullable(EnumUtils.getEnum(OptionSelectorType.class, prefix)).orElse(OptionSelectorType.label), value); }
@Override public IHistoryLogSearchQuery differencesMandatoryFor(Set<HistoryEventType> mandatoryDifferencesEventTypes) { if (!mandatoryDifferencesEventTypes.isEmpty()) { List<HistoryEventType> allowedWithoutDifferenceEventTypes = EnumUtils.getEnumList(HistoryEventType.class); allowedWithoutDifferenceEventTypes.removeAll(mandatoryDifferencesEventTypes); BooleanJunction<?> junction = getDefaultQueryBuilder().bool(); shouldIfNotNull( junction, matchOneIfGiven(Bindings.historyLog().eventType(), allowedWithoutDifferenceEventTypes), matchIfGiven(AbstractHistoryLog.HAS_DIFFERENCES, true) ); must(junction.createQuery()); } return this; }
public static <E extends Enum<E>> Expression<E> enumFromName(final Class<E> clazz, Expression<String> expression) { return Expressions2.fromFunction(String.class, expression, clazz, new Function<String, E>() { @Override public E apply(String input) { return input != null ? EnumUtils.getEnum(clazz, input) : null; } }); }
@Override protected M createMap(Person... persons) { M map = mapSupplier.get(); Iterator<KeyEnum> valueIt = EnumUtils.getEnumList(KeyEnum.class).iterator(); for (Person person : persons) { map.put(valueIt.next(), person); } return map; }
protected M createMap(KeyEnum... items) { M map = mapSupplier.get(); Iterator<ValueEnum> valueIt = EnumUtils.getEnumList(ValueEnum.class).iterator(); for (KeyEnum item : items) { map.put(item, valueIt.next()); } return map; }
@Override protected M createMap(Person... persons) { M map = mapSupplier.get(); Iterator<ValueEnum> valueIt = EnumUtils.getEnumList(ValueEnum.class).iterator(); for (Person person : persons) { map.put(person, valueIt.next()); } return map; }
private static Object getCellValueFromFormula(FormulaEvaluator formulaEvaluator, Cell cell) { try { CellValue cellValue = formulaEvaluator.evaluate(cell); if (cellValue.getCellType() == Cell.CELL_TYPE_NUMERIC) { if (DateUtil.isCellDateFormatted(cell)) { Calendar calendar = GregorianCalendar.getInstance(); calendar.setTime(DateUtil.getJavaDate(cellValue.getNumberValue())); return calendar.getTime(); } else { return DECIMAL_FORMAT.format(cellValue.getNumberValue()); } } else if (cellValue.getCellType() == Cell.CELL_TYPE_STRING) { if (StringUtils.hasText(cellValue.getStringValue())) { return cellValue.getStringValue(); } } } catch (NotImplementedException e) { // If formula use Excel features not implemented in POI (like proper), // we can retrieve the cached value (which may no longer be correct, depending of what you do on your file). FormulaFeature feature = EnumUtils.getEnum(FormulaFeature.class, e.getCause().getMessage()); if (ALLOWED_NOT_IMPLEMENTED_FORMULA_FEATURES.contains(feature)) { return getCellPrimitiveValue(cell, cell.getCachedFormulaResultType()); } else { throw e; } } return null; }