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