cz.muni.fi.pa165.rentalofconstructionmachinery.restclient.MachineRestController.java Source code

Java tutorial

Introduction

Here is the source code for cz.muni.fi.pa165.rentalofconstructionmachinery.restclient.MachineRestController.java

Source

package cz.muni.fi.pa165.rentalofconstructionmachinery.restclient;

import cz.muni.fi.pa165.rentalofconstructionmachinery.dto.MachineDTO;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.Arrays;
import java.util.List;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.web.client.RestTemplate;

/**
 *
 * @author Zuzana Krejcova
 */
public class MachineRestController {

    private static String MACHINE_URL = App.WEBAPP_LOCATION + "machine/";
    private static RestTemplate rt = new RestTemplate();
    private static HttpHeaders httpHeaders;

    public static void setHttpHeaders(HttpHeaders headers) {
        httpHeaders = headers;
    }

    public static void deleteMachine(Long id) throws URISyntaxException {
        String url = MACHINE_URL + id;
        rt.exchange(new URI(url), HttpMethod.DELETE, new HttpEntity<>(httpHeaders), Object.class);
    }

    public static void newMachine(String licensePlate, String type) {
        MachineDTO machine = new MachineDTO(null, licensePlate, type);
        rt.postForLocation(MACHINE_URL, new HttpEntity<>(machine, httpHeaders));
    }

    public static void editMachine(Long id, String licensePlate, String type) {
        String url = MACHINE_URL + id;
        MachineDTO machine = new MachineDTO(id, licensePlate, type);
        rt.put(url, new HttpEntity<>(machine, httpHeaders));
    }

    public static MachineDTO machineDetails(Long id) throws URISyntaxException {
        String url = MACHINE_URL + id;
        HttpEntity re = rt.exchange(new URI(url), HttpMethod.GET, new HttpEntity<>(httpHeaders), MachineDTO.class);
        return (MachineDTO) re.getBody();
    }

    public static List<MachineDTO> listMachines() throws URISyntaxException {
        HttpEntity re = rt.exchange(new URI(MACHINE_URL), HttpMethod.GET, new HttpEntity<>(httpHeaders),
                MachineDTO[].class);
        return Arrays.asList((MachineDTO[]) re.getBody());
    }
}