Policy 1707 commit to LF
[policy/engine.git] / ECOMP-PAP-REST / src / main / java / org / openecomp / policy / pap / xacml / rest / handler / PushPolicyHandler.java
1 /*-
2  * ============LICENSE_START=======================================================
3  * ECOMP-PAP-REST
4  * ================================================================================
5  * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
6  * ================================================================================
7  * Licensed under the Apache License, Version 2.0 (the "License");
8  * you may not use this file except in compliance with the License.
9  * You may obtain a copy of the License at
10  * 
11  *      http://www.apache.org/licenses/LICENSE-2.0
12  * 
13  * Unless required by applicable law or agreed to in writing, software
14  * distributed under the License is distributed on an "AS IS" BASIS,
15  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16  * See the License for the specific language governing permissions and
17  * limitations under the License.
18  * ============LICENSE_END=========================================================
19  */
20 package org.openecomp.policy.pap.xacml.rest.handler;
21
22 import java.io.File;
23 import java.net.URI;
24 import java.net.URL;
25 import java.nio.file.Path;
26 import java.nio.file.Paths;
27 import java.util.List;
28
29 import javax.persistence.EntityManager;
30 import javax.persistence.Query;
31 import javax.servlet.http.HttpServletRequest;
32 import javax.servlet.http.HttpServletResponse;
33
34 import org.openecomp.policy.common.logging.eelf.MessageCodes;
35 import org.openecomp.policy.common.logging.eelf.PolicyLogger;
36 import org.openecomp.policy.pap.xacml.rest.XACMLPapServlet;
37 import org.openecomp.policy.rest.XACMLRestProperties;
38 import org.openecomp.policy.rest.jpa.PolicyVersion;
39 import org.openecomp.policy.xacml.api.pap.EcompPDPGroup;
40 import org.openecomp.policy.xacml.std.pap.StdPDPPolicy;
41 import org.openecomp.policy.xacml.util.XACMLPolicyScanner;
42
43 import com.att.research.xacml.util.XACMLProperties;
44
45 import oasis.names.tc.xacml._3_0.core.schema.wd_17.PolicySetType;
46 import oasis.names.tc.xacml._3_0.core.schema.wd_17.PolicyType;
47
48 public class PushPolicyHandler {
49         
50         /*
51          * Get Active Version. 
52          */
53         public void getActiveVersion(HttpServletRequest request, HttpServletResponse response) {
54                 EntityManager em = null;
55                 if(XACMLPapServlet.getEmf()!=null){
56                         em = (EntityManager) XACMLPapServlet.getEmf().createEntityManager();
57                 }
58                 if (em==null){
59                         PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE + " Error creating entity manager with persistence unit: " + XACMLPapServlet.getPersistenceUnit());
60                         return;
61                 }
62                 String policyScope = request.getParameter("policyScope");
63                 String filePrefix = request.getParameter("filePrefix");
64                 String policyName = request.getParameter("policyName");
65
66                 String pvName = policyScope + File.separator + filePrefix + policyName;
67                 int activeVersion = 0;
68
69                 //Get the Active Version to use in the ID
70                 em.getTransaction().begin();
71                 Query query = em.createQuery("Select p from PolicyVersion p where p.policyName=:pname");
72                 query.setParameter("pname", pvName);
73
74                 @SuppressWarnings("rawtypes")
75                 List result = query.getResultList();
76                 PolicyVersion versionEntity = null;
77                 if (!result.isEmpty()) {
78                         versionEntity = (PolicyVersion) result.get(0);
79                         em.persist(versionEntity);
80                         activeVersion = versionEntity.getActiveVersion();
81                         em.getTransaction().commit();
82                 } else {
83                         PolicyLogger.debug("No PolicyVersion using policyName found");
84                 }
85
86                 //clean up connection
87                 em.close();
88                 if (String.valueOf(activeVersion)!=null || !String.valueOf(activeVersion).equalsIgnoreCase("")) {                                                       
89                         response.setStatus(HttpServletResponse.SC_OK);                                                          
90                         response.addHeader("version", String.valueOf(activeVersion));                                                           
91                 } else {
92                         response.setStatus(HttpServletResponse.SC_NOT_FOUND);                                                           
93                 }
94         }
95         
96         /*
97          * Get Git Path 
98          */
99         public void getGitPath(HttpServletRequest request, HttpServletResponse response) {
100                 String policyScope = request.getParameter("policyScope");
101                 String filePrefix = request.getParameter("filePrefix");
102                 String policyName = request.getParameter("policyName");
103                 String activeVersion = request.getParameter("activeVersion");
104                 
105                 Path workspacePath = Paths.get(XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_WORKSPACE), "admin");
106                 Path repositoryPath = Paths.get(XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_REPOSITORY));
107                 Path gitPath = Paths.get(workspacePath.toString(), repositoryPath.getFileName().toString());
108                 
109                 //getting the fullpath of the gitPath and convert to string
110                 String fullGitPath = gitPath.toAbsolutePath().toString();
111                 String finalGitPath = null;
112                 
113                 //creating the parentPath directory for the Admin Console use
114                 if(fullGitPath.contains("\\")){
115                         if(fullGitPath.contains("ECOMP-PAP-REST")){
116                                 finalGitPath = fullGitPath.replace("ECOMP-PAP-REST", "ecomp-sdk-app");
117                         }else{
118                                 finalGitPath = fullGitPath.replace("ATT-PAP-REST", "ATT-ecomp-sdk-app");
119                         }
120                 }else{
121                         finalGitPath = fullGitPath.replace("pap",  "console");
122                 }
123
124                 finalGitPath += File.separator + policyScope + File.separator + filePrefix + policyName + "." + activeVersion + ".xml";
125                 File file = new File(finalGitPath);
126                 URI uri = file.toURI();
127
128                 //
129                 // Extract XACML policy information
130                 //
131                 Boolean isValid = false;
132                 String policyId = null;
133                 String description = null;
134                 String  version = null;
135
136                 URL url;
137                 try {
138                         url = uri.toURL();
139                         Object rootElement = XACMLPolicyScanner.readPolicy(url.openStream());
140                         if (rootElement == null ||
141                                         (
142                                                         ! (rootElement instanceof PolicySetType) &&
143                                                         ! (rootElement instanceof PolicyType)
144                                                         )       ) {
145                                 PolicyLogger.warn("No root policy element in URI: " + uri.toString() + " : " + rootElement);
146                                 isValid = false;
147                         } else {
148                                 if (rootElement instanceof PolicySetType) {
149                                         policyId = ((PolicySetType)rootElement).getPolicySetId();
150                                         description = ((PolicySetType)rootElement).getDescription();
151                                         isValid = true;
152                                         version = ((PolicySetType)rootElement).getVersion();
153                                 } else if (rootElement instanceof PolicyType) {
154                                         policyId = ((PolicyType)rootElement).getPolicyId();
155                                         description = ((PolicyType)rootElement).getDescription();
156                                         version = ((PolicyType)rootElement).getVersion();
157                                         isValid = true;
158                                 } else {
159                                         PolicyLogger.error("Unknown root element: " + rootElement.getClass().getCanonicalName());
160                                 }
161                         }
162                 } catch (Exception e) {
163                         PolicyLogger.error("Exception Occured While Extracting Policy Information");
164                 } 
165                 if (!finalGitPath.equalsIgnoreCase("") || policyId!=null || description!=null || version!=null || isValid!=null) {                                                      
166                         response.setStatus(HttpServletResponse.SC_OK);                                                          
167                         response.addHeader("gitPath", finalGitPath);
168                         response.addHeader("policyId", policyId);
169                         response.addHeader("description", description);
170                         response.addHeader("version", version);
171                         response.addHeader("isValid", isValid.toString());
172                 }
173         }
174         
175         /*
176          * Get Selected URI path. 
177          */
178         public void getSelectedURI(HttpServletRequest request, HttpServletResponse response) {
179                 String gitPath = request.getParameter("gitPath");
180                 File file = new File(gitPath);
181                 PolicyLogger.debug("The fileItem is : " + file.toString());
182                 URI selectedURI = file.toURI();
183                 String uri = selectedURI.toString();
184                 if (!uri.equalsIgnoreCase("")) {                                                        
185                         response.setStatus(HttpServletResponse.SC_OK);                                                          
186                         response.addHeader("selectedURI", uri);                                                         
187                 } else {                                                
188                         response.setStatus(HttpServletResponse.SC_NOT_FOUND);                                                           
189                 }                                               
190         }
191         
192         public boolean preSafetyCheck(StdPDPPolicy policy, String configHome){
193                 return true;
194         }
195         
196         public boolean preSafetyCheck(EcompPDPGroup policy, String configHome){
197                 return true;
198         }
199         
200         public static PushPolicyHandler getInstance() {
201                 try {
202                         Class<?> pushPolicyHandler = Class.forName(XACMLProperties.getProperty("pushPolicy.impl.className", PushPolicyHandler.class.getName()));
203                         PushPolicyHandler instance = (PushPolicyHandler) pushPolicyHandler.newInstance(); 
204                         return instance;
205                 } catch (Exception e) {
206                         PolicyLogger.error(e.getMessage());
207                 }
208                 return null;
209         }
210 }