View Javadoc
1   /*******************************************************************************
2    * Copyright 2016 Internet2
3    * 
4    * Licensed under the Apache License, Version 2.0 (the "License");
5    * you may not use this file except in compliance with the License.
6    * You may obtain a copy of the License at
7    * 
8    *   http://www.apache.org/licenses/LICENSE-2.0
9    * 
10   * Unless required by applicable law or agreed to in writing, software
11   * distributed under the License is distributed on an "AS IS" BASIS,
12   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13   * See the License for the specific language governing permissions and
14   * limitations under the License.
15   ******************************************************************************/
16  package edu.internet2.middleware.grouper.ws.samples.rest.attribute;
17  
18  import org.apache.commons.httpclient.Credentials;
19  import org.apache.commons.httpclient.DefaultHttpMethodRetryHandler;
20  import org.apache.commons.httpclient.Header;
21  import org.apache.commons.httpclient.HttpClient;
22  import org.apache.commons.httpclient.UsernamePasswordCredentials;
23  import org.apache.commons.httpclient.auth.AuthScope;
24  import org.apache.commons.httpclient.methods.PostMethod;
25  import org.apache.commons.httpclient.methods.StringRequestEntity;
26  import org.apache.commons.httpclient.params.DefaultHttpParams;
27  import org.apache.commons.httpclient.params.HttpMethodParams;
28  import org.apache.commons.lang.StringUtils;
29  
30  import edu.internet2.middleware.grouper.ws.coresoap.WsFindAttributeDefsResults;
31  import edu.internet2.middleware.grouper.ws.rest.WsRestResultProblem;
32  import edu.internet2.middleware.grouper.ws.rest.attribute.WsRestFindAttributeDefsLiteRequest;
33  import edu.internet2.middleware.grouper.ws.samples.types.WsSampleRest;
34  import edu.internet2.middleware.grouper.ws.samples.types.WsSampleRestType;
35  import edu.internet2.middleware.grouper.ws.util.RestClientSettings;
36  
37  /**
38   * @author vsachdeva
39   */
40  public class WsSampleFindAttributeDefsRestLite implements WsSampleRest {
41  
42    /**
43     * find groups lite web service with REST
44     * @param wsSampleRestType is the type of rest (xml, xhtml, etc)
45     */
46    public static void findAttributeDefsLite(WsSampleRestType wsSampleRestType) {
47  
48      try {
49        HttpClient httpClient = new HttpClient();
50        
51        DefaultHttpParams.getDefaultParams().setParameter(
52            HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler(0, false));
53  
54        //URL e.g. http://localhost:8093/grouper-ws/servicesRest/v1_3_000/...
55        //NOTE: aStem:aAttributeDefName urlencoded substitutes %3A for a colon
56        PostMethod method = new PostMethod(
57            RestClientSettings.URL + "/" + RestClientSettings.VERSION  
58              + "/attributeDefs");
59        
60        httpClient.getParams().setAuthenticationPreemptive(true);
61        Credentials defaultcreds = new UsernamePasswordCredentials(RestClientSettings.USER, 
62            RestClientSettings.PASS);
63        
64        //no keep alive so response if easier to indent for tests
65        method.setRequestHeader("Connection", "close");
66        
67        //e.g. localhost and 8093
68        httpClient.getState()
69            .setCredentials(new AuthScope(RestClientSettings.HOST, RestClientSettings.PORT), defaultcreds);
70  
71        //Make the body of the request, in this case with beans and marshaling, but you can make
72        //your request document in whatever language or way you want
73        WsRestFindAttributeDefsLiteRequest findAttributeDefsLite = new WsRestFindAttributeDefsLiteRequest();
74  
75        findAttributeDefsLite.setScope("test:");
76        findAttributeDefsLite.setNameOfAttributeDef("test1:testAttributeDef_xhtml");
77              
78        //get the xml / json / xhtml / paramString
79        String requestDocument = wsSampleRestType.getWsLiteRequestContentType().writeString(findAttributeDefsLite);
80        
81        //make sure right content type is in request (e.g. application/xhtml+xml
82        String contentType = wsSampleRestType.getWsLiteRequestContentType().getContentType();
83        
84        method.setRequestEntity(new StringRequestEntity(requestDocument, contentType, "UTF-8"));
85        
86        httpClient.executeMethod(method);
87  
88        //make sure a request came back
89        Header successHeader = method.getResponseHeader("X-Grouper-success");
90        String successString = successHeader == null ? null : successHeader.getValue();
91        if (StringUtils.isBlank(successString)) {
92          throw new RuntimeException("Web service did not even respond!");
93        }
94        boolean success = "T".equals(successString);
95        String resultCode = method.getResponseHeader("X-Grouper-resultCode").getValue();
96        
97        String response = RestClientSettings.responseBodyAsString(method);
98  
99        Object resultObject = wsSampleRestType.getWsLiteResponseContentType().parseString(response);
100     
101       //see if problem
102       if (resultObject instanceof WsRestResultProblem) {
103         throw new RuntimeException(((WsRestResultProblem)resultObject).getResultMetadata().getResultMessage());
104       }
105 
106       //convert to object (from xhtml, xml, json, etc)
107       WsFindAttributeDefsResults wsFindAttributeDefsResults = (WsFindAttributeDefsResults)resultObject;
108       
109       String resultMessage = wsFindAttributeDefsResults.getResultMetadata().getResultMessage();
110 
111       // see if request worked or not
112       if (!success) {
113         throw new RuntimeException("Bad response from web service: resultCode: " + resultCode
114             + ", " + resultMessage);
115       }
116       
117       System.out.println("Server version: " + wsFindAttributeDefsResults.getResponseMetadata().getServerVersion()
118           + ", result code: " + resultCode
119           + ", result message: " + resultMessage );
120 
121     } catch (Exception e) {
122       throw new RuntimeException(e);
123     }
124 
125   }
126 
127   /**
128    * @param args
129    */
130   public static void main(String[] args) {
131     findAttributeDefsLite(WsSampleRestType.xhtml);
132   }
133 
134   /**
135    * @see edu.internet2.middleware.grouper.ws.samples.types.WsSampleRest#executeSample(edu.internet2.middleware.grouper.ws.samples.types.WsSampleRestType)
136    */
137   @Override
138   public void executeSample(WsSampleRestType wsSampleRestType) {
139     findAttributeDefsLite(wsSampleRestType);
140   }
141 
142   /**
143    * @see edu.internet2.middleware.grouper.ws.samples.types.WsSampleRest#validType(edu.internet2.middleware.grouper.ws.samples.types.WsSampleRestType)
144    */
145   @Override
146   public boolean validType(WsSampleRestType wsSampleRestType) {
147     //allow all
148     return true;
149   }
150 }