Example usage for org.springframework.util StringUtils collectionToCommaDelimitedString

List of usage examples for org.springframework.util StringUtils collectionToCommaDelimitedString

Introduction

In this page you can find the example usage for org.springframework.util StringUtils collectionToCommaDelimitedString.

Prototype

public static String collectionToCommaDelimitedString(@Nullable Collection<?> coll) 

Source Link

Document

Convert a Collection into a delimited String (e.g., CSV).

Usage

From source file:org.geoserver.security.RESTfulPathBasedFilterInvocationDefinitionMap.java

public Collection<ConfigAttribute> lookupAttributes(String url, String httpMethod) {
    // Strip anything after a question mark symbol, as per SEC-161. See also SEC-321
    int firstQuestionMarkIndex = url.indexOf("?");

    if (firstQuestionMarkIndex != -1) {
        url = url.substring(0, firstQuestionMarkIndex);
    }//  ww w  .  j  ava2s .c om

    if (isConvertUrlToLowercaseBeforeComparison()) {
        url = url.toLowerCase();

        if (log.isDebugEnabled()) {
            log.debug("Converted URL to lowercase, from: '" + url + "'; to: '" + url + "'  and httpMethod= "
                    + httpMethod);
        }
    }

    Iterator iter = requestMap.iterator();
    while (iter.hasNext()) {
        EntryHolder entryHolder = (EntryHolder) iter.next();

        String antPath = entryHolder.getAntPath();
        String[] methodList = entryHolder.getHttpMethodList();
        if (log.isDebugEnabled()) {
            log.debug("~~~~~~~~~~ antPath= " + antPath + " methodList= " + Arrays.toString(methodList));
        }

        boolean matchedPath = pathMatcher.match(antPath, url);
        boolean matchedMethods = true;
        if (methodList != null) {
            matchedMethods = false;
            for (int ii = 0; ii < methodList.length; ii++) {
                if (methodList[ii].equals(httpMethod)) {
                    matchedMethods = true;
                    break;
                }
            }
        }
        if (log.isDebugEnabled())
            log.debug("Candidate is: '" + url + "'; antPath is " + antPath + "; matchedPath=" + matchedPath
                    + "; matchedMethods=" + matchedMethods);

        if (matchedPath && matchedMethods) {
            log.debug("returning "
                    + StringUtils.collectionToCommaDelimitedString(entryHolder.getConfigAttributes()));
            return entryHolder.getConfigAttributes();
        }
    }
    return null;
}

From source file:org.LexGrid.LexBIG.gui.load.LoaderExtensionShell.java

/**
 * Builds the gui./*  w w w. j  a v a 2  s. com*/
 * 
 * @param shell the shell
 * @param loader the loader
 */
private void buildGUI(final Shell shell, final Loader loader) {

    Group options = new Group(shell, SWT.NONE);
    options.setText("Load Options");
    shell.setLayout(new GridLayout());

    GridData gd = new GridData(GridData.FILL_HORIZONTAL);
    options.setLayoutData(gd);

    GridLayout layout = new GridLayout(1, false);
    options.setLayout(layout);

    Group groupUri = new Group(options, SWT.NONE);
    groupUri.setLayout(new GridLayout(3, false));
    groupUri.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));

    String uriHelp = "The URI of the resource to load.";

    Label label = new Label(groupUri, SWT.NONE);
    label.setText("URI:");
    label.setToolTipText(uriHelp);

    final Text file = new Text(groupUri, SWT.BORDER);
    file.setLayoutData(new GridData(GridData.GRAB_HORIZONTAL | GridData.FILL_HORIZONTAL));
    file.setToolTipText(uriHelp);

    OptionHolder optionHolder = loader.getOptions();

    final Button uriChooseButton;

    if (optionHolder.isResourceUriFolder()) {
        uriChooseButton = Utility.getFolderChooseButton(groupUri, file);
    } else {
        uriChooseButton = Utility.getFileChooseButton(groupUri, file,
                optionHolder.getResourceUriAllowedFileTypes().toArray(new String[0]),
                optionHolder.getResourceUriAllowedFileTypes().toArray(new String[0]));
    }
    uriChooseButton.setToolTipText(uriHelp);

    // Get resolved value sets
    LexEVSResolvedValueSetService resolvedValueSetService = new LexEVSResolvedValueSetServiceImpl();
    java.util.List<CodingScheme> resolvedValueSets = null;
    try {
        resolvedValueSets = resolvedValueSetService.listAllResolvedValueSets();
    } catch (LBException e) {
        resolvedValueSets = null;
    }

    for (final URIOption uriOption : optionHolder.getURIOptions()) {
        Composite group1 = new Composite(options, SWT.NONE);

        group1.setLayout(new GridLayout(3, false));
        group1.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));

        Label uriOptionLable = new Label(group1, SWT.NONE);
        uriOptionLable.setText(uriOption.getOptionName() + ":");
        uriOptionLable.setToolTipText(uriOption.getHelpText());

        final Text uriOptionFile = new Text(group1, SWT.BORDER);
        uriOptionFile.setLayoutData(new GridData(GridData.GRAB_HORIZONTAL | GridData.FILL_HORIZONTAL));
        uriOptionFile.setToolTipText(uriOption.getHelpText());

        Button uriOptionfileChooseButton = Utility.getFileChooseButton(group1, uriOptionFile,
                uriOption.getAllowedFileExtensions().toArray(new String[0]), null);
        uriOptionfileChooseButton.setToolTipText(uriOption.getHelpText());
        uriOptionfileChooseButton.addSelectionListener(new SelectionListener() {

            public void widgetDefaultSelected(SelectionEvent arg0) {
                //
            }

            public void widgetSelected(SelectionEvent arg0) {
                try {
                    uriOption.setOptionValue(Utility.getAndVerifyURIFromTextField(uriOptionFile));
                } catch (Exception e) {
                    throw new RuntimeException(e);
                }
            }
        });
    }

    for (final Option<Boolean> boolOption : optionHolder.getBooleanOptions()) {
        Composite group2 = new Composite(options, SWT.NONE);

        RowLayout rlo = new RowLayout();
        rlo.marginWidth = 0;
        group2.setLayout(rlo);

        final Button button = new Button(group2, SWT.CHECK);
        button.setText(boolOption.getOptionName());
        button.setToolTipText(boolOption.getHelpText());

        if (boolOption.getOptionValue() != null) {
            button.setSelection(boolOption.getOptionValue());
        }
        button.addSelectionListener(new SelectionListener() {

            public void widgetDefaultSelected(SelectionEvent event) {
                //
            }

            public void widgetSelected(SelectionEvent event) {
                boolOption.setOptionValue(button.getSelection());
            }

        });
    }

    for (final Option<String> stringOption : optionHolder.getStringOptions()) {
        Composite group3 = new Composite(options, SWT.NONE);

        RowLayout rlo = new RowLayout();
        rlo.marginWidth = 0;
        group3.setLayout(rlo);

        Label textLabel = new Label(group3, SWT.NONE);
        textLabel.setText(stringOption.getOptionName() + ":");
        textLabel.setToolTipText(stringOption.getHelpText());

        if (CollectionUtils.isNotEmpty(stringOption.getPickList())) {
            final Combo comboDropDown = new Combo(group3, SWT.DROP_DOWN | SWT.BORDER);

            comboDropDown.setToolTipText(stringOption.getHelpText());

            for (String pickListItem : stringOption.getPickList()) {

                // Add if it is not a resolved value set
                if (resolvedValueSets != null && !isResolvedValueSet(resolvedValueSets, pickListItem)) {
                    comboDropDown.add(pickListItem);
                }
            }

            comboDropDown.addSelectionListener(new SelectionListener() {

                @Override
                public void widgetDefaultSelected(SelectionEvent arg0) {
                    //
                }

                @Override
                public void widgetSelected(SelectionEvent event) {
                    String option = comboDropDown.getItem(comboDropDown.getSelectionIndex());
                    stringOption.setOptionValue(option);
                }
            });
        } else {

            final Text text = new Text(group3, SWT.BORDER);
            RowData textGd = new RowData();
            textGd.width = 25;
            text.setLayoutData(textGd);

            text.setToolTipText(stringOption.getHelpText());

            text.addModifyListener(new ModifyListener() {

                public void modifyText(ModifyEvent event) {
                    stringOption.setOptionValue(text.getText());
                }
            });
        }
    }

    for (final Option<Integer> integerOption : optionHolder.getIntegerOptions()) {
        Composite group3 = new Composite(options, SWT.NONE);

        RowLayout rlo = new RowLayout();
        rlo.marginWidth = 0;
        group3.setLayout(rlo);

        Label textLabel = new Label(group3, SWT.NONE);
        textLabel.setText(integerOption.getOptionName() + ":");
        textLabel.setToolTipText(integerOption.getHelpText());

        final Text text = new Text(group3, SWT.BORDER);
        text.setToolTipText(integerOption.getHelpText());

        if (integerOption.getOptionValue() != null) {
            text.setText(integerOption.getOptionValue().toString());
        }

        text.addModifyListener(new ModifyListener() {

            public void modifyText(ModifyEvent event) {
                integerOption.setOptionValue(Integer.parseInt(text.getText()));
            }
        });
    }

    for (final MultiValueOption<String> stringArrayOption : optionHolder.getStringArrayOptions()) {
        Composite group4 = new Composite(options, SWT.NONE);

        RowLayout rlo = new RowLayout();
        rlo.marginWidth = 0;
        group4.setLayout(rlo);

        Label textLabel = new Label(group4, SWT.NONE);
        String appendString = CollectionUtils.isNotEmpty(stringArrayOption.getPickList()) ? ""
                : "\n\t(Comma Seperated):";
        textLabel.setText(stringArrayOption.getOptionName() + appendString);
        textLabel.setToolTipText(stringArrayOption.getHelpText());

        if (CollectionUtils.isNotEmpty(stringArrayOption.getPickList())) {
            final List multi = new List(group4, SWT.BORDER | SWT.MULTI | SWT.V_SCROLL);

            multi.setToolTipText(stringArrayOption.getHelpText());

            for (String pickListItem : stringArrayOption.getPickList()) {
                multi.add(pickListItem);
            }
            for (int i = 0; i < stringArrayOption.getPickList().size(); i++) {
                if (stringArrayOption.getOptionValue().contains(stringArrayOption.getPickList().get(i))) {
                    multi.select(i);
                }
            }

            multi.addSelectionListener(new SelectionListener() {

                @Override
                public void widgetDefaultSelected(SelectionEvent arg0) {
                    //
                }

                @Override
                public void widgetSelected(SelectionEvent event) {
                    String[] options = multi.getSelection();
                    stringArrayOption.setOptionValue(Arrays.asList(options));
                }
            });
        } else {
            final Text text = new Text(group4, SWT.BORDER);

            text.setToolTipText(stringArrayOption.getHelpText());

            String arrayString = StringUtils
                    .collectionToCommaDelimitedString(stringArrayOption.getOptionValue());
            text.setText(arrayString);

            text.addModifyListener(new ModifyListener() {

                public void modifyText(ModifyEvent event) {
                    String[] options = StringUtils.commaDelimitedListToStringArray(text.getText());
                    stringArrayOption.setOptionValue(Arrays.asList(options));
                }
            });
        }
    }

    Group groupControlButtons = new Group(options, SWT.NONE);
    groupControlButtons.setLayout(new GridLayout(3, false));
    groupControlButtons.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));

    final Button load = new Button(groupControlButtons, SWT.PUSH);
    final Button nextLoad = new Button(groupControlButtons, SWT.PUSH);
    final Button close = new Button(groupControlButtons, SWT.PUSH);
    close.setLayoutData(new GridData(SWT.RIGHT, SWT.CENTER, true, true, 1, 1));

    load.setText("Load");
    load.setToolTipText("Start Load Process.");
    load.addSelectionListener(new SelectionListener() {

        public void widgetSelected(SelectionEvent arg0) {

            URI uri = null;
            // is this a local file?
            File theFile = new File(file.getText());

            if (theFile.exists()) {
                uri = theFile.toURI();
            } else {
                // is it a valid URI (like http://something)
                try {
                    uri = new URI(file.getText());
                    uri.toURL().openConnection();
                } catch (Exception e) {
                    dialog_.showError("Path Error", "No file could be located at this location");
                    return;
                }
            }

            setLoading(true);
            load.setEnabled(false);
            close.setEnabled(false);
            loader.load(uri);

            // Create/start a new thread to update the buttons when the load completes.
            ButtonUpdater buttonUpdater = new ButtonUpdater(nextLoad, close, loader);
            Thread t = new Thread(buttonUpdater);
            t.setDaemon(true);
            t.start();
        }

        public void widgetDefaultSelected(SelectionEvent arg0) {
            // 
        }

    });

    nextLoad.setText("Next Load");
    nextLoad.setToolTipText("Start a New Load Process.");
    nextLoad.setEnabled(false);
    nextLoad.addSelectionListener(new SelectionListener() {

        public void widgetSelected(SelectionEvent arg0) {

            Loader newLoader = null;
            try {
                newLoader = lb_gui_.getLbs().getServiceManager(null).getLoader(loader.getName());
            } catch (LBException e) {
                e.printStackTrace();
            }
            if (!isLoading()) {

                // close the current window and create/initialize it again with the same loader
                shell.dispose();
                setMonitorLoader(true);
                initializeLBGui(newLoader);
            }
        }

        public void widgetDefaultSelected(SelectionEvent arg0) {
            // 
        }

    });

    close.setText("Close");
    close.setToolTipText("Close this Loader Window.");
    close.addSelectionListener(new SelectionListener() {

        public void widgetSelected(SelectionEvent arg0) {
            shell.dispose();
        }

        public void widgetDefaultSelected(SelectionEvent arg0) {
            // 
        }

    });

    Composite status = getStatusComposite(shell, loader);
    gd = new GridData(GridData.FILL_BOTH);
    status.setLayoutData(gd);
}

From source file:org.opennms.netmgt.config.DefaultEventConfDao.java

private void processEvents(Events events, Resource resource, EventConfiguration eventConfiguration,
        String resourceDescription, boolean denyIncludes) {
    if (denyIncludes) {
        if (events.getGlobal() != null) {
            throw new ObjectRetrievalFailureException(Resource.class, resource,
                    "The event resource " + resource
                            + " included from the root event configuration file cannot have a 'global' element",
                    null);/*from  ww w  . j a va  2 s.c  om*/
        }
        if (events.getEventFileCollection().size() > 0) {
            throw new ObjectRetrievalFailureException(Resource.class, resource, "The event resource " + resource
                    + " included from the root event configuration file cannot include other configuration files: "
                    + StringUtils.collectionToCommaDelimitedString(events.getEventFileCollection()), null);
        }
    }

    eventConfiguration.getEventFiles().put(resource, events);
    for (Event event : events.getEventCollection()) {
        eventConfiguration.getEventConfData().put(event);
    }

    log().info("DefaultEventConfDao: Loaded " + events.getEventCollection().size() + " events from "
            + resourceDescription + " event configuration resource: " + resource);

    eventConfiguration.incrementEventCount(events.getEventCount());
}

From source file:org.sakaiproject.tool.impl.SessionComponent.java

public String getClusterableTools() {
    return StringUtils.collectionToCommaDelimitedString(clusterableTools);
    // return clusterableTools;
}

From source file:org.springframework.amqp.rabbit.listener.adapter.MessageListenerAdapter.java

/**
 * Invoke the specified listener method.
 * @param methodName the name of the listener method
 * @param arguments the message arguments to be passed in
 * @return the result returned from the listener method
 * @throws Exception if thrown by Rabbit API methods
 * @see #getListenerMethodName/*from   w  w w.  ja va2s .  co m*/
 * @see #buildListenerArguments
 */
protected Object invokeListenerMethod(String methodName, Object[] arguments) throws Exception {
    try {
        MethodInvoker methodInvoker = new MethodInvoker();
        methodInvoker.setTargetObject(getDelegate());
        methodInvoker.setTargetMethod(methodName);
        methodInvoker.setArguments(arguments);
        methodInvoker.prepare();
        return methodInvoker.invoke();
    } catch (InvocationTargetException ex) {
        Throwable targetEx = ex.getTargetException();
        if (targetEx instanceof IOException) {
            throw new AmqpIOException((IOException) targetEx);
        } else {
            throw new ListenerExecutionFailedException("Listener method '" + methodName + "' threw exception",
                    targetEx);
        }
    } catch (Throwable ex) {
        ArrayList<String> arrayClass = new ArrayList<String>();
        if (arguments != null) {
            for (int i = 0; i < arguments.length; i++) {
                arrayClass.add(arguments[i].getClass().toString());
            }
        }
        throw new ListenerExecutionFailedException("Failed to invoke target method '" + methodName
                + "' with argument type = [" + StringUtils.collectionToCommaDelimitedString(arrayClass)
                + "], value = [" + ObjectUtils.nullSafeToString(arguments) + "]", ex);
    }
}

From source file:org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.java

/**
 * Actually create the specified bean. Pre-creation processing has already happened
 * at this point, e.g. checking {@code postProcessBeforeInstantiation} callbacks.
 * <p>Differentiates between default bean instantiation, use of a
 * factory method, and autowiring a constructor.
 * @param beanName the name of the bean/*from w w w . ja v  a2 s .  c  om*/
 * @param mbd the merged bean definition for the bean
 * @param args explicit arguments to use for constructor or factory method invocation
 * @return a new instance of the bean
 * @throws BeanCreationException if the bean could not be created
 * @see #instantiateBean
 * @see #instantiateUsingFactoryMethod
 * @see #autowireConstructor
 */
protected Object doCreateBean(final String beanName, final RootBeanDefinition mbd,
        final @Nullable Object[] args) throws BeanCreationException {

    // Instantiate the bean.
    BeanWrapper instanceWrapper = null;
    if (mbd.isSingleton()) {
        instanceWrapper = this.factoryBeanInstanceCache.remove(beanName);
    }
    if (instanceWrapper == null) {
        instanceWrapper = createBeanInstance(beanName, mbd, args);
    }
    final Object bean = instanceWrapper.getWrappedInstance();
    Class<?> beanType = instanceWrapper.getWrappedClass();
    if (beanType != NullBean.class) {
        mbd.resolvedTargetType = beanType;
    }

    // Allow post-processors to modify the merged bean definition.
    synchronized (mbd.postProcessingLock) {
        if (!mbd.postProcessed) {
            try {
                applyMergedBeanDefinitionPostProcessors(mbd, beanType, beanName);
            } catch (Throwable ex) {
                throw new BeanCreationException(mbd.getResourceDescription(), beanName,
                        "Post-processing of merged bean definition failed", ex);
            }
            mbd.postProcessed = true;
        }
    }

    // Eagerly cache singletons to be able to resolve circular references
    // even when triggered by lifecycle interfaces like BeanFactoryAware.
    boolean earlySingletonExposure = (mbd.isSingleton() && this.allowCircularReferences
            && isSingletonCurrentlyInCreation(beanName));
    if (earlySingletonExposure) {
        if (logger.isTraceEnabled()) {
            logger.trace("Eagerly caching bean '" + beanName
                    + "' to allow for resolving potential circular references");
        }
        addSingletonFactory(beanName, () -> getEarlyBeanReference(beanName, mbd, bean));
    }

    // Initialize the bean instance.
    Object exposedObject = bean;
    try {
        populateBean(beanName, mbd, instanceWrapper);
        exposedObject = initializeBean(beanName, exposedObject, mbd);
    } catch (Throwable ex) {
        if (ex instanceof BeanCreationException
                && beanName.equals(((BeanCreationException) ex).getBeanName())) {
            throw (BeanCreationException) ex;
        } else {
            throw new BeanCreationException(mbd.getResourceDescription(), beanName,
                    "Initialization of bean failed", ex);
        }
    }

    if (earlySingletonExposure) {
        Object earlySingletonReference = getSingleton(beanName, false);
        if (earlySingletonReference != null) {
            if (exposedObject == bean) {
                exposedObject = earlySingletonReference;
            } else if (!this.allowRawInjectionDespiteWrapping && hasDependentBean(beanName)) {
                String[] dependentBeans = getDependentBeans(beanName);
                Set<String> actualDependentBeans = new LinkedHashSet<>(dependentBeans.length);
                for (String dependentBean : dependentBeans) {
                    if (!removeSingletonIfCreatedForTypeCheckOnly(dependentBean)) {
                        actualDependentBeans.add(dependentBean);
                    }
                }
                if (!actualDependentBeans.isEmpty()) {
                    throw new BeanCurrentlyInCreationException(beanName, "Bean with name '" + beanName
                            + "' has been injected into other beans ["
                            + StringUtils.collectionToCommaDelimitedString(actualDependentBeans)
                            + "] in its raw version as part of a circular reference, but has eventually been "
                            + "wrapped. This means that said other beans do not use the final version of the "
                            + "bean. This is often the result of over-eager type matching - consider using "
                            + "'getBeanNamesOfType' with the 'allowEagerInit' flag turned off, for example.");
                }
            }
        }
    }

    // Register bean as disposable.
    try {
        registerDisposableBeanIfNecessary(beanName, bean, mbd);
    } catch (BeanDefinitionValidationException ex) {
        throw new BeanCreationException(mbd.getResourceDescription(), beanName, "Invalid destruction signature",
                ex);
    }

    return exposedObject;
}

From source file:org.springframework.beans.factory.support.ConstructorResolver.java

/**
 * Instantiate the bean using a named factory method. The method may be static, if the
 * bean definition parameter specifies a class, rather than a "factory-bean", or
 * an instance variable on a factory object itself configured using Dependency Injection.
 * <p>Implementation requires iterating over the static or instance methods with the
 * name specified in the RootBeanDefinition (the method may be overloaded) and trying
 * to match with the parameters. We don't have the types attached to constructor args,
 * so trial and error is the only way to go here. The explicitArgs array may contain
 * argument values passed in programmatically via the corresponding getBean method.
 * @param beanName the name of the bean//from  w w w  .ja  va  2  s.  co  m
 * @param mbd the merged bean definition for the bean
 * @param explicitArgs argument values passed in programmatically via the getBean
 * method, or {@code null} if none (-> use constructor argument values from bean definition)
 * @return a BeanWrapper for the new instance
 */
public BeanWrapper instantiateUsingFactoryMethod(final String beanName, final RootBeanDefinition mbd,
        @Nullable final Object[] explicitArgs) {

    BeanWrapperImpl bw = new BeanWrapperImpl();
    this.beanFactory.initBeanWrapper(bw);

    Object factoryBean;
    Class<?> factoryClass;
    boolean isStatic;

    String factoryBeanName = mbd.getFactoryBeanName();
    if (factoryBeanName != null) {
        if (factoryBeanName.equals(beanName)) {
            throw new BeanDefinitionStoreException(mbd.getResourceDescription(), beanName,
                    "factory-bean reference points back to the same bean definition");
        }
        factoryBean = this.beanFactory.getBean(factoryBeanName);
        if (mbd.isSingleton() && this.beanFactory.containsSingleton(beanName)) {
            throw new ImplicitlyAppearedSingletonException();
        }
        factoryClass = factoryBean.getClass();
        isStatic = false;
    } else {
        // It's a static factory method on the bean class.
        if (!mbd.hasBeanClass()) {
            throw new BeanDefinitionStoreException(mbd.getResourceDescription(), beanName,
                    "bean definition declares neither a bean class nor a factory-bean reference");
        }
        factoryBean = null;
        factoryClass = mbd.getBeanClass();
        isStatic = true;
    }

    Method factoryMethodToUse = null;
    ArgumentsHolder argsHolderToUse = null;
    Object[] argsToUse = null;

    if (explicitArgs != null) {
        argsToUse = explicitArgs;
    } else {
        Object[] argsToResolve = null;
        synchronized (mbd.constructorArgumentLock) {
            factoryMethodToUse = (Method) mbd.resolvedConstructorOrFactoryMethod;
            if (factoryMethodToUse != null && mbd.constructorArgumentsResolved) {
                // Found a cached factory method...
                argsToUse = mbd.resolvedConstructorArguments;
                if (argsToUse == null) {
                    argsToResolve = mbd.preparedConstructorArguments;
                }
            }
        }
        if (argsToResolve != null) {
            argsToUse = resolvePreparedArguments(beanName, mbd, bw, factoryMethodToUse, argsToResolve, true);
        }
    }

    if (factoryMethodToUse == null || argsToUse == null) {
        // Need to determine the factory method...
        // Try all methods with this name to see if they match the given arguments.
        factoryClass = ClassUtils.getUserClass(factoryClass);

        Method[] rawCandidates = getCandidateMethods(factoryClass, mbd);
        List<Method> candidateSet = new ArrayList<>();
        for (Method candidate : rawCandidates) {
            if (Modifier.isStatic(candidate.getModifiers()) == isStatic && mbd.isFactoryMethod(candidate)) {
                candidateSet.add(candidate);
            }
        }
        Method[] candidates = candidateSet.toArray(new Method[0]);
        AutowireUtils.sortFactoryMethods(candidates);

        ConstructorArgumentValues resolvedValues = null;
        boolean autowiring = (mbd.getResolvedAutowireMode() == RootBeanDefinition.AUTOWIRE_CONSTRUCTOR);
        int minTypeDiffWeight = Integer.MAX_VALUE;
        Set<Method> ambiguousFactoryMethods = null;

        int minNrOfArgs;
        if (explicitArgs != null) {
            minNrOfArgs = explicitArgs.length;
        } else {
            // We don't have arguments passed in programmatically, so we need to resolve the
            // arguments specified in the constructor arguments held in the bean definition.
            if (mbd.hasConstructorArgumentValues()) {
                ConstructorArgumentValues cargs = mbd.getConstructorArgumentValues();
                resolvedValues = new ConstructorArgumentValues();
                minNrOfArgs = resolveConstructorArguments(beanName, mbd, bw, cargs, resolvedValues);
            } else {
                minNrOfArgs = 0;
            }
        }

        LinkedList<UnsatisfiedDependencyException> causes = null;

        for (Method candidate : candidates) {
            Class<?>[] paramTypes = candidate.getParameterTypes();

            if (paramTypes.length >= minNrOfArgs) {
                ArgumentsHolder argsHolder;

                if (explicitArgs != null) {
                    // Explicit arguments given -> arguments length must match exactly.
                    if (paramTypes.length != explicitArgs.length) {
                        continue;
                    }
                    argsHolder = new ArgumentsHolder(explicitArgs);
                } else {
                    // Resolved constructor arguments: type conversion and/or autowiring necessary.
                    try {
                        String[] paramNames = null;
                        ParameterNameDiscoverer pnd = this.beanFactory.getParameterNameDiscoverer();
                        if (pnd != null) {
                            paramNames = pnd.getParameterNames(candidate);
                        }
                        argsHolder = createArgumentArray(beanName, mbd, resolvedValues, bw, paramTypes,
                                paramNames, candidate, autowiring, candidates.length == 1);
                    } catch (UnsatisfiedDependencyException ex) {
                        if (logger.isTraceEnabled()) {
                            logger.trace("Ignoring factory method [" + candidate + "] of bean '" + beanName
                                    + "': " + ex);
                        }
                        // Swallow and try next overloaded factory method.
                        if (causes == null) {
                            causes = new LinkedList<>();
                        }
                        causes.add(ex);
                        continue;
                    }
                }

                int typeDiffWeight = (mbd.isLenientConstructorResolution()
                        ? argsHolder.getTypeDifferenceWeight(paramTypes)
                        : argsHolder.getAssignabilityWeight(paramTypes));
                // Choose this factory method if it represents the closest match.
                if (typeDiffWeight < minTypeDiffWeight) {
                    factoryMethodToUse = candidate;
                    argsHolderToUse = argsHolder;
                    argsToUse = argsHolder.arguments;
                    minTypeDiffWeight = typeDiffWeight;
                    ambiguousFactoryMethods = null;
                }
                // Find out about ambiguity: In case of the same type difference weight
                // for methods with the same number of parameters, collect such candidates
                // and eventually raise an ambiguity exception.
                // However, only perform that check in non-lenient constructor resolution mode,
                // and explicitly ignore overridden methods (with the same parameter signature).
                else if (factoryMethodToUse != null && typeDiffWeight == minTypeDiffWeight
                        && !mbd.isLenientConstructorResolution()
                        && paramTypes.length == factoryMethodToUse.getParameterCount()
                        && !Arrays.equals(paramTypes, factoryMethodToUse.getParameterTypes())) {
                    if (ambiguousFactoryMethods == null) {
                        ambiguousFactoryMethods = new LinkedHashSet<>();
                        ambiguousFactoryMethods.add(factoryMethodToUse);
                    }
                    ambiguousFactoryMethods.add(candidate);
                }
            }
        }

        if (factoryMethodToUse == null) {
            if (causes != null) {
                UnsatisfiedDependencyException ex = causes.removeLast();
                for (Exception cause : causes) {
                    this.beanFactory.onSuppressedException(cause);
                }
                throw ex;
            }
            List<String> argTypes = new ArrayList<>(minNrOfArgs);
            if (explicitArgs != null) {
                for (Object arg : explicitArgs) {
                    argTypes.add(arg != null ? arg.getClass().getSimpleName() : "null");
                }
            } else if (resolvedValues != null) {
                Set<ValueHolder> valueHolders = new LinkedHashSet<>(resolvedValues.getArgumentCount());
                valueHolders.addAll(resolvedValues.getIndexedArgumentValues().values());
                valueHolders.addAll(resolvedValues.getGenericArgumentValues());
                for (ValueHolder value : valueHolders) {
                    String argType = (value.getType() != null ? ClassUtils.getShortName(value.getType())
                            : (value.getValue() != null ? value.getValue().getClass().getSimpleName()
                                    : "null"));
                    argTypes.add(argType);
                }
            }
            String argDesc = StringUtils.collectionToCommaDelimitedString(argTypes);
            throw new BeanCreationException(mbd.getResourceDescription(), beanName,
                    "No matching factory method found: "
                            + (mbd.getFactoryBeanName() != null
                                    ? "factory bean '" + mbd.getFactoryBeanName() + "'; "
                                    : "")
                            + "factory method '" + mbd.getFactoryMethodName() + "(" + argDesc + ")'. "
                            + "Check that a method with the specified name "
                            + (minNrOfArgs > 0 ? "and arguments " : "") + "exists and that it is "
                            + (isStatic ? "static" : "non-static") + ".");
        } else if (void.class == factoryMethodToUse.getReturnType()) {
            throw new BeanCreationException(mbd.getResourceDescription(), beanName, "Invalid factory method '"
                    + mbd.getFactoryMethodName() + "': needs to have a non-void return type!");
        } else if (ambiguousFactoryMethods != null) {
            throw new BeanCreationException(mbd.getResourceDescription(), beanName,
                    "Ambiguous factory method matches found in bean '" + beanName + "' "
                            + "(hint: specify index/type/name arguments for simple parameters to avoid type ambiguities): "
                            + ambiguousFactoryMethods);
        }

        if (explicitArgs == null && argsHolderToUse != null) {
            argsHolderToUse.storeCache(mbd, factoryMethodToUse);
        }
    }

    try {
        Object beanInstance;

        if (System.getSecurityManager() != null) {
            final Object fb = factoryBean;
            final Method factoryMethod = factoryMethodToUse;
            final Object[] args = argsToUse;
            beanInstance = AccessController.doPrivileged(
                    (PrivilegedAction<Object>) () -> this.beanFactory.getInstantiationStrategy()
                            .instantiate(mbd, beanName, this.beanFactory, fb, factoryMethod, args),
                    this.beanFactory.getAccessControlContext());
        } else {
            beanInstance = this.beanFactory.getInstantiationStrategy().instantiate(mbd, beanName,
                    this.beanFactory, factoryBean, factoryMethodToUse, argsToUse);
        }

        bw.setBeanInstance(beanInstance);
        return bw;
    } catch (Throwable ex) {
        throw new BeanCreationException(mbd.getResourceDescription(), beanName,
                "Bean instantiation via factory method failed", ex);
    }
}

From source file:org.springframework.boot.autoconfigure.data.redis.RedisAutoConfigurationTests.java

@Test
public void testRedisConfigurationWithSentinel() {
    List<String> sentinels = Arrays.asList("127.0.0.1:26379", "127.0.0.1:26380");
    this.contextRunner
            .withPropertyValues("spring.redis.sentinel.master:mymaster",
                    "spring.redis.sentinel.nodes:" + StringUtils.collectionToCommaDelimitedString(sentinels))
            .run((context) -> assertThat(context.getBean(LettuceConnectionFactory.class).isRedisSentinelAware())
                    .isTrue());/*from  w  ww.  j  a  va2 s  .  c om*/
}

From source file:org.springframework.boot.cli.command.init.ProjectGenerationRequest.java

/**
 * Generates the URI to use to generate a project represented by this request.
 * @param metadata the metadata that describes the service
 * @return the project generation URI/*w  w w  .j  a va 2s . co  m*/
 */
URI generateUrl(InitializrServiceMetadata metadata) {
    try {
        URIBuilder builder = new URIBuilder(this.serviceUrl);
        StringBuilder sb = new StringBuilder();
        if (builder.getPath() != null) {
            sb.append(builder.getPath());
        }

        ProjectType projectType = determineProjectType(metadata);
        this.type = projectType.getId();
        sb.append(projectType.getAction());
        builder.setPath(sb.toString());

        if (!this.dependencies.isEmpty()) {
            builder.setParameter("dependencies",
                    StringUtils.collectionToCommaDelimitedString(this.dependencies));
        }

        if (this.groupId != null) {
            builder.setParameter("groupId", this.groupId);
        }
        String resolvedArtifactId = resolveArtifactId();
        if (resolvedArtifactId != null) {
            builder.setParameter("artifactId", resolvedArtifactId);
        }
        if (this.version != null) {
            builder.setParameter("version", this.version);
        }
        if (this.name != null) {
            builder.setParameter("name", this.name);
        }
        if (this.description != null) {
            builder.setParameter("description", this.description);
        }
        if (this.packageName != null) {
            builder.setParameter("packageName", this.packageName);
        }
        if (this.type != null) {
            builder.setParameter("type", projectType.getId());
        }
        if (this.packaging != null) {
            builder.setParameter("packaging", this.packaging);
        }
        if (this.javaVersion != null) {
            builder.setParameter("javaVersion", this.javaVersion);
        }
        if (this.language != null) {
            builder.setParameter("language", this.language);
        }
        if (this.bootVersion != null) {
            builder.setParameter("bootVersion", this.bootVersion);
        }

        return builder.build();
    } catch (URISyntaxException e) {
        throw new ReportableException("Invalid service URL (" + e.getMessage() + ")");
    }
}

From source file:org.springframework.boot.cloud.CloudFoundryVcapEnvironmentPostProcessor.java

@SuppressWarnings("unchecked")
private void flatten(Properties properties, Map<String, Object> input, String path) {
    for (Entry<String, Object> entry : input.entrySet()) {
        String key = getFullKey(path, entry.getKey());
        Object value = entry.getValue();
        if (value instanceof Map) {
            // Need a compound key
            flatten(properties, (Map<String, Object>) value, key);
        } else if (value instanceof Collection) {
            // Need a compound key
            Collection<Object> collection = (Collection<Object>) value;
            properties.put(key, StringUtils.collectionToCommaDelimitedString(collection));
            int count = 0;
            for (Object item : collection) {
                String itemKey = "[" + (count++) + "]";
                flatten(properties, Collections.singletonMap(itemKey, item), key);
            }//from w w  w  .  j  ava2s  .  co  m
        } else if (value instanceof String) {
            properties.put(key, value);
        } else if (value instanceof Number) {
            properties.put(key, value.toString());
        } else if (value instanceof Boolean) {
            properties.put(key, value.toString());
        } else {
            properties.put(key, value == null ? "" : value);
        }
    }
}