org.springframework.http.MediaType

Here are the examples of the java api org.springframework.http.MediaType taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.

1345 Examples 7

19 Source : RestAuthenticationEntryPoint.java
with MIT License
from zidoshare

/**
 * @author zido
 */
public clreplaced RestAuthenticationEntryPoint implements AuthenticationEntryPoint {

    private MediaType mediaType;

    private String content;

    public RestAuthenticationEntryPoint() {
    }

    public RestAuthenticationEntryPoint(String content) {
        this(MediaType.APPLICATION_JSON, content);
    }

    public RestAuthenticationEntryPoint(MediaType mediaType, String content) {
        this.mediaType = mediaType;
        this.content = content;
    }

    public void setMediaType(MediaType mediaType) {
        this.mediaType = mediaType;
    }

    public void setContent(String content) {
        this.content = content;
    }

    @Override
    public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authException) throws IOException, ServletException {
        response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
        if (this.mediaType != null) {
            response.setHeader("Content-Type", this.mediaType.toString());
        }
        if (StringUtils.hasLength(content)) {
            response.getWriter().write(content);
        }
    }
}

19 Source : RestAuthenticationEntryPoint.java
with MIT License
from zidoshare

public void setMediaType(MediaType mediaType) {
    this.mediaType = mediaType;
}

19 Source : RestAccessDeniedHandlerImpl.java
with MIT License
from zidoshare

public clreplaced RestAccessDeniedHandlerImpl implements AccessDeniedHandler {

    private MediaType mediaType;

    private String successBody;

    public RestAccessDeniedHandlerImpl() {
    }

    public RestAccessDeniedHandlerImpl(String successBody) {
        this(MediaType.APPLICATION_JSON, successBody);
    }

    public RestAccessDeniedHandlerImpl(MediaType mediaType, String successBody) {
        this.mediaType = mediaType;
        this.successBody = successBody;
    }

    public void setMediaType(MediaType mediaType) {
        this.mediaType = mediaType;
    }

    public void setSuccessBody(String successBody) {
        this.successBody = successBody;
    }

    @Override
    public void handle(HttpServletRequest request, HttpServletResponse response, AccessDeniedException accessDeniedException) throws IOException, ServletException {
        response.setStatus(HttpServletResponse.SC_FORBIDDEN);
        if (this.mediaType != null) {
            response.setHeader("Content-Type", this.mediaType.toString());
        }
        if (StringUtils.hasLength(successBody)) {
            response.getWriter().write(successBody);
        }
    }
}

19 Source : RestAuthenticationSuccessHandler.java
with MIT License
from zidoshare

/**
 * @author zido
 */
public clreplaced RestAuthenticationSuccessHandler implements AuthenticationSuccessHandler {

    private MediaType mediaType;

    private String successBody;

    public RestAuthenticationSuccessHandler() {
    }

    public RestAuthenticationSuccessHandler(String successBody) {
        this(MediaType.APPLICATION_JSON, successBody);
    }

    public RestAuthenticationSuccessHandler(MediaType mediaType, String successBody) {
        this.mediaType = mediaType;
        this.successBody = successBody;
    }

    @Override
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
        if (this.mediaType != null) {
            response.setHeader("Content-Type", this.mediaType.toString());
        }
        if (StringUtils.hasLength(successBody)) {
            response.getWriter().write(successBody);
        }
    }

    public void setMediaType(MediaType mediaType) {
        this.mediaType = mediaType;
    }

    public void setSuccessBody(String successBody) {
        this.successBody = successBody;
    }
}

19 Source : RestAuthenticationFailureHandler.java
with MIT License
from zidoshare

/**
 * @author zido
 */
public clreplaced RestAuthenticationFailureHandler implements AuthenticationFailureHandler {

    private MediaType mediaType;

    private String successBody;

    public RestAuthenticationFailureHandler() {
    }

    public RestAuthenticationFailureHandler(String successBody) {
        this(MediaType.APPLICATION_JSON, successBody);
    }

    public RestAuthenticationFailureHandler(MediaType mediaType, String successBody) {
        this.mediaType = mediaType;
        this.successBody = successBody;
    }

    public void setMediaType(MediaType mediaType) {
        this.mediaType = mediaType;
    }

    public void setSuccessBody(String successBody) {
        this.successBody = successBody;
    }

    @Override
    public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, AuthenticationException exception) throws IOException, ServletException {
        response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
        if (this.mediaType != null) {
            response.setHeader("Content-Type", this.mediaType.toString());
        }
        if (StringUtils.hasLength(successBody)) {
            response.getWriter().write(successBody);
        }
    }
}

19 Source : AbstractStreamingResponseBody.java
with Apache License 2.0
from zhouxx

public AbstractStreamingResponseBody mediaType(MediaType mediaType) {
    this.mediaType = mediaType;
    return this;
}

19 Source : ErrorPagesController.java
with MIT License
from zhangyd-c

/**
 * Determine if the stacktrace attribute should be included.
 *
 * @param request  the source request
 * @param produces the media type produced (or {@code MediaType.ALL})
 * @return if the stacktrace attribute should be included
 */
protected boolean isIncludeStackTrace(HttpServletRequest request, MediaType produces) {
    ErrorProperties.IncludeStacktrace include = this.serverProperties.getError().getIncludeStacktrace();
    if (include == ErrorProperties.IncludeStacktrace.ALWAYS) {
        return true;
    }
    return include == ErrorProperties.IncludeStacktrace.ON_TRACE_PARAM && getTraceParameter(request);
}

19 Source : ErrorPagesController.java
with GNU General Public License v3.0
from zhangyd-c

/**
 * Determine if the stacktrace attribute should be included.
 *
 * @param request
 *         the source request
 * @param produces
 *         the media type produced (or {@code MediaType.ALL})
 * @return if the stacktrace attribute should be included
 */
protected boolean isIncludeStackTrace(HttpServletRequest request, MediaType produces) {
    ErrorProperties.IncludeStacktrace include = this.serverProperties.getError().getIncludeStacktrace();
    if (include == ErrorProperties.IncludeStacktrace.ALWAYS) {
        return true;
    }
    return include == ErrorProperties.IncludeStacktrace.ON_TRACE_PARAM && getTraceParameter(request);
}

19 Source : HttpTunnelServer.java
with Apache License 2.0
from yuanmabiji

/**
 * A server that can be used to tunnel TCP traffic over HTTP. Similar in design to the
 * <a href="http://xmpp.org/extensions/xep-0124.html">Bidirectional-streams Over
 * Synchronous HTTP (BOSH)</a> XMPP extension protocol, the server uses long polling with
 * HTTP requests held open until a response is available. A typical traffic pattern would
 * be as follows:
 *
 * <pre>
 * [ CLIENT ]                      [ SERVER ]
 *     | (a) Initial empty request     |
 *     |------------------------------>|
 *     | (b) Data I                    |
 *  -->|------------------------------>|--->
 *     | Response I (a)                |
 *  <--|<------------------------------|<---
 *     |                               |
 *     | (c) Data II                   |
 *  -->|------------------------------>|--->
 *     | Response II (b)               |
 *  <--|<------------------------------|<---
 *     .                               .
 *     .                               .
 * </pre>
 *
 * Each incoming request is held open to be used to carry the next available response. The
 * server will hold at most two connections open at any given time.
 * <p>
 * Requests should be made using HTTP GET or POST (depending if there is a payload), with
 * any payload contained in the body. The following response codes can be returned from
 * the server:
 * <table>
 * <caption>Response Codes</caption>
 * <tr>
 * <th>Status</th>
 * <th>Meaning</th>
 * </tr>
 * <tr>
 * <td>200 (OK)</td>
 * <td>Data payload response.</td>
 * </tr>
 * <tr>
 * <td>204 (No Content)</td>
 * <td>The long poll has timed out and the client should start a new request.</td>
 * </tr>
 * <tr>
 * <td>429 (Too many requests)</td>
 * <td>There are already enough connections open, this one can be dropped.</td>
 * </tr>
 * <tr>
 * <td>410 (Gone)</td>
 * <td>The target server has disconnected.</td>
 * </tr>
 * <tr>
 * <td>503 (Service Unavailable)</td>
 * <td>The target server is unavailable</td>
 * </tr>
 * </table>
 * <p>
 * Requests and responses that contain payloads include a {@code x-seq} header that
 * contains a running sequence number (used to ensure data is applied in the correct
 * order). The first request containing a payload should have a {@code x-seq} value of
 * {@code 1}.
 *
 * @author Phillip Webb
 * @author Andy Wilkinson
 * @since 1.3.0
 * @see org.springframework.boot.devtools.tunnel.client.HttpTunnelConnection
 */
public clreplaced HttpTunnelServer {

    private static final long DEFAULT_LONG_POLL_TIMEOUT = TimeUnit.SECONDS.toMillis(10);

    private static final long DEFAULT_DISCONNECT_TIMEOUT = TimeUnit.SECONDS.toMillis(30);

    private static final MediaType DISCONNECT_MEDIA_TYPE = new MediaType("application", "x-disconnect");

    private static final Log logger = LogFactory.getLog(HttpTunnelServer.clreplaced);

    private final TargetServerConnection serverConnection;

    private int longPollTimeout = (int) DEFAULT_LONG_POLL_TIMEOUT;

    private long disconnectTimeout = DEFAULT_DISCONNECT_TIMEOUT;

    private volatile ServerThread serverThread;

    /**
     * Creates a new {@link HttpTunnelServer} instance.
     * @param serverConnection the connection to the target server
     */
    public HttpTunnelServer(TargetServerConnection serverConnection) {
        replacedert.notNull(serverConnection, "ServerConnection must not be null");
        this.serverConnection = serverConnection;
    }

    /**
     * Handle an incoming HTTP connection.
     * @param request the HTTP request
     * @param response the HTTP response
     * @throws IOException in case of I/O errors
     */
    public void handle(ServerHttpRequest request, ServerHttpResponse response) throws IOException {
        handle(new HttpConnection(request, response));
    }

    /**
     * Handle an incoming HTTP connection.
     * @param httpConnection the HTTP connection
     * @throws IOException in case of I/O errors
     */
    protected void handle(HttpConnection httpConnection) throws IOException {
        try {
            getServerThread().handleIncomingHttp(httpConnection);
            httpConnection.waitForResponse();
        } catch (ConnectException ex) {
            httpConnection.respond(HttpStatus.GONE);
        }
    }

    /**
     * Returns the active server thread, creating and starting it if necessary.
     * @return the {@code ServerThread} (never {@code null})
     * @throws IOException in case of I/O errors
     */
    protected ServerThread getServerThread() throws IOException {
        synchronized (this) {
            if (this.serverThread == null) {
                ByteChannel channel = this.serverConnection.open(this.longPollTimeout);
                this.serverThread = new ServerThread(channel);
                this.serverThread.start();
            }
            return this.serverThread;
        }
    }

    /**
     * Called when the server thread exits.
     */
    void clearServerThread() {
        synchronized (this) {
            this.serverThread = null;
        }
    }

    /**
     * Set the long poll timeout for the server.
     * @param longPollTimeout the long poll timeout in milliseconds
     */
    public void setLongPollTimeout(int longPollTimeout) {
        replacedert.isTrue(longPollTimeout > 0, "LongPollTimeout must be a positive value");
        this.longPollTimeout = longPollTimeout;
    }

    /**
     * Set the maximum amount of time to wait for a client before closing the connection.
     * @param disconnectTimeout the disconnect timeout in milliseconds
     */
    public void setDisconnectTimeout(long disconnectTimeout) {
        replacedert.isTrue(disconnectTimeout > 0, "DisconnectTimeout must be a positive value");
        this.disconnectTimeout = disconnectTimeout;
    }

    /**
     * The main server thread used to transfer tunnel traffic.
     */
    protected clreplaced ServerThread extends Thread {

        private final ByteChannel targetServer;

        private final Deque<HttpConnection> httpConnections;

        private final HttpTunnelPayloadForwarder payloadForwarder;

        private boolean closed;

        private AtomicLong responseSeq = new AtomicLong();

        private long lastHttpRequestTime;

        public ServerThread(ByteChannel targetServer) {
            replacedert.notNull(targetServer, "TargetServer must not be null");
            this.targetServer = targetServer;
            this.httpConnections = new ArrayDeque<>(2);
            this.payloadForwarder = new HttpTunnelPayloadForwarder(targetServer);
        }

        @Override
        public void run() {
            try {
                try {
                    readAndForwardTargetServerData();
                } catch (Exception ex) {
                    logger.trace("Unexpected exception from tunnel server", ex);
                }
            } finally {
                this.closed = true;
                closeHttpConnections();
                closeTargetServer();
                HttpTunnelServer.this.clearServerThread();
            }
        }

        private void readAndForwardTargetServerData() throws IOException {
            while (this.targetServer.isOpen()) {
                closeStaleHttpConnections();
                ByteBuffer data = HttpTunnelPayload.getPayloadData(this.targetServer);
                synchronized (this.httpConnections) {
                    if (data != null) {
                        HttpTunnelPayload payload = new HttpTunnelPayload(this.responseSeq.incrementAndGet(), data);
                        payload.logIncoming();
                        HttpConnection connection = getOrWaitForHttpConnection();
                        connection.respond(payload);
                    }
                }
            }
        }

        private HttpConnection getOrWaitForHttpConnection() {
            synchronized (this.httpConnections) {
                HttpConnection httpConnection = this.httpConnections.pollFirst();
                while (httpConnection == null) {
                    try {
                        this.httpConnections.wait(HttpTunnelServer.this.longPollTimeout);
                    } catch (InterruptedException ex) {
                        Thread.currentThread().interrupt();
                        closeHttpConnections();
                    }
                    httpConnection = this.httpConnections.pollFirst();
                }
                return httpConnection;
            }
        }

        private void closeStaleHttpConnections() throws IOException {
            synchronized (this.httpConnections) {
                checkNotDisconnected();
                Iterator<HttpConnection> iterator = this.httpConnections.iterator();
                while (iterator.hasNext()) {
                    HttpConnection httpConnection = iterator.next();
                    if (httpConnection.isOlderThan(HttpTunnelServer.this.longPollTimeout)) {
                        httpConnection.respond(HttpStatus.NO_CONTENT);
                        iterator.remove();
                    }
                }
            }
        }

        private void checkNotDisconnected() {
            if (this.lastHttpRequestTime > 0) {
                long timeout = HttpTunnelServer.this.disconnectTimeout;
                long duration = System.currentTimeMillis() - this.lastHttpRequestTime;
                replacedert.state(duration < timeout, () -> "Disconnect timeout: " + timeout + " " + duration);
            }
        }

        private void closeHttpConnections() {
            synchronized (this.httpConnections) {
                while (!this.httpConnections.isEmpty()) {
                    try {
                        this.httpConnections.removeFirst().respond(HttpStatus.GONE);
                    } catch (Exception ex) {
                        logger.trace("Unable to close remote HTTP connection");
                    }
                }
            }
        }

        private void closeTargetServer() {
            try {
                this.targetServer.close();
            } catch (IOException ex) {
                logger.trace("Unable to target server connection");
            }
        }

        /**
         * Handle an incoming {@link HttpConnection}.
         * @param httpConnection the connection to handle.
         * @throws IOException in case of I/O errors
         */
        public void handleIncomingHttp(HttpConnection httpConnection) throws IOException {
            if (this.closed) {
                httpConnection.respond(HttpStatus.GONE);
            }
            synchronized (this.httpConnections) {
                while (this.httpConnections.size() > 1) {
                    this.httpConnections.removeFirst().respond(HttpStatus.TOO_MANY_REQUESTS);
                }
                this.lastHttpRequestTime = System.currentTimeMillis();
                this.httpConnections.addLast(httpConnection);
                this.httpConnections.notify();
            }
            forwardToTargetServer(httpConnection);
        }

        private void forwardToTargetServer(HttpConnection httpConnection) throws IOException {
            if (httpConnection.isDisconnectRequest()) {
                this.targetServer.close();
                interrupt();
            }
            ServerHttpRequest request = httpConnection.getRequest();
            HttpTunnelPayload payload = HttpTunnelPayload.get(request);
            if (payload != null) {
                this.payloadForwarder.forward(payload);
            }
        }
    }

    /**
     * Encapsulates a HTTP request/response pair.
     */
    protected static clreplaced HttpConnection {

        private final long createTime;

        private final ServerHttpRequest request;

        private final ServerHttpResponse response;

        private ServerHttpAsyncRequestControl async;

        private volatile boolean complete = false;

        public HttpConnection(ServerHttpRequest request, ServerHttpResponse response) {
            this.createTime = System.currentTimeMillis();
            this.request = request;
            this.response = response;
            this.async = startAsync();
        }

        /**
         * Start asynchronous support or if unavailable return {@code null} to cause
         * {@link #waitForResponse()} to block.
         * @return the async request control
         */
        protected ServerHttpAsyncRequestControl startAsync() {
            try {
                // Try to use async to save blocking
                ServerHttpAsyncRequestControl async = this.request.getAsyncRequestControl(this.response);
                async.start();
                return async;
            } catch (Exception ex) {
                return null;
            }
        }

        /**
         * Return the underlying request.
         * @return the request
         */
        public final ServerHttpRequest getRequest() {
            return this.request;
        }

        /**
         * Return the underlying response.
         * @return the response
         */
        protected final ServerHttpResponse getResponse() {
            return this.response;
        }

        /**
         * Determine if a connection is older than the specified time.
         * @param time the time to check
         * @return {@code true} if the request is older than the time
         */
        public boolean isOlderThan(int time) {
            long runningTime = System.currentTimeMillis() - this.createTime;
            return (runningTime > time);
        }

        /**
         * Cause the request to block or use asynchronous methods to wait until a response
         * is available.
         */
        public void waitForResponse() {
            if (this.async == null) {
                while (!this.complete) {
                    try {
                        synchronized (this) {
                            wait(1000);
                        }
                    } catch (InterruptedException ex) {
                        Thread.currentThread().interrupt();
                    }
                }
            }
        }

        /**
         * Detect if the request is actually a signal to disconnect.
         * @return if the request is a signal to disconnect
         */
        public boolean isDisconnectRequest() {
            return DISCONNECT_MEDIA_TYPE.equals(this.request.getHeaders().getContentType());
        }

        /**
         * Send a HTTP status response.
         * @param status the status to send
         * @throws IOException in case of I/O errors
         */
        public void respond(HttpStatus status) throws IOException {
            replacedert.notNull(status, "Status must not be null");
            this.response.setStatusCode(status);
            complete();
        }

        /**
         * Send a payload response.
         * @param payload the payload to send
         * @throws IOException in case of I/O errors
         */
        public void respond(HttpTunnelPayload payload) throws IOException {
            replacedert.notNull(payload, "Payload must not be null");
            this.response.setStatusCode(HttpStatus.OK);
            payload.replacedignTo(this.response);
            complete();
        }

        /**
         * Called when a request is complete.
         */
        protected void complete() {
            if (this.async != null) {
                this.async.complete();
            } else {
                synchronized (this) {
                    this.complete = true;
                    notifyAll();
                }
            }
        }
    }
}

19 Source : BasicErrorController.java
with Apache License 2.0
from yuanmabiji

/**
 * Determine if the stacktrace attribute should be included.
 * @param request the source request
 * @param produces the media type produced (or {@code MediaType.ALL})
 * @return if the stacktrace attribute should be included
 */
protected boolean isIncludeStackTrace(HttpServletRequest request, MediaType produces) {
    IncludeStacktrace include = getErrorProperties().getIncludeStacktrace();
    if (include == IncludeStacktrace.ALWAYS) {
        return true;
    }
    if (include == IncludeStacktrace.ON_TRACE_PARAM) {
        return getTraceParameter(request);
    }
    return false;
}

19 Source : DefaultErrorWebExceptionHandler.java
with Apache License 2.0
from yuanmabiji

/**
 * Determine if the stacktrace attribute should be included.
 * @param request the source request
 * @param produces the media type produced (or {@code MediaType.ALL})
 * @return if the stacktrace attribute should be included
 */
protected boolean isIncludeStackTrace(ServerRequest request, MediaType produces) {
    ErrorProperties.IncludeStacktrace include = this.errorProperties.getIncludeStacktrace();
    if (include == ErrorProperties.IncludeStacktrace.ALWAYS) {
        return true;
    }
    if (include == ErrorProperties.IncludeStacktrace.ON_TRACE_PARAM) {
        return isTraceEnabled(request);
    }
    return false;
}

19 Source : RepositoryRestProperties.java
with Apache License 2.0
from yuanmabiji

public void setDefaultMediaType(MediaType defaultMediaType) {
    this.defaultMediaType = defaultMediaType;
}

19 Source : MustacheView.java
with Apache License 2.0
from yuanmabiji

private Optional<Charset> getCharset(MediaType mediaType) {
    return Optional.ofNullable((mediaType != null) ? mediaType.getCharset() : null);
}

19 Source : TestUtil.java
with Apache License 2.0
from yodamad

/**
 * Utility clreplaced for testing REST controllers.
 */
public clreplaced TestUtil {

    /**
     * MediaType for JSON UTF8
     */
    public static final MediaType APPLICATION_JSON_UTF8 = new MediaType(MediaType.APPLICATION_JSON.getType(), MediaType.APPLICATION_JSON.getSubtype(), StandardCharsets.UTF_8);

    /**
     * Convert an object to JSON byte array.
     *
     * @param object
     *            the object to convert
     * @return the JSON byte array
     * @throws IOException
     */
    public static byte[] convertObjectToJsonBytes(Object object) throws IOException {
        ObjectMapper mapper = new ObjectMapper();
        mapper.setSerializationInclusion(JsonInclude.Include.NON_EMPTY);
        JavaTimeModule module = new JavaTimeModule();
        mapper.registerModule(module);
        return mapper.writeValueAsBytes(object);
    }

    /**
     * Create a byte array with a specific size filled with specified data.
     *
     * @param size the size of the byte array
     * @param data the data to put in the byte array
     * @return the JSON byte array
     */
    public static byte[] createByteArray(int size, String data) {
        byte[] byteArray = new byte[size];
        for (int i = 0; i < size; i++) {
            byteArray[i] = Byte.parseByte(data, 2);
        }
        return byteArray;
    }

    /**
     * A matcher that tests that the examined string represents the same instant as the reference datetime.
     */
    public static clreplaced ZonedDateTimeMatcher extends TypeSafeDiagnosingMatcher<String> {

        private final ZonedDateTime date;

        public ZonedDateTimeMatcher(ZonedDateTime date) {
            this.date = date;
        }

        @Override
        protected boolean matchesSafely(String item, Description mismatchDescription) {
            try {
                if (!date.isEqual(ZonedDateTime.parse(item))) {
                    mismatchDescription.appendText("was ").appendValue(item);
                    return false;
                }
                return true;
            } catch (DateTimeParseException e) {
                mismatchDescription.appendText("was ").appendValue(item).appendText(", which could not be parsed as a ZonedDateTime");
                return false;
            }
        }

        @Override
        public void describeTo(Description description) {
            description.appendText("a String representing the same Instant as ").appendValue(date);
        }
    }

    /**
     * Creates a matcher that matches when the examined string reprensents the same instant as the reference datetime
     * @param date the reference datetime against which the examined string is checked
     */
    public static ZonedDateTimeMatcher sameInstant(ZonedDateTime date) {
        return new ZonedDateTimeMatcher(date);
    }

    /**
     * Verifies the equals/hashcode contract on the domain object.
     */
    public static <T> void equalsVerifier(Clreplaced<T> clazz) throws Exception {
        T domainObject1 = clazz.getConstructor().newInstance();
        replacedertThat(domainObject1.toString()).isNotNull();
        replacedertThat(domainObject1).isEqualTo(domainObject1);
        replacedertThat(domainObject1.hashCode()).isEqualTo(domainObject1.hashCode());
        // Test with an instance of another clreplaced
        Object testOtherObject = new Object();
        replacedertThat(domainObject1).isNotEqualTo(testOtherObject);
        replacedertThat(domainObject1).isNotEqualTo(null);
        // Test with an instance of the same clreplaced
        T domainObject2 = clazz.getConstructor().newInstance();
        replacedertThat(domainObject1).isNotEqualTo(domainObject2);
        // HashCodes are equals because the objects are not persisted yet
        replacedertThat(domainObject1.hashCode()).isEqualTo(domainObject2.hashCode());
    }

    /**
     * Create a FormattingConversionService which use ISO date format, instead of the localized one.
     * @return the FormattingConversionService
     */
    public static FormattingConversionService createFormattingConversionService() {
        DefaultFormattingConversionService dfcs = new DefaultFormattingConversionService();
        DateTimeFormatterRegistrar registrar = new DateTimeFormatterRegistrar();
        registrar.setUseIsoFormat(true);
        registrar.registerFormatters(dfcs);
        return dfcs;
    }
}

19 Source : ClientHttpRequestInterceptorImpl.java
with Apache License 2.0
from yin5980280

/**
 * restTemplate 请求响应信息拦截器
 * @author yinlin
 */
@Slf4j
public clreplaced ClientHttpRequestInterceptorImpl implements ClientHttpRequestInterceptor {

    /**
     * application/json;charset=UTF-8
     */
    private final MediaType APPLICATION_JSON_UTF8 = MediaType.parseMediaType("application/json;charset=UTF-8");

    /**
     * (non-Javadoc)
     *
     * @see org.springframework.http.client.ClientHttpRequestInterceptor#intercept
     * (org.springframework.http.HttpRequest, byte[],
     * org.springframework.http.client.ClientHttpRequestExecution)
     */
    @Override
    public ClientHttpResponse intercept(HttpRequest request, byte[] body, ClientHttpRequestExecution execution) throws IOException {
        HttpHeaders headers = request.getHeaders();
        long start = System.currentTimeMillis();
        EnhancerClientHttpResponse response = null;
        try {
            response = new EnhancerClientHttpResponse(execution.execute(request, body));
        } finally {
            String respText = response == null ? "" : response.responseText();
            int status = response == null ? 400 : response.getRawStatusCode();
            log.info("请求地址: [{}], 请求头信息: [{}], 请求参数: [{}] => 请求状态: [{}], 返回结果: [{}]. 请求花费: [{}]毫秒.", request.getURI().toString(), new ObjectMapper().writeValuereplacedtring(headers.entrySet()), new String(body), status, respText, System.currentTimeMillis() - start);
        }
        return response;
    }
}

19 Source : HttpRequestTemplate.java
with Apache License 2.0
from yin5980280

/**
 * @author : yinlin
 * @version : 1.0
 * @date : 2019-09-27 10:47
 * @Description :
 * @Copyright : Copyright (c) 2019
 * @Company : EasySite Technology Chengdu Co. Ltd.
 * @link : cn.org.easysite.spring.boot.http.HttpRequestTemplate
 */
@Slf4j
public clreplaced HttpRequestTemplate {

    /**
     * 定义JSON
     */
    private static final MediaType MEDIA_TYPE_JSON = new MediaType("application", "json", DEFAULT_CHARSET_OBJ);

    /**
     * 定义FORM请求
     */
    private static final MediaType MEDIA_TYPE_FORM = new MediaType("application", "x-www-form-urlencoded", DEFAULT_CHARSET_OBJ);

    /**
     * 定义XML请求
     */
    private static final MediaType MEDIA_TYPE_XML = new MediaType("application", "xml", DEFAULT_CHARSET_OBJ);

    private RestTemplate restTemplate;

    public HttpRequestTemplate(RestTemplate restTemplate) {
        this.restTemplate = restTemplate;
    }

    public <T> T postJson(String url, Object request, Clreplaced<T> responseType) throws RestClientException {
        if (responseType == String.clreplaced) {
            return (T) this.postJson(url, request);
        }
        return this.postJson(url, request, JsonMapper.constructType(responseType));
    }

    public <T> T postJson(String url, Object request, JavaType responseType) throws RestClientException {
        String res = this.postJson(url, request);
        return JsonMapper.fromJson(res, responseType);
    }

    /**
     *  post 支持带http header信息
     * @param url
     * @param request
     * @param headersParam
     * @return
     * @throws RestClientException
     */
    public String postJson(String url, Object request, Map<String, List<String>> headersParam) throws RestClientException {
        return this.exchange(url, HttpMethod.POST, JsonMapper.toJson(request), headersParam);
    }

    public String postJson(String url, Object request) throws RestClientException {
        return this.exchange(url, HttpMethod.POST, JsonMapper.toJson(request));
    }

    public String postJson(String url, String json) throws RestClientException {
        return this.exchange(url, HttpMethod.POST, json);
    }

    public <T> T postJsonForm(String url, Object request, Clreplaced<T> responseType) throws RestClientException {
        if (responseType == String.clreplaced) {
            return (T) this.postJsonForm(url, request);
        }
        return this.postJsonForm(url, request, JsonMapper.constructType(responseType));
    }

    public <T> T postJsonForm(String url, Object request, JavaType responseType) throws RestClientException {
        String res = this.postJsonForm(url, request);
        return JsonMapper.fromJson(res, responseType);
    }

    public String postJsonForm(String url, Object request) throws RestClientException {
        Map<String, Object> map = MapUtils.toJsonMap(request);
        return this.postForm(url, map);
    }

    public <T> T postForm(String url, Object request, Clreplaced<T> responseType) throws RestClientException {
        Map<String, Object> map = MapUtils.toTreeMap(request, true);
        return this.postForm(url, map, responseType);
    }

    /**
     * form 提交
     * @param url
     * @param request
     * @param responseType
     * @param <T>
     * @return
     * @throws RestClientException
     */
    public <T> T postForm(String url, Map<String, ? extends Object> request, Clreplaced<T> responseType) throws RestClientException {
        String res = this.postForm(url, request);
        if (responseType == String.clreplaced) {
            return (T) res;
        }
        return JsonMapper.fromJson(res, responseType);
    }

    /**
     * form提交
     * @param url
     * @param request
     * @param responseType
     * @param <T>
     * @return
     * @throws RestClientException
     */
    public <T> T postForm(String url, Map<String, ? extends Object> request, JavaType responseType) throws RestClientException {
        String res = this.postForm(url, request);
        return JsonMapper.fromJson(res, responseType);
    }

    public String postForm(String url, Map<String, ? extends Object> request) throws RestClientException {
        MultiValueMap<String, String> map = new LinkedMultiValueMap();
        for (Map.Entry<String, ?> entry : request.entrySet()) {
            Object value = entry.getValue();
            if (null == value) {
                continue;
            }
            String s;
            if (value instanceof String) {
                s = (String) value;
            } else {
                s = value.toString();
            }
            map.add(entry.getKey(), s);
        }
        HttpHeaders headers = this.getHeaders(MEDIA_TYPE_FORM);
        HttpEnreplacedy<MultiValueMap<String, String>> httpEnreplacedy = new HttpEnreplacedy<>(map, headers);
        return this.httpExchange(url, HttpMethod.POST, httpEnreplacedy);
    }

    /**
     * 提交xml
     * @param url
     * @param request
     * @param clazz
     * @param <T>
     * @return
     */
    public <T> T postXml(String url, Object request, Clreplaced<T> clazz) {
        String res = this.postXml(url, request);
        return XmlXStreamUtils.xml2Object(res, clazz);
    }

    public String postXml(String url, Object request) {
        String xml;
        if (request instanceof String) {
            xml = (String) request;
        } else {
            xml = XmlXStreamUtils.object2Xml(request);
        }
        HttpHeaders headers = this.getHeaders(MEDIA_TYPE_XML);
        HttpEnreplacedy<String> httpEnreplacedy = new HttpEnreplacedy<>(xml, headers);
        return this.httpExchange(url, HttpMethod.POST, httpEnreplacedy);
    }

    public <T> T get(String url, JavaType responseType) throws RestClientException {
        String res = this.get(url);
        return JsonMapper.fromJson(res, responseType);
    }

    public String get(String url) throws RestClientException {
        return this.exchange(url, HttpMethod.GET, null);
    }

    private String exchange(String url, HttpMethod method, String body) throws RestClientException {
        return this.exchange(url, method, body, new HttpHeaders());
    }

    private HttpHeaders getHeaders(MediaType mediaType) {
        HttpHeaders headers = this.getHeaders();
        if (null != mediaType) {
            headers.setContentType(mediaType);
        }
        return headers;
    }

    private HttpHeaders getHeaders() {
        HttpHeaders headers = new HttpHeaders();
        headers.add(MDCUtils.KEY_MSG_ID, MDCUtils.getOrGenMsgId());
        return headers;
    }

    /**
     * 支持传header
     *
     * @param url
     * @param method
     * @param body
     * @return
     * @throws RestClientException
     */
    public String exchange(String url, HttpMethod method, String body, Map<String, List<String>> headersParam) throws RestClientException {
        HttpHeaders headers = new HttpHeaders();
        if (headersParam != null) {
            Iterator<Map.Entry<String, List<String>>> it = headersParam.entrySet().iterator();
            while (it.hasNext()) {
                Map.Entry<String, List<String>> row = it.next();
                headers.put(row.getKey(), row.getValue());
            }
        }
        return this.exchange(url, method, body, headers);
    }

    public String exchange(String url, HttpMethod method, String body, HttpHeaders headers) {
        HttpEnreplacedy<String> httpEnreplacedy;
        if (HttpMethod.POST == method) {
            headers.setContentType(MEDIA_TYPE_JSON);
            httpEnreplacedy = new HttpEnreplacedy<>(body, headers);
        } else {
            httpEnreplacedy = new HttpEnreplacedy<>(headers);
        }
        return this.httpExchange(url, method, httpEnreplacedy);
    }

    public String httpExchange(String url, HttpMethod method, HttpEnreplacedy httpEnreplacedy) throws RestClientException {
        return this.httpExchange(url, method, httpEnreplacedy, String.clreplaced);
    }

    public <T> T httpExchange(String url, HttpMethod method, HttpEnreplacedy httpEnreplacedy, Clreplaced<T> responseType) throws RestClientException {
        if (StringUtils.isBlank(url)) {
            throw new RestClientException("request url can not blank");
        }
        if (url.indexOf(' ') >= 0) {
            log.warn("url中含有空格,现将空格转换为20%,以便能正常执行请求");
            url = url.replaceAll(" ", "20%");
        }
        try {
            ResponseEnreplacedy<T> responseEnreplacedy = restTemplate.exchange(url, method, httpEnreplacedy, responseType);
            HttpStatus status = responseEnreplacedy.getStatusCode();
            T res = responseEnreplacedy.getBody();
            if (status == HttpStatus.OK) {
                return res;
            }
        } catch (RestClientException e) {
            log.error("request RestClientException:" + e.getLocalizedMessage());
            throw e;
        }
        return null;
    }
}

19 Source : SpringHttpMessageConverter.java
with Apache License 2.0
from yi-jun

private Charset getContentTypeCharset(MediaType contentType) {
    if (contentType != null && contentType.getCharSet() != null) {
        return contentType.getCharSet();
    } else {
        return DEFAULT_CHARSET;
    }
}

19 Source : TestUtil.java
with Apache License 2.0
from xm-online

/**
 * Utility clreplaced for testing REST controllers.
 */
public clreplaced TestUtil {

    /**
     * MediaType for JSON UTF8
     */
    public static final MediaType APPLICATION_JSON_UTF8 = new MediaType(MediaType.APPLICATION_JSON.getType(), MediaType.APPLICATION_JSON.getSubtype(), Charset.forName("utf8"));

    /**
     * Convert an object to JSON byte array.
     *
     * @param object
     *            the object to convert
     * @return the JSON byte array
     * @throws IOException
     */
    public static byte[] convertObjectToJsonBytes(Object object) throws IOException {
        ObjectMapper mapper = new ObjectMapper();
        mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
        JavaTimeModule module = new JavaTimeModule();
        mapper.registerModule(module);
        return mapper.writeValueAsBytes(object);
    }

    /**
     * Create a byte array with a specific size filled with specified data.
     *
     * @param size the size of the byte array
     * @param data the data to put in the byte array
     * @return the JSON byte array
     */
    public static byte[] createByteArray(int size, String data) {
        byte[] byteArray = new byte[size];
        for (int i = 0; i < size; i++) {
            byteArray[i] = Byte.parseByte(data, 2);
        }
        return byteArray;
    }

    /**
     * A matcher that tests that the examined string represents the same instant as the reference datetime.
     */
    public static clreplaced ZonedDateTimeMatcher extends TypeSafeDiagnosingMatcher<String> {

        private final ZonedDateTime date;

        public ZonedDateTimeMatcher(ZonedDateTime date) {
            this.date = date;
        }

        @Override
        protected boolean matchesSafely(String item, Description mismatchDescription) {
            try {
                if (!date.isEqual(ZonedDateTime.parse(item))) {
                    mismatchDescription.appendText("was ").appendValue(item);
                    return false;
                }
                return true;
            } catch (DateTimeParseException e) {
                mismatchDescription.appendText("was ").appendValue(item).appendText(", which could not be parsed as a ZonedDateTime");
                return false;
            }
        }

        @Override
        public void describeTo(Description description) {
            description.appendText("a String representing the same Instant as ").appendValue(date);
        }
    }

    /**
     * Creates a matcher that matches when the examined string reprensents the same instant as the reference datetime
     * @param date the reference datetime against which the examined string is checked
     */
    public static ZonedDateTimeMatcher sameInstant(ZonedDateTime date) {
        return new ZonedDateTimeMatcher(date);
    }

    /**
     * Verifies the equals/hashcode contract on the domain object.
     */
    @SuppressWarnings("unchecked")
    public static void equalsVerifier(Clreplaced clazz) throws Exception {
        Object domainObject1 = clazz.getConstructor().newInstance();
        replacedertThat(domainObject1.toString()).isNotNull();
        replacedertThat(domainObject1).isEqualTo(domainObject1);
        replacedertThat(domainObject1.hashCode()).isEqualTo(domainObject1.hashCode());
        // Test with an instance of another clreplaced
        Object testOtherObject = new Object();
        replacedertThat(domainObject1).isNotEqualTo(testOtherObject);
        replacedertThat(domainObject1).isNotEqualTo(null);
        // Test with an instance of the same clreplaced
        Object domainObject2 = clazz.getConstructor().newInstance();
        replacedertThat(domainObject1).isNotEqualTo(domainObject2);
        // HashCodes are equals because the objects are not persisted yet
        replacedertThat(domainObject1.hashCode()).isEqualTo(domainObject2.hashCode());
    }
}

19 Source : TestUtil.java
with Apache License 2.0
from xm-online

/**
 * Utility clreplaced for testing REST controllers.
 */
public clreplaced TestUtil {

    /**
     * MediaType for JSON UTF8
     */
    public static final MediaType APPLICATION_JSON_UTF8 = new MediaType(MediaType.APPLICATION_JSON.getType(), MediaType.APPLICATION_JSON.getSubtype(), Charset.forName("utf8"));

    /**
     * Convert an object to JSON byte array.
     *
     * @param object the object to convert
     * @return the JSON byte array
     * @throws IOException
     */
    public static byte[] convertObjectToJsonBytes(Object object) throws IOException {
        ObjectMapper mapper = getObjectMapper();
        return mapper.writeValueAsBytes(object);
    }

    public static <T> T convertJsonBytesToObject(byte[] bytes, Clreplaced<T> clazz) throws IOException {
        ObjectMapper mapper = getObjectMapper();
        return mapper.readValue(bytes, clazz);
    }

    private static ObjectMapper getObjectMapper() {
        ObjectMapper mapper = new ObjectMapper();
        mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
        JavaTimeModule module = new JavaTimeModule();
        mapper.registerModule(module);
        return mapper;
    }

    /**
     * Create a byte array with a specific size filled with specified data.
     *
     * @param size the size of the byte array
     * @param data the data to put in the byte array
     * @return the JSON byte array
     */
    public static byte[] createByteArray(int size, String data) {
        byte[] byteArray = new byte[size];
        for (int i = 0; i < size; i++) {
            byteArray[i] = Byte.parseByte(data, 2);
        }
        return byteArray;
    }

    /**
     * A matcher that tests that the examined string represents the same instant as the reference datetime.
     */
    public static clreplaced InstantMatcher extends TypeSafeDiagnosingMatcher<String> {

        private final Instant date;

        public InstantMatcher(Instant date) {
            this.date = date;
        }

        @Override
        protected boolean matchesSafely(String item, Description mismatchDescription) {
            try {
                if (!date.equals(Instant.parse(item))) {
                    mismatchDescription.appendText("was ").appendValue(item);
                    return false;
                }
                return true;
            } catch (DateTimeParseException e) {
                mismatchDescription.appendText("was ").appendValue(item).appendText(", which could not be parsed as a Instant");
                return false;
            }
        }

        @Override
        public void describeTo(Description description) {
            description.appendText("a String representing the same Instant as ").appendValue(date);
        }
    }

    /**
     * Creates a matcher that matches when the examined string reprensents the same instant as the reference datetime
     *
     * @param date the reference datetime against which the examined string is checked
     */
    public static InstantMatcher sameInstant(Instant date) {
        return new InstantMatcher(date);
    }

    /**
     * Verifies the equals/hashcode contract on the domain object.
     */
    @SuppressWarnings("unchecked")
    public static void equalsVerifier(Clreplaced clazz) throws Exception {
        Object domainObject1 = clazz.getConstructor().newInstance();
        replacedertThat(domainObject1.toString()).isNotNull();
        replacedertThat(domainObject1).isEqualTo(domainObject1);
        replacedertThat(domainObject1.hashCode()).isEqualTo(domainObject1.hashCode());
        // Test with an instance of another clreplaced
        Object testOtherObject = new Object();
        replacedertThat(domainObject1).isNotEqualTo(testOtherObject);
        replacedertThat(domainObject1).isNotEqualTo(null);
        // Test with an instance of the same clreplaced
        Object domainObject2 = clazz.getConstructor().newInstance();
        replacedertThat(domainObject1).isNotEqualTo(domainObject2);
        // HashCodes are equals because the objects are not persisted yet
        replacedertThat(domainObject1.hashCode()).isEqualTo(domainObject2.hashCode());
    }
}

19 Source : MultipartMixedConverter.java
with Apache License 2.0
from xm-online

private boolean isMultipart(MultiValueMap<String, ?> map, MediaType contentType) {
    if (contentType != null) {
        return MediaType.MULTIPART_FORM_DATA.includes(contentType) || mixed.includes(contentType) || related.includes(contentType);
    }
    for (Map.Entry<String, ?> entiry : map.entrySet()) {
        for (Object value : map.get(entiry.getKey())) {
            if (value != null && !(value instanceof String)) {
                return true;
            }
        }
    }
    return false;
}

19 Source : WebMvcConfiguration.java
with Apache License 2.0
from xm-online

private void addSupportedMediaTypesTo(List<HttpMessageConverter<?>> converters, Clreplaced<? extends AbstractHttpMessageConverter<?>> targetConverterClreplaced, MediaType... mediaTypes) {
    converters.stream().filter(conv -> conv.getClreplaced() == targetConverterClreplaced).map(conv -> (AbstractHttpMessageConverter) conv).forEach(conv -> addSupportedMediaTypes(conv, Arrays.asList(mediaTypes)));
}

19 Source : TestUtil.java
with Apache License 2.0
from xm-online

/**
 * Utility clreplaced for testing REST controllers.
 */
public clreplaced TestUtil {

    /**
     * MediaType for JSON UTF8
     */
    public static final MediaType APPLICATION_JSON_UTF8 = new MediaType(MediaType.APPLICATION_JSON.getType(), MediaType.APPLICATION_JSON.getSubtype(), StandardCharsets.UTF_8);

    /**
     * Convert an object to JSON byte array.
     *
     * @param object
     *            the object to convert
     * @return the JSON byte array
     * @throws IOException
     */
    public static byte[] convertObjectToJsonBytes(Object object) throws IOException {
        ObjectMapper mapper = new ObjectMapper();
        mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
        JavaTimeModule module = new JavaTimeModule();
        mapper.registerModule(module);
        return mapper.writeValueAsBytes(object);
    }

    /**
     * Create a byte array with a specific size filled with specified data.
     *
     * @param size the size of the byte array
     * @param data the data to put in the byte array
     * @return the JSON byte array
     */
    public static byte[] createByteArray(int size, String data) {
        byte[] byteArray = new byte[size];
        for (int i = 0; i < size; i++) {
            byteArray[i] = Byte.parseByte(data, 2);
        }
        return byteArray;
    }

    @SneakyThrows
    public static String loadFile(String path) {
        InputStream cfgInputStream = new ClreplacedPathResource(path).getInputStream();
        return IOUtils.toString(cfgInputStream, UTF_8);
    }

    /**
     * A matcher that tests that the examined string represents the same instant as the reference datetime.
     */
    public static clreplaced ZonedDateTimeMatcher extends TypeSafeDiagnosingMatcher<String> {

        private final ZonedDateTime date;

        public ZonedDateTimeMatcher(ZonedDateTime date) {
            this.date = date;
        }

        @Override
        protected boolean matchesSafely(String item, Description mismatchDescription) {
            try {
                if (!date.isEqual(ZonedDateTime.parse(item))) {
                    mismatchDescription.appendText("was ").appendValue(item);
                    return false;
                }
                return true;
            } catch (DateTimeParseException e) {
                mismatchDescription.appendText("was ").appendValue(item).appendText(", which could not be parsed as a ZonedDateTime");
                return false;
            }
        }

        @Override
        public void describeTo(Description description) {
            description.appendText("a String representing the same Instant as ").appendValue(date);
        }
    }

    /**
     * Creates a matcher that matches when the examined string reprensents the same instant as the reference datetime
     * @param date the reference datetime against which the examined string is checked
     */
    public static ZonedDateTimeMatcher sameInstant(ZonedDateTime date) {
        return new ZonedDateTimeMatcher(date);
    }

    /**
     * Verifies the equals/hashcode contract on the domain object.
     */
    public static void equalsVerifier(Clreplaced<?> clazz) throws Exception {
        Object domainObject1 = clazz.getConstructor().newInstance();
        replacedertThat(domainObject1.toString()).isNotNull();
        replacedertThat(domainObject1).isEqualTo(domainObject1);
        replacedertThat(domainObject1.hashCode()).isEqualTo(domainObject1.hashCode());
        // Test with an instance of another clreplaced
        Object testOtherObject = new Object();
        replacedertThat(domainObject1).isNotEqualTo(testOtherObject);
        replacedertThat(domainObject1).isNotEqualTo(null);
        // Test with an instance of the same clreplaced
        Object domainObject2 = clazz.getConstructor().newInstance();
        replacedertThat(domainObject1).isNotEqualTo(domainObject2);
    }
}

19 Source : SignFilter.java
with MIT License
from xk11961677

/**
 * 检测是否验证签名与修改请求体
 * 验证post请求 且 json 请求
 *
 * @param method
 * @param mediaType
 * @return
 */
private boolean match(String method, MediaType mediaType) {
    return GatewayConstants.METHOD_POST.equals(method) && MediaType.APPLICATION_JSON.isCompatibleWith(mediaType);
}

19 Source : ErrorExceptionHandler.java
with MIT License
from wligang

/**
 * Determine if the stacktrace attribute should be included.
 *
 * @param request  the source request
 * @param produces the media type produced (or {@code MediaType.ALL})
 * @return if the stacktrace attribute should be included
 */
protected boolean isIncludeStackTrace(HttpServletRequest request, MediaType produces) {
    ErrorProperties.IncludeStacktrace include = this.serverProperties.getError().getIncludeStacktrace();
    if (include == ErrorProperties.IncludeStacktrace.ALWAYS) {
        return true;
    }
    if (include == ErrorProperties.IncludeStacktrace.ON_TRACE_PARAM) {
        return getTraceParameter(request);
    }
    return false;
}

19 Source : TestAcceptedMediaTypes.java
with Apache License 2.0
from wkorando

/**
 * Example of using dynamic test functionality in JUnit 5. Examples demonstrates
 * how dynamic test might be used to ensure POST endpoints consume a predefined
 * list of MediaTypes.
 *
 * @author William.Korando
 */
public clreplaced TestAcceptedMediaTypes {

    private static final MediaType[] SUPPORTED_MEDIA_TYPES = new MediaType[] { MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML };

    @TestFactory
    Collection<DynamicNode> testAcceptedMediaTypes() throws Exception {
        // Creating a clreplacedpath scanner to find all controller clreplacedes in project
        ClreplacedPathBeanDefinitionScanner scanner = new ClreplacedPathBeanDefinitionScanner(new DefaultListableBeanFactory(), false);
        scanner.addIncludeFilter(new AnnotationTypeFilter(RestController.clreplaced));
        Set<BeanDefinition> beanDefinitons = scanner.findCandidateComponents("com.bk.hotel");
        Set<Object> controllers = new HashSet<>();
        Set<Clreplaced<?>> controllersClreplacedes = new HashSet<>();
        // Instantiating controller clreplacedes
        for (BeanDefinition beanDefiniton : beanDefinitons) {
            String clreplacedName = beanDefiniton.getBeanClreplacedName();
            Clreplaced<?> controllerClazz = ClreplacedLoader.getSystemClreplacedLoader().loadClreplaced(clreplacedName);
            controllersClreplacedes.add(controllerClazz);
            Constructor<?> constructor = controllerClazz.getDeclaredConstructors()[0];
            Object[] arguments = new Object[constructor.getParameterTypes().length];
            int i = 0;
            for (Clreplaced<?> parameterType : constructor.getParameterTypes()) {
                arguments[i] = mock(parameterType);
                i++;
            }
            controllers.add(constructor.newInstance(arguments));
        }
        MockMvc mockMvc = MockMvcBuilders.standaloneSetup(controllers.toArray()).build();
        List<DynamicNode> containers = new ArrayList<>();
        // Check if controller has a POST endpoint and call it with all the different
        // mediatypes, throw an error in a 415 (unsupported media type) is returned
        for (Clreplaced<?> controllerClazz : controllersClreplacedes) {
            RequestMapping mapping = controllerClazz.getAnnotationsByType(RequestMapping.clreplaced)[0];
            StringBuilder builder = new StringBuilder();
            builder.append(mapping.value()[0]);
            for (Method method : controllerClazz.getMethods()) {
                if (method.isAnnotationPresent(PostMapping.clreplaced)) {
                    List<DynamicTest> dynamicTests = new ArrayList<>();
                    for (MediaType mediaType : SUPPORTED_MEDIA_TYPES) {
                        dynamicTests.add(dynamicTest(mediaType.toString(), () -> mockMvc.perform(post(builder.toString()).contentType(mediaType)).andExpect(status().is(IsNot.not(415)))));
                    }
                    // Group the test into containers so the test report will be separated by controller
                    containers.add(dynamicContainer(builder.toString(), dynamicTests));
                }
            }
        }
        return containers;
    }
}

19 Source : TestUtil.java
with Apache License 2.0
from viz-centric

/**
 * Utility clreplaced for testing REST controllers.
 */
public clreplaced TestUtil {

    /**
     * MediaType for JSON UTF8
     */
    public static final MediaType APPLICATION_JSON_UTF8 = new MediaType(MediaType.APPLICATION_JSON.getType(), MediaType.APPLICATION_JSON.getSubtype(), Charset.forName("utf8"));

    /**
     * Convert an object to JSON byte array.
     *
     * @param object
     *            the object to convert
     * @return the JSON byte array
     * @throws IOException
     */
    public static byte[] convertObjectToJsonBytes(Object object) throws IOException {
        ObjectMapper mapper = new ObjectMapper();
        mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
        JavaTimeModule module = new JavaTimeModule();
        mapper.registerModule(module);
        return mapper.writeValueAsBytes(object);
    }

    /**
     * Create a byte array with a specific size filled with specified data.
     *
     * @param size the size of the byte array
     * @param data the data to put in the byte array
     * @return the JSON byte array
     */
    public static byte[] createByteArray(int size, String data) {
        byte[] byteArray = new byte[size];
        for (int i = 0; i < size; i++) {
            byteArray[i] = Byte.parseByte(data, 2);
        }
        return byteArray;
    }

    /**
     * A matcher that tests that the examined string represents the same instant as the reference datetime.
     */
    public static clreplaced ZonedDateTimeMatcher extends TypeSafeDiagnosingMatcher<String> {

        private final ZonedDateTime date;

        public ZonedDateTimeMatcher(ZonedDateTime date) {
            this.date = date;
        }

        @Override
        protected boolean matchesSafely(String item, Description mismatchDescription) {
            try {
                if (!date.isEqual(ZonedDateTime.parse(item))) {
                    mismatchDescription.appendText("was ").appendValue(item);
                    return false;
                }
                return true;
            } catch (DateTimeParseException e) {
                mismatchDescription.appendText("was ").appendValue(item).appendText(", which could not be parsed as a ZonedDateTime");
                return false;
            }
        }

        @Override
        public void describeTo(Description description) {
            description.appendText("a String representing the same Instant as ").appendValue(date);
        }
    }

    /**
     * Creates a matcher that matches when the examined string reprensents the same instant as the reference datetime
     * @param date the reference datetime against which the examined string is checked
     */
    public static ZonedDateTimeMatcher sameInstant(ZonedDateTime date) {
        return new ZonedDateTimeMatcher(date);
    }

    /**
     * Verifies the equals/hashcode contract on the domain object.
     */
    @SuppressWarnings("unchecked")
    public static void equalsVerifier(Clreplaced clazz) throws Exception {
        Object domainObject1 = clazz.getConstructor().newInstance();
        replacedertThat(domainObject1.toString()).isNotNull();
        replacedertThat(domainObject1).isEqualTo(domainObject1);
        replacedertThat(domainObject1.hashCode()).isEqualTo(domainObject1.hashCode());
        // Test with an instance of another clreplaced
        Object testOtherObject = new Object();
        replacedertThat(domainObject1).isNotEqualTo(testOtherObject);
        // Test with an instance of the same clreplaced
        Object domainObject2 = clazz.getConstructor().newInstance();
        replacedertThat(domainObject1).isNotEqualTo(domainObject2);
    }
}

19 Source : TestUtil.java
with Apache License 2.0
from viz-centric

/**
 * Utility clreplaced for testing REST controllers.
 */
public clreplaced TestUtil {

    /**
     * MediaType for JSON UTF8
     */
    public static final MediaType APPLICATION_JSON_UTF8 = new MediaType(MediaType.APPLICATION_JSON.getType(), MediaType.APPLICATION_JSON.getSubtype(), Charset.forName("utf8"));

    /**
     * Convert an object to JSON byte array.
     *
     * @param object
     *            the object to convert
     * @return the JSON byte array
     * @throws IOException
     */
    public static byte[] convertObjectToJsonBytes(Object object) throws IOException {
        ObjectMapper mapper = new ObjectMapper();
        mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
        JavaTimeModule module = new JavaTimeModule();
        mapper.registerModule(module);
        return mapper.writeValueAsBytes(object);
    }

    /**
     * Create a byte array with a specific size filled with specified data.
     *
     * @param size the size of the byte array
     * @param data the data to put in the byte array
     * @return the JSON byte array
     */
    public static byte[] createByteArray(int size, String data) {
        byte[] byteArray = new byte[size];
        for (int i = 0; i < size; i++) {
            byteArray[i] = Byte.parseByte(data, 2);
        }
        return byteArray;
    }

    /**
     * A matcher that tests that the examined string represents the same instant as the reference datetime.
     */
    public static clreplaced ZonedDateTimeMatcher extends TypeSafeDiagnosingMatcher<String> {

        private final ZonedDateTime date;

        public ZonedDateTimeMatcher(ZonedDateTime date) {
            this.date = date;
        }

        @Override
        protected boolean matchesSafely(String item, Description mismatchDescription) {
            try {
                if (!date.isEqual(ZonedDateTime.parse(item))) {
                    mismatchDescription.appendText("was ").appendValue(item);
                    return false;
                }
                return true;
            } catch (DateTimeParseException e) {
                mismatchDescription.appendText("was ").appendValue(item).appendText(", which could not be parsed as a ZonedDateTime");
                return false;
            }
        }

        @Override
        public void describeTo(Description description) {
            description.appendText("a String representing the same Instant as ").appendValue(date);
        }
    }

    /**
     * Creates a matcher that matches when the examined string reprensents the same instant as the reference datetime
     * @param date the reference datetime against which the examined string is checked
     */
    public static ZonedDateTimeMatcher sameInstant(ZonedDateTime date) {
        return new ZonedDateTimeMatcher(date);
    }

    /**
     * Verifies the equals/hashcode contract on the domain object.
     */
    @SuppressWarnings("unchecked")
    public static void equalsVerifier(Clreplaced clazz) throws Exception {
        Object domainObject1 = clazz.getConstructor().newInstance();
        replacedertThat(domainObject1.toString()).isNotNull();
        replacedertThat(domainObject1).isEqualTo(domainObject1);
        replacedertThat(domainObject1.hashCode()).isEqualTo(domainObject1.hashCode());
        // Test with an instance of another clreplaced
        Object testOtherObject = new Object();
        replacedertThat(domainObject1).isNotEqualTo(testOtherObject);
        replacedertThat(domainObject1).isNotEqualTo(null);
        // Test with an instance of the same clreplaced
        Object domainObject2 = clazz.getConstructor().newInstance();
        replacedertThat(domainObject1).isNotEqualTo(domainObject2);
        // HashCodes are equals because the objects are not persisted yet
        replacedertThat(domainObject1.hashCode()).isEqualTo(domainObject2.hashCode());
    }

    public static ComparatorType getComparetorType(String opr) {
        switch(opr) {
            case "=":
                return ComparatorType.EQ;
            case ">":
                return ComparatorType.GT;
            case "<":
                return ComparatorType.LT;
            case "<=":
                return ComparatorType.LTE;
            case ">=":
                return ComparatorType.GTE;
            case "<>":
                return ComparatorType.NEQ;
        }
        return null;
    }
}

19 Source : RequestResponseBodyAdviceChainTests.java
with MIT License
from Vip-Augus

/**
 * Unit tests for {@link RequestResponseBodyAdviceChain}.
 *
 * @author Rossen Stoyanchev
 * @since 4.2
 */
public clreplaced RequestResponseBodyAdviceChainTests {

    private String body;

    private MediaType contentType;

    private Clreplaced<? extends HttpMessageConverter<?>> converterType;

    private MethodParameter paramType;

    private MethodParameter returnType;

    private ServerHttpRequest request;

    private ServerHttpResponse response;

    @Before
    public void setup() {
        this.body = "body";
        this.contentType = MediaType.TEXT_PLAIN;
        this.converterType = StringHttpMessageConverter.clreplaced;
        this.paramType = new MethodParameter(ClreplacedUtils.getMethod(this.getClreplaced(), "handle", String.clreplaced), 0);
        this.returnType = new MethodParameter(ClreplacedUtils.getMethod(this.getClreplaced(), "handle", String.clreplaced), -1);
        this.request = new ServletServerHttpRequest(new MockHttpServletRequest());
        this.response = new ServletServerHttpResponse(new MockHttpServletResponse());
    }

    @SuppressWarnings("unchecked")
    @Test
    public void requestBodyAdvice() throws IOException {
        RequestBodyAdvice requestAdvice = Mockito.mock(RequestBodyAdvice.clreplaced);
        ResponseBodyAdvice<String> responseAdvice = Mockito.mock(ResponseBodyAdvice.clreplaced);
        List<Object> advice = Arrays.asList(requestAdvice, responseAdvice);
        RequestResponseBodyAdviceChain chain = new RequestResponseBodyAdviceChain(advice);
        HttpInputMessage wrapped = new ServletServerHttpRequest(new MockHttpServletRequest());
        given(requestAdvice.supports(this.paramType, String.clreplaced, this.converterType)).willReturn(true);
        given(requestAdvice.beforeBodyRead(eq(this.request), eq(this.paramType), eq(String.clreplaced), eq(this.converterType))).willReturn(wrapped);
        replacedertSame(wrapped, chain.beforeBodyRead(this.request, this.paramType, String.clreplaced, this.converterType));
        String modified = "body++";
        given(requestAdvice.afterBodyRead(eq(this.body), eq(this.request), eq(this.paramType), eq(String.clreplaced), eq(this.converterType))).willReturn(modified);
        replacedertEquals(modified, chain.afterBodyRead(this.body, this.request, this.paramType, String.clreplaced, this.converterType));
    }

    @SuppressWarnings("unchecked")
    @Test
    public void responseBodyAdvice() {
        RequestBodyAdvice requestAdvice = Mockito.mock(RequestBodyAdvice.clreplaced);
        ResponseBodyAdvice<String> responseAdvice = Mockito.mock(ResponseBodyAdvice.clreplaced);
        List<Object> advice = Arrays.asList(requestAdvice, responseAdvice);
        RequestResponseBodyAdviceChain chain = new RequestResponseBodyAdviceChain(advice);
        String expected = "body++";
        given(responseAdvice.supports(this.returnType, this.converterType)).willReturn(true);
        given(responseAdvice.beforeBodyWrite(eq(this.body), eq(this.returnType), eq(this.contentType), eq(this.converterType), same(this.request), same(this.response))).willReturn(expected);
        String actual = (String) chain.beforeBodyWrite(this.body, this.returnType, this.contentType, this.converterType, this.request, this.response);
        replacedertEquals(expected, actual);
    }

    @Test
    public void controllerAdvice() {
        Object adviceBean = new ControllerAdviceBean(new MyControllerAdvice());
        RequestResponseBodyAdviceChain chain = new RequestResponseBodyAdviceChain(Collections.singletonList(adviceBean));
        String actual = (String) chain.beforeBodyWrite(this.body, this.returnType, this.contentType, this.converterType, this.request, this.response);
        replacedertEquals("body-MyControllerAdvice", actual);
    }

    @Test
    public void controllerAdviceNotApplicable() {
        Object adviceBean = new ControllerAdviceBean(new TargetedControllerAdvice());
        RequestResponseBodyAdviceChain chain = new RequestResponseBodyAdviceChain(Collections.singletonList(adviceBean));
        String actual = (String) chain.beforeBodyWrite(this.body, this.returnType, this.contentType, this.converterType, this.request, this.response);
        replacedertEquals(this.body, actual);
    }

    @ControllerAdvice
    private static clreplaced MyControllerAdvice implements ResponseBodyAdvice<String> {

        @Override
        public boolean supports(MethodParameter returnType, Clreplaced<? extends HttpMessageConverter<?>> converterType) {
            return true;
        }

        @Override
        public String beforeBodyWrite(String body, MethodParameter returnType, MediaType contentType, Clreplaced<? extends HttpMessageConverter<?>> converterType, ServerHttpRequest request, ServerHttpResponse response) {
            return body + "-MyControllerAdvice";
        }
    }

    @ControllerAdvice(annotations = Controller.clreplaced)
    private static clreplaced TargetedControllerAdvice implements ResponseBodyAdvice<String> {

        @Override
        public boolean supports(MethodParameter returnType, Clreplaced<? extends HttpMessageConverter<?>> converterType) {
            return true;
        }

        @Override
        public String beforeBodyWrite(String body, MethodParameter returnType, MediaType contentType, Clreplaced<? extends HttpMessageConverter<?>> converterType, ServerHttpRequest request, ServerHttpResponse response) {
            return body + "-TargetedControllerAdvice";
        }
    }

    @SuppressWarnings("unused")
    @ResponseBody
    public String handle(String body) {
        return "";
    }
}

19 Source : ContentNegotiatingViewResolver.java
with MIT License
from Vip-Augus

/**
 * Return the more specific of the acceptable and the producible media types
 * with the q-value of the former.
 */
private MediaType getMostSpecificMediaType(MediaType acceptType, MediaType produceType) {
    produceType = produceType.copyQualityValue(acceptType);
    return (MediaType.SPECIFICITY_COMPARATOR.compare(acceptType, produceType) < 0 ? acceptType : produceType);
}

19 Source : SseEmitter.java
with MIT License
from Vip-Augus

/**
 * A specialization of {@link ResponseBodyEmitter} for sending
 * <a href="https://www.w3.org/TR/eventsource/">Server-Sent Events</a>.
 *
 * @author Rossen Stoyanchev
 * @author Juergen Hoeller
 * @since 4.2
 */
public clreplaced SseEmitter extends ResponseBodyEmitter {

    static final MediaType TEXT_PLAIN = new MediaType("text", "plain", StandardCharsets.UTF_8);

    static final MediaType UTF8_TEXT_EVENTSTREAM = new MediaType("text", "event-stream", StandardCharsets.UTF_8);

    /**
     * Create a new SseEmitter instance.
     */
    public SseEmitter() {
        super();
    }

    /**
     * Create a SseEmitter with a custom timeout value.
     * <p>By default not set in which case the default configured in the MVC
     * Java Config or the MVC namespace is used, or if that's not set, then the
     * timeout depends on the default of the underlying server.
     * @param timeout timeout value in milliseconds
     * @since 4.2.2
     */
    public SseEmitter(Long timeout) {
        super(timeout);
    }

    @Override
    protected void extendResponse(ServerHttpResponse outputMessage) {
        super.extendResponse(outputMessage);
        HttpHeaders headers = outputMessage.getHeaders();
        if (headers.getContentType() == null) {
            headers.setContentType(UTF8_TEXT_EVENTSTREAM);
        }
    }

    /**
     * Send the object formatted as a single SSE "data" line. It's equivalent to:
     * <pre>
     * // static import of SseEmitter.*
     *
     * SseEmitter emitter = new SseEmitter();
     * emitter.send(event().data(myObject));
     * </pre>
     *
     * <p>Please, see {@link ResponseBodyEmitter#send(Object) parent Javadoc}
     * for important notes on exception handling.
     *
     * @param object the object to write
     * @throws IOException raised when an I/O error occurs
     * @throws java.lang.IllegalStateException wraps any other errors
     */
    @Override
    public void send(Object object) throws IOException {
        send(object, null);
    }

    /**
     * Send the object formatted as a single SSE "data" line. It's equivalent to:
     * <pre>
     * // static import of SseEmitter.*
     *
     * SseEmitter emitter = new SseEmitter();
     * emitter.send(event().data(myObject, MediaType.APPLICATION_JSON));
     * </pre>
     *
     * <p>Please, see {@link ResponseBodyEmitter#send(Object) parent Javadoc}
     * for important notes on exception handling.
     *
     * @param object the object to write
     * @param mediaType a MediaType hint for selecting an HttpMessageConverter
     * @throws IOException raised when an I/O error occurs
     */
    @Override
    public void send(Object object, @Nullable MediaType mediaType) throws IOException {
        send(event().data(object, mediaType));
    }

    /**
     * Send an SSE event prepared with the given builder. For example:
     * <pre>
     * // static import of SseEmitter
     * SseEmitter emitter = new SseEmitter();
     * emitter.send(event().name("update").id("1").data(myObject));
     * </pre>
     * @param builder a builder for an SSE formatted event.
     * @throws IOException raised when an I/O error occurs
     */
    public void send(SseEventBuilder builder) throws IOException {
        Set<DataWithMediaType> dataToSend = builder.build();
        synchronized (this) {
            for (DataWithMediaType entry : dataToSend) {
                super.send(entry.getData(), entry.getMediaType());
            }
        }
    }

    @Override
    public String toString() {
        return "SseEmitter@" + ObjectUtils.getIdenreplacedyHexString(this);
    }

    public static SseEventBuilder event() {
        return new SseEventBuilderImpl();
    }

    /**
     * A builder for an SSE event.
     */
    public interface SseEventBuilder {

        /**
         * Add an SSE "id" line.
         */
        SseEventBuilder id(String id);

        /**
         * Add an SSE "event" line.
         */
        SseEventBuilder name(String eventName);

        /**
         * Add an SSE "retry" line.
         */
        SseEventBuilder reconnectTime(long reconnectTimeMillis);

        /**
         * Add an SSE "comment" line.
         */
        SseEventBuilder comment(String comment);

        /**
         * Add an SSE "data" line.
         */
        SseEventBuilder data(Object object);

        /**
         * Add an SSE "data" line.
         */
        SseEventBuilder data(Object object, @Nullable MediaType mediaType);

        /**
         * Return one or more Object-MediaType  pairs to write via
         * {@link #send(Object, MediaType)}.
         * @since 4.2.3
         */
        Set<DataWithMediaType> build();
    }

    /**
     * Default implementation of SseEventBuilder.
     */
    private static clreplaced SseEventBuilderImpl implements SseEventBuilder {

        private final Set<DataWithMediaType> dataToSend = new LinkedHashSet<>(4);

        @Nullable
        private StringBuilder sb;

        @Override
        public SseEventBuilder id(String id) {
            append("id:").append(id).append("\n");
            return this;
        }

        @Override
        public SseEventBuilder name(String name) {
            append("event:").append(name).append("\n");
            return this;
        }

        @Override
        public SseEventBuilder reconnectTime(long reconnectTimeMillis) {
            append("retry:").append(String.valueOf(reconnectTimeMillis)).append("\n");
            return this;
        }

        @Override
        public SseEventBuilder comment(String comment) {
            append(":").append(comment).append("\n");
            return this;
        }

        @Override
        public SseEventBuilder data(Object object) {
            return data(object, null);
        }

        @Override
        public SseEventBuilder data(Object object, @Nullable MediaType mediaType) {
            append("data:");
            saveAppendedText();
            this.dataToSend.add(new DataWithMediaType(object, mediaType));
            append("\n");
            return this;
        }

        SseEventBuilderImpl append(String text) {
            if (this.sb == null) {
                this.sb = new StringBuilder();
            }
            this.sb.append(text);
            return this;
        }

        @Override
        public Set<DataWithMediaType> build() {
            if (!StringUtils.hasLength(this.sb) && this.dataToSend.isEmpty()) {
                return Collections.emptySet();
            }
            append("\n");
            saveAppendedText();
            return this.dataToSend;
        }

        private void saveAppendedText() {
            if (this.sb != null) {
                this.dataToSend.add(new DataWithMediaType(this.sb.toString(), TEXT_PLAIN));
                this.sb = null;
            }
        }
    }
}

19 Source : SseEmitter.java
with MIT License
from Vip-Augus

/**
 * Send the object formatted as a single SSE "data" line. It's equivalent to:
 * <pre>
 * // static import of SseEmitter.*
 *
 * SseEmitter emitter = new SseEmitter();
 * emitter.send(event().data(myObject, MediaType.APPLICATION_JSON));
 * </pre>
 *
 * <p>Please, see {@link ResponseBodyEmitter#send(Object) parent Javadoc}
 * for important notes on exception handling.
 *
 * @param object the object to write
 * @param mediaType a MediaType hint for selecting an HttpMessageConverter
 * @throws IOException raised when an I/O error occurs
 */
@Override
public void send(Object object, @Nullable MediaType mediaType) throws IOException {
    send(event().data(object, mediaType));
}

19 Source : ResponseBodyEmitter.java
with MIT License
from Vip-Augus

private void sendInternal(Object object, @Nullable MediaType mediaType) throws IOException {
    if (this.handler != null) {
        try {
            this.handler.send(object, mediaType);
        } catch (IOException ex) {
            this.sendFailed = true;
            throw ex;
        } catch (Throwable ex) {
            this.sendFailed = true;
            throw new IllegalStateException("Failed to send " + object, ex);
        }
    } else {
        this.earlySendAttempts.add(new DataWithMediaType(object, mediaType));
    }
}

19 Source : ResponseBodyEmitter.java
with MIT License
from Vip-Augus

/**
 * Overloaded variant of {@link #send(Object)} that also accepts a MediaType
 * hint for how to serialize the given Object.
 * @param object the object to write
 * @param mediaType a MediaType hint for selecting an HttpMessageConverter
 * @throws IOException raised when an I/O error occurs
 * @throws java.lang.IllegalStateException wraps any other errors
 */
public synchronized void send(Object object, @Nullable MediaType mediaType) throws IOException {
    replacedert.state(!this.complete, "ResponseBodyEmitter is already set complete");
    sendInternal(object, mediaType);
}

19 Source : RequestResponseBodyAdviceChain.java
with MIT License
from Vip-Augus

@Override
@Nullable
public Object beforeBodyWrite(@Nullable Object body, MethodParameter returnType, MediaType contentType, Clreplaced<? extends HttpMessageConverter<?>> converterType, ServerHttpRequest request, ServerHttpResponse response) {
    return processBody(body, returnType, contentType, converterType, request, response);
}

19 Source : ReactiveTypeHandler.java
with MIT License
from Vip-Augus

private ResponseBodyEmitter getEmitter(MediaType mediaType) {
    return new ResponseBodyEmitter(STREAMING_TIMEOUT_VALUE) {

        @Override
        protected void extendResponse(ServerHttpResponse outputMessage) {
            outputMessage.getHeaders().setContentType(mediaType);
        }
    };
}

19 Source : AbstractMessageConverterMethodProcessor.java
with MIT License
from Vip-Augus

private boolean safeMediaType(MediaType mediaType) {
    return (WHITELISTED_MEDIA_BASE_TYPES.contains(mediaType.getType()) || mediaType.getSubtype().endsWith("+xml"));
}

19 Source : ProducesRequestCondition.java
with MIT License
from Vip-Augus

private int indexOfEqualMediaType(MediaType mediaType) {
    for (int i = 0; i < getExpressionsToCompare().size(); i++) {
        MediaType currentMediaType = getExpressionsToCompare().get(i).getMediaType();
        if (mediaType.getType().equalsIgnoreCase(currentMediaType.getType()) && mediaType.getSubtype().equalsIgnoreCase(currentMediaType.getSubtype())) {
            return i;
        }
    }
    return -1;
}

19 Source : ProducesRequestCondition.java
with MIT License
from Vip-Augus

/**
 * Compares this and another "produces" condition as follows:
 * <ol>
 * <li>Sort 'Accept' header media types by quality value via
 * {@link MediaType#sortByQualityValue(List)} and iterate the list.
 * <li>Get the first index of matching media types in each "produces"
 * condition first matching with {@link MediaType#equals(Object)} and
 * then with {@link MediaType#includes(MediaType)}.
 * <li>If a lower index is found, the condition at that index wins.
 * <li>If both indexes are equal, the media types at the index are
 * compared further with {@link MediaType#SPECIFICITY_COMPARATOR}.
 * </ol>
 * <p>It is replacedumed that both instances have been obtained via
 * {@link #getMatchingCondition(HttpServletRequest)} and each instance
 * contains the matching producible media type expression only or
 * is otherwise empty.
 */
@Override
public int compareTo(ProducesRequestCondition other, HttpServletRequest request) {
    try {
        List<MediaType> acceptedMediaTypes = getAcceptedMediaTypes(request);
        for (MediaType acceptedMediaType : acceptedMediaTypes) {
            int thisIndex = this.indexOfEqualMediaType(acceptedMediaType);
            int otherIndex = other.indexOfEqualMediaType(acceptedMediaType);
            int result = compareMatchingMediaTypes(this, thisIndex, other, otherIndex);
            if (result != 0) {
                return result;
            }
            thisIndex = this.indexOfIncludedMediaType(acceptedMediaType);
            otherIndex = other.indexOfIncludedMediaType(acceptedMediaType);
            result = compareMatchingMediaTypes(this, thisIndex, other, otherIndex);
            if (result != 0) {
                return result;
            }
        }
        return 0;
    } catch (HttpMediaTypeNotAcceptableException ex) {
        // should never happen
        throw new IllegalStateException("Cannot compare without having any requested media types", ex);
    }
}

19 Source : ConsumesRequestCondition.java
with MIT License
from Vip-Augus

@Nullable
private List<ConsumeMediaTypeExpression> getMatchingExpressions(MediaType contentType) {
    List<ConsumeMediaTypeExpression> result = null;
    for (ConsumeMediaTypeExpression expression : this.expressions) {
        if (expression.match(contentType)) {
            result = result != null ? result : new ArrayList<>();
            result.add(expression);
        }
    }
    return result;
}

19 Source : ConsumesRequestCondition.java
with MIT License
from Vip-Augus

/**
 * Checks if any of the contained media type expressions match the given
 * request 'Content-Type' header and returns an instance that is guaranteed
 * to contain matching expressions only. The match is performed via
 * {@link MediaType#includes(MediaType)}.
 * @param request the current request
 * @return the same instance if the condition contains no expressions;
 * or a new condition with matching expressions only;
 * or {@code null} if no expressions match
 */
@Override
@Nullable
public ConsumesRequestCondition getMatchingCondition(HttpServletRequest request) {
    if (CorsUtils.isPreFlightRequest(request)) {
        return EMPTY_CONDITION;
    }
    if (isEmpty()) {
        return this;
    }
    if (!hasBody(request) && !this.bodyRequired) {
        return EMPTY_CONDITION;
    }
    // Common media types are cached at the level of MimeTypeUtils
    MediaType contentType;
    try {
        contentType = StringUtils.hasLength(request.getContentType()) ? MediaType.parseMediaType(request.getContentType()) : MediaType.APPLICATION_OCTET_STREAM;
    } catch (InvalidMediaTypeException ex) {
        return null;
    }
    List<ConsumeMediaTypeExpression> result = getMatchingExpressions(contentType);
    return !CollectionUtils.isEmpty(result) ? new ConsumesRequestCondition(result) : null;
}

19 Source : AbstractMediaTypeExpression.java
with MIT License
from Vip-Augus

/**
 * Supports media type expressions as described in:
 * {@link RequestMapping#consumes()} and {@link RequestMapping#produces()}.
 *
 * @author Arjen Poutsma
 * @author Rossen Stoyanchev
 * @since 3.1
 */
abstract clreplaced AbstractMediaTypeExpression implements MediaTypeExpression, Comparable<AbstractMediaTypeExpression> {

    protected final Log logger = LogFactory.getLog(getClreplaced());

    private final MediaType mediaType;

    private final boolean isNegated;

    AbstractMediaTypeExpression(String expression) {
        if (expression.startsWith("!")) {
            this.isNegated = true;
            expression = expression.substring(1);
        } else {
            this.isNegated = false;
        }
        this.mediaType = MediaType.parseMediaType(expression);
    }

    AbstractMediaTypeExpression(MediaType mediaType, boolean negated) {
        this.mediaType = mediaType;
        this.isNegated = negated;
    }

    @Override
    public MediaType getMediaType() {
        return this.mediaType;
    }

    @Override
    public boolean isNegated() {
        return this.isNegated;
    }

    @Override
    public int compareTo(AbstractMediaTypeExpression other) {
        return MediaType.SPECIFICITY_COMPARATOR.compare(this.getMediaType(), other.getMediaType());
    }

    @Override
    public boolean equals(@Nullable Object other) {
        if (this == other) {
            return true;
        }
        if (other == null || getClreplaced() != other.getClreplaced()) {
            return false;
        }
        AbstractMediaTypeExpression otherExpr = (AbstractMediaTypeExpression) other;
        return (this.mediaType.equals(otherExpr.mediaType) && this.isNegated == otherExpr.isNegated);
    }

    @Override
    public int hashCode() {
        return this.mediaType.hashCode();
    }

    @Override
    public String toString() {
        if (this.isNegated) {
            return '!' + this.mediaType.toString();
        }
        return this.mediaType.toString();
    }
}

19 Source : RequestPredicates.java
with MIT License
from Vip-Augus

/**
 * Return a {@code RequestPredicate} that tests if the request's
 * {@linkplain ServerRequest.Headers#contentType() content type} is
 * {@linkplain MediaType#includes(MediaType) included} by any of the given media types.
 * @param mediaTypes the media types to match the request's content type against
 * @return a predicate that tests the request's content type against the given media types
 */
public static RequestPredicate contentType(MediaType... mediaTypes) {
    replacedert.notEmpty(mediaTypes, "'mediaTypes' must not be empty");
    return new ContentTypePredicate(mediaTypes);
}

19 Source : RequestPredicates.java
with MIT License
from Vip-Augus

/**
 * Return a {@code RequestPredicate} that tests if the request's
 * {@linkplain ServerRequest.Headers#accept() accept} header is
 * {@linkplain MediaType#isCompatibleWith(MediaType) compatible} with any of the given media types.
 * @param mediaTypes the media types to match the request's accept header against
 * @return a predicate that tests the request's accept header against the given media types
 */
public static RequestPredicate accept(MediaType... mediaTypes) {
    replacedert.notEmpty(mediaTypes, "'mediaTypes' must not be empty");
    return new AcceptPredicate(mediaTypes);
}

19 Source : DefaultServerResponseBuilder.java
with MIT License
from Vip-Augus

@Override
public ServerResponse.BodyBuilder contentType(MediaType contentType) {
    this.headers.setContentType(contentType);
    return this;
}

19 Source : DefaultEntityResponseBuilder.java
with MIT License
from Vip-Augus

@Override
public EnreplacedyResponse.Builder<T> contentType(MediaType contentType) {
    this.headers.setContentType(contentType);
    return this;
}

19 Source : ContentNegotiationConfigurer.java
with MIT License
from Vip-Augus

/**
 * Set the default content type(s) to use when no content type is requested
 * in order of priority.
 * <p>If destinations are present that do not support any of the given media
 * types, consider appending {@link MediaType#ALL} at the end.
 * <p>By default this is not set.
 * @see #defaultContentTypeStrategy
 */
public ContentNegotiationConfigurer defaultContentType(MediaType... defaultContentTypes) {
    this.factory.setDefaultContentTypes(Arrays.asList(defaultContentTypes));
    return this;
}

19 Source : ContentNegotiationConfigurer.java
with MIT License
from Vip-Augus

/**
 * Add a mapping from a key, extracted from a path extension or a query
 * parameter, to a MediaType. This is required in order for the parameter
 * strategy to work. Any extensions explicitly registered here are also
 * whitelisted for the purpose of Reflected File Download attack detection
 * (see Spring Framework reference doreplacedentation for more details on RFD
 * attack protection).
 * <p>The path extension strategy will also try to use
 * {@link ServletContext#getMimeType} and {@link MediaTypeFactory} to resolve path
 * extensions. To change this behavior see the {@link #useRegisteredExtensionsOnly} property.
 * @param extension the key to look up
 * @param mediaType the media type
 * @see #mediaTypes(Map)
 * @see #replaceMediaTypes(Map)
 */
public ContentNegotiationConfigurer mediaType(String extension, MediaType mediaType) {
    this.mediaTypes.put(extension, mediaType);
    return this;
}

19 Source : HandlerResultHandlerTests.java
with MIT License
from Vip-Augus

// SPR-9160
@Test
public void sortsByQuality() throws Exception {
    MockServerWebExchange exchange = MockServerWebExchange.from(MockServerHttpRequest.get("/path").header("Accept", "text/plain; q=0.5, application/json"));
    List<MediaType> mediaTypes = Arrays.asList(TEXT_PLAIN, APPLICATION_JSON);
    MediaType actual = this.resultHandler.selectMediaType(exchange, () -> mediaTypes);
    replacedertEquals(APPLICATION_JSON, actual);
}

19 Source : ViewResolutionResultHandler.java
with MIT License
from Vip-Augus

private Mono<? extends Void> render(List<View> views, Map<String, Object> model, ServerWebExchange exchange) {
    for (View view : views) {
        if (view.isRedirectView()) {
            return view.render(model, null, exchange);
        }
    }
    List<MediaType> mediaTypes = getMediaTypes(views);
    MediaType bestMediaType = selectMediaType(exchange, () -> mediaTypes);
    if (bestMediaType != null) {
        for (View view : views) {
            for (MediaType mediaType : view.getSupportedMediaTypes()) {
                if (mediaType.isCompatibleWith(bestMediaType)) {
                    return view.render(model, mediaType, exchange);
                }
            }
        }
    }
    throw new NotAcceptableStatusException(mediaTypes);
}

19 Source : FreeMarkerView.java
with MIT License
from Vip-Augus

private Charset getCharset(@Nullable MediaType mediaType) {
    return Optional.ofNullable(mediaType).map(MimeType::getCharset).orElse(getDefaultCharset());
}

See More Examples