com.jameswolfeoliver.pigeon.Server.Endpoints.Endpoint.java Source code

Java tutorial

Introduction

Here is the source code for com.jameswolfeoliver.pigeon.Server.Endpoints.Endpoint.java

Source

/*
 * Copyright (c) 2017 James Oliver
 *
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership.  The ASF licenses this file
 * to you under the Apache License, Version 2.0 (the
 * "License"); you may not use this file except in compliance
 * with the License.  You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing,
 * software distributed under the License is distributed on an
 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 * KIND, either express or implied.  See the License for the
 * specific language governing permissions and limitations
 * under the License.
 */

package com.jameswolfeoliver.pigeon.Server.Endpoints;

import android.util.Log;

import com.jameswolfeoliver.pigeon.Models.ClientResponses.Error;
import com.jameswolfeoliver.pigeon.Models.Session;
import com.jameswolfeoliver.pigeon.Server.Sessions.SessionManager;
import com.jameswolfeoliver.pigeon.Utilities.PigeonApplication;

import org.nanohttpd.protocols.http.IHTTPSession;
import org.nanohttpd.protocols.http.content.CookieHandler;
import org.nanohttpd.protocols.http.response.Response;
import org.nanohttpd.protocols.http.response.Status;

import java.util.HashMap;
import java.util.Map;

import static org.apache.commons.lang3.StringEscapeUtils.escapeHtml4;

public abstract class Endpoint {
    // MIME Types
    protected final static String MIME_JSON = "application/json";
    protected final static String MIME_HTML = "text/html";
    protected final static String MIME_PLAIN = "text/plain";
    protected final static String MIME_JPEG = "image/jpeg";
    protected final static String MIME_PNG = "image/png";
    protected static final String COOKIE_PIGEON_ID = "pigeonId";

    protected SessionManager sessionManager;

    public Endpoint(SessionManager sessionManager) {
        this.sessionManager = sessionManager;
    }

    protected static String sanitizeText(String s) {
        return escapeHtml4(s);
    }

    protected static String getPostData(IHTTPSession session) {
        Map<String, String> bodyMap = new HashMap<>();
        try {
            session.parseBody(bodyMap);
        } catch (Exception e) {
            Log.e(Endpoint.class.getSimpleName(), "Failed to parse body", e);
            return null;
        }
        return bodyMap.get("postData");
    }

    protected static Response buildJsonResponse(String responseJson, Status status) {
        return Response.newFixedLengthResponse(status, MIME_JSON, responseJson);
    }

    protected static Response buildJsonError(int errorCode, String error, Status status) {
        return Response.newFixedLengthResponse(status, MIME_JSON,
                PigeonApplication.getGson().toJson(new Error(errorCode, error), Error.class));
    }

    public Response serve(IHTTPSession session) {
        switch (session.getMethod()) {
        case GET:
            return onGet(session);
        case POST:
            return onPost(session);
        default:
            return Response.newFixedLengthResponse(Status.METHOD_NOT_ALLOWED, MIME_PLAIN, new byte[0]);
        }
    }

    abstract protected Response onGet(IHTTPSession session);

    abstract protected Response onPost(IHTTPSession session);

    protected boolean isSessionValid(IHTTPSession session) {
        Session curr = extractCurrentSession(session);
        return curr != null && sessionManager.checkSessionValidity(curr);
    }

    protected Session extractCurrentSession(IHTTPSession session) {
        CookieHandler cookieHandler = session.getCookies();
        String pigeonId = cookieHandler.read(COOKIE_PIGEON_ID);
        return pigeonId != null ? new Session(COOKIE_PIGEON_ID, pigeonId) : null;
    }
}