Java Code Examples for org.springframework.util.ObjectUtils#isEmpty()

The following examples show how to use org.springframework.util.ObjectUtils#isEmpty() . 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: PropertyMatches.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
@Override
public String buildErrorMessage() {
	String propertyName = getPropertyName();
	String[] possibleMatches = getPossibleMatches();
	StringBuilder msg = new StringBuilder();
	msg.append("Bean property '");
	msg.append(propertyName);
	msg.append("' is not writable or has an invalid setter method. ");

	if (ObjectUtils.isEmpty(possibleMatches)) {
		msg.append("Does the parameter type of the setter match the return type of the getter?");
	}
	else {
		appendHintMessage(msg);
	}
	return msg.toString();
}
 
Example 2
Source File: CastorMarshaller.java    From spring4-understanding with Apache License 2.0 6 votes vote down vote up
/**
 * Create the Castor {@code XMLContext}. Subclasses can override this to create a custom context.
 * <p>The default implementation loads mapping files if defined, or the target class or packages if defined.
 * @return the created resolver
 * @throws MappingException when the mapping file cannot be loaded
 * @throws IOException in case of I/O errors
 * @see XMLContext#addMapping(org.exolab.castor.mapping.Mapping)
 * @see XMLContext#addClass(Class)
 */
protected XMLContext createXMLContext(Resource[] mappingLocations, Class<?>[] targetClasses,
		String[] targetPackages) throws MappingException, ResolverException, IOException {

	XMLContext context = new XMLContext();
	if (!ObjectUtils.isEmpty(mappingLocations)) {
		Mapping mapping = new Mapping();
		for (Resource mappingLocation : mappingLocations) {
			mapping.loadMapping(SaxResourceUtils.createInputSource(mappingLocation));
		}
		context.addMapping(mapping);
	}
	if (!ObjectUtils.isEmpty(targetClasses)) {
		context.addClasses(targetClasses);
	}
	if (!ObjectUtils.isEmpty(targetPackages)) {
		context.addPackages(targetPackages);
	}
	if (this.castorProperties != null) {
		for (Map.Entry<String, String> property : this.castorProperties.entrySet()) {
			context.setProperty(property.getKey(), property.getValue());
		}
	}
	return context;
}
 
Example 3
Source File: ResourceFieldLoader.java    From api-boot with Apache License 2.0 6 votes vote down vote up
/**
 * load method declared ResourceField Annotation List
 *
 * @param method declared method
 * @return ResourceField Annotation List
 */
public static List<ResourceField> getDeclaredResourceField(Method method) {
    List<ResourceField> resourceFieldList = new ArrayList();
    // single ResourceField Annotation
    ResourceField resourceField = method.getDeclaredAnnotation(ResourceField.class);
    if (!ObjectUtils.isEmpty(resourceField)) {
        resourceFieldList.add(resourceField);
    }

    // multiple ResourceField Annotation
    ResourceFields ResourceFields = method.getDeclaredAnnotation(ResourceFields.class);
    if (!ObjectUtils.isEmpty(ResourceFields)) {
        resourceFieldList.addAll(Arrays.asList(ResourceFields.value()));
    }

    return resourceFieldList;
}
 
Example 4
Source File: ContextConfigurationAttributes.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
/**
 * Construct a new {@link ContextConfigurationAttributes} instance for the
 * {@linkplain Class test class} that declared the
 * {@link ContextConfiguration @ContextConfiguration} annotation and its
 * corresponding attributes.
 * @param declaringClass the test class that declared {@code @ContextConfiguration}
 * @param locations the resource locations declared via {@code @ContextConfiguration}
 * @param classes the annotated classes declared via {@code @ContextConfiguration}
 * @param inheritLocations the {@code inheritLocations} flag declared via {@code @ContextConfiguration}
 * @param initializers the context initializers declared via {@code @ContextConfiguration}
 * @param inheritInitializers the {@code inheritInitializers} flag declared via {@code @ContextConfiguration}
 * @param name the name of level in the context hierarchy, or {@code null} if not applicable
 * @param contextLoaderClass the {@code ContextLoader} class declared via {@code @ContextConfiguration}
 * @throws IllegalArgumentException if the {@code declaringClass} or {@code contextLoaderClass} is
 * {@code null}
 */
public ContextConfigurationAttributes(
		Class<?> declaringClass, String[] locations, Class<?>[] classes, boolean inheritLocations,
		Class<? extends ApplicationContextInitializer<? extends ConfigurableApplicationContext>>[] initializers,
		boolean inheritInitializers, String name, Class<? extends ContextLoader> contextLoaderClass) {

	Assert.notNull(declaringClass, "declaringClass must not be null");
	Assert.notNull(contextLoaderClass, "contextLoaderClass must not be null");

	if (!ObjectUtils.isEmpty(locations) && !ObjectUtils.isEmpty(classes) && logger.isDebugEnabled()) {
		logger.debug(String.format(
				"Test class [%s] has been configured with @ContextConfiguration's 'locations' (or 'value') %s " +
						"and 'classes' %s attributes. Most SmartContextLoader implementations support " +
						"only one declaration of resources per @ContextConfiguration annotation.",
				declaringClass.getName(), ObjectUtils.nullSafeToString(locations),
				ObjectUtils.nullSafeToString(classes)));
	}

	this.declaringClass = declaringClass;
	this.locations = locations;
	this.classes = classes;
	this.inheritLocations = inheritLocations;
	this.initializers = initializers;
	this.inheritInitializers = inheritInitializers;
	this.name = (StringUtils.hasText(name) ? name : null);
	this.contextLoaderClass = contextLoaderClass;
}
 
Example 5
Source File: DataBinder.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Add a custom formatter for the field type specified in {@link Formatter} class,
 * applying it to the specified fields only, if any, or otherwise to all fields.
 * <p>Registers a corresponding {@link PropertyEditor} adapter underneath the covers.
 * @param formatter the formatter to add, generically declared for a specific type
 * @param fields the fields to apply the formatter to, or none if to be applied to all
 * @since 4.2
 * @see #registerCustomEditor(Class, String, PropertyEditor)
 */
public void addCustomFormatter(Formatter<?> formatter, String... fields) {
	FormatterPropertyEditorAdapter adapter = new FormatterPropertyEditorAdapter(formatter);
	Class<?> fieldType = adapter.getFieldType();
	if (ObjectUtils.isEmpty(fields)) {
		getPropertyEditorRegistry().registerCustomEditor(fieldType, adapter);
	}
	else {
		for (String field : fields) {
			getPropertyEditorRegistry().registerCustomEditor(fieldType, field, adapter);
		}
	}
}
 
Example 6
Source File: SockJsServiceRegistration.java    From spring-analysis-note with MIT License 5 votes vote down vote up
public SockJsServiceRegistration setTransportHandlerOverrides(TransportHandler... handlers) {
	this.transportHandlerOverrides.clear();
	if (!ObjectUtils.isEmpty(handlers)) {
		this.transportHandlerOverrides.addAll(Arrays.asList(handlers));
	}
	return this;
}
 
Example 7
Source File: SpringletsMvcUriComponentsBuilder.java    From springlets with Apache License 2.0 5 votes vote down vote up
private static String getTypeRequestMapping(Class<?> controllerType) {
	Assert.notNull(controllerType, "'controllerType' must not be null");
	RequestMapping requestMapping = AnnotatedElementUtils.findMergedAnnotation(controllerType, RequestMapping.class);
	if (requestMapping == null) {
		return "/";
	}
	String[] paths = requestMapping.path();
	if (ObjectUtils.isEmpty(paths) || StringUtils.isEmpty(paths[0])) {
		return "/";
	}
	if (paths.length > 1 && logger.isWarnEnabled()) {
		logger.warn("Multiple paths on controller {}, using first one", controllerType.getName());
	}
	return paths[0];
}
 
Example 8
Source File: ClassArrayEditor.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
@Override
public String getAsText() {
	Class<?>[] classes = (Class[]) getValue();
	if (ObjectUtils.isEmpty(classes)) {
		return "";
	}
	StringBuilder sb = new StringBuilder();
	for (int i = 0; i < classes.length; ++i) {
		if (i > 0) {
			sb.append(",");
		}
		sb.append(ClassUtils.getQualifiedName(classes[i]));
	}
	return sb.toString();
}
 
Example 9
Source File: UriComponentsBuilder.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
public void addPathSegments(String... pathSegments) {
	if (!ObjectUtils.isEmpty(pathSegments)) {
		PathSegmentComponentBuilder psBuilder = getLastBuilder(PathSegmentComponentBuilder.class);
		FullPathComponentBuilder fpBuilder = getLastBuilder(FullPathComponentBuilder.class);
		if (psBuilder == null) {
			psBuilder = new PathSegmentComponentBuilder();
			this.builders.add(psBuilder);
			if (fpBuilder != null) {
				fpBuilder.removeTrailingSlash();
			}
		}
		psBuilder.append(pathSegments);
	}
}
 
Example 10
Source File: LdapSyncTaskJob.java    From incubator-wikift with Apache License 2.0 5 votes vote down vote up
private String getUserName(LdapUserModel userModel) {
    for (String s : default_username) {
        Object result = ReflectUtils.getFieldValue(s, userModel);
        if (ObjectUtils.isEmpty(result)) {
            continue;
        }
        return String.valueOf(result);
    }
    return null;
}
 
Example 11
Source File: PropertyMatches.java    From java-technology-stack with MIT License 5 votes vote down vote up
@Override
public String buildErrorMessage() {
	StringBuilder msg = new StringBuilder(80);
	msg.append("Bean property '").append(getPropertyName()).append("' has no matching field.");
	if (!ObjectUtils.isEmpty(getPossibleMatches())) {
		msg.append(' ');
		appendHintMessage(msg);
	}
	return msg.toString();
}
 
Example 12
Source File: PayloadMethodArgumentResolver.java    From spring-analysis-note with MIT License 5 votes vote down vote up
@Nullable
private Consumer<Object> getValidator(Message<?> message, MethodParameter parameter) {
	if (this.validator == null) {
		return null;
	}
	for (Annotation ann : parameter.getParameterAnnotations()) {
		Validated validatedAnn = AnnotationUtils.getAnnotation(ann, Validated.class);
		if (validatedAnn != null || ann.annotationType().getSimpleName().startsWith("Valid")) {
			Object hints = (validatedAnn != null ? validatedAnn.value() : AnnotationUtils.getValue(ann));
			Object[] validationHints = (hints instanceof Object[] ? (Object[]) hints : new Object[] {hints});
			String name = Conventions.getVariableNameForParameter(parameter);
			return target -> {
				BeanPropertyBindingResult bindingResult = new BeanPropertyBindingResult(target, name);
				if (!ObjectUtils.isEmpty(validationHints) && this.validator instanceof SmartValidator) {
					((SmartValidator) this.validator).validate(target, bindingResult, validationHints);
				}
				else {
					this.validator.validate(target, bindingResult);
				}
				if (bindingResult.hasErrors()) {
					throw new MethodArgumentNotValidException(message, parameter, bindingResult);
				}
			};
		}
	}
	return null;
}
 
Example 13
Source File: UserReadRecordService.java    From api-boot with Apache License 2.0 5 votes vote down vote up
/**
 * 执行添加阅读记录
 * 如果已经存阅读记录进行更新时间
 * 如果不存在执行添加
 *
 * @param userId    用户编号
 * @param articleId 文章编号
 * @throws KnowledgeException
 */
public void insertReadRecord(String userId, String articleId) throws KnowledgeException {
    UserReadRecordEntity readRecordEntity = selectReadRecord(userId, articleId);
    if (ObjectUtils.isEmpty(readRecordEntity)) {
        // 执行添加阅读记录
        readRecordEntity = UserReadRecordStruct.INSTANCE.from(userId, articleId);
        userReadRecordMapper.insert(readRecordEntity);
    } else {
        // 更新阅读时间为当前时间
        readRecordEntity.setUrrCreateTime(new Timestamp(System.currentTimeMillis()));
        userReadRecordMapper.update(readRecordEntity);
    }
}
 
Example 14
Source File: WebContentGenerator.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Set the HTTP methods that this content generator should support.
 * <p>Default is GET, HEAD and POST for simple form controller types;
 * unrestricted for general controllers and interceptors.
 */
public final void setSupportedMethods(String... methods) {
	if (!ObjectUtils.isEmpty(methods)) {
		this.supportedMethods = new LinkedHashSet<String>(Arrays.asList(methods));
	}
	else {
		this.supportedMethods = null;
	}
	initAllowHeader();
}
 
Example 15
Source File: ProxyFactoryBean.java    From lams with GNU General Public License v2.0 4 votes vote down vote up
/**
 * Create the advisor (interceptor) chain. Advisors that are sourced
 * from a BeanFactory will be refreshed each time a new prototype instance
 * is added. Interceptors added programmatically through the factory API
 * are unaffected by such changes.
 */
private synchronized void initializeAdvisorChain() throws AopConfigException, BeansException {
	if (this.advisorChainInitialized) {
		return;
	}

	if (!ObjectUtils.isEmpty(this.interceptorNames)) {
		if (this.beanFactory == null) {
			throw new IllegalStateException("No BeanFactory available anymore (probably due to serialization) " +
					"- cannot resolve interceptor names " + Arrays.asList(this.interceptorNames));
		}

		// Globals can't be last unless we specified a targetSource using the property...
		if (this.interceptorNames[this.interceptorNames.length - 1].endsWith(GLOBAL_SUFFIX) &&
				this.targetName == null && this.targetSource == EMPTY_TARGET_SOURCE) {
			throw new AopConfigException("Target required after globals");
		}

		// Materialize interceptor chain from bean names.
		for (String name : this.interceptorNames) {
			if (logger.isTraceEnabled()) {
				logger.trace("Configuring advisor or advice '" + name + "'");
			}

			if (name.endsWith(GLOBAL_SUFFIX)) {
				if (!(this.beanFactory instanceof ListableBeanFactory)) {
					throw new AopConfigException(
							"Can only use global advisors or interceptors with a ListableBeanFactory");
				}
				addGlobalAdvisor((ListableBeanFactory) this.beanFactory,
						name.substring(0, name.length() - GLOBAL_SUFFIX.length()));
			}

			else {
				// If we get here, we need to add a named interceptor.
				// We must check if it's a singleton or prototype.
				Object advice;
				if (this.singleton || this.beanFactory.isSingleton(name)) {
					// Add the real Advisor/Advice to the chain.
					advice = this.beanFactory.getBean(name);
				}
				else {
					// It's a prototype Advice or Advisor: replace with a prototype.
					// Avoid unnecessary creation of prototype bean just for advisor chain initialization.
					advice = new PrototypePlaceholderAdvisor(name);
				}
				addAdvisorOnChainCreation(advice, name);
			}
		}
	}

	this.advisorChainInitialized = true;
}
 
Example 16
Source File: AnnotationReadingVisitorUtils.java    From spring4-understanding with Apache License 2.0 4 votes vote down vote up
/**
 * Retrieve the merged attributes of the annotation of the given type,
 * if any, from the supplied {@code attributesMap}.
 * <p>Annotation attribute values appearing <em>lower</em> in the annotation
 * hierarchy (i.e., closer to the declaring class) will override those
 * defined <em>higher</em> in the annotation hierarchy.
 * @param attributesMap the map of annotation attribute lists, keyed by
 * annotation type name
 * @param metaAnnotationMap the map of meta annotation relationships,
 * keyed by annotation type name
 * @param annotationName the fully qualified class name of the annotation
 * type to look for
 * @return the merged annotation attributes, or {@code null} if no
 * matching annotation is present in the {@code attributesMap}
 * @since 4.0.3
 */
public static AnnotationAttributes getMergedAnnotationAttributes(
		LinkedMultiValueMap<String, AnnotationAttributes> attributesMap,
		Map<String, Set<String>> metaAnnotationMap, String annotationName) {

	// Get the unmerged list of attributes for the target annotation.
	List<AnnotationAttributes> attributesList = attributesMap.get(annotationName);
	if (attributesList == null || attributesList.isEmpty()) {
		return null;
	}

	// To start with, we populate the results with a copy of all attribute
	// values from the target annotation. A copy is necessary so that we do
	// not inadvertently mutate the state of the metadata passed to this
	// method.
	AnnotationAttributes results = new AnnotationAttributes(attributesList.get(0));

	Set<String> overridableAttributeNames = new HashSet<String>(results.keySet());
	overridableAttributeNames.remove(AnnotationUtils.VALUE);

	// Since the map is a LinkedMultiValueMap, we depend on the ordering of
	// elements in the map and reverse the order of the keys in order to traverse
	// "down" the annotation hierarchy.
	List<String> annotationTypes = new ArrayList<String>(attributesMap.keySet());
	Collections.reverse(annotationTypes);

	// No need to revisit the target annotation type:
	annotationTypes.remove(annotationName);

	for (String currentAnnotationType : annotationTypes) {
		List<AnnotationAttributes> currentAttributesList = attributesMap.get(currentAnnotationType);
		if (!ObjectUtils.isEmpty(currentAttributesList)) {
			Set<String> metaAnns = metaAnnotationMap.get(currentAnnotationType);
			if (metaAnns != null && metaAnns.contains(annotationName)) {
				AnnotationAttributes currentAttributes = currentAttributesList.get(0);
				for (String overridableAttributeName : overridableAttributeNames) {
					Object value = currentAttributes.get(overridableAttributeName);
					if (value != null) {
						// Store the value, potentially overriding a value from an
						// attribute of the same name found higher in the annotation
						// hierarchy.
						results.put(overridableAttributeName, value);
					}
				}
			}
		}
	}

	return results;
}
 
Example 17
Source File: GenUtil.java    From yshopmall with Apache License 2.0 4 votes vote down vote up
/**
 * 定义后端文件路径以及名称
 */
private static String getAdminFilePath(String templateName, GenConfig genConfig, String className, String rootPath) {
    String projectPath = rootPath + File.separator + genConfig.getModuleName();
    String packagePath = projectPath + File.separator + "src" +File.separator+ "main" + File.separator + "java" + File.separator;
    if (!ObjectUtils.isEmpty(genConfig.getPack())) {
        packagePath += genConfig.getPack().replace(".", File.separator) + File.separator;
    }

    if ("Entity".equals(templateName)) {
        return packagePath + "domain" + File.separator + className + ".java";
    }
    if ("EntityP".equals(templateName)) {
        return packagePath + "domain" + File.separator + className + ".java";
    }
    if ("Controller".equals(templateName)) {
        return packagePath + "rest" + File.separator + className + "Controller.java";
    }
    if ("ControllerP".equals(templateName)) {
        return packagePath + "rest" + File.separator + className + "Controller.java";
    }
    if ("Service".equals(templateName)) {
        return packagePath + "service" + File.separator + className + "Service.java";
    }
    if ("ServiceP".equals(templateName)) {
        return packagePath + "service" + File.separator + className + "Service.java";
    }

    if ("ServiceImpl".equals(templateName)) {
        return packagePath + "service" + File.separator + "impl" + File.separator + className + "ServiceImpl.java";
    }
    if ("ServiceImplP".equals(templateName)) {
        return packagePath + "service" + File.separator + "impl" + File.separator + className + "ServiceImpl.java";
    }

    if ("Dto".equals(templateName)) {
        return packagePath + "service" + File.separator + "dto" + File.separator + className + "Dto.java";
    }
    if ("DtoP".equals(templateName)) {
        return packagePath + "service" + File.separator + "dto" + File.separator + className + "Dto.java";
    }


    if ("QueryCriteria".equals(templateName)) {
        return packagePath + "service" + File.separator + "dto" + File.separator + className + "QueryCriteria.java";
    }
    if ("QueryCriteriaP".equals(templateName)) {
        return packagePath + "service" + File.separator + "dto" + File.separator + className + "QueryCriteria.java";
    }

    if ("Mapper".equals(templateName)) {
        return packagePath + "service" + File.separator + "mapper" + File.separator + className + "Mapper.java";
    }
    if ("MapperP".equals(templateName)) {
        return packagePath + "service" + File.separator + "mapper" + File.separator + className + "Mapper.java";
    }

    if ("Repository".equals(templateName)) {
        return packagePath + "repository" + File.separator + className + "Repository.java";
    }

    return null;
}
 
Example 18
Source File: SimpleJdbcTemplate.java    From effectivejava with Apache License 2.0 4 votes vote down vote up
@Override
public List<Map<String, Object>> queryForList(String sql, Object... args) throws DataAccessException {
	return (ObjectUtils.isEmpty(args) ?
			getJdbcOperations().queryForList(sql) :
			getJdbcOperations().queryForList(sql, getArguments(args)));
}
 
Example 19
Source File: ApiBootQuartzServiceDefaultSupport.java    From api-boot with Apache License 2.0 3 votes vote down vote up
/**
 * Pause based on the given jobKey collection
 * <p>
 * Iterate through each {@link ApiBootJobWrapper#getJobKey()} to pause the job
 * </p>
 *
 * @param jobKeys {@link ApiBootJobWrapper#getJobKey()} jobKey collection
 */
@Override
public void pauseJobs(Collection<String> jobKeys) {
    if (!ObjectUtils.isEmpty(jobKeys)) {
        jobKeys.forEach(jobKey -> pauseJob(jobKey));
    }
}
 
Example 20
Source File: BeanUtils.java    From spring-context-support with Apache License 2.0 3 votes vote down vote up
/**
 * Is Bean Present or not?
 *
 * @param beanFactory        {@link ListableBeanFactory}
 * @param beanClass          The  {@link Class} of Bean
 * @param includingAncestors including ancestors or not
 * @return If present , return <code>true</code> , or <code>false</code>
 */
public static boolean isBeanPresent(ListableBeanFactory beanFactory,
                                    Class<?> beanClass,
                                    boolean includingAncestors) {

    String[] beanNames = getBeanNames(beanFactory, beanClass, includingAncestors);

    return !ObjectUtils.isEmpty(beanNames);

}