8df505e979c26d807d4a1f166713c5238c949ee4
[so.git] /
1 /*-
2  * ============LICENSE_START=======================================================
3  * ONAP - SO
4  * ================================================================================
5  * Copyright (C) 2017 - 2018 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
10  * 
11  *      http://www.apache.org/licenses/LICENSE-2.0
12  * 
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=========================================================
19  */
20
21 package org.onap.aaiclient.client.aai;
22
23 import java.io.IOException;
24 import java.util.ArrayList;
25 import java.util.List;
26 import java.util.Optional;
27 import javax.ws.rs.core.GenericType;
28 import org.onap.so.client.RestClient;
29 import org.onap.aaiclient.client.aai.entities.AAIEdgeLabel;
30 import org.onap.aaiclient.client.aai.entities.AAIError;
31 import org.onap.aaiclient.client.aai.entities.singletransaction.OperationBodyRequest;
32 import org.onap.aaiclient.client.aai.entities.singletransaction.OperationBodyResponse;
33 import org.onap.aaiclient.client.aai.entities.singletransaction.SingleTransactionRequest;
34 import org.onap.aaiclient.client.aai.entities.singletransaction.SingleTransactionResponse;
35 import org.onap.aaiclient.client.aai.entities.uri.AAIBaseResourceUri;
36 import org.onap.aaiclient.client.aai.entities.uri.AAIResourceUri;
37 import org.onap.aaiclient.client.aai.entities.uri.AAIUriFactory;
38 import org.onap.aaiclient.client.graphinventory.GraphInventoryPatchConverter;
39 import org.onap.aaiclient.client.graphinventory.GraphInventoryTransactionClient;
40 import org.onap.aaiclient.client.graphinventory.exceptions.BulkProcessFailed;
41 import com.fasterxml.jackson.core.JsonProcessingException;
42 import com.fasterxml.jackson.databind.ObjectMapper;
43 import com.google.common.base.Joiner;
44
45 public class AAISingleTransactionClient extends
46         GraphInventoryTransactionClient<AAISingleTransactionClient, AAIBaseResourceUri<?, ?>, AAIResourceUri, AAIEdgeLabel> {
47
48     private final SingleTransactionRequest request;
49     private AAIResourcesClient resourcesClient;
50     private AAIClient aaiClient;
51
52     protected AAISingleTransactionClient(AAIResourcesClient resourcesClient, AAIClient aaiClient) {
53         super();
54         this.resourcesClient = resourcesClient;
55         this.aaiClient = aaiClient;
56         this.request = new SingleTransactionRequest();
57     }
58
59     /*
60      * (non-Javadoc)
61      * 
62      * @see org.onap.aaiclient.client.aai.GraphInventoryTransactionClient#execute()
63      */
64     @Override
65     public void execute() throws BulkProcessFailed {
66         try {
67             if (!this.request.getOperations().isEmpty()) {
68                 RestClient client =
69                         aaiClient.createClient(AAIUriFactory.createResourceUri(AAIObjectType.SINGLE_TRANSACTION));
70                 SingleTransactionResponse response = client.post(this.request, SingleTransactionResponse.class);
71                 if (response != null) {
72                     final Optional<String> errorMessage = this.locateErrorMessages(response);
73                     if (errorMessage.isPresent()) {
74                         throw new BulkProcessFailed(
75                                 "One or more transactions failed in A&AI. Check logs for payloads.\nMessages:\n"
76                                         + errorMessage.get());
77                     }
78                 } else {
79                     throw new BulkProcessFailed(
80                             "Transactions acccepted by A&AI, but there was no response. Unsure of result.");
81                 }
82             }
83         } finally {
84             this.request.getOperations().clear();
85             this.actionCount = 0;
86         }
87     }
88
89     @Override
90     public void execute(boolean dryRun) throws BulkProcessFailed {
91         final ObjectMapper mapper = new ObjectMapper();
92         if (dryRun) {
93             try {
94                 if (logger.isDebugEnabled()) {
95                     logger.debug("Would execute: {}", mapper.writeValueAsString(this.request));
96                 }
97             } catch (JsonProcessingException e) {
98                 logger.debug("Could not format request to JSON", e);
99             }
100         } else {
101             this.execute();
102         }
103     }
104
105     protected Optional<String> locateErrorMessages(SingleTransactionResponse response) {
106         final List<String> errorMessages = new ArrayList<>();
107         final ObjectMapper mapper = new ObjectMapper();
108
109         for (OperationBodyResponse body : response.getOperationResponses()) {
110             if (Optional.ofNullable(body.getResponseStatusCode()).orElse(400) > 300) {
111                 AAIError error;
112                 try {
113                     error = mapper.readValue(mapper.writeValueAsString(body.getResponseBody()), AAIError.class);
114                 } catch (IOException e) {
115                     logger.error("could not parse error object from A&AI", e);
116                     error = new AAIError();
117                 }
118                 AAIErrorFormatter formatter = new AAIErrorFormatter(error);
119                 String outputMessage = formatter.getMessage();
120                 errorMessages.add(outputMessage);
121             }
122         }
123
124         if (!errorMessages.isEmpty()) {
125             return Optional.of(Joiner.on("\n").join(errorMessages));
126         } else {
127             return Optional.empty();
128         }
129     }
130
131     protected SingleTransactionRequest getRequest() {
132         return this.request;
133     }
134
135     @Override
136     protected void put(String uri, Object body) {
137         request.getOperations().add(new OperationBodyRequest().withAction("put").withUri(uri).withBody(body));
138     }
139
140     @Override
141     protected void delete(String uri) {
142         request.getOperations()
143                 .add(new OperationBodyRequest().withAction("delete").withUri(uri).withBody(new Object()));
144     }
145
146     @Override
147     protected void delete(String uri, Object obj) {
148         request.getOperations().add(new OperationBodyRequest().withAction("delete").withUri(uri).withBody(obj));
149     }
150
151     @Override
152     protected void patch(String uri, Object body) {
153         request.getOperations().add(new OperationBodyRequest().withAction("patch").withUri(uri).withBody(body));
154     }
155
156     @Override
157     protected <T> Optional<T> get(GenericType<T> genericType, AAIBaseResourceUri<?, ?> clone) {
158         return resourcesClient.get(genericType, clone);
159     }
160
161     @Override
162     protected boolean exists(AAIBaseResourceUri<?, ?> uri) {
163         return resourcesClient.exists(uri);
164     }
165
166     @Override
167     protected String getGraphDBName() {
168         return aaiClient.getGraphDBName();
169     }
170
171     @Override
172     protected GraphInventoryPatchConverter getPatchConverter() {
173         return this.patchConverter;
174     }
175 }