dc1c6eb55281a04d1a0f04d6e137bc5c62bbcd3a
[aai/sparky-be.git] / src / main / java / org / onap / aai / sparky / editattributes / AttributeEditProcessor.java
1 /**
2  * ============LICENSE_START=======================================================
3  * org.onap.aai
4  * ================================================================================
5  * Copyright © 2017 AT&T Intellectual Property. All rights reserved.
6  * Copyright © 2017 Amdocs
7  * ================================================================================
8  * Licensed under the Apache License, Version 2.0 (the "License");
9  * you may not use this file except in compliance with the License.
10  * You may obtain a copy of the License at
11  *
12  *       http://www.apache.org/licenses/LICENSE-2.0
13  *
14  * Unless required by applicable law or agreed to in writing, software
15  * distributed under the License is distributed on an "AS IS" BASIS,
16  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
17  * See the License for the specific language governing permissions and
18  * limitations under the License.
19  * ============LICENSE_END=========================================================
20  *
21  * ECOMP is a trademark and service mark of AT&T Intellectual Property.
22  */
23 package org.onap.aai.sparky.editattributes;
24
25 import java.io.UnsupportedEncodingException;
26 import java.util.Map;
27
28 import org.apache.camel.Exchange;
29 import org.apache.camel.component.restlet.RestletConstants;
30 import org.onap.aai.cl.api.Logger;
31 import org.onap.aai.cl.eelf.LoggerFactory;
32 import org.onap.aai.cl.mdc.MdcContext;
33 import org.onap.aai.restclient.client.OperationResult;
34 import org.onap.aai.sparky.editattributes.entity.EditRequest;
35 import org.onap.aai.sparky.logging.AaiUiMsgs;
36 import org.onap.aai.sparky.util.NodeUtils;
37 import org.restlet.Request;
38 import org.restlet.Response;
39 import org.restlet.data.ClientInfo;
40 import org.restlet.data.Cookie;
41 import org.restlet.data.MediaType;
42 import org.restlet.data.Status;
43 import org.restlet.util.Series;
44
45 import com.fasterxml.jackson.annotation.JsonInclude.Include;
46 import com.fasterxml.jackson.databind.ObjectMapper;
47
48 /**
49  * The Class AttributeEditProcessor.
50  */
51 public class AttributeEditProcessor {
52
53   private static final Logger LOG =
54       LoggerFactory.getInstance().getLogger(AttributeEditProcessor.class);
55
56   private ObjectMapper mapper;
57   private AttributeUpdater attrUpdater;
58
59   public AttributeEditProcessor(AttributeUpdater attributeUpdater) {
60     this.attrUpdater = attributeUpdater;
61
62     this.mapper = new ObjectMapper();
63     mapper.setSerializationInclusion(Include.NON_EMPTY);
64   }
65
66   public void editAttribute(Exchange exchange) {
67
68     Object xTransactionId = exchange.getIn().getHeader("X-TransactionId");
69
70     if (xTransactionId == null) {
71       xTransactionId = NodeUtils.getRandomTxnId();
72     }
73
74     Object partnerName = exchange.getIn().getHeader("X-FromAppId");
75     if (partnerName == null) {
76       partnerName = "Browser";
77     }
78
79     Request request = exchange.getIn().getHeader(RestletConstants.RESTLET_REQUEST, Request.class);
80
81     /*
82      * Disables automatic Apache Camel Restlet component logging which prints out an undesirable log
83      * entry which includes client (e.g. browser) information
84      */
85     request.setLoggable(false);
86
87     ClientInfo clientInfo = request.getClientInfo();
88     MdcContext.initialize((String) xTransactionId, "AAI-UI", "", (String) partnerName,
89         clientInfo.getAddress() + ":" + clientInfo.getPort());
90
91     String payload = exchange.getIn().getBody(String.class);
92     EditRequest editRequest = null;
93     OperationResult operationResult = new OperationResult();
94
95     Response response = exchange.getIn().getHeader(RestletConstants.RESTLET_RESPONSE, Response.class);
96     response.setStatus(Status.SUCCESS_OK); // 200 is assumed unless an actual exception occurs (a failure is still a valid response)
97     
98     boolean wasErrorDuringProcessing = false;
99     String errorMessage = null;
100     
101     
102     try {
103       
104       if (payload != null && !payload.isEmpty()) {
105         editRequest = mapper.readValue(payload, EditRequest.class);
106
107         if (editRequest != null) {
108
109           String attUid = getAttUid(request.getCookies());
110           String objectUri = editRequest.getEntityUri();
111           Map<String, Object> attributeValues = editRequest.getAttributes();
112           
113           if (attUid != null && !attUid.isEmpty() && objectUri != null && !objectUri.isEmpty()
114               && attributeValues != null && !attributeValues.isEmpty()) {
115
116             LOG.info(AaiUiMsgs.ATTRIBUTES_HANDLING_EDIT, objectUri, editRequest.toString());
117             
118             operationResult = attrUpdater.updateObjectAttribute(objectUri, attributeValues, attUid);
119
120             boolean wasSuccess = (operationResult.getResultCode() == 200);
121             String message = String.format("Edit Attributes completed with Result Code : %s (%s).",
122                 operationResult.getResultCode(), wasSuccess ? "success" : "failed");
123
124             LOG.info(AaiUiMsgs.INFO_GENERIC, message);
125           }
126         }
127       } else {
128         wasErrorDuringProcessing = true;
129         errorMessage = "Empty payload provided, need details to complete request";
130       }
131     } catch (Exception exc) {
132       LOG.error(AaiUiMsgs.ATTRIBUTES_NOT_UPDATED_EXCEPTION, exc.getLocalizedMessage());
133       operationResult.setResult(500, "Error encountered while trying to update attributes.");
134       response.setStatus(Status.SERVER_ERROR_INTERNAL);
135     }
136     
137     if(wasErrorDuringProcessing) {
138       LOG.error(AaiUiMsgs.ATTRIBUTES_NOT_UPDATED_MESSAGE, errorMessage);
139     }
140
141     response.setEntity(operationResult.getResult(), MediaType.APPLICATION_JSON);
142     exchange.getOut().setBody(response);
143   }
144
145   /**
146    * Gets the att uid.
147    *
148    * @param request the request
149    * @return the att uid
150    * @throws UnsupportedEncodingException the unsupported encoding exception
151    */
152   public String getAttUid(Series<Cookie> cookies) throws UnsupportedEncodingException {
153     String attId = "";
154     if (cookies == null) {
155       LOG.error(AaiUiMsgs.COOKIE_NOT_FOUND);
156       return attId;
157     }
158     for (Cookie cookie : cookies) {
159       if (cookie.getName().equals("attESHr")) {
160         // This cookie is of the form :
161         // "FIRSTNAME|LASTNAME|emailname@domain.com|||ab1234||fl6789,RBFMSKQ,"
162         // + "Z9V2298,9762186|YNNNNNNNNNNNNNYNNYYNNNNN|FIRSTNAME|EY6SC9000|"
163         // we are to extract fl6789 from this which would be the attuid for the user.
164         String value = cookie.getValue();
165         value = java.net.URLDecoder.decode(value, "UTF-8");
166         LOG.info(AaiUiMsgs.COOKIE_FOUND, value);
167         String[] values = value.split("\\|");
168         if (values.length > 7) {
169           attId = (values[7].split(","))[0];
170
171           String initials = (values[0].substring(0, 1) + values[1].substring(0, 1)).toLowerCase();
172           if (attId.startsWith(initials)) {
173             return attId;
174           }
175         }
176       }
177     }
178     return attId;
179   }
180 }