Can anyone explain why event type is an arbitrary string in seam? - events

I noticed that the event type is just an arbitrary string in seam which will be used in component.xml or annotations. Sometimes it is error-prone if I missspell them, for example "org.jboss.seam.security.notLogedIn", actually it should be "org.jboss.seam.security.notLoggedIn". Is there any alternative way to handle event types?

Since most of the event keys (types) are declared as public static final (as the one you reference), you can reference them without having troubles of misspelling.
#Observer(Identity.EVENT_NOT_LOGGED_IN)
public void handleNotLoggedIn() {
}
Unfortunately, you cannot use EL in event type declaration in component.xml. I recently tried that.
<event type="#{...}">
<!-- does not work -->
</event>
There is, IMHO, no other way than copy-and-paste the event keys into the component.xml to prevent misspelling.

Related

Forcing validation annotation to provide a message

I am using hibernate validator to do POJO validation, and also i have created some custom ones. Here is an example:
//lombok annotations
public class Address {
#NotNull // standard
#State //Custom created
String country;
}
We have a requirement to represents all the validations errors with specific codes rather than messages. In order to achieve this we have decided to specify codes in every annotation that we use. The above example now looks like this:
//lombok annotations
public class Address {
#NotNull(message="ERR_001")
#State(message="ERR_002")
String country;
}
But we have a problem with this approach. We could not enforce to provide a message(error code in our case) all the time in an annotation. For custom annotation, it is still ok as we do not provide a default message, but for the standard ones there is chance to miss it and a string message will silently generated if we accidentally miss to provide a custom message.
Is there a way to enforce to provide message all the time in the annotation. It will probably help to have some consistency.
To my knowledge no, there is no way to do that. Maybe your best option is to create your own annotation and make the attribute mandatory.
Sevntu-Checkstyle provides additional checks to Checkstyle, including a check that an annotation is used with all required parameters.
<module name="RequiredParameterForAnnotation">
<property name="annotationName" value="NotNull"/>
<property name="requiredParameters" value="message"/>
</module>
I could not find a good way to handle it. But for now i have implemented a test which give us some control over it. Its not the best solution but solves the issue for now.
I am using classgraph to read all the annotations on POJO classes inside a package and filtering it on javax validations and if the default messages appears to be from javax.validation, then i am adding to a list.
Later on a unit test, i am checking if this list is empty or not.
private List<String> getAnnotationProperties(String appliedOn, AnnotationInfoList annotationInfos) {
return annotationInfos.stream()
.filter(annotationInfo -> annotationInfo.getName().contains("javax.validation.constraints"))
.filter(annotationInfo -> ((String) annotationInfo.getParameterValues().getValue("message")).contains("javax.validation.constraints"))
.map(annotationInfo -> annotationInfo.getName())
.collect(Collectors.toList());
}

Is there any way to intercept all Linq to SQL queries?

I've built some code that can rebuild expression trees so I can avoid triggering the no supported translation to SQL exception and it works fine as long as I call my function to replace the iqueryable. The problem is that I'd like it to automatically be applied to all queries in my project without having to worry about calling this function on each one separately. Is there any way that I can intercept everything?
I've tried using Reflection.Emit to create a wrapping provider and using reflection to replace it on the data context and it turns out that even with Reflection.Emit I can't implement the internal IProvider interface.
I've also tried replacing the provider with a RealProxy based class and that works for non-compiled queries, but the CompiledQuery.Execute method is throwing an exception because it won't cast to the SqlProvider class. I tried replacing the response to the Compile method on the provider with another proxy so I could intercept the Execute call, but that failed a check on the return type being correct.
I'm open to any other ideas or ways of using what I've already tried?
It's hard to tell whether this is an applicable solution without seeing your code, but if you have a DI-friendly app architecture you can implement an interceptor and have your favorite IoC container emit the appropriate type for you, at run-time.
Esoteric? A little. Consider an interface like this:
public interface ISomeService
{
IEnumerable<SomeEntity> GetSomeEntities();
// ...
}
This interface might be implemented like this:
public class SomeService : ISomeService
{
private readonly DbContext _context // this is a dependency!
private readonly IQueryTweaker _tweaker; // this is a dependency!
public SomeService(DbContext context, IQueryTweaker tweaker) // this is constructor injection!
{
_context = context;
_tweaker = tweaker;
}
public IEnumerable<SomeEntity> GetSomeEntities()
{
return _tweaker.TweakTheQuery(_context.SomeEntities).ToList();
}
}
Every time you implement a method of the ISomeService interface, there's always a call to _tweaker.TweakTheQuery() that wraps the IQueryable, and that not only gets boring, it also feels like something is missing a feature - the same feeling you'd get by wrapping every one of these calls inside a try/catch block, or if you're familiar with MVVM in WPF, by raising this annoying PropertyChanged event for every single property setter in your ViewModel.
With DI Interception, you factor this requirement out of your "normal" code and into an "interceptor": you basically tell the IoC container that instead of binding ISomeService directly to the SomeService implementation, you're going to be decorating it with an interceptor, and emit another type, perhaps SomeInterceptedService (the name is irrelevant, the actual type only exists at run-time) which "injects" the desired behavior into the desired methods. Simple? Not exactly.
If you haven't designed your code with DI in mind (are your dependencies "injected" into your classes' constructor?), it could mean a major refactoring.
The first step breaks your code: remove the IQueryTweaker dependency and all the TweakTheQuery calls from all ISomeService implementations, to make them look like this - notice the virtualness of the method to be intercepted:
public class SomeService : ISomeService
{
private readonly DbContext _context
public SomeService(DbContext context)
{
_context = context;
}
public virtual IEnumerable<SomeEntity> GetSomeEntities()
{
return _context.SomeEntities.ToList();
}
}
The next step is to configure the IoC container so that it knows to inject the SomeService implementation whenever a type's constructor requires an ISomeService:
_kernel.Bind<ISomeService>().To<SomeService>();
At that point you're ready to configure the interception - if using Ninject this could help.
But before jumping into that rabbit's hole you should read this article which shows how decorator and interceptor are related.
The key point is, you're not intercepting anything that's internal to LINQ to SQL or the .NET framework itself - you're intercepting your own method calls, wrapping them with your own code, and with a little bit of help from any decent IoC container, you'll be intercepting the calls to methods that call upon Linq to SQL, rather than the direct calls to Linq to SQL itself. Essentially the IQueryTweaker dependency becomes a dependency of your interceptor class, and you'll only code its usage once.
An interesting thing about DI interception, is that interceptors can be combined, so you can have a ExecutionTimerServiceInterceptor on top of a AuditServiceInterceptor, on top of a CircuitBreakerServiceInterceptor... and the best part is that you can configure your IoC container so that you can completely forget it exists and, as you add more service classes to the application, all you need to do is follow a naming convention you've defined and voilĂ , you've just written a service that not only accomplishes all the strictly data-related tasks you've just coded, but also a service that will disable itself for 3 minutes if the database server is down, and will remain disabled until it's back up; that service also logs all inserts, updates and deletes, and stores its execution time in a database for performance analysis. The term automagical seems appropriate.
This technique - interception - can be used to address cross-cutting concerns; another way to address those is through AOP, although some articles (and Mark Seeman's excellent Dependency Injection in .NET) clearly demonstrate how AOP frameworks are a less ideal solution over DI interception.

Update field annotated with #Value in runtime

Let's imagine we have such a component in Spring:
#Component
public class MyComponent {
#Value("${someProperty}")
private String text;
}
If we define the property placeholder:
<context:property-placeholder location="classpath:myProps.properties"/>
And myPropos.properties contains the value for someProperty the value will be injected to the text field when the context is initialized. That's quite simple and easy.
But let's say that I have a service that enables user to change the value of the someProperty:
public void changeProp(String name, String newValue);
Is there a chance I can re-inject the newValue to text field. I mean it should be quite straight forward.. Basically it's nothing different than the after-initialization injection. I can not imagine that Spring does not have support for this? Can I fire some event or something?
I could do this on my own basically, but I wander is it maybe something there already? If not does anyone know what Spring class is in fact handling the injections at the first place? I could probably reuse the code there do perform this on my own if a solution does not exists.
I expect spring does not have a support for this, because the normal injection is done while creating the bean, but not will it is put in service.
Anyway: in this blog entry "Reloadable Application Properties with Spring 3.1, Java 7 and Google Guava", you can find the idea for an solution.
The key idea is to use a post processor to build a list of all fields with property fields. And if the properties are changed on can use this list to update the fields.

Struts 2 convert error

I created an action in struts 2
class MyAction extends ActionSupport {
private List<User> users;
//getters and setters users
public String execute(){
users=//code to get users;
return SUCCESS;
}
}
I mapped this action class with url /MyAction and the success result is a jsp which displays the users when i open the url:
http: //localhost:8080/MyAction.action
When I open the page as:
http: //localhost:8080/MyAction.action?xyz=123
I do not get any error. But when I open the page as:
http: //localhost:8080/MyAction.action?users=123
Struts tries to call setUsers() method and fails to convert 123 to a list of Users. Hence I get an Conversion error.
Since the action is not expecting any parameter it should behave in same way to all extra parameters provided. It should not just ignore few and show error for others.
The solution that I was able to find for this problem is to make all the setter methods private except for the setters for expected parameters.
Does anyone has a better solution?
You can use ParameterNameAware.
The above link should make the usage clear.
Although as anu was suggesting, your action is generally a public interface. Struts2 exposes setters as a convenience, and a great convince it is. You should only have setters for input. The action then does all of its work at another layer (Business), which typically in turn uses another layer(or tier if you prefer), which accesses persistent data. You probably know this but by only putting what is appropriate in the action layer, life is made less complicated (your issue never comes up).
Anu's right. I think what you are trying to fix is not a problem, it is the framework's functionality itself.
Thanks for your replies. I understand that this is struts functionality, but what I'm pointing out is that if struts is ignoring other parameters (for which there is no setter) it should ignore all the parameters that the action does not require. But yes, there should be some way for specifying the list of acceptable parameters.
As Quaternion pointed out ParameterNameAware is a solution but this works when there is only one action method in the action class or all the action methods must accept the same list of parameters.
I have found another way of specifying the list of acceptable parameters for each action using the params interceptor.
<action name="xxx" class="yyy" method="action1">
<intercecptor-ref name="defaultStack">
<param name="params.excludeParams">regex</param>
</intercecptor-ref>
<!-- other code -->
</action>
in place of regex you specify the regular expression for the excluding the parameters except for the ones that are not excepted by your expression.

MarshallingView in Spring to adjust output?

I have some POJOs which are the basis for this RESTful API I am working on. However, some of the responses I need to include some other information to make the API more complete. I really don't want to put these extra information in the POJO, but include it at the web service layer as if it were.
It deals with "People" who have "Appointments". Each appointment only has one person.
So, I have a RESTful call like /Patients/1 and it basically grabs the POJO for the Person and I am currently using XStream to serialize it and send it on its way. This works great, but I would like to do something like this:
<Person>
<firstName>James</firstName>
... other fields ...
<nextAppointment href="/Appointment/12345>2010-02-19</nextAppointment>
<prevAppointment href="/Appointment/12346>2010-01-01</prevAppointemnt>
</Person>
Where next and prev appointment are not actually included in the Person POJO. I am looking for a good "spring way" to accomplish this. The client could do something like this /Patients/1/PreviousAppointment and /Patients/1/NextAppointment, but I am looking to cut the amount of calls (maybe pre-optimization?) and give them a way to get more information if they need it by using he href.
It is very elegant using the XStreamMarshaller since all I do it hand the view the POJO or list of POJO and it handles it. But I need to doctors those up a bit before they are sent out.
Thanks!
This is the problem with handing your business objects directly to the marshaller - you have very little flexibility in how they turn that object into the response. There is something to be said for pre-transforming the objects yourself, you get more control that way.
So if you have a specific output structure that you want, then with XStream you need to build a class structure that looks like it. You then transform your business objects into that class structure, and pass that to XStream instead.
It may seem less elegant, but your system will be much less prone to being broken by small changes in your business object model, which you your current XStream-based system will be.
Solution to your problem : CREATE A CUSTOMIZEDCONVERTER...
public class CustomizedConverter implements Converter {
#Override
public void marshal(Object source, HierarchicalStreamWriter writer,MarshallingContext context) { ....}
#Override
public Object unmarshal(HierarchicalStreamReader reader,UnmarshallingContext context) {..}
#Override
public boolean canConvert(Class clazz) {..}
}
To know what to use the converter with the Marshaller refer this.
So basically the CONVERTER works on the POJO and ensures we get the XML response as given in the contract.

Resources