Grizzly HTTP Server 415 Неподдерживаемый тип носителя

Я разрабатываю набор сервисов REST, используя RESTEasy и WildFly 9.0.2.

Один из них позволяет мне загрузить файл.

@POST
@Path("/upload")
@Consumes(MediaType.MULTIPART_FORM_DATA)
public Response upload(MultipartFormDataInput input);

Мне удалось позвонить в службу REST и загрузить файл на сервер, поэтому я начал внедрять интеграционные тесты.

Для этого я использую встроенный HTTP-сервер Grizzly:

@Before
public void setUp() throws Exception {
    // Weld and container initialization
    weld = new Weld();
    weld.initialize();
    ResourceConfig resourceConfig = new ResourceConfig().packages("...");
    server = GrizzlyHttpServerFactory.createHttpServer(URI.create(BASE_URI), resourceConfig);
}

Проблема возникла, когда я попытался протестировать недавно созданный сервис:

@Test
public void hubbleMapServiceUploadMapTest() throws FileNotFoundException, IOException {
    Client client = null;
    WebTarget webTarget = null;
    Builder builder = null;
    Response response = null;

    try {
        client = ClientBuilder.newBuilder().build();

        webTarget = client.target(BASE_URI).path("/service/upload");
        builder = webTarget.request(MediaType.APPLICATION_JSON, MediaType.TEXT_PLAIN, MediaType.WILDCARD);

        response = builder.post(Entity.entity(getEntityAsMultipart(), MediaType.MULTIPART_FORM_DATA));

    } catch (Exception ex) {
        ex.printStackTrace();
    } finally {
        if (response != null) {
            response.close();
        }

        if (client != null) {
            client.close();
        }
    }

    assertNotNull(response);
    assertThat(response.getStatus(), is(Status.OK.getStatusCode()));
}

private GenericEntity<MultipartFormDataOutput> getEntityAsMultipart() {
    String resource = "my.file";
    MultipartFormDataOutput mfdo = new MultipartFormDataOutput();

    try {
        mfdo.addFormData("file",
                new FileInputStream(new File(getClass().getClassLoader().getResource(resource).getFile())),
                MediaType.APPLICATION_OCTET_STREAM_TYPE, resource);
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    }

    GenericEntity<MultipartFormDataOutput> entity = new GenericEntity<MultipartFormDataOutput>(mfdo) {
    };

    return entity;
}

Код ответа всегда 415 Unsupported Media Type.

Все остальные интеграционные тесты работают правильно.

Что я делаю неправильно? Нужно ли мне как-то включать функцию Multipart от Grizzly?

1 ответ

Решение

Paul Samsotha совету Paul Samsotha, я переключился на встроенный сервер Sun JDK HTTP Server с поддержкой CDI.

Для этого нужно сделать следующее:

  1. Добавьте RESTEasy и WELD необходимые зависимости Maven:

    <dependency>
        <groupId>org.jboss.resteasy</groupId>
        <artifactId>resteasy-jdk-http</artifactId>
        <version>3.0.17.Final</version>
        <scope>test</scope>
    </dependency>
    
    <dependency>
        <groupId>org.jboss.resteasy</groupId>
        <artifactId>resteasy-cdi</artifactId>
        <version>3.0.17.Final</version>
        <scope>test</scope>
    </dependency>
    
    <dependency>
        <groupId>org.jboss.weld.se</groupId>
        <artifactId>weld-se</artifactId>
        <version>2.3.4.Final</version>
        <scope>test</scope>
    </dependency>
    
  2. Сконфигурируйте расширение WELD и RESTEasy CDI для использования в конфигурации развертывания HTTP-сервера Sun JDK:

    private Weld weld;
    private SunHttpJaxrsServer server;
    
    @Before
    public void setUp() throws Exception {
        // Weld initialization
        weld = new Weld();
        weld.initialize();
    
        // RESTEasy CDI extension configuration
        ResteasyCdiExtension cdiExtension = CDI.current().select(ResteasyCdiExtension.class).get();
        ResteasyDeployment deployment = new ResteasyDeployment();
        deployment.setActualResourceClasses(cdiExtension.getResources());
        deployment.setInjectorFactoryClass(CdiInjectorFactory.class.getName());
        deployment.getActualProviderClasses().addAll(cdiExtension.getProviders());
    
        // Container initialization
        server = new SunHttpJaxrsServer();
        server.setDeployment(deployment);
        server.setPort(8787);
        server.setRootResourcePath("/some-context-root/rest");
        server.getDeployment().getActualResourceClasses().add(MyService.class);
        server.start();
    }
    

Чтобы узнать, как настроить расширение CDI RESTEasy, я использовал John Ament.

Другие вопросы по тегам