List of usage examples for org.springframework.util StringUtils commaDelimitedListToStringArray
public static String[] commaDelimitedListToStringArray(@Nullable String str)
From source file:com.mystudy.source.spring.mvc.DispatcherServlet.java
/** * Create a List of default strategy objects for the given strategy interface. * <p>The default implementation uses the "DispatcherServlet.properties" file (in the same * package as the DispatcherServlet class) to determine the class names. It instantiates * the strategy objects through the context's BeanFactory. * @param context the current WebApplicationContext * @param strategyInterface the strategy interface * @return the List of corresponding strategy objects *//* w w w . j ava2 s. c o m*/ @SuppressWarnings("unchecked") protected <T> List<T> getDefaultStrategies(ApplicationContext context, Class<T> strategyInterface) { String key = strategyInterface.getName(); String value = defaultStrategies.getProperty(key); if (value != null) { String[] classNames = StringUtils.commaDelimitedListToStringArray(value); List<T> strategies = new ArrayList<T>(classNames.length); for (String className : classNames) { try { Class<?> clazz = ClassUtils.forName(className, DispatcherServlet.class.getClassLoader()); Object strategy = createDefaultStrategy(context, clazz); strategies.add((T) strategy); } catch (ClassNotFoundException ex) { throw new BeanInitializationException( "Could not find DispatcherServlet's default strategy class [" + className + "] for interface [" + key + "]", ex); } catch (LinkageError err) { throw new BeanInitializationException( "Error loading DispatcherServlet's default strategy class [" + className + "] for interface [" + key + "]: problem with class file or dependent class", err); } } return strategies; } else { return new LinkedList<T>(); } }
From source file:gal.udc.fic.muei.tfm.dap.flipper.config.cassandra.CassandraProperties.java
public Cluster createCluster() { Cluster.Builder builder = Cluster.builder().withClusterName(this.getClusterName()).withPort(this.getPort()); if (ProtocolVersion.V1.name().equals(this.getProtocolVersion())) { builder.withProtocolVersion(ProtocolVersion.V1); } else if (ProtocolVersion.V2.name().equals(this.getProtocolVersion())) { builder.withProtocolVersion(ProtocolVersion.V2); } else if (ProtocolVersion.V3.name().equals(this.getProtocolVersion())) { builder.withProtocolVersion(ProtocolVersion.V3); }/*from w w w . jav a 2 s. c o m*/ // Manage compression protocol if (ProtocolOptions.Compression.SNAPPY.name().equals(this.getCompression())) { builder.withCompression(ProtocolOptions.Compression.SNAPPY); } else if (ProtocolOptions.Compression.LZ4.name().equals(this.getCompression())) { builder.withCompression(ProtocolOptions.Compression.LZ4); } else { builder.withCompression(ProtocolOptions.Compression.NONE); } // Manage the load balancing policy if (!StringUtils.isEmpty(this.getLoadBalancingPolicy())) { try { builder.withLoadBalancingPolicy(parseLbPolicy(this.getLoadBalancingPolicy())); } catch (ClassNotFoundException e) { log.warn("The load balancing policy could not be loaded, falling back to the default policy", e); } catch (InstantiationException e) { log.warn("The load balancing policy could not be instanced, falling back to the default policy", e); } catch (IllegalAccessException e) { log.warn("The load balancing policy could not be created, falling back to the default policy", e); } catch (ClassCastException e) { log.warn("The load balancing policy does not implement the correct interface, falling back to the " + "default policy", e); } catch (NoSuchMethodException e) { log.warn("The load balancing policy could not be created, falling back to the default policy", e); } catch (SecurityException e) { log.warn("The load balancing policy could not be created, falling back to the default policy", e); } catch (IllegalArgumentException e) { log.warn("The load balancing policy could not be created, falling back to the default policy", e); } catch (InvocationTargetException e) { log.warn("The load balancing policy could not be created, falling back to the default policy", e); } } // Manage query options QueryOptions queryOptions = new QueryOptions(); if (this.getConsistency() != null) { ConsistencyLevel consistencyLevel = ConsistencyLevel.valueOf(this.getConsistency()); queryOptions.setConsistencyLevel(consistencyLevel); } if (this.getSerialConsistency() != null) { ConsistencyLevel serialConsistencyLevel = ConsistencyLevel.valueOf(this.getSerialConsistency()); queryOptions.setSerialConsistencyLevel(serialConsistencyLevel); } queryOptions.setFetchSize(this.getFetchSize()); builder.withQueryOptions(queryOptions); // Manage the reconnection policy if (!StringUtils.isEmpty(this.getReconnectionPolicy())) { try { builder.withReconnectionPolicy(parseReconnectionPolicy(this.getReconnectionPolicy())); } catch (ClassNotFoundException e) { log.warn("The reconnection policy could not be loaded, falling back to the default policy", e); } catch (InstantiationException e) { log.warn("The reconnection policy could not be instanced, falling back to the default policy", e); } catch (IllegalAccessException e) { log.warn("The reconnection policy could not be created, falling back to the default policy", e); } catch (ClassCastException e) { log.warn("The reconnection policy does not implement the correct interface, falling back to the " + "default policy", e); } catch (NoSuchMethodException e) { log.warn("The reconnection policy could not be created, falling back to the default policy", e); } catch (SecurityException e) { log.warn("The reconnection policy could not be created, falling back to the default policy", e); } catch (IllegalArgumentException e) { log.warn("The reconnection policy could not be created, falling back to the default policy", e); } catch (InvocationTargetException e) { log.warn("The reconnection policy could not be created, falling back to the default policy", e); } } // Manage the retry policy if (!StringUtils.isEmpty(this.getRetryPolicy())) { try { builder.withRetryPolicy(parseRetryPolicy(this.getRetryPolicy())); } catch (ClassNotFoundException e) { log.warn("The retry policy could not be loaded, falling back to the default policy", e); } catch (InstantiationException e) { log.warn("The retry policy could not be instanced, falling back to the default policy", e); } catch (IllegalAccessException e) { log.warn("The retry policy could not be created, falling back to the default policy", e); } catch (ClassCastException e) { log.warn("The retry policy does not implement the correct interface, falling back to the default " + "policy", e); } catch (NoSuchMethodException e) { log.warn("The retry policy could not be created, falling back to the default policy", e); } catch (SecurityException e) { log.warn("The retry policy could not be created, falling back to the default policy", e); } catch (IllegalArgumentException e) { log.warn("The retry policy could not be created, falling back to the default policy", e); } catch (InvocationTargetException e) { log.warn("The retry policy could not be created, falling back to the default policy", e); } catch (NoSuchFieldException e) { log.warn("The retry policy could not be created, falling back to the default policy", e); } } if (!StringUtils.isEmpty(this.getUser()) && !StringUtils.isEmpty(this.getPassword())) { builder.withCredentials(this.getUser(), this.getPassword()); } // Manage socket options SocketOptions socketOptions = new SocketOptions(); socketOptions.setConnectTimeoutMillis(this.getConnectTimeoutMillis()); socketOptions.setReadTimeoutMillis(this.getReadTimeoutMillis()); builder.withSocketOptions(socketOptions); // Manage SSL if (this.isSsl()) { builder.withSSL(); } // Manage the contact points builder.addContactPoints(StringUtils.commaDelimitedListToStringArray(this.getContactPoints())); return builder.build(); }
From source file:it.doqui.index.ecmengine.business.personalization.hibernate.RoutingLocalSessionFactoryBean.java
protected SessionFactory buildSessionFactory() throws Exception { logger.debug("[RoutingLocalSessionFactoryBean::buildSessionFactory] BEGIN"); SessionFactory sf = null;//from w w w .ja va 2 s.c o m // Create Configuration instance. Configuration config = newConfiguration(); DataSource currentDataSource = getCurrentDataSource(); logger.debug("[RoutingLocalSessionFactoryBean::buildSessionFactory] " + "Repository '" + RepositoryManager.getCurrentRepository() + "' -- Got currentDataSource: " + currentDataSource); if (currentDataSource == null) { throw new IllegalStateException("Null DataSource!"); } // Make given DataSource available for SessionFactory configuration. logger.debug("[RoutingLocalSessionFactoryBean::buildSessionFactory] " + "Thread '" + Thread.currentThread().getName() + "' -- Setting DataSource for current thread: " + currentDataSource); CONFIG_TIME_DS_HOLDER.set(currentDataSource); if (this.jtaTransactionManager != null) { // Make Spring-provided JTA TransactionManager available. CONFIG_TIME_TM_HOLDER.set(this.jtaTransactionManager); } if (this.lobHandler != null) { // Make given LobHandler available for SessionFactory configuration. // Do early because because mapping resource might refer to custom types. CONFIG_TIME_LOB_HANDLER_HOLDER.set(this.lobHandler); } try { // Set connection release mode "on_close" as default. // This was the case for Hibernate 3.0; Hibernate 3.1 changed // it to "auto" (i.e. "after_statement" or "after_transaction"). // However, for Spring's resource management (in particular for // HibernateTransactionManager), "on_close" is the better default. config.setProperty(Environment.RELEASE_CONNECTIONS, ConnectionReleaseMode.ON_CLOSE.toString()); if (!isExposeTransactionAwareSessionFactory()) { // Not exposing a SessionFactory proxy with transaction-aware // getCurrentSession() method -> set Hibernate 3.1 CurrentSessionContext // implementation instead, providing the Spring-managed Session that way. // Can be overridden by a custom value for corresponding Hibernate property. config.setProperty(Environment.CURRENT_SESSION_CONTEXT_CLASS, "org.springframework.orm.hibernate3.SpringSessionContext"); } if (this.entityInterceptor != null) { // Set given entity interceptor at SessionFactory level. config.setInterceptor(this.entityInterceptor); } if (this.namingStrategy != null) { // Pass given naming strategy to Hibernate Configuration. config.setNamingStrategy(this.namingStrategy); } if (this.typeDefinitions != null) { // Register specified Hibernate type definitions. Mappings mappings = config.createMappings(); for (int i = 0; i < this.typeDefinitions.length; i++) { TypeDefinitionBean typeDef = this.typeDefinitions[i]; mappings.addTypeDef(typeDef.getTypeName(), typeDef.getTypeClass(), typeDef.getParameters()); } } if (this.filterDefinitions != null) { // Register specified Hibernate FilterDefinitions. for (int i = 0; i < this.filterDefinitions.length; i++) { config.addFilterDefinition(this.filterDefinitions[i]); } } if (this.configLocations != null) { for (int i = 0; i < this.configLocations.length; i++) { // Load Hibernate configuration from given location. config.configure(this.configLocations[i].getURL()); } } if (this.hibernateProperties != null) { // Add given Hibernate properties to Configuration. config.addProperties(this.hibernateProperties); } if (currentDataSource != null) { boolean actuallyTransactionAware = (this.useTransactionAwareDataSource || currentDataSource instanceof TransactionAwareDataSourceProxy); // Set Spring-provided DataSource as Hibernate ConnectionProvider. config.setProperty(Environment.CONNECTION_PROVIDER, actuallyTransactionAware ? TransactionAwareDataSourceConnectionProvider.class.getName() : RoutingLocalDataSourceConnectionProvider.class.getName()); } if (this.jtaTransactionManager != null) { // Set Spring-provided JTA TransactionManager as Hibernate property. config.setProperty(Environment.TRANSACTION_MANAGER_STRATEGY, LocalTransactionManagerLookup.class.getName()); } if (this.mappingLocations != null) { // Register given Hibernate mapping definitions, contained in resource files. for (int i = 0; i < this.mappingLocations.length; i++) { config.addInputStream(this.mappingLocations[i].getInputStream()); } } if (this.cacheableMappingLocations != null) { // Register given cacheable Hibernate mapping definitions, read from the file system. for (int i = 0; i < this.cacheableMappingLocations.length; i++) { config.addCacheableFile(this.cacheableMappingLocations[i].getFile()); } } if (this.mappingJarLocations != null) { // Register given Hibernate mapping definitions, contained in jar files. for (int i = 0; i < this.mappingJarLocations.length; i++) { Resource resource = this.mappingJarLocations[i]; config.addJar(resource.getFile()); } } if (this.mappingDirectoryLocations != null) { // Register all Hibernate mapping definitions in the given directories. for (int i = 0; i < this.mappingDirectoryLocations.length; i++) { File file = this.mappingDirectoryLocations[i].getFile(); if (!file.isDirectory()) { throw new IllegalArgumentException("Mapping directory location [" + this.mappingDirectoryLocations[i] + "] does not denote a directory"); } config.addDirectory(file); } } if (this.entityCacheStrategies != null) { // Register cache strategies for mapped entities. for (Enumeration<?> classNames = this.entityCacheStrategies.propertyNames(); classNames .hasMoreElements(); /* */) { String className = (String) classNames.nextElement(); String[] strategyAndRegion = StringUtils .commaDelimitedListToStringArray(this.entityCacheStrategies.getProperty(className)); if (strategyAndRegion.length > 1) { config.setCacheConcurrencyStrategy(className, strategyAndRegion[0], strategyAndRegion[1]); } else if (strategyAndRegion.length > 0) { config.setCacheConcurrencyStrategy(className, strategyAndRegion[0]); } } } if (this.collectionCacheStrategies != null) { // Register cache strategies for mapped collections. for (Enumeration<?> collRoles = this.collectionCacheStrategies.propertyNames(); collRoles .hasMoreElements(); /* */) { String collRole = (String) collRoles.nextElement(); String[] strategyAndRegion = StringUtils .commaDelimitedListToStringArray(this.collectionCacheStrategies.getProperty(collRole)); if (strategyAndRegion.length > 1) { config.setCollectionCacheConcurrencyStrategy(collRole, strategyAndRegion[0], strategyAndRegion[1]); } else if (strategyAndRegion.length > 0) { config.setCollectionCacheConcurrencyStrategy(collRole, strategyAndRegion[0]); } } } if (this.eventListeners != null) { // Register specified Hibernate event listeners. for (Map.Entry<?, ?> entry : this.eventListeners.entrySet()) { Assert.isTrue(entry.getKey() instanceof String, "Event listener key needs to be of type String"); String listenerType = (String) entry.getKey(); Object listenerObject = entry.getValue(); if (listenerObject instanceof Collection) { Collection<?> listeners = (Collection<?>) listenerObject; EventListeners listenerRegistry = config.getEventListeners(); Object[] listenerArray = (Object[]) Array .newInstance(listenerRegistry.getListenerClassFor(listenerType), listeners.size()); listenerArray = listeners.toArray(listenerArray); config.setListeners(listenerType, listenerArray); } else { config.setListener(listenerType, listenerObject); } } } // Perform custom post-processing in subclasses. postProcessConfiguration(config); // Build SessionFactory instance. logger.debug( "[RoutingLocalSessionFactoryBean::buildSessionFactory] Building new Hibernate SessionFactory."); this.configuration = config; SessionFactoryProxy sessionFactoryProxy = new SessionFactoryProxy( repositoryManager.getDefaultRepository().getId()); for (Repository repository : repositoryManager.getRepositories()) { logger.debug("[RoutingLocalSessionFactoryBean::buildSessionFactory] " + "Repository '" + repository.getId() + "' -- Building SessionFactory..."); RepositoryManager.setCurrentRepository(repository.getId()); sessionFactoryProxy.addSessionFactory(repository.getId(), newSessionFactory(config)); } RepositoryManager.setCurrentRepository(repositoryManager.getDefaultRepository().getId()); sf = sessionFactoryProxy; } finally { if (currentDataSource != null) { // Reset DataSource holder. CONFIG_TIME_DS_HOLDER.set(null); } if (this.jtaTransactionManager != null) { // Reset TransactionManager holder. CONFIG_TIME_TM_HOLDER.set(null); } if (this.lobHandler != null) { // Reset LobHandler holder. CONFIG_TIME_LOB_HANDLER_HOLDER.set(null); } } // Execute schema update if requested. if (this.schemaUpdate) { updateDatabaseSchema(); } return sf; }
From source file:net.solarnetwork.node.backup.FileBackupResourceProvider.java
/** * Set the {@code resourceDirectories} property as a comma-delimited string. * /* ww w . j av a 2s . c o m*/ * @param list * a comma-delimited list of paths */ public void setResourceDirs(String list) { setResourceDirectories(StringUtils.commaDelimitedListToStringArray(list)); }
From source file:net.tanesha.tftpd.vfs.VersioningHelper.java
public void afterPropertiesSet() throws Exception { String[] models = StringUtils.commaDelimitedListToStringArray(properties.getProperty("models")); for (int i = 0; i < models.length; i++) { String model = models[i].trim(); //String name = properties.getProperty(model + ".name"); String name = model;//from w w w . j a va 2 s.com String matcher = properties.getProperty(model + ".matcher"); if (name == null || matcher == null) throw new Exception("Invalid configuration, " + model + " not configured properly."); matchers.put(name, Pattern.compile(matcher)); } LOG.info("VersioningHelper configured: " + matchers); }
From source file:org.acegisecurity.intercept.method.MethodDefinitionSourceEditor.java
public void setAsText(String s) throws IllegalArgumentException { MethodDefinitionMap source = new MethodDefinitionMap(); if ((s == null) || "".equals(s)) { // Leave value in property editor null } else {//from w w w . j ava 2s . c om // Use properties editor to tokenize the string PropertiesEditor propertiesEditor = new PropertiesEditor(); propertiesEditor.setAsText(s); Properties props = (Properties) propertiesEditor.getValue(); // Now we have properties, process each one individually List mappings = new ArrayList(); for (Iterator iter = props.keySet().iterator(); iter.hasNext();) { String name = (String) iter.next(); String value = props.getProperty(name); MethodDefinitionSourceMapping mapping = new MethodDefinitionSourceMapping(); mapping.setMethodName(name); String[] tokens = StringUtils.commaDelimitedListToStringArray(value); for (int i = 0; i < tokens.length; i++) { mapping.addConfigAttribute(tokens[i].trim()); } mappings.add(mapping); } source.setMappings(mappings); } setValue(source); }
From source file:org.cloudfoundry.identity.uaa.BootstrapTests.java
private ConfigurableApplicationContext getServletContext(String... resources) { String environmentConfigLocations = "required_configuration.yml,${LOGIN_CONFIG_URL},file:${LOGIN_CONFIG_PATH}/login.yml,file:${CLOUD_FOUNDRY_CONFIG_PATH}/login.yml,${UAA_CONFIG_URL},file:${UAA_CONFIG_FILE},file:${UAA_CONFIG_PATH}/uaa.yml,file:${CLOUD_FOUNDRY_CONFIG_PATH}/uaa.yml"; String profiles = null;/*w w w. jav a2s . com*/ String[] resourcesToLoad = resources; if (!resources[0].endsWith(".xml")) { profiles = resources[0]; resourcesToLoad = new String[resources.length - 1]; System.arraycopy(resources, 1, resourcesToLoad, 0, resourcesToLoad.length); } final String[] configLocations = resourcesToLoad; AbstractRefreshableWebApplicationContext context = new AbstractRefreshableWebApplicationContext() { @Override protected void loadBeanDefinitions(DefaultListableBeanFactory beanFactory) throws BeansException, IOException { XmlBeanDefinitionReader beanDefinitionReader = new XmlBeanDefinitionReader(beanFactory); // Configure the bean definition reader with this context's // resource loading environment. beanDefinitionReader.setEnvironment(this.getEnvironment()); beanDefinitionReader.setResourceLoader(this); beanDefinitionReader.setEntityResolver(new ResourceEntityResolver(this)); if (configLocations != null) { for (String configLocation : configLocations) { beanDefinitionReader.loadBeanDefinitions(configLocation); } } } }; MockServletContext servletContext = new MockServletContext() { @Override public RequestDispatcher getNamedDispatcher(String path) { return new MockRequestDispatcher("/"); } public String getVirtualServerName() { return null; } }; context.setServletContext(servletContext); MockServletConfig servletConfig = new MockServletConfig(servletContext); servletConfig.addInitParameter("environmentConfigLocations", environmentConfigLocations); context.setServletConfig(servletConfig); YamlServletProfileInitializer initializer = new YamlServletProfileInitializer(); initializer.initialize(context); if (profiles != null) { context.getEnvironment().setActiveProfiles(StringUtils.commaDelimitedListToStringArray(profiles)); } context.refresh(); return context; }
From source file:org.cloudfoundry.identity.uaa.db.DatabaseParametersTests.java
@Override @Before//from ww w.j a v a2s . c o m public void setUp() throws Exception { MockEnvironment environment = new MockEnvironment(); environment.setProperty("database.initialsize", "0"); environment.setProperty("database.validationquerytimeout", "5"); environment.setProperty("database.connecttimeout", "5"); if (System.getProperty("spring.profiles.active") != null) { environment.setActiveProfiles( StringUtils.commaDelimitedListToStringArray(System.getProperty("spring.profiles.active"))); } super.setUp(environment); vendor = webApplicationContext.getBean(DatabaseUrlModifier.class).getDatabaseType(); }
From source file:org.cloudfoundry.identity.uaa.login.BootstrapTests.java
private ConfigurableApplicationContext getServletContext(String profiles, String loginYmlPath, String uaaYamlPath, String... resources) { String[] resourcesToLoad = resources; if (!resources[0].endsWith(".xml")) { resourcesToLoad = new String[resources.length - 1]; System.arraycopy(resources, 1, resourcesToLoad, 0, resourcesToLoad.length); }//w w w. j a va 2s. c o m final String[] configLocations = resourcesToLoad; AbstractRefreshableWebApplicationContext context = new AbstractRefreshableWebApplicationContext() { @Override protected void loadBeanDefinitions(DefaultListableBeanFactory beanFactory) throws BeansException, IOException { XmlBeanDefinitionReader beanDefinitionReader = new XmlBeanDefinitionReader(beanFactory); // Configure the bean definition reader with this context's // resource loading environment. beanDefinitionReader.setEnvironment(this.getEnvironment()); beanDefinitionReader.setResourceLoader(this); beanDefinitionReader.setEntityResolver(new ResourceEntityResolver(this)); if (configLocations != null) { for (String configLocation : configLocations) { beanDefinitionReader.loadBeanDefinitions(configLocation); } } } }; if (profiles != null) { context.getEnvironment().setActiveProfiles(StringUtils.commaDelimitedListToStringArray(profiles)); } MockServletContext servletContext = new MockServletContext() { @Override public RequestDispatcher getNamedDispatcher(String path) { return new MockRequestDispatcher("/"); } }; context.setServletContext(servletContext); MockServletConfig servletConfig = new MockServletConfig(servletContext); servletConfig.addInitParameter("environmentConfigLocations", loginYmlPath + "," + uaaYamlPath); context.setServletConfig(servletConfig); YamlServletProfileInitializer initializer = new YamlServletProfileInitializer(); initializer.initialize(context); if (profiles != null) { context.getEnvironment().setActiveProfiles(StringUtils.commaDelimitedListToStringArray(profiles)); } context.refresh(); return context; }
From source file:org.cloudfoundry.identity.uaa.resources.jdbc.AbstractQueryable.java
protected void validateOrderBy(String orderBy, String fields) throws IllegalArgumentException { if (!StringUtils.hasText(orderBy)) { return;//from w ww.ja v a2 s . co m } String[] input = StringUtils.commaDelimitedListToStringArray(orderBy); Set<String> compare = new HashSet<>(); StringUtils.commaDelimitedListToSet(fields).stream().forEach(p -> compare.add(p.toLowerCase().trim())); boolean allints = true; for (String s : input) { try { Integer.parseInt(s); } catch (NumberFormatException e) { allints = false; if (!compare.contains(s.toLowerCase().trim())) { throw new IllegalArgumentException("Invalid sort field:" + s); } } } if (allints) { return; } }