[SDC-29] rebase continue work to align source
[sdc.git] / asdctool / src / main / java / org / openecomp / sdc / asdctool / impl / migration / v1707 / jsonmodel / UserStatesMigration.java
1 package org.openecomp.sdc.asdctool.impl.migration.v1707.jsonmodel;
2
3 import com.thinkaurelius.titan.core.TitanVertex;
4 import fj.data.Either;
5 import org.apache.tinkerpop.gremlin.structure.Direction;
6 import org.apache.tinkerpop.gremlin.structure.Edge;
7 import org.apache.tinkerpop.gremlin.structure.Property;
8 import org.apache.tinkerpop.gremlin.structure.Vertex;
9 import org.openecomp.sdc.asdctool.impl.migration.MigrationMsg;
10 import org.openecomp.sdc.be.dao.neo4j.GraphPropertiesDictionary;
11 import org.openecomp.sdc.be.dao.titan.TitanGenericDao;
12 import org.openecomp.sdc.be.dao.titan.TitanOperationStatus;
13 import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum;
14 import org.openecomp.sdc.be.model.operations.impl.UniqueIdBuilder;
15 import org.openecomp.sdc.be.resources.data.UserData;
16 import org.slf4j.Logger;
17 import org.slf4j.LoggerFactory;
18
19 import javax.annotation.Resource;
20 import java.util.ArrayList;
21 import java.util.List;
22 import java.util.stream.Collectors;
23
24 import static fj.data.List.list;
25 import static org.openecomp.sdc.asdctool.impl.migration.v1707.MigrationUtils.handleError;
26
27 public class UserStatesMigration extends JsonModelMigration<Edge> {
28
29     private static final String MIGRATING_USER_ID = "jh0003";
30     private static final int OUT_VERTEX_INDEX = 0;
31     private static final int IN_VERTEX_INDEX = 1;
32     private static Logger LOGGER = LoggerFactory.getLogger(UserStatesMigration.class);
33
34     @Resource(name = "titan-generic-dao")
35     private TitanGenericDao genericDao;
36
37     @Resource(name = "titan-generic-dao-migration")
38     private TitanGenericDao genericDaoMigration;
39
40     @Override
41     public String description() {
42         return "migrate user states";
43     }
44
45
46     @Override
47     public boolean migrate() {
48 //        return removeMigratingUserStates() && super.migrate();
49         return super.migrate();
50     }
51
52     @Override
53     Either<List<Edge>, TitanOperationStatus> getElementsToMigrate() {
54         LOGGER.debug("fetching user states edges from old graph");
55         return genericDao.getAll(NodeTypeEnum.User, UserData.class)
56                          .left().bind(this::getEdgesForUsers);
57     }
58
59     @Override
60     Either<Edge, TitanOperationStatus> getElementFromNewGraph(Edge edge) {
61         LOGGER.debug("finding user state edge in new graph");
62         Vertex outVertex = edge.outVertex();
63         String outVertexUIDKey = getVertexUniqueId(outVertex);
64         String outVertexUIDValue = outVertex.property(outVertexUIDKey).value().toString();
65
66         Vertex inVertex = edge.inVertex();
67         String inVertexUIDKey = getVertexUniqueId(inVertex);
68         String inVertexUIDValue = inVertex.property(inVertexUIDKey).value().toString();
69
70         return genericDaoMigration.getEdgeByVerticies(outVertexUIDKey, outVertexUIDValue, inVertexUIDKey, inVertexUIDValue, edge.label());
71     }
72
73     @Override
74     boolean save(Edge userState) {
75         Either<InOutVertices, TitanOperationStatus> titanVertices = findEdgeInOutVerticesInNewGraph(userState);
76         return titanVertices.either(inOutVertices -> saveUserState(inOutVertices, userState),
77                                     err ->  handleError(String.format("could not find user edge %s in vertx. error: %s", userState.label(), err.name())));
78     }
79
80     private boolean saveUserState(InOutVertices inOutVertices, Edge userState) {
81         return genericDaoMigration.copyEdge(inOutVertices.getOutVertex(), inOutVertices.getInVertex(), userState)
82                 .either(edge -> true,
83                         err -> handleError(String.format("failed to save user state edge %s. reason: %s", userState.label(), err.name())));
84     }
85
86     @Override
87     TitanOperationStatus getNotFoundErrorStatus() {
88         return TitanOperationStatus.NOT_FOUND;
89     }
90
91 //    private boolean removeMigratingUserStates() {
92 //        Either<UserData, TitanOperationStatus> migratingUser = genericDaoMigration.getNode(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.User), MIGRATING_USER_ID, UserData.class);
93 //        return migratingUser.either(user -> deleteAllEdges(user, Direction.OUT),
94 //                                    errorStatus -> MigrationUtils.handleError(MigrationMsg.FAILED_TO_RETRIEVE_MIGRATION_USER.getMessage(MIGRATING_USER_ID, errorStatus.name())));
95 //    }
96
97     private Either<List<Edge>, TitanOperationStatus> getEdgesForUsers(List<UserData> users) {
98         List<Edge> edges = new ArrayList<>();
99         for (UserData user : users) {
100             Either<List<Edge>, TitanOperationStatus> edgesForNode = genericDao.getEdgesForNode(user, Direction.OUT);
101             if (edgesForNode.isRight()) {
102                 TitanOperationStatus errorStatus = edgesForNode.right().value();
103                 LOGGER.error(MigrationMsg.FAILED_TO_RETRIEVE_USER_STATES.getMessage(user.getEmail(), errorStatus.name()));
104                 return Either.right(errorStatus);
105             }
106             edges.addAll(edgesForNode.left().value());
107         }
108         return Either.left(ignoreProductEdges(edges));
109     }
110
111     private List<Edge> ignoreProductEdges(List<Edge> edges) {
112         return edges.stream().filter(edge -> !isInEdgeOfProductType(edge.inVertex())).collect(Collectors.toList());
113     }
114
115     private boolean isInEdgeOfProductType(Vertex inVertex) {
116         Property<Object> nodeLabelProperty = inVertex.property(GraphPropertiesDictionary.LABEL.getProperty());
117         return nodeLabelProperty != null && nodeLabelProperty.value().equals(NodeTypeEnum.Product.getName());
118     }
119
120     private String getVertexUniqueId(Vertex vertex) {
121         String nodeLabel = vertex.property(GraphPropertiesDictionary.LABEL.getProperty()).value().toString();
122         return UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.getByName(nodeLabel));
123     }
124
125     private Either<InOutVertices, TitanOperationStatus> findEdgeInOutVerticesInNewGraph(Edge userEdge) {
126         Either<TitanVertex, TitanOperationStatus> outVertex = getMigratedVertexByOldVertex(userEdge.outVertex());
127         Either<TitanVertex, TitanOperationStatus> inVertex = getMigratedVertexByOldVertex(userEdge.inVertex());
128         return Either.sequenceLeft(list(outVertex, inVertex)).left().map(InOutVertices::new);
129     }
130
131     private Either<TitanVertex, TitanOperationStatus> getMigratedVertexByOldVertex(Vertex vertex) {
132         String vertexUniqueId = getVertexUniqueId(vertex);
133         LOGGER.debug(String.format("fetching vertex %s from new graph", vertexUniqueId));
134         return genericDaoMigration.getVertexByProperty(vertexUniqueId, vertex.property(vertexUniqueId).value())
135                                    .right().map(err -> handleError(err, String.format("could not find vertex %s in new graph.", vertexUniqueId)))  ;
136     }
137
138 //    private boolean deleteAllEdges(UserData userData, Direction direction) {
139 //        Either<List<Edge>, TitanOperationStatus> edgesForNode = genericDaoMigration.getEdgesForNode(userData, direction);
140 //        if (edgesForNode.isRight()) {
141 //            LOGGER.error(MigrationMsg.FAILED_TO_RETRIEVE_MIGRATION_USER_STATES.getMessage(MIGRATING_USER_ID, edgesForNode.right().value().name()));
142 //            return false;
143 //        }
144 //        edgesForNode.left().value().forEach(Edge::remove);
145 //        return true;
146 //    }
147
148     private class InOutVertices {
149         private TitanVertex outVertex;
150         private TitanVertex inVertex;
151
152         InOutVertices(fj.data.List<TitanVertex> inOutVertices) {
153             outVertex = inOutVertices.index(OUT_VERTEX_INDEX);
154             inVertex = inOutVertices.index(IN_VERTEX_INDEX);
155         }
156
157         TitanVertex getOutVertex() {
158             return outVertex;
159         }
160
161         TitanVertex getInVertex() {
162             return inVertex;
163         }
164
165     }
166
167 }