All Downloads are FREE. Search and download functionalities are using the official Maven repository.

com.turbospaces.resteasy.MockClientResponse Maven / Gradle / Ivy

package com.turbospaces.resteasy;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Objects;

import org.apache.http.HttpStatus;
import org.jboss.resteasy.specimpl.BuiltResponse;
import org.jboss.resteasy.spi.MarshalledEntity;

import com.fasterxml.jackson.databind.ObjectMapper;

public class MockClientResponse extends BuiltResponse {
    private final MarshalledEntity wrapper;

    private MockClientResponse(MarshalledEntity wrapper) {
        super();
        this.wrapper = Objects.requireNonNull(wrapper);
        setEntity(wrapper.getEntity());
    }
    private MockClientResponse(MarshalledEntity wrapper, int status) {
        this(wrapper);
        setStatus(status);
    }
    @Override
    protected InputStream getInputStream() {
        return new ByteArrayInputStream(wrapper.getMarshalledBytes());
    }

    public static  MockClientResponse ok(ObjectMapper mapper, T entity) throws IOException {
        return newInstance(mapper, entity, HttpStatus.SC_OK);
    }
    public static  MockClientResponse newInstance(ObjectMapper mapper, T entity, int status) throws IOException {
        try (ByteArrayOutputStream out = new ByteArrayOutputStream()) {
            mapper.writeValue(out, entity);
            out.flush();

            return new MockClientResponse<>(new MarshalledEntity() {
                @Override
                public byte[] getMarshalledBytes() {
                    return out.toByteArray();
                }
                @Override
                public T getEntity() {
                    return entity;
                }
            }, status);
        }
    }
}




© 2015 - 2025 Weber Informatics LLC | Privacy Policy