View Javadoc
1   /*
2    * Licensed to the Apache Software Foundation (ASF) under one
3    * or more contributor license agreements.  See the NOTICE file
4    * distributed with this work for additional information
5    * regarding copyright ownership.  The ASF licenses this file
6    * to you under the Apache License, Version 2.0 (the
7    * "License"); you may not use this file except in compliance
8    * with the License.  You may obtain a copy of the License at
9    *
10   *   http://www.apache.org/licenses/LICENSE-2.0
11   *
12   * Unless required by applicable law or agreed to in writing,
13   * software distributed under the License is distributed on an
14   * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
15   * KIND, either express or implied.  See the License for the
16   * specific language governing permissions and limitations
17   * under the License.
18   */
19  package org.apache.syncope.client.console;
20  
21  import com.fasterxml.jackson.core.type.TypeReference;
22  import com.fasterxml.jackson.databind.json.JsonMapper;
23  import java.io.IOException;
24  import java.io.Serializable;
25  import java.io.StringWriter;
26  import java.util.ArrayList;
27  import java.util.Base64;
28  import java.util.HashMap;
29  import java.util.List;
30  import java.util.Map;
31  import java.util.stream.Collectors;
32  import org.apache.commons.lang3.StringUtils;
33  import org.apache.commons.lang3.math.NumberUtils;
34  import org.apache.wicket.util.cookies.CookieDefaults;
35  import org.apache.wicket.util.cookies.CookieUtils;
36  import org.slf4j.Logger;
37  import org.slf4j.LoggerFactory;
38  
39  public final class PreferenceManager implements Serializable {
40  
41      private static final long serialVersionUID = 3581434664555284193L;
42  
43      private static final Logger LOG = LoggerFactory.getLogger(PreferenceManager.class);
44  
45      private static final String COOKIE_NAME = "syncope2ConsolePrefs";
46  
47      private static final int ONE_YEAR_TIME = 60 * 60 * 24 * 365;
48  
49      private static final JsonMapper MAPPER = JsonMapper.builder().findAndAddModules().build();
50  
51      private static final TypeReference<Map<String, String>> MAP_TYPE_REF = new TypeReference<>() {
52      };
53  
54      private static final List<Integer> PAGINATOR_CHOICES = List.of(10, 25, 50);
55  
56      private static final CookieUtils COOKIE_UTILS;
57  
58      static {
59          CookieDefaults cookieDefaults = new CookieDefaults();
60          cookieDefaults.setMaxAge(ONE_YEAR_TIME);
61          COOKIE_UTILS = new CookieUtils(cookieDefaults);
62      }
63  
64      public static List<Integer> getPaginatorChoices() {
65          return PAGINATOR_CHOICES;
66      }
67  
68      private static Map<String, String> getPrefs(final String value) {
69          Map<String, String> prefs;
70          try {
71              if (StringUtils.isNotBlank(value)) {
72                  prefs = MAPPER.readValue(value, MAP_TYPE_REF);
73              } else {
74                  throw new Exception("Invalid cookie value '" + value + '\'');
75              }
76          } catch (Exception e) {
77              LOG.debug("No preferences found", e);
78              prefs = new HashMap<>();
79          }
80  
81          return prefs;
82      }
83  
84      private static String setPrefs(final Map<String, String> prefs) throws IOException {
85          StringWriter writer = new StringWriter();
86          MAPPER.writeValue(writer, prefs);
87  
88          return writer.toString();
89      }
90  
91      public static String get(final String key) {
92          String result = null;
93  
94          String prefString = COOKIE_UTILS.load(COOKIE_NAME);
95          if (prefString != null) {
96              Map<String, String> prefs = getPrefs(new String(Base64.getDecoder().decode(prefString.getBytes())));
97              result = prefs.get(key);
98          }
99  
100         return result;
101     }
102 
103     public static Integer getPaginatorRows(final String key) {
104         Integer result = getPaginatorChoices().get(0);
105 
106         String value = get(key);
107         if (value != null) {
108             result = NumberUtils.toInt(value, 10);
109         }
110 
111         return result;
112     }
113 
114     public static List<String> getList(final String key) {
115         final List<String> result = new ArrayList<>();
116 
117         final String compound = get(key);
118 
119         if (StringUtils.isNotBlank(compound)) {
120             String[] items = compound.split(";");
121             result.addAll(List.of(items));
122         }
123 
124         return result;
125     }
126 
127     public static void set(final Map<String, List<String>> prefs) {
128         Map<String, String> current = new HashMap<>();
129 
130         String prefString = COOKIE_UTILS.load(COOKIE_NAME);
131         if (prefString != null) {
132             current.putAll(getPrefs(new String(Base64.getDecoder().decode(prefString.getBytes()))));
133         }
134 
135         // after retrieved previous setting in order to overwrite the key ...
136         prefs.forEach((key, values) -> current.put(key, values.stream().collect(Collectors.joining(";"))));
137 
138         try {
139             COOKIE_UTILS.save(COOKIE_NAME, Base64.getEncoder().encodeToString(setPrefs(current).getBytes()));
140         } catch (IOException e) {
141             LOG.error("Could not save {} info: {}", PreferenceManager.class.getSimpleName(), current, e);
142         }
143     }
144 
145     public static void set(final String key, final String value) {
146         String prefString = COOKIE_UTILS.load(COOKIE_NAME);
147 
148         final Map<String, String> current = new HashMap<>();
149         if (prefString != null) {
150             current.putAll(getPrefs(new String(Base64.getDecoder().decode(prefString.getBytes()))));
151         }
152 
153         // after retrieved previous setting in order to overwrite the key ...
154         current.put(key, value);
155 
156         try {
157             COOKIE_UTILS.save(COOKIE_NAME, Base64.getEncoder().encodeToString(setPrefs(current).getBytes()));
158         } catch (IOException e) {
159             LOG.error("Could not save {} info: {}", PreferenceManager.class.getSimpleName(), current, e);
160         }
161     }
162 
163     public static void setList(final String key, final List<String> values) {
164         set(key, values.stream().collect(Collectors.joining(";")));
165     }
166 
167     public static void setList(final Map<String, List<String>> prefs) {
168         set(prefs);
169     }
170 
171     private PreferenceManager() {
172         // private constructor for static utility class
173     }
174 }