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

The following are Jave code examples for showing how to use hasLength() 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: jetcache   File: CreateCacheAnnotationBeanPostProcessor.java   View Source Code Vote up 6 votes
private InjectionMetadata findAutowiringMetadata(String beanName, Class<?> clazz, PropertyValues pvs) {
    // Fall back to class name as cache key, for backwards compatibility with custom callers.
    String cacheKey = (StringUtils.hasLength(beanName) ? beanName : clazz.getName());
    // Quick check on the concurrent map first, with minimal locking.
    InjectionMetadata metadata = this.injectionMetadataCache.get(cacheKey);
    if (InjectionMetadata.needsRefresh(metadata, clazz)) {
        synchronized (this.injectionMetadataCache) {
            metadata = this.injectionMetadataCache.get(cacheKey);
            if (InjectionMetadata.needsRefresh(metadata, clazz)) {
                if (metadata != null) {
                    clear(metadata, pvs);
                }
                try {
                    metadata = buildAutowiringMetadata(clazz);
                    this.injectionMetadataCache.put(cacheKey, metadata);
                } catch (NoClassDefFoundError err) {
                    throw new IllegalStateException("Failed to introspect bean class [" + clazz.getName() +
                            "] for autowiring metadata: could not find class that it depends on", err);
                }
            }
        }
    }
    return metadata;
}
 
Example 2
Project: amazon-ecs-java-microservices   File: PetValidator.java   View Source Code Vote up 6 votes
@Override
public void validate(Object obj, Errors errors) {
    Pet pet = (Pet) obj;
    String name = pet.getName();
    // name validation
    if (!StringUtils.hasLength(name)) {
        errors.rejectValue("name", REQUIRED, REQUIRED);
    }

    // type validation
    if (pet.isNew() && pet.getType() == null) {
        errors.rejectValue("type", REQUIRED, REQUIRED);
    }

    // birth date validation
    if (pet.getBirthDate() == null) {
        errors.rejectValue("birthDate", REQUIRED, REQUIRED);
    }
}
 
Example 3
Project: amazon-ecs-java-microservices   File: PetValidator.java   View Source Code Vote up 6 votes
@Override
public void validate(Object obj, Errors errors) {
    Pet pet = (Pet) obj;
    String name = pet.getName();
    // name validation
    if (!StringUtils.hasLength(name)) {
        errors.rejectValue("name", REQUIRED, REQUIRED);
    }

    // type validation
    if (pet.isNew() && pet.getType() == null) {
        errors.rejectValue("type", REQUIRED, REQUIRED);
    }

    // birth date validation
    if (pet.getBirthDate() == null) {
        errors.rejectValue("birthDate", REQUIRED, REQUIRED);
    }
}
 
Example 4
Project: amazon-ecs-java-microservices   File: PetValidator.java   View Source Code Vote up 6 votes
@Override
public void validate(Object obj, Errors errors) {
    Pet pet = (Pet) obj;
    String name = pet.getName();
    // name validation
    if (!StringUtils.hasLength(name)) {
        errors.rejectValue("name", REQUIRED, REQUIRED);
    }

    // type validation
    if (pet.isNew() && pet.getType() == null) {
        errors.rejectValue("type", REQUIRED, REQUIRED);
    }

    // birth date validation
    if (pet.getBirthDate() == null) {
        errors.rejectValue("birthDate", REQUIRED, REQUIRED);
    }
}
 
Example 5
Project: lams   File: MetadataMBeanInfoAssembler.java   View Source Code Vote up 6 votes
private void populateMetricDescriptor(Descriptor desc, ManagedMetric metric) {
	applyCurrencyTimeLimit(desc, metric.getCurrencyTimeLimit());

	if (StringUtils.hasLength(metric.getPersistPolicy())) {
		desc.setField(FIELD_PERSIST_POLICY, metric.getPersistPolicy());
	}
	if (metric.getPersistPeriod() >= 0) {
		desc.setField(FIELD_PERSIST_PERIOD, Integer.toString(metric.getPersistPeriod()));
	}

	if (StringUtils.hasLength(metric.getDisplayName())) {
		desc.setField(FIELD_DISPLAY_NAME, metric.getDisplayName());
	}

	if(StringUtils.hasLength(metric.getUnit())) {
		desc.setField(FIELD_UNITS, metric.getUnit());
	}

	if(StringUtils.hasLength(metric.getCategory())) {
		desc.setField(FIELD_METRIC_CATEGORY, metric.getCategory());
	}

	String metricType = (metric.getMetricType() == null) ? MetricType.GAUGE.toString() : metric.getMetricType().toString();
	desc.setField(FIELD_METRIC_TYPE, metricType);
}
 
Example 6
Project: amazon-ecs-java-microservices   File: PetValidator.java   View Source Code Vote up 6 votes
@Override
public void validate(Object obj, Errors errors) {
    Pet pet = (Pet) obj;
    String name = pet.getName();
    // name validation
    if (!StringUtils.hasLength(name)) {
        errors.rejectValue("name", REQUIRED, REQUIRED);
    }

    // type validation
    if (pet.isNew() && pet.getType() == null) {
        errors.rejectValue("type", REQUIRED, REQUIRED);
    }

    // birth date validation
    if (pet.getBirthDate() == null) {
        errors.rejectValue("birthDate", REQUIRED, REQUIRED);
    }
}
 
Example 7
Project: lams   File: SimpleClientHttpResponse.java   View Source Code Vote up 6 votes
@Override
public HttpHeaders getHeaders() {
	if (this.headers == null) {
		this.headers = new HttpHeaders();
		// Header field 0 is the status line for most HttpURLConnections, but not on GAE
		String name = this.connection.getHeaderFieldKey(0);
		if (StringUtils.hasLength(name)) {
			this.headers.add(name, this.connection.getHeaderField(0));
		}
		int i = 1;
		while (true) {
			name = this.connection.getHeaderFieldKey(i);
			if (!StringUtils.hasLength(name)) {
				break;
			}
			this.headers.add(name, this.connection.getHeaderField(i));
			i++;
		}
	}
	return this.headers;
}
 
Example 8
Project: amazon-ecs-java-microservices   File: PetValidator.java   View Source Code Vote up 6 votes
@Override
public void validate(Object obj, Errors errors) {
    Pet pet = (Pet) obj;
    String name = pet.getName();
    // name validation
    if (!StringUtils.hasLength(name)) {
        errors.rejectValue("name", REQUIRED, REQUIRED);
    }

    // type validation
    if (pet.isNew() && pet.getType() == null) {
        errors.rejectValue("type", REQUIRED, REQUIRED);
    }

    // birth date validation
    if (pet.getBirthDate() == null) {
        errors.rejectValue("birthDate", REQUIRED, REQUIRED);
    }
}
 
Example 9
Project: lams   File: JmxUtils.java   View Source Code Vote up 5 votes
/**
 * Attempt to find a locally running {@code MBeanServer}. Fails if no
 * {@code MBeanServer} can be found. Logs a warning if more than one
 * {@code MBeanServer} found, returning the first one from the list.
 * @param agentId the agent identifier of the MBeanServer to retrieve.
 * If this parameter is {@code null}, all registered MBeanServers are considered.
 * If the empty String is given, the platform MBeanServer will be returned.
 * @return the {@code MBeanServer} if found
 * @throws org.springframework.jmx.MBeanServerNotFoundException
 * if no {@code MBeanServer} could be found
 * @see javax.management.MBeanServerFactory#findMBeanServer(String)
 */
public static MBeanServer locateMBeanServer(String agentId) throws MBeanServerNotFoundException {
	MBeanServer server = null;

	// null means any registered server, but "" specifically means the platform server
	if (!"".equals(agentId)) {
		List<MBeanServer> servers = MBeanServerFactory.findMBeanServer(agentId);
		if (servers != null && servers.size() > 0) {
			// Check to see if an MBeanServer is registered.
			if (servers.size() > 1 && logger.isWarnEnabled()) {
				logger.warn("Found more than one MBeanServer instance" +
						(agentId != null ? " with agent id [" + agentId + "]" : "") +
						". Returning first from list.");
			}
			server = servers.get(0);
		}
	}

	if (server == null && !StringUtils.hasLength(agentId)) {
		// Attempt to load the PlatformMBeanServer.
		try {
			server = ManagementFactory.getPlatformMBeanServer();
		}
		catch (SecurityException ex) {
			throw new MBeanServerNotFoundException("No specific MBeanServer found, " +
					"and not allowed to obtain the Java platform MBeanServer", ex);
		}
	}

	if (server == null) {
		throw new MBeanServerNotFoundException(
				"Unable to locate an MBeanServer instance" +
				(agentId != null ? " with agent id [" + agentId + "]" : ""));
	}

	if (logger.isDebugEnabled()) {
		logger.debug("Found MBeanServer: " + server);
	}
	return server;
}
 
Example 10
Project: spring-security-oauth2-boot   File: OAuth2RestOperationsConfiguration.java   View Source Code Vote up 5 votes
@Override
public ConditionOutcome getMatchOutcome(ConditionContext context,
		AnnotatedTypeMetadata metadata) {
	String clientId = context.getEnvironment()
			.getProperty("security.oauth2.client.client-id");
	ConditionMessage.Builder message = ConditionMessage
			.forCondition("OAuth Client ID");
	if (StringUtils.hasLength(clientId)) {
		return ConditionOutcome.match(message
				.foundExactly("security.oauth2.client.client-id property"));
	}
	return ConditionOutcome.noMatch(message
			.didNotFind("security.oauth2.client.client-id property").atAll());
}
 
Example 11
Project: qpid-jms-spring-boot   File: QpidJMSConnectionFactoryFactory.java   View Source Code Vote up 5 votes
/**
 * Creates and returns a JmsConnectionFactory instance using the current
 * configuration to prepare the factory for use.
 *
 * @param factoryClass
 *      The type of JmsConnectionFactory to create.
 *
 * @return a newly created and configured JmsConnectionFactory instance.
 */
public JmsConnectionFactory createConnectionFactory(Class<JmsConnectionFactory> factoryClass) {
    try {
        JmsConnectionFactory factory = new JmsConnectionFactory();

        factory.setRemoteURI(getRemoteURI());

        // Override the URI options with configuration values, but only if
        // the value is actually set.

        if (StringUtils.hasLength(properties.getUsername())) {
            factory.setUsername(properties.getUsername());
        }

        if (StringUtils.hasLength(properties.getPassword())) {
            factory.setPassword(properties.getPassword());
        }

        if (StringUtils.hasLength(properties.getClientId())) {
            factory.setClientID(properties.getClientId());
        }

        if (properties.isReceiveLocalOnly() != null) {
            factory.setReceiveLocalOnly(properties.isReceiveLocalOnly());
        }

        if (properties.isReceiveNoWaitLocalOnly() != null) {
            factory.setReceiveNoWaitLocalOnly(properties.isReceiveNoWaitLocalOnly());
        }

        configureDeserializationPolicy(properties, factory);

        return factory;
    } catch (Exception ex) {
        LOG.error("Exception while createing Qpid JMS Connection Factory.", ex);
        throw new IllegalStateException("Failed to create the Qpid JMS ConnectionFactory, " +
            "make sure the client Jar is on the Classpath.", ex);
    }
}
 
Example 12
Project: lams   File: MetadataMBeanInfoAssembler.java   View Source Code Vote up 5 votes
/**
 * Adds descriptor fields from the {@code ManagedResource} attribute
 * to the MBean descriptor. Specifically, adds the {@code currencyTimeLimit},
 * {@code persistPolicy}, {@code persistPeriod}, {@code persistLocation}
 * and {@code persistName} descriptor fields if they are present in the metadata.
 */
@Override
protected void populateMBeanDescriptor(Descriptor desc, Object managedBean, String beanKey) {
	ManagedResource mr = this.attributeSource.getManagedResource(getClassToExpose(managedBean));
	if (mr == null) {
		throw new InvalidMetadataException(
				"No ManagedResource attribute found for class: " + getClassToExpose(managedBean));
	}

	applyCurrencyTimeLimit(desc, mr.getCurrencyTimeLimit());

	if (mr.isLog()) {
		desc.setField(FIELD_LOG, "true");
	}
	if (StringUtils.hasLength(mr.getLogFile())) {
		desc.setField(FIELD_LOG_FILE, mr.getLogFile());
	}

	if (StringUtils.hasLength(mr.getPersistPolicy())) {
		desc.setField(FIELD_PERSIST_POLICY, mr.getPersistPolicy());
	}
	if (mr.getPersistPeriod() >= 0) {
		desc.setField(FIELD_PERSIST_PERIOD, Integer.toString(mr.getPersistPeriod()));
	}
	if (StringUtils.hasLength(mr.getPersistName())) {
		desc.setField(FIELD_PERSIST_NAME, mr.getPersistName());
	}
	if (StringUtils.hasLength(mr.getPersistLocation())) {
		desc.setField(FIELD_PERSIST_LOCATION, mr.getPersistLocation());
	}
}
 
Example 13
Project: lams   File: MutableSortDefinition.java   View Source Code Vote up 5 votes
/**
 * Set the property to compare.
 * <p>If the property was the same as the current, the sort is reversed if
 * "toggleAscendingOnProperty" is activated, else simply ignored.
 * @see #setToggleAscendingOnProperty
 */
public void setProperty(String property) {
	if (!StringUtils.hasLength(property)) {
		this.property = "";
	}
	else {
		// Implicit toggling of ascending?
		if (isToggleAscendingOnProperty()) {
			this.ascending = (!property.equals(this.property) || !this.ascending);
		}
		this.property = property;
	}
}
 
Example 14
Project: artifactory-resource   File: ArtifactoryServerConnection.java   View Source Code Vote up 5 votes
private Delegate<?> getDelegate() {
	String serverLocation = System.getProperty(SERVER_PROPERTY);
	if (StringUtils.hasLength(serverLocation) && !serverLocation.startsWith("$")) {
		return new RunningServerDelegate(serverLocation);
	}
	return new DockerDelegate();

}
 
Example 15
Project: SimpleProcessControl   File: BeanFactoryUtil.java   View Source Code Vote up 5 votes
/**
 * 获取bean实例对象
 *
 * @param name bean名称
 * @param <T>  泛型类
 * @return Object 一个以所给名字注册的bean的实例
 * @throws BeansException 获取bean失败异常
 */
public static <T> T getBean(String name) throws BeansException {
    if (!StringUtils.hasLength(name)){
        return null;
    }
    char[] chars = name.toCharArray();
    chars[0] = String.valueOf(chars[0]).toLowerCase().charAt(0);
    return (T) beanFactory.getBean(String.valueOf(chars));
}
 
Example 16
Project: lams   File: JtaTransactionManager.java   View Source Code Vote up 5 votes
/**
 * Initialize the UserTransaction as well as the TransactionManager handle.
 * @throws TransactionSystemException if initialization failed
 */
protected void initUserTransactionAndTransactionManager() throws TransactionSystemException {
	if (this.userTransaction == null) {
		// Fetch JTA UserTransaction from JNDI, if necessary.
		if (StringUtils.hasLength(this.userTransactionName)) {
			this.userTransaction = lookupUserTransaction(this.userTransactionName);
			this.userTransactionObtainedFromJndi = true;
		}
		else {
			this.userTransaction = retrieveUserTransaction();
			if (this.userTransaction == null && this.autodetectUserTransaction) {
				// Autodetect UserTransaction at its default JNDI location.
				this.userTransaction = findUserTransaction();
			}
		}
	}

	if (this.transactionManager == null) {
		// Fetch JTA TransactionManager from JNDI, if necessary.
		if (StringUtils.hasLength(this.transactionManagerName)) {
			this.transactionManager = lookupTransactionManager(this.transactionManagerName);
		}
		else {
			this.transactionManager = retrieveTransactionManager();
			if (this.transactionManager == null && this.autodetectTransactionManager) {
				// Autodetect UserTransaction object that implements TransactionManager,
				// and check fallback JNDI locations otherwise.
				this.transactionManager = findTransactionManager(this.userTransaction);
			}
		}
	}

	// If only JTA TransactionManager specified, create UserTransaction handle for it.
	if (this.userTransaction == null && this.transactionManager != null) {
		this.userTransaction = buildUserTransaction(this.transactionManager);
	}
}
 
Example 17
Project: DWSurvey   File: AssertUtils.java   View Source Code Vote up 4 votes
public static void hasLength(String text, RuntimeException throwIfAssertFail) {
	if (!StringUtils.hasLength(text)) {
		throw throwIfAssertFail;
	}
}
 
Example 18
Project: Ins_fb_pictureSpider_WEB   File: AssertUtils.java   View Source Code Vote up 4 votes
public static void doesNotContain(String textToSearch, String substring, RuntimeException throwIfAssertFail) {
    if (StringUtils.hasLength(textToSearch) && StringUtils.hasLength(substring)
            && textToSearch.indexOf(substring) != -1) {
        throw throwIfAssertFail;
    }
}
 
Example 19
Project: lams   File: TransactionAttributeEditor.java   View Source Code Vote up 4 votes
/**
 * Format is PROPAGATION_NAME,ISOLATION_NAME,readOnly,timeout_NNNN,+Exception1,-Exception2.
 * Null or the empty string means that the method is non transactional.
 * @see java.beans.PropertyEditor#setAsText(java.lang.String)
 */
@Override
public void setAsText(String text) throws IllegalArgumentException {
	if (StringUtils.hasLength(text)) {
		// tokenize it with ","
		String[] tokens = StringUtils.commaDelimitedListToStringArray(text);
		RuleBasedTransactionAttribute attr = new RuleBasedTransactionAttribute();
		for (int i = 0; i < tokens.length; i++) {
			// Trim leading and trailing whitespace.
			String token = StringUtils.trimWhitespace(tokens[i].trim());
			// Check whether token contains illegal whitespace within text.
			if (StringUtils.containsWhitespace(token)) {
				throw new IllegalArgumentException(
						"Transaction attribute token contains illegal whitespace: [" + token + "]");
			}
			// Check token type.
			if (token.startsWith(RuleBasedTransactionAttribute.PREFIX_PROPAGATION)) {
				attr.setPropagationBehaviorName(token);
			}
			else if (token.startsWith(RuleBasedTransactionAttribute.PREFIX_ISOLATION)) {
				attr.setIsolationLevelName(token);
			}
			else if (token.startsWith(RuleBasedTransactionAttribute.PREFIX_TIMEOUT)) {
				String value = token.substring(DefaultTransactionAttribute.PREFIX_TIMEOUT.length());
				attr.setTimeout(Integer.parseInt(value));
			}
			else if (token.equals(RuleBasedTransactionAttribute.READ_ONLY_MARKER)) {
				attr.setReadOnly(true);
			}
			else if (token.startsWith(RuleBasedTransactionAttribute.PREFIX_COMMIT_RULE)) {
				attr.getRollbackRules().add(new NoRollbackRuleAttribute(token.substring(1)));
			}
			else if (token.startsWith(RuleBasedTransactionAttribute.PREFIX_ROLLBACK_RULE)) {
				attr.getRollbackRules().add(new RollbackRuleAttribute(token.substring(1)));
			}
			else {
				throw new IllegalArgumentException("Invalid transaction attribute token: [" + token + "]");
			}
		}
		setValue(attr);
	}
	else {
		setValue(null);
	}
}
 
Example 20
Project: lams   File: BeanDefinitionParserDelegate.java   View Source Code Vote up 4 votes
/**
 * Parses the supplied {@code &lt;bean&gt;} element. May return {@code null}
 * if there were errors during parse. Errors are reported to the
 * {@link org.springframework.beans.factory.parsing.ProblemReporter}.
 */
public BeanDefinitionHolder parseBeanDefinitionElement(Element ele, BeanDefinition containingBean) {
	String id = ele.getAttribute(ID_ATTRIBUTE);
	String nameAttr = ele.getAttribute(NAME_ATTRIBUTE);

	List<String> aliases = new ArrayList<String>();
	if (StringUtils.hasLength(nameAttr)) {
		String[] nameArr = StringUtils.tokenizeToStringArray(nameAttr, MULTI_VALUE_ATTRIBUTE_DELIMITERS);
		aliases.addAll(Arrays.asList(nameArr));
	}

	String beanName = id;
	if (!StringUtils.hasText(beanName) && !aliases.isEmpty()) {
		beanName = aliases.remove(0);
		if (logger.isDebugEnabled()) {
			logger.debug("No XML 'id' specified - using '" + beanName +
					"' as bean name and " + aliases + " as aliases");
		}
	}

	if (containingBean == null) {
		checkNameUniqueness(beanName, aliases, ele);
	}

	AbstractBeanDefinition beanDefinition = parseBeanDefinitionElement(ele, beanName, containingBean);
	if (beanDefinition != null) {
		if (!StringUtils.hasText(beanName)) {
			try {
				if (containingBean != null) {
					beanName = BeanDefinitionReaderUtils.generateBeanName(
							beanDefinition, this.readerContext.getRegistry(), true);
				}
				else {
					beanName = this.readerContext.generateBeanName(beanDefinition);
					// Register an alias for the plain bean class name, if still possible,
					// if the generator returned the class name plus a suffix.
					// This is expected for Spring 1.2/2.0 backwards compatibility.
					String beanClassName = beanDefinition.getBeanClassName();
					if (beanClassName != null &&
							beanName.startsWith(beanClassName) && beanName.length() > beanClassName.length() &&
							!this.readerContext.getRegistry().isBeanNameInUse(beanClassName)) {
						aliases.add(beanClassName);
					}
				}
				if (logger.isDebugEnabled()) {
					logger.debug("Neither XML 'id' nor 'name' specified - " +
							"using generated bean name [" + beanName + "]");
				}
			}
			catch (Exception ex) {
				error(ex.getMessage(), ele);
				return null;
			}
		}
		String[] aliasesArray = StringUtils.toStringArray(aliases);
		return new BeanDefinitionHolder(beanDefinition, beanName, aliasesArray);
	}

	return null;
}