Java Code Examples for org.springframework.util.ClassUtils#getConstructorIfAvailable()

The following examples show how to use org.springframework.util.ClassUtils#getConstructorIfAvailable() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: TestContextManager.java    From spring-analysis-note with MIT License 6 votes vote down vote up
/**
 * Attempt to create a copy of the supplied {@code TestContext} using its
 * <em>copy constructor</em>.
 */
private static TestContext copyTestContext(TestContext testContext) {
	Constructor<? extends TestContext> constructor =
			ClassUtils.getConstructorIfAvailable(testContext.getClass(), testContext.getClass());

	if (constructor != null) {
		try {
			ReflectionUtils.makeAccessible(constructor);
			return constructor.newInstance(testContext);
		}
		catch (Exception ex) {
			if (logger.isInfoEnabled()) {
				logger.info(String.format("Failed to invoke copy constructor for [%s]; " +
						"concurrent test execution is therefore likely not supported.",
						testContext), ex);
			}
		}
	}

	// Fallback to original instance
	return testContext;
}
 
Example 2
Source File: PagedResultsRequestControl.java    From spring-ldap with Apache License 2.0 6 votes vote down vote up
public Control createRequestControl() {
	byte[] actualCookie = null;
	if (cookie != null) {
		actualCookie = cookie.getCookie();
	}
	Constructor constructor = ClassUtils.getConstructorIfAvailable(requestControlClass, new Class[] { int.class,
			byte[].class, boolean.class });
	if (constructor == null) {
		throw new IllegalArgumentException("Failed to find an appropriate RequestControl constructor");
	}

	Control result = null;
	try {
		result = (Control) constructor.newInstance(pageSize, actualCookie,
                   critical);
	}
	catch (Exception e) {
		ReflectionUtils.handleReflectionException(e);
	}

	return result;
}
 
Example 3
Source File: TestContextManager.java    From java-technology-stack with MIT License 6 votes vote down vote up
/**
 * Attempt to create a copy of the supplied {@code TestContext} using its
 * <em>copy constructor</em>.
 */
private static TestContext copyTestContext(TestContext testContext) {
	Constructor<? extends TestContext> constructor =
			ClassUtils.getConstructorIfAvailable(testContext.getClass(), testContext.getClass());

	if (constructor != null) {
		try {
			ReflectionUtils.makeAccessible(constructor);
			return constructor.newInstance(testContext);
		}
		catch (Exception ex) {
			if (logger.isInfoEnabled()) {
				logger.info(String.format("Failed to invoke copy constructor for [%s]; " +
						"concurrent test execution is therefore likely not supported.",
						testContext), ex);
			}
		}
	}

	// Fallback to original instance
	return testContext;
}
 
Example 4
Source File: AbstractFallbackRequestAndResponseControlDirContextProcessor.java    From spring-ldap with Apache License 2.0 6 votes vote down vote up
/**
 * Creates a request control using the constructor parameters given in
 * <code>params</code>.
 * @param paramTypes Types of the constructor parameters
 * @param params Actual constructor parameters
 * @return Control to be used by the DirContextProcessor
 */
public Control createRequestControl(Class<?>[] paramTypes, Object[] params) {
	Constructor<?> constructor = ClassUtils.getConstructorIfAvailable(requestControlClass, paramTypes);
	if (constructor == null) {
		throw new IllegalArgumentException("Failed to find an appropriate RequestControl constructor");
	}

	Control result = null;
	try {
		result = (Control) constructor.newInstance(params);
	}
	catch (Exception e) {
		ReflectionUtils.handleReflectionException(e);
	}

	return result;
}
 
Example 5
Source File: KeyValueRepositoryFactory.java    From spring-data-keyvalue with Apache License 2.0 6 votes vote down vote up
@Override
@SuppressWarnings("unchecked")
public RepositoryQuery resolveQuery(Method method, RepositoryMetadata metadata, ProjectionFactory factory,
		NamedQueries namedQueries) {

	QueryMethod queryMethod = new QueryMethod(method, metadata, factory);

	Constructor<? extends KeyValuePartTreeQuery> constructor = (Constructor<? extends KeyValuePartTreeQuery>) ClassUtils
			.getConstructorIfAvailable(this.repositoryQueryType, QueryMethod.class,
					QueryMethodEvaluationContextProvider.class, KeyValueOperations.class, Class.class);

	Assert.state(constructor != null,
			String.format(
					"Constructor %s(QueryMethod, EvaluationContextProvider, KeyValueOperations, Class) not available!",
					ClassUtils.getShortName(this.repositoryQueryType)));

	return BeanUtils.instantiateClass(constructor, queryMethod, evaluationContextProvider, this.keyValueOperations,
			this.queryCreator);
}
 
Example 6
Source File: SimpleEmailServiceJavaMailSender.java    From spring-cloud-aws with Apache License 2.0 6 votes vote down vote up
@Override
public MimeMessage createMimeMessage() {

	// We have to use reflection as SmartMimeMessage is not package-private
	if (ClassUtils.isPresent(SMART_MIME_MESSAGE_CLASS_NAME,
			ClassUtils.getDefaultClassLoader())) {
		Class<?> smartMimeMessage = ClassUtils.resolveClassName(
				SMART_MIME_MESSAGE_CLASS_NAME, ClassUtils.getDefaultClassLoader());
		Constructor<?> constructor = ClassUtils.getConstructorIfAvailable(
				smartMimeMessage, Session.class, String.class, FileTypeMap.class);
		if (constructor != null) {
			Object mimeMessage = BeanUtils.instantiateClass(constructor, getSession(),
					this.defaultEncoding, this.defaultFileTypeMap);
			return (MimeMessage) mimeMessage;
		}
	}

	return new MimeMessage(getSession());
}
 
Example 7
Source File: SolrClientUtils.java    From dubbox with Apache License 2.0 6 votes vote down vote up
private static SolrClient cloneCloudSolrClient(SolrClient solrClient, String core) {
	if (VersionUtil.isSolr3XAvailable() || solrClient == null) {
		return null;
	}

	CloudSolrClient cloudServer = (CloudSolrClient) solrClient;
	String zkHost = readField(solrClient, "zkHost");

	Constructor<? extends SolrClient> constructor = (Constructor<? extends SolrClient>) ClassUtils
			.getConstructorIfAvailable(solrClient.getClass(), String.class, LBHttpSolrClient.class);

	CloudSolrClient clone = (CloudSolrClient) BeanUtils.instantiateClass(constructor, zkHost,
			cloneLBHttpSolrClient(cloudServer.getLbClient(), core));

	if (org.springframework.util.StringUtils.hasText(core)) {
		clone.setDefaultCollection(core);
	}
	return clone;
}
 
Example 8
Source File: SolrClientUtils.java    From dubbox with Apache License 2.0 6 votes vote down vote up
private static HttpClient cloneHttpClient(HttpClient sourceClient)
		throws InstantiationException, IllegalAccessException, IllegalArgumentException, InvocationTargetException {

	if (sourceClient == null) {
		return null;
	}

	Class<?> clientType = ClassUtils.getUserClass(sourceClient);
	Constructor<?> constructor = ClassUtils.getConstructorIfAvailable(clientType, HttpParams.class);
	if (constructor != null) {

		HttpClient targetClient = (HttpClient) constructor.newInstance(sourceClient.getParams());
		BeanUtils.copyProperties(sourceClient, targetClient);
		return targetClient;
	} else {
		return new DefaultHttpClient(sourceClient.getParams());
	}

}
 
Example 9
Source File: JpaCloningServiceImpl.java    From spring-content with Apache License 2.0 6 votes vote down vote up
@Override
public Object clone(Object entity) {

    Class clazz = entity.getClass();
    Constructor copyCtor = ClassUtils.getConstructorIfAvailable(clazz, clazz);
    if (copyCtor == null) {
        throw new LockingAndVersioningException(format("no copy constructor: %s", clazz.getCanonicalName()));
    }

    Object newInstance = null;
    try {
        newInstance = copyCtor.newInstance(entity);
    } catch (Exception e) {
        throw new LockingAndVersioningException("copy constructor failed", e);
    }
    return newInstance;
}
 
Example 10
Source File: TableComponent.java    From jdal with Apache License 2.0 5 votes vote down vote up
/**
 * Create the BeanContainer to use.
 * @param beanClass bean type in container
 * @param data intial data.
 * @return a new BeanContainer
 */
protected Container createBeanContainer(Class<T> beanClass, List<T> data) {
	Constructor<?extends Container> ctor = 
			ClassUtils.getConstructorIfAvailable(this.containerClass, Class.class, Collection.class);
	
	if (ctor != null)
		return BeanUtils.instantiateClass(ctor, beanClass, data);
	
	return new BeanItemContainer<T>(beanClass, data);
}
 
Example 11
Source File: ComponentDescriptor.java    From fenixedu-cms with GNU Lesser General Public License v3.0 5 votes vote down vote up
private Constructor<?> getCustomCtor(Class<?> type) {
    for (Constructor<?> ctor : type.getDeclaredConstructors()) {
        if (ctor.isAnnotationPresent(DynamicComponent.class) && !isJsonConstructor(ctor)) {
            return ctor;
        }
    }
    return ClassUtils.getConstructorIfAvailable(type);
}
 
Example 12
Source File: SolrClientUtils.java    From dubbox with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings({ "unchecked", "rawtypes" })
private static SolrClient cloneEmbeddedSolrServer(SolrClient solrClient, String core) {

	CoreContainer coreContainer = ((EmbeddedSolrServer) solrClient).getCoreContainer();
	try {
		Constructor constructor = ClassUtils.getConstructorIfAvailable(solrClient.getClass(), CoreContainer.class,
				String.class);
		return (SolrClient) BeanUtils.instantiateClass(constructor, coreContainer, core);
	} catch (Exception e) {
		throw new BeanInstantiationException(solrClient.getClass(),
				"Cannot create instace of " + solrClient.getClass() + ".", e);
	}
}
 
Example 13
Source File: DashboardExtensionsPanel.java    From syncope with Apache License 2.0 4 votes vote down vote up
public DashboardExtensionsPanel(
        final String id, final List<Class<? extends BaseExtWidget>> extWidgetClasses, final PageReference pageRef) {

    super(id);

    List<BaseExtWidget> instances = new ArrayList<>();

    for (final Class<? extends BaseExtWidget> clazz : extWidgetClasses) {
        final Constructor<? extends BaseExtWidget> constructor =
                ClassUtils.getConstructorIfAvailable(clazz, String.class, PageReference.class);
        if (constructor == null) {
            LOG.error("Could not find required construtor in {}, ignoring", clazz);
        } else {
            try {
                instances.add(constructor.newInstance("widget", pageRef));
            } catch (Exception e) {
                LOG.error("While creating instance of {}", clazz, e);
            }
        }
    }

    ListView<BaseExtWidget> widgets = new ListView<BaseExtWidget>("widgets", instances) {

        private static final long serialVersionUID = 4949588177564901031L;

        @Override
        protected void populateItem(final ListItem<BaseExtWidget> item) {
            WebMarkupContainer widgetContainer = new WebMarkupContainer("widgetContainer");
            widgetContainer.setOutputMarkupId(true);
            ExtWidget ann = item.getModelObject().getClass().getAnnotation(ExtWidget.class);
            if (ann != null) {
                widgetContainer.add(new AttributeModifier("class", ann.cssClass()));
            }
            item.add(widgetContainer);

            item.getModelObject().setOutputMarkupId(true);
            widgetContainer.add(item.getModelObject());
        }
    };
    add(widgets);
}
 
Example 14
Source File: ObjectToObjectConverter.java    From spring4-understanding with Apache License 2.0 4 votes vote down vote up
private static Constructor<?> determineFactoryConstructor(Class<?> targetClass, Class<?> sourceClass) {
	return ClassUtils.getConstructorIfAvailable(targetClass, sourceClass);
}
 
Example 15
Source File: KeyValuePartTreeQuery.java    From spring-data-keyvalue with Apache License 2.0 4 votes vote down vote up
ConstructorCachingQueryCreatorFactory(Class<? extends AbstractQueryCreator<?, ?>> type) {

			this.type = type;
			this.constructor = ClassUtils.getConstructorIfAvailable(type, PartTree.class, ParameterAccessor.class);
		}
 
Example 16
Source File: ObjectToObjectConverter.java    From lams with GNU General Public License v2.0 4 votes vote down vote up
private static Constructor<?> determineFactoryConstructor(Class<?> targetClass, Class<?> sourceClass) {
	return ClassUtils.getConstructorIfAvailable(targetClass, sourceClass);
}
 
Example 17
Source File: ObjectToObjectConverter.java    From java-technology-stack with MIT License 4 votes vote down vote up
@Nullable
private static Constructor<?> determineFactoryConstructor(Class<?> targetClass, Class<?> sourceClass) {
	return ClassUtils.getConstructorIfAvailable(targetClass, sourceClass);
}
 
Example 18
Source File: ObjectToObjectConverter.java    From spring-analysis-note with MIT License 4 votes vote down vote up
@Nullable
private static Constructor<?> determineFactoryConstructor(Class<?> targetClass, Class<?> sourceClass) {
	return ClassUtils.getConstructorIfAvailable(targetClass, sourceClass);
}
 
Example 19
Source File: EmbeddedSolrServerFactory.java    From dubbox with Apache License 2.0 2 votes vote down vote up
/**
 * Create {@link org.apache.solr.core.CoreContainer} via its constructor
 * (Solr 3.6.0 - 4.3.1)
 *
 * @param solrHomeDirectory
 * @param solrXmlFile
 * @return
 */
private CoreContainer createCoreContainerViaConstructor(String solrHomeDirectory, File solrXmlFile) {
	Constructor<CoreContainer> constructor = ClassUtils.getConstructorIfAvailable(CoreContainer.class, String.class,
			File.class);
	return BeanUtils.instantiateClass(constructor, solrHomeDirectory, solrXmlFile);
}