Seam 3 - retrieve all seam components in application context - seam

is there a way to get all the Seam 3 component classes which are #ApplicationScoped?

Didn't try myself, just a guess after reading 16.5. The Bean interface chapter of Weld documentation
class ApplicationScopedBeans {
#Inject BeanManager beanManager;
public Set<Bean<?>> getApplicationScopedBeans() {
Set<Bean<?>> allBeans = beanManager.getBeans(Object.class, new AnnotationLiteral<Any>() {});
Set<Bean<?>> result = new HashSet<Bean<?>>();
for(Bean<?> bean : allBeans) {
if(bean.getScope().equals(ApplicationScoped.class)) {
result.add(bean);
}
}
return result;
}
}
UPDATE
To obtain an instance of a Bean:
public Object getApplicationScopedInstance(Bean<?> bean) {
CreationalContext ctx = beanManager.createCreationalContext(bean);
Context appCtx = beanManager.getContext(ApplicationScoped.class);
return appCtx.get(bean, ctx);
}
UPDATE 2
Looks like all above misses the whole point of CDI :)
class ApplicationScopedBeans {
#Inject #ApplicationScoped Instance<Object> appScopedBeans;
}

if you want to call a method from a component in applicationContext or use a field in this, it's better that u define it as producer method or field and inject it where u want.

You would use getApplicationContext() to get the context, and then the getNames() to get all names of things that are application scope, and then you would use get()to retrieve them by name.
What are you trying to do? From there you would have to use reflection to get them to the right type..
Context appContext = Contexts.getApplicationContext();
String [] names = appContext.getNames();
//Do whatever with them..
for(String s : names){
Object x = appContext.get(name);
// do something.
}

Related

Spring Data Elasticsearch #Document indexName defined at runtime

Is it possible to specify dynamically (at runtime) the indexName for each #Document, for example, via a configuration file? Or is it possible to make #Document Spring environment (dev, prod) dependant?
Thank you!
The #Document annotation does not permit to pass the indexname in parameter directly. However I found a work around.
In my configuration class I created a Bean returning a string. In this string I injected the name of the index with #Value :
#Value("${etrali.indexname}")
private String indexName;
#Bean
public String indexName(){
return indexName;
}
Afterward it is possible to inject the index into the #Documentation annotation like this :
#Document(indexName="#{#indexName}",type = "syslog_watcher")
It works for me, I hope it will help you.
Best regards
The solution from Bruno probably works but the "I created a Bean returning a string" part is a bit confusing.
Here is how I do it :
Have the "index.name" key valued in an application.properties file loaded by "<context:property-placeholder location="classpath:application.properties" />"
Create a bean named ConfigBean annotated with #Named or #Component
#Named
public class ConfigBean {
#Value("${index.name}")
private String indexName;
public String getIndexName() {
return indexName;
}
public void setIndexName(String indexName) {
this.indexName = indexName;
}
}
Inject the value of configBean.getIndexName() into the "#Document" annotation using Spring EL : #Document(indexName = "#{ configBean.indexName }", type = "myType")
P.S. : You may achieve the same result directly using the implicit bean "systemProperties" (something like #{ systemProperties['index.name'] }) but it didn't work for me and it's pretty hard to debug since u can't resolve systemProperties in a programmatic context (https://jira.spring.io/browse/SPR-6651)
The Bruno's solution works but there is no need to create a new Bean in this way. What I do is:
create a bean annotated with #org.springframework.stereotype.Service where the index name is loaded from the database:
#Service
public class ElasticsearchIndexConfigService {
private String elasticsearchIndexName;
// some code to update the elasticsearchIndexName variable
public String getIndexName() {
return elasticsearchIndexName;
}
}
call the getIndexName() method from the bean in the #Document annotation using the SpEL:
#Document(indexName = "#{#elasticsearchIndexConfigService.getIndexName()}", createIndex = false)
public class MyEntity {
}
The crucial part is to use # - #{elasticsearchIndexConfigService.getIndexName()} won't work. I lost some time to figure this out.

Asp.Net Web Api - attribute for not binding/formatting a parameter?

I have a method on an ApiController that looks like this:
public IEnumerable<Items> GetSlideSets() {
IServiceClass serviceClass = new ServiceClass();
//...
Yes, I am aware that this is not good design but I'm addressing this issue in a different iteration.
At a certain point in my application I need to call this functionality from within the project itself so I thought I could simply reuse the controller (and why not, I can pluck it out of my IoC container). The only problem is that in this case, I need to inject my own implementation of IServiceClass, easy enough:
public IEnumerable<Items> GetSlideSets(IServiceClass serviceClass = null) {
serviceClass = serviceClass ?? new ServiceClass();
//...
Except now I am getting errors when calling this via a regular Api call Optionalparameter 'serviceClass' is not supported by FormatterParameterBinding.
I know that there are various attributes that control bindings. Is there one that I can put on the parameter to say it shouldn't bind.
Like others have mentioned, it's probably a better idea to inject the dependency in the constructor.
But if you really must avoid binding an action parameter, there isn't a built-in attribute but you can create one pretty easily. Here's what it could look like:
public class DontBindAttribute : ParameterBindingAttribute
{
public override HttpParameterBinding GetBinding(HttpParameterDescriptor parameter)
{
return new DontBindParameterBinding(parameter);
}
private class DontBindParameterBinding : HttpParameterBinding
{
public DontBindParameterBinding(HttpParameterDescriptor parameter) : base(parameter)
{
}
public override Task ExecuteBindingAsync(ModelMetadataProvider metadataProvider, HttpActionContext actionContext, CancellationToken cancellationToken)
{
actionContext.ActionArguments.Add(Descriptor.ParameterName, Descriptor.DefaultValue);
var completedTaskSource = new TaskCompletionSource<object>();
completedTaskSource.SetResult(null);
return completedTaskSource.Task;
}
}
}
You just need to apply the attribute to the parameter afterwards:
public IEnumerable<Items> GetSlideSets([DontBind] IServiceClass serviceClass = null)

Moq a static method in static class

public Product GetbyID(int id)
{
try
{
//mycode Product p=..........
}
catch (DataAccessException ex)
{
throw new BusinessException(ex.ErrorCode);
}
catch (Exception ex)
{
BusinessExceptionHandler.LogException(ex);
}
return p;
}
Given above is a code snippet that i need to write test cases.
here LogException(ex); is a static method in static class BusinessExceptionHandler
I have reference to Moq frame work 2.6.1014.1
How can I Moq the method BusinessExceptionHandler.LogException
I do prefer a mocking mechanism that don't need any change in method GetbyID
Moq doesn't allow the mocking of static methods so you will probably need to change the working of the static method. One option is to have the static method call an instance method of a dependency. So you'll create a "Logger" class with a Log method and add a static Logger field / property (BusinessExceptionHandler.Logger) to your static class. In the real-world scenario you can populate BusinessExceptionHandler.Logger with a standard Logger instance, using it as a Singleton. For testing, inject a Mock into the BusinessExceptionHandler.Logger and set up your expectations and verify against the mock.
Moq (and NMock, RhinoMock) will not help you here. You will have to create a wrapper class ( and virtual method ) around the LogException and use it in production code and test using that.
Or you can use a tool like TypeMock, Microsoft.Fakes etc ( http://stacktoheap.com/blog/2012/11/11/testing-extension-methods-with-microsoft-fakes/ ) if you absolutely cannot change your existing code.
Here is how I get around the problem. Say this is the class you want to unit-test:
public static class TaskFactory
{
public static T CreateTask<T>(long workRequestId, ProcessTriggerType workRequestType)
{
var task = some code to do the work;
return (T)task;
}
}
Create an interface and a wrapper class implementing it:
public interface ITaskFactoryFacade
{
T CreateTask<T>(long workRequestId, ProcessTriggerType workRequestType);
}
public class TaskFactoryFacade : ITaskFactoryFacade
{
public T CreateTask<T>(long workRequestId, ProcessTriggerType workRequestType)
{
return TaskFactory.CreateTask<T>(workRequestId, workRequestType);
}
}
Now mock out this class:
var taskFactoryFacadeMock = new Mock<ITaskFactoryFacade>();
taskFactoryFacadeMock.Setup(t => t.CreateTask<SomeTask>(It.IsAny<long>(), It.IsAny<SomeType>())).Returns(new SomeTask());
Happy Moqing.

Grails Databinding to a Map Property From URL. Custom Data Binder Never Gets Called

I am working on a simple cart application that needs the ability to pass quantities for specific products in the URL. I imagined doing this by having a map property on a command object to keep the data binding simple. However, when I hit my action with a parameter that I would expect to be put into the map, I get the following error:
ERROR errors.GrailsExceptionResolver - Exception occurred when processing request: [GET] /mygrailsapp/action
itemQty[123].id: 5
java.lang.NullPointerException
at grails.plugin.springcache.web.GrailsFragmentCachingFilter.doFilter(GrailsFragmentCachingFilter.groovy:66)
at net.sf.ehcache.constructs.web.filter.Filter.doFilter(Filter.java:86)
at com.infusionsoft.cam.security.filter.BlackListIpAddressFilter.doFilter(BlackListIpAddressFilter.java:78)
at java.lang.Thread.run(Thread.java:662)
The command object looks like this:
class MyCommand {
Map itemQty
static constraints = {
itemQty(nullable: true, blank: true)
}
}
The controller action looks like this:
def action = {MyCommand myCommand ->
// some code
}
An example url I am hitting is /mygrailsapp/action?itemQty[123]=5
I am following the example from the Grails Docs for binding data to a map, the only difference is I am trying to do so from the URL and not from post like in the docs. I am using Grails 1.3.7. I have tried encoding the brackets - [ and ] - but I get the same error.
Any help would be appreciated. Thanks!
Edit: I found out that this is occurring because spring expects the map to have the key in it before setting the value and will not insert new entries.
I am now trying to use a custom binder to populate the map but the property editor class methods are never called.
Here is my property editor (I was calling super just to verify that control was getting to the method):
class ItemQuantityPropertyEditor extends PropertyEditorSupport {
#Override
public void setValue(Object value) {
super.setValue(value)
}
#Override
void setAsText(String text) {
super.setAsText(text)
}
#Override
Object getValue() {
return super.getValue()
}
#Override
String getAsText() {
return super.getAsText()
}
}
Here is the registrar:
class ItemQuantityPropertyEditorRegistrar implements PropertyEditorRegistrar {
void registerCustomEditors(PropertyEditorRegistry propertyEditorRegistry) {
propertyEditorRegistry.registerCustomEditor(MyCommand, "itemQty", new ItemQuantityPropertyEditor())
}
}
Here is my entry in resources.groovy:
beans = {
itemQuantityPropertyEditorRegistrar(ItemQuantityPropertyEditorRegistrar)
}
Try initialising the Map with a commons collections lazy map:
import org.apache.commons.collections.MapUtils
import org.apache.commons.collections.FactoryUtils
class MyCommand {
Map itemQty = MapUtils.lazyMap([:], FactoryUtils.constantFactory(''))
static constraints = {
itemQty(nullable: true, blank: true)
}
}
You should not need the custom binding PropertyEditor stuff...

Mocking a base class method call with Moq

I am modifiying a class method which formats some input paramater dates which are subsequently used as params in a method call into the base class (which lives in another assembly).
I want to verify that the dates i pass in to my method are in the correct format when they are passed to the base class method so i would like to Moq the base class method call. Is this possible with Moq?
As of 2013 with latest Moq you can. Here is an example
public class ViewModelBase
{
public virtual bool IsValid(DateTime date)
{
//some complex shared stuff here
}
}
public class MyViewModel : ViewModelBase
{
public void Save(DateTime date)
{
if (IsValid(date))
{
//do something here
}
}
}
public void MyTest()
{
//arrange
var mockMyViewModel = new Mock<MyViewModel>(){CallBase = true};
mockMyViewModel.Setup(x => x.IsValid(It.IsAny<DateTime>())).Returns(true);
//act
mockMyViewModel.Object.Save();
//assert
//do your assertions here
}
If I understand your question correctly, you have a class A defined in some other assembly, and then an class B implemented more or less like this:
public class B : A
{
public override MyMethod(object input)
{
// Do something
base.MyMethod(input);
}
}
And now you want to verify that base.MyMethod is called?
I don't see how you can do this with a dynamic mock library. All dynamic mock libraries (with the exception of TypeMock) work by dynamically emitting classes that derive from the type in question.
In your case, you can't very well ask Moq to derive from A, since you want to test B.
This means that you must ask Moq to give you a Mock<B>. However, this means that the emitted type derives from B, and while it can override MyMethod (which is still virtual) and call its base (B.MyMethod), it has no way of getting to the original class and verify that B calls base.MyMethod.
Imagine that you have to write a class (C) that derives from B. While you can override MyMethod, there's no way you can verify that B calls A:
public class C : B
{
public override MyMethod(object input)
{
// How to verify that base calls its base?
// base in this context means B, not A
}
}
Again with the possible exception of TypeMock, dynamic mock libraries cannot do anything that you cannot do manually.
However, I would assume that calling the base method you are trying to verify has some observable side effect, so if possible, can you use state-based testing instead of behaviour-based testing to verify the outcome of calling the method?
In any case, state-based testing ought to be your default approach in most cases.
Agree with Mark, it's not possible using Moq.
Depending on your situation you may consider swithcing from inheritance to composition. Then you'll be able to mock the dependency and verify your method. Of course in some cases it just might not worth it.
wrap the base class method in a method and setup that method
e.g.
public class B : A
{
public virtual BaseMyMethod(object input)
{
// Do something
base.MyMethod(input);
}
public override MyMethod(object input)
{
// Do something
BaseMyMethod(input);
}
}
and now Setup the BaseMyMethod
It is quite possible mocking base class. But you will have to modify target class.
For ex. DerivedClass extends BaseClass.
BaseClass has methods MethodA(), MethodB(), MethodC()...
The DerivedClass has this method:
void MyMethod() {
this.MethodA();
this.MethodB();
this.MethodC();
}
You want to mock base class in order to validate that all MethodA(), MethodB(), MethodC() are being called inside MyMethod().
You have to create a field in the DerivedClass:
class DerivedClass {
private BaseClass self = this;
...
}
And also You have to modify the MyMethod():
void MyMethod() {
self.MethodA();
self.MethodB();
self.MethodC();
}
Also add a method, which can inject the this.self field with Mock object
public void setMock(BaseClass mock) {
this.self = mock;
}
Now you can mock:
DerivedClass target = new DerivedClass ();
BaseClass mock = new Mock(typeof(BaseClass));
target.setMock(mock);
target.MyMethod();
mock.verify(MethodA);
mock.verify(MethodB);
mock.verify(MethodC);
Using this technic, you can also mock nested method calls.
I found this solution - ugly but it could work.
var real = new SubCoreClass();
var mock = new Mock<SubCoreClass>();
mock.CallBase = true;
var obj = mock.Object;
mock
.Setup(c => c.Execute())
.Callback(() =>
{
obj.CallBaseMember(typeof(Action), real, "Execute");
Console.WriteLine(obj.GetHashCode());
}
);
public static Delegate CreateBaseCallDelegate(object injectedInstance, Type templateDelegate, object instanceOfBase, string methodName)
{
var deleg = Delegate.CreateDelegate(templateDelegate, instanceOfBase, methodName);
deleg.GetType().BaseType.BaseType.GetField("_target", BindingFlags.Instance | BindingFlags.NonPublic).SetValue(deleg, injectedInstance);
return deleg;
}
public static object CallBaseMember(this object injectedInstance, Type templateDelegate, object instanceOfBase, string methodName, params object[] arguments)
{
return CreateBaseCallDelegate(injectedInstance, templateDelegate, instanceOfBase, methodName).DynamicInvoke(arguments);
}

Resources