View Javadoc
1   /*
2    * Copyright (c) 2002-2023, City of Paris
3    * All rights reserved.
4    *
5    * Redistribution and use in source and binary forms, with or without
6    * modification, are permitted provided that the following conditions
7    * are met:
8    *
9    *  1. Redistributions of source code must retain the above copyright notice
10   *     and the following disclaimer.
11   *
12   *  2. Redistributions in binary form must reproduce the above copyright notice
13   *     and the following disclaimer in the documentation and/or other materials
14   *     provided with the distribution.
15   *
16   *  3. Neither the name of 'Mairie de Paris' nor 'Lutece' nor the names of its
17   *     contributors may be used to endorse or promote products derived from
18   *     this software without specific prior written permission.
19   *
20   * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
21   * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
22   * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
23   * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR CONTRIBUTORS BE
24   * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
25   * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
26   * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
27   * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
28   * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
29   * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
30   * POSSIBILITY OF SUCH DAMAGE.
31   *
32   * License 1.0
33   */
34  package fr.paris.lutece.plugins.geocode.v1.web.rs.service;
35  
36  import com.fasterxml.jackson.core.JsonProcessingException;
37  import com.fasterxml.jackson.databind.JsonNode;
38  import com.fasterxml.jackson.databind.ObjectMapper;
39  import org.apache.commons.lang3.StringUtils;
40  import org.apache.log4j.Logger;
41  
42  import javax.ws.rs.core.HttpHeaders;
43  import javax.ws.rs.core.MediaType;
44  import java.util.HashMap;
45  import java.util.Map;
46  
47  /**
48   * IdentityRestClientService
49   */
50  public final class HttpApiManagerAccessTransport extends HttpAccessTransport
51  {
52      /** The Constant PARAMS_ACCES_TOKEN. */
53      private static final String PARAMS_ACCES_TOKEN = "access_token";
54      private static final String TYPE_AUTHENTIFICATION_BASIC = "Basic";
55      private static final String TYPE_AUTHENTIFICATION_BEARER = "Bearer";
56  
57      /** The Constant PARAMS_GRANT_TYPE. */
58      private static final String PARAMS_GRANT_TYPE = "grant_type";
59  
60      /** The Constant PARAMS_GRANT_TYPE_VALUE. */
61      private static final String PARAMS_GRANT_TYPE_VALUE = "client_credentials";
62  
63      private static Logger _logger = Logger.getLogger( HttpApiManagerAccessTransport.class );
64      private static final ObjectMapper _objectMapper = new ObjectMapper( );
65  
66      /** URL for REST service apiManager */
67      private String _strAccessManagerEndPointUrl;
68      private String _strAccessManagerCredentials;
69  
70      /**
71       * setter of apiManagerEndPoint
72       * 
73       * @param strApiManagerEndPoint
74       *            value to use
75       */
76      public void setAccessManagerEndPointUrl( String strApiManagerEndPoint )
77      {
78          this._strAccessManagerEndPointUrl = strApiManagerEndPoint;
79      }
80  
81      /**
82       * Sets the API Manager credentials
83       * 
84       * @param strCredentials
85       *            the API Manager credentials
86       */
87      public void setAccessManagerCredentials( String strCredentials )
88      {
89          this._strAccessManagerCredentials = strCredentials;
90      }
91  
92      /**
93       * Gets the security token from API Manager
94       * 
95       * @return the token
96       * @throws IdentityStoreException
97       */
98      private String getToken( ) throws Exception
99      {
100         String strToken = StringUtils.EMPTY;
101 
102         _logger.debug( "AccessManager Rest Transport getToken with URL_TOKEN property [" + _strAccessManagerEndPointUrl + "]" );
103 
104         Map<String, String> mapHeadersRequest = new HashMap<String, String>( );
105         Map<String, String> mapParams = new HashMap<String, String>( );
106 
107         mapParams.put( PARAMS_GRANT_TYPE, PARAMS_GRANT_TYPE_VALUE );
108 
109         mapHeadersRequest.put( HttpHeaders.ACCEPT, MediaType.APPLICATION_JSON );
110         mapHeadersRequest.put( HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_FORM_URLENCODED );
111         mapHeadersRequest.put( HttpHeaders.AUTHORIZATION, TYPE_AUTHENTIFICATION_BASIC + " " + _strAccessManagerCredentials );
112 
113         final Map<String, String> mapHeadersResponse = new HashMap<>( );
114         String strOutput = StringUtils.EMPTY;
115 
116         try
117         {
118             strOutput = this._httpClient.doPost( _strAccessManagerEndPointUrl, mapParams, null, null, mapHeadersRequest, mapHeadersResponse );
119         }
120         catch( Exception e )
121         {
122         	String strError = "API GEOCODE - Error get token '" + strOutput + "' : ";
123             _logger.error( strError + e.getMessage( ), e );
124         }
125 
126         JsonNode strResponseApiManagerJsonObject = null;
127 
128         try
129         {
130             strResponseApiManagerJsonObject = _objectMapper.readTree( strOutput );
131 
132             if ( ( strResponseApiManagerJsonObject != null ) && strResponseApiManagerJsonObject.has( PARAMS_ACCES_TOKEN ) )
133             {
134                 strToken = strResponseApiManagerJsonObject.get( PARAMS_ACCES_TOKEN ).asText( );
135             }
136         }
137         catch( JsonProcessingException e )
138         {
139             _logger.debug( "ApiManagerRest.getToken invalid response [" + strOutput + "]" );
140         }
141 
142         return strToken;
143     }
144 
145     /**
146      * {@inheritDoc}
147      * 
148      * @throws IdentityStoreException
149      */
150     @Override
151     protected void addAuthentication( Map<String, String> mapHeadersRequest ) throws Exception
152     {
153         String strToken = getToken( );
154 
155         if ( StringUtils.isNotBlank( strToken ) )
156         {
157             mapHeadersRequest.put( HttpHeaders.AUTHORIZATION, TYPE_AUTHENTIFICATION_BEARER + " " + strToken );
158         }
159     }
160 }