2 * ============LICENSE_START=======================================================
4 * ================================================================================
5 * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
6 * ================================================================================
7 * Licensed under the Apache License, Version 2.0 (the "License");
8 * you may not use this file except in compliance with the License.
9 * You may obtain a copy of the License at
11 * http://www.apache.org/licenses/LICENSE-2.0
13 * Unless required by applicable law or agreed to in writing, software
14 * distributed under the License is distributed on an "AS IS" BASIS,
15 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16 * See the License for the specific language governing permissions and
17 * limitations under the License.
18 * ============LICENSE_END=========================================================
21 package org.onap.so.client.aai;
23 import java.io.IOException;
24 import java.util.ArrayList;
25 import java.util.HashMap;
26 import java.util.List;
28 import java.util.Map.Entry;
29 import java.util.Optional;
31 import javax.ws.rs.NotFoundException;
32 import javax.ws.rs.core.GenericType;
33 import javax.ws.rs.core.Response;
35 import org.onap.aai.domain.yang.Relationship;
36 import org.onap.so.client.RestClient;
37 import org.onap.so.client.aai.entities.AAIError;
38 import org.onap.so.client.aai.entities.bulkprocess.OperationBody;
39 import org.onap.so.client.aai.entities.bulkprocess.Transaction;
40 import org.onap.so.client.aai.entities.bulkprocess.Transactions;
41 import org.onap.so.client.aai.entities.uri.AAIResourceUri;
42 import org.onap.so.client.aai.entities.uri.AAIUri;
43 import org.onap.so.client.aai.entities.uri.AAIUriFactory;
44 import org.onap.so.client.graphinventory.exceptions.BulkProcessFailed;
45 import org.onap.so.jsonpath.JsonPathUtil;
47 import com.fasterxml.jackson.core.type.TypeReference;
48 import com.fasterxml.jackson.databind.ObjectMapper;
49 import com.google.common.base.Joiner;
51 public class AAITransactionalClient extends AAIClient {
53 private final Transactions transactions;
54 private Transaction currentTransaction;
55 private final AAIVersion version;
56 private int actionCount = 0;
57 protected AAITransactionalClient(AAIVersion version) {
59 this.version = version;
60 this.transactions = new Transactions();
64 private void startTransaction() {
65 Transaction transaction = new Transaction();
66 transactions.getTransactions().add(transaction);
67 currentTransaction = transaction;
71 * adds an additional transaction and closes the previous transaction
73 * @return AAITransactionalClient
75 public AAITransactionalClient beginNewTransaction() {
81 * creates a new object in A&AI
83 * @param obj - can be any object which will marshal into a valid A&AI payload
87 public AAITransactionalClient create(AAIResourceUri uri, Object obj) {
88 currentTransaction.getPut().add(new OperationBody().withUri(uri.build().toString()).withBody(obj));
89 incrementActionAmount();
94 * creates a new object in A&AI with no payload body
99 public AAITransactionalClient createEmpty(AAIResourceUri uri) {
100 currentTransaction.getPut().add(new OperationBody().withUri(uri.build().toString()).withBody(new HashMap<String, String>()));
101 incrementActionAmount();
106 * Adds a relationship between two objects in A&AI
111 public AAITransactionalClient connect(AAIResourceUri uriA, AAIResourceUri uriB) {
112 AAIResourceUri uriAClone = uriA.clone();
113 currentTransaction.getPut().add(new OperationBody().withUri(uriAClone.relationshipAPI().build().toString()).withBody(this.buildRelationship(uriB)));
114 incrementActionAmount();
119 * relationship between multiple objects in A&AI - connects A to all objects specified in list
125 public AAITransactionalClient connect(AAIResourceUri uriA, List<AAIResourceUri> uris) {
126 for (AAIResourceUri uri : uris) {
127 this.connect(uriA, uri);
133 * Removes relationship from two objects in A&AI
139 public AAITransactionalClient disconnect(AAIResourceUri uriA, AAIResourceUri uriB) {
140 AAIResourceUri uriAClone = uriA.clone();
141 currentTransaction.getDelete().add(new OperationBody().withUri(uriAClone.relationshipAPI().build().toString()).withBody(this.buildRelationship(uriB)));
142 incrementActionAmount();
147 * Removes relationship from multiple objects - disconnects A from all objects specified in list
152 public AAITransactionalClient disconnect(AAIResourceUri uriA, List<AAIResourceUri> uris) {
153 for (AAIResourceUri uri : uris) {
154 this.disconnect(uriA, uri);
159 * Deletes object from A&AI. Automatically handles resource-version.
164 public AAITransactionalClient delete(AAIResourceUri uri) {
165 AAIResourcesClient client = new AAIResourcesClient();
166 AAIResourceUri clone = uri.clone();
167 Map<String, Object> result = client.get(new GenericType<Map<String, Object>>(){}, clone)
168 .orElseThrow(() -> new NotFoundException(clone.build() + " does not exist in A&AI"));
169 String resourceVersion = (String) result.get("resource-version");
170 currentTransaction.getDelete().add(new OperationBody().withUri(clone.resourceVersion(resourceVersion).build().toString()).withBody(""));
171 incrementActionAmount();
176 * @param obj - can be any object which will marshal into a valid A&AI payload
180 public AAITransactionalClient update(AAIResourceUri uri, Object obj) {
181 currentTransaction.getPatch().add(new OperationBody().withUri(uri.build().toString()).withBody(obj));
182 incrementActionAmount();
186 private void incrementActionAmount() {
190 * Executes all created transactions in A&AI
191 * @throws BulkProcessFailed
193 public void execute() throws BulkProcessFailed {
194 RestClient client = this.createClient(AAIUriFactory.createResourceUri(AAIObjectType.BULK_PROCESS));
196 Response response = client.put(this.transactions);
197 if (response.hasEntity()) {
198 final Optional<String> errorMessage = this.locateErrorMessages(response.readEntity(String.class));
199 if (errorMessage.isPresent()) {
200 throw new BulkProcessFailed("One or more transactions failed in A&AI. Check logs for payloads.\nMessages:\n" + errorMessage.get());
203 throw new BulkProcessFailed("Transactions acccepted by A&AI, but there was no response. Unsure of result.");
206 this.transactions.getTransactions().clear();
207 this.currentTransaction = null;
208 this.actionCount = 0;
212 protected Optional<String> locateErrorMessages(String response) {
213 final List<String> errorMessages = new ArrayList<>();
214 final List<String> results = JsonPathUtil.getInstance().locateResultList(response, "$..body");
215 final ObjectMapper mapper = new ObjectMapper();
216 if (!results.isEmpty()) {
217 List<Map<String, Object>> parsed = new ArrayList<>();
219 for (String result : results) {
220 parsed.add(mapper.readValue(result, new TypeReference<Map<String, Object>>(){}));
222 } catch (IOException e) {
223 logger.error("could not map json", e);
225 for (Map<String, Object> map : parsed) {
226 for (Entry<String, Object> entry : map.entrySet()) {
227 if (!entry.getKey().matches("2\\d\\d")) {
230 error = mapper.readValue(entry.getValue().toString(), AAIError.class);
231 } catch (IOException e) {
232 logger.error("could not parse error object from A&AI", e);
233 error = new AAIError();
235 AAIErrorFormatter formatter = new AAIErrorFormatter(error);
236 String outputMessage = formatter.getMessage();
237 logger.error("part of a bulk action failed in A&AI: " + entry.getValue());
238 errorMessages.add(outputMessage);
244 if (!errorMessages.isEmpty()) {
245 return Optional.of(Joiner.on("\n").join(errorMessages));
247 return Optional.empty();
250 private Relationship buildRelationship(AAIUri uri) {
251 final Relationship result = new Relationship();
252 result.setRelatedLink(uri.build().toString());
257 protected AAIVersion getVersion() {
261 protected Transactions getTransactions() {
262 return this.transactions;