aboutsummaryrefslogtreecommitdiffstats
path: root/graph-inventory/aai-client/src/main/java/org/onap/aaiclient/client/aai/entities/uri/AAIFluentTypeReverseLookup.java
blob: bd9f4c713f71fab2c7803b541952bc1721f208d1 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
package org.onap.aaiclient.client.aai.entities.uri;

import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;
import org.onap.aaiclient.client.aai.AAIObjectType;
import org.onap.aaiclient.client.graphinventory.GraphInventoryFluentType;
import org.onap.aaiclient.client.graphinventory.entities.uri.parsers.UriParserSpringImpl;
import com.google.common.base.CaseFormat;

public class AAIFluentTypeReverseLookup {

    public AAIObjectType fromName(String name, String uri) {

        String className = CaseFormat.LOWER_HYPHEN.to(CaseFormat.UPPER_CAMEL, name);

        uri = uri.replaceFirst(".*?/v\\d+", "");
        try {
            Class<? extends GraphInventoryFluentType.Info> clazz =
                    (Class<? extends GraphInventoryFluentType.Info>) Class
                            .forName("org.onap.aaiclient.client.generated.fluentbuilders." + className + "$Info");

            GraphInventoryFluentType.Info type = clazz.newInstance();

            Optional<String> parentTemplate = findParentPath(type, uri);
            if (parentTemplate.isPresent()) {
                return new AAIObjectType(parentTemplate.get(), type.getPartialUri(), type.getName(), false);
            } else {
                // fallback to enum lookup
                return AAIObjectType.fromTypeName(name);
            }
        } catch (ClassNotFoundException | InstantiationException | IllegalAccessException e) {
        }
        return AAIObjectType.UNKNOWN;
    }

    protected Optional<String> findParentPath(GraphInventoryFluentType.Info type, String uri) {

        List<UriParserSpringImpl> parsers =
                type.getPaths().stream().map(path -> new UriParserSpringImpl(path)).collect(Collectors.toList());

        for (UriParserSpringImpl parser : parsers) {
            if (parser.isMatch(uri)) {
                String partialUriReplacer = type.getPartialUri().replaceAll("\\{[^}]+\\}", "[^/]+");
                return Optional.of(parser.getTemplate().replaceFirst(partialUriReplacer + "$", ""));
            }
        }

        return Optional.empty();
    }
}