View Javadoc
1   /**
2    * Copyright 2013 The Kuali Foundation Licensed under the
3    * Educational Community License, Version 2.0 (the "License"); you may
4    * not use this file except in compliance with the License. You may
5    * obtain a copy of the License at
6    *
7    * http://www.osedu.org/licenses/ECL-2.0
8    *
9    * Unless required by applicable law or agreed to in writing,
10   * software distributed under the License is distributed on an "AS IS"
11   * BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
12   * or implied. See the License for the specific language governing
13   * permissions and limitations under the License.
14   */
15  package org.kuali.mobility.admin.service;
16  
17  import java.util.ArrayList;
18  import java.util.Collections;
19  import java.util.Enumeration;
20  import java.util.Iterator;
21  import java.util.List;
22  
23  import javax.annotation.Resource;
24  import javax.servlet.http.Cookie;
25  import javax.servlet.http.HttpServletRequest;
26  import javax.servlet.http.HttpSession;
27  import javax.ws.rs.GET;
28  import javax.ws.rs.POST;
29  import javax.ws.rs.Path;
30  import javax.ws.rs.core.Context;
31  
32  import org.apache.cxf.jaxrs.ext.MessageContext;
33  import org.apache.cxf.phase.PhaseInterceptorChain;
34  import org.slf4j.Logger;
35  import org.slf4j.LoggerFactory;
36  import org.kuali.mobility.admin.entity.HomeScreen;
37  import org.kuali.mobility.admin.entity.HomeTool;
38  import org.kuali.mobility.admin.entity.Tool;
39  import org.kuali.mobility.alerts.service.AlertsService;
40  import org.kuali.mobility.security.authz.entity.AclExpression;
41  import org.kuali.mobility.security.user.api.User;
42  import org.kuali.mobility.shared.Constants;
43  import org.kuali.mobility.shared.entity.Backdoor;
44  import org.kuali.mobility.util.LocalisationUtil;
45  import org.springframework.beans.factory.annotation.Autowired;
46  import org.springframework.beans.factory.annotation.Qualifier;
47  import org.springframework.context.MessageSource;
48  import org.springframework.stereotype.Service;
49  
50  /**
51   * Implementation of the CXF Device Service
52   * 
53   * @author Kuali Mobility Team (mobility.dev@kuali.org)
54   * @since 3.0
55   */
56  @Service
57  public class CXFHomeScreenService {
58  	/** A reference to a logger for this service */
59  	private static final Logger LOG = LoggerFactory.getLogger(CXFHomeScreenService.class);
60  	
61  	@Resource(name = "messageSource")
62  	private MessageSource messageSource;
63  	
64      @Context
65      private MessageContext messageContext;
66  	
67  	@Autowired
68  	private AdminService adminService;
69  	
70      /**
71       * A reference to the <code>LocalisationUtil</code>
72       */
73      @Autowired
74      @Qualifier("localisationUtil")
75      private LocalisationUtil localisationUtil;
76  	
77  	@Autowired
78  	private AlertsService alertsService;
79  
80  	@GET
81  	@Path("/ping/get")
82  	public String pingGet(){
83  		return "{\"status\":\"OK\"}";
84  	}
85  
86  	@POST
87  	@Path("/ping/post")
88  	public String pingPost(){
89  		return "{\"status\":\"OK\"}";
90  	}
91  	
92  	/**
93  	 * Return HomeScreen as Json.
94  	 * @return
95  	 */
96  	@GET
97  	@Path("/json")
98  	public String getHomeScreenAsJson(){
99  		String alias = "PUBLIC";
100 //		List<HomeTool> hometools = getAllHomeTools(alias);		
101 		List<HomeTool> hometools = getHomeTools();		
102 		
103 		Iterator<HomeTool> it = hometools.iterator();
104 		String json = "";
105 		while(it.hasNext()){
106 			HomeTool ht = it.next();
107 			json += "{\"homeToolId\":" + 	ht.getHomeToolId() + ",";
108 			json += "\"homeScreenId\":" + 	ht.getHomeScreenId() +  ","; 
109 			json += "\"toolId\":" + 		ht.getToolId() +  ",";
110 			json += "\"order\":" + 		ht.getOrder() + ",";
111 			json += "\"versionNumber\":" + ht.getVersionNumber() + ",";
112 			json += "\"tool\":" + localizeTool(ht.getTool()).toJson() + "},";
113 		}
114 		json = json.substring(0, json.length() - 1);		
115 		return "{\"tools\":[" + json + "]}";
116 	}
117 	
118 	/**
119 	 * Return badge text and count with tool id for showing on homesreen temporary static values as Json.
120 	 * @return
121 	 */
122 	@GET
123 	@Path("/badges")
124 	public String getBadgeDetails(){
125 		String returnJson="{\"tools\":[{\"homeToolId\":1,\"badgeText\":\"Beta\",\"badgeCount\":1},{\"homeToolId\":2,\"badgeText\":\"\",\"badgeCount\":2},{\"homeToolId\":3,\"badgeText\":\"Beta\",\"badgeCount\":3},{\"homeToolId\":4,\"badgeText\":\"\",\"badgeCount\":4},{\"homeToolId\":6,\"badgeText\":\"\",\"badgeCount\":6},{\"homeToolId\":7,\"badgeText\":\"Beta\",\"badgeCount\":7}]}";
126 		return returnJson;
127 	}
128 	
129 	private String decode(String code){
130 		if(code != null){
131 			return messageSource.getMessage(code, null, null);
132 		}else{
133 			return code;
134 		}
135 	}
136 	
137 	private Tool localizeTool(Tool tool){
138 		Tool result = new Tool();
139 		result.setAclPublishingId(tool.getAclPublishingId());
140 		result.setAclViewingId(tool.getAclViewingId());
141 		result.setAlias(tool.getAlias());
142 		result.setBadgeCount(tool.getBadgeCount());
143 		result.setBadgeText(tool.getBadgeText());
144 		result.setContacts(tool.getContacts());
145 		result.setToolId(tool.getToolId());
146 		result.setUrl(tool.getUrl());
147 		result.setIconUrl(tool.getIconUrl());
148 		result.setKeywords(tool.getKeywords());
149 		result.setPublishingPermission(tool.getPublishingPermission());
150 		result.setRequisites(tool.getRequisites());
151 		
152 		//Localised Fields
153 		result.setSubtitle(decode(tool.getSubtitle()));
154 		result.setTitle(decode(tool.getTitle()));
155 		result.setDescription(decode(tool.getDescription()));
156 		return result;
157 	}
158 	
159 	
160 	private List<HomeTool> getAllHomeTools(String alias){
161 		HomeScreen home = getAdminService().getHomeScreenByAlias(alias);
162 		List<HomeTool> copy;
163 		if (home == null) {
164 			LOG.error("Home screen object still null when it should not be.");
165 			copy = new ArrayList<HomeTool>();
166 		} else {
167 			copy = new ArrayList<HomeTool>(home.getHomeTools());
168 		}
169 		Collections.sort(copy);
170 
171 		List<HomeTool> userTools = new ArrayList<HomeTool>();
172 		for (HomeTool homeTool : copy) {
173 			userTools.add(homeTool);
174 		}
175 		return userTools;
176 	}
177 	
178 	private List<HomeTool> getHomeTools(){		
179 //		HttpServletRequest request = (HttpServletRequest)PhaseInterceptorChain.getCurrentMessage().get("HTTP.REQUEST");		
180 		HttpServletRequest request = (HttpServletRequest) this.getMessageContext().getHttpServletRequest();
181 		User user = (User) request.getSession().getAttribute(Constants.KME_USER_KEY);
182 		Backdoor backdoor = (Backdoor) request.getSession().getAttribute(Constants.KME_BACKDOOR_USER_KEY);
183 
184 		int myState = 0;
185 		Cookie cks[] = request.getCookies();
186 		if (cks != null) {
187 			for (Cookie c : cks) {
188 				if (c.getName().equals("native")) {
189 					if ("yes".equals(c.getValue())) {
190 						myState |= Tool.NATIVE;
191 					} else {
192 						myState |= Tool.NON_NATIVE;
193 					}
194 				}
195 				if (c.getName().equals("platform")) {
196 					if ("iOS".equals(c.getValue())) {
197 						myState |= Tool.IOS;
198 					} else if ("Android".equals(c.getValue())) {
199 						myState |= Tool.ANDROID;
200 					} else if ("WindowsMobile".equals(c.getValue())) {
201 						myState |= Tool.WINDOWS_PHONE;
202 					} else if ("Blackberry".equals(c.getValue())) {
203 						myState |= Tool.BLACKBERRY;
204 					}
205 				}
206 			}
207 		}
208 
209 		String alias = "PUBLIC";
210 		if (request.getParameter("alias") != null) {
211 			alias = request.getParameter("alias").toUpperCase();
212 		}
213 
214 		HomeScreen home;
215 		if (user != null && user.getViewCampus() != null) {
216 			alias = user.getViewCampus();
217 		}
218 		
219 		home = getAdminService().getHomeScreenByAlias(alias);
220 		if (home == null) {
221 			LOG.debug("Home screen was null, getting PUBLIC screen.");
222 			home = getAdminService().getHomeScreenByAlias("PUBLIC");
223 		}
224 
225 		List<HomeTool> copy;
226 		if (home == null) {
227 			LOG.error("Home screen object still null when it should not be.");
228 			copy = new ArrayList<HomeTool>();
229 		} else {
230 			copy = new ArrayList<HomeTool>(home.getHomeTools());
231 		}
232 		Collections.sort(copy);
233 
234 		List<HomeTool> userTools = new ArrayList<HomeTool>();
235 		for (HomeTool homeTool : copy) {
236 			Tool tool = homeTool.getTool();
237 
238 			AclExpression viewingPermission = tool.getViewingPermission();
239 			if (viewingPermission != null && viewingPermission.getParsedExpression() != null && !viewingPermission.getParsedExpression().evaluate(user)) {
240 				continue;
241 			}
242 
243 			if ("alerts".equals(tool.getAlias())) {
244 				int count = getAlertsService().findAlertCountByCampus(alias);
245 				if (count > 0) {
246 					tool.setBadgeCount(Integer.toString(count));
247 					tool.setIconUrl("images/service-icons/srvc-alerts-red.png");
248 				} else {
249 					tool.setBadgeCount(null);
250 					tool.setIconUrl("images/service-icons/srvc-alerts-green.png");
251 				}
252 			}
253 			if ("incident".equals(tool.getAlias()) || "reportingadmin".equals(tool.getAlias())) {
254 				tool.setBadgeText("beta");
255 			}
256 
257 			if ("backdoor".equals(tool.getAlias())) {
258 				if (backdoor != null) {
259 					tool.setBadgeCount(backdoor.getUserId());
260 				} else {
261 					tool.setBadgeCount("");
262 				}
263 			}
264 			// If a tools requisites is unset it will be treated as available to any, same as Tool.ANY.
265 			if ((tool.getRequisites() & myState) == myState || (tool.getRequisites() == Tool.UNDEFINED_REQUISITES)) {
266 				LOG.info("--- SHOW TOOL: " + tool.getAlias());
267 				userTools.add(homeTool);
268 			} else {
269 				LOG.info("--- HIDE TOOL: " + tool.getAlias());
270 			}
271 		}
272 		return userTools;
273 	}
274 	
275 	
276 	
277 	
278 	/**
279 	 * @return the messageSource
280 	 */
281 	public MessageSource getMessageSource() {
282 		return messageSource;
283 	}
284 
285 	/**
286 	 * @param messageSource the messageSource to set
287 	 */
288 	public void setMessageSource(MessageSource messageSource) {
289 		this.messageSource = messageSource;
290 	}
291 
292 	/**
293 	 * @return the messageContext
294 	 */
295 	public MessageContext getMessageContext() {
296 		return messageContext;
297 	}
298 
299 	/**
300 	 * @param messageContext the messageContext to set
301 	 */
302 	public void setMessageContext(MessageContext messageContext) {
303 		this.messageContext = messageContext;
304 	}
305 
306 	/**
307 	 * @return the adminService
308 	 */
309 	public AdminService getAdminService() {
310 		return adminService;
311 	}
312 
313 	/**
314 	 * @param adminService the adminService to set
315 	 */
316 	public void setAdminService(AdminService adminService) {
317 		this.adminService = adminService;
318 	}
319 
320 
321 
322 	/**
323 	 * @return the localisationUtil
324 	 */
325 	public LocalisationUtil getLocalisationUtil() {
326 		return localisationUtil;
327 	}
328 
329 	/**
330 	 * @param localisationUtil the localisationUtil to set
331 	 */
332 	public void setLocalisationUtil(LocalisationUtil localisationUtil) {
333 		this.localisationUtil = localisationUtil;
334 	}
335 
336 	/**
337 	 * @return the alertsService
338 	 */
339 	public AlertsService getAlertsService() {
340 		return alertsService;
341 	}
342 
343 	/**
344 	 * @param alertsService the alertsService to set
345 	 */
346 	public void setAlertsService(AlertsService alertsService) {
347 		this.alertsService = alertsService;
348 	}
349 		
350 }