View Javadoc
1   /*
2    * Copyright 2022 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.springframework.core.convert.converter.Converter;
26  import org.springframework.data.convert.ReadingConverter;
27  import org.springframework.lang.NonNull;
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    }
44  
45    @Override
46    public Acl convert(@NonNull Document source) {
47      String owner = source.getString(Acl.OWNER);
48      Object entries = source.get(Acl.ENTRIES);
49      Map<String, Ace> permissionMap = new HashMap<>();
50      if (entries instanceof Map) {
51        //noinspection unchecked
52        Map<String, Object> entryMap = (Map<String, Object>) entries;
53        for (Map.Entry<String, Object> entry : entryMap.entrySet()) {
54          String permission = entry.getKey();
55          Object aceObj = entry.getValue();
56          if (aceObj instanceof Ace) {
57            permissionMap.put(permission, (Ace) aceObj);
58          } else if (aceObj instanceof Map) {
59            //noinspection unchecked
60            Map<String, Object> aceMap = (Map<String, Object>) aceObj;
61            Ace ace = aceConverter.convert(new Document(aceMap));
62            permissionMap.put(permission, ace);
63          }
64        }
65      }
66      return Acl.builder()
67          .owner(owner)
68          .permissionMap(permissionMap)
69          .build();
70    }
71  
72    @Override
73    public boolean equals(Object o) {
74      if (this == o) {
75        return true;
76      }
77      return o != null && getClass() == o.getClass();
78    }
79  
80    @Override
81    public int hashCode() {
82      return Objects.hashCode(getClass());
83    }
84  
85  }