jueves, 23 de febrero de 2012

Spring MVC 3.0 y Maven

For this example I'm using MacBook Pro with Mac OS x 10.7.2, SpringSource Tool Suite  2.8.1 and Maven 2.0

First of all, we have to create a maven project.

Next check the first checkbox to avoid creating the application with a archetype.

The code of the file pom.xml is the following(Notice that I added dependencies and plugins to deploy the app on Jetty)
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <groupId>com.example.web</groupId>
    <artifactId>SF</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <packaging>war</packaging>
    <build>
        <finalName>AplicacionWeb</finalName>
        <plugins>
            <plugin>
                <artifactId>maven-compiler-plugin</artifactId>
                <configuration>
                    <source>1.6</source>
                    <target>1.6</target>
                </configuration>
            </plugin>
            <plugin>
                <groupId>org.mortbay.jetty</groupId>
                <artifactId>maven-jetty-plugin</artifactId>
            </plugin>
        </plugins>
    </build>
    <dependencies>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-webmvc</artifactId>
            <version>3.0.6.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>jstl</artifactId>
            <version>1.2</version>
            <scope>provided</scope>
        </dependency>
    </dependencies>
</project>

Next you have to run eclipse:eclipse to run the project and download the libraries to your project.

After this, you have to refresh the project. 

Next, create the package com.example.model.
Into this package you have to create the a Java class named Product. This class should implements Serializable. Also, it contains the following code:

package com.example.model;

import java.io.Serializable;

public class Product implements Serializable{
    private static final long serialVersionUID = 1L;
    private String name;
    private Double price;
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public Double getPrice() {
        return price;
    }
    public void setPrice(Double price) {
        this.price = price;
    }
}

Next, create a package named com.example.service
Into this package create an interface named ProductService.
This interface have two functions.
ListgetAllProducts()       -- To retrieve all the products
void addProduct(Product product)  -- To add a product.

This is the code of the ProductService:
package com.example.service;

package com.example.service;

import java.util.List;

import com.example.model.Product;

public interface ProductService {
    List<Product> getAllProducts();
    void addProduct(Product product);
}

The we have to implement the Interface, hence we create a new package named com.example.impl This package will contain a class named ProductServiceImpl. This is a service class, so it implements the @Service annotation. This is the code for ProductServiceImpl.java

package com.example.impl;

import java.util.ArrayList;
import java.util.List;

import org.springframework.stereotype.Service;

import com.example.model.Product;
import com.example.service.ProductService;
@Service
public class ProductServiceImpl implements ProductService {
    List products=new ArrayList();
   
    public List getAllProducts() {
        return products;
    }
   
    public void addProduct(Product product) {
        products.add(product);
    }
}



Next, we have to create the controller.
Create a package named com.example.controller. Into this package you have to create a Class named ProductController:
package com.example.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;

import com.example.model.Product;
import com.example.service.ProductService;

@Controller
@RequestMapping(value="product")// This is also the path of the URL after the App
public class ProductController {
    @Autowired
    private ProductService productService;
  
    /*
     * When a link from the app calls viewAllProducts this function is called.
     * Also the list object is updated with the use of the function addObject and
     * the variable products
     */
    @RequestMapping(value="listProducts",method=RequestMethod.GET)
    public ModelAndView viewAll(){
        ModelAndView mav=new ModelAndView();
        mav.setViewName("list");//The name of the JSP page
        mav.addObject("products",productService.getAllProducts());
        return mav;
    }
  
    /*
     * When a link from the app calls newProduct this function is called.
     * Also the product is added to the current list of products. Also a new empty
     * instance of the object is created.
     */
    @RequestMapping(value="newProduct",method=RequestMethod.GET)
    public ModelAndView newproduct(){
        ModelAndView mav=new ModelAndView();
        mav.setViewName("new");//The name of the JSP page
        mav.addObject("product",new Product());
        return mav;
    }
  
    /*
     * When a link from the app calls newProduct this function is called.
     * Also the product is added to the current list of products. Also a new empty
     * instance of the object is created.
     */
    @RequestMapping(value="addProduct",method=RequestMethod.POST)
    public String add(@ModelAttribute(value="product") Product product){
        productService.addProduct(product);
        return "redirect:listProducts.htm";
    }
}



After this, we have to create the following route of directories webapp/WEB-INF/jsp  into src/main.
Into webapp/WEB-INF we have to create two xml files web.xml and dispatcher-servlet.xml.
web.xml will be configurated to support the Servlet for the use of Springfrmework also its mapping.
This is code for web.xml:
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="3.0" xmlns="http://java.sun.com/xml/ns/javaee"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd">
    <servlet>
        <servlet-name>dispatcher</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        
    </servlet>
    <servlet-mapping>
        <servlet-name>dispatcher</servlet-name>
        <url-pattern>*.htm</url-pattern>
    </servlet-mapping>
    <welcome-file-list>
        <welcome-file>index.jsp</welcome-file>
    </welcome-file-list>
</web-app>

The file dispatcher-server.xml has the springframework configuration to locate the implementation of the services and controllers. Also it is used to specify the directories where the jsp are stored.
This is the source code of dispatcher-server.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xmlns:context="http://www.springframework.org/schema/context"
         xsi:schemaLocation="http://www.springframework.org/schema/beans
                             http://www.springframework.org/schema/beans/spring-beans.xsd
                             http://www.springframework.org/schema/context
                             http://www.springframework.org/schema/context/spring-context.xsd">
<context:component-scan base-package="com.example.controller"/>
<context:component-scan base-package="com.example.impl"/>
<context:annotation-config />     
<bean id="viewResolver"
          class="org.springframework.web.servlet.view.InternalResourceViewResolver">
          <property name="prefix"><value>/WEB-INF/jsp/</value></property>
          <property name="suffix"><value>.jsp</value></property>
          </bean>    
</beans>


Next, we have to create the JSP pages into webapp/WEB-INF/jsp.
 The information will be displayed with the help of SpringFramework JSTL.
Next, we have to create a JSP named index.jsp to redirect the app to the list of products. So that, create a page named index.jsp at webapp directory with the following code:
<jsp:forward page="product/listProducts.htm"></jsp:forward>


Create a JSP page named as  include.jsp. This page will be used to save the calls to the JSTL libraries. This is the code for include.jsp:
<%@page isELIgnored="false" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt"%>


Next, create a JSP named list.jsp
This page will display the information of the products in memory.<%@ include file="include.jsp"%>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Product List</title>
</head>
<body>
<table>
<tr>
<td>Product Name</td>
<td>Price</td>
</tr>
<c:forEach items="${products}" var="product">
<tr>
<td>${product.name}</td>
<td>${product.price}</td>
</tr>
</c:forEach>
</table>
<a href="/SF/product/newProduct.htm">Add New Product</a>
</body>
</html>

Also, create a page named new.jsp This page will add a product to the current list in memory.
<%@ include file="include.jsp"%>
<%@taglib prefix="form" uri="http://www.springframework.org/tags/form" %>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>New Product</title>
</head>
<body>
<form:form action="addProduct.htm" method="post" commandName="product">
Product Name:<form:input path="name"/>
Price:<form:input path="price"/>
<input type="submit" value="add"/>
</form:form>
</body>
</html>
Run the app with mvn jetty:run
Finally open an Internet browser at http://localhost:8080/SF










martes, 24 de enero de 2012

Jtwitter

For this example I'm using a MacBook Pro with Lion, Netbeans and JDK1.6

First of all you have to create a Twitter app, hence you have to go to dev.twitter.com and log in with your twitter account
Next create a new application with the details related to your app.
Then click on setting and change the Application Type to Read, Write and Access direct messages
 
Then  click on update this twitter application's settings

Create my Access tokens



First of all you need the following libraries
common-codec-1.4.jar http://mirrors.ibiblio.org/pub/mirrors/maven2/commons-codec/commons-codec/1.4/commons-codec-1.4.jar
jtwitter.jar http://www.winterwell.com/software/jtwitter/jtwitter.jar
sign-core-1.2.1.1.jar http://code.google.com/p/oauth-signpost/downloads/detail?name=signpost-core-1.2.1.1.jar

Next create a Web application with Netbeans

In the index.jsp set the following code.
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title>JSP Page</title>
    </head>
    <body>
        <form name="form1" action="NewServlet" method="Post">
        User:<input type="textfield" name="user"/><br/>
        Message:<input type="textfield" name="message"/><br/>
        <input type="submit" value="Enviar"/>
        </form>
    </body>
</html>

Next create a Servlet. You may call it NewServlet
with the following code:




package com.ejemplo;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.Date;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import winterwell.jtwitter.OAuthSignpostClient;
import winterwell.jtwitter.Twitter;

public class NewServlet extends HttpServlet {
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        String JTWITTER_OAUTH_KEY = "xxxxxxxxxxxxxxxxxxxxxxxxx";
        String JTWITTER_OAUTH_SECRET = "XXXXXXXXXXXXXXXXXX";
        String JTWITTER_ACCESS_TOKEN = "yyyyyyyyyyyyyyyyyyyyyyyyyy";
        String JTWITTER_ACCESS_TOKEN_SECRET = "YYYYYYYYYYYYYYY";
        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();
        try {
            out.println("Your Message was sent");
            OAuthSignpostClient oauthClient = new OAuthSignpostClient(JTWITTER_OAUTH_KEY, JTWITTER_OAUTH_SECRET, JTWITTER_ACCESS_TOKEN, JTWITTER_ACCESS_TOKEN_SECRET);
            Twitter twitter = new Twitter(request.getParameter("user"), oauthClient);
            String fecha = (new Date()).toString();
            twitter.updateStatus(request.getParameter("message") + fecha);
        } catch (Exception ex) {
            out.println(ex.getMessage());
            ex.printStackTrace();
        } finally {
            out.close();
        }
    }

    //
    /**
     * Handles the HTTP GET method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /**
     * Handles the HTTP POST method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /**
     * Returns a short description of the servlet.
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }//

}

Replace xxxxx with Consumer key
Replace XXXX with Consumer secret
Replace yyyyy with  Access token
Replace YYYY with Access token secret

Finally upload you application to a webserver and run the app