+ /** Returns content session consistent with this HTTP context. */
+ public static ContentSession getContentSession(ContentRepository contentRepository, HttpExchange exchange) {
+ ContentSession session = RemoteAuthUtils.doAs(() -> contentRepository.get(),
+ new RemoteAuthHttpExchange(exchange));
+ return session;
+ }
+
+ /*
+ * QUERY PARAMETERS
+ */
+ /** Returns the HTTP parameters form an {@link HttpExchange}. */
+ public static Map<String, List<String>> parseParameters(HttpExchange exchange) {
+ // TODO check encoding?
+ Charset encoding = StandardCharsets.UTF_8;
+
+ Map<String, List<String>> parameters = new HashMap<>();
+ URI requestedUri = exchange.getRequestURI();
+ String query = requestedUri.getRawQuery();
+ parseQuery(query, parameters, encoding);
+
+ // TODO do we really want to support POST?
+ if (HttpMethod.POST.name().equalsIgnoreCase(exchange.getRequestMethod())) {
+ String postQuery;
+ try {
+ // We do not close the stream on purpose, since the body still needs to be read
+ BufferedReader br = new BufferedReader(new InputStreamReader(exchange.getRequestBody(), encoding));
+ postQuery = br.readLine();
+ } catch (IOException e) {
+ throw new UncheckedIOException("Cannot read exchange body", e);
+ }
+ parseQuery(postQuery, parameters, encoding);
+ }
+ return parameters;
+ }
+
+ private static void parseQuery(String query, Map<String, List<String>> parameters, Charset encoding) {
+ if (query == null)
+ return;
+ String pairs[] = query.split("[&]");
+ for (String pair : pairs) {
+ String param[] = pair.split("[=]");
+
+ String key = null;
+ String value = null;
+ if (param.length > 0) {
+ key = URLDecoder.decode(param[0], encoding);
+ }
+
+ if (param.length > 1) {
+ value = URLDecoder.decode(param[1], encoding);
+ }
+
+ if (!parameters.containsKey(key))
+ parameters.put(key, new ArrayList<>());
+ parameters.get(key).add(value);
+ }
+ }
+