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

co.easimart.vertx.http.Http404NotFoundHandler Maven / Gradle / Ivy

package co.easimart.vertx.http;

import io.netty.handler.codec.http.HttpHeaderNames;
import io.netty.handler.codec.http.HttpHeaderValues;
import io.netty.handler.codec.http.HttpResponseStatus;
import io.vertx.core.Handler;
import io.vertx.core.json.JsonObject;
import io.vertx.ext.web.RoutingContext;

import static com.google.common.base.Preconditions.checkNotNull;

/**
 * @author ichen
 * @since 21/11/17
 */
public abstract class Http404NotFoundHandler implements Handler {
    private static final String ERROR = "error";
    private static final String ERROR_CODE = "code";
    private static final String ERROR_REASON = "reason";

    /**
     * @return Subclass to override this to provide the content type of the response.
     * @see HttpHeaderValues
     */
    public abstract String getContentType();

    /**
     * @return Subclass to override this to provide the actual content value of the response.
     */
    public abstract String getContentValue();

    @Override
    public void handle(final RoutingContext rc) {
        checkNotNull(rc);
        rc.response()
                .putHeader(HttpHeaderNames.CONTENT_TYPE.toString(), getContentType())
                .setStatusCode(HttpResponseStatus.NOT_FOUND.code())
                .end(getContentValue());
    }

    /**
     * Default implementation of {@link Http404NotFoundHandler} which returns JSON response.
     */
    public final static class NotFoundJsonHandler extends Http404NotFoundHandler {
        @Override
        public String getContentType() {
            return HttpHeaderValues.APPLICATION_JSON.toString();
        }

        @Override
        public String getContentValue() {
            JsonObject jsonObject = new JsonObject()
                    .put(ERROR_CODE, HttpResponseStatus.NOT_FOUND.code())
                    .put(ERROR_REASON, "HTTP 404 - Not Found");
            return new JsonObject().put(ERROR, jsonObject).encode();
        }
    }
}




© 2015 - 2025 Weber Informatics LLC | Privacy Policy