netbeans Gradle Sping Boot 应用程序无法从Json文件中提取数据

2cmtqfgy  于 2022-11-10  发布在  其他
关注(0)|答案(1)|浏览(126)

我创建了一个带有spring Boot 依赖项的Gradle项目,这是一个rest api。我默认使用netbeans版本12.6和java 17。应用程序运行在端口号8080的tomcat服务器上。我想在调用rest api方法时将数据显示到localhost中,但主要问题是当我尝试调用www.example.com的方法instance.http://localhost:8080/result/2。它显示以下错误消息。

{“错误”:“未找到-001”,“消息”:“未找到2”}

这是杰森的档案。

{
    "id": 16,
    "name": "Arfon",
    "seqNo": 2,
    "partyResults": [
        {
            "party": "LAB",
            "votes": 8484,
            "share": 33.90
        },
        {
            "party": "PC",
            "votes": 8028,
            "share": 32.10
        },
        {
            "party": "CON",
            "votes": 4106,
            "share": 16.40
        },
        {
            "party": "LD",
            "votes": 3942,
            "share": 15.70
        },
        {
            "party": "UKIP",
            "votes": 482,
            "share": 1.90
        },
        {
            "party": "OTH",
            "votes": 0,
            "share": 0.00
        }
    ]
}

下面是主类代码。

@SpringBootApplication
public class ElectionsApiApplication {

    public static void main(String[] args) throws IOException {
        SpringApplication.run(ElectionsApiApplication.class, args);

    }

}

这里是存储库。

@Component
public class MapBasedRepository implements ResultService {

    private final Map<Integer,ConstituencyResult> results;

    public MapBasedRepository() {
        results = new ConcurrentHashMap<>();
    }

    @Override
    public ConstituencyResult GetResult(Integer id) {
        return results.get(id);
    }

    @Override
    public void NewResult(ConstituencyResult result) {
        results.put(result.getId(), result);
    }

    @Override
    public Map<Integer, ConstituencyResult> GetAll() {
        return results;
    }

    @Override
    public void reset() {
        results.clear();
    }

    @Override
    public Scoreboard soreboardResult(Scoreboard scoreboard) {
        return scoreboard;
     }

}

下面是控制器代码。

@RestController
public class ResultsController {

    private final ResultService results;

    public ResultsController(ResultService resultService) {
        this.results = resultService;
    }

    @GetMapping("/result/{id}")
    ConstituencyResult getResult(@PathVariable Integer id) {
        ConstituencyResult result = results.GetResult(id);
        if (result == null) {
            throw new ResultNotFoundException(id);
        }
        return results.GetResult(id);
    }

    @PostMapping("/result")
    ResponseEntity<String> newResult(@RequestBody ConstituencyResult result) {
        if (result.getId() != null) {
            results.NewResult(result);
            return ResponseEntity.created(URI.create("/result/"+result.getId())).build();
        }
        return ResponseEntity.badRequest().body("Id was null");
    }

    @GetMapping("/scoreoard")
   Scoreboard soreboardResult(Scoreboard scoreboard) {
        if(scoreboard==null){
            throw new ResultNotFoundException();
        }

        return new Scoreboard();
    }
}

下面是异常处理程序类。

@RestControllerAdvice
public class ResultsExceptionHandler {

    @ExceptionHandler(ResultNotFoundException.class)
    public ResponseEntity<ApiResponse> handleNotFoundApiException(
            ResultNotFoundException ex) {
        ApiResponse response =
                ApiResponse.builder()
                        .error("not-found-001")
                        .message(String.format("%d not found",ex.getId()))
                        .build();
        return new ResponseEntity<>(response, HttpStatus.NOT_FOUND);
    }

    @ExceptionHandler(NotImplementedException.class)
    public ResponseEntity<ApiResponse> handleNotImplementedApiException(
            NotImplementedException ex) {
        ApiResponse response =
                ApiResponse.builder()
                        .error("not-implemented-002")
                        .message("Function not yet implemented")
                        .build();
        return new ResponseEntity<>(response, HttpStatus.INTERNAL_SERVER_ERROR);
    }
}

下面是测试代码。

@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
class ElectionsApiApplicationIntegrationTests {
    @LocalServerPort
    private int port;

    private URL base;

    @Autowired
    private ObjectMapper objectMapper;

    @Autowired
    private TestRestTemplate template;

    @Autowired
    private ResultService resultService;

    @BeforeEach
    public void setUp() throws Exception {
        this.base = new URL("http://localhost:" + port + "/");
    }

    @AfterEach
    public void reset() throws Exception {
        resultService.reset();
    }

    @Test
    public void first5Test() throws Exception {
        Scoreboard scoreboard = runTest(5);

        assertNotNull(scoreboard);
               //Scoreboard sc = objectMapper.readValue(new File(".\\result001.json"), Scoreboard.class);
              //  System.out.println(sc);  

        // assert LD == 1
        // assert LAB = 4
        // assert winner = noone

    }

    @Test
    public void first100Test() throws Exception {
        Scoreboard scoreboard = runTest(100);

        assertNotNull(scoreboard);
        // assert LD == 12
        // assert LAB == 56
        // assert CON == 31
        // assert winner = noone
    }

    @Test
    public void first554Test() throws Exception {
        Scoreboard scoreboard = runTest(554);

        assertNotNull(scoreboard);
        // assert LD == 52
        // assert LAB = 325
        // assert CON = 167
        // assert winner = LAB
    }

    @Test
    public void allTest() throws Exception {
        Scoreboard scoreboard = runTest(650);

        assertNotNull(scoreboard);
        // assert LD == 62
        // assert LAB == 349
        // assert CON == 210
        // assert winner = LAB
        // assert sum = 650
    }

    private Scoreboard runTest(int numberOfResults) throws Exception {
        for (int i = 1; i <= numberOfResults; i++ ) {
            Class<?> clazz  = this.getClass();
            InputStream is = clazz.getResourceAsStream(String.format("/sample-election-results/result%s.json",String.format("%03d",i)));
            ConstituencyResult cr = objectMapper.readValue(is, ConstituencyResult.class);
            template.postForEntity(base.toString()+"/result", cr,String.class);
        }
        ResponseEntity<Scoreboard> scores = template.getForEntity(base.toString()+"/scoreboard", Scoreboard.class);
        return scores.getBody();
    }
}
xiozqbni

xiozqbni1#

请求路径为http://localhost:8080/result/2,这是在查询id = 2,而您的json文件中不存在该id = 2。此文件仅包含id = 16

相关问题