1

Dropwizard に実装されたファイル アップロード REST エンドポイントがあります。私はこれが初めてで、ただ学ぼうとしています。

@Path("/files")
@Produces(MediaType.APPLICATION_JSON)
public class FileUploadResource {

    private final MyAppWebConfiguration configuration;
    private static final Logger logger = LoggerFactory.getLogger(FileUploadResource.class);

    public FileUploadResource(MyAppWebConfiguration configuration) {
        this.configuration = configuration;
    }

    @POST
    @Consumes(MediaType.MULTIPART_FORM_DATA)
    public Response uploadFile(
            @FormDataParam("file") InputStream uploadedInputStream,
            @FormDataParam("file") FormDataContentDisposition fileDetail) throws IOException {

        logger.info("Request to upload the file ", fileDetail.getFileName());
        final String uploadedFileLocation = configuration.getCsvUploadPath();
        final String fileName = fileDetail.getFileName();
        writeToFile(uploadedInputStream, uploadedFileLocation, fileName);
        return Response.ok("File " + fileName + " is uploaded to the location " + uploadedFileLocation).build();
    }

    // save uploaded file to new location
    protected void writeToFile(InputStream uploadedInputStream, String uploadedFileLocation, String fileName) throws IOException {
        logger.info("Writing {} to {}", fileName, uploadedFileLocation);
        final java.nio.file.Path outputPath = FileSystems.getDefault().getPath(uploadedFileLocation, fileName);
        Files.copy(uploadedInputStream, outputPath, StandardCopyOption.REPLACE_EXISTING);
        logger.info("Uploaded {} to the location {}", fileName, uploadedFileLocation);
    }

コードは正常に機能し、ファイルをアップロードできます。https://gist.github.com/psamsotha/218c6bbeb6164bac7cbcに基づいて、以下のコードでテストしようとしています:

public class FileUploadResourceTest extends JerseyTest {

    private final static MyAppWebConfiguration mockConfiguration = mock(MyAppWebConfiguration.class);

    @Override
    public ResourceConfig configure() {
        return new ResourceConfig(FileUploadResource.class)
                .register(MultiPartFeature.class)
                .register(new LoggingFilter(Logger.getAnonymousLogger(), true));
    }

    @Override
    public void configureClient(ClientConfig config) {
        config.register(MultiPartFeature.class);
    }

    @Test
    public void test() {
        FileDataBodyPart filePart = new FileDataBodyPart("file", new File("/Users/rocky/Downloads/test.csv"));
        filePart.setContentDisposition(FormDataContentDisposition.name("file").fileName("/Users/rocky/Downloads/test.csv").build());

        MultiPart multiPart = new FormDataMultiPart()
                .bodyPart(filePart);
        Response response = target("/files").request()
                .post(Entity.entity(multiPart, MediaType.MULTIPART_FORM_DATA_TYPE));
        assertThat(response.getStatus()).isEqualTo(Response.Status.OK.getStatusCode());
        response.close();
    }

このテストは、次のエラーで失敗します。

WARNING: The following warnings have been detected: WARNING: HK2 service reification failed for [com.my.app.resources.FileUploadResource] with an exception:
MultiException stack 1 of 2
java.lang.NoSuchMethodException: Could not find a suitable constructor in com.my.app.resources.FileUploadResource class.
    at org.glassfish.jersey.internal.inject.JerseyClassAnalyzer.getConstructor(JerseyClassAnalyzer.java:192)
    at org.jvnet.hk2.internal.Utilities.getConstructor(Utilities.java:178)
    at org.jvnet.hk2.internal.ClazzCreator.initialize(ClazzCreator.java:128)
    at org.jvnet.hk2.internal.ClazzCreator.initialize(ClazzCreator.java:179)

引数なしのコンストラクターはありませんが、引数なしのコンストラクターFileUploadResourceが必要new ResourceConfig(FileUploadResource.class)です。ここで 1 つの引数コンストラクターに関する情報を渡すにはどうすればよいですか?

ここで何か助けていただければ幸いです。また、コードとテストに関するその他のベスト プラクティスを提案してください。改善できるようにします。

よろしくお願いします。

4

1 に答える 1

2

リソースをクラスとして登録する場合

new ResourceConfig(FileUploadResource.class)

Jersey にそれを作成するように指示しています。しかし、ジャージーが何も知らない構成オブジェクトを受け入れるコンストラクターしかないため、それを作成する方法がわかりません。代わりに、オブジェクトとして登録する必要があります。Dropwizard に登録する場合と同じ方法 ( env.jersey().register(...))。

new ResourceConfig().regster(new FileUploadResource(mockConfiguration))
    ...

余談ですが、Dropwizard では、. を明示的に使用する必要はありませんJerseyTest。Dropwizard には、独自の を明示的に実行する JUnit ルールが付属しており、JerseyTestルールを使用して構成できます。完全な例を投稿したこの問題を参照してください。

于 2016-04-07T23:24:43.207 に答える