aboutsummaryrefslogtreecommitdiffstats
path: root/aai-resources/src/main/java/org/onap/aai/IncreaseNodesTool.java
blob: 23814bf1e1f6842777ca5835648da41f9854a60a (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
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
/**
 * ============LICENSE_START=======================================================
 * org.onap.aai
 * ================================================================================
 * Copyright © 2017-2018 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.onap.aai;

import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

import com.att.eelf.configuration.EELFLogger;
import com.att.eelf.configuration.EELFManager;
import org.springframework.context.ApplicationContext;
import org.apache.tinkerpop.gremlin.process.traversal.dsl.graph.GraphTraversalSource;
import org.apache.tinkerpop.gremlin.structure.Vertex;
import org.janusgraph.core.JanusGraph;
import org.janusgraph.core.JanusGraphTransaction;
import org.onap.aai.config.PropertyPasswordConfiguration;
import org.onap.aai.config.SpringContextAware;
import org.onap.aai.dbmap.AAIGraph;
import org.onap.aai.edges.EdgeIngestor;
import org.onap.aai.exceptions.AAIException;
import org.onap.aai.introspection.Introspector;
import org.onap.aai.introspection.Loader;
import org.onap.aai.introspection.LoaderFactory;
import org.onap.aai.introspection.ModelType;
import org.onap.aai.introspection.exceptions.AAIUnknownObjectException;
import org.onap.aai.logging.ErrorLogHelper;
import org.onap.aai.logging.LoggingContext;
import org.onap.aai.setup.SchemaVersions;
import org.onap.aai.util.AAISystemExitUtil;
import org.onap.aai.util.PositiveNumValidator;
import org.onap.aai.serialization.engines.TransactionalGraphEngine;
import org.onap.aai.serialization.db.EdgeSerializer;
import com.beust.jcommander.JCommander;
import com.beust.jcommander.Parameter;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.beans.factory.annotation.Autowired;

public class IncreaseNodesTool {

   public static long nodeCount = 0;
   
   @Autowired
   protected static EdgeSerializer edgeSerializer;
   
   private LoaderFactory loaderFactory;
   private SchemaVersions schemaVersions;
   protected TransactionalGraphEngine engine;
    Vertex parentVtx;

    private static final EELFLogger LOGGER = EELFManager.getInstance().getLogger(IncreaseNodesTool.class);

   public IncreaseNodesTool(LoaderFactory loaderFactory, SchemaVersions schemaVersions){
       this.loaderFactory = loaderFactory;
       this.schemaVersions = schemaVersions;
   }

   public static void main(String[] args) throws AAIUnknownObjectException, UnsupportedEncodingException, AAIException {

       AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext();
       PropertyPasswordConfiguration initializer = new PropertyPasswordConfiguration();
       initializer.initialize(context);
       try {
           context.scan(
                   "org.onap.aai.config",
                   "org.onap.aai.setup"
           );
           context.refresh();
       } catch (Exception e) {
           AAIException aai = ResourcesApp.schemaServiceExceptionTranslator(e);
           LOGGER.error("Problems running the tool "+aai.getMessage());
           LoggingContext.statusCode(LoggingContext.StatusCode.ERROR);
           LoggingContext.responseCode(LoggingContext.DATA_ERROR);
           ErrorLogHelper.logError(aai.getCode(), e.getMessage() + ", resolve and retry");
           throw aai;
       }

       LoaderFactory loaderFactory = context.getBean(LoaderFactory.class);
       SchemaVersions schemaVersions = (SchemaVersions) SpringContextAware.getBean("schemaVersions");

       IncreaseNodesTool increaseNodesTool = new IncreaseNodesTool(loaderFactory, schemaVersions);
       JanusGraph janusGraph = AAIGraph.getInstance().getGraph();
       
       ApplicationContext ctx = (ApplicationContext) SpringContextAware.getApplicationContext();
       edgeSerializer = ctx.getBean(EdgeSerializer.class);
       
       increaseNodesTool.run(janusGraph,args);
       AAISystemExitUtil.systemExitCloseAAIGraph(0);

   }


    public void run(JanusGraph janusGraph, String[] args) throws AAIUnknownObjectException, UnsupportedEncodingException {
        CommandLineArgs cArgs = new CommandLineArgs();
        JCommander jCommander = new JCommander(cArgs,args);
        jCommander.setProgramName(IncreaseNodesTool.class.getSimpleName());

        Loader loader = loaderFactory.createLoaderForVersion(ModelType.MOXY, schemaVersions.getDefaultVersion());
        Introspector obj = loader.introspectorFromName(cArgs.nodeType);

        List<String> propList = new ArrayList<String>();
        propList.addAll(obj.getRequiredProperties());


        nodeCount = Long.parseLong(cArgs.numberOfNodes);
        addVertex(janusGraph, cArgs.nodeType,propList,cArgs);
    }
    /***
     * adds a vertex based on user inputs of node type number of nodes and the node uri
     * /cloud-infrastructure/pservers/pserver/
     * /network/pnfs/pnf/
     * /cloud-infrastructure/pservers/pserver/random-056fd6c4-7313-4fa0-b854-0d9983bdb0ab/p-interfaces/p-interface/
     * @param
     * @param
     * @param cArgs
     */
    public  void addVertex(JanusGraph janusGraph, String nodeType, List<String> propList,CommandLineArgs cArgs){

        long startTime = System.currentTimeMillis();
        try (JanusGraphTransaction transaction = janusGraph.newTransaction()) {
            boolean success = true;

            try {
                GraphTraversalSource g = transaction.traversal();
                for (long i = 1; i <= nodeCount; i++) {
                    String randomId = UUID.randomUUID().toString();
                    Vertex v = g.addV().next();
                    
                    v.property("aai-node-type", nodeType);
                    v.property("source-of-truth", "IncreaseNodesTool");
                    v.property("aai-uri", cArgs.uri+"random-"+randomId);


                    for(String propName : propList){
                        if(propName.equals("in-maint")){
                            v.property(propName,"false");
                            continue;
                        }
                        v.property(propName, "random-" + randomId);
                        System.out.println("node " + i + " added " + propList.get(0)+": " + "random-"+randomId);
                    }
                    
                    if(cArgs.child.equals("true")){

                        if(parentVtx == null){
                            String[] uriTokens = cArgs.uri.split("/");
                            String ParentNodeType = uriTokens[uriTokens.length-4]; //parent node type
                            String keyVal = uriTokens[uriTokens.length-3]; // parent unique key
                            Loader loader = loaderFactory.createLoaderForVersion(ModelType.MOXY, schemaVersions.getDefaultVersion());
                            if (loader != null)
                            {
	                            Introspector objParent = loader.introspectorFromName(ParentNodeType);
	                            if (objParent != null)
	                            {
		                            List<String> parentPropList = new ArrayList<String>();
		                            parentPropList.addAll(objParent.getRequiredProperties());
		                            if (parentPropList.size() > 0)
		                            { 
		                            	System.out.println("parent node (" + ParentNodeType + ") key (" + parentPropList.get(0)+" ) =" + keyVal);
			                            parentVtx = g.V().has(parentPropList.get(0),keyVal).next();
			                            edgeSerializer.addTreeEdgeIfPossible(g,parentVtx,v);
		                            }
	                            }
                            }

                        }
                        else{
                            edgeSerializer.addTreeEdgeIfPossible(g,parentVtx,v);
                        }
                    }

                }
            } catch (Exception ex) {
                success = false;
            } finally {
                if (success) {
                    transaction.commit();
                    System.out.println("Transaction Committed");
                    long endTime = System.currentTimeMillis();
                    System.out.println("Total Time: "+ ((endTime - startTime)/ 1000.0) + "seconds");
                } else {
                    transaction.rollback();
                }
            }
        }
    }

   }



class CommandLineArgs {

    @Parameter(names = "-numberOfNodes", description = "how many nodes you would like to enter", required = true , validateWith = PositiveNumValidator.class)
    public String numberOfNodes;

    @Parameter(names = "-nodeType", description = "The aai-node-type of the node being entered", required = true)
    public String nodeType;

    @Parameter(names = "-uri", description = "uri to be passed for the node",required = true)
    public String uri;

    @Parameter(names = "-child", description = "is this a child node",required = true)
    public String child;

}