Skip to content

Instantly share code, notes, and snippets.

@alejandro-du
Last active July 4, 2019 17:17
Show Gist options
  • Save alejandro-du/94749cfe0d5bb885e5a4b17f13cbf9fb to your computer and use it in GitHub Desktop.
Save alejandro-du/94749cfe0d5bb885e5a4b17f13cbf9fb to your computer and use it in GitHub Desktop.

Workshop sobre Vaadin en Español

Comentario.java

package com.example.backend;

import java.time.LocalDateTime;
import java.util.Objects;

public class Comentario {

    private Integer id;

    private LocalDateTime fechaCreacion;

    private String texto;

    public Comentario() {
        this(null);
    }

    public Comentario(String texto) {
        this.fechaCreacion = LocalDateTime.now();
        this.texto = texto;
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;
        Comentario that = (Comentario) o;
        return Objects.equals(id, that.id);
    }

    @Override
    public int hashCode() {
        return Objects.hash(id);
    }

    public Integer getId() {
        return id;
    }

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

    public LocalDateTime getFechaCreacion() {
        return fechaCreacion;
    }

    public void setFechaCreacion(LocalDateTime fechaCreacion) {
        this.fechaCreacion = fechaCreacion;
    }

    public String getTexto() {
        return texto;
    }

    public void setTexto(String texto) {
        this.texto = texto;
    }

}

ComentarioService.java

package com.example.backend;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.IntStream;

public class ComentarioService {

    private static AtomicInteger nextId = new AtomicInteger(0);
    private static List<Comentario> comentarios = new ArrayList<>();

    static {
        IntStream.rangeClosed(1, 5)
                .mapToObj(i -> new Comentario("Comentario " + i))
                .forEach(ComentarioService::save);
    }

    public static List<Comentario> findAll() {
        return Collections.unmodifiableList(comentarios);
    }

    public static synchronized Comentario save(Comentario comentario) {
        if (comentario.getId() == null) {
            comentario.setId(nextId.incrementAndGet());
        } else {
            comentarios.remove(comentario);
        }

        comentarios.add(comentario);
        return comentario;
    }

    public static synchronized void delete(Comentario comentario) {
        comentarios.remove(comentario);
    }

}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment