idx int64 0 41.2k | question stringlengths 73 5.81k | target stringlengths 5 918 |
|---|---|---|
9,900 | public List < CountPerProjectPermission > countUsersByProjectPermission ( DbSession dbSession , Collection < Long > projectIds ) { return executeLargeInputs ( projectIds , mapper ( dbSession ) :: countUsersByProjectPermission ) ; } | Count the number of users per permission for a given list of projects |
9,901 | public List < String > selectGlobalPermissionsOfUser ( DbSession dbSession , int userId , String organizationUuid ) { return mapper ( dbSession ) . selectGlobalPermissionsOfUser ( userId , organizationUuid ) ; } | Gets all the global permissions granted to user for the specified organization . |
9,902 | public List < String > selectProjectPermissionsOfUser ( DbSession dbSession , int userId , long projectId ) { return mapper ( dbSession ) . selectProjectPermissionsOfUser ( userId , projectId ) ; } | Gets all the project permissions granted to user for the specified project . |
9,903 | public void deleteGlobalPermission ( DbSession dbSession , int userId , String permission , String organizationUuid ) { mapper ( dbSession ) . deleteGlobalPermission ( userId , permission , organizationUuid ) ; } | Removes a single global permission from user |
9,904 | public void deleteProjectPermission ( DbSession dbSession , int userId , String permission , long projectId ) { mapper ( dbSession ) . deleteProjectPermission ( userId , permission , projectId ) ; } | Removes a single project permission from user |
9,905 | public int deleteProjectPermissionOfAnyUser ( DbSession dbSession , long projectId , String permission ) { return mapper ( dbSession ) . deleteProjectPermissionOfAnyUser ( projectId , permission ) ; } | Deletes the specified permission on the specified project for any user . |
9,906 | public Map < PluginClassLoaderDef , ClassLoader > create ( Collection < PluginClassLoaderDef > defs ) { ClassLoader baseClassLoader = baseClassLoader ( ) ; ClassloaderBuilder builder = new ClassloaderBuilder ( ) ; builder . newClassloader ( API_CLASSLOADER_KEY , baseClassLoader ) ; builder . setMask ( API_CLASSLOADER_KEY , apiMask ( ) ) ; for ( PluginClassLoaderDef def : defs ) { builder . newClassloader ( def . getBasePluginKey ( ) ) ; builder . setParent ( def . getBasePluginKey ( ) , API_CLASSLOADER_KEY , new Mask ( ) ) ; builder . setLoadingOrder ( def . getBasePluginKey ( ) , def . isSelfFirstStrategy ( ) ? SELF_FIRST : PARENT_FIRST ) ; for ( File jar : def . getFiles ( ) ) { builder . addURL ( def . getBasePluginKey ( ) , fileToUrl ( jar ) ) ; } exportResources ( def , builder , defs ) ; } return build ( defs , builder ) ; } | Creates as many classloaders as requested by the input parameter . |
9,907 | private void exportResources ( PluginClassLoaderDef def , ClassloaderBuilder builder , Collection < PluginClassLoaderDef > allPlugins ) { builder . setExportMask ( def . getBasePluginKey ( ) , def . getExportMask ( ) ) ; for ( PluginClassLoaderDef other : allPlugins ) { if ( ! other . getBasePluginKey ( ) . equals ( def . getBasePluginKey ( ) ) ) { builder . addSibling ( def . getBasePluginKey ( ) , other . getBasePluginKey ( ) , new Mask ( ) ) ; } } } | A plugin can export some resources to other plugins |
9,908 | private Map < PluginClassLoaderDef , ClassLoader > build ( Collection < PluginClassLoaderDef > defs , ClassloaderBuilder builder ) { Map < PluginClassLoaderDef , ClassLoader > result = new HashMap < > ( ) ; Map < String , ClassLoader > classloadersByBasePluginKey = builder . build ( ) ; for ( PluginClassLoaderDef def : defs ) { ClassLoader classloader = classloadersByBasePluginKey . get ( def . getBasePluginKey ( ) ) ; if ( classloader == null ) { throw new IllegalStateException ( String . format ( "Fail to create classloader for plugin [%s]" , def . getBasePluginKey ( ) ) ) ; } result . put ( def , classloader ) ; } return result ; } | Builds classloaders and verifies that all of them are correctly defined |
9,909 | public ContextPropertiesCache put ( String key , String value ) { checkArgument ( key != null , "Key of context property must not be null" ) ; checkArgument ( value != null , "Value of context property must not be null" ) ; props . put ( key , value ) ; return this ; } | Value is overridden if the key was already stored . |
9,910 | public static void deleteDirectory ( File directory ) throws IOException { requireNonNull ( directory , DIRECTORY_CAN_NOT_BE_NULL ) ; if ( ! directory . exists ( ) ) { return ; } Path path = directory . toPath ( ) ; if ( Files . isSymbolicLink ( path ) ) { throw new IOException ( format ( "Directory '%s' is a symbolic link" , directory ) ) ; } if ( directory . isFile ( ) ) { throw new IOException ( format ( "Directory '%s' is a file" , directory ) ) ; } deleteDirectoryImpl ( path ) ; if ( directory . exists ( ) ) { throw new IOException ( format ( "Unable to delete directory '%s'" , directory ) ) ; } } | Deletes a directory recursively . Does not support symbolic link to directories . |
9,911 | public static long sizeOf ( Path path ) throws IOException { SizeVisitor visitor = new SizeVisitor ( ) ; Files . walkFileTree ( path , visitor ) ; return visitor . size ; } | Size of file or directory in bytes . In case of a directory the size is the sum of the sizes of all files recursively traversed . |
9,912 | public static void reset ( File directory , int processNumber ) { try ( DefaultProcessCommands processCommands = new DefaultProcessCommands ( directory , processNumber , true ) ) { } } | Clears the shared memory space of the specified process number . |
9,913 | private void checkQualityProfilesConsistency ( ScannerReport . Metadata metadata , Organization organization ) { List < String > profileKeys = metadata . getQprofilesPerLanguage ( ) . values ( ) . stream ( ) . map ( QProfile :: getKey ) . collect ( toList ( metadata . getQprofilesPerLanguage ( ) . size ( ) ) ) ; try ( DbSession dbSession = dbClient . openSession ( false ) ) { List < QProfileDto > profiles = dbClient . qualityProfileDao ( ) . selectByUuids ( dbSession , profileKeys ) ; String badKeys = profiles . stream ( ) . filter ( p -> ! p . getOrganizationUuid ( ) . equals ( organization . getUuid ( ) ) ) . map ( QProfileDto :: getKee ) . collect ( MoreCollectors . join ( Joiner . on ( ", " ) ) ) ; if ( ! badKeys . isEmpty ( ) ) { throw MessageException . of ( format ( "Quality profiles with following keys don't exist in organization [%s]: %s" , organization . getKey ( ) , badKeys ) ) ; } } } | Check that the Quality profiles sent by scanner correctly relate to the project organization . |
9,914 | public List < WebhookDeliveryLiteDto > selectByWebhookUuid ( DbSession dbSession , String webhookUuid , int offset , int limit ) { return mapper ( dbSession ) . selectByWebhookUuid ( webhookUuid , new RowBounds ( offset , limit ) ) ; } | All the deliveries for the specified webhook . Results are ordered by descending date . |
9,915 | public List < WebhookDeliveryLiteDto > selectOrderedByComponentUuid ( DbSession dbSession , String componentUuid , int offset , int limit ) { return mapper ( dbSession ) . selectOrderedByComponentUuid ( componentUuid , new RowBounds ( offset , limit ) ) ; } | All the deliveries for the specified component . Results are ordered by descending date . |
9,916 | public List < WebhookDeliveryLiteDto > selectOrderedByCeTaskUuid ( DbSession dbSession , String ceTaskUuid , int offset , int limit ) { return mapper ( dbSession ) . selectOrderedByCeTaskUuid ( ceTaskUuid , new RowBounds ( offset , limit ) ) ; } | All the deliveries for the specified CE task . Results are ordered by descending date . |
9,917 | private void stopProcess ( ProcessId processId ) { SQProcess process = processesById . get ( processId ) ; if ( process != null ) { process . stop ( 1 , TimeUnit . MINUTES ) ; } } | Request for graceful stop then blocks until process is stopped . Returns immediately if the process is disabled in configuration . |
9,918 | public void terminate ( ) { restartRequested . set ( false ) ; restartDisabled . set ( true ) ; if ( nodeLifecycle . tryToMoveTo ( NodeLifecycle . State . STOPPING ) ) { LOG . info ( "Stopping SonarQube" ) ; } stopAll ( ) ; if ( stopperThread != null ) { stopperThread . interrupt ( ) ; } if ( restarterThread != null ) { restarterThread . interrupt ( ) ; } keepAlive . countDown ( ) ; } | Blocks until all processes are stopped . Pending restart if any is disabled . |
9,919 | private Map < String , ComponentDto > indexExistingDtosByUuids ( DbSession session ) { return dbClient . componentDao ( ) . selectAllComponentsFromProjectKey ( session , treeRootHolder . getRoot ( ) . getDbKey ( ) ) . stream ( ) . collect ( Collectors . toMap ( ComponentDto :: uuid , Function . identity ( ) ) ) ; } | Returns a mutable map of the components currently persisted in database for the project including disabled components . |
9,920 | private static void setParentModuleProperties ( ComponentDto componentDto , PathAwareVisitor . Path < ComponentDtoHolder > path ) { componentDto . setProjectUuid ( path . root ( ) . getDto ( ) . uuid ( ) ) ; ComponentDto parentModule = from ( path . getCurrentPath ( ) ) . filter ( ParentModulePathElement . INSTANCE ) . first ( ) . get ( ) . getElement ( ) . getDto ( ) ; componentDto . setUuidPath ( formatUuidPathFromParent ( path . parent ( ) . getDto ( ) ) ) ; componentDto . setRootUuid ( parentModule . uuid ( ) ) ; componentDto . setModuleUuid ( parentModule . uuid ( ) ) ; componentDto . setModuleUuidPath ( parentModule . moduleUuidPath ( ) ) ; } | Applies to a node of type either DIRECTORY or FILE |
9,921 | private < T > List < Object > getDependents ( T extension ) { return new ArrayList < > ( evaluateAnnotatedClasses ( extension , DependedUpon . class ) ) ; } | Objects that depend upon this extension . |
9,922 | public Optional < File > get ( InstalledPlugin plugin ) { File jarInCache = jarInCache ( plugin . key , plugin . hash ) ; if ( jarInCache . exists ( ) && jarInCache . isFile ( ) ) { return Optional . of ( jarInCache ) ; } return download ( plugin ) ; } | Get the JAR file of specified plugin . If not present in user local cache then it s downloaded from server and added to cache . |
9,923 | private EventComponentChangeDto setChangeCategory ( String changeCategory ) { this . category = ChangeCategory . fromDbValue ( changeCategory ) . orElseThrow ( ( ) -> new IllegalArgumentException ( "Unsupported changeCategory DB value: " + changeCategory ) ) ; return this ; } | Used by MyBatis through reflection . |
9,924 | public boolean isCompatibleWith ( String runtimeVersion ) { if ( null == this . minimalSqVersion ) { return true ; } Version effectiveMin = Version . create ( minimalSqVersion . getName ( ) ) . removeQualifier ( ) ; Version effectiveVersion = Version . create ( runtimeVersion ) . removeQualifier ( ) ; if ( runtimeVersion . endsWith ( "-SNAPSHOT" ) ) { effectiveMin = Version . create ( effectiveMin . getMajor ( ) + "." + effectiveMin . getMinor ( ) ) ; } return effectiveVersion . compareTo ( effectiveMin ) >= 0 ; } | Find out if this plugin is compatible with a given version of SonarQube . The version of SQ must be greater than or equal to the minimal version needed by the plugin . |
9,925 | void match ( Input < RAW > rawInput , Input < BASE > baseInput , Tracking < RAW , BASE > tracking ) { BlockHashSequence rawHashSequence = rawInput . getBlockHashSequence ( ) ; BlockHashSequence baseHashSequence = baseInput . getBlockHashSequence ( ) ; Multimap < Integer , RAW > rawsByLine = groupByLine ( tracking . getUnmatchedRaws ( ) , rawHashSequence ) ; Multimap < Integer , BASE > basesByLine = groupByLine ( tracking . getUnmatchedBases ( ) , baseHashSequence ) ; Map < Integer , HashOccurrence > occurrencesByHash = new HashMap < > ( ) ; for ( Integer line : basesByLine . keySet ( ) ) { int hash = baseHashSequence . getBlockHashForLine ( line ) ; HashOccurrence hashOccurrence = occurrencesByHash . get ( hash ) ; if ( hashOccurrence == null ) { hashOccurrence = new HashOccurrence ( ) ; hashOccurrence . baseLine = line ; hashOccurrence . baseCount = 1 ; occurrencesByHash . put ( hash , hashOccurrence ) ; } else { hashOccurrence . baseCount ++ ; } } for ( Integer line : rawsByLine . keySet ( ) ) { int hash = rawHashSequence . getBlockHashForLine ( line ) ; HashOccurrence hashOccurrence = occurrencesByHash . get ( hash ) ; if ( hashOccurrence != null ) { hashOccurrence . rawLine = line ; hashOccurrence . rawCount ++ ; } } for ( HashOccurrence hashOccurrence : occurrencesByHash . values ( ) ) { if ( hashOccurrence . baseCount == 1 && hashOccurrence . rawCount == 1 ) { map ( rawsByLine . get ( hashOccurrence . rawLine ) , basesByLine . get ( hashOccurrence . baseLine ) , tracking ) ; basesByLine . removeAll ( hashOccurrence . baseLine ) ; rawsByLine . removeAll ( hashOccurrence . rawLine ) ; } } if ( basesByLine . keySet ( ) . size ( ) * rawsByLine . keySet ( ) . size ( ) >= 250_000 ) { return ; } List < LinePair > possibleLinePairs = Lists . newArrayList ( ) ; for ( Integer baseLine : basesByLine . keySet ( ) ) { for ( Integer rawLine : rawsByLine . keySet ( ) ) { int weight = lengthOfMaximalBlock ( baseInput . getLineHashSequence ( ) , baseLine , rawInput . getLineHashSequence ( ) , rawLine ) ; if ( weight > 0 ) { possibleLinePairs . add ( new LinePair ( baseLine , rawLine , weight ) ) ; } } } Collections . sort ( possibleLinePairs , LinePairComparator . INSTANCE ) ; for ( LinePair linePair : possibleLinePairs ) { map ( rawsByLine . get ( linePair . rawLine ) , basesByLine . get ( linePair . baseLine ) , tracking ) ; } } | If base source code is available then detect code moves through block hashes . Only the issues associated to a line can be matched here . |
9,926 | public Set < String > loadUuidsOfComponentsWithOpenIssues ( ) { try ( DbSession dbSession = dbClient . openSession ( false ) ) { return dbClient . issueDao ( ) . selectComponentUuidsOfOpenIssuesForProjectUuid ( dbSession , treeRootHolder . getRoot ( ) . getUuid ( ) ) ; } } | Uuids of all the components that have open issues on this project . |
9,927 | public boolean shouldExecute ( DefaultPostJobDescriptor descriptor ) { if ( ! settingsCondition ( descriptor ) ) { LOG . debug ( "'{}' skipped because one of the required properties is missing" , descriptor . name ( ) ) ; return false ; } return true ; } | Decide if the given PostJob should be executed . |
9,928 | private void ensureLastAdminIsNotRemoved ( DbSession dbSession , GroupDto group , UserDto user ) { int remainingAdmins = dbClient . authorizationDao ( ) . countUsersWithGlobalPermissionExcludingGroupMember ( dbSession , group . getOrganizationUuid ( ) , OrganizationPermission . ADMINISTER . getKey ( ) , group . getId ( ) , user . getId ( ) ) ; checkRequest ( remainingAdmins > 0 , "The last administrator user cannot be removed" ) ; } | Ensure that there are still users with admin global permission if user is removed from the group . |
9,929 | public T addSubFields ( DefaultIndexSettingsElement ... analyzers ) { Arrays . stream ( analyzers ) . forEach ( analyzer -> addSubField ( analyzer . getSubFieldSuffix ( ) , analyzer . fieldMapping ( ) ) ) ; return castThis ( ) ; } | Add subfields one for each analyzer . |
9,930 | public static void createSchema ( Connection connection , String dialect , boolean createSchemaMigrations ) { if ( createSchemaMigrations ) { executeScript ( connection , "org/sonar/db/version/schema_migrations-" + dialect + ".ddl" ) ; } executeScript ( connection , "org/sonar/db/version/schema-" + dialect + ".ddl" ) ; executeScript ( connection , "org/sonar/db/version/rows-" + dialect + ".sql" ) ; } | The connection is commited in this method but not closed . |
9,931 | private RuleDto getRuleDto ( RuleUpdate change ) { try ( DbSession dbSession = dbClient . openSession ( false ) ) { RuleDto rule = dbClient . ruleDao ( ) . selectOrFailByKey ( dbSession , change . getOrganization ( ) , change . getRuleKey ( ) ) ; if ( RuleStatus . REMOVED == rule . getStatus ( ) ) { throw new IllegalArgumentException ( "Rule with REMOVED status cannot be updated: " + change . getRuleKey ( ) ) ; } return rule ; } } | Load all the DTOs required for validating changes and updating rule |
9,932 | private Multimap < String , Setting > loadComponentSettings ( DbSession dbSession , Set < String > keys , ComponentDto component ) { List < String > componentUuids = DOT_SPLITTER . splitToList ( component . moduleUuidPath ( ) ) ; List < ComponentDto > componentDtos = dbClient . componentDao ( ) . selectByUuids ( dbSession , componentUuids ) ; Set < Long > componentIds = componentDtos . stream ( ) . map ( ComponentDto :: getId ) . collect ( Collectors . toSet ( ) ) ; Map < Long , String > uuidsById = componentDtos . stream ( ) . collect ( Collectors . toMap ( ComponentDto :: getId , ComponentDto :: uuid ) ) ; List < PropertyDto > properties = dbClient . propertiesDao ( ) . selectPropertiesByKeysAndComponentIds ( dbSession , keys , componentIds ) ; List < PropertyDto > propertySets = dbClient . propertiesDao ( ) . selectPropertiesByKeysAndComponentIds ( dbSession , getPropertySetKeys ( properties ) , componentIds ) ; Multimap < String , Setting > settingsByUuid = TreeMultimap . create ( Ordering . explicit ( componentUuids ) , Ordering . arbitrary ( ) ) ; for ( PropertyDto propertyDto : properties ) { Long componentId = propertyDto . getResourceId ( ) ; String componentUuid = uuidsById . get ( componentId ) ; String propertyKey = propertyDto . getKey ( ) ; settingsByUuid . put ( componentUuid , Setting . createFromDto ( propertyDto , getPropertySets ( propertyKey , propertySets , componentId ) , propertyDefinitions . get ( propertyKey ) ) ) ; } return settingsByUuid ; } | Return list of settings by component uuid sorted from project to lowest module |
9,933 | private static boolean isPeerChanged ( Change change , ChangedIssue issue ) { Optional < User > assignee = issue . getAssignee ( ) ; return ! assignee . isPresent ( ) || ! change . isAuthorLogin ( assignee . get ( ) . getLogin ( ) ) ; } | Is the author of the change the assignee of the specified issue? If not it means the issue has been changed by a peer of the author of the change . |
9,934 | public LinkedHashMap < String , Long > get ( String facetName ) { return facetsByName . get ( facetName ) ; } | The buckets of the given facet . Null if the facet does not exist |
9,935 | protected List < ComponentDto > doKeepAuthorizedComponents ( String permission , Collection < ComponentDto > components ) { boolean allowPublicComponent = PUBLIC_PERMISSIONS . contains ( permission ) ; return components . stream ( ) . filter ( c -> ( allowPublicComponent && ! c . isPrivate ( ) ) || hasComponentPermission ( permission , c ) ) . collect ( MoreCollectors . toList ( ) ) ; } | Naive implementation to be overridden if needed |
9,936 | public Map < String , String > getProperties ( ) { ImmutableMap . Builder < String , String > builder = ImmutableMap . builder ( ) ; builder . putAll ( parentSettings . getProperties ( ) ) ; builder . putAll ( localProperties ) ; return builder . build ( ) ; } | Only returns the currently loaded properties . |
9,937 | public void insert ( DbSession session , DuplicationUnitDto dto ) { session . getMapper ( DuplicationMapper . class ) . batchInsert ( dto ) ; } | Insert rows in the table DUPLICATIONS_INDEX . Note that generated ids are not returned . |
9,938 | static String basePluginKey ( PluginInfo plugin , Map < String , PluginInfo > allPluginsPerKey ) { String base = plugin . getKey ( ) ; String parentKey = plugin . getBasePlugin ( ) ; while ( ! Strings . isNullOrEmpty ( parentKey ) ) { PluginInfo parentPlugin = allPluginsPerKey . get ( parentKey ) ; base = parentPlugin . getKey ( ) ; parentKey = parentPlugin . getBasePlugin ( ) ; } return base ; } | Get the root key of a tree of plugins . For example if plugin C depends on B which depends on A then B and C must be attached to the classloader of A . The method returns A in the three cases . |
9,939 | public Result isUTF16 ( byte [ ] buffer , boolean failOnNull ) { if ( buffer . length < 2 ) { return Result . INVALID ; } int beAscii = 0 ; int beLines = 0 ; int leAscii = 0 ; int leLines = 0 ; for ( int i = 0 ; i < buffer . length / 2 ; i ++ ) { byte c1 = buffer [ i * 2 ] ; byte c2 = buffer [ i * 2 + 1 ] ; if ( c1 == 0 ) { if ( c2 != 0 ) { if ( c2 == 0x0a || c2 == 0x0d ) { beLines ++ ; } beAscii ++ ; } else if ( failOnNull ) { return Result . INVALID ; } } else if ( c2 == 0 ) { leAscii ++ ; if ( c1 == 0x0a || c1 == 0x0d ) { leLines ++ ; } } } double beAsciiPerc = beAscii * 2.0 / ( double ) buffer . length ; double leAsciiPerc = leAscii * 2.0 / ( double ) buffer . length ; if ( leLines == 0 ) { if ( beAsciiPerc >= UTF_16_NULL_PASS_THRESHOLD && leAsciiPerc < UTF_16_NULL_FAIL_THRESHOLD ) { return Result . newValid ( StandardCharsets . UTF_16BE ) ; } if ( beLines > 0 ) { return Result . newValid ( StandardCharsets . UTF_16BE ) ; } } else if ( beLines > 0 ) { return Result . INVALID ; } if ( beLines == 0 ) { if ( leAsciiPerc >= UTF_16_NULL_PASS_THRESHOLD && beAsciiPerc < UTF_16_NULL_FAIL_THRESHOLD ) { return Result . newValid ( StandardCharsets . UTF_16LE ) ; } if ( leLines > 0 ) { return Result . newValid ( StandardCharsets . UTF_16LE ) ; } } return new Result ( Validation . MAYBE , null ) ; } | Checks if an array of bytes looks UTF - 16 encoded . We look for clues by checking the presence of nulls and new line control chars in both little and big endian byte orders . Failing on nulls will greatly reduce FPs if the buffer is actually encoded in UTF - 32 . |
9,940 | public Result isValidWindows1252 ( byte [ ] buf ) { for ( byte b : buf ) { if ( ! VALID_WINDOWS_1252 [ b + 128 ] ) { return Result . INVALID ; } } try { return new Result ( Validation . MAYBE , Charset . forName ( "Windows-1252" ) ) ; } catch ( UnsupportedCharsetException e ) { return Result . INVALID ; } } | Verify that the buffer doesn t contain bytes that are not supposed to be used by Windows - 1252 . |
9,941 | public Map < K , V > getAll ( Iterable < K > keys ) { List < K > missingKeys = new ArrayList < > ( ) ; Map < K , V > result = new HashMap < > ( ) ; for ( K key : keys ) { V value = map . get ( key ) ; if ( value == null && ! map . containsKey ( key ) ) { missingKeys . add ( key ) ; } else { result . put ( key , value ) ; } } if ( ! missingKeys . isEmpty ( ) ) { Map < K , V > missingValues = loader . loadAll ( missingKeys ) ; map . putAll ( missingValues ) ; result . putAll ( missingValues ) ; for ( K missingKey : missingKeys ) { if ( ! map . containsKey ( missingKey ) ) { map . put ( missingKey , null ) ; result . put ( missingKey , null ) ; } } } return result ; } | Get values associated with keys . All the requested keys are included in the Map result . Value is null if the key is not found in cache . |
9,942 | public void configureForSubprocessGobbler ( Props props , String logPattern ) { if ( isAllLogsToConsoleEnabled ( props ) ) { LoggerContext ctx = getRootContext ( ) ; ctx . getLogger ( ROOT_LOGGER_NAME ) . addAppender ( newConsoleAppender ( ctx , "root_console" , logPattern ) ) ; } } | Make the logback configuration for a sub process to correctly push all its logs to be read by a stream gobbler on the sub process s System . out . |
9,943 | public void resetFromXml ( String xmlResourcePath ) throws JoranException { LoggerContext context = ( LoggerContext ) LoggerFactory . getILoggerFactory ( ) ; JoranConfigurator configurator = new JoranConfigurator ( ) ; configurator . setContext ( context ) ; context . reset ( ) ; configurator . doConfigure ( LogbackHelper . class . getResource ( xmlResourcePath ) ) ; } | Generally used to reset logback in logging tests |
9,944 | public void launch ( Monitored mp ) { if ( ! lifecycle . tryToMoveTo ( Lifecycle . State . STARTING ) ) { throw new IllegalStateException ( "Already started" ) ; } monitored = mp ; Logger logger = LoggerFactory . getLogger ( getClass ( ) ) ; try { launch ( logger ) ; } catch ( Exception e ) { logger . warn ( "Fail to start {}" , getKey ( ) , e ) ; } finally { stop ( ) ; } } | Launch process and waits until it s down |
9,945 | static boolean applyTags ( RuleDto rule , Set < String > tags ) { for ( String tag : tags ) { RuleTagFormat . validate ( tag ) ; } Set < String > initialTags = rule . getTags ( ) ; final Set < String > systemTags = rule . getSystemTags ( ) ; Set < String > withoutSystemTags = Sets . filter ( tags , input -> input != null && ! systemTags . contains ( input ) ) ; rule . setTags ( withoutSystemTags ) ; return withoutSystemTags . size ( ) != initialTags . size ( ) || ! withoutSystemTags . containsAll ( initialTags ) ; } | Validates tags and resolves conflicts between user and system tags . |
9,946 | public List < OrgActiveRuleDto > selectByProfileUuid ( DbSession dbSession , String uuid ) { return mapper ( dbSession ) . selectByProfileUuid ( uuid ) ; } | Active rule on removed rule are NOT returned |
9,947 | public List < ActiveRuleParamDto > selectParamsByActiveRuleId ( DbSession dbSession , Integer activeRuleId ) { return mapper ( dbSession ) . selectParamsByActiveRuleId ( activeRuleId ) ; } | Nested DTO ActiveRuleParams |
9,948 | private Optional < String > guessScmAuthor ( DefaultIssue issue , Component component ) { String author = null ; if ( scmChangesets != null ) { author = IssueLocations . allLinesFor ( issue , component . getUuid ( ) ) . filter ( scmChangesets :: hasChangesetForLine ) . mapToObj ( scmChangesets :: getChangesetForLine ) . filter ( c -> StringUtils . isNotEmpty ( c . getAuthor ( ) ) ) . max ( Comparator . comparingLong ( Changeset :: getDate ) ) . map ( Changeset :: getAuthor ) . orElse ( null ) ; } return Optional . ofNullable ( defaultIfEmpty ( author , lastCommitAuthor ) ) ; } | Author of the latest change on the lines involved by the issue . If no authors are set on the lines then the author of the latest change on the file is returned . |
9,949 | private static Set < OrgLang > selectOrgsWithMultipleDefaultProfiles ( Context context ) throws SQLException { Select rows = context . prepareSelect ( "select organization_uuid, language from rules_profiles " + " where is_default = ? " + " group by organization_uuid, language " + " having count(kee) > 1 " ) . setBoolean ( 1 , true ) ; return new HashSet < > ( rows . list ( row -> new OrgLang ( row . getString ( 1 ) , row . getString ( 2 ) ) ) ) ; } | By design the table rules_profiles does not enforce to have a single profile marked as default for an organization and language . This method returns the buggy rows . |
9,950 | public static String cleanKeyForFilename ( String projectKey ) { String cleanKey = StringUtils . deleteWhitespace ( projectKey ) ; return StringUtils . replace ( cleanKey , ":" , "_" ) ; } | Clean provided string to remove chars that are not valid as file name . |
9,951 | public void deleteByKeys ( String projectUuid , Collection < String > issueKeys ) { if ( issueKeys . isEmpty ( ) ) { return ; } BulkIndexer bulkIndexer = createBulkIndexer ( Size . REGULAR , IndexingListener . FAIL_ON_ERROR ) ; bulkIndexer . start ( ) ; issueKeys . forEach ( issueKey -> bulkIndexer . addDeletion ( TYPE_ISSUE . getMainType ( ) , issueKey , AuthorizationDoc . idOf ( projectUuid ) ) ) ; bulkIndexer . stop ( ) ; } | Used by Compute Engine no need to recovery on errors |
9,952 | private void applySeverityAndParamToChange ( RuleActivation request , RuleActivationContext context , ActiveRuleChange change ) { RuleWrapper rule = context . getRule ( ) ; ActiveRuleWrapper activeRule = context . getActiveRule ( ) ; ActiveRuleWrapper parentActiveRule = context . getParentActiveRule ( ) ; String severity ; if ( request . isReset ( ) ) { severity = firstNonNull ( parentActiveRule != null ? parentActiveRule . get ( ) . getSeverityString ( ) : null , rule . get ( ) . getSeverityString ( ) ) ; } else if ( context . getRulesProfile ( ) . isBuiltIn ( ) ) { severity = firstNonNull ( request . getSeverity ( ) , rule . get ( ) . getSeverityString ( ) ) ; } else { severity = firstNonNull ( request . getSeverity ( ) , activeRule == null ? null : activeRule . get ( ) . getSeverityString ( ) , parentActiveRule != null ? parentActiveRule . get ( ) . getSeverityString ( ) : null , rule . get ( ) . getSeverityString ( ) ) ; } change . setSeverity ( severity ) ; for ( RuleParamDto ruleParamDto : rule . getParams ( ) ) { String paramKey = ruleParamDto . getName ( ) ; String paramValue ; if ( request . isReset ( ) ) { paramValue = firstNonNull ( parentActiveRule != null ? parentActiveRule . getParamValue ( paramKey ) : null , rule . getParamDefaultValue ( paramKey ) ) ; } else if ( context . getRulesProfile ( ) . isBuiltIn ( ) ) { paramValue = firstNonNull ( context . getRequestedParamValue ( request , paramKey ) , rule . getParamDefaultValue ( paramKey ) ) ; } else { String parentValue = parentActiveRule != null ? parentActiveRule . getParamValue ( paramKey ) : null ; String activeRuleValue = activeRule == null ? null : activeRule . getParamValue ( paramKey ) ; paramValue = context . hasRequestedParamValue ( request , paramKey ) ? firstNonNull ( context . getRequestedParamValue ( request , paramKey ) , parentValue , rule . getParamDefaultValue ( paramKey ) ) : firstNonNull ( activeRuleValue , parentValue , rule . getParamDefaultValue ( paramKey ) ) ; } change . setParameter ( paramKey , validateParam ( ruleParamDto , paramValue ) ) ; } } | Update severity and params |
9,953 | private static boolean isSameAsParent ( ActiveRuleChange change , RuleActivationContext context ) { ActiveRuleWrapper parentActiveRule = context . getParentActiveRule ( ) ; if ( parentActiveRule == null ) { return false ; } if ( ! StringUtils . equals ( change . getSeverity ( ) , parentActiveRule . get ( ) . getSeverityString ( ) ) ) { return false ; } for ( Map . Entry < String , String > entry : change . getParameters ( ) . entrySet ( ) ) { if ( entry . getValue ( ) != null && ! entry . getValue ( ) . equals ( parentActiveRule . getParamValue ( entry . getKey ( ) ) ) ) { return false ; } } return true ; } | True if trying to override an inherited rule but with exactly the same values |
9,954 | private static Double valueAsDouble ( Measure measure ) { switch ( measure . getValueType ( ) ) { case BOOLEAN : return measure . getBooleanValue ( ) ? 1.0d : 0.0d ; case INT : return ( double ) measure . getIntValue ( ) ; case LONG : return ( double ) measure . getLongValue ( ) ; case DOUBLE : return measure . getDoubleValue ( ) ; case NO_VALUE : case STRING : case LEVEL : default : return null ; } } | return the numerical value as a double . It s the type used in db . Returns null if no numerical value found |
9,955 | private void ensureBuiltInDefaultQPContainsRules ( DbSession dbSession ) { Map < String , RulesProfileDto > rulesProfilesByLanguage = dbClient . qualityProfileDao ( ) . selectBuiltInRuleProfilesWithActiveRules ( dbSession ) . stream ( ) . collect ( toMap ( RulesProfileDto :: getLanguage , Function . identity ( ) , ( oldValue , newValue ) -> oldValue ) ) ; dbClient . qualityProfileDao ( ) . selectDefaultBuiltInProfilesWithoutActiveRules ( dbSession , rulesProfilesByLanguage . keySet ( ) ) . forEach ( qp -> { RulesProfileDto rulesProfile = rulesProfilesByLanguage . get ( qp . getLanguage ( ) ) ; if ( rulesProfile == null ) { return ; } QProfileDto qualityProfile = dbClient . qualityProfileDao ( ) . selectByRuleProfileUuid ( dbSession , qp . getOrganizationUuid ( ) , rulesProfile . getKee ( ) ) ; if ( qualityProfile == null ) { return ; } Set < String > uuids = dbClient . defaultQProfileDao ( ) . selectExistingQProfileUuids ( dbSession , qp . getOrganizationUuid ( ) , Collections . singleton ( qp . getKee ( ) ) ) ; dbClient . defaultQProfileDao ( ) . deleteByQProfileUuids ( dbSession , uuids ) ; dbClient . defaultQProfileDao ( ) . insertOrUpdate ( dbSession , new DefaultQProfileDto ( ) . setQProfileUuid ( qualityProfile . getKee ( ) ) . setLanguage ( qp . getLanguage ( ) ) . setOrganizationUuid ( qp . getOrganizationUuid ( ) ) ) ; LOGGER . info ( "Default built-in quality profile for language [{}] has been updated from [{}] to [{}] since previous default does not have active rules." , qp . getLanguage ( ) , qp . getName ( ) , rulesProfile . getName ( ) ) ; } ) ; dbSession . commit ( ) ; } | This method ensure that if a default built - in quality profile does not have any active rules but another built - in one for the same language does have active rules the last one will be the default one . |
9,956 | private static long hash ( byte [ ] input ) { long hash = FNV1_INIT ; for ( byte b : input ) { hash ^= b & 0xff ; hash *= FNV1_PRIME ; } return hash ; } | hash method of a String independant of the JVM FNV - 1a hash method |
9,957 | public static IssueDto toDtoForServerInsert ( DefaultIssue issue , ComponentDto component , ComponentDto project , int ruleId , long now ) { return toDtoForComputationInsert ( issue , ruleId , now ) . setComponent ( component ) . setProject ( project ) ; } | On server side we need component keys and uuid |
9,958 | public void stopScheduling ( ) { LOG . debug ( "Stopping compute engine" ) ; for ( ChainingCallback chainingCallback : chainingCallbacks ) { chainingCallback . stop ( false ) ; } long until = System . currentTimeMillis ( ) + gracefulStopTimeoutInMs ; LOG . info ( "Waiting for workers to finish in-progress tasks" ) ; while ( System . currentTimeMillis ( ) < until && ceWorkerController . hasAtLeastOneProcessingWorker ( ) ) { try { Thread . sleep ( 200L ) ; } catch ( InterruptedException e ) { LOG . debug ( "Graceful stop period has been interrupted: {}" , e ) ; Thread . currentThread ( ) . interrupt ( ) ; break ; } } if ( ceWorkerController . hasAtLeastOneProcessingWorker ( ) ) { LOG . info ( "Some in-progress tasks did not finish in due time. Tasks will be stopped." ) ; } for ( ChainingCallback chainingCallback : chainingCallbacks ) { chainingCallback . stop ( true ) ; } } | This method is stopping all the workers giving them a delay before killing them . |
9,959 | public void load ( RulesDefinition . NewRepository repo , InputStream input , String encoding ) { load ( repo , input , Charset . forName ( encoding ) ) ; } | Loads rules by reading the XML input stream . The input stream is not always closed by the method so it should be handled by the caller . |
9,960 | public void load ( RulesDefinition . NewRepository repo , Reader reader ) { XMLInputFactory xmlFactory = XMLInputFactory . newInstance ( ) ; xmlFactory . setProperty ( XMLInputFactory . IS_COALESCING , Boolean . TRUE ) ; xmlFactory . setProperty ( XMLInputFactory . IS_NAMESPACE_AWARE , Boolean . FALSE ) ; xmlFactory . setProperty ( XMLInputFactory . SUPPORT_DTD , Boolean . FALSE ) ; xmlFactory . setProperty ( XMLInputFactory . IS_VALIDATING , Boolean . FALSE ) ; SMInputFactory inputFactory = new SMInputFactory ( xmlFactory ) ; try { SMHierarchicCursor rootC = inputFactory . rootElementCursor ( reader ) ; rootC . advance ( ) ; SMInputCursor rulesC = rootC . childElementCursor ( "rule" ) ; while ( rulesC . getNext ( ) != null ) { processRule ( repo , rulesC ) ; } } catch ( XMLStreamException e ) { throw new IllegalStateException ( "XML is not valid" , e ) ; } } | Loads rules by reading the XML input stream . The reader is not closed by the method so it should be handled by the caller . |
9,961 | public static SonarRuntime forSonarQube ( Version version , SonarQubeSide side ) { return new SonarRuntimeImpl ( version , SonarProduct . SONARQUBE , side ) ; } | Create an instance for SonarQube runtime environment . |
9,962 | public List < ActiveRule > getActiveRulesByRepository ( String repositoryKey ) { List < ActiveRule > result = new ArrayList < > ( ) ; for ( ActiveRule activeRule : activeRules ) { if ( repositoryKey . equals ( activeRule . getRepositoryKey ( ) ) && activeRule . isEnabled ( ) ) { result . add ( activeRule ) ; } } return result ; } | Get the active rules of a specific repository . Only enabled rules are selected . Disabled rules are excluded . |
9,963 | private static DefaultIssueComment copyComment ( String issueKey , DefaultIssueComment c ) { DefaultIssueComment comment = new DefaultIssueComment ( ) ; comment . setIssueKey ( issueKey ) ; comment . setKey ( Uuids . create ( ) ) ; comment . setUserUuid ( c . userUuid ( ) ) ; comment . setMarkdownText ( c . markdownText ( ) ) ; comment . setCreatedAt ( c . createdAt ( ) ) . setUpdatedAt ( c . updatedAt ( ) ) ; comment . setNew ( true ) ; return comment ; } | Copy a comment from another issue |
9,964 | private static Optional < FieldDiffs > copyFieldDiffOfIssueFromOtherBranch ( String issueKey , FieldDiffs c ) { FieldDiffs result = new FieldDiffs ( ) ; result . setIssueKey ( issueKey ) ; result . setUserUuid ( c . userUuid ( ) ) ; result . setCreationDate ( c . creationDate ( ) ) ; c . diffs ( ) . entrySet ( ) . stream ( ) . filter ( e -> ! e . getKey ( ) . equals ( IssueFieldsSetter . FILE ) ) . forEach ( e -> result . setDiff ( e . getKey ( ) , e . getValue ( ) . oldValue ( ) , e . getValue ( ) . newValue ( ) ) ) ; if ( result . diffs ( ) . isEmpty ( ) ) { return Optional . empty ( ) ; } return Optional . of ( result ) ; } | Copy a diff from another issue |
9,965 | public Stream < BASE > getUnmatchedBases ( ) { return bases . stream ( ) . filter ( base -> ! baseToRaw . containsKey ( base ) ) ; } | The base issues that are not matched by a raw issue and that need to be closed . |
9,966 | public void synchronizeUserOrganizationMembership ( DbSession dbSession , UserDto user , ALM alm , Set < String > organizationAlmIds ) { Set < String > userOrganizationUuids = dbClient . organizationMemberDao ( ) . selectOrganizationUuidsByUser ( dbSession , user . getId ( ) ) ; Set < String > userOrganizationUuidsWithMembersSyncEnabled = dbClient . organizationAlmBindingDao ( ) . selectByOrganizationUuids ( dbSession , userOrganizationUuids ) . stream ( ) . filter ( OrganizationAlmBindingDto :: isMembersSyncEnable ) . map ( OrganizationAlmBindingDto :: getOrganizationUuid ) . collect ( toSet ( ) ) ; Set < String > almOrganizationUuidsWithMembersSyncEnabled = dbClient . organizationAlmBindingDao ( ) . selectByOrganizationAlmIds ( dbSession , alm , organizationAlmIds ) . stream ( ) . filter ( OrganizationAlmBindingDto :: isMembersSyncEnable ) . map ( OrganizationAlmBindingDto :: getOrganizationUuid ) . collect ( toSet ( ) ) ; Set < String > organizationUuidsToBeAdded = difference ( almOrganizationUuidsWithMembersSyncEnabled , userOrganizationUuidsWithMembersSyncEnabled ) ; Set < String > organizationUuidsToBeRemoved = difference ( userOrganizationUuidsWithMembersSyncEnabled , almOrganizationUuidsWithMembersSyncEnabled ) ; Map < String , OrganizationDto > allOrganizationsByUuid = dbClient . organizationDao ( ) . selectByUuids ( dbSession , union ( organizationUuidsToBeAdded , organizationUuidsToBeRemoved ) ) . stream ( ) . collect ( uniqueIndex ( OrganizationDto :: getUuid ) ) ; allOrganizationsByUuid . entrySet ( ) . stream ( ) . filter ( entry -> organizationUuidsToBeAdded . contains ( entry . getKey ( ) ) ) . forEach ( entry -> addMemberInDb ( dbSession , entry . getValue ( ) , user ) ) ; allOrganizationsByUuid . entrySet ( ) . stream ( ) . filter ( entry -> organizationUuidsToBeRemoved . contains ( entry . getKey ( ) ) ) . forEach ( entry -> removeMemberInDb ( dbSession , entry . getValue ( ) , user ) ) ; } | Synchronize organization membership of a user from a list of ALM organization specific ids Please note that no commit will not be executed . |
9,967 | public Map < String , Integer > countByStatusAndMainComponentUuids ( DbSession dbSession , CeQueueDto . Status status , Set < String > projectUuids ) { if ( projectUuids . isEmpty ( ) ) { return emptyMap ( ) ; } ImmutableMap . Builder < String , Integer > builder = ImmutableMap . builder ( ) ; executeLargeUpdates ( projectUuids , partitionOfProjectUuids -> { List < QueueCount > i = mapper ( dbSession ) . countByStatusAndMainComponentUuids ( status , partitionOfProjectUuids ) ; i . forEach ( o -> builder . put ( o . getMainComponentUuid ( ) , o . getTotal ( ) ) ) ; } ) ; return builder . build ( ) ; } | Counts entries in the queue with the specified status for each specified main component uuid . |
9,968 | public File writeMetadata ( ScannerReport . Metadata metadata ) { Protobuf . write ( metadata , fileStructure . metadataFile ( ) ) ; return fileStructure . metadataFile ( ) ; } | Metadata is mandatory |
9,969 | public Set < String > selectOrganizationPermissions ( DbSession dbSession , String organizationUuid , int userId ) { return mapper ( dbSession ) . selectOrganizationPermissions ( organizationUuid , userId ) ; } | Loads all the permissions granted to user for the specified organization |
9,970 | public Set < String > selectOrganizationPermissionsOfAnonymous ( DbSession dbSession , String organizationUuid ) { return mapper ( dbSession ) . selectOrganizationPermissionsOfAnonymous ( organizationUuid ) ; } | Loads all the permissions granted to anonymous user for the specified organization |
9,971 | public List < Integer > selectUserIdsWithGlobalPermission ( DbSession dbSession , String organizationUuid , String permission ) { return mapper ( dbSession ) . selectUserIdsWithGlobalPermission ( organizationUuid , permission ) ; } | The list of users who have the global permission . The anyone virtual group is not taken into account . |
9,972 | public Collection < Integer > keepAuthorizedUsersForRoleAndProject ( DbSession dbSession , Collection < Integer > userIds , String role , long projectId ) { return executeLargeInputs ( userIds , partitionOfIds -> mapper ( dbSession ) . keepAuthorizedUsersForRoleAndProject ( role , projectId , partitionOfIds ) , partitionSize -> partitionSize / 3 ) ; } | Keep only authorized user that have the given permission on a given project . Please Note that if the permission is Anyone is NOT taking into account by this method . |
9,973 | public Set < EmailSubscriberDto > selectGlobalAdministerEmailSubscribers ( DbSession dbSession ) { return mapper ( dbSession ) . selectEmailSubscribersWithGlobalPermission ( ADMINISTER . getKey ( ) ) ; } | Used by license notifications |
9,974 | private void configureDirectToConsoleLoggers ( LoggerContext context , String ... loggerNames ) { RootLoggerConfig config = newRootLoggerConfigBuilder ( ) . setProcessId ( ProcessId . APP ) . setThreadIdFieldPattern ( "" ) . build ( ) ; String logPattern = helper . buildLogPattern ( config ) ; ConsoleAppender < ILoggingEvent > consoleAppender = helper . newConsoleAppender ( context , "CONSOLE" , logPattern ) ; for ( String loggerName : loggerNames ) { Logger consoleLogger = context . getLogger ( loggerName ) ; consoleLogger . setAdditive ( false ) ; consoleLogger . addAppender ( consoleAppender ) ; } } | Setup one or more specified loggers to be non additive and to print to System . out which will be caught by the Main Process and written to sonar . log . |
9,975 | public String content ( ) { try ( ResponseBody body = okResponse . body ( ) ) { return body . string ( ) ; } catch ( IOException e ) { throw fail ( e ) ; } } | Get body content as a String . This response will be automatically closed . |
9,976 | public String getDefaultMessage ( ) { String defaultMessage = getFieldValue ( DEFAULT_MESSAGE_KEY ) ; if ( defaultMessage == null ) { defaultMessage = this . toString ( ) ; } return defaultMessage ; } | Returns the default message to display for this notification . |
9,977 | private Long computeExecutionTimeMs ( CeQueueDto dto ) { Long startedAt = dto . getStartedAt ( ) ; if ( startedAt == null ) { return null ; } return system2 . now ( ) - startedAt ; } | now - startedAt |
9,978 | private void generateAuthenticationEvent ( HttpServletRequest request , HttpServletResponse response ) { try { Optional < JwtHttpHandler . Token > token = jwtHttpHandler . getToken ( request , response ) ; String userLogin = token . isPresent ( ) ? token . get ( ) . getUserDto ( ) . getLogin ( ) : null ; authenticationEvent . logoutSuccess ( request , userLogin ) ; } catch ( AuthenticationException e ) { authenticationEvent . logoutFailure ( request , e . getMessage ( ) ) ; } } | The generation of the authentication event should not prevent the removal of JWT cookie that s why it s done in a separate method |
9,979 | public String format ( Locale locale , Duration duration , DurationFormat format ) { return format ( duration ) ; } | Return the formatted work duration . |
9,980 | public T add ( String str ) { requireNonNull ( str , JVM_OPTION_NOT_NULL_ERROR_MESSAGE ) ; String value = str . trim ( ) ; if ( isInvalidOption ( value ) ) { throw new IllegalArgumentException ( "a JVM option can't be empty and must start with '-'" ) ; } checkMandatoryOptionOverwrite ( value ) ; options . add ( value ) ; return castThis ( ) ; } | Add an option . Argument is trimmed before being added . |
9,981 | public static Date parseDate ( String s ) { return Date . from ( parseLocalDate ( s ) . atStartOfDay ( ZoneId . systemDefault ( ) ) . toInstant ( ) ) ; } | Return a date at the start of day . |
9,982 | public static Date addDays ( Date date , int numberOfDays ) { return Date . from ( date . toInstant ( ) . plus ( numberOfDays , ChronoUnit . DAYS ) ) ; } | Adds a number of days to a date returning a new object . The original date object is unchanged . |
9,983 | private static SSLSocketFactory createSocketFactory ( Ssl context ) { try { return context . newFactory ( new AlwaysTrustManager ( ) ) ; } catch ( Exception e ) { throw new IllegalStateException ( "Fail to build SSL factory" , e ) ; } } | Trust all certificates |
9,984 | private static HostnameVerifier createHostnameVerifier ( ) { return new HostnameVerifier ( ) { public boolean verify ( String hostname , SSLSession session ) { return true ; } } ; } | Trust all hosts |
9,985 | public List < ComponentDto > selectByKeysAndBranches ( DbSession session , Map < String , String > branchesByKey ) { Set < String > dbKeys = branchesByKey . entrySet ( ) . stream ( ) . map ( entry -> generateBranchKey ( entry . getKey ( ) , entry . getValue ( ) ) ) . collect ( toSet ( ) ) ; return selectByDbKeys ( session , dbKeys ) ; } | Return list of components that will will mix main and branch components . Please note that a project can only appear once in the list it s not possible to ask for many branches on same project with this method . |
9,986 | public List < ComponentDto > selectAncestors ( DbSession dbSession , ComponentDto component ) { if ( component . isRoot ( ) ) { return Collections . emptyList ( ) ; } List < String > ancestorUuids = component . getUuidPathAsList ( ) ; List < ComponentDto > ancestors = selectByUuids ( dbSession , ancestorUuids ) ; return Ordering . explicit ( ancestorUuids ) . onResultOf ( ComponentDto :: uuid ) . immutableSortedCopy ( ancestors ) ; } | List of ancestors ordered from root to parent . The list is empty if the component is a tree root . Disabled components are excluded by design as tree represents the more recent analysis . |
9,987 | void selectChild ( QProfileDto to ) { checkState ( ! to . isBuiltIn ( ) ) ; QProfileDto qp = requireNonNull ( this . profilesByUuid . get ( to . getKee ( ) ) , ( ) -> "No profile with uuid " + to . getKee ( ) ) ; RulesProfileDto ruleProfile = RulesProfileDto . from ( qp ) ; doSwitch ( ruleProfile , getRule ( ) . get ( ) . getId ( ) ) ; } | Moves cursor to a child profile |
9,988 | public static < T > Collector < T , ? , T > toOneElement ( ) { return java . util . stream . Collectors . collectingAndThen ( java . util . stream . Collectors . toList ( ) , list -> { if ( list . size ( ) != 1 ) { throw new IllegalStateException ( "Stream should have only one element" ) ; } return list . get ( 0 ) ; } ) ; } | For stream of one expected element return the element |
9,989 | private static void putLong ( byte [ ] array , long l , int pos , int numberOfLongBytes ) { for ( int i = 0 ; i < numberOfLongBytes ; ++ i ) { array [ pos + numberOfLongBytes - i - 1 ] = ( byte ) ( l >>> ( i * 8 ) ) ; } } | Puts the lower numberOfLongBytes from l into the array starting index pos . |
9,990 | public String getOrCreateForKey ( String key ) { return uuidsByKey . computeIfAbsent ( key , k -> Uuids . create ( ) ) ; } | Get UUID from database if it exists otherwise generate a new one . |
9,991 | private Map < String , String > collectModuleSpecificProps ( DefaultInputModule module ) { Map < String , String > moduleSpecificProps = new HashMap < > ( ) ; AbstractProjectOrModule parent = hierarchy . parent ( module ) ; if ( parent == null ) { moduleSpecificProps . putAll ( module . properties ( ) ) ; } else { Map < String , String > parentProps = parent . properties ( ) ; for ( Map . Entry < String , String > entry : module . properties ( ) . entrySet ( ) ) { if ( ! parentProps . containsKey ( entry . getKey ( ) ) || ! parentProps . get ( entry . getKey ( ) ) . equals ( entry . getValue ( ) ) ) { moduleSpecificProps . put ( entry . getKey ( ) , entry . getValue ( ) ) ; } } } return moduleSpecificProps ; } | Only keep props that are not in parent |
9,992 | private Multimap < String , PropertyDto > loadComponentSettings ( DbSession dbSession , Optional < String > key , ComponentDto component ) { List < String > componentUuids = DOT_SPLITTER . splitToList ( component . moduleUuidPath ( ) ) ; List < ComponentDto > componentDtos = dbClient . componentDao ( ) . selectByUuids ( dbSession , componentUuids ) ; Set < Long > componentIds = componentDtos . stream ( ) . map ( ComponentDto :: getId ) . collect ( Collectors . toSet ( ) ) ; Map < Long , String > uuidsById = componentDtos . stream ( ) . collect ( Collectors . toMap ( ComponentDto :: getId , ComponentDto :: uuid ) ) ; List < PropertyDto > properties = key . isPresent ( ) ? dbClient . propertiesDao ( ) . selectPropertiesByKeysAndComponentIds ( dbSession , Collections . singleton ( key . get ( ) ) , componentIds ) : dbClient . propertiesDao ( ) . selectPropertiesByComponentIds ( dbSession , componentIds ) ; Multimap < String , PropertyDto > propertyDtosByUuid = TreeMultimap . create ( Ordering . explicit ( componentUuids ) , Ordering . arbitrary ( ) ) ; for ( PropertyDto propertyDto : properties ) { Long componentId = propertyDto . getResourceId ( ) ; String componentUuid = uuidsById . get ( componentId ) ; propertyDtosByUuid . put ( componentUuid , propertyDto ) ; } return propertyDtosByUuid ; } | Return list of propertyDto by component uuid sorted from project to lowest module |
9,993 | static List < ProjectDefinition > getTopDownParentProjects ( ProjectDefinition project ) { List < ProjectDefinition > result = new ArrayList < > ( ) ; ProjectDefinition p = project ; while ( p != null ) { result . add ( 0 , p ) ; p = p . getParent ( ) ; } return result ; } | From root to given project |
9,994 | AddIfStartupLeader addIfStartupLeader ( Object ... objects ) { if ( addIfStartupLeader == null ) { this . addIfStartupLeader = new AddIfStartupLeader ( getWebServer ( ) . isStartupLeader ( ) ) ; } addIfStartupLeader . ifAdd ( objects ) ; return addIfStartupLeader ; } | Add a component to container only if the web server is startup leader . |
9,995 | AddIfCluster addIfCluster ( Object ... objects ) { if ( addIfCluster == null ) { addIfCluster = new AddIfCluster ( ! getWebServer ( ) . isStandalone ( ) ) ; } addIfCluster . ifAdd ( objects ) ; return addIfCluster ; } | Add a component to container only if clustering is enabled . |
9,996 | AddIfStandalone addIfStandalone ( Object ... objects ) { if ( addIfStandalone == null ) { addIfStandalone = new AddIfStandalone ( getWebServer ( ) . isStandalone ( ) ) ; } addIfStandalone . ifAdd ( objects ) ; return addIfStandalone ; } | Add a component to container only if this is a standalone instance without clustering . |
9,997 | private static Map < String , String > mandatoryOptions ( System2 system2 , EsInstallation esInstallation ) { Map < String , String > res = new LinkedHashMap < > ( 16 ) ; res . put ( "-XX:+UseConcMarkSweepGC" , "" ) ; res . put ( "-XX:CMSInitiatingOccupancyFraction=" , "75" ) ; res . put ( "-XX:+UseCMSInitiatingOccupancyOnly" , "" ) ; res . put ( "-Des.networkaddress.cache.ttl=" , "60" ) ; res . put ( "-Des.networkaddress.cache.negative.ttl=" , "10" ) ; res . put ( "-XX:+AlwaysPreTouch" , "" ) ; res . put ( "-Xss1m" , "" ) ; res . put ( "-Djava.awt.headless=" , "true" ) ; res . put ( "-Dfile.encoding=" , "UTF-8" ) ; res . put ( "-Djna.nosys=" , "true" ) ; res . put ( "-XX:-OmitStackTraceInFastThrow" , "" ) ; res . put ( "-Dio.netty.noUnsafe=" , "true" ) ; res . put ( "-Dio.netty.noKeySetOptimization=" , "true" ) ; res . put ( "-Dio.netty.recycler.maxCapacityPerThread=" , "0" ) ; res . put ( "-Dlog4j.shutdownHookEnabled=" , "false" ) ; res . put ( "-Dlog4j2.disable.jmx=" , "true" ) ; res . put ( "-Djava.io.tmpdir=" , esInstallation . getTmpDirectory ( ) . getAbsolutePath ( ) ) ; res . put ( "-XX:ErrorFile=" , new File ( esInstallation . getLogDirectory ( ) , "es_hs_err_pid%p.log" ) . getAbsolutePath ( ) ) ; if ( system2 . isJava9 ( ) ) { res . put ( "-Djava.locale.providers=" , "COMPAT" ) ; } if ( system2 . isJava10 ( ) ) { res . put ( "-XX:UseAVX=" , "2" ) ; } return res ; } | with some changes to fit running bundled in SQ |
9,998 | public final void close ( ) { try { doClose ( ) ; isClosed = true ; } catch ( Exception e ) { Throwables . propagate ( e ) ; } } | Do not declare throws IOException |
9,999 | public Block first ( String resourceId ) { for ( Block block : blocks ) { if ( resourceId . equals ( block . getResourceId ( ) ) ) { return block ; } } return null ; } | First block from this group with specified resource id . |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.