get an html page using JAXRS - java

I am a Java developer, I want to write my own blogging application (that bloggers use to write their blogs with) i know it may sound crazy but i want it just for learning purpose, i am using JSF EJB Hibernate and RESTeasy tools,i started it i have created the database and the view.
From the information that i collected it is recommended to store the blog content in database(in html text), i find that i can use for that Javascript editor like CKEditor after the blogger write his blog in CKEditor i will concatenate it with a prepared header and footer after that i will store it in the database, and i found out that i can get blog post using RESTeasy API.
As an example(sorry):
after the blog is stored in the database
i want to present it to visitors like this:
link containing a path and the id of the article
<div>
Read More...
</div>
when the visitor press the link a REST Controller handle the request, fetch the article from the database using the provided id in the link and return an html page (without creating it statically).
The RESTeasy part perhaps something like this:
#Stateless
#Path("/article/")
public class ArticleResource {
#EJB
private ArticleService articleService;
#GET
#Path("/{id}")
#Produces(value = MediaType.TEXT_HTML)
public Response getArticleById(#PathParam("id") Long id){
//get article post from the database
Article article = articleService.findById(id);
//something here i didn't know
//return article post as an html page
}
}
Please if there is anything here that you see is wrong feel free to inform me, i am just learning here. And if there is an even better approach that you see is good, i really appreciate it.
I know perhaps using Spring it can be better but i want just to learn here how to do it.
I want to know how to get an html page stored in database using JAXRS,
the html page has no file in the application it is just stored in the database something like this:
"<html><head>...</head> <body>...content of the blog here</body> </html>"
Thank you in advance.

Use Jersey's MVC Templates
You can use freemarker as template engine to produce HTML with context
Your template will be similar to:
<html><head>...</head> <body> ${article.toString()}</body> </html>
You can follow example:
In this example, the FruitResource JAX-RS resource class is the controller. The Viewable instance encapsulates the referenced data model which is a simple String.
Furthermore, we also include a named reference to the associated view template – index.ftl.
In this example, we’ve used the #Template annotation. This avoids wrapping our model directly in a template reference via Viewable and makes our resource method more readable.

Related

HATEOAS JAX-RS Link-Headers

I am currently trying to build a RESTful API using raw JAX-RS. I have learned that when building REST APIs, there is the principle called HATEOAS(Hypermedia as the engine of application state). In my class we used Link Headers to tell the client, how to further progress the application. I have managed to implement all basic functionality and can access the server after deploying the application to a tomcat server.
My question now is, how do I add a header-link that contains a wildcard for the user to fill in, for example an id?
So far I have tried
#Path("/resources")
#Produces(MediaType.APPLICATION_JSON)
public Response listAllResources()
{
List<TestResource> resources = ...
// get stuff from database
return Response.ok(resources)
.link(UriInfo.getAbsolutePathBuilder().path("{id}").build(), "edit")
.build;
}
After I try to access the above defined path, I get an error message that the template variable id is undefined.
I can't find any helpful resource that shows me how to create a link header that looks like:
link: <http://example.com/api/resources/{id}>; rel: "edit"
I hope my question was clear enough since this is my first question on stackoverflow :)
Thanks in advance!
I found out, that links like in my example http://example.com/api/resources/{id} aren't possible by JAX-RS because the UriBuilder tries to resolve any URL part that's surrounded by curly braces. So just use like http://example.com/api/resources/:id, if you want to give an Uri Template. Unfortunately the client then has to do something like a String.replace() to actually "create" a valid URI.

Create new static address dynamically in Java web application

When developing a Web Application in Java, launching in Tomcat, I need to be able to create (dynamically) a new static address (link,URL) in the server that will be used to view the information of a new item, let's call it new_item_001, which have been just created by one user.
Say I want to create a new address
www.domain.com/webapp/items/new_item_001
which can be used to render a view of the contents of new_item_001.
Which is the best approach to do this?
Should I dynamically create a new servlet class for this view?
Should I dynamically create the folder items and one html file new_item_001 for this item inside of it?
Should I edit the server address mapping rules to create this static address and map it to a central servlet which somehow knows which item to display?
I understand the question is ill posed, and that I am far from even understanding the issue, so I would like some guidelines on what to look for.
None of the above.
You should simply have a servlet mapped to /items/*. When a request come to this servlet, analyze the actual path of the request, extract the part after /items/ to know the actual value (new_item_001) in your example, get the data corresponding to this item from the database, and send it to the browser.
Using a true MVC framework like Spring MVC would make that much easier. You could simply map a method of a controller using
#RequestMapping("/items/{itemId}")
public Item getItem(#PathVariable("itemId") String itemId) {
...
}
and let the framework do all the URL parsing for you.
I would like to tackle this in a simple way. Creating a servlet for each created item would be overkill and become quite cumbersome to manage after a successful run of the application for some time.
Changing/editing server mapping URL looks very naive approach and is not scaling too. Let configuration be there and change them only when you actually need to change them.
My suggestion is to create one servlet that handles all these requests. For example, you may save item information on a datastore or on file system(i.e images uploaded by user etc..). Next time a GET request is received by the application to fetch saved information of an item, servlet should be able to reference the item on database associated with the item id on the URL. If you don't wish to expose item id/surrogate key in the database, you can also have a simple mapping between them by implementing your own logic. Frameworks like Spring MVC do a good job in mapping URLs to resources like this should you wish to use a framework.
Additionally to minimize the number of requests to the same item, you can also implement an HTTP caching strategy(i.e. ETAG, If-Modified-Since) by instructing your web server at the time of first GET request from a user.

Understanding the flow of spring framework & MVC

I am having some trouble understanding this. Can someone help me better understand this?
MVC
Model --> Java- Spring Framework
View ---> templating language(JSP velocity) & Javascript
DB --> SQL
Q-1)
Now, When I open a particular page, I can't visualize the flow. I've read about DAO, controller , service etc and I understand them individually but I am really confused when I club all together what's the order of execution? Whats the flow exactly ? Is it that first the view is loaded then it sends JS request to fetch the necessary data from backend and then the controller and service are invoked and the DAO queries the db? Then how does the API come into picture? DAO deals with the API?
Q-2)
Why do we need xyz.properties? I have removed a module from my page. If I remove a particular js file(related to that module) from the scripts.properties, then ideally that js should not get executed at all right? Then still why would I see the api call to fetch the data related to that module? I don't see the module but I sure see the api call. Why is that?
DB doesn't enter in MVC model. And you're forgetting a principal element in your analysis: the Controller. The flow goes like this:
Client performs a request to an URL
The application server gets the URL and passes the handling to the web application.
The web application using Spring MVC will handle the URL processing to the Controller: DispatchServlet, which is a Servlet.
The DispatchServlet will try handle the URL. If there's an URL mapping, then it will pass it to the class (mapped in the spring.xml config or decorated with #Controller annotation).
This controller (which in fact is part of the model) will handle the request. It will call services, daos, etc (Model) and return the necessary data to complete the response to the DispatchServlet.
The DispatchServlet will finish the request handling and, in the end, will generate the results e.g. a text/json response, or it will forward to a JSP file (View).
For question two, I never have used such scripts.properties file, so I don't know what you're talking about. Usage of a properties file is to store application properties that should not change until an application redeploy. They have 3 main advantages:
They can be easily manipulated by human users. It's no rocket science to add, edit or remove values.
Since it is a plain text, it's easier to version using a version control system like SVN, Git or another of your preference.
It provides a faster access since it is usually in the same disk as the application, so there's no much time penalty when accessing to its contents compared to a database configuration. But since it is in disk, it still has a disadvantage against RAM access only.
In simple layman's term, MVC explained in pictorial form
(inputing data) (data related part) (display rendering)
-request mapping -classes -JSP (Script,CSS,HTML)
-request param -interface -velocity
Controller ------------->Model--------------->View
||
\/
(data processing logic) (access to Databse)
-optimization -JDBC
-business logic -SQL
Service--------------------->DAO

Play Framework Authorization Java

Does anybody know if there's play framework module that allows you to authorize pages dynamically in Java?
I'm using the play-authenticate/deadbolt modules (http://joscha.github.io/play-authenticate/ and https://github.com/schaloner/deadbolt-2) for the the authentication/authorization mechanism. However, deadbolt doesn't have a straight forward sample on how to implement authorization per page or resource. It does have the ability to create dynamic constrains but the docs are limited and don't tell you if you can create per page authorization using a model or something else.
I'm thinking of creating a model "Page" that allows you to keep track of all the permissions per page dynamically. Is there a better way ?
Thanks.
You could do this in Deadbolt by wrapping your page content in a dynamic tag. The name given to the tag maps to a DynamicResourceHandler, which can then do a lookup in the DB to see if the current user has access to the page.
For example, you view would look like this:
#(handler: my.app.MyDynamicResourceHandler)
#dynamic("handlerName", "pageKey", handler) {
Your page content goes here
}
And the handler's isAllowed method would be implemented along the lines of
public boolean isAllowed(String name,
String meta,
DeadboltHandler deadboltHandler,
Http.Context context)
{
Subject subject = deadboltHandler.getSubject();
result = // check your user's access to the page key (provided as the meta argument)
return result;
}
The documentation is being improved at the moment, and in the meantime you can see more examples at http://deadbolt-2-java.herokuapp.com/#template-dynamic

what is a good pattern for serving a web page given a HttpServletRequest?

I've created a abstract base class Page that figures out how to construct a dynamic web page. I'm trying to come up with a good way to generate a Page based off the GET request that comes in as a HttpServletRequest. For example...
public class RootServlet extends HttpServlet {
#Override
public void doGet(HttpServletRequest request, HttpServletResponse response) {
Page page = Page.generatePage(request);
// do stuff with page and write back response
}
}
In the generatePage() method, I somehow have to figure out what page is being requested, build the correct page, and then return an instance of it. But I'm not sure how to do this well... for example, I need to handle these kinds of URLs coming in:
http://example.com/ : build the default home page
http://example.com/ab123 : build the page corresponding to the given token "ab123"
http://example.com/about/ : build the "about" page
http://help.example.com/ : build the "help" page
Each of these "pages" extend the abstract base class Page so they know how to build themselves, but I'm not sure how to determine that the AboutPage needs to be built, or the HelpPage, as opposed to the default HomePage.
I'm using Apache Velocity as the template engine, so these Page objects really contain only the important information needed to generate that page, like which styles and scripts to use, and the relevant content to be displayed on the page.
I would think there are better ways to do this than to look at the end of the URL and see if "about" is a substring to build the AboutPage, for example. Any suggestions?
There are dozens of off the shelf tools frameworks that do this for you. In the very least I'd suggest Spring MVC which will work with velocity.
Spring MVC has a great way to deal with this kind of stuff using controllers with annotated methods to handle the specific pattern that you want.
They have a great example application here:
https://github.com/SpringSource/spring-mvc-showcase
Anyway, it is not a good practice to build your pages using java code.

Categories

Resources