/** * Find the serialiser binding based on the content types accepted by the client. * * @param routingContext the Vert.x routing context * @return the serialiser */ private SerialisationService findSerialiser(RoutingContext routingContext) { final List<String> acceptedContentTypes = HttpUtil.readAcceptedContentTypes(routingContext); // add as default to end of the list if (!acceptedContentTypes.contains(CONTENT_TYPE_JSON)) { acceptedContentTypes.add(CONTENT_TYPE_JSON); } // search the ordered list for (String contentType : acceptedContentTypes) { try { final SerialisationService serialiser = injector.getInstance(Key.get(SerialisationService.class, Names.named(contentType))); LOGGER.debug("Found serialiser binding {} for content type '{}'", serialiser.getClass().getSimpleName(), contentType); return serialiser; } catch (Exception e) { LOGGER.trace("Unable to load serialiser binding for content type '{}'", contentType, e); } } throw new RuntimeException(String.format( "Unable to find serialiser matching any accepted content type: %s", acceptedContentTypes)); }
private Router configureRoutes() { final Router router = Router.router(vertx); router.route().handler(new BodyHandlerImpl()); // status check to indicate when server is up router.get("/system/status").handler(routingContext -> routingContext.response() .putHeader(HttpUtil.CONTENT_TYPE, HttpUtil.CONTENT_TYPE_JSON) .end(HttpUtil.buildStatusResponse())); pluginManager.getPlugins().forEach(plugin -> plugin.configureRoutes(router)); return router; } }
/** * Read the content types accepted by the requesting client, ordered by their weighting. * * @param routingContext the Vert.x routing context * @return the ordered content types */ public static List<String> readAcceptedContentTypes(RoutingContext routingContext) { return readAcceptedContentTypes(routingContext.request().getHeader("Accept")); }
final List<String> matchedContentTypes = HttpUtil.readAcceptedContentTypes(routingContext).parallelStream() .filter(produces::contains) .collect(Collectors.toList());
@Test public void readAcceptedContentTypes() throws Exception { // note: provided out of order, but should be sorted by 'q' weight final String acceptHeader = "text/html; q=1.0, text/*; q=0.8, image/jpeg; q=0.5, image/gif; q=0.7, image/*; q=0.4, */*; q=0.1"; final List<String> actual = HttpUtil.readAcceptedContentTypes(acceptHeader); assertNotNull(actual); assertEquals(6, actual.size()); // check order assertEquals("text/html", actual.get(0)); assertEquals("text/*", actual.get(1)); assertEquals("image/gif", actual.get(2)); assertEquals("image/jpeg", actual.get(3)); assertEquals("image/*", actual.get(4)); assertEquals("*/*", actual.get(5)); } }