idx
int64 0
41.2k
| question
stringlengths 73
5.81k
| target
stringlengths 5
918
|
|---|---|---|
2,400
|
protected void configure ( HttpSecurity http ) throws Exception { SecureRandom random = new SecureRandom ( ) ; byte [ ] randomBytes = new byte [ 64 ] ; random . nextBytes ( randomBytes ) ; String rememberBeKey = new String ( Hex . encode ( randomBytes ) ) ; http . antMatcher ( "/**" ) . httpBasic ( ) . authenticationEntryPoint ( apiBasicAuthenticationEntryPoint ) . realmName ( "ontrack" ) . and ( ) . logout ( ) . logoutUrl ( "/user/logout" ) . logoutSuccessUrl ( "/user/logged-out" ) . addLogoutHandler ( basicRememberMeUserDetailsService ( ) ) . and ( ) . csrf ( ) . disable ( ) . authorizeRequests ( ) . antMatchers ( "/**" ) . permitAll ( ) . and ( ) . rememberMe ( ) . rememberMeServices ( rememberMeServices ( rememberBeKey ) ) . key ( rememberBeKey ) . tokenValiditySeconds ( 604800 ) . and ( ) . headers ( ) . cacheControl ( ) . disable ( ) ; }
|
By default all queries are accessible anonymously . Security is enforced at service level .
|
2,401
|
public JsonNode forStorage ( AutoPromotionProperty value ) { return format ( MapBuilder . create ( ) . with ( "validationStamps" , value . getValidationStamps ( ) . stream ( ) . map ( Entity :: id ) . collect ( Collectors . toList ( ) ) ) . with ( "include" , value . getInclude ( ) ) . with ( "exclude" , value . getExclude ( ) ) . get ( ) ) ; }
|
As a list of validation stamp IDs
|
2,402
|
public VersionInfo toInfo ( ) { return new VersionInfo ( parseDate ( date ) , display , full , branch , build , commit , source , sourceType ) ; }
|
Gets the representation of the version
|
2,403
|
public ExtensionFeatureOptions withDependency ( ExtensionFeature feature ) { Set < String > existing = this . dependencies ; Set < String > newDependencies ; if ( existing == null ) { newDependencies = new HashSet < > ( ) ; } else { newDependencies = new HashSet < > ( existing ) ; } newDependencies . add ( feature . getId ( ) ) ; return withDependencies ( newDependencies ) ; }
|
Adds a dependency
|
2,404
|
@ RequestMapping ( value = "" , method = RequestMethod . GET ) public Resources < Account > getAccounts ( ) { return Resources . of ( accountService . getAccounts ( ) , uri ( on ( getClass ( ) ) . getAccounts ( ) ) ) . with ( Link . CREATE , uri ( on ( AccountController . class ) . getCreationForm ( ) ) ) . with ( "_actions" , uri ( on ( AccountController . class ) . getAccountMgtActions ( ) ) ) ; }
|
List of accounts
|
2,405
|
@ RequestMapping ( value = "actions" , method = RequestMethod . GET ) public Resources < Action > getAccountMgtActions ( ) { return Resources . of ( extensionManager . getExtensions ( AccountMgtActionExtension . class ) . stream ( ) . map ( this :: resolveExtensionAction ) . filter ( action -> action != null ) , uri ( on ( AccountController . class ) . getAccountMgtActions ( ) ) ) ; }
|
Action management contributions
|
2,406
|
@ RequestMapping ( value = "create" , method = RequestMethod . GET ) public Form getCreationForm ( ) { return Form . create ( ) . with ( Form . defaultNameField ( ) ) . with ( Text . of ( "fullName" ) . length ( 100 ) . label ( "Full name" ) . help ( "Display name for the account" ) ) . with ( Email . of ( "email" ) . label ( "Email" ) . length ( 200 ) . help ( "Contact email for the account" ) ) . with ( Password . of ( "password" ) . label ( "Password" ) . length ( 40 ) . help ( "Password for the account" ) ) . with ( MultiSelection . of ( "groups" ) . label ( "Groups" ) . items ( accountService . getAccountGroupsForSelection ( ID . NONE ) ) ) ; }
|
Form to create a built - in account
|
2,407
|
@ RequestMapping ( value = "groups" , method = RequestMethod . GET ) public Resources < AccountGroup > getAccountGroups ( ) { return Resources . of ( accountService . getAccountGroups ( ) , uri ( on ( getClass ( ) ) . getAccountGroups ( ) ) ) . with ( Link . CREATE , uri ( on ( AccountController . class ) . getGroupCreationForm ( ) ) ) ; }
|
List of groups
|
2,408
|
protected Collection < ConfiguredIssueService > getConfiguredIssueServices ( IssueServiceConfiguration issueServiceConfiguration ) { CombinedIssueServiceConfiguration combinedIssueServiceConfiguration = ( CombinedIssueServiceConfiguration ) issueServiceConfiguration ; return combinedIssueServiceConfiguration . getIssueServiceConfigurationIdentifiers ( ) . stream ( ) . map ( issueServiceRegistry :: getConfiguredIssueService ) . collect ( Collectors . toList ( ) ) ; }
|
Gets the list of attached configured issue services .
|
2,409
|
@ RequestMapping ( value = "branches/{branchId}/update/bulk" , method = RequestMethod . GET ) public Form bulkUpdate ( @ SuppressWarnings ( "UnusedParameters" ) ID branchId ) { return Form . create ( ) . with ( Replacements . of ( "replacements" ) . label ( "Replacements" ) ) ; }
|
Gets the form for a bulk update of the branch
|
2,410
|
public static < T > List < SelectableItem > listOf ( Collection < T > items , Function < T , String > idFn , Function < T , String > nameFn , Predicate < T > selectedFn ) { return items . stream ( ) . map ( i -> new SelectableItem ( selectedFn . test ( i ) , idFn . apply ( i ) , nameFn . apply ( i ) ) ) . collect ( Collectors . toList ( ) ) ; }
|
Creation of a list of selectable items from a list of items using an extractor for the id and the name and a predicate for the selection .
|
2,411
|
public void configureContentNegotiation ( ContentNegotiationConfigurer configurer ) { configurer . favorParameter ( false ) ; configurer . favorPathExtension ( false ) ; }
|
Uses the HTTP header for content negociation .
|
2,412
|
public IssueServiceConfiguration getConfigurationByName ( String name ) { String [ ] tokens = StringUtils . split ( name , GitHubGitConfiguration . CONFIGURATION_REPOSITORY_SEPARATOR ) ; if ( tokens == null || tokens . length != 2 ) { throw new IllegalStateException ( "The GitHub issue configuration identifier name is expected using configuration:repository as a format" ) ; } String configuration = tokens [ 0 ] ; String repository = tokens [ 1 ] ; return new GitHubIssueServiceConfiguration ( configurationService . getConfiguration ( configuration ) , repository ) ; }
|
A GitHub configuration name
|
2,413
|
@ RequestMapping ( value = "" , method = RequestMethod . GET ) public Resource < ExtensionList > getExtensions ( ) { return Resource . of ( extensionManager . getExtensionList ( ) , uri ( MvcUriComponentsBuilder . on ( getClass ( ) ) . getExtensions ( ) ) ) ; }
|
Gets the list of extensions .
|
2,414
|
public static < T > Decoration < T > of ( Decorator < T > decorator , T data ) { Validate . notNull ( decorator , "The decorator is required" ) ; Validate . notNull ( data , "The decoration data is required" ) ; return new Decoration < > ( decorator , data , null ) ; }
|
Basic construction . Only the data is required
|
2,415
|
public static < T > Decoration < T > error ( Decorator < T > decorator , String error ) { Validate . notNull ( decorator , "The decorator is required" ) ; Validate . notBlank ( error , "The decoration error is required" ) ; return new Decoration < > ( decorator , null , error ) ; }
|
Basic construction . With an error
|
2,416
|
@ RequestMapping ( value = "configurations" , method = RequestMethod . GET ) public Resources < StashConfiguration > getConfigurations ( ) { return Resources . of ( configurationService . getConfigurations ( ) , uri ( on ( getClass ( ) ) . getConfigurations ( ) ) ) . with ( Link . CREATE , uri ( on ( getClass ( ) ) . getConfigurationForm ( ) ) ) . with ( "_test" , uri ( on ( getClass ( ) ) . testConfiguration ( null ) ) , securityService . isGlobalFunctionGranted ( GlobalSettings . class ) ) ; }
|
Gets the configurations
|
2,417
|
@ RequestMapping ( value = "changeLog/fileFilter/{projectId}/create" , method = RequestMethod . GET ) public Form createChangeLogFileFilterForm ( @ SuppressWarnings ( "UnusedParameters" ) ID projectId ) { return Form . create ( ) . with ( Text . of ( "name" ) . label ( "Name" ) . help ( "Name to use to save the filter." ) ) . with ( Memo . of ( "patterns" ) . label ( "Filter(s)" ) . help ( "List of ANT-like patterns (one per line)." ) ) ; }
|
Form to create a change log filter
|
2,418
|
@ RequestMapping ( value = "" , method = RequestMethod . GET ) public Resource < Info > info ( ) { return Resource . of ( infoService . getInfo ( ) , uri ( on ( getClass ( ) ) . info ( ) ) ) . with ( "user" , uri ( on ( UserController . class ) . getCurrentUser ( ) ) ) . with ( "_applicationInfo" , uri ( on ( InfoController . class ) . applicationInfo ( ) ) ) ; }
|
General information about the application
|
2,419
|
@ RequestMapping ( value = "application" , method = RequestMethod . GET ) public Resources < ApplicationInfo > applicationInfo ( ) { return Resources . of ( applicationInfoService . getApplicationInfoList ( ) , uri ( on ( InfoController . class ) . applicationInfo ( ) ) ) ; }
|
Messages about the application
|
2,420
|
public boolean canEdit ( ProjectEntity entity , SecurityService securityService ) { return securityService . isProjectFunctionGranted ( entity . projectId ( ) , ProjectConfig . class ) && propertyService . hasProperty ( entity . getProject ( ) , SVNProjectConfigurationPropertyType . class ) ; }
|
One can edit the SVN configuration of a branch only if he can configurure a project and if the project is itself configured with SVN .
|
2,421
|
public void start ( ) { register ( STATUS_PASSED ) ; register ( STATUS_FIXED ) ; register ( STATUS_DEFECTIVE ) ; register ( STATUS_EXPLAINED , FIXED ) ; register ( STATUS_INVESTIGATING , DEFECTIVE , EXPLAINED , FIXED ) ; register ( STATUS_INTERRUPTED , INVESTIGATING , FIXED ) ; register ( STATUS_FAILED , INTERRUPTED , INVESTIGATING , EXPLAINED , DEFECTIVE ) ; register ( STATUS_WARNING , INTERRUPTED , INVESTIGATING , EXPLAINED , DEFECTIVE ) ; for ( ValidationRunStatusID statusID : statuses . values ( ) ) { for ( String nextStatus : statusID . getFollowingStatuses ( ) ) { if ( ! statuses . containsKey ( nextStatus ) ) { throw new ValidationRunStatusUnknownDependencyException ( statusID . getId ( ) , nextStatus ) ; } } } for ( ValidationRunStatusID statusID : statuses . values ( ) ) { logger . info ( "[status] {} -> {}" , statusID . getId ( ) , StringUtils . join ( statusID . getFollowingStatuses ( ) , "," ) ) ; } }
|
Registers the tree of validation run status ids .
|
2,422
|
protected < T > List < ? extends Decoration > getDecorations ( ProjectEntity entity , Decorator < T > decorator ) { try { return decorator . getDecorations ( entity ) ; } catch ( Exception ex ) { return Collections . singletonList ( Decoration . error ( decorator , getErrorMessage ( ex ) ) ) ; } }
|
Gets the decoration for an entity and returns an error decoration in case of problem .
|
2,423
|
public static List < String > asList ( String text ) { if ( StringUtils . isBlank ( text ) ) { return Collections . emptyList ( ) ; } else { try { return IOUtils . readLines ( new StringReader ( text ) ) ; } catch ( IOException e ) { throw new RuntimeException ( "Cannot get lines" , e ) ; } } }
|
Splits a text in several lines .
|
2,424
|
public static String toHexString ( byte [ ] bytes , int start , int len ) { StringBuilder buf = new StringBuilder ( ) ; for ( int i = 0 ; i < len ; i ++ ) { int b = bytes [ start + i ] & 0xFF ; if ( b < 16 ) buf . append ( '0' ) ; buf . append ( Integer . toHexString ( b ) ) ; } return buf . toString ( ) ; }
|
Writes some bytes in Hexadecimal format
|
2,425
|
public boolean canEdit ( ProjectEntity entity , SecurityService securityService ) { return securityService . isProjectFunctionGranted ( entity , ProjectConfig . class ) && propertyService . hasProperty ( entity , SVNBranchConfigurationPropertyType . class ) ; }
|
One can edit the SVN synchronisation only if he can configure the project and if the branch is configured for SVN .
|
2,426
|
@ RequestMapping ( value = "configurations/descriptors" , method = RequestMethod . GET ) public Resources < ConfigurationDescriptor > getConfigurationsDescriptors ( ) { return Resources . of ( jenkinsService . getConfigurationDescriptors ( ) , uri ( on ( getClass ( ) ) . getConfigurationsDescriptors ( ) ) ) ; }
|
Gets the configuration descriptors
|
2,427
|
protected T injectCredentials ( T configuration ) { T oldConfig = findConfiguration ( configuration . getName ( ) ) . orElse ( null ) ; T target ; if ( StringUtils . isBlank ( configuration . getPassword ( ) ) ) { if ( oldConfig != null && StringUtils . equals ( oldConfig . getUser ( ) , configuration . getUser ( ) ) ) { target = configuration . withPassword ( oldConfig . getPassword ( ) ) ; } else { target = configuration ; } } else { target = configuration ; } return target ; }
|
Adjust a configuration so that it contains a password if 1 ) the password is empty 2 ) the configuration already exists 3 ) the user name is the same
|
2,428
|
@ RequestMapping ( value = "predefinedValidationStamps" , method = RequestMethod . GET ) public Resources < PredefinedValidationStamp > getPredefinedValidationStampList ( ) { return Resources . of ( predefinedValidationStampService . getPredefinedValidationStamps ( ) , uri ( on ( getClass ( ) ) . getPredefinedValidationStampList ( ) ) ) . with ( Link . CREATE , uri ( on ( getClass ( ) ) . getPredefinedValidationStampCreationForm ( ) ) ) ; }
|
Gets the list of predefined validation stamps .
|
2,429
|
@ RequestMapping ( value = "" , method = RequestMethod . GET ) public Resources < DescribedForm > configuration ( ) { securityService . checkGlobalFunction ( GlobalSettings . class ) ; List < DescribedForm > forms = settingsManagers . stream ( ) . sorted ( ( o1 , o2 ) -> o1 . getTitle ( ) . compareTo ( o2 . getTitle ( ) ) ) . map ( this :: getSettingsForm ) . collect ( Collectors . toList ( ) ) ; return Resources . of ( forms , uri ( on ( getClass ( ) ) . configuration ( ) ) ) ; }
|
List of forms to configure .
|
2,430
|
public OptionalLong extractRevision ( String buildName ) { String regex = getRegex ( ) ; Matcher matcher = Pattern . compile ( regex ) . matcher ( buildName ) ; if ( matcher . matches ( ) ) { String token = matcher . group ( 1 ) ; return OptionalLong . of ( Long . parseLong ( token , 10 ) ) ; } else { return OptionalLong . empty ( ) ; } }
|
Extracts the revision from a build name .
|
2,431
|
public static OntrackSVNIssueInfo empty ( SVNConfiguration configuration ) { return new OntrackSVNIssueInfo ( configuration , null , null , Collections . emptyList ( ) , Collections . emptyList ( ) ) ; }
|
Empty issue info .
|
2,432
|
public boolean canEdit ( ProjectEntity entity , SecurityService securityService ) { switch ( entity . getProjectEntityType ( ) ) { case BUILD : return securityService . isProjectFunctionGranted ( entity , BuildCreate . class ) ; case PROMOTION_RUN : return securityService . isProjectFunctionGranted ( entity , PromotionRunCreate . class ) ; case VALIDATION_RUN : return securityService . isProjectFunctionGranted ( entity , ValidationRunCreate . class ) ; default : throw new PropertyUnsupportedEntityTypeException ( getClass ( ) . getName ( ) , entity . getProjectEntityType ( ) ) ; } }
|
Depends on the nature of the entity . Allowed to the ones who can create the associated entity .
|
2,433
|
public static void main ( String [ ] args ) { File pid = new File ( "ontrack.pid" ) ; SpringApplication application = new SpringApplication ( Application . class ) ; application . addListeners ( new ApplicationPidFileWriter ( pid ) ) ; application . run ( args ) ; }
|
Start - up point
|
2,434
|
public boolean hasValidationStamp ( String name , String status ) { return ( StringUtils . equals ( name , getValidationStamp ( ) . getName ( ) ) ) && isRun ( ) && ( StringUtils . isBlank ( status ) || StringUtils . equals ( status , getLastStatus ( ) . getStatusID ( ) . getId ( ) ) ) ; }
|
Checks if the validation run view has the given validation stamp with the given status .
|
2,435
|
protected Stream < Branch > getSVNConfiguredBranches ( ) { return structureService . getProjectList ( ) . stream ( ) . filter ( project -> propertyService . hasProperty ( project , SVNProjectConfigurationPropertyType . class ) ) . flatMap ( project -> structureService . getBranchesForProject ( project . getId ( ) ) . stream ( ) ) . filter ( branch -> propertyService . hasProperty ( branch , SVNBranchConfigurationPropertyType . class ) ) ; }
|
Gets the list of all branches for all projects which are properly configured for SVN .
|
2,436
|
@ RequestMapping ( value = "globals" , method = RequestMethod . GET ) public Resources < GlobalPermission > getGlobalPermissions ( ) { return Resources . of ( accountService . getGlobalPermissions ( ) , uri ( on ( PermissionController . class ) . getGlobalPermissions ( ) ) ) . with ( "_globalRoles" , uri ( on ( PermissionController . class ) . getGlobalRoles ( ) ) ) ; }
|
List of global permissions
|
2,437
|
@ RequestMapping ( value = "globals/roles" , method = RequestMethod . GET ) public Resources < GlobalRole > getGlobalRoles ( ) { return Resources . of ( rolesService . getGlobalRoles ( ) , uri ( on ( PermissionController . class ) . getGlobalRoles ( ) ) ) ; }
|
List of global roles
|
2,438
|
@ RequestMapping ( value = "projects/roles" , method = RequestMethod . GET ) public Resources < ProjectRole > getProjectRoles ( ) { return Resources . of ( rolesService . getProjectRoles ( ) , uri ( on ( PermissionController . class ) . getProjectRoles ( ) ) ) ; }
|
List of project roles
|
2,439
|
protected Set < File > jrxmlFilesToCompile ( SourceMapping mapping ) throws MojoExecutionException { if ( ! sourceDirectory . isDirectory ( ) ) { String message = sourceDirectory . getName ( ) + " is not a directory" ; if ( failOnMissingSourceDirectory ) { throw new IllegalArgumentException ( message ) ; } else { log . warn ( message + ", skip JasperReports reports compiling." ) ; return Collections . emptySet ( ) ; } } try { SourceInclusionScanner scanner = createSourceInclusionScanner ( ) ; scanner . addSourceMapping ( mapping ) ; return scanner . getIncludedSources ( sourceDirectory , outputDirectory ) ; } catch ( InclusionScanException e ) { throw new MojoExecutionException ( "Error scanning source root: \'" + sourceDirectory + "\'." , e ) ; } }
|
Determines source files to be compiled .
|
2,440
|
private void checkOutDirWritable ( File outputDirectory ) throws MojoExecutionException { if ( ! outputDirectory . exists ( ) ) { checkIfOutputCanBeCreated ( ) ; checkIfOutputDirIsWritable ( ) ; if ( verbose ) { log . info ( "Output dir check OK" ) ; } } else if ( ! outputDirectory . canWrite ( ) ) { throw new MojoExecutionException ( "The output dir exists but was not writable. " + "Try running maven with the 'clean' goal." ) ; } }
|
Check if the output directory exist and is writable . If not try to create an output dir and see if that is writable .
|
2,441
|
public Void call ( ) throws Exception { OutputStream out = null ; InputStream in = null ; try { out = new FileOutputStream ( destination ) ; in = new FileInputStream ( source ) ; JasperCompileManager . compileReportToStream ( in , out ) ; if ( verbose ) { log . info ( "Compiling " + source . getName ( ) ) ; } } catch ( Exception e ) { cleanUpAndThrowError ( destination , e ) ; } finally { if ( out != null ) { out . close ( ) ; } if ( in != null ) { in . close ( ) ; } } return null ; }
|
Compile the source file . If the source file doesn t have the right extension it is skipped .
|
2,442
|
public static Bitmap screenshot ( int width , int height ) { if ( METHOD_screenshot_II == null ) { Log . e ( TAG , "screenshot method was not found." ) ; return null ; } return ( Bitmap ) CompatUtils . invoke ( null , null , METHOD_screenshot_II , width , height ) ; }
|
Copy the current screen contents into a bitmap and return it . Use width = 0 and height = 0 to obtain an unscaled screenshot .
|
2,443
|
public static Bitmap createScreenshot ( Context context ) { if ( ! hasScreenshotPermission ( context ) ) { LogUtils . log ( ScreenshotUtils . class , Log . ERROR , "Screenshot permission denied." ) ; return null ; } final WindowManager windowManager = ( WindowManager ) context . getSystemService ( Context . WINDOW_SERVICE ) ; final Bitmap bitmap = SurfaceControlCompatUtils . screenshot ( 0 , 0 ) ; if ( bitmap == null ) { LogUtils . log ( ScreenshotUtils . class , Log . ERROR , "Failed to take screenshot." ) ; return null ; } final int width = bitmap . getWidth ( ) ; final int height = bitmap . getHeight ( ) ; final int rotation = windowManager . getDefaultDisplay ( ) . getRotation ( ) ; final int outWidth ; final int outHeight ; final float rotationDegrees ; switch ( rotation ) { case Surface . ROTATION_90 : outWidth = height ; outHeight = width ; rotationDegrees = 90 ; break ; case Surface . ROTATION_180 : outWidth = width ; outHeight = height ; rotationDegrees = 180 ; break ; case Surface . ROTATION_270 : outWidth = height ; outHeight = width ; rotationDegrees = 270 ; break ; default : return bitmap ; } final Bitmap rotatedBitmap = Bitmap . createBitmap ( outWidth , outHeight , Bitmap . Config . RGB_565 ) ; final Canvas c = new Canvas ( rotatedBitmap ) ; c . translate ( outWidth / 2.0f , outHeight / 2.0f ) ; c . rotate ( - rotationDegrees ) ; c . translate ( - width / 2.0f , - height / 2.0f ) ; c . drawBitmap ( bitmap , 0 , 0 , null ) ; bitmap . recycle ( ) ; return rotatedBitmap ; }
|
Returns a screenshot with the contents of the current display that matches the current display rotation .
|
2,444
|
public void reset ( AccessibilityNodeInfoCompat newNode ) { if ( mNode != newNode && mNode != null && mOwned ) { mNode . recycle ( ) ; } mNode = newNode ; mOwned = true ; }
|
Resets this object to contain a new node taking ownership of the new node .
|
2,445
|
public void init ( Context context ) { if ( ! mNotFoundClassesMap . isEmpty ( ) ) { buildInstalledPackagesCache ( context ) ; } mPackageMonitor . register ( context ) ; }
|
Builds the package cache and registers the package monitor
|
2,446
|
private void buildInstalledPackagesCache ( Context context ) { final List < PackageInfo > installedPackages = context . getPackageManager ( ) . getInstalledPackages ( 0 ) ; for ( PackageInfo installedPackage : installedPackages ) { addInstalledPackageToCache ( installedPackage . packageName ) ; } }
|
Builds a cache of installed packages .
|
2,447
|
private void processSwatch ( Bitmap image ) { final Map < Integer , Integer > colorHistogram = processLuminanceData ( image ) ; extractFgBgData ( colorHistogram ) ; mContrastRatio = Math . round ( ContrastUtils . calculateContrastRatio ( mBackgroundLuminance , mForegroundLuminance ) * 100.0d ) / 100.0d ; }
|
Compute the background and foreground colors and luminance for the image and the contrast ratio .
|
2,448
|
private void extractFgBgData ( Map < Integer , Integer > colorHistogram ) { if ( colorHistogram . isEmpty ( ) ) { mBackgroundLuminance = mForegroundLuminance = 0 ; mBackgroundColor = Color . BLACK ; mForegroundColor = Color . BLACK ; } else if ( colorHistogram . size ( ) == 1 ) { final int singleColor = colorHistogram . keySet ( ) . iterator ( ) . next ( ) ; mBackgroundLuminance = mForegroundLuminance = ContrastUtils . calculateLuminance ( singleColor ) ; mForegroundColor = singleColor ; mBackgroundColor = singleColor ; } else { double luminanceSum = 0 ; for ( int color : colorHistogram . keySet ( ) ) { luminanceSum += ContrastUtils . calculateLuminance ( color ) ; } final double averageLuminance = luminanceSum / colorHistogram . size ( ) ; double lowLuminanceContributor = 0.0d ; double highLuminanceContributor = 1.0d ; int lowLuminanceColor = - 1 ; int highLuminanceColor = - 1 ; int maxLowLuminanceFrequency = 0 ; int maxHighLuminanceFrequency = 0 ; for ( Entry < Integer , Integer > entry : colorHistogram . entrySet ( ) ) { final int color = entry . getKey ( ) ; final double luminanceValue = ContrastUtils . calculateLuminance ( color ) ; final int frequency = entry . getValue ( ) ; if ( ( luminanceValue < averageLuminance ) && ( frequency > maxLowLuminanceFrequency ) ) { lowLuminanceContributor = luminanceValue ; maxLowLuminanceFrequency = frequency ; lowLuminanceColor = color ; } else if ( ( luminanceValue >= averageLuminance ) && ( frequency > maxHighLuminanceFrequency ) ) { highLuminanceContributor = luminanceValue ; maxHighLuminanceFrequency = frequency ; highLuminanceColor = color ; } } if ( maxHighLuminanceFrequency > maxLowLuminanceFrequency ) { mBackgroundLuminance = highLuminanceContributor ; mBackgroundColor = highLuminanceColor ; mForegroundLuminance = lowLuminanceContributor ; mForegroundColor = lowLuminanceColor ; } else { mBackgroundLuminance = lowLuminanceContributor ; mBackgroundColor = lowLuminanceColor ; mForegroundLuminance = highLuminanceContributor ; mForegroundColor = highLuminanceColor ; } } }
|
Set the fields mBackgroundColor mForegroundColor mBackgroundLuminance and mForegroundLuminance based upon the color histogram .
|
2,449
|
public static AccessibilityNodeInfoCompat focusSearch ( AccessibilityNodeInfoCompat node , int direction ) { final AccessibilityNodeInfoRef ref = AccessibilityNodeInfoRef . unOwned ( node ) ; switch ( direction ) { case SEARCH_FORWARD : { if ( ! ref . nextInOrder ( ) ) { return null ; } return ref . release ( ) ; } case SEARCH_BACKWARD : { if ( ! ref . previousInOrder ( ) ) { return null ; } return ref . release ( ) ; } } return null ; }
|
Perform in - order navigation from a given node in a particular direction .
|
2,450
|
public static boolean performNavigationByDOMObject ( AccessibilityNodeInfoCompat node , int direction ) { final int action = ( direction == DIRECTION_FORWARD ) ? AccessibilityNodeInfoCompat . ACTION_NEXT_HTML_ELEMENT : AccessibilityNodeInfoCompat . ACTION_PREVIOUS_HTML_ELEMENT ; return node . performAction ( action ) ; }
|
Sends an instruction to ChromeVox to navigate by DOM object in the given direction within a node .
|
2,451
|
public static boolean supportsWebActions ( AccessibilityNodeInfoCompat node ) { return AccessibilityNodeInfoUtils . supportsAnyAction ( node , AccessibilityNodeInfoCompat . ACTION_NEXT_HTML_ELEMENT , AccessibilityNodeInfoCompat . ACTION_PREVIOUS_HTML_ELEMENT ) ; }
|
Determines whether or not the given node contains web content .
|
2,452
|
public static boolean hasLegacyWebContent ( AccessibilityNodeInfoCompat node ) { if ( node == null ) { return false ; } if ( ! supportsWebActions ( node ) ) { return false ; } AccessibilityNodeInfoCompat parent = node . getParent ( ) ; if ( supportsWebActions ( parent ) ) { if ( parent != null ) { parent . recycle ( ) ; } return false ; } if ( parent != null ) { parent . recycle ( ) ; } return node . getChildCount ( ) == 0 ; }
|
Determines whether or not the given node contains ChromeVox content .
|
2,453
|
public static boolean shouldFocusNode ( Context context , AccessibilityNodeInfoCompat node ) { if ( node == null ) { return false ; } if ( ! isVisibleOrLegacy ( node ) ) { LogUtils . log ( AccessibilityNodeInfoUtils . class , Log . VERBOSE , "Don't focus, node is not visible" ) ; return false ; } if ( FILTER_ACCESSIBILITY_FOCUSABLE . accept ( context , node ) ) { if ( node . getChildCount ( ) <= 0 ) { LogUtils . log ( AccessibilityNodeInfoUtils . class , Log . VERBOSE , "Focus, node is focusable and has no children" ) ; return true ; } else if ( isSpeakingNode ( context , node ) ) { LogUtils . log ( AccessibilityNodeInfoUtils . class , Log . VERBOSE , "Focus, node is focusable and has something to speak" ) ; return true ; } else { LogUtils . log ( AccessibilityNodeInfoUtils . class , Log . VERBOSE , "Don't focus, node is focusable but has nothing to speak" ) ; return false ; } } if ( ! hasMatchingAncestor ( context , node , FILTER_ACCESSIBILITY_FOCUSABLE ) && hasText ( node ) ) { LogUtils . log ( AccessibilityNodeInfoUtils . class , Log . VERBOSE , "Focus, node has text and no focusable ancestors" ) ; return true ; } LogUtils . log ( AccessibilityNodeInfoUtils . class , Log . VERBOSE , "Don't focus, failed all focusability tests" ) ; return false ; }
|
Returns whether a node should receive accessibility focus from navigation . This method should never be called recursively since it traverses up the parent hierarchy on every call .
|
2,454
|
private static boolean hasMatchingAncestor ( Context context , AccessibilityNodeInfoCompat node , NodeFilter filter ) { if ( node == null ) { return false ; } final AccessibilityNodeInfoCompat result = getMatchingAncestor ( context , node , filter ) ; if ( result == null ) { return false ; } result . recycle ( ) ; return true ; }
|
Check whether a given node has a scrollable ancestor .
|
2,455
|
private static boolean isScrollable ( AccessibilityNodeInfoCompat node ) { if ( node . isScrollable ( ) ) { return true ; } return supportsAnyAction ( node , AccessibilityNodeInfoCompat . ACTION_SCROLL_FORWARD , AccessibilityNodeInfoCompat . ACTION_SCROLL_BACKWARD ) ; }
|
Check whether a given node is scrollable .
|
2,456
|
private static boolean hasText ( AccessibilityNodeInfoCompat node ) { if ( node == null ) { return false ; } return ( ! TextUtils . isEmpty ( node . getText ( ) ) || ! TextUtils . isEmpty ( node . getContentDescription ( ) ) ) ; }
|
Returns whether the specified node has text .
|
2,457
|
public static boolean isTopLevelScrollItem ( Context context , AccessibilityNodeInfoCompat node ) { if ( node == null ) { return false ; } AccessibilityNodeInfoCompat parent = null ; try { parent = node . getParent ( ) ; if ( parent == null ) { return false ; } if ( isScrollable ( node ) ) { return true ; } if ( nodeMatchesAnyClassByType ( context , parent , android . widget . AdapterView . class , android . widget . ScrollView . class , android . widget . HorizontalScrollView . class , CLASS_TOUCHWIZ_TWADAPTERVIEW ) && ! nodeMatchesAnyClassByType ( context , parent , android . widget . Spinner . class ) ) { return true ; } return false ; } finally { recycleNodes ( parent ) ; } }
|
Determines whether a node is a top - level item in a scrollable container .
|
2,458
|
public static boolean isEdgeListItem ( Context context , AccessibilityNodeInfoCompat node , int direction , NodeFilter filter ) { if ( node == null ) { return false ; } if ( ( direction <= 0 ) && isMatchingEdgeListItem ( context , node , NodeFocusFinder . SEARCH_BACKWARD , FILTER_SCROLL_BACKWARD . and ( filter ) ) ) { return true ; } if ( ( direction >= 0 ) && isMatchingEdgeListItem ( context , node , NodeFocusFinder . SEARCH_FORWARD , FILTER_SCROLL_FORWARD . and ( filter ) ) ) { return true ; } return false ; }
|
Determines if the current item is at the edge of a list by checking the scrollable predecessors of the items on either or both sides .
|
2,459
|
private static boolean isMatchingEdgeListItem ( Context context , AccessibilityNodeInfoCompat cursor , int direction , NodeFilter filter ) { AccessibilityNodeInfoCompat ancestor = null ; AccessibilityNodeInfoCompat searched = null ; AccessibilityNodeInfoCompat searchedAncestor = null ; try { ancestor = getMatchingAncestor ( null , cursor , filter ) ; if ( ancestor == null ) { return false ; } searched = NodeFocusFinder . focusSearch ( cursor , direction ) ; while ( ( searched != null ) && ! AccessibilityNodeInfoUtils . shouldFocusNode ( context , searched ) ) { final AccessibilityNodeInfoCompat temp = searched ; searched = NodeFocusFinder . focusSearch ( temp , direction ) ; temp . recycle ( ) ; } if ( ( searched == null ) || searched . equals ( ancestor ) ) { return true ; } searchedAncestor = getMatchingAncestor ( null , searched , filter ) ; if ( ! ancestor . equals ( searchedAncestor ) ) { return true ; } } finally { recycleNodes ( ancestor , searched , searchedAncestor ) ; } return false ; }
|
Utility method for determining if a searching past a particular node will fall off the edge of a scrollable container .
|
2,460
|
public static AccessibilityNodeInfoCompat searchFromBfs ( Context context , AccessibilityNodeInfoCompat node , NodeFilter filter ) { if ( node == null ) { return null ; } final LinkedList < AccessibilityNodeInfoCompat > queue = new LinkedList < AccessibilityNodeInfoCompat > ( ) ; queue . add ( AccessibilityNodeInfoCompat . obtain ( node ) ) ; while ( ! queue . isEmpty ( ) ) { final AccessibilityNodeInfoCompat item = queue . removeFirst ( ) ; if ( filter . accept ( context , item ) ) { return AccessibilityNodeInfoCompat . obtain ( item ) ; } final int childCount = item . getChildCount ( ) ; for ( int i = 0 ; i < childCount ; i ++ ) { final AccessibilityNodeInfoCompat child = item . getChild ( i ) ; if ( child != null ) { queue . addLast ( child ) ; } } } return null ; }
|
Returns the result of applying a filter using breadth - first traversal .
|
2,461
|
public static AccessibilityNodeInfoCompat searchFromInOrderTraversal ( Context context , AccessibilityNodeInfoCompat root , NodeFilter filter , int direction ) { AccessibilityNodeInfoCompat currentNode = NodeFocusFinder . focusSearch ( root , direction ) ; final HashSet < AccessibilityNodeInfoCompat > seenNodes = new HashSet < AccessibilityNodeInfoCompat > ( ) ; while ( ( currentNode != null ) && ! seenNodes . contains ( currentNode ) && ! filter . accept ( context , currentNode ) ) { seenNodes . add ( currentNode ) ; currentNode = NodeFocusFinder . focusSearch ( currentNode , direction ) ; } AccessibilityNodeInfoUtils . recycleNodes ( seenNodes ) ; return currentNode ; }
|
Performs in - order traversal from a given node in a particular direction until a node matching the specified filter is reached .
|
2,462
|
public boolean isCompatible ( DefaultVersionRange otherRange ) { int lowerCompare = compareTo ( this . lowerBound , this . lowerBoundInclusive , otherRange . lowerBound , otherRange . lowerBoundInclusive , false ) ; int upperCompare = compareTo ( this . upperBound , this . upperBoundInclusive , otherRange . upperBound , otherRange . upperBoundInclusive , true ) ; if ( lowerCompare == 0 || upperCompare == 0 ) { return true ; } if ( lowerCompare > 0 && upperCompare < 0 ) { return true ; } if ( lowerCompare < 0 && upperCompare > 0 ) { return true ; } return lowerCompare < 0 ? isCompatible ( this . upperBound , this . upperBoundInclusive , otherRange . lowerBound , otherRange . lowerBoundInclusive ) : isCompatible ( otherRange . upperBound , otherRange . upperBoundInclusive , this . lowerBound , this . lowerBoundInclusive ) ; }
|
Indicate if the provided version range is compatible with the provided version range .
|
2,463
|
protected Class < ? > getGenericRole ( Field field ) { Type type = field . getGenericType ( ) ; if ( type instanceof ParameterizedType ) { ParameterizedType pType = ( ParameterizedType ) type ; Type [ ] types = pType . getActualTypeArguments ( ) ; if ( types . length > 0 && types [ types . length - 1 ] instanceof Class ) { return ( Class ) types [ types . length - 1 ] ; } } return null ; }
|
Extract generic type from the list field .
|
2,464
|
private DefaultLocalExtension createExtension ( Extension extension ) { DefaultLocalExtension localExtension = new DefaultLocalExtension ( this , extension ) ; localExtension . setFile ( this . storage . getNewExtensionFile ( localExtension . getId ( ) , localExtension . getType ( ) ) ) ; return localExtension ; }
|
Create a new local extension from a remote extension .
|
2,465
|
private ExtensionDependency getDependency ( Extension extension , String dependencyId ) { for ( ExtensionDependency dependency : extension . getDependencies ( ) ) { if ( dependency . getId ( ) . equals ( dependencyId ) ) { return dependency ; } } return null ; }
|
Extract extension with the provided id from the provided extension .
|
2,466
|
private Set < InstalledExtension > getReplacedInstalledExtensions ( Extension extension , String namespace ) throws IncompatibleVersionConstraintException , ResolveException , InstallException { if ( namespace != null ) { checkRootExtension ( extension . getId ( ) . getId ( ) ) ; } Set < InstalledExtension > previousExtensions = new LinkedHashSet < > ( ) ; Set < InstalledExtension > installedExtensions = getInstalledExtensions ( extension . getId ( ) . getId ( ) , namespace ) ; VersionConstraint versionConstraint = checkReplacedInstalledExtensions ( installedExtensions , extension . getId ( ) , namespace , null ) ; previousExtensions . addAll ( installedExtensions ) ; for ( ExtensionId feature : extension . getExtensionFeatures ( ) ) { if ( namespace != null ) { checkRootExtension ( feature . getId ( ) ) ; } installedExtensions = getInstalledExtensions ( feature . getId ( ) , namespace ) ; versionConstraint = checkReplacedInstalledExtensions ( installedExtensions , feature , namespace , versionConstraint ) ; previousExtensions . addAll ( installedExtensions ) ; } if ( extension instanceof InstalledExtension ) { previousExtensions . remove ( extension ) ; } return previousExtensions ; }
|
Search and validate existing extensions that will be replaced by the extension .
|
2,467
|
public static boolean verify ( SignerInformation signer , CertifiedPublicKey certKey , BcContentVerifierProviderBuilder contentVerifierProviderBuilder , DigestFactory digestProvider ) throws CMSException { if ( certKey == null ) { throw new CMSException ( "No certified key for proceeding to signature validation." ) ; } return signer . verify ( new SignerInformationVerifier ( new DefaultCMSSignatureAlgorithmNameGenerator ( ) , new DefaultSignatureAlgorithmIdentifierFinder ( ) , contentVerifierProviderBuilder . build ( certKey ) , ( DigestCalculatorProvider ) digestProvider ) ) ; }
|
Verify a CMS signature .
|
2,468
|
public void setProperties ( Map < String , Object > properties ) { this . properties . clear ( ) ; this . properties . putAll ( properties ) ; }
|
Replace existing properties with provided properties .
|
2,469
|
public < T > Cache < T > createNewCache ( CacheConfiguration config , String cacheHint ) throws CacheException { CacheFactory cacheFactory ; try { cacheFactory = this . componentManager . getInstance ( CacheFactory . class , cacheHint ) ; } catch ( ComponentLookupException e ) { throw new CacheException ( "Failed to get cache factory for role hint [" + cacheHint + "]" , e ) ; } return cacheFactory . newCache ( config ) ; }
|
Lookup the cache component with provided hint and create a new cache .
|
2,470
|
private Method getPrivateMethod ( VelMethod velMethod ) throws Exception { Field methodField = velMethod . getClass ( ) . getDeclaredField ( "method" ) ; boolean isAccessible = methodField . isAccessible ( ) ; try { methodField . setAccessible ( true ) ; return ( Method ) methodField . get ( velMethod ) ; } finally { methodField . setAccessible ( isAccessible ) ; } }
|
This is hackish but there s no way in Velocity to get access to the underlying Method from a VelMethod instance .
|
2,471
|
private Object [ ] convertArguments ( Object obj , String methodName , Object [ ] args ) { for ( Method method : obj . getClass ( ) . getMethods ( ) ) { if ( method . getName ( ) . equalsIgnoreCase ( methodName ) && ( method . getGenericParameterTypes ( ) . length == args . length || method . isVarArgs ( ) ) ) { try { return convertArguments ( args , method . getGenericParameterTypes ( ) , method . isVarArgs ( ) ) ; } catch ( Exception e ) { } } } return null ; }
|
Converts the given arguments to match a method with the specified name and the same number of formal parameters as the number of arguments .
|
2,472
|
private void initializeExtension ( InstalledExtension installedExtension , String namespaceToLoad , Map < String , Set < InstalledExtension > > initializedExtensions ) throws ExtensionException { if ( installedExtension . getNamespaces ( ) != null ) { if ( namespaceToLoad == null ) { for ( String namespace : installedExtension . getNamespaces ( ) ) { initializeExtensionInNamespace ( installedExtension , namespace , initializedExtensions ) ; } } else if ( installedExtension . getNamespaces ( ) . contains ( namespaceToLoad ) ) { initializeExtensionInNamespace ( installedExtension , namespaceToLoad , initializedExtensions ) ; } } else if ( namespaceToLoad == null ) { initializeExtensionInNamespace ( installedExtension , null , initializedExtensions ) ; } }
|
Initialize extension .
|
2,473
|
private void initializeExtensionInNamespace ( InstalledExtension installedExtension , String namespace , Map < String , Set < InstalledExtension > > initializedExtensions ) throws ExtensionException { if ( ! installedExtension . isValid ( namespace ) ) { return ; } Set < InstalledExtension > initializedExtensionsInNamespace = initializedExtensions . get ( namespace ) ; if ( initializedExtensionsInNamespace == null ) { initializedExtensionsInNamespace = new HashSet < > ( ) ; initializedExtensions . put ( namespace , initializedExtensionsInNamespace ) ; } if ( ! initializedExtensionsInNamespace . contains ( installedExtension ) ) { initializeExtensionInNamespace ( installedExtension , namespace , initializedExtensions , initializedExtensionsInNamespace ) ; } }
|
Initialize an extension in the given namespace .
|
2,474
|
private void logWarning ( String deprecationType , Object object , String methodName , Info info ) { this . log . warn ( String . format ( "Deprecated usage of %s [%s] in %s@%d,%d" , deprecationType , object . getClass ( ) . getCanonicalName ( ) + "." + methodName , info . getTemplateName ( ) , info . getLine ( ) , info . getColumn ( ) ) ) ; }
|
Helper method to log a warning when a deprecation has been found .
|
2,475
|
protected void extractBeanDescriptor ( ) { Object defaultInstance = null ; try { defaultInstance = getBeanClass ( ) . newInstance ( ) ; } catch ( Exception e ) { LOGGER . debug ( "Failed to create a new default instance for class " + this . beanClass + ". The BeanDescriptor will not contains any default value information." , e ) ; } try { for ( Class < ? > currentClass = this . beanClass ; currentClass != null ; currentClass = currentClass . getSuperclass ( ) ) { Field [ ] fields = currentClass . getFields ( ) ; for ( Field field : fields ) { if ( ! Modifier . isStatic ( field . getModifiers ( ) ) ) { extractPropertyDescriptor ( field , defaultInstance ) ; } } } BeanInfo beanInfo = Introspector . getBeanInfo ( this . beanClass ) ; java . beans . PropertyDescriptor [ ] propertyDescriptors = beanInfo . getPropertyDescriptors ( ) ; if ( propertyDescriptors != null ) { for ( java . beans . PropertyDescriptor propertyDescriptor : propertyDescriptors ) { if ( propertyDescriptor != null ) { extractPropertyDescriptor ( propertyDescriptor , defaultInstance ) ; } } } } catch ( Exception e ) { LOGGER . error ( "Failed to load bean descriptor for class " + this . beanClass , e ) ; } }
|
Extract informations form the bean .
|
2,476
|
protected < T extends Annotation > T extractPropertyAnnotation ( Method writeMethod , Method readMethod , Class < T > annotationClass ) { T parameterDescription = writeMethod . getAnnotation ( annotationClass ) ; if ( parameterDescription == null && readMethod != null ) { parameterDescription = readMethod . getAnnotation ( annotationClass ) ; } return parameterDescription ; }
|
Get the parameter annotation . Try first on the setter then on the getter if no annotation has been found .
|
2,477
|
public int size ( boolean recurse ) { if ( ! recurse ) { return this . children != null ? this . children . size ( ) : 0 ; } int size = 0 ; for ( LogEvent logEvent : this ) { ++ size ; if ( logEvent instanceof LogTreeNode ) { size += ( ( LogTreeNode ) logEvent ) . size ( true ) ; } } return size ; }
|
The number of logs .
|
2,478
|
public static CertificateProvider getCertificateProvider ( ComponentManager manager , Store store , CertificateProvider certificateProvider ) throws GeneralSecurityException { CertificateProvider provider = newCertificateProvider ( manager , store ) ; if ( certificateProvider == null ) { return provider ; } return new ChainingCertificateProvider ( provider , certificateProvider ) ; }
|
Get a certificate provider for a given store and an additional certificate provider .
|
2,479
|
public static void addCertificatesToVerifiedData ( Store store , BcCMSSignedDataVerified verifiedData , CertificateFactory certFactory ) { for ( X509CertificateHolder cert : getCertificates ( store ) ) { verifiedData . addCertificate ( BcUtils . convertCertificate ( certFactory , cert ) ) ; } }
|
Add certificate from signed data to the verified signed data .
|
2,480
|
public static CertificateProvider getCertificateProvider ( ComponentManager manager , Collection < CertifiedPublicKey > certificates ) throws GeneralSecurityException { if ( certificates == null || certificates . isEmpty ( ) ) { return null ; } Collection < X509CertificateHolder > certs = new ArrayList < X509CertificateHolder > ( certificates . size ( ) ) ; for ( CertifiedPublicKey cert : certificates ) { certs . add ( BcUtils . getX509CertificateHolder ( cert ) ) ; } return newCertificateProvider ( manager , new CollectionStore ( certs ) ) ; }
|
Create a new store containing the given certificates and return it as a certificate provider .
|
2,481
|
private static CertificateProvider newCertificateProvider ( ComponentManager manager , Store store ) throws GeneralSecurityException { try { CertificateProvider provider = manager . getInstance ( CertificateProvider . class , "BCStoreX509" ) ; ( ( BcStoreX509CertificateProvider ) provider ) . setStore ( store ) ; return provider ; } catch ( ComponentLookupException e ) { throw new GeneralSecurityException ( "Unable to initialize the certificates store" , e ) ; } }
|
Wrap a bouncy castle store into an adapter for the CertificateProvider interface .
|
2,482
|
public static CertifiedPublicKey getCertificate ( CertificateProvider provider , SignerInformation signer , CertificateFactory factory ) { SignerId id = signer . getSID ( ) ; if ( provider instanceof BcStoreX509CertificateProvider ) { X509CertificateHolder cert = ( ( BcStoreX509CertificateProvider ) provider ) . getCertificate ( id ) ; return ( cert != null ) ? BcUtils . convertCertificate ( factory , cert ) : null ; } X500Name bcIssuer = id . getIssuer ( ) ; BigInteger serial = id . getSerialNumber ( ) ; byte [ ] keyId = id . getSubjectKeyIdentifier ( ) ; if ( bcIssuer != null ) { PrincipalIndentifier issuer = new DistinguishedName ( bcIssuer ) ; if ( keyId != null ) { return provider . getCertificate ( issuer , serial , keyId ) ; } return provider . getCertificate ( issuer , serial ) ; } if ( keyId != null ) { return provider . getCertificate ( keyId ) ; } return null ; }
|
Retrieve the certificate matching the given signer from the certificate provider .
|
2,483
|
public static Version getStrictVersion ( Collection < ? extends VersionRangeCollection > ranges ) { for ( VersionRangeCollection collection : ranges ) { if ( collection . getRanges ( ) . size ( ) == 1 ) { VersionRange range = collection . getRanges ( ) . iterator ( ) . next ( ) ; if ( range instanceof DefaultVersionRange ) { DefaultVersionRange defaultRange = ( DefaultVersionRange ) range ; Version lowerBound = defaultRange . getLowerBound ( ) ; if ( lowerBound != null && ( lowerBound . equals ( defaultRange . getUpperBound ( ) ) ) ) { return lowerBound ; } } } } return null ; }
|
Check if passed range collection is a strict version .
|
2,484
|
public DefaultJobProgressStep addLevel ( int steps , Object newLevelSource , boolean levelStep ) { assertModifiable ( ) ; this . maximumChildren = steps ; this . levelSource = newLevelSource ; if ( steps > 0 ) { this . childSize = 1.0D / steps ; } if ( this . maximumChildren > 0 ) { this . children = new ArrayList < > ( this . maximumChildren ) ; } else { this . children = new ArrayList < > ( ) ; } this . levelStep = levelStep ; return new DefaultJobProgressStep ( null , newLevelSource , this ) ; }
|
Add children to the step and return the first one .
|
2,485
|
public DefaultJobProgressStep nextStep ( Message stepMessage , Object newStepSource ) { assertModifiable ( ) ; finishStep ( ) ; return addStep ( stepMessage , newStepSource ) ; }
|
Move to next child step .
|
2,486
|
public void finishStep ( ) { if ( this . children != null && ! this . children . isEmpty ( ) ) { this . children . get ( this . children . size ( ) - 1 ) . finish ( ) ; } }
|
Finish current step .
|
2,487
|
private void removeNodes ( String xpathExpression , Document domdoc ) { List < Node > nodes = domdoc . selectNodes ( xpathExpression ) ; for ( Node node : nodes ) { node . detach ( ) ; } }
|
Remove the nodes found with the xpath expression .
|
2,488
|
public < T > T get ( String fieldName ) { switch ( fieldName . toLowerCase ( ) ) { case FIELD_REPOSITORY : return ( T ) getRepository ( ) ; case FIELD_ID : return ( T ) getId ( ) . getId ( ) ; case FIELD_VERSION : return ( T ) getId ( ) . getVersion ( ) ; case FIELD_FEATURE : case FIELD_FEATURES : return ( T ) ExtensionIdConverter . toStringList ( getExtensionFeatures ( ) ) ; case FIELD_EXTENSIONFEATURE : case FIELD_EXTENSIONFEATURES : return ( T ) getExtensionFeatures ( ) ; case FIELD_SUMMARY : return ( T ) getSummary ( ) ; case FIELD_DESCRIPTION : return ( T ) getDescription ( ) ; case FIELD_AUTHOR : case FIELD_AUTHORS : return ( T ) getAuthors ( ) ; case FIELD_CATEGORY : return ( T ) getCategory ( ) ; case FIELD_LICENSE : case FIELD_LICENSES : return ( T ) getLicenses ( ) ; case FIELD_NAME : return ( T ) getName ( ) ; case FIELD_TYPE : return ( T ) getType ( ) ; case FIELD_WEBSITE : return ( T ) getWebSite ( ) ; case FIELD_NAMESPACES : case FIELD_ALLOWEDNAMESPACE : case FIELD_ALLOWEDNAMESPACES : return ( T ) getAllowedNamespaces ( ) ; case FIELD_SCM : return ( T ) getScm ( ) ; case FIELD_REPOSITORIES : return ( T ) getRepositories ( ) ; case FIELD_PROPERTIES : return ( T ) getProperties ( ) ; default : return getProperty ( fieldName ) ; } }
|
Get an extension field by name . Fallback on properties .
|
2,489
|
public static String extractXML ( Node node , int start , int length ) { ExtractHandler handler = null ; try { handler = new ExtractHandler ( start , length ) ; Transformer xformer = TransformerFactory . newInstance ( ) . newTransformer ( ) ; xformer . transform ( new DOMSource ( node ) , new SAXResult ( handler ) ) ; return handler . getResult ( ) ; } catch ( Throwable t ) { if ( handler != null && handler . isFinished ( ) ) { return handler . getResult ( ) ; } else { throw new RuntimeException ( "Failed to extract XML" , t ) ; } } }
|
Extracts a well - formed XML fragment from the given DOM tree .
|
2,490
|
public static String unescape ( Object content ) { if ( content == null ) { return null ; } String str = String . valueOf ( content ) ; str = APOS_PATTERN . matcher ( str ) . replaceAll ( "'" ) ; str = QUOT_PATTERN . matcher ( str ) . replaceAll ( "\"" ) ; str = LT_PATTERN . matcher ( str ) . replaceAll ( "<" ) ; str = GT_PATTERN . matcher ( str ) . replaceAll ( ">" ) ; str = AMP_PATTERN . matcher ( str ) . replaceAll ( "&" ) ; str = LCURL_PATTERN . matcher ( str ) . replaceAll ( "{" ) ; return str ; }
|
Unescape encoded special XML characters . Only > ; < ; & ; and { are unescaped since they are the only ones that affect the resulting markup .
|
2,491
|
public static Document parse ( LSInput source ) { try { LSParser p = LS_IMPL . createLSParser ( DOMImplementationLS . MODE_SYNCHRONOUS , null ) ; p . getDomConfig ( ) . setParameter ( "validate" , false ) ; if ( p . getDomConfig ( ) . canSetParameter ( DISABLE_DTD_PARAM , false ) ) { p . getDomConfig ( ) . setParameter ( DISABLE_DTD_PARAM , false ) ; } return p . parse ( source ) ; } catch ( Exception ex ) { LOGGER . warn ( "Cannot parse XML document: [{}]" , ex . getMessage ( ) ) ; return null ; } }
|
Parse a DOM Document from a source .
|
2,492
|
public static String serialize ( Node node , boolean withXmlDeclaration ) { if ( node == null ) { return "" ; } try { LSOutput output = LS_IMPL . createLSOutput ( ) ; StringWriter result = new StringWriter ( ) ; output . setCharacterStream ( result ) ; LSSerializer serializer = LS_IMPL . createLSSerializer ( ) ; serializer . getDomConfig ( ) . setParameter ( "xml-declaration" , withXmlDeclaration ) ; serializer . setNewLine ( "\n" ) ; String encoding = "UTF-8" ; if ( node instanceof Document ) { encoding = ( ( Document ) node ) . getXmlEncoding ( ) ; } else if ( node . getOwnerDocument ( ) != null ) { encoding = node . getOwnerDocument ( ) . getXmlEncoding ( ) ; } output . setEncoding ( encoding ) ; serializer . write ( node , output ) ; return result . toString ( ) ; } catch ( Exception ex ) { LOGGER . warn ( "Failed to serialize node to XML String: [{}]" , ex . getMessage ( ) ) ; return "" ; } }
|
Serialize a DOM Node into a string with an optional XML declaration at the start .
|
2,493
|
public static String transform ( Source xml , Source xslt ) { if ( xml != null && xslt != null ) { try { StringWriter output = new StringWriter ( ) ; Result result = new StreamResult ( output ) ; javax . xml . transform . TransformerFactory . newInstance ( ) . newTransformer ( xslt ) . transform ( xml , result ) ; return output . toString ( ) ; } catch ( Exception ex ) { LOGGER . warn ( "Failed to apply XSLT transformation: [{}]" , ex . getMessage ( ) ) ; } } return null ; }
|
Apply an XSLT transformation to a Document .
|
2,494
|
public static String formatXMLContent ( String content ) throws TransformerFactoryConfigurationError , TransformerException { Transformer transformer = TransformerFactory . newInstance ( ) . newTransformer ( ) ; transformer . setOutputProperty ( OutputKeys . INDENT , "yes" ) ; transformer . setOutputProperty ( "{http://xml.apache.org/xslt}indent-amount" , "2" ) ; StreamResult result = new StreamResult ( new StringWriter ( ) ) ; SAXSource source = new SAXSource ( new InputSource ( new StringReader ( content ) ) ) ; try { XMLReader reader = org . xml . sax . helpers . XMLReaderFactory . createXMLReader ( ) ; reader . setEntityResolver ( new org . xml . sax . EntityResolver ( ) { public InputSource resolveEntity ( String publicId , String systemId ) throws SAXException , IOException { return new InputSource ( new StringReader ( "" ) ) ; } } ) ; source . setXMLReader ( reader ) ; } catch ( Exception e ) { throw new TransformerException ( String . format ( "Failed to create XML Reader while pretty-printing content [%s]" , content ) , e ) ; } transformer . transform ( source , result ) ; return result . getWriter ( ) . toString ( ) ; }
|
Parse and pretty print a XML content .
|
2,495
|
private void declareProperty ( ExecutionContextProperty property ) { if ( this . properties . containsKey ( property . getKey ( ) ) ) { throw new PropertyAlreadyExistsException ( property . getKey ( ) ) ; } this . properties . put ( property . getKey ( ) , property ) ; }
|
Declare a property .
|
2,496
|
public Object setExtensionProperty ( String key , Object value ) { return getExtensionProperties ( ) . put ( key , value ) ; }
|
Sets a custom extension property to be set on each of the extensions that are going to be installed from this request .
|
2,497
|
org . bouncycastle . crypto . params . DSAParameters getDsaParameters ( SecureRandom random , DSAKeyParametersGenerationParameters params ) { DSAParametersGenerator paramGen = getGenerator ( params . getHashHint ( ) ) ; if ( params . use186r3 ( ) ) { DSAParameterGenerationParameters p = new DSAParameterGenerationParameters ( params . getPrimePsize ( ) * 8 , params . getPrimeQsize ( ) * 8 , params . getCertainty ( ) , random , getUsageIndex ( params . getUsage ( ) ) ) ; paramGen . init ( p ) ; } else { paramGen . init ( params . getStrength ( ) * 8 , params . getCertainty ( ) , random ) ; } return paramGen . generateParameters ( ) ; }
|
Generate DSA parameters .
|
2,498
|
private DSAParametersGenerator getGenerator ( String hint ) { if ( hint == null || "SHA-1" . equals ( hint ) ) { return new DSAParametersGenerator ( ) ; } DigestFactory factory ; try { factory = this . manager . getInstance ( DigestFactory . class , hint ) ; } catch ( ComponentLookupException e ) { throw new UnsupportedOperationException ( "Cryptographic hash (digest) algorithm not found." , e ) ; } if ( ! ( factory instanceof AbstractBcDigestFactory ) ) { throw new IllegalArgumentException ( "Requested cryptographic hash algorithm is not implemented by a factory compatible with this factory." + " Factory found: " + factory . getClass ( ) . getName ( ) ) ; } return new DSAParametersGenerator ( ( ( AbstractBcDigestFactory ) factory ) . getDigestInstance ( ) ) ; }
|
Create an instance of a DSA parameter generator using the appropriate hash algorithm .
|
2,499
|
static int getUsageIndex ( DSAKeyValidationParameters . Usage usage ) { if ( usage == DSAKeyValidationParameters . Usage . DIGITAL_SIGNATURE ) { return DSAParameterGenerationParameters . DIGITAL_SIGNATURE_USAGE ; } else if ( usage == DSAKeyValidationParameters . Usage . KEY_ESTABLISHMENT ) { return DSAParameterGenerationParameters . KEY_ESTABLISHMENT_USAGE ; } return - 1 ; }
|
Convert key usage to key usage index .
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.