Simplified navigation.
[svjatoslav_commons.git] / src / main / java / eu / svjatoslav / commons / network / navigation / NavigationItem.java
1 /*
2  * Svjatoslav Commons - shared library of common functionality.
3  * Copyright ©2012-2017, 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 eu.svjatoslav.commons.string.WildCardMatcher;
13
14 import java.util.ArrayList;
15 import java.util.List;
16
17 public class NavigationItem {
18
19     private final ArrayList<NavigationItem> children = new ArrayList<>();
20     private final String url;
21     private String pattern;
22     private String title;
23     private boolean isDefault;
24
25     public NavigationItem(final String url, String pattern, String title ) {
26         this.url = url;
27         this.pattern = pattern;
28         this.title = title;
29     }
30
31     public NavigationItem setDefault(){
32         isDefault = true;
33         return this;
34     }
35
36     public boolean isDefault(){
37         return isDefault;
38     }
39
40     public void add(final NavigationItem navigationItem) {
41         children.add(navigationItem);
42     }
43
44     public String getUrl() {
45         return url;
46     }
47
48     NavigationItem getMatch(final String requestPath) {
49         if (matchesUrl(requestPath))
50             return this;
51
52         for (final NavigationItem childNavigationItem : children) {
53             final NavigationItem match = childNavigationItem.getMatch(requestPath);
54
55             if (match != null)
56                 return match;
57         }
58         return null;
59     }
60
61     public List<NavigationItem> getChildren() {
62         return children;
63     }
64
65     public String getTitle() {
66         return title;
67     }
68
69     public boolean matchesUrl(final String url) {
70         return WildCardMatcher.match(url, pattern);
71     }
72
73     public NavigationItem getDefaultNavigationItem() {
74         for (NavigationItem child : children)
75             if (child.isDefault())
76                 return child;
77         return null;
78     }
79 }