summaryrefslogtreecommitdiff
path: root/src/main/java/com/android/vts/servlet/BaseServlet.java
blob: 5319ee18334b8817655bb7697db9dd8d72feef1e (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
/*
 * Copyright (c) 2016 Google Inc. All Rights Reserved.
 *
 * Licensed 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.android.vts.servlet;

import com.android.vts.entity.CoverageEntity;
import com.android.vts.entity.TestSuiteResultEntity;
import com.android.vts.entity.UserEntity;
import com.android.vts.util.EmailHelper;
import com.android.vts.util.GcsHelper;
import com.google.appengine.api.users.User;
import com.google.appengine.api.users.UserService;
import com.google.appengine.api.users.UserServiceFactory;
import com.google.gson.Gson;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import java.util.Properties;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.ServletConfig;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

public abstract class BaseServlet extends HttpServlet {

    protected final Logger logger = Logger.getLogger(getClass().getName());

    protected String ERROR_MESSAGE_JSP = "WEB-INF/jsp/error_msg.jsp";

    // Environment variables
    protected static String GERRIT_URI;
    protected static String GERRIT_SCOPE;
    protected static String CLIENT_ID;
    protected static String ANALYTICS_ID;

    protected static final String TREE_DEFAULT_PARAM = "treeDefault";

    public enum PageType {
        TOT("Test", "/"),
        RELEASE("Release", "/show_release"),
        COVERAGE_OVERVIEW("Coverage", "/show_coverage_overview"),
        PROFILING_LIST("Profiling", "/show_profiling_list"),
        TABLE("", "/show_table"),
        TREE("", "/show_tree"),
        GRAPH("Profiling", "/show_graph"),
        COVERAGE("Coverage", "/show_coverage"),
        PERFORMANCE_DIGEST("Performance Digest", "/show_performance_digest"),
        PLAN_RELEASE("", "/show_plan_release"),
        PLAN_RUN("Plan Run", "/show_plan_run"),
        PROFILING_OVERVIEW("", "/show_profiling_overview");

        public final String defaultName;
        public final String defaultUrl;

        PageType(String defaultName, String defaultUrl) {
            this.defaultName = defaultName;
            this.defaultUrl = defaultUrl;
        }
    }

    public static class Page {

        private final PageType type;
        private final String name;
        private final String url;

        public Page(PageType type) {
            this.type = type;
            this.name = type.defaultName;
            this.url = type.defaultUrl;
        }

        public Page(PageType type, String name, String url) {
            this.type = type;
            this.name = type.defaultName + name;
            this.url = type.defaultUrl + url;
        }

        public Page(PageType type, String name, String url, Boolean withoutDefault) {
            this.type = type;
            this.name = name;
            this.url = type.defaultUrl + url;
        }

        public Page(PageType type, String url) {
            this.type = type;
            this.name = type.defaultName;
            this.url = type.defaultUrl + url;
        }

        public String getName() {
            return name;
        }

        public String getUrl() {
            return url;
        }
    }

    public static final List<Page> navbarLinks;

    static {
        List<Page> links = new ArrayList<>();
        links.add(new Page(PageType.TOT));
        links.add(new Page(PageType.RELEASE));
        links.add(new Page(PageType.COVERAGE_OVERVIEW));
        links.add(new Page(PageType.PROFILING_LIST));
        navbarLinks = links;
    }

    public abstract PageType getNavParentType();

    /**
     * Get a list of URL/Display name pairs for the breadcrumb hierarchy.
     *
     * @param request The HttpServletRequest object for the page request.
     * @return a list of Page entries.
     */
    public abstract List<Page> getBreadcrumbLinks(HttpServletRequest request);

    /** System Configuration Property class */
    protected static Properties systemConfigProp = new Properties();

    @Override
    public void init(ServletConfig cfg) throws ServletException {
        super.init(cfg);

        systemConfigProp =
                Properties.class.cast(cfg.getServletContext().getAttribute("systemConfigProp"));

        GERRIT_URI = systemConfigProp.getProperty("gerrit.uri");
        GERRIT_SCOPE = systemConfigProp.getProperty("gerrit.scope");
        CLIENT_ID = systemConfigProp.getProperty("appengine.clientID");
        ANALYTICS_ID = systemConfigProp.getProperty("analytics.id");

        CoverageEntity.setPropertyValues(systemConfigProp);
        TestSuiteResultEntity.setPropertyValues(systemConfigProp);
        EmailHelper.setPropertyValues(systemConfigProp);
        GcsHelper.setGcsProjectId(systemConfigProp.getProperty("gcs.projectID"));
    }

    @Override
    public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException {
        // If the user is logged out, allow them to log back in and return to the page.
        // Set the logout URL to direct back to a login page that directs to the current request.
        UserService userService = UserServiceFactory.getUserService();
        Optional<User> currentUser = Optional.ofNullable(userService.getCurrentUser());
        String currentUserEmail =
                currentUser.isPresent()
                        ? currentUser.map(user -> user.getEmail().trim()).orElse("")
                        : "";
        String requestUri = request.getRequestURI();
        String requestArgs = request.getQueryString();
        String loginURI = userService.createLoginURL(requestUri + '?' + requestArgs);
        String logoutURI = userService.createLogoutURL(loginURI);
        if (currentUserEmail != "") {

            int activeIndex;
            switch (getNavParentType()) {
                case PROFILING_LIST:
                    activeIndex = 3;
                    break;
                case COVERAGE_OVERVIEW:
                    activeIndex = 2;
                    break;
                case RELEASE:
                    activeIndex = 1;
                    break;
                default:
                    activeIndex = 0;
                    break;
            }
            if (request.getParameter(TREE_DEFAULT_PARAM) != null) {
                HttpSession session = request.getSession(true);
                boolean treeDefault = request.getParameter(TREE_DEFAULT_PARAM).equals("true");
                session.setAttribute(TREE_DEFAULT_PARAM, treeDefault);
            }

            request.setAttribute("serverName", request.getServerName());
            request.setAttribute("logoutURL", logoutURI);
            request.setAttribute("email", currentUserEmail);
            request.setAttribute("analyticsID", new Gson().toJson(ANALYTICS_ID));
            request.setAttribute("breadcrumbLinks", getBreadcrumbLinks(request));
            request.setAttribute("navbarLinks", navbarLinks);
            request.setAttribute("activeIndex", activeIndex);
            response.setContentType("text/html");

            if (currentUserEmail.endsWith("@google.com")
                    || UserEntity.getUserList().contains(currentUserEmail)) {
                doGetHandler(request, response);
            } else {
                RequestDispatcher dispatcher =
                        request.getRequestDispatcher("WEB-INF/jsp/auth_error.jsp");
                try {
                    dispatcher.forward(request, response);
                } catch (ServletException e) {
                    logger.log(Level.SEVERE, "Servlet Exception caught : ", e);
                }
            }
        } else {
            response.sendRedirect(loginURI);
        }
    }

    /**
     * Implementation of the doGet method to be executed by servlet subclasses.
     *
     * @param request The HttpServletRequest object.
     * @param response The HttpServletResponse object.
     */
    public abstract void doGetHandler(HttpServletRequest request, HttpServletResponse response)
            throws IOException;
}