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 . ge...
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 ) ; } } ...
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 ) { ...
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 f...
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 ( ) ...
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 ( ...
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 ( ) ) { NetworkInterfac...
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 + ...
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...
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 < File...
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 > multipartConte...
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 > pa...
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 uu...
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 = addS...
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...
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...
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 ( ) . toLowerCa...
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 ( ) ; fir...
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 ( "application...
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 { JSONA...
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...
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 ite...
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 ) ; Se...
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 = ec2Clien...
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 ( in...
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 ( ) ) { ...
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 ( )...
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 . getDura...
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 = ...
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 > > ( ) ; L...
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 . getCollectorIte...
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 ( ) ) ||...
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 . is...
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 . g...
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 ( ) ...
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 ( agil...
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 . COD...
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 ) ; ret...
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 ) ) ;...
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 ) ; } i...
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 . ...
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 , ...
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 . LIBR...
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...
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 , get...
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 collect...
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 ( ) ...
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 ( dash...
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...
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 ( )...
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 ( ) , CodeQualit...
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 . getCollect...
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 . isAnyEmp...
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 ( ) , b...
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 = V1Con...
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 re...
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" ...
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 !...
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 . getTea...
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...
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 ( featureBoa...
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 , featu...
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 != nu...
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 ) . col...
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 . getNumb...
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 ) dashboardCollectorIt...
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 ( " ...
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 ( "" , "" ...
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 . get...
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 > parentRevisionNumb...
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 ...
For a given commit will traverse the pipeline and find the time it entered in each stage of the pipeline