Initial OpenECOMP policy/engine commit
[policy/engine.git] / ecomp-sdk-app / src / main / java / org / openecomp / policy / admin / XacmlAdminUI.java
1 /*-
2  * ============LICENSE_START=======================================================
3  * ECOMP Policy Engine
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
21 package org.openecomp.policy.admin;
22
23
24 import java.io.IOException;
25 import java.nio.file.Files;
26 import java.nio.file.Path;
27 import java.nio.file.Paths;
28
29 import javax.servlet.ServletConfig;
30 import javax.servlet.ServletException;
31 import javax.servlet.annotation.WebInitParam;
32 import javax.servlet.annotation.WebServlet;
33 import javax.servlet.http.HttpServlet;
34
35
36 import org.eclipse.jgit.api.Git;
37 import org.eclipse.jgit.api.errors.GitAPIException;
38 import org.eclipse.jgit.lib.Repository;
39 import org.eclipse.jgit.lib.StoredConfig;
40 import org.eclipse.jgit.storage.file.FileRepositoryBuilder;
41 import org.hibernate.Session;
42 import org.hibernate.SessionFactory;
43 import org.openecomp.policy.rest.XACMLRest;
44 import org.openecomp.policy.rest.XACMLRestProperties;
45 import org.openecomp.policy.rest.dao.UserInfoDao;
46 import org.openecomp.policy.rest.jpa.UserInfo;
47 import org.openecomp.policy.rest.util.Webapps;
48 import org.openecomp.policy.xacml.api.pap.PAPPolicyEngine;
49 import org.springframework.beans.factory.annotation.Autowired;
50
51 import com.att.research.xacml.util.XACMLProperties;
52 import com.google.common.base.Splitter;
53
54
55
56 public class XacmlAdminUI extends HttpServlet implements PAPNotificationBroadcaster.PAPNotificationBroadcastListener{
57
58         private static final long serialVersionUID = 1L;
59         //
60         // The PAP Engine
61         //
62         private PAPPolicyEngine papEngine;
63         private static Path repositoryPath;
64         private static Repository repository;
65         
66         @Autowired
67         UserInfoDao userInfoDao;
68         
69         @Autowired
70         SessionFactory sessionfactory;
71         
72         @WebServlet(value = "/policy#/*", description = "XACML Admin Console", asyncSupported = true, loadOnStartup = 1, initParams = { @WebInitParam(name = "XACML_PROPERTIES_NAME", value = "xacml.admin.properties", description = "The location of the properties file holding configuration information.") })
73         public static class Servlet extends HttpServlet {
74                 private static final long serialVersionUID = -5274600248961852835L;
75
76                 @Override
77                 public void init(ServletConfig servletConfig) throws ServletException {
78                         super.init(servletConfig);
79                         //
80                         // Common initialization
81                         //
82                         XACMLRest.xacmlInit(servletConfig);
83                         //
84                         // Initialize GIT repository.
85                         //
86                         XacmlAdminUI.initializeGitRepository();
87                         //
88                         // Read the Props
89                         // The webapps Action and Config are read when getActionHome or getConfigHome are called
90                         try {
91                                 getConfigHome();
92                         } catch (Exception e) {
93                                 throw new ServletException(e);
94                         }
95
96                 }
97
98
99                 @Override
100                 public void destroy() {
101                         if (XacmlAdminUI.repository != null) {
102                                 XacmlAdminUI.repository.close();
103                         }
104                         super.destroy();
105                 }
106         }
107         
108         private static void initializeGitRepository() throws ServletException {
109                 
110                 try {
111                         XacmlAdminUI.repositoryPath = Paths.get(XACMLProperties.getProperty(XACMLRestProperties.PROP_ADMIN_REPOSITORY));
112                 } catch (Exception e) {
113                         XACMLProperties.reloadProperties();
114                         XacmlAdminUI.repositoryPath = Paths.get(XACMLProperties.getProperty(XACMLRestProperties.PROP_ADMIN_REPOSITORY));
115                 }
116                 FileRepositoryBuilder builder = new FileRepositoryBuilder();
117                 try {
118                         XacmlAdminUI.repository = builder.setGitDir(XacmlAdminUI.repositoryPath.toFile()).readEnvironment().findGitDir().setBare().build();
119                         if (Files.notExists(XacmlAdminUI.repositoryPath)|| Files.notExists(Paths.get(XacmlAdminUI.repositoryPath.toString(), "HEAD"))) {
120                                 //
121                                 // Create it if it doesn't exist. As a bare repository
122                                 XacmlAdminUI.repository.create();
123                                 //
124                                 // Add the magic file so remote works.
125                                 //
126                                 Path daemon = Paths.get(XacmlAdminUI.repositoryPath.toString(), "git-daemon-export-ok");
127                                 Files.createFile(daemon);
128                         }
129                 } catch (IOException e) {
130                         throw new ServletException(e.getMessage(), e.getCause());
131                 }
132                 //
133                 // Make sure the workspace directory is created
134                 //
135                 Path workspace = Paths.get(XACMLProperties.getProperty(XACMLRestProperties.PROP_ADMIN_WORKSPACE));
136                 workspace = workspace.toAbsolutePath();
137                 if (Files.notExists(workspace)) {
138                         try {
139                                 Files.createDirectory(workspace);
140                         } catch (IOException e) {
141                                 throw new ServletException(e.getMessage(), e.getCause());
142                         }
143                 }
144                 //
145                 // Create the user workspace directory
146                 //
147                 workspace = Paths.get(workspace.toString(), "admin");
148                 
149                 if (Files.notExists(workspace)) {
150                         try {
151                                 Files.createDirectory(workspace);
152                         } catch (IOException e) {
153                                 throw new ServletException(e.getMessage(), e.getCause());
154                         }
155                 }
156                 //
157                 // Get the path to where the repository is going to be
158                 //
159                 Path gitPath = Paths.get(workspace.toString(), XacmlAdminUI.repositoryPath.getFileName().toString());
160                 if (Files.notExists(gitPath)) {
161                         try {
162                                 Files.createDirectory(gitPath);
163                         } catch (IOException e) {
164                                 throw new ServletException(e.getMessage(), e.getCause());
165                         }
166                 }
167                 //
168                 // Initialize the domain structure
169                 //
170                 String base = null;
171                 String domain = XacmlAdminUI.getDomain();
172                 if (domain != null) {
173                         for (String part : Splitter.on(':').trimResults().split(domain)) {
174                                 if (base == null) {
175                                         base = part;
176                                 }
177                                 Path subdir = Paths.get(gitPath.toString(), part);
178                                 if (Files.notExists(subdir)) {
179                                         try {
180                                                 Files.createDirectory(subdir);
181                                                 Files.createFile(Paths.get(subdir.toString(), ".svnignore"));
182                                         } catch (IOException e) {
183                                                 throw new ServletException(e.getMessage(), e.getCause());
184                                         }
185                                 }
186                         }
187                 } else {
188                         try {
189                                 Files.createFile(Paths.get(workspace.toString(), ".svnignore"));
190                                 base = ".svnignore";
191                         } catch (IOException e) {
192                                 throw new ServletException(e.getMessage(), e.getCause());
193                         }
194                 }
195                 try {
196                         //
197                         // These are the sequence of commands that must be done initially to
198                         // finish setting up the remote bare repository.
199                         //
200                         Git git = Git.init().setDirectory(gitPath.toFile()).setBare(false).call();
201                         git.add().addFilepattern(base).call();
202                         git.commit().setMessage("Initialize Bare Repository").call();
203                         StoredConfig config = git.getRepository().getConfig();
204                         config.setString("remote", "origin", "url", XacmlAdminUI.repositoryPath.toAbsolutePath().toString());
205                         config.setString("remote", "origin", "fetch", "+refs/heads/*:refs/remotes/origin/*");
206                         config.save();
207                         git.push().setRemote("origin").add("master").call();
208                         /*
209                          * This will not work unless
210                          * git.push().setRemote("origin").add("master").call(); is called
211                          * first. Otherwise it throws an exception. However, if the push()
212                          * is called then calling this function seems to add nothing.
213                          * 
214                          * git.branchCreate().setName("master")
215                          * .setUpstreamMode(SetupUpstreamMode.SET_UPSTREAM)
216                          * .setStartPoint("origin/master").setForce(true).call();
217                          */
218                 } catch (GitAPIException | IOException e) {
219                         throw new ServletException(e.getMessage(), e.getCause());
220                 }
221         }
222
223         public UserInfo getUserNameFromUserInfoTable(String createdBy){
224                 String loginId = createdBy;
225                 Object user = null;
226                 Session session = sessionfactory.openSession();
227                 user = session.load(UserInfo.class, loginId);
228                 return (UserInfo) user;
229         }
230         
231         @Override
232         public void updateAllGroups() {
233
234         }
235
236         public PAPPolicyEngine getPapEngine() {
237                 return papEngine;
238         }
239
240         public void setPapEngine(PAPPolicyEngine papEngine) {
241                 this.papEngine = papEngine;
242         }
243         
244         public static String getConfigHome() {
245                 return Webapps.getConfigHome();
246         }
247         
248         public static String getDomain() {
249                 return XACMLProperties.getProperty(XACMLRestProperties.PROP_ADMIN_DOMAIN, "urn");
250         }
251         
252         // get the repository path from property file
253         public static Path getRepositoryPath() {
254                 if(repositoryPath == null){
255                         try {
256                                 initializeGitRepository();
257                         } catch (ServletException e) {
258
259                         }
260                 }
261                 return repositoryPath;
262         }
263         
264         
265 }
266