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