Generating RESTful controllers without full scaffolding - json

I want the Roo-generated JSON controller stuff. I don't want the full HTML scaffolding stuff.
As far as I can see, I can only generate the former as an aspect on the latter. Is it possible to generate them separately? I have a whole set of view controllers I'm writing of my own. Is there an annotation I can put on my controller to have Roo give me REST functions?

I figured it out.
The annotation #RooWebScaffold is the answer. I can't find a roo command to install those, but putting that annotation on my classes makes it generate the web scaffolding for the REST interface.
EDIT: Actually that completely doesn't answer my question. It DOES generate the REST access code, but it ALSO generates all the web scaffolding stuff. I've submitted a ticket on the JIRA for this feature.

Related

Interactive T4 Templates

I'm using a set of T4 templates in most of my MVC projects that create a set of Managers (think repositories), ViewModels and Extensions - utility extension methods such as ToModel(), ToViewModel() and ToSelectList(). So far so good. An enormous amount of basic 'plumbing' code is now written for me.
What I'd really like is an ability to configure variables that are used within those templates from an external file and then have the template use that file when executing.
I know I can run another T4 template from within another, but I can't find a way to add configuration in a separate file.
Presently, I include an 'Entity' table in my database and use that for configuration. It works but it feels dirty to have this in the database.
T4 is just C#/VB.Net code in the end, you can pretty much use any libraries you want. If you want an external configuration file you could use json.net and a simple json file in your project. At the start of your template, use the file io in the framework to read your json files contents, pass that to json.net and then extract the parameters you need. The most common way to use json.net is to serialize and deserialize classes but it also gives you access to a lower json dictionary like object that you can use linq to get any data you need from the json.
But remember there is always more then one way to solve a problem and this is a problem I have been trying to solve for a while. My preferred solution is an extension that I have created called T4 Awesome. My extension takes a totally different approach to using T4 for scaffolding inside Visual Studio. I add multiple tool windows and context menus around the IDE to make managing and using T4 templates faster and easier. I have a dynamic UI that lets you define simple parameters and pass them to your templates and also give you much more control over the final output files location. Feel free to check it out. And full disclaimer, I charge for this extension but have a free community version that should be able to do what you want.

Why present view with servlet if we can do it with jsp?

It seems that both can represent a view, that is if you request a servlet it will show you an html page, and so the same if you request a jsp file, just the way they are implemented are different.
Now I know that servlet are more than, that. They control requests and so on, but still after reading so many days, still don't know how to use them in harmony together.
If i need some logic, do I put it in a servlet, and then what? How do I present my data, from the servlet or from a jsp file located in the same folder?
In other words, do I even need jsp files when I use servlet, and if yeas why???
It seems that both can represent a view, ...
JSP was introduced because it's much easier to invoke Java to render parts that are dynamic in an otherwise static HTML template rather than trying to print out the whole page in Java through servlets (too many println(), escaping quotes etc. it's a mess). So, JSP is better suited for rendering views.
MVC is all about separation of concerns: request handling and routing, business logic and application data, and the views with all the presentation logic.
JSPs later enhanced with EL (Expression Language), JSTL (Java Standard Tag Lbrary) and other such tag libraries that encapsulate the presentation logic are better suited to support the View layer.
Model represents your application data and all the business rules that you apply on them. They're implemented as POJOs (plain old Java objects i.e. not extending or implementing platform specific classes or interfaces) .
Servlets and Filters with their request dispatching capabilities and inherently existing in the Java environment are better suited as Controllers to interact with the Application Server, the Model and the View. They facilitate all the routing and the flow of data between the three layers.
If i need some logic, do I put it in a servlet, and then what?
Your business logic neither goes in Servlets nor JSPs. That goes into your business classes (POJOs) insulated as much as possible from the type of application platform (which is J2EE here).
A simple request to demonstrate its use would be to ask you to port your application into .Net. A-ha! Suddenly, writing all that business logic inside your Servlets/JSPs, that cannot be easily reused now, doesn't feel like such a good idea.
So, ideally, your servlets would intercept the client requests and invoke some business class to fulfill it. This may return some data (like results from a SQL query) wrapped as a domain data object (also referred to as data value or data transfer objects).
How do I present my data, from the servlet or from a jsp file located in the same folder?
Before redirecting to an appropriate View, the Controller servlet would push the domain object into some scope (could be request, session or application depending on the requirements) or a sophisticated data store available with an MVC framework (like the ValueStack in Struts 2).
The View, which is your JSP, would then pull the domain object from one of these scopes or ValueStack and render its required properties for display through EL with JSTL tags or OGNL expressions with tag libraries provided by the MVC framework.
It is of good style to separate logic from presentation. (1) You can easily change the logic not touching the presentation and vice versa. (2) You can use a right tool for each task. Pure Java in servlet's code is good for implementing logic. Templating engine, including JSP, is good for presentation, where your work is largely in HTML with some points where you're inserting data from the application.
You can read about Spring as an example how to use JSP in the best way.

Project structure to use jquery ajax in spring mvc using json data in eclipse

I am new to spring mvc. I have a lot of doubts to be cleared before i can continue.
I want to create a simple application wherein an employee details such as name age phone etc is entered and through ajax call the form data has to be to sent to server using json. For server side i am using spring. And the submitted data has to be shown in a jquery data table. And again to retrieve data an ajax call has to be used to get the data as a json. And no binding tool like jackson should be used.
1.) how do i go about creating an application in eclipse. If i should do a simpel java project or a dynamic web project?
2.) Could any one pls provide a sample code of each of the steps.
Thank you in advance
First, I think it's easier to start with Maven, create a WAR project, and use that to generate the Eclipse project files, which you can then import. This has the advantage of allowing Maven to not only create the correct folder structure, but also let it manage your dependencies. There are plugins for Eclipse that help you work with Maven, and you should be able to find lots of How-Tos using Google. Otherwise, you would have to create a project type that generates the WAR, one of which I believe is a Web Project, and layout the folder structure manually.
After you have the proper folder layout, you will need to setup your web.xml to enable Spring, add your Java classes and view files (html, jsps, whatever), and build a WAR. The final step would be to deploy that WAR to a web container of some sort, like maybe Tomcat or Jetty. You can ether run it externally, or configure Eclipse to deploy and launch your WAR in the IDE directly. I prefer the latter approach, as it makes it easier to setup debugging, not that running it external makes it impossible.
In addition, I would recommend adding the Spring pluggins to Eclipse, or just download their STS (Spring Tool Suite), which is just Eclipse with all the Spring plugins already added and configured. STS has the bonus of already having tcServer available, which is Spring Source's flavor of Tomcat. Again, loads of how-tos available on how to do all of this.
Edit to answer first comment
I don't know if I can address your comment here fully, as it's a very broad request. You are basically asking how do I write a full application using jQuery and Spring MVC. The volumes of books dedicated to this subject, as well as many websites you could visit that give tutorials on how to start developing. In fact, I think the Spring website has a tutorial for building their demo Pet Clinic site using Spring MVC. What I will try to do is give you some direction on what you should be asking.
Spring MVC, as the name suggests, is a Model-View-Controller framework that leverages the Spring Framework. I will not attempt to go into any great detail, as again there are volumes of books out there on the subject of Spring and all its wonders, but in general Spring MVC wants an application broken into the following chunks:
1. The Model
These are the objects you are using to represent your "data". This can be data from a Database, flat file, some other web service call, or maybe just passed around in your Controller. You will hear them commonly referred to as domain objects or entities to name a few. But, no matter how you refer to them they are typically POJO (Plain Old Java Objects) Java Beans with no real business logic, who's only existence is to represent some "data" and how it relates to other "data".
Some people prefer to have this object know how to read/write itself to its data store, some people like to have an external object that is only used to handle the read/writes. These are sometime referred to as a DAO (Data Access Object) or a Repository. There are also frameworks you can use for dealing with this stuff, like Hibernate or JPA for databases.
2. The Service Layer
This isn't represented in the MVC acronym, and one might argue this is part of the "Controller", but it's usually a good idea to put your business logic into a service layer. This is typically a POJO class that has methods to do the things you need to do with your Model objects. It houses your business logic so all the business rules are in one place. These are usually split to represent business functions. For instance, if you had an application dealing with car purchases you might have one service class to deal with the User related functions (create a user, update a password, get his preferences), one to deal with inventory (what is in stock, what is on its way, what is the current sales price), and one to deal with making a purchase (validate the customer's credit, start the tag process, etc). Its also common for these services to have reference to each other. For instance, the User service above might use the Inventory service to get a list of VIN numbers for cars Bill sold last week.
3. The Controller
The controller is what glues the "view" to the service layer. It provides the mapping of the URLs in your app to the function(s) they perform in the service layer. Most people try not to clutter the Controller object with too much code, and try to push as much down into the Service layer as they can. But, as long as it's simple logic I personally don't mind having a tad bit of code in the Controller.
4. The View
This is what you are sending to the user. It may be a web page backed by a JSP. It may be an Excel spreadsheet report generated from user input. It may be a simple JSON response to a REST call. It's sort of "the sky's the limit" here. But, for the most part this is either a JSP view or a JSON or XML response from a web service call.
Now to address your comment more directly...
Since you are a novice, I would recommend one of 3 approaches:
Go get a book...do what the book says to do. There are tons out there. Find one that has a good walk-through of a project, and copy/paste their procedures. A good book will usually have a chapter on how to setup all the necessary tools (Eclipse, Tomcat/Jetty, etc)
Find a good how-to on the Internet. There are lots of people that have tutorials. Find one and copy/paste their procedures.
Use something like Spring Roo. Spring Roo is a code generation tool that can be used to build a fully working site with little to no code. I am a big fan of Roo, especially for lone developers not working in a team, as it can generate a TON of the boiler plate code most developers hate to write. It also does things in a very Spring-like fashion, since after all it was created by the Spring folks.
These will get you past the "how do I create the project in Eclipse" problem. Part 2 of question one is a little more tricky. I would say, for now, don't focus on AJAX and stuff. Focus on simply understanding how Spring MVC works. The problem is, you are basically trying to cram 10 things down at once. Spring MVC is hard enough to get your head wrapped around (the annotations, JSTL, EL, and the Spring custom tag libraries, not to mention all the other things you will probably be touching like Spring Data, etc), but then you want to add dynamic web pages, which is JavaScript (and most likely some framework like jQuery), and to cap it off you don't want to use anything like Jackson (not sure why, but ok...) to help ease the transition from Java to JavaScript. That's a tall order. Again, I would cut out AJAX/JavaScript stuff at first, get a good handle on how a SIMPLE application is built, and then you can jump into all the dynamic stuff.
For the last question, providing code samples, I would point you to mkyong's fantastic blog full of Spring-related tutorials as well as Spring's own Tutorial site and Spring's Sample site as a good starting point.

Resources on how to design a framework

Are there any resources on how to design frameworks, i.e. tips and tricks, best practices, etc..
For .NET there's
Framework Design Guidelines: Conventions, Idioms, and Patterns for Reusable .NET Libraries
http://www.amazon.com/Framework-Design-Guidelines-Conventions-Libraries/dp/0321545613
You can also study frameworks like Spring.
The google tech talk lecture How To Design A Good API and Why it Matters provides many insights on how to design a good API.
In regards to PHP ehre are some Tips from me:
Use MVC as your framework type.
MVC (Model-View-Controller) is the best way to create a framework, keeping your Logic and Models separate to your Views etc is the best way to accomplish a fresh clean application.
I believe thatStack Overflow uses a MVC pattern, Not sure if its PHP / ASP tho.
Make your code as open as possible.
Meaning that practically any object is accessible throughout the application.
A way i achive this is by creating a static class that as a global scope to overcome the problem, for example:
class Registry{....}
Registry::add('Database',New Database);
Registry::add('Input',New Input);
Registry::add('Output',New Output);
then anywhere throughout the application you can easily get objects like so:
Regsitry::get('Database')->query('Select .... LIMI 10')->fetchObject();
Do not use template engines
In my eyes template engines are not the best as PHP is itself a template engine, there's no need to create a lot of code to parse your templates and then have PHP parse it again, its logical.
Instead create an system where the user will tell the View what template file to output and check the catch for that, if its not in the cache then that object will transfer it to another object called lets say ViewLoader, Witch within the __Construct it includes the php template file, but also has other methods like url() and escape() etc so in tempalte fiels you can then use
$this->url('controller','method',$this->params);
Hope this helps you!

Migrating from LINQ to SQL to Entity Framework 4.0 - Tips, Documentation, etc

I tried out EF back in .NET 3.5 SP1, and I was one of the many who got frustrated and decided to learn LINQ to SQL instead. Now that I know EF is the "chosen" path forward, plus EF 4.0 has some exciting new features, I'd like to migrate my app to EF 4.0.
Can anyone suggest any good resources that are specifically targeted towards 4.0 and L2S migration? NOTE: I can find plenty of blogs and articles related to migrating from L2S to EF on .NET 3.5, but I feel like many of those were obviously dated and unhelpful to someone using 4.0.
I'd really like as much deep, under-the-hood stuff as I can get; I want to really come away feeling like I know EF 4.0 the way I currently know L2S 3.5.
TIA!
I have done loads of this very type of conversion and FWIW, I would say there are more similarities than differences. I don't think there is any definitive documentation that will make you feel like an expert in EF4, beyond the stuff that is already out there...
http://msdn.microsoft.com/en-us/library/ex6y04yf(VS.100).aspx
What I can give you are the more obvious "gotchas." Specifically, Linq2Sql wanted to combine the business layer and the data layer a lot more obviously. It really pushed you to create your own partial classes. I could go on and on about way, but the most specific reason is the way the one-to-one mapper will create public parent and child properties for all relations.
If you attempt to use any type of serialization against this model, you will like run into circular reference problems as a serializer moves from a parent to a child and then back to the parent as the Linq2Sql serialization behavior automatically includes all children in the graph. This can also be really annoying when you try to grab a customer record to check the "Name" property and automatically get all the related order records included in the graph. You can set these parent and child navigation properties to be either "public" or "internal" which means if you want access to them, but don't want the serializers to automatically create circular references, you pretty much have to access them in partial classes.
Once you start down the partial class path you generally just continue the pattern and eventually will start to add helper methods for accessing your data into your individual entity classes. Also, with the Linq2Sql DataContext being more lightweight, you often find people using some kind of Singleton pattern or Repository pattern for their context. You don't see this as much at all with EF 3.5 / 4.
So let's say you have some environment similar to the one described and you want to start converting. Well, you need to find out when your DataContext is going to be create/destroyed...some people will just start each Business Layer method with a using() statement and let the context pretty much live for the lifetime of the method. Obviously this means you can get into some hairy situations that require adding .ToList() or some other extension method to the ends of your questions you can have a fully in-memory collection of your objects to pass to a child method or whatever and even then you can have problems with attempting to update entities on a context that they weren't originally retrieved from.
You'll also need to figure out how to much of the BusinessLogic incorporated in your Linq2Sql partial classes out into another layer if it doesn't deal explicitly with the data operations. This will not be painless as you figure out when you need/don't need your context, but it is for the best..
Next, you will want to deal with the object graph situation. Because of the difference in the way lazy-loading works (they made this configurable in EF 4.0 to make it behave more like Linq2Sql for those who wanted it) you will probably need to check any implied uses of child objects in the graph from your Linq2Sql implementation and verify that it doesn't now require an explicit .Include() or a .Load() to get the child objects in the graph.
Finally, you will need to decide on a serialization solution in general. By default, the DataContracts and DataMember attributes that are generated as part of an EF model work great with WCF, but not at all great with the XmlSerializer used for things like old .asmx WebServices. Even in this circumstance you might be able to get away with it if you never need to serialize child objects over the wire. Since that usually isn't the case, you are going to want to move to WCF if you have a more SOA, which will add a whole new host of opportunies, yet headaches.
In order to deal with the partial classes situation, and the hefty DataContext and even the serialization issues, there are a number of new code-generation templates available with EF 4.0. The POCO-Entity template has a lot of people excited as it creates POCO classes, just as you'd expect (the trouble is that excludes any class or member attributes for WCF etc etc). Also, the Self-Tracking Entities model pretty much solves the context issue, because you can pass your entities around and let them remember when and how they were updated, so you can create/dispose your contexts much more freely (like Linq2Sql). As another bonus, this template is the go-to template for WCF or anything that builds on WCF like RIA Services or WCF Data Services, so they have the [DataContract], [DataMember], and [KnownType] attributes already figured out.
Here is a link to the POCO template (not included out of the box):
(EDIT: I cannot post two hyperlinks, so just visit the visualstudio gallery website and search for "ADO.NET C# POCO Entity Generator")
Be sure to read the link on the ADO.net team blog about implementing this. You might like the bit about splitting your context and your entities into separate projects/assemblies if you fall into the WebService vs. WCF Service category. The "Add Service Reference..." proxy generation doesn't do namespaces the same way "Add Web Reference..." used to, so you might like to actually reference your entity class assembly in your client app so you can "exclude types from reference libraries" or whatever on your service references so you don't get a lot of ambiguous references from multiple services which use the same EF model and expose those entities...
I know this is long and rambling, but these little gotchas were waaay more of an issue for me than remembering to use context.EntityCollection.AddObject() instead of context.EntityCollection.InsertOnSubmit() and context.SaveChanges() instead of context.SubmitChanges()...
For EF Code First, it's mostly about reverse engineering the existing tables into EF classes. EF Power Tools now does this for you:
http://msdn.microsoft.com/en-us/data/jj200620.aspx
The rest is the obvious work of modifying your existing code to use those generated classes to talk to the database instead of LINQ to SQL.