View Javadoc
1   /*
2    * This file is part of ***  M y C o R e  ***
3    * See http://www.mycore.de/ for details.
4    *
5    * MyCoRe is free software: you can redistribute it and/or modify
6    * it under the terms of the GNU General Public License as published by
7    * the Free Software Foundation, either version 3 of the License, or
8    * (at your option) any later version.
9    *
10   * MyCoRe is distributed in the hope that it will be useful,
11   * but WITHOUT ANY WARRANTY; without even the implied warranty of
12   * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13   * GNU General Public License for more details.
14   *
15   * You should have received a copy of the GNU General Public License
16   * along with MyCoRe.  If not, see <http://www.gnu.org/licenses/>.
17   */
18  package org.mycore.restapi.v1.utils;
19  
20  import java.util.LinkedHashMap;
21  import java.util.Map;
22  import java.util.Optional;
23  
24  import org.glassfish.jersey.server.ServerProperties;
25  
26  import jakarta.ws.rs.core.Application;
27  
28  /**
29   * This class contains some generic utility functions for the REST API
30   * 
31   * @author Thomas Scheffler (yagee)
32   */
33  public class MCRRestAPIUtil {
34      public static String getWWWAuthenticateHeader(String s,
35          Map<String, String> attributes, Application app) {
36          LinkedHashMap<String, String> attrMap = new LinkedHashMap<>();
37          String realm = app.getProperties()
38              .getOrDefault(ServerProperties.APPLICATION_NAME, "REST API")
39              .toString();
40          attrMap.put("realm", realm);
41          Optional.ofNullable(attributes).ifPresent(attrMap::putAll);
42          StringBuilder b = new StringBuilder();
43          attrMap.entrySet().stream()
44              .forEach(e -> appendFieldValue(b, e.getKey(), e.getValue()));
45          b.insert(0, " ");
46          return Optional.ofNullable(s).orElse("Basic") + b;
47      }
48  
49      private static void appendField(StringBuilder b, String field) {
50          if (b.length() > 0) {
51              b.append(", ");
52          }
53          b.append(field);
54      }
55  
56      private static void appendValue(StringBuilder b, String value) {
57          for (char c : value.toCharArray()) {
58              if ((c < 0x20) || (c == 0x22) || (c == 0x5c) || (c > 0x7e)) {
59                  b.append(' ');
60              } else {
61                  b.append(c);
62              }
63          }
64      }
65  
66      private static void appendFieldValue(StringBuilder b, String field, String value) {
67          appendField(b, field);
68          if (value != null && !value.isEmpty()) {
69              b.append("=\"");
70              appendValue(b, value);
71              b.append('\"');
72          }
73      }
74  
75  }