Initial OpenECOMP policy/engine commit
[policy/engine.git] / ECOMP-TEST / src / test / java / org / openecomp / policy / pdp / test / annotations / TestAnnotation.java
1 /*-
2  * ============LICENSE_START=======================================================
3  * ECOMP-TEST
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.pdp.test.annotations;
22
23 import java.io.IOException;
24 import java.net.MalformedURLException;
25 import java.net.URI;
26 import java.nio.file.Files;
27 import java.nio.file.Path;
28 import java.nio.file.Paths;
29 import java.util.Arrays;
30 import java.util.Calendar;
31 import java.util.Collection;
32 import java.util.Date;
33 import java.util.TimeZone;
34
35 import org.apache.commons.cli.ParseException;
36 import org.apache.commons.logging.Log;
37 import org.apache.commons.logging.LogFactory;
38 import org.openecomp.policy.pdp.test.TestBase;
39
40 import com.att.research.xacml.api.DataTypeException;
41 import com.att.research.xacml.api.Response;
42 import com.att.research.xacml.std.annotations.RequestParser;
43 import com.att.research.xacml.std.annotations.XACMLAction;
44 import com.att.research.xacml.std.annotations.XACMLAttribute;
45 import com.att.research.xacml.std.annotations.XACMLEnvironment;
46 import com.att.research.xacml.std.annotations.XACMLMultiRequest;
47 import com.att.research.xacml.std.annotations.XACMLRequest;
48 import com.att.research.xacml.std.annotations.XACMLRequestReference;
49 import com.att.research.xacml.std.annotations.XACMLResource;
50 import com.att.research.xacml.std.annotations.XACMLSubject;
51 import com.att.research.xacml.std.datatypes.HexBinary;
52 import com.att.research.xacml.std.datatypes.IPAddress;
53 import com.att.research.xacml.std.datatypes.IPv4Address;
54 import com.att.research.xacml.std.datatypes.ISO8601DateTime;
55 import com.att.research.xacml.std.datatypes.ISO8601Time;
56 import com.att.research.xacml.util.FactoryException;
57
58 /**
59  * This example application shows how to use annotations for Java classes to create requests to send to the
60  * engine.
61  * 
62  *
63  */
64 public class TestAnnotation extends TestBase {
65         private static final Log logger = LogFactory.getLog(TestAnnotation.class);
66         
67         private int     num;
68         
69         /**
70          * This is a sample class that uses annotations. In addition to demonstrating how to use XACML annotations,
71          * it also demonstrates the various Java objects that can be used and how the request parser will
72          * resolve each object's datatype.
73          * 
74          *
75          */
76         @XACMLRequest(ReturnPolicyIdList=true)
77         public class MyRequestAttributes {
78                 
79                 public MyRequestAttributes(String user, String action, String resource) {
80                         this.userID = user;
81                         this.action = action;
82                         this.resource = resource;
83                         this.today = new Date();
84                         this.yesterday = Calendar.getInstance();
85                         this.yesterday.add(Calendar.DAY_OF_MONTH, -1);
86                 }
87
88                 @XACMLSubject(includeInResults=true)
89                 String  userID;
90                 
91                 @XACMLSubject(attributeId="urn:oasis:names:tc:xacml:1.0:subject:subject-id-qualifier")
92                 boolean admin = false;
93                 
94                 @XACMLSubject(attributeId="urn:oasis:names:tc:xacml:1.0:subject:key-info", issuer="com:foo:security")
95                 HexBinary publicKey = new HexBinary(new byte[] {'1', '0'});
96                 
97                 @XACMLSubject(attributeId="urn:oasis:names:tc:xacml:1.0:subject:authentication-time")
98                 ISO8601Time     authenticationTime = new ISO8601Time(8, 0, 0, 0);
99                 
100                 /**
101                  * Here our base object is "Object", but it is reflected as a Java "String". The parser
102                  * will then use the XACML http://www.w3.org/2001/XMLSchema#string as the datatype.
103                  */
104                 @XACMLSubject(attributeId="urn:oasis:names:tc:xacml:1.0:subject:authentication-method")
105                 Object authenticationMethod = new String("RSA Public Key");
106                 
107                 /**
108                  * Here our base object is "String", but we use the annotation for datatype to clarify
109                  * that the real XACML data type is http://www.w3.org/2001/XMLSchema#time. The parser will
110                  * use the data type factory to convert the "String" to a "ISO8601Time" Java object.
111                  */
112                 @XACMLSubject(attributeId="urn:oasis:names:tc:xacml:1.0:subject:request-time", datatype="http://www.w3.org/2001/XMLSchema#time")
113                 String requestTime = new String("13:20:00-05:00");
114                 
115                 @XACMLSubject(attributeId="urn:oasis:names:tc:xacml:1.0:subject:session-start-time")
116                 ISO8601DateTime sessionStart = new ISO8601DateTime(TimeZone.getDefault().getID(), 2014, 1, 1, 10, 0, 0, 0);
117                 
118                 @XACMLSubject(attributeId="urn:oasis:names:tc:xacml:3.0:subject:authn-locality:ip-address")
119                 IPAddress ip = new IPv4Address(new short[] {123, 134, 156, 255 }, null, null);
120                 
121                 @XACMLSubject(attributeId="urn:oasis:names:tc:xacml:3.0:subject:authn-locality:dns-name")
122                 String dnsName = "localhost";
123                 
124                 @XACMLAction()
125                 String  action;
126                 
127                 @XACMLAction(attributeId="urn:oasis:names:tc:xacml:1.0:action:implied-action")
128                 long    impliedAction;
129                 
130                 @XACMLResource()
131                 String  resource;
132                 
133                 @XACMLEnvironment()
134                 Date            today;
135                 
136                 @XACMLEnvironment()
137                 Calendar        yesterday;
138                 
139                 /**
140                  * This field demonstrates how the parser can detect collections and build a bag of values.
141                  */
142                 @XACMLAttribute(attributeId="foo:bar:attribute")
143                 Collection<Double>              fooBar = Arrays.asList(2.5, 3.5);
144                 
145                 /**
146                  * The XACMLAttribute annotation allows one to specify all the 
147                  */
148                 @XACMLAttribute(category="foo:bar:category", attributeId="foo:bar:attribute2")
149                 double          fooBar2 = 3.999;
150                 
151                 /**
152                  * This field demonstrates how the parser can detect arrays and build a bag of values.
153                  */
154                 @XACMLAttribute(category="foo:bar:category", attributeId="foo:bar:attribute:many")
155                 URI[]           fooBarMany = new URI[] {URI.create("file://opt/app/test"), URI.create("https://localhost:8443/")};
156                 
157         };
158
159         @XACMLRequest(
160                 Defaults="http://www.w3.org/TR/1999/Rec-xpath-19991116",
161                 multiRequest=@XACMLMultiRequest(values={
162                         @XACMLRequestReference(values={"subject1", "action", "resource"}),
163                         @XACMLRequestReference(values={"subject2", "action", "resource"})})
164         )
165         public class MyMultiRequestAttributes {
166                 
167                 @XACMLSubject(id="subject1")
168                 String  userID1 = "John";
169                 
170                 @XACMLSubject(id="subject2")
171                 String  userID2 = "Ringo";
172
173                 @XACMLAction(id="action")
174                 String  action = "access";
175
176                 @XACMLResource(id="resource")
177                 String  resource = "www.mywebsite.com";
178         }
179
180         public TestAnnotation(String[] args) throws MalformedURLException, ParseException, HelpException {
181                 super(args);
182         }
183
184         @Override
185         public void run() throws IOException, FactoryException {
186                 //
187                 // We are not going to iterate any existing request files. So we will override
188                 // any TestBase code that assumes there are request files present.
189                 //
190                 //
191                 // Configure ourselves
192                 //
193                 this.configure();
194                 //
195                 // Cycle through creating a few objects
196                 //
197                 this.num = 0;
198                 this.doRequest(new MyRequestAttributes("John", "access", "www.mywebsite.com"));
199                 this.num++;
200                 this.doRequest(new MyRequestAttributes("Ringo", "access", "www.mywebsite.com"));
201                 this.num++;
202                 this.doRequest(new MyMultiRequestAttributes());
203                 this.num++;
204         }
205
206         private void doRequest(Object info) {
207                 try {
208                         Response response = this.callPDP(RequestParser.parseRequest(info));
209                         Path resultFile;
210                         if (this.output != null) {
211                                 resultFile = Paths.get(this.output.toString(), "Response." + String.format("%03d", this.num) + ".json");
212                         } else {
213                                 resultFile = Paths.get(this.directory, "results", "Response." + String.format("%03d", this.num) + ".json");
214                         }
215                         //
216                         // Write the response to the result file
217                         //
218                         logger.info("Response is: " + response.toString());
219                         if (resultFile != null) {
220                                 Files.write(resultFile, response.toString().getBytes());
221                         }
222                 } catch (IllegalArgumentException | IllegalAccessException | DataTypeException | IOException e) {
223                         logger.error(e);
224                         e.printStackTrace();
225                 }
226         }
227         
228         public static void main(String[] args) {
229                 try {
230                         new TestAnnotation(args).run();
231                 } catch (ParseException | IOException | FactoryException e) {
232                         logger.error(e);
233                 } catch (HelpException e) {
234                         //
235                         // ignore this, its thrown just to exit the application
236                         // after dumping help to stdout.
237                         //
238                 }               
239         }
240 }