Coding architectural question - web-services

I'm after some guidance on how to approach coding a problem, I don't want to jump straight into coding without think about it as I need it to be as generic and customisable as possible,
The scenario is i have a web service that acts as a gateway to downstream services, with the aim of authenticating and authorising SOAP message destined for down stream services, basically allivating the downstream service from doing it themselves. Each SOAP message has a variety of different WS-Security mechanisms attached usually a WS-UsernameToken, WS-Timestamp, and a XML Signature of the message body.
My problem is i want to figure out a good extensible way of validating all these security mechanims, I'm not after how to do it just how to appraoch it.
I thought about having a controller class that is intialised and controls the validation flow i.e.
ISecurityController controller = SecurityControllerFacotry.getInstance();
boolean proceed = controller.Validate(soapMessage);
using it very much like a template design pattern which ditates the flow of logic i.e.
public Boolean Validate(Message soapMessage)
{
return ValidateAuthentication(soapMessage) && ValidateTimeStamp(soapMessage) && ValidateSignture(soapMessage);
}
Would this be the best apporach to the problem?
Also would it be best to put these validation methods each into a class of there own that which implemented a common interface? So that a class could be instantiated and retrieved from some sort of validation factory i.e.
IValidationMechanism val = ValidationFactory.getValidationType(ValidationFactory.UsernameToken);
boolean result = val.Validate(soapMessage);
This would give me an an easily extensible aspect.
Would this be an vaible solution or can anyone think of other ways of doing it?
I'm interset in design patterns and good oo principles so would like to go down a route utilising them if possible.
Thanks in advance
Jon
EDIT: The service is basically a gateway security service that relieves the burden of authentication and authorisation from services that sit behind it. The security service can be thought of as an implicitly invoke intermediary on the SOAP message path that validates the security mechanisms in the SOAP message and depending on the validation result forwards the message to the appropriate down stream service by interrogating the WS-addressing headers. Although the service is not really the question it is more on how to implement the validation procedure.

I think your intuition on this is good; go with the single interface approach. That is, hide your validation implementations behind a single validation interface; this allows you to extend your validation implementations later without modifying the calling code.
And yes, the idea of putting the validation into its own class is a good one; you might want to think about having a common base class, if you have any common validation items (for example, username might be a common validation element, even though each different validation scheme may encode it differently; one as an element, another as an attribute, etc.). I think validation classes is a more appropriate mapping for the level of complexity that you're talking about anyhow, as opposed to validation methods; I suspect that the type of validation you're doing requires groups of methods (i.e., classes).

I can think of another way to validate your SOAP message against different validations. You use a visitor Pattern.
For that You will have a simple wrapper around the SOAP message you get.
MySoapMessage{
SOAPMessage soapMessage;
List<String> validatonErrors;
void accept(Validator validator){
validator.isValid(this);
}
}
Your security Controller will contain the list of Validatiors which you will inject basically.
SecurityController{
List<IValidator> validators;
//Validate the message
void validate(MySOAPMessage soapMessage){
forEach(Validator validator: validators){
soapMessage.isValid(validator)
}
}
}
Your Validators will look something like this.
UserNameValidator implements IValidator{
public void validate(MySOAPMessage message){
// Validate and put error if any
}
}
You dont need and unnecessary factory here for the validators.. if you want to want to add/remove validators from the controller you just inject/un inject then from the list.

Spring has a generic validation package that handles this type of process nicely IMHO.
Theirs looks something like
public interface Validator {
public boolean supports(Class<?> clazz);
public void validate(Object o, Errors errors);
}
Granted, they're using an Errors param to return validation issues in, which might or might not suit your goal.

Related

Rest uniform interface for calculator app

I am designing the rest api's for a basic calculator.
I need to know which is the best practise for defining interfaces?
/calc-service/add
/calc-service/sub
/cal-service/mul
2nd method
/calc-service/?params
I need to know which is the best practise for defining interfaces?
REST doesn't care what spelling you use for your resource identifiers.
Most computation queries are safe, which is to say "read only", so you would normally plan to use GET semantics for the request, which in turn means that all of the client provided operands would appear in the target-uri
/calc-service/add/x=2/y=3
/calc-service/add?x=2&y=3
/calc-service?add&x=2&y=3
/calc-service/x=2/y=3/add
/calc-service/x=2/y=3?add
/calc-service?op=add&x=2&y=3
These are all fine.
Using application/x-www-form-urlencoded parameters in your query string has the advantage that HTML clients already follow standards for form processing that produce URI with that shape from the data provided by the user in the form.
But any pattern that is easily expressed as a URI Template will be fine for clients that have the appropriate level of template processing available.
It could make sense in some cases to use coarse grained representations (think DTO), with URI identifying specific sub elements
/calc-service/x=2/y=3#add
/calc-service/x=2/y=3#sub
/calc-service/x=2/y=3#mul

Design architecture to contact 3rd party Web Service

Actually the code is structured as in the first design. But I think it's not very readable..
The namespaces name are saying nothing of the responsability of each class
Is it really useful to split between DAO and BLO layer a so small architecture? There is almost no logic..
The logic / responsability of the BLO is not identifiable by the names of class / methods / namespace
What is UserType? The namespace is not grouping it with any other class..
Config class is a good name for me since it identifies a functionality. But It's the only class with a precise purpose specified by its name.
Get3rdPartyUrl and logging in (to that url) could all be put together in a same class, while InitializeConfigValue and ParseErrorMessage could be put into some other Help class.
Contacting a 3rdParty WS is reusable. Everything should inherit from just one interface also defining logging.
The WS which I contact will make a callback to my infrastructure. I could I recognize / trace the session between this two calls? From my infrastructure and back to my infrastructure?
I wait your comment and proposal!
EDIT
This is the result after the first refactoring. What do you think about?
I do not split beetwen DAO and BLO levels in small projects. I use QueryObject pattern and put all my queries into this objects. You can put simple logic (validation f.e.) into this queries.
The WS which I contact will make a callback to my infrastructure. I could I recognize / >trace the session between this two calls? From my infrastructure and back to my >infrastructure?
You can use WS-Addressing. WS-Addressing headers has fields wsa:MessageID and wsa:RelatesTo for message correlations (mean this as MessageId and CorrelationId) and wsa:ReplyTo/wsa:Address for callback server address.
For example Oracle SOA Suite has strong WS-Addressing support out-of-the-box.

Return record from a database table using Apache CXF

I am using Apache CXF (apache-cxf-2.5.0) to create Web Services using a bottom-up approach (Java first approach). I want to return some data/records (for example, username, email) from a database table. I can write a Java class which returns a simple response. But I am not able to find way to return a response such as data/records extracted from a database table. How to do that?
You don't mention how you are accessing the database, but the basic idea is that you ensure that the classes that you return have JAXB annotations (notably #XmlRootElement or #XmlType) on them, which allows CXF to convert the instances of those classes into XML document fragments. The classes which you annotate this way probably should not have lots of functionality in them; they should exist just to hold data. (I find anything else too confusing given the complex lifecycle they'll have.) Once the annotations are in place, just return the relevant objects and all the conversions will happen automatically.
I'm talking a simple class like this:
#XmlRootElement // <---- THIS LINE HERE!
public class UserInfo {
public String username;
public String email;
}
You can use this in conjunction with other annotations (e.g., for your ORM) as necessary. Of course, if you're talking straight JDBC to the DB to get the information out, you won't need to worry about that.
The one tricky bit is that the objects being returned will have a lifespan that goes beyond that of the database transaction you're using; you may need to detach (i.e., do some copying, though the ORM layer might provide assistance) the objects extracted from the DB for that to work. This won't be much of a concern in this case as the DB you're describing is very simple (one table, no inter-row relations) but could be an issue if you make things more complex.

Where do I put business logic when I'm using the repository pattern?

I am using the Repository Pattern for my application. I have a class User. User is identified by Email. The UserRepository contains a method CreateUser(User user). There is a business rule saying that users should have a unique Email.
I want to implement a transaction which first checks whether an email is in use and if not, the user is created. Where should I put this code which is responsible for checking the uniqueness of the Email?
This is definitely a business rule; it is business logic. I think it is not correct to put this check in my UserRepository implementation.
This sort of thing typically goes in either (1) a service or (2) directly into the schema as a database constraint (and frequently both).
Using a service, you don't access the Repository directly from client code; you call a service which does the useful operations for you.
For example, something like:
public class UserService : ... {
private Repository<User> _userRepository;
public void CreateUser(User u) {
// Verify that the user's email is unique.
if ( ... ) {
_userRepository.Create(u);
}
}
}
If you're building an application large enough to warrent a repository pattern then you'll want to put this validation as close to the data as possible, probably a database constraint such as a unique index/key. This prevents situations of bugs leaking into code later due to corrupt data.
Assuming you're using a database for storage, you should definitely add a unique constraint on the e-mail column in the database.
Check out this excellent article on Simple Talk:
Five Simple Database Design Errors You Should Avoid
See in Section 4:
Enforcing Integrity via applications
Proponents of application based
integrity usually argues that
constraints negatively impact data
access. They also assume selectively
applying rules based on the needs of
the application is the best route to
take. .....
The solution is simple.
Rely on nothing else to provide
completeness and correctness except
the database itself. By nothing, I
mean neither users nor applications
external to the database.**
So in your case - a unique constraint on your e-mail column should really be modelled in the database. That's the best place to put that piece of business logic, and will save you from a lot of grief in the long run.
Marc

What's a good design pattern for web method return values?

When coding web services, how do you structure your return values? How do you handle error conditions (expected ones and unexpected ones)? If you are returning something simple like an int, do you just return it, or embed it in a more complex object? Do all of the web methods within one service return an instance of a single class, or do you create a custom return value class for each method?
I like the Request/Response object pattern, where you encapsulate your arguments into a single [Operation]Request class, which has simple public properties on it.
Something like AddCustomerRequest, which would return AddCustomerResponse.
The response can include information on the success/failure of the operation, any messages that might be used by the UI, possibly the ID of the customer that was added, for example.
Another good pattern is to make these all derive from a simple IMessage interface, where your general end-point is something like Process(params IMessage[] messages)... this way you can pass in multiple operations in the same web request.
+1 for Ben's answer.
In addition, I suggest considering that the generic response allow for multiple error/warning items, to allow the reply to be as comprehensive and actionable as possible. (Would you want to use a compiler that stopped after the first error message, or one that told you as much as possible?)
If you're using SOAP web services then SOAP faults are the standard way to return error details, where the fault messages can return whatever additional detail you like.
Soap faults are a standard practice where the calling application is a Soap client. There are cases, such as a COM client using XMLHTTP, where the Soap is parsed as XML and Soap faults cannot be easily handled. Can't vote yet but another +1 for #Ben Scheirman.