Commit 499f59e6 authored by Michele Fiori's avatar Michele Fiori

Updated REST part with Spring

parent 35fb943b
plugins {
id "java"
id "war" // for REST
id 'java'
id 'org.springframework.boot' version '2.4.0'
id 'io.spring.dependency-management' version '1.0.15.RELEASE'
}
group 'org.example'
version '1.0-SNAPSHOT'
group = 'org.example'
version = '1.0-SNAPSHOT'
sourceCompatibility = '1.8'
repositories {
mavenCentral()
}
dependencies {
testImplementation 'org.junit.jupiter:junit-jupiter-api:5.6.0'
testRuntimeOnly 'org.junit.jupiter:junit-jupiter-engine'
compile 'com.google.code.gson:gson:2.7'
// REST Dependencies
// https://mvnrepository.com/artifact/org.codehaus.jackson/jackson-core-asl
compile group: 'org.codehaus.jackson', name: 'jackson-core-asl', version: '1.9.2'
// https://mvnrepository.com/artifact/org.codehaus.jackson/jackson-jaxrs
compile group: 'org.codehaus.jackson', name: 'jackson-jaxrs', version: '1.9.2'
// https://mvnrepository.com/artifact/org.codehaus.jackson/jackson-mapper-asl
compile group: 'org.codehaus.jackson', name: 'jackson-mapper-asl', version: '1.9.2'
// https://mvnrepository.com/artifact/org.codehaus.jackson/jackson-xc
compile group: 'org.codehaus.jackson', name: 'jackson-xc', version: '1.9.2'
// https://mvnrepository.com/artifact/com.sun.jersey/jersey-client
compile group: 'com.sun.jersey', name: 'jersey-client', version: '1.19.1'
// https://mvnrepository.com/artifact/com.sun.jersey/jersey-core
compile group: 'com.sun.jersey', name: 'jersey-core', version: '1.19.1'
// https://mvnrepository.com/artifact/com.sun.jersey/jersey-json
compile group: 'com.sun.jersey', name: 'jersey-json', version: '1.19.1'
// https://mvnrepository.com/artifact/com.sun.jersey/jersey-server
compile group: 'com.sun.jersey', name: 'jersey-server', version: '1.19.1'
// https://mvnrepository.com/artifact/com.sun.jersey/jersey-servlet
compile group: 'com.sun.jersey', name: 'jersey-servlet', version: '1.19.1'
// https://mvnrepository.com/artifact/org.codehaus.jettison/jettison
compile group: 'org.codehaus.jettison', name: 'jettison', version: '1.1'
// https://mvnrepository.com/artifact/javax.ws.rs/jsr311-api
compile group: 'javax.ws.rs', name: 'jsr311-api', version: '1.1.1'
// https://mvnrepository.com/artifact/com.sun.jersey/jersey-server
compile group: 'com.sun.jersey', name: 'jersey-server', version: '1.2'
// MQTT Dependencies
// https://mvnrepository.com/artifact/org.eclipse.paho/org.eclipse.paho.client.mqttv3
compile group: 'org.eclipse.paho', name: 'org.eclipse.paho.client.mqttv3', version: '1.2.5'
// Spring Web for REST
implementation 'org.springframework.boot:spring-boot-starter-web'
// MQTT
implementation 'org.eclipse.paho:org.eclipse.paho.client.mqttv3:1.2.5'
}
test {
useJUnitPlatform()
}
REST/services/HelloWorld.java
REST.services.HelloWorld
REST/beans/User.java
REST.beans.User
REST/services/UsersService.java
REST.services.UsersService
REST/StartServer.java
REST.StartServer
REST/beans/Users.java
REST.beans.Users
spring/User.java
spring.User
spring/UsersController.java
spring.UsersController
spring/Application.java
spring.Application
spring/UserService.java
spring.UserService
MQTT/PubExample.java
MQTT.PubExample
MQTT/SubExample.java
MQTT.SubExample
MQTT.SubExample$1
REST/Client/ClientExample.java
REST.Client.ClientExample
MQTT/PubExampleCallback.java
MQTT.PubExampleCallback
MQTT.PubExampleCallback$1
MQTT/PubSubExample.java
MQTT.PubSubExample
MQTT.PubSubExample$1
spring/ClientExample.java
spring.ClientExample
package REST.Client;
import REST.beans.User;
import REST.beans.Users;
import com.google.gson.Gson;
import com.sun.jersey.api.client.Client;
import com.sun.jersey.api.client.ClientHandlerException;
import com.sun.jersey.api.client.ClientResponse;
import com.sun.jersey.api.client.WebResource;
public class ClientExample {
public static void main(String args[]){
Client client = Client.create();
String serverAddress = "http://localhost:1337";
ClientResponse clientResponse = null;
// POST EXAMPLE
String postPath = "/users/add";
User user = new User("John","Cena");
clientResponse = postRequest(client,serverAddress+postPath,user);
System.out.println(clientResponse.toString());
//GET REQUEST #1
String getPath = "/users";
clientResponse = getRequest(client,serverAddress+getPath);
System.out.println(clientResponse.toString());
Users users = clientResponse.getEntity(Users.class);
System.out.println("Users List");
for (User u : users.getUserslist()){
System.out.println("Name: " + u.getName() + " Surname: " + u.getSurname());
}
//GET REQUEST #2
String getUserPath = "/users/get/john";
clientResponse = getRequest(client,serverAddress+getUserPath);
System.out.println(clientResponse.toString());
User userResponse = clientResponse.getEntity(User.class);
System.out.println("Name: " + userResponse.getName() + " Surname: " + userResponse.getSurname());
}
public static ClientResponse postRequest(Client client, String url, User u){
WebResource webResource = client.resource(url);
String input = new Gson().toJson(u);
try {
return webResource.type("application/json").post(ClientResponse.class, input);
} catch (ClientHandlerException e) {
System.out.println("Server not available");
return null;
}
}
public static ClientResponse getRequest(Client client, String url){
WebResource webResource = client.resource(url);
try {
return webResource.type("application/json").get(ClientResponse.class);
} catch (ClientHandlerException e) {
System.out.println("Server not available");
return null;
}
}
}
package REST;
import com.sun.jersey.api.container.httpserver.HttpServerFactory;
import com.sun.net.httpserver.HttpServer;
import java.io.IOException;
public class StartServer {
private static final String HOST = "localhost";
private static final int PORT = 1337;
public static void main(String[] args) throws IOException {
HttpServer server = HttpServerFactory.create("http://"+HOST+":"+PORT+"/");
server.start();
System.out.println("Server running!");
System.out.println("Server started on: http://"+HOST+":"+PORT);
System.out.println("Hit return to stop...");
System.in.read();
System.out.println("Stopping server");
server.stop(0);
System.out.println("Server stopped");
}
}
package REST.beans;
import javax.xml.bind.annotation.XmlRootElement;
@XmlRootElement
public class User {
private String name;
private String surname;
public User(){}
public User(String name, String surname) {
this.name = name;
this.surname = surname;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getSurname() {
return surname;
}
public void setSurname(String surname) {
this.surname = surname;
}
}
\ No newline at end of file
package REST.beans;
import java.util.ArrayList;
import java.util.List;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
@XmlRootElement
@XmlAccessorType (XmlAccessType.FIELD)
public class Users {
@XmlElement(name="my_users")
private List<User> userslist;
private static Users instance;
private Users() {
userslist = new ArrayList<User>();
}
//Singleton
public synchronized static Users getInstance(){
if(instance==null)
instance = new Users();
return instance;
}
public synchronized List<User> getUserslist() {
return new ArrayList<>(userslist);
}
public synchronized void setUserslist(List<User> userslist) {
this.userslist = userslist;
}
public synchronized void add(User u){
userslist.add(u);
}
public User getByName(String name){
List<User> usersCopy = getUserslist();
for(User u: usersCopy)
if(u.getName().toLowerCase().equals(name.toLowerCase()))
return u;
return null;
}
}
\ No newline at end of file
package REST.services;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
@Path("/helloworld")
public class HelloWorld {
@GET
@Produces("text/plain")
public String helloWorld(){
return "Hello world!";
}
@GET
@Path("{name}")
@Produces({"text/plain"})
public String helloWorldName(@PathParam("name") String name){
return "Hello, "+name+"!";
}
@GET
@Produces("application/json")
public String helloWorld2(){
return "{\"message\": \"helloWorld\"}";
}
@Path("inner")
@GET
@Produces("text/plain")
public String innerHello(){
return "Inner Hello!";
}
}
package REST.services;
import REST.beans.User;
import REST.beans.Users;
import javax.ws.rs.*;
import javax.ws.rs.core.Response;
@Path("users")
public class UsersService {
//restituisce la lista di utenti
@GET
@Produces({"application/json", "application/xml"})
public Response getUsersList(){
return Response.ok(Users.getInstance()).build();
}
//permette di inserire un utente (nome e cognome)
@Path("add")
@POST
@Consumes({"application/json", "application/xml"})
public Response addUser(User u){
Users.getInstance().add(u);
return Response.ok().build();
}
//permette di prelevare un utente con un determinato nome
@Path("get/{name}")
@GET
@Produces({"application/json", "application/xml"})
public Response getByName(@PathParam("name") String name){
User u = Users.getInstance().getByName(name);
if(u!=null)
return Response.ok(u).build();
else
return Response.status(Response.Status.NOT_FOUND).build();
}
}
\ 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