idx int64 0 41.2k | question stringlengths 73 5.81k | target stringlengths 5 918 |
|---|---|---|
10,000 | private static BlocksGroup intersect ( BlocksGroup group1 , BlocksGroup group2 ) { BlocksGroup intersection = new BlocksGroup ( ) ; List < Block > list1 = group1 . blocks ; List < Block > list2 = group2 . blocks ; int i = 0 ; int j = 0 ; while ( i < list1 . size ( ) && j < list2 . size ( ) ) { Block block1 = list1 . get ( i ) ; Block block2 = list2 . get ( j ) ; int c = RESOURCE_ID_COMPARATOR . compare ( block1 . getResourceId ( ) , block2 . getResourceId ( ) ) ; if ( c > 0 ) { j ++ ; continue ; } if ( c < 0 ) { i ++ ; continue ; } if ( c == 0 ) { c = block1 . getIndexInFile ( ) + 1 - block2 . getIndexInFile ( ) ; } if ( c == 0 ) { i ++ ; j ++ ; intersection . blocks . add ( block2 ) ; } if ( c > 0 ) { j ++ ; } if ( c < 0 ) { i ++ ; } } return intersection ; } | Intersection of two groups is a group which contains blocks from second group that have corresponding block from first group with same resource id and with corrected index . |
10,001 | private static boolean subsumedBy ( BlocksGroup group1 , BlocksGroup group2 , int indexCorrection ) { List < Block > list1 = group1 . blocks ; List < Block > list2 = group2 . blocks ; int i = 0 ; int j = 0 ; while ( i < list1 . size ( ) && j < list2 . size ( ) ) { Block block1 = list1 . get ( i ) ; Block block2 = list2 . get ( j ) ; int c = RESOURCE_ID_COMPARATOR . compare ( block1 . getResourceId ( ) , block2 . getResourceId ( ) ) ; if ( c != 0 ) { j ++ ; continue ; } c = block1 . getIndexInFile ( ) - indexCorrection - block2 . getIndexInFile ( ) ; if ( c < 0 ) { break ; } if ( c != 0 ) { j ++ ; } if ( c == 0 ) { i ++ ; j ++ ; } } return i == list1 . size ( ) ; } | One group is subsumed by another group when each block from first group has corresponding block from second group with same resource id and with corrected index . |
10,002 | public RuleDto persistAndIndex ( DbSession dbSession , NewAdHocRule adHoc , OrganizationDto organizationDto ) { RuleDao dao = dbClient . ruleDao ( ) ; Optional < RuleDto > existingRuleDtoOpt = dao . selectByKey ( dbSession , organizationDto , adHoc . getKey ( ) ) ; RuleMetadataDto metadata ; long now = system2 . now ( ) ; if ( ! existingRuleDtoOpt . isPresent ( ) ) { RuleDefinitionDto dto = new RuleDefinitionDto ( ) . setRuleKey ( adHoc . getKey ( ) ) . setIsExternal ( true ) . setIsAdHoc ( true ) . setName ( adHoc . getEngineId ( ) + ":" + adHoc . getRuleId ( ) ) . setScope ( ALL ) . setStatus ( READY ) . setCreatedAt ( now ) . setUpdatedAt ( now ) ; dao . insert ( dbSession , dto ) ; metadata = new RuleMetadataDto ( ) . setRuleId ( dto . getId ( ) ) . setOrganizationUuid ( organizationDto . getUuid ( ) ) ; } else { RuleDto ruleDto = existingRuleDtoOpt . get ( ) ; Preconditions . checkState ( ruleDto . isExternal ( ) && ruleDto . isAdHoc ( ) ) ; metadata = ruleDto . getMetadata ( ) ; } if ( adHoc . hasDetails ( ) ) { boolean changed = false ; if ( ! Objects . equals ( metadata . getAdHocName ( ) , adHoc . getName ( ) ) ) { metadata . setAdHocName ( substring ( adHoc . getName ( ) , 0 , MAX_LENGTH_AD_HOC_NAME ) ) ; changed = true ; } if ( ! Objects . equals ( metadata . getAdHocDescription ( ) , adHoc . getDescription ( ) ) ) { metadata . setAdHocDescription ( substring ( adHoc . getDescription ( ) , 0 , MAX_LENGTH_AD_HOC_DESC ) ) ; changed = true ; } if ( ! Objects . equals ( metadata . getAdHocSeverity ( ) , adHoc . getSeverity ( ) ) ) { metadata . setAdHocSeverity ( adHoc . getSeverity ( ) ) ; changed = true ; } RuleType ruleType = requireNonNull ( adHoc . getRuleType ( ) , "Rule type should not be null" ) ; if ( ! Objects . equals ( metadata . getAdHocType ( ) , ruleType . getDbConstant ( ) ) ) { metadata . setAdHocType ( ruleType ) ; changed = true ; } if ( changed ) { metadata . setUpdatedAt ( now ) ; metadata . setCreatedAt ( now ) ; dao . insertOrUpdate ( dbSession , metadata ) ; } } RuleDto ruleDto = dao . selectOrFailByKey ( dbSession , organizationDto , adHoc . getKey ( ) ) ; ruleIndexer . commitAndIndex ( dbSession , ruleDto . getId ( ) ) ; return ruleDto ; } | Persists a new add hoc rule in the DB and indexes it . |
10,003 | boolean hasSecretKey ( ) { String path = getPathToSecretKey ( ) ; if ( StringUtils . isNotBlank ( path ) ) { File file = new File ( path ) ; return file . exists ( ) && file . isFile ( ) ; } return false ; } | This method checks the existence of the file but not the validity of the contained key . |
10,004 | public PreparedStatement newScrollingSelectStatement ( DbSession session , String sql ) { int fetchSize = database . getDialect ( ) . getScrollDefaultFetchSize ( ) ; return newScrollingSelectStatement ( session , sql , fetchSize ) ; } | Create a PreparedStatement for SELECT requests with scrolling of results |
10,005 | public Collection < QProfileDto > selectDescendants ( DbSession dbSession , Collection < QProfileDto > profiles ) { if ( profiles . isEmpty ( ) ) { return emptyList ( ) ; } Collection < QProfileDto > children = selectChildren ( dbSession , profiles ) ; List < QProfileDto > descendants = new ArrayList < > ( children ) ; descendants . addAll ( selectDescendants ( dbSession , children ) ) ; return descendants ; } | All descendants in any order . The specified profiles are not included into results . |
10,006 | public Rule setParams ( List < RuleParam > params ) { this . params . clear ( ) ; for ( RuleParam param : params ) { param . setRule ( this ) ; this . params . add ( param ) ; } return this ; } | Sets the rule parameters |
10,007 | public Rule setTags ( String [ ] tags ) { this . tags = tags == null ? null : StringUtils . join ( tags , ',' ) ; return this ; } | For definition of rule only |
10,008 | public String getHashForLine ( int line ) { if ( line > 0 && line <= hashes . size ( ) ) { return Strings . nullToEmpty ( hashes . get ( line - 1 ) ) ; } return "" ; } | Hash of the given line which starts with 1 . Return empty string is the line does not exist . |
10,009 | public TextRange newRange ( int startOffset , int endOffset ) { checkMetadata ( ) ; return newRangeValidPointers ( newPointer ( startOffset ) , newPointer ( endOffset ) , false ) ; } | Create Range from global offsets . Used for backward compatibility with older API . |
10,010 | public Language get ( String languageKey ) { org . sonar . api . resources . Language language = languages . get ( languageKey ) ; return language != null ? new Language ( language . getKey ( ) , language . getName ( ) , language . getFileSuffixes ( ) ) : null ; } | Get language . |
10,011 | public Collection < Language > all ( ) { org . sonar . api . resources . Language [ ] all = languages . all ( ) ; Collection < Language > result = new ArrayList < > ( all . length ) ; for ( org . sonar . api . resources . Language language : all ) { result . add ( new Language ( language . getKey ( ) , language . getName ( ) , language . getFileSuffixes ( ) ) ) ; } return result ; } | Get list of all supported languages . |
10,012 | public NotificationDispatcherMetadata setProperty ( String key , String value ) { properties . put ( key , value ) ; return this ; } | Sets a property on this metadata object . |
10,013 | public void setBorderGap ( int borderGap ) { this . borderGap = borderGap ; Border inner = new EmptyBorder ( 0 , borderGap , 0 , borderGap ) ; setBorder ( new CompoundBorder ( OUTER , inner ) ) ; lastDigits = 0 ; setPreferredWidth ( ) ; } | The border gap is used in calculating the left and right insets of the border . Default value is 5 . |
10,014 | private void setPreferredWidth ( ) { Element root = component . getDocument ( ) . getDefaultRootElement ( ) ; int lines = root . getElementCount ( ) ; int digits = Math . max ( String . valueOf ( lines ) . length ( ) , minimumDisplayDigits ) ; if ( lastDigits != digits ) { lastDigits = digits ; FontMetrics fontMetrics = getFontMetrics ( getFont ( ) ) ; int width = fontMetrics . charWidth ( '0' ) * digits ; Insets insets = getInsets ( ) ; int preferredWidth = insets . left + insets . right + width ; Dimension d = getPreferredSize ( ) ; d . setSize ( preferredWidth , HEIGHT ) ; setPreferredSize ( d ) ; setSize ( d ) ; } } | Calculate the width needed to display the maximum line number |
10,015 | public void paintComponent ( Graphics g ) { super . paintComponent ( g ) ; FontMetrics fontMetrics = component . getFontMetrics ( component . getFont ( ) ) ; Insets insets = getInsets ( ) ; int availableWidth = getSize ( ) . width - insets . left - insets . right ; Rectangle clip = g . getClipBounds ( ) ; int rowStartOffset = component . viewToModel ( new Point ( 0 , clip . y ) ) ; int endOffset = component . viewToModel ( new Point ( 0 , clip . y + clip . height ) ) ; while ( rowStartOffset <= endOffset ) { try { if ( isCurrentLine ( rowStartOffset ) ) g . setColor ( getCurrentLineForeground ( ) ) ; else g . setColor ( getForeground ( ) ) ; String lineNumber = getTextLineNumber ( rowStartOffset ) ; int stringWidth = fontMetrics . stringWidth ( lineNumber ) ; int x = getOffsetX ( availableWidth , stringWidth ) + insets . left ; int y = getOffsetY ( rowStartOffset , fontMetrics ) ; g . drawString ( lineNumber , x , y ) ; rowStartOffset = Utilities . getRowEnd ( component , rowStartOffset ) + 1 ; } catch ( Exception e ) { break ; } } } | Draw the line numbers |
10,016 | public boolean hasProjectSubscribersForTypes ( String projectUuid , Set < Class < ? extends Notification > > notificationTypes ) { Set < String > dispatcherKeys = handlers . stream ( ) . filter ( handler -> notificationTypes . stream ( ) . anyMatch ( notificationType -> handler . getNotificationClass ( ) == notificationType ) ) . map ( NotificationHandler :: getMetadata ) . filter ( Optional :: isPresent ) . map ( Optional :: get ) . map ( NotificationDispatcherMetadata :: getDispatcherKey ) . collect ( MoreCollectors . toSet ( notificationTypes . size ( ) ) ) ; return dbClient . propertiesDao ( ) . hasProjectNotificationSubscribersForDispatchers ( projectUuid , dispatcherKeys ) ; } | Returns true if at least one user is subscribed to at least one notification with given types . Subscription can be global or on the specific project . |
10,017 | public String getKey ( ) { List < String > split = BRANCH_OR_PULL_REQUEST_SPLITTER . splitToList ( kee ) ; return split . size ( ) == 2 ? split . get ( 0 ) : kee ; } | The key to be displayed to user doesn t contain information on branches |
10,018 | public Metadata readMetadata ( Reader reader ) { LineCounter lineCounter = new LineCounter ( "fromString" , StandardCharsets . UTF_16 ) ; FileHashComputer fileHashComputer = new FileHashComputer ( "fromString" ) ; LineOffsetCounter lineOffsetCounter = new LineOffsetCounter ( ) ; CharHandler [ ] handlers = { lineCounter , fileHashComputer , lineOffsetCounter } ; try { read ( reader , handlers ) ; } catch ( IOException e ) { throw new IllegalStateException ( "Should never occur" , e ) ; } return new Metadata ( lineCounter . lines ( ) , lineCounter . nonBlankLines ( ) , fileHashComputer . getHash ( ) , lineOffsetCounter . getOriginalLineStartOffsets ( ) , lineOffsetCounter . getOriginalLineEndOffsets ( ) , lineOffsetCounter . getLastValidOffset ( ) ) ; } | For testing purpose |
10,019 | public static void computeLineHashesForIssueTracking ( InputFile f , LineHashConsumer consumer ) { try { readFile ( f . inputStream ( ) , f . charset ( ) , f . absolutePath ( ) , new CharHandler [ ] { new LineHashComputer ( consumer , f . file ( ) ) } ) ; } catch ( IOException e ) { throw new IllegalStateException ( "Failed to compute line hashes for " + f . absolutePath ( ) , e ) ; } } | Compute a MD5 hash of each line of the file after removing of all blank chars |
10,020 | public String getOrCreateForKey ( String key ) { return uuidsByDbKey . computeIfAbsent ( key , k1 -> uuidsByMigratedKey . computeIfAbsent ( k1 , k2 -> Uuids . create ( ) ) ) ; } | Get UUID from component having the same key in database if it exists otherwise look for migrated keys and finally generate a new one . |
10,021 | public QueryBuilder createQueryFilter ( ) { if ( userSession . isRoot ( ) ) { return QueryBuilders . matchAllQuery ( ) ; } Integer userId = userSession . getUserId ( ) ; BoolQueryBuilder filter = boolQuery ( ) ; filter . should ( QueryBuilders . termQuery ( FIELD_ALLOW_ANYONE , true ) ) ; Optional . ofNullable ( userId ) . map ( Integer :: longValue ) . ifPresent ( id -> filter . should ( termQuery ( FIELD_USER_IDS , id ) ) ) ; userSession . getGroups ( ) . stream ( ) . map ( GroupDto :: getId ) . forEach ( groupId -> filter . should ( termQuery ( FIELD_GROUP_IDS , groupId ) ) ) ; return JoinQueryBuilders . hasParentQuery ( TYPE_AUTHORIZATION , QueryBuilders . boolQuery ( ) . filter ( filter ) , false ) ; } | Build a filter to restrict query to the documents on which user has read access . |
10,022 | public static void checkProjectAdmin ( UserSession userSession , String organizationUuid , Optional < ProjectId > projectId ) { userSession . checkLoggedIn ( ) ; if ( userSession . hasPermission ( OrganizationPermission . ADMINISTER , organizationUuid ) ) { return ; } if ( projectId . isPresent ( ) ) { userSession . checkComponentUuidPermission ( UserRole . ADMIN , projectId . get ( ) . getUuid ( ) ) ; } else { throw insufficientPrivilegesException ( ) ; } } | Checks that user is administrator of the specified project or of the specified organization if project is not defined . |
10,023 | public static Collection < String > listFiles ( ClassLoader classLoader , String rootPath ) { return listResources ( classLoader , rootPath , path -> ! StringUtils . endsWith ( path , "/" ) ) ; } | Finds files within a given directory and its subdirectories |
10,024 | public static Collection < String > listResources ( ClassLoader classLoader , String rootPath , Predicate < String > predicate ) { String jarPath = null ; JarFile jar = null ; try { Collection < String > paths = new ArrayList < > ( ) ; URL root = classLoader . getResource ( rootPath ) ; if ( root != null ) { checkJarFile ( root ) ; String rootDirectory = rootPath ; if ( StringUtils . substringAfterLast ( rootPath , "/" ) . indexOf ( '.' ) >= 0 ) { rootDirectory = StringUtils . substringBeforeLast ( rootPath , "/" ) ; } jarPath = root . getPath ( ) . substring ( 5 , root . getPath ( ) . indexOf ( '!' ) ) ; jar = new JarFile ( URLDecoder . decode ( jarPath , UTF_8 . name ( ) ) ) ; Enumeration < JarEntry > entries = jar . entries ( ) ; while ( entries . hasMoreElements ( ) ) { String name = entries . nextElement ( ) . getName ( ) ; if ( name . startsWith ( rootDirectory ) && predicate . test ( name ) ) { paths . add ( name ) ; } } } return paths ; } catch ( Exception e ) { throw Throwables . propagate ( e ) ; } finally { closeJar ( jar , jarPath ) ; } } | Finds directories and files within a given directory and its subdirectories . |
10,025 | public void load ( RulesDefinition . NewRepository repo ) { for ( RulesDefinition . NewRule rule : repo . rules ( ) ) { String name = i18n . getName ( repo . key ( ) , rule . key ( ) ) ; if ( StringUtils . isNotBlank ( name ) ) { rule . setName ( name ) ; } String desc = i18n . getDescription ( repo . key ( ) , rule . key ( ) ) ; if ( StringUtils . isNotBlank ( desc ) ) { rule . setHtmlDescription ( desc ) ; } for ( RulesDefinition . NewParam param : rule . params ( ) ) { String paramDesc = i18n . getParamDescription ( repo . key ( ) , rule . key ( ) , param . key ( ) ) ; if ( StringUtils . isNotBlank ( paramDesc ) ) { param . setDescription ( paramDesc ) ; } } } } | Loads descriptions of rules and related rule parameters . Existing descriptions are overridden if English labels exist in bundles . |
10,026 | private static void hackFixForProjectMeasureTreeQueries ( Connection connection ) { int metricId = 1 ; try ( PreparedStatement preparedStatement = connection . prepareStatement ( "insert into PROJECT_MEASURES (METRIC_ID,COMPONENT_UUID,ANALYSIS_UUID) values (?,?,?);" ) ) { batchExecute ( 1 , 1000 , preparedStatement , connection , ( stmt , counter ) -> { preparedStatement . setInt ( 1 , metricId ) ; preparedStatement . setString ( 2 , "foo_" + counter ) ; preparedStatement . setString ( 3 , "bar_" + counter ) ; } ) ; } catch ( SQLException e ) { throw new RuntimeException ( "Failed to insert fake rows into table PROJECT_MEASURES" , e ) ; } } | see SONAR - 8586 |
10,027 | private static List < ProjectDefinition > collectProjects ( ProjectDefinition def , List < ProjectDefinition > collected ) { collected . add ( def ) ; for ( ProjectDefinition child : def . getSubProjects ( ) ) { collectProjects ( child , collected ) ; } return collected ; } | Populates list of projects from hierarchy . |
10,028 | public Optional < Iterable < DbFileSources . Line > > getLines ( DbSession dbSession , String fileUuid , int from , int toInclusive ) { return getLines ( dbSession , fileUuid , from , toInclusive , Function . identity ( ) ) ; } | Returns a range of lines as raw db data . User permission is not verified . |
10,029 | public Optional < Iterable < String > > getLinesAsRawText ( DbSession dbSession , String fileUuid , int from , int toInclusive ) { return getLines ( dbSession , fileUuid , from , toInclusive , DbFileSources . Line :: getSource ) ; } | Returns a range of lines as raw text . |
10,030 | public void setMetadata ( String moduleKeyWithBranch , final DefaultInputFile inputFile , Charset defaultEncoding ) { CharsetDetector charsetDetector = new CharsetDetector ( inputFile . path ( ) , defaultEncoding ) ; try { Charset charset ; if ( charsetDetector . run ( ) ) { charset = charsetDetector . charset ( ) ; } else { LOG . debug ( "Failed to detect a valid charset for file '{}'. Using default charset." , inputFile ) ; charset = defaultEncoding ; } InputStream is = charsetDetector . inputStream ( ) ; inputFile . setCharset ( charset ) ; Metadata metadata = fileMetadata . readMetadata ( is , charset , inputFile . absolutePath ( ) , exclusionsScanner . createCharHandlerFor ( inputFile ) ) ; inputFile . setMetadata ( metadata ) ; inputFile . setStatus ( statusDetection . status ( moduleKeyWithBranch , inputFile , metadata . hash ( ) ) ) ; LOG . debug ( "'{}' generated metadata{} with charset '{}'" , inputFile , inputFile . type ( ) == Type . TEST ? " as test " : "" , charset ) ; } catch ( Exception e ) { throw new IllegalStateException ( e ) ; } } | Sets all metadata in the file including charset and status . It is an expensive computation reading the entire file . |
10,031 | public String mandatoryParam ( String key ) { String value = param ( key ) ; checkArgument ( value != null && ! value . isEmpty ( ) , format ( MSG_PARAMETER_MISSING , key ) ) ; return value ; } | Returns a non - null value . To be used when parameter is required or has a default value . |
10,032 | public boolean mandatoryParamAsBoolean ( String key ) { String s = mandatoryParam ( key ) ; return parseBoolean ( key , s ) ; } | Returns a boolean value . To be used when parameter is required or has a default value . |
10,033 | public int mandatoryParamAsInt ( String key ) { String s = mandatoryParam ( key ) ; return parseInt ( key , s ) ; } | Returns an int value . To be used when parameter is required or has a default value . |
10,034 | public long mandatoryParamAsLong ( String key ) { String s = mandatoryParam ( key ) ; return parseLong ( key , s ) ; } | Returns a long value . To be used when parameter is required or has a default value . |
10,035 | private static void configure ( InputStream input , Map < String , String > substitutionVariables ) { LoggerContext lc = ( LoggerContext ) LoggerFactory . getILoggerFactory ( ) ; try { JoranConfigurator configurator = new JoranConfigurator ( ) ; configurator . setContext ( configureContext ( lc , substitutionVariables ) ) ; configurator . doConfigure ( input ) ; } catch ( JoranException e ) { } finally { IOUtils . closeQuietly ( input ) ; } StatusPrinter . printInCaseOfErrorsOrWarnings ( lc ) ; } | Note that this method closes the input stream |
10,036 | public void applyAndCommit ( DbSession dbSession , PermissionTemplateDto template , Collection < ComponentDto > projects ) { if ( projects . isEmpty ( ) ) { return ; } for ( ComponentDto project : projects ) { copyPermissions ( dbSession , template , project , null ) ; } projectIndexers . commitAndIndex ( dbSession , projects , ProjectIndexer . Cause . PERMISSION_CHANGE ) ; } | Apply a permission template to a set of projects . Authorization to administrate these projects is not verified . The projects must exist so the project creator permissions defined in the template are ignored . |
10,037 | private PermissionTemplateDto findTemplate ( DbSession dbSession , ComponentDto component ) { String organizationUuid = component . getOrganizationUuid ( ) ; List < PermissionTemplateDto > allPermissionTemplates = dbClient . permissionTemplateDao ( ) . selectAll ( dbSession , organizationUuid , null ) ; List < PermissionTemplateDto > matchingTemplates = new ArrayList < > ( ) ; for ( PermissionTemplateDto permissionTemplateDto : allPermissionTemplates ) { String keyPattern = permissionTemplateDto . getKeyPattern ( ) ; if ( StringUtils . isNotBlank ( keyPattern ) && component . getDbKey ( ) . matches ( keyPattern ) ) { matchingTemplates . add ( permissionTemplateDto ) ; } } checkAtMostOneMatchForComponentKey ( component . getDbKey ( ) , matchingTemplates ) ; if ( matchingTemplates . size ( ) == 1 ) { return matchingTemplates . get ( 0 ) ; } DefaultTemplates defaultTemplates = dbClient . organizationDao ( ) . getDefaultTemplates ( dbSession , organizationUuid ) . orElseThrow ( ( ) -> new IllegalStateException ( format ( "No Default templates defined for organization with uuid '%s'" , organizationUuid ) ) ) ; String qualifier = component . qualifier ( ) ; DefaultTemplatesResolverImpl . ResolvedDefaultTemplates resolvedDefaultTemplates = defaultTemplatesResolver . resolve ( defaultTemplates ) ; switch ( qualifier ) { case Qualifiers . PROJECT : return dbClient . permissionTemplateDao ( ) . selectByUuid ( dbSession , resolvedDefaultTemplates . getProject ( ) ) ; case Qualifiers . VIEW : String portDefaultTemplateUuid = resolvedDefaultTemplates . getPortfolio ( ) . orElseThrow ( ( ) -> new IllegalStateException ( "Attempt to create a view when Governance plugin is not installed" ) ) ; return dbClient . permissionTemplateDao ( ) . selectByUuid ( dbSession , portDefaultTemplateUuid ) ; case Qualifiers . APP : String appDefaultTemplateUuid = resolvedDefaultTemplates . getApplication ( ) . orElseThrow ( ( ) -> new IllegalStateException ( "Attempt to create a view when Governance plugin is not installed" ) ) ; return dbClient . permissionTemplateDao ( ) . selectByUuid ( dbSession , appDefaultTemplateUuid ) ; default : throw new IllegalArgumentException ( format ( "Qualifier '%s' is not supported" , qualifier ) ) ; } } | Return the permission template for the given component . If no template key pattern match then consider default template for the component qualifier . |
10,038 | public Iterator < Integer > searchAll ( RuleQuery query ) { SearchRequestBuilder esSearch = client . prepareSearch ( TYPE_RULE ) . setScroll ( TimeValue . timeValueMinutes ( SCROLL_TIME_IN_MINUTES ) ) ; optimizeScrollRequest ( esSearch ) ; QueryBuilder qb = buildQuery ( query ) ; Map < String , QueryBuilder > filters = buildFilters ( query ) ; BoolQueryBuilder fb = boolQuery ( ) ; for ( QueryBuilder filterBuilder : filters . values ( ) ) { fb . must ( filterBuilder ) ; } esSearch . setQuery ( boolQuery ( ) . must ( qb ) . filter ( fb ) ) ; SearchResponse response = esSearch . get ( ) ; return scrollIds ( client , response , Integer :: parseInt ) ; } | Return all rule ids matching the search query without pagination nor facets |
10,039 | private static StartupMetadata load ( DbClient dbClient ) { try ( DbSession dbSession = dbClient . openSession ( false ) ) { String startedAt = selectProperty ( dbClient , dbSession , SERVER_STARTTIME ) ; return new StartupMetadata ( DateUtils . parseDateTime ( startedAt ) . getTime ( ) ) ; } } | Load from database |
10,040 | private void startLevel34Containers ( ) { level3 = start ( new PlatformLevel3 ( level2 ) ) ; level4 = start ( new PlatformLevel4 ( level3 , level4AddedComponents ) ) ; } | Starts level 3 and 4 |
10,041 | public void doStop ( ) { try { stopAutoStarter ( ) ; stopSafeModeContainer ( ) ; stopLevel234Containers ( ) ; stopLevel1Container ( ) ; currentLevel = null ; dbConnected = false ; started = false ; } catch ( Exception e ) { LOGGER . error ( "Fail to stop server - ignored" , e ) ; } } | Do not rename stop |
10,042 | public static void register ( String name , Object instance ) { try { Class < Object > mbeanInterface = guessMBeanInterface ( instance ) ; ManagementFactory . getPlatformMBeanServer ( ) . registerMBean ( new StandardMBean ( instance , mbeanInterface ) , new ObjectName ( name ) ) ; } catch ( MalformedObjectNameException | NotCompliantMBeanException | InstanceAlreadyExistsException | MBeanRegistrationException e ) { throw new IllegalStateException ( "Can not register MBean [" + name + "]" , e ) ; } } | Register a MBean to JMX server |
10,043 | public static void unregister ( String name ) { try { ManagementFactory . getPlatformMBeanServer ( ) . unregisterMBean ( new ObjectName ( name ) ) ; } catch ( Exception e ) { LoggerFactory . getLogger ( Jmx . class ) . warn ( "Can not unregister MBean [{}]" , name , e ) ; } } | Unregister a MBean from JMX server . Errors are ignored and logged as warnings . |
10,044 | public void clearIndex ( Index index ) { BulkIndexer . delete ( esClient , IndexType . main ( index , index . getName ( ) ) , esClient . prepareSearch ( index ) . setQuery ( matchAllQuery ( ) ) ) ; } | Completely remove a index with all types |
10,045 | private static void truncateOrganizations ( String tableName , Statement ddlStatement , Connection connection ) throws SQLException { try ( PreparedStatement preparedStatement = connection . prepareStatement ( "delete from organizations where kee <> ?" ) ) { preparedStatement . setString ( 1 , "default-organization" ) ; preparedStatement . execute ( ) ; connection . commit ( ) ; } } | Default organization must never be deleted |
10,046 | private static void truncateUsers ( String tableName , Statement ddlStatement , Connection connection ) throws SQLException { try ( PreparedStatement preparedStatement = connection . prepareStatement ( "delete from users where login <> ?" ) ) { preparedStatement . setString ( 1 , "admin" ) ; preparedStatement . execute ( ) ; connection . commit ( ) ; } try ( PreparedStatement preparedStatement = connection . prepareStatement ( "update users set is_root=?" ) ) { preparedStatement . setBoolean ( 1 , false ) ; preparedStatement . execute ( ) ; connection . commit ( ) ; } } | User admin must never be deleted . |
10,047 | private void updateViewDefaultTemplateWhenGovernanceIsNotInstalled ( DbSession dbSession , PermissionTemplateDto template , DefaultTemplates defaultTemplates ) { String viewDefaultTemplateUuid = defaultTemplates . getApplicationsUuid ( ) ; if ( viewDefaultTemplateUuid != null && viewDefaultTemplateUuid . equals ( template . getUuid ( ) ) ) { defaultTemplates . setApplicationsUuid ( null ) ; dbClient . organizationDao ( ) . setDefaultTemplates ( dbSession , template . getOrganizationUuid ( ) , defaultTemplates ) ; } } | The default template for view can be removed when Governance is not installed . To avoid keeping a reference to a non existing template we update the default templates . |
10,048 | public static boolean shouldStartHazelcast ( AppSettings appSettings ) { return isClusterEnabled ( appSettings . getProps ( ) ) && toNodeType ( appSettings . getProps ( ) ) . equals ( NodeType . APPLICATION ) ; } | Hazelcast must be started when cluster is activated on all nodes but search ones |
10,049 | public static ComponentUpdateDto copyFrom ( ComponentDto from ) { return new ComponentUpdateDto ( ) . setUuid ( from . uuid ( ) ) . setBChanged ( false ) . setBKey ( from . getDbKey ( ) ) . setBCopyComponentUuid ( from . getCopyResourceUuid ( ) ) . setBDescription ( from . description ( ) ) . setBEnabled ( from . isEnabled ( ) ) . setBUuidPath ( from . getUuidPath ( ) ) . setBLanguage ( from . language ( ) ) . setBLongName ( from . longName ( ) ) . setBModuleUuid ( from . moduleUuid ( ) ) . setBModuleUuidPath ( from . moduleUuidPath ( ) ) . setBName ( from . name ( ) ) . setBPath ( from . path ( ) ) . setBQualifier ( from . qualifier ( ) ) ; } | Copy the A - fields to B - fields . The field bChanged is kept to false . |
10,050 | public HazelcastMemberBuilder setMembers ( Collection < String > c ) { this . members = c . stream ( ) . map ( host -> host . contains ( ":" ) ? host : format ( "%s:%s" , host , CLUSTER_NODE_HZ_PORT . getDefaultValue ( ) ) ) . collect ( Collectors . toList ( ) ) ; return this ; } | Adds references to cluster members . If port is missing then default port is automatically added . |
10,051 | public static List < String > getPropertyValues ( ClassLoader classloader , String key ) { List < String > values = new ArrayList < > ( ) ; try { Enumeration < URL > resources = classloader . getResources ( "META-INF/MANIFEST.MF" ) ; while ( resources . hasMoreElements ( ) ) { Manifest manifest = new Manifest ( resources . nextElement ( ) . openStream ( ) ) ; Attributes attributes = manifest . getMainAttributes ( ) ; String value = attributes . getValue ( key ) ; if ( value != null ) { values . add ( value ) ; } } } catch ( IOException e ) { throw new SonarException ( "Fail to load manifests from classloader: " + classloader , e ) ; } return values ; } | Search for a property in all the manifests found in the classloader |
10,052 | public void saveAsEmpty ( DbSession dbSession , String key ) { checkKey ( key ) ; InternalPropertiesMapper mapper = getMapper ( dbSession ) ; mapper . deleteByKey ( key ) ; mapper . insertAsEmpty ( key , system2 . now ( ) ) ; } | Save a property which value is empty . |
10,053 | public Optional < String > selectByKey ( DbSession dbSession , String key ) { checkKey ( key ) ; InternalPropertiesMapper mapper = getMapper ( dbSession ) ; InternalPropertyDto res = enforceSingleElement ( key , mapper . selectAsText ( singletonList ( key ) ) ) ; if ( res == null ) { return Optional . empty ( ) ; } if ( res . isEmpty ( ) ) { return OPTIONAL_OF_EMPTY_STRING ; } if ( res . getValue ( ) != null ) { return Optional . of ( res . getValue ( ) ) ; } res = enforceSingleElement ( key , mapper . selectAsClob ( singletonList ( key ) ) ) ; if ( res == null ) { Loggers . get ( InternalPropertiesDao . class ) . debug ( "Internal property {} has been found in db but has neither text value nor is empty. " + "Still it couldn't be retrieved with clob value. Ignoring the property." , key ) ; return Optional . empty ( ) ; } return Optional . of ( res . getValue ( ) ) ; } | No streaming of value |
10,054 | public List < UserDto > selectByIds ( DbSession session , Collection < Integer > ids ) { return executeLargeInputs ( ids , mapper ( session ) :: selectByIds ) ; } | Select users by ids including disabled users . An empty list is returned if list of ids is empty without any db round trips . |
10,055 | public List < UserDto > selectByLogins ( DbSession session , Collection < String > logins ) { return executeLargeInputs ( logins , mapper ( session ) :: selectByLogins ) ; } | Select users by logins including disabled users . An empty list is returned if list of logins is empty without any db round trips . |
10,056 | public List < UserDto > selectByUuids ( DbSession session , Collection < String > uuids ) { return executeLargeInputs ( uuids , mapper ( session ) :: selectByUuids ) ; } | Select users by uuids including disabled users . An empty list is returned if list of uuids is empty without any db round trips . |
10,057 | public List < UserDto > selectByEmail ( DbSession dbSession , String emailCaseInsensitive ) { return mapper ( dbSession ) . selectByEmail ( emailCaseInsensitive . toLowerCase ( ENGLISH ) ) ; } | Search for an active user with the given emailCaseInsensitive exits in database |
10,058 | public NoSonarFilter noSonarInFile ( InputFile inputFile , Set < Integer > noSonarLines ) { ( ( DefaultInputFile ) inputFile ) . noSonarAt ( noSonarLines ) ; return this ; } | Register lines in a file that contains the NOSONAR flag . |
10,059 | private static void configureRouting ( IssueQuery query , SearchOptions options , SearchRequestBuilder requestBuilder ) { Collection < String > uuids = query . projectUuids ( ) ; if ( ! uuids . isEmpty ( ) && options . getFacets ( ) . isEmpty ( ) ) { requestBuilder . setRouting ( uuids . stream ( ) . map ( AuthorizationDoc :: idOf ) . toArray ( String [ ] :: new ) ) ; } } | Optimization - do not send ES request to all shards when scope is restricted to a set of projects . Because project UUID is used for routing the request can be sent to only the shards containing the specified projects . Note that sticky facets may involve all projects so this optimization must be disabled when facets are enabled . |
10,060 | public ProjectDefinition setProperties ( Properties properties ) { for ( Entry < Object , Object > entry : properties . entrySet ( ) ) { this . properties . put ( entry . getKey ( ) . toString ( ) , entry . getValue ( ) . toString ( ) ) ; } return this ; } | Copies specified properties into this object . |
10,061 | private GroupDto insertOwnersGroup ( DbSession dbSession , OrganizationDto organization ) { GroupDto group = dbClient . groupDao ( ) . insert ( dbSession , new GroupDto ( ) . setOrganizationUuid ( organization . getUuid ( ) ) . setName ( OWNERS_GROUP_NAME ) . setDescription ( format ( OWNERS_GROUP_DESCRIPTION_PATTERN , organization . getName ( ) ) ) ) ; permissionService . getAllOrganizationPermissions ( ) . forEach ( p -> addPermissionToGroup ( dbSession , group , p ) ) ; return group ; } | Owners group has an hard coded name a description based on the organization s name and has all global permissions . |
10,062 | public void start ( ) { try { forceMkdir ( downloadDir ) ; for ( File tempFile : listTempFile ( this . downloadDir ) ) { deleteQuietly ( tempFile ) ; } } catch ( IOException e ) { throw new IllegalStateException ( "Fail to create the directory: " + downloadDir , e ) ; } } | Deletes the temporary files remaining from previous downloads |
10,063 | public Optional < PropertyDefinition > getDefinition ( String key ) { return Optional . ofNullable ( definitions . get ( key ) ) ; } | The definition related to the specified property . It may be empty . |
10,064 | public String [ ] getStringLines ( String key ) { String value = getString ( key ) ; if ( StringUtils . isEmpty ( value ) ) { return new String [ 0 ] ; } return value . split ( "\r?\n|\r" , - 1 ) ; } | Value is split by carriage returns . |
10,065 | public String [ ] getStringArrayBySeparator ( String key , String separator ) { String value = getString ( key ) ; if ( value != null ) { String [ ] strings = StringUtils . splitByWholeSeparator ( value , separator ) ; String [ ] result = new String [ strings . length ] ; for ( int index = 0 ; index < strings . length ; index ++ ) { result [ index ] = trim ( strings [ index ] ) ; } return result ; } return ArrayUtils . EMPTY_STRING_ARRAY ; } | Value is split and trimmed . |
10,066 | public < T extends Notification > T getFromQueue ( ) { int batchSize = 1 ; List < NotificationQueueDto > notificationDtos = dbClient . notificationQueueDao ( ) . selectOldest ( batchSize ) ; if ( notificationDtos . isEmpty ( ) ) { return null ; } dbClient . notificationQueueDao ( ) . delete ( notificationDtos ) ; return convertToNotification ( notificationDtos ) ; } | Give the notification queue so that it can be processed |
10,067 | public List < CeActivityDto > selectByQuery ( DbSession dbSession , CeTaskQuery query , Pagination pagination ) { if ( query . isShortCircuitedByMainComponentUuids ( ) ) { return Collections . emptyList ( ) ; } return mapper ( dbSession ) . selectByQuery ( query , pagination ) ; } | Ordered by id desc - > newest to oldest |
10,068 | public PvmProcessInstance createProcessInstanceForInitial ( ActivityImpl initial ) { ensureNotNull ( "Cannot start process instance, initial activity where the process instance should start is null" , "initial" , initial ) ; PvmExecutionImpl processInstance = newProcessInstance ( ) ; processInstance . setProcessDefinition ( this ) ; processInstance . setProcessInstance ( processInstance ) ; processInstance . setActivity ( initial ) ; return processInstance ; } | creates a process instance using the provided activity as initial |
10,069 | public static HalRelation build ( String relName , Class < ? > resourceType , UriBuilder urlTemplate ) { HalRelation relation = new HalRelation ( ) ; relation . relName = relName ; relation . uriTemplate = urlTemplate ; relation . resourceType = resourceType ; return relation ; } | Build a relation to a resource . |
10,070 | protected ActivityImpl determineFirstActivity ( ProcessDefinitionImpl processDefinition , ProcessInstanceModificationBuilderImpl modificationBuilder ) { AbstractProcessInstanceModificationCommand firstInstruction = modificationBuilder . getModificationOperations ( ) . get ( 0 ) ; if ( firstInstruction instanceof AbstractInstantiationCmd ) { AbstractInstantiationCmd instantiationInstruction = ( AbstractInstantiationCmd ) firstInstruction ; CoreModelElement targetElement = instantiationInstruction . getTargetElement ( processDefinition ) ; ensureNotNull ( NotValidException . class , "Element '" + instantiationInstruction . getTargetElementId ( ) + "' does not exist in process " + processDefinition . getId ( ) , "targetElement" , targetElement ) ; if ( targetElement instanceof ActivityImpl ) { return ( ActivityImpl ) targetElement ; } else if ( targetElement instanceof TransitionImpl ) { return ( ActivityImpl ) ( ( TransitionImpl ) targetElement ) . getDestination ( ) ; } } return null ; } | get the activity that is started by the first instruction if exists ; return null if the first instruction is a start - transition instruction |
10,071 | public ActivityImpl getInnerActivity ( PvmActivity miBodyActivity ) { for ( PvmActivity activity : miBodyActivity . getActivities ( ) ) { ActivityImpl innerActivity = ( ActivityImpl ) activity ; if ( ! innerActivity . isCompensationHandler ( ) ) { return innerActivity ; } } throw new ProcessEngineException ( "inner activity of multi instance body activity '" + miBodyActivity . getId ( ) + "' not found" ) ; } | Get the inner activity of the multi instance execution . |
10,072 | public void registerActivitiStateHandler ( ActivitiStateHandlerRegistration registration ) { String regKey = registrationKey ( registration . getProcessName ( ) , registration . getStateName ( ) ) ; this . registrations . put ( regKey , registration ) ; } | used at runtime to register state handlers as they are registered with the spring context |
10,073 | protected Long evaluateValueProvider ( ParameterValueProvider valueProvider , ExecutionEntity execution , String errorMessageHeading ) { Object value ; try { value = valueProvider . getValue ( execution ) ; } catch ( ProcessEngineException e ) { if ( Context . getProcessEngineConfiguration ( ) . isEnableGracefulDegradationOnContextSwitchFailure ( ) && isSymptomOfContextSwitchFailure ( e , execution ) ) { value = getDefaultPriorityOnResolutionFailure ( ) ; logNotDeterminingPriority ( execution , value , e ) ; } else { throw e ; } } if ( ! ( value instanceof Number ) ) { throw new ProcessEngineException ( errorMessageHeading + ": Priority value is not an Integer" ) ; } else { Number numberValue = ( Number ) value ; if ( isValidLongValue ( numberValue ) ) { return numberValue . longValue ( ) ; } else { throw new ProcessEngineException ( errorMessageHeading + ": Priority value must be either Short, Integer, or Long" ) ; } } } | Evaluates a given value provider with the given execution entity to determine the correct value . The error message heading is used for the error message if the validation fails because the value is no valid priority . |
10,074 | protected Long getProcessDefinedPriority ( ProcessDefinitionImpl processDefinition , String propertyKey , ExecutionEntity execution , String errorMsgHead ) { if ( processDefinition != null ) { ParameterValueProvider priorityProvider = ( ParameterValueProvider ) processDefinition . getProperty ( propertyKey ) ; if ( priorityProvider != null ) { return evaluateValueProvider ( priorityProvider , execution , errorMsgHead ) ; } } return null ; } | Returns the priority which is defined in the given process definition . The priority value is identified with the given propertyKey . Returns null if the process definition is null or no priority was defined . |
10,075 | protected String getDiagramResourceForDefinition ( DeploymentEntity deployment , String resourceName , DefinitionEntity definition , Map < String , ResourceEntity > resources ) { for ( String diagramSuffix : getDiagramSuffixes ( ) ) { String definitionDiagramResource = getDefinitionDiagramResourceName ( resourceName , definition , diagramSuffix ) ; String diagramForFileResource = getGeneralDiagramResourceName ( resourceName , definition , diagramSuffix ) ; if ( resources . containsKey ( definitionDiagramResource ) ) { return definitionDiagramResource ; } else if ( resources . containsKey ( diagramForFileResource ) ) { return diagramForFileResource ; } } return null ; } | Returns the default name of the image resource for a certain definition . |
10,076 | public List < HalResource < ? > > resolveLinks ( String [ ] linkedIds , ProcessEngine processEngine ) { Cache cache = getCache ( ) ; if ( cache == null ) { return resolveNotCachedLinks ( linkedIds , processEngine ) ; } else { ArrayList < String > notCachedLinkedIds = new ArrayList < String > ( ) ; List < HalResource < ? > > resolvedResources = resolveCachedLinks ( linkedIds , cache , notCachedLinkedIds ) ; if ( ! notCachedLinkedIds . isEmpty ( ) ) { List < HalResource < ? > > notCachedResources = resolveNotCachedLinks ( notCachedLinkedIds . toArray ( new String [ notCachedLinkedIds . size ( ) ] ) , processEngine ) ; resolvedResources . addAll ( notCachedResources ) ; putIntoCache ( notCachedResources ) ; } sortResolvedResources ( resolvedResources ) ; return resolvedResources ; } } | Resolve resources for linked ids if configured uses a cache . |
10,077 | protected void sortResolvedResources ( List < HalResource < ? > > resolvedResources ) { Comparator < HalResource < ? > > comparator = getResourceComparator ( ) ; if ( comparator != null ) { Collections . sort ( resolvedResources , comparator ) ; } } | Sort the resolved resources to ensure consistent order of resolved resources . |
10,078 | protected List < HalResource < ? > > resolveCachedLinks ( String [ ] linkedIds , Cache cache , List < String > notCachedLinkedIds ) { ArrayList < HalResource < ? > > resolvedResources = new ArrayList < HalResource < ? > > ( ) ; for ( String linkedId : linkedIds ) { HalResource < ? > resource = ( HalResource < ? > ) cache . get ( linkedId ) ; if ( resource != null ) { resolvedResources . add ( resource ) ; } else { notCachedLinkedIds . add ( linkedId ) ; } } return resolvedResources ; } | Returns a list with all resources which are cached . |
10,079 | protected void putIntoCache ( List < HalResource < ? > > notCachedResources ) { Cache cache = getCache ( ) ; for ( HalResource < ? > notCachedResource : notCachedResources ) { cache . put ( getResourceId ( notCachedResource ) , notCachedResource ) ; } } | Put a resource into the cache . |
10,080 | public void updateModifiableFieldsFromEntity ( ProcessDefinitionEntity updatingProcessDefinition ) { if ( this . key . equals ( updatingProcessDefinition . key ) && this . deploymentId . equals ( updatingProcessDefinition . deploymentId ) ) { this . revision = updatingProcessDefinition . revision ; this . suspensionState = updatingProcessDefinition . suspensionState ; this . historyTimeToLive = updatingProcessDefinition . historyTimeToLive ; } else { LOG . logUpdateUnrelatedProcessDefinitionEntity ( this . key , updatingProcessDefinition . key , this . deploymentId , updatingProcessDefinition . deploymentId ) ; } } | Updates all modifiable fields from another process definition entity . |
10,081 | public static boolean isDynamicScriptExpression ( String language , String value ) { return StringUtil . isExpression ( value ) && ( language != null && ! JuelScriptEngineFactory . names . contains ( language . toLowerCase ( ) ) ) ; } | Checks if the value is an expression for a dynamic script source or resource . |
10,082 | public static ScriptFactory getScriptFactory ( ) { ProcessEngineConfigurationImpl processEngineConfiguration = Context . getProcessEngineConfiguration ( ) ; if ( processEngineConfiguration != null ) { return processEngineConfiguration . getScriptFactory ( ) ; } else { return new ScriptFactory ( ) ; } } | Returns the configured script factory in the context or a new one . |
10,083 | protected Set < String > resumePreviousByProcessDefinitionKey ( CommandContext commandContext , DeploymentEntity deployment , Set < String > processKeysToRegisterFor ) { Set < String > processDefinitionKeys = new HashSet < String > ( processKeysToRegisterFor ) ; List < ? extends ProcessDefinition > deployedProcesses = getDeployedProcesses ( deployment ) ; for ( ProcessDefinition deployedProcess : deployedProcesses ) { if ( deployedProcess . getVersion ( ) > 1 ) { processDefinitionKeys . add ( deployedProcess . getKey ( ) ) ; } } return findDeploymentIdsForProcessDefinitions ( commandContext , processDefinitionKeys ) ; } | Searches in previous deployments for the same processes and retrieves the deployment ids . |
10,084 | protected Set < String > resumePreviousByDeploymentName ( CommandContext commandContext , DeploymentEntity deployment ) { List < Deployment > previousDeployments = new DeploymentQueryImpl ( ) . deploymentName ( deployment . getName ( ) ) . list ( ) ; Set < String > deploymentIds = new HashSet < String > ( previousDeployments . size ( ) ) ; for ( Deployment d : previousDeployments ) { deploymentIds . add ( d . getId ( ) ) ; } return deploymentIds ; } | Searches for previous deployments with the same name . |
10,085 | protected List < String > getSatisfiedSentries ( List < String > sentryIds ) { List < String > result = new ArrayList < String > ( ) ; if ( sentryIds != null ) { for ( String sentryId : sentryIds ) { if ( isSentrySatisfied ( sentryId ) ) { result . add ( sentryId ) ; } } } return result ; } | Checks for each given sentry id whether the corresponding sentry is satisfied . |
10,086 | protected List < String > getSatisfiedSentriesInExecutionTree ( List < String > sentryIds , Map < String , List < CmmnSentryPart > > allSentries ) { List < String > result = new ArrayList < String > ( ) ; if ( sentryIds != null ) { for ( String sentryId : sentryIds ) { List < CmmnSentryPart > sentryParts = allSentries . get ( sentryId ) ; if ( isSentryPartsSatisfied ( sentryId , sentryParts ) ) { result . add ( sentryId ) ; } } } return result ; } | Checks for each given sentry id in the execution tree whether the corresponding sentry is satisfied . |
10,087 | public Object getValue ( ELContext context , Object base , Object property ) { if ( context == null ) { throw new NullPointerException ( "context is null" ) ; } Object result = null ; if ( isResolvable ( base ) ) { int index = toIndex ( null , property ) ; result = index < 0 || index >= Array . getLength ( base ) ? null : Array . get ( base , index ) ; context . setPropertyResolved ( true ) ; } return result ; } | If the base object is a Java language array returns the value at the given index . The index is specified by the property argument and coerced into an integer . If the coercion could not be performed an IllegalArgumentException is thrown . If the index is out of bounds null is returned . If the base is a Java language array the propertyResolved property of the ELContext object must be set to true by this resolver before returning . If this property is not true after this method is called the caller should ignore the return value . |
10,088 | public void setValue ( ELContext context , Object base , Object property , Object value ) { if ( context == null ) { throw new NullPointerException ( "context is null" ) ; } if ( isResolvable ( base ) ) { if ( readOnly ) { throw new PropertyNotWritableException ( "resolver is read-only" ) ; } Array . set ( base , toIndex ( base , property ) , value ) ; context . setPropertyResolved ( true ) ; } } | If the base object is a Java language array attempts to set the value at the given index with the given value . The index is specified by the property argument and coerced into an integer . If the coercion could not be performed an IllegalArgumentException is thrown . If the index is out of bounds a PropertyNotFoundException is thrown . If the base is a Java language array the propertyResolved property of the ELContext object must be set to true by this resolver before returning . If this property is not true after this method is called the caller can safely assume no value was set . If this resolver was constructed in read - only mode this method will always throw PropertyNotWritableException . |
10,089 | public static Integer parseHistoryTimeToLive ( String historyTimeToLive ) { Integer timeToLive = null ; if ( historyTimeToLive != null && ! historyTimeToLive . isEmpty ( ) ) { Matcher matISO = REGEX_TTL_ISO . matcher ( historyTimeToLive ) ; if ( matISO . find ( ) ) { historyTimeToLive = matISO . group ( 1 ) ; } timeToLive = parseIntegerAttribute ( "historyTimeToLive" , historyTimeToLive ) ; } if ( timeToLive != null && timeToLive < 0 ) { throw new NotValidException ( "Cannot parse historyTimeToLive: negative value is not allowed" ) ; } return timeToLive ; } | Parse History Time To Live in ISO - 8601 format to integer and set into the given entity |
10,090 | public FormFieldValidator createValidator ( Element constraint , BpmnParse bpmnParse , ExpressionManager expressionManager ) { String name = constraint . attribute ( "name" ) ; String config = constraint . attribute ( "config" ) ; if ( "validator" . equals ( name ) ) { if ( config == null || config . isEmpty ( ) ) { bpmnParse . addError ( "validator configuration needs to provide either a fully " + "qualified classname or an expression resolving to a custom FormFieldValidator implementation." , constraint ) ; } else { if ( StringUtil . isExpression ( config ) ) { Expression validatorExpression = expressionManager . createExpression ( config ) ; return new DelegateFormFieldValidator ( validatorExpression ) ; } else { return new DelegateFormFieldValidator ( config ) ; } } } else { Class < ? extends FormFieldValidator > validator = validators . get ( name ) ; if ( validator != null ) { FormFieldValidator validatorInstance = createValidatorInstance ( validator ) ; return validatorInstance ; } else { bpmnParse . addError ( "Cannot find validator implementation for name '" + name + "'." , constraint ) ; } } return null ; } | factory method for creating validator instances |
10,091 | public < T > T execute ( Callable < T > callable ) throws ProcessApplicationExecutionException { try { return callable . call ( ) ; } catch ( Exception e ) { throw LOG . processApplicationExecutionException ( e ) ; } } | Since the process engine is loaded by the same classloader as the process application nothing needs to be done . |
10,092 | public void startWithoutExecuting ( Map < String , Object > variables ) { initialize ( ) ; initializeTimerDeclarations ( ) ; fireHistoricProcessStartEvent ( ) ; performOperation ( PvmAtomicOperation . FIRE_PROCESS_START ) ; setActivity ( null ) ; setActivityInstanceId ( getId ( ) ) ; setVariables ( variables ) ; } | perform starting behavior but don t execute the initial activity |
10,093 | public void end ( boolean completeScope ) { setCompleteScope ( completeScope ) ; isActive = false ; isEnded = true ; if ( hasReplacedParent ( ) ) { getParent ( ) . replacedBy = null ; } performOperation ( PvmAtomicOperation . ACTIVITY_NOTIFY_LISTENER_END ) ; } | Ends an execution . Invokes end listeners for the current activity and notifies the flow scope execution of this happening which may result in the flow scope ending . |
10,094 | public void executeActivitiesConcurrent ( List < PvmActivity > activityStack , PvmActivity targetActivity , PvmTransition targetTransition , Map < String , Object > variables , Map < String , Object > localVariables , boolean skipCustomListeners , boolean skipIoMappings ) { ScopeImpl flowScope = null ; if ( ! activityStack . isEmpty ( ) ) { flowScope = activityStack . get ( 0 ) . getFlowScope ( ) ; } else if ( targetActivity != null ) { flowScope = targetActivity . getFlowScope ( ) ; } else if ( targetTransition != null ) { flowScope = targetTransition . getSource ( ) . getFlowScope ( ) ; } PvmExecutionImpl propagatingExecution = null ; if ( flowScope . getActivityBehavior ( ) instanceof ModificationObserverBehavior ) { ModificationObserverBehavior flowScopeBehavior = ( ModificationObserverBehavior ) flowScope . getActivityBehavior ( ) ; propagatingExecution = ( PvmExecutionImpl ) flowScopeBehavior . createInnerInstance ( this ) ; } else { propagatingExecution = createConcurrentExecution ( ) ; } propagatingExecution . executeActivities ( activityStack , targetActivity , targetTransition , variables , localVariables , skipCustomListeners , skipIoMappings ) ; } | Instantiates the given activity stack under this execution . Sets the variables for the execution responsible to execute the most deeply nested activity . |
10,095 | public Map < PvmActivity , PvmExecutionImpl > instantiateScopes ( List < PvmActivity > activityStack , boolean skipCustomListeners , boolean skipIoMappings ) { if ( activityStack . isEmpty ( ) ) { return Collections . emptyMap ( ) ; } this . skipCustomListeners = skipCustomListeners ; this . skipIoMapping = skipIoMappings ; ExecutionStartContext executionStartContext = new ExecutionStartContext ( false ) ; InstantiationStack instantiationStack = new InstantiationStack ( new LinkedList < > ( activityStack ) ) ; executionStartContext . setInstantiationStack ( instantiationStack ) ; setStartContext ( executionStartContext ) ; performOperation ( PvmAtomicOperation . ACTIVITY_INIT_STACK_AND_RETURN ) ; Map < PvmActivity , PvmExecutionImpl > createdExecutions = new HashMap < > ( ) ; PvmExecutionImpl currentExecution = this ; for ( PvmActivity instantiatedActivity : activityStack ) { currentExecution = currentExecution . getNonEventScopeExecutions ( ) . get ( 0 ) ; if ( currentExecution . isConcurrent ( ) ) { currentExecution = currentExecution . getNonEventScopeExecutions ( ) . get ( 0 ) ; } createdExecutions . put ( instantiatedActivity , currentExecution ) ; } return createdExecutions ; } | Instantiates the given set of activities and returns the execution for the bottom - most activity |
10,096 | public void executeActivities ( List < PvmActivity > activityStack , PvmActivity targetActivity , PvmTransition targetTransition , Map < String , Object > variables , Map < String , Object > localVariables , boolean skipCustomListeners , boolean skipIoMappings ) { this . skipCustomListeners = skipCustomListeners ; this . skipIoMapping = skipIoMappings ; this . activityInstanceId = null ; this . isEnded = false ; if ( ! activityStack . isEmpty ( ) ) { ExecutionStartContext executionStartContext = new ExecutionStartContext ( false ) ; InstantiationStack instantiationStack = new InstantiationStack ( activityStack , targetActivity , targetTransition ) ; executionStartContext . setInstantiationStack ( instantiationStack ) ; executionStartContext . setVariables ( variables ) ; executionStartContext . setVariablesLocal ( localVariables ) ; setStartContext ( executionStartContext ) ; performOperation ( PvmAtomicOperation . ACTIVITY_INIT_STACK ) ; } else if ( targetActivity != null ) { setVariables ( variables ) ; setVariablesLocal ( localVariables ) ; setActivity ( targetActivity ) ; performOperation ( PvmAtomicOperation . ACTIVITY_START_CREATE_SCOPE ) ; } else if ( targetTransition != null ) { setVariables ( variables ) ; setVariablesLocal ( localVariables ) ; setActivity ( targetTransition . getSource ( ) ) ; setTransition ( targetTransition ) ; performOperation ( PvmAtomicOperation . TRANSITION_START_NOTIFY_LISTENER_TAKE ) ; } } | Instantiates the given activity stack . Uses this execution to execute the highest activity in the stack . Sets the variables for the execution responsible to execute the most deeply nested activity . |
10,097 | @ SuppressWarnings ( "unchecked" ) public void setParent ( PvmExecutionImpl parent ) { PvmExecutionImpl currentParent = getParent ( ) ; setParentExecution ( parent ) ; if ( currentParent != null ) { currentParent . getExecutions ( ) . remove ( this ) ; } if ( parent != null ) { ( ( List < PvmExecutionImpl > ) parent . getExecutions ( ) ) . add ( this ) ; } } | Sets the execution s parent and updates the old and new parents set of child executions |
10,098 | public void delayEvent ( PvmExecutionImpl targetScope , VariableEvent variableEvent ) { DelayedVariableEvent delayedVariableEvent = new DelayedVariableEvent ( targetScope , variableEvent ) ; delayEvent ( delayedVariableEvent ) ; } | Delays a given variable event with the given target scope . |
10,099 | public void delayEvent ( DelayedVariableEvent delayedVariableEvent ) { Boolean hasConditionalEvents = this . getProcessDefinition ( ) . getProperties ( ) . get ( BpmnProperties . HAS_CONDITIONAL_EVENTS ) ; if ( hasConditionalEvents == null || ! hasConditionalEvents . equals ( Boolean . TRUE ) ) { return ; } if ( isProcessInstanceExecution ( ) ) { delayedEvents . add ( delayedVariableEvent ) ; } else { getProcessInstance ( ) . delayEvent ( delayedVariableEvent ) ; } } | Delays and stores the given DelayedVariableEvent on the process instance . |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.