forked from howtoprogram/Java-Examples
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathBookRepositoryImplJersey.java
More file actions
69 lines (53 loc) · 2.22 KB
/
Copy pathBookRepositoryImplJersey.java
File metadata and controls
69 lines (53 loc) · 2.22 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
package com.howtoprogram.repository;
import javax.ws.rs.client.Client;
import javax.ws.rs.client.ClientBuilder;
import javax.ws.rs.client.Entity;
import javax.ws.rs.client.WebTarget;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import com.howtoprogram.domain.Book;
public class BookRepositoryImplJersey {
private static final String URI_BOOK = "http://localhost:8080/v1/books";
public void deleteBook(Long id) {
Client client = ClientBuilder.newClient();
WebTarget target = client.target(URI_BOOK).path(String.valueOf(id));
Response response = target.request().delete();
System.out.println("Status code:" + response.getStatus());
}
public static void main(String[] args) throws Exception {
BookRepositoryImplJersey bookRepository = new BookRepositoryImplJersey();
// Getting the first book from the RESTful service
Book book = bookRepository.getAllBooks()[0];
bookRepository.deleteBook(book.getId());
}
public Book updateBook(Book book) throws Exception {
Client client = ClientBuilder.newClient();
WebTarget target = client.target(URI_BOOK).path(String.valueOf(book.getId()));
Response response = target.request(MediaType.APPLICATION_JSON_TYPE)
.put(Entity.entity(book, MediaType.APPLICATION_JSON_TYPE));
int status = response.getStatus();
System.out.println("Status code: " + status);
Book createdBook = response.readEntity(Book.class);
return createdBook;
}
public Book createBook(Book book) throws Exception {
Client client = ClientBuilder.newClient();
Response response = client.target(URI_BOOK).request()
.post(Entity.entity(book, MediaType.APPLICATION_JSON_TYPE));
int status = response.getStatus();
System.out.println("Status code: " + status);
Book createdBook = response.readEntity(Book.class);
return createdBook;
}
public Book[] getAllBooks() throws Exception {
Client client = ClientBuilder.newClient();
Response response = client.target(URI_BOOK).request().get();
int status = response.getStatus();
System.out.println("Status code: " + status);
Book[] books = response.readEntity(Book[].class);
return books;
}
public Book findBookById(Long id) {
return null;
}
}