Pet

parent 39a7b6b2
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="ClientPropertiesManager">
<properties class="javax.swing.AbstractButton">
<property name="hideActionText" class="java.lang.Boolean" />
</properties>
<properties class="javax.swing.JComponent">
<property name="html.disable" class="java.lang.Boolean" />
</properties>
<properties class="javax.swing.JEditorPane">
<property name="JEditorPane.w3cLengthUnits" class="java.lang.Boolean" />
<property name="JEditorPane.honorDisplayProperties" class="java.lang.Boolean" />
<property name="charset" class="java.lang.String" />
</properties>
<properties class="javax.swing.JList">
<property name="List.isFileList" class="java.lang.Boolean" />
</properties>
<properties class="javax.swing.JPasswordField">
<property name="JPasswordField.cutCopyAllowed" class="java.lang.Boolean" />
</properties>
<properties class="javax.swing.JSlider">
<property name="Slider.paintThumbArrowShape" class="java.lang.Boolean" />
<property name="JSlider.isFilled" class="java.lang.Boolean" />
</properties>
<properties class="javax.swing.JTable">
<property name="Table.isFileList" class="java.lang.Boolean" />
<property name="JTable.autoStartsEdit" class="java.lang.Boolean" />
<property name="terminateEditOnFocusLost" class="java.lang.Boolean" />
</properties>
<properties class="javax.swing.JToolBar">
<property name="JToolBar.isRollover" class="java.lang.Boolean" />
</properties>
<properties class="javax.swing.JTree">
<property name="JTree.lineStyle" class="java.lang.String" />
</properties>
<properties class="javax.swing.text.JTextComponent">
<property name="caretAspectRatio" class="java.lang.Double" />
<property name="caretWidth" class="java.lang.Integer" />
</properties>
</component>
<component name="ProjectRootManager" version="2" languageLevel="JDK_1_8" default="true" project-jdk-name="1.8" project-jdk-type="JavaSDK">
<output url="file://$PROJECT_DIR$/out" />
</component>
</project>
\ No newline at end of file
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="ProjectModuleManager">
<modules>
<module fileurl="file://$PROJECT_DIR$/src/main/main.iml" filepath="$PROJECT_DIR$/src/main/main.iml" />
<module fileurl="file://$PROJECT_DIR$/src/test/test.iml" filepath="$PROJECT_DIR$/src/test/test.iml" />
</modules>
</component>
</project>
\ No newline at end of file
This diff is collapsed.
-- phpMyAdmin SQL Dump
-- version 4.6.5.2
-- https://www.phpmyadmin.net/
--
-- Servidor: 127.0.0.1
-- Tiempo de generación: 26-02-2017 a las 19:38:32
-- Versión del servidor: 10.1.21-MariaDB
-- Versión de PHP: 5.6.30
SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO";
SET time_zone = "+00:00";
/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;
/*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */;
/*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */;
/*!40101 SET NAMES utf8mb4 */;
--
-- Base de datos: `daaexample`
--
-- --------------------------------------------------------
--
-- Estructura de tabla para la tabla `people`
--
CREATE TABLE `people` (
`id` int(11) NOT NULL,
`name` varchar(50) NOT NULL,
`surname` varchar(100) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
--
-- Volcado de datos para la tabla `people`
--
INSERT INTO `people` (`id`, `name`, `surname`) VALUES
(1, 'Antón', 'Pérez'),
(2, 'Manuel', 'Martínez'),
(3, 'Laura', 'Reboredo'),
(4, 'Perico', 'Palotes'),
(5, 'Ana', 'María'),
(6, 'María', 'Nuevo'),
(7, 'Alba', 'Fernández'),
(8, 'Asunción', 'Jiménez');
-- --------------------------------------------------------
--
-- Estructura de tabla para la tabla `pet`
--
CREATE TABLE `pet` (
`id` int(11) NOT NULL,
`personId` int(50) NOT NULL,
`nombre` varchar(50) NOT NULL,
`especie` varchar(50) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
--
-- Volcado de datos para la tabla `pet`
--
INSERT INTO `pet` (`id`, `personId`, `nombre`, `especie`) VALUES
(14, 1, 'Dog', 'Dog'),
(15, 2, 'Cat', 'Cat');
-- --------------------------------------------------------
--
-- Estructura de tabla para la tabla `users`
--
CREATE TABLE `users` (
`login` varchar(100) NOT NULL,
`password` varchar(64) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
--
-- Volcado de datos para la tabla `users`
--
INSERT INTO `users` (`login`, `password`) VALUES
('admin', '43f413b773f7d0cfad0e8e6529ec1249ce71e8697919eab30d82d800a3986b70'),
('normal', '688f21dd2d65970f174e2c9d35159250a8a23e27585452683db8c5d10b586336');
--
-- Índices para tablas volcadas
--
--
-- Indices de la tabla `people`
--
ALTER TABLE `people`
ADD PRIMARY KEY (`id`);
--
-- Indices de la tabla `pet`
--
ALTER TABLE `pet`
ADD PRIMARY KEY (`id`),
ADD KEY `pet_ibfk_1` (`personId`);
--
-- Indices de la tabla `users`
--
ALTER TABLE `users`
ADD PRIMARY KEY (`login`);
--
-- AUTO_INCREMENT de las tablas volcadas
--
--
-- AUTO_INCREMENT de la tabla `people`
--
ALTER TABLE `people`
MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=9;
--
-- AUTO_INCREMENT de la tabla `pet`
--
ALTER TABLE `pet`
MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=17;
--
-- Restricciones para tablas volcadas
--
--
-- Filtros para la tabla `pet`
--
ALTER TABLE `pet`
ADD CONSTRAINT `pet_ibfk_1` FOREIGN KEY (`personId`) REFERENCES `people` (`id`) ON DELETE CASCADE;
/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */;
/*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */;
/*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;
......@@ -581,7 +581,7 @@
</activation>
<properties>
<geckodriver.url>https://github.com/mozilla/geckodriver/releases/download/${geckodriver.version}/geckodriver-${geckodriver.version}-${geckodriver.suffix}.tar.gz</geckodriver.url>
<geckodriver.basepath>${settings.localRepository}${file.separator}geckodriver${file.separator}${os.name}${file.separator}${os.arch}${file.separator}${project.build.directory}${file.separator}</geckodriver.basepath>
<geckodriver.basepath>${settings.localRepository}${file.separator}geckodriver${file.separator}${os.name}${file.separator}${os.arch}${file.separator}</geckodriver.basepath>
<geckodriver.compressed.path>${geckodriver.basepath}${file.separator}geckodriver-${geckodriver.version}-${geckodriver.suffix}.tar.gz</geckodriver.compressed.path>
<geckodriver.uncompressed.path>${geckodriver.basepath}${file.separator}geckodriver</geckodriver.uncompressed.path>
</properties>
......@@ -620,7 +620,7 @@
</activation>
<properties>
<geckodriver.url>https://github.com/mozilla/geckodriver/releases/download/${geckodriver.version}/geckodriver-${geckodriver.version}-${geckodriver.suffix}.zip</geckodriver.url>
<geckodriver.basepath>${settings.localRepository}${file.separator}geckodriver${file.separator}${os.name}${file.separator}${os.arch}${file.separator}${project.build.directory}${file.separator}</geckodriver.basepath>
<geckodriver.basepath>${settings.localRepository}${file.separator}geckodriver${file.separator}${os.name}${file.separator}${os.arch}${file.separator}</geckodriver.basepath>
<geckodriver.compressed.path>${geckodriver.basepath}${file.separator}geckodriver-${geckodriver.version}-${geckodriver.suffix}.zip</geckodriver.compressed.path>
<geckodriver.uncompressed.path>${geckodriver.basepath}${file.separator}geckodriver.exe</geckodriver.uncompressed.path>
</properties>
......@@ -714,7 +714,7 @@
<properties>
<geckodriver.suffix>mac</geckodriver.suffix>
<geckodriver.url>https://github.com/mozilla/geckodriver/releases/download/${geckodriver.version}/geckodriver-${geckodriver.version}-${geckodriver.suffix}.tar.gz</geckodriver.url>
<geckodriver.basepath>${settings.localRepository}${file.separator}geckodriver${file.separator}${os.name}${file.separator}${os.arch}${file.separator}${project.build.directory}${file.separator}</geckodriver.basepath>
<geckodriver.basepath>${settings.localRepository}${file.separator}geckodriver${file.separator}${os.name}${file.separator}${os.arch}${file.separator}</geckodriver.basepath>
<geckodriver.compressed.path>${geckodriver.basepath}${file.separator}geckodriver-${geckodriver.version}-${geckodriver.suffix}.tar.gz</geckodriver.compressed.path>
<geckodriver.uncompressed.path>${geckodriver.basepath}${file.separator}geckodriver</geckodriver.uncompressed.path>
</properties>
......
......@@ -11,6 +11,7 @@ import javax.ws.rs.ApplicationPath;
import javax.ws.rs.core.Application;
import es.uvigo.esei.daa.rest.PeopleResource;
import es.uvigo.esei.daa.rest.PetResource;
import es.uvigo.esei.daa.rest.UsersResource;
/**
......@@ -26,7 +27,8 @@ public class DAAExampleApplication extends Application {
public Set<Class<?>> getClasses() {
return Stream.of(
PeopleResource.class,
UsersResource.class
UsersResource.class,
PetResource.class
).collect(toSet());
}
......
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 java.util.logging.Level;
import java.util.logging.Logger;
import es.uvigo.esei.daa.entities.Pet;
/**
* DAO class for the {@link Pet} entities.
*
* Created by LuisF on 23/02/2017.
*/
public class PetDAO extends DAO
{
private final static Logger LOG = Logger.getLogger(PetDAO.class.getName());
/**
* Returns a pet stored persisted in the system.
*
* @param id identifier of the pet.
* @return a pet with the provided identifier.
* @throws DAOException if an error happens while retrieving the pet.
* @throws IllegalArgumentException if the provided id does not corresponds
* with any persisted pet.
*/
public Pet get(int id)
throws DAOException, IllegalArgumentException
{
try (final Connection conn = this.getConnection())
{
final String query = "SELECT * FROM pet WHERE id=?";
try (final PreparedStatement statement = conn.prepareStatement(query))
{
statement.setInt(1, id);
try (final ResultSet resultado = statement.executeQuery())
{
if (resultado.next())
{
return rowToEntity(resultado);
} else
{
throw new IllegalArgumentException("Invalid id");
}
}
}
} catch (SQLException e) {
LOG.log(Level.SEVERE, "Error getting a pet", e);
throw new DAOException(e);
}
}
/**
* Returns a list with all the pet persisted in the system.
*
* @return a list with all the pet persisted in the system.
* @throws DAOException if an error happens while retrieving the pet.
*/
public List<Pet> list() throws DAOException
{
try (final Connection conn = this.getConnection())
{
final String query = "SELECT * FROM pet";
try (final PreparedStatement statement = conn.prepareStatement(query))
{
try (final ResultSet result = statement.executeQuery()) {
final List<Pet> pet = new LinkedList<>();
while (result.next()) {
pet.add(rowToEntity(result));
}
return pet;
}
}
} catch (SQLException e) {
LOG.log(Level.SEVERE, "Error listing pet", e);
throw new DAOException(e);
}
}
/**
* Persists a new pet in the system. An identifier will be assigned
* automatically to tte new pet.
*
* @param nombre name of the new pet. Can't be {@code null}.
* @param especie surname of the new pet. Can't be {@code null}.
* @param personID surname of the new pet. Can't be {@code null}.
* @return a {@link Pet} entity representing the persisted pet.
* @throws DAOException if an error happens while persisting the new person.
* @throws IllegalArgumentException if the name or specie are {@code null}.
*/
public Pet add(int personID, String nombre, String especie)
throws DAOException, IllegalArgumentException {
if (nombre == null || especie == null) {
throw new IllegalArgumentException("name and specie can't be null");
}
try (Connection conn = this.getConnection()) {
final String query = "INSERT INTO pet VALUES(null, ?, ?, ?)";
try (PreparedStatement statement = conn.prepareStatement(query, Statement.RETURN_GENERATED_KEYS)) {
statement.setInt(1, personID);
statement.setString(2, nombre);
statement.setString(3, especie);
if (statement.executeUpdate() == 1) {
try (ResultSet resultKeys = statement.getGeneratedKeys()) {
if (resultKeys.next()) {
return new Pet(resultKeys.getInt(1),personID, nombre, especie);
} else {
LOG.log(Level.SEVERE, "Error retrieving inserted id");
throw new SQLException("Error retrieving inserted id");
}
}
} else {
LOG.log(Level.SEVERE, "Error inserting value");
throw new SQLException("Error inserting value");
}
}
} catch (SQLException e) {
LOG.log(Level.SEVERE, "Error adding a pet", e);
throw new DAOException(e);
}
}
/**
* Modifies a pet previously persisted in the system. The pet will be
* retrieved by the provided id and its current name and specie will be
* replaced with the provided.
*
* @param pet a {@link Pet} entity with the new data.
* @throws DAOException if an error happens while modifying the new pet.
* @throws IllegalArgumentException if the pet is {@code null}.
*/
public void modify(Pet pet)
throws DAOException, IllegalArgumentException
{
if (pet == null)
{
throw new IllegalArgumentException("pet can't be null");
}
try (Connection conn = this.getConnection())
{
final String query = "UPDATE pet SET nombre=?, especie=? WHERE id=?";
try (PreparedStatement statement = conn.prepareStatement(query)) {
statement.setString(1, pet.getNombre());
statement.setString(2, pet.getEspecie());
statement.setInt(3, pet.getId());
if (statement.executeUpdate() != 1) {
throw new IllegalArgumentException("name and specie can't be null");
}
}
} catch (SQLException e) {
LOG.log(Level.SEVERE, "Error modifying a pet", e);
throw new DAOException();
}
}
/**
* Removes a persisted pet from the system.
*
* @param id identifier of the pet to be deleted.
* @throws DAOException if an error happens while deleting the pet.
* @throws IllegalArgumentException if the provided id does not corresponds
* with any persisted pet.
*/
public void delete(int id)
throws DAOException, IllegalArgumentException
{
try (final Connection conn = this.getConnection()) {
final String query = "DELETE FROM pet WHERE id=?";
try (final PreparedStatement statement = conn.prepareStatement(query))
{
statement.setInt(1, id);
if (statement.executeUpdate() != 1) {
throw new IllegalArgumentException("Invalid id");
}
}
} catch (SQLException e) {
LOG.log(Level.SEVERE, "Error deleting a pet", e);
throw new DAOException(e);
}
}
private Pet rowToEntity(ResultSet row) throws SQLException {
return new Pet(
row.getInt("id"),
row.getInt("personId"),
row.getString("nombre"),
row.getString("especie")
);
}
}
package es.uvigo.esei.daa.entities;
import static java.util.Objects.requireNonNull;
/**
* Entidad que representa Mascota
*
* Created by Luis Francisco on 23/02/2017.
*/
public class Pet
{
private int id;
private int personId;
private String nombre;
private String especie;
// Constructor needed for the JSON conversion
Pet() {}
/**
* Constructs a new instance of {@link Pet}.
*
* @param id identificador de la mascota.
* @param nombre nombre de la mascota.
* @param especie tipo de especie de la mascota.
*/
public Pet(int id, int personId, String nombre, String especie)
{
this.personId = personId;
this.id = id;
this.setNombre(nombre);
this.setEspecie(especie);
}
/**
* Devuelve el identificador de la mascota.
*
* @return identificador de la mascota.
*/
public int getId()
{
return id;
}
/**
* Devuelve el identificador del dueño de la mascota.
*
* @return identificador del dueño de la mascota.
*/
public int getPersonId()
{
return personId;
}
/**
* Devuelve el nombre de la mascota.
*
* @return nombre de la mascota.
*/
public String getNombre()
{
return nombre;
}
/**
* Modifica el nombre de la mascota.
*
* @param nombre nuevo nombre de la mascota.
* @throws NullPointerException if the {@code name} is {@code null}.
*/
public void setNombre(String nombre)
{
this.nombre = requireNonNull(nombre, "Name can't be null");
}
/**
* Devuelve el especie de la mascota.
*
* @return especie de la mascota.
*/
public String getEspecie()
{
return especie;
}
/**
* Modifica la especie de la mascota.
*
* @param especie especie de la mascota.
* @throws NullPointerException if the {@code name} is {@code null}.
*/
public void setEspecie(String especie)
{
this.especie = requireNonNull(especie, "Specie can't be null");
}
//Faltan los override, preguntarle a Martín
}
package es.uvigo.esei.daa.rest;
import es.uvigo.esei.daa.dao.DAOException;
import es.uvigo.esei.daa.dao.PetDAO;
import es.uvigo.esei.daa.entities.Pet;
import javax.ws.rs.*;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
* REST resource for managing pet.
*
* @author Miguel Reboiro Jato.
*/
@Path("/pet")
@Produces(MediaType.APPLICATION_JSON)
public class PetResource {
private final static Logger LOG = Logger.getLogger(PetResource.class.getName());
private final PetDAO dao;
/**
* Constructs a new instance of {@link PetResource}.
*/
public PetResource() {
this(new PetDAO());
}
// Needed for testing purposes
PetResource(PetDAO dao) {
this.dao = dao;
}
/**
* Returns a pet with the provided identifier.
*
* @param id the identifier of the pet to retrieve.
* @return a 200 OK response with a pet that has the provided identifier.
* If the identifier does not corresponds with any user, a 400 Bad Request
* response with an error message will be returned. If an error happens
* while retrieving the list, a 500 Internal Server Error response with an
* error message will be returned.
*/
@GET
@Path("/{id}")
public Response get(
@PathParam("id") int id
) {
try {
final Pet pet = this.dao.get(id);
return Response.ok(pet).build();
} catch (IllegalArgumentException iae) {
LOG.log(Level.FINE, "Invalid pet id in get method", iae);
return Response.status(Response.Status.BAD_REQUEST)
.entity(iae.getMessage())
.build();
} catch (DAOException e) {
LOG.log(Level.SEVERE, "Error getting a pet", e);
return Response.serverError()
.entity(e.getMessage())
.build();
}
}
/**
* Returns the complete list of pet stored in the system.
*
* @return a 200 OK response with the complete list of pet stored in the
* system. If an error happens while retrieving the list, a 500 Internal
* Server Error response with an error message will be returned.
*/
@GET
public Response list(
) {
try {
return Response.ok(this.dao.list()).build();
} catch (DAOException e) {
LOG.log(Level.SEVERE, "Error listing pet", e);
return Response.serverError().entity(e.getMessage()).build();
}
}
/**
* Creates a new pet in the system.
*
* @param name the name of the new pet.
* @param surname the surname of the new pet.
* @return a 200 OK response with a pet that has been created. If the
* name or the surname are not provided, a 400 Bad Request response with an
* error message will be returned. If an error happens while retrieving the
* list, a 500 Internal Server Error response with an error message will be
* returned.
*/
@POST
@Path("/{personId}")
public Response add(
@PathParam("personId") int id,
@FormParam("nombre") String nombre,
@FormParam("especie") String especie
) {
try {
final Pet newpet = this.dao.add(id, nombre, especie);
return Response.ok(newpet).build();
} catch (IllegalArgumentException iae) {
LOG.log(Level.FINE, "Invalid pet id in add method", iae);
return Response.status(Response.Status.BAD_REQUEST)
.entity(iae.getMessage())
.build();
} catch (DAOException e) {
LOG.log(Level.SEVERE, "Error adding a pet", e);
return Response.serverError()
.entity(e.getMessage())
.build();
}
}
/**
* Modifies the data of a pet.
*
* @param id identifier of the pet to modify.
* @param name the new name of the pet.
* @param surname the new surname of the pet.
* @return a 200 OK response with a pet that has been modified. If the
* identifier does not corresponds with any user or the name or surname are
* not provided, a 400 Bad Request response with an error message will be
* returned. If an error happens while retrieving the list, a 500 Internal
* Server Error response with an error message will be returned.
*/
@PUT
@Path("/{id}")
public Response modify(
@PathParam("id") int id,
@FormParam("nombre") String name,
@FormParam("especie") String surname
) {
try {
final Pet modifiedpet = new Pet(id, 0, name, surname);
this.dao.modify(modifiedpet);
return Response.ok(modifiedpet).build();
} catch (NullPointerException npe) {
final String message = String.format("Invalid data for pet (name: %s, surname: %s)", name, surname);
LOG.log(Level.FINE, message);
return Response.status(Response.Status.BAD_REQUEST)
.entity(message)
.build();
} catch (IllegalArgumentException iae) {
LOG.log(Level.FINE, "Invalid pet id in modify method", iae);
return Response.status(Response.Status.BAD_REQUEST)
.entity(iae.getMessage())
.build();
} catch (DAOException e) {
LOG.log(Level.SEVERE, "Error modifying a pet", e);
return Response.serverError()
.entity(e.getMessage())
.build();
}
}
/**
* Deletes a pet from the system.
*
* @param id the identifier of the pet to be deleted.
* @return a 200 OK response with the identifier of the pet that has
* been deleted. If the identifier does not corresponds with any user, a 400
* Bad Request response with an error message will be returned. If an error
* happens while retrieving the list, a 500 Internal Server Error response
* with an error message will be returned.
*/
@DELETE
@Path("/{id}")
public Response delete(
@PathParam("id") int id
) {
try {
this.dao.delete(id);
return Response.ok(id).build();
} catch (IllegalArgumentException iae) {
LOG.log(Level.FINE, "Invalid pet id in delete method", iae);
return Response.status(Response.Status.BAD_REQUEST)
.entity(iae.getMessage())
.build();
} catch (DAOException e) {
LOG.log(Level.SEVERE, "Error deleting a pet", e);
return Response.serverError()
.entity(e.getMessage())
.build();
}
}
}
<?xml version="1.0" encoding="UTF-8"?>
<module type="JAVA_MODULE" version="4">
<component name="FacetManager">
<facet type="web" name="Web">
<configuration>
<descriptors>
<deploymentDescriptor name="web.xml" url="file://$MODULE_DIR$/webapp/WEB-INF/web.xml" />
</descriptors>
<webroots>
<root url="file://$MODULE_DIR$/webapp" relative="/" />
</webroots>
</configuration>
</facet>
</component>
<component name="NewModuleRootManager" inherit-compiler-output="true">
<exclude-output />
<content url="file://$MODULE_DIR$">
<sourceFolder url="file://$MODULE_DIR$/java" isTestSource="false" />
</content>
<orderEntry type="inheritedJdk" />
<orderEntry type="sourceFolder" forTests="false" />
</component>
</module>
\ No newline at end of file
var PetDAO = (function() {
var resourcePath = "rest/pet/";
var requestByAjax = function(data, done, fail, always) {
done = typeof done !== 'undefined' ? done : function() {};
fail = typeof fail !== 'undefined' ? fail : function() {};
always = typeof always !== 'undefined' ? always : function() {};
$.ajax(data)
.done(done)
.fail(fail)
.always(always);
};
function PetDAO() {
this.listPet = function(done, fail, always) {
requestByAjax({
url: resourcePath,
type: 'GET'
}, done, fail, always);
};
this.getUser = function(done, fail, always) {
requestByAjax({
url: resourcePath,
type: 'GET'
}, done, fail, always);
};
this.addPet = function(pet, done, fail, always) {
requestByAjax({
url: resourcePath + pet.personId,
type: 'POST',
data: pet
}, done, fail, always);
};
this.modifyPet = function(pet, done, fail, always) {
requestByAjax({
url: resourcePath + pet.id,
type: 'PUT',
data: pet
}, done, fail, always);
};
this.deletePet = function(id, done, fail, always) {
requestByAjax({
url: resourcePath + id,
type: 'DELETE',
}, done, fail, always);
};
}
return PetDAO;
})();
\ No newline at end of file
......@@ -148,6 +148,9 @@ var PeopleView = (function() {
<td>\
<a class="delete" href="#">Delete</a>\
</td>\
<td>\
<a class="pet" href="#">Pet</a>\
</td>\
</tr>';
}
......@@ -171,6 +174,12 @@ var PeopleView = (function() {
);
}
});
//pasamos la id de persona
$('#person-' + person.id + ' a.pet').click(function() {
location.href="pet.html?"+person.id;
});
}
var appendToTable = function(person) {
......
var PetView = (function() {
var dao;
// Referencia a this que permite acceder a las funciones públicas desde las funciones de jQuery.
var self;
var url = window.location.href;
var personId;
var formId = 'pet-form';
var listId = 'pet-list';
var formQuery = '#' + formId;
var listQuery = '#' + listId;
function PetView(petDao, formContainerId, listContainerId) {
dao = petDao;
self = this;
personId= url.substring(url.lastIndexOf('?') + 1);
insertPetForm($('#' + formContainerId));
insertPetList($('#' + listContainerId));
this.init = function() {
var pet = self.getPetInForm();
dao.listPet(function(pet)
{
$.each(pet, function(key, pet) {
appendToTable(pet);
});
});
// La acción por defecto de enviar formulario (submit) se sobreescribe
// para que el envío sea a través de AJAX
$(formQuery).submit(function(event) {
var pet = self.getPetInForm();
if (self.isEditing()) {
dao.modifyPet(pet,
function(pet) {
$('#pet-' + pet.id + ' td.personId').text(pet.personId);
$('#pet-' + pet.id + ' td.nombre').text(pet.nombre);
$('#pet-' + pet.id + ' td.especie').text(pet.especie);
self.resetForm();
},
showErrorMessage,
self.enableForm
);
} else {
dao.addPet(pet,
function(pet) {
appendToTable(pet);
self.resetForm();
},
showErrorMessage,
self.enableForm
);
}
return false;
});
$('#btnClear').click(this.resetForm);
};
this.getPetInForm = function() {
var form = $(formQuery);
return {
'id': form.find('input[name="id"]').val(),
'personId': form.find('input[name="personId"]').val(),
'nombre': form.find('input[name="nombre"]').val(),
'especie': form.find('input[name="especie"]').val()
};
};
this.getPetInRow = function(id) {
var row = $('#pet-' + id);
if (row !== undefined) {
return {
'id': id,
'nombre': row.find('td.nombre').text(),
'especie': row.find('td.especie').text()
};
} else {
return undefined;
}
};
this.editpet = function(id) {
var row = $('#pet-' + id);
console.log(row);
if (row !== undefined) {
var form = $(formQuery);
console.log(form);
console.log(row.find('td.nombre').text());
console.log(row.find('td.especie').text());
form.find('input[name="id"]').val(id);
form.find('input[name="nombre"]').val(row.find('td.nombre').text());
form.find('input[name="especie"]').val(row.find('td.especie').text());
}
}
this.isEditing = function() {
return $(formQuery + ' input[name="id"]').val() != "";
};
this.disableForm = function() {
$(formQuery + ' input').prop('disabled', true);
};
this.enableForm = function() {
$(formQuery + ' input').prop('disabled', false);
};
this.resetForm = function() {
$(formQuery)[0].reset();
$(formQuery + ' input[name="id"]').val('');
$('#btnSubmit').val('Crear');
};
}
var insertPetList = function(parent) {
parent.append(
'<table id="' + listId + '">\
<tr>\
<th>Nombre</th>\
<th>Especie</th>\
<th></th>\
<th></th>\
</tr>\
</table>'
);
}
var insertPetForm = function(parent) {
parent.append(
'<form id="' + formId + '">\
<input name="id" type="hidden" value=""/>\
<input name="personId" type="hidden" value="'+ personId +' "/>\
<input name="nombre" type="text" value="" />\
<input name="especie" type="text" value=""/>\
<input id="btnSubmit" type="submit" value="Create"/>\
<input id="btnClear" type="reset" value="Limpiar"/>\
</form>'
);
}
var createpetRow = function(pet) {
if(pet.personId == personId) {
return '<tr id="pet-' + pet.id + '">\
<td class="nombre">' + pet.nombre + '</td>\
<td class="especie">' + pet.especie + '</td>\
<td>\
<a class="edit" href="#">Edit</a>\
</td>\
<td>\
<a class="delete" href="#">Delete</a>\
</td>\
</td>';
}
}
var showErrorMessage = function(jqxhr, textStatus, error) {
alert(textStatus + ": " + error);
}
var addRowListeners = function(pet) {
$('#pet-' + pet.id + ' a.edit').click(function() {
self.editpet(pet.id);
$('input#btnSubmit').val('Modificar');
});
$('#pet-' + pet.id + ' a.delete').click(function() {
if (confirm('Está a punto de eliminar a una mascota. ¿Está seguro de que desea continuar?')) {
dao.deletePet(pet.id,
function() {
$('tr#pet-' + pet.id).remove();
},
showErrorMessage
);
}
});
}
var appendToTable = function(pet) {
$(listQuery + ' > tbody:last')
.append(createpetRow(pet));
addRowListeners(pet);
}
return PetView;
})();
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>DAA Example</title>
</head>
<body>
<div id="pet-container">
<h1>Pet</h1>
<a id="#logout" href="logout">Logout</a>
<a id="#home" href="main.html">Home</a>
</div>
<script type="text/javascript" src="http://code.jquery.com/jquery-2.2.0.min.js"></script>
<script type="text/javascript" src="js/dao/pet.js"></script>
<script type="text/javascript" src="js/view/pet.js"></script>
<script type="text/javascript">
$(document).ready(function() {
var view = new PetView(new PetDAO(), 'pet-container', 'pet-container');
view.init();
});
</script>
</body>
</html>
\ No newline at end of file
<?xml version="1.0" encoding="UTF-8"?>
<module type="JAVA_MODULE" version="4">
<component name="NewModuleRootManager" inherit-compiler-output="true">
<exclude-output />
<content url="file://$MODULE_DIR$">
<sourceFolder url="file://$MODULE_DIR$/java" isTestSource="true" />
</content>
<orderEntry type="inheritedJdk" />
<orderEntry type="sourceFolder" forTests="false" />
<orderEntry type="module" module-name="main" />
</component>
</module>
\ No newline at end of file
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