org.apache.commons.lang3.EnumUtils Java Examples

The following examples show how to use org.apache.commons.lang3.EnumUtils. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: DiffDateExpressionProcessor.java    From vividus with Apache License 2.0 6 votes vote down vote up
@Override
public Optional<String> execute(String expression)
{
    Matcher expressionMatcher = DIFF_DATE_PATTERN.matcher(expression);
    if (expressionMatcher.find())
    {
        ZonedDateTime firstZonedDateTime = getZonedDateTime(expressionMatcher, FIRST_INPUT_DATE_GROUP,
                FIRST_INPUT_FORMAT_GROUP);
        ZonedDateTime secondZonedDateTime = getZonedDateTime(expressionMatcher, SECOND_INPUT_DATE_GROUP,
                SECOND_INPUT_FORMAT_GROUP);
        Duration duration = Duration.between(firstZonedDateTime, secondZonedDateTime);
        String durationAsString = duration.toString();
        return Optional.ofNullable(expressionMatcher.group(FORMAT_GROUP))
                       .map(String::trim)
                       .map(String::toUpperCase)
                       .map(t -> EnumUtils.getEnum(ChronoUnit.class, t))
                       .map(u -> u.between(firstZonedDateTime, secondZonedDateTime))
                       .map(Object::toString)
                       .or(() -> processNegative(duration, durationAsString));
    }
    return Optional.empty();
}
 
Example #2
Source File: JobTrigger.java    From spring-cloud-shop with MIT License 6 votes vote down vote up
/**
 * 获取正在运行的job任务
 *
 * @param scheduler scheduler
 */
public static List<JobInfo> getRunningJobs(Scheduler scheduler) throws SchedulerException {
    return Optional.ofNullable(scheduler.getCurrentlyExecutingJobs()).orElse(Collections.emptyList()).stream().map(context -> {
        JobDetail jobDetail = context.getJobDetail();
        Trigger trigger = context.getTrigger();
        JobKey jobKey = jobDetail.getKey();
        JobInfo job = new JobInfo();
        job.setJobName(jobKey.getName());
        job.setJobGroup(jobKey.getGroup());
        job.setDescription(String.format("触发器 ======== %s", trigger.getKey()));
        try {
            Trigger.TriggerState state = scheduler.getTriggerState(trigger.getKey());
            job.setJobStatus(EnumUtils.getEnum(JobStatusEnums.class, state.name()).getCode());
            if (trigger instanceof CronTrigger) {
                CronTrigger cronTrigger = (CronTrigger) trigger;
                job.setCron(cronTrigger.getCronExpression());
                return job;
            }
        } catch (SchedulerException e) {
            e.printStackTrace();
        }
        return null;
    }).filter(Objects::nonNull).collect(Collectors.toList());
}
 
Example #3
Source File: JobTrigger.java    From spring-cloud-shop with MIT License 6 votes vote down vote up
/**
 * 获取所有job任务
 */
public static List<JobInfo> getJobs(Scheduler scheduler) throws SchedulerException {
    GroupMatcher<JobKey> matcher = GroupMatcher.anyJobGroup();

    List<JobInfo> jobs = Lists.newArrayList();
    Set<JobKey> jobKeys = scheduler.getJobKeys(matcher);

    for (JobKey jobKey : jobKeys) {
        List<? extends Trigger> triggers = scheduler.getTriggersOfJob(jobKey);
        for (Trigger trigger : triggers) {

            JobInfo event = new JobInfo();
            event.setJobName(jobKey.getName());
            event.setJobGroup(jobKey.getGroup());
            event.setDescription(String.format("触发器 ======== %s", trigger.getKey()));
            Trigger.TriggerState state = scheduler.getTriggerState(trigger.getKey());
            event.setJobStatus(EnumUtils.getEnum(JobStatusEnums.class, state.name()).getCode());
            if (trigger instanceof CronTrigger) {
                CronTrigger cronTrigger = (CronTrigger) trigger;
                event.setCron(cronTrigger.getCronExpression());
                jobs.add(event);
            }
        }
    }
    return jobs;
}
 
Example #4
Source File: SMSServiceImpl.java    From spring-cloud-shop with MIT License 6 votes vote down vote up
@Override
public Response<String> sendSms(String phone, String event) {

    SMSCodeEnums smsCodeEnums = EnumUtils.getEnum(SMSCodeEnums.class, event);

    if (Objects.isNull(smsCodeEnums)) {
        return new Response<>(ResponseStatus.Code.FAIL_CODE, "未找到短信发送渠道");
    }

    Response<SMSTemplateResponse> templateResponse = smsTemplateService.sms(smsCodeEnums.getCode());

    // 模板查询未成功
    if (ResponseStatus.Code.SUCCESS != templateResponse.getCode()) {
        return new Response<>(templateResponse.getCode(), templateResponse.getMsg());
    }

    String content = templateResponse.getData().getTemplateContent();

    return new Response<>(getContent(smsCodeEnums, content, phone));
}
 
Example #5
Source File: RequestHelper.java    From azure-cosmosdb-java with MIT License 6 votes vote down vote up
public static ConsistencyLevel GetConsistencyLevelToUse(GatewayServiceConfigurationReader serviceConfigReader,
                                                        RxDocumentServiceRequest request) throws DocumentClientException {
    ConsistencyLevel consistencyLevelToUse = serviceConfigReader.getDefaultConsistencyLevel();

    String requestConsistencyLevelHeaderValue = request.getHeaders().get(HttpConstants.HttpHeaders.CONSISTENCY_LEVEL);

    if (!Strings.isNullOrEmpty(requestConsistencyLevelHeaderValue)) {
        ConsistencyLevel requestConsistencyLevel = EnumUtils.getEnum(ConsistencyLevel.class, requestConsistencyLevelHeaderValue);
        if (requestConsistencyLevel == null) {
            throw new BadRequestException(
                    String.format(
                            RMResources.InvalidHeaderValue,
                            requestConsistencyLevelHeaderValue,
                            HttpConstants.HttpHeaders.CONSISTENCY_LEVEL));
        }

        consistencyLevelToUse = requestConsistencyLevel;
    }

    return consistencyLevelToUse;
}
 
Example #6
Source File: ServerStoreModel.java    From azure-cosmosdb-java with MIT License 6 votes vote down vote up
public Observable<RxDocumentServiceResponse> processMessage(RxDocumentServiceRequest request) {
    String requestConsistencyLevelHeaderValue = request.getHeaders().get(HttpConstants.HttpHeaders.CONSISTENCY_LEVEL);

    request.requestContext.originalRequestConsistencyLevel = null;

    if (!Strings.isNullOrEmpty(requestConsistencyLevelHeaderValue)) {
        ConsistencyLevel requestConsistencyLevel;

        if ((requestConsistencyLevel = EnumUtils.getEnum(ConsistencyLevel.class, requestConsistencyLevelHeaderValue)) == null) {
            return Observable.error(new BadRequestException(
                String.format(
                    RMResources.InvalidHeaderValue,
                    requestConsistencyLevelHeaderValue,
                    HttpConstants.HttpHeaders.CONSISTENCY_LEVEL)));
        }

        request.requestContext.originalRequestConsistencyLevel = requestConsistencyLevel;
    }

    if (ReplicatedResourceClient.isMasterResource(request.getResourceType())) {
        request.getHeaders().put(HttpConstants.HttpHeaders.CONSISTENCY_LEVEL, ConsistencyLevel.Strong.toString());
    }

    Single<RxDocumentServiceResponse> response = this.storeClient.processMessageAsync(request);
    return response.toObservable();
}
 
Example #7
Source File: CgmesModelTripleStore.java    From powsybl-core with Mozilla Public License 2.0 6 votes vote down vote up
@Override
public void add(String context, String type, PropertyBags objects) {
    String contextName = EnumUtils.isValidEnum(CgmesSubset.class, context)
        ? contextNameFor(CgmesSubset.valueOf(context))
        : context;
    try {
        if (type.equals(CgmesNames.FULL_MODEL)) {
            tripleStore.add(contextName, mdNamespace(), type, objects);
        } else {
            tripleStore.add(contextName, cimNamespace, type, objects);
        }
    } catch (TripleStoreException x) {
        String msg = String.format("Adding objects of type %s to context %s", type, context);
        throw new CgmesModelException(msg, x);
    }
}
 
Example #8
Source File: ActionListWithReferenceTypeWithReference.java    From o2oa with GNU Affero General Public License v3.0 6 votes vote down vote up
ActionResult<List<Wo>> execute(EffectivePerson effectivePerson, String referenceTypeString, String reference)
		throws Exception {
	try (EntityManagerContainer emc = EntityManagerContainerFactory.instance().create()) {
		ActionResult<List<Wo>> result = new ActionResult<>();
		Business business = new Business(emc);
		ReferenceType referenceType = EnumUtils.getEnum(ReferenceType.class, referenceTypeString);
		if (null == referenceType) {
			throw new ExceptionInvalidReferenceType(referenceTypeString);
		}
		if (StringUtils.isEmpty(reference)) {
			throw new ExceptionEmptyReference(reference);
		}
		List<String> ids = business.file().listWithReferenceTypeWithReference(referenceType, reference);
		List<Wo> wos = Wo.copier.copy(emc.list(File.class, ids));
		wos = wos.stream().sorted(Comparator.comparing(File::getName, Comparator.nullsLast(String::compareTo)))
				.collect(Collectors.toList());
		result.setData(wos);
		return result;
	}
}
 
Example #9
Source File: UserRoleManage.java    From bbs with GNU Affero General Public License v3.0 6 votes vote down vote up
/**
 * 处理标签资源
 * @param resourceGroupCode 资源组编号
 * @return
 */
private List<UserResource> processingTagResource(Integer resourceGroupCode){
	List<UserResource> userResourceList = new ArrayList<UserResource>();
	
	List<ResourceEnum> resourceEnumList = EnumUtils.getEnumList(ResourceEnum.class);
	if(resourceEnumList != null && resourceEnumList.size() >0){
		for(ResourceEnum resourceEnum:  resourceEnumList){
			
			if(resourceEnum.getResourceGroupCode().equals(resourceGroupCode)){
				UserResource userResource = new UserResource();
				userResource.setCode(resourceEnum.getCode());
				userResource.setName(resourceEnum.getName());
				userResource.setResourceGroupCode(resourceEnum.getResourceGroupCode());
				userResourceList.add(userResource);
			}
			
			
		}
	}
	return userResourceList;
}
 
Example #10
Source File: FileRemoveQueue.java    From o2oa with GNU Affero General Public License v3.0 6 votes vote down vote up
@Override
protected void execute(Map<String, String> map) throws Exception {
	String reference = map.get(REFERENCE);
	String referenceTypeString = map.get(REFERENCETYPE);
	ReferenceType referenceType = EnumUtils.getEnum(ReferenceType.class, referenceTypeString);
	if (StringUtils.isEmpty(reference) || (null == referenceType)) {
		logger.warn("接收到无效的删除文件请求, referenceType: {}, reference: {}.", referenceTypeString, reference);
	} else {
		try (EntityManagerContainer emc = EntityManagerContainerFactory.instance().create()) {
			Business business = new Business(emc);
			List<String> ids = business.file().listWithReferenceTypeWithReference(referenceType, reference);
			for (File o : emc.list(File.class, ids)) {
				StorageMapping mapping = ThisApplication.context().storageMappings().get(File.class,
						o.getStorage());
				if (null == mapping) {
					throw new ExceptionStorageMappingNotExisted(o.getStorage());
				} else {
					o.deleteContent(mapping);
					emc.beginTransaction(File.class);
					emc.remove(o);
					emc.commit();
				}
			}
		}
	}
}
 
Example #11
Source File: ActionCopy.java    From o2oa with GNU Affero General Public License v3.0 6 votes vote down vote up
ActionResult<Wo> execute(EffectivePerson effectivePerson, String attachmentId, String referenceTypeString,
		String reference, Integer scale) throws Exception {
	ActionResult<Wo> result = new ActionResult<>();
	try (EntityManagerContainer emc = EntityManagerContainerFactory.instance().create()) {
		Business business = new Business(emc);
		ReferenceType referenceType = EnumUtils.getEnum(ReferenceType.class, referenceTypeString);
		if (null == referenceType) {
			throw new ExceptionInvalidReferenceType(referenceTypeString);
		}
		if (StringUtils.isEmpty(reference)) {
			throw new ExceptionEmptyReference(reference);
		}
		Attachment attachment = emc.find(attachmentId, Attachment.class);
		if (null == attachment) {
			throw new ExceptionAttachmentNotExisted(attachmentId);
		}
		if (effectivePerson.isNotManager() && effectivePerson.isNotPerson(attachment.getPerson())) {
			throw new ExceptionAttachmentAccessDenied(effectivePerson.getDistinguishedName(), attachment.getName(),
					attachment.getId());
		}
		String id = this.copy(effectivePerson, business, referenceType, reference, attachment, scale);
		Wo wo = new Wo();
		wo.setId(id);
		return result;
	}
}
 
Example #12
Source File: ActionListWithReferenceTypeWithReference.java    From o2oa with GNU Affero General Public License v3.0 6 votes vote down vote up
ActionResult<List<Wo>> execute(EffectivePerson effectivePerson, String referenceTypeString, String reference)
		throws Exception {
	try (EntityManagerContainer emc = EntityManagerContainerFactory.instance().create()) {
		ActionResult<List<Wo>> result = new ActionResult<>();
		Business business = new Business(emc);
		ReferenceType referenceType = EnumUtils.getEnum(ReferenceType.class, referenceTypeString);
		if (null == referenceType) {
			throw new ExceptionInvalidReferenceType(referenceTypeString);
		}
		if (StringUtils.isEmpty(reference)) {
			throw new ExceptionEmptyReference(reference);
		}
		List<String> ids = business.file().listWithReferenceTypeWithReference(referenceType, reference);
		List<Wo> wos = Wo.copier.copy(emc.list(File.class, ids));
		wos = wos.stream().sorted(Comparator.comparing(File::getName, Comparator.nullsLast(String::compareTo)))
				.collect(Collectors.toList());
		result.setData(wos);
		return result;
	}
}
 
Example #13
Source File: ActionCopy.java    From o2oa with GNU Affero General Public License v3.0 6 votes vote down vote up
ActionResult<Wo> execute(EffectivePerson effectivePerson, String attachmentId, String referenceTypeString,
		String reference, Integer scale) throws Exception {
	ActionResult<Wo> result = new ActionResult<>();
	try (EntityManagerContainer emc = EntityManagerContainerFactory.instance().create()) {
		Business business = new Business(emc);
		ReferenceType referenceType = EnumUtils.getEnum(ReferenceType.class, referenceTypeString);
		if (null == referenceType) {
			throw new ExceptionInvalidReferenceType(referenceTypeString);
		}
		if (StringUtils.isEmpty(reference)) {
			throw new ExceptionEmptyReference(reference);
		}
		Attachment attachment = emc.find(attachmentId, Attachment.class);
		if (null == attachment) {
			throw new ExceptionAttachmentNotExisted(attachmentId);
		}
		if (effectivePerson.isNotManager() && effectivePerson.isNotPerson(attachment.getPerson())) {
			throw new ExceptionAttachmentAccessDenied(effectivePerson.getDistinguishedName(), attachment.getName(),
					attachment.getId());
		}
		String id = this.copy(effectivePerson, business, referenceType, reference, attachment, scale);
		Wo wo = new Wo();
		wo.setId(id);
		return result;
	}
}
 
Example #14
Source File: EventPushParser.java    From wechat-mp-sdk with Apache License 2.0 6 votes vote down vote up
@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;
}
 
Example #15
Source File: ReplyUtil.java    From wechat-mp-sdk with Apache License 2.0 6 votes vote down vote up
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;
}
 
Example #16
Source File: FileRemoveQueue.java    From o2oa with GNU Affero General Public License v3.0 6 votes vote down vote up
@Override
protected void execute(Map<String, String> map) throws Exception {
	String reference = map.get(REFERENCE);
	String referenceTypeString = map.get(REFERENCETYPE);
	ReferenceType referenceType = EnumUtils.getEnum(ReferenceType.class, referenceTypeString);
	if (StringUtils.isEmpty(reference) || (null == referenceType)) {
		logger.warn("接收到无效的删除文件请求, referenceType: {}, reference: {}.", referenceTypeString, reference);
	} else {
		try (EntityManagerContainer emc = EntityManagerContainerFactory.instance().create()) {
			Business business = new Business(emc);
			List<String> ids = business.file().listWithReferenceTypeWithReference(referenceType, reference);
			for (File o : emc.list(File.class, ids)) {
				StorageMapping mapping = ThisApplication.context().storageMappings().get(File.class,
						o.getStorage());
				if (null == mapping) {
					throw new ExceptionStorageMappingNotExisted(o.getStorage());
				} else {
					o.deleteContent(mapping);
					emc.beginTransaction(File.class);
					emc.remove(o);
					emc.commit();
				}
			}
		}
	}
}
 
Example #17
Source File: PushTest.java    From wechat-mp-sdk with Apache License 2.0 6 votes vote down vote up
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");
    }
}
 
Example #18
Source File: DescriptorMetadataActions.java    From blackduck-alert with Apache License 2.0 6 votes vote down vote up
private Set<DescriptorMetadata> getDescriptors(@Nullable String name, @Nullable String type, @Nullable String context,
    BiFunction<Set<Descriptor>, ConfigContextEnum, Set<DescriptorMetadata>> generatorFunction) {
    Predicate<Descriptor> filter = Descriptor::hasUIConfigs;
    if (name != null) {
        filter = filter.and(descriptor -> name.equalsIgnoreCase(descriptor.getDescriptorKey().getUniversalKey()));
    }

    DescriptorType typeEnum = EnumUtils.getEnumIgnoreCase(DescriptorType.class, type);
    if (typeEnum != null) {
        filter = filter.and(descriptor -> typeEnum.equals(descriptor.getType()));
    } else if (type != null) {
        return Set.of();
    }

    ConfigContextEnum contextEnum = EnumUtils.getEnumIgnoreCase(ConfigContextEnum.class, context);
    if (contextEnum != null) {
        filter = filter.and(descriptor -> descriptor.hasUIConfigForType(contextEnum));
    } else if (context != null) {
        return Set.of();
    }

    Set<Descriptor> filteredDescriptors = filter(descriptors, filter);
    return generatorFunction.apply(filteredDescriptors, contextEnum);
}
 
Example #19
Source File: GaEnumUtils.java    From jvm-sandbox with GNU Lesser General Public License v3.0 6 votes vote down vote up
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;
}
 
Example #20
Source File: EnumExcelConverter.java    From easyexcel-utils with Apache License 2.0 6 votes vote down vote up
@Override
public Enum convertToJavaData(CellData cellData, ExcelContentProperty contentProperty, GlobalConfiguration globalConfiguration) {
    String cellDataStr = cellData.getStringValue();

    EnumFormat annotation = contentProperty.getField().getAnnotation(EnumFormat.class);
    Class enumClazz = annotation.value();
    String[] fromExcel = annotation.fromExcel();
    String[] toJavaEnum = annotation.toJavaEnum();

    Enum anEnum = null;
    if (ArrayUtils.isNotEmpty(fromExcel) && ArrayUtils.isNotEmpty(toJavaEnum)) {
        Assert.isTrue(fromExcel.length == toJavaEnum.length, "fromExcel 与 toJavaEnum 的长度必须相同");
        for (int i = 0; i < fromExcel.length; i++) {
            if (Objects.equals(fromExcel[i], cellDataStr)) {
                anEnum = EnumUtils.getEnum(enumClazz, toJavaEnum[i]);
            }
        }
    } else {
        anEnum = EnumUtils.getEnum(enumClazz, cellDataStr);
    }

    Assert.notNull(anEnum, "枚举值不合法");
    return anEnum;
}
 
Example #21
Source File: DateTimeGranularitySpec.java    From incubator-pinot with Apache License 2.0 5 votes vote down vote up
/**
 * Check correctness of granularity of {@link DateTimeFieldSpec}
 * @param granularity
 * @return
 */
public static boolean isValidGranularity(String granularity) {
  Preconditions.checkNotNull(granularity);
  String[] granularityTokens = granularity.split(COLON_SEPARATOR);
  Preconditions.checkArgument(granularityTokens.length == MAX_GRANULARITY_TOKENS, GRANULARITY_TOKENS_ERROR_STR);
  Preconditions.checkArgument(granularityTokens[GRANULARITY_SIZE_POSITION].matches(NUMBER_REGEX),
      GRANULARITY_PATTERN_ERROR_STR);
  Preconditions.checkArgument(EnumUtils.isValidEnum(TimeUnit.class, granularityTokens[GRANULARITY_UNIT_POSITION]),
      GRANULARITY_PATTERN_ERROR_STR);

  return true;
}
 
Example #22
Source File: FilterableEnumUtils.java    From synopsys-detect with Apache License 2.0 5 votes vote down vote up
public static <T extends Enum<T>> List<T> populatedValues(@NotNull List<FilterableEnumValue<T>> filterableList, Class<T> enumClass) {
    if (FilterableEnumUtils.containsNone(filterableList)) {
        return new ArrayList<>();
    } else if (FilterableEnumUtils.containsAll(filterableList)) {
        return EnumUtils.getEnumList(enumClass);
    } else {
        return FilterableEnumUtils.toPresentValues(filterableList);
    }
}
 
Example #23
Source File: HttpResourceFetcher.java    From apiman with Apache License 2.0 5 votes vote down vote up
public HttpResourceFetcher(Vertx vertx, URI uri, Map<String, String> config, boolean isHttps) {
    this.vertx = vertx;
    this.uri = uri;
    this.isHttps = isHttps;
    this.config = config;

    String authString = config.getOrDefault("auth", "NONE").toUpperCase();
    Arguments.require(EnumUtils.isValidEnum(AuthType.class, authString), "auth must be one of: " + AuthType.all());
    authenticator = AuthType.valueOf(authString).getAuthenticator();
    authenticator.validateConfig(config);
}
 
Example #24
Source File: Utils.java    From Java-Library with MIT License 5 votes vote down vote up
private static ApiError checkQueryParams(String query) {
    if (!EnumUtils.isValidEnum(QueryParams.class, query)) {
        return Utils.convertToApiError(setError("Please provide a proper query, refer to the documentation for more information", 14));
    }

    return null;
}
 
Example #25
Source File: DateTimeFormatUnitSpec.java    From incubator-pinot with Apache License 2.0 5 votes vote down vote up
public DateTimeFormatUnitSpec(String unit) {
  if (!isValidUnitSpec(unit)) {
    throw new IllegalArgumentException("Unit must belong to enum TimeUnit or DateTimeTransformUnit");
  }
  if (EnumUtils.isValidEnum(TimeUnit.class, unit)) {
    _timeUnit = TimeUnit.valueOf(unit);
  }
  if (EnumUtils.isValidEnum(DateTimeTransformUnit.class, unit)) {
    _dateTimeTransformUnit = DateTimeTransformUnit.valueOf(unit);
  }
}
 
Example #26
Source File: SvType.java    From gatk with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
public static SortedSet<String> getKnownTypes() {
    final SortedSet<String> knownTypes = new TreeSet<>( EnumUtils.getEnumMap(SimpleSVType.SupportedType.class).keySet() );

    knownTypes.add(GATKSVVCFConstants.CPX_SV_SYB_ALT_ALLELE_STR);
    knownTypes.add(GATKSVVCFConstants.BREAKEND_STR);

    return Collections.unmodifiableSortedSet(knownTypes);
}
 
Example #27
Source File: ConfigurationFieldModelConverter.java    From blackduck-alert with Apache License 2.0 5 votes vote down vote up
public final Map<String, ConfigurationFieldModel> convertToConfigurationFieldModelMap(FieldModel fieldModel) throws AlertDatabaseConstraintException {
    ConfigContextEnum context = EnumUtils.getEnum(ConfigContextEnum.class, fieldModel.getContext());
    String descriptorName = fieldModel.getDescriptorName();
    DescriptorKey descriptorKey = descriptorMap.getDescriptorKey(descriptorName).orElseThrow(() -> new AlertDatabaseConstraintException("Could not find a Descriptor with the name: " + descriptorName));

    List<DefinedFieldModel> fieldsForContext = descriptorAccessor.getFieldsForDescriptor(descriptorKey, context);
    Map<String, ConfigurationFieldModel> configurationModels = new HashMap<>();
    for (DefinedFieldModel definedField : fieldsForContext) {
        fieldModel.getFieldValueModel(definedField.getKey())
            .flatMap(fieldValueModel -> convertFromDefinedFieldModel(definedField, fieldValueModel.getValues(), fieldValueModel.isSet()))
            .ifPresent(configurationFieldModel -> configurationModels.put(configurationFieldModel.getFieldKey(), configurationFieldModel));
    }

    return configurationModels;
}
 
Example #28
Source File: ConfigActions.java    From blackduck-alert with Apache License 2.0 5 votes vote down vote up
public FieldModel saveConfig(FieldModel fieldModel, DescriptorKey descriptorKey) throws AlertException {
    validateConfig(fieldModel, new HashMap<>());
    FieldModel modifiedFieldModel = fieldModelProcessor.performBeforeSaveAction(fieldModel);
    String context = modifiedFieldModel.getContext();
    Map<String, ConfigurationFieldModel> configurationFieldModelMap = modelConverter.convertToConfigurationFieldModelMap(modifiedFieldModel);
    ConfigurationModel configuration = configurationAccessor.createConfiguration(descriptorKey, EnumUtils.getEnum(ConfigContextEnum.class, context), configurationFieldModelMap.values());
    FieldModel dbSavedModel = modelConverter.convertToFieldModel(configuration);
    FieldModel afterSaveAction = fieldModelProcessor.performAfterSaveAction(dbSavedModel);
    return dbSavedModel.fill(afterSaveAction);
}
 
Example #29
Source File: LancamentoController.java    From ponto-inteligente-api with MIT License 5 votes vote down vote up
/**
 * 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;
}
 
Example #30
Source File: ConfigValidator.java    From J-Kinopoisk2IMDB with Apache License 2.0 5 votes vote down vote up
/**
 * 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!");
    }
}