|
1 | 1 | package massbank_export_api.api; |
2 | 2 |
|
3 | 3 | import massbank.RecordParser; |
| 4 | +import massbank_export_api.model.ValidationError; |
4 | 5 | import org.petitparser.context.Result; |
5 | 6 | import org.springframework.context.annotation.Primary; |
6 | 7 | import org.springframework.http.HttpStatus; |
| 8 | +import org.springframework.http.MediaType; |
7 | 9 | import org.springframework.http.ResponseEntity; |
8 | 10 | import org.springframework.stereotype.Service; |
9 | 11 |
|
10 | 12 | import java.util.HashSet; |
| 13 | +import java.util.Map; |
11 | 14 |
|
12 | 15 | @Primary |
13 | 16 | @Service |
14 | 17 | public class ValidateApiDelegateImpl implements ValidateApiDelegate { |
15 | 18 |
|
16 | | - final RecordParser recordparser = new RecordParser(new HashSet<>()); |
| 19 | + private final RecordParser recordParser; |
| 20 | + |
| 21 | + public ValidateApiDelegateImpl() { |
| 22 | + recordParser = new RecordParser(new HashSet<>()); |
| 23 | + } |
17 | 24 |
|
18 | 25 | @Override |
19 | 26 | public ResponseEntity<Void> validatePost(String body) { |
20 | | - Result result = recordparser.parse(body); |
21 | | - if (result.isSuccess()) return new ResponseEntity<>(HttpStatus.OK); |
22 | | - else { |
23 | | - return new ResponseEntity<>(HttpStatus.UNPROCESSABLE_ENTITY); |
| 27 | + if (body == null || body.trim().isEmpty()) { |
| 28 | + return ResponseEntity.badRequest().build(); |
| 29 | + } |
| 30 | + |
| 31 | + Result result = recordParser.parse(body); |
| 32 | + if (result.isSuccess()) { |
| 33 | + return ResponseEntity.ok().build(); |
| 34 | + } |
| 35 | + |
| 36 | + String message = result.getMessage(); |
| 37 | + int pos = result.getPosition(); |
| 38 | + |
| 39 | + String[] tokens = body.split("\\n"); |
| 40 | + int offset = 0; |
| 41 | + int lineNumber = 1; |
| 42 | + int col = 0; |
| 43 | + for (String token : tokens) { |
| 44 | + offset += token.length() + 1; |
| 45 | + if (pos < offset) { |
| 46 | + col = pos - (offset - (token.length() + 1)); |
| 47 | + break; |
| 48 | + } |
| 49 | + lineNumber++; |
24 | 50 | } |
| 51 | + |
| 52 | + ValidationError error = new ValidationError(); |
| 53 | + error.setMessage(message); |
| 54 | + error.setLine(lineNumber); |
| 55 | + error.setColumn(col); |
| 56 | + |
| 57 | + ResponseEntity<ValidationError> respWithBody = |
| 58 | + ResponseEntity.status(HttpStatus.UNPROCESSABLE_ENTITY) |
| 59 | + .contentType(MediaType.APPLICATION_JSON) |
| 60 | + .body(error); |
| 61 | + |
| 62 | + @SuppressWarnings("unchecked") |
| 63 | + ResponseEntity<Void> casted = (ResponseEntity<Void>)(ResponseEntity<?>) respWithBody; |
| 64 | + return casted; |
25 | 65 | } |
26 | 66 |
|
27 | 67 | } |
0 commit comments