Where do I put my methods with MVC? - java

I have a folder /controllers with controllers and another /models where i put my models with get/sets.
Now, where is the usual place to put the methods to get data from the db,etc...?
In my last project I put it under the get/sets and it was a bit confusing.
Any helP?

For database you can have a DTO folder, but you could also have a intermediate Service folder where you put all the business rules. I like having a separate DTO object to make mocking easier too.

For strictly data access, spring boot handles most of CRUD. You just need to config spring to know you have a data access layer. #JpaRepository does this. This is probably where you should start looking. For custom data calls you're going to have to write custom methods inside the classes that make up the data access laters.
Your question is extremely broad but I hope I've given you enough to look at.
https://spring.io/guides/gs/accessing-data-jpa/

Related

How to implement an xml saveable/loadable class?

I would like to create a class, which would be loadable and saveable to an XML file. I want to use one class which is doing the loading task and I want to integrate it with the actual class that I want to save and load, everything seems to be doable up to the point where JAVA doesn't allow the class instance to be change from within the class, i.e. there is no:
this = JAXBLoader.load();
So currently that's the problem I'm facing.
And I want to be able to control the loading and saving it via the public methods from the class itself, so that from the outside I don't need any factories or managers to load it. Currently the only solution I've seen to this was if I extended the class that I want to save as an xml and then delegate all the methods to the intance of the actual class and then when loading a new instance from the file, the instance would get replaced. But it is a bit of overhead to have to delegate all of the methods, especially pain in the ass if you need to add new methods to the class and have multiple implementations...
So are there any good practices or patterns on achieving something similar or solving the problem I demonstrated above? Actually I'm open, if somebody can overall share what are the best ways to do class saving and loading the easiest ways I would really glad about it.
I'm not quite sure why do you want to avoid external factories and managers. For me it seems quite natural to extract serialization and not handle it in the model classes themselves. But okay.
What I understood is that your core problem is to load data into this instance. Here's a simple way to achieve this with JAXB.
I'm the author of JAXB2 Basics, a plugin package for JAXB/XJC. It contains the copyable plugin which generates a few copyTo methods in the schema-derived classes.
This will give you methods like copyTo(Object target). With this you can first unmarshal data from XML into some temporary instance and then copyTo(this). Something like:
MyType temporaryInstance = unmarshaller.unmarshal(source, MyType.class).getValue();
temporaryInstance.copyTo(this);
You can add this method to your schema-derived code via code injection or by subclassing.

Rails application, but all data layer is using a json/xml based web service

I have a web service layer that is written in Java/Jersey, and it serves JSON.
For the front-end of the application, I want to use Rails.
How should I go about building my models?
Should I do something like this?
response = api_client.get_user(123)
User user = User.new(response)
What is the best approach to mapping the JSON to the Ruby object?
What options do I have? Since this is a critical part, I want to know my options, because performance is a factor. This, along with mapping JSON to a Ruby object and going from Ruby object => JSON, is a common occurance in the application.
Would I still be able to make use of validations? Or wouldn't it make sense since I would have validation duplicated on the front-end and the service layer?
Models in Rails do not have to do database operation, they are just normal classes. Normally they are imbued with ActiveRecord magic when you subclass them from ActiveRecord::Base.
You can use a gem such as Virtus that will give you models with attributes. And for validations you can go with Vanguard. If you want something close to ActiveRecord but without the database and are running Rails 3+ you can also include ActiveModel into your model to get attributes and validations as well as have them working in forms. See Yehuda Katz's post for details on that.
In your case it will depend on the data you will consume. If all the datasources have the same basic format for example you could create your own base class to keep all the logic that you want to share across the individual classes (inheritance).
If you have a few different types of data coming in you could create modules to encapsulate behavior for the different types and include the models you need in the appropriate classes (composition).
Generally though you probably want to end up with one class per resource in the remote API that maps 1-to-1 with whatever domain logic you have. You can do this in many different ways, but following the method naming used by ActiveRecord might be a good idea, both since you learn ActiveRecord while building your class structure and it will help other Rails developers later if your API looks and works like ActiveRecords.
Think about it in terms of what you want to be able to do to an object (this is where TDD comes in). You want to be able to fetch a collection Model.all, a specific element Model.find(identifier), push a changed element to the remote service updated_model.save and so on.
What the actual logic on the inside of these methods will have to be will depend on the remote service. But you will probably want each model class to hold a url to it's resource endpoint and you will defiantly want to keep the logic in your models. So instead of:
response = api_client.get_user(123)
User user = User.new(response)
you will do
class User
...
def find id
#api_client.get_user(id)
end
...
end
User.find(123)
or more probably
class ApiClient
...
protected
def self.uri resource_uri
#uri = resource_uri
end
def get id
# basically whatever code you envisioned for api_client.get_user
end
...
end
class User < ApiClient
uri 'http://path.to.remote/resource.json'
...
def find id
get(id)
end
...
end
User.find(123)
Basic principles: Collect all the shared logic in a class (ApiClient). Subclass that on a per resource basis (User). Keep all the logic in your models, no other part of your system should have to know if it's a DB backed app or if you are using an external REST API. Best of all is if you can keep the integration logic completely in the base class. That way you have only one place to update if the external datasource changes.
As for going the other way, Rails have several good methods to convert objects to JSON. From the to_json method to using a gem such as RABL to have actual views for your JSON objects.
You can get validations by using part of the ActiveRecord modules. As of Rails 4 this is a module called ActiveModel, but you can do it in Rails 3 and there are several tutorials for it online, not least of all a RailsCast.
Performance will not be a problem except what you can incur when calling a remote service, if the network is slow you will be to. Some of that could probably be helped with caching (see another answer by me for details) but that is also dependent on the data you are using.
Hope that put you on the right track. And if you want a more thorough grounding in how to design these kind of structures you should pick up a book on the subject, for example Practical Object-Oriented Design in Ruby: An Agile Primer by Sandi Metz.

Java annoations

I used a lot annotations in java but I never wrote one. I read though several guides and I am really confused.
They are using annotations like meta information eg names, age etc. That is really confusing because I want to do something different
http://www.developer.com/java/other/article.php/3556176/An-Introduction-to-Java-Annotations.htm
I want to control the function calls.
for example
#Permission(user)
public static void account(){
...
}
So my functions only gets called if the user has the permission, otherwise the user should be redirected to the login page.
I could not find any information, maybe I am using the wrong keyword?
I hope you can clear things up,
Thanks.
You can do that, but with a lot of extra code. Intercepting method calls is part of AOP (aspect oriented programming). You need to make proxies of you target objects, and in the invocation handler parse the annotation.
Luckily, you don't have to do that - since you have a webapp, just use spring/spring-mvc/spring-security. Spring gives you an AOP framework that you can use to define aspects handling your permission logic
Not sure how you can do this by yourself but if you are using Spring they have something that may help
http://static.springsource.org/spring-security/site/docs/3.0.7.RELEASE/reference/el-access.html
I use it my current project and it works well
Something like that should really be done in the function itself (or in some other part of the program). Note that annotations provide data about a program that is not part of the program itself (see this reference).
I think what you are after is an AOP advisor which is run before your method. See here: http://java-questions.com/spring_aop.html
As an alternative to Spring, you could use AspectJ: http://www.andrewewhite.net/wordpress/2010/03/17/aspectj-annotation-tutorial/

How best to implement save() and setDirty() for my Java beans model?

I have a Java model which is effectively a tree of Java beans. Different areas of my application can change different beans of the model. When finished, I want to save the model, which should be able to work out which beans have actually changed, and call there
I know I can implement save(), isDirty() and setDirty() methods in all the beans, and have the setter check whether there is a change and call setDirty(). But ideally I don't want to have to programmicatically do this for each setter. I want to just be able to add new properties to the beans with no additional coding.
I'm also aware of PropertyChangeListeners, but again I would have to programmatically fire a change in each setter.
Can anyone recommend a pattern/aspect/annotation that I might be able to use to make my life easier? I don't think what I'm trying to achieve is everything new or groundbreaking so hoping there's something out there I can use.
Note that I'm coding in basic Java, so no fancy frameworks to fall back on (expect Spring for bean management - outside of my model).
Thanks in advance.

Creating objects from request

I'm working on some user related tasks for a website. For cases when the person is registering or editing a user, they fill out a form and the request is handled in a servlet. At the moment, the servlet is taking all the request parameters and building a User object from them, like this:
User toRegister = new User(request.getParameter("name"),
request.getParameter("lastName"));
There's more parameters but you get the point.
So this sort of code is being reused in a bunch of different servlets (registering, admin adding user, user updating self, admin updating others etc) and it's kinda ugly, so I wanted to clean it up. The two alternatives I could think of were a constructor that takes the request object or a static method in the User class to create and return a new User based on the request.
It's not much of a question since I know they would both work but I couldn't find any sort of best practices for this situation. Should I keep to handling the requests individually in the servlets in case the forms change or should I implement one of the above methods?
DON'T add a c'tor that takes a Request as an argument. You only couple your User class to the Servlet API this way.
Instead use a Web Framework as #skaffman suggests. There are many of these, and it will make your life easier.
EDIT: If you refuse to learn a new framework you can at least use BeanUtils of some similar framework to do the data binding only. I do recommend the Web Framework option though.
Instead of coding all the business logic in the servlet, why dont you use basic MVC framework. Using a framework will make your coding and testing a lot easier.

Categories

Resources