Ravi Srinivasan
2018-09-10 aaf094af7ecf98e07e31a231fdab871b25961bd1
commit | author | age
aaf094 1 package com.redhat.training.services;
RS 2
3 import java.time.LocalDateTime;
4 import java.time.format.DateTimeFormatter;
5 import java.util.List;
6
7 import javax.ejb.EJBException;
8 import javax.ejb.Stateless;
9 import javax.persistence.EntityManager;
10 import javax.persistence.PersistenceContext;
11 import javax.persistence.TypedQuery;
12
13 import com.redhat.training.model.Person;
14
15 @Stateless
16
17 public class PersonService {
18     //TODO: obtain an EntityManager instance using @PersistenceContext 
19     @PersistenceContext(unitName="hello")
20     private EntityManager entityManager;
21
22     // Simple non-RESTy method for JSF bean invocation
23     public String hello(String name) {
24         try {
25                 // let's grab the current date and time on the server
26                 LocalDateTime today = LocalDateTime.now();
27
28                 // format it nicely for on-screen display
29                 DateTimeFormatter format = DateTimeFormatter.ofPattern("MMM dd yyyy hh:mm:ss a");
30                 String fdate = today.format(format);
31
32                 // Create a new Person object and persist to database
33                 Person p = new Person();
34                 p.setName(name);
35                 // call persist() method of entity manager to save the data                                                                
36                 entityManager.persist(p);
37
38                 // respond back with Hello and convert the name to UPPERCASE. Also, send the
39                 // current time on the server.
40                 return "Hello " + name.toUpperCase() + "!. " + "Time on the server is: " + fdate;
41         } catch (Exception e) {
42             throw new EJBException(e);
43         }
44     }
45
46     // TODO:add public String getPerson(Long id) method here to fetch result 
47     //by Person id using find() method 
48
49     public String getPerson(Long id) {
50            
51         return entityManager.find(Person.class, id).getPersonName();
52     }
53
54     // Get all Person objects in the Database
55     public List<Person> getAllPersons() {
56         TypedQuery<Person> query = entityManager.createQuery("SELECT p FROM Person p", Person.class);
57         List<Person> persons = query.getResultList();
58
59         return persons;
60     }
61
62 }