View Javadoc
1   /*
2    * Copyright (c) 2002-2016, Mairie de 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.mydashboard.modules.identity.util;
35  
36  import java.util.ArrayList;
37  import java.util.Arrays;
38  import java.util.Date;
39  import java.util.HashMap;
40  import java.util.List;
41  import java.util.Map;
42  import java.util.Optional;
43  import java.util.Map.Entry;
44  
45  import javax.servlet.http.HttpServletRequest;
46  
47  import org.apache.commons.lang3.StringUtils;
48  
49  import com.fasterxml.jackson.core.JsonProcessingException;
50  import com.fasterxml.jackson.databind.DeserializationFeature;
51  import com.fasterxml.jackson.databind.ObjectMapper;
52  
53  import fr.paris.lutece.plugins.identitystore.v3.web.rs.dto.common.AttributeDto;
54  import fr.paris.lutece.plugins.identitystore.v3.web.rs.dto.common.AuthorType;
55  import fr.paris.lutece.plugins.identitystore.v3.web.rs.dto.common.IdentityDto;
56  import fr.paris.lutece.plugins.identitystore.v3.web.rs.dto.common.RequestAuthor;
57  import fr.paris.lutece.plugins.identitystore.v3.web.rs.dto.common.ResponseStatusType;
58  import fr.paris.lutece.plugins.identitystore.v3.web.rs.dto.contract.AttributeDefinitionDto;
59  import fr.paris.lutece.plugins.identitystore.v3.web.rs.dto.contract.ServiceContractSearchResponse;
60  import fr.paris.lutece.plugins.identitystore.v3.web.rs.dto.crud.IdentityChangeRequest;
61  import fr.paris.lutece.plugins.identitystore.v3.web.rs.dto.crud.IdentityChangeResponse;
62  import fr.paris.lutece.plugins.identitystore.v3.web.rs.dto.search.IdentitySearchResponse;
63  import fr.paris.lutece.plugins.identitystore.v3.web.service.IdentityService;
64  import fr.paris.lutece.plugins.identitystore.web.exception.IdentityNotFoundException;
65  import fr.paris.lutece.plugins.identitystore.web.exception.IdentityStoreException;
66  import fr.paris.lutece.plugins.mydashboard.modules.identity.business.AttributeCategory;
67  import fr.paris.lutece.plugins.mydashboard.modules.identity.business.DashboardAttribute;
68  import fr.paris.lutece.plugins.mydashboard.modules.identity.business.DashboardIdentity;
69  import fr.paris.lutece.portal.service.security.UserNotSignedException;
70  import fr.paris.lutece.portal.service.spring.SpringContextService;
71  import fr.paris.lutece.portal.service.util.AppException;
72  import fr.paris.lutece.portal.service.util.AppLogService;
73  import fr.paris.lutece.portal.service.util.AppPropertiesService;
74  import fr.paris.lutece.util.ReferenceItem;
75  import fr.paris.lutece.util.ReferenceList;
76  import fr.paris.lutece.util.url.UrlItem;
77  
78  
79  /**
80   *
81   * class to help managing identity feature
82   *
83   */
84  public class DashboardIdentityUtils
85  {
86      private static DashboardIdentityUtils _instance;   
87      private static final String BEAN_IDENTITYSTORE_SERVICE = "mydashboard-identity.identitystore.service";
88      //For matching on DBAttributes and Identity store attributes
89      private static Map<String,String> _mapAttributeKeyMatch;
90      private static  Map<String,String> _mapAttributeKeyMatchIdentityInformations;
91      private static  Map<String,String> _mapAttributeKeyMatchCoordinates;
92      private static ObjectMapper _mapper;
93      static
94      {
95          _mapper = new ObjectMapper( );
96          _mapper.disable( DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES );
97      }
98  
99      
100     
101     private IdentityService _identityService;
102     public static final String DASHBOARD_APP_CODE = AppPropertiesService.getProperty( Constants.PROPERTY_APPLICATION_CODE );
103     static {
104         _mapAttributeKeyMatch = new HashMap<String,String>( );
105         _mapAttributeKeyMatchIdentityInformations= new HashMap<String, String>();
106         _mapAttributeKeyMatchCoordinates= new HashMap<String, String>();
107          //Identity Informations          
108         _mapAttributeKeyMatchIdentityInformations.put(Constants.ATTRIBUTE_DB_IDENTITY_LAST_NAME, Constants.PROPERTY_KEY_NAME );
109         _mapAttributeKeyMatchIdentityInformations.put(Constants.ATTRIBUTE_DB_IDENTITY_PREFERRED_USER_NAME, Constants.PROPERTY_KEY_PREFERREDUSERNAME );
110         _mapAttributeKeyMatchIdentityInformations.put(Constants.ATTRIBUTE_DB_IDENTITY_FIRSTNAME, Constants.PROPERTY_KEY_FIRSTNAME );
111         _mapAttributeKeyMatchIdentityInformations.put(Constants.ATTRIBUTE_DB_IDENTITY_GENDER, Constants.PROPERTY_KEY_GENDER );
112         _mapAttributeKeyMatchIdentityInformations.put(Constants.ATTRIBUTE_DB_IDENTITY_BIRTHDATE, Constants.PROPERTY_KEY_BIRTHDATE );
113         _mapAttributeKeyMatchIdentityInformations.put(Constants.ATTRIBUTE_DB_IDENTITY_BIRTHPLACE, Constants.PROPERTY_KEY_BIRTHPLACE );
114         _mapAttributeKeyMatchIdentityInformations.put(Constants.ATTRIBUTE_DB_IDENTITY_BIRTHCOUNTRY, Constants.PROPERTY_KEY_BIRTHCOUNTRY );
115          _mapAttributeKeyMatchIdentityInformations.put(Constants.ATTRIBUTE_DB_IDENTITY_BIRTHPLACE_CODE, Constants.PROPERTY_KEY_BIRTHPLACE_CODE );
116         _mapAttributeKeyMatchIdentityInformations.put(Constants.ATTRIBUTE_DB_IDENTITY_BIRTHCOUNTRY_CODE, Constants.PROPERTY_KEY_BIRTHCOUNTRY_CODE );
117         //Coordinates Informations
118         _mapAttributeKeyMatchCoordinates.put(Constants.ATTRIBUTE_DB_IDENTITY_ADDRESS, Constants.PROPERTY_KEY_ADDRESS );
119         _mapAttributeKeyMatchCoordinates.put(Constants.ATTRIBUTE_DB_IDENTITY_ADDRESS_DETAIL, Constants.PROPERTY_KEY_ADDRESSDETAIL );
120         _mapAttributeKeyMatchCoordinates.put(Constants.ATTRIBUTE_DB_IDENTITY_ADDRESS_POSTAL_CODE, Constants.PROPERTY_KEY_ADDRESS_POSTAL_CODE );
121         _mapAttributeKeyMatchCoordinates.put(Constants.ATTRIBUTE_DB_IDENTITY_ADDRESS_CITY, Constants.PROPERTY_KEY_ADDRESS_CITY );
122         _mapAttributeKeyMatchCoordinates.put(Constants.ATTRIBUTE_DB_IDENTITY_PHONE, Constants.PROPERTY_KEY_PHONE );
123         _mapAttributeKeyMatchCoordinates.put(Constants.ATTRIBUTE_DB_IDENTITY_MOBILE_PHONE, Constants.PROPERTY_KEY_MOBILE_PHONE );
124         _mapAttributeKeyMatchCoordinates.put(Constants.ATTRIBUTE_DB_IDENTITY_EMAIL, Constants.PROPERTY_KEY_EMAIL );
125         
126         _mapAttributeKeyMatch.putAll(_mapAttributeKeyMatchIdentityInformations);
127         _mapAttributeKeyMatch.putAll(_mapAttributeKeyMatchCoordinates);
128         
129         _mapAttributeKeyMatch.put(Constants.ATTRIBUTE_DB_IDENTITY_LOGIN, Constants.PROPERTY_KEY_LOGIN );
130         
131     }
132     private static ReferenceList _lstContactModeList;
133     private static ReferenceList _lstGenderList;
134     private static final String SPLIT_PATTERN = ";";
135     private static final String SESSION_DASHBOARD_IDENTITY = "dashboardIdentity";
136     private static final String SESSION_REDIRECT_URL = "redirectUrl";
137     public static final String SESSION_ERROR_MESSAGE = "errorMessage";
138     public static final String SESSION_INFO_MESSAGE = "infoMessage";
139     public static final String SESSION_SN_NAME = "serviceNumericName";
140     
141     /**
142      * private constructor for singleton
143      */
144     private DashboardIdentityUtils(  )
145     {
146     }
147     
148     public static DashboardIdentityUtils getInstance( )
149     {
150         if ( _instance == null )
151         {
152             _instance = new DashboardIdentityUtils( );
153             _instance._identityService = SpringContextService.getBean( BEAN_IDENTITYSTORE_SERVICE );
154             _lstGenderList = new ReferenceList( );
155 
156             int i = 0;
157 
158             for ( String sItem : Constants.PROPERTY_KEY_GENDER_LIST.split( SPLIT_PATTERN ) )
159             {
160                 ReferenceItem refItm = new ReferenceItem( );
161                 refItm.setName( sItem );
162                 refItm.setCode( String.valueOf( i ) );
163                 _lstGenderList.add( refItm );
164                 i++;
165             }
166 
167             _lstContactModeList = new ReferenceList( );
168 
169             for ( String sItem : Constants.PROPERTY_KEY_CONTACT_MODE_LIST.split( SPLIT_PATTERN ) )
170             {
171                 ReferenceItem refItm = new ReferenceItem( );
172                 refItm.setName( sItem );
173                 refItm.setCode( sItem );
174                 _lstContactModeList.add( refItm );
175             }
176         }
177             return _instance;
178     }
179     
180     
181     
182     
183     /**
184      * return an dashboardIdentity from a identityDto
185      *
186      * @param identitySearchResponse
187      *          identitySearchResponse to convert
188      * @return dashboardIdentity initialized from provided identityDto
189      */
190     public DashboardIdentity convertToDashboardIdentity( IdentityDto identity )
191     {     
192     	return convertToDashboardIdentity( identity, null);
193     }
194     
195    
196     
197     
198 
199     /**
200      * return an dashboardIdentity from a identityDto
201      *
202      * @param identity
203      *          identityDto to convert
204      *          
205      * @param  contractSearchResponse The App contract        
206      * @return dashboardIdentity initialized from provided identityDto
207      */
208     public DashboardIdentity convertToDashboardIdentity( IdentityDto identity, ServiceContractSearchResponse contractSearchResponse )
209     {
210         DashboardIdentitydules/identity/business/DashboardIdentity.html#DashboardIdentity">DashboardIdentity dashboardIdentity = new DashboardIdentity(  );
211        
212         
213         if(identity!=null)
214         {
215         	dashboardIdentity.setLastUpdateDate(identity.getLastUpdateDate());
216         	
217         	dashboardIdentity.setConnectionId( new DashboardAttribute( 
218                 Constants.ATTRIBUTE_DB_IDENTITY_CONNECTION_ID, 
219                 identity.getConnectionId( ) ) );
220         
221         
222         	dashboardIdentity.setCustomerId( new DashboardAttribute(
223                 Constants.ATTRIBUTE_DB_IDENTITY_CUSTOMER_ID,
224                 identity.getCustomerId( ) ) );
225         	dashboardIdentity.setCoverage( identity.getQuality() != null ? identity.getQuality().getCoverage() : 0);
226         	
227         }
228         
229         
230         for ( Map.Entry<String,String> attributeMatch : _mapAttributeKeyMatch.entrySet( ) )
231         {
232             dashboardIdentity.setAttribute( 
233                     attributeMatch.getKey( ), 
234                     getDashboardAttributeFromAttributeDtoKey (
235                     		identity, 
236                         attributeMatch.getValue( ), 
237                         attributeMatch.getKey( ),contractSearchResponse ) 
238                     ) ;
239         }
240 
241         return dashboardIdentity;
242         
243     }
244     
245     public boolean needCertification( DashboardIdentity dashboardIdentity, ServiceContractSearchResponse contractSearchResponse, List<String> strAttributesNeedFC, int nLevelMin)
246     {
247         
248         for( String attributeKey : strAttributesNeedFC )
249         {
250            String strValueAttribute =  _mapAttributeKeyMatch.get( attributeKey );
251            
252            if( StringUtils.isNotEmpty( strValueAttribute ) )
253            {
254                DashboardAttribute attribute = dashboardIdentity.getAttribute( attributeKey );
255                Optional<AttributeDefinitionDto> optionalContract = contractSearchResponse.getServiceContract( ).getAttributeDefinitions( )
256                        .stream( ).filter( e -> e.getKeyName( ).equals( strValueAttribute ) ).findFirst( );
257                
258                if ( optionalContract.isPresent( ) && optionalContract.get( ).getAttributeRequirement( ) != null 
259                        && attribute.getCertifierLevel( ) < Integer.valueOf( optionalContract.get( ).getAttributeRequirement( ).getLevel( ) ) 
260                            && Integer.valueOf( optionalContract.get( ).getAttributeRequirement( ).getLevel( ) ) >= nLevelMin )
261                {
262                    return true;
263                }
264            }
265         }
266     	return false;
267     }
268     
269     
270     
271 
272     
273 
274     /**
275      * return an identityDto from a DashboardIdentity
276      *
277      * @param dashboardIdentity
278      *          dashboardIdentity to convert
279      *  @param bOnlyMandatory true the IdentitityDTO must contains only Mandatory informations
280      * @return identityDto initialized from provided dashboardIdentity
281      */
282     public IdentityDto convertToIdentityDto( DashboardIdentity dashboardIdentity,boolean bOnlyMandatory )
283     {      
284        return convertToIdentityDto(dashboardIdentity, bOnlyMandatory,null);
285     }
286     
287     
288     /**
289      * return an identityDto from a DashboardIdentity
290      *
291      * @param dashboardIdentity
292      *          dashboardIdentity to convert
293      *  @param bOnlyMandatory true the IdentitityDTO must contains only Mandatory informations
294      *  @param attributeCategory update only attribute in this category
295      * @return identityDto initialized from provided dashboardIdentity
296      */
297     public IdentityDto convertToIdentityDto( DashboardIdentity dashboardIdentity,boolean bOnlyMandatory,AttributeCategory attributeCategory )
298     {      
299         IdentityDto identity = new IdentityDto( ); 
300         
301         identity.setLastUpdateDate(dashboardIdentity.getLastUpdateDate());
302         identity.setConnectionId(dashboardIdentity.getConnectionId(  )!=null?  dashboardIdentity.getConnectionId(  ).getValue( ):null );
303         identity.setCustomerId( dashboardIdentity.getCustomerId(  )!=null? dashboardIdentity.getCustomerId(  ).getValue( ):null );
304         
305         List<AttributeDto> listCertifiedAttribute = new ArrayList< >( );
306         
307         DashboardIdentity dashboardIdentityFromRic = convertToDashboardIdentity( getIdentity( identity.getConnectionId( ) ) );
308         
309         for ( Map.Entry<String,String> attributeMatch : getMapAttributeKey(attributeCategory).entrySet( ) )
310         {
311             DashboardAttribute dashboardAttribute = dashboardIdentity.getAttribute( attributeMatch.getKey( ) );
312             if ( dashboardIdentityFromRic == null )
313             {
314                 if ( !bOnlyMandatory || dashboardAttribute.isMandatory( ) )
315                 {
316                     listCertifiedAttribute.add( getCertifiedAttribute( dashboardAttribute, attributeMatch.getValue( ) ) );
317                 }
318             }
319             else if ( ( !bOnlyMandatory || dashboardAttribute.isMandatory( ) ) && hasChanged( dashboardAttribute, dashboardIdentityFromRic.getAttribute( attributeMatch.getKey( ) ) ) )
320             {
321                 listCertifiedAttribute.add( getCertifiedAttribute( dashboardAttribute, attributeMatch.getValue( ) ) );
322             }
323         }
324         identity.setAttributes( listCertifiedAttribute );
325         
326 
327 
328         return identity;
329     }
330     
331     /**
332      * 
333      * @param dashboardAttribute
334      * @param attributeValue
335      * @return the certifiedAttribute
336      */
337     private AttributeDto getCertifiedAttribute( DashboardAttribute dashboardAttribute, String attributeValue )
338     {
339         AttributeDto certifiedAttribute = new AttributeDto(  );
340         certifiedAttribute.setKey( attributeValue );
341         certifiedAttribute.setValue( dashboardAttribute.getValue( ) );
342         certifiedAttribute.setCertifier( dashboardAttribute.getCertifierCode( ) );
343         certifiedAttribute.setCertificationDate( new Date() );
344         certifiedAttribute.setCertificationLevel(dashboardAttribute.getCertifierLevel());
345         
346         return certifiedAttribute;
347     }
348     
349     /**
350      * 
351      * @param newAttribute the new dashboard attribute submitted
352      * @param oldAttribute the old dashboard attribute saved
353      * @return true if the two attributes are different
354      */
355     private boolean hasChanged( DashboardAttribute./../../fr/paris/lutece/plugins/mydashboard/modules/identity/business/DashboardAttribute.html#DashboardAttribute">DashboardAttribute newAttribute, DashboardAttribute oldAttribute )
356     {
357         return ( newAttribute.getValue( ) != null && !newAttribute.getValue( ).equals( oldAttribute.getValue( ) ) )
358                 || ( newAttribute.getCertifierCode( ) != null && !newAttribute.getCertifierCode( ).equals( oldAttribute.getCertifierCode( ) ) )
359                 || ( newAttribute.getCertificateDate( ) != null && oldAttribute.getCertificateDate( ) != null && !newAttribute.getCertificateDate( ).equals( oldAttribute.getCertificateDate( ) ) );
360     }
361     
362     /**
363      * Get DashboardAttribute From AttributeDto
364      * @param identitySearchResponse the identitySearchResponse
365      * @param identityDtoAttributeKey the identityDto attribute key
366      * @param dashboardAttributeKey the Dashboard attribute key
367      * @param contractSearchResponse the contractSearchResponse
368      * @return 
369      */
370     private DashboardAttribute getDashboardAttributeFromAttributeDtoKey ( IdentityDto identity, String identityDtoAttributeKey, String dashboardAttributeKey, ServiceContractSearchResponse contractSearchResponse )
371     {
372         
373     	
374     	Optional<AttributeDto> certifiedAttribute=null;
375     	
376     	if(identity!=null)
377     	{
378     		certifiedAttribute =
379     		   identity.getAttributes( )
380                .stream( )
381                .filter( attribute -> attribute.getKey( ).equals( identityDtoAttributeKey ) )
382                .findAny( );
383     	}
384         
385         DashboardAttribute dashboardAttribute = null;
386         if ( certifiedAttribute != null && certifiedAttribute.isPresent( ) )
387         {
388             if ( certifiedAttribute.get( ).getCertifier( ) != null )
389             {
390             	dashboardAttribute= new DashboardAttribute(
391                     dashboardAttributeKey,
392                     certifiedAttribute.get( ).getValue( ),
393                     certifiedAttribute.get( ).getCertifier( ),
394                     certifiedAttribute.get( ).getCertifier( ),
395                     certifiedAttribute.get( ).getCertificationLevel( ),
396                     null,
397                     certifiedAttribute.get( ).getCertificationDate( ) );
398             	
399             }
400             else
401             {
402             	dashboardAttribute= new DashboardAttribute(
403                     dashboardAttributeKey,
404                     certifiedAttribute.get( ).getValue( ) );
405             	
406             }
407             
408         }
409         else
410         {
411 	        dashboardAttribute= new DashboardAttribute(
412 	            dashboardAttributeKey, StringUtils.EMPTY);
413 	        
414 	        List<String> certificationProcessNotCertifiable = Arrays.asList( Constants.PROPERTY_CERTIFICATION_PROCESS_NOT_CERTIFIABLE.split( ";" ) );
415 	        if(certificationProcessNotCertifiable !=null &&  certificationProcessNotCertifiable.size()>0)
416 	        {
417 	        	dashboardAttribute.setCertifierCode(   certificationProcessNotCertifiable.get(0));  
418 	         }
419         }
420         
421         dashboardAttribute.setMandatory( isMandatoryAttribute( contractSearchResponse, identityDtoAttributeKey ) );
422         
423         return dashboardAttribute;
424     }
425     
426     /**
427      * Return true if the attribute is mandatory
428      * @param contractSearchResponse
429      * @param identityAttributeKey
430      * @return true if the attribute key is mandatory
431      */
432     public boolean isMandatoryAttribute ( ServiceContractSearchResponse contractSearchResponse, String identityAttributeKey )
433     {
434         if ( contractSearchResponse != null && contractSearchResponse.getServiceContract( ) != null 
435                 && contractSearchResponse.getServiceContract( ).getAttributeDefinitions( ) != null  )
436         {
437             return contractSearchResponse.getServiceContract( ).getAttributeDefinitions( )
438                     .stream( )
439                     .anyMatch( x -> x.getKeyName( ).equals( identityAttributeKey ) && x.getAttributeRight( ).isMandatory( ) );
440         }
441         return false;
442     }
443     
444     /**
445      * populaite DashboardIdentity from the request
446      * @param identity the DashboardIdentity
447      * @param attributeCategory only populate attribute associate to the category
448      * @param request the HttpServletRequest
449      */
450     public void populateDashboardIdentity ( DashboardIdentity identity, HttpServletRequest request,AttributeCategory attributeCategory  )
451     {
452         
453         for ( String strAttributeKey :  getMapAttributeKey(attributeCategory) .keySet( ) )
454         {
455             String attributeValue = request.getParameter( strAttributeKey );
456             if ( attributeValue != null )
457             {
458                 identity.setAttributeValue( strAttributeKey, attributeValue );
459             }
460         }
461     }
462     
463     /**
464      * Drop attributes from IdentityDto if there is a certificate. This is used to not update identity when a certificate is found.
465      * @param identity 
466      */
467     
468     public void filterByCertifier ( IdentityDto identity )
469     {
470     	
471         List<AttributeDto> listCertifiedAttribute = new ArrayList< >();
472     	if( identity != null && identity.getAttributes( ) != null )
473         {        
474             for ( AttributeDto certifiedAttribute : identity.getAttributes( ) )
475             {
476                 if ( certifiedAttribute.getCertifier() == null 
477                     ||  certifiedAttribute.getCertificationLevel() == null || certifiedAttribute.getCertificationLevel()  <= Constants.PROPERTY_CERTIFICATION_PROCESS_NOT_CERTIFIABLE_LEVEL  )
478                 {
479                     listCertifiedAttribute.add( certifiedAttribute );
480                 }
481             }
482             identity.setAttributes( listCertifiedAttribute );
483         }
484     }
485     
486    
487     
488   
489     
490     /**
491      * Gets the identity.
492      *
493      * @param strConnectionId the str connection id
494      * @return the identity
495      */
496     public IdentityDto getIdentity( String strConnectionId )
497     {
498    
499         return getIdentity(strConnectionId, DASHBOARD_APP_CODE);
500     }
501     
502     
503  /**
504   * Gets the identity.
505   *
506   * @param strConnectionId the str connection id
507   * @param strAppCode the str app code
508   * @return the identity
509   */
510     public IdentityDto getIdentity( String strConnectionId,String strAppCode )
511     {
512         IdentitySearchResponse identitySearchResponse = null;
513         IdentityDto identity=null;
514 
515         try
516         {
517             RequestAuthor requestAuthor = new RequestAuthor( );
518             requestAuthor.setName( strAppCode );
519             requestAuthor.setType( AuthorType.owner );
520             identitySearchResponse = _identityService.getIdentityByConnectionId( strConnectionId, strAppCode ,requestAuthor);
521         	if( identitySearchResponse!=null && 
522 					!ResponseStatusType.NOT_FOUND.equals(identitySearchResponse.getStatus().getType()) 
523 					&&  identitySearchResponse.getIdentities() != null 
524 					&& identitySearchResponse.getIdentities().size() > 0 )
525         	{
526                 identity=identitySearchResponse.getIdentities().get(0);   
527         	}
528         	else
529         	{
530         	    identity=new IdentityDto();
531         	    identity.setConnectionId(strConnectionId);
532         	}
533             
534         }
535         catch( IdentityStoreException | AppException infe )
536         {
537             AppLogService.error( "Identity App Exception for :" + strConnectionId, infe );
538             identity=new IdentityDto();
539     	    identity.setConnectionId(strConnectionId);
540             
541         }
542 
543         return identity;
544     }
545     
546     /**
547      * Get Identity Coverage for a connectionId and a app Coe
548      * @param strConnectionId
549      * @param strAppCode
550      * @return
551      */
552     public int getIdentityCoverage( String strConnectionId,String strAppCode )
553     {
554     	int nCoverage=0;
555     	
556     	IdentityDto identity=getIdentity(strConnectionId, strAppCode);
557     	if(identity!=null && identity.getQuality()!=null )
558     	{
559     		nCoverage= identity .getQuality().getCoverage();
560     		
561     	}
562     	return nCoverage;
563     }
564     
565     /**
566      * Update Identity from an IdentityDto.
567      *
568      * @param identityDto            identity Data transfer Object
569      * @throws IdentityNotFoundException the identity not found exception
570      * @throws AppException the app exception
571      */
572     public void updateIdentity(   IdentityDto identity )throws AppException
573     {
574         IdentityChangeRequest identityChangeRequest = buildIdentityChangeDto( identity );
575         
576         try
577         {
578             if( !StringUtils.isEmpty( identity.getCustomerId( ) ) )
579             {
580             	final IdentityChangeResponse response= _identityService.updateIdentity( identityChangeRequest.getIdentity( ).getCustomerId( ), identityChangeRequest, DASHBOARD_APP_CODE,getOwnerRequestAuthor() );
581             	if (response==null ||  (!ResponseStatusType.SUCCESS.equals(response.getStatus().getType()) && !ResponseStatusType.INCOMPLETE_SUCCESS.equals(response.getStatus().getType()))   )
582           	  {
583           		  AppLogService.error( "Error when  updating the identity for connectionId {} the identity change status is {}, the json identity response is {} ", identity.getConnectionId( ), response!=null? response.getStatus().getMessage():"",printJsonObjectAsString(response));
584           		  
585           		  throw new IdentityStoreException(response==null ? "":response.getStatus().getType().name());
586           	  }
587             }
588             else
589             {
590             	final IdentityChangeResponse response=_identityService.createIdentity( identityChangeRequest, DASHBOARD_APP_CODE ,getOwnerRequestAuthor());
591             	  if (response==null || !ResponseStatusType.SUCCESS.equals( response.getStatus().getType()  ))
592             	  {
593             		  AppLogService.error( "Error when creating  the identity for connectionId {} the identity change status is {} , the json identity response is {}", identity.getConnectionId( ), response!=null? response.getStatus().getMessage():"",printJsonObjectAsString(response));
594             		  
595             		  throw new IdentityStoreException(response==null ? "":response.getStatus().getType().name());
596             	  }
597             	
598             }
599         } catch ( AppException | IdentityStoreException e )
600         {
601             AppLogService.error( "Error when creating or updating the identity for connectionId {}", identity.getConnectionId( ),e );
602         }
603         	
604     }
605     
606     /**
607      * build a changeDto from Identity.
608      *
609      * @param identity            identity to update
610      * @return IdentityChangeDto
611      */
612     private IdentityChangeRequest buildIdentityChangeDto(  IdentityDto identity)
613     {
614         IdentityChangeRequest identityChangeRequest = new IdentityChangeRequest( );
615                 
616         identityChangeRequest.setIdentity( identity );
617 
618         return identityChangeRequest;
619     }
620     
621     
622     /**
623      * Gets the owner request author.
624      *
625      * @return the owner request author
626      */
627     public RequestAuthor getOwnerRequestAuthor()
628     {
629     
630 	    RequestAuthor requestAuthor = new RequestAuthor( );
631 	    requestAuthor.setName( DASHBOARD_APP_CODE );
632 	    requestAuthor.setType( AuthorType.owner );
633 	    
634 	    return requestAuthor;
635     }
636     
637     /**
638      * 
639      * @return
640      */
641     public Map<String,String> getMapAttributeKeyMatch ( )
642     {
643         return _mapAttributeKeyMatch;
644     }
645     
646     /**
647      * 
648      * @param request
649      * @return
650      */
651     public DashboardIdentity getCurrentDashboardIdentityInSession( HttpServletRequest request )
652     {
653         return ( DashboardIdentity ) request.getSession( ).getAttribute( SESSION_DASHBOARD_IDENTITY );
654     }
655 	
656     /**
657      * 
658      * @param request
659      * @param dashboardIdentity
660      */
661     public void setCurrentDashboardIdentityInSession ( HttpServletRequest request, DashboardIdentity dashboardIdentity )
662     {
663         if( dashboardIdentity != null )
664         {
665             request.getSession( ).setAttribute( SESSION_DASHBOARD_IDENTITY, dashboardIdentity );
666         }
667         else
668         {
669             request.getSession( ).removeAttribute( SESSION_DASHBOARD_IDENTITY );
670         }
671     }
672     
673     /**
674      * 
675      * @param request
676      * @return
677      */
678     public String getRedirectUrlAfterCompletionInSession ( HttpServletRequest request )
679     {
680         return ( String ) request.getSession( ).getAttribute( SESSION_REDIRECT_URL );
681     }
682     
683     /**
684      * 
685      * @param strRedirectXPage
686      * @param request
687      */
688     public void setRedirectUrlAfterCompletionInSession ( String strPage, String strView , HttpServletRequest request)
689     {
690         if( StringUtils.isNotEmpty( strPage ) && StringUtils.isNotEmpty( strView ) )
691         {
692             UrlItem url = new UrlItem( "Portal.jsp?page=" + strPage + "&view=" + strView );
693             
694             request.getSession( ).setAttribute( SESSION_REDIRECT_URL, url.getUrl( ) );
695         }
696     }
697     
698     /**
699      * Get name of numeric service in the session
700      * @param request
701      * @return the name of numeric service in the session
702      */
703     public String getNumericServiceNameInSession ( HttpServletRequest request  )
704     {
705         return ( String ) request.getSession( ).getAttribute( SESSION_SN_NAME );
706     }
707     
708     /**
709      * Set Numeric service name in session
710      * @param strServiceNumericName
711      * @param request
712      */
713     public void setNumericServiceNameInSession ( String strServiceNumericName, HttpServletRequest request )
714     {
715         if( StringUtils.isNotEmpty( strServiceNumericName ) )
716         {
717             request.getSession( ).setAttribute( SESSION_SN_NAME, strServiceNumericName );
718         }
719     }
720     
721     
722     /**
723      * Get message in the session
724      * @param bErrorMessage ( set true if is a error message and false if is a info message )
725      * @param bRemoveAttribute
726      * @param request
727      * @param request
728      * @return the message in session
729      */
730     public String getMessageInSession ( boolean bErrorMessage, boolean bRemoveAttribute, HttpServletRequest request )
731     {
732         String strAttributeName = bErrorMessage ? SESSION_ERROR_MESSAGE : SESSION_INFO_MESSAGE;
733              
734         String strMessage = ( String ) request.getSession( ).getAttribute( strAttributeName );
735         
736         if( bRemoveAttribute )
737         {
738             request.getSession( ).removeAttribute( strAttributeName );
739         }
740         
741         return strMessage;
742     }
743     
744     /**
745      * Set message in the session
746      * @param strMessage
747      * @param bErrorMessage ( set true if is a error message and false if is a info message )
748      * @param request
749      */
750     public void setMessageInSession ( String strMessage, boolean bErrorMessage, HttpServletRequest request )
751     {
752         if( StringUtils.isNotEmpty( strMessage ) )
753         {
754             String strAttributeName = bErrorMessage ? SESSION_ERROR_MESSAGE : SESSION_INFO_MESSAGE;
755             
756             request.getSession( ).setAttribute( strAttributeName, strMessage );
757         }
758     }
759     
760     
761     /**
762      * Gets all rules
763      * @return
764      */
765     public List<String> getAllSuspiciousIdentityRules ( )
766     {
767         List<String> listAllRules = new ArrayList< >( );
768         listAllRules.addAll( getSuspiciousIdentityStrictRules( ) );
769         listAllRules.addAll( getSuspiciousIdentityNotStrictRules( ) );
770         
771         return listAllRules;
772     }
773     
774     /**
775      * Gets strict rules
776      * @return list of strict rules
777      */
778     public List<String> getSuspiciousIdentityStrictRules ( )
779     {
780         return Arrays.asList( Constants.PROPERTY_SUSPICIOUS_LIST_RULE_STRIC.split( ";" ));
781     }
782     
783     /**
784      * Gets not strict rules
785      * @return list of not strict rules
786      */
787     public List<String> getSuspiciousIdentityNotStrictRules ( )
788     {
789         return Arrays.asList( Constants.PROPERTY_SUSPICIOUS_LIST_RULE_NOT_STRIC.split( ";" ));        
790     }
791     
792     /**
793      * Set mandatory attribute for completion identity
794      */
795     public DashboardIdentitys/mydashboard/modules/identity/business/DashboardIdentity.html#DashboardIdentity">DashboardIdentity initMandatoryAttributeForCompletionIdentity( DashboardIdentity completionIdentity, String strOriginActionCompletion )
796     {
797         for ( Map.Entry<String, String> attribute : DashboardIdentityUtils.getInstance( ).getMapAttributeKeyMatch( ).entrySet( ) )
798         {            
799             switch ( Integer.parseInt( strOriginActionCompletion ) )
800             {
801                 case Constants.ORIGIN_ACTION_CREATE_ACCOUNT  :
802                     completionIdentity.getAttribute( attribute.getKey( ) ).setMandatory( isMandatoryCompletionCreateAndCompletionAccount( attribute ) );
803                     break;
804                 case Constants.ORIGIN_ACTION_MODIFY_ACCOUNT:
805                     completionIdentity.getAttribute( attribute.getKey( ) ).setMandatory( isMandatoryCompletionModifyAccount( attribute ) );
806                     break;
807                 case Constants.ORIGIN_ACTION_COMPLETION_ACCOUNT  :
808                     completionIdentity.getAttribute( attribute.getKey( ) ).setMandatory( isMandatoryCompletionCreateAndCompletionAccount( attribute ) );
809                     break;
810                 default:
811                     break;
812             }           
813         }
814         
815         return completionIdentity;
816     }
817     
818     /**
819      * Return true if the attribute is mandatory for create account completion
820      * @param attribute
821      * @return true if the attributie is mandatory
822      */
823     public boolean isMandatoryCompletionCreateAndCompletionAccount ( Entry<String, String> attribute   )
824     {
825         return attribute.getValue( ).equals( Constants.PROPERTY_KEY_BIRTHPLACE ) 
826                 || attribute.getValue( ).equals( Constants.PROPERTY_KEY_BIRTHCOUNTRY ) ;
827 
828     }
829     
830     /**
831      * Return true if the attribute is mandatory for modify account completion
832      * @param attribute
833      * @return true if the attribute is mandatory
834      */
835     public boolean isMandatoryCompletionModifyAccount ( Entry<String, String> attribute   )
836     {
837         return attribute.getValue( ).equals( Constants.PROPERTY_KEY_BIRTHPLACE ) 
838                 || attribute.getValue( ).equals( Constants.PROPERTY_KEY_BIRTHCOUNTRY )
839                 || attribute.getValue( ).equals( Constants.PROPERTY_KEY_GENDER ) 
840                 || attribute.getValue( ).equals( Constants.PROPERTY_KEY_FIRSTNAME )
841                 || attribute.getValue( ).equals( Constants.PROPERTY_KEY_BIRTHDATE )
842                 || attribute.getValue( ).equals( Constants.PROPERTY_KEY_NAME ) ;
843     }
844     
845     /**
846      * Update dashboardIdentity in the session
847      * @param currentDasboardIdentity
848      * @param currentDasboardIdentity in session
849      */
850     public void updateDashboardIdentityInSession( DashboardIdentity/paris/lutece/plugins/mydashboard/modules/identity/business/DashboardIdentity.html#DashboardIdentity">DashboardIdentity currentDasboardIdentity, DashboardIdentity dasboardIdentitySession )
851     {
852         
853         if( currentDasboardIdentity.getGender( ) != null && StringUtils.isNotEmpty( currentDasboardIdentity.getGender( ).getValue( ) ) )
854         {
855             dasboardIdentitySession.setGender( currentDasboardIdentity.getGender( ) );
856             dasboardIdentitySession.getGender( ).setMandatory( true );
857         }
858         if( currentDasboardIdentity.getFirstname( ) != null && StringUtils.isNotEmpty( currentDasboardIdentity.getFirstname( ).getValue( ) ) )
859         {
860             dasboardIdentitySession.setFirstname( currentDasboardIdentity.getFirstname( ) );
861             dasboardIdentitySession.getFirstname( ).setMandatory( true );
862         }
863         if( currentDasboardIdentity.getLastName( ) != null && StringUtils.isNotEmpty( currentDasboardIdentity.getLastName( ).getValue( ) ) )
864         {
865             dasboardIdentitySession.setLastName( currentDasboardIdentity.getLastName( ) );
866             dasboardIdentitySession.getLastName( ).setMandatory( true );
867         }        
868         if( currentDasboardIdentity.getBirthdate( ) != null && StringUtils.isNotEmpty( currentDasboardIdentity.getBirthdate( ).getValue( ) ) )
869         {
870             dasboardIdentitySession.setBirthdate( currentDasboardIdentity.getBirthdate( ) );
871             dasboardIdentitySession.getBirthdate( ).setMandatory( true );
872         }  
873         if( currentDasboardIdentity.getPreferredUsername( ) != null && StringUtils.isNotEmpty( currentDasboardIdentity.getPreferredUsername( ).getValue( ) ) )
874         {
875             dasboardIdentitySession.setPreferredUsername( currentDasboardIdentity.getPreferredUsername( ) );
876             dasboardIdentitySession.getPreferredUsername( ).setMandatory( true );
877         }        
878         if( currentDasboardIdentity.getBirthplace( ) != null && StringUtils.isNotEmpty( currentDasboardIdentity.getBirthplace( ).getValue( ) ) )
879         {
880             dasboardIdentitySession.setBirthplace( currentDasboardIdentity.getBirthplace( ) );
881             dasboardIdentitySession.getBirthplace( ).setMandatory( true );
882         }        
883         if( currentDasboardIdentity.getBirthcountry( ) != null && StringUtils.isNotEmpty( currentDasboardIdentity.getBirthcountry( ).getValue( ) ) )
884         {
885             dasboardIdentitySession.setBirthcountry( currentDasboardIdentity.getBirthcountry( ) );
886             dasboardIdentitySession.getBirthcountry( ).setMandatory( true );
887         }
888     }
889     
890     
891     
892     /**
893      * return true if the attribute  have a level of certification > declaratif
894      * @param dashboardAttribute
895      * @return
896      */
897     public static boolean isDashboardAttributeCertified(DashboardAttribute dashboardAttribute)
898     {
899     	
900     	return dashboardAttribute.getCertifierLevel()>Constants.PROPERTY_CERTIFICATION_PROCESS_NOT_CERTIFIABLE_LEVEL;
901     	
902     }
903     
904     
905     
906     
907     /**
908      * get Map Attributes Keys
909      * @param attributeCategory the attribute Category
910      * @return Map Attributes 
911      */
912 	public Map<String, String> getMapAttributeKey(AttributeCategory attributeCategory) {
913 		if(attributeCategory!=null)
914 		{
915 			switch (attributeCategory) {
916 			case COORDINATES_INFORMATIONS:
917 				return _mapAttributeKeyMatchCoordinates;
918 	
919 			case IDENTITY_INDORMATIONS:
920 				return _mapAttributeKeyMatchIdentityInformations;
921 	
922 			default:
923 	
924 				break;
925 	
926 			}
927 		}
928 
929 		return _mapAttributeKeyMatch;
930 	}
931 	
932 	  /**
933      * Print JsonObject as String
934      * @param o the json Object
935      * @return Json String
936      */
937     public static String printJsonObjectAsString(Object o) 
938     {
939 		if (o != null) {
940 
941 			try {
942 				return _mapper.writeValueAsString(o);
943 			} catch (JsonProcessingException e) {
944 				// TODO Auto-generated catch block
945 				AppLogService.error("Failed to write object as Json", e);
946 			}
947 		}
948     	return "";
949     }
950     
951 }