diff options
author | Venkata Harish K Kajur <vk250x@att.com> | 2017-06-16 15:43:33 -0400 |
---|---|---|
committer | Venkata Harish K Kajur <vk250x@att.com> | 2017-06-16 17:18:31 -0400 |
commit | 2e6b67eb491d70631ed1afada618adf45e6bfd38 (patch) | |
tree | 2d70e7bfa001a8df32379936bfbd961e753571bc /aai-resources/src/main/java/org/openecomp | |
parent | 2dd06f1f3180ba20485f268fd4a83b4961f15b8e (diff) |
[AAI-ONAP] Keep the onap updated and remove code
Change-Id: I2eee989cf835d45a84b2edf2d3ec342e9411f1e5
Signed-off-by: Venkata Harish K Kajur <vk250x@att.com>
Diffstat (limited to 'aai-resources/src/main/java/org/openecomp')
17 files changed, 970 insertions, 2023 deletions
diff --git a/aai-resources/src/main/java/org/openecomp/aai/config/DmaapConfig.java b/aai-resources/src/main/java/org/openecomp/aai/config/DmaapConfig.java index aeee99f..e8676ca 100644 --- a/aai-resources/src/main/java/org/openecomp/aai/config/DmaapConfig.java +++ b/aai-resources/src/main/java/org/openecomp/aai/config/DmaapConfig.java @@ -5,16 +5,16 @@ * 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. + * 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========================================================= */ diff --git a/aai-resources/src/main/java/org/openecomp/aai/migration/Enabled.java b/aai-resources/src/main/java/org/openecomp/aai/migration/Enabled.java new file mode 100644 index 0000000..3534013 --- /dev/null +++ b/aai-resources/src/main/java/org/openecomp/aai/migration/Enabled.java @@ -0,0 +1,36 @@ +/*- + * ============LICENSE_START======================================================= + * org.openecomp.aai + * ================================================================================ + * 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.aai.migration; + +import java.lang.annotation.ElementType; +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; +import java.lang.annotation.Target; + + +/** + * Used to enable a migration to be picked up by the {@link com.openecomp.aai.migration.MigrationControllerInternal MigrationController} + */ +@Target(ElementType.TYPE) +@Retention(value = RetentionPolicy.RUNTIME) +public @interface Enabled { + +} diff --git a/aai-resources/src/main/java/org/openecomp/aai/migration/EventAction.java b/aai-resources/src/main/java/org/openecomp/aai/migration/EventAction.java index 82b7cad..643af9b 100644 --- a/aai-resources/src/main/java/org/openecomp/aai/migration/EventAction.java +++ b/aai-resources/src/main/java/org/openecomp/aai/migration/EventAction.java @@ -20,6 +20,9 @@ package org.openecomp.aai.migration; +/** + * Used to describe the type of DMaaP event you would like to create + */ public enum EventAction { CREATE, UPDATE, diff --git a/aai-resources/src/main/java/org/openecomp/aai/migration/MigrationController.java b/aai-resources/src/main/java/org/openecomp/aai/migration/MigrationController.java new file mode 100644 index 0000000..024645c --- /dev/null +++ b/aai-resources/src/main/java/org/openecomp/aai/migration/MigrationController.java @@ -0,0 +1,49 @@ +/*- + * ============LICENSE_START======================================================= + * org.openecomp.aai + * ================================================================================ + * 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.aai.migration; + +import org.openecomp.aai.dbmap.AAIGraph; + +/** + * Wrapper class to allow {@link com.openecomp.aai.migration.MigrationControllerInternal MigrationControllerInternal} + * to be run from a shell script + */ +public class MigrationController { + + /** + * The main method. + * + * @param args + * the arguments + */ + public static void main(String[] args) { + + MigrationControllerInternal internal = new MigrationControllerInternal(); + + try { + internal.run(args); + } catch (Exception e) { + //ignore + } + AAIGraph.getInstance().getGraph().close(); + System.exit(0); + } +} diff --git a/aai-resources/src/main/java/org/openecomp/aai/migration/MigrationControllerInternal.java b/aai-resources/src/main/java/org/openecomp/aai/migration/MigrationControllerInternal.java new file mode 100644 index 0000000..a296c76 --- /dev/null +++ b/aai-resources/src/main/java/org/openecomp/aai/migration/MigrationControllerInternal.java @@ -0,0 +1,417 @@ +/*- + * ============LICENSE_START======================================================= + * org.openecomp.aai + * ================================================================================ + * 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.aai.migration; + +import java.io.File; +import java.io.IOException; +import java.lang.reflect.InvocationTargetException; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.Paths; +import java.util.ArrayList; +import java.util.Collections; +import java.util.Comparator; +import java.util.List; +import java.util.Properties; +import java.util.Set; + +import org.apache.activemq.broker.BrokerService; +import org.apache.commons.configuration.ConfigurationException; +import org.apache.commons.configuration.PropertiesConfiguration; +import org.apache.commons.lang.exception.ExceptionUtils; +import org.apache.tinkerpop.gremlin.structure.io.IoCore; +import org.openecomp.aai.db.props.AAIProperties; +import org.openecomp.aai.dbmap.AAIGraph; +import org.openecomp.aai.dbmap.DBConnectionType; +import org.openecomp.aai.exceptions.AAIException; +import org.openecomp.aai.introspection.Loader; +import org.openecomp.aai.introspection.LoaderFactory; +import org.openecomp.aai.introspection.ModelType; +import org.openecomp.aai.introspection.Version; +import org.openecomp.aai.serialization.engines.QueryStyle; +import org.openecomp.aai.serialization.engines.TitanDBEngine; +import org.openecomp.aai.serialization.engines.TransactionalGraphEngine; +import org.openecomp.aai.util.AAIConstants; +import org.openecomp.aai.util.FormatDate; +import org.reflections.Reflections; +import org.slf4j.MDC; + +import com.att.eelf.configuration.Configuration; +import com.att.eelf.configuration.EELFLogger; +import com.att.eelf.configuration.EELFManager; +import com.beust.jcommander.JCommander; +import com.beust.jcommander.Parameter; +import com.thinkaurelius.titan.core.TitanTransaction; + +/** + * Runs a series of migrations from a defined directory based on the presence of + * the {@link com.openecomp.aai.migration.Enabled Enabled} annotation + * + * It will also write a record of the migrations run to the database. + */ +public class MigrationControllerInternal { + + private EELFLogger logger; + private final int DANGER_ZONE = 10; + private final String vertexType = "migration-list-1707"; + private final List<String> resultsSummary = new ArrayList<>(); + private BrokerService broker; + private final List<NotificationHelper> notifications = new ArrayList<>(); + private final String snapshotLocation = AAIConstants.AAI_HOME + AAIConstants.AAI_FILESEP + "logs" + AAIConstants.AAI_FILESEP + "data" + AAIConstants.AAI_FILESEP + "migrationSnapshots"; + /** + * The main method. + * + * @param args + * the arguments + */ + public void run(String[] args) { + // Set the logging file properties to be used by EELFManager + Properties props = System.getProperties(); + props.setProperty(Configuration.PROPERTY_LOGGING_FILE_NAME, "migration-logback.xml"); + props.setProperty(Configuration.PROPERTY_LOGGING_FILE_PATH, AAIConstants.AAI_HOME_ETC_APP_PROPERTIES); + + logger = EELFManager.getInstance().getLogger(MigrationControllerInternal.class.getSimpleName()); + MDC.put("logFilenameAppender", MigrationController.class.getSimpleName()); + + boolean loadSnapshot = false; + + CommandLineArgs cArgs = new CommandLineArgs(); + + JCommander jCommander = new JCommander(cArgs, args); + jCommander.setProgramName(MigrationController.class.getSimpleName()); + // Set flag to load from snapshot based on the presence of snapshot and + // graph storage backend of inmemory + if (cArgs.dataSnapshot != null && !cArgs.dataSnapshot.isEmpty()) { + try { + PropertiesConfiguration config = new PropertiesConfiguration(cArgs.config); + if (config.getString("storage.backend").equals("inmemory")) { + loadSnapshot = true; + System.setProperty("load.snapshot.file", "true"); + System.setProperty("snapshot.location", cArgs.dataSnapshot); + } + } catch (ConfigurationException e) { + logAndPrint("ERROR: Could not load titan configuration.\n" + ExceptionUtils.getFullStackTrace(e)); + return; + } + } + System.setProperty("realtime.db.config", cArgs.config); + logAndPrint("\n\n---------- Connecting to Graph ----------"); + AAIGraph.getInstance(); + + logAndPrint("---------- Connection Established ----------"); + Version version = AAIProperties.LATEST; + QueryStyle queryStyle = QueryStyle.TRAVERSAL; + ModelType introspectorFactoryType = ModelType.MOXY; + Loader loader = LoaderFactory.createLoaderForVersion(introspectorFactoryType, version); + TransactionalGraphEngine engine = new TitanDBEngine(queryStyle, DBConnectionType.REALTIME, loader); + + if (cArgs.help) { + jCommander.usage(); + engine.rollback(); + return; + } else if (cArgs.list) { + Reflections reflections = new Reflections("org.openecomp.aai.migration"); + Set<Class<? extends Migrator>> migratorClasses = findClasses(reflections); + List<Migrator> migratorList = createMigratorList(cArgs, migratorClasses); + + sortList(migratorList); + engine.startTransaction(); + System.out.println("---------- List of all migrations ----------"); + migratorList.forEach(migrator -> { + boolean enabledAnnotation = migrator.getClass().isAnnotationPresent(Enabled.class); + String enabled = enabledAnnotation ? "Enabled" : "Disabled"; + StringBuilder sb = new StringBuilder(); + sb.append(migrator.getClass().getSimpleName() + " " + enabled); + sb.append(" "); + sb.append("[" + getDbStatus(migrator.getClass().getSimpleName(), engine) + "]"); + System.out.println(sb.toString()); + }); + engine.rollback(); + System.out.println("---------- Done ----------"); + return; + } + + + Reflections reflections = new Reflections("org.openecomp.aai.migration"); + + logAndPrint("---------- Looking for migration scripts to be executed. ----------"); + Set<Class<? extends Migrator>> migratorClasses = findClasses(reflections); + List<Migrator> migratorList = createMigratorList(cArgs, migratorClasses); + + sortList(migratorList); + + if (!cArgs.scripts.isEmpty() && migratorList.size() == 0) { + logAndPrint("\tERROR: Failed to find migrations " + cArgs.scripts + "."); + logAndPrint("---------- Done ----------"); + } + + logAndPrint("\tFound " + migratorList.size() + " migration scripts."); + logAndPrint("---------- Executing Migration Scripts ----------"); + + + + takeSnapshotIfRequired(engine, cArgs, migratorList); + + for (Migrator migratorClass : migratorList) { + String name = migratorClass.getClass().getSimpleName(); + Migrator migrator; + if (migratorClass.getClass().isAnnotationPresent(Enabled.class)) { + + try { + engine.startTransaction(); + if (!cArgs.forced && hasAlreadyRun(name, engine)) { + logAndPrint("Migration " + name + " has already been run on this database and will not be executed again. Use -f to force execution"); + continue; + } + migrator = migratorClass.getClass().getConstructor(TransactionalGraphEngine.class).newInstance(engine); + } catch (InstantiationException | IllegalAccessException | IllegalArgumentException | InvocationTargetException | NoSuchMethodException | SecurityException e) { + logAndPrint("EXCEPTION caught initalizing migration class " + migratorClass.getClass().getSimpleName() + ".\n" + ExceptionUtils.getFullStackTrace(e)); + engine.rollback(); + continue; + } + logAndPrint("\tRunning " + migratorClass.getClass().getSimpleName() + " migration script."); + logAndPrint("\t\t See " + System.getProperty("AJSC_HOME") + "/logs/migration/" + migratorClass.getClass().getSimpleName() + "/* for logs."); + MDC.put("logFilenameAppender", migratorClass.getClass().getSimpleName() + "/" + migratorClass.getClass().getSimpleName()); + + migrator.run(); + + commitChanges(engine, migrator, cArgs); + } else { + logAndPrint("\tSkipping " + migratorClass.getClass().getSimpleName() + " migration script because it has been disabled."); + } + } + MDC.put("logFilenameAppender", MigrationController.class.getSimpleName()); + for (NotificationHelper notificationHelper : notifications) { + try { + notificationHelper.triggerEvents(); + } catch (AAIException e) { + logAndPrint("\tcould not event"); + logger.error("could not event", e); + } + } + logAndPrint("---------- Done ----------"); + + // Save post migration snapshot if snapshot was loaded + generateSnapshot(engine, "post"); + + outputResultsSummary(); + } + + private String getDbStatus(String name, TransactionalGraphEngine engine) { + if (hasAlreadyRun(name, engine)) { + return "Already executed in this env"; + } + return "Will be run on next execution"; + } + + private boolean hasAlreadyRun(String name, TransactionalGraphEngine engine) { + return engine.asAdmin().getReadOnlyTraversalSource().V().has(AAIProperties.NODE_TYPE, vertexType).has(name, true).hasNext(); + } + private Set<Class<? extends Migrator>> findClasses(Reflections reflections) { + Set<Class<? extends Migrator>> migratorClasses = reflections.getSubTypesOf(Migrator.class); + migratorClasses.remove(PropertyMigrator.class); + return migratorClasses; + } + + + private void takeSnapshotIfRequired(TransactionalGraphEngine engine, CommandLineArgs cArgs, List<Migrator> migratorList) { + + /*int sum = 0; + for (Migrator migrator : migratorList) { + if (migrator.getClass().isAnnotationPresent(Enabled.class)) { + sum += migrator.getDangerRating(); + } + } + + if (sum >= DANGER_ZONE) { + + logAndPrint("Entered Danger Zone. Taking snapshot."); + }*/ + + //always take snapshot for now + generateSnapshot(engine, "pre"); + + } + + + private List<Migrator> createMigratorList(CommandLineArgs cArgs, + Set<Class<? extends Migrator>> migratorClasses) { + List<Migrator> migratorList = new ArrayList<>(); + + for (Class<? extends Migrator> migratorClass : migratorClasses) { + if (!cArgs.scripts.isEmpty() && !cArgs.scripts.contains(migratorClass.getSimpleName())) { + continue; + } else { + Migrator migrator; + try { + + migrator = migratorClass.getConstructor().newInstance(); + } catch (InstantiationException | IllegalAccessException | IllegalArgumentException | InvocationTargetException | NoSuchMethodException | SecurityException e) { + logAndPrint("EXCEPTION caught initalizing migration class " + migratorClass.getSimpleName() + ".\n" + ExceptionUtils.getFullStackTrace(e)); + continue; + } + migratorList.add(migrator); + } + } + return migratorList; + } + + + private void sortList(List<Migrator> migratorList) { + Collections.sort(migratorList, new Comparator<Migrator>() { + public int compare(Migrator m1, Migrator m2) { + try { + + if (m1.getPriority() > m2.getPriority()) { + return 1; + } else if (m1.getPriority() < m2.getPriority()) { + return -1; + } else { + return m1.getClass().getSimpleName().compareTo(m2.getClass().getSimpleName()); + } + } catch (Exception e) { + return 0; + } + } + }); + } + + + private void generateSnapshot(TransactionalGraphEngine engine, String phase) { + + FormatDate fd = new FormatDate("yyyyMMddHHmm", "GMT"); + String dateStr= fd.getDateTime(); + String fileName = snapshotLocation + File.separator + phase + "Migration." + dateStr + ".graphson"; + logAndPrint("Saving snapshot of inmemory graph " + phase + " migration to " + fileName); + TitanTransaction transaction = null; + try { + + Path pathToFile = Paths.get(fileName); + if (!pathToFile.toFile().exists()) { + Files.createDirectories(pathToFile.getParent()); + } + transaction = engine.startTransaction(); + transaction.io(IoCore.graphson()).writeGraph(fileName); + engine.rollback(); + } catch (IOException e) { + logAndPrint("ERROR: Could not write in memory graph to " + phase + "Migration file. \n" + ExceptionUtils.getFullStackTrace(e)); + engine.rollback(); + } + + logAndPrint( phase + " migration snapshot saved to " + fileName); + } + /** + * Log and print. + * + * @param logger + * the logger + * @param msg + * the msg + */ + protected void logAndPrint(String msg) { + System.out.println(msg); + logger.info(msg); + } + + /** + * Commit changes. + * + * @param g + * the g + * @param migrator + * the migrator + * @param logger + * the logger + */ + protected void commitChanges(TransactionalGraphEngine engine, Migrator migrator, CommandLineArgs cArgs) { + + String simpleName = migrator.getClass().getSimpleName(); + String message; + if (migrator.getStatus().equals(Status.FAILURE)) { + message = "Migration " + simpleName + " Failed. Rolling back."; + logAndPrint("\t" + message); + migrator.rollback(); + } else if (migrator.getStatus().equals(Status.CHECK_LOGS)) { + message = "Migration " + simpleName + " encountered an anomily, check logs. Rolling back."; + logAndPrint("\t" + message); + migrator.rollback(); + } else { + MDC.put("logFilenameAppender", simpleName + "/" + migrator.getClass().getSimpleName()); + + if (cArgs.commit) { + if (!engine.asAdmin().getTraversalSource().V().has(AAIProperties.NODE_TYPE, vertexType).hasNext()) { + engine.asAdmin().getTraversalSource().addV(AAIProperties.NODE_TYPE, vertexType).iterate(); + } + engine.asAdmin().getTraversalSource().V().has(AAIProperties.NODE_TYPE, vertexType) + .property(simpleName, true).iterate(); + MDC.put("logFilenameAppender", MigrationController.class.getSimpleName()); + notifications.add(migrator.getNotificationHelper()); + migrator.commit(); + message = "Migration " + simpleName + " Succeeded. Changes Committed."; + logAndPrint("\t"+ message +"\t"); + } else { + message = "--commit not specified. Not committing changes for " + simpleName + " to database."; + logAndPrint("\t" + message); + migrator.rollback(); + } + + } + + resultsSummary.add(message); + + } + + private void outputResultsSummary() { + logAndPrint("---------------------------------"); + logAndPrint("-------------Summary-------------"); + for (String result : resultsSummary) { + logAndPrint(result); + } + logAndPrint("---------------------------------"); + logAndPrint("---------------------------------"); + } + +} + +class CommandLineArgs { + + @Parameter(names = "--help", help = true) + public boolean help; + + @Parameter(names = "-c", description = "location of configuration file") + public String config; + + @Parameter(names = "-m", description = "names of migration scripts") + public List<String> scripts = new ArrayList<>(); + + @Parameter(names = "-l", description = "list the status of migrations") + public boolean list = false; + + @Parameter(names = "-d", description = "location of data snapshot", hidden = true) + public String dataSnapshot; + + @Parameter(names = "-f", description = "force migrations to be rerun") + public boolean forced = false; + + @Parameter(names = "--commit", description = "commit changes to graph") + public boolean commit = false; + +} diff --git a/aai-resources/src/main/java/org/openecomp/aai/migration/Migrator.java b/aai-resources/src/main/java/org/openecomp/aai/migration/Migrator.java new file mode 100644 index 0000000..5ed0213 --- /dev/null +++ b/aai-resources/src/main/java/org/openecomp/aai/migration/Migrator.java @@ -0,0 +1,262 @@ +/*- + * ============LICENSE_START======================================================= + * org.openecomp.aai + * ================================================================================ + * 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.aai.migration; + +import java.util.Iterator; +import java.util.Optional; + +import org.apache.tinkerpop.gremlin.process.traversal.dsl.graph.__; +import org.apache.tinkerpop.gremlin.structure.Direction; +import org.apache.tinkerpop.gremlin.structure.Edge; +import org.apache.tinkerpop.gremlin.structure.Property; +import org.apache.tinkerpop.gremlin.structure.Vertex; +import org.apache.tinkerpop.gremlin.structure.VertexProperty; +import org.json.JSONException; +import org.json.JSONObject; +import org.openecomp.aai.db.props.AAIProperties; +import org.openecomp.aai.exceptions.AAIException; +import org.openecomp.aai.introspection.Loader; +import org.openecomp.aai.introspection.LoaderFactory; +import org.openecomp.aai.introspection.ModelType; +import org.openecomp.aai.introspection.Version; +import org.openecomp.aai.serialization.db.DBSerializer; +import org.openecomp.aai.serialization.db.EdgeRules; +import org.openecomp.aai.serialization.db.EdgeType; +import org.openecomp.aai.serialization.db.exceptions.NoEdgeRuleFoundException; +import org.openecomp.aai.serialization.engines.TransactionalGraphEngine; + +import com.att.eelf.configuration.EELFLogger; +import com.att.eelf.configuration.EELFManager; + +/** + * This class defines an A&AI Migration + */ +public abstract class Migrator implements Runnable { + + protected EELFLogger logger = null; + + protected DBSerializer serializer = null; + protected Loader loader = null; + + protected TransactionalGraphEngine engine; + protected NotificationHelper notificationHelper; + + public Migrator() { + //used for not great reflection implementation + } + /** + * Instantiates a new migrator. + * + * @param g the g + */ + public Migrator(TransactionalGraphEngine engine){ + this.engine = engine; + initDBSerializer(); + this.notificationHelper = new NotificationHelper(loader, serializer, engine, "AAI-MIGRATION", this.getMigrationName()); + logger = EELFManager.getInstance().getLogger(this.getClass().getSimpleName()); + logger.info("\tInitilization of " + this.getClass().getSimpleName() + " migration script complete."); + } + + /** + * Gets the status. + * + * @return the status + */ + public abstract Status getStatus(); + + /** + * Rollback. + */ + public void rollback() { + engine.rollback(); + } + + /** + * Commit. + */ + public void commit() { + engine.commit(); + } + + /** + * Gets the priority. + * + * Lower number has higher priority + * + * @return the priority + */ + public abstract int getPriority(); + + /** + * The larger the number, the more danger + * + * Range is 0-10 + * + * @return danger rating + */ + public abstract int getDangerRating(); + /** + * As string. + * + * @param v the v + * @return the string + */ + protected String asString(Vertex v) { + final JSONObject result = new JSONObject(); + Iterator<VertexProperty<Object>> properties = v.properties(); + Property<Object> pk = null; + try { + while (properties.hasNext()) { + pk = properties.next(); + result.put(pk.key(), pk.value()); + } + } catch (JSONException e) { + logger.error("Warning error reading vertex: " + e); + } + + return result.toString(); + } + + /** + * As string. + * + * @param edge the edge + * @return the string + */ + protected String asString(Edge edge) { + final JSONObject result = new JSONObject(); + Iterator<Property<Object>> properties = edge.properties(); + Property<Object> pk = null; + try { + while (properties.hasNext()) { + pk = properties.next(); + result.put(pk.key(), pk.value()); + } + } catch (JSONException e) { + logger.error("Warning error reading edge: " + e); + } + + return result.toString(); + } + /** + * Checks for edge between. + * + * @param vertex a + * @param vertex b + * @param direction d + * @param edgeLabel the edge label + * @return true, if successful + */ + protected boolean hasEdgeBetween(Vertex a, Vertex b, Direction d, String edgeLabel) { + + if (d.equals(Direction.OUT)) { + return engine.asAdmin().getReadOnlyTraversalSource().V(a).out(edgeLabel).where(__.otherV().hasId(b)).hasNext(); + } else { + return engine.asAdmin().getReadOnlyTraversalSource().V(a).in(edgeLabel).where(__.otherV().hasId(b)).hasNext(); + } + + } + + /** + * Creates the edge + * + * @param edgeType the edge type - COUSIN or TREE + * @param out the out + * @param in the in + * @return the edge + */ + protected Edge createEdge(EdgeType type, Vertex out, Vertex in) throws AAIException { + Edge newEdge = null; + try { + if (type.equals(EdgeType.COUSIN)){ + newEdge = EdgeRules.getInstance().addEdge(this.engine.asAdmin().getTraversalSource(), out, in); + } else { + newEdge = EdgeRules.getInstance().addTreeEdge(this.engine.asAdmin().getTraversalSource(), out, in); + } + } catch (NoEdgeRuleFoundException e) { + throw new AAIException("AAI_6129", e); + } + return newEdge; + } + + /** + * Creates the TREE edge + * + * @param out the out + * @param in the in + * @return the edge + */ + protected Edge createTreeEdge(Vertex out, Vertex in) throws AAIException { + Edge newEdge = createEdge(EdgeType.TREE, out, in); + return newEdge; + } + + /** + * Creates the COUSIN edge + * + * @param out the out + * @param in the in + * @return the edge + */ + protected Edge createCousinEdge(Vertex out, Vertex in) throws AAIException { + Edge newEdge = createEdge(EdgeType.COUSIN, out, in); + return newEdge; + } + + protected Edge createCousinEdgeBestEffort(Vertex out, Vertex in) throws AAIException { + return EdgeRules.getInstance().addEdgeIfPossible(this.engine.asAdmin().getTraversalSource(), out, in); + } + private void initDBSerializer() { + Version version = AAIProperties.LATEST; + ModelType introspectorFactoryType = ModelType.MOXY; + loader = LoaderFactory.createLoaderForVersion(introspectorFactoryType, version); + try { + this.serializer = new DBSerializer(version, this.engine, introspectorFactoryType, this.getMigrationName()); + } catch (AAIException e) { + throw new RuntimeException("could not create seralizer", e); + } + } + + /** + * These are the node types you would like your traversal to process + * @return + */ + public abstract Optional<String[]> getAffectedNodeTypes(); + + /** + * used as the "fromAppId" when modifying vertices + * @return + */ + public abstract String getMigrationName(); + + /** + * updates all internal vertex properties + * @param v + * @param isNewVertex + */ + protected void touchVertexProperties(Vertex v, boolean isNewVertex) { + this.serializer.touchStandardVertexProperties(v, isNewVertex); + } + + public NotificationHelper getNotificationHelper() { + return this.notificationHelper; + } +} diff --git a/aai-resources/src/main/java/org/openecomp/aai/migration/NotificationHelper.java b/aai-resources/src/main/java/org/openecomp/aai/migration/NotificationHelper.java index b956705..b00128d 100644 --- a/aai-resources/src/main/java/org/openecomp/aai/migration/NotificationHelper.java +++ b/aai-resources/src/main/java/org/openecomp/aai/migration/NotificationHelper.java @@ -28,7 +28,6 @@ import java.util.List; import javax.ws.rs.core.Response.Status; import org.apache.tinkerpop.gremlin.structure.Vertex; - import org.openecomp.aai.exceptions.AAIException; import org.openecomp.aai.introspection.Introspector; import org.openecomp.aai.introspection.Loader; @@ -37,9 +36,13 @@ import org.openecomp.aai.rest.ueb.UEBNotification; import org.openecomp.aai.serialization.db.DBSerializer; import org.openecomp.aai.serialization.engines.TransactionalGraphEngine; import org.openecomp.aai.serialization.engines.query.QueryEngine; + import com.att.eelf.configuration.EELFLogger; import com.att.eelf.configuration.EELFManager; +/** + * Allows for DMaaP notifications from Migrations + */ public class NotificationHelper { private static final EELFLogger LOGGER = EELFManager.getInstance().getLogger(NotificationHelper.class); diff --git a/aai-resources/src/main/java/org/openecomp/aai/migration/PropertyMigrator.java b/aai-resources/src/main/java/org/openecomp/aai/migration/PropertyMigrator.java new file mode 100644 index 0000000..ccc8aa6 --- /dev/null +++ b/aai-resources/src/main/java/org/openecomp/aai/migration/PropertyMigrator.java @@ -0,0 +1,149 @@ +/*- + * ============LICENSE_START======================================================= + * org.openecomp.aai + * ================================================================================ + * 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.aai.migration; + +import java.util.Optional; + +import org.apache.tinkerpop.gremlin.process.traversal.P; +import org.apache.tinkerpop.gremlin.process.traversal.dsl.graph.GraphTraversal; +import org.apache.tinkerpop.gremlin.structure.Vertex; +import org.openecomp.aai.db.props.AAIProperties; +import org.openecomp.aai.serialization.engines.TransactionalGraphEngine; + +import com.thinkaurelius.titan.core.Cardinality; +import com.thinkaurelius.titan.core.PropertyKey; +import com.thinkaurelius.titan.core.schema.TitanManagement; + +/** + * A migration template for migrating a property from one name to another + */ +public abstract class PropertyMigrator extends Migrator { + + protected final String OLD_FIELD; + protected final String NEW_FIELD; + protected final Class<?> fieldType; + protected final Cardinality cardinality; + protected final TitanManagement graphMgmt; + public PropertyMigrator() { + //used for not great reflection implementation + super(); + this.OLD_FIELD = null; + this.NEW_FIELD = null; + this.fieldType = null; + this.cardinality = null; + this.graphMgmt = null; + } + public PropertyMigrator(TransactionalGraphEngine engine, String oldName, String newName, Class<?> type, Cardinality cardinality) { + super(engine); + this.OLD_FIELD = oldName; + this.NEW_FIELD = newName; + this.fieldType = type; + this.cardinality = cardinality; + this.graphMgmt = engine.asAdmin().getManagementSystem(); + } + + /** + * Do not override this method as an inheritor of this class + */ + @Override + public void run() { + + modifySchema(); + executeModifyOperation(); + + } + + protected void modifySchema() { + this.addIndex(this.addProperty()); + graphMgmt.commit(); + } + + /** + * This is where inheritors should add their logic + */ + protected void executeModifyOperation() { + changePropertyName(); + } + + protected void changePropertyName() { + GraphTraversal<Vertex, Vertex> g = this.engine.asAdmin().getTraversalSource().V(); + if (this.getAffectedNodeTypes().isPresent()) { + g.has(AAIProperties.NODE_TYPE, P.within(this.getAffectedNodeTypes().get())); + } + g.has(OLD_FIELD).sideEffect(t -> { + final Vertex v = t.get(); + final String value = v.value(OLD_FIELD); + v.property(OLD_FIELD).remove(); + v.property(NEW_FIELD, value); + this.touchVertexProperties(v, false); + }).iterate(); + } + + @Override + public Status getStatus() { + GraphTraversal<Vertex, Vertex> g = this.engine.asAdmin().getTraversalSource().V(); + if (this.getAffectedNodeTypes().isPresent()) { + g.has(AAIProperties.NODE_TYPE, P.within(this.getAffectedNodeTypes().get())); + } + long result = g.has(OLD_FIELD).count().next(); + if (result == 0) { + return Status.SUCCESS; + } else { + return Status.FAILURE; + } + } + + @Override + public int getPriority() { + return 0; + } + + @Override + public int getDangerRating() { + return 1; + } + + protected Optional<PropertyKey> addProperty() { + + if (!graphMgmt.containsPropertyKey(this.NEW_FIELD)) { + logger.info(" PropertyKey [" + this.NEW_FIELD + "] created in the DB. "); + return Optional.of(graphMgmt.makePropertyKey(this.NEW_FIELD).dataType(this.fieldType).cardinality(this.cardinality) + .make()); + } else { + logger.info(" PropertyKey [" + this.NEW_FIELD + "] already existed in the DB. "); + return Optional.empty(); + } + + } + + protected void addIndex(Optional<PropertyKey> key) { + if (isIndexed() && key.isPresent()) { + if (graphMgmt.containsGraphIndex(key.get().name())) { + logger.debug(" Index [" + key.get().name() + "] already existed in the DB. "); + } else { + logger.info("Add index for PropertyKey: [" + key.get().name() + "]"); + graphMgmt.buildIndex(key.get().name(), Vertex.class).addKey(key.get()).buildCompositeIndex(); + } + } + } + public abstract boolean isIndexed(); + +} diff --git a/aai-resources/src/main/java/org/openecomp/aai/migration/Status.java b/aai-resources/src/main/java/org/openecomp/aai/migration/Status.java new file mode 100644 index 0000000..a681d4d --- /dev/null +++ b/aai-resources/src/main/java/org/openecomp/aai/migration/Status.java @@ -0,0 +1,30 @@ +/*- + * ============LICENSE_START======================================================= + * org.openecomp.aai + * ================================================================================ + * 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.aai.migration; + +/** + * Defines the status of the completed migration + */ +public enum Status { + SUCCESS, + CHECK_LOGS, + FAILURE +} diff --git a/aai-resources/src/main/java/org/openecomp/aai/rest/exceptions/AAIInvalidXMLNamespace.java b/aai-resources/src/main/java/org/openecomp/aai/rest/exceptions/AAIInvalidXMLNamespace.java index e71e1f2..28d7e94 100644 --- a/aai-resources/src/main/java/org/openecomp/aai/rest/exceptions/AAIInvalidXMLNamespace.java +++ b/aai-resources/src/main/java/org/openecomp/aai/rest/exceptions/AAIInvalidXMLNamespace.java @@ -5,16 +5,16 @@ * 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. + * 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========================================================= */ diff --git a/aai-resources/src/main/java/org/openecomp/aai/util/GetResource.java b/aai-resources/src/main/java/org/openecomp/aai/util/GetResource.java deleted file mode 100644 index a0a3297..0000000 --- a/aai-resources/src/main/java/org/openecomp/aai/util/GetResource.java +++ /dev/null @@ -1,152 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * org.openecomp.aai - * ================================================================================ - * 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.aai.util; - -import java.security.KeyManagementException; -import java.util.Properties; -import java.util.UUID; - -import org.openecomp.aai.exceptions.AAIException; -import org.openecomp.aai.logging.ErrorLogHelper; -import com.att.eelf.configuration.Configuration; -import com.att.eelf.configuration.EELFLogger; -import com.att.eelf.configuration.EELFManager; -import com.fasterxml.jackson.databind.ObjectMapper; -import com.sun.jersey.api.client.Client; -import com.sun.jersey.api.client.ClientResponse; - - -public class GetResource { - - private static EELFLogger LOGGER; - private static final String FROMAPPID = "AAI-TOOLS"; - private static final String TRANSID = UUID.randomUUID().toString(); - private static final String USAGE_STRING = "Usage: getTool.sh <resource-path> \n + " - + "for example: resource-path for a particular customer is business/customers/customer/global-customer-id-1 \n"; - - /** - * The main method. - * - * @param args the arguments - */ - public static void main(String[] args) { - - // Set the logging file properties to be used by EELFManager - Properties props = System.getProperties(); - props.setProperty(Configuration.PROPERTY_LOGGING_FILE_NAME, AAIConstants.AAI_GETRES_LOGBACK_PROPS); - props.setProperty(Configuration.PROPERTY_LOGGING_FILE_PATH, AAIConstants.AAI_HOME_ETC_APP_PROPERTIES); - LOGGER = EELFManager.getInstance().getLogger(GetResource.class); - String url = null; - try { - if (args.length < 1) { - System.out.println("Nothing to get or Insufficient arguments"); - System.out.println(USAGE_STRING); - System.exit(1); - } else { - // Assume the config AAI_SERVER_URL has a last slash so remove if - // resource-path has it as the first char - url = args[0].replaceFirst("^/", ""); - url = AAIConfig.get(AAIConstants.AAI_SERVER_URL) + url; - - String dmsg = "url=" + url; - LOGGER.debug( dmsg ); - System.out.println( dmsg ); - - getNode(url); - System.exit(0); - } - } catch (AAIException e) { - String emsg = "GET failed: " + e.getMessage(); - System.out.println(emsg); - LOGGER.error(emsg); - ErrorLogHelper.logException(e); - System.exit(1); - } catch (Exception e) { - String emsg = "GET failed: " + e.getMessage(); - System.out.println(emsg); - LOGGER.error(emsg); - ErrorLogHelper.logError("AAI_7402", e.getMessage()); - System.exit(1); - } - - } - - /** - * Gets the node. - * - * @param aaiLogger the aai logger - * @param logline the logline - * @param url the url - * @return the node - * @throws AAIException the AAI exception - */ - public static void getNode(String url) throws AAIException { - try { - String useBasicAuth = AAIConfig.get("aai.tools.enableBasicAuth"); - Client client = null; - - if("true".equals(useBasicAuth)){ - client = HttpsAuthClient.getBasicAuthClient(); - } else { - client = HttpsAuthClient.getTwoWaySSLClient(); - } - - System.out.println("Getting the resource...: " + url); - - ClientResponse cres = client.resource(url) - .header("X-TransactionId", TRANSID) - .header("X-FromAppId", FROMAPPID) - .header("Authorization", HttpsAuthClient.getBasicAuthHeaderValue()) - - .accept("application/json") - .get(ClientResponse.class); - - if (cres.getStatus() == 404) { // resource not found - String infmsg = "\nResource does not exist: " + cres.getStatus() - + ":" + cres.getEntity(String.class); - System.out.println(infmsg); - LOGGER.info(infmsg); - throw new AAIException("AAI_7404", "Resource does not exist"); - } else if (cres.getStatus() == 200){ - String msg = cres.getEntity(String.class); - ObjectMapper mapper = new ObjectMapper(); - Object json = mapper.readValue(msg, Object.class); - String indented = mapper.writerWithDefaultPrettyPrinter() - .writeValueAsString(json); - System.out.println(indented); - LOGGER.info(indented); - } else { - String emsg = "Getting the Resource failed: " + cres.getStatus() - + ":\n" + cres.getEntity(String.class); - System.out.println(emsg); - LOGGER.error(emsg); - throw new AAIException("AAI_7402", "Error during GET"); - } - } catch (AAIException e) { - throw e; - } catch (KeyManagementException e) { - throw new AAIException("AAI_7401", e, "Error during GET"); - } catch (Exception e) { - throw new AAIException("AAI_7402", e, "Error during GET"); - } - } - -} diff --git a/aai-resources/src/main/java/org/openecomp/aai/util/MergeResource.java b/aai-resources/src/main/java/org/openecomp/aai/util/MergeResource.java deleted file mode 100644 index 427f65b..0000000 --- a/aai-resources/src/main/java/org/openecomp/aai/util/MergeResource.java +++ /dev/null @@ -1,205 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * org.openecomp.aai - * ================================================================================ - * 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.aai.util; - -import java.lang.reflect.Field; -import java.lang.reflect.Method; -import java.util.Date; - -import com.sun.tools.javac.util.List; - -//SWGK - 01/08/2016 - Helper function to deal with concurrency control -public class MergeResource { - - //Merge Assumptions: - //fromresource and toresource are the same resource type and same resource object - //fromresource is the latest version from the DB - //toresource is the version of the same resource with updates - //merging of child elements are complete overwrite of fromresource corresponding child element - //merging of relationshiplist is complete overwrite of fromresource corresponding releationship element - //In case of supplying the only specific child element update, please specify the child element type (need not be in canonical form) - //For parent only update (not involving child or relationship element update), then all the child elements and relationship list will be set as null in the merged object - //For setting null to primitive type (including String) you have to do it after the merge is called specifically for parent only copy - - - /** - * Merge. - * - * @param <T> the generic type - * @param fromresource the fromresource - * @param toresource the toresource - * @param bupdateChildren the bupdate children - * @param childNamelist the child namelist - * @param bupdateRelatedLink the bupdate related link - * @return the t - */ - public static <T> T merge(T fromresource, T toresource, boolean bupdateChildren, String childNamelist[], boolean bupdateRelatedLink) - { - Field[] fields = fromresource.getClass().getDeclaredFields(); - if (fields != null) - { - for (Field field : fields) - { - try - { - field.setAccessible(true); - if ( field.getName().equalsIgnoreCase("resourceVersion") ) - continue; - if ( isValidMergeType(field.getType()) ) - { - Object obj = field.get(toresource); - // If the updated resource's any property to be set null then one has to set it separately for the merged object - if (obj != null) - field.set(fromresource, obj); - continue; - } - else - // set the child list or relatedTo link to be null so no updates takes place - field.set(fromresource, null); - //override situation - if (bupdateChildren || bupdateRelatedLink) - { - if (bupdateRelatedLink && field.getName().equalsIgnoreCase("relationshipList")) - { - Object obj = field.get(toresource); - field.set(fromresource, obj); - continue; - } - if (field.getName().equalsIgnoreCase("relationshipList")) - if (!bupdateRelatedLink) - continue; - // not an efficient as it blindly updates all children - onus is on callee to nullify - // specific child(ren) that they don't want to update after the merge call. - // can be optimized to send a list of children class names in canonical form - // but deferring for next release so that only those children can be merged - if (bupdateChildren && (childNamelist != null)) - { - for (String classStringName : childNamelist) - { - if ( !classStringName.isEmpty() && field.getType().toString().toLowerCase().endsWith(classStringName.toLowerCase()) ) - { - Object obj = field.get(toresource); - field.set(fromresource, obj); - } - } - continue; - } - - if (bupdateChildren && (childNamelist == null)) - { - Object obj = field.get(toresource); - field.set(fromresource, obj); - - } - } - - } - catch (Exception e) - { - - } - - - } - } - return fromresource; - } - - - /** - * Merge. - * - * @param <T> the generic type - * @param fromresource the fromresource - * @param toresource the toresource - * @return the t - */ - public static <T> T merge(T fromresource, T toresource) - { - return merge(fromresource, toresource, false, false); - } - - /** - * Merge. - * - * @param <T> the generic type - * @param fromresource the fromresource - * @param toresource the toresource - * @param bupdateChildren the bupdate children - * @param bupdateRelatedLink the bupdate related link - * @return the t - */ - public static <T> T merge(T fromresource, T toresource, boolean bupdateChildren, boolean bupdateRelatedLink) - { - return merge(fromresource, toresource, bupdateChildren, null, bupdateRelatedLink); - } - - /** - * Checks if is valid merge type. - * - * @param fieldType the field type - * @return true, if is valid merge type - */ - public static boolean isValidMergeType(Class<?> fieldType) { - if (fieldType.equals(String.class)) { - return true; - } else if (Date.class.isAssignableFrom(fieldType)) { - return true; - } else if (Number.class.isAssignableFrom(fieldType)) { - return true; - } else if (fieldType.equals(Integer.TYPE)) { - return true; - } else if (fieldType.equals(Long.TYPE)) { - return true; - } else if (Enum.class.isAssignableFrom(fieldType)) { - return true; - } else if (Boolean.class.isAssignableFrom(fieldType)) { - return true; - } - else { - return false; - } - } - - /** - * Gets the child return type. - * - * @param classname the classname - * @param methodname the methodname - * @return the class - */ - public static Class<?> GetChildReturnType(String classname, String methodname) - { - try { - Class<?> c = Class.forName(classname); - Method[] allMethods = c.getDeclaredMethods(); - for (Method m : allMethods) { - if (!m.getName().equals(methodname)) { - return m.getReturnType(); - } - } - } catch (ClassNotFoundException x) { - - } - - return null; - } -} diff --git a/aai-resources/src/main/java/org/openecomp/aai/util/PostResource.java b/aai-resources/src/main/java/org/openecomp/aai/util/PostResource.java deleted file mode 100644 index 1caeb09..0000000 --- a/aai-resources/src/main/java/org/openecomp/aai/util/PostResource.java +++ /dev/null @@ -1,183 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * org.openecomp.aai - * ================================================================================ - * 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.aai.util; - -import java.io.BufferedReader; -import java.io.FileReader; -import java.io.IOException; -import java.nio.file.Path; -import java.nio.file.Paths; -import java.util.Properties; -import java.util.UUID; - -import org.openecomp.aai.exceptions.AAIException; -import org.openecomp.aai.logging.ErrorLogHelper; -import com.att.eelf.configuration.Configuration; -import com.att.eelf.configuration.EELFLogger; -import com.att.eelf.configuration.EELFManager; -import com.fasterxml.jackson.databind.ObjectMapper; -import com.google.common.base.CaseFormat; - -/* - * Allows to call POST REST API that AAI supports - currently for edge-tag-query - */ -public class PostResource { - - private static EELFLogger LOGGER; - private static final String FROMAPPID = "AAI-TOOLS"; - private static final String TRANSID = UUID.randomUUID().toString(); - private static final String USAGE_STRING = "Usage: postTool.sh <resource-path> <filename>\n" + - "resource-path for a particular resource or query starting after the aai/<version>\n" + - "filename is the path to a file which contains the json input for the payload\n" + - "for example: postTool.sh search/edge-tag-query /tmp/query-input.json\n"; - - /** - * The main method. - * - * @param <T> the generic type - * @param args the arguments - */ - public static <T> void main(String[] args) { - - // Set the logging file properties to be used by EELFManager - Properties props = System.getProperties(); - props.setProperty(Configuration.PROPERTY_LOGGING_FILE_NAME, AAIConstants.AAI_POSTTOOL_LOGBACK_PROPS); - props.setProperty(Configuration.PROPERTY_LOGGING_FILE_PATH, AAIConstants.AAI_HOME_ETC_APP_PROPERTIES); - LOGGER = EELFManager.getInstance().getLogger(PostResource.class); - try { - if (args.length < 2) { - System.out.println("Insufficient arguments"); - System.out.println(USAGE_STRING); - System.exit(1); - } - - // Assume the config AAI_SERVER_URL has a last slash so remove if - // resource-path has it as the first char - String path = args[0].replaceFirst("^/", ""); - Path p = Paths.get(path); - - // currently , it is for edge-taq-query only - String query = p.getName(p.getNameCount() - 1).toString(); - String resourceClass = null; - if (query.equals("edge-tag-query")) - resourceClass = "org.openecomp.aai.domain.search." + - CaseFormat.LOWER_HYPHEN.to(CaseFormat.UPPER_CAMEL, query) + "Request"; - else { - ErrorLogHelper.logError("AAI_7403", "Incorrect resource or query"); - System.exit(1); - } - - String dMsg = "class=" + resourceClass; - System.out.println(dMsg); - LOGGER.debug(dMsg); - - dMsg = "path=" + path; - System.out.println(dMsg); - LOGGER.debug(dMsg); - - @SuppressWarnings("unchecked") - T resJson1 = (T)readJsonFile(Class.forName(resourceClass), args[1]); - - String response = RestController.<T>Post(resJson1, FROMAPPID, TRANSID, path); - ObjectMapper mapper = new ObjectMapper(); - Object json = mapper.readValue(response, Object.class); - - String infMsg = " POST succeeded\n"; - System.out.println(infMsg); - LOGGER.info(infMsg); - - infMsg = "Response = " + mapper.writer().withDefaultPrettyPrinter().writeValueAsString(json); - System.out.println(infMsg); - LOGGER.info(infMsg); - - infMsg = "\nDone!!"; - System.out.println(infMsg); - LOGGER.info(infMsg); - - System.exit(0); - - } catch (AAIException e) { - ErrorLogHelper.logException(e); - System.exit(1); - } catch (Exception e) { - ErrorLogHelper.logError("AAI_7402", e.getMessage()); - System.exit(1); - } - } - - /** - * Gets the single instance of PostResource. - * - * @param <T> the generic type - * @param clazz the clazz - * @return single instance of PostResource - * @throws IllegalAccessException the illegal access exception - * @throws InstantiationException the instantiation exception - */ - public static <T> T getInstance(Class<T> clazz) throws IllegalAccessException, InstantiationException - { - return clazz.newInstance(); - } - - /** - * Read json file. - * - * @param <T> the generic type - * @param clazz the clazz - * @param fName the f name - * @return the t - * @throws AAIException the AAI exception - */ - public static <T> T readJsonFile( Class<T> clazz, String fName ) throws AAIException - { - String jsonData = ""; - BufferedReader br = null; - T t; - - try { - String line; - br = new BufferedReader(new FileReader(fName)); - while ((line = br.readLine()) != null) { - jsonData += line + "\n"; - } - } catch (IOException e) { - throw new AAIException("AAI_7403", e, "Error opening json file"); - } finally { - try { - if (br != null) - br.close(); - } catch (IOException ex) { - ex.printStackTrace(); - throw new AAIException("AAI_7403", ex, "Error closing json file"); - } - } - - try { - t = MapperUtil.readWithDashesAsObjectOf(clazz, jsonData); - } - catch (Exception je){ - throw new AAIException("AAI_7403", je, "Error parsing json file"); - } - - return t; - - }//End readJsonFile() -} diff --git a/aai-resources/src/main/java/org/openecomp/aai/util/PutResource.java b/aai-resources/src/main/java/org/openecomp/aai/util/PutResource.java deleted file mode 100644 index ced51cd..0000000 --- a/aai-resources/src/main/java/org/openecomp/aai/util/PutResource.java +++ /dev/null @@ -1,432 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * org.openecomp.aai - * ================================================================================ - * 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.aai.util; - -import java.io.BufferedReader; -import java.io.FileReader; -import java.io.IOException; -import java.lang.reflect.Field; -import java.net.URI; -import java.nio.file.Path; -import java.nio.file.Paths; -import java.security.KeyManagementException; -import java.util.Properties; -import java.util.UUID; - -import org.openecomp.aai.db.props.AAIProperties; -import org.openecomp.aai.exceptions.AAIException; -import org.openecomp.aai.introspection.Loader; -import org.openecomp.aai.introspection.LoaderFactory; -import org.openecomp.aai.introspection.ModelType; -import org.openecomp.aai.logging.ErrorLogHelper; -import org.openecomp.aai.parsers.uri.URIToObject; - -import com.att.eelf.configuration.Configuration; -import com.att.eelf.configuration.EELFLogger; -import com.att.eelf.configuration.EELFManager; -import com.google.common.base.CaseFormat; -import com.sun.jersey.api.client.Client; -import com.sun.jersey.api.client.ClientResponse; - -/* - * SWGK - 09/03/2015 - Added Generics to Put as well as to Get the object that was created/updated - * by Put to get the Object back. - */ -public class PutResource { - - private static EELFLogger LOGGER; - private static final String FROMAPPID = "AAI-TOOLS"; - private static final String TRANSID = UUID.randomUUID().toString(); - private static final String USAGE_STRING = "Usage: putTool.sh <resource-path> <filename> <UpdatingRelationshiplist> <UpdatingChild> <ChildNameList> <SkipIfExists>\n" + - "resource-path for a particular resource starting after the aai/<version>\n" + - "filename is the path to a file which contains the json input for the payload\n" + - "optional UpdatingRelationshiplist setting 1 for updating the relationship list and if setting 0 relationship list will not be updated.\n" + - "optional UpdatingChild setting 1 for updating the child(r)en and if setting 0 child(ren) will not be updated.\n" + - "optional ChildNameList is a comma-separated child(ren) name list only applicable if UpdatingChild is set to 1.\n" + - "optional SkipIfExisting setting 1 to skip the update if resource exists and if setting 0 put will be done.\n" + - "for example 1: putTool.sh cloud-infrastructure/oam-networks/oam-network/test-100-oam /tmp/putoam.json\n" + - "for example 2: putTool.sh cloud-infrastructure/pservers/pserver/dpa2r04c009-swgk-009 /tmp/pserver.json 0 1 PInterfaces,LagInterfaces\n" + - "for example 2: putTool.sh cloud-infrastructure/pservers/pserver/dpa2r04c009-swgk-009 /tmp/pserver.json 0 1 PInterfaces,LagInterfaces 1\n"; - - /** - * The main method. - * - * @param <T> the generic type - * @param args the arguments - */ - public static <T> void main(String[] args) { - - // Set the logging file properties to be used by EELFManager - Properties props = System.getProperties(); - props.setProperty(Configuration.PROPERTY_LOGGING_FILE_NAME, AAIConstants.AAI_PUTTOOL_LOGBACK_PROPS); - props.setProperty(Configuration.PROPERTY_LOGGING_FILE_PATH, AAIConstants.AAI_HOME_ETC_APP_PROPERTIES); - LOGGER = EELFManager.getInstance().getLogger(PutResource.class); - Boolean bResVersionEnabled = false; - - try - { - String strEnableResVersion = AAIConfig.get(AAIConstants.AAI_RESVERSION_ENABLEFLAG); - if (strEnableResVersion != null && !strEnableResVersion.isEmpty()) - bResVersionEnabled = Boolean.valueOf(strEnableResVersion); - } - catch (Exception e) { - - } - - boolean doPutIfExists = true; - if (args.length > 5) - if (args[5].equals("1")) - doPutIfExists = false; - - try { - if (args.length < 2) { - System.out.println("Insufficient arguments"); - System.out.println(USAGE_STRING); - System.exit(1); - } - - Loader loader = LoaderFactory.createLoaderForVersion(ModelType.MOXY, AAIProperties.LATEST); - // Assume the config AAI_SERVER_URL has a last slash so remove if - // resource-path has it as the first char - URI uri = new URI(args[0]); - String path = args[0].replaceFirst("^/", ""); - Path p = Paths.get(path); - - URIToObject parser = new URIToObject(loader, uri); - String resource = parser.getEntityName(); - - String resourceClass = CaseFormat.LOWER_HYPHEN.to(CaseFormat.UPPER_CAMEL, resource); - resourceClass = "org.openecomp.aai.domain.yang." + resourceClass; - - LOGGER.debug("class=" + resourceClass); - LOGGER.debug("path=" + path); - - RestObject<T> restObj = new RestObject<T>(); - @SuppressWarnings("unchecked") - T t2 = (T)getInstance(Class.forName(resourceClass)); - restObj.set(t2); - - boolean bExist = true; - - try - { - if ( !doPutIfExists ) { - - String url = AAIConfig.get(AAIConstants.AAI_SERVER_URL) + path; - - LOGGER.debug("url=" + url); - if ( nodeExists( url) ) { - String infMsg ="PUT succeeded, the resource exists already in the DB. Skipping the put based on the skipIfExists command line parameter.\n"; - System.out.println(infMsg); - LOGGER.info(infMsg); - System.exit(0); - } - } - RestController.<T>Get(t2, FROMAPPID, TRANSID, path, restObj, false); - t2 = restObj.get(); - String infMsg = " GET succeeded\n"; - System.out.println(infMsg); - LOGGER.info(infMsg); - - } catch (AAIException e) { - if ( !doPutIfExists ) { - System.out.println("Warning - Caught exception while attempting to PUT resource"); - LOGGER.warn("Caught exception while attempting to PUT resource", e); - } - bExist = false; - } - catch (Exception e1) - { - if ( !doPutIfExists ) { - System.out.println("Warning - GET exception ignored with skipExists parameter\n"); - LOGGER.warn(" GET exception ignored with skipExists parameter\n", e1); - } - bExist = false; - } - - - @SuppressWarnings("unchecked") - T resJson1 = (T)readJsonFile(Class.forName(resourceClass), args[1]); - String resourceUpdateVersion = GetResourceVersion(resJson1); - - - if (bResVersionEnabled && bExist) - { - - String DBresourceVersion = GetResourceVersion(t2); - if ( !doPutIfExists ) { - String infMsg = "PUT succeeded, the resource exists already in the DB. Skipping the put based on the skipIfExists command line parameter.\n"; - System.out.println(infMsg); - LOGGER.info(infMsg); - System.exit(0); - } - - if (resourceUpdateVersion == null || resourceUpdateVersion.isEmpty()) - { - if ( DBresourceVersion != null && !DBresourceVersion.isEmpty()){ - String eMsg = "The resource with version = " + DBresourceVersion + " exists already in the DB. Please supply the right resourceVersion in input data file.\n"; - System.out.println(eMsg); - LOGGER.error(eMsg); - } - else{ - String eMsg = "The resource exists already in the DB. Please supply the right resourceVersion in input data file.\n"; - System.out.println(eMsg); - LOGGER.error(eMsg); - } - System.exit(1); - } - - if ( DBresourceVersion != null && !DBresourceVersion.isEmpty() ) - { - if ( resourceUpdateVersion != null && !resourceUpdateVersion.isEmpty() ) - if (!DBresourceVersion.equals(resourceUpdateVersion)) - { - String eMsg = "DB version doesn't match current version. Please get the latest version and modify.\n"; - System.out.println(eMsg); - LOGGER.error(eMsg); - System.exit(1); - } - } - } - else //sanity check - { - if ( bResVersionEnabled && resourceUpdateVersion != null && !resourceUpdateVersion.isEmpty()) - { - String eMsg = "DB doesn't have this resource any more. Please create a new version by taking out the resourceVersion tag from your input resource data file.\n"; - System.out.println(eMsg); - LOGGER.error(eMsg); - System.exit(1); - } - - } - - if (bExist) //merge - { - boolean bUpdateChildren = false; - boolean bUpdateRL = false; - - if (args.length == 3) - { - if (args[2].equals("1")) - bUpdateRL = true; - resJson1 = MergeResource.merge(t2, resJson1, false, bUpdateRL); - } - else if (args.length == 4) - { - if (args[2].equals("1")) - bUpdateRL = true; - if (args[3].equals("1")) - bUpdateChildren = true; - resJson1 = MergeResource.merge(t2, resJson1, bUpdateChildren, bUpdateRL); - } - else if (args.length == 5) - { - if (args[2].equals("1")) - bUpdateRL = true; - if (args[3].equals("1")) - bUpdateChildren = true; - String[] strChildArray = args[4].split("\\,"); - resJson1 = MergeResource.merge(t2, resJson1, bUpdateChildren, strChildArray, bUpdateRL); - - } - else - resJson1 = MergeResource.merge(t2, resJson1); - - } - - RestController.<T>Put(resJson1, FROMAPPID, TRANSID, path, false); - - String infMsg = " PUT succeeded"; - System.out.println(infMsg); - LOGGER.info(infMsg); - infMsg = "Done!!"; - System.out.println(infMsg); - LOGGER.info(infMsg); - - System.exit(0); - - } catch (AAIException e) { - if ( !doPutIfExists ) { // ignore 412 failure - if ( e.getMessage().equals("AAI_7116") ) { - if ( e.getMessage().indexOf("status=412") > 0) { - String infMsg = "PUT succeeded, return 412 ignored\n"; - System.out.println(infMsg); - LOGGER.info(infMsg); - - infMsg = "\nDone!!"; - System.out.println(infMsg); - LOGGER.info(infMsg); - System.exit(0); - } - } - } - - ErrorLogHelper.logException(e); - System.exit(1); - } catch (Exception e) { - ErrorLogHelper.logError("AAI_7402", e.getMessage()); - System.exit(1); - } - } - - /** - * Gets the single instance of PutResource. - * - * @param <T> the generic type - * @param clazz the clazz - * @return single instance of PutResource - * @throws IllegalAccessException the illegal access exception - * @throws InstantiationException the instantiation exception - */ - public static <T> T getInstance(Class<T> clazz) throws IllegalAccessException, InstantiationException - { - return clazz.newInstance(); - } - - /** - * Read json file. - * - * @param <T> the generic type - * @param clazz the clazz - * @param fName the f name - * @return the t - * @throws AAIException the AAI exception - */ - public static <T> T readJsonFile( Class<T> clazz, String fName ) throws AAIException - { - String jsonData = ""; - BufferedReader br = null; - T t; - - try { - String line; - br = new BufferedReader(new FileReader(fName)); - while ((line = br.readLine()) != null) { - jsonData += line + "\n"; - } - } catch (IOException e) { - - throw new AAIException("AAI_7403", e, "Error opening json file"); - } finally { - try { - if (br != null) - br.close(); - } catch (IOException ex) { - throw new AAIException("AAI_7403", ex, "Error closing json file"); - } - } - - try { - t = MapperUtil.readWithDashesAsObjectOf(clazz, jsonData); - } - catch (Exception je){ - throw new AAIException("AAI_7403", je, "Error parsing json file"); - } - - return t; - - }//End readJsonFile() - - /** - * Gets the resource version. - * - * @param <T> the generic type - * @param resource the resource - * @return the string - */ - public static <T> String GetResourceVersion(T resource) - { - Field[] fields = resource.getClass().getDeclaredFields(); - if (fields != null) - { - for (Field field : fields) - { - try - { - field.setAccessible(true); - if ( field.getName().equalsIgnoreCase("resourceVersion") ) - { - Object obj = field.get(resource); - return (String)obj; - } - - - } - catch (Exception e) - { - - } - - - } - } - return null; - } - - /** - * Node exists. - * - * @param url the url - * @return true, if successful - * @throws AAIException the AAI exception - */ - public static boolean nodeExists(String url) throws AAIException { - try{ - String useBasicAuth = AAIConfig.get("aai.tools.enableBasicAuth"); - Client client = null; - - if("true".equals(useBasicAuth)){ - client = HttpsAuthClient.getBasicAuthClient(); - } else { - client = HttpsAuthClient.getTwoWaySSLClient(); - } - - String infMsg = "Getting the resource...: " + url; - System.out.println(infMsg); - LOGGER.info(infMsg); - - ClientResponse cres = client.resource(url) - .header("X-TransactionId", TRANSID) - .header("X-FromAppId", FROMAPPID) - .header("Authorization", HttpsAuthClient.getBasicAuthHeaderValue()) - .accept("application/json") - .get(ClientResponse.class); - - - if (cres.getStatus() == 404) { // resource not found - return false; - } else if (cres.getStatus() == 200){ - return true; - } else { - String eMsg = "Getting the Resource failed: " + cres.getStatus() - + ": " + cres.getEntity(String.class); - System.out.println(eMsg); - LOGGER.error(eMsg); - return false; - } - } catch (KeyManagementException e) { - throw new AAIException("AAI_7401", e, "Error during GET"); - } catch (Exception e) { - throw new AAIException("AAI_7402", e, "Error during GET"); - } - } - -} diff --git a/aai-resources/src/main/java/org/openecomp/aai/util/RelationshipPutDel.java b/aai-resources/src/main/java/org/openecomp/aai/util/RelationshipPutDel.java deleted file mode 100644 index a6a21ca..0000000 --- a/aai-resources/src/main/java/org/openecomp/aai/util/RelationshipPutDel.java +++ /dev/null @@ -1,211 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * org.openecomp.aai - * ================================================================================ - * 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.aai.util; - -import java.io.BufferedReader; -import java.io.FileReader; -import java.io.IOException; -import java.security.KeyManagementException; -import java.util.Properties; -import java.util.UUID; - -import org.openecomp.aai.domain.yang.Relationship; -import org.openecomp.aai.exceptions.AAIException; -import com.att.eelf.configuration.Configuration; -import com.att.eelf.configuration.EELFLogger; -import com.att.eelf.configuration.EELFManager; -import com.sun.jersey.api.client.Client; -import com.sun.jersey.api.client.ClientResponse; - - -public class RelationshipPutDel { - - private static final String FROMAPPID = "AAI-TOOLS"; - private static final String TRANSID = UUID.randomUUID().toString(); - private static EELFLogger LOGGER; - private static final String USAGE_STRING = "Usage: rshipTool.sh <PUT|DELETE> <resource-path> <filename>\n" + - "resource-path for a particular resource starting after the aai/<version>, relationship-list/relationship gets added by script\n" + - "filename is the path to a file which contains the json input for the relationship payload" + - "for example: relTool.sh PUT cloud-infrastructure/oam-networks/oam-network/test-100-oam /tmp/putrship.json\n"; - - /** - * The main method. - * - * @param args the arguments - */ - public static void main(String[] args) { - - // Set the logging file properties to be used by EELFManager - Properties props = System.getProperties(); - props.setProperty(Configuration.PROPERTY_LOGGING_FILE_NAME, AAIConstants.AAI_RSHIPTOOL_LOGBACK_PROPS); - props.setProperty(Configuration.PROPERTY_LOGGING_FILE_PATH, AAIConstants.AAI_HOME_ETC_APP_PROPERTIES); - LOGGER = EELFManager.getInstance().getLogger(RelationshipPutDel.class); - String dMsg = "Start processing..."; - System.out.println(dMsg); - LOGGER.debug(dMsg); - - String rshipURL, resURL = null; - Relationship rship = null; - - try { - if ((args.length < 3) || (!args[0].equalsIgnoreCase("PUT") && !args[0].equalsIgnoreCase("DELETE"))) { - System.out.println("Insufficient or Invalid arguments"); - System.out.println(USAGE_STRING); - System.exit(1); - } - - rship = readJsonFile(args[2]); - - // Assume the config AAI_SERVER_URL has a last slash so remove if - // resource-path has it as the first char - resURL = args[1].replaceFirst("^/", ""); - resURL = AAIConfig.get(AAIConstants.AAI_SERVER_URL) + resURL; - rshipURL = resURL.concat("/relationship-list/relationship"); - - dMsg = "Resource URL=" + rshipURL; - System.out.println(dMsg); - LOGGER.debug(dMsg); - - PutDelRelationship(rshipURL, rship, args[0]); - - String infMsg = args[0] + " Relationship succeeded to: " + rship.getRelatedTo() + "\n"; - System.out.println(infMsg); - LOGGER.info(infMsg); - - GetResource.getNode(resURL); - infMsg = "Done!!"; - System.out.println(infMsg); - LOGGER.info(infMsg); - - System.exit(0); - - } catch (AAIException e) { - LOGGER.error(args[0] + " Relationship PUT/DELETE failed", e); - System.out.println(args[0] + " Relationship PUT/DELETE failed"); - System.exit(1); - } catch (Exception e) { - LOGGER.error(args[0] + " Relationship PUT/DELETE failed", e); - System.out.println(args[0] + " Relationship PUT/DELETE failed"); - System.exit(1); - } - } - - /** - * Read json file. - * - * @param fName the f name - * @return the relationship - * @throws AAIException the AAI exception - */ - public static Relationship readJsonFile( String fName ) throws AAIException { - String jsonData = ""; - BufferedReader br = null; - Relationship rship = new Relationship(); - - try { - String line; - br = new BufferedReader(new FileReader(fName)); - while ((line = br.readLine()) != null) { - jsonData += line + "\n"; - } - } catch (IOException e) { - throw new AAIException("AAI_7403", e, "Error opening json file"); - } finally { - try { - if (br != null) - br.close(); - } catch (IOException ex) { - throw new AAIException("AAI_7403", ex, "Error closing json file"); - } - } - - try { - rship = MapperUtil.readWithDashesAsObjectOf(Relationship.class, jsonData); - } - catch (Exception je){ - throw new AAIException("AAI_7403", je, "Error parsing json file"); - } - - return rship; - - }//End readJsonFile() - - - /** - * Put del relationship. - * - * @param aaiLogger the aai logger - * @param logline the logline - * @param rshipURL the rship URL - * @param rship the rship - * @param action the action - * @throws AAIException the AAI exception - */ - public static void PutDelRelationship(String rshipURL, - Relationship rship, - String action) throws AAIException{ - try { - Client client = HttpsAuthClient.getClient(); - ClientResponse cres = null; - - if (action.equalsIgnoreCase("PUT")) - cres = client.resource(rshipURL) - .header("X-TransactionId", TRANSID) - .header("X-FromAppId", FROMAPPID) - .accept("application/json") - .entity(rship) - .put(ClientResponse.class); - else - cres = client.resource(rshipURL) - .header("X-TransactionId", TRANSID) - .header("X-FromAppId", FROMAPPID) - .accept("application/json") - .entity(rship) - .delete(ClientResponse.class); - - if (cres.getStatus() == 404) { // resource not found - String infMsg = "Resource does not exist...: " + cres.getStatus() - + ":\n" + cres.getEntity(String.class); - System.out.println(infMsg); - LOGGER.info(infMsg); - throw new AAIException("AAI_7404", "Resource does not exist"); - } else if ((action.equalsIgnoreCase("PUT") && cres.getStatus() == 200) || - (action.equalsIgnoreCase("DELETE") && cres.getStatus() == 204)) { - String infMsg = action + " Resource status: " + cres.getStatus(); - System.out.println(infMsg); - LOGGER.info(infMsg); - } else { - String eMsg = action + " Resource failed: " + cres.getStatus() - + ":\n" + cres.getEntity(String.class); - System.out.println(eMsg); - LOGGER.error(eMsg); - throw new AAIException("AAI_7402", "Error during PutDel"); - } - } catch (AAIException e) { - throw e; - } catch (KeyManagementException e) { - throw new AAIException("AAI_7401", "Error during PutDel"); - } catch (Exception e) { - throw new AAIException("AAI_7402", "Error during PutDel"); - } - } - -} diff --git a/aai-resources/src/main/java/org/openecomp/aai/util/RestController.java b/aai-resources/src/main/java/org/openecomp/aai/util/RestController.java deleted file mode 100644 index e21fd90..0000000 --- a/aai-resources/src/main/java/org/openecomp/aai/util/RestController.java +++ /dev/null @@ -1,685 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * org.openecomp.aai - * ================================================================================ - * 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.aai.util; - -import java.net.MalformedURLException; -import java.net.URI; -import java.net.URISyntaxException; -import java.net.URL; -import java.security.KeyManagementException; -import java.util.ArrayList; -import java.util.List; -import java.util.UUID; - -import org.openecomp.aai.exceptions.AAIException; -import org.openecomp.aai.logging.LoggingContext; -import com.att.eelf.configuration.EELFLogger; -import com.att.eelf.configuration.EELFManager; -import com.fasterxml.jackson.databind.ObjectMapper; -import com.fasterxml.jackson.databind.type.TypeFactory; -import com.sun.jersey.api.client.Client; -import com.sun.jersey.api.client.ClientHandlerException; -import com.sun.jersey.api.client.ClientResponse; - -public class RestController { - - private static EELFLogger LOGGER = EELFManager.getInstance().getLogger(RestController.class); - - private static Client client = null; - - private String restSrvrBaseURL; - - //To do - Come up with helper function that will automatically - //generate the REST API path based on path parameter(s) and query parameter(s)! - public static final String REST_APIPATH_COMPLEXES = "cloud-infrastructure/complexes"; - public static final String REST_APIPATH_COMPLEX = "cloud-infrastructure/complexes/complex/"; - public static final String REST_APIPATH_PSERVERS = "cloud-infrastructure/pservers"; - public static final String REST_APIPATH_PSERVER = "cloud-infrastructure/pservers/pserver/"; - public static final String REST_APIPATH_PHYSICALLINKS = "network/physical-links/"; - public static final String REST_APIPATH_PHYSICALLINK = "network/physical-links/physical-link/"; - public static final String REST_APIPATH_PINTERFACES = "network/p-interfaces/"; - public static final String REST_APIPATH_PINTERFACE = "network/p-interfaces/p-interface/"; - public static final String REST_APIPATH_VPLSPES = "network/vpls-pes/"; - public static final String REST_APIPATH_VPLSPE = "network/vpls-pes/vpls-pe/"; - public static final String REST_APIPATH_UPDATE = "actions/update/"; - public static final String REST_APIPATH_SEARCH = "search/nodes-query?search-node-type="; - - public static final String REST_APIPATH_CLOUDREGION = "cloud-infrastructure/cloud-regions/cloud-region/"; - public static final String REST_APIPATH_TENANT = "cloud-infrastructure/tenants/tenant/"; - public static final String REST_APIPATH_VPE = "network/vpes/vpe/"; - public static final String REST_APIPATH_VIRTUAL_DATA_CENTER = "cloud-infrastructure/virtual-data-centers/virtual-data-center/"; - public static final String REST_APIPATH_VIRTUAL_DATA_CENTERS = "cloud-infrastructure/virtual-data-centers/"; - //network/generic-vnfs/generic-vnf/{vnf-id} - public static final String REST_APIPATH_GENERIC_VNF = "network/generic-vnfs/generic-vnf/"; - public static final String REST_APIPATH_GENERIC_VNFS = "network/generic-vnfs"; - public static final String REST_APIPATH_L3_NETWORK = "network/l3-networks/l3-network/"; - public static final String REST_APIPATH_L3_NETWORKS = "network/l3-networks"; - public static final String REST_APIPATH_INSTANCE_GROUP = "network/instance-groups/instance-group"; - public static final String REST_APIPATH_INSTANCE_GROUPS = "network/instance-groups"; - - public static final String REST_APIPATH_VCE = "network/vces/vce/"; - - public static final String REST_APIPATH_SERVICE = "service-design-and-creation/services/service/"; - public static final String REST_APIPATH_LOGICALLINKS = "network/logical-links/"; - public static final String REST_APIPATH_LOGICALLINK = "network/logical-links/logical-link/"; - - /** - * Inits the rest client. - * - * @throws AAIException the AAI exception - */ - private static void initRestClient() throws AAIException - { - if (client == null) { - try { - String useBasicAuth = AAIConfig.get("aai.tools.enableBasicAuth"); - if (useBasicAuth != null && useBasicAuth.equals("true")) { - - client = HttpsAuthClient.getBasicAuthClient(); - } else { - client = HttpsAuthClient.getTwoWaySSLClient(); - } - - } - catch (KeyManagementException e){ - throw new AAIException("AAI_7117", "KeyManagementException in REST call to DB: " + e.toString()); - } catch (Exception e) { - throw new AAIException("AAI_7117", " Exception in REST call to DB: " + e.toString()); - } - } - } - - /** - * Sets the rest srvr base URL. - * - * @param baseURL the base URL - * @throws AAIException the AAI exception - */ - public void SetRestSrvrBaseURL(String baseURL) throws AAIException - { - if (baseURL == null) - throw new AAIException("AAI_7117", "REST Server base URL cannot be null."); - restSrvrBaseURL = baseURL; - } - - /** - * Gets the rest srvr base URL. - * - * @return the rest srvr base URL - */ - public String getRestSrvrBaseURL() - { - return restSrvrBaseURL; - } - - /** - * To do - optimization and automation. Also make it as generic as possible. - * - * @param <T> the generic type - * @param t the t - * @param sourceID the source ID - * @param transId the trans id - * @param path the path - * @param restObject the rest object - * @param oldserver the oldserver - * @throws AAIException the AAI exception - */ - @SuppressWarnings("unchecked") - public static <T> void Get(T t, String sourceID, String transId, String path, RestObject<T> restObject, boolean oldserver) throws AAIException { - String methodName = "Get"; - String url=""; - transId += ":" + UUID.randomUUID().toString(); - - LoggingContext.save(); - LoggingContext.partnerName(sourceID); - - LOGGER.debug(methodName + " start"); - - restObject.set(t); - - if (oldserver) - url = AAIConfig.get(AAIConstants.AAI_OLDSERVER_URL) + path; - else - url = AAIConfig.get(AAIConstants.AAI_SERVER_URL) + path; - initRestClient(); - LOGGER.debug(url + " for the get REST API"); - ClientResponse cres = client.resource(url) - .accept("application/json") - .header("X-TransactionId", transId) - .header("X-FromAppId", sourceID) - .header("Authorization", HttpsAuthClient.getBasicAuthHeaderValue()) - .type("application/json") - .get(ClientResponse.class); - -// System.out.println("cres.EntityInputSream()="+cres.getEntityInputStream().toString()); -// System.out.println("cres.tostring()="+cres.toString()); - - if (cres.getStatus() == 200) { -// System.out.println(methodName + ": url=" + url); - t = (T) cres.getEntity(t.getClass()); - restObject.set(t); - LOGGER.debug(methodName + "REST api GET was successfull!"); - } else { - LoggingContext.restore(); -// System.out.println(methodName + ": url=" + url + " failed with status=" + cres.getStatus()); - throw new AAIException("AAI_7116", methodName +" with status="+cres.getStatus()+", url="+url); - } - - LoggingContext.restore(); - } - - - /** - * - * @param <T> the generic type - * @param t the t - * @param sourceID the source ID - * @param transId the trans id - * @param path the path - * @param restObject the rest object - * @param apiVersion the api version - * @throws AAIException the AAI exception - */ - @SuppressWarnings("unchecked") - public static <T> void Get(T t, String sourceID, String transId, String path, RestObject<T> restObject, String apiVersion) throws AAIException { - String methodName = "Get"; - String url=""; - transId += ":" + UUID.randomUUID().toString(); - LOGGER.debug(methodName + " start"); - - restObject.set(t); - - url = AAIConfig.get(AAIConstants.AAI_SERVER_URL_BASE) + apiVersion + "/"+ path; - - initRestClient(); - LOGGER.debug(url + " for the get REST API"); - ClientResponse cres = client.resource(url) - .accept("application/json") - .header("X-TransactionId", transId) - .header("X-FromAppId", sourceID) - .header("Authorization", HttpsAuthClient.getBasicAuthHeaderValue()) - .type("application/json") - .get(ClientResponse.class); - -// System.out.println("cres.EntityInputSream()="+cres.getEntityInputStream().toString()); -// System.out.println("cres.tostring()="+cres.toString()); - - if (cres.getStatus() == 200) { -// System.out.println(methodName + ": url=" + url); - t = (T) cres.getEntity(t.getClass()); - restObject.set(t); - LOGGER.debug(methodName + "REST api GET was successfull!"); - - } else { -// System.out.println(methodName + ": url=" + url + " failed with status=" + cres.getStatus()); - throw new AAIException("AAI_7116", methodName +" with status="+cres.getStatus()+", url="+url); - } - - } - - /** - * Gets the. - * - * @param <T> the generic type - * @param t the t - * @param requestObj the request obj - * @throws AAIException the AAI exception - */ - public static <T> void Get(T t, Request<T> requestObj) throws AAIException { - String methodName = "Get"; - String url=""; - String transId = requestObj.transactionId; - transId += ":" + UUID.randomUUID().toString(); - LOGGER.debug(methodName + " start"); - - requestObj.restObj.set(t); - - if (requestObj.oldServer) - url = AAIConfig.get(AAIConstants.AAI_SERVER_URL_BASE) + "server/" + requestObj.path; - else - url = AAIConfig.get(AAIConstants.AAI_SERVER_URL_BASE) + requestObj.path; - initRestClient(); - - try { - URL urlObj= new URL(url); - URI uri = new URI(urlObj.getProtocol(), urlObj.getUserInfo(), urlObj.getHost(), urlObj.getPort(), urlObj.getPath(), urlObj.getQuery(), urlObj.getRef()); - url = uri.toASCIIString(); - } catch (URISyntaxException | MalformedURLException e) { - throw new AAIException("AAI_7116", "bad URL"); - - } - LOGGER.debug(url + " for the get REST API"); - ClientResponse cres = client.resource(url) - .accept("application/json") - .header("X-TransactionId", transId) - .header("X-FromAppId", requestObj.fromAppId) - .header("Authorization", HttpsAuthClient.getBasicAuthHeaderValue()) - .type("application/json") - .get(ClientResponse.class); - -// System.out.println("cres.EntityInputSream()="+cres.getEntityInputStream().toString()); -// System.out.println("cres.tostring()="+cres.toString()); - - if (cres.getStatus() == 200) { -// System.out.println(methodName + ": url=" + url); - t = (T) cres.getEntity(t.getClass()); - requestObj.restObj.set(t); - LOGGER.debug(methodName + "REST api GET was successfull!"); - - } else { -// System.out.println(methodName + ": url=" + url + " failed with status=" + cres.getStatus()); - throw new AAIException("AAI_7116", methodName +" with status="+cres.getStatus()+", url="+url); - } - - } - - /** - * Put. - * - * @param <T> the generic type - * @param t the t - * @param requestObj the request obj - * @throws AAIException the AAI exception - */ - public static <T> void Put(T t, Request<T> requestObj) throws AAIException { - String methodName = "Put"; - String url=""; - String transId = requestObj.transactionId; - transId += ":" + UUID.randomUUID().toString(); - LOGGER.debug(methodName + " start"); - - initRestClient(); - - if (requestObj.oldServer) - url = AAIConfig.get(AAIConstants.AAI_SERVER_URL_BASE) + "server/" + requestObj.path; - else - url = AAIConfig.get(AAIConstants.AAI_SERVER_URL_BASE) + requestObj.path; - - try { - URL urlObj= new URL(url); - URI uri = new URI(urlObj.getProtocol(), urlObj.getUserInfo(), urlObj.getHost(), urlObj.getPort(), urlObj.getPath(), urlObj.getQuery(), urlObj.getRef()); - url = uri.toASCIIString(); - } catch (URISyntaxException | MalformedURLException e) { - throw new AAIException("AAI_7116", "bad URL"); - - } - ClientResponse cres = client.resource(url) - .accept("application/json") - .header("X-TransactionId", transId) - .header("X-FromAppId", requestObj.fromAppId) - .header("Authorization", HttpsAuthClient.getBasicAuthHeaderValue()) - .type("application/json") - .entity(t) - .put(ClientResponse.class); - - int statuscode = cres.getStatus(); - if ( statuscode >= 200 && statuscode <= 299 ) { - LOGGER.debug(methodName+": url=" + url + ", request=" + url); - } else { - throw new AAIException("AAI_7116", methodName +" with status="+statuscode+", url="+url); - } - } - - /** - * Multiple Generic Get. - * - * @param <T> the generic type - * @param t the t - * @param sourceID the source ID - * @param transId the trans id - * @param path the path - * @param oldserver the oldserver - * @return the list - * @throws AAIException the AAI exception - */ - public static <T> List<T> Get(T t, String sourceID, String transId, String path, boolean oldserver) throws AAIException { - String methodName = "Get"; - String url=""; - transId += ":" + UUID.randomUUID().toString(); - LOGGER.debug(methodName + " start"); - - List<T> list; - - try { - if (oldserver) - url = AAIConfig.get(AAIConstants.AAI_OLDSERVER_URL) + path; - else - url = AAIConfig.get(AAIConstants.AAI_SERVER_URL) + path; - initRestClient(); - LOGGER.debug(url + " for the get REST API"); - ClientResponse cres = client.resource(url) - .accept("application/json") - .header("X-TransactionId", transId) - .header("X-FromAppId", sourceID) - .header("Authorization", HttpsAuthClient.getBasicAuthHeaderValue()) - .type("application/json") - .get(ClientResponse.class); - - - //System.out.println("cres.EntityInputSream()="+cres.getEntityInputStream().toString()); - //System.out.println("cres.tostring()="+cres.toString()); - - if (cres.getStatus() == 200) { - //System.out.println(methodName + ": url=" + url); - //list = cres.getEntity(new GenericType<List<T>>() { }); - String datainJson = cres.getEntity(String.class); - list = mapJsonToObjectList(t, datainJson, t.getClass()); - - LOGGER.debug(methodName + "REST api GET was successfull!"); - return list; - - } else { - throw new AAIException("AAI_7116", methodName +" with status="+cres.getStatus()+", url="+url); - } - } catch (AAIException e) { - throw new AAIException("AAI_7116", methodName + " with url="+url+ ", Exception: " + e.toString()); - } catch (Exception e) - { - throw new AAIException("AAI_7116", methodName + " with url="+url+ ", Exception: " + e.toString()); - - } - - } - - /** - * Map json to object list. - * - * @param <T> the generic type - * @param typeDef the type def - * @param json the json - * @param clazz the clazz - * @return the list - * @throws Exception the exception - */ - private static <T> List<T> mapJsonToObjectList(T typeDef,String json, Class clazz) throws Exception - { - List<T> list; - ObjectMapper mapper = new ObjectMapper(); - System.out.println(json); - TypeFactory t = TypeFactory.defaultInstance(); - list = mapper.readValue(json, t.constructCollectionType(ArrayList.class,clazz)); - - return list; - } - - /** - * Put. - * - * @param <T> the generic type - * @param t the t - * @param sourceID the source ID - * @param transId the trans id - * @param path the path - * @throws AAIException the AAI exception - */ - public static <T> void Put(T t, String sourceID, String transId, String path) throws AAIException { - Put( t, sourceID, transId, path, false); - } - - /** - * Put. - * - * @param <T> the generic type - * @param t the t - * @param sourceID the source ID - * @param transId the trans id - * @param path the path - * @param oldserver the oldserver - * @throws AAIException the AAI exception - */ - public static <T> void Put(T t, String sourceID, String transId, String path, boolean oldserver) throws AAIException { - String methodName = "Put"; - String url=""; - transId += ":" + UUID.randomUUID().toString(); - - LOGGER.debug(methodName + " start"); - - initRestClient(); - - if (oldserver) - url = AAIConfig.get(AAIConstants.AAI_OLDSERVER_URL) + path; - else - url = AAIConfig.get(AAIConstants.AAI_SERVER_URL) + path; - - ClientResponse cres = client.resource(url) - .accept("application/json") - .header("X-TransactionId", transId) - .header("X-FromAppId", sourceID) - .header("Authorization", HttpsAuthClient.getBasicAuthHeaderValue()) - .type("application/json") - .entity(t) - .put(ClientResponse.class); - -// System.out.println("cres.tostring()="+cres.toString()); - - int statuscode = cres.getStatus(); - if ( statuscode >= 200 && statuscode <= 299 ) { - LOGGER.debug(methodName+": url=" + url + ", request=" + path); - } else { - throw new AAIException("AAI_7116", methodName +" with status="+statuscode+", url="+url + ", msg=" + cres.getEntity(String.class)); - } - } - - /** - * Delete. - * - * @param requestObj the request obj - * @throws AAIException the AAI exception - */ - public static void Delete(Request requestObj) throws AAIException { - String methodName = "Delete"; - - String url=""; - String transId = requestObj.transactionId; - transId += ":" + UUID.randomUUID().toString(); - - LOGGER.debug(methodName + " start"); - - initRestClient(); - - if (requestObj.oldServer) - url = AAIConfig.get(AAIConstants.AAI_SERVER_URL_BASE) + "servers/" + requestObj.path; - else - url = AAIConfig.get(AAIConstants.AAI_SERVER_URL_BASE) + requestObj.path; - - try { - URL urlObj= new URL(url); - URI uri = new URI(urlObj.getProtocol(), urlObj.getUserInfo(), urlObj.getHost(), urlObj.getPort(), urlObj.getPath(), urlObj.getQuery(), urlObj.getRef()); - url = uri.toASCIIString(); - } catch (URISyntaxException | MalformedURLException e) { - throw new AAIException("AAI_7116", "bad URL"); - - } - - ClientResponse cres = client.resource(url) - .accept("application/json") - .header("X-TransactionId", transId) - .header("X-FromAppId", requestObj.fromAppId) - .header("Authorization", HttpsAuthClient.getBasicAuthHeaderValue()) - .type("application/json") - .entity("{}") - .delete(ClientResponse.class); - - if (cres.getStatus() == 204) { - LOGGER.debug(methodName+": url=" + url); - } else { - throw new AAIException("AAI_7116", methodName +" with status="+cres.getStatus()+", url="+url); - } - - } - - /** - * Delete. - * - * @param sourceID the source ID - * @param transId the trans id - * @param path the path - * @throws AAIException the AAI exception - */ - public static void Delete(String sourceID, String transId, String path) throws AAIException { - String methodName = "Delete"; - String url=""; - transId += ":" + UUID.randomUUID().toString(); - LOGGER.debug(methodName + " start"); - - initRestClient(); - String request = "{}"; - url = AAIConfig.get(AAIConstants.AAI_SERVER_URL) + path; - ClientResponse cres = client.resource(url) - .accept("application/json") - .header("X-TransactionId", transId) - .header("X-FromAppId", sourceID) - .header("Authorization", HttpsAuthClient.getBasicAuthHeaderValue()) - .type("application/json") - .entity(request) - .delete(ClientResponse.class); - - if (cres.getStatus() == 404) { // resource not found - LOGGER.info("Resource does not exist...: " + cres.getStatus() - + ":" + cres.getEntity(String.class)); - } else if (cres.getStatus() == 200 || cres.getStatus() == 204){ - LOGGER.info("Resource " + url + " deleted"); - } else { - LOGGER.error("Deleting Resource failed: " + cres.getStatus() - + ":" + cres.getEntity(String.class)); - throw new AAIException("AAI_7116", "Error during DELETE"); - } - } - - /** - * Post. - * - * @param <T> the generic type - * @param t the t - * @param sourceID the source ID - * @param transId the trans id - * @param path the path - * @return the string - * @throws Exception the exception - */ - public static <T> String Post(T t, String sourceID, String transId, String path) throws Exception { - String methodName = "Post"; - String url=""; - transId += ":" + UUID.randomUUID().toString(); - - LOGGER.debug(methodName + " start"); - - try { - - initRestClient(); - - url = AAIConfig.get(AAIConstants.AAI_SERVER_URL) + path; - - ClientResponse cres = client.resource(url) - .accept("application/json") - .header("X-TransactionId", transId) - .header("X-FromAppId", sourceID) - .header("Authorization", HttpsAuthClient.getBasicAuthHeaderValue()) - .type("application/json") - .entity(t) - .post(ClientResponse.class); - - int statuscode = cres.getStatus(); - if ( statuscode >= 200 && statuscode <= 299 ) { - LOGGER.debug(methodName + "REST api POST was successful!"); - return cres.getEntity(String.class); - } else { - throw new AAIException("AAI_7116", methodName +" with status="+statuscode+", url="+url + ", msg=" + cres.getEntity(String.class)); - } - - } catch (AAIException e) { - throw new AAIException("AAI_7116", methodName + " with url="+url+ ", Exception: " + e.toString()); - } catch (Exception e) - { - throw new AAIException("AAI_7116", methodName + " with url="+url+ ", Exception: " + e.toString()); - - } - } - - - /** - * Gets the single instance of RestController. - * - * @param <T> the generic type - * @param clazz the clazz - * @return single instance of RestController - * @throws IllegalAccessException the illegal access exception - * @throws InstantiationException the instantiation exception - */ - public static <T> T getInstance(Class<T> clazz) throws IllegalAccessException, InstantiationException - { - return clazz.newInstance(); - } - - /** - * Does resource exist. - * - * @param <T> the generic type - * @param resourcePath the resource path - * @param resourceClassName the resource class name - * @param fromAppId the from app id - * @param transId the trans id - * @return the t - */ - /* - * DoesResourceExist - * - * To check whether a resource exist or get a copy of the existing version of the resource - * - * Resourcepath: should contain the qualified resource path (including encoded unique key identifier value), - * resourceClassName: is the canonical name of the resource class name, - * fromAppId: - * transId: - * - * Will return null (if the resource doesn’t exist) (or) - * Will return the specified resource from the Graph. - * - * Example: - * LogicalLink llink = new LogicalLink(); - * String resourceClassName = llink.getClass().getCanonicalName(); - * llink = RestController.DoesResourceExist("network/logical-links/logical-link/" + <encoded-link-name>, resourceClassName, fromAppId, transId); - */ - public static <T> T DoesResourceExist(String resourcePath, String resourceClassName, String fromAppId, String transId) { - - try { - - RestObject<T> restObj = new RestObject<T>(); - @SuppressWarnings("unchecked") - T resourceObj = (T)getInstance(Class.forName(resourceClassName)); - restObj.set(resourceObj); - RestController.<T>Get(resourceObj, fromAppId, transId, resourcePath, restObj, false); - - resourceObj = restObj.get(); - if (resourceObj != null) - return resourceObj; - - } catch (AAIException e) { - - } catch (ClientHandlerException che) { - - }catch (Exception e) { - - } - - return null; - } - -} diff --git a/aai-resources/src/main/java/org/openecomp/aai/util/UpdateResource.java b/aai-resources/src/main/java/org/openecomp/aai/util/UpdateResource.java deleted file mode 100644 index 1597a7b..0000000 --- a/aai-resources/src/main/java/org/openecomp/aai/util/UpdateResource.java +++ /dev/null @@ -1,134 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * org.openecomp.aai - * ================================================================================ - * 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.aai.util; - -import java.util.Properties; -import java.util.UUID; - -import org.openecomp.aai.domain.yang.Action; -import org.openecomp.aai.domain.yang.ActionData; -import org.openecomp.aai.domain.yang.Update; -import org.openecomp.aai.exceptions.AAIException; -import org.openecomp.aai.logging.ErrorLogHelper; -import com.att.eelf.configuration.Configuration; -import com.att.eelf.configuration.EELFLogger; -import com.att.eelf.configuration.EELFManager; - - -public class UpdateResource { - - private static EELFLogger LOGGER; - private static final String FROMAPPID = "AAIUPDT"; - private static final String TRANSID = UUID.randomUUID().toString(); - private static final String UPDATE_URL = "actions/update"; - private static final String USAGE_STRING = "Usage: updateTool.sh \n" + - "<node type> <update node URI> <property name>:<property value>[,<property name>:<property value]* | \n" + - "where update node uri is the URI path for that node \n" + - " for ex. ./updateTool.sh pserver cloud-infrastructure/pservers/pserver/XXX prov-status:NEWSTATUS"; - - /** - * The main method. - * - * @param args the arguments - */ - public static void main(String[] args) { - - String nodeType = null; - String nodeURI = null; - String updValueList = null; - - // Set the logging file properties to be used by EELFManager - Properties props = System.getProperties(); - props.setProperty(Configuration.PROPERTY_LOGGING_FILE_NAME, AAIConstants.AAI_UPDTOOL_LOGBACK_PROPS); - props.setProperty(Configuration.PROPERTY_LOGGING_FILE_PATH, AAIConstants.AAI_HOME_ETC_APP_PROPERTIES); - LOGGER = EELFManager.getInstance().getLogger(UpdateResource.class.getName()); - try { - if (args.length < 3) { - System.out.println("Nothing to update or Insufficient arguments"); - System.out.println(USAGE_STRING); - System.exit(1); - } else { - nodeType = args[0]; - nodeURI = args[1]; - updValueList = args[2]; - - update(nodeType, nodeURI, updValueList); - } - - System.exit(0); - - } catch (AAIException e) { - System.out.println("Error - Update Failed."); - ErrorLogHelper.logException(e); - System.exit(1); - } catch (Exception e) { - System.out.println("Error - Update Failed." + e.getMessage()); - ErrorLogHelper.logError("AAI_7402", "Update failed: " + e.getMessage()); - System.exit(1); - } - } - - /** - * Update. - * - * @param <T> the generic type - * @param aaiLogger the aai logger - * @param logline the logline - * @param nodeType the node type - * @param nodeURI the node URI - * @param updValueList the upd value list - * @throws AAIException the AAI exception - */ - public static <T> void update(String nodeType, String nodeURI, String updValueList) throws AAIException { - try { - Update update = new Update(); - update.setUpdateNodeType(nodeType); - update.setUpdateNodeUri(nodeURI); - - Action action = new Action(); - action.setActionType("replace"); - - for (String updValue: updValueList.split(",")) { - ActionData data = new ActionData(); - data.setPropertyName(updValue.substring(0, updValue.indexOf(':'))); - data.setPropertyValue(updValue.substring(updValue.indexOf(':') + 1)); - action.getActionData().add(data); - } - - update.getAction().add(action); - - String infMsg = "updating the resource... "; - System.out.println(infMsg); - LOGGER.info(infMsg); - - RestController.<Update>Put(update, FROMAPPID, TRANSID, UPDATE_URL); - - infMsg = "Update Successful"; - System.out.println(infMsg); - LOGGER.info(infMsg); - - } catch (AAIException e) { - throw e; - } catch (Exception e) { - throw new AAIException("AAI_7402", e, "Error during UPDATE"); - } - } -} |