idx
int64
0
41.2k
question
stringlengths
74
4.04k
target
stringlengths
7
750
29,300
public Label buildLabel ( ) { final Label label = createLabel ( ) ; label . setImmediate ( false ) ; label . setWidth ( "-1px" ) ; label . setHeight ( "-1px" ) ; if ( StringUtils . hasText ( caption ) ) { label . setCaption ( caption ) ; } return label ; }
Build label .
29,301
@ SuppressWarnings ( "unchecked" ) public void updateTarget ( final Target updatedTarget ) { if ( updatedTarget != null ) { final Item item = getItem ( updatedTarget . getId ( ) ) ; item . getItemProperty ( SPUILabelDefinitions . VAR_TARGET_STATUS ) . setValue ( updatedTarget . getUpdateStatus ( ) ) ; item . getItemProperty ( SPUILabelDefinitions . LAST_QUERY_DATE ) . setValue ( updatedTarget . getLastTargetQuery ( ) ) ; item . getItemProperty ( SPUILabelDefinitions . VAR_LAST_MODIFIED_BY ) . setValue ( UserDetailsFormatter . loadAndFormatLastModifiedBy ( updatedTarget ) ) ; item . getItemProperty ( SPUILabelDefinitions . VAR_LAST_MODIFIED_DATE ) . setValue ( SPDateTimeUtil . getFormattedDate ( updatedTarget . getLastModifiedAt ( ) ) ) ; item . getItemProperty ( SPUILabelDefinitions . VAR_DESC ) . setValue ( updatedTarget . getDescription ( ) ) ; item . getItemProperty ( SPUILabelDefinitions . VAR_NAME ) . setValue ( updatedTarget . getName ( ) ) ; } }
To update target details in the table .
29,302
private void resetTargetCountDetails ( ) { final long totalTargetsCount = getTotalTargetsCount ( ) ; managementUIState . setTargetsCountAll ( totalTargetsCount ) ; final boolean noTagClicked = managementUIState . getTargetTableFilters ( ) . isNoTagSelected ( ) ; final Long distributionId = managementUIState . getTargetTableFilters ( ) . getDistributionSet ( ) . map ( DistributionSetIdName :: getId ) . orElse ( null ) ; final Long pinnedDistId = managementUIState . getTargetTableFilters ( ) . getPinnedDistId ( ) . orElse ( null ) ; final String searchText = managementUIState . getTargetTableFilters ( ) . getSearchText ( ) . map ( text -> { if ( StringUtils . isEmpty ( text ) ) { return null ; } return String . format ( "%%%s%%" , text ) ; } ) . orElse ( null ) ; String [ ] targetTags = null ; if ( isFilteredByTags ( ) ) { targetTags = managementUIState . getTargetTableFilters ( ) . getClickedTargetTags ( ) . toArray ( new String [ 0 ] ) ; } Collection < TargetUpdateStatus > status = null ; if ( isFilteredByStatus ( ) ) { status = managementUIState . getTargetTableFilters ( ) . getClickedStatusTargetTags ( ) ; } Boolean overdueState = null ; if ( managementUIState . getTargetTableFilters ( ) . isOverdueFilterEnabled ( ) ) { overdueState = managementUIState . getTargetTableFilters ( ) . isOverdueFilterEnabled ( ) ; } final long size = getTargetsCountWithFilter ( totalTargetsCount , pinnedDistId , new FilterParams ( status , overdueState , searchText , distributionId , noTagClicked , targetTags ) ) ; if ( size > SPUIDefinitions . MAX_TABLE_ENTRIES ) { managementUIState . setTargetsTruncated ( size - SPUIDefinitions . MAX_TABLE_ENTRIES ) ; } }
Set total target count and count of targets truncated in target table .
29,303
static ServerViewComponentClientCriterion [ ] createViewComponentClientCriteria ( ) { final ServerViewComponentClientCriterion [ ] criteria = new ServerViewComponentClientCriterion [ 1 ] ; criteria [ 0 ] = ServerViewComponentClientCriterion . createBuilder ( ) . dragSourceIdPrefix ( UIComponentIdProvider . UPLOAD_SOFTWARE_MODULE_TABLE ) . dropTargetIdPrefixes ( UIComponentIdProvider . DIST_TABLE_ID ) . dropAreaIds ( UIComponentIdProvider . DIST_TABLE_ID ) . build ( ) ; return criteria ; }
Configures the elements of the composite accept criterion for the Distributions View .
29,304
@ EventBusListenerMethod ( scope = EventScope . UI ) void onEvent ( final RolloutEvent event ) { switch ( event ) { case FILTER_BY_TEXT : case CREATE_ROLLOUT : case UPDATE_ROLLOUT : case SHOW_ROLLOUTS : refreshContainer ( ) ; break ; default : break ; } }
Handles the RolloutEvent to refresh Grid .
29,305
@ EventBusListenerMethod ( scope = EventScope . UI ) public void onRolloutChangeEvent ( final RolloutChangeEventContainer eventContainer ) { eventContainer . getEvents ( ) . forEach ( this :: handleEvent ) ; }
Handles the RolloutChangeEvent to refresh the item in the grid .
29,306
public void populateMetadata ( final Target target ) { removeAllItems ( ) ; if ( target == null ) { return ; } selectedTargetId = target . getId ( ) ; final List < TargetMetadata > targetMetadataList = targetManagement . findMetaDataByControllerId ( PageRequest . of ( 0 , MAX_METADATA_QUERY ) , target . getControllerId ( ) ) . getContent ( ) ; if ( targetMetadataList != null && ! targetMetadataList . isEmpty ( ) ) { targetMetadataList . forEach ( this :: setMetadataProperties ) ; } }
Populate target metadata .
29,307
private boolean scheduleRolloutGroup ( final JpaRollout rollout , final JpaRolloutGroup group ) { final long targetsInGroup = rolloutTargetGroupRepository . countByRolloutGroup ( group ) ; final long countOfActions = actionRepository . countByRolloutAndRolloutGroup ( rollout , group ) ; long actionsLeft = targetsInGroup - countOfActions ; if ( actionsLeft > 0 ) { actionsLeft -= createActionsForRolloutGroup ( rollout , group ) ; } if ( actionsLeft <= 0 ) { group . setStatus ( RolloutGroupStatus . SCHEDULED ) ; rolloutGroupRepository . save ( group ) ; return true ; } return false ; }
Schedules a group of the rollout . Scheduled Actions are created to achieve this . The creation of those Actions is allowed to fail .
29,308
private void createScheduledAction ( final Collection < Target > targets , final DistributionSet distributionSet , final ActionType actionType , final Long forcedTime , final Rollout rollout , final RolloutGroup rolloutGroup ) { final List < Long > targetIds = targets . stream ( ) . map ( Target :: getId ) . collect ( Collectors . toList ( ) ) ; deploymentManagement . cancelInactiveScheduledActionsForTargets ( targetIds ) ; targets . forEach ( target -> { assertActionsPerTargetQuota ( target , 1 ) ; final JpaAction action = new JpaAction ( ) ; action . setTarget ( target ) ; action . setActive ( false ) ; action . setDistributionSet ( distributionSet ) ; action . setActionType ( actionType ) ; action . setForcedTime ( forcedTime ) ; action . setStatus ( Status . SCHEDULED ) ; action . setRollout ( rollout ) ; action . setRolloutGroup ( rolloutGroup ) ; actionRepository . save ( action ) ; } ) ; }
Creates an action entry into the action repository . In case of existing scheduled actions the scheduled actions gets canceled . A scheduled action is created in - active .
29,309
public static ResponseEntity < Void > writeMD5FileResponse ( final HttpServletResponse response , final String md5Hash , final String filename ) throws IOException { if ( md5Hash == null ) { return ResponseEntity . notFound ( ) . build ( ) ; } final StringBuilder builder = new StringBuilder ( ) ; builder . append ( md5Hash ) ; builder . append ( " " ) ; builder . append ( filename ) ; final byte [ ] content = builder . toString ( ) . getBytes ( StandardCharsets . US_ASCII ) ; final StringBuilder header = new StringBuilder ( ) . append ( "attachment;filename=" ) . append ( filename ) . append ( ARTIFACT_MD5_DWNL_SUFFIX ) ; response . setContentLength ( content . length ) ; response . setHeader ( HttpHeaders . CONTENT_DISPOSITION , header . toString ( ) ) ; response . getOutputStream ( ) . write ( content ) ; return ResponseEntity . ok ( ) . build ( ) ; }
Write a md5 file response .
29,310
public String getItemCaption ( final Object itemId ) { if ( itemId != null && itemId . equals ( getValue ( ) ) && ! StringUtils . isEmpty ( selectedValueCaption ) ) { return selectedValueCaption ; } return super . getItemCaption ( itemId ) ; }
Overriden in order to return the caption for the selected distribution set from cache . Otherwise it could lead to multiple database queries trying to retrieve the caption from container when it is not present in filtered options .
29,311
public int setInitialValueFilter ( final String initialFilterString ) { final Filter filter = buildFilter ( initialFilterString , getFilteringMode ( ) ) ; if ( filter != null ) { final LazyQueryContainer container = ( LazyQueryContainer ) getContainerDataSource ( ) ; try { container . addContainerFilter ( filter ) ; return container . size ( ) ; } finally { container . removeContainerFilter ( filter ) ; } } return 0 ; }
Before setting the value of the selected distribution set we need to initialize the container and apply the right filter in order to limit the number of entities and save them in container cache . Otherwise combobox will try to find the corresponding id from container leading to multiple database queries .
29,312
private void addContainerproperties ( ) { container . addContainerProperty ( SPUILabelDefinitions . NAME , String . class , null ) ; container . addContainerProperty ( SPUILabelDefinitions . VAR_CREATED_BY , String . class , null ) ; container . addContainerProperty ( SPUILabelDefinitions . VAR_CREATED_DATE , Date . class , null ) ; container . addContainerProperty ( SPUILabelDefinitions . VAR_LAST_MODIFIED_BY , String . class , null , false , true ) ; container . addContainerProperty ( SPUILabelDefinitions . VAR_LAST_MODIFIED_DATE , String . class , null , false , true ) ; container . addContainerProperty ( SPUILabelDefinitions . VAR_TARGET_STATUS , TargetUpdateStatus . class , null ) ; container . addContainerProperty ( SPUILabelDefinitions . VAR_DESC , String . class , "" , false , true ) ; container . addContainerProperty ( ASSIGN_DIST_SET , DistributionSet . class , null , false , true ) ; container . addContainerProperty ( INSTALL_DIST_SET , DistributionSet . class , null , false , true ) ; container . addContainerProperty ( SPUILabelDefinitions . ASSIGNED_DISTRIBUTION_NAME_VER , String . class , "" ) ; container . addContainerProperty ( SPUILabelDefinitions . INSTALLED_DISTRIBUTION_NAME_VER , String . class , null ) ; }
Create a empty HierarchicalContainer .
29,313
static JpaRolloutGroup prepareRolloutGroupWithDefaultConditions ( final RolloutGroupCreate create , final RolloutGroupConditions conditions ) { final JpaRolloutGroup group = ( ( JpaRolloutGroupCreate ) create ) . build ( ) ; if ( group . getSuccessCondition ( ) == null ) { group . setSuccessCondition ( conditions . getSuccessCondition ( ) ) ; } if ( group . getSuccessConditionExp ( ) == null ) { group . setSuccessConditionExp ( conditions . getSuccessConditionExp ( ) ) ; } if ( group . getSuccessAction ( ) == null ) { group . setSuccessAction ( conditions . getSuccessAction ( ) ) ; } if ( group . getSuccessActionExp ( ) == null ) { group . setSuccessActionExp ( conditions . getSuccessActionExp ( ) ) ; } if ( group . getErrorCondition ( ) == null ) { group . setErrorCondition ( conditions . getErrorCondition ( ) ) ; } if ( group . getErrorConditionExp ( ) == null ) { group . setErrorConditionExp ( conditions . getErrorConditionExp ( ) ) ; } if ( group . getErrorAction ( ) == null ) { group . setErrorAction ( conditions . getErrorAction ( ) ) ; } if ( group . getErrorActionExp ( ) == null ) { group . setErrorActionExp ( conditions . getErrorActionExp ( ) ) ; } return group ; }
In case the given group is missing conditions or actions they will be set from the supplied default conditions .
29,314
@ RabbitListener ( queues = "${hawkbit.dmf.rabbitmq.receiverQueue:dmf_receiver}" , containerFactory = "listenerContainerFactory" ) public Message onMessage ( final Message message , @ Header ( name = MessageHeaderKey . TYPE , required = false ) final String type , @ Header ( name = MessageHeaderKey . TENANT , required = false ) final String tenant ) { return onMessage ( message , type , tenant , getRabbitTemplate ( ) . getConnectionFactory ( ) . getVirtualHost ( ) ) ; }
Method to handle all incoming DMF amqp messages .
29,315
private void registerTarget ( final Message message , final String virtualHost ) { final String thingId = getStringHeaderKey ( message , MessageHeaderKey . THING_ID , "ThingId is null" ) ; final String replyTo = message . getMessageProperties ( ) . getReplyTo ( ) ; if ( StringUtils . isEmpty ( replyTo ) ) { logAndThrowMessageError ( message , "No ReplyTo was set for the createThing message." ) ; } final URI amqpUri = IpUtil . createAmqpUri ( virtualHost , replyTo ) ; final Target target = controllerManagement . findOrRegisterTargetIfItDoesNotExist ( thingId , amqpUri ) ; LOG . debug ( "Target {} reported online state." , thingId ) ; lookIfUpdateAvailable ( target ) ; }
Method to create a new target or to find the target if it already exists .
29,316
private void handleIncomingEvent ( final Message message ) { switch ( EventTopic . valueOf ( getStringHeaderKey ( message , MessageHeaderKey . TOPIC , "EventTopic is null" ) ) ) { case UPDATE_ACTION_STATUS : updateActionStatus ( message ) ; break ; case UPDATE_ATTRIBUTES : updateAttributes ( message ) ; break ; default : logAndThrowMessageError ( message , "Got event without appropriate topic." ) ; break ; } }
Method to handle the different topics to an event .
29,317
private void updateActionStatus ( final Message message ) { final DmfActionUpdateStatus actionUpdateStatus = convertMessage ( message , DmfActionUpdateStatus . class ) ; final Action action = checkActionExist ( message , actionUpdateStatus ) ; final List < String > messages = actionUpdateStatus . getMessage ( ) ; if ( isCorrelationIdNotEmpty ( message ) ) { messages . add ( RepositoryConstants . SERVER_MESSAGE_PREFIX + "DMF message correlation-id " + message . getMessageProperties ( ) . getCorrelationId ( ) ) ; } final Status status = mapStatus ( message , actionUpdateStatus , action ) ; final ActionStatusCreate actionStatus = entityFactory . actionStatus ( ) . create ( action . getId ( ) ) . status ( status ) . messages ( messages ) ; final Action addUpdateActionStatus = getUpdateActionStatus ( status , actionStatus ) ; if ( ! addUpdateActionStatus . isActive ( ) || ( addUpdateActionStatus . hasMaintenanceSchedule ( ) && addUpdateActionStatus . isMaintenanceWindowAvailable ( ) ) ) { lookIfUpdateAvailable ( action . getTarget ( ) ) ; } }
Method to update the action status of an action through the event .
29,318
@ SuppressWarnings ( "squid:S3655" ) private Action checkActionExist ( final Message message , final DmfActionUpdateStatus actionUpdateStatus ) { final Long actionId = actionUpdateStatus . getActionId ( ) ; LOG . debug ( "Target notifies intermediate about action {} with status {}." , actionId , actionUpdateStatus . getActionStatus ( ) ) ; final Optional < Action > findActionWithDetails = controllerManagement . findActionWithDetails ( actionId ) ; if ( ! findActionWithDetails . isPresent ( ) ) { logAndThrowMessageError ( message , "Got intermediate notification about action " + actionId + " but action does not exist" ) ; } return findActionWithDetails . get ( ) ; }
get will not be called
29,319
public boolean matchRemoteEvent ( final TenantAwareEvent tenantAwareEvent ) { if ( ! ( tenantAwareEvent instanceof RemoteIdEvent ) || entityClass == null || entityIds == null ) { return false ; } final RemoteIdEvent remoteIdEvent = ( RemoteIdEvent ) tenantAwareEvent ; try { final Class < ? > remoteEntityClass = Class . forName ( remoteIdEvent . getEntityClass ( ) ) ; return entityClass . isAssignableFrom ( remoteEntityClass ) && entityIds . contains ( remoteIdEvent . getEntityId ( ) ) ; } catch ( final ClassNotFoundException e ) { LOG . error ( "Entity Class of remoteIdEvent cannot be found" , e ) ; return false ; } }
Checks if the remote event is the same as this UI event . Then maybe you can skip the remote event because it is already executed .
29,320
public void init ( ) { if ( defaultDistributionSetTypeLayout . getComponentCount ( ) > 0 ) { configurationViews . add ( defaultDistributionSetTypeLayout ) ; } configurationViews . add ( repositoryConfigurationView ) ; configurationViews . add ( rolloutConfigurationView ) ; configurationViews . add ( authenticationConfigurationView ) ; configurationViews . add ( pollingConfigurationView ) ; if ( customConfigurationViews != null ) { configurationViews . addAll ( customConfigurationViews . stream ( ) . filter ( ConfigurationGroup :: show ) . collect ( Collectors . toList ( ) ) ) ; } final Panel rootPanel = new Panel ( ) ; rootPanel . setStyleName ( "tenantconfig-root" ) ; final VerticalLayout rootLayout = new VerticalLayout ( ) ; rootLayout . setSizeFull ( ) ; rootLayout . setMargin ( true ) ; rootLayout . setSpacing ( true ) ; configurationViews . forEach ( rootLayout :: addComponent ) ; final HorizontalLayout buttonContent = saveConfigurationButtonsLayout ( ) ; rootLayout . addComponent ( buttonContent ) ; rootLayout . setComponentAlignment ( buttonContent , Alignment . BOTTOM_LEFT ) ; rootPanel . setContent ( rootLayout ) ; setCompositionRoot ( rootPanel ) ; configurationViews . forEach ( view -> view . addChangeListener ( this ) ) ; }
Init method adds all Configuration Views to the list of Views .
29,321
public ResponseEntity < InputStream > downloadArtifact ( @ PathVariable ( "softwareModuleId" ) final Long softwareModuleId , @ PathVariable ( "artifactId" ) final Long artifactId ) { final SoftwareModule module = softwareModuleManagement . get ( softwareModuleId ) . orElseThrow ( ( ) -> new EntityNotFoundException ( SoftwareModule . class , softwareModuleId ) ) ; final Artifact artifact = module . getArtifact ( artifactId ) . orElseThrow ( ( ) -> new EntityNotFoundException ( Artifact . class , artifactId ) ) ; final AbstractDbArtifact file = artifactManagement . loadArtifactBinary ( artifact . getSha1Hash ( ) ) . orElseThrow ( ( ) -> new ArtifactBinaryNotFoundException ( artifact . getSha1Hash ( ) ) ) ; final HttpServletRequest request = requestResponseContextHolder . getHttpServletRequest ( ) ; final String ifMatch = request . getHeader ( HttpHeaders . IF_MATCH ) ; if ( ifMatch != null && ! HttpUtil . matchesHttpHeader ( ifMatch , artifact . getSha1Hash ( ) ) ) { return new ResponseEntity < > ( HttpStatus . PRECONDITION_FAILED ) ; } return FileStreamingUtil . writeFileResponse ( file , artifact . getFilename ( ) , artifact . getCreatedAt ( ) , requestResponseContextHolder . getHttpServletResponse ( ) , request , null ) ; }
Handles the GET request for downloading an artifact .
29,322
public String putHeader ( final String name , final String value ) { if ( headers == null ) { headers = new TreeMap < > ( String . CASE_INSENSITIVE_ORDER ) ; } return headers . put ( name , value ) ; }
Associates the specified header value with the specified name .
29,323
public void setValue ( final Duration tenantDuration ) { if ( tenantDuration == null ) { checkBox . setValue ( false ) ; durationField . setDuration ( globalDuration ) ; durationField . setEnabled ( false ) ; return ; } checkBox . setValue ( true ) ; durationField . setDuration ( tenantDuration ) ; durationField . setEnabled ( true ) ; }
Set the value of the duration field
29,324
public Authentication doAuthenticate ( final DmfTenantSecurityToken securityToken ) { resolveTenant ( securityToken ) ; PreAuthenticatedAuthenticationToken authentication = new PreAuthenticatedAuthenticationToken ( null , null ) ; for ( final PreAuthenticationFilter filter : filterChain ) { final PreAuthenticatedAuthenticationToken authenticationRest = createAuthentication ( filter , securityToken ) ; if ( authenticationRest != null ) { authentication = authenticationRest ; authentication . setDetails ( new TenantAwareAuthenticationDetails ( securityToken . getTenant ( ) , true ) ) ; break ; } } return preAuthenticatedAuthenticationProvider . authenticate ( authentication ) ; }
Performs authentication with the security token .
29,325
public static void addTargetLinks ( final MgmtTarget response ) { response . add ( linkTo ( methodOn ( MgmtTargetRestApi . class ) . getAssignedDistributionSet ( response . getControllerId ( ) ) ) . withRel ( MgmtRestConstants . TARGET_V1_ASSIGNED_DISTRIBUTION_SET ) ) ; response . add ( linkTo ( methodOn ( MgmtTargetRestApi . class ) . getInstalledDistributionSet ( response . getControllerId ( ) ) ) . withRel ( MgmtRestConstants . TARGET_V1_INSTALLED_DISTRIBUTION_SET ) ) ; response . add ( linkTo ( methodOn ( MgmtTargetRestApi . class ) . getAttributes ( response . getControllerId ( ) ) ) . withRel ( MgmtRestConstants . TARGET_V1_ATTRIBUTES ) ) ; response . add ( linkTo ( methodOn ( MgmtTargetRestApi . class ) . getActionHistory ( response . getControllerId ( ) , 0 , MgmtRestConstants . REQUEST_PARAMETER_PAGING_DEFAULT_LIMIT_VALUE , ActionFields . ID . getFieldName ( ) + ":" + SortDirection . DESC , null ) ) . withRel ( MgmtRestConstants . TARGET_V1_ACTIONS ) . expand ( ) ) ; response . add ( linkTo ( methodOn ( MgmtTargetRestApi . class ) . getMetadata ( response . getControllerId ( ) , MgmtRestConstants . REQUEST_PARAMETER_PAGING_DEFAULT_OFFSET_VALUE , MgmtRestConstants . REQUEST_PARAMETER_PAGING_DEFAULT_LIMIT_VALUE , null , null ) ) . withRel ( "metadata" ) ) ; }
Add links to a target response .
29,326
public static List < MgmtTarget > toResponse ( final Collection < Target > targets ) { if ( targets == null ) { return Collections . emptyList ( ) ; } return new ResponseList < > ( targets . stream ( ) . map ( MgmtTargetMapper :: toResponse ) . collect ( Collectors . toList ( ) ) ) ; }
Create a response for targets .
29,327
public static MgmtTarget toResponse ( final Target target ) { if ( target == null ) { return null ; } final MgmtTarget targetRest = new MgmtTarget ( ) ; targetRest . setControllerId ( target . getControllerId ( ) ) ; targetRest . setDescription ( target . getDescription ( ) ) ; targetRest . setName ( target . getName ( ) ) ; targetRest . setUpdateStatus ( target . getUpdateStatus ( ) . name ( ) . toLowerCase ( ) ) ; final URI address = target . getAddress ( ) ; if ( address != null ) { if ( IpUtil . isIpAddresKnown ( address ) ) { targetRest . setIpAddress ( address . getHost ( ) ) ; } targetRest . setAddress ( address . toString ( ) ) ; } targetRest . setCreatedBy ( target . getCreatedBy ( ) ) ; targetRest . setLastModifiedBy ( target . getLastModifiedBy ( ) ) ; targetRest . setCreatedAt ( target . getCreatedAt ( ) ) ; targetRest . setLastModifiedAt ( target . getLastModifiedAt ( ) ) ; targetRest . setSecurityToken ( target . getSecurityToken ( ) ) ; targetRest . setRequestAttributes ( target . isRequestControllerAttributes ( ) ) ; final Long lastTargetQuery = target . getLastTargetQuery ( ) ; final Long installationDate = target . getInstallationDate ( ) ; if ( lastTargetQuery != null ) { targetRest . setLastControllerRequestAt ( lastTargetQuery ) ; } if ( installationDate != null ) { targetRest . setInstalledAt ( installationDate ) ; } targetRest . add ( linkTo ( methodOn ( MgmtTargetRestApi . class ) . getTarget ( target . getControllerId ( ) ) ) . withSelfRel ( ) ) ; return targetRest ; }
Create a response for target .
29,328
private void selectDistributionSetValue ( ) { selectedDefaultDisSetType = ( Long ) combobox . getValue ( ) ; if ( ! selectedDefaultDisSetType . equals ( currentDefaultDisSetType ) ) { changeIcon . setVisible ( true ) ; notifyConfigurationChanged ( ) ; } else { changeIcon . setVisible ( false ) ; } }
Method that is called when combobox event is performed .
29,329
private void confirmAndForceAction ( final Long actionId ) { final ConfirmationDialog confirmDialog = new ConfirmationDialog ( i18n . getMessage ( "caption.force.action.confirmbox" ) , i18n . getMessage ( "message.force.action.confirm" ) , i18n . getMessage ( UIMessageIdProvider . BUTTON_OK ) , i18n . getMessage ( UIMessageIdProvider . BUTTON_CANCEL ) , ok -> { if ( ! ok ) { return ; } deploymentManagement . forceTargetAction ( actionId ) ; populateAndUpdateTargetDetails ( selectedTarget ) ; notification . displaySuccess ( i18n . getMessage ( "message.force.action.success" ) ) ; } , UIComponentIdProvider . CONFIRMATION_POPUP_ID ) ; UI . getCurrent ( ) . addWindow ( confirmDialog . getWindow ( ) ) ; confirmDialog . getWindow ( ) . bringToFront ( ) ; }
Show confirmation window and if ok then only force the action .
29,330
private void confirmAndForceQuitAction ( final Long actionId ) { final ConfirmationDialog confirmDialog = new ConfirmationDialog ( i18n . getMessage ( "caption.forcequit.action.confirmbox" ) , i18n . getMessage ( "message.forcequit.action.confirm" ) , i18n . getMessage ( UIMessageIdProvider . BUTTON_OK ) , i18n . getMessage ( UIMessageIdProvider . BUTTON_CANCEL ) , ok -> { if ( ! ok ) { return ; } final boolean cancelResult = forceQuitActiveAction ( actionId ) ; if ( cancelResult ) { populateAndUpdateTargetDetails ( selectedTarget ) ; notification . displaySuccess ( i18n . getMessage ( "message.forcequit.action.success" ) ) ; } else { notification . displayValidationError ( i18n . getMessage ( "message.forcequit.action.failed" ) ) ; } } , FontAwesome . WARNING , UIComponentIdProvider . CONFIRMATION_POPUP_ID , null ) ; UI . getCurrent ( ) . addWindow ( confirmDialog . getWindow ( ) ) ; confirmDialog . getWindow ( ) . bringToFront ( ) ; }
Show confirmation window and if ok then only force quit action .
29,331
private void updateDistributionTableStyle ( ) { managementUIState . getDistributionTableFilters ( ) . getPinnedTarget ( ) . ifPresent ( pinnedTarget -> { if ( pinnedTarget . getTargetId ( ) . equals ( selectedTarget . getId ( ) ) ) { eventBus . publish ( this , PinUnpinEvent . PIN_TARGET ) ; } } ) ; }
Update the colors of Assigned and installed distribution set in Target Pinning .
29,332
private void setColumnsSize ( final double min , final double max , final String ... columnPropertyIds ) { for ( final String columnPropertyId : columnPropertyIds ) { getColumn ( columnPropertyId ) . setMinimumWidth ( min ) ; getColumn ( columnPropertyId ) . setMaximumWidth ( max ) ; } }
Conveniently sets min - and max - width for a bunch of columns .
29,333
@ Scheduled ( initialDelayString = PROP_AUTO_CLEANUP_INTERVAL , fixedDelayString = PROP_AUTO_CLEANUP_INTERVAL ) public void run ( ) { LOGGER . debug ( "Auto cleanup scheduler has been triggered." ) ; if ( ! cleanupTasks . isEmpty ( ) ) { systemSecurityContext . runAsSystem ( this :: executeAutoCleanup ) ; } }
Scheduler method which kicks off the cleanup process .
29,334
@ SuppressWarnings ( "squid:S3516" ) private Void executeAutoCleanup ( ) { systemManagement . forEachTenant ( tenant -> cleanupTasks . forEach ( task -> { final Lock lock = obtainLock ( task , tenant ) ; if ( ! lock . tryLock ( ) ) { return ; } try { task . run ( ) ; } catch ( final RuntimeException e ) { LOGGER . error ( "Cleanup task failed." , e ) ; } finally { lock . unlock ( ) ; } } ) ) ; return null ; }
Method which executes each registered cleanup task for each tenant .
29,335
public void styleDistributionSetTable ( final Long installedDistItemId , final Long assignedDistTableItemId ) { setCellStyleGenerator ( ( source , itemId , propertyId ) -> getPinnedDistributionStyle ( installedDistItemId , assignedDistTableItemId , itemId ) ) ; }
Added by Saumya Target pin listener .
29,336
private static FontIconData createFontIconData ( StatusFontIcon meta ) { FontIconData result = new FontIconData ( ) ; result . setFontIconHtml ( meta . getFontIcon ( ) . getHtml ( ) ) ; result . setTitle ( meta . getTitle ( ) ) ; result . setStyle ( meta . getStyle ( ) ) ; result . setId ( meta . getId ( ) ) ; result . setDisabled ( meta . isDisabled ( ) ) ; return result ; }
Creates a data transport object for the icon meta data .
29,337
public static List < String > getAllAuthorities ( ) { final List < String > allPermissions = new ArrayList < > ( ) ; final Field [ ] declaredFields = SpPermission . class . getDeclaredFields ( ) ; for ( final Field field : declaredFields ) { if ( Modifier . isPublic ( field . getModifiers ( ) ) && Modifier . isStatic ( field . getModifiers ( ) ) ) { field . setAccessible ( true ) ; try { final String role = ( String ) field . get ( null ) ; allPermissions . add ( role ) ; } catch ( final IllegalAccessException e ) { LOGGER . error ( e . getMessage ( ) , e ) ; } } } return allPermissions ; }
Return all permission .
29,338
@ SuppressWarnings ( { "squid:S1166" , "squid:S2221" } ) boolean isValidDragSource ( final VDragEvent drag , final UIDL configuration ) { try { final String dragSource = drag . getTransferable ( ) . getDragSource ( ) . getWidget ( ) . getElement ( ) . getId ( ) ; final String dragSourcePrefix = configuration . getStringAttribute ( DRAG_SOURCE ) ; if ( dragSource . startsWith ( dragSourcePrefix ) ) { return true ; } } catch ( final Exception e ) { LOGGER . log ( Level . SEVERE , "Error verifying drag source: " + e . getLocalizedMessage ( ) ) ; } return false ; }
Exception semantics changes
29,339
@ RabbitListener ( queues = "${hawkbit.dmf.rabbitmq.authenticationReceiverQueue:authentication_receiver}" , containerFactory = "listenerContainerFactory" ) public Message onAuthenticationRequest ( final Message message ) { checkContentTypeJson ( message ) ; final SecurityContext oldContext = SecurityContextHolder . getContext ( ) ; try { return handleAuthenticationMessage ( message ) ; } catch ( final RuntimeException ex ) { throw new AmqpRejectAndDontRequeueException ( ex ) ; } finally { SecurityContextHolder . setContext ( oldContext ) ; } }
Executed on an authentication request .
29,340
private void checkIfArtifactIsAssignedToTarget ( final DmfTenantSecurityToken secruityToken , final String sha1Hash ) { if ( secruityToken . getControllerId ( ) != null ) { checkByControllerId ( sha1Hash , secruityToken . getControllerId ( ) ) ; } else if ( secruityToken . getTargetId ( ) != null ) { checkByTargetId ( sha1Hash , secruityToken . getTargetId ( ) ) ; } else { LOG . info ( "anonymous download no authentication check for artifact {}" , sha1Hash ) ; } }
check action for this download purposes the method will throw an EntityNotFoundException in case the controller is not allowed to download this file because it s not assigned to an action and not assigned to this controller . Otherwise no controllerId is set = anonymous download
29,341
public Long getTotalTargetCountByStatus ( final Status status ) { final Long count = statusTotalCountMap . get ( status ) ; return count == null ? 0L : count ; }
Gets the total target count from a state .
29,342
private void addToTotalCount ( final List < TotalTargetCountActionStatus > targetCountActionStatus ) { if ( targetCountActionStatus == null ) { statusTotalCountMap . put ( TotalTargetCountStatus . Status . NOTSTARTED , totalTargetCount ) ; return ; } statusTotalCountMap . put ( Status . RUNNING , 0L ) ; Long notStartedTargetCount = totalTargetCount ; for ( final TotalTargetCountActionStatus item : targetCountActionStatus ) { addToTotalCount ( item ) ; notStartedTargetCount -= item . getCount ( ) ; } statusTotalCountMap . put ( TotalTargetCountStatus . Status . NOTSTARTED , notStartedTargetCount ) ; }
Populate all target status to a the given map
29,343
@ SuppressWarnings ( "squid:MethodCyclomaticComplexity" ) private Status convertStatus ( final Action . Status status ) { switch ( status ) { case SCHEDULED : return Status . SCHEDULED ; case ERROR : return Status . ERROR ; case FINISHED : return Status . FINISHED ; case CANCELED : return Status . CANCELLED ; case RETRIEVED : case RUNNING : case WARNING : case DOWNLOAD : case CANCELING : return Status . RUNNING ; case DOWNLOADED : return Action . ActionType . DOWNLOAD_ONLY . equals ( rolloutType ) ? Status . FINISHED : Status . RUNNING ; default : throw new IllegalArgumentException ( "State " + status + "is not valid" ) ; } }
really complex .
29,344
public void populateModule ( final DistributionSet distributionSet ) { removeAllItems ( ) ; if ( distributionSet != null ) { if ( isUnassignSoftModAllowed && permissionChecker . hasUpdateRepositoryPermission ( ) ) { try { isTargetAssigned = false ; } catch ( final EntityReadOnlyException exception ) { isTargetAssigned = true ; LOG . info ( "Target already assigned for the distribution set: " + distributionSet . getName ( ) , exception ) ; } } final Set < SoftwareModuleType > swModuleMandatoryTypes = distributionSet . getType ( ) . getMandatoryModuleTypes ( ) ; final Set < SoftwareModuleType > swModuleOptionalTypes = distributionSet . getType ( ) . getOptionalModuleTypes ( ) ; if ( ! CollectionUtils . isEmpty ( swModuleMandatoryTypes ) ) { swModuleMandatoryTypes . forEach ( swModule -> setSwModuleProperties ( swModule , true , distributionSet ) ) ; } if ( ! CollectionUtils . isEmpty ( swModuleOptionalTypes ) ) { swModuleOptionalTypes . forEach ( swModule -> setSwModuleProperties ( swModule , false , distributionSet ) ) ; } setAmountOfTableRows ( getContainerDataSource ( ) . size ( ) ) ; } }
Populate software module table .
29,345
protected Label buildTitleLabel ( ) { title = new LabelBuilder ( ) . name ( titleText ) . buildCaptionLabel ( ) ; title . setImmediate ( true ) ; title . setContentMode ( ContentMode . HTML ) ; return title ; }
Builds the title label .
29,346
protected HorizontalLayout buildTitleLayout ( ) { titleLayout = new HorizontalLayout ( ) ; titleLayout . addStyleName ( SPUIStyleDefinitions . WIDGET_TITLE ) ; titleLayout . setSpacing ( false ) ; titleLayout . setMargin ( false ) ; titleLayout . setSizeFull ( ) ; titleLayout . addComponent ( title ) ; titleLayout . setComponentAlignment ( title , Alignment . TOP_LEFT ) ; titleLayout . setExpandRatio ( title , 0.8F ) ; if ( hasHeaderMaximizeSupport ( ) ) { titleLayout . addComponents ( getHeaderMaximizeSupport ( ) . maxMinButton ) ; titleLayout . setComponentAlignment ( getHeaderMaximizeSupport ( ) . maxMinButton , Alignment . TOP_RIGHT ) ; titleLayout . setExpandRatio ( getHeaderMaximizeSupport ( ) . maxMinButton , 0.2F ) ; } return titleLayout ; }
Builds the title layout .
29,347
protected void buildComponent ( ) { addComponent ( titleLayout ) ; setComponentAlignment ( titleLayout , Alignment . TOP_LEFT ) ; setWidth ( 100 , Unit . PERCENTAGE ) ; setImmediate ( true ) ; addStyleName ( "action-history-header" ) ; addStyleName ( "bordered-layout" ) ; addStyleName ( "no-border-bottom" ) ; }
Builds the layout for the header component .
29,348
public static boolean isMaintenanceWindowValid ( final MaintenanceWindowLayout maintenanceWindowLayout , final UINotification notification ) { if ( maintenanceWindowLayout . isEnabled ( ) ) { try { MaintenanceScheduleHelper . validateMaintenanceSchedule ( maintenanceWindowLayout . getMaintenanceSchedule ( ) , maintenanceWindowLayout . getMaintenanceDuration ( ) , maintenanceWindowLayout . getMaintenanceTimeZone ( ) ) ; } catch ( final InvalidMaintenanceScheduleException e ) { LOG . error ( "Maintenance window is not valid" , e ) ; notification . displayValidationError ( e . getMessage ( ) ) ; return false ; } } return true ; }
Check wether the maintenance window is valid or not
29,349
public static ConfirmationTab createAssignmentTab ( final ActionTypeOptionGroupAssignmentLayout actionTypeOptionGroupLayout , final MaintenanceWindowLayout maintenanceWindowLayout , final Consumer < Boolean > saveButtonToggle , final VaadinMessageSource i18n , final UiProperties uiProperties ) { final CheckBox maintenanceWindowControl = maintenanceWindowControl ( i18n , maintenanceWindowLayout , saveButtonToggle ) ; final Link maintenanceWindowHelpLink = maintenanceWindowHelpLinkControl ( uiProperties , i18n ) ; final HorizontalLayout layout = createHorizontalLayout ( maintenanceWindowControl , maintenanceWindowHelpLink ) ; actionTypeOptionGroupLayout . selectDefaultOption ( ) ; initMaintenanceWindow ( maintenanceWindowLayout , saveButtonToggle ) ; addValueChangeListener ( actionTypeOptionGroupLayout , maintenanceWindowControl , maintenanceWindowHelpLink ) ; return createAssignmentTab ( actionTypeOptionGroupLayout , layout , maintenanceWindowLayout ) ; }
Create the Assignment Confirmation Tab
29,350
public static TimeZone getBrowserTimeZone ( ) { if ( ! StringUtils . isEmpty ( fixedTimeZoneProperty ) ) { return TimeZone . getTimeZone ( fixedTimeZoneProperty ) ; } final WebBrowser webBrowser = com . vaadin . server . Page . getCurrent ( ) . getWebBrowser ( ) ; final String [ ] timeZones = TimeZone . getAvailableIDs ( webBrowser . getRawTimezoneOffset ( ) ) ; TimeZone tz = TimeZone . getDefault ( ) ; for ( final String string : timeZones ) { final TimeZone t = TimeZone . getTimeZone ( string ) ; if ( t . getRawOffset ( ) == webBrowser . getRawTimezoneOffset ( ) ) { tz = t ; } } return tz ; }
Get browser time zone or fixed time zone if configured
29,351
public static ZoneId getTimeZoneId ( final TimeZone tz ) { return ZoneId . of ( tz . getID ( ) , ZoneId . SHORT_IDS ) ; }
Get time zone id . ZoneId . SHORT_IDS used get id if time zone is abbreviated like IST .
29,352
public static String getFormattedDate ( final Long lastQueryDate , final String datePattern ) { return formatDate ( lastQueryDate , null , datePattern ) ; }
Get formatted date with browser time zone .
29,353
public static String formatLastModifiedAt ( final BaseEntity baseEntity , final String datePattern ) { if ( baseEntity == null ) { return "" ; } return formatDate ( baseEntity . getLastModifiedAt ( ) , "" , datePattern ) ; }
Get formatted date last modified at by entity .
29,354
public static String getDurationFormattedString ( final long startMillis , final long endMillis , final VaadinMessageSource i18N ) { final String formatDuration = DurationFormatUtils . formatPeriod ( startMillis , endMillis , DURATION_FORMAT , false , getBrowserTimeZone ( ) ) ; final StringBuilder formattedDuration = new StringBuilder ( ) ; final String [ ] split = formatDuration . split ( "," ) ; for ( int index = 0 ; index < split . length ; index ++ ) { if ( index != 0 && formattedDuration . length ( ) > 0 ) { formattedDuration . append ( ' ' ) ; } final int value = Integer . parseInt ( split [ index ] ) ; if ( value != 0 ) { final String suffix = ( value == 1 ) ? i18N . getMessage ( DURATION_I18N . get ( index ) . getSingle ( ) ) : i18N . getMessage ( DURATION_I18N . get ( index ) . getPlural ( ) ) ; formattedDuration . append ( value ) . append ( ' ' ) . append ( suffix ) ; } } return formattedDuration . toString ( ) ; }
Creates a formatted string of a duration in format 1 year 2 months 3 days 4 hours 5 minutes 6 seconds zero values will be ignored in the formatted string .
29,355
private Label getSWModlabel ( final String labelName , final SoftwareModule swModule ) { return SPUIComponentProvider . createNameValueLabel ( labelName + " : " , swModule . getName ( ) , swModule . getVersion ( ) ) ; }
Create Label for SW Module .
29,356
public static < T > Specification < T > combineWithAnd ( final List < Specification < T > > specList ) { if ( specList . isEmpty ( ) ) { return null ; } Specification < T > specs = Specification . where ( specList . get ( 0 ) ) ; for ( final Specification < T > specification : specList . subList ( 1 , specList . size ( ) ) ) { specs = specs . and ( specification ) ; } return specs ; }
Combine all given specification with and . The first specification is the where clause .
29,357
public static String getDistributionBarAsHTMLString ( final Map < Status , Long > statusTotalCountMap ) { final StringBuilder htmlString = new StringBuilder ( ) ; final Map < Status , Long > statusMapWithNonZeroValues = getStatusMapWithNonZeroValues ( statusTotalCountMap ) ; final Long totalValue = getTotalSizes ( statusTotalCountMap ) ; if ( statusMapWithNonZeroValues . size ( ) <= 0 ) { return getUnintialisedBar ( ) ; } int partIndex = 1 ; htmlString . append ( getParentDivStart ( ) ) ; for ( final Map . Entry < Status , Long > entry : statusMapWithNonZeroValues . entrySet ( ) ) { if ( entry . getValue ( ) > 0 ) { htmlString . append ( getPart ( partIndex , entry . getKey ( ) , entry . getValue ( ) , totalValue , statusMapWithNonZeroValues . size ( ) ) ) ; partIndex ++ ; } } htmlString . append ( HTML_DIV_END ) ; return htmlString . toString ( ) ; }
Returns a string with details of status and count .
29,358
public static Map < Status , Long > getStatusMapWithNonZeroValues ( final Map < Status , Long > statusTotalCountMap ) { return statusTotalCountMap . entrySet ( ) . stream ( ) . filter ( p -> p . getValue ( ) > 0 ) . collect ( Collectors . toMap ( p -> p . getKey ( ) , p -> p . getValue ( ) ) ) ; }
Returns the map with status having non zero values .
29,359
public static String getTooltip ( final Map < Status , Long > statusCountMap ) { final Map < Status , Long > nonZeroStatusCountMap = DistributionBarHelper . getStatusMapWithNonZeroValues ( statusCountMap ) ; final StringBuilder tooltip = new StringBuilder ( ) ; for ( final Entry < Status , Long > entry : nonZeroStatusCountMap . entrySet ( ) ) { tooltip . append ( entry . getKey ( ) . toString ( ) . toLowerCase ( ) ) . append ( " : " ) . append ( entry . getValue ( ) ) . append ( "<br>" ) ; } return tooltip . toString ( ) ; }
Returns tool tip for progress bar .
29,360
public static String durationToFormattedString ( final Duration duration ) { if ( duration == null ) { return null ; } return LocalTime . ofNanoOfDay ( duration . toNanos ( ) ) . format ( DateTimeFormatter . ofPattern ( DURATION_FORMAT ) ) ; }
Converts a Duration into a formatted String
29,361
public static Duration formattedStringToDuration ( final String formattedDuration ) { if ( formattedDuration == null ) { return null ; } final TemporalAccessor ta = DateTimeFormatter . ofPattern ( DURATION_FORMAT ) . parse ( formattedDuration . trim ( ) ) ; return Duration . between ( LocalTime . MIDNIGHT , LocalTime . from ( ta ) ) ; }
Converts a formatted String into a Duration object .
29,362
public static Duration getDurationByTimeValues ( final long hours , final long minutes , final long seconds ) { return Duration . ofHours ( hours ) . plusMinutes ( minutes ) . plusSeconds ( seconds ) ; }
converts values of time constants to a Duration object ..
29,363
private void resetComponents ( ) { defineGroupsLayout . resetComponents ( ) ; editRolloutEnabled = false ; rolloutName . clear ( ) ; targetFilterQuery . clear ( ) ; resetFields ( ) ; enableFields ( ) ; populateDistributionSet ( ) ; populateTargetFilterQuery ( ) ; setDefaultSaveStartGroupOption ( ) ; groupsLegendLayout . reset ( ) ; groupSizeLabel . setVisible ( false ) ; noOfGroups . setVisible ( true ) ; removeComponent ( 1 , 2 ) ; addComponent ( targetFilterQueryCombo , 1 , 2 ) ; addGroupsLegendLayout ( ) ; addGroupsDefinitionTabs ( ) ; actionTypeOptionGroupLayout . selectDefaultOption ( ) ; autoStartOptionGroupLayout . selectDefaultOption ( ) ; totalTargetsCount = 0L ; rollout = null ; groupsDefinitionTabs . setVisible ( true ) ; groupsDefinitionTabs . setSelectedTab ( 0 ) ; approvalLabel . setVisible ( false ) ; approvalButtonsLayout . setVisible ( false ) ; approveButtonsGroup . clear ( ) ; approvalRemarkField . clear ( ) ; approveButtonsGroup . removeAllValidators ( ) ; }
Reset the field values .
29,364
public void resetComponents ( ) { dsNamecomboBox . clear ( ) ; descTextArea . clear ( ) ; targetBulkTokenTags . getTokenField ( ) . clear ( ) ; targetBulkTokenTags . populateContainer ( ) ; progressBar . setValue ( 0F ) ; progressBar . setVisible ( false ) ; managementUIState . getTargetTableFilters ( ) . getBulkUpload ( ) . setProgressBarCurrentValue ( 0F ) ; targetsCountLabel . setVisible ( false ) ; }
Reset the values in popup .
29,365
public void restoreComponentsValue ( ) { targetBulkTokenTags . populateContainer ( ) ; final TargetBulkUpload targetBulkUpload = managementUIState . getTargetTableFilters ( ) . getBulkUpload ( ) ; progressBar . setValue ( targetBulkUpload . getProgressBarCurrentValue ( ) ) ; dsNamecomboBox . setValue ( targetBulkUpload . getDsNameAndVersion ( ) ) ; descTextArea . setValue ( targetBulkUpload . getDescription ( ) ) ; targetBulkTokenTags . addAlreadySelectedTags ( ) ; if ( targetBulkUpload . getProgressBarCurrentValue ( ) >= 1 ) { targetsCountLabel . setVisible ( true ) ; targetsCountLabel . setCaption ( getFormattedCountLabelValue ( targetBulkUpload . getSucessfulUploadCount ( ) , targetBulkUpload . getFailedUploadCount ( ) ) ) ; } }
Restore the target bulk upload layout field values .
29,366
public void onUploadCompletion ( ) { final TargetBulkUpload targetBulkUpload = managementUIState . getTargetTableFilters ( ) . getBulkUpload ( ) ; final String targetCountLabel = getFormattedCountLabelValue ( targetBulkUpload . getSucessfulUploadCount ( ) , targetBulkUpload . getFailedUploadCount ( ) ) ; getTargetsCountLabel ( ) . setVisible ( true ) ; getTargetsCountLabel ( ) . setCaption ( targetCountLabel ) ; closeButton . setEnabled ( true ) ; minimizeButton . setEnabled ( false ) ; }
Actions once bulk upload is completed .
29,367
public Window getWindow ( ) { managementUIState . setBulkUploadWindowMinimised ( false ) ; bulkUploadWindow = new WindowBuilder ( SPUIDefinitions . CREATE_UPDATE_WINDOW ) . caption ( "" ) . content ( this ) . buildWindow ( ) ; bulkUploadWindow . addStyleName ( "bulk-upload-window" ) ; bulkUploadWindow . setImmediate ( true ) ; if ( managementUIState . getTargetTableFilters ( ) . getBulkUpload ( ) . getProgressBarCurrentValue ( ) <= 0 ) { bulkUploader . getUpload ( ) . setEnabled ( true ) ; } else { bulkUploader . getUpload ( ) . setEnabled ( false ) ; } return bulkUploadWindow ; }
create and return window
29,368
protected void init ( ) { this . gridHeader = createGridHeader ( ) ; this . grid = createGrid ( ) ; buildLayout ( ) ; setSizeFull ( ) ; setImmediate ( true ) ; if ( doSubscribeToEventBus ( ) ) { eventBus . subscribe ( this ) ; } }
Initializes this layout that presents a header and a grid .
29,369
protected void buildLayout ( ) { setSizeFull ( ) ; setSpacing ( true ) ; setMargin ( false ) ; setStyleName ( "group" ) ; final VerticalLayout gridHeaderLayout = new VerticalLayout ( ) ; gridHeaderLayout . setSizeFull ( ) ; gridHeaderLayout . setSpacing ( false ) ; gridHeaderLayout . setMargin ( false ) ; gridHeaderLayout . setStyleName ( "table-layout" ) ; gridHeaderLayout . addComponent ( gridHeader ) ; gridHeaderLayout . setComponentAlignment ( gridHeader , Alignment . TOP_CENTER ) ; gridHeaderLayout . addComponent ( grid ) ; gridHeaderLayout . setComponentAlignment ( grid , Alignment . TOP_CENTER ) ; gridHeaderLayout . setExpandRatio ( grid , 1.0F ) ; addComponent ( gridHeaderLayout ) ; setComponentAlignment ( gridHeaderLayout , Alignment . TOP_CENTER ) ; setExpandRatio ( gridHeaderLayout , 1.0F ) ; if ( hasFooterSupport ( ) ) { final Layout footerLayout = getFooterSupport ( ) . createFooterMessageComponent ( ) ; addComponent ( footerLayout ) ; setComponentAlignment ( footerLayout , Alignment . BOTTOM_CENTER ) ; } }
Layouts header grid and optional footer .
29,370
public void registerDetails ( final AbstractGrid < ? > . DetailsSupport details ) { grid . addSelectionListener ( event -> { final Long masterId = ( Long ) event . getSelected ( ) . stream ( ) . findFirst ( ) . orElse ( null ) ; details . populateMasterDataAndRecalculateContainer ( masterId ) ; } ) ; }
Registers the selection of this grid as master for another grid that displays the details .
29,371
public < T , I extends Serializable > Slice < T > findAll ( final Specification < T > spec , final Pageable pageable , final Class < T > domainClass ) { final SimpleJpaNoCountRepository < T , I > noCountDao = new SimpleJpaNoCountRepository < > ( domainClass , em ) ; return noCountDao . findAll ( spec , pageable ) ; }
Searches without the need for an extra count query .
29,372
public TenantUsage addUsageData ( final String key , final String value ) { getLazyUsageData ( ) . put ( key , value ) ; return this ; }
Add a key and value as usage data to the system usage stats .
29,373
public void setChartState ( final List < Long > groupTargetCounts , final Long totalTargetsCount ) { getState ( ) . setGroupTargetCounts ( groupTargetCounts ) ; getState ( ) . setTotalTargetCount ( totalTargetsCount ) ; markAsDirty ( ) ; }
Updates the state of the chart
29,374
@ Bean ( name = AbstractApplicationContext . APPLICATION_EVENT_MULTICASTER_BEAN_NAME ) ApplicationEventMulticaster applicationEventMulticaster ( @ Qualifier ( "asyncExecutor" ) final Executor executor , final TenantAware tenantAware ) { final SimpleApplicationEventMulticaster simpleApplicationEventMulticaster = new TenantAwareApplicationEventPublisher ( tenantAware , applicationEventFilter ( ) ) ; simpleApplicationEventMulticaster . setTaskExecutor ( executor ) ; return simpleApplicationEventMulticaster ; }
Server internal event publisher that allows parallel event processing if the event listener is marked as so .
29,375
@ Transactional ( propagation = Propagation . REQUIRES_NEW ) public void check ( ) { LOGGER . debug ( "Auto assigned check call" ) ; final PageRequest pageRequest = PageRequest . of ( 0 , PAGE_SIZE ) ; final Page < TargetFilterQuery > filterQueries = targetFilterQueryManagement . findWithAutoAssignDS ( pageRequest ) ; for ( final TargetFilterQuery filterQuery : filterQueries ) { checkByTargetFilterQueryAndAssignDS ( filterQuery ) ; } }
Checks all target filter queries with an auto assign distribution set and triggers the check and assignment to targets that don t have the design DS yet
29,376
private void checkByTargetFilterQueryAndAssignDS ( final TargetFilterQuery targetFilterQuery ) { try { final DistributionSet distributionSet = targetFilterQuery . getAutoAssignDistributionSet ( ) ; int count ; do { count = runTransactionalAssignment ( targetFilterQuery , distributionSet . getId ( ) ) ; } while ( count == PAGE_SIZE ) ; } catch ( PersistenceException | AbstractServerRtException e ) { LOGGER . error ( "Error during auto assign check of target filter query " + targetFilterQuery . getId ( ) , e ) ; } }
Fetches the distribution set gets all controllerIds and assigns the DS to them . Catches PersistenceException and own exceptions derived from AbstractServerRtException
29,377
private int runTransactionalAssignment ( final TargetFilterQuery targetFilterQuery , final Long dsId ) { final String actionMessage = String . format ( ACTION_MESSAGE , targetFilterQuery . getName ( ) ) ; return DeploymentHelper . runInNewTransaction ( transactionManager , "autoAssignDSToTargets" , Isolation . READ_COMMITTED . value ( ) , status -> { final List < TargetWithActionType > targets = getTargetsWithActionType ( targetFilterQuery . getQuery ( ) , dsId , targetFilterQuery . getAutoAssignActionType ( ) , PAGE_SIZE ) ; final int count = targets . size ( ) ; if ( count > 0 ) { deploymentManagement . assignDistributionSet ( dsId , targets , actionMessage ) ; } return count ; } ) ; }
Runs one page of target assignments within a dedicated transaction
29,378
private List < TargetWithActionType > getTargetsWithActionType ( final String targetFilterQuery , final Long dsId , final ActionType type , final int count ) { final Page < Target > targets = targetManagement . findByTargetFilterQueryAndNonDS ( PageRequest . of ( 0 , count ) , dsId , targetFilterQuery ) ; final ActionType autoAssignActionType = type == null ? ActionType . FORCED : type ; return targets . getContent ( ) . stream ( ) . map ( t -> new TargetWithActionType ( t . getControllerId ( ) , autoAssignActionType , RepositoryModelConstants . NO_FORCE_TIME ) ) . collect ( Collectors . toList ( ) ) ; }
Gets all matching targets with the designated action from the target management
29,379
private String convert ( final T status ) { if ( adapter == null ) { throw new IllegalStateException ( "Adapter must be set before usage! Convertion without adapter is not possible!" ) ; } final StatusFontIcon statusProps = adapter . adapt ( status ) ; if ( statusProps == null ) { return "" ; } final String codePoint = getCodePoint ( statusProps ) ; final String title = statusProps . getTitle ( ) ; return getStatusLabelDetailsInString ( codePoint , statusProps . getStyle ( ) , title , statusProps . getId ( ) , statusProps . isDisabled ( ) ) ; }
Converts the model data to a string representation of the presentation label that is used on client - side to style the label .
29,380
private static Component buildLabelWrapper ( final ValoMenuItemButton menuItemButton , final Component notificationLabel ) { final CssLayout dashboardWrapper = new CssLayout ( menuItemButton ) ; dashboardWrapper . addStyleName ( "labelwrapper" ) ; dashboardWrapper . addStyleName ( ValoTheme . MENU_ITEM ) ; notificationLabel . addStyleName ( ValoTheme . MENU_BADGE ) ; notificationLabel . setWidthUndefined ( ) ; notificationLabel . setVisible ( false ) ; notificationLabel . setId ( UIComponentIdProvider . NOTIFICATION_MENU_ID + menuItemButton . getCaption ( ) . toLowerCase ( ) ) ; dashboardWrapper . addComponent ( notificationLabel ) ; return dashboardWrapper ; }
Creates the wrapper which contains the menu item and the adjacent label for displaying the occurred events
29,381
private List < DashboardMenuItem > getAccessibleViews ( ) { return this . dashboardVaadinViews . stream ( ) . filter ( view -> permissionService . hasAtLeastOnePermission ( view . getPermissions ( ) ) ) . collect ( Collectors . toList ( ) ) ; }
Returns all views which are currently accessible by the current logged in user .
29,382
public DashboardMenuItem getByViewName ( final String viewName ) { final Optional < DashboardMenuItem > findFirst = dashboardVaadinViews . stream ( ) . filter ( view -> view . getViewName ( ) . equals ( viewName ) ) . findAny ( ) ; if ( ! findFirst . isPresent ( ) ) { return null ; } return findFirst . get ( ) ; }
Returns the dashboard view type by a given view name .
29,383
public boolean isAccessDenied ( final String viewName ) { final List < DashboardMenuItem > accessibleViews = getAccessibleViews ( ) ; boolean accessDeined = Boolean . TRUE . booleanValue ( ) ; for ( final DashboardMenuItem dashboardViewType : accessibleViews ) { if ( dashboardViewType . getViewName ( ) . equals ( viewName ) ) { accessDeined = Boolean . FALSE . booleanValue ( ) ; } } return accessDeined ; }
Is the given view accessible .
29,384
public static void successCancellation ( final JpaAction action , final ActionRepository actionRepository , final TargetRepository targetRepository ) { action . setActive ( false ) ; action . setStatus ( Status . CANCELED ) ; final JpaTarget target = ( JpaTarget ) action . getTarget ( ) ; final List < Action > nextActiveActions = actionRepository . findByTargetAndActiveOrderByIdAsc ( target , true ) . stream ( ) . filter ( a -> ! a . getId ( ) . equals ( action . getId ( ) ) ) . collect ( Collectors . toList ( ) ) ; if ( nextActiveActions . isEmpty ( ) ) { target . setAssignedDistributionSet ( target . getInstalledDistributionSet ( ) ) ; target . setUpdateStatus ( TargetUpdateStatus . IN_SYNC ) ; } else { target . setAssignedDistributionSet ( nextActiveActions . get ( 0 ) . getDistributionSet ( ) ) ; } targetRepository . save ( target ) ; }
This method is called when cancellation has been successful . It sets the action to canceled resets the meta data of the target and in case there is a new action this action is triggered .
29,385
public void displaySuccess ( final String message ) { notificationMessage . showNotification ( SPUIStyleDefinitions . SP_NOTIFICATION_SUCCESS_MESSAGE_STYLE , null , message , true ) ; }
Display success type of notification message .
29,386
public void displayWarning ( final String message ) { notificationMessage . showNotification ( SPUIStyleDefinitions . SP_NOTIFICATION_WARNING_MESSAGE_STYLE , null , message , true ) ; }
Display warning type of notification message .
29,387
public void displayValidationError ( final String message ) { final StringBuilder updatedMsg = new StringBuilder ( FontAwesome . EXCLAMATION_TRIANGLE . getHtml ( ) ) ; updatedMsg . append ( ' ' ) ; updatedMsg . append ( message ) ; notificationMessage . showNotification ( SPUIStyleDefinitions . SP_NOTIFICATION_ERROR_MESSAGE_STYLE , null , updatedMsg . toString ( ) , true ) ; }
Display error type of notification message .
29,388
public final void setOrginaleValues ( ) { for ( final AbstractField < ? > field : allComponents ) { Object value = field . getValue ( ) ; if ( field instanceof Table ) { value = ( ( Table ) field ) . getContainerDataSource ( ) . getItemIds ( ) ; } orginalValues . put ( field , value ) ; } saveButton . setEnabled ( isSaveButtonEnabledAfterValueChange ( null , null ) ) ; }
saves the original values in a Map so we can use them for detecting changes
29,389
public void addComponentListeners ( ) { removeListeners ( ) ; for ( final AbstractField < ? > field : allComponents ) { if ( field instanceof TextChangeNotifier ) { ( ( TextChangeNotifier ) field ) . addTextChangeListener ( new ChangeListener ( field ) ) ; } if ( field instanceof Table ) { ( ( Table ) field ) . addItemSetChangeListener ( new ChangeListener ( field ) ) ; } field . addValueChangeListener ( new ChangeListener ( field ) ) ; } }
adds a listener to a component . Depending on the type of component a valueChange - textChange - or itemSetChangeListener will be added .
29,390
public void updateAllComponents ( final AbstractField < ? > component ) { allComponents . add ( component ) ; component . addValueChangeListener ( new ChangeListener ( component ) ) ; }
Adds the component manually to the allComponents - List and adds a ValueChangeListener to it . Necessary in Update Distribution Type as the CheckBox concerned is an ItemProperty ...
29,391
public CommonDialogWindow buildCommonDialogWindow ( ) { final CommonDialogWindow window = new CommonDialogWindow ( caption , content , helpLink , saveDialogCloseListener , cancelButtonClickListener , layout , i18n ) ; decorateWindow ( window ) ; return window ; }
Build the common dialog window .
29,392
public Window buildWindow ( ) { final Window window = new Window ( caption ) ; window . setContent ( content ) ; window . setSizeUndefined ( ) ; window . setModal ( true ) ; window . setResizable ( false ) ; decorateWindow ( window ) ; if ( SPUIDefinitions . CREATE_UPDATE_WINDOW . equals ( type ) ) { window . setClosable ( false ) ; } return window ; }
Build window based on type .
29,393
void showNotification ( final String styleName , final String caption , final String description , final Boolean autoClose ) { decorate ( styleName , caption , description , autoClose ) ; this . show ( Page . getCurrent ( ) ) ; }
Notification message component .
29,394
@ SuppressWarnings ( "squid:S1166" ) public static Optional < ZonedDateTime > getNextMaintenanceWindow ( final String cronSchedule , final String duration , final String timezone ) { try { final ExecutionTime scheduleExecutor = ExecutionTime . forCron ( getCronFromExpression ( cronSchedule ) ) ; final ZonedDateTime now = ZonedDateTime . now ( ZoneOffset . of ( timezone ) ) ; final ZonedDateTime after = now . minus ( convertToISODuration ( duration ) ) ; final ZonedDateTime next = scheduleExecutor . nextExecution ( after ) ; return Optional . of ( next ) ; } catch ( final RuntimeException ignored ) { return Optional . empty ( ) ; } }
expression or duration is wrong ) we simply return empty value
29,395
public static void validateDuration ( final String duration ) { try { if ( StringUtils . hasText ( duration ) ) { convertDurationToLocalTime ( duration ) ; } } catch ( final DateTimeParseException e ) { throw new InvalidMaintenanceScheduleException ( "Provided duration is not valid" , e , e . getErrorIndex ( ) ) ; } }
Validates the format of the maintenance window duration
29,396
public static void validateCronSchedule ( final String cronSchedule ) { try { if ( StringUtils . hasText ( cronSchedule ) ) { getCronFromExpression ( cronSchedule ) ; } } catch ( final IllegalArgumentException e ) { throw new InvalidMaintenanceScheduleException ( e . getMessage ( ) , e ) ; } }
Validates the format of the maintenance window cron expression
29,397
public void populateActionHistoryDetails ( final Target target ) { if ( null != target ) { ( ( ActionHistoryHeader ) getHeader ( ) ) . updateActionHistoryHeader ( target . getName ( ) ) ; ( ( ActionHistoryGrid ) getGrid ( ) ) . populateSelectedTarget ( target ) ; } else { ( ( ActionHistoryHeader ) getHeader ( ) ) . updateActionHistoryHeader ( " " ) ; } }
Populate action header and table for the target .
29,398
public void incrementUnreadNotification ( final AbstractNotificationView view , final EventContainer < ? > newEventContainer ) { if ( ! view . equals ( currentView ) || newEventContainer . getUnreadNotificationMessageKey ( ) == null ) { return ; } NotificationUnreadValue notificationUnreadValue = unreadNotifications . get ( newEventContainer . getClass ( ) ) ; if ( notificationUnreadValue == null ) { notificationUnreadValue = new NotificationUnreadValue ( 0 , newEventContainer . getUnreadNotificationMessageKey ( ) ) ; unreadNotifications . put ( newEventContainer . getClass ( ) , notificationUnreadValue ) ; } notificationUnreadValue . incrementUnreadNotifications ( ) ; unreadNotificationCounter ++ ; refreshCaption ( ) ; }
Increment the counter .
29,399
protected List < ProxyDistribution > loadBeans ( final int startIndex , final int count ) { Page < DistributionSet > distBeans ; final List < ProxyDistribution > proxyDistributions = new ArrayList < > ( ) ; if ( startIndex == 0 && firstPageDistributionSets != null ) { distBeans = firstPageDistributionSets ; } else if ( pinnedTarget != null ) { final DistributionSetFilterBuilder distributionSetFilterBuilder = new DistributionSetFilterBuilder ( ) . setIsDeleted ( false ) . setIsComplete ( true ) . setSearchText ( searchText ) . setSelectDSWithNoTag ( noTagClicked ) . setTagNames ( distributionTags ) ; distBeans = getDistributionSetManagement ( ) . findByFilterAndAssignedInstalledDsOrderedByLinkTarget ( new OffsetBasedPageRequest ( startIndex , count , sort ) , distributionSetFilterBuilder , pinnedTarget . getControllerId ( ) ) ; } else if ( distributionTags . isEmpty ( ) && StringUtils . isEmpty ( searchText ) && ! noTagClicked ) { distBeans = getDistributionSetManagement ( ) . findByCompleted ( new OffsetBasedPageRequest ( startIndex , count , sort ) , true ) ; } else { final DistributionSetFilter distributionSetFilter = new DistributionSetFilterBuilder ( ) . setIsDeleted ( false ) . setIsComplete ( true ) . setSearchText ( searchText ) . setSelectDSWithNoTag ( noTagClicked ) . setTagNames ( distributionTags ) . build ( ) ; distBeans = getDistributionSetManagement ( ) . findByDistributionSetFilter ( new OffsetBasedPageRequest ( startIndex , count , sort ) , distributionSetFilter ) ; } for ( final DistributionSet distributionSet : distBeans ) { final ProxyDistribution proxyDistribution = new ProxyDistribution ( ) ; proxyDistribution . setName ( distributionSet . getName ( ) ) ; proxyDistribution . setDescription ( distributionSet . getDescription ( ) ) ; proxyDistribution . setId ( distributionSet . getId ( ) ) ; proxyDistribution . setDistId ( distributionSet . getId ( ) ) ; proxyDistribution . setVersion ( distributionSet . getVersion ( ) ) ; proxyDistribution . setCreatedDate ( SPDateTimeUtil . getFormattedDate ( distributionSet . getCreatedAt ( ) ) ) ; proxyDistribution . setLastModifiedDate ( SPDateTimeUtil . getFormattedDate ( distributionSet . getLastModifiedAt ( ) ) ) ; proxyDistribution . setCreatedByUser ( UserDetailsFormatter . loadAndFormatCreatedBy ( distributionSet ) ) ; proxyDistribution . setModifiedByUser ( UserDetailsFormatter . loadAndFormatLastModifiedBy ( distributionSet ) ) ; proxyDistribution . setNameVersion ( HawkbitCommonUtil . getFormattedNameVersion ( distributionSet . getName ( ) , distributionSet . getVersion ( ) ) ) ; proxyDistributions . add ( proxyDistribution ) ; } return proxyDistributions ; }
Load all the Distribution set .