summaryrefslogtreecommitdiffstats
path: root/src/main/java/org/onap/aai/sparky/editattributes/AttributeUpdater.java
blob: 79b54660723d6db6a1040406e4b86ff8275677be (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
/**
 * ============LICENSE_START=======================================================
 * org.onap.aai
 * ================================================================================
 * Copyright © 2017-2018 AT&T Intellectual Property. All rights reserved.
 * Copyright © 2017-2018 Amdocs
 * ================================================================================
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *       http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * ============LICENSE_END=========================================================
 */
package org.onap.aai.sparky.editattributes;

import java.net.URI;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.ws.rs.core.UriBuilder;

import org.eclipse.persistence.dynamic.DynamicType;
import org.onap.aai.cl.api.Logger;
import org.onap.aai.cl.eelf.LoggerFactory;
import org.onap.aai.restclient.client.OperationResult;
import org.onap.aai.sparky.config.oxm.OxmEntityLookup;
import org.onap.aai.sparky.config.oxm.OxmModelLoader;
import org.onap.aai.sparky.dal.ActiveInventoryAdapter;
import org.onap.aai.sparky.editattributes.exception.AttributeUpdateException;
import org.onap.aai.sparky.logging.AaiUiMsgs;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.ObjectWriter;
import com.fasterxml.jackson.databind.PropertyNamingStrategy;

/**
 * Class to process attribute updates on AAI objects.
 *
 *
 */
public class AttributeUpdater {
  
  /**
   * The Class AaiEditObject.
   */
  public class AaiEditObject {
    String objectType;
    String rootElement;
    String keyName;
    String keyValue;
    String schemaVersion;

    /**
     * Instantiates a new aai edit object.
     */
    public AaiEditObject() {

    }

    /**
     * Instantiates a new aai edit object.
     *
     * @param objectType the object type
     * @param idName the id name
     * @param schemaVersion the schema version
     */
    public AaiEditObject(String objectType, String idName, String schemaVersion) {
      super();
      this.objectType = objectType;
      this.keyName = idName;
      this.schemaVersion = schemaVersion;
    }

    public String getObjectType() {
      return objectType;
    }

    public void setObjectType(String objectType) {
      this.objectType = objectType;
    }

    public String getKeyName() {
      return keyName;
    }

    public void setKeyName(String idName) {
      this.keyName = idName;
    }

    public String getSchemaVersion() {
      return schemaVersion;
    }

    public void setSchemaVersion(String schemaVersion) {
      this.schemaVersion = schemaVersion;
    }

    public void setKeyValue(String keyValue) {
      this.keyValue = keyValue;
    }

    public String getKeyValue() {
      return keyValue;
    }

    public String getRootElement() {
      return rootElement;
    }

    public void setRootElement(String rootElement) {
      this.rootElement = rootElement;
    }

  }

  private static final Logger LOG = LoggerFactory.getInstance().getLogger(AttributeUpdater.class);
  private static final String MESSAGE_VERSION_EXTRACTION_REGEX = "\\/(v[0-9]+)";
  private static final String ATTRIBUTES_UPDATED_SUCCESSFULLY = "Attributes updated successfully";
  private static final String ATTRIBUTES_NOT_UPDATED = "Attributes not updated. ";

  private ActiveInventoryAdapter aaiAdapter;
  private UserValidator validator;
  private OxmModelLoader oxmModelLoader;
  private OxmEntityLookup oxmEntityLookup;
  
  /**
   * Instantiates a new attribute updater.
   * @throws AttributeUpdateException 
   */
  public AttributeUpdater(OxmModelLoader oxmModelLoader, OxmEntityLookup oxmEntityLookup, ActiveInventoryAdapter activeInventoryAdapter) throws AttributeUpdateException {
    super();
    this.oxmModelLoader = oxmModelLoader;
    this.oxmEntityLookup = oxmEntityLookup;
    this.aaiAdapter = activeInventoryAdapter;
    
    try {
      this.validator = new UserValidator();
    } catch (Exception exc) {
      LOG.error(AaiUiMsgs.ATTRIBUTES_ERROR_GETTING_AAI_CONFIG_OR_ADAPTER, exc.getLocalizedMessage());
      throw new AttributeUpdateException(exc);
    }
  }
  
  protected String getResourceBasePath() {

    String versionStr = null;
    if (oxmModelLoader != null) {
      versionStr = String.valueOf(oxmModelLoader.getLatestVersionNum());
    }

    return "/aai/v" + versionStr;

  }
  
  protected URI getBaseUri() {
    return UriBuilder
        .fromUri("https://" + aaiAdapter.getEndpointConfig().getEndpointIpAddress() + ":"
            + aaiAdapter.getEndpointConfig().getEndpointServerPort() + getResourceBasePath())
        .build();
  }

  /**
   * Update object attribute.
   *
   * @param objectUri - Valid URI of the object as per OXM model.
   * @param attributeValues - Map of (attribute-name & attribute-value) for
   *        any attributes to be updated to the value.
   * @param attUid - ATTUID of the user requesting the update.
   * @return - OperationResult with success or failure reason.
   */
  public OperationResult updateObjectAttribute(String objectUri, Map<String, Object> attributeValues, String attUid) {
    OperationResult result = new OperationResult();
    LOG.info(AaiUiMsgs.ATTRIBUTES_UPDATE_METHOD_CALLED, objectUri, attUid, String.valueOf(attributeValues));
    if (!validator.isAuthorizedUser(attUid)) {
      result.setResultCode(403);
      result.setResult(String.format("User %s is not authorized for Attributes update ", attUid));
      LOG.error(AaiUiMsgs.ATTRIBUTES_USER_NOT_AUTHORIZED_TO_UPDATE, attUid);
      return result;
    }

    AaiEditObject object = null;

    try {
      object = getEditObjectFromUri(objectUri);
    } catch (AttributeUpdateException exc) {
      result.setResultCode(400);
      result.setResult(ATTRIBUTES_NOT_UPDATED);
      LOG.error(AaiUiMsgs.ATTRIBUTES_NOT_UPDATED_EXCEPTION, exc.getLocalizedMessage());
      return result;
    }
    try {
      String jsonPayload = convertEditRequestToJson(object, attributeValues);
      String patchUri = getBaseUri().toString() + getRelativeUri(objectUri);

      
      /*
       * FIX ME:   Dave Adams, 8-Nov-2017
       */
      
      //result = aaiAdapter.doPatch(patchUri, jsonPayload, MediaType.APPLICATION_JSON);

      result = new OperationResult();
      result.setResultCode(404);
      
      if (result.getResultCode() == 200) {
        result.setResult(ATTRIBUTES_UPDATED_SUCCESSFULLY);
        String message = result.getResult() + " for " + objectUri;
        LOG.info(AaiUiMsgs.INFO_GENERIC, message);
      } else {
        String message = ATTRIBUTES_NOT_UPDATED + " For: " + objectUri + ". AAI PATCH Status Code : "
            + result.getResultCode() + ". Error : " + result.getResult();
        LOG.error(AaiUiMsgs.ATTRIBUTES_NOT_UPDATED_MESSAGE, message);
      }
    } catch (AttributeUpdateException exc) {
      result.setResultCode(500);
      result.setResult(ATTRIBUTES_NOT_UPDATED + exc.getLocalizedMessage());
      LOG.error(AaiUiMsgs.ATTRIBUTES_NOT_UPDATED_EXCEPTION, exc.getLocalizedMessage());
    }
    return result;

  }

  /**
   * Gets the relative uri.
   *
   * @param objectUri the object uri
   * @return the relative uri
   */
  public String getRelativeUri(String objectUri) {
    String tempUri = objectUri;
    final Pattern pattern = Pattern.compile(MESSAGE_VERSION_EXTRACTION_REGEX, Pattern.DOTALL);
    Matcher matcher = pattern.matcher(objectUri);
    while (matcher.find()) {
      tempUri = objectUri.substring(matcher.end());
    }
    if (!tempUri.startsWith("/")) {
      tempUri = "/" + tempUri;
    }
    return tempUri;
  }

  /**
   * Gets the edits the object from uri.
   *
   * @param objectUri the object uri
   * @return the edits the object from uri
   * @throws AttributeUpdateException the attribute update exception
   */
  public AaiEditObject getEditObjectFromUri(String objectUri) throws AttributeUpdateException {

    AaiEditObject object = new AaiEditObject();
    String version = getVersionFromUri(objectUri);

    if ( null == version ) {
      version = "v" + String.valueOf(oxmModelLoader.getLatestVersionNum());
    }
    object.setSchemaVersion(version);

    String[] values = objectUri.split("/");
    if (values.length < 2) {
      throw new AttributeUpdateException("Invalid or malformed object URI : " + objectUri);
    }
    String keyValue = values[values.length - 1];
    String rootElement = values[values.length - 2];

    object.setKeyValue(keyValue);
    object.setRootElement(rootElement);

    String objectJavaType = null;
    Map<String, DynamicType> entityTypeLookup = oxmEntityLookup.getEntityTypeLookup();
    DynamicType entity = entityTypeLookup.get(rootElement);
    if ( null != entity ) {
      objectJavaType = entity.getName();
      String message = "Descriptor: Alias: " + objectJavaType + " : DefaultRootElement: "
          + rootElement;
      LOG.debug(AaiUiMsgs.DEBUG_GENERIC, message);
    }
    
    
    if (objectJavaType == null) {
      throw new AttributeUpdateException(
          "Object type could not be determined from the URI : " + objectUri);
    }
    object.setObjectType(objectJavaType);

    // Set key attribute name
    final List<String> primaryKeys = entity.getDescriptor().getPrimaryKeyFieldNames();

    if (primaryKeys.isEmpty()) {
      throw new AttributeUpdateException("Object primary key not found in OXM version " + version);
    }

    for (int i = 0; i < primaryKeys.size(); i++) {
      final String primaryKey = primaryKeys.get(i);
      if (primaryKey.indexOf("/text()") != -1) {
        primaryKeys.set(i, primaryKey.replace("/text()", ""));
      }
    }
    object.setKeyName(primaryKeys.iterator().next());

    return object;
  }

  /**
   * Gets the version from uri.
   *
   * @param objectUri the object uri
   * @return the version from uri
   * @throws AttributeUpdateException the attribute update exception
   */
  private String getVersionFromUri(String objectUri) throws AttributeUpdateException {
    final Pattern pattern = Pattern.compile(MESSAGE_VERSION_EXTRACTION_REGEX, Pattern.DOTALL);
    Matcher matcher = pattern.matcher(objectUri);
    String messageSchemaVersion = null;
    while (matcher.find()) {
      messageSchemaVersion = matcher.group(1);
      break;
    }
    return messageSchemaVersion;
  }

  /**
   * Convert edit request to json.
   *
   * @param object the object
   * @param attributeValues the attribute values
   * @return the string
   * @throws AttributeUpdateException the attribute update exception
   */
  private static String convertEditRequestToJson(AaiEditObject object,
      Map<String, Object> attributeValues) throws AttributeUpdateException {

    ObjectMapper mapper = new ObjectMapper();
    mapper.setPropertyNamingStrategy(new PropertyNamingStrategy.KebabCaseStrategy());
    ObjectWriter ow = mapper.writer();

    Map<String, Object> patchAttributes = new HashMap<>();
    patchAttributes.put(object.getKeyName(), object.getKeyValue());
    patchAttributes.putAll(attributeValues);

    try {
      return ow.writeValueAsString(patchAttributes);
    } catch (JsonProcessingException exc) {
      throw new AttributeUpdateException("Caught a JPE while creating PATCH request body = ", exc);
    }
  }
}