View Javadoc
1   /*
2    * Copyright 2022-2026 the original author or authors.
3    *
4    * Licensed under the Apache License, Version 2.0 (the "License");
5    * you may not use this file except in compliance with the License.
6    * You may obtain a copy of the License at
7    *
8    *      http://www.apache.org/licenses/LICENSE-2.0
9    *
10   * Unless required by applicable law or agreed to in writing, software
11   * distributed under the License is distributed on an "AS IS" BASIS,
12   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13   * See the License for the specific language governing permissions and
14   * limitations under the License.
15   */
16  
17  package org.bremersee.acl.spring.data.mongodb.convert;
18  
19  import java.util.HashMap;
20  import java.util.Map;
21  import java.util.Objects;
22  import org.bremersee.acl.Ace;
23  import org.bremersee.acl.Acl;
24  import org.bson.Document;
25  import org.jspecify.annotations.NonNull;
26  import org.springframework.core.convert.converter.Converter;
27  import org.springframework.data.convert.ReadingConverter;
28  
29  /**
30   * The document to acl converter.
31   *
32   * @author Christian Bremer
33   */
34  @ReadingConverter
35  public class DocumentToAclConverter implements Converter<Document, Acl> {
36  
37    private final DocumentToAceConverter aceConverter = new DocumentToAceConverter();
38  
39    /**
40     * Instantiates a new document to acl converter.
41     */
42    public DocumentToAclConverter() {
43      super();
44    }
45  
46    @Override
47    public Acl convert(@NonNull Document source) {
48      String owner = source.getString(Acl.OWNER);
49      Object entries = source.get(Acl.ENTRIES);
50      Map<String, Ace> permissionMap = new HashMap<>();
51      if (entries instanceof Map) {
52        //noinspection unchecked
53        Map<String, Object> entryMap = (Map<String, Object>) entries;
54        for (Map.Entry<String, Object> entry : entryMap.entrySet()) {
55          String permission = entry.getKey();
56          Object aceObj = entry.getValue();
57          if (aceObj instanceof Ace ace) {
58            permissionMap.put(permission, ace);
59          } else if (aceObj instanceof Map) {
60            //noinspection unchecked
61            Map<String, Object> aceMap = (Map<String, Object>) aceObj;
62            Ace ace = aceConverter.convert(new Document(aceMap));
63            permissionMap.put(permission, ace);
64          }
65        }
66      }
67      return Acl.builder()
68          .owner(owner)
69          .permissionMap(permissionMap)
70          .build();
71    }
72  
73    @Override
74    public boolean equals(Object o) {
75      if (this == o) {
76        return true;
77      }
78      return o != null && getClass() == o.getClass();
79    }
80  
81    @Override
82    public int hashCode() {
83      return Objects.hashCode(getClass());
84    }
85  
86  }