Access Properties from utility classes used by Action - struts2

I just want to know if there's a way to access the properties from a utility class used by an Action class. To access the properties from an Action class we extend the ActionSupport and use the getText("property.key.name") method.
So, my question is -should every other class extend the ActionSupport to access properties, even though its not an Action class? or is there any other way?
Thanks

I wouldn't extend ActionSupport unless you're actually defining an action.
The S2/XW2 ActionSupport class uses com.opensymphony.xwork2.DefaultTextProvider; you might be able to use it in your own classes. I'm a little wary of this since I'm not convinced non-action classes should be accessing the web-app's resources, but I haven't given it much thought, so it could be valid. I also haven't tried to do it.

ActionSuport is kind of helper class being developed by S2 developers to supplement the Development as it provides many features OOTB.
getText() is one of the use-case where S2 provides a way to read the property files.This method is specific to S2 as it know how to transverse the hierarchy to read the property files and in what order.
There are many ways to read the property files in a application and few of them are
ResourceBundle
if you are using Spring, it has a very handy mechanism to read property files
- how-to-read-properties-file-in-spring
Apache Common also provides a way to read the file
Apache-Common
In short to read properties file there are many ways, S2 getText() is a way developed by the S2 to read the property file with respect to your actions.

//I wanna make you understand how struts doing it.
public class ActionSupport implements Action, Validateable, ValidationAware, TextProvider, LocaleProvider, Serializable {
//Action support implementation.
//Here TextProvider takes care about resource bundle thing.
}

Related

Force .NET MVC Controller to Call Service Methods Rather Than Directly Calling Base Class

I have a standard class stack in a .NET MVC5 using Entity Framework 6:
MyController()
MyService() : ServiceBase()
ServiceBase() : IServiceBase
All methods/classes are public at the moment.
ServiceBase() contains generic(T) methods and is inherited by all services.
The problem is that MyController() can call the generic methods in ServiceBase() directly. Important properties need to be set on the Entity before being passed to ServiceBase().
Is there any way to hide the ServiceBase() methods from MyController() forcing MyController() to go through MyService() rather than calling ServiceBase() methods directly?
Thanks all.
Why are you starting from an interface? I think you are getting your OO a little confused. I think the problem you are having is that you start at an interface, which doesn't have method visiblity controls. So you try to hide it in ServiceBase, but MyService has to know about the interface so that is why you cannot change visibility midway through.
I would suggest you rethink your OO strategy a bit.
However, if you really want to keep the interface and hide the methods in the base class, you can blank them out in MyService and inside of another method of MyService you can directly call the base class. I have created an example here.
But like I said, I would discourage this behavior and come up with a better OO strategy. If you can get around to posting your code, perhaps in a separate question, then I and the rest of the community can help you out with that. FYI, this might go better in the codereview stackexchange site.
The answer is to make the base classes that I don't want the controllers to access directly abstract while continuing to contain method implementation.
Make the ServiceBase classes abstract with a protected constructor. Then only classes that derive from them can access their methods directly, forcing the controller to call the controllers service which then calls the base service classes.
I wrote all this up in a blog post here

Advantages of WebServiceGatewaySupport vs WebServiceTemplate

I have to implement a webservice client using Spring WS.
I've read the documentation at http://static.springsource.org/spring-ws/site/reference/html/client.html but it's not clear to me what are the advantages of extending WebServiceGatewaySupport versus directly using WebServiceTemplate in my service class.
As far as I can tell from the source, the WebServiceGatewaySupport only has a couple of wrapper methods for the WebServiceTemplate and some initialization support.
So why should I extend WebServiceGatewaySupport instead of directly using a WebServiceTemplate ?
Thank you!
I think this sums it all up (found in the client reference you linked):
Alternatively, consider deriving from Spring-WS's
WebServiceGatewaySupport convenience base class, which exposes
convenient bean properties to enable easy configuration. (You do not
have to extend this base class... it is provided as a convenience
class only.)
So, if the WebserviceTemplate offers all you need, that'll probably suffice. If you need anything extra you can use the WebServiceGatewaySupport as an example on how to wrap your own convenience methods around the WebserviceTemplate.
In my client software, I just configure the WebserviceTemplate in my #Configuration class like this:
#Bean
public WebServiceTemplate webServiceTemplate() {
WebServiceTemplate template = new WebServiceTemplate();
template.setMessageFactory(messageFactory());
template.setDefaultUri(defaultUri);
template.setMarshaller(marshaller());
template.setUnmarshaller(marshaller());
template.setInterceptors(new ClientInterceptor[] {interceptor()});
return template;
}
(All the method calls are references to other methods in the configuration which aren't that relevant in this example).
I can use that bean everywhere in my code to send messages.

ServiceManager Advice

I'm simply looking for advice on the best way I should handle this situation.
Right now I've got several files in a folder called Service. The files contact several functions which do random things of course. Each of these files needs access to the SM Adapter.
My question is, should I implement the ServiceManagerAwareInterface in each of these files OR should I just make a new class which implements the ServiceManagerAwareInterface and just extend my classes on the new class which implements this service?
Both ways work as they should, just not sure which way would be more proper.
If you think that your system will always rely on ZF2, both approaches are equivalent.
Now from an OO design perspective, personally I have a preference for the approach in which you extend your service then implement the ServiceManagerAwareInterface. I would even use an interface for the dependency over the ServiceLocator to protect even more my classes. Why?
Extending your classes does not cost you a lot, same for making your class depending on interfaces.
Let's take this example, Imagine you did not use this approach during a ZF1 project, during which you had probably resolved your dependencies with the Zend_Registry.
Now, let's assume you moved to a ZF2 implementation, how much time you think you'll spend refactoring your code from something like Zend_Registry::get($serviceX) to $this->getServiceManager()->get($serviceX) on your Service layer?
Now Assume you had made the choice of protecting your classes, first by creating your own Service locator interface, as simple as:
public interface MyOwnServiceLocatorInterface{
public function get($service);
}
Under ZF1 you had created an adapter class using the Zend_Registry:
public class MyZF1ServiceLocator implements MyOwnServiceLocatorInterface{
public function get($service){
Zend_Registry::get($service);
}
}
Your Service classes are not coupled to the Zend_Registry, which make the refactoring much more easier.
Now, You decide to move to ZF2 so you'll logically use the ServiceManger. You create then this new Adapter class:
public class MyZF2ServiceLocator implements
ServiceManagerAwareInterface,MyOwnServiceLocatorInterface
{
private $_sm;
public function get($service){
$this->_sm->get($service);
}
public function setServiceManager($serviceManager){
$this->_sm = $serviceManager;
}
}
Again, your Service classes are not coupled to the ZF2 ServiceManger.
Now, how would look like the configuration/registration of you Service layer on the ServiceManager. Well, you'll use your Module::getServiceConfig class for that:
//Module.php
public function getServiceConfig()
{
return array(
'factories'=>array(
'My\ServiceA'=>function($sm){
return new My\ServiceA($sm->get('My\Service\Name\Space\MyZF2ServiceLocator'));
}
//Some other config
)
}
As you can see, no refactoring is needed within your Service classes as we protected them by relying on interface and using adapters. As we used a closure factory, we don't even need to extend our Service classes and implement the ServiceLocatorAwareInterface.
Now, before concluding in my previous example i have to note that I did not treat the case in which my classes are constructed via factories, however, you can check one of my previous answers that address the factory topic but also the importance of loose coupling among an application layers.
you can add initializers to do that. It can reduce repetitive injection in getting the service that pass db adapter. OR, you can set abstract_factories, it will reduce repetitive SM registration. I just posted SM Cheatsheet here, Hope helpful :)
https://samsonasik.wordpress.com/2013/01/02/zend-framework-2-cheat-sheet-service-manager/

Struts2: Why to extend ActionSupport class?

I am a beginner to Struts2. Please tell me why to extend ActionSupport class? (When one doesn't have the requirement of validation or internationalization)
Are there any other benefits provided by extending ActionSupport class?
Convenience and access to basic, common functionality.
It has default implementations of common methods (e.g., execute(), input()), gives access to Action.SUCCESS and other result names, etc.
Note that the I18N functionality goes a bit beyond simple translation, but includes some formatting, allows non-programmers to provide labels/texts, and so on.
There's rarely (ever?) a good reason not to extend it. Even REST plugin actions, e.g., those that handle JSON endpoints, often use validation and I18N support.
IF you don't want to use out of the box features provided by the struts2 you can always avoid using ActionSupport class
This is basically a helper class which provides many out of the box features for you, but at same time Struts2 framework do not ask to use this class, all it want is an entry method for your action class with return type as String and which can throw a general Exception
beside validation or Internationalization this class also provides many other features like Action level Errors etc.
Follow the documentation for detail
ActionSupport

A pragmatic view on private vs public

I've always wondered on the topic of public, protected and private properties. My memory can easily recall times when I had to hack somebody's code, and having the hacked-upon class variables declared as private was always upsetting.
Also, there were (more) times I've written a class myself, and had never recognized any potential gain of privatizing the property. I should note here that using public vars is not in my habit: I adhere to the principles of OOP by utilizing getters and setters.
So, what's the whole point in these restrictions?
The use of private and public is called Encapsulation. It is the simple insight that a software package (class or module) needs an inside and an outside.
The outside (public) is your contract with the rest of the world. You should try to keep it simple, coherent, obvious, foolproof and, very important, stable.
If you are interested in good software design the rule simply is: make all data private, and make methods only public when they need to be.
The principle for hiding the data is that the sum of all fields in a class define the objects state. For a well written class, each object should be responsible for keeping a valid state. If part of the state is public, the class can never give such guarantees.
A small example, suppose we have:
class MyDate
{
public int y, m, d;
public void AdvanceDays(int n) { ... } // complicated month/year overflow
// other utility methods
};
You cannot prevent a user of the class to ignore AdvanceDays() and simply do:
date.d = date.d + 1; // next day
But if you make y, m, d private and test all your MyDate methods, you can guarantee that there will only be valid dates in the system.
The whole point is to use private and protected to prevent exposing internal details of your class, so that other classes only have access to the public "interfaces" provided by your class. This can be worthwhile if done properly.
I agree that private can be a real pain, especially if you are extending classes from a library. Awhile back I had to extend various classes from the Piccolo.NET framework and it was refreshing that they had declared everything I needed as protected instead of private, so I was able to extend everything I needed without having to copy their code and/or modify the library. An important take-away lesson from that is if you are writing code for a library or other "re-usable" component, that you really should think twice before declaring anything private.
The keyword private shouldn't be used to privatize a property that you want to expose, but to protect the internal code of your class. I found them very helpful because they help you to define the portions of your code that must be hidden from those that can be accessible to everyone.
One example that comes to my mind is when you need to do some sort of adjustment or checking before setting/getting the value of a private member. Therefore you'd create a public setter/getter with some logic (check if something is null or any other calculations) instead of accessing the private variable directly and always having to handle that logic in your code. It helps with code contracts and what is expected.
Another example is helper functions. You might break down some of your bigger logic into smaller functions, but that doesn't mean you want to everyone to see and use these helper functions, you only want them to access your main API functions.
In other words, you want to hide some of the internals in your code from the interface.
See some videos on APIs, such as this Google talk.
Having recently had the extreme luxury of being able to design and implement an object system from scratch, I took the policy of forcing all variables to be (equivalent to) protected. My goal was to encourage users to always treat the variables as part of the implementation and not the specification. OTOH, I also left in hooks to allow code to break this restriction as there remain reasons to not follow it (e.g., the object serialization engine cannot follow the rules).
Note that my classes did not need to enforce security; the language had other mechanisms for that.
In my opinion the most important reason for use private members is hiding implementation, so that it can changed in the future without changing descendants.
Some languages - Smalltalk, for instance - don't have visibility modifiers at all.
In Smalltalk's case, all instance variables are always private and all methods are always public. A developer indicates that a method's "private" - something that might change, or a helper method that doesn't make much sense on its own - by putting the method in the "private" protocol.
Users of a class can then see that they should think twice about sending a message marked private to that class, but still have the freedom to make use of the method.
(Note: "properties" in Smalltalk are simply getter and setter methods.)
I personally rarely make use of protected members. I usually favor composition, the decorator pattern or the strategy pattern. There are very few cases in which I trust a subclass(ing programmer) to handle protected variables correctly. Sometimes I have protected methods to explicitly offer an interface specifically for subclasses, but these cases are actually rare.
Most of the time I have an absract base class with only public pure virtuals (talking C++ now), and implementing classes implement these. Sometimes they add some special initialization methods or other specific features, but the rest is private.
First of all 'properties' could refer to different things in different languages. For example, in Java you would be meaning instance variables, whilst C# has a distinction between the two.
I'm going to assume you mean instance variables since you mention getters/setters.
The reason as others have mentioned is Encapsulation. And what does Encapsulation buy us?
Flexibility
When things have to change (and they usually do), we are much less likely to break the build by properly encapsulating properties.
For example we may decide to make a change like:
int getFoo()
{
return foo;
}
int getFoo()
{
return bar + baz;
}
If we had not encapsulated 'foo' to begin with, then we'd have much more code to change. (than this one line)
Another reason to encapsulate a property, is to provide a way of bullet-proofing our code:
void setFoo(int val)
{
if(foo < 0)
throw MyException(); // or silently ignore
foo = val;
}
This is also handy as we can set a breakpoint in the mutator, so that we can break whenever something tries to modify our data.
If our property was public, then we could not do any of this!

Resources