3
\$\begingroup\$

I am creating introduction app to java ee and APIs of java ee and i want know if my code is ok (like its working but if it could be done better) and what should i avoid in future

package sk.studenthosting.simec.API;

import javax.ws.rs.ApplicationPath;
import javax.ws.rs.core.Application;

@ApplicationPath("/rest")
public class Rest extends Application {

}
package sk.studenthosting.simec.API;


import sk.studenthosting.simec.dao.TaskDao;
import sk.studenthosting.simec.dao.TaskDaoJpa;
import sk.studenthosting.simec.service.TaskService;

import javax.ejb.EJB;
import javax.ws.rs.*;
import javax.ws.rs.core.MediaType;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.List;

@Path("/rest")
public class Rest_api {
    @EJB
    private TaskService service;

    @EJB
    private TaskDao notes;

    @GET
    @Produces(MediaType.TEXT_HTML)
    public String Index(){
        List allNotes = notes.getAllNotes();
        return (service.createTable(allNotes));
    }

    @POST
    @Consumes(MediaType.APPLICATION_FORM_URLENCODED)
    @Produces(MediaType.TEXT_HTML)
    public String createNote(@FormParam("Note") String Note,
                             @QueryParam("Note") String Note2) {
        List allNotes = notes.getAllNotes();
        if (Note == null){Note = Note2;}
        if (Note.equals("") || Note == null) {
            return (service.createTable(allNotes)) + "<h1>Note field cannot be empty</h1>";
        } else {
                TaskDaoJpa addNote = new TaskDaoJpa();
                Timestamp timestamp = new Timestamp(System.currentTimeMillis());
                addNote.setTime(timestamp);
                addNote.setNote(Note);
                notes.addNote(addNote);
                return (service.createTable(allNotes)) + "<p>Note was successfully created</p>";
            }
    }


    @DELETE
    @Produces(MediaType.TEXT_HTML)
    public String deleteNote(@QueryParam("Id") int Id) {
        List allNotes = notes.getAllNotes();
        try {
            notes.deleteNote(Id);
        } catch (Exception e) {
            return (service.createTable(allNotes))+"<h1>Note with this Id was not found</h1>";
        }
        return (service.createTable(allNotes))+"<h1>Note was successfully deleted</h1>";
}


    @PUT
    @Produces(MediaType.TEXT_HTML)
    public String editNote(@QueryParam("Id") int Id,
                           @QueryParam("Note") String Note) {
        List allNotes = notes.getAllNotes();
        try {
            TaskDaoJpa note = notes.getNote(Id);
            note.setNote(Note);
            notes.editNote(note);
        } catch (Exception e) {
            return (service.createTable(allNotes))+"<h1>Note with this Id was not found</h1>";
        }
        return (service.createTable(allNotes))+"<h1>Note was successfully edited</h1>";
    }

    @GET
    @Path("/{Id}")
    @Produces(MediaType.TEXT_HTML)
    public String gettingId(@PathParam("Id") String Ids,
                            @QueryParam("Id") String Ids2){
        List allNotes = notes.getAllNotes();
        if (Ids == null){Ids = Ids2;}
        try {
            int Id = Integer.parseInt(Ids);
            TaskDaoJpa note = notes.getNote(Id);
            ArrayList<TaskDaoJpa> myList = new ArrayList<>();
            myList.add(note);
            return (service.createTable(myList));
        } catch (NumberFormatException e) {
            return (service.createTable(allNotes)) + "<h1>In order to get note you have to insert Id(number)</h1>";

        } catch (Exception ex){
            return (service.createTable(allNotes)) + "<h1>Note with this number doesnt exist</h1>";
        }
    }

}

i know its not best to create only html

package sk.studenthosting.simec.dao;


import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import java.util.List;

@Stateless
public class TaskDao {
    @PersistenceContext
    private EntityManager em;

    public void addNote(TaskDaoJpa note) {
        em.persist(note);
    }

    public void editNote(TaskDaoJpa note) {
        em.merge(note);
    }

    public void deleteNote(int noteId) {
        em.remove(getNote(noteId));
    }

    public TaskDaoJpa getNote(int noteId) {
        return em.find(TaskDaoJpa.class, noteId);
    }

    public List getAllNotes() {
        return em.createNamedQuery("Notes.getAll").getResultList();
    }

}

i will eventually add text filter and filter for more than one Id

package sk.studenthosting.simec.dao;

import javax.persistence.*;
import java.io.Serializable;
import java.sql.Timestamp;

@Entity
@Table(name = "notes")
@NamedQuery(name = "Notes.getAll", query = "SELECT t From TaskDaoJpa t")
public class TaskDaoJpa implements Serializable {
    private int noteId;
    private String note;
    private Timestamp time;

    @Id
    @GeneratedValue(strategy=GenerationType.IDENTITY)
    @Column(name = "noteId", nullable = false, updatable = false)
    public int getNoteId() {
        return noteId;
    }

    protected void setNoteId(int noteId) {
        this.noteId = noteId;
    }

    @Basic
    @Column(name = "note", nullable = false, length = -1)
    public String getNote() {
        return note;
    }

    public void setNote(String note) {
        this.note = note;
    }

    @Basic
    @Column(name = "time", nullable = true)
    public Timestamp getTime() {
        return time;
    }

    public void setTime(Timestamp time) {
        this.time = time;
    }

    public TaskDaoJpa(int noteId, String note, Timestamp time) {
        this.noteId = noteId;
        this.note = note;
        this.time = time;
    }

    public TaskDaoJpa(){}
}
package sk.studenthosting.simec.service;

import sk.studenthosting.simec.dao.TaskDaoJpa;

import javax.ejb.Local;
import java.util.List;

@Local
public interface TaskService {

    String createTable(List<TaskDaoJpa> notes);

}
package sk.studenthosting.simec.service;

import sk.studenthosting.simec.dao.TaskDaoJpa;

import javax.ejb.Stateless;
import java.util.List;

@Stateless
public class TaskServiceEjb implements TaskService {

    public TaskServiceEjb() {
    }


    @Override
    public String createTable(List<TaskDaoJpa> notes) {
        StringBuilder tableTemp = new StringBuilder();
        for (Object noteInfo : notes) {

            TaskDaoJpa temporary = (TaskDaoJpa) noteInfo;
            String betterTime = temporary.getTime().toString().replaceAll("\\.\\d+", "");
            tableTemp.append("<tr><td>");
            tableTemp.append(temporary.getNoteId());
            tableTemp.append("</td><td>");
            tableTemp.append(betterTime);
            tableTemp.append("</td><td>");
            tableTemp.append(temporary.getNote());
            tableTemp.append("</td></tr>");
        }
        String table = " <table border='1'><th>id</th><th>time</th><th>note</th>" + tableTemp + "</table><form action='' method='GET'><input type='text' style='width: 3em;' placeholder='Id' name='Id'/>" +
                "<input type='text' placeholder='Note' name='Note'/><br/>" +
                "<input type='submit' formmethod='POST' value='Pridat'/>" +
                "<input type='submit' value='Vyhladat'/>" +
                "<input type='submit' value='Delete'/></form>";
        return table;
    }

}

i was also thinking about button i created(Delete button) could be in post method and in jax rs i would create, thanks to java, http Delete request and and sent it again to page, does it work or is there a lot easier method ? Thanks everyone who will try to help me.

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.