Improved IntelliJ startup script.
[svjatoslav_commons.git] / src / main / java / eu / svjatoslav / commons / network / navigation / Navigation.java
1 /*
2  * Svjatoslav Commons - shared library of common functionality.
3  * Copyright ©2012-2019, Svjatoslav Agejenko, svjatoslav@svjatoslav.eu
4  *
5  * This program is free software; you can redistribute it and/or
6  * modify it under the terms of version 3 of the GNU Lesser General Public License
7  * or later as published by the Free Software Foundation.
8  */
9
10 package eu.svjatoslav.commons.network.navigation;
11
12 import javax.servlet.http.HttpServletRequest;
13 import java.net.MalformedURLException;
14 import java.net.URL;
15
16 public class Navigation {
17
18     private NavigationItem root = new NavigationItem(null, null, null);
19
20     public NavigationItem getRoot(){
21         return root;
22     }
23
24     public NavigationItem getSelectedItem(final HttpServletRequest request) {
25         final String requestUrl = request.getRequestURL().toString();
26
27         final String requestPath;
28         try {
29             requestPath = new URL(requestUrl).getPath();
30         } catch (MalformedURLException e) {
31             throw new IllegalArgumentException("Illegal request URL provided." , e);
32         }
33
34         @SuppressWarnings("unchecked") final NavigationItem match = root.getMatch(requestPath);
35
36         if (match != null)
37             return match;
38
39         return root.getDefaultNavigationItem();
40     }
41
42     @SuppressWarnings("unchecked")
43     public String getTopMenu(final HttpServletRequest request) {
44
45         final NavigationItem selectedItem = getSelectedItem(request);
46         final StringBuilder result = new StringBuilder();
47
48         result.append("<div class=\"navigationMenu\">");
49
50         for (final NavigationItem item : root.getChildren()) {
51
52             if (item == selectedItem)
53                 result.append("<a class=\"menuItemSelected\" href=\""
54                         + item.getUrl() + "\">");
55             else
56                 result.append("<a class=\"menuItem\" href=\""
57                         + item.getUrl() + "\">");
58
59             result.append("<div>" + item.getTitle() + "</div>");
60             result.append("</a>");
61         }
62
63         result.append("</div>");
64
65         return result.toString();
66     }
67
68 }