95cb1fe7c24819797bc058c3ec230eb93be99395
[so.git] /
1 package org.onap.aaiclient.client.aai.entities.uri;
2
3 import java.lang.reflect.InvocationTargetException;
4 import java.util.List;
5 import java.util.Optional;
6 import java.util.stream.Collectors;
7 import org.onap.aaiclient.client.aai.AAIObjectType;
8 import org.onap.aaiclient.client.graphinventory.GraphInventoryFluentType;
9 import org.onap.aaiclient.client.graphinventory.entities.uri.parsers.UriParserSpringImpl;
10 import com.google.common.base.CaseFormat;
11
12 public class AAIFluentTypeReverseLookup {
13
14     public AAIObjectType fromName(String name, String uri) {
15
16         String className = CaseFormat.LOWER_HYPHEN.to(CaseFormat.UPPER_CAMEL, name);
17
18         uri = uri.replaceFirst(".*?/v\\d+", "");
19         try {
20             Class<? extends GraphInventoryFluentType.Info> clazz =
21                     (Class<? extends GraphInventoryFluentType.Info>) Class
22                             .forName("org.onap.aaiclient.client.generated.fluentbuilders." + className + "$Info");
23
24             GraphInventoryFluentType.Info type = clazz.getConstructor().newInstance();
25
26             Optional<String> parentTemplate = findParentPath(type, uri);
27             if (parentTemplate.isPresent()) {
28                 return new AAIObjectType(parentTemplate.get(), type.getPartialUri(), type.getName(), false);
29             } else {
30                 // fallback to enum lookup
31                 return AAIObjectType.fromTypeName(name);
32             }
33         } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | IllegalArgumentException
34                 | InvocationTargetException | NoSuchMethodException | SecurityException e) {
35         }
36         return AAIObjectType.UNKNOWN;
37     }
38
39     protected Optional<String> findParentPath(GraphInventoryFluentType.Info type, String uri) {
40
41         List<UriParserSpringImpl> parsers =
42                 type.getPaths().stream().map(path -> new UriParserSpringImpl(path)).collect(Collectors.toList());
43
44         for (UriParserSpringImpl parser : parsers) {
45             if (parser.isMatch(uri)) {
46                 String partialUriReplacer = type.getPartialUri().replaceAll("\\{[^}]+\\}", "[^/]+");
47                 return Optional.of(parser.getTemplate().replaceFirst(partialUriReplacer + "$", ""));
48             }
49         }
50
51         return Optional.empty();
52     }
53 }