idx int64 0 41.2k | question stringlengths 73 5.81k | target stringlengths 5 918 |
|---|---|---|
22,800 | public static < T > Set < T > newSets ( T ... values ) { if ( null == values || values . length == 0 ) { Assert . notNull ( values , "values not is null." ) ; } return new HashSet < > ( Arrays . asList ( values ) ) ; } | New Set and add values |
22,801 | public static long getDirSize ( String path ) { StatFs stat ; try { stat = new StatFs ( path ) ; } catch ( Exception e ) { return 0 ; } if ( Build . VERSION . SDK_INT >= Build . VERSION_CODES . JELLY_BEAN_MR2 ) { return stat . getBlockSizeLong ( ) * stat . getAvailableBlocksLong ( ) ; } else { return ( long ) stat . getBlockSize ( ) * ( long ) stat . getAvailableBlocks ( ) ; } } | Access to a directory available size . |
22,802 | public static boolean delFileOrFolder ( File file ) { if ( file == null || ! file . exists ( ) ) { } else if ( file . isFile ( ) ) { file . delete ( ) ; } else if ( file . isDirectory ( ) ) { File [ ] files = file . listFiles ( ) ; if ( files != null ) { for ( File sonFile : files ) { delFileOrFolder ( sonFile ) ; } } file . delete ( ) ; } return true ; } | Delete file or folder . |
22,803 | @ SuppressWarnings ( "unchecked" ) public static < E > void mergeArrayIntoCollection ( Object array , Collection < E > collection ) { if ( collection == null ) { throw new IllegalArgumentException ( "Collection must not be null" ) ; } Object [ ] arr = ObjectUtils . toObjectArray ( array ) ; for ( Object elem : arr ) { collection . add ( ( E ) elem ) ; } } | Merge the given array into the given Collection . |
22,804 | public static boolean contains ( Iterator < ? > iterator , Object element ) { if ( iterator != null ) { while ( iterator . hasNext ( ) ) { Object candidate = iterator . next ( ) ; if ( ObjectUtils . nullSafeEquals ( candidate , element ) ) { return true ; } } } return false ; } | Check whether the given Iterator contains the given element . |
22,805 | public static boolean contains ( Enumeration < ? > enumeration , Object element ) { if ( enumeration != null ) { while ( enumeration . hasMoreElements ( ) ) { Object candidate = enumeration . nextElement ( ) ; if ( ObjectUtils . nullSafeEquals ( candidate , element ) ) { return true ; } } } return false ; } | Check whether the given Enumeration contains the given element . |
22,806 | public static boolean hasUniqueObject ( Collection < ? > collection ) { if ( isEmpty ( collection ) ) { return false ; } boolean hasCandidate = false ; Object candidate = null ; for ( Object elem : collection ) { if ( ! hasCandidate ) { hasCandidate = true ; candidate = elem ; } else if ( candidate != elem ) { return false ; } } return true ; } | Determine whether the given Collection only contains a single unique object . |
22,807 | public static Class < ? > findCommonElementType ( Collection < ? > collection ) { if ( isEmpty ( collection ) ) { return null ; } Class < ? > candidate = null ; for ( Object val : collection ) { if ( val != null ) { if ( candidate == null ) { candidate = val . getClass ( ) ; } else if ( candidate != val . getClass ( ) ) { return null ; } } } return candidate ; } | Find the common element type of the given Collection if any . |
22,808 | public static < A , E extends A > A [ ] toArray ( Enumeration < E > enumeration , A [ ] array ) { ArrayList < A > elements = new ArrayList < > ( ) ; while ( enumeration . hasMoreElements ( ) ) { elements . add ( enumeration . nextElement ( ) ) ; } return elements . toArray ( array ) ; } | Marshal the elements from the given enumeration into an array of the given type . Enumeration elements must be assignable to the type of the given array . The array returned will be a different instance than the array given . |
22,809 | public void shutdown ( ) { if ( ! isRunning ) return ; Executors . getInstance ( ) . execute ( new Runnable ( ) { public void run ( ) { if ( mHttpServer != null ) { mHttpServer . shutdown ( 3 , TimeUnit . MINUTES ) ; isRunning = false ; Executors . getInstance ( ) . post ( new Runnable ( ) { public void run ( ) { if ( mListener != null ) mListener . onStopped ( ) ; } } ) ; } } } ) ; } | Quit the server . |
22,810 | public static InetAddress getLocalIPAddress ( ) { Enumeration < NetworkInterface > enumeration = null ; try { enumeration = NetworkInterface . getNetworkInterfaces ( ) ; } catch ( SocketException e ) { e . printStackTrace ( ) ; } if ( enumeration != null ) { while ( enumeration . hasMoreElements ( ) ) { NetworkInterface nif = enumeration . nextElement ( ) ; Enumeration < InetAddress > inetAddresses = nif . getInetAddresses ( ) ; if ( inetAddresses != null ) { while ( inetAddresses . hasMoreElements ( ) ) { InetAddress inetAddress = inetAddresses . nextElement ( ) ; if ( ! inetAddress . isLoopbackAddress ( ) && isIPv4Address ( inetAddress . getHostAddress ( ) ) ) { return inetAddress ; } } } } } return null ; } | Get local Ip address . |
22,811 | public void onServerStart ( String ip ) { closeDialog ( ) ; mBtnStart . setVisibility ( View . GONE ) ; mBtnStop . setVisibility ( View . VISIBLE ) ; mBtnBrowser . setVisibility ( View . VISIBLE ) ; if ( ! TextUtils . isEmpty ( ip ) ) { List < String > addressList = new LinkedList < > ( ) ; mRootUrl = "http://" + ip + ":8080/" ; addressList . add ( mRootUrl ) ; addressList . add ( "http://" + ip + ":8080/login.html" ) ; mTvMessage . setText ( TextUtils . join ( "\n" , addressList ) ) ; } else { mRootUrl = null ; mTvMessage . setText ( R . string . server_ip_error ) ; } } | Start notify . |
22,812 | public void onServerError ( String message ) { closeDialog ( ) ; mRootUrl = null ; mBtnStart . setVisibility ( View . VISIBLE ) ; mBtnStop . setVisibility ( View . GONE ) ; mBtnBrowser . setVisibility ( View . GONE ) ; mTvMessage . setText ( message ) ; } | Error notify . |
22,813 | public void onServerStop ( ) { closeDialog ( ) ; mRootUrl = null ; mBtnStart . setVisibility ( View . VISIBLE ) ; mBtnStop . setVisibility ( View . GONE ) ; mBtnBrowser . setVisibility ( View . GONE ) ; mTvMessage . setText ( R . string . server_stop_succeed ) ; } | Stop notify . |
22,814 | public void setUploadTempDir ( File uploadTempDir ) throws IOException { if ( ! uploadTempDir . exists ( ) && ! uploadTempDir . mkdirs ( ) ) { String message = "Given uploadTempDir [" + uploadTempDir + "] could not be created." ; throw new IllegalArgumentException ( message ) ; } this . mFileItemFactory . setRepository ( uploadTempDir ) ; } | Set the temporary directory where uploaded files get stored . |
22,815 | private MultipartParsingResult parseRequest ( HttpRequest request ) throws MultipartException { String encoding = determineEncoding ( request ) ; FileUpload fileUpload = prepareFileUpload ( encoding ) ; try { RequestBody body = request . getBody ( ) ; Assert . notNull ( body , "The body cannot be null." ) ; List < FileItem > fileItems = fileUpload . parseRequest ( new BodyContext ( body ) ) ; return parseFileItems ( fileItems , encoding ) ; } catch ( FileUploadBase . SizeLimitExceededException ex ) { throw new MaxUploadSizeExceededException ( fileUpload . getSizeMax ( ) , ex ) ; } catch ( FileUploadBase . FileSizeLimitExceededException ex ) { throw new MaxUploadSizeExceededException ( fileUpload . getFileSizeMax ( ) , ex ) ; } catch ( FileUploadException ex ) { throw new MultipartException ( "Failed to parse multipart servlet request." , ex ) ; } } | Parse the given request resolving its multipart elements . |
22,816 | private String determineEncoding ( HttpRequest request ) { MediaType mimeType = request . getContentType ( ) ; if ( mimeType == null ) return Charsets . UTF_8 . name ( ) ; Charset charset = mimeType . getCharset ( ) ; return charset == null ? Charsets . UTF_8 . name ( ) : charset . name ( ) ; } | Determine the encoding for the given request . |
22,817 | protected MultipartParsingResult parseFileItems ( List < FileItem > fileItems , String encoding ) { MultiValueMap < String , MultipartFile > multipartFiles = new LinkedMultiValueMap < > ( ) ; MultiValueMap < String , String > multipartParameters = new LinkedMultiValueMap < > ( ) ; Map < String , String > multipartContentTypes = new HashMap < > ( ) ; for ( FileItem fileItem : fileItems ) { if ( fileItem . isFormField ( ) ) { String value ; String partEncoding = determineEncoding ( fileItem . getContentType ( ) , encoding ) ; if ( partEncoding != null ) { try { value = fileItem . getString ( partEncoding ) ; } catch ( UnsupportedEncodingException ex ) { value = fileItem . getString ( ) ; } } else { value = fileItem . getString ( ) ; } List < String > curParam = multipartParameters . get ( fileItem . getFieldName ( ) ) ; if ( curParam == null ) { curParam = new LinkedList < > ( ) ; curParam . add ( value ) ; multipartParameters . put ( fileItem . getFieldName ( ) , curParam ) ; } else { curParam . add ( value ) ; } multipartContentTypes . put ( fileItem . getFieldName ( ) , fileItem . getContentType ( ) ) ; } else { StandardMultipartFile file = createMultipartFile ( fileItem ) ; multipartFiles . add ( file . getName ( ) , file ) ; } } return new MultipartParsingResult ( multipartFiles , multipartParameters , multipartContentTypes ) ; } | Parse the given List of Commons FileItems into a MultipartParsingResult containing MultipartFile instances and a Map of multipart parameter . |
22,818 | private void startServer ( ) { if ( mServer . isRunning ( ) ) { String hostAddress = mServer . getInetAddress ( ) . getHostAddress ( ) ; ServerManager . onServerStart ( CoreService . this , hostAddress ) ; } else { mServer . startup ( ) ; } } | Start server . |
22,819 | public static String successfulJson ( Object data ) { ReturnData returnData = new ReturnData ( ) ; returnData . setSuccess ( true ) ; returnData . setErrorCode ( 200 ) ; returnData . setData ( data ) ; return JSON . toJSONString ( returnData ) ; } | Business is successful . |
22,820 | public static String failedJson ( int code , String message ) { ReturnData returnData = new ReturnData ( ) ; returnData . setSuccess ( false ) ; returnData . setErrorCode ( code ) ; returnData . setErrorMsg ( message ) ; return JSON . toJSONString ( returnData ) ; } | Business is failed . |
22,821 | public static < T > T parseJson ( String json , Type type ) { return JSON . parseObject ( json , type ) ; } | Parse json to object . |
22,822 | protected boolean isAvailable ( ) { if ( fileItem . isInMemory ( ) ) { return true ; } if ( fileItem instanceof DiskFileItem ) { return ( ( DiskFileItem ) fileItem ) . getStoreLocation ( ) . exists ( ) ; } return ( fileItem . getSize ( ) == size ) ; } | Determine whether the multipart content is still available . If a temporary file has been moved the content is no longer available . |
22,823 | private List < Mapping > getMappings ( String httpPath ) { List < Mapping > returned = new ArrayList < > ( ) ; List < Path . Segment > httpSegments = Path . pathToList ( httpPath ) ; Map < Mapping , RequestHandler > mappings = getMappingMap ( ) ; for ( Mapping mapping : mappings . keySet ( ) ) { List < Path . Rule > paths = mapping . getPath ( ) . getRuleList ( ) ; for ( Path . Rule path : paths ) { List < Path . Segment > segments = path . getSegments ( ) ; if ( httpSegments . size ( ) != segments . size ( ) ) continue ; String pathStr = Path . listToPath ( segments ) ; if ( pathStr . equals ( httpPath ) ) { returned . add ( mapping ) ; break ; } boolean matches = true ; for ( int i = 0 ; i < segments . size ( ) ; i ++ ) { Path . Segment segment = segments . get ( i ) ; if ( ! segment . equals ( httpSegments . get ( i ) ) && ! segment . isBlurred ( ) ) { matches = false ; break ; } } if ( matches ) returned . add ( mapping ) ; } } return returned ; } | Get the mapping corresponding to the path . |
22,824 | public static File createRandomFile ( MultipartFile file ) { String extension = MimeTypeMap . getSingleton ( ) . getExtensionFromMimeType ( file . getContentType ( ) . toString ( ) ) ; if ( StringUtils . isEmpty ( extension ) ) { extension = MimeTypeMap . getFileExtensionFromUrl ( file . getFilename ( ) ) ; } String uuid = UUID . randomUUID ( ) . toString ( ) ; return new File ( App . getInstance ( ) . getRootDir ( ) , uuid + "." + extension ) ; } | Create a random file based on mimeType . |
22,825 | public static boolean storageAvailable ( ) { if ( Environment . getExternalStorageState ( ) . equals ( Environment . MEDIA_MOUNTED ) ) { File sd = new File ( Environment . getExternalStorageDirectory ( ) . getAbsolutePath ( ) ) ; return sd . canWrite ( ) ; } else { return false ; } } | SD is available . |
22,826 | public static String getUrlExtension ( String url ) { String extension = MimeTypeMap . getFileExtensionFromUrl ( url ) ; return TextUtils . isEmpty ( extension ) ? "" : extension ; } | Get he extension by url . |
22,827 | public static Executors getInstance ( ) { if ( instance == null ) { synchronized ( Executors . class ) { if ( instance == null ) instance = new Executors ( ) ; } } return instance ; } | Get instance . |
22,828 | public < T > Future < T > submit ( Runnable runnable , T result ) { return mService . submit ( runnable , result ) ; } | Submit a runnable . |
22,829 | public < T > Future < T > submit ( Callable < T > callable ) { return mService . submit ( callable ) ; } | Submit a callable . |
22,830 | private boolean preHandle ( HttpRequest request , HttpResponse response , RequestHandler handler ) throws Exception { for ( HandlerInterceptor interceptor : mInterceptorList ) { if ( interceptor . onIntercept ( request , response , handler ) ) return true ; } return false ; } | Intercept the execution of a handler . |
22,831 | public Charset getCharset ( ) { String charset = getParameter ( PARAM_CHARSET ) ; return ( charset != null ? Charset . forName ( unquote ( charset ) ) : null ) ; } | Return the character set as indicated by a charset parameter if any . |
22,832 | private void tryScanFile ( ) { if ( ! isScanned ) { synchronized ( AssetsWebsite . class ) { if ( ! isScanned ) { List < String > fileList = mReader . scanFile ( mRootPath ) ; for ( String filePath : fileList ) { String httpPath = filePath . substring ( mRootPath . length ( ) , filePath . length ( ) ) ; httpPath = addStartSlash ( httpPath ) ; mPatternMap . put ( httpPath , filePath ) ; String indexFileName = getIndexFileName ( ) ; if ( filePath . endsWith ( indexFileName ) ) { httpPath = filePath . substring ( 0 , filePath . indexOf ( indexFileName ) - 1 ) ; httpPath = addStartSlash ( httpPath ) ; mPatternMap . put ( httpPath , filePath ) ; mPatternMap . put ( addEndSlash ( httpPath ) , filePath ) ; } } isScanned = true ; } } } } | Try to scan the file no longer scan if it has already been scanned . |
22,833 | private boolean isToken ( String value ) { int len = value . length ( ) ; for ( int i = 0 ; i < len ; i ++ ) { char c = value . charAt ( i ) ; if ( c < 0x20 || c >= 0x7f || TSPECIALS . indexOf ( c ) != - 1 ) { return false ; } } return true ; } | Tests a string and returns true if the string counts as a reserved token in the Java language . |
22,834 | public static String getCurrentDate ( ) { synchronized ( FORMAT ) { long now = System . currentTimeMillis ( ) ; return FORMAT . format ( new Date ( now ) ) ; } } | Get the current date in HTTP format . |
22,835 | public static String formatDate ( long value ) { synchronized ( HttpDateFormat . class ) { Date dateValue = new Date ( value ) ; return FORMAT . format ( dateValue ) ; } } | Get the HTTP format of the specified date . |
22,836 | public static long parseDate ( String value ) { Date date = null ; for ( SimpleDateFormat format : FORMATS_TEMPLATE ) { try { date = format . parse ( value ) ; } catch ( ParseException e ) { } } if ( date == null ) return - 1L ; return date . getTime ( ) ; } | Try to parse the given date as a HTTP date . |
22,837 | public void setComparator ( int index , Comparator < T > comparator , boolean ascending ) { this . comparators . set ( index , new InvertibleComparator < > ( comparator , ascending ) ) ; } | Replace the Comparator at the given index using the given sort order . |
22,838 | public static List < String > getDexFilePaths ( Context context ) { ApplicationInfo appInfo = context . getApplicationInfo ( ) ; File sourceApk = new File ( appInfo . sourceDir ) ; List < String > sourcePaths = new ArrayList < > ( ) ; sourcePaths . add ( appInfo . sourceDir ) ; if ( ! isVMMultidexCapable ( ) ) { String extractedFilePrefix = sourceApk . getName ( ) + EXTRACTED_NAME_EXT ; int totalDexNumber = getMultiDexPreferences ( context ) . getInt ( KEY_DEX_NUMBER , 1 ) ; File dexDir = new File ( appInfo . dataDir , CODE_CACHE_SECONDARY_DIRECTORY ) ; for ( int secondaryNumber = 2 ; secondaryNumber <= totalDexNumber ; secondaryNumber ++ ) { String fileName = extractedFilePrefix + secondaryNumber + EXTRACTED_SUFFIX ; File extractedFile = new File ( dexDir , fileName ) ; if ( extractedFile . isFile ( ) ) { sourcePaths . add ( extractedFile . getAbsolutePath ( ) ) ; } } } if ( AndServer . isDebug ( ) ) { sourcePaths . addAll ( loadInstantRunDexFile ( appInfo ) ) ; } return sourcePaths ; } | Obtain all the dex path . |
22,839 | private static boolean isVMMultidexCapable ( ) { boolean isMultidexCapable = false ; String vmVersion = System . getProperty ( "java.vm.version" ) ; try { Matcher matcher = Pattern . compile ( "(\\d+)\\.(\\d+)(\\.\\d+)?" ) . matcher ( vmVersion ) ; if ( matcher . matches ( ) ) { int major = Integer . parseInt ( matcher . group ( 1 ) ) ; int minor = Integer . parseInt ( matcher . group ( 2 ) ) ; isMultidexCapable = ( major > 2 ) || ( ( major == 2 ) && ( minor >= 1 ) ) ; } } catch ( Exception ignore ) { } String multidex = isMultidexCapable ? "has Multidex support" : "does not have Multidex support" ; Log . i ( AndServer . TAG , String . format ( "VM with version %s %s." , vmVersion , multidex ) ) ; return false ; } | Identifies if the current VM has a native support for multidex . |
22,840 | private List < String > getBusinessServiceList ( String firstName , String lastName ) { List < String > businessServiceList = new ArrayList < > ( ) ; List < Cmdb > cmdbs = cmdbService . getAllBusServices ( ) ; Predicate < Cmdb > supportOwnerLn = p -> p . getSupportOwner ( ) != null ? p . getSupportOwner ( ) . toLowerCase ( ) . contains ( lastName ) : false ; Predicate < Cmdb > serviceOwnerLn = p -> p . getAppServiceOwner ( ) != null ? p . getAppServiceOwner ( ) . toLowerCase ( ) . contains ( lastName ) : false ; Predicate < Cmdb > developmentOwnerLn = p -> p . getDevelopmentOwner ( ) != null ? p . getDevelopmentOwner ( ) . toLowerCase ( ) . contains ( lastName ) : false ; Predicate < Cmdb > businessOwnerLn = p -> p . getBusinessOwner ( ) != null ? p . getBusinessOwner ( ) . toLowerCase ( ) . contains ( lastName ) : false ; Predicate < Cmdb > fullPredicate = supportOwnerLn . or ( serviceOwnerLn ) . or ( developmentOwnerLn ) . or ( businessOwnerLn ) ; List < Cmdb > matching = cmdbs . stream ( ) . filter ( fullPredicate ) . collect ( Collectors . toList ( ) ) ; for ( Cmdb cmdb : matching ) { String businessServiceApp = cmdb . getConfigurationItem ( ) ; boolean serviceOwnerMatch = doesMatchFullName ( firstName , cmdb . getAppServiceOwner ( ) ) ; boolean businessOwnerMatch = doesMatchFullName ( firstName , cmdb . getBusinessOwner ( ) ) ; boolean supportOwnerMatch = doesMatchFullName ( firstName , cmdb . getSupportOwner ( ) ) ; boolean developmentOwnerMatch = doesMatchFullName ( firstName , cmdb . getDevelopmentOwner ( ) ) ; if ( ( serviceOwnerMatch || businessOwnerMatch || supportOwnerMatch || developmentOwnerMatch ) && ! businessServiceList . contains ( businessServiceApp ) ) { businessServiceList . add ( businessServiceApp ) ; } } return businessServiceList ; } | Takes First name and last name and returns any Business Services where one of the 4 owner fields match the input |
22,841 | private boolean doesMatchFullName ( String firstName , String fullName ) { boolean matching = false ; if ( firstName != null && ! firstName . isEmpty ( ) && fullName != null && ! fullName . isEmpty ( ) ) { String firstFromCMDB ; String [ ] array = fullName . split ( " " ) ; firstName = firstName . toLowerCase ( ) ; firstFromCMDB = array [ 0 ] ; firstFromCMDB = firstFromCMDB . toLowerCase ( ) ; if ( firstFromCMDB . length ( ) < firstName . length ( ) ) { if ( firstName . indexOf ( firstFromCMDB ) != - 1 ) { matching = true ; } } else if ( firstFromCMDB . indexOf ( firstName ) != - 1 ) { matching = true ; } } return matching ; } | Takes first name and full name and returns true or false if first name is found in full name |
22,842 | public List < NexusIQApplication > getApplications ( String instanceUrl ) { List < NexusIQApplication > nexusIQApplications = new ArrayList < > ( ) ; String url = instanceUrl + API_V2_APPLICATIONS ; try { JSONObject jsonObject = parseAsObject ( url ) ; JSONArray jsonArray = ( JSONArray ) jsonObject . get ( "applications" ) ; for ( Object obj : jsonArray ) { JSONObject applicationData = ( JSONObject ) obj ; NexusIQApplication application = new NexusIQApplication ( ) ; application . setInstanceUrl ( instanceUrl ) ; application . setApplicationId ( str ( applicationData , ID ) ) ; application . setApplicationName ( str ( applicationData , NAME ) ) ; application . setDescription ( application . getApplicationName ( ) ) ; application . setPublicId ( str ( applicationData , PUBLIC_ID ) ) ; nexusIQApplications . add ( application ) ; } } catch ( ParseException e ) { LOG . error ( "Could not parse response from: " + url , e ) ; } catch ( RestClientException rce ) { LOG . error ( rce ) ; } return nexusIQApplications ; } | Get all the applications from the nexus IQ server |
22,843 | public List < LibraryPolicyReport > getApplicationReport ( NexusIQApplication application ) { List < LibraryPolicyReport > applicationReports = new ArrayList < > ( ) ; String appReportLinkUrl = String . format ( application . getInstanceUrl ( ) + API_V2_REPORTS_LINKS , application . getApplicationId ( ) ) ; try { JSONArray reports = parseAsArray ( appReportLinkUrl ) ; if ( ( reports == null ) || ( reports . isEmpty ( ) ) ) return null ; for ( Object element : reports ) { LibraryPolicyReport appReport = new LibraryPolicyReport ( ) ; String stage = str ( ( JSONObject ) element , "stage" ) ; appReport . setStage ( stage ) ; appReport . setEvaluationDate ( timestamp ( ( JSONObject ) element , "evaluationDate" ) ) ; appReport . setReportDataUrl ( application . getInstanceUrl ( ) + "/" + str ( ( JSONObject ) element , "reportDataUrl" ) ) ; appReport . setReportUIUrl ( application . getInstanceUrl ( ) + "/" + str ( ( JSONObject ) element , "reportHtmlUrl" ) ) ; applicationReports . add ( appReport ) ; } } catch ( ParseException e ) { LOG . error ( "Could not parse response from: " + appReportLinkUrl , e ) ; } catch ( RestClientException rce ) { LOG . error ( "RestClientException: " + appReportLinkUrl + ". Error code=" + rce . getMessage ( ) ) ; } return applicationReports ; } | Get report links for a given application . |
22,844 | public static String rebuildJobUrl ( String build , String server ) throws URISyntaxException , MalformedURLException , UnsupportedEncodingException { URL instanceUrl = new URL ( server ) ; String userInfo = instanceUrl . getUserInfo ( ) ; String instanceProtocol = instanceUrl . getProtocol ( ) ; URL buildUrl = new URL ( URLDecoder . decode ( build , "UTF-8" ) ) ; String buildPath = buildUrl . getPath ( ) ; String host = buildUrl . getHost ( ) ; int port = buildUrl . getPort ( ) ; URI newUri = new URI ( instanceProtocol , userInfo , host , port , buildPath , null , null ) ; return newUri . toString ( ) ; } | does not save the auth user info and we need to add it back . |
22,845 | public int getRemainingDays ( String startDate , String endDate , Date currentDate ) throws java . text . ParseException { DateFormat dateFormat = new SimpleDateFormat ( "yyyy-MM-dd" ) ; Calendar iterationEndDate = Calendar . getInstance ( ) ; iterationEndDate . setTime ( dateFormat . parse ( endDate ) ) ; Calendar iterationStartDate = Calendar . getInstance ( ) ; iterationStartDate . setTime ( dateFormat . parse ( startDate ) ) ; Calendar currentCalendarDate = Calendar . getInstance ( ) ; currentCalendarDate . setTime ( currentDate ) ; int remainingDays = 0 ; if ( ( iterationStartDate . compareTo ( currentCalendarDate ) == 1 ) || ( iterationEndDate . compareTo ( currentCalendarDate ) == - 1 ) ) { return remainingDays ; } while ( iterationEndDate . compareTo ( currentCalendarDate ) == 1 ) { if ( ( currentCalendarDate . get ( Calendar . DAY_OF_WEEK ) != Calendar . SATURDAY ) && ( currentCalendarDate . get ( Calendar . DAY_OF_WEEK ) != Calendar . SUNDAY ) ) { ++ remainingDays ; } currentCalendarDate . add ( Calendar . DAY_OF_MONTH , 1 ) ; } return remainingDays ; } | Helper method to find the remaining days |
22,846 | private SecurityReviewAuditResponse getStaticSecurityScanResponse ( CollectorItem collectorItem , long beginDate , long endDate ) { List < CodeQuality > codeQualities = codeQualityRepository . findByCollectorItemIdAndTimestampIsBetweenOrderByTimestampDesc ( collectorItem . getId ( ) , beginDate - 1 , endDate + 1 ) ; SecurityReviewAuditResponse securityReviewAuditResponse = new SecurityReviewAuditResponse ( ) ; securityReviewAuditResponse . setAuditEntity ( collectorItem . getOptions ( ) ) ; securityReviewAuditResponse . setLastUpdated ( collectorItem . getLastUpdated ( ) ) ; if ( CollectionUtils . isEmpty ( codeQualities ) ) { securityReviewAuditResponse . addAuditStatus ( CodeQualityAuditStatus . STATIC_SECURITY_SCAN_MISSING ) ; return securityReviewAuditResponse ; } CodeQuality returnQuality = codeQualities . get ( 0 ) ; securityReviewAuditResponse . setCodeQuality ( returnQuality ) ; securityReviewAuditResponse . setLastExecutionTime ( returnQuality . getTimestamp ( ) ) ; Set < CodeQualityMetric > metrics = returnQuality . getMetrics ( ) ; if ( metrics . stream ( ) . anyMatch ( metric -> metric . getName ( ) . equalsIgnoreCase ( STR_CRITICAL ) ) ) { securityReviewAuditResponse . addAuditStatus ( CodeQualityAuditStatus . STATIC_SECURITY_SCAN_FOUND_CRITICAL ) ; } else if ( metrics . stream ( ) . anyMatch ( metric -> metric . getName ( ) . equalsIgnoreCase ( STR_HIGH ) ) ) { securityReviewAuditResponse . addAuditStatus ( CodeQualityAuditStatus . STATIC_SECURITY_SCAN_FOUND_HIGH ) ; } else { CodeQualityMetric scoreMetric = metrics . stream ( ) . filter ( metric -> metric . getName ( ) . equalsIgnoreCase ( STR_SCORE ) ) . findFirst ( ) . get ( ) ; Integer nScore = StringUtils . isNumeric ( scoreMetric . getValue ( ) ) ? Integer . parseInt ( scoreMetric . getValue ( ) ) : 0 ; if ( nScore > 0 ) { securityReviewAuditResponse . addAuditStatus ( CodeQualityAuditStatus . STATIC_SECURITY_SCAN_OK ) ; } else { securityReviewAuditResponse . addAuditStatus ( CodeQualityAuditStatus . STATIC_SECURITY_SCAN_FAIL ) ; } } return securityReviewAuditResponse ; } | Reusable method for constructing the CodeQualityAuditResponse object |
22,847 | public Map < String , List < CloudInstance > > getCloudInstances ( CloudInstanceRepository repository ) { DescribeInstancesResult instanceResult ; if ( null == settings . getFilters ( ) || settings . getFilters ( ) . isEmpty ( ) ) { instanceResult = ec2Client . describeInstances ( ) ; } else { instanceResult = ec2Client . describeInstances ( buildFilterRequest ( settings . getFilters ( ) ) ) ; } DescribeAutoScalingInstancesResult autoScaleResult = autoScalingClient . describeAutoScalingInstances ( ) ; List < AutoScalingInstanceDetails > autoScalingInstanceDetails = autoScaleResult . getAutoScalingInstances ( ) ; Map < String , String > autoScaleMap = new HashMap < > ( ) ; for ( AutoScalingInstanceDetails ai : autoScalingInstanceDetails ) { autoScaleMap . put ( ai . getInstanceId ( ) , ai . getAutoScalingGroupName ( ) ) ; } Map < String , List < Instance > > ownerInstanceMap = new HashMap < > ( ) ; List < Instance > instanceList = new ArrayList < > ( ) ; List < Reservation > reservations = instanceResult . getReservations ( ) ; for ( Reservation currRes : reservations ) { List < Instance > currInstanceList = currRes . getInstances ( ) ; if ( CollectionUtils . isEmpty ( ownerInstanceMap . get ( currRes . getOwnerId ( ) ) ) ) { ownerInstanceMap . put ( currRes . getOwnerId ( ) , currRes . getInstances ( ) ) ; } else { ownerInstanceMap . get ( currRes . getOwnerId ( ) ) . addAll ( currRes . getInstances ( ) ) ; } instanceList . addAll ( currInstanceList ) ; } Map < String , List < CloudInstance > > returnList = new HashMap < > ( ) ; int i = 0 ; for ( String acct : ownerInstanceMap . keySet ( ) ) { ArrayList < CloudInstance > rawDataList = new ArrayList < > ( ) ; for ( Instance currInstance : ownerInstanceMap . get ( acct ) ) { i = i + 1 ; LOGGER . info ( "Collecting instance details for " + i + " of " + instanceList . size ( ) + ". Instance ID=" + currInstance . getInstanceId ( ) ) ; CloudInstance object = getCloudInstanceDetails ( acct , currInstance , autoScaleMap , repository ) ; rawDataList . add ( object ) ; } if ( CollectionUtils . isEmpty ( returnList . get ( acct ) ) ) { returnList . put ( acct , rawDataList ) ; } else { returnList . get ( acct ) . addAll ( rawDataList ) ; } } return returnList ; } | Calls AWS API and collects instance details . |
22,848 | private CloudInstance getCloudInstanceDetails ( String account , Instance currInstance , Map < String , String > autoScaleMap , CloudInstanceRepository repository ) { long lastUpdated = System . currentTimeMillis ( ) ; CloudInstance instance = repository . findByInstanceId ( currInstance . getInstanceId ( ) ) ; if ( instance != null ) { lastUpdated = instance . getLastUpdatedDate ( ) ; } CloudInstance object = new CloudInstance ( ) ; object . setAccountNumber ( account ) ; object . setLastUpdatedDate ( System . currentTimeMillis ( ) ) ; object . setAge ( getInstanceAge ( currInstance ) ) ; object . setCpuUtilization ( getInstanceCPUSinceLastRun ( currInstance . getInstanceId ( ) , lastUpdated ) ) ; object . setIsTagged ( isInstanceTagged ( currInstance ) ) ; object . setIsStopped ( isInstanceStopped ( currInstance ) ) ; object . setNetworkIn ( getLastHourInstanceNetworkIn ( currInstance . getInstanceId ( ) , lastUpdated ) ) ; object . setNetworkOut ( getLastHourIntanceNetworkOut ( currInstance . getInstanceId ( ) , lastUpdated ) ) ; object . setDiskRead ( getLastHourInstanceDiskRead ( currInstance . getInstanceId ( ) , lastUpdated ) ) ; object . setDiskWrite ( getLastInstanceHourDiskWrite ( currInstance . getInstanceId ( ) ) ) ; object . setImageId ( currInstance . getImageId ( ) ) ; object . setInstanceId ( currInstance . getInstanceId ( ) ) ; object . setInstanceType ( currInstance . getInstanceType ( ) ) ; object . setIsMonitored ( "enabled" . equalsIgnoreCase ( currInstance . getMonitoring ( ) . getState ( ) ) ) ; object . setPrivateDns ( currInstance . getPrivateDnsName ( ) ) ; object . setPrivateIp ( currInstance . getPrivateIpAddress ( ) ) ; object . setPublicDns ( currInstance . getPublicDnsName ( ) ) ; object . setPublicIp ( currInstance . getPublicIpAddress ( ) ) ; object . setVirtualNetworkId ( currInstance . getVpcId ( ) ) ; object . setRootDeviceName ( currInstance . getRootDeviceName ( ) ) ; object . setSubnetId ( currInstance . getSubnetId ( ) ) ; object . setAutoScaleName ( autoScaleMap . getOrDefault ( currInstance . getInstanceId ( ) , "NONE" ) ) ; object . setLastAction ( "ADD" ) ; List < Tag > tags = currInstance . getTags ( ) ; if ( ! CollectionUtils . isEmpty ( tags ) ) { for ( Tag tag : tags ) { NameValue nv = new NameValue ( tag . getKey ( ) , tag . getValue ( ) ) ; object . getTags ( ) . add ( nv ) ; } } List < GroupIdentifier > groups = currInstance . getSecurityGroups ( ) ; for ( GroupIdentifier gi : groups ) { object . addSecurityGroups ( gi . getGroupName ( ) ) ; } return object ; } | Fill out the CloudInstance object |
22,849 | public Map < String , List < CloudVolumeStorage > > getCloudVolumes ( Map < String , String > instanceToAccountMap ) { Map < String , List < CloudVolumeStorage > > returnMap = new HashMap < > ( ) ; DescribeVolumesResult volumeResult = ec2Client . describeVolumes ( ) ; for ( Volume v : volumeResult . getVolumes ( ) ) { CloudVolumeStorage object = new CloudVolumeStorage ( ) ; for ( VolumeAttachment va : v . getAttachments ( ) ) { object . getAttachInstances ( ) . add ( va . getInstanceId ( ) ) ; } String account = NO_ACCOUNT ; if ( ! CollectionUtils . isEmpty ( object . getAttachInstances ( ) ) && ! StringUtils . isEmpty ( instanceToAccountMap . get ( object . getAttachInstances ( ) . get ( 0 ) ) ) ) { account = instanceToAccountMap . get ( object . getAttachInstances ( ) . get ( 0 ) ) ; } object . setAccountNumber ( account ) ; object . setZone ( v . getAvailabilityZone ( ) ) ; object . setAccountNumber ( account ) ; object . setCreationDate ( v . getCreateTime ( ) . getTime ( ) ) ; object . setEncrypted ( v . isEncrypted ( ) ) ; object . setSize ( v . getSize ( ) ) ; object . setStatus ( v . getState ( ) ) ; object . setType ( v . getVolumeType ( ) ) ; object . setVolumeId ( v . getVolumeId ( ) ) ; List < Tag > tags = v . getTags ( ) ; if ( ! CollectionUtils . isEmpty ( tags ) ) { for ( Tag tag : tags ) { NameValue nv = new NameValue ( tag . getKey ( ) , tag . getValue ( ) ) ; object . getTags ( ) . add ( nv ) ; } } if ( CollectionUtils . isEmpty ( returnMap . get ( object . getAccountNumber ( ) ) ) ) { List < CloudVolumeStorage > temp = new ArrayList < > ( ) ; temp . add ( object ) ; returnMap . put ( account , temp ) ; } else { returnMap . get ( account ) . add ( object ) ; } } return returnMap ; } | Returns a map of account number of list of volumes associated with the account |
22,850 | private Double fetchBuildSuccessRatio ( Iterable < Build > builds ) { int totalBuilds = 0 , totalSuccess = 0 ; for ( Build build : builds ) { if ( Constants . IGNORE_STATUS . contains ( build . getBuildStatus ( ) ) ) { continue ; } totalBuilds ++ ; if ( Constants . SUCCESS_STATUS . contains ( build . getBuildStatus ( ) ) ) { totalSuccess ++ ; } } if ( totalBuilds == 0 ) { return 0.0d ; } return ( ( totalSuccess * 100 ) / ( double ) totalBuilds ) ; } | Calculate percentage of successful builds Any build with status InProgress Aborted is excluded from calculation Builds with status as Success Unstable is included as success build |
22,851 | private Double fetchBuildDurationWithinThresholdRatio ( Iterable < Build > builds , long thresholdInMillis ) { int totalBuilds = 0 , totalBelowThreshold = 0 ; for ( Build build : builds ) { if ( ! Constants . SUCCESS_STATUS . contains ( build . getBuildStatus ( ) ) ) { continue ; } totalBuilds ++ ; if ( build . getDuration ( ) < thresholdInMillis ) { totalBelowThreshold ++ ; } } if ( totalBuilds == 0 ) { return 0.0d ; } return ( ( totalBelowThreshold * 100 ) / ( double ) totalBuilds ) ; } | Calculate builds that completed successfully within threshold time Only builds with status as Success Unstable is included for calculation |
22,852 | private String getItemType ( Cmdb cmdb ) { String itemType = null ; String subType = cmdb . getConfigurationItemSubType ( ) ; String type = cmdb . getConfigurationItemType ( ) ; String hpsmSettingsSubType = hpsmSettings . getAppSubType ( ) ; String hpsmSettingsType = hpsmSettings . getAppType ( ) ; boolean typeCheck = false ; boolean subTypeCheck = false ; if ( ! "" . equals ( hpsmSettingsType ) ) { typeCheck = true ; } if ( ! "" . equals ( hpsmSettingsSubType ) ) { subTypeCheck = true ; } if ( ! typeCheck && subTypeCheck ) { if ( subType != null && subType . equals ( hpsmSettings . getAppSubType ( ) ) ) { itemType = APP_TYPE ; } else if ( subType != null && subType . equals ( hpsmSettings . getCompSubType ( ) ) ) { itemType = COMPONENT_TYPE ; } else if ( subType != null && subType . equals ( hpsmSettings . getEnvSubType ( ) ) ) { itemType = ENVIRONMENT_TYPE ; } } else if ( typeCheck && ! subTypeCheck ) { if ( type != null && type . equals ( hpsmSettings . getAppType ( ) ) ) { itemType = APP_TYPE ; } else if ( type != null && type . equals ( hpsmSettings . getCompType ( ) ) ) { itemType = COMPONENT_TYPE ; } else if ( type != null && type . equals ( hpsmSettings . getEnvType ( ) ) ) { itemType = ENVIRONMENT_TYPE ; } } else { if ( subType != null && subType . equals ( hpsmSettings . getAppSubType ( ) ) && type != null && type . equals ( hpsmSettings . getAppType ( ) ) ) { itemType = APP_TYPE ; } else if ( subType != null && subType . equals ( hpsmSettings . getCompSubType ( ) ) && type != null && type . equals ( hpsmSettings . getCompType ( ) ) ) { itemType = COMPONENT_TYPE ; } else if ( subType != null && subType . equals ( hpsmSettings . getEnvSubType ( ) ) && type != null && type . equals ( hpsmSettings . getEnvType ( ) ) ) { itemType = ENVIRONMENT_TYPE ; } } return itemType ; } | Returns the type of the configuration item . |
22,853 | private void clean ( ArtifactoryCollector collector , List < ArtifactoryRepo > existingRepos ) { Set < String > serversToBeCollected = new HashSet < > ( ) ; serversToBeCollected . addAll ( collector . getArtifactoryServers ( ) ) ; List < Set < String > > repoNamesToBeCollected = new ArrayList < Set < String > > ( ) ; List < String [ ] > allRepos = new ArrayList < > ( ) ; artifactorySettings . getServers ( ) . forEach ( serverSetting -> { allRepos . add ( ( String [ ] ) getRepoAndPatternsForServ ( serverSetting . getRepoAndPatterns ( ) ) . keySet ( ) . toArray ( ) ) ; } ) ; for ( int i = 0 ; i < allRepos . size ( ) ; i ++ ) { Set < String > reposSet = new HashSet < > ( ) ; if ( allRepos . get ( i ) != null ) { reposSet . addAll ( Arrays . asList ( allRepos . get ( i ) ) ) ; } repoNamesToBeCollected . add ( reposSet ) ; } assert ( serversToBeCollected . size ( ) == repoNamesToBeCollected . size ( ) ) ; List < ArtifactoryRepo > stateChangeRepoList = new ArrayList < > ( ) ; for ( ArtifactoryRepo repo : existingRepos ) { if ( isRepoEnabledAndNotCollected ( collector , serversToBeCollected , repoNamesToBeCollected , repo ) || isRepoDisabledAndToBeCollected ( collector , serversToBeCollected , repoNamesToBeCollected , repo ) ) { repo . setEnabled ( isRepoCollected ( collector , serversToBeCollected , repoNamesToBeCollected , repo ) ) ; stateChangeRepoList . add ( repo ) ; } } if ( ! CollectionUtils . isEmpty ( stateChangeRepoList ) ) { artifactoryRepoRepository . save ( stateChangeRepoList ) ; } } | Clean up unused artifactory collector items |
22,854 | public DataResponse < List < Feature > > getStory ( ObjectId componentId , String storyNumber ) { Component component = componentRepository . findOne ( componentId ) ; if ( ( component == null ) || CollectionUtils . isEmpty ( component . getCollectorItems ( ) ) || CollectionUtils . isEmpty ( component . getCollectorItems ( ) . get ( CollectorType . AgileTool ) ) || ( component . getCollectorItems ( ) . get ( CollectorType . AgileTool ) . get ( 0 ) == null ) ) { return getEmptyLegacyDataResponse ( ) ; } CollectorItem item = component . getCollectorItems ( ) . get ( CollectorType . AgileTool ) . get ( 0 ) ; QScopeOwner team = new QScopeOwner ( "team" ) ; BooleanBuilder builder = new BooleanBuilder ( ) ; builder . and ( team . collectorItemId . eq ( item . getId ( ) ) ) ; List < Feature > story = featureRepository . getStoryByNumber ( storyNumber ) ; Collector collector = collectorRepository . findOne ( item . getCollectorId ( ) ) ; return new DataResponse < > ( story , collector . getLastExecuted ( ) ) ; } | Retrieves a single story based on a back - end story number |
22,855 | public DataResponse < List < Feature > > getRelevantStories ( ObjectId componentId , String teamId , String projectId , Optional < String > agileType ) { Component component = componentRepository . findOne ( componentId ) ; if ( ( component == null ) || CollectionUtils . isEmpty ( component . getCollectorItems ( ) ) || CollectionUtils . isEmpty ( component . getCollectorItems ( ) . get ( CollectorType . AgileTool ) ) || ( component . getCollectorItems ( ) . get ( CollectorType . AgileTool ) . get ( 0 ) == null ) ) { return getEmptyLegacyDataResponse ( ) ; } CollectorItem item = component . getCollectorItems ( ) . get ( CollectorType . AgileTool ) . get ( 0 ) ; QScopeOwner team = new QScopeOwner ( "team" ) ; BooleanBuilder builder = new BooleanBuilder ( ) ; builder . and ( team . collectorItemId . eq ( item . getId ( ) ) ) ; List < Feature > relevantStories = getFeaturesForCurrentSprints ( teamId , projectId , item . getCollectorId ( ) , agileType . isPresent ( ) ? agileType . get ( ) : null , false ) ; Collector collector = collectorRepository . findOne ( item . getCollectorId ( ) ) ; return new DataResponse < > ( relevantStories , collector . getLastExecuted ( ) ) ; } | Retrieves all stories for a given team and their current sprint |
22,856 | public DataResponse < List < Feature > > getFeatureEpicEstimates ( ObjectId componentId , String teamId , String projectId , Optional < String > agileType , Optional < String > estimateMetricType ) { Component component = componentRepository . findOne ( componentId ) ; if ( ( component == null ) || CollectionUtils . isEmpty ( component . getCollectorItems ( ) ) || CollectionUtils . isEmpty ( component . getCollectorItems ( ) . get ( CollectorType . AgileTool ) ) || ( component . getCollectorItems ( ) . get ( CollectorType . AgileTool ) . get ( 0 ) == null ) ) { return getEmptyLegacyDataResponse ( ) ; } CollectorItem item = component . getCollectorItems ( ) . get ( CollectorType . AgileTool ) . get ( 0 ) ; List < Feature > relevantFeatureEstimates = getFeaturesForCurrentSprints ( teamId , projectId , item . getCollectorId ( ) , agileType . isPresent ( ) ? agileType . get ( ) : null , true ) ; Map < String , Feature > epicIDToEpicFeatureMap = new HashMap < > ( ) ; for ( Feature tempRs : relevantFeatureEstimates ) { String epicID = tempRs . getsEpicID ( ) ; if ( StringUtils . isEmpty ( epicID ) ) continue ; Feature feature = epicIDToEpicFeatureMap . get ( epicID ) ; if ( feature == null ) { feature = new Feature ( ) ; feature . setId ( null ) ; feature . setsEpicID ( epicID ) ; feature . setsEpicNumber ( tempRs . getsEpicNumber ( ) ) ; feature . setsEpicUrl ( tempRs . getsEpicUrl ( ) ) ; feature . setsEpicName ( tempRs . getsEpicName ( ) ) ; feature . setsEpicAssetState ( tempRs . getsEpicAssetState ( ) ) ; feature . setsEstimate ( "0" ) ; epicIDToEpicFeatureMap . put ( epicID , feature ) ; } int estimate = getEstimate ( tempRs , estimateMetricType ) ; feature . setsEstimate ( String . valueOf ( Integer . valueOf ( feature . getsEstimate ( ) ) + estimate ) ) ; } if ( isEstimateTime ( estimateMetricType ) ) { for ( Feature f : epicIDToEpicFeatureMap . values ( ) ) { f . setsEstimate ( String . valueOf ( Integer . valueOf ( f . getsEstimate ( ) ) / 60 ) ) ; } } Collector collector = collectorRepository . findOne ( item . getCollectorId ( ) ) ; return new DataResponse < > ( new ArrayList < > ( epicIDToEpicFeatureMap . values ( ) ) , collector . getLastExecuted ( ) ) ; } | Retrieves all unique super features and their total sub feature estimates for a given team and their current sprint |
22,857 | public DataResponse < List < Feature > > getInProgressEstimate ( ObjectId componentId , String teamId , Optional < String > agileType , Optional < String > estimateMetricType ) { Component component = componentRepository . findOne ( componentId ) ; if ( ( component == null ) || CollectionUtils . isEmpty ( component . getCollectorItems ( ) ) || CollectionUtils . isEmpty ( component . getCollectorItems ( ) . get ( CollectorType . AgileTool ) ) || ( component . getCollectorItems ( ) . get ( CollectorType . AgileTool ) . get ( 0 ) == null ) ) { return getEmptyLegacyDataResponse ( ) ; } CollectorItem item = component . getCollectorItems ( ) . get ( CollectorType . AgileTool ) . get ( 0 ) ; SprintEstimate estimate = getSprintEstimates ( teamId , FeatureCollectorConstants . PROJECT_ID_ANY , item . getCollectorId ( ) , agileType , estimateMetricType ) ; List < Feature > list = Collections . singletonList ( new Feature ( ) ) ; list . get ( 0 ) . setsEstimate ( Integer . toString ( estimate . getInProgressEstimate ( ) ) ) ; Collector collector = collectorRepository . findOne ( item . getCollectorId ( ) ) ; return new DataResponse < > ( list , collector . getLastExecuted ( ) ) ; } | Retrieves estimate in - progress of all features in the current sprint and for the current team . |
22,858 | public DataResponse < List < Feature > > getCurrentSprintDetail ( ObjectId componentId , String teamId , String projectId , Optional < String > agileType ) { Component component = componentRepository . findOne ( componentId ) ; if ( ( component == null ) || CollectionUtils . isEmpty ( component . getCollectorItems ( ) ) || CollectionUtils . isEmpty ( component . getCollectorItems ( ) . get ( CollectorType . AgileTool ) ) || ( component . getCollectorItems ( ) . get ( CollectorType . AgileTool ) . get ( 0 ) == null ) ) { return getEmptyLegacyDataResponse ( ) ; } CollectorItem item = component . getCollectorItems ( ) . get ( CollectorType . AgileTool ) . get ( 0 ) ; List < Feature > sprintResponse = getFeaturesForCurrentSprints ( teamId , projectId , item . getCollectorId ( ) , agileType . isPresent ( ) ? agileType . get ( ) : null , true ) ; Collector collector = collectorRepository . findOne ( item . getCollectorId ( ) ) ; return new DataResponse < > ( sprintResponse , collector . getLastExecuted ( ) ) ; } | Retrieves the current sprint s detail for a given team . |
22,859 | private List < Feature > getFeaturesForCurrentSprints ( String teamId , String projectId , ObjectId collectorId , String agileType , boolean minimal ) { List < Feature > rt = new ArrayList < Feature > ( ) ; String now = getCurrentISODateTime ( ) ; if ( FeatureCollectorConstants . SPRINT_KANBAN . equalsIgnoreCase ( agileType ) ) { rt . addAll ( featureRepository . findByNullSprints ( teamId , projectId , collectorId , minimal ) ) ; rt . addAll ( featureRepository . findByUnendingSprints ( teamId , projectId , collectorId , minimal ) ) ; } else { rt . addAll ( featureRepository . findByActiveEndingSprints ( teamId , projectId , collectorId , now , minimal ) ) ; } return rt ; } | Get the features that belong to the current sprints |
22,860 | private static Audit getCodeReviewAudit ( JSONArray jsonArray , JSONArray global ) { LOGGER . info ( "NFRR Audit Collector auditing CODE_REVIEW" ) ; Audit audit = new Audit ( ) ; audit . setType ( AuditType . CODE_REVIEW ) ; Audit basicAudit ; if ( ( basicAudit = doBasicAuditCheck ( jsonArray , global , AuditType . CODE_REVIEW ) ) != null ) { return basicAudit ; } audit . setAuditStatus ( AuditStatus . OK ) ; audit . setDataStatus ( DataStatus . OK ) ; for ( Object o : jsonArray ) { JSONObject jo = ( JSONObject ) o ; audit . getUrl ( ) . add ( ( String ) jo . get ( STR_URL ) ) ; JSONArray directCommits = ( JSONArray ) jo . get ( STR_DIRECTCOMMITS ) ; if ( ! CollectionUtils . isEmpty ( directCommits ) ) { audit . setAuditStatus ( AuditStatus . FAIL ) ; audit . setDataStatus ( DataStatus . OK ) ; return audit ; } JSONArray pulls = ( JSONArray ) ( ( JSONObject ) o ) . get ( STR_PULLREQUESTS ) ; for ( Object po : pulls ) { JSONArray auditJO = ( JSONArray ) ( ( JSONObject ) po ) . get ( STR_AUDITSTATUSES ) ; boolean reviewed = false ; auditJO . stream ( ) . map ( aj -> audit . getAuditStatusCodes ( ) . add ( ( String ) aj ) ) ; for ( Object s : auditJO ) { String status = ( String ) s ; audit . getAuditStatusCodes ( ) . add ( status ) ; if ( CodeReviewAuditStatus . PEER_REVIEW_GHR . name ( ) . equalsIgnoreCase ( status ) || ( CodeReviewAuditStatus . PEER_REVIEW_LGTM_SUCCESS . name ( ) . equalsIgnoreCase ( status ) ) ) { reviewed = true ; break ; } } if ( ! reviewed ) { audit . setAuditStatus ( AuditStatus . FAIL ) ; audit . setDataStatus ( DataStatus . OK ) ; return audit ; } } } return audit ; } | Get Code Review Audit Results |
22,861 | private static Audit doBasicAuditCheck ( JSONArray jsonArray , JSONArray global , AuditType auditType ) { Audit audit = new Audit ( ) ; audit . setType ( auditType ) ; if ( ! isConfigured ( auditType , global ) ) { audit . setDataStatus ( DataStatus . NOT_CONFIGURED ) ; audit . setAuditStatus ( AuditStatus . NA ) ; return audit ; } if ( jsonArray == null || CollectionUtils . isEmpty ( jsonArray ) ) { audit . setAuditStatus ( AuditStatus . NA ) ; audit . setDataStatus ( DataStatus . NO_DATA ) ; return audit ; } if ( isCollectorError ( jsonArray ) ) { audit . setAuditStatus ( AuditStatus . NA ) ; audit . setDataStatus ( DataStatus . ERROR ) ; return audit ; } return null ; } | Do basic audit check - configuration collector error no data |
22,862 | private static boolean isCollectorError ( JSONArray jsonArray ) { Stream < JSONObject > jsonObjectStream = jsonArray . stream ( ) . map ( ( Object object ) -> ( JSONObject ) object ) ; Stream < JSONArray > auditStatusArray = jsonObjectStream . map ( jsonObject -> ( JSONArray ) jsonObject . get ( STR_AUDITSTATUSES ) ) ; return auditStatusArray . anyMatch ( aSArray -> aSArray . toJSONString ( ) . contains ( DashboardAuditStatus . COLLECTOR_ITEM_ERROR . name ( ) ) ) ; } | Check for collector error |
22,863 | @ SuppressWarnings ( "PMD.NPathComplexity" ) private static boolean isConfigured ( AuditType auditType , JSONArray jsonArray ) { if ( auditType . equals ( AuditType . CODE_REVIEW ) ) { return ( jsonArray . toJSONString ( ) . contains ( DashboardAuditStatus . DASHBOARD_REPO_CONFIGURED . name ( ) ) ? true : false ) ; } if ( auditType . equals ( AuditType . CODE_QUALITY ) ) { return ( jsonArray . toJSONString ( ) . contains ( DashboardAuditStatus . DASHBOARD_CODEQUALITY_CONFIGURED . name ( ) ) ? true : false ) ; } if ( auditType . equals ( AuditType . STATIC_SECURITY_ANALYSIS ) ) { return ( jsonArray . toJSONString ( ) . contains ( DashboardAuditStatus . DASHBOARD_STATIC_SECURITY_ANALYSIS_CONFIGURED . name ( ) ) ? true : false ) ; } if ( auditType . equals ( AuditType . LIBRARY_POLICY ) ) { return ( jsonArray . toJSONString ( ) . contains ( DashboardAuditStatus . DASHBOARD_LIBRARY_POLICY_ANALYSIS_CONFIGURED . name ( ) ) ? true : false ) ; } if ( auditType . equals ( AuditType . TEST_RESULT ) ) { return ( jsonArray . toJSONString ( ) . contains ( DashboardAuditStatus . DASHBOARD_TEST_CONFIGURED . name ( ) ) ? true : false ) ; } if ( auditType . equals ( AuditType . PERF_TEST ) ) { return ( jsonArray . toJSONString ( ) . contains ( DashboardAuditStatus . DASHBOARD_PERFORMANCE_TEST_CONFIGURED . name ( ) ) ? true : false ) ; } if ( auditType . equals ( AuditType . BUILD_REVIEW ) ) { return ( jsonArray . toJSONString ( ) . contains ( DashboardAuditStatus . DASHBOARD_BUILD_CONFIGURED . name ( ) ) ? true : false ) ; } return false ; } | Check for dashboard audit type configuration |
22,864 | private static Audit getCodeQualityAudit ( JSONArray jsonArray , JSONArray global ) { LOGGER . info ( "NFRR Audit Collector auditing CODE_QUALITY" ) ; Audit audit = new Audit ( ) ; audit . setType ( AuditType . CODE_QUALITY ) ; Audit basicAudit ; if ( ( basicAudit = doBasicAuditCheck ( jsonArray , global , AuditType . CODE_QUALITY ) ) != null ) { return basicAudit ; } audit . setAuditStatus ( AuditStatus . OK ) ; audit . setDataStatus ( DataStatus . OK ) ; for ( Object o : jsonArray ) { Optional < Object > urlOptObj = Optional . ofNullable ( ( ( JSONObject ) o ) . get ( STR_URL ) ) ; urlOptObj . ifPresent ( urlObj -> audit . getUrl ( ) . add ( urlOptObj . get ( ) . toString ( ) ) ) ; JSONArray auditJO = ( JSONArray ) ( ( JSONObject ) o ) . get ( STR_AUDITSTATUSES ) ; auditJO . stream ( ) . map ( aj -> audit . getAuditStatusCodes ( ) . add ( ( String ) aj ) ) ; boolean ok = false ; for ( Object s : auditJO ) { String status = ( String ) s ; audit . getAuditStatusCodes ( ) . add ( status ) ; if ( CodeQualityAuditStatus . CODE_QUALITY_AUDIT_OK . name ( ) . equalsIgnoreCase ( status ) ) { ok = true ; break ; } if ( CodeQualityAuditStatus . CODE_QUALITY_DETAIL_MISSING . name ( ) . equalsIgnoreCase ( status ) ) { audit . setAuditStatus ( AuditStatus . NA ) ; audit . setDataStatus ( DataStatus . NO_DATA ) ; return audit ; } } if ( ! ok ) { audit . setAuditStatus ( AuditStatus . FAIL ) ; return audit ; } } return audit ; } | Get code quality audit results |
22,865 | private static Audit getSecurityAudit ( JSONArray jsonArray , JSONArray global ) { LOGGER . info ( "NFRR Audit Collector auditing STATIC_SECURITY_ANALYSIS" ) ; Audit audit = new Audit ( ) ; audit . setType ( AuditType . STATIC_SECURITY_ANALYSIS ) ; Audit basicAudit ; if ( ( basicAudit = doBasicAuditCheck ( jsonArray , global , AuditType . STATIC_SECURITY_ANALYSIS ) ) != null ) { return basicAudit ; } Set < String > auditStatuses ; for ( Object o : jsonArray ) { JSONArray auditJO = ( JSONArray ) ( ( JSONObject ) o ) . get ( STR_AUDITSTATUSES ) ; Optional < Object > urlOptObj = Optional . ofNullable ( ( ( JSONObject ) o ) . get ( STR_URL ) ) ; urlOptObj . ifPresent ( urlObj -> audit . getUrl ( ) . add ( urlOptObj . get ( ) . toString ( ) ) ) ; auditJO . stream ( ) . forEach ( status -> audit . getAuditStatusCodes ( ) . add ( ( String ) status ) ) ; } auditStatuses = audit . getAuditStatusCodes ( ) ; if ( auditStatuses . contains ( CodeQualityAuditStatus . STATIC_SECURITY_SCAN_FAIL . name ( ) ) || auditStatuses . contains ( CodeQualityAuditStatus . STATIC_SECURITY_SCAN_FOUND_HIGH . name ( ) ) || auditStatuses . contains ( CodeQualityAuditStatus . STATIC_SECURITY_SCAN_FOUND_CRITICAL . name ( ) ) ) { audit . setAuditStatus ( AuditStatus . FAIL ) ; audit . setDataStatus ( DataStatus . OK ) ; } else if ( auditStatuses . contains ( CodeQualityAuditStatus . STATIC_SECURITY_SCAN_OK . name ( ) ) ) { audit . setAuditStatus ( AuditStatus . OK ) ; audit . setDataStatus ( DataStatus . OK ) ; } else { audit . setAuditStatus ( AuditStatus . NA ) ; audit . setDataStatus ( DataStatus . NO_DATA ) ; } return audit ; } | Get security audit results |
22,866 | private static Audit getOSSAudit ( JSONArray jsonArray , JSONArray global ) { LOGGER . info ( "NFRR Audit Collector auditing LIBRARY_POLICY" ) ; Audit audit = new Audit ( ) ; audit . setType ( AuditType . LIBRARY_POLICY ) ; Audit basicAudit ; if ( ( basicAudit = doBasicAuditCheck ( jsonArray , global , AuditType . LIBRARY_POLICY ) ) != null ) { return basicAudit ; } audit . setAuditStatus ( AuditStatus . OK ) ; audit . setDataStatus ( DataStatus . OK ) ; for ( Object o : jsonArray ) { JSONArray auditJO = ( JSONArray ) ( ( JSONObject ) o ) . get ( STR_AUDITSTATUSES ) ; Optional < Object > lpOptObj = Optional . ofNullable ( ( ( JSONObject ) o ) . get ( STR_LIBRARYPOLICYRESULT ) ) ; lpOptObj . ifPresent ( lpObj -> audit . getUrl ( ) . add ( ( ( JSONObject ) lpOptObj . get ( ) ) . get ( STR_REPORTURL ) . toString ( ) ) ) ; auditJO . stream ( ) . map ( aj -> audit . getAuditStatusCodes ( ) . add ( ( String ) aj ) ) ; boolean ok = false ; for ( Object s : auditJO ) { String status = ( String ) s ; audit . getAuditStatusCodes ( ) . add ( status ) ; if ( LibraryPolicyAuditStatus . LIBRARY_POLICY_AUDIT_OK . name ( ) . equalsIgnoreCase ( status ) ) { ok = true ; break ; } if ( LibraryPolicyAuditStatus . LIBRARY_POLICY_AUDIT_MISSING . name ( ) . equalsIgnoreCase ( status ) ) { audit . setAuditStatus ( AuditStatus . NA ) ; audit . setDataStatus ( DataStatus . NO_DATA ) ; return audit ; } } if ( ! ok ) { audit . setAuditStatus ( AuditStatus . FAIL ) ; return audit ; } } return audit ; } | Get library policy audit results |
22,867 | @ SuppressWarnings ( "PMD" ) public static Map < AuditType , Audit > getAudit ( Dashboard dashboard , AuditSettings settings , long begin , long end ) { Map < AuditType , Audit > audits = new HashMap < > ( ) ; String url = getAuditAPIUrl ( dashboard , settings , begin , end ) ; JSONObject auditResponseObj = parseObject ( url , settings ) ; if ( auditResponseObj == null ) { return audits ; } JSONArray globalStatus = ( JSONArray ) auditResponseObj . get ( STR_AUDITSTATUSES ) ; JSONObject review = ( JSONObject ) auditResponseObj . get ( STR_REVIEW ) ; JSONArray codeReviewJO = review . get ( AuditType . CODE_REVIEW . name ( ) ) == null ? null : ( JSONArray ) review . get ( AuditType . CODE_REVIEW . name ( ) ) ; Audit audit = getCodeReviewAudit ( codeReviewJO , globalStatus ) ; audits . put ( audit . getType ( ) , audit ) ; JSONArray scaJO = review . get ( AuditType . CODE_QUALITY . name ( ) ) == null ? null : ( JSONArray ) review . get ( AuditType . CODE_QUALITY . name ( ) ) ; audit = getCodeQualityAudit ( scaJO , globalStatus ) ; audits . put ( audit . getType ( ) , audit ) ; JSONArray perfJO = review . get ( AuditType . PERF_TEST . name ( ) ) == null ? null : ( JSONArray ) review . get ( AuditType . PERF_TEST . name ( ) ) ; audit = getPerfAudit ( perfJO , globalStatus ) ; audits . put ( audit . getType ( ) , audit ) ; JSONArray ossJO = review . get ( AuditType . LIBRARY_POLICY . name ( ) ) == null ? null : ( JSONArray ) review . get ( AuditType . LIBRARY_POLICY . name ( ) ) ; audit = getOSSAudit ( ossJO , globalStatus ) ; audits . put ( audit . getType ( ) , audit ) ; JSONArray testJO = review . get ( AuditType . TEST_RESULT . name ( ) ) == null ? null : ( JSONArray ) review . get ( AuditType . TEST_RESULT . name ( ) ) ; audit = getTestAudit ( testJO , globalStatus ) ; audits . put ( audit . getType ( ) , audit ) ; JSONArray sscaJO = review . get ( AuditType . STATIC_SECURITY_ANALYSIS . name ( ) ) == null ? null : ( JSONArray ) review . get ( AuditType . STATIC_SECURITY_ANALYSIS . name ( ) ) ; audit = getSecurityAudit ( sscaJO , globalStatus ) ; audits . put ( audit . getType ( ) , audit ) ; return audits ; } | Get all audit results |
22,868 | protected static JSONObject parseObject ( String url , AuditSettings settings ) { LOGGER . info ( "NFRR Audit Collector Audit API Call" ) ; RestTemplate restTemplate = new RestTemplate ( ) ; JSONObject responseObj = null ; try { ResponseEntity < String > response = restTemplate . exchange ( url , HttpMethod . GET , getHeaders ( settings ) , String . class ) ; JSONParser jsonParser = new JSONParser ( ) ; responseObj = ( JSONObject ) jsonParser . parse ( response . getBody ( ) ) ; } catch ( Exception e ) { LOGGER . error ( "Error while calling audit api for the params : " + url . substring ( url . lastIndexOf ( "?" ) ) , e ) ; } return responseObj ; } | Make audit api rest call and parse response |
22,869 | protected static String getAuditAPIUrl ( Dashboard dashboard , AuditSettings settings , long beginDate , long endDate ) { LOGGER . info ( "NFRR Audit Collector creates Audit API URL" ) ; if ( CollectionUtils . isEmpty ( settings . getServers ( ) ) ) { LOGGER . error ( "No Server Found to run NoFearRelease audit collector" ) ; throw new MBeanServerNotFoundException ( "No Server Found to run NoFearRelease audit collector" ) ; } URIBuilder auditURI = new URIBuilder ( ) ; auditURI . setPath ( settings . getServers ( ) . get ( 0 ) + HYGIEIA_AUDIT_URL ) ; auditURI . addParameter ( AUDIT_PARAMS . title . name ( ) , dashboard . getTitle ( ) ) ; auditURI . addParameter ( AUDIT_PARAMS . businessService . name ( ) , dashboard . getConfigurationItemBusServName ( ) ) ; auditURI . addParameter ( AUDIT_PARAMS . businessApplication . name ( ) , dashboard . getConfigurationItemBusAppName ( ) ) ; auditURI . addParameter ( AUDIT_PARAMS . beginDate . name ( ) , String . valueOf ( beginDate ) ) ; auditURI . addParameter ( AUDIT_PARAMS . endDate . name ( ) , String . valueOf ( endDate ) ) ; auditURI . addParameter ( AUDIT_PARAMS . auditType . name ( ) , "" ) ; String auditURIStr = auditURI . toString ( ) . replace ( "+" , " " ) ; return auditURIStr + AUDITTYPES_PARAM ; } | Construct audit api url |
22,870 | protected static HttpEntity getHeaders ( AuditSettings auditSettings ) { HttpHeaders headers = new HttpHeaders ( ) ; if ( ! CollectionUtils . isEmpty ( auditSettings . getUsernames ( ) ) && ! CollectionUtils . isEmpty ( auditSettings . getApiKeys ( ) ) ) { headers . set ( STR_APIUSER , auditSettings . getUsernames ( ) . iterator ( ) . next ( ) ) ; headers . set ( STR_AUTHORIZATION , STR_APITOKENSPACE + auditSettings . getApiKeys ( ) . iterator ( ) . next ( ) ) ; } return new HttpEntity < > ( headers ) ; } | Get api authentication headers |
22,871 | @ SuppressWarnings ( "PMD.NPathComplexity" ) public static void addAuditResultByAuditType ( Dashboard dashboard , Map < AuditType , Audit > auditMap , CmdbRepository cmdbRepository , long timestamp ) { if ( CollectionUtils . isEmpty ( auditMap ) ) { return ; } Cmdb cmdb = cmdbRepository . findByConfigurationItem ( dashboard . getConfigurationItemBusServName ( ) ) ; ObjectId dashboardId = dashboard . getId ( ) ; String dashboardTitle = dashboard . getTitle ( ) ; String ownerDept = ( ( cmdb == null || cmdb . getOwnerDept ( ) == null ) ? "" : cmdb . getOwnerDept ( ) ) ; String appService = ( dashboard . getConfigurationItemBusServName ( ) == null ? "" : dashboard . getConfigurationItemBusServName ( ) ) ; String appBusApp = ( dashboard . getConfigurationItemBusAppName ( ) == null ? "" : dashboard . getConfigurationItemBusAppName ( ) ) ; String appServiceOwner = ( ( cmdb == null || cmdb . getAppServiceOwner ( ) == null ) ? "" : cmdb . getAppServiceOwner ( ) ) ; String appBusAppOwner = ( ( cmdb == null || cmdb . getBusinessOwner ( ) == null ) ? "" : cmdb . getBusinessOwner ( ) ) ; Arrays . stream ( AuditType . values ( ) ) . forEach ( ( AuditType auditType ) -> { if ( ! ( auditType . equals ( AuditType . ALL ) || auditType . equals ( AuditType . BUILD_REVIEW ) ) ) { Audit audit = auditMap . get ( auditType ) ; AuditResult auditResult = new AuditResult ( dashboardId , dashboardTitle , ownerDept , appService , appBusApp , appServiceOwner , appBusAppOwner , auditType , audit . getDataStatus ( ) . name ( ) , audit . getAuditStatus ( ) . name ( ) , String . join ( "," , audit . getAuditStatusCodes ( ) ) , String . join ( "," , audit . getUrl ( ) ) , timestamp ) ; auditResult . setOptions ( audit . getOptions ( ) != null ? audit . getOptions ( ) : null ) ; auditResults . add ( auditResult ) ; } } ) ; } | Add audit result by audit type |
22,872 | private Double fetchDeploySuccessRatio ( ObjectId collectorItemId ) { int totalDeploys = 0 , totalDeploySuccess = 0 ; Double deploySuccessScore = null ; List < EnvironmentComponent > components = environmentComponentRepository . findByCollectorItemId ( collectorItemId ) ; if ( null == components || components . isEmpty ( ) ) { return null ; } for ( EnvironmentComponent environmentComponent : components ) { totalDeploys ++ ; if ( environmentComponent . isDeployed ( ) ) { totalDeploySuccess ++ ; } } deploySuccessScore = ( ( totalDeploySuccess * 100 ) / ( double ) totalDeploys ) ; LOGGER . info ( "totalDeploys " + totalDeploys + " totalDeploySuccess " + totalDeploySuccess + " deploySuccessScore " + deploySuccessScore ) ; return deploySuccessScore ; } | Calculate percentage of successfully deployed components |
22,873 | private Double fetchInstancesOnlineRatio ( ObjectId collectorItemId ) { int totalInstances = 0 , totalInstancesOnline = 0 ; Double instancesOnlineScore = null ; List < EnvironmentStatus > statuses = environmentStatusRepository . findByCollectorItemId ( collectorItemId ) ; if ( null == statuses || statuses . isEmpty ( ) ) { return null ; } for ( EnvironmentStatus environmentStatus : statuses ) { totalInstances ++ ; if ( environmentStatus . isOnline ( ) ) { totalInstancesOnline ++ ; } } instancesOnlineScore = ( ( totalInstancesOnline * 100 ) / ( double ) totalInstances ) ; LOGGER . info ( "totalInstances " + totalInstances + " totalInstancesOnline " + totalInstancesOnline + " instancesOnlineScore " + instancesOnlineScore ) ; return instancesOnlineScore ; } | Calculate percentage of instances online |
22,874 | private String getReportURL ( String projectUrl , String path , String projectId ) { StringBuilder sb = new StringBuilder ( projectUrl ) ; if ( ! projectUrl . endsWith ( "/" ) ) { sb . append ( "/" ) ; } sb . append ( path ) . append ( projectId ) ; return sb . toString ( ) ; } | get projectUrl and projectId from collectorItem and form reportUrl |
22,875 | public void visit ( JunitXmlReport report ) { int testsPassed = report . getTests ( ) - report . getFailures ( ) - report . getErrors ( ) ; Map < String , Pair < Integer , CodeQualityMetricStatus > > metricsMap = new HashMap < > ( ) ; metricsMap . put ( TOTAL_NO_OF_TESTS , Pair . of ( report . getTests ( ) , CodeQualityMetricStatus . Ok ) ) ; metricsMap . put ( TEST_FAILURES , Pair . of ( report . getFailures ( ) , report . getFailures ( ) > 0 ? CodeQualityMetricStatus . Warning : CodeQualityMetricStatus . Ok ) ) ; metricsMap . put ( TEST_ERRORS , Pair . of ( report . getErrors ( ) , report . getErrors ( ) > 0 ? CodeQualityMetricStatus . Alert : CodeQualityMetricStatus . Ok ) ) ; metricsMap . put ( TEST_SUCCESS_DENSITY , Pair . of ( testsPassed , CodeQualityMetricStatus . Ok ) ) ; if ( null != report . getTimestamp ( ) ) { long timestamp = Math . max ( quality . getTimestamp ( ) , report . getTimestamp ( ) . toGregorianCalendar ( ) . getTimeInMillis ( ) ) ; quality . setTimestamp ( timestamp ) ; } quality . setType ( CodeQualityType . StaticAnalysis ) ; this . sumMetrics ( metricsMap ) ; } | function tests .. |
22,876 | @ SuppressWarnings ( "PMD.AvoidDeeplyNestedIfStmts" ) private void clean ( RallyCollector collector , List < RallyProject > existingProjects ) { Set < ObjectId > uniqueIDs = new HashSet < > ( ) ; for ( com . capitalone . dashboard . model . Component comp : dbComponentRepository . findAll ( ) ) { if ( comp . getCollectorItems ( ) != null && ! comp . getCollectorItems ( ) . isEmpty ( ) ) { List < CollectorItem > itemList = comp . getCollectorItems ( ) . get ( CollectorType . AgileTool ) ; if ( itemList != null ) { for ( CollectorItem ci : itemList ) { if ( ci != null && ci . getCollectorId ( ) . equals ( collector . getId ( ) ) ) { uniqueIDs . add ( ci . getId ( ) ) ; } } } } } List < RallyProject > stateChangeJobList = new ArrayList < > ( ) ; Set < ObjectId > udId = new HashSet < > ( ) ; udId . add ( collector . getId ( ) ) ; for ( RallyProject job : existingProjects ) { if ( ( job . isEnabled ( ) && ! uniqueIDs . contains ( job . getId ( ) ) ) || ( ! job . isEnabled ( ) && uniqueIDs . contains ( job . getId ( ) ) ) ) { job . setEnabled ( uniqueIDs . contains ( job . getId ( ) ) ) ; stateChangeJobList . add ( job ) ; } } if ( ! CollectionUtils . isEmpty ( stateChangeJobList ) ) { rallyProjectRepository . save ( stateChangeJobList ) ; } } | Clean up unused rally collector items |
22,877 | public static String getChangeDateMinutePrior ( String changeDateISO , int priorMinutes ) { return DateUtil . toISODateRealTimeFormat ( DateUtil . getDatePriorToMinutes ( DateUtil . fromISODateTimeFormat ( changeDateISO ) , priorMinutes ) ) ; } | Generates and retrieves the change date that occurs a minute prior to the specified change date in ISO format . |
22,878 | public boolean evaluateSprintLength ( String startDate , String endDate , int maxKanbanIterationLength ) { boolean sprintIndicator = false ; Calendar startCalendar = Calendar . getInstance ( ) ; Calendar endCalendar = Calendar . getInstance ( ) ; if ( ! StringUtils . isAnyEmpty ( startDate ) && ! StringUtils . isAnyEmpty ( endDate ) ) { Date strDt = convertIntoDate ( startDate . substring ( 0 , 4 ) + "-" + startDate . substring ( 5 , 7 ) + "-" + startDate . substring ( 8 , 10 ) , "yyyy-MM-dd" ) ; Date endDt = convertIntoDate ( endDate . substring ( 0 , 4 ) + "-" + endDate . substring ( 5 , 7 ) + "-" + endDate . substring ( 8 , 10 ) , "yyyy-MM-dd" ) ; if ( strDt != null && endDate != null ) { startCalendar . setTime ( strDt ) ; endCalendar . setTime ( endDt ) ; long diffMill = endCalendar . getTimeInMillis ( ) - startCalendar . getTimeInMillis ( ) ; long diffDays = TimeUnit . DAYS . convert ( diffMill , TimeUnit . MILLISECONDS ) ; if ( diffDays <= maxKanbanIterationLength ) { sprintIndicator = true ; } } } else { sprintIndicator = false ; } return sprintIndicator ; } | Evaluates whether a sprint length appears to be kanban or scrum |
22,879 | private boolean isInteger ( String s , int radix ) { Scanner sc = new Scanner ( s . trim ( ) ) ; if ( ! sc . hasNextInt ( radix ) ) return false ; sc . nextInt ( radix ) ; return ! sc . hasNext ( ) ; } | Determines if string is an integer of the radix base number system provided . |
22,880 | private LibraryPolicyAuditResponse getLibraryPolicyAuditResponse ( CollectorItem collectorItem , long beginDate , long endDate ) { List < LibraryPolicyResult > libraryPolicyResults = libraryPolicyResultsRepository . findByCollectorItemIdAndEvaluationTimestampIsBetweenOrderByTimestampDesc ( collectorItem . getId ( ) , beginDate - 1 , endDate + 1 ) ; LibraryPolicyAuditResponse libraryPolicyAuditResponse = new LibraryPolicyAuditResponse ( ) ; if ( CollectionUtils . isEmpty ( libraryPolicyResults ) ) { libraryPolicyAuditResponse . addAuditStatus ( LibraryPolicyAuditStatus . LIBRARY_POLICY_AUDIT_MISSING ) ; return libraryPolicyAuditResponse ; } LibraryPolicyResult returnPolicyResult = libraryPolicyResults . get ( 0 ) ; libraryPolicyAuditResponse . setLibraryPolicyResult ( returnPolicyResult ) ; libraryPolicyAuditResponse . setLastExecutionTime ( returnPolicyResult . getEvaluationTimestamp ( ) ) ; Set < LibraryPolicyResult . Threat > securityThreats = ! MapUtils . isEmpty ( returnPolicyResult . getThreats ( ) ) ? returnPolicyResult . getThreats ( ) . get ( LibraryPolicyType . Security ) : SetUtils . EMPTY_SET ; Set < LibraryPolicyResult . Threat > licenseThreats = ! MapUtils . isEmpty ( returnPolicyResult . getThreats ( ) ) ? returnPolicyResult . getThreats ( ) . get ( LibraryPolicyType . License ) : SetUtils . EMPTY_SET ; boolean isOk = true ; if ( licenseThreats . stream ( ) . anyMatch ( threat -> Objects . equals ( threat . getLevel ( ) , LibraryPolicyThreatLevel . Critical ) && hasViolations ( threat ) ) ) { libraryPolicyAuditResponse . addAuditStatus ( LibraryPolicyAuditStatus . LIBRARY_POLICY_FOUND_CRITICAL_LICENSE ) ; isOk = false ; } if ( licenseThreats . stream ( ) . anyMatch ( threat -> Objects . equals ( threat . getLevel ( ) , LibraryPolicyThreatLevel . High ) && hasViolations ( threat ) ) ) { libraryPolicyAuditResponse . addAuditStatus ( LibraryPolicyAuditStatus . LIBRARY_POLICY_FOUND_HIGH_LICENSE ) ; isOk = false ; } if ( securityThreats . stream ( ) . anyMatch ( threat -> Objects . equals ( threat . getLevel ( ) , LibraryPolicyThreatLevel . Critical ) && hasViolations ( threat ) ) ) { libraryPolicyAuditResponse . addAuditStatus ( LibraryPolicyAuditStatus . LIBRARY_POLICY_FOUND_CRITICAL_SECURITY ) ; isOk = false ; } if ( securityThreats . stream ( ) . anyMatch ( threat -> Objects . equals ( threat . getLevel ( ) , LibraryPolicyThreatLevel . High ) && hasViolations ( threat ) ) ) { libraryPolicyAuditResponse . addAuditStatus ( LibraryPolicyAuditStatus . LIBRARY_POLICY_FOUND_HIGH_SECURITY ) ; isOk = false ; } if ( isOk ) { libraryPolicyAuditResponse . addAuditStatus ( LibraryPolicyAuditStatus . LIBRARY_POLICY_AUDIT_OK ) ; } return libraryPolicyAuditResponse ; } | Reusable method for constructing the LibraryPolicyAuditResponse object |
22,881 | private V1Connector versionOneAuthentication ( Map < String , String > auth ) throws HygieiaException { V1Connector connector ; try { if ( ! StringUtils . isEmpty ( auth . get ( "v1ProxyUrl" ) ) ) { ProxyProvider proxyProvider = new ProxyProvider ( new URI ( auth . get ( "v1ProxyUrl" ) ) , "" , "" ) ; connector = V1Connector . withInstanceUrl ( auth . get ( "v1BaseUri" ) ) . withUserAgentHeader ( FeatureCollectorConstants . AGENT_NAME , FeatureCollectorConstants . AGENT_VER ) . withAccessToken ( auth . get ( "v1AccessToken" ) ) . withProxy ( proxyProvider ) . build ( ) ; } else { connector = V1Connector . withInstanceUrl ( auth . get ( "v1BaseUri" ) ) . withUserAgentHeader ( FeatureCollectorConstants . AGENT_NAME , FeatureCollectorConstants . AGENT_VER ) . withAccessToken ( auth . get ( "v1AccessToken" ) ) . build ( ) ; } } catch ( V1Exception ve ) { throw new HygieiaException ( "FAILED: VersionOne was not able to authenticate" , ve , HygieiaException . INVALID_CONFIGURATION ) ; } catch ( MalformedURLException | URISyntaxException me ) { throw new HygieiaException ( "FAILED: Invalid VersionOne URL." , me , HygieiaException . INVALID_CONFIGURATION ) ; } return connector ; } | Used for establishing connection to VersionOne based on authentication |
22,882 | public String buildPagingQuery ( int inPageIndex ) { this . setPageIndex ( inPageIndex ) ; String pageFilter = "\npage:\n" + " size: " + pageSize + "\n" + " start: " + pageIndex ; this . setPagingQuery ( this . getBasicQuery ( ) + pageFilter ) ; return this . getPagingQuery ( ) ; } | Creates a query on demand based on a given basic query and a specified page index value . It is recommended to use this method in a loop to ensure all pages are covered . |
22,883 | public JSONArray getPagingQueryResponse ( ) throws HygieiaException { synchronized ( this . v1Service ) { Object obj = this . v1Service . executePassThroughQuery ( this . getPagingQuery ( ) ) ; if ( obj == null ) { throw new HygieiaException ( "FAILED: There was a problem parsing or casting JSON types from a message response" , HygieiaException . JSON_FORMAT_ERROR ) ; } if ( obj . toString ( ) . equalsIgnoreCase ( "{\"error\":\"Unauthorized\"}" ) ) { throw new HygieiaException ( "FAILED: There was a problem authenticating with VersionOne" , HygieiaException . INVALID_CONFIGURATION ) ; } return makeJsonOutputArray ( obj . toString ( ) ) ; } } | Runs the VersionOneConnection library tools against a given YAML - formatted query . This requires a pre - formatted paged query to run and will not perform the paging for you - there are other helper methods for this . |
22,884 | private JSONArray makeJsonOutputArray ( String stringResult ) { JSONParser parser = new JSONParser ( ) ; try { return ( JSONArray ) parser . parse ( stringResult ) ; } catch ( ParseException | ClassCastException e ) { LOGGER . error ( "There was a problem parsing the JSONArray response value from the source system:\n" + e . getMessage ( ) + " | " + e . getCause ( ) ) ; return new JSONArray ( ) ; } } | Mutator method for JSON response output array . |
22,885 | public FeatureCollector getCollector ( ) { JiraMode mode = featureSettings . isJiraBoardAsTeam ( ) ? JiraMode . Board : JiraMode . Team ; FeatureCollector collector = FeatureCollector . prototype ( mode ) ; FeatureCollector existing = featureCollectorRepository . findByName ( collector . getName ( ) ) ; if ( existing != null ) { collector . setLastRefreshTime ( existing . getLastRefreshTime ( ) ) ; } return collector ; } | Accessor method for the collector prototype object |
22,886 | protected List < Team > updateTeamInformation ( FeatureCollector collector ) { long projectDataStart = System . currentTimeMillis ( ) ; List < Team > teams = featureSettings . isJiraBoardAsTeam ( ) ? jiraClient . getBoards ( ) : jiraClient . getTeams ( ) ; teams . forEach ( newTeam -> { String teamId = newTeam . getTeamId ( ) ; newTeam . setCollectorId ( collector . getId ( ) ) ; LOGGER . info ( String . format ( "Adding %s:%s-%s" , collector . getMode ( ) , teamId , newTeam . getName ( ) ) ) ; Team existing = teamRepository . findByTeamId ( teamId ) ; if ( existing == null ) { teamRepository . save ( newTeam ) ; } else { newTeam . setId ( existing . getId ( ) ) ; teamRepository . save ( newTeam ) ; } } ) ; log ( collector . getMode ( ) + " Data Collected. Added " , projectDataStart , teams . size ( ) ) ; projectDataStart = System . currentTimeMillis ( ) ; List < Team > existingTeams = teamRepository . findByCollectorId ( collector . getId ( ) ) ; Set < String > newTeamIds = teams . stream ( ) . map ( Team :: getTeamId ) . collect ( Collectors . toSet ( ) ) ; Set < Team > toDelete = existingTeams . stream ( ) . filter ( e -> ! newTeamIds . contains ( e . getTeamId ( ) ) ) . collect ( Collectors . toSet ( ) ) ; if ( ! CollectionUtils . isEmpty ( toDelete ) ) { toDelete . forEach ( td -> { LOGGER . info ( String . format ( "Deleting %s:%s-%s" , collector . getMode ( ) , td . getTeamId ( ) , td . getName ( ) ) ) ; } ) ; teamRepository . delete ( toDelete ) ; log ( collector . getMode ( ) + " Data Collected. Deleted " , projectDataStart , toDelete . size ( ) ) ; } return teams ; } | Update team information |
22,887 | protected Set < Scope > updateProjectInformation ( Collector collector ) { long projectDataStart = System . currentTimeMillis ( ) ; Set < Scope > projects = jiraClient . getProjects ( ) ; projects . forEach ( jiraScope -> { LOGGER . info ( String . format ( "Adding :%s-%s" , jiraScope . getpId ( ) , jiraScope . getName ( ) ) ) ; jiraScope . setCollectorId ( collector . getId ( ) ) ; Scope existing = projectRepository . findByCollectorIdAndPId ( collector . getId ( ) , jiraScope . getpId ( ) ) ; if ( existing == null ) { projectRepository . save ( jiraScope ) ; } else { jiraScope . setId ( existing . getId ( ) ) ; projectRepository . save ( jiraScope ) ; } } ) ; log ( "Project Data Collected" , projectDataStart , projects . size ( ) ) ; List < Scope > existingProjects = projectRepository . findByCollectorId ( collector . getId ( ) ) ; Set < String > newProjectIds = projects . stream ( ) . map ( Scope :: getpId ) . collect ( Collectors . toSet ( ) ) ; Set < Scope > toDelete = existingProjects . stream ( ) . filter ( e -> ! newProjectIds . contains ( e . getpId ( ) ) ) . collect ( Collectors . toSet ( ) ) ; if ( ! CollectionUtils . isEmpty ( toDelete ) ) { toDelete . forEach ( td -> { LOGGER . info ( String . format ( "Deleting :%s-%s" , td . getpId ( ) , td . getName ( ) ) ) ; } ) ; projectRepository . delete ( toDelete ) ; log ( "Project Data Collected. Deleted " , projectDataStart , toDelete . size ( ) ) ; } return projects ; } | Update project information |
22,888 | private List < Team > getBoardList ( ObjectId collectorId ) { List < Team > boards ; if ( featureSettings . isCollectorItemOnlyUpdate ( ) ) { Set < Team > uniqueTeams = new HashSet < > ( ) ; for ( FeatureBoard featureBoard : enabledFeatureBoards ( collectorId ) ) { Team team = teamRepository . findByTeamId ( featureBoard . getTeamId ( ) ) ; if ( team != null ) { uniqueTeams . add ( team ) ; } } boards = new ArrayList < > ( uniqueTeams ) ; } else { boards = teamRepository . findByCollectorId ( collectorId ) ; } return boards ; } | Returns a full team list or partial based on whether or not isCollectorItemOnlyUpdate is true |
22,889 | private Set < Scope > getScopeList ( ObjectId collectorId ) { Set < Scope > projects = new HashSet < > ( ) ; if ( featureSettings . isCollectorItemOnlyUpdate ( ) ) { for ( FeatureBoard featureBoard : enabledFeatureBoards ( collectorId ) ) { Scope scope = projectRepository . findByCollectorIdAndPId ( collectorId , featureBoard . getProjectId ( ) ) ; if ( scope != null ) { projects . add ( scope ) ; } } } else { projects = new HashSet < > ( projectRepository . findByCollectorId ( collectorId ) ) ; } return projects ; } | Returns a full project list or partial based on whether or not isCollectorItemOnlyUpdate is true |
22,890 | private void saveFeatures ( List < Feature > features , FeatureCollector collector ) { features . forEach ( f -> { f . setCollectorId ( collector . getId ( ) ) ; Feature existing = featureRepository . findByCollectorIdAndSIdAndSTeamID ( collector . getId ( ) , f . getsId ( ) , f . getsTeamID ( ) ) ; if ( existing != null ) { f . setId ( existing . getId ( ) ) ; } featureRepository . save ( f ) ; } ) ; } | Save features to repository |
22,891 | private void refreshValidIssues ( FeatureCollector collector , List < Team > teams , Set < Scope > scopes ) { long refreshValidIssuesStart = System . currentTimeMillis ( ) ; List < String > lookUpIds = Objects . equals ( collector . getMode ( ) , JiraMode . Board ) ? teams . stream ( ) . map ( Team :: getTeamId ) . collect ( Collectors . toList ( ) ) : scopes . stream ( ) . map ( Scope :: getpId ) . collect ( Collectors . toList ( ) ) ; lookUpIds . forEach ( l -> { LOGGER . info ( "Refreshing issues for " + collector . getMode ( ) + " ID:" + l ) ; List < String > issueIds = jiraClient . getAllIssueIds ( l , collector . getMode ( ) ) ; List < Feature > existingFeatures = Objects . equals ( collector . getMode ( ) , JiraMode . Board ) ? featureRepository . findAllByCollectorIdAndSTeamID ( collector . getId ( ) , l ) : featureRepository . findAllByCollectorIdAndSProjectID ( collector . getId ( ) , l ) ; List < Feature > deletedFeatures = existingFeatures . stream ( ) . filter ( e -> ! issueIds . contains ( e . getsId ( ) ) ) . collect ( Collectors . toList ( ) ) ; deletedFeatures . forEach ( d -> { LOGGER . info ( "Deleting Feature " + d . getsId ( ) + ':' + d . getsName ( ) ) ; featureRepository . delete ( d ) ; } ) ; } ) ; log ( collector . getMode ( ) + " Issues Refreshed " , refreshValidIssuesStart ) ; } | Get a list of all issue ids for a given board or project and delete ones that are not in JIRA anymore |
22,892 | private static boolean isEpicChanged ( Feature feature , Epic epic ) { if ( ! feature . getsEpicAssetState ( ) . equalsIgnoreCase ( epic . getStatus ( ) ) ) { return true ; } if ( ! feature . getsEpicName ( ) . equalsIgnoreCase ( epic . getName ( ) ) || ! feature . getsEpicNumber ( ) . equalsIgnoreCase ( epic . getNumber ( ) ) ) { return true ; } if ( ! StringUtils . isEmpty ( feature . getChangeDate ( ) ) && ! StringUtils . isEmpty ( epic . getChangeDate ( ) ) && ! Objects . equals ( Utilities . parseDateWithoutFraction ( feature . getChangeDate ( ) ) , Utilities . parseDateWithoutFraction ( epic . getChangeDate ( ) ) ) ) { return true ; } if ( ! StringUtils . isEmpty ( feature . getsEpicBeginDate ( ) ) && ! StringUtils . isEmpty ( epic . getBeginDate ( ) ) && ! Objects . equals ( Utilities . parseDateWithoutFraction ( feature . getsEpicBeginDate ( ) ) , Utilities . parseDateWithoutFraction ( epic . getBeginDate ( ) ) ) ) { return true ; } return ! StringUtils . isEmpty ( feature . getsEpicEndDate ( ) ) && ! StringUtils . isEmpty ( epic . getEndDate ( ) ) && ! Objects . equals ( Utilities . parseDateWithoutFraction ( feature . getsEpicEndDate ( ) ) , Utilities . parseDateWithoutFraction ( epic . getEndDate ( ) ) ) ; } | Checks if epic information on a feature needs update |
22,893 | public static String parseDateWithoutFraction ( String date ) { if ( date == null ) return "" ; if ( date . length ( ) < 20 ) { return date ; } return date . substring ( 0 , 19 ) ; } | This is weird but way faster than Java date time formatter etc . |
22,894 | private PipelineResponse buildPipelineResponse ( Pipeline pipeline , Long lowerBound , Long upperBound ) { CollectorItem dashboardCollectorItem = collectorItemRepository . findOne ( pipeline . getCollectorItemId ( ) ) ; Dashboard dashboard = dashboardRepository . findOne ( new ObjectId ( ( String ) dashboardCollectorItem . getOptions ( ) . get ( "dashboardId" ) ) ) ; PipelineResponse pipelineResponse = new PipelineResponse ( ) ; pipelineResponse . setCollectorItemId ( dashboardCollectorItem . getId ( ) ) ; pipelineResponse . setProdStage ( PipelineUtils . getProdStage ( dashboard ) ) ; pipelineResponse . setOrderMap ( PipelineUtils . getOrderForStages ( dashboard ) ) ; Map < PipelineStage , String > stageToEnvironmentNameMap = PipelineUtils . getStageToEnvironmentNameMap ( dashboard ) ; List < PipelineStage > pipelineStageList = new ArrayList < > ( ) ; for ( PipelineStage pl : stageToEnvironmentNameMap . keySet ( ) ) { pipelineStageList . add ( pl ) ; } for ( PipelineStage stage : pipelineStageList ) { List < PipelineResponseCommit > commitsForStage = findNotPropagatedCommits ( dashboard , pipeline , stage , pipelineStageList ) ; pipelineResponse . setStageCommits ( stage , commitsForStage ) ; } return pipelineResponse ; } | Creates the response that is returned to the client |
22,895 | protected void processCommits ( Pipeline pipeline , List < Commit > commits ) { Set < String > seenRevisionNumbers = new HashSet < > ( ) ; if ( logger . isDebugEnabled ( ) ) { StringBuilder sb = new StringBuilder ( ) ; sb . append ( "\n===== Commit List =====\n" ) ; for ( Commit commit : commits ) { sb . append ( " - " + commit . getId ( ) + " (" + commit . getScmRevisionNumber ( ) + ") - " + commit . getScmCommitLog ( ) + "\n" ) ; } logger . debug ( sb . toString ( ) ) ; } for ( Commit commit : commits ) { boolean commitNotSeen = seenRevisionNumbers . add ( commit . getScmRevisionNumber ( ) ) ; if ( commitNotSeen ) { pipeline . addCommit ( PipelineStage . COMMIT . getName ( ) , new PipelineCommit ( commit , commit . getScmCommitTimestamp ( ) ) ) ; } } } | Computes the commit stage of the pipeline . |
22,896 | protected RepoBranch getComponentRepoBranch ( Component component ) { CollectorItem item = component . getFirstCollectorItemForType ( CollectorType . SCM ) ; if ( item == null ) { logger . warn ( "Error encountered building pipeline: could not find scm collector item for dashboard." ) ; return new RepoBranch ( "" , "" , RepoType . Unknown ) ; } String url = ( String ) item . getOptions ( ) . get ( "url" ) ; String branch = ( String ) item . getOptions ( ) . get ( "branch" ) ; return new RepoBranch ( url , branch , RepoType . Unknown ) ; } | Determine the SCM url and branch that is set for the component . Information is gathered with the assumption that the data is stored in options . url and options . branch . |
22,897 | private Map < Environment , Collection < ArtifactIdentifier > > getArtifactIdentifiers ( List < Environment > environments ) { Map < Environment , Collection < ArtifactIdentifier > > rt = new HashMap < > ( ) ; for ( Environment env : environments ) { Set < ArtifactIdentifier > ids = new HashSet < > ( ) ; if ( env . getUnits ( ) != null ) { for ( DeployableUnit du : env . getUnits ( ) ) { String artifactName = du . getName ( ) ; String artifactExtension = null ; int dotIdx = artifactName . lastIndexOf ( '.' ) ; if ( dotIdx > 0 ) { artifactName = artifactName . substring ( 0 , dotIdx ) ; artifactExtension = artifactName . substring ( dotIdx ) ; } ArtifactIdentifier id = new ArtifactIdentifier ( null , artifactName , du . getVersion ( ) , null , artifactExtension ) ; ids . add ( id ) ; } } rt . put ( env , new ArrayList < > ( ids ) ) ; } return rt ; } | this is here for future expansion |
22,898 | private Map < String , Collection < String > > buildCommitGraph ( List < Commit > commits ) { Map < String , Collection < String > > rt = new HashMap < > ( ) ; for ( Commit commit : commits ) { String revisionNumber = commit . getScmRevisionNumber ( ) ; boolean alreadyExists = false ; List < String > parentRevisionNumbers = commit . getScmParentRevisionNumbers ( ) ; if ( parentRevisionNumbers == null ) { alreadyExists = rt . put ( revisionNumber , new ArrayList < > ( ) ) != null ; } else { alreadyExists = rt . put ( revisionNumber , parentRevisionNumbers ) != null ; } if ( alreadyExists ) { logger . warn ( "Error encountered building pipeline: multiple commits exist for revision number " + revisionNumber ) ; } } return rt ; } | We assume each commit belongs to the same repo + branch |
22,899 | private PipelineResponseCommit applyStageTimestamps ( PipelineResponseCommit commit , Dashboard dashboard , Pipeline pipeline , List < PipelineStage > pipelineStageList ) { PipelineResponseCommit returnCommit = new PipelineResponseCommit ( commit ) ; for ( PipelineStage systemStage : pipelineStageList ) { Map < String , PipelineCommit > commitMap = findCommitsForStage ( dashboard , pipeline , systemStage ) ; PipelineCommit pipelineCommit = commitMap . get ( commit . getScmRevisionNumber ( ) ) ; if ( pipelineCommit != null && ! returnCommit . getProcessedTimestamps ( ) . containsKey ( systemStage . getName ( ) ) ) { Long timestamp = pipelineCommit . getTimestamp ( ) ; returnCommit . addNewPipelineProcessedTimestamp ( systemStage , timestamp ) ; } } return returnCommit ; } | For a given commit will traverse the pipeline and find the time it entered in each stage of the pipeline |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.