Skip to content

Commit

Permalink
refactor: Change getOrFunction call in Cache [TECH-782] (dhis2#9124)
Browse files Browse the repository at this point in the history
  • Loading branch information
enricocolasante authored Oct 26, 2021
1 parent f79c5d5 commit a8a45e9
Show file tree
Hide file tree
Showing 29 changed files with 66 additions and 96 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -72,7 +72,7 @@ public interface Cache<V>
* Optional.empty() if the computed value is null
* @throws IllegalArgumentException if the specified mappingFunction is null
*/
Optional<V> get( String key, Function<String, V> mappingFunction );
V get( String key, Function<String, V> mappingFunction );

/**
* Returns a collection of all the values in the cache
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -100,7 +100,7 @@ public Optional<V> get( String key )
}

@Override
public Optional<V> get( String key, Function<String, V> mappingFunction )
public V get( String key, Function<String, V> mappingFunction )
{
if ( null == mappingFunction )
{
Expand All @@ -119,7 +119,7 @@ public Optional<V> get( String key, Function<String, V> mappingFunction )
}
}

return Optional.ofNullable( Optional.ofNullable( value ).orElse( defaultValue ) );
return Optional.ofNullable( value ).orElse( defaultValue );
}

@Override
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -72,13 +72,13 @@ public Optional<V> get( String key )
}

@Override
public Optional<V> get( String key, Function<String, V> mappingFunction )
public V get( String key, Function<String, V> mappingFunction )
{
if ( null == mappingFunction )
{
throw new IllegalArgumentException( "MappingFunction cannot be null" );
}
return Optional.ofNullable( Optional.ofNullable( mappingFunction.apply( key ) ).orElse( defaultValue ) );
return Optional.ofNullable( mappingFunction.apply( key ) ).orElse( defaultValue );
}

@Override
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -308,8 +308,7 @@ public Period createPeriod()
*/
public Period createPeriod( final Date date )
{
return PERIOD_CACHE.get( getCacheKey( date ), s -> createPeriod( createCalendarInstance( date ) ) )
.orElse( null );
return PERIOD_CACHE.get( getCacheKey( date ), s -> createPeriod( createCalendarInstance( date ) ) );
}

public Period createPeriod( Calendar cal )
Expand All @@ -332,7 +331,7 @@ public Period createPeriod( Calendar cal )
public Period createPeriod( final Date date, final org.hisp.dhis.calendar.Calendar calendar )
{
return PERIOD_CACHE.get( getCacheKey( calendar, date ),
p -> createPeriod( calendar.fromIso( DateTimeUnit.fromJdkDate( date ) ), calendar ) ).orElse( null );
p -> createPeriod( calendar.fromIso( DateTimeUnit.fromJdkDate( date ) ), calendar ) );
}

public Period toIsoPeriod( DateTimeUnit start, DateTimeUnit end )
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,6 @@
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.Optional;
import java.util.Set;

import org.hisp.dhis.attribute.exception.NonUniqueAttributeValueException;
Expand Down Expand Up @@ -108,8 +107,7 @@ public Attribute getAttribute( long id )
@Transactional( readOnly = true )
public Attribute getAttribute( String uid )
{
Optional<Attribute> attribute = attributeCache.get( uid, attr -> attributeStore.getByUid( uid ) );
return attribute.orElse( null );
return attributeCache.get( uid, attr -> attributeStore.getByUid( uid ) );
}

@Override
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,6 @@
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;
import java.util.Set;
import java.util.stream.Collectors;

Expand Down Expand Up @@ -1183,21 +1182,21 @@ public List<? extends IdentifiableObject> getAllByAttributeAndValues( Class<? ex
@Transactional( readOnly = true )
public Map<Class<? extends IdentifiableObject>, IdentifiableObject> getDefaults()
{
Optional<IdentifiableObject> categoryObjects = defaultObjectCache.get( Category.class.getName(),
IdentifiableObject categoryObjects = defaultObjectCache.get( Category.class.getName(),
key -> HibernateProxyUtils.unproxy( getByName( Category.class, DEFAULT ) ) );
Optional<IdentifiableObject> categoryComboObjects = defaultObjectCache.get( CategoryCombo.class.getName(),
IdentifiableObject categoryComboObjects = defaultObjectCache.get( CategoryCombo.class.getName(),
key -> HibernateProxyUtils.unproxy( getByName( CategoryCombo.class, DEFAULT ) ) );
Optional<IdentifiableObject> categoryOptionObjects = defaultObjectCache.get( CategoryOption.class.getName(),
IdentifiableObject categoryOptionObjects = defaultObjectCache.get( CategoryOption.class.getName(),
key -> HibernateProxyUtils.unproxy( getByName( CategoryOption.class, DEFAULT ) ) );
Optional<IdentifiableObject> categoryOptionCombo = defaultObjectCache.get(
IdentifiableObject categoryOptionCombo = defaultObjectCache.get(
CategoryOptionCombo.class.getName(),
key -> HibernateProxyUtils.unproxy( getByName( CategoryOptionCombo.class, DEFAULT ) ) );

return new ImmutableMap.Builder<Class<? extends IdentifiableObject>, IdentifiableObject>()
.put( Category.class, Objects.requireNonNull( categoryObjects.orElse( null ) ) )
.put( CategoryCombo.class, Objects.requireNonNull( categoryComboObjects.orElse( null ) ) )
.put( CategoryOption.class, Objects.requireNonNull( categoryOptionObjects.orElse( null ) ) )
.put( CategoryOptionCombo.class, Objects.requireNonNull( categoryOptionCombo.orElse( null ) ) )
.put( Category.class, Objects.requireNonNull( categoryObjects ) )
.put( CategoryCombo.class, Objects.requireNonNull( categoryComboObjects ) )
.put( CategoryOption.class, Objects.requireNonNull( categoryOptionObjects ) )
.put( CategoryOptionCombo.class, Objects.requireNonNull( categoryOptionCombo ) )
.build();
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -260,8 +260,7 @@ private DataApprovalLevel getUserApprovalLevelWithCache( String orgUnitUid, Data
userApprovalLevel = USER_APPROVAL_LEVEL_CACHE.get( user.getId() + "-" + organisationUnitUid,
c -> dataApprovalLevelService.getUserApprovalLevel( user,
organisationUnitService.getOrganisationUnit( organisationUnitUid ),
dataApprovalWorkflow.getSortedLevels() ) )
.orElse( null );
dataApprovalWorkflow.getSortedLevels() ) );

return userApprovalLevel;
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -230,8 +230,7 @@ public List<DataApproval> getDataApprovals( Collection<DataApprovalLevel> dataAp
@Override
public boolean dataApprovalExists( DataApproval dataApproval )
{
return isApprovedCache.get( dataApproval.getCacheKey(), key -> dataApprovalExistsInternal( dataApproval ) )
.orElse( false );
return isApprovedCache.get( dataApproval.getCacheKey(), key -> dataApprovalExistsInternal( dataApproval ) );
}

private boolean dataApprovalExistsInternal( DataApproval dataApproval )
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -167,7 +167,7 @@ public List<String> canWriteCached( User user, CategoryOptionCombo optionCombo )
{
String cacheKey = user.getUid() + "-" + optionCombo.getUid();

return canDataWriteCocCache.get( cacheKey, key -> canWrite( user, optionCombo ) ).orElse( null );
return canDataWriteCocCache.get( cacheKey, key -> canWrite( user, optionCombo ) );
}

@Override
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -70,7 +70,6 @@
import static org.springframework.util.ObjectUtils.isEmpty;

import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
Expand Down Expand Up @@ -677,8 +676,7 @@ public Object getExpressionValue( String expression, ParseType parseType,
*/
private Map<String, Constant> getConstantMap()
{
return constantMapCache.get( "x", key -> constantService.getConstantMap() )
.orElse( Collections.emptyMap() );
return constantMapCache.get( "x", key -> constantService.getConstantMap() );
}

/**
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -480,8 +480,7 @@ public boolean isInUserHierarchyCached( User user, OrganisationUnit organisation
{
String cacheKey = joinHyphen( user.getUsername(), organisationUnit.getUid() );

return inUserOrgUnitHierarchyCache.get( cacheKey, ou -> isInUserHierarchy( user, organisationUnit ) )
.orElse( false );
return inUserOrgUnitHierarchyCache.get( cacheKey, ou -> isInUserHierarchy( user, organisationUnit ) );
}

@Override
Expand Down Expand Up @@ -530,8 +529,7 @@ public boolean isInUserDataViewHierarchyCached( User user, OrganisationUnit orga
String cacheKey = joinHyphen( user.getUsername(), organisationUnit.getUid() );

return inUserOrgUnitViewHierarchyCache
.get( cacheKey, ou -> isInUserDataViewHierarchy( user, organisationUnit ) )
.orElse( false );
.get( cacheKey, ou -> isInUserDataViewHierarchy( user, organisationUnit ) );
}

@Override
Expand All @@ -555,7 +553,7 @@ public boolean isInUserSearchHierarchyCached( User user, OrganisationUnit organi
String cacheKey = joinHyphen( user.getUsername(), organisationUnit.getUid() );

return inUserOrgUnitSearchHierarchyCache
.get( cacheKey, ou -> isInUserSearchHierarchy( user, organisationUnit ) ).orElse( false );
.get( cacheKey, ou -> isInUserSearchHierarchy( user, organisationUnit ) );
}

@Override
Expand Down Expand Up @@ -610,8 +608,7 @@ public boolean isCaptureOrgUnitCountAboveThreshold( int threshold )
params.setParents( user.getOrganisationUnits() );
params.setFetchChildren( true );
return organisationUnitStore.isOrgUnitCountAboveThreshold( params, threshold );
} )
.orElse( false );
} );
}

// -------------------------------------------------------------------------
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -192,8 +192,7 @@ public Period reloadPeriod( Period period )

Long id = periodIdCache
.get( period.getCacheKey(),
key -> getPeriodId( period.getStartDate(), period.getEndDate(), period.getPeriodType() ) )
.orElse( null );
key -> getPeriodId( period.getStartDate(), period.getEndDate(), period.getPeriodType() ) );

Period storedPeriod = id != null ? getSession().get( Period.class, id ) : null;

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -366,8 +366,7 @@ private String getAnalyticsSqlCached( String expression, ProgramIndicator progra
String cacheKey = getAnalyticsSqlCacheKey( expression, programIndicator, startDate, endDate, tableAlias );

return analyticsSqlCache
.get( cacheKey, k -> _getAnalyticsSql( expression, programIndicator, startDate, endDate, tableAlias ) )
.orElse( null );
.get( cacheKey, k -> _getAnalyticsSql( expression, programIndicator, startDate, endDate, tableAlias ) );
}

private String getAnalyticsSqlCacheKey( String expression, ProgramIndicator programIndicator, Date startDate,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -104,8 +104,7 @@ public List<ProgramNotificationTemplate> getProgramNotificationByTriggerType( No
public boolean isProgramLinkedToWebHookNotification( Program program )
{
return programWebHookNotificationCache
.get( program.getUid(), uid -> store.isProgramLinkedToWebHookNotification( program.getId() ) )
.orElse( false );
.get( program.getUid(), uid -> store.isProgramLinkedToWebHookNotification( program.getId() ) );
}

@Override
Expand All @@ -114,8 +113,7 @@ public boolean isProgramStageLinkedToWebHookNotification( ProgramStage programSt
{
return programStageWebHookNotificationCache
.get( programStage.getUid(),
uid -> store.isProgramStageLinkedToWebHookNotification( programStage.getId() ) )
.orElse( false );
uid -> store.isProgramStageLinkedToWebHookNotification( programStage.getId() ) );
}

@Override
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -364,7 +364,7 @@ private OrganisationUnit getOwnerExpanded( String entityInstance, OrganisationUn
ou = trackedEntityProgramOwner.getOrganisationUnit();
}
return ou;
} ).get();
} );
}

/**
Expand All @@ -390,7 +390,7 @@ private OrganisationUnit getOwner( Long entityInstanceId, Program program,
} )
.orElseGet( orgUnitIfMissingSupplier );

} ).get();
} );
}

/**
Expand Down Expand Up @@ -439,7 +439,7 @@ private boolean hasTemporaryAccess( TrackedEntityInstance entityInstance, Progra
return tempOwnerCache
.get( getTempOwnershipCacheKey( entityInstance.getUid(), program.getUid(), user.getUid() ), s -> {
return (programTempOwnerService.getValidTempOwnerRecordCount( program, entityInstance, user ) > 0);
} ).orElse( false );
} );
}

private boolean hasTemporaryAccessWithUid( String entityInstanceUid, Program program, User user )
Expand All @@ -458,7 +458,7 @@ private boolean hasTemporaryAccessWithUid( String entityInstanceUid, Program pro
return true;
}
return (programTempOwnerService.getValidTempOwnerRecordCount( program, entityInstance, user ) > 0);
} ).orElse( false );
} );
}

/**
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -97,7 +97,7 @@ public User getCurrentUser()
return null;
}

Long userId = usernameIdCache.get( username, this::getUserId ).orElse( null );
Long userId = usernameIdCache.get( username, this::getUserId );

if ( userId == null )
{
Expand Down Expand Up @@ -141,7 +141,7 @@ public User getCurrentUserInTransaction()

User user = null;

Long userId = usernameIdCache.get( username, this::getUserId ).orElse( null );
Long userId = usernameIdCache.get( username, this::getUserId );

if ( userId != null )
{
Expand Down Expand Up @@ -187,7 +187,7 @@ public UserInfo getCurrentUserInfo()
return null;
}

Long userId = usernameIdCache.get( currentUsername, this::getUserId ).orElse( null );
Long userId = usernameIdCache.get( currentUsername, this::getUserId );

if ( userId == null )
{
Expand Down Expand Up @@ -251,7 +251,7 @@ public CurrentUserGroupInfo getCurrentUserGroupsInfo()
}

return currentUserGroupInfoCache
.get( currentUserInfo.getUsername(), this::getCurrentUserGroupsInfo ).orElse( null );
.get( currentUserInfo.getUsername(), this::getCurrentUserGroupsInfo );
}

@Override
Expand All @@ -264,7 +264,7 @@ public CurrentUserGroupInfo getCurrentUserGroupsInfo( UserInfo userInfo )
}

return currentUserGroupInfoCache
.get( userInfo.getUsername(), this::getCurrentUserGroupsInfo ).orElse( null );
.get( userInfo.getUsername(), this::getCurrentUserGroupsInfo );
}

@Override
Expand All @@ -287,7 +287,7 @@ private CurrentUserGroupInfo getCurrentUserGroupsInfo( String username )
return null;
}

Long userId = usernameIdCache.get( username, this::getUserId ).orElse( null );
Long userId = usernameIdCache.get( username, this::getUserId );

if ( userId == null )
{
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -264,6 +264,6 @@ public List<UserGroup> getUserGroupsBetweenByName( String name, int first, int m
public String getDisplayName( String uid )
{
return userGroupNameCache.get( uid,
n -> userGroupStore.getByUidNoAcl( uid ).getDisplayName() ).orElse( null );
n -> userGroupStore.getByUidNoAcl( uid ).getDisplayName() );
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -833,6 +833,6 @@ public Set<String> findNotifiableUsersWithLastLoginBetween( Date from, Date to )
@Override
public String getDisplayName( String userUid )
{
return userDisplayNameCache.get( userUid, c -> userStore.getDisplayName( userUid ) ).orElse( null );
return userDisplayNameCache.get( userUid, c -> userStore.getDisplayName( userUid ) );
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -311,7 +311,7 @@ private SerializableOptional getUserSetting( UserSettingKey key, Optional<User>
String cacheKey = getCacheKey( key.getName(), username );

SerializableOptional result = userSettingCache
.get( cacheKey, c -> getUserSettingOptional( key, username ) ).get();
.get( cacheKey, c -> getUserSettingOptional( key, username ) );

if ( !result.isPresent() && NAME_SETTING_KEY_MAP.containsKey( key.getName() ) )
{
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -140,13 +140,12 @@ public List<TrackedEntityInstance> find( List<Long> ids, TrackedEntityInstancePa
.get( user.getUid(),
userUID -> getSecurityContext( userUID,
userGroupUIDCache.get( userUID ).orElse( Lists.newArrayList() ) ) )
.map( c -> c.toBuilder()
.userId( user.getId() )
.superUser( user.isSuper() )
.params( params )
.queryParams( queryParams )
.build() )
.orElse( AggregateContext.builder().build() );
.toBuilder()
.userId( user.getId() )
.superUser( user.isSuper() )
.params( params )
.queryParams( queryParams )
.build();

/*
* Async fetch Relationships for the given TrackedEntityInstance id
Expand Down Expand Up @@ -218,12 +217,10 @@ public List<TrackedEntityInstance> find( List<Long> ids, TrackedEntityInstancePa
tei.setAttributes( filterAttributes( attributes.get( uid ), ownedTeis.get( uid ),
teiAttributesCache
.get( "ALL_ATTRIBUTES",
s -> trackedEntityAttributeService.getTrackedEntityAttributesByTrackedEntityTypes() )
.orElse( null ),
s -> trackedEntityAttributeService.getTrackedEntityAttributesByTrackedEntityTypes() ),
programTeiAttributesCache
.get( "ATTRIBUTES_BY_PROGRAM",
s -> trackedEntityAttributeService.getTrackedEntityAttributesByProgram() )
.orElse( null ),
s -> trackedEntityAttributeService.getTrackedEntityAttributesByProgram() ),
ctx ) );
tei.setRelationships( new ArrayList<>( relationships.get( uid ) ) );
tei.setEnrollments( filterEnrollments( enrollments.get( uid ), ownedTeis.get( uid ), ctx ) );
Expand Down
Loading

0 comments on commit a8a45e9

Please sign in to comment.