Tuesday, January 28, 2014

Daniel That: How to display code in blogger posts

Daniel That: How to display code in blogger posts



How to display code in blogger posts

In this post, I'm going to show step by step how to display code nicely in blogger posts using SyntaxHighlighter.

1) First, we need to add the html code below on the head section of our blogger template. To do this, inside blogger:
  • Select Template on the left hand side.
  • Click Edit HTML.
  • Then copy the code below just before the closing head tag (i.e </head>). You can easily find it by using the search box accessing to it with Control+F.

<link href='http://alexgorbatchev.com/pub/sh/current/styles/shCore.css' rel='stylesheet' type='text/css'/>
<link href='http://alexgorbatchev.com/pub/sh/current/styles/shThemeEclipse.css' rel='stylesheet' type='text/css'/>
<script src='http://alexgorbatchev.com/pub/sh/current/scripts/shCore.js' type='text/javascript'/>
<script src='http://alexgorbatchev.com/pub/sh/current/scripts/shBrushJava.js' type='text/javascript'/>
<script src='http://alexgorbatchev.com/pub/sh/current/scripts/shBrushXml.js' type='text/javascript'/>
<script language='javascript' type='text/javascript'>
SyntaxHighlighter.config.bloggerMode = true;
SyntaxHighlighter.all();
</script>

On line 4 and 5 (violet color), I'm loading the syntax template for Java code and XML code, but there are much more like PHP, Perl, SQL,... you can find the complete list here.


2) Now that the blogger template is ready, we need to prepare the code to ensure correct rendering. Basically, we need to HTML escape some characters like right angle brackets, e.g. all < must be replaced with &lt;. To do so, you can use one of the following online tools:

http://www.accessify.com/tools-and-wizards/developer-tools/quick-escape/default.php


3) Once you have the code with escaped characters, you can copy it on your blogger post inside <pre> tags. In the title you can choose a title for the code block and in the class you choose the code template to use.

<pre title="here goes a title" class="brush:xml;">
...
</pre>


4) And that's it, here is an example:
html code using SyntaxHighlight
1
2
3
4
5
6
7
8
9
<link href='http://alexgorbatchev.com/pub/sh/current/styles/shCore.css' rel='stylesheet' type='text/css'/>
<link href='http://alexgorbatchev.com/pub/sh/current/styles/shThemeEclipse.css' rel='stylesheet' type='text/css'/>
<script src='http://alexgorbatchev.com/pub/sh/current/scripts/shCore.js' type='text/javascript'/>
<script language='javascript' type='text/javascript'>
    SyntaxHighlighter.config.bloggerMode = true;
    SyntaxHighlighter.all();
</script>

JSF 2.0 Example Code

Excerpted from  http://balusc.blogspot.com/2011/01/jsf-20-tutorial-with-eclipse-and.html 

Model:



package com.example;

import java.io.Serializable;
import java.util.Date;

import javax.validation.constraints.NotNull;
import javax.validation.constraints.Pattern;

public class User implements Serializable {

 private static final long serialVersionUID = 1L;
 private Long id;
 @NotNull (message = "Please enter username")
 private String username;
 @NotNull (message = "Please enter password")
 @Pattern(regexp = ".*(?=.{8,})(?=.*\\d)(?=.*[a-z])(?=.*[A-Z]).*", message = "Password is not strong enough")
 private String password;
 @NotNull (message = "Please enter email")
 @Pattern(regexp = "([^.@]+)(\\.[^.@]+)*@([^.@]+\\.)+([^.@]+)", message = "Email is not in valid format")
 private String email;
 private Date birthdate;

 public Long getId() {
  return id;
 }

 public void setId(Long id) {
  this.id = id;
 }

 public String getUsername() {
  return username;
 }

 public void setUsername(String username) {
  this.username = username;
 }

 public String getPassword() {
  return password;
 }

 public void setPassword(String password) {
  this.password = password;
 }

 public String getEmail() {
  return email;
 }

 public void setEmail(String email) {
  this.email = email;
 }

 public Date getBirthdate() {
  return birthdate;
 }

 public void setBirthdate(Date birthdate) {
  this.birthdate = birthdate;
 }

}

Backing Bean:


package com.example;

import java.io.Serializable;

import javax.annotation.PostConstruct;
import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ViewScoped;
import javax.faces.context.FacesContext;

@ManagedBean
@ViewScoped
public class Register implements Serializable {

 private static final long serialVersionUID = 1L;
 private User user;

    @PostConstruct
    public void init() {
        user = new User();
    }
    
    public void submit() {
        FacesMessage message = new FacesMessage("Registration succesful!");
        FacesContext.getCurrentInstance().addMessage(null, message);
    }
    
    public User getUser() {
        return user;
    }
}

View:


<!DOCTYPE html>
<html lang="en" xmlns="http://www.w3.org/1999/xhtml" xmlns:f="http://java.sun.com/jsf/core"
    xmlns:h="http://java.sun.com/jsf/html" xmlns:ui="http://java.sun.com/jsf/facelets">
<h:head>
    <title>Register User</title>
</h:head>
<h:body>
    <h:form id="form">
        <h:panelGrid columns="3">
            <h:outputLabel for="username">Username</h:outputLabel>
            
            <h:inputText id="username" label="Username" value="#{register.user.username}">
                <f:ajax event="blur" render="usernameMessage" />
            </h:inputText>
            <h:message id="usernameMessage" for="username" />

            <h:outputLabel for="password">Password</h:outputLabel>
            
            <h:inputSecret id="password" label="Password" value="#{register.user.password}"  redisplay="true">
                <f:ajax event="blur" render="passwordMessage" />
            </h:inputSecret>
            <h:message id="passwordMessage" for="password" />

            <h:outputLabel for="email">Email</h:outputLabel>
            
            <h:inputText id="email" label="Email" value="#{register.user.email}" >
                <f:ajax event="blur" render="emailMessage" />
            </h:inputText>
            <h:message id="emailMessage" for="email" />

            <h:outputLabel for="birthdate">Birthdate (yyyy-MM-dd)</h:outputLabel>
            <h:inputText id="birthdate" converterMessage="Please enter date in yyyy-MM-dd format" label="Birthdate" value="#{register.user.birthdate}">
                <f:convertDateTime pattern="yyyy-MM-dd" />
                <f:ajax event="blur" render="birthdateMessage" />
            </h:inputText>
            <h:message id="birthdateMessage" for="birthdate" />

            <h:panelGroup />
            <h:commandButton value="Register" action="#{register.submit}">
                <f:ajax execute="@form" render="@form" />
            </h:commandButton>
            <h:messages globalOnly="true" layout="table" />
        </h:panelGrid>
    </h:form>
</h:body>
</html>


Monday, January 27, 2014

java - Design Patterns web based applications - Stack Overflow

java - Design Patterns web based applications - Stack Overflow




A bit decent web application consists of a mix of design patterns. I'll mention only the most important ones.

Model View Controller pattern

The core (architectural) design pattern you'd like to use is the Model-View-Controller pattern. TheController is to be represented by a Servlet which (in)directly creates/uses a specific Model and Viewbased on the request. The Model is to be represented by Javabean classes. This is often further dividable in Business Model which contains the actions (behaviour) and Data Model which contains the data (information). The View is to be represented by JSP files which have direct access to the (Data)Model by EL (Expression Language).
Then there are variations based on how actions and events are handled. The popular ones are:
  • Request (action) based MVC: this is the simplest to implement. The (BusinessModel works directly with HttpServletRequest and HttpServletResponse objects. You have to gather, convert and validate the request parameters (mostly) yourself. The View can be represented by plain vanilla HTML/CSS/JS and it does not maintain state across requests. This is how among others Spring MVCStruts and Stripes works.
  • Component based MVC: this is harder to implement. But you end up with a simpler model and view wherein all the "raw" Servlet API is abstracted completely away. You shouldn't have the need to gather, convert and validate the request parameters yourself. The Controller does this task and sets the gathered, converted and validated request parameters in the Model. All you need to do is to define action methods which works directly with the model properties. The View is represented by "components" in flavor of JSP taglibs or XML elements which in turn generates HTML/CSS/JS. The state of the View for the subsequent requests is maintained in the session. This is particularly helpful for server-side conversion, validation and value change events. This is how among othersJSFWicket and Play! works.
As a side note, I warmly recommend to pick an existing framework rather than reinventing your own. Learning an existing and well-developed framework takes in long term less time than developing and maintaining a robust framework yourself. From the mentioned ones I personally recommend JSF 2.0.
In the below detailed explanation I'll restrict myself to request based MVC since that's easier to implement.

Front Controller pattern (Mediator pattern)

First, the Controller part should implement the Front Controller pattern (which is a specialized kind ofMediator pattern). It should consist of only a single servlet which provides a centralized entry point of all requests. It should create the Model based on information available by the request, such as the pathinfo or servletpath, the method and/or specific parameters. The Business Model is called Action in the below HttpServlet example.
protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    try {
        Action action = ActionFactory.getAction(request);
        String view = action.execute(request, response);
        if (view.equals(request.getPathInfo().substring(1)) {
            request.getRequestDispatcher("/WEB-INF/" + view + ".jsp").forward(request, response);
        } else {
            response.sendRedirect(view); // We'd like to fire redirect in case of a view change as result of the action (PRG pattern).
        }
    } catch (Exception e) {
        throw new ServletException("Executing action failed.", e);
    }
}
Executing the action should return some identifier to locate the view. Simplest would be to use it as filename of the JSP. Map this servlet on a specific url-pattern in web.xml, e.g. /pages/*,*.do or even just *.html.
In case of prefix-patterns as for example /pages/* you could then invoke URL's likehttp://example.com/pages/registerhttp://example.com/pages/login, etc and provide /WEB-INF/register.jsp/WEB-INF/login.jsp with the appropriate GET and POST actions. The partsregisterlogin, etc are then available by request.getPathInfo() as in above example.
When you're using suffix-patterns like *.do*.html, etc, then you could then invoke URL's likehttp://example.com/register.dohttp://example.com/login.do, etc and you should change the code examples in this answer (also the ActionFactory) to extract the register and login parts byrequest.getServletPath() instead.

Strategy pattern

The Action should follow the Strategy pattern. It needs to be defined as an abstract/interface type which should do the work based on the passed-in arguments of the abstract method (this is the difference with the Command pattern, wherein the abstract/interface type should do the work based on the arguments which are been passed-in during the creation of the implementation).
public interface Action {
    public String execute(HttpServletRequest request, HttpServletResponse response) throws Exception;
}
You may want to make the Exception more specific with a custom exception likeActionException. It's just a basic kickoff example, the rest is all up to you.
Here's an example of a LoginAction which (as its name says) logs in the user. The User itself is in turn a Data Model. The View is aware of the presence of the User.
public class LoginAction implements Action {
    public String execute(HttpServletRequest request, HttpServletResponse response) throws Exception {
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        User user = userDAO.find(username, password);
        if (user != null) {
            request.getSession().setAttribute("user", user); // Login user.
            return "home"; // Redirect to home page.
        } else {
            request.setAttribute("error", "Unknown username/password. Please retry."); // Store error message in request scope.
            return "login"; // Go back to redisplay login form with error.
        }
    }
}

Factory method pattern

The ActionFactory should follow the Factory method pattern. Basically, it should provide a creational method which returns a concrete implementation of an abstract/interface type. In this case, it should return an implementation of the Action interface based on the information provided by the request. For example, the method and pathinfo (the pathinfo is the part after the context and servlet path in the request URL, excluding the query string).
public static Action getAction(HttpServletRequest request) {
    return actions.get(request.getMethod() + request.getPathInfo());
}
The actions in turn should be some static/applicationwide Map<String, Action> which holds all known actions. It's up to you how to fill this map. Hardcoding:
actions.put("POST/register", new RegisterAction());
actions.put("POST/login", new LoginAction());
actions.put("GET/logout", new LogoutAction());
// ...
Or configurable based on a properties/XML configuration file in the classpath: (pseudo)
for (Entry entry : configuration) {
    actions.put(entry.getKey(), Class.forName(entry.getValue()).newInstance());
}
Or dynamically based on a scan in the classpath for classes implementing a certain interface and/or annotation: (pseudo)
for (ClassFile classFile : classpath) {
    if (classFile.isInstanceOf(Action.class)) {
       actions.put(classFile.getAnnotation("mapping"), classFile.newInstance());
    }
}
Keep in mind to create a "do nothing" Action for the case there's no mapping. Let it for example return directly the request.getPathInfo().substring(1) then.

Other patterns

Those were the important patterns so far.
To get a step further, you could use the Facade pattern to create a Context class which in turn wraps the request and response objects and offers several convenience methods delegating to the request and response objects and pass that as argument into the Action#execute() method instead. This adds an extra abstract layer to hide the raw Servlet API away. You should then basically end up withzero import javax.servlet.* declarations in every Action implementation. In JSF terms, this is what the FacesContext and ExternalContext classes are doing.
Then there's the State pattern for the case that you'd like to add an extra abstraction layer to split the tasks of gathering the request parameters, converting them, validating them, updating the model values and execute the actions. In JSF terms, this is what the LifeCycle is doing.
Then there's the Composite pattern for the case that you'd like to create a component based view which can be attached with the model and whose behaviour depends on the state of the request based lifecycle. In JSF terms, this is what the UIComponent represent.
This way you can evolve bit by bit towards a component based framework.

Related questions/answers

share|edit

Book Review: Spring Start Here: Learn what you need and learn it well

  Spring Start Here: Learn what you need and learn it well by Laurentiu Spilca My rating: 5 of 5 stars This is an excellent book on gett...