Commit 7de0b1a9 authored by michada's avatar michada

First working version.

In this first version, this applicacion includes a complete CRUD using
an AJAX+JSON+REST architecture.
parent 574e436f
target/
/bin
/target
/assembly
.project
.classpath
.settings
<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/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>es.uvigo.esei.daa</groupId>
<artifactId>example</artifactId>
<packaging>war</packaging>
<version>0.0.1-SNAPSHOT</version>
<name>DAA Example</name>
<licenses>
<license>
<name>GNU GENERAL PUBLIC LICENSE, Version 3</name>
<url>http://www.gnu.org/licenses/gpl.html</url>
<distribution>repo</distribution>
</license>
</licenses>
<properties>
<maven.compiler.source>1.7</maven.compiler.source>
<maven.compiler.target>1.7</maven.compiler.target>
</properties>
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.11</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.glassfish.jersey.containers</groupId>
<artifactId>jersey-container-servlet</artifactId>
<version>2.5.1</version>
</dependency>
<dependency>
<groupId>org.glassfish.jersey.media</groupId>
<artifactId>jersey-media-json-jackson</artifactId>
<version>2.5.1</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.28</version>
</dependency>
</dependencies>
<build>
<finalName>DAAExample</finalName>
<plugins>
<!-- Build war -->
<plugin>
<artifactId>maven-war-plugin</artifactId>
<groupId>org.apache.maven.plugins</groupId>
<version>2.1.1</version>
<configuration>
<warName>DAAExample</warName>
</configuration>
</plugin>
</plugins>
</build>
</project>
package es.uvigo.esei.daa.dao;
import java.sql.Connection;
import java.sql.SQLException;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.sql.DataSource;
public abstract class DAO {
private final static String JNDI_NAME = "java:/comp/env/jdbc/daaexample";
private final DataSource dataSource;
public DAO() {
Context initContext;
try {
initContext = new InitialContext();
this.dataSource = (DataSource) initContext.lookup(JNDI_NAME);
} catch (NamingException e) {
throw new RuntimeException(e);
}
}
protected Connection getConnection() throws SQLException {
return this.dataSource.getConnection();
}
}
package es.uvigo.esei.daa.dao;
public class DAOException extends Exception {
private static final long serialVersionUID = 1L;
public DAOException() {
}
public DAOException(String message) {
super(message);
}
public DAOException(Throwable cause) {
super(cause);
}
public DAOException(String message, Throwable cause) {
super(message, cause);
}
public DAOException(String message, Throwable cause,
boolean enableSuppression, boolean writableStackTrace) {
super(message, cause, enableSuppression, writableStackTrace);
}
}
package es.uvigo.esei.daa.dao;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.LinkedList;
import java.util.List;
import es.uvigo.esei.daa.entities.Person;
public class PeopleDAO extends DAO {
public List<Person> list() throws DAOException {
try (final Connection conn = this.getConnection()) {
try (Statement statement = conn.createStatement()) {
try (ResultSet result = statement.executeQuery("SELECT * FROM people")) {
final List<Person> people = new LinkedList<>();
while (result.next()) {
people.add(new Person(
result.getInt("id"),
result.getString("name"),
result.getString("surname")
));
}
return people;
}
}
} catch (SQLException e) {
throw new DAOException(e);
}
}
public void delete(int id) throws DAOException {
try (final Connection conn = this.getConnection()) {
final String query = "DELETE FROM people WHERE id=?";
try (PreparedStatement statement = conn.prepareStatement(query)) {
statement.setInt(1, id);
if (statement.executeUpdate() != 1) {
throw new SQLException("Error inserting value");
}
}
} catch (SQLException e) {
throw new DAOException(e);
}
}
public Person modify(int id, String name, String surname) throws DAOException {
try (final Connection conn = this.getConnection()) {
final String query = "UPDATE people SET name=?, surname=? WHERE id=?";
try (PreparedStatement statement = conn.prepareStatement(query)) {
statement.setString(1, name);
statement.setString(2, surname);
statement.setInt(3, id);
if (statement.executeUpdate() == 1) {
return new Person(id, name, surname);
} else {
throw new SQLException("Error inserting value");
}
}
} catch (SQLException e) {
throw new DAOException();
}
}
public Person add(String name, String surname) throws DAOException {
try (final Connection conn = this.getConnection()) {
final String query = "INSERT INTO people VALUES(null, ?, ?)";
try (PreparedStatement statement = conn.prepareStatement(query, Statement.RETURN_GENERATED_KEYS)) {
statement.setString(1, name);
statement.setString(2, surname);
if (statement.executeUpdate() == 1) {
try (ResultSet resultKeys = statement.getGeneratedKeys()) {
if (resultKeys.next()) {
return new Person(resultKeys.getInt(1), name, surname);
} else {
throw new SQLException("Error retrieving inserted id");
}
}
} else {
throw new SQLException("Error inserting value");
}
}
} catch (SQLException e) {
throw new DAOException(e);
}
}
}
package es.uvigo.esei.daa.entities;
public class Person {
private int id;
private String name;
private String surname;
public Person(int id, String name, String surname) {
this.id = id;
this.name = name;
this.surname = surname;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getSurname() {
return surname;
}
public void setSurname(String surname) {
this.surname = surname;
}
}
package es.uvigo.esei.daa.rest;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import es.uvigo.esei.daa.dao.DAOException;
import es.uvigo.esei.daa.dao.PeopleDAO;
@Path("/people")
@Produces(MediaType.APPLICATION_JSON)
public class People {
private final PeopleDAO dao;
public People() {
this.dao = new PeopleDAO();
}
@GET
@Path("/list")
public Response list() {
try {
return Response.ok(this.dao.list(), MediaType.APPLICATION_JSON).build();
} catch (DAOException e) {
e.printStackTrace();
return Response.serverError().entity(e.getMessage()).build();
}
}
@GET
@Path("/delete")
public Response delete(
@QueryParam("id") int id
) {
try {
this.dao.delete(id);
return Response.ok(id).build();
} catch (DAOException e) {
e.printStackTrace();
return Response.serverError().entity(e.getMessage()).build();
}
}
@GET
@Path("/modify")
public Response modify(
@QueryParam("id") int id,
@QueryParam("name") String name,
@QueryParam("surname") String surname
) {
try {
return Response.ok(this.dao.modify(id, name, surname)).build();
} catch (DAOException e) {
e.printStackTrace();
return Response.serverError().entity(e.getMessage()).build();
}
}
@GET
@Path("/add")
public Response add(
@QueryParam("name") String name,
@QueryParam("surname") String surname
) {
try {
return Response.ok(this.dao.add(name, surname)).build();
} catch (DAOException e) {
e.printStackTrace();
return Response.serverError().entity(e.getMessage()).build();
}
}
}
Manifest-Version: 1.0
Class-Path:
<Context>
<!-- maxActive: Maximum number of database connections in pool. Make sure
you configure your mysqld max_connections large enough to handle all of your
db connections. Set to -1 for no limit. -->
<!-- maxIdle: Maximum number of idle database connections to retain in pool.
Set to -1 for no limit. See also the DBCP documentation on this and the minEvictableIdleTimeMillis
configuration parameter. -->
<!-- maxWait: Maximum time to wait for a database connection to become available
in ms, in this example 10 seconds. An Exception is thrown if this timeout
is exceeded. Set to -1 to wait indefinitely. -->
<!-- username and password: MySQL username and password for database connections -->
<!-- driverClassName: Class name for the old mm.mysql JDBC driver is org.gjt.mm.mysql.Driver
- we recommend using Connector/J though. Class name for the official MySQL
Connector/J driver is com.mysql.jdbc.Driver. -->
<!-- url: The JDBC connection url for connecting to your MySQL database. -->
<Resource name="jdbc/daaexample" auth="Container" type="javax.sql.DataSource"
maxActive="100" maxIdle="30" maxWait="10000" username="daa" password="daa"
driverClassName="com.mysql.jdbc.Driver" url="jdbc:mysql://localhost:3306/daaexample" />
</Context>
\ No newline at end of file
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0">
<display-name>DAAExampleTMP</display-name>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
<welcome-file>index.htm</welcome-file>
<welcome-file>index.jsp</welcome-file>
<welcome-file>default.html</welcome-file>
<welcome-file>default.htm</welcome-file>
<welcome-file>default.jsp</welcome-file>
</welcome-file-list>
<resource-ref>
<description>DAA Example DB Connection</description>
<res-ref-name>jdbc/daaexample</res-ref-name>
<res-type>javax.sql.DataSource</res-type>
<res-auth>Container</res-auth>
</resource-ref>
<servlet>
<servlet-name>javax.ws.rs.core.Application</servlet-name>
</servlet>
<servlet-mapping>
<servlet-name>javax.ws.rs.core.Application</servlet-name>
<url-pattern>/rest/*</url-pattern>
</servlet-mapping>
</web-app>
\ No newline at end of file
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>DAA Example</title>
</head>
<body>
<div id="people-container">
<h1>People</h1>
</div>
<script type="text/javascript" src="http://code.jquery.com/jquery-2.1.0.js"></script>
<script type="text/javascript" src="js/view/people.js"></script>
<script type="text/javascript">
$(document).ready(function() {
insertPeopleForm($('#people-container'));
insertPeopleList($('#people-container'));
initPeople();
});
</script>
</body>
</html>
\ No newline at end of file
function listPeople(done, fail, always) {
done = typeof done !== 'undefined' ? done : function() {};
fail = typeof fail !== 'undefined' ? fail : function() {};
always = typeof always !== 'undefined' ? always : function() {};
$.getJSON('rest/people/list')
.done(done)
.fail(fail)
.always(always);
}
function addPerson(person, done, fail, always) {
done = typeof done !== 'undefined' ? done : function() {};
fail = typeof fail !== 'undefined' ? fail : function() {};
always = typeof always !== 'undefined' ? always : function() {};
$.getJSON('rest/people/add', person)
.done(done)
.fail(fail)
.always(always);
}
function modifyPerson(person, done, fail, always) {
done = typeof done !== 'undefined' ? done : function() {};
fail = typeof fail !== 'undefined' ? fail : function() {};
always = typeof always !== 'undefined' ? always : function() {};
$.getJSON('rest/people/modify', person)
.done(done)
.fail(fail)
.always(always);
}
function deletePerson(id, done, fail, always) {
done = typeof done !== 'undefined' ? done : function() {};
fail = typeof fail !== 'undefined' ? fail : function() {};
always = typeof always !== 'undefined' ? always : function() {};
$.getJSON('rest/people/delete', { 'id': id })
.done(done)
.fail(fail)
.always(always);
}
\ No newline at end of file
var peopleFormId = 'people-form';
var peopleListId = 'people-list';
var peopleFormQuery = '#' + peopleFormId;
var peopleListQuery = '#' + peopleListId;
function insertPeopleList(parent) {
parent.append(
'<table id="' + peopleListId + '">\
<tr>\
<th>Nombre</th>\
<th>Apellido</th>\
<th></th>\
<th></th>\
</tr>\
</table>'
);
}
function insertPeopleForm(parent) {
parent.append(
'<form id="' + peopleFormId + '">\
<input name="id" type="hidden" value=""/>\
<input name="name" type="text" value="" />\
<input name="surname" type="text" value=""/>\
<input id="btnSubmit" type="submit" value="Create"/>\
<input id="btnClear" type="reset" value="Limpiar"/>\
</form>'
);
}
function createPersonRow(person) {
return '<tr id="person-'+ person.id +'">\
<td class="name">' + person.name + '</td>\
<td class="surname">' + person.surname + '</td>\
<td>\
<a class="edit" href="#">Edit</a>\
</td>\
<td>\
<a class="delete" href="#">Delete</a>\
</td>\
</tr>';
}
function formToPerson() {
var form = $(peopleFormQuery);
return {
'id': form.find('input[name="id"]').val(),
'name': form.find('input[name="name"]').val(),
'surname': form.find('input[name="surname"]').val()
};
}
function rowToPerson(id) {
var row = $('#person-' + id);
return {
'id': id,
'name': row.find('td.name').text(),
'surname': row.find('td.surname').text()
};
}
function personToForm(person) {
var form = $(peopleFormQuery);
form.find('input[name="id"]').val(person.id);
form.find('input[name="name"]').val(person.name);
form.find('input[name="surname"]').val(person.surname);
}
function isEditing() {
return $(peopleFormQuery + ' input[name="id"]').val() != "";
}
function disableForm() {
$(peopleFormQuery + ' input').prop('disabled', true);
}
function enableForm() {
$(peopleFormQuery + ' input').prop('disabled', false);
}
function showErrorMessage(jqxhr, textStatus, error) {
alert(textStatus + ": " + error);
}
function resetForm() {
$(peopleFormQuery)[0].reset();
$(peopleFormQuery + ' input[name="id"]').val('');
$('#btnSubmit').val('Crear');
}
function addRowListeners(person) {
$('#person-' + person.id + ' a.edit').click(function() {
personToForm(rowToPerson(person.id));
$('input#btnSubmit').val('Modificar');
});
$('#person-' + person.id + ' a.delete').click(function() {
if (confirm('Está a punto de eliminar a una persona. ¿Está seguro de que desea continuar?')) {
deletePerson(person.id,
function() {
$('tr#person-' + person.id).remove();
},
showErrorMessage
);
}
});
}
function appendToTable(person) {
$(peopleListQuery + ' > tbody:last')
.append(createPersonRow(person));
addRowListeners(person);
}
function initPeople() {
$.getScript('js/dao/people.js', function() {
listPeople(function(people) {
$.each(people, function(key, person) {
appendToTable(person);
});
});
$(peopleFormQuery).submit(function(event) {
var person = formToPerson();
if (isEditing()) {
modifyPerson(person,
function(person) {
$('#person-' + person.id + ' td.name').text(person.name);
$('#person-' + person.id + ' td.surname').text(person.surname);
resetForm();
},
showErrorMessage,
enableForm
);
} else {
addPerson(person,
function(person) {
appendToTable(person);
resetForm();
},
showErrorMessage,
enableForm
);
}
return false;
});
$('#btnClear').click(resetForm);
});
};
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment