Java Code Examples for org.springframework.util.StringUtils.hasText()

The following are Jave code examples for showing how to use hasText() of the org.springframework.util.StringUtils class. You can vote up the examples you like. Your votes will be used in our system to get more good examples.
+ Save this method
Example 1
Project: seldon-core   File: SeldonRestTemplateExchangeTagsProvider.java   View Source Code Vote up 6 votes
@Override
public Iterable<Tag> getTags(String urlTemplate, HttpRequest request, ClientHttpResponse response) 
{
	Tag uriTag = StringUtils.hasText(urlTemplate)? RestTemplateExchangeTags.uri(urlTemplate): RestTemplateExchangeTags.uri(request);
	
	
            
	return Arrays.asList(RestTemplateExchangeTags.method(request), uriTag,
			RestTemplateExchangeTags.status(response),
            RestTemplateExchangeTags.clientName(request),
            modelName(request),
            modelImage(request),
            modelVersion(request),
            projectName(),
            deploymentName(),
            deploymentVersion(),
            predictorName(),
            predictorVersion());
}
 
Example 2
Project: spring-microservice-sample   File: PostSpecifications.java   View Source Code Vote up 6 votes
public static Specification<Post> filterByKeywordAndStatus(
    final String keyword,//
    final Post.Status status) {
    return (Root<Post> root, CriteriaQuery<?> query, CriteriaBuilder cb) -> {
        List<Predicate> predicates = new ArrayList<>();
        if (StringUtils.hasText(keyword)) {
            predicates.add(
                cb.or(
                    cb.like(root.get(Post_.title), "%" + keyword + "%"),
                    cb.like(root.get(Post_.content), "%" + keyword + "%")
                )
            );
        }

        if (status != null) {
            predicates.add(cb.equal(root.get(Post_.status), status));
        }

        return cb.and(predicates.toArray(new Predicate[predicates.size()]));
    };
}
 
Example 3
Project: spring-cloud-skipper   File: ConfigValueUtils.java   View Source Code Vote up 6 votes
/**
 * Merge configuration values from the Package and values passed at runtime. Values passed
 * at runtime override those specified in the package. The ConfigValue string is assumed
 * to be in YAML format and parsed into a Map.
 * <p>
 * The values for dependencies of packages are also merged, which higher level packages
 * overriding lower level packages. Only one level of dependent packages are currently
 * supported.
 * <p>
 * @param pkg The package to be installed or upgraded.
 * @param overrideValues Configuration values pass in at runtime, when installing or
 * updating.
 * @return The merged configuration values.
 */
public static Map<String, Object> mergeConfigValues(Package pkg, ConfigValues overrideValues) {
	// parse ConfigValues to a map.
	Yaml yaml = new Yaml();
	Map<String, Object> mergedValues;
	// merge top level override values on top level package values
	if (StringUtils.hasText(overrideValues.getRaw())) {
		Object data = yaml.load(overrideValues.getRaw());
		if (data instanceof Map) {
			Map<String, Object> overrideMap = (Map<String, Object>) yaml.load(overrideValues.getRaw());
			mergedValues = mergeOverrideMap(pkg, overrideMap);
		}
		else {
			throw new SkipperException("Was expecting override values to produce a Map, instead got class = " +
					data.getClass() + "overrideValues.getRaw() = " + overrideValues.getRaw());
		}
	}
	else {
		mergedValues = mergeOverrideMap(pkg, new TreeMap<>());
	}
	// return mergedValues;
	return mergePackagesIncludingDependencies(pkg, mergedValues);
}
 
Example 4
Project: springboot-shiro-cas-mybatis   File: PrincipalFromRequestRemoteUserNonInteractiveCredentialsAction.java   View Source Code Vote up 6 votes
@Override
protected Credential constructCredentialsFromRequest(
        final RequestContext context) {
    final HttpServletRequest request = WebUtils
            .getHttpServletRequest(context);
    final String remoteUser = request.getRemoteUser();

    if (StringUtils.hasText(remoteUser)) {
        logger.debug("Remote  User [{}] found in HttpServletRequest", remoteUser);
        return new PrincipalBearingCredential(this.principalFactory.createPrincipal(remoteUser));
    }

    logger.debug("Remote User not found in HttpServletRequest.");

    return null;
}
 
Example 5
Project: bdf2   File: ReportMaintain.java   View Source Code Vote up 6 votes
@DataProvider
public Collection<ReportResource> loadResources(String definitionId){
	String hql="from "+ReportResource.class.getName()+" where reportDefinitionId=:definitionId";
	Map<String,Object> map=new HashMap<String,Object>();
	map.put("definitionId", definitionId);
	Collection<ReportResource> resources=this.query(hql, map);
	IFileService fileService=ContextHolder.getBean(IFileService.BEAN_ID);
	for(ReportResource res:resources){
		String resFile=res.getResourceFile();
		if(StringUtils.hasText(resFile)){
			UploadDefinition uploadDefinition=fileService.getUploadDefinition(resFile);
			if(uploadDefinition!=null){
				res.setResourceFileName(uploadDefinition.getFileName());
			}
		}
	}
	return resources;
}
 
Example 6
Project: lams   File: ScriptingDefaultsParser.java   View Source Code Vote up 5 votes
@Override
public BeanDefinition parse(Element element, ParserContext parserContext) {
	BeanDefinition bd =
			LangNamespaceUtils.registerScriptFactoryPostProcessorIfNecessary(parserContext.getRegistry());
	String refreshCheckDelay = element.getAttribute(REFRESH_CHECK_DELAY_ATTRIBUTE);
	if (StringUtils.hasText(refreshCheckDelay)) {
		bd.getPropertyValues().add("defaultRefreshCheckDelay", new Long(refreshCheckDelay));
	}
	String proxyTargetClass = element.getAttribute(PROXY_TARGET_CLASS_ATTRIBUTE);
	if (StringUtils.hasText(proxyTargetClass)) {
		bd.getPropertyValues().add("defaultProxyTargetClass", new TypedStringValue(proxyTargetClass, Boolean.class));
	}
	return null;
}
 
Example 7
Project: cstruct-parser   File: CjavaTcHeaderBeanDefinitionParser.java   View Source Code Vote up 5 votes
@Override
protected void doParse(Element element, BeanDefinitionBuilder builder)
{

	String key = element.getAttribute("key");
	
	builder.addPropertyValue("key", key);
	
	setDefault(element,builder);
	
	String className = element.getAttribute("class");
	if (StringUtils.hasText(className)) {
		builder.getBeanDefinition().setBeanClassName(className);
	}

	List<Element> childElts = DomUtils.getChildElements(element);
	// 解析fields
	if (CollectionUtils.isEmpty(childElts)) {
		throw new IllegalArgumentException("cjava:tc-header node must contain fields");
	}

	Field[] values = new Field[childElts.size()];
	for (int i = 0; i < childElts.size(); i++) {
		Element node = childElts.get(i);
		// 解析
		values[i] = parserField(node,false);
	}
	builder.addPropertyValue("fields", values);

}
 
Example 8
Project: lams   File: ControllerAdviceBean.java   View Source Code Vote up 5 votes
private static List<Package> initBasePackagesFromBeanType(Class<?> beanType, ControllerAdvice annotation) {
	List<Package> basePackages = new ArrayList<Package>();
	List<String> basePackageNames = new ArrayList<String>();
	basePackageNames.addAll(Arrays.asList(annotation.value()));
	basePackageNames.addAll(Arrays.asList(annotation.basePackages()));
	for (String pkgName : basePackageNames) {
		if (StringUtils.hasText(pkgName)) {
			Package pkg = Package.getPackage(pkgName);
			if(pkg != null) {
				basePackages.add(pkg);
			}
			else {
				logger.warn("Package [" + pkgName + "] was not found, see [" + beanType.getName() + "]");
			}
		}
	}
	for (Class<?> markerClass : annotation.basePackageClasses()) {
		Package pack = markerClass.getPackage();
		if (pack != null) {
			basePackages.add(pack);
		}
		else {
			logger.warn("Package was not found for class [" + markerClass.getName() +
					"], see [" + beanType.getName() + "]");
		}
	}
	return basePackages;
}
 
Example 9
Project: TorgCRM-Server   File: JWTFilter.java   View Source Code Vote up 5 votes
private String resolveToken(HttpServletRequest request){
    String bearerToken = request.getHeader(JWTConfigurer.AUTHORIZATION_HEADER);
    if (StringUtils.hasText(bearerToken) && bearerToken.startsWith("Bearer ")) {
        return bearerToken.substring(7, bearerToken.length());
    }
    return null;
}
 
Example 10
Project: jwala   File: ResponseMessageBodyWriter.java   View Source Code Vote up 5 votes
@Override
public void writeTo(ApplicationResponse t, Class<?> type, Type genericType, Annotation[] annotations,
        MediaType mediaType, MultivaluedMap<String, Object> httpHeaders, OutputStream entityStream)
        throws IOException {
    
    ByteArrayOutputStream boss = new ByteArrayOutputStream();
    ObjectMapper om = jsonProvider.locateMapper(type, MediaType.APPLICATION_JSON_TYPE);
    if(om != null) {
        jsonProvider.writeTo(t, type, genericType, annotations, MediaType.APPLICATION_JSON_TYPE, httpHeaders, boss);
        boss.flush();
    }

    Writer osWriter = new OutputStreamWriter(entityStream);
    String code, text, prefix;
    if(StringUtils.hasText(t.getMsgCode())) { 
        code = "400"; prefix = t.getMsgCode();
    } else {
        code = "200"; prefix = "";
    }
    if(StringUtils.hasText(t.getMessage())) { 
        text = prefix + " " + t.getMessage();
    } else {
        text = "ok";
    }
    osWriter.write("<html><body status='"+code+"' statusText='" + text + "'>");
    osWriter.flush();
    entityStream.write(boss.toByteArray());
    boss.close();
    osWriter.write("</body></html>");
    osWriter.close();
}
 
Example 11
Project: bean-grid   File: ColumnDefinition.java   View Source Code Vote up 5 votes
/**
 * @return Optional of format string that should be used for formatting the
 *         cell value. Most commonly used with number or date formats but
 *         can also be used to pad strings in textual fields etc.
 */
public Optional<String> getFormat() {
	if (StringUtils.hasText(columnDefinitionAnnotation.format())) {
		return Optional.of(columnDefinitionAnnotation.format());
	}

	return Optional.empty();
}
 
Example 12
Project: spring-data-ebean   File: StringQuery.java   View Source Code Vote up 5 votes
/**
 * Return the appropriate {@link ParameterBindingType} for the given {@link String}. Returns {@keyword #AS_IS} in
 * case no other {@link ParameterBindingType} could be found.
 *
 * @param typeSource
 * @return
 */
static ParameterBindingType of(String typeSource) {

  if (!StringUtils.hasText(typeSource)) {
    return AS_IS;
  }

  for (ParameterBindingType type : values()) {
    if (type.name().equalsIgnoreCase(typeSource.trim())) {
      return type;
    }
  }

  throw new IllegalArgumentException(String.format("Unsupported parameter binding type %s!", typeSource));
}
 
Example 13
Project: lams   File: PersistenceUnitReader.java   View Source Code Vote up 5 votes
/**
 * Parse the {@code class} XML elements.
 */
protected void parseManagedClasses(Element persistenceUnit, SpringPersistenceUnitInfo unitInfo) {
	List<Element> classes = DomUtils.getChildElementsByTagName(persistenceUnit, MANAGED_CLASS_NAME);
	for (Element element : classes) {
		String value = DomUtils.getTextValue(element).trim();
		if (StringUtils.hasText(value))
			unitInfo.addManagedClassName(value);
	}
}
 
Example 14
Project: parabuild-ci   File: DwrNamespaceHandler.java   View Source Code Vote up 5 votes
/**
 *  Try getting the beanClassName from the definition and if that fails try to get it from 
 *  the parent (and even parent BeanFactory if we have to).
 *  
 *  @param definition 
 *  @param registry
 *  @return class name or null if not found
 */
private String resolveBeanClassname(BeanDefinition definition, BeanDefinitionRegistry registry) 
{
    String beanClassName = definition.getBeanClassName();    
    if (!StringUtils.hasText(beanClassName)) 
    {
        while (definition instanceof ChildBeanDefinition )
        {
            String parentName = ((ChildBeanDefinition)definition).getParentName();                    
            BeanDefinition parentDefinition = findParentDefinition(parentName, registry);
            if (parentDefinition == null)
            {
                if (log.isDebugEnabled()) 
                {
                    log.debug("No parent bean named '" + parentName + "' could be found in the " + 
                              "hierarchy of BeanFactorys. Check you've defined a bean called '" + parentName + "'");
                }
                break;
            }
            beanClassName = parentDefinition.getBeanClassName();
            if (StringUtils.hasText(beanClassName ))
            {
                // found the class name we were looking for
                break;
            }
            definition = parentDefinition;
        }
    }
   
    return beanClassName;
}
 
Example 15
Project: lams   File: ConfigBeanDefinitionParser.java   View Source Code Vote up 5 votes
/**
 * Parses the {@code pointcut} or {@code pointcut-ref} attributes of the supplied
 * {@link Element} and add a {@code pointcut} property as appropriate. Generates a
 * {@link org.springframework.beans.factory.config.BeanDefinition} for the pointcut if  necessary
 * and returns its bean name, otherwise returns the bean name of the referred pointcut.
 */
private Object parsePointcutProperty(Element element, ParserContext parserContext) {
	if (element.hasAttribute(POINTCUT) && element.hasAttribute(POINTCUT_REF)) {
		parserContext.getReaderContext().error(
				"Cannot define both 'pointcut' and 'pointcut-ref' on <advisor> tag.",
				element, this.parseState.snapshot());
		return null;
	}
	else if (element.hasAttribute(POINTCUT)) {
		// Create a pointcut for the anonymous pc and register it.
		String expression = element.getAttribute(POINTCUT);
		AbstractBeanDefinition pointcutDefinition = createPointcutDefinition(expression);
		pointcutDefinition.setSource(parserContext.extractSource(element));
		return pointcutDefinition;
	}
	else if (element.hasAttribute(POINTCUT_REF)) {
		String pointcutRef = element.getAttribute(POINTCUT_REF);
		if (!StringUtils.hasText(pointcutRef)) {
			parserContext.getReaderContext().error(
					"'pointcut-ref' attribute contains empty value.", element, this.parseState.snapshot());
			return null;
		}
		return pointcutRef;
	}
	else {
		parserContext.getReaderContext().error(
				"Must define one of 'pointcut' or 'pointcut-ref' on <advisor> tag.",
				element, this.parseState.snapshot());
		return null;
	}
}
 
Example 16
Project: springboot-shiro-cas-mybatis   File: SamlService.java   View Source Code Vote up 4 votes
/**
 * Creates the SAML service from the request.
 *
 * @param request the request
 * @return the SAML service
 */
public static SamlService createServiceFrom(
        final HttpServletRequest request) {
    final String service = request.getParameter(SamlProtocolConstants.CONST_PARAM_TARGET);
    final String artifactId;
    final String requestBody = getRequestBody(request);
    final String requestId;

    if (!StringUtils.hasText(service) && !StringUtils.hasText(requestBody)) {
        LOGGER.debug("Request does not specify a {} or request body is empty",
                SamlProtocolConstants.CONST_PARAM_TARGET);
        return null;
    }

    final String id = cleanupUrl(service);

    if (StringUtils.hasText(requestBody)) {

        final String tagStart;
        final String tagEnd;
        if (requestBody.contains(CONST_START_ARTIFACT_XML_TAG)) {
            tagStart = CONST_START_ARTIFACT_XML_TAG;
            tagEnd = CONST_END_ARTIFACT_XML_TAG;
        } else {
            tagStart = CONST_START_ARTIFACT_XML_TAG_NO_NAMESPACE;
            tagEnd = CONST_END_ARTIFACT_XML_TAG_NO_NAMESPACE;
        }
        final int startTagLocation = requestBody.indexOf(tagStart);
        final int artifactStartLocation = startTagLocation + tagStart.length();
        final int endTagLocation = requestBody.indexOf(tagEnd);

        artifactId = requestBody.substring(artifactStartLocation, endTagLocation).trim();

        // is there a request id?
        requestId = extractRequestId(requestBody);
    } else {
        artifactId = null;
        requestId = null;
    }

    LOGGER.debug("Attempted to extract Request from HttpServletRequest. Results:");
    LOGGER.debug("Request Body: {}", requestBody);
    LOGGER.debug("Extracted ArtifactId: {}", artifactId);
    LOGGER.debug("Extracted Request Id: {}", requestId);

    return new SamlService(id, service, artifactId, requestId);
}
 
Example 17
Project: spring-cloud-skipper   File: TargetHolder.java   View Source Code Vote up 4 votes
private void attemptConnection() throws Exception {
	SkipperClient skipperClient = null;

	try {
		final HttpClientConfigurer httpClientConfigurer = HttpClientConfigurer.create()
				.targetHost(this.getTarget().getTargetUri())
				.skipTlsCertificateVerification(this.getTarget().isSkipSslValidation());
		if (this.getTarget().getTargetCredentials() != null
				&& StringUtils.hasText(this.getTarget().getTargetCredentials().getUsername())
				&& StringUtils.hasText(this.getTarget().getTargetCredentials().getPassword())) {
			httpClientConfigurer.basicAuthCredentials(this.getTarget().getTargetCredentials().getUsername(),
					this.getTarget().getTargetCredentials().getPassword());
		}
		if (StringUtils.hasText(credentialsProviderCommand)) {
			this.getTarget().setTargetCredentials(new TargetCredentials(true));
			final Resource credentialsResource = new ProcessOutputResource(
					credentialsProviderCommand.split("\\s+"));
			httpClientConfigurer.addInterceptor(new ResourceBasedAuthorizationInterceptor(credentialsResource));
		}
		this.restTemplate.setRequestFactory(httpClientConfigurer.buildClientHttpRequestFactory());

		String uri = this.getTarget().getTargetUri().toURL().toString();
		skipperClient = new DefaultSkipperClient(uri, this.restTemplate);
		// Actually attempt connection
		skipperClient.info();

		this.getTarget()
				.setTargetResultMessage(String.format("Successfully targeted %s", uri));

	}
	catch (Exception e) {
		this.getTarget().setTargetException(e);
		skipperClient = null;
		throw e;
	}
	finally {
		applicationEventPublisher.publishEvent(new SkipperClientUpdatedEvent(skipperClient));
	}
	// Other commands will be notified of the new SkipperClient object (may be null)

}
 
Example 18
Project: spring-cloud-release-tools   File: ReleaserProperties.java   View Source Code Vote up 4 votes
public String getWorkingDir() {
	return StringUtils.hasText(this.workingDir) ?
			this.workingDir : System.getProperty("user.dir");
}
 
Example 19
Project: gemini.blueprint   File: AbstractOsgiServiceImportFactoryBean.java   View Source Code Vote up 4 votes
/**
 * Assembles the configuration properties into one unified OSGi filter. Note that this implementation creates the
 * filter on the first call and caches it afterwards.
 * 
 * @return unified filter based on this factory bean configuration
 */
public Filter getUnifiedFilter() {
	if (unifiedFilter != null) {
		return unifiedFilter;
	}

	String filterWithClasses =
			(!ObjectUtils.isEmpty(interfaces) ? OsgiFilterUtils.unifyFilter(interfaces, filter) : filter);

	boolean trace = log.isTraceEnabled();
	if (trace)
		log.trace("Unified classes=" + ObjectUtils.nullSafeToString(interfaces) + " and filter=[" + filter
				+ "]  in=[" + filterWithClasses + "]");

	// add the serviceBeanName/Blueprint component name constraint
	String nameFilter;
	if (StringUtils.hasText(serviceBeanName)) {
		StringBuilder nsFilter = new StringBuilder("(|(");
		nsFilter.append(OsgiServicePropertiesResolver.BEAN_NAME_PROPERTY_KEY);
		nsFilter.append("=");
		nsFilter.append(serviceBeanName);
		nsFilter.append(")(");
		nsFilter.append(OsgiServicePropertiesResolver.SPRING_DM_BEAN_NAME_PROPERTY_KEY);
		nsFilter.append("=");
		nsFilter.append(serviceBeanName);
		nsFilter.append(")(");
		nsFilter.append(OsgiServicePropertiesResolver.BLUEPRINT_COMP_NAME);
		nsFilter.append("=");
		nsFilter.append(serviceBeanName);
		nsFilter.append("))");
		nameFilter = nsFilter.toString();
	} else {
		nameFilter = null;
	}

	String filterWithServiceBeanName = filterWithClasses;
	if (nameFilter != null) {
		StringBuilder finalFilter = new StringBuilder();
		finalFilter.append("(&");
		finalFilter.append(filterWithClasses);
		finalFilter.append(nameFilter);
		finalFilter.append(")");
		filterWithServiceBeanName = finalFilter.toString();
	}

	if (trace)
		log.trace("Unified serviceBeanName [" + ObjectUtils.nullSafeToString(serviceBeanName) + "] and filter=["
				+ filterWithClasses + "]  in=[" + filterWithServiceBeanName + "]");

	// create (which implies validation) the actual filter
	unifiedFilter = OsgiFilterUtils.createFilter(filterWithServiceBeanName);

	return unifiedFilter;
}
 
Example 20
Project: DWSurvey   File: AssertUtils.java   View Source Code Vote up 2 votes
/**
 * Assert that the given String has valid text content; that is, it must not
 * be <code>null</code> and must contain at least one non-whitespace character.
 * <pre class="code">Assert.hasText(name, "'name' must not be empty");</pre>
 * @param text the String to check
 * @param message the exception message to use if the assertion fails
 * @see StringUtils#hasText
 */
public static void hasText(String text, String message) {
	if (!StringUtils.hasText(text)) {
		throw new IllegalArgumentException(message);
	}
}