Change to fix SQLInvalidAuthorizationSpecException
[policy/xacml-pdp.git] / applications / common / src / main / java / org / onap / policy / pdp / xacml / application / common / operationshistory / GetOperationOutcomePip.java
1 /*-
2  * ============LICENSE_START=======================================================
3  * Copyright (C) 2019 AT&T Intellectual Property. All rights reserved.
4  * ================================================================================
5  * Licensed under the Apache License, Version 2.0 (the "License");
6  * you may not use this file except in compliance with the License.
7  * You may obtain a copy of the License at
8  *
9  *      http://www.apache.org/licenses/LICENSE-2.0
10  *
11  * Unless required by applicable law or agreed to in writing, software
12  * distributed under the License is distributed on an "AS IS" BASIS,
13  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14  * See the License for the specific language governing permissions and
15  * limitations under the License.
16  * ============LICENSE_END=========================================================
17  */
18
19
20 package org.onap.policy.pdp.xacml.application.common.operationshistory;
21
22 import com.att.research.xacml.api.XACML3;
23 import com.att.research.xacml.api.pip.PIPException;
24 import com.att.research.xacml.api.pip.PIPFinder;
25 import com.att.research.xacml.api.pip.PIPRequest;
26 import com.att.research.xacml.api.pip.PIPResponse;
27 import com.att.research.xacml.std.pip.StdMutablePIPResponse;
28 import com.att.research.xacml.std.pip.StdPIPResponse;
29 import com.google.common.base.Strings;
30
31 import java.util.Arrays;
32 import java.util.Base64;
33 import java.util.Collection;
34 import java.util.Properties;
35
36 import javax.persistence.Persistence;
37
38 import org.onap.policy.pdp.xacml.application.common.ToscaDictionary;
39 import org.onap.policy.pdp.xacml.application.common.std.StdOnapPip;
40 import org.slf4j.Logger;
41 import org.slf4j.LoggerFactory;
42
43
44 public class GetOperationOutcomePip extends StdOnapPip {
45     public static final String ISSUER_NAME = "get-operation-outcome";
46     private static Logger logger = LoggerFactory.getLogger(GetOperationOutcomePip.class);
47
48     public GetOperationOutcomePip() {
49         super();
50     }
51
52     @Override
53     public Collection<PIPRequest> attributesRequired() {
54         return Arrays.asList(PIP_REQUEST_TARGET);
55     }
56
57     @Override
58     public void configure(String id, Properties properties) throws PIPException {
59         super.configure(id, properties);
60         //
61         // Create our entity manager
62         //
63         em = null;
64         try {
65             //
66             // In case there are any overloaded properties for the JPA
67             //
68             Properties emProperties = new Properties();
69             emProperties.putAll(properties);
70
71             //
72             // Need to decode the password before creating the EntityManager
73             //
74             String decodedPassword = new String(Base64.getDecoder()
75                     .decode(emProperties.getProperty("javax.persistence.jdbc.password")));
76             emProperties.setProperty("javax.persistence.jdbc.password", decodedPassword);
77
78             //
79             // Create the entity manager factory
80             //
81             em = Persistence.createEntityManagerFactory(
82                     properties.getProperty(ISSUER_NAME + ".persistenceunit"),
83                     emProperties).createEntityManager();
84         } catch (Exception e) {
85             logger.error("Persistence failed {} operations history db {}", e.getLocalizedMessage(), e);
86         }
87     }
88
89     /**
90      * getAttributes.
91      *
92      * @param pipRequest the request
93      * @param pipFinder the pip finder
94      * @return PIPResponse
95      */
96     @Override
97     public PIPResponse getAttributes(PIPRequest pipRequest, PIPFinder pipFinder) throws PIPException {
98         logger.debug("getAttributes requesting attribute {} of type {} for issuer {}",
99                 pipRequest.getAttributeId(), pipRequest.getDataTypeId(), pipRequest.getIssuer());
100         //
101         // Determine if the issuer is correct
102         //
103         if (Strings.isNullOrEmpty(pipRequest.getIssuer())) {
104             logger.debug("issuer is null - returning empty response");
105             //
106             // We only respond to ourself as the issuer
107             //
108             return StdPIPResponse.PIP_RESPONSE_EMPTY;
109         }
110         if (! pipRequest.getIssuer().startsWith(ToscaDictionary.GUARD_ISSUER_PREFIX)) {
111             logger.debug("Issuer does not start with guard");
112             //
113             // We only respond to ourself as the issuer
114             //
115             return StdPIPResponse.PIP_RESPONSE_EMPTY;
116         }
117         //
118         // Parse out the issuer which denotes the time window
119         // Eg: any-prefix:clname:some-controlloop-name
120         //
121         String[] s1 = pipRequest.getIssuer().split("clname:");
122         String clname = s1[1];
123         String target = null;
124         target = getAttribute(pipFinder, PIP_REQUEST_TARGET);
125
126         logger.debug("Going to query DB about: clname={}, target={}", clname, target);
127         String outcome = doDatabaseQuery(clname, target);
128         logger.debug("Query result is: {}", outcome);
129
130         StdMutablePIPResponse pipResponse = new StdMutablePIPResponse();
131         this.addStringAttribute(pipResponse,
132                 XACML3.ID_ATTRIBUTE_CATEGORY_RESOURCE,
133                 ToscaDictionary.ID_RESOURCE_GUARD_OPERATIONOUTCOME,
134                 outcome,
135                 pipRequest);
136         return new StdPIPResponse(pipResponse);
137     }
138
139     private String doDatabaseQuery(String clname, String target) {
140         logger.info("Querying operations history for {} {}", clname, target);
141         //
142         // Only can query if we have an EntityManager
143         //
144         if (em == null) {
145             logger.error("No EntityManager available");
146             return null;
147         }
148         //
149         // Do the query
150         //
151         try {
152             //
153             // We are expecting a single result
154             //
155             return em.createQuery("select e.outcome from Dbao e"
156                                   + " where e.closedLoopName= ?1"
157                                   + " and e.target= ?2"
158                                   + " order by e.endtime desc",
159                                   String.class)
160                 .setParameter(1, clname)
161                 .setParameter(2, target)
162                 .setMaxResults(1)
163                 .getSingleResult();
164         } catch (Exception e) {
165             logger.error("Typed query failed ", e);
166             return null;
167         }
168     }
169 }