summaryrefslogtreecommitdiffstats
path: root/asdctool/src/main/java/org/openecomp/sdc/asdctool/impl/migration/MigrationOperationUtils.java
blob: 7a34521d93b0fd40418e34f71166d0ff502bb62e (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
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
/*-
 * ============LICENSE_START=======================================================
 * SDC
 * ================================================================================
 * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
 * ================================================================================
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * 
 *      http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * ============LICENSE_END=========================================================
 */

package org.openecomp.sdc.asdctool.impl.migration;

import com.thinkaurelius.titan.core.PropertyKey;
import com.thinkaurelius.titan.core.TitanGraph;
import com.thinkaurelius.titan.core.TitanVertex;
import com.thinkaurelius.titan.core.schema.TitanManagement;
import fj.data.Either;
import org.apache.tinkerpop.gremlin.structure.VertexProperty;
import org.openecomp.sdc.be.dao.titan.TitanGenericDao;
import org.openecomp.sdc.be.dao.titan.TitanOperationStatus;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Map;
import java.util.Optional;

@Component("migrationUtils")
public class MigrationOperationUtils {

    private static Logger log = LoggerFactory.getLogger(MigrationOperationUtils.class);

    @Autowired
    private TitanGenericDao titanGenericDao;

    /**
     * rename a set or property keys
     *
     * @param propertyKeys a mapping between the old property key name and the property key name to replace it with
     *
     * @return true if rename ended successfully or false otherwise
     */
    public boolean renamePropertyKeys(Map<String, String> propertyKeys) {
        Either<TitanGraph, TitanOperationStatus> graph = titanGenericDao.getGraph();
        return graph.either((titanGraph) ->  renamePropertyKeys(titanGraph, propertyKeys),
                            (titanOperationStatus) -> operationFailed(MigrationMsg.FAILED_TO_RETRIEVE_GRAPH.getMessage(titanOperationStatus.name())));
    }

    private boolean renamePropertyKeys(TitanGraph titanGraph, Map<String, String> propertyKeys) {
        try {
            for (Map.Entry<String, String> propertyKeyEntry : propertyKeys.entrySet()) {
                boolean renameSucceeded = renamePropertyKey(titanGraph, propertyKeyEntry);
                if (!renameSucceeded) {
                    return false;
                }
            }
            return true;
        } catch (RuntimeException e) {
            log.error(e.getMessage(), e);
            return false;
        }
    }

    private Boolean renamePropertyKey(TitanGraph titanGraph, Map.Entry<String, String> propertyKeyEntry) {
        String renameFromKey = propertyKeyEntry.getKey();
        String renameToKey = propertyKeyEntry.getValue();
        log.info(String.format("renaming property key %s to %s", renameFromKey, renameToKey));
        return renameProperty(titanGraph, renameFromKey, renameToKey);
    }

    private Boolean renameProperty(TitanGraph titanGraph, String renameFromKey, String renameToKey) {
        if (titanGraph.containsPropertyKey(renameFromKey) && titanGraph.containsPropertyKey(renameToKey)) {//new property already exist, we cant rename to it we need to add new and remove old on every vertices which has the old one.
            return renamePropertyOnEachVertex(titanGraph, renameFromKey, renameToKey);
        }
        return renamePropertyOnGraphLevel(titanGraph, renameFromKey, renameToKey);
    }

    private Boolean renamePropertyOnGraphLevel(TitanGraph titanGraph, String renameFromKey, String renameToKey) {
        TitanManagement titanManagement = titanGraph.openManagement();
        return Optional.ofNullable(titanManagement.getPropertyKey(renameFromKey))
                .map(propertyKey -> renamePropertyOnGraph(titanManagement, propertyKey, renameToKey))
                .orElseGet(() -> {log.info(MigrationMsg.PROPERTY_KEY_NOT_EXIST.getMessage(renameFromKey)); return true;}) ;//if property key not exist rename is considered to be successful
    }

    private boolean renamePropertyOnEachVertex(TitanGraph graph, String oldKey, String newKey) {
        addNewPropertyKeyOnVertices(graph, oldKey, newKey);
        removeOldPropertyKeyFromGraph(graph, oldKey);
        graph.tx().commit();
        return true;
    }

    private void removeOldPropertyKeyFromGraph(TitanGraph graph, String oldKey) {
        graph.getPropertyKey(oldKey).remove();
    }

	private void addNewPropertyKeyOnVertices(TitanGraph graph, String oldKey, String newKey) {
        graph.query().has(oldKey).vertices().forEach(titanVertex -> {
            copyOldKeyValueAndDropKey(oldKey, newKey, (TitanVertex) titanVertex);
        });
    }

    private void copyOldKeyValueAndDropKey(String oldKey, String newKey, TitanVertex titanVertex) {
        VertexProperty<Object> oldProperty = titanVertex.property(oldKey);
        Object oldKeyValue = oldProperty.value();

        titanVertex.property(newKey, oldKeyValue);
        oldProperty.remove();
    }

    private boolean renamePropertyOnGraph(TitanManagement titanManagement, PropertyKey fromPropertyKey, String toKey) {
        try {
            titanManagement.changeName(fromPropertyKey, toKey);
            titanManagement.commit();
            return true;
        } catch (RuntimeException e) {
            log.error(MigrationMsg.RENAME_KEY_PROPERTY_FAILED.getMessage(fromPropertyKey.name()), e.getMessage());
            titanManagement.rollback();
            return false;
        }
    }

    private boolean operationFailed(String errorMessage) {
        log.error(errorMessage);
        return false;
    }


}