idx int64 0 41.2k | question stringlengths 73 5.81k | target stringlengths 5 918 |
|---|---|---|
22,900 | private Map < String , PipelineCommit > findCommitsForStage ( Dashboard dashboard , Pipeline pipeline , PipelineStage stage ) { Map < String , PipelineCommit > commitMap = new HashMap < > ( ) ; String psuedoEnvironmentName = PipelineStage . COMMIT . equals ( stage ) || PipelineStage . BUILD . equals ( stage ) ? stage . getName ( ) : PipelineUtils . getStageToEnvironmentNameMap ( dashboard ) . get ( stage ) ; if ( psuedoEnvironmentName != null ) { commitMap = pipeline . getCommitsByEnvironmentName ( psuedoEnvironmentName ) ; } return commitMap ; } | Gets all commits for a given pipeline stage taking into account the mappings for environment stages |
22,901 | public List < PipelineResponseCommit > findNotPropagatedCommits ( Dashboard dashboard , Pipeline pipeline , PipelineStage stage , List < PipelineStage > pipelineStageList ) { Map < String , PipelineCommit > startingStage = findCommitsForStage ( dashboard , pipeline , stage ) ; List < PipelineResponseCommit > notPropagatedCommits = new ArrayList < > ( ) ; for ( Map . Entry < String , PipelineCommit > entry : startingStage . entrySet ( ) ) { PipelineResponseCommit commit = applyStageTimestamps ( new PipelineResponseCommit ( ( PipelineCommit ) entry . getValue ( ) ) , dashboard , pipeline , pipelineStageList ) ; notPropagatedCommits . add ( commit ) ; } return notPropagatedCommits ; } | get the commits for a given stage by finding which commits havent passed to a later stage |
22,902 | protected List < AuditResult > getAuditResults ( Iterable < Dashboard > dashboards ) { int numberOfAuditDays = settings . getDays ( ) ; long auditBeginDateTimeStamp = Instant . now ( ) . minus ( Duration . ofDays ( numberOfAuditDays ) ) . toEpochMilli ( ) ; long auditEndDateTimeStamp = Instant . now ( ) . toEpochMilli ( ) ; LOGGER . info ( "NFRR Audit Collector audits with begin,end timestamps as " + auditBeginDateTimeStamp + "," + auditEndDateTimeStamp ) ; dashboards . forEach ( ( Dashboard dashboard ) -> { Map < AuditType , Audit > auditMap = AuditCollectorUtil . getAudit ( dashboard , settings , auditBeginDateTimeStamp , auditEndDateTimeStamp ) ; LOGGER . info ( "NFRR Audit Collector adding audit results for the dashboard : " + dashboard . getTitle ( ) ) ; AuditCollectorUtil . addAuditResultByAuditType ( dashboard , auditMap , cmdbRepository , auditEndDateTimeStamp ) ; } ) ; return AuditCollectorUtil . getAuditResults ( ) ; } | Get audit statuses for the dashboards |
22,903 | public void collect ( AWSCloudCollector collector ) { log ( "Starting AWS collection..." ) ; log ( "Collecting AWS Cloud Data..." ) ; Map < String , List < CloudInstance > > accountToInstanceMap = collectInstances ( ) ; Map < String , String > instanceToAccountMap = new HashMap < > ( ) ; for ( String account : accountToInstanceMap . keySet ( ) ) { Collection < CloudInstance > instanceList = accountToInstanceMap . get ( account ) ; for ( CloudInstance ci : instanceList ) { instanceToAccountMap . put ( ci . getInstanceId ( ) , account ) ; } } collectVolume ( instanceToAccountMap ) ; log ( "Finished Cloud collection." ) ; } | The collection action . This is the task which will run on a schedule to gather data from the feature content source system and update the repository with retrieved . |
22,904 | private BuildAuditResponse getBuildJobAuditResponse ( CollectorItem buildItem , long beginDate , long endDate , List < CollectorItem > repoItems ) { BuildAuditResponse buildAuditResponse = new BuildAuditResponse ( ) ; List < CollectorItemConfigHistory > jobConfigHists = collItemConfigHistoryRepository . findByCollectorItemIdAndTimestampIsBetweenOrderByTimestampDesc ( buildItem . getId ( ) , beginDate - 1 , endDate + 1 ) ; buildAuditResponse . setConfigHistory ( jobConfigHists ) ; if ( ! CollectionUtils . isEmpty ( repoItems ) ) { Build build = buildRepository . findTop1ByCollectorItemIdOrderByTimestampDesc ( buildItem . getId ( ) ) ; if ( build != null ) { List < RepoBranch > repoBranches = build . getCodeRepos ( ) ; List < ParsedRepo > codeRepos = repoItems . stream ( ) . map ( r -> new ParsedRepo ( ( String ) r . getOptions ( ) . get ( "url" ) , ( String ) r . getOptions ( ) . get ( "branch" ) ) ) . collect ( Collectors . toList ( ) ) ; List < ParsedRepo > buildRepos = repoBranches . stream ( ) . map ( b -> new ParsedRepo ( b . getUrl ( ) , b . getBranch ( ) ) ) . collect ( Collectors . toList ( ) ) ; List < ParsedRepo > intersection = codeRepos . stream ( ) . filter ( buildRepos :: contains ) . collect ( Collectors . toList ( ) ) ; buildAuditResponse . addAuditStatus ( CollectionUtils . isEmpty ( intersection ) ? BuildAuditStatus . BUILD_REPO_MISMATCH : BuildAuditStatus . BUILD_MATCHES_REPO ) ; } else { buildAuditResponse . addAuditStatus ( BuildAuditStatus . NO_BUILD_FOUND ) ; } } Set < String > codeAuthors = CommonCodeReview . getCodeAuthors ( repoItems , beginDate , endDate , commitRepository ) ; List < String > overlap = jobConfigHists . stream ( ) . map ( CollectorItemConfigHistory :: getUserID ) . filter ( codeAuthors :: contains ) . collect ( Collectors . toList ( ) ) ; buildAuditResponse . addAuditStatus ( ! CollectionUtils . isEmpty ( overlap ) ? BuildAuditStatus . BUILD_AUTHOR_EQ_REPO_AUTHOR : BuildAuditStatus . BUILD_AUTHOR_NE_REPO_AUTHOR ) ; return buildAuditResponse ; } | Calculates Audit Response for a given dashboard |
22,905 | public static AWSCloudCollector prototype ( ) { AWSCloudCollector protoType = new AWSCloudCollector ( ) ; protoType . setName ( "AWSCloud" ) ; protoType . setOnline ( true ) ; protoType . setEnabled ( true ) ; protoType . setCollectorType ( CollectorType . Cloud ) ; protoType . setLastExecuted ( System . currentTimeMillis ( ) ) ; return protoType ; } | Creates a static prototype of the Cloud Collector which includes any specific settings or configuration required for the use of this collector including settings for connecting to any source systems . |
22,906 | @ RequestMapping ( value = "/feature/estimates/aggregatedsprints" , method = GET , produces = APPLICATION_JSON_VALUE ) public DataResponse < SprintEstimate > featureAggregatedSprintEstimates ( @ RequestParam ( value = "projectId" , required = true ) String projectId , @ RequestParam ( value = "agileType" , required = false ) Optional < String > agileType , @ RequestParam ( value = "estimateMetricType" , required = false ) Optional < String > estimateMetricType , @ RequestParam ( value = "component" , required = true ) String cId , @ RequestParam ( value = "teamId" , required = true ) String teamId ) { ObjectId componentId = new ObjectId ( cId ) ; return this . featureService . getAggregatedSprintEstimates ( componentId , teamId , projectId , agileType , estimateMetricType ) ; } | REST endpoint for retrieving the current sprint estimates for a team |
22,907 | public Collection < CodeReviewAuditResponse > getPeerReviewResponses ( String repoUrl , String repoBranch , String scmName , long beginDt , long endDt ) { Collector githubCollector = collectorRepository . findByName ( ! StringUtils . isEmpty ( scmName ) ? scmName : "GitHub" ) ; CollectorItem collectorItem = collectorItemRepository . findRepoByUrlAndBranch ( githubCollector . getId ( ) , repoUrl , repoBranch , true ) ; List < CollectorItem > filteredCollectorItemList = new ArrayList < > ( ) ; if ( ( collectorItem != null ) && ( collectorItem . isPushed ( ) ) ) { List < ObjectId > collectorIdList = new ArrayList < > ( ) ; collectorIdList . add ( githubCollector . getId ( ) ) ; Iterable < CollectorItem > collectorItemIterable = collectorItemRepository . findAllByOptionNameValueAndCollectorIdsIn ( REPO_URL , repoUrl , collectorIdList ) ; for ( CollectorItem ci : collectorItemIterable ) { if ( repoBranch . equalsIgnoreCase ( ( String ) ci . getOptions ( ) . get ( BRANCH ) ) ) { continue ; } filteredCollectorItemList . add ( ci ) ; } return codeReviewEvaluatorLegacy . evaluate ( collectorItem , filteredCollectorItemList , beginDt , endDt , null ) ; } return codeReviewEvaluatorLegacy . evaluate ( collectorItem , beginDt , endDt , null ) ; } | Calculates peer review response |
22,908 | public boolean isUserValid ( String userId , AuthType authType ) { if ( userInfoRepository . findByUsernameAndAuthType ( userId , authType ) != null ) { return true ; } else { if ( authType == AuthType . LDAP ) { try { return searchLdapUser ( userId ) ; } catch ( NamingException ne ) { LOGGER . error ( "Failed to query ldap for " + userId , ne ) ; return false ; } } else { return false ; } } } | Can be called to check validity of userId when creating a dashboard remotely via api |
22,909 | private List < Owner > getOwners ( DashboardRemoteRequest request ) throws HygieiaException { DashboardRemoteRequest . DashboardMetaData metaData = request . getMetaData ( ) ; Owner owner = metaData . getOwner ( ) ; List < Owner > owners = metaData . getOwners ( ) ; if ( owner == null && CollectionUtils . isEmpty ( owners ) ) { throw new HygieiaException ( "There are no owner/owners field in the request" , HygieiaException . INVALID_CONFIGURATION ) ; } if ( owners == null ) { owners = new ArrayList < Owner > ( ) ; owners . add ( owner ) ; } else if ( owner != null ) { owners . add ( owner ) ; } Set < Owner > uniqueOwners = new HashSet < Owner > ( owners ) ; return new ArrayList < Owner > ( uniqueOwners ) ; } | Creates a list of unique owners from the owner and owners requests |
22,910 | private Map < String , WidgetRequest > generateRequestWidgetList ( List < DashboardRemoteRequest . Entry > entries , Dashboard dashboard ) throws HygieiaException { Map < String , WidgetRequest > allWidgetRequests = new HashMap < > ( ) ; for ( DashboardRemoteRequest . Entry entry : entries ) { List < Collector > collectors = collectorRepository . findByCollectorTypeAndName ( entry . getType ( ) , entry . getToolName ( ) ) ; if ( CollectionUtils . isEmpty ( collectors ) ) { throw new HygieiaException ( entry . getToolName ( ) + " collector is not available." , HygieiaException . BAD_DATA ) ; } Collector collector = collectors . get ( 0 ) ; WidgetRequest widgetRequest = allWidgetRequests . get ( entry . getWidgetName ( ) ) ; if ( widgetRequest == null ) { widgetRequest = entryToWidgetRequest ( dashboard , entry , collector ) ; allWidgetRequests . put ( entry . getWidgetName ( ) , widgetRequest ) ; } else { CollectorItem item = entryToCollectorItem ( entry , collector ) ; if ( item != null ) { widgetRequest . getCollectorItemIds ( ) . add ( item . getId ( ) ) ; } } } return allWidgetRequests ; } | Generates a Widget Request list of Widgets to be created from the request |
22,911 | private List < Dashboard > findExistingDashboardsFromRequest ( DashboardRemoteRequest request ) { String businessService = request . getMetaData ( ) . getBusinessService ( ) ; String businessApplication = request . getMetaData ( ) . getBusinessApplication ( ) ; if ( ! StringUtils . isEmpty ( businessService ) && ! StringUtils . isEmpty ( businessApplication ) ) { return dashboardRepository . findAllByConfigurationItemBusServNameContainingIgnoreCaseAndConfigurationItemBusAppNameContainingIgnoreCase ( businessService , businessApplication ) ; } else { return dashboardRepository . findByTitle ( request . getMetaData ( ) . getTitle ( ) ) ; } } | Takes a DashboardRemoteRequest . If the request contains a Business Service and Business Application then returns dashboard . Otherwise Checks dashboards for existing Title and returns dashboards . |
22,912 | private WidgetRequest entryToWidgetRequest ( Dashboard dashboard , DashboardRemoteRequest . Entry entry , Collector collector ) throws HygieiaException { WidgetRequest request = new WidgetRequest ( ) ; CollectorItem item = entryToCollectorItem ( entry , collector ) ; if ( item != null ) { request . setName ( entry . getWidgetName ( ) ) ; request . setComponentId ( dashboard . getApplication ( ) . getComponents ( ) . get ( 0 ) . getId ( ) ) ; request . setOptions ( entry . toWidgetOptions ( ) ) ; List < ObjectId > ids = new ArrayList < > ( ) ; ids . add ( item . getId ( ) ) ; request . setCollectorItemIds ( ids ) ; } return request ; } | Creates a widget from entry |
22,913 | private Dashboard requestToDashboard ( DashboardRemoteRequest request ) throws HygieiaException { DashboardRemoteRequest . DashboardMetaData metaData = request . getMetaData ( ) ; Application application = new Application ( metaData . getApplicationName ( ) , new Component ( metaData . getComponentName ( ) ) ) ; String appName = null ; String serviceName = null ; if ( ! StringUtils . isEmpty ( metaData . getBusinessApplication ( ) ) ) { Cmdb app = cmdbRepository . findByConfigurationItemAndItemType ( metaData . getBusinessApplication ( ) , "component" ) ; if ( app == null ) throw new HygieiaException ( "Invalid Business Application Name." , HygieiaException . BAD_DATA ) ; appName = app . getConfigurationItem ( ) ; } if ( ! StringUtils . isEmpty ( metaData . getBusinessService ( ) ) ) { Cmdb service = cmdbRepository . findByConfigurationItemAndItemType ( metaData . getBusinessService ( ) , "app" ) ; if ( service == null ) throw new HygieiaException ( "Invalid Business Service Name." , HygieiaException . BAD_DATA ) ; serviceName = service . getConfigurationItem ( ) ; } List < String > activeWidgets = new ArrayList < > ( ) ; return new Dashboard ( true , metaData . getTemplate ( ) , metaData . getTitle ( ) , application , metaData . getOwners ( ) , DashboardType . fromString ( metaData . getType ( ) ) , serviceName , appName , activeWidgets , false , ScoreDisplayType . HEADER ) ; } | Creates a Dashboard object from the request . |
22,914 | private ScoreWeight getDashboardScoreFromWidgets ( List < ScoreWeight > widgetScores ) { if ( null == widgetScores ) { return getDashboardScore ( new ScoreTypeValue ( Constants . ZERO_SCORE ) , widgetScores ) ; } try { return getDashboardScore ( ScoreCalculationUtils . calculateComponentScoreTypeValue ( widgetScores , PropagateType . dashboard ) , widgetScores ) ; } catch ( PropagateScoreException ex ) { ScoreWeight scoreDashboard = new ScoreWeight ( ) ; scoreDashboard . setScore ( ex . getScore ( ) ) ; scoreDashboard . setMessage ( ex . getMessage ( ) ) ; scoreDashboard . setState ( ex . getState ( ) ) ; scoreDashboard . setChildren ( widgetScores ) ; return scoreDashboard ; } } | Calculate dashboard score from widget score settings |
22,915 | private List < ScoreWeight > processWidgetScores ( List < Widget > widgets , ScoreCriteriaSettings scoreCriteriaSettings ) { List < ScoreWeight > scoreWeights = new ArrayList < > ( ) ; Map < String , ScoreComponentSettings > scoreParamSettingsMap = generateWidgetSettings ( scoreCriteriaSettings ) ; Set < String > widgetTypes = scoreParamSettingsMap . keySet ( ) ; if ( widgetTypes . isEmpty ( ) ) { return null ; } for ( String widgetType : widgetTypes ) { ScoreComponentSettings scoreSettings = scoreParamSettingsMap . get ( widgetType ) ; WidgetScore widgetScore = getWidgetScoreByType ( widgetType ) ; ScoreWeight score = widgetScore . processWidgetScore ( getWidgetByName ( widgets , widgetType ) , scoreSettings ) ; LOGGER . info ( "Widget for type: " + widgetType + " score" + score ) ; if ( null != score ) { setWidgetAlert ( score , scoreCriteriaSettings . getComponentAlert ( ) ) ; scoreWeights . add ( score ) ; } } return scoreWeights ; } | Process scores for each widget based on widget settings |
22,916 | private void addSettingsToMap ( Map < String , ScoreComponentSettings > scoreParamSettingsMap , String widgetType , ScoreComponentSettings scoreComponentSettings ) { LOGGER . info ( "addSettingsToMap with widgetType:" + widgetType + " scoreParamSettings:" + scoreComponentSettings ) ; if ( null != scoreComponentSettings ) { scoreParamSettingsMap . put ( widgetType , scoreComponentSettings ) ; } } | Add settings for widget in map if it exists This map is used to calculate score for team |
22,917 | private Map < String , ScoreComponentSettings > generateWidgetSettings ( ScoreCriteriaSettings scoreCriteriaSettings ) { Map < String , ScoreComponentSettings > scoreParamSettingsMap = new HashMap < > ( ) ; addSettingsToMap ( scoreParamSettingsMap , Constants . WIDGET_BUILD , getSettingsIfEnabled ( scoreCriteriaSettings . getBuild ( ) ) ) ; addSettingsToMap ( scoreParamSettingsMap , Constants . WIDGET_DEPLOY , getSettingsIfEnabled ( scoreCriteriaSettings . getDeploy ( ) ) ) ; addSettingsToMap ( scoreParamSettingsMap , Constants . WIDGET_CODE_ANALYSIS , getSettingsIfEnabled ( scoreCriteriaSettings . getQuality ( ) ) ) ; addSettingsToMap ( scoreParamSettingsMap , Constants . WIDGET_GITHUB_SCM , getSettingsIfEnabled ( scoreCriteriaSettings . getScm ( ) ) ) ; return scoreParamSettingsMap ; } | Generate criteria settings for each widget type |
22,918 | private CodeQualityAuditResponse codeQualityDetailsForMissingStatus ( CollectorItem codeQualityCollectorItem ) { CodeQualityAuditResponse detailsMissing = new CodeQualityAuditResponse ( ) ; detailsMissing . addAuditStatus ( CodeQualityAuditStatus . CODE_QUALITY_DETAIL_MISSING ) ; detailsMissing . setLastUpdated ( codeQualityCollectorItem . getLastUpdated ( ) ) ; List < CodeQuality > codeQualities = codeQualityRepository . findByCollectorItemIdOrderByTimestampDesc ( codeQualityCollectorItem . getId ( ) ) ; for ( CodeQuality returnCodeQuality : codeQualities ) { detailsMissing . setUrl ( returnCodeQuality . getUrl ( ) ) ; detailsMissing . setName ( returnCodeQuality . getName ( ) ) ; detailsMissing . setLastExecutionTime ( returnCodeQuality . getTimestamp ( ) ) ; } return detailsMissing ; } | It will return response when codeQuality details not found in given date range . |
22,919 | private void auditStatusWhenQualityGateDetailsFound ( Map condition , CodeQualityAuditResponse codeQualityAuditResponse ) { if ( StringUtils . equalsIgnoreCase ( condition . get ( "metric" ) . toString ( ) , CodeQualityMetricType . BLOCKER_VIOLATIONS . getType ( ) ) ) { codeQualityAuditResponse . addAuditStatus ( CodeQualityAuditStatus . CODE_QUALITY_THRESHOLD_BLOCKER_FOUND ) ; if ( ! StringUtils . equalsIgnoreCase ( condition . get ( "level" ) . toString ( ) , "ERROR" ) ) { codeQualityAuditResponse . addAuditStatus ( CodeQualityAuditStatus . CODE_QUALITY_THRESHOLD_BLOCKER_MET ) ; } } else if ( StringUtils . equalsIgnoreCase ( condition . get ( "metric" ) . toString ( ) , CodeQualityMetricType . CRITICAL_VIOLATIONS . getType ( ) ) ) { codeQualityAuditResponse . addAuditStatus ( CodeQualityAuditStatus . CODE_QUALITY_THRESHOLD_CRITICAL_FOUND ) ; if ( ! StringUtils . equalsIgnoreCase ( condition . get ( "level" ) . toString ( ) , "ERROR" ) ) { codeQualityAuditResponse . addAuditStatus ( CodeQualityAuditStatus . CODE_QUALITY_THRESHOLD_CRITICAL_MET ) ; } } else if ( StringUtils . equalsIgnoreCase ( condition . get ( "metric" ) . toString ( ) , CodeQualityMetricType . UNIT_TEST . getType ( ) ) ) { codeQualityAuditResponse . addAuditStatus ( CodeQualityAuditStatus . CODE_QUALITY_THRESHOLD_UNIT_TEST_FOUND ) ; if ( ! StringUtils . equalsIgnoreCase ( condition . get ( "level" ) . toString ( ) , "ERROR" ) ) { codeQualityAuditResponse . addAuditStatus ( CodeQualityAuditStatus . CODE_QUALITY_THRESHOLD_UNIT_TEST_MET ) ; } } else if ( StringUtils . equalsIgnoreCase ( condition . get ( "metric" ) . toString ( ) , CodeQualityMetricType . NEW_COVERAGE . getType ( ) ) || StringUtils . equalsIgnoreCase ( condition . get ( "metric" ) . toString ( ) , CodeQualityMetricType . COVERAGE . getType ( ) ) ) { codeQualityAuditResponse . addAuditStatus ( CodeQualityAuditStatus . CODE_QUALITY_THRESHOLD_CODE_COVERAGE_FOUND ) ; if ( ! StringUtils . equalsIgnoreCase ( condition . get ( "level" ) . toString ( ) , "ERROR" ) ) { codeQualityAuditResponse . addAuditStatus ( CodeQualityAuditStatus . CODE_QUALITY_THRESHOLD_CODE_COVERAGE_MET ) ; } } } | Sets audit status when code quality gate details are found . Sonar 6 . 7 style data . |
22,920 | private JSONObject getDataFromRestCallPost ( GitHubParsed gitHubParsed , GitHubRepo repo , String password , String personalAccessToken , JSONObject query ) throws MalformedURLException , HygieiaException { ResponseEntity < String > response = makeRestCallPost ( gitHubParsed . getGraphQLUrl ( ) , repo . getUserId ( ) , password , personalAccessToken , query ) ; JSONObject data = ( JSONObject ) parseAsObject ( response ) . get ( "data" ) ; JSONArray errors = getArray ( parseAsObject ( response ) , "errors" ) ; if ( CollectionUtils . isEmpty ( errors ) ) { return data ; } JSONObject error = ( JSONObject ) errors . get ( 0 ) ; if ( ! error . containsKey ( "type" ) || ! error . get ( "type" ) . equals ( "NOT_FOUND" ) ) { throw new HygieiaException ( "Error in GraphQL query:" + errors . toJSONString ( ) , HygieiaException . JSON_FORMAT_ERROR ) ; } RedirectedStatus redirectedStatus = checkForRedirectedRepo ( repo ) ; if ( ! redirectedStatus . isRedirected ( ) ) { throw new HygieiaException ( "Error in GraphQL query:" + errors . toJSONString ( ) , HygieiaException . JSON_FORMAT_ERROR ) ; } String redirectedUrl = redirectedStatus . getRedirectedUrl ( ) ; LOG . debug ( "Repo was redirected from: " + repo . getRepoUrl ( ) + " to " + redirectedUrl ) ; repo . setRepoUrl ( redirectedUrl ) ; gitHubParsed . updateForRedirect ( redirectedUrl ) ; JSONParser parser = new JSONParser ( ) ; try { JSONObject variableJSON = ( JSONObject ) parser . parse ( str ( query , "variables" ) ) ; variableJSON . put ( "name" , gitHubParsed . getRepoName ( ) ) ; variableJSON . put ( "owner" , gitHubParsed . getOrgName ( ) ) ; query . put ( "variables" , variableJSON . toString ( ) ) ; } catch ( ParseException e ) { LOG . error ( "Could not parse JSON String" , e ) ; } return getDataFromRestCallPost ( gitHubParsed , repo , password , personalAccessToken , query ) ; } | Makes use of the graphQL endpoint will not work for REST api |
22,921 | public ScoreWeight processWidgetScore ( Widget widget , ScoreComponentSettings paramSettings ) { if ( ! Utils . isScoreEnabled ( paramSettings ) ) { return null ; } ScoreWeight scoreWidget = initWidgetScore ( paramSettings ) ; if ( null == widget ) { scoreWidget . setScore ( paramSettings . getCriteria ( ) . getNoWidgetFound ( ) ) ; scoreWidget . setState ( ScoreWeight . ProcessingState . criteria_failed ) ; scoreWidget . setMessage ( Constants . SCORE_ERROR_NO_WIDGET_FOUND ) ; processWidgetScoreChildren ( scoreWidget ) ; return scoreWidget ; } scoreWidget . setRefId ( widget . getId ( ) ) ; try { calculateCategoryScores ( widget , paramSettings , scoreWidget . getChildren ( ) ) ; } catch ( DataNotFoundException ex ) { scoreWidget . setState ( ScoreWeight . ProcessingState . criteria_failed ) ; scoreWidget . setScore ( paramSettings . getCriteria ( ) . getNoDataFound ( ) ) ; scoreWidget . setMessage ( ex . getMessage ( ) ) ; processWidgetScoreChildren ( scoreWidget ) ; return scoreWidget ; } catch ( ThresholdException ex ) { setThresholdFailureWeight ( ex , scoreWidget ) ; processWidgetScoreChildren ( scoreWidget ) ; return scoreWidget ; } LOGGER . debug ( "scoreWidget {}" , scoreWidget ) ; LOGGER . debug ( "scoreWidget.getChildren {}" , scoreWidget . getChildren ( ) ) ; calculateWidgetScore ( scoreWidget ) ; return scoreWidget ; } | Process widget score |
22,922 | public String getMaxChangeDate ( ) { Collector col = featureCollectorRepository . findByName ( FeatureCollectorConstants . VERSIONONE ) ; if ( col == null ) return "" ; if ( StringUtils . isEmpty ( getFeatureSettings ( ) . getDeltaCollectorItemStartDate ( ) ) ) return "" ; List < Team > response = teamRepo . findTopByChangeDateDesc ( col . getId ( ) , getFeatureSettings ( ) . getDeltaCollectorItemStartDate ( ) ) ; if ( ! CollectionUtils . isEmpty ( response ) ) return response . get ( 0 ) . getChangeDate ( ) ; return "" ; } | Retrieves the maximum change date for a given query . |
22,923 | private Double getPercentCoverageForDays ( Iterable < Commit > commits , int days ) { Set < String > dates = new HashSet < > ( ) ; for ( Commit commit : commits ) { dates . add ( Constants . DAY_FORMAT . format ( new Date ( commit . getScmCommitTimestamp ( ) ) ) ) ; } return ( dates . size ( ) / ( double ) days ) * 100 ; } | Calculate percentage of days with commits out of total days |
22,924 | private List < PipelineStage > findUnmappedStages ( Dashboard dashboard , List < PipelineStage > pipelineStageList ) { List < PipelineStage > unmappedStages = new ArrayList < > ( ) ; Map < PipelineStage , String > stageToEnvironmentNameMap = PipelineUtils . getStageToEnvironmentNameMap ( dashboard ) ; for ( PipelineStage systemStage : pipelineStageList ) { if ( PipelineStageType . DEPLOY . equals ( systemStage . getType ( ) ) ) { String mappedName = stageToEnvironmentNameMap . get ( systemStage ) ; if ( mappedName == null || mappedName . isEmpty ( ) ) { unmappedStages . add ( systemStage ) ; } } } return unmappedStages ; } | finds any stages for a dashboard that aren t mapped . |
22,925 | private Map < String , PipelineCommit > getCommitsAfterStage ( PipelineStage stage , Pipeline pipeline , Dashboard dashboard , List < PipelineStage > pipelineStageList , Map < String , String > orderMap ) { Map < String , PipelineCommit > unionOfAllSets = new HashMap < > ( ) ; List < String > list = getKeysByValue ( orderMap , stage . getName ( ) ) ; int ordinal = Integer . parseInt ( list . get ( 0 ) ) ; for ( int systemStageOrdinal = ordinal + 1 ; systemStageOrdinal < pipelineStageList . size ( ) ; ++ systemStageOrdinal ) { PipelineStage systemStage = null ; for ( Map . Entry < String , String > entry : orderMap . entrySet ( ) ) { String stageOrder = entry . getKey ( ) ; String stageName = entry . getValue ( ) ; if ( Integer . parseInt ( stageOrder ) == systemStageOrdinal ) { for ( PipelineStage currentStage : pipelineStageList ) { if ( stageName . equalsIgnoreCase ( currentStage . getName ( ) ) ) { systemStage = currentStage ; } } } } Map < String , PipelineCommit > commits = findCommitsForStage ( dashboard , pipeline , systemStage ) ; unionOfAllSets . putAll ( commits ) ; } return unionOfAllSets ; } | Finds a map of commits for all stages after the current stage |
22,926 | public static String determineArtifactName ( FilePath file , String version ) { String fileName = file . getBaseName ( ) ; if ( "" . equals ( version ) ) return fileName ; int vIndex = fileName . indexOf ( version ) ; if ( vIndex <= 0 ) return fileName ; if ( ( fileName . charAt ( vIndex - 1 ) == '-' ) || ( fileName . charAt ( vIndex - 1 ) == '_' ) ) { vIndex = vIndex - 1 ; } return fileName . substring ( 0 , vIndex ) ; } | Determine the artifact s name . The name excludes the version string and the file extension . |
22,927 | public static AuditCollector prototype ( List < String > servers ) { AuditCollector protoType = new AuditCollector ( ) ; protoType . setName ( "AuditCollector" ) ; protoType . setCollectorType ( CollectorType . Audit ) ; protoType . setOnline ( true ) ; protoType . setEnabled ( true ) ; protoType . auditServers . addAll ( servers ) ; return protoType ; } | Audit Collector Instance built with required config settings |
22,928 | private void processOrphanCommits ( GitHubRepo repo ) { long refTime = Math . min ( System . currentTimeMillis ( ) - gitHubSettings . getCommitPullSyncTime ( ) , gitHubClient . getRepoOffsetTime ( repo ) ) ; List < Commit > orphanCommits = commitRepository . findCommitsByCollectorItemIdAndTimestampAfterAndPullNumberIsNull ( repo . getId ( ) , refTime ) ; List < GitRequest > pulls = gitRequestRepository . findByCollectorItemIdAndMergedAtIsBetween ( repo . getId ( ) , refTime , System . currentTimeMillis ( ) ) ; orphanCommits = CommitPullMatcher . matchCommitToPulls ( orphanCommits , pulls ) ; List < Commit > orphanSaveList = orphanCommits . stream ( ) . filter ( c -> ! StringUtils . isEmpty ( c . getPullNumber ( ) ) ) . collect ( Collectors . toList ( ) ) ; orphanSaveList . forEach ( c -> LOG . info ( "Updating orphan " + c . getScmRevisionNumber ( ) + " " + new DateTime ( c . getScmCommitTimestamp ( ) ) . toString ( "yyyy-MM-dd hh:mm:ss.SSa" ) + " with pull " + c . getPullNumber ( ) ) ) ; commitRepository . save ( orphanSaveList ) ; } | Retrieves a st of previous commits and Pulls and tries to reconnect them |
22,929 | public Set < AppdynamicsApplication > getApplications ( String instanceUrl ) { Set < AppdynamicsApplication > returnSet = new HashSet < > ( ) ; try { String url = joinURL ( instanceUrl , APPLICATION_LIST_PATH ) ; ResponseEntity < String > responseEntity = makeRestCall ( url ) ; String returnJSON = responseEntity . getBody ( ) ; JSONParser parser = new JSONParser ( ) ; try { JSONArray array = ( JSONArray ) parser . parse ( returnJSON ) ; for ( Object entry : array ) { JSONObject jsonEntry = ( JSONObject ) entry ; String appName = getString ( jsonEntry , "name" ) ; String appId = String . valueOf ( getLong ( jsonEntry , "id" ) ) ; String desc = getString ( jsonEntry , "description" ) ; if ( StringUtils . isEmpty ( desc ) ) { desc = appName ; } AppdynamicsApplication app = new AppdynamicsApplication ( ) ; app . setAppID ( appId ) ; app . setAppName ( appName ) ; app . setAppDesc ( desc ) ; app . setDescription ( desc ) ; returnSet . add ( app ) ; } } catch ( ParseException e ) { LOG . error ( "Parsing applications on instance: " + instanceUrl , e ) ; } } catch ( RestClientException rce ) { LOG . error ( "client exception loading applications" , rce ) ; throw rce ; } catch ( MalformedURLException mfe ) { LOG . error ( "malformed url for loading applications" , mfe ) ; } return returnSet ; } | Retrieves a JSON array of all of the applications that are registered in AppDynamics . |
22,930 | public Map < String , Object > getPerformanceMetrics ( AppdynamicsApplication application , String instanceUrl ) { Map < String , Object > metrics = new HashMap < > ( ) ; metrics . putAll ( getOverallMetrics ( application , instanceUrl ) ) ; metrics . putAll ( getCalculatedMetrics ( metrics ) ) ; metrics . putAll ( getHealthMetrics ( application , instanceUrl ) ) ; metrics . putAll ( getViolations ( application , instanceUrl ) ) ; metrics . putAll ( getSeverityMetrics ( application , instanceUrl ) ) ; return metrics ; } | Obtains the relevant data via different appdynamics api calls . |
22,931 | private Map < String , Object > getHealthMetrics ( AppdynamicsApplication application , String instanceUrl ) { long numNodeViolations = 0 ; long numBusinessViolations = 0 ; long numNodes = 0 ; long numBusinessTransactions = 0 ; double nodeHealthPercent = 0.0 ; double businessHealthPercent = 0.0 ; Map < String , Object > healthMetrics = new HashMap < > ( ) ; try { String url = joinURL ( instanceUrl , String . format ( HEALTH_VIOLATIONS_PATH , application . getAppID ( ) ) ) ; ResponseEntity < String > responseEntity = makeRestCall ( url ) ; String returnJSON = responseEntity . getBody ( ) ; JSONParser parser = new JSONParser ( ) ; JSONArray array = ( JSONArray ) parser . parse ( returnJSON ) ; for ( Object entry : array ) { JSONObject jsonEntry = ( JSONObject ) entry ; if ( getString ( jsonEntry , "incidentStatus" ) . equals ( "RESOLVED" ) ) continue ; JSONObject affEntityObj = ( JSONObject ) jsonEntry . get ( "affectedEntityDefinition" ) ; String entityType = getString ( affEntityObj , "entityType" ) ; if ( entityType . equals ( "APPLICATION_COMPONENT_NODE" ) ) { numNodeViolations ++ ; } else if ( entityType . equals ( BUSINESS_TRANSACTION ) ) { numBusinessViolations ++ ; } } url = joinURL ( instanceUrl , String . format ( NODE_LIST_PATH , application . getAppID ( ) ) ) ; responseEntity = makeRestCall ( url ) ; returnJSON = responseEntity . getBody ( ) ; parser = new JSONParser ( ) ; array = ( JSONArray ) parser . parse ( returnJSON ) ; numNodes = array . size ( ) ; url = joinURL ( instanceUrl , String . format ( BUSINESS_TRANSACTION_LIST_PATH , application . getAppID ( ) ) ) ; responseEntity = makeRestCall ( url ) ; returnJSON = responseEntity . getBody ( ) ; parser = new JSONParser ( ) ; array = ( JSONArray ) parser . parse ( returnJSON ) ; numBusinessTransactions = array . size ( ) ; } catch ( MalformedURLException e ) { LOG . error ( "client exception loading applications" , e ) ; } catch ( ParseException e ) { LOG . error ( "client exception loading applications" , e ) ; } if ( numNodes != 0 ) nodeHealthPercent = Math . floor ( 100.0 * ( 1.0 - ( ( double ) ( numNodeViolations ) / ( double ) ( numNodes ) ) ) ) / 100.0 ; healthMetrics . put ( NODE_HEALTH_PECENT , nodeHealthPercent ) ; if ( numBusinessTransactions != 0 ) businessHealthPercent = Math . floor ( 100.0 * ( 1.0 - ( ( double ) ( numBusinessViolations ) / ( double ) ( numBusinessTransactions ) ) ) ) / 100.0 ; healthMetrics . put ( BUSINESS_TRANSACTION_HEALTH , businessHealthPercent ) ; return healthMetrics ; } | Calculates the Node Health Percent and Business Health Percent values |
22,932 | public List < Comment > getComments ( String commentsUrl , GitHubRepo repo ) throws RestClientException { List < Comment > comments = new ArrayList < > ( ) ; String decryptedPassword = decryptString ( repo . getPassword ( ) , settings . getKey ( ) ) ; String personalAccessToken = ( String ) repo . getOptions ( ) . get ( "personalAccessToken" ) ; String decryptedPersonalAccessToken = decryptString ( personalAccessToken , settings . getKey ( ) ) ; boolean lastPage = false ; String queryUrlPage = commentsUrl ; while ( ! lastPage ) { ResponseEntity < String > response = makeRestCall ( queryUrlPage , repo . getUserId ( ) , decryptedPassword , decryptedPersonalAccessToken ) ; JSONArray jsonArray = parseAsArray ( response ) ; for ( Object item : jsonArray ) { JSONObject jsonObject = ( JSONObject ) item ; Comment comment = new Comment ( ) ; JSONObject userJsonObj = ( JSONObject ) jsonObject . get ( "user" ) ; comment . setUser ( ( String ) userJsonObj . get ( "login" ) ) ; long crt = new DateTime ( str ( jsonObject , "created_at" ) ) . getMillis ( ) ; comment . setCreatedAt ( crt ) ; long upd = new DateTime ( str ( jsonObject , "updated_at" ) ) . getMillis ( ) ; comment . setUpdatedAt ( upd ) ; comment . setBody ( str ( jsonObject , "body" ) ) ; comments . add ( comment ) ; } if ( CollectionUtils . isEmpty ( jsonArray ) ) { lastPage = true ; } else { if ( isThisLastPage ( response ) ) { lastPage = true ; } else { lastPage = false ; queryUrlPage = getNextPageUrl ( response ) ; } } } return comments ; } | Get comments from the given comment url |
22,933 | public List < CommitStatus > getCommitStatuses ( String statusUrl , GitHubRepo repo ) throws RestClientException { Map < String , CommitStatus > statuses = new HashMap < > ( ) ; String decryptedPassword = decryptString ( repo . getPassword ( ) , settings . getKey ( ) ) ; String personalAccessToken = ( String ) repo . getOptions ( ) . get ( "personalAccessToken" ) ; String decryptedPersonalAccessToken = decryptString ( personalAccessToken , settings . getKey ( ) ) ; boolean lastPage = false ; String queryUrlPage = statusUrl ; while ( ! lastPage ) { ResponseEntity < String > response = makeRestCall ( queryUrlPage , repo . getUserId ( ) , decryptedPassword , decryptedPersonalAccessToken ) ; JSONArray jsonArray = parseAsArray ( response ) ; for ( Object item : jsonArray ) { JSONObject jsonObject = ( JSONObject ) item ; String context = str ( jsonObject , "context" ) ; if ( ( context != null ) && ! statuses . containsKey ( context ) ) { CommitStatus status = new CommitStatus ( ) ; status . setContext ( context ) ; status . setDescription ( str ( jsonObject , "description" ) ) ; status . setState ( str ( jsonObject , "state" ) ) ; statuses . put ( context , status ) ; } } if ( CollectionUtils . isEmpty ( jsonArray ) ) { lastPage = true ; } else { if ( isThisLastPage ( response ) ) { lastPage = true ; } else { lastPage = false ; queryUrlPage = getNextPageUrl ( response ) ; } } } return new ArrayList < > ( statuses . values ( ) ) ; } | Get commit statuses from the given commit status url Retrieve the most recent status for each unique context . |
22,934 | public List < Review > getReviews ( String reviewsUrl , GitHubRepo repo ) throws RestClientException { List < Review > reviews = new ArrayList < > ( ) ; String decryptedPassword = decryptString ( repo . getPassword ( ) , settings . getKey ( ) ) ; String personalAccessToken = ( String ) repo . getOptions ( ) . get ( "personalAccessToken" ) ; String decryptedPersonalAccessToken = decryptString ( personalAccessToken , settings . getKey ( ) ) ; boolean lastPage = false ; String queryUrlPage = reviewsUrl ; while ( ! lastPage ) { ResponseEntity < String > response = makeRestCall ( queryUrlPage , repo . getUserId ( ) , decryptedPassword , decryptedPersonalAccessToken ) ; JSONArray jsonArray = parseAsArray ( response ) ; for ( Object item : jsonArray ) { JSONObject jsonObject = ( JSONObject ) item ; Review review = new Review ( ) ; review . setState ( str ( jsonObject , "state" ) ) ; review . setBody ( str ( jsonObject , "body" ) ) ; reviews . add ( review ) ; } if ( CollectionUtils . isEmpty ( jsonArray ) ) { lastPage = true ; } else { if ( isThisLastPage ( response ) ) { lastPage = true ; } else { lastPage = false ; queryUrlPage = getNextPageUrl ( response ) ; } } } return reviews ; } | Get reviews from the given reviews url |
22,935 | private boolean isRateLimitReached ( ResponseEntity < String > response ) { HttpHeaders header = response . getHeaders ( ) ; List < String > limit = header . get ( "X-RateLimit-Remaining" ) ; boolean rateLimitReached = CollectionUtils . isEmpty ( limit ) ? false : Integer . valueOf ( limit . get ( 0 ) ) < settings . getRateLimitThreshold ( ) ; if ( rateLimitReached ) { LOG . error ( "Github rate limit reached. Threshold =" + settings . getRateLimitThreshold ( ) + ". Current remaining =" + Integer . valueOf ( limit . get ( 0 ) ) ) ; } return rateLimitReached ; } | Checks rate limit |
22,936 | private static String getTimeForApi ( Date dt ) { Calendar calendar = new GregorianCalendar ( ) ; TimeZone timeZone = calendar . getTimeZone ( ) ; Calendar cal = Calendar . getInstance ( timeZone ) ; cal . setTime ( dt ) ; return String . format ( "%tFT%<tRZ" , cal ) ; } | Format date the way Github api wants |
22,937 | protected String makeSoapCall ( String soapMessageString , HpsmSoapModel hpsmSoapModel ) throws HygieiaException { String requestAction = hpsmSoapModel . getSoapAction ( ) ; String response = "" ; contentType = hpsmSettings . getContentType ( ) ; charset = hpsmSettings . getCharset ( ) ; try { startHttpConnection ( ) ; RequestEntity entity = new StringRequestEntity ( soapMessageString , contentType , charset ) ; post . setRequestEntity ( entity ) ; post . setRequestHeader ( "SOAPAction" , requestAction ) ; httpclient . executeMethod ( post ) ; response = getResponseString ( post . getResponseBodyAsStream ( ) ) ; if ( ! "OK" . equals ( post . getStatusText ( ) ) ) { throw new HygieiaException ( "Soap Request Failure: " + post . getStatusCode ( ) + "|response: " + response , HygieiaException . BAD_DATA ) ; } stopHttpConnection ( ) ; } catch ( IOException e ) { LOG . error ( "Error while trying to make soap call: " + e ) ; } return response ; } | Makes SOAP request for given soap message |
22,938 | protected Document responseToDoc ( String response ) { Document doc = null ; try { DocumentBuilderFactory factory = new DocumentBuilderFactoryImpl ( ) ; DocumentBuilderFactory . newInstance ( ) ; DocumentBuilder builder = factory . newDocumentBuilder ( ) ; ByteArrayInputStream input = new ByteArrayInputStream ( response . getBytes ( "UTF-8" ) ) ; doc = builder . parse ( input ) ; } catch ( ParserConfigurationException e ) { LOG . error ( "ParserConfigurationException" , e ) ; } catch ( UnsupportedEncodingException e ) { LOG . error ( "UnsupportedEncodingException" , e ) ; } catch ( IOException e ) { LOG . error ( "IOException" , e ) ; } catch ( SAXException e ) { LOG . error ( "SAXException" , e ) ; } return doc ; } | Converts String response into document for parsing |
22,939 | public List < Team > getBoards ( ) { int count = 0 ; int startAt = 0 ; boolean isLast = false ; List < Team > result = new ArrayList < > ( ) ; while ( ! isLast ) { String url = featureSettings . getJiraBaseUrl ( ) + ( featureSettings . getJiraBaseUrl ( ) . endsWith ( "/" ) ? "" : "/" ) + BOARD_TEAMS_REST_SUFFIX + "?startAt=" + startAt ; try { ResponseEntity < String > responseEntity = makeRestCall ( url ) ; String responseBody = responseEntity . getBody ( ) ; JSONObject teamsJson = ( JSONObject ) parser . parse ( responseBody ) ; if ( teamsJson != null ) { JSONArray valuesArray = ( JSONArray ) teamsJson . get ( "values" ) ; if ( ! CollectionUtils . isEmpty ( valuesArray ) ) { for ( Object obj : valuesArray ) { JSONObject jo = ( JSONObject ) obj ; String teamId = getString ( jo , "id" ) ; String teamName = getString ( jo , "name" ) ; String teamType = getString ( jo , "type" ) ; Team team = new Team ( teamId , teamName ) ; team . setTeamType ( teamType ) ; team . setChangeDate ( "" ) ; team . setAssetState ( "Active" ) ; team . setIsDeleted ( "False" ) ; result . add ( team ) ; count = count + 1 ; } isLast = ( boolean ) teamsJson . get ( "isLast" ) ; LOGGER . info ( "JIRA Collector collected " + count + " boards" ) ; if ( ! isLast ) { startAt += JIRA_BOARDS_PAGING ; } } else { isLast = true ; } } else { isLast = true ; } } catch ( ParseException pe ) { isLast = true ; LOGGER . error ( "Parser exception when parsing teams" , pe ) ; } catch ( HygieiaException | HttpClientErrorException | HttpServerErrorException e ) { isLast = true ; LOGGER . error ( "Error in calling JIRA API: " + url , e . getMessage ( ) ) ; } } return result ; } | Get a list of Boards . It s saved as Team in Hygieia |
22,940 | public List < Team > getTeams ( ) { List < Team > result = new ArrayList < > ( ) ; try { String url = featureSettings . getJiraBaseUrl ( ) + ( featureSettings . getJiraBaseUrl ( ) . endsWith ( "/" ) ? "" : "/" ) + TEMPO_TEAMS_REST_SUFFIX ; ResponseEntity < String > responseEntity = makeRestCall ( url ) ; String responseBody = responseEntity . getBody ( ) ; JSONArray teamsJson = ( JSONArray ) parser . parse ( responseBody ) ; if ( teamsJson != null ) { for ( Object obj : teamsJson ) { JSONObject jo = ( JSONObject ) obj ; String teamId = getString ( jo , "id" ) ; String teamName = getString ( jo , "name" ) ; Team team = new Team ( teamId , teamName ) ; team . setChangeDate ( "" ) ; team . setTeamType ( "" ) ; team . setAssetState ( "Active" ) ; team . setIsDeleted ( "False" ) ; result . add ( team ) ; } } } catch ( ParseException pe ) { LOGGER . error ( "Parser exception when parsing teams" , pe ) ; } catch ( HygieiaException e ) { LOGGER . error ( "Error in calling JIRA API" , e ) ; } return result ; } | Get all the teams using Jira Rest API |
22,941 | protected static void processEpicData ( Feature feature , Epic epic ) { feature . setsEpicID ( epic . getId ( ) ) ; feature . setsEpicIsDeleted ( "false" ) ; feature . setsEpicName ( epic . getName ( ) ) ; feature . setsEpicNumber ( epic . getNumber ( ) ) ; feature . setsEpicType ( "" ) ; feature . setsEpicAssetState ( epic . getStatus ( ) ) ; feature . setsEpicBeginDate ( epic . getBeginDate ( ) ) ; feature . setsEpicChangeDate ( epic . getChangeDate ( ) ) ; feature . setsEpicEndDate ( epic . getEndDate ( ) ) ; feature . setsEpicUrl ( epic . getUrl ( ) ) ; } | Process Epic data for a feature updating the passed in feature |
22,942 | protected void processSprintData ( Feature feature , Sprint sprint ) { feature . setsSprintChangeDate ( "" ) ; feature . setsSprintIsDeleted ( "False" ) ; feature . setsSprintID ( sprint . getId ( ) ) ; feature . setsSprintName ( sprint . getName ( ) ) ; feature . setsSprintBeginDate ( sprint . getStartDateStr ( ) ) ; feature . setsSprintEndDate ( sprint . getEndDateStr ( ) ) ; feature . setsSprintAssetState ( sprint . getState ( ) ) ; String rapidViewId = sprint . getRapidViewId ( ) ; if ( ! StringUtils . isEmpty ( rapidViewId ) && ! StringUtils . isEmpty ( feature . getsSprintID ( ) ) ) { feature . setsSprintUrl ( featureSettings . getJiraBaseUrl ( ) + ( Objects . equals ( featureSettings . getJiraBaseUrl ( ) . substring ( featureSettings . getJiraBaseUrl ( ) . length ( ) - 1 ) , "/" ) ? "" : "/" ) + "secure/RapidBoard.jspa?rapidView=" + rapidViewId + "&view=reporting&chart=sprintRetrospective&sprint=" + feature . getsSprintID ( ) ) ; } } | Process Sprint data for a feature updating the passed in feature |
22,943 | @ SuppressWarnings ( "PMD.NPathComplexity" ) protected static void processAssigneeData ( Feature feature , JSONObject assignee ) { if ( assignee == null ) { return ; } String key = getString ( assignee , "key" ) ; String name = getString ( assignee , "name" ) ; String displayName = getString ( assignee , "displayName" ) ; feature . setsOwnersID ( key != null ? Collections . singletonList ( key ) : Collections . EMPTY_LIST ) ; feature . setsOwnersUsername ( name != null ? Collections . singletonList ( name ) : Collections . EMPTY_LIST ) ; feature . setsOwnersShortName ( feature . getsOwnersUsername ( ) ) ; feature . setsOwnersFullName ( displayName != null ? Collections . singletonList ( displayName ) : Collections . EMPTY_LIST ) ; } | Process Assignee data for a feature updating the passed in feature |
22,944 | protected static List < FeatureIssueLink > getIssueLinks ( JSONArray issueLinkArray ) { if ( issueLinkArray == null ) { return Collections . EMPTY_LIST ; } List < FeatureIssueLink > jiraIssueLinks = new ArrayList < > ( ) ; issueLinkArray . forEach ( issueLink -> { JSONObject outward = ( JSONObject ) ( ( JSONObject ) issueLink ) . get ( "outwardIssue" ) ; JSONObject inward = ( JSONObject ) ( ( JSONObject ) issueLink ) . get ( "inwardIssue" ) ; JSONObject type = ( JSONObject ) ( ( JSONObject ) issueLink ) . get ( "type" ) ; String targetKey = "" ; String direction = "" ; String name = "" ; String description = "" ; String targetUrl = "" ; if ( outward != null ) { targetKey = getString ( outward , "key" ) ; direction = "OUTBOUND" ; name = getString ( type , "name" ) ; description = getString ( type , "outward" ) ; targetUrl = getString ( outward , "self" ) ; } else if ( inward != null ) { targetKey = getString ( inward , "key" ) ; direction = "INBOUND" ; name = getString ( type , "name" ) ; description = getString ( type , "inward" ) ; targetUrl = getString ( inward , "self" ) ; } FeatureIssueLink jiraIssueLink = new FeatureIssueLink ( ) ; jiraIssueLink . setTargetIssueKey ( targetKey ) ; jiraIssueLink . setIssueLinkName ( name ) ; jiraIssueLink . setIssueLinkType ( description ) ; jiraIssueLink . setIssueLinkDirection ( direction ) ; jiraIssueLink . setTargetIssueUri ( targetUrl ) ; jiraIssueLinks . add ( jiraIssueLink ) ; } ) ; return jiraIssueLinks ; } | Get Array of issuesLinks |
22,945 | public Epic getEpic ( String epicKey , Map < String , Epic > epicMap ) { try { String url = featureSettings . getJiraBaseUrl ( ) + ( featureSettings . getJiraBaseUrl ( ) . endsWith ( "/" ) ? "" : "/" ) + String . format ( EPIC_REST_SUFFIX , epicKey ) ; ResponseEntity < String > responseEntity = makeRestCall ( url ) ; String responseBody = responseEntity . getBody ( ) ; JSONObject issue = ( JSONObject ) parser . parse ( responseBody ) ; if ( issue == null ) { return null ; } return saveEpic ( issue , epicMap , false ) ; } catch ( ParseException pe ) { LOGGER . error ( "Parser exception when parsing teams" , pe ) ; } catch ( HygieiaException e ) { LOGGER . error ( "Error in calling JIRA API" , e ) ; } return null ; } | Get Epic using Jira API |
22,946 | public static boolean checkForServiceAccount ( String userLdapDN , ApiSettings settings , Map < String , String > allowedUsers , String author , List < String > commitFiles , boolean isCommit , AuditReviewResponse auditReviewResponse ) { List < String > serviceAccountOU = settings . getServiceAccountOU ( ) ; boolean isValid = false ; if ( ! MapUtils . isEmpty ( allowedUsers ) && isCommit ) { isValid = isValidServiceAccount ( author , allowedUsers , commitFiles ) ; if ( isValid ) { auditReviewResponse . addAuditStatus ( CodeReviewAuditStatus . DIRECT_COMMIT_CHANGE_WHITELISTED_ACCOUNT ) ; } } if ( ! CollectionUtils . isEmpty ( serviceAccountOU ) && StringUtils . isNotBlank ( userLdapDN ) && ! isValid ) { try { String userLdapDNParsed = LdapUtils . getStringValue ( new LdapName ( userLdapDN ) , "OU" ) ; List < String > matches = serviceAccountOU . stream ( ) . filter ( it -> it . contains ( userLdapDNParsed ) ) . collect ( Collectors . toList ( ) ) ; isValid = CollectionUtils . isNotEmpty ( matches ) ; } catch ( InvalidNameException e ) { LOGGER . error ( "Error parsing LDAP DN:" + userLdapDN ) ; } } else { LOGGER . info ( "API Settings missing service account RDN" ) ; } return isValid ; } | Check if the passed in account is a Service Account or not by comparing against list of valid ServiceAccountOU in ApiSettings . |
22,947 | private static Map < String , String > getActors ( GitRequest pr ) { Map < String , String > actors = new HashMap < > ( ) ; if ( ! StringUtils . isEmpty ( pr . getMergeAuthorLDAPDN ( ) ) ) { actors . put ( pr . getMergeAuthor ( ) , pr . getMergeAuthorLDAPDN ( ) ) ; } Optional . ofNullable ( pr . getCommits ( ) ) . orElse ( Collections . emptyList ( ) ) . stream ( ) . filter ( c -> ! StringUtils . isEmpty ( c . getScmAuthorLDAPDN ( ) ) ) . forEach ( c -> actors . put ( c . getScmAuthor ( ) , c . getScmAuthorLDAPDN ( ) ) ) ; Optional . ofNullable ( pr . getComments ( ) ) . orElse ( Collections . emptyList ( ) ) . stream ( ) . filter ( c -> ! StringUtils . isEmpty ( c . getUserLDAPDN ( ) ) ) . forEach ( c -> actors . put ( c . getUser ( ) , c . getUserLDAPDN ( ) ) ) ; Optional . ofNullable ( pr . getReviews ( ) ) . orElse ( Collections . emptyList ( ) ) . stream ( ) . filter ( r -> ! StringUtils . isEmpty ( r . getAuthorLDAPDN ( ) ) ) . forEach ( r -> actors . put ( r . getAuthor ( ) , r . getAuthorLDAPDN ( ) ) ) ; return actors ; } | Get all the actors associated with this user . s |
22,948 | private static boolean isPRLookedAtByPeer ( GitRequest pr ) { Set < String > commentUsers = pr . getComments ( ) != null ? pr . getComments ( ) . stream ( ) . map ( Comment :: getUser ) . collect ( Collectors . toCollection ( HashSet :: new ) ) : new HashSet < > ( ) ; Set < String > reviewAuthors = pr . getReviews ( ) != null ? pr . getReviews ( ) . stream ( ) . map ( Review :: getAuthor ) . collect ( Collectors . toCollection ( HashSet :: new ) ) : new HashSet < > ( ) ; reviewAuthors . remove ( "unknown" ) ; Set < String > prCommitAuthors = pr . getCommits ( ) != null ? pr . getCommits ( ) . stream ( ) . map ( Commit :: getScmAuthorLogin ) . collect ( Collectors . toCollection ( HashSet :: new ) ) : new HashSet < > ( ) ; prCommitAuthors . add ( pr . getUserId ( ) ) ; prCommitAuthors . remove ( "unknown" ) ; commentUsers . removeAll ( prCommitAuthors ) ; reviewAuthors . removeAll ( prCommitAuthors ) ; return ( commentUsers . size ( ) > 0 ) || ( reviewAuthors . size ( ) > 0 ) ; } | Calculates if the PR was looked at by a peer |
22,949 | public Page < Scope > getScopeByCollectorWithFilter ( ObjectId collectorId , String projectName , Pageable pageable ) { Page < Scope > scopeItems = scopeRepository . findAllByCollectorIdAndNameContainingIgnoreCase ( collectorId , projectName , pageable ) ; return scopeItems ; } | Finds paged results of scope items of a given collectorId projectName pageable |
22,950 | private void processQualityCCScore ( ScoreComponentSettings qualityCCSettings , Iterable < CodeQuality > codeQualityIterable , List < ScoreWeight > categoryScores ) { ScoreWeight qualityCCScore = getCategoryScoreByIdName ( categoryScores , WIDGET_QUALITY_CC_ID_NAME ) ; Double qualityCCRatio = fetchQualityValue ( codeQualityIterable , QUALITY_PARAM_CC ) ; if ( null == qualityCCRatio ) { qualityCCScore . setScore ( qualityCCSettings . getCriteria ( ) . getNoDataFound ( ) ) ; qualityCCScore . setMessage ( Constants . SCORE_ERROR_NO_DATA_FOUND ) ; qualityCCScore . setState ( ScoreWeight . ProcessingState . criteria_failed ) ; } else { try { checkPercentThresholds ( qualityCCSettings , qualityCCRatio ) ; qualityCCScore . setScore ( new ScoreTypeValue ( qualityCCRatio ) ) ; qualityCCScore . setState ( ScoreWeight . ProcessingState . complete ) ; } catch ( ThresholdException ex ) { setThresholdFailureWeight ( ex , qualityCCScore ) ; } } } | Process Code Coverage score |
22,951 | private void processQualityUTScore ( ScoreComponentSettings qualityUTSettings , Iterable < CodeQuality > codeQualityIterable , List < ScoreWeight > categoryScores ) { ScoreWeight qualityUTScore = getCategoryScoreByIdName ( categoryScores , WIDGET_QUALITY_UT_ID_NAME ) ; Double qualityUTRatio = fetchQualityValue ( codeQualityIterable , QUALITY_PARAM_UT ) ; if ( null == qualityUTRatio ) { qualityUTScore . setScore ( qualityUTSettings . getCriteria ( ) . getNoDataFound ( ) ) ; qualityUTScore . setMessage ( Constants . SCORE_ERROR_NO_DATA_FOUND ) ; qualityUTScore . setState ( ScoreWeight . ProcessingState . criteria_failed ) ; } else { try { checkPercentThresholds ( qualityUTSettings , qualityUTRatio ) ; qualityUTScore . setScore ( new ScoreTypeValue ( qualityUTRatio ) ) ; qualityUTScore . setState ( ScoreWeight . ProcessingState . complete ) ; } catch ( ThresholdException ex ) { setThresholdFailureWeight ( ex , qualityUTScore ) ; } } } | Process Unit Tests score |
22,952 | private void processQualityViolationsScore ( QualityScoreSettings . ViolationsScoreSettings qualityViolationsSettings , Iterable < CodeQuality > codeQualityIterable , List < ScoreWeight > categoryScores ) { ScoreWeight qualityViolationsScore = getCategoryScoreByIdName ( categoryScores , WIDGET_QUALITY_VIOLATIONS_ID_NAME ) ; Double qualityBlockerRatio = fetchQualityValue ( codeQualityIterable , QUALITY_PARAM_BLOCKER_VIOLATIONS ) ; Double qualityCriticalRatio = fetchQualityValue ( codeQualityIterable , QUALITY_PARAM_CRITICAL_VIOLATIONS ) ; Double qualityMajorRatio = fetchQualityValue ( codeQualityIterable , QUALITY_PARAM_MAJOR_VIOLATIONS ) ; if ( null == qualityBlockerRatio && null == qualityCriticalRatio && null == qualityMajorRatio ) { qualityViolationsScore . setScore ( qualityViolationsSettings . getCriteria ( ) . getNoDataFound ( ) ) ; qualityViolationsScore . setMessage ( Constants . SCORE_ERROR_NO_DATA_FOUND ) ; qualityViolationsScore . setState ( ScoreWeight . ProcessingState . criteria_failed ) ; } else { try { Double violationScore = Double . valueOf ( Constants . MAX_SCORE ) - ( getViolationScore ( qualityBlockerRatio , qualityViolationsSettings . getBlockerViolationsWeight ( ) ) + getViolationScore ( qualityCriticalRatio , qualityViolationsSettings . getCriticalViolationsWeight ( ) ) + getViolationScore ( qualityMajorRatio , qualityViolationsSettings . getMajorViolationWeight ( ) ) ) ; if ( ! qualityViolationsSettings . isAllowNegative ( ) && violationScore . compareTo ( Constants . ZERO_SCORE ) < 0 ) { violationScore = Constants . ZERO_SCORE ; } checkPercentThresholds ( qualityViolationsSettings , violationScore ) ; qualityViolationsScore . setScore ( new ScoreTypeValue ( violationScore ) ) ; qualityViolationsScore . setState ( ScoreWeight . ProcessingState . complete ) ; } catch ( ThresholdException ex ) { setThresholdFailureWeight ( ex , qualityViolationsScore ) ; } } } | Calculate Violations score based on Blocker Critical & Major violations |
22,953 | private Double fetchQualityValue ( Iterable < CodeQuality > qualityIterable , String param ) { Double paramValue = null ; Iterator < CodeQuality > qualityIterator = qualityIterable . iterator ( ) ; if ( ! qualityIterator . hasNext ( ) ) { return paramValue ; } CodeQuality codeQuality = qualityIterator . next ( ) ; for ( CodeQualityMetric codeQualityMetric : codeQuality . getMetrics ( ) ) { if ( codeQualityMetric . getName ( ) . equals ( param ) ) { paramValue = Double . valueOf ( codeQualityMetric . getValue ( ) ) ; break ; } } return paramValue ; } | Fetch param value by param name from quality values |
22,954 | @ RequestMapping ( value = "/cloud/instance/refresh" , method = POST , consumes = APPLICATION_JSON_VALUE , produces = APPLICATION_JSON_VALUE ) public ResponseEntity < Collection < String > > refreshInstances ( @ RequestBody ( required = false ) CloudInstanceListRefreshRequest request ) { return ResponseEntity . ok ( ) . body ( cloudInstanceService . refreshInstances ( request ) ) ; } | Cloud Instance Endpoints |
22,955 | public final void generateDashboardScoreSettings ( ) { ScoreCriteriaSettings dashboardScoreCriteriaSettings = new ScoreCriteriaSettings ( ) ; dashboardScoreCriteriaSettings . setMaxScore ( this . scoreSettings . getMaxScore ( ) ) ; dashboardScoreCriteriaSettings . setType ( ScoreValueType . DASHBOARD ) ; dashboardScoreCriteriaSettings . setComponentAlert ( ComponentAlert . cloneComponentAlert ( this . scoreSettings . getComponentAlert ( ) ) ) ; dashboardScoreCriteriaSettings . setBuild ( BuildScoreSettings . cloneBuildScoreSettings ( this . scoreSettings . getBuildWidget ( ) ) ) ; dashboardScoreCriteriaSettings . setDeploy ( DeployScoreSettings . cloneDeployScoreSettings ( this . scoreSettings . getDeployWidget ( ) ) ) ; dashboardScoreCriteriaSettings . setQuality ( QualityScoreSettings . cloneQualityScoreSettings ( this . scoreSettings . getQualityWidget ( ) ) ) ; dashboardScoreCriteriaSettings . setScm ( ScmScoreSettings . cloneScmScoreSettings ( this . scoreSettings . getScmWidget ( ) ) ) ; LOGGER . debug ( "Generate Score Dashboard Settings dashboardScoreCriteriaSettings {}" , dashboardScoreCriteriaSettings ) ; this . dashboardScoreCriteriaSettings = dashboardScoreCriteriaSettings ; } | Generate Score Criteria Settings from Score Settings |
22,956 | private void initBuildScoreChildrenSettings ( BuildScoreSettings buildScoreSettings ) { ScoreComponentSettings buildStatusSettings = Utils . getInstanceIfNull ( buildScoreSettings . getStatus ( ) , ScoreComponentSettings . class ) ; buildStatusSettings . setCriteria ( Utils . mergeCriteria ( buildScoreSettings . getCriteria ( ) , buildStatusSettings . getCriteria ( ) ) ) ; buildScoreSettings . setStatus ( buildStatusSettings ) ; BuildScoreSettings . BuildDurationScoreSettings buildDurationSettings = Utils . getInstanceIfNull ( buildScoreSettings . getDuration ( ) , BuildScoreSettings . BuildDurationScoreSettings . class ) ; buildDurationSettings . setCriteria ( Utils . mergeCriteria ( buildScoreSettings . getCriteria ( ) , buildDurationSettings . getCriteria ( ) ) ) ; buildScoreSettings . setDuration ( buildDurationSettings ) ; } | Initialize Settings for child components in build widget 1 . Build Status criteria settings 2 . Build Duration criteria settings |
22,957 | private void initDeployScoreChildrenSettings ( DeployScoreSettings deployScoreSettings ) { ScoreComponentSettings deploySuccessSettings = Utils . getInstanceIfNull ( deployScoreSettings . getDeploySuccess ( ) , ScoreComponentSettings . class ) ; deploySuccessSettings . setCriteria ( Utils . mergeCriteria ( deployScoreSettings . getCriteria ( ) , deploySuccessSettings . getCriteria ( ) ) ) ; deployScoreSettings . setDeploySuccess ( deploySuccessSettings ) ; ScoreComponentSettings instanceOnlineSettings = Utils . getInstanceIfNull ( deployScoreSettings . getIntancesOnline ( ) , ScoreComponentSettings . class ) ; instanceOnlineSettings . setCriteria ( Utils . mergeCriteria ( deployScoreSettings . getCriteria ( ) , instanceOnlineSettings . getCriteria ( ) ) ) ; deployScoreSettings . setIntancesOnline ( instanceOnlineSettings ) ; } | Initialize Settings for child components in deploy widget 1 . Deploys Success criteria settings 2 . Instances Online criteria settings |
22,958 | private void initQualityScoreChildrenSettings ( QualityScoreSettings qualityScoreSettings ) { ScoreComponentSettings qualityCCSettings = Utils . getInstanceIfNull ( qualityScoreSettings . getCodeCoverage ( ) , ScoreComponentSettings . class ) ; qualityCCSettings . setCriteria ( Utils . mergeCriteria ( qualityScoreSettings . getCriteria ( ) , qualityCCSettings . getCriteria ( ) ) ) ; qualityScoreSettings . setCodeCoverage ( qualityCCSettings ) ; ScoreComponentSettings qualityUTSettings = Utils . getInstanceIfNull ( qualityScoreSettings . getUnitTests ( ) , ScoreComponentSettings . class ) ; qualityUTSettings . setCriteria ( Utils . mergeCriteria ( qualityScoreSettings . getCriteria ( ) , qualityUTSettings . getCriteria ( ) ) ) ; qualityScoreSettings . setUnitTests ( qualityUTSettings ) ; QualityScoreSettings . ViolationsScoreSettings violationsSettings = Utils . getInstanceIfNull ( qualityScoreSettings . getViolations ( ) , QualityScoreSettings . ViolationsScoreSettings . class ) ; violationsSettings . setCriteria ( Utils . mergeCriteria ( qualityScoreSettings . getCriteria ( ) , violationsSettings . getCriteria ( ) ) ) ; qualityScoreSettings . setViolations ( violationsSettings ) ; } | Initialize Settings for child components in quality widget 1 . Code Coverage criteria settings 2 . Unit Tests criteria settings 3 . Violations criteria settings |
22,959 | private void initGithubScmScoreChildrenSettings ( ScmScoreSettings scmScoreSettings ) { ScoreComponentSettings commitsPerDaySettings = Utils . getInstanceIfNull ( scmScoreSettings . getCommitsPerDay ( ) , ScoreComponentSettings . class ) ; commitsPerDaySettings . setCriteria ( Utils . mergeCriteria ( scmScoreSettings . getCriteria ( ) , commitsPerDaySettings . getCriteria ( ) ) ) ; scmScoreSettings . setCommitsPerDay ( commitsPerDaySettings ) ; } | Initialize Settings for child components in scm widget 1 . Commits Per Day criteria settings |
22,960 | private Page < CollectorItem > removeJobUrlAndInstanceUrl ( Page < CollectorItem > collectorItems ) { for ( CollectorItem cItem : collectorItems ) { if ( cItem . getOptions ( ) . containsKey ( "jobUrl" ) ) cItem . getOptions ( ) . remove ( "jobUrl" ) ; if ( cItem . getOptions ( ) . containsKey ( "instanceUrl" ) ) cItem . getOptions ( ) . remove ( "instanceUrl" ) ; } return collectorItems ; } | method to remove jobUrl and instanceUrl from build collector items . |
22,961 | public CollectorItem createCollectorItemSelectOptions ( CollectorItem item , Map < String , Object > allOptions , Map < String , Object > uniqueOptions ) { Collector collector = collectorRepository . findOne ( item . getCollectorId ( ) ) ; Map < String , Object > uniqueFieldsFromCollector = collector . getUniqueFields ( ) ; List < CollectorItem > existing = customRepositoryQuery . findCollectorItemsBySubsetOptions ( item . getCollectorId ( ) , allOptions , uniqueOptions , uniqueFieldsFromCollector ) ; if ( ! CollectionUtils . isEmpty ( existing ) ) { CollectorItem existingItem = existing . get ( 0 ) ; existingItem . getOptions ( ) . putAll ( item . getOptions ( ) ) ; return collectorItemRepository . save ( existingItem ) ; } return collectorItemRepository . save ( item ) ; } | just update the new credentials . |
22,962 | public static List < String > toCanonicalList ( List < String > list ) { return list . stream ( ) . map ( BaseClient :: sanitizeResponse ) . collect ( Collectors . toList ( ) ) ; } | Canonicalizes a given JSONArray to a basic List object to avoid the use of JSON parsers . |
22,963 | public Page < Team > getTeamByCollectorWithFilter ( ObjectId collectorId , String teamName , Pageable pageable ) { Page < Team > teams = teamRepository . findAllByCollectorIdAndNameContainingIgnoreCase ( collectorId , teamName , pageable ) ; return teams ; } | Retrieves the team information for a given collectorId teamName pageable |
22,964 | public List < Dashboard > getDashboardsByCollectorItems ( Set < CollectorItem > collectorItems , CollectorType collectorType ) { if ( org . apache . commons . collections4 . CollectionUtils . isEmpty ( collectorItems ) ) { return new ArrayList < > ( ) ; } List < ObjectId > collectorItemIds = collectorItems . stream ( ) . map ( BaseModel :: getId ) . collect ( Collectors . toList ( ) ) ; List < com . capitalone . dashboard . model . Component > components = componentRepository . findByCollectorTypeAndItemIdIn ( collectorType , collectorItemIds ) ; List < ObjectId > componentIds = components . stream ( ) . map ( BaseModel :: getId ) . collect ( Collectors . toList ( ) ) ; return dashboardRepository . findByApplicationComponentIdsIn ( componentIds ) ; } | Get all the dashboards that have the collector items |
22,965 | private void handleCollectorItems ( List < Component > components ) { for ( Component component : components ) { Map < CollectorType , List < CollectorItem > > itemMap = component . getCollectorItems ( ) ; for ( CollectorType type : itemMap . keySet ( ) ) { List < CollectorItem > items = itemMap . get ( type ) ; for ( CollectorItem i : items ) { if ( CollectionUtils . isEmpty ( customRepositoryQuery . findComponents ( i . getCollectorId ( ) , type , i ) ) ) { i . setEnabled ( false ) ; collectorItemRepository . save ( i ) ; } } } } } | For the dashboard get all the components and get all the collector items for the components . If a collector item is NOT associated with any Component disable it . |
22,966 | private void setAppAndComponentNameToDashboard ( Dashboard dashboard , String appName , String compName ) { if ( appName != null && ! "" . equals ( appName ) ) { Cmdb cmdb = cmdbService . configurationItemByConfigurationItem ( appName ) ; if ( cmdb != null ) { dashboard . setConfigurationItemBusServName ( cmdb . getConfigurationItem ( ) ) ; dashboard . setValidServiceName ( cmdb . isValidConfigItem ( ) ) ; } } if ( compName != null && ! "" . equals ( compName ) ) { Cmdb cmdb = cmdbService . configurationItemByConfigurationItem ( compName ) ; if ( cmdb != null ) { dashboard . setConfigurationItemBusAppName ( cmdb . getConfigurationItem ( ) ) ; dashboard . setValidAppName ( cmdb . isValidConfigItem ( ) ) ; } } } | Sets business service business application and valid flag for each to the give Dashboard |
22,967 | private void duplicateDashboardErrorCheck ( Dashboard dashboard ) throws HygieiaException { String appName = dashboard . getConfigurationItemBusServName ( ) ; String compName = dashboard . getConfigurationItemBusAppName ( ) ; if ( appName != null && ! appName . isEmpty ( ) && compName != null && ! compName . isEmpty ( ) ) { Dashboard existingDashboard = dashboardRepository . findByConfigurationItemBusServNameIgnoreCaseAndConfigurationItemBusAppNameIgnoreCase ( appName , compName ) ; if ( existingDashboard != null && ! existingDashboard . getId ( ) . equals ( dashboard . getId ( ) ) ) { throw new HygieiaException ( "Existing Dashboard: " + existingDashboard . getTitle ( ) , HygieiaException . DUPLICATE_DATA ) ; } } } | Takes Dashboard and checks to see if there is an existing Dashboard with the same business service and business application Throws error if found |
22,968 | public Integer getAllDashboardsByTitleCount ( String title , String type ) { List < Dashboard > dashboards = null ; if ( ( type != null ) && ( ! type . isEmpty ( ) ) && ( ! UNDEFINED . equalsIgnoreCase ( type ) ) ) { dashboards = dashboardRepository . findAllByTypeContainingIgnoreCaseAndTitleContainingIgnoreCase ( type , title ) ; } else { dashboards = dashboardRepository . findAllByTitleContainingIgnoreCase ( title ) ; } return dashboards != null ? dashboards . size ( ) : 0 ; } | Get count of all dashboards filtered by title |
22,969 | public long count ( String type ) { if ( ( type != null ) && ( ! type . isEmpty ( ) ) && ( ! UNDEFINED . equalsIgnoreCase ( type ) ) ) { return dashboardRepository . countByTypeContainingIgnoreCase ( type ) ; } else { return dashboardRepository . count ( ) ; } } | Get count of all dashboards use dashboard type if supplied |
22,970 | private void updateRelationship ( CmdbRequest request ) { if ( ! StringUtils . isEmpty ( request . getConfigurationItemBusServName ( ) ) ) { Cmdb busServiceItem = cmdbRepository . findByConfigurationItemAndItemType ( request . getConfigurationItemBusServName ( ) , APP_TYPE ) ; if ( busServiceItem . getComponents ( ) == null ) { List < String > components = new ArrayList < > ( ) ; components . add ( request . getConfigurationItem ( ) ) ; busServiceItem . setComponents ( components ) ; } else { busServiceItem . getComponents ( ) . add ( request . getConfigurationItem ( ) ) ; } cmdbRepository . save ( busServiceItem ) ; } } | If ConfigurationItemBusServName is set then update it with the new relationship |
22,971 | private void validateRequest ( CmdbRequest request ) throws HygieiaException { String busServiceName = request . getConfigurationItemBusServName ( ) ; if ( ! StringUtils . isEmpty ( busServiceName ) && cmdbRepository . findByConfigurationItemAndItemType ( busServiceName , APP_TYPE ) == null ) { throw new HygieiaException ( "Configuration Item " + busServiceName + " does not exist" , HygieiaException . BAD_DATA ) ; } Cmdb cmdb = cmdbRepository . findByConfigurationItemIgnoreCaseOrCommonNameIgnoreCase ( request . getConfigurationItem ( ) , request . getCommonName ( ) ) ; if ( cmdb != null ) { throw new HygieiaException ( "Configuration Item " + cmdb . getConfigurationItem ( ) + " already exists" , HygieiaException . DUPLICATE_DATA ) ; } List < Collector > collectors = collectorRepository . findByCollectorTypeAndName ( CollectorType . CMDB , request . getToolName ( ) ) ; if ( CollectionUtils . isEmpty ( collectors ) ) { throw new HygieiaException ( request . getToolName ( ) + " collector is not available." , HygieiaException . BAD_DATA ) ; } } | Validates CmdbRequest for errors |
22,972 | private Cmdb requestToCmdb ( CmdbRequest request ) { Cmdb cmdb = new Cmdb ( ) ; cmdb . setConfigurationItem ( request . getConfigurationItem ( ) ) ; cmdb . setConfigurationItemSubType ( request . getConfigurationItemSubType ( ) ) ; cmdb . setConfigurationItemType ( request . getConfigurationItemType ( ) ) ; cmdb . setAssignmentGroup ( request . getAssignmentGroup ( ) ) ; cmdb . setOwnerDept ( request . getOwnerDept ( ) ) ; cmdb . setCommonName ( request . getCommonName ( ) ) ; cmdb . setValidConfigItem ( true ) ; cmdb . setTimestamp ( System . currentTimeMillis ( ) ) ; cmdb . setItemType ( COMPONENT_TYPE ) ; return cmdb ; } | Takes CmdbRequest and converts to Cmdb Object |
22,973 | private CollectorItem buildCollectorItem ( CmdbRequest request , Collector collector ) { CollectorItem collectorItem = new CollectorItem ( ) ; collectorItem . setCollectorId ( collector . getId ( ) ) ; collectorItem . setEnabled ( false ) ; collectorItem . setPushed ( true ) ; collectorItem . setDescription ( request . getCommonName ( ) ) ; collectorItem . setLastUpdated ( System . currentTimeMillis ( ) ) ; collectorItem . getOptions ( ) . put ( CONFIGURATION_ITEM , request . getConfigurationItem ( ) ) ; collectorItem . getOptions ( ) . put ( COMMON_NAME , request . getCommonName ( ) ) ; return collectorService . createCollectorItem ( collectorItem ) ; } | Builds collector Item for new Cmdb item |
22,974 | @ SuppressWarnings ( { "PMD.NPathComplexity" } ) URI buildUri ( final String rawUrl , final String branch , final String lastKnownCommit ) throws URISyntaxException { URIBuilder builder = new URIBuilder ( ) ; String repoUrlRaw = rawUrl ; String repoUrlProcessed = repoUrlRaw ; if ( repoUrlProcessed . endsWith ( ".git" ) ) { repoUrlProcessed = repoUrlProcessed . substring ( 0 , repoUrlProcessed . lastIndexOf ( ".git" ) ) ; } URI uri = URI . create ( repoUrlProcessed . replaceAll ( " " , "%20" ) ) ; String host = uri . getHost ( ) ; String scheme = "ssh" . equalsIgnoreCase ( uri . getScheme ( ) ) ? "https" : uri . getScheme ( ) ; int port = uri . getPort ( ) ; String path = uri . getPath ( ) ; if ( ( path . startsWith ( "scm/" ) || path . startsWith ( "/scm" ) ) && path . length ( ) > 4 ) { path = path . substring ( 4 ) ; } if ( path . length ( ) > 0 && path . charAt ( 0 ) == '/' ) { path = path . substring ( 1 , path . length ( ) ) ; } String [ ] splitPath = path . split ( "/" ) ; String projectKey = "" ; String repositorySlug = "" ; if ( splitPath . length > 1 ) { projectKey = splitPath [ 0 ] ; repositorySlug = path . substring ( path . indexOf ( '/' ) + 1 , path . length ( ) ) ; } else { projectKey = "" ; repositorySlug = path ; } String apiPath = settings . getApi ( ) != null ? settings . getApi ( ) : "" ; if ( apiPath . endsWith ( "/" ) ) { apiPath = settings . getApi ( ) . substring ( 0 , settings . getApi ( ) . length ( ) - 1 ) ; } builder . setScheme ( scheme ) ; builder . setHost ( host ) ; if ( port != - 1 ) { builder . setPort ( port ) ; } builder . setPath ( apiPath + "/projects/" + projectKey + "/repos/" + repositorySlug + "/commits" ) ; if ( branch == null || branch . length ( ) == 0 ) { builder . addParameter ( "until" , "master" ) ; } else { builder . addParameter ( "until" , branch . replaceAll ( " " , "%20" ) ) ; } if ( lastKnownCommit != null && lastKnownCommit . length ( ) > 0 ) { builder . addParameter ( "since" , lastKnownCommit ) ; } if ( settings . getPageSize ( ) > 0 ) { builder . addParameter ( "limit" , String . valueOf ( settings . getPageSize ( ) ) ) ; } return builder . build ( ) ; } | package for junit |
22,975 | @ SuppressWarnings ( "PMD.NPathComplexity" ) public DashboardReviewResponse getDashboardReviewResponse ( String dashboardTitle , DashboardType dashboardType , String businessService , String businessApp , long beginDate , long endDate , Set < AuditType > auditTypes ) throws AuditException { validateParameters ( dashboardTitle , dashboardType , businessService , businessApp , beginDate , endDate ) ; DashboardReviewResponse dashboardReviewResponse = new DashboardReviewResponse ( ) ; Dashboard dashboard = getDashboard ( dashboardTitle , dashboardType , businessService , businessApp ) ; if ( dashboard == null ) { dashboardReviewResponse . addAuditStatus ( DashboardAuditStatus . DASHBOARD_NOT_REGISTERED ) ; return dashboardReviewResponse ; } dashboardReviewResponse . setDashboardTitle ( dashboard . getTitle ( ) ) ; dashboardReviewResponse . setBusinessApplication ( StringUtils . isEmpty ( businessApp ) ? dashboard . getConfigurationItemBusAppName ( ) : businessApp ) ; dashboardReviewResponse . setBusinessService ( StringUtils . isEmpty ( businessService ) ? dashboard . getConfigurationItemBusServName ( ) : businessService ) ; if ( auditTypes . contains ( AuditType . ALL ) ) { auditTypes . addAll ( Sets . newHashSet ( AuditType . values ( ) ) ) ; auditTypes . remove ( AuditType . ALL ) ; } auditTypes . forEach ( auditType -> { Evaluator evaluator = auditModel . evaluatorMap ( ) . get ( auditType ) ; try { Collection < AuditReviewResponse > auditResponse = evaluator . evaluate ( dashboard , beginDate , endDate , null ) ; dashboardReviewResponse . addReview ( auditType , auditResponse ) ; dashboardReviewResponse . addAuditStatus ( auditModel . successStatusMap ( ) . get ( auditType ) ) ; } catch ( AuditException e ) { if ( e . getErrorCode ( ) == AuditException . NO_COLLECTOR_ITEM_CONFIGURED ) { dashboardReviewResponse . addAuditStatus ( auditModel . errorStatusMap ( ) . get ( auditType ) ) ; } } } ) ; return dashboardReviewResponse ; } | Calculates audit response for a given dashboard |
22,976 | private Dashboard getDashboard ( String title , DashboardType type , String busServ , String busApp ) throws AuditException { if ( ! StringUtils . isEmpty ( title ) && ( type != null ) ) { return dashboardRepository . findByTitleAndType ( title , type ) ; } else if ( ! StringUtils . isEmpty ( busServ ) && ! StringUtils . isEmpty ( busApp ) ) { Cmdb busServItem = cmdbRepository . findByConfigurationItemAndItemType ( busServ , "app" ) ; if ( busServItem == null ) throw new AuditException ( "Invalid Business Service Name." , AuditException . BAD_INPUT_DATA ) ; Cmdb busAppItem = cmdbRepository . findByConfigurationItemAndItemType ( busApp , "component" ) ; if ( busAppItem == null ) throw new AuditException ( "Invalid Business Application Name." , AuditException . BAD_INPUT_DATA ) ; return dashboardRepository . findByConfigurationItemBusServNameIgnoreCaseAndConfigurationItemBusAppNameIgnoreCase ( busServItem . getConfigurationItem ( ) , busAppItem . getConfigurationItem ( ) ) ; } return null ; } | Finds the dashboard |
22,977 | public static void toFile ( InputStream input , File file ) throws IOException { OutputStream os = new FileOutputStream ( file ) ; int bytesRead = 0 ; byte [ ] buffer = new byte [ DEFAULT_BUFFER_SIZE ] ; while ( ( bytesRead = input . read ( buffer , 0 , DEFAULT_BUFFER_SIZE ) ) != - 1 ) { os . write ( buffer , 0 , bytesRead ) ; } IOUtils . closeQuietly ( os ) ; IOUtils . closeQuietly ( input ) ; } | InputStream to File |
22,978 | public static String get ( String url , Map < String , String > queryParas , Map < String , String > headers ) { HttpURLConnection conn = null ; try { conn = getHttpConnection ( buildUrlWithQueryString ( url , queryParas ) , GET , headers ) ; conn . connect ( ) ; return readResponseString ( conn ) ; } catch ( Exception e ) { throw new RuntimeException ( e ) ; } finally { if ( conn != null ) { conn . disconnect ( ) ; } } } | Send GET request |
22,979 | public static String post ( String url , Map < String , String > queryParas , String data , Map < String , String > headers ) { HttpURLConnection conn = null ; try { conn = getHttpConnection ( buildUrlWithQueryString ( url , queryParas ) , POST , headers ) ; conn . connect ( ) ; OutputStream out = conn . getOutputStream ( ) ; out . write ( data != null ? data . getBytes ( CHARSET ) : null ) ; out . flush ( ) ; out . close ( ) ; return readResponseString ( conn ) ; } catch ( Exception e ) { throw new RuntimeException ( e ) ; } finally { if ( conn != null ) { conn . disconnect ( ) ; } } } | Send POST request |
22,980 | private static String buildUrlWithQueryString ( String url , Map < String , String > queryParas ) { if ( queryParas == null || queryParas . isEmpty ( ) ) return url ; StringBuilder sb = new StringBuilder ( url ) ; boolean isFirst ; if ( ! url . contains ( "?" ) ) { isFirst = true ; sb . append ( "?" ) ; } else { isFirst = false ; } for ( Entry < String , String > entry : queryParas . entrySet ( ) ) { if ( isFirst ) isFirst = false ; else sb . append ( "&" ) ; String key = entry . getKey ( ) ; String value = entry . getValue ( ) ; if ( StrKit . notBlank ( value ) ) try { value = URLEncoder . encode ( value , CHARSET ) ; } catch ( UnsupportedEncodingException e ) { throw new RuntimeException ( e ) ; } sb . append ( key ) . append ( "=" ) . append ( value ) ; } return sb . toString ( ) ; } | Build queryString of the url |
22,981 | public IdempotentPo getIdempotentPo ( EasyTransFilterChain filterChain , Map < String , Object > header , EasyTransRequest < ? , ? > reqest ) { BusinessIdentifer businessType = ReflectUtil . getBusinessIdentifer ( reqest . getClass ( ) ) ; Object trxIdObj = header . get ( EasytransConstant . CallHeadKeys . PARENT_TRX_ID_KEY ) ; TransactionId transactionId = ( TransactionId ) trxIdObj ; Integer callSeq = Integer . parseInt ( header . get ( EasytransConstant . CallHeadKeys . CALL_SEQ ) . toString ( ) ) ; JdbcTemplate jdbcTemplate = getJdbcTemplate ( filterChain , reqest ) ; List < IdempotentPo > listQuery = jdbcTemplate . query ( selectSql , new Object [ ] { stringCodecer . findId ( APP_ID , transactionId . getAppId ( ) ) , stringCodecer . findId ( BUSINESS_CODE , transactionId . getBusCode ( ) ) , transactionId . getTrxId ( ) , stringCodecer . findId ( APP_ID , businessType . appId ( ) ) , stringCodecer . findId ( BUSINESS_CODE , businessType . busCode ( ) ) , callSeq , stringCodecer . findId ( APP_ID , appId ) } , beanPropertyRowMapper ) ; if ( listQuery . size ( ) == 1 ) { return listQuery . get ( 0 ) ; } else if ( listQuery . size ( ) == 0 ) { return null ; } else { throw new RuntimeException ( "Unkonw Error!" + listQuery ) ; } } | get execute result from database |
22,982 | public Boolean getFinalMasterTransStatus ( ) { if ( finalMasterTransStatus == null ) { finalMasterTransStatus = checkTransStatusByLogs ( ) ; if ( finalMasterTransStatus == null ) { finalMasterTransStatus = transStatusChecker . checkTransactionStatus ( getLogCollection ( ) . getAppId ( ) , getLogCollection ( ) . getBusCode ( ) , getLogCollection ( ) . getTrxId ( ) ) ; } } return finalMasterTransStatus ; } | status true for commit false for roll back null for unknown |
22,983 | private CompletableFuture < Void > postScaleRequest ( final AutoScaleEvent request , final List < Long > segments , final List < Map . Entry < Double , Double > > newRanges , final long requestId ) { ScaleOpEvent event = new ScaleOpEvent ( request . getScope ( ) , request . getStream ( ) , segments , newRanges , false , System . currentTimeMillis ( ) , requestId ) ; return streamMetadataTasks . writeEvent ( event ) ; } | Scale tasks exceptions are absorbed . |
22,984 | public static < T > boolean await ( CompletableFuture < T > f , long timeout ) { Exceptions . handleInterrupted ( ( ) -> { try { f . get ( timeout , TimeUnit . MILLISECONDS ) ; } catch ( TimeoutException | ExecutionException e ) { } } ) ; return isSuccessful ( f ) ; } | Waits for the provided future to be complete and returns true if it was successful false if it failed or did not complete . |
22,985 | public static < T > void completeAfter ( Supplier < CompletableFuture < ? extends T > > futureSupplier , CompletableFuture < T > toComplete ) { Preconditions . checkArgument ( ! toComplete . isDone ( ) , "toComplete is already completed." ) ; try { CompletableFuture < ? extends T > f = futureSupplier . get ( ) ; f . thenAccept ( toComplete :: complete ) ; Futures . exceptionListener ( f , toComplete :: completeExceptionally ) ; } catch ( Throwable ex ) { toComplete . completeExceptionally ( ex ) ; throw ex ; } } | Given a Supplier returning a Future completes another future either with the result of the first future in case of normal completion or exceptionally with the exception of the first future . |
22,986 | public static < T > boolean isSuccessful ( CompletableFuture < T > f ) { return f . isDone ( ) && ! f . isCompletedExceptionally ( ) && ! f . isCancelled ( ) ; } | Returns true if the future is done and successful . |
22,987 | public static < T > Throwable getException ( CompletableFuture < T > future ) { try { future . getNow ( null ) ; return null ; } catch ( Exception e ) { return Exceptions . unwrap ( e ) ; } } | If the future has failed returns the exception that caused it . Otherwise returns null . |
22,988 | public static < ResultT , ExceptionT extends Exception > ResultT getAndHandleExceptions ( Future < ResultT > future , Function < Throwable , ExceptionT > exceptionConstructor ) throws ExceptionT { Preconditions . checkNotNull ( exceptionConstructor ) ; try { return Exceptions . handleInterruptedCall ( ( ) -> future . get ( ) ) ; } catch ( ExecutionException e ) { ExceptionT result = exceptionConstructor . apply ( e . getCause ( ) ) ; if ( result == null ) { return null ; } else { throw result ; } } } | Calls get on the provided future handling interrupted and transforming the executionException into an exception of the type whose constructor is provided . |
22,989 | public static < T > CompletableFuture < T > failedFuture ( Throwable exception ) { CompletableFuture < T > result = new CompletableFuture < > ( ) ; result . completeExceptionally ( exception ) ; return result ; } | Creates a new CompletableFuture that is failed with the given exception . |
22,990 | public static < T > void exceptionListener ( CompletableFuture < T > completableFuture , Consumer < Throwable > exceptionListener ) { completableFuture . whenComplete ( ( r , ex ) -> { if ( ex != null ) { Callbacks . invokeSafely ( exceptionListener , ex , null ) ; } } ) ; } | Registers an exception listener to the given CompletableFuture . |
22,991 | @ SuppressWarnings ( "unchecked" ) public static < T , E extends Throwable > void exceptionListener ( CompletableFuture < T > completableFuture , Class < E > exceptionClass , Consumer < E > exceptionListener ) { completableFuture . whenComplete ( ( r , ex ) -> { if ( ex != null && exceptionClass . isAssignableFrom ( ex . getClass ( ) ) ) { Callbacks . invokeSafely ( exceptionListener , ( E ) ex , null ) ; } } ) ; } | Registers an exception listener to the given CompletableFuture for a particular type of exception . |
22,992 | public static < T > CompletableFuture < Void > toVoid ( CompletableFuture < T > future ) { return future . thenAccept ( Callbacks :: doNothing ) ; } | Returns a CompletableFuture that will end when the given future ends but discards its result . If the given future fails the returned future will fail with the same exception . |
22,993 | public static < T > CompletableFuture < List < T > > filter ( List < T > input , Function < T , CompletableFuture < Boolean > > predicate ) { Preconditions . checkNotNull ( input ) ; val allFutures = input . stream ( ) . collect ( Collectors . toMap ( key -> key , predicate :: apply ) ) ; return Futures . allOf ( allFutures . values ( ) ) . thenApply ( ignored -> allFutures . entrySet ( ) . stream ( ) . filter ( e -> e . getValue ( ) . join ( ) ) . map ( Map . Entry :: getKey ) . collect ( Collectors . toList ( ) ) ) ; } | Filter that takes a predicate that evaluates in future and returns the filtered list that evaluates in future . |
22,994 | public static CompletableFuture < Void > delayedFuture ( Duration delay , ScheduledExecutorService executorService ) { CompletableFuture < Void > result = new CompletableFuture < > ( ) ; if ( delay . toMillis ( ) == 0 ) { result . complete ( null ) ; } else { ScheduledFuture < Boolean > sf = executorService . schedule ( ( ) -> result . complete ( null ) , delay . toMillis ( ) , TimeUnit . MILLISECONDS ) ; result . whenComplete ( ( r , ex ) -> sf . cancel ( true ) ) ; } return result ; } | Creates a CompletableFuture that will do nothing and complete after a specified delay without using a thread during the delay . |
22,995 | public static < T > CompletableFuture < T > delayedFuture ( final Supplier < CompletableFuture < T > > task , final long delay , final ScheduledExecutorService executorService ) { return delayedFuture ( Duration . ofMillis ( delay ) , executorService ) . thenCompose ( v -> task . get ( ) ) ; } | Executes the asynchronous task after the specified delay . |
22,996 | public static < T > CompletableFuture < T > delayedTask ( final Supplier < T > task , final Duration delay , final ScheduledExecutorService executorService ) { CompletableFuture < T > result = new CompletableFuture < > ( ) ; executorService . schedule ( ( ) -> result . complete ( runOrFail ( ( ) -> task . get ( ) , result ) ) , delay . toMillis ( ) , TimeUnit . MILLISECONDS ) ; return result ; } | Executes the given task after the specified delay . |
22,997 | public static < T > CompletableFuture < Void > loop ( Iterable < T > iterable , Function < T , CompletableFuture < Boolean > > loopBody , Executor executor ) { Iterator < T > iterator = iterable . iterator ( ) ; AtomicBoolean canContinue = new AtomicBoolean ( true ) ; return loop ( ( ) -> iterator . hasNext ( ) && canContinue . get ( ) , ( ) -> loopBody . apply ( iterator . next ( ) ) , canContinue :: set , executor ) ; } | Executes a loop using CompletableFutures over the given Iterable processing each item in order without overlap using the given Executor for task execution . |
22,998 | public static < T > CompletableFuture < Void > doWhileLoop ( Supplier < CompletableFuture < T > > loopBody , Predicate < T > condition , Executor executor ) { CompletableFuture < Void > result = new CompletableFuture < > ( ) ; AtomicBoolean canContinue = new AtomicBoolean ( ) ; Consumer < T > iterationResultHandler = ir -> canContinue . set ( condition . test ( ir ) ) ; loopBody . get ( ) . thenAccept ( iterationResultHandler ) . thenRunAsync ( ( ) -> { Loop < T > loop = new Loop < > ( canContinue :: get , loopBody , iterationResultHandler , result , executor ) ; executor . execute ( loop ) ; } , executor ) . exceptionally ( ex -> { result . completeExceptionally ( ex ) ; return null ; } ) ; return result ; } | Executes a code fragment returning a CompletableFutures while a condition on the returned value is satisfied . |
22,999 | private void pingTransactions ( ) { log . info ( "Start sending transaction pings." ) ; txnList . stream ( ) . forEach ( uuid -> { try { log . debug ( "Sending ping request for txn ID: {} with lease: {}" , uuid , txnLeaseMillis ) ; controller . pingTransaction ( stream , uuid , txnLeaseMillis ) . exceptionally ( e -> { log . warn ( "Ping Transaction for txn ID:{} failed" , uuid , e ) ; return null ; } ) ; } catch ( Exception e ) { log . warn ( "Encountered exception when attepting to ping transactions" , e ) ; } } ) ; log . trace ( "Completed sending transaction pings." ) ; } | Ping all the transactions present in the list . Controller client performs retries in case of a failures . On a failure the particular transaction it is removed from the ping list . |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.