Я использую Spring для создания REST api. На данный момент я использую эту структуру, чтобы обеспечить обслуживание Проводник:Управление ответом REST с помощью Spring MVC
FileModel.java
package hello;
public class FileModel {
private String name;
private Long lastUpdate;
private Long size;
/**
* Void Constructor
*/
public FileModel() {
}
/**
* Parametrized constructor
* @param name
* @param created
* @param lastUpdate
* @param size
*/
public FileModel(String name, Long lastUpdate, Long size) {
super();
this.name = name;
this.lastUpdate = lastUpdate;
this.size = size;
}
/**
* @return the name
*/
public String getName() {
return name;
}
/**
* @param name the name to set
*/
public void setName(String name) {
this.name = name;
}
/**
* @return the lastUpdate:A long value representing the time the file was last modified,
* measured in milliseconds since the epoch (00:00:00 GMT, January 1, 1970)
*/
public Long getLastUpdate() {
return lastUpdate;
}
/**
* @param lastUpdate the lastUpdate to set
*/
public void setLastUpdate(Long lastUpdate) {
this.lastUpdate = lastUpdate;
}
/**
* @return the size in bytes
*/
public Long getSize() {
return size;
}
/**
* @param size the size to set
*/
public void setSize(Long size) {
this.size = size;
}
}
FileServices.java
package hello;
import java.io.File;
import java.io.FileNotFoundException;
import java.nio.file.Files;
import java.nio.file.LinkOption;
import java.util.ArrayList;
import org.springframework.stereotype.Service;
@Service
public class FileServices {
public ArrayList<FileModel> getAllFiles(String path) throws FileNotFoundException {
ArrayList<FileModel> files=new ArrayList<FileModel>();
File directory = new File(path);
if (directory.exists()){
//get all the files from a directory
File[] fList = directory.listFiles();
//check if list is null
for (File file : fList){
if (file.isFile()){
FileModel f=new FileModel(file.getName(),file.lastModified(),file.length());
files.add(f);
}
}
return files;
}
else throw new ResourceNotFoundException(path);
}
}
ResourceNotFoundException.java
package hello;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ResponseStatus;
@ResponseStatus(HttpStatus.NOT_FOUND)
public class ResourceNotFoundException extends RuntimeException {
private static final long serialVersionUID = 1L;
public ResourceNotFoundException(String path){
super("The specified path: "+ path +" doesn't exist");
}
}
FileManager
package hello;
import java.io.FileNotFoundException;
import java.util.Collection;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class FileManager {
@Autowired
private FileServices file;
@RequestMapping(value = "/files", method = RequestMethod.GET)
public Collection<FileModel> getAllFiles(@RequestParam(value="path", defaultValue="/home") String path) throws FileNotFoundException {
return file.getAllFiles(path);
}
}
Ответ либо сообщение об ошибке, как этот
> { "timestamp": 1442560477794, "status": 404, "error": "Not
> Found", "exception": "hello.ResourceNotFoundException", "message":
> "The specified path: /home doesn't exist", "path":
> "/MatlabLib/files" }
или это.
[
{
"name": "apache-tomcat-8.0.26-windows-x64.zip",
"lastUpdate": 1441282759343,
"size": 10470002
},
{
"name": "desktop.ini",
"lastUpdate": 1441357976196,
"size": 282
}
]
Учитывая, что я должен управлять этой веб-службы с помощью других Java или код MatLab, мне нужен собственный ответ, например, со статусом, ошибки, исключения, сообщение, тело так что я могу проверить код состояния и undestand если есть ошибка или меньше. Есть ли весной метод строительства?
Благодаря
UPDATE: Я создал два класса ответа, один для ErrorResponse и один для реагирования с различным количеством Fied. Тогда я использовал
@ControllerAdvice
public class ErrorController {
/**
*
* @param e: exception thrown
* @return ErroreResponse
*/
@ExceptionHandler(Exception.class)
public @ResponseBody ErrorResponse errorHandler(Exception e){
//Make the exception by buildErrorResponse
return ErrorResponseBuilder.buildErrorResponse(e);
}
в ErrorResponseBuilder сделал этот метод:
/**
* Build exception response beginning from exception
* @param e exception thrown
* @return ErrorResponse: response of an exception
*/
public static ErrorResponse buildErrorResponse(Exception e){
StringWriter errors = new StringWriter();
e.printStackTrace(new PrintWriter(errors));
return new ErrorResponse(HttpStatusManager.getHttpCode(e),e.getClass().getName(),e.getMessage(),errors.toString());
}
и в HttpStatusManager я реализовал это:
public HttpStatusManager() {
}
/**
* Add to this class all new exception associating a code error
* @param exception
* @return
*/
public static int getHttpCode(Exception exception){
if (exception instanceof ResourceNotFoundException);
return HttpStatus.NOT_FOUND.value();
}
так из Controlle использовать эту простую линию
@RequestMapping(value = "/files", method = RequestMethod.GET)
public Response<Collection<FileModel>> getAllFiles(@RequestParam(value="path", defaultValue="/home") String path) throws ResourceNotFoundException {
Collection<FileModel> result;
result = file.getAllFiles(path);
return new Response<Collection<FileModel>>(HttpStatus.OK.value(),result);
}
Как вы думаете?
Это не весна, но я думаю, она может удовлетворить ваши потребности: javax.ws.rs.core.Response. – pzeszko
Это уже есть, это называется HTTP. В первом случае ваш http-код будет 404 в последнем 200. В основном что-то в диапазоне 400 или 500 указывает на ошибку ... –