idx
int64
0
165k
question
stringlengths
73
4.15k
target
stringlengths
5
918
len_question
int64
21
890
len_target
int64
3
255
29,300
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 .
89
9
29,301
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
138
10
29,302
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
199
6
29,303
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
169
10
29,304
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 .
40
24
29,305
public static String getFormattedDate ( final Long lastQueryDate , final String datePattern ) { return formatDate ( lastQueryDate , null , datePattern ) ; }
Get formatted date with browser time zone .
35
8
29,306
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 .
55
9
29,307
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 .
256
32
29,308
private Label getSWModlabel ( final String labelName , final SoftwareModule swModule ) { return SPUIComponentProvider . createNameValueLabel ( labelName + " : " , swModule . getName ( ) , swModule . getVersion ( ) ) ; }
Create Label for SW Module .
57
6
29,309
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 .
104
16
29,310
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 .
233
10
29,311
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 .
87
10
29,312
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 .
140
7
29,313
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
64
8
29,314
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 .
81
10
29,315
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 ..
46
11
29,316
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 .
261
6
29,317
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 .
115
7
29,318
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 .
200
10
29,319
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 .
132
8
29,320
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
162
4
29,321
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 .
65
12
29,322
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 .
279
9
29,323
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 .
78
17
29,324
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 .
91
12
29,325
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 .
36
14
29,326
public void setChartState ( final List < Long > groupTargetCounts , final Long totalTargetsCount ) { getState ( ) . setGroupTargetCounts ( groupTargetCounts ) ; getState ( ) . setTotalTargetCount ( totalTargetsCount ) ; markAsDirty ( ) ; }
Updates the state of the chart
67
7
29,327
@ 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 .
123
18
29,328
@ 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
112
28
29,329
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
126
33
29,330
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
184
11
29,331
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 ) ; // the action type is set to FORCED per default (when not explicitly // specified) 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
180
13
29,332
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 ) ; // fail fast 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 .
142
25
29,333
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
170
18
29,334
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 .
66
14
29,335
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 .
86
11
29,336
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 .
103
6
29,337
public static void successCancellation ( final JpaAction action , final ActionRepository actionRepository , final TargetRepository targetRepository ) { // set action inactive 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 .
233
37
29,338
public void displaySuccess ( final String message ) { notificationMessage . showNotification ( SPUIStyleDefinitions . SP_NOTIFICATION_SUCCESS_MESSAGE_STYLE , null , message , true ) ; }
Display success type of notification message .
52
7
29,339
public void displayWarning ( final String message ) { notificationMessage . showNotification ( SPUIStyleDefinitions . SP_NOTIFICATION_WARNING_MESSAGE_STYLE , null , message , true ) ; }
Display warning type of notification message .
50
7
29,340
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 .
105
7
29,341
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
101
16
29,342
public void addComponentListeners ( ) { // avoid duplicate registration 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 .
116
30
29,343
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 ...
41
37
29,344
public CommonDialogWindow buildCommonDialogWindow ( ) { final CommonDialogWindow window = new CommonDialogWindow ( caption , content , helpLink , saveDialogCloseListener , cancelButtonClickListener , layout , i18n ) ; decorateWindow ( window ) ; return window ; }
Build the common dialog window .
57
6
29,345
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 .
96
6
29,346
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 .
51
5
29,347
@ 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
167
11
29,348
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
79
9
29,349
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
81
11
29,350
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 .
90
10
29,351
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 .
171
5
29,352
@ Override 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 ) { // if no search filters available 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 .
669
6
29,353
@ Override public boolean isApprovalNeeded ( final Rollout rollout ) { final UserDetails userDetails = this . getActor ( rollout ) ; final boolean approvalEnabled = this . tenantConfigurationManagement . getConfigurationValue ( TenantConfigurationKey . ROLLOUT_APPROVAL_ENABLED , Boolean . class ) . getValue ( ) ; return approvalEnabled && userDetails . getAuthorities ( ) . stream ( ) . noneMatch ( authority -> SpPermission . APPROVE_ROLLOUT . equals ( authority . getAuthority ( ) ) ) ; }
Returns true if rollout approval is enabled and rollout creator doesn t have approval role .
120
16
29,354
@ Override protected Date handleUnparsableDateString ( final String value ) throws ConversionException { try { return durationFormat . parse ( value ) ; } catch ( final ParseException e1 ) { try { return additionalFormat . parse ( "000000" . substring ( value . length ( ) <= 6 ? value . length ( ) : 6 ) + value ) ; } catch ( final ParseException e2 ) { // if Parsing is not possible ConversionException is thrown } } throw new ConversionException ( "input is not in HH:MM:SS format." ) ; }
This method is called to handle a non - empty date string from the client if the client could not parse it as a Date . In the current case two different parsing schemas are tried . If parsing is not possible a ConversionException is thrown which marks the DurationField as invalid .
122
56
29,355
public void setDuration ( @ NotNull final Duration duration ) { if ( duration . compareTo ( MAXIMUM_DURATION ) > 0 ) { throw new IllegalArgumentException ( "The duaration has to be smaller than 23:59:59." ) ; } super . setValue ( durationToDate ( duration ) ) ; }
Sets the duration value
71
5
29,356
public void setMinimumDuration ( @ NotNull final Duration minimumDuration ) { if ( minimumDuration . compareTo ( MAXIMUM_DURATION ) > 0 ) { throw new IllegalArgumentException ( "The minimum duaration has to be smaller than 23:59:59." ) ; } this . minimumDuration = durationToDate ( minimumDuration ) ; }
Sets the minimal allowed duration value as a String
75
10
29,357
public void setMaximumDuration ( @ NotNull final Duration maximumDuration ) { if ( maximumDuration . compareTo ( MAXIMUM_DURATION ) > 0 ) { throw new IllegalArgumentException ( "The maximum duaration has to be smaller than 23:59:59." ) ; } this . maximumDuration = durationToDate ( maximumDuration ) ; }
Sets the maximum allowed duration value as a String
75
10
29,358
private int compareTimeOfDates ( final Date d1 , final Date d2 ) { final LocalTime lt1 = LocalDateTime . ofInstant ( d1 . toInstant ( ) , ZONEID_UTC ) . toLocalTime ( ) ; final LocalTime lt2 = LocalDateTime . ofInstant ( d2 . toInstant ( ) , ZONEID_UTC ) . toLocalTime ( ) ; return lt1 . compareTo ( lt2 ) ; }
Because parsing done by base class returns a different date than parsing done by the user or converting duration to a date . But for the DurationField comparison only the time is important . This function helps comparing the time and ignores the values for day month and year .
103
51
29,359
private void maxArtifactDetails ( ) { final Boolean flag = ( Boolean ) maxMinButton . getData ( ) ; if ( flag == null || Boolean . FALSE . equals ( flag ) ) { // Clicked on max Button maximizedArtifactDetailsView ( ) ; } else { minimizedArtifactDetailsView ( ) ; } }
will be used by button click listener of action history expand icon .
69
13
29,360
public void createMaxArtifactDetailsTable ( ) { maxArtifactDetailsTable = createArtifactDetailsTable ( ) ; maxArtifactDetailsTable . setId ( UIComponentIdProvider . UPLOAD_ARTIFACT_DETAILS_TABLE_MAX ) ; maxArtifactDetailsTable . setContainerDataSource ( artifactDetailsTable . getContainerDataSource ( ) ) ; addGeneratedColumn ( maxArtifactDetailsTable ) ; if ( ! readOnly ) { addGeneratedColumnButton ( maxArtifactDetailsTable ) ; } setTableColumnDetails ( maxArtifactDetailsTable ) ; }
Create Max artifact details Table .
127
6
29,361
public void populateArtifactDetails ( final SoftwareModule softwareModule ) { if ( softwareModule == null ) { populateArtifactDetails ( null , null ) ; } else { populateArtifactDetails ( softwareModule . getId ( ) , HawkbitCommonUtil . getFormattedNameVersion ( softwareModule . getName ( ) , softwareModule . getVersion ( ) ) ) ; } }
Populate artifact details .
80
5
29,362
private void setTitleOfLayoutHeader ( ) { titleOfArtifactDetails . setValue ( HawkbitCommonUtil . getArtifactoryDetailsLabelId ( "" , i18n ) ) ; titleOfArtifactDetails . setContentMode ( ContentMode . HTML ) ; }
Set title of artifact details header layout .
58
8
29,363
public RolloutGroupConditionBuilder successCondition ( final RolloutGroupSuccessCondition condition , final String expression ) { conditions . setSuccessCondition ( condition ) ; conditions . setSuccessConditionExp ( expression ) ; return this ; }
Sets the finish condition and expression on the builder .
45
11
29,364
public RolloutGroupConditionBuilder successAction ( final RolloutGroupSuccessAction action , final String expression ) { conditions . setSuccessAction ( action ) ; conditions . setSuccessActionExp ( expression ) ; return this ; }
Sets the success action and expression on the builder .
45
11
29,365
public RolloutGroupConditionBuilder errorCondition ( final RolloutGroupErrorCondition condition , final String expression ) { conditions . setErrorCondition ( condition ) ; conditions . setErrorConditionExp ( expression ) ; return this ; }
Sets the error condition and expression on the builder .
45
11
29,366
public RolloutGroupConditionBuilder errorAction ( final RolloutGroupErrorAction action , final String expression ) { conditions . setErrorAction ( action ) ; conditions . setErrorActionExp ( expression ) ; return this ; }
Sets the error action and expression on the builder .
45
11
29,367
public RolloutGroupConditionBuilder withDefaults ( ) { successCondition ( RolloutGroupSuccessCondition . THRESHOLD , "50" ) ; successAction ( RolloutGroupSuccessAction . NEXTGROUP , "" ) ; errorCondition ( RolloutGroupErrorCondition . THRESHOLD , "50" ) ; errorAction ( RolloutGroupErrorAction . PAUSE , "" ) ; return this ; }
Sets condition defaults .
84
5
29,368
@ Override public AnonymousIpResponse anonymousIp ( InetAddress ipAddress ) throws IOException , GeoIp2Exception { return this . get ( ipAddress , AnonymousIpResponse . class , "GeoIP2-Anonymous-IP" ) ; }
Look up an IP address in a GeoIP2 Anonymous IP .
56
13
29,369
@ Override public AsnResponse asn ( InetAddress ipAddress ) throws IOException , GeoIp2Exception { return this . get ( ipAddress , AsnResponse . class , "GeoLite2-ASN" ) ; }
Look up an IP address in a GeoLite2 ASN database .
53
15
29,370
@ Override public ConnectionTypeResponse connectionType ( InetAddress ipAddress ) throws IOException , GeoIp2Exception { return this . get ( ipAddress , ConnectionTypeResponse . class , "GeoIP2-Connection-Type" ) ; }
Look up an IP address in a GeoIP2 Connection Type database .
53
14
29,371
@ Override public DomainResponse domain ( InetAddress ipAddress ) throws IOException , GeoIp2Exception { return this . get ( ipAddress , DomainResponse . class , "GeoIP2-Domain" ) ; }
Look up an IP address in a GeoIP2 Domain database .
48
13
29,372
@ Override public EnterpriseResponse enterprise ( InetAddress ipAddress ) throws IOException , GeoIp2Exception { return this . get ( ipAddress , EnterpriseResponse . class , "Enterprise" ) ; }
Look up an IP address in a GeoIP2 Enterprise database .
44
13
29,373
@ Override public IspResponse isp ( InetAddress ipAddress ) throws IOException , GeoIp2Exception { return this . get ( ipAddress , IspResponse . class , "GeoIP2-ISP" ) ; }
Look up an IP address in a GeoIP2 ISP database .
52
13
29,374
public void addListener ( Listener listener , long listenerCheckMillis ) { queue . add ( listener ) ; long newFrequency = Math . min ( MINIMUM_CHECK_DELAY_MILLIS , listenerCheckMillis ) ; //first listener if ( currentScheduledFrequency . get ( ) == - 1 ) { if ( currentScheduledFrequency . compareAndSet ( - 1 , newFrequency ) ) { fixedSizedScheduler . schedule ( checker , listenerCheckMillis , TimeUnit . MILLISECONDS ) ; } } else { long frequency = currentScheduledFrequency . get ( ) ; if ( frequency > newFrequency ) { currentScheduledFrequency . compareAndSet ( frequency , newFrequency ) ; } } }
Add listener to validation list .
169
6
29,375
public void removeListener ( Listener listener ) { queue . remove ( listener ) ; if ( queue . isEmpty ( ) ) { synchronized ( queue ) { if ( currentScheduledFrequency . get ( ) > 0 && queue . isEmpty ( ) ) { currentScheduledFrequency . set ( - 1 ) ; } } } }
Remove listener to validation list .
72
6
29,376
public TraceObject put ( TraceObject value ) { String key = increment . incrementAndGet ( ) + "- " + DateTimeFormatter . ISO_INSTANT . format ( Instant . now ( ) ) ; return put ( key , value ) ; }
Add value to map .
52
5
29,377
public synchronized String printStack ( ) { StringBuilder sb = new StringBuilder ( ) ; Set < Map . Entry < String , TraceObject > > set = entrySet ( ) ; for ( Map . Entry < String , TraceObject > entry : set ) { TraceObject traceObj = entry . getValue ( ) ; String key = entry . getKey ( ) ; String indicator = "" ; switch ( traceObj . getIndicatorFlag ( ) ) { case TraceObject . NOT_COMPRESSED : break ; case TraceObject . COMPRESSED_PROTOCOL_NOT_COMPRESSED_PACKET : indicator = " (compressed protocol - packet not compressed)" ; break ; case TraceObject . COMPRESSED_PROTOCOL_COMPRESSED_PACKET : indicator = " (compressed protocol - packet compressed)" ; break ; default : break ; } if ( traceObj . isSend ( ) ) { sb . append ( "\nsend at -exchange:" ) ; } else { sb . append ( "\nread at -exchange:" ) ; } sb . append ( key ) . append ( indicator ) . append ( Utils . hexdump ( traceObj . getBuf ( ) ) ) ; traceObj . remove ( ) ; } this . clear ( ) ; return sb . toString ( ) ; }
Value of trace cache in a readable format .
285
9
29,378
public synchronized void clearMemory ( ) { Collection < TraceObject > traceObjects = values ( ) ; for ( TraceObject traceObject : traceObjects ) { traceObject . remove ( ) ; } this . clear ( ) ; }
Permit to clear array s of array to help garbage .
48
12
29,379
private Object handleFailOver ( SQLException qe , Method method , Object [ ] args , Protocol protocol ) throws Throwable { HostAddress failHostAddress = null ; boolean failIsMaster = true ; if ( protocol != null ) { failHostAddress = protocol . getHostAddress ( ) ; failIsMaster = protocol . isMasterConnection ( ) ; } HandleErrorResult handleErrorResult = listener . handleFailover ( qe , method , args , protocol ) ; if ( handleErrorResult . mustThrowError ) { listener . throwFailoverMessage ( failHostAddress , failIsMaster , qe , handleErrorResult . isReconnected ) ; } return handleErrorResult . resultObject ; }
After a connection exception launch failover .
148
8
29,380
public boolean hasToHandleFailover ( SQLException exception ) { return exception . getSQLState ( ) != null && ( exception . getSQLState ( ) . startsWith ( "08" ) || ( exception . getSQLState ( ) . equals ( "70100" ) && 1927 == exception . getErrorCode ( ) ) ) ; }
Check if this Sqlerror is a connection exception . if that s the case must be handle by failover
73
23
29,381
public void reconnect ( ) throws SQLException { try { listener . reconnect ( ) ; } catch ( SQLException e ) { ExceptionMapper . throwException ( e , null , null ) ; } }
Launch reconnect implementation .
45
4
29,382
public String readStringNullEnd ( final Charset charset ) { int initialPosition = position ; int cnt = 0 ; while ( remaining ( ) > 0 && ( buf [ position ++ ] != 0 ) ) { cnt ++ ; } return new String ( buf , initialPosition , cnt , charset ) ; }
Reads a string from the buffer looks for a 0 to end the string .
68
16
29,383
public byte [ ] readBytesNullEnd ( ) { int initialPosition = position ; int cnt = 0 ; while ( remaining ( ) > 0 && ( buf [ position ++ ] != 0 ) ) { cnt ++ ; } final byte [ ] tmpArr = new byte [ cnt ] ; System . arraycopy ( buf , initialPosition , tmpArr , 0 , cnt ) ; return tmpArr ; }
Reads a byte array from the buffer looks for a 0 to end the array .
88
17
29,384
public String readStringLengthEncoded ( final Charset charset ) { int length = ( int ) getLengthEncodedNumeric ( ) ; String string = new String ( buf , position , length , charset ) ; position += length ; return string ; }
Reads length - encoded string .
55
7
29,385
public String readString ( final int numberOfBytes ) { position += numberOfBytes ; return new String ( buf , position - numberOfBytes , numberOfBytes ) ; }
Read String with defined length .
36
6
29,386
public byte [ ] readRawBytes ( final int numberOfBytes ) { final byte [ ] tmpArr = new byte [ numberOfBytes ] ; System . arraycopy ( buf , position , tmpArr , 0 , numberOfBytes ) ; position += numberOfBytes ; return tmpArr ; }
Read raw data .
63
4
29,387
public void skipLengthEncodedBytes ( ) { int type = this . buf [ this . position ++ ] & 0xff ; switch ( type ) { case 251 : break ; case 252 : position += 2 + ( 0xffff & ( ( ( buf [ position ] & 0xff ) + ( ( buf [ position + 1 ] & 0xff ) << 8 ) ) ) ) ; break ; case 253 : position += 3 + ( 0xffffff & ( ( buf [ position ] & 0xff ) + ( ( buf [ position + 1 ] & 0xff ) << 8 ) + ( ( buf [ position + 2 ] & 0xff ) << 16 ) ) ) ; break ; case 254 : position += 8 + ( ( buf [ position ] & 0xff ) + ( ( long ) ( buf [ position + 1 ] & 0xff ) << 8 ) + ( ( long ) ( buf [ position + 2 ] & 0xff ) << 16 ) + ( ( long ) ( buf [ position + 3 ] & 0xff ) << 24 ) + ( ( long ) ( buf [ position + 4 ] & 0xff ) << 32 ) + ( ( long ) ( buf [ position + 5 ] & 0xff ) << 40 ) + ( ( long ) ( buf [ position + 6 ] & 0xff ) << 48 ) + ( ( long ) ( buf [ position + 7 ] & 0xff ) << 56 ) ) ; break ; default : position += type ; break ; } }
Skip next length encode binary data .
305
7
29,388
public byte [ ] getLengthEncodedBytes ( ) { int type = this . buf [ this . position ++ ] & 0xff ; int length ; switch ( type ) { case 251 : return null ; case 252 : length = 0xffff & readShort ( ) ; break ; case 253 : length = 0xffffff & read24bitword ( ) ; break ; case 254 : length = ( int ) ( ( buf [ position ++ ] & 0xff ) + ( ( long ) ( buf [ position ++ ] & 0xff ) << 8 ) + ( ( long ) ( buf [ position ++ ] & 0xff ) << 16 ) + ( ( long ) ( buf [ position ++ ] & 0xff ) << 24 ) + ( ( long ) ( buf [ position ++ ] & 0xff ) << 32 ) + ( ( long ) ( buf [ position ++ ] & 0xff ) << 40 ) + ( ( long ) ( buf [ position ++ ] & 0xff ) << 48 ) + ( ( long ) ( buf [ position ++ ] & 0xff ) << 56 ) ) ; break ; default : length = type ; break ; } byte [ ] tmpBuf = new byte [ length ] ; System . arraycopy ( buf , position , tmpBuf , 0 , length ) ; position += length ; return tmpBuf ; }
Get next data bytes with length encoded prefix .
276
9
29,389
public void writeStringSmallLength ( byte [ ] value ) { int length = value . length ; while ( remaining ( ) < length + 1 ) { grow ( ) ; } buf [ position ++ ] = ( byte ) length ; System . arraycopy ( value , 0 , buf , position , length ) ; position += length ; }
Write value with length encoded prefix . value length MUST be less than 251 char
68
15
29,390
public void writeBytes ( byte header , byte [ ] bytes ) { int length = bytes . length ; while ( remaining ( ) < length + 10 ) { grow ( ) ; } writeLength ( length + 1 ) ; buf [ position ++ ] = header ; System . arraycopy ( bytes , 0 , buf , position , length ) ; position += length ; }
Write bytes .
74
3
29,391
public void writeLength ( long length ) { if ( length < 251 ) { buf [ position ++ ] = ( byte ) length ; } else if ( length < 65536 ) { buf [ position ++ ] = ( byte ) 0xfc ; buf [ position ++ ] = ( byte ) length ; buf [ position ++ ] = ( byte ) ( length >>> 8 ) ; } else if ( length < 16777216 ) { buf [ position ++ ] = ( byte ) 0xfd ; buf [ position ++ ] = ( byte ) length ; buf [ position ++ ] = ( byte ) ( length >>> 8 ) ; buf [ position ++ ] = ( byte ) ( length >>> 16 ) ; } else { buf [ position ++ ] = ( byte ) 0xfe ; buf [ position ++ ] = ( byte ) length ; buf [ position ++ ] = ( byte ) ( length >>> 8 ) ; buf [ position ++ ] = ( byte ) ( length >>> 16 ) ; buf [ position ++ ] = ( byte ) ( length >>> 24 ) ; buf [ position ++ ] = ( byte ) ( length >>> 32 ) ; buf [ position ++ ] = ( byte ) ( length >>> 40 ) ; buf [ position ++ ] = ( byte ) ( length >>> 48 ) ; buf [ position ++ ] = ( byte ) ( length >>> 54 ) ; } }
Write length .
276
3
29,392
public static void writeCmd ( final int statementId , final ParameterHolder [ ] parameters , final int parameterCount , ColumnType [ ] parameterTypeHeader , final PacketOutputStream pos , final byte cursorFlag ) throws IOException { pos . write ( Packet . COM_STMT_EXECUTE ) ; pos . writeInt ( statementId ) ; pos . write ( cursorFlag ) ; pos . writeInt ( 1 ) ; //Iteration pos //create null bitmap if ( parameterCount > 0 ) { int nullCount = ( parameterCount + 7 ) / 8 ; byte [ ] nullBitsBuffer = new byte [ nullCount ] ; for ( int i = 0 ; i < parameterCount ; i ++ ) { if ( parameters [ i ] . isNullData ( ) ) { nullBitsBuffer [ i / 8 ] |= ( 1 << ( i % 8 ) ) ; } } pos . write ( nullBitsBuffer , 0 , nullCount ) ; //check if parameters type (using setXXX) have change since previous request, and resend new header type if so boolean mustSendHeaderType = false ; if ( parameterTypeHeader [ 0 ] == null ) { mustSendHeaderType = true ; } else { for ( int i = 0 ; i < parameterCount ; i ++ ) { if ( ! parameterTypeHeader [ i ] . equals ( parameters [ i ] . getColumnType ( ) ) ) { mustSendHeaderType = true ; break ; } } } if ( mustSendHeaderType ) { pos . write ( ( byte ) 0x01 ) ; //Store types of parameters in first in first package that is sent to the server. for ( int i = 0 ; i < parameterCount ; i ++ ) { parameterTypeHeader [ i ] = parameters [ i ] . getColumnType ( ) ; pos . writeShort ( parameterTypeHeader [ i ] . getType ( ) ) ; } } else { pos . write ( ( byte ) 0x00 ) ; } } for ( int i = 0 ; i < parameterCount ; i ++ ) { ParameterHolder holder = parameters [ i ] ; if ( ! holder . isNullData ( ) && ! holder . isLongData ( ) ) { holder . writeBinary ( pos ) ; } } }
Write COM_STMT_EXECUTE sub - command to output buffer .
478
16
29,393
public static void send ( final PacketOutputStream pos , final int statementId , final ParameterHolder [ ] parameters , final int parameterCount , ColumnType [ ] parameterTypeHeader , byte cursorFlag ) throws IOException { pos . startPacket ( 0 ) ; writeCmd ( statementId , parameters , parameterCount , parameterTypeHeader , pos , cursorFlag ) ; pos . flush ( ) ; }
Send a prepare statement binary stream .
84
7
29,394
private void execute ( String command ) throws XAException { try { connection . createStatement ( ) . execute ( command ) ; } catch ( SQLException sqle ) { throw mapXaException ( sqle ) ; } }
Execute a query .
49
5
29,395
private String exWithQuery ( String message , PrepareResult serverPrepareResult , ParameterHolder [ ] parameters ) { if ( options . dumpQueriesOnException ) { StringBuilder sql = new StringBuilder ( serverPrepareResult . getSql ( ) ) ; if ( serverPrepareResult . getParamCount ( ) > 0 ) { sql . append ( ", parameters [" ) ; if ( parameters . length > 0 ) { for ( int i = 0 ; i < Math . min ( parameters . length , serverPrepareResult . getParamCount ( ) ) ; i ++ ) { sql . append ( parameters [ i ] . toString ( ) ) . append ( "," ) ; } sql = new StringBuilder ( sql . substring ( 0 , sql . length ( ) - 1 ) ) ; } sql . append ( "]" ) ; } if ( options . maxQuerySizeToLog != 0 && sql . length ( ) > options . maxQuerySizeToLog - 3 ) { return message + "\nQuery is: " + sql . substring ( 0 , options . maxQuerySizeToLog - 3 ) + "..." + "\njava thread: " + Thread . currentThread ( ) . getName ( ) ; } else { return message + "\nQuery is: " + sql + "\njava thread: " + Thread . currentThread ( ) . getName ( ) ; } } return message ; }
Return exception message with query .
297
6
29,396
public byte [ ] getPacketArray ( boolean reUsable ) throws IOException { byte [ ] cachePacket = getNextCachePacket ( ) ; if ( cachePacket != null ) { return cachePacket ; } //loop until having the whole packet do { //Read 7 byte header readBlocking ( header , 7 ) ; int compressedLength = ( header [ 0 ] & 0xff ) + ( ( header [ 1 ] & 0xff ) << 8 ) + ( ( header [ 2 ] & 0xff ) << 16 ) ; compressPacketSeq = header [ 3 ] & 0xff ; int decompressedLength = ( header [ 4 ] & 0xff ) + ( ( header [ 5 ] & 0xff ) << 8 ) + ( ( header [ 6 ] & 0xff ) << 16 ) ; byte [ ] rawBytes ; if ( reUsable && decompressedLength == 0 && compressedLength < REUSABLE_BUFFER_LENGTH ) { rawBytes = reusableArray ; } else { rawBytes = new byte [ decompressedLength != 0 ? decompressedLength : compressedLength ] ; } readCompressBlocking ( rawBytes , compressedLength , decompressedLength ) ; if ( traceCache != null ) { int length = decompressedLength != 0 ? decompressedLength : compressedLength ; traceCache . put ( new TraceObject ( false , decompressedLength == 0 ? COMPRESSED_PROTOCOL_NOT_COMPRESSED_PACKET : COMPRESSED_PROTOCOL_COMPRESSED_PACKET , Arrays . copyOfRange ( header , 0 , 7 ) , Arrays . copyOfRange ( rawBytes , 0 , length > 1000 ? 1000 : length ) ) ) ; } if ( logger . isTraceEnabled ( ) ) { int length = decompressedLength != 0 ? decompressedLength : compressedLength ; logger . trace ( "read {} {}{}" , ( decompressedLength == 0 ? "uncompress" : "compress" ) , serverThreadLog , Utils . hexdump ( maxQuerySizeToLog - 7 , 0 , length , header , rawBytes ) ) ; } cache ( rawBytes , decompressedLength == 0 ? compressedLength : decompressedLength ) ; byte [ ] packet = getNextCachePacket ( ) ; if ( packet != null ) { return packet ; } } while ( true ) ; }
Get next packet . Packet can be compressed and if so can contain many standard packet .
502
18
29,397
public static void throwException ( SQLException exception , MariaDbConnection connection , MariaDbStatement statement ) throws SQLException { throw getException ( exception , connection , statement , false ) ; }
Helper to throw exception .
42
5
29,398
public static void checkConnectionException ( SQLException exception , MariaDbConnection connection ) { if ( exception . getSQLState ( ) != null ) { SqlStates state = SqlStates . fromString ( exception . getSQLState ( ) ) ; if ( SqlStates . CONNECTION_EXCEPTION . equals ( state ) ) { connection . setHostFailed ( ) ; if ( connection . pooledConnection != null ) { connection . pooledConnection . fireConnectionErrorOccured ( exception ) ; } } } }
Check connection exception to report to poolConnection listeners .
110
10
29,399
public static MariaDbConnection newConnection ( UrlParser urlParser , GlobalStateInfo globalInfo ) throws SQLException { if ( urlParser . getOptions ( ) . pool ) { return Pools . retrievePool ( urlParser ) . getConnection ( ) ; } Protocol protocol = Utils . retrieveProxy ( urlParser , globalInfo ) ; return new MariaDbConnection ( protocol ) ; }
Create new connection Object .
82
5