idx
int64
0
41.2k
question
stringlengths
73
5.81k
target
stringlengths
5
918
9,800
public static String nonBlank ( final String input ) { if ( null == input || "" . equals ( input . trim ( ) ) ) { return null ; } else { return input . trim ( ) ; } }
Return null if the input is null or empty or whitespace otherwise return the input string trimmed .
9,801
public final void verifySingleJarFile ( JarFile jf ) throws IOException , CertificateException , VerifierException { Vector entriesVec = new Vector ( ) ; Manifest man = jf . getManifest ( ) ; if ( man == null ) { throw new VerifierException ( "The JAR is not signed" ) ; } byte [ ] buffer = new byte [ 8192 ] ; Enumerati...
Verify the JAR file signatures with the trusted CA certificates .
9,802
public NodeStepResult executeScriptFile ( StepExecutionContext context , INodeEntry node , String scriptString , String serverScriptFilePath , InputStream scriptAsStream , String fileExtension , String [ ] args , String scriptInterpreter , boolean quoted , final NodeExecutionService executionService , final boolean exp...
Execute a script on a remote node
9,803
public File writeScriptToTempFile ( StepExecutionContext context , INodeEntry node , String scriptString , String serverScriptFilePath , InputStream scriptAsStream , boolean expandTokens ) throws FileCopierException { File temp ; if ( null != scriptString ) { temp = fileCopierUtil . writeScriptTempFile ( context , null...
Copy the script input to a temp file and expand embedded tokens if it is a string or inputstream . If it is a local file use the original without modification
9,804
public ExecArgList removeArgsForOsFamily ( String filepath , String osFamily ) { if ( "windows" . equalsIgnoreCase ( osFamily ) ) { return ExecArgList . fromStrings ( false , "del" , filepath ) ; } else { return ExecArgList . fromStrings ( false , "rm" , "-f" , filepath ) ; } }
Return ExecArgList for removing a file for the given OS family
9,805
public boolean shouldExclude ( final INodeEntry entry ) { if ( null != getSingleNodeName ( ) ) { return ! getSingleNodeName ( ) . equals ( entry . getNodename ( ) ) ; } boolean includesMatch = includes != null && includes . matches ( entry ) ; boolean excludesMatch = excludes != null && excludes . matches ( entry ) ; i...
Return true if the node entry should be excluded based on the includes and excludes parameters . When both include and exclude patterns match the node it will be excluded based on which filterset is dominant .
9,806
public void validate ( ) { if ( null != failedNodesfile && failedNodesfile . getName ( ) . startsWith ( "${" ) && failedNodesfile . getName ( ) . endsWith ( "}" ) ) { failedNodesfile = null ; } }
Validate input . If failedNodesfile looks like an invalid property reference set it to null .
9,807
public static NodeSet fromFilter ( String filter ) { Map < String , Map < String , String > > stringMapMap = parseFilter ( filter ) ; NodeSet nodeSet = new NodeSet ( ) ; nodeSet . createInclude ( stringMapMap . get ( "include" ) ) ; nodeSet . createExclude ( stringMapMap . get ( "exclude" ) ) ; return nodeSet ; }
Create a NodeSet from a filter
9,808
public static Path pathForFileInRoot ( final File rootDir , final File file ) { String filePath = file . getAbsolutePath ( ) ; String rootPath = rootDir . getAbsolutePath ( ) ; if ( ! filePath . startsWith ( rootPath ) ) { throw new IllegalArgumentException ( "not a file in the root directory: " + file ) ; } return pat...
Return a storage Path given a file within a given root dir
9,809
public static Path pathForRelativeFilepath ( final String filepath , final String separator ) { String [ ] comps = filepath . split ( Pattern . quote ( separator ) ) ; return PathUtil . pathFromComponents ( comps ) ; }
Return a storage path given a relative file path string
9,810
private PasswordSource passwordSourceWithPrefix ( final NodeSSHConnectionInfo nodeAuthentication , final String prefix ) throws IOException { if ( null != nodeAuthentication . getSudoPasswordStoragePath ( prefix ) ) { return new BasicSource ( nodeAuthentication . getSudoPasswordStorageData ( prefix ) ) ; } else { retur...
create password source
9,811
void shutdownAndAwaitTermination ( ExecutorService pool ) { pool . shutdownNow ( ) ; try { logger . debug ( "Waiting up to 30 seconds for ExecutorService to shut down" ) ; if ( ! pool . awaitTermination ( 30 , TimeUnit . SECONDS ) ) { logger . debug ( "Pool did not terminate" ) ; } } catch ( InterruptedException ie ) {...
Shutdown the ExecutorService
9,812
private TreeBuilder < ResourceMeta > baseConverter ( TreeBuilder < ResourceMeta > builder ) { if ( null != defaultConverters && defaultConverters . contains ( "StorageTimestamperConverter" ) ) { logger . debug ( "Configuring base converter: StorageTimestamperConverter" ) ; builder = builder . convert ( new StorageConve...
Apply base converters for metadata timestamps
9,813
private TreeBuilder < ResourceMeta > addLogger ( TreeBuilder < ResourceMeta > builder , Map < String , String > config ) { String loggerName = getLoggerName ( ) ; if ( null != config . get ( LOGGER_NAME ) ) { loggerName = config . get ( LOGGER_NAME ) ; } if ( null == loggerName ) { loggerName = ORG_RUNDECK_STORAGE_EVEN...
Append final listeners to the tree
9,814
private TreeBuilder < ResourceMeta > baseStorage ( TreeBuilder < ResourceMeta > builder ) { Map < String , String > config1 = expandConfig ( getBaseStorageConfig ( ) ) ; logger . debug ( "Default base storage provider: " + getBaseStorageType ( ) + ", " + "config: " + config1 ) ; StoragePlugin base = loadPlugin ( getBas...
Set up the base storage layer for the tree
9,815
private TreeBuilder < ResourceMeta > configureConverterPlugin ( TreeBuilder < ResourceMeta > builder , int index , Map < String , String > configProps ) { String pref1 = getConverterConfigPrefix ( ) + SEP + index ; String pluginType = configProps . get ( pref1 + SEP + TYPE ) ; String pathProp = pref1 + SEP + PATH ; Str...
Configure converter plugins for the builder
9,816
private TreeBuilder < ResourceMeta > buildConverterPlugin ( TreeBuilder < ResourceMeta > builder , String pluginType , String path , String selector , Map < String , String > config ) { StorageConverterPlugin converterPlugin = loadPlugin ( pluginType , config , storageConverterPluginProviderService ) ; return builder ....
Append a converter plugin to the tree builder
9,817
private Map < String , String > subPropertyMap ( String configPrefix , Map propertiesMap ) { Map < String , String > config = new HashMap < String , String > ( ) ; for ( Object o : propertiesMap . keySet ( ) ) { String key = ( String ) o ; if ( key . startsWith ( configPrefix ) ) { String conf = key . substring ( confi...
Extract a map of the property values starting with the given prefix
9,818
private void configureStoragePlugin ( TreeBuilder < ResourceMeta > builder , int index , Map < String , String > configProps ) { String pref1 = getStorageConfigPrefix ( ) + SEP + index ; String pluginType = configProps . get ( pref1 + SEP + TYPE ) ; String path = configProps . get ( pref1 + SEP + PATH ) ; boolean remov...
Configures storage plugins with the builder
9,819
private Map < String , String > expandConfig ( Map < String , String > map ) { return expandAllProperties ( map , getPropertyLookup ( ) . getPropertiesMap ( ) ) ; }
Expand embedded framework property references in the map values
9,820
public static File writeScriptTempfile ( final Framework framework , final Reader source , final LineEndingStyle style ) throws IOException { return writeScriptTempfile ( framework , null , null , source , style ) ; }
Copy reader content to a tempfile for script execution
9,821
public static File writeScriptTempfile ( final Framework framework , final InputStream stream , final String source , final Reader reader , final LineEndingStyle style ) throws IOException { final File scriptfile = createTempFile ( framework ) ; writeScriptFile ( stream , source , reader , style , scriptfile ) ; return...
Copy a source stream or string content to a tempfile for script execution
9,822
public static void writeScriptFile ( InputStream stream , String scriptString , Reader reader , LineEndingStyle style , File scriptfile ) throws IOException { try ( FileWriter writer = new FileWriter ( scriptfile ) ) { if ( null != scriptString ) { ScriptfileUtils . writeReader ( new StringReader ( scriptString ) , wri...
Write script content to a destination file from one of the sources
9,823
public static void setExecutePermissions ( final File scriptfile ) throws IOException { if ( ! scriptfile . setExecutable ( true , true ) ) { System . err . println ( "Unable to set executable bit on temp script file, execution may fail: " + scriptfile . getAbsolutePath ( ) ) ; } }
Set the executable flag on a file if supported by the OS
9,824
public int getDocId ( String url ) { synchronized ( mutex ) { OperationStatus result = null ; DatabaseEntry value = new DatabaseEntry ( ) ; try { DatabaseEntry key = new DatabaseEntry ( url . getBytes ( ) ) ; result = docIDsDB . get ( null , key , value , null ) ; } catch ( RuntimeException e ) { if ( config . isHaltOn...
Returns the docid of an already seen url .
9,825
protected byte [ ] toByteArray ( HttpEntity entity , int maxBytes ) throws IOException { if ( entity == null ) { return new byte [ 0 ] ; } try ( InputStream is = entity . getContent ( ) ) { int size = ( int ) entity . getContentLength ( ) ; int readBufferLength = size ; if ( readBufferLength <= 0 ) { readBufferLength =...
Read contents from an entity with a specified maximum . This is a replacement of EntityUtils . toByteArray because that function does not impose a maximum size .
9,826
public void load ( HttpEntity entity , int maxBytes ) throws IOException { contentType = null ; Header type = entity . getContentType ( ) ; if ( type != null ) { contentType = type . getValue ( ) ; } contentEncoding = null ; Header encoding = entity . getContentEncoding ( ) ; if ( encoding != null ) { contentEncoding =...
Loads the content of this page from a fetched HttpEntity .
9,827
public static boolean matchesRobotsPattern ( String pattern , String path ) { return robotsPatternToRegexp ( pattern ) . matcher ( path ) . matches ( ) ; }
Check if the specified path matches a robots . txt pattern
9,828
public void validate ( ) throws Exception { if ( crawlStorageFolder == null ) { throw new Exception ( "Crawl storage folder is not set in the CrawlConfig." ) ; } if ( politenessDelay < 0 ) { throw new Exception ( "Invalid value for politeness delay: " + politenessDelay ) ; } if ( maxDepthOfCrawling < - 1 ) { throw new ...
Validates the configs specified by this instance .
9,829
public boolean allows ( WebURL webURL ) throws IOException , InterruptedException { if ( ! config . isEnabled ( ) ) { return true ; } try { URL url = new URL ( webURL . getURL ( ) ) ; String host = getHost ( url ) ; String path = url . getPath ( ) ; HostDirectives directives = host2directivesCache . get ( host ) ; if (...
Please note that in the case of a bad URL TRUE will be returned
9,830
public int checkAccess ( String path ) { timeLastAccessed = System . currentTimeMillis ( ) ; int result = UNDEFINED ; String myUA = config . getUserAgentName ( ) ; boolean ignoreUADisc = config . getIgnoreUADiscrimination ( ) ; for ( UserAgentDirectives ua : rules ) { int score = ua . match ( myUA ) ; if ( score == 0 &...
Check if any of the rules say anything about the specified path
9,831
private static Map < String , String > createParameterMap ( String queryString ) { if ( ( queryString == null ) || queryString . isEmpty ( ) ) { return null ; } final String [ ] pairs = queryString . split ( "&" ) ; final Map < String , String > params = new LinkedHashMap < > ( pairs . length ) ; for ( final String pai...
Takes a query string separates the constituent name - value pairs and stores them in a LinkedHashMap ordered by their original order .
9,832
public int match ( String userAgent ) { userAgent = userAgent . toLowerCase ( ) ; int maxLength = 0 ; for ( String ua : userAgents ) { if ( ua . equals ( "*" ) || userAgent . contains ( ua ) ) { maxLength = Math . max ( maxLength , ua . length ( ) ) ; } } return maxLength ; }
Match the current user agent directive set with the given user agent . The returned value will be the maximum match length of any user agent .
9,833
public void init ( int id , CrawlController crawlController ) throws InstantiationException , IllegalAccessException { this . myId = id ; this . pageFetcher = crawlController . getPageFetcher ( ) ; this . robotstxtServer = crawlController . getRobotstxtServer ( ) ; this . docIdServer = crawlController . getDocIdServer ...
Initializes the current instance of the crawler
9,834
protected void onUnhandledException ( WebURL webUrl , Throwable e ) { if ( myController . getConfig ( ) . isHaltOnError ( ) && ! ( e instanceof IOException ) ) { throw new RuntimeException ( "unhandled exception" , e ) ; } else { String urlStr = ( webUrl == null ? "NULL" : webUrl . getURL ( ) ) ; logger . warn ( "Unhan...
This function is called when a unhandled exception was encountered during fetching
9,835
public boolean shouldVisit ( Page referringPage , WebURL url ) { if ( myController . getConfig ( ) . isRespectNoFollow ( ) ) { return ! ( ( referringPage != null && referringPage . getContentType ( ) != null && referringPage . getContentType ( ) . contains ( "html" ) && ( ( HtmlParseData ) referringPage . getParseData ...
Classes that extends WebCrawler should overwrite this function to tell the crawler whether the given url should be crawled or not . The following default implementation indicates that all urls should be included in the crawl except those with a nofollow flag .
9,836
public < T extends WebCrawler > void start ( Class < T > clazz , int numberOfCrawlers ) { this . start ( new DefaultWebCrawlerFactory < > ( clazz ) , numberOfCrawlers , true ) ; }
Start the crawling session and wait for it to finish . This method utilizes default crawler factory that creates new crawler using Java reflection
9,837
public < T extends WebCrawler > void start ( WebCrawlerFactory < T > crawlerFactory , int numberOfCrawlers ) { this . start ( crawlerFactory , numberOfCrawlers , true ) ; }
Start the crawling session and wait for it to finish .
9,838
public < T extends WebCrawler > void startNonBlocking ( WebCrawlerFactory < T > crawlerFactory , final int numberOfCrawlers ) { this . start ( crawlerFactory , numberOfCrawlers , false ) ; }
Start the crawling session and return immediately .
9,839
public < T extends WebCrawler > void startNonBlocking ( Class < T > clazz , int numberOfCrawlers ) { start ( new DefaultWebCrawlerFactory < > ( clazz ) , numberOfCrawlers , false ) ; }
Start the crawling session and return immediately . This method utilizes default crawler factory that creates new crawler using Java reflection
9,840
public void waitUntilFinish ( ) { while ( ! finished ) { synchronized ( waitingLock ) { if ( config . isHaltOnError ( ) ) { Throwable t = getError ( ) ; if ( t != null && config . isHaltOnError ( ) ) { if ( t instanceof RuntimeException ) { throw ( RuntimeException ) t ; } else if ( t instanceof Error ) { throw ( Error...
Wait until this crawling session finishes .
9,841
public void addSeed ( String pageUrl , int docId ) throws IOException , InterruptedException { String canonicalUrl = URLCanonicalizer . getCanonicalURL ( pageUrl ) ; if ( canonicalUrl == null ) { logger . error ( "Invalid seed URL: {}" , pageUrl ) ; } else { if ( docId < 0 ) { docId = docIdServer . getDocId ( canonical...
Adds a new seed URL . A seed URL is a URL that is fetched by the crawler to extract new URLs in it and follow them for crawling . You can also specify a specific document id to be assigned to this seed URL . This document id needs to be unique . Also note that if you add three seeds with document ids 1 2 and 7 . Then t...
9,842
public void addSeenUrl ( String url , int docId ) throws UnsupportedEncodingException { String canonicalUrl = URLCanonicalizer . getCanonicalURL ( url ) ; if ( canonicalUrl == null ) { logger . error ( "Invalid Url: {} (can't cannonicalize it!)" , url ) ; } else { try { docIdServer . addUrlAndDocId ( canonicalUrl , doc...
This function can called to assign a specific document id to a url . This feature is useful when you have had a previous crawl and have stored the Urls and their associated document ids and want to have a new crawl which is aware of the previously seen Urls and won t re - crawl them .
9,843
private void addNtCredentials ( NtAuthInfo authInfo , Map < AuthScope , Credentials > credentialsMap ) { logger . info ( "NT authentication for: {}" , authInfo . getLoginTarget ( ) ) ; try { Credentials credentials = new NTCredentials ( authInfo . getUsername ( ) , authInfo . getPassword ( ) , InetAddress . getLocalHos...
Do NT auth for Microsoft AD sites .
9,844
public static ViewDragHelper create ( ViewGroup forParent , Interpolator interpolator , Callback cb ) { return new ViewDragHelper ( forParent . getContext ( ) , forParent , interpolator , cb ) ; }
Factory method to create a new ViewDragHelper with the specified interpolator .
9,845
private float clampMag ( float value , float absMin , float absMax ) { final float absValue = Math . abs ( value ) ; if ( absValue < absMin ) return 0 ; if ( absValue > absMax ) return value > 0 ? absMax : - absMax ; return value ; }
Clamp the magnitude of value for absMin and absMax . If the value is below the minimum it will be clamped to zero . If the value is above the maximum it will be clamped to the maximum .
9,846
boolean tryCaptureViewForDrag ( View toCapture , int pointerId ) { if ( toCapture == mCapturedView && mActivePointerId == pointerId ) { return true ; } if ( toCapture != null && mCallback . tryCaptureView ( toCapture , pointerId ) ) { mActivePointerId = pointerId ; captureChildView ( toCapture , pointerId ) ; return tr...
Attempt to capture the view with the given pointer ID . The callback will be involved . This will put us into the dragging state . If we ve already captured this view with this pointer this method will immediately return true without consulting the callback .
9,847
private boolean checkTouchSlop ( View child , float dx , float dy ) { if ( child == null ) { return false ; } final boolean checkHorizontal = mCallback . getViewHorizontalDragRange ( child ) > 0 ; final boolean checkVertical = mCallback . getViewVerticalDragRange ( child ) > 0 ; if ( checkHorizontal && checkVertical ) ...
Check if we ve crossed a reasonable touch slop for the given child view . If the child cannot be dragged along the horizontal or vertical axis motion along that axis will not count toward the slop check .
9,848
public boolean checkTouchSlop ( int directions ) { final int count = mInitialMotionX . length ; for ( int i = 0 ; i < count ; i ++ ) { if ( checkTouchSlop ( directions , i ) ) { return true ; } } return false ; }
Check if any pointer tracked in the current gesture has crossed the required slop threshold .
9,849
public boolean checkTouchSlop ( int directions , int pointerId ) { if ( ! isPointerDown ( pointerId ) ) { return false ; } final boolean checkHorizontal = ( directions & DIRECTION_HORIZONTAL ) == DIRECTION_HORIZONTAL ; final boolean checkVertical = ( directions & DIRECTION_VERTICAL ) == DIRECTION_VERTICAL ; final float...
Check if the specified pointer tracked in the current gesture has crossed the required slop threshold .
9,850
public boolean isViewUnder ( View view , int x , int y ) { if ( view == null ) { return false ; } return x >= view . getLeft ( ) && x < view . getRight ( ) && y >= view . getTop ( ) && y < view . getBottom ( ) ; }
Determine if the supplied view is under the given point in the parent view s coordinate system .
9,851
public int getScrollableViewScrollPosition ( View scrollableView , boolean isSlidingUp ) { if ( scrollableView == null ) return 0 ; if ( scrollableView instanceof ScrollView ) { if ( isSlidingUp ) { return scrollableView . getScrollY ( ) ; } else { ScrollView sv = ( ( ScrollView ) scrollableView ) ; View child = sv . g...
Returns the current scroll position of the scrollable view . If this method returns zero or less it means at the scrollable view is in a position such as the panel should handle scrolling . If the method returns anything above zero then the panel will let the scrollable view handle the scrolling
9,852
protected void onFinishInflate ( ) { super . onFinishInflate ( ) ; if ( mDragViewResId != - 1 ) { setDragView ( findViewById ( mDragViewResId ) ) ; } if ( mScrollableViewResId != - 1 ) { setScrollableView ( findViewById ( mScrollableViewResId ) ) ; } }
Set the Drag View after the view is inflated
9,853
public void setPanelHeight ( int val ) { if ( getPanelHeight ( ) == val ) { return ; } mPanelHeight = val ; if ( ! mFirstLayout ) { requestLayout ( ) ; } if ( getPanelState ( ) == PanelState . COLLAPSED ) { smoothToBottom ( ) ; invalidate ( ) ; return ; } }
Set the collapsed panel height in pixels
9,854
public void setPanelState ( PanelState state ) { if ( mDragHelper . getViewDragState ( ) == ViewDragHelper . STATE_SETTLING ) { Log . d ( TAG , "View is settling. Aborting animation." ) ; mDragHelper . abort ( ) ; } if ( state == null || state == PanelState . DRAGGING ) { throw new IllegalArgumentException ( "Panel sta...
Change panel state to the given state with
9,855
private void trimNode ( final Node node ) { NodeList children = node . getChildNodes ( ) ; for ( int i = children . getLength ( ) - 1 ; i >= 0 ; i -- ) { trimChild ( node , children . item ( i ) ) ; } }
Whitespace will be kept by DOM parser .
9,856
public static int copy ( InputStream in , OutputStream out ) throws IOException { int byteCount = 0 ; byte [ ] buffer = new byte [ BUFFER_SIZE ] ; int bytesRead = - 1 ; while ( ( bytesRead = in . read ( buffer ) ) != - 1 ) { out . write ( buffer , 0 , bytesRead ) ; byteCount += bytesRead ; } out . flush ( ) ; return by...
Copy the contents of the given InputStream to the given OutputStream . Leaves both streams open when done .
9,857
public static String convertToXML ( Object object ) { try { if ( ! JAXB_CONTEXT_MAP . containsKey ( object . getClass ( ) ) ) { JAXB_CONTEXT_MAP . put ( object . getClass ( ) , JAXBContext . newInstance ( object . getClass ( ) ) ) ; } Marshaller marshaller = JAXB_CONTEXT_MAP . get ( object . getClass ( ) ) . createMars...
Object to XML
9,858
public GrpcServerLimiterBuilder partitionByHeader ( Metadata . Key < String > header ) { return partitionResolver ( context -> context . getHeaders ( ) . get ( header ) ) ; }
Partition the limit by a request header .
9,859
public GrpcServerLimiterBuilder partitionByAttribute ( Attributes . Key < String > attribute ) { return partitionResolver ( context -> context . getCall ( ) . getAttributes ( ) . get ( attribute ) ) ; }
Partition the limit by a request attribute .
9,860
public ServletLimiterBuilder partitionByHeader ( String name ) { return partitionResolver ( request -> Optional . ofNullable ( request . getHeader ( name ) ) . orElse ( null ) ) ; }
Partition the limit by header
9,861
public ServletLimiterBuilder partitionByAttribute ( String name ) { return partitionResolver ( request -> Optional . ofNullable ( request . getAttribute ( name ) ) . map ( Object :: toString ) . orElse ( null ) ) ; }
Partition the limit by request attribute
9,862
public ServletLimiterBuilder partitionByParameter ( String name ) { return partitionResolver ( request -> Optional . ofNullable ( request . getParameter ( name ) ) . orElse ( null ) ) ; }
Partition the limit by request parameter
9,863
public static < ContextT > BlockingLimiter < ContextT > wrap ( Limiter < ContextT > delegate , Duration timeout ) { Preconditions . checkArgument ( timeout . compareTo ( MAX_TIMEOUT ) < 0 , "Timeout cannot be greater than " + MAX_TIMEOUT ) ; return new BlockingLimiter < > ( delegate , timeout ) ; }
Wrap a limiter such that acquire will block up to a provided timeout if the limit was reached instead of return an empty listener immediately
9,864
public Optional < QualityGateData > getQualityGate ( DbSession dbSession , OrganizationDto organization , ComponentDto component ) { Optional < QualityGateData > res = dbClient . projectQgateAssociationDao ( ) . selectQGateIdByComponentId ( dbSession , component . getId ( ) ) . map ( qualityGateId -> dbClient . quality...
Return effective quality gate of a project .
9,865
private void unloadIncompatiblePlugins ( ) { Set < String > removedKeys = new HashSet < > ( ) ; do { removedKeys . clear ( ) ; for ( PluginInfo plugin : pluginInfosByKeys . values ( ) ) { if ( ! isCompatible ( plugin , runtime , pluginInfosByKeys ) ) { removedKeys . add ( plugin . getKey ( ) ) ; } } for ( String remove...
Removes the plugins that are not compatible with current environment .
9,866
public void uninstall ( String pluginKey , File uninstallDir ) { Set < String > uninstallKeys = new HashSet < > ( ) ; uninstallKeys . add ( pluginKey ) ; appendDependentPluginKeys ( pluginKey , uninstallKeys ) ; for ( String uninstallKey : uninstallKeys ) { PluginInfo info = getPluginInfo ( uninstallKey ) ; try { if ( ...
Uninstall a plugin and its dependents
9,867
private void appendDependentPluginKeys ( String pluginKey , Set < String > appendTo ) { for ( PluginInfo otherPlugin : getPluginInfos ( ) ) { if ( ! otherPlugin . getKey ( ) . equals ( pluginKey ) ) { for ( PluginInfo . RequiredPlugin requirement : otherPlugin . getRequiredPlugins ( ) ) { if ( requirement . getKey ( ) ...
Appends dependent plugins only the ones that still exist in the plugins folder .
9,868
public static Map < String , Long > toMap ( List < KeyLongValue > values ) { return values . stream ( ) . collect ( uniqueIndex ( KeyLongValue :: getKey , KeyLongValue :: getValue , values . size ( ) ) ) ; }
This method does not keep order of list .
9,869
private void removeDuplicatedProjects ( DbSession session , String projectKey ) { List < ComponentDto > duplicated = dbClient . componentDao ( ) . selectComponentsHavingSameKeyOrderedById ( session , projectKey ) ; for ( int i = 1 ; i < duplicated . size ( ) ; i ++ ) { dbClient . componentDao ( ) . delete ( session , d...
On MySQL as PROJECTS . KEE is not unique if the same project is provisioned multiple times then it will be duplicated in the database . So after creating a project we commit and we search in the db if their are some duplications and we remove them .
9,870
public void endOfGroup ( ) { ClonePart origin = null ; CloneGroup . Builder builder = CloneGroup . builder ( ) . setLength ( length ) ; List < ClonePart > parts = new ArrayList < > ( count ) ; for ( int [ ] b : blockNumbers ) { Block firstBlock = text . getBlock ( b [ 0 ] ) ; Block lastBlock = text . getBlock ( b [ 1 ]...
Constructs CloneGroup and saves it .
9,871
private boolean isFirstAnalysisSecondaryLongLivingBranch ( ) { if ( analysisMetadataHolder . isFirstAnalysis ( ) ) { Branch branch = analysisMetadataHolder . getBranch ( ) ; return ! branch . isMain ( ) && branch . getType ( ) == BranchType . LONG ; } return false ; }
Special case where we want to do the issue tracking with the merge branch and copy matched issue to the current branch .
9,872
public List < CustomMeasureDto > selectByMetricKeyAndTextValue ( DbSession session , String metricKey , String textValue ) { return mapper ( session ) . selectByMetricKeyAndTextValue ( metricKey , textValue ) ; }
Used by Views plugin
9,873
public String getId ( ) { return config . get ( CoreProperties . SERVER_ID ) . orElse ( null ) ; }
Can be null when server is waiting for migration
9,874
static int getNextAvailablePort ( InetAddress address , PortAllocator portAllocator ) { for ( int i = 0 ; i < PORT_MAX_TRIES ; i ++ ) { int port = portAllocator . getAvailable ( address ) ; if ( isValidPort ( port ) ) { PORTS_ALREADY_ALLOCATED . add ( port ) ; return port ; } } throw new IllegalStateException ( "Fail t...
Warning - the allocated ports are kept in memory and are never clean - up . Besides the memory consumption that means that ports already allocated are never freed . As a consequence no more than ~64512 calls to this method are allowed .
9,875
public void commitAndIndex ( DbSession dbSession , int ruleId , OrganizationDto organization ) { List < EsQueueDto > items = asList ( createQueueDtoForRule ( ruleId ) , createQueueDtoForRuleExtension ( ruleId , organization ) ) ; dbClient . esQueueDao ( ) . insert ( dbSession , items ) ; dbSession . commit ( ) ; postCo...
Commit a change on a rule and its extension on the given organization
9,876
public SearchOptions setLimit ( int limit ) { if ( limit <= 0 ) { this . limit = MAX_LIMIT ; } else { this . limit = Math . min ( limit , MAX_LIMIT ) ; } return this ; }
Sets the limit on the number of results to return .
9,877
public static File unzip ( File zip , File toDir ) throws IOException { return unzip ( zip , toDir , ( Predicate < ZipEntry > ) ze -> true ) ; }
Unzip a file into a directory . The directory is created if it does not exist .
9,878
public boolean match ( String value ) { value = StringUtils . removeStart ( value , "/" ) ; value = StringUtils . removeEnd ( value , "/" ) ; return pattern . matcher ( value ) . matches ( ) ; }
Returns true if specified value matches this pattern .
9,879
public static boolean match ( WildcardPattern [ ] patterns , String value ) { for ( WildcardPattern pattern : patterns ) { if ( pattern . match ( value ) ) { return true ; } } return false ; }
Returns true if specified value matches one of specified patterns .
9,880
public String readString ( URI uri , Charset charset ) { return searchForSupportedProcessor ( uri ) . readString ( uri , charset ) ; }
Reads all characters from uri using the given character set . It throws an unchecked exception if an error occurs .
9,881
public String description ( URI uri ) { SchemeProcessor reader = searchForSupportedProcessor ( uri ) ; return reader . description ( uri ) ; }
Returns a detailed description of the given uri . For example HTTP URIs are completed with the configured HTTP proxy .
9,882
private static Optional < EvaluatedCondition > evaluateCondition ( Condition condition , ValueType type , Comparable value ) { Comparable threshold = getThreshold ( condition , type ) ; if ( reachThreshold ( value , threshold , condition ) ) { return of ( new EvaluatedCondition ( condition , EvaluationStatus . ERROR , ...
Evaluates the error condition . Returns empty if threshold or measure value is not defined .
9,883
public < T > Cursor < T > selectCursor ( String statement ) { return session . selectCursor ( statement ) ; }
We only care about the the commit section . The rest is simply passed to its parent .
9,884
public static Properties parseArguments ( String [ ] args ) { Properties props = argumentsToProperties ( args ) ; for ( Map . Entry < Object , Object > entry : System . getProperties ( ) . entrySet ( ) ) { String key = entry . getKey ( ) . toString ( ) ; if ( key . startsWith ( "sonar." ) ) { props . setProperty ( key ...
Build properties from command - line arguments and system properties
9,885
static Properties argumentsToProperties ( String [ ] args ) { Properties props = new Properties ( ) ; for ( String arg : args ) { if ( ! arg . startsWith ( "-D" ) || ! arg . contains ( "=" ) ) { throw new IllegalArgumentException ( String . format ( "Command-line argument must start with -D, for example -Dsonar.jdbc.us...
Convert strings - Dkey = value to properties
9,886
private void ensureCapacity ( ) { if ( size < resourceIds . length ) { return ; } int newCapacity = ( resourceIds . length * 3 ) / 2 + 1 ; String [ ] oldResourceIds = resourceIds ; resourceIds = new String [ newCapacity ] ; System . arraycopy ( oldResourceIds , 0 , resourceIds , 0 , oldResourceIds . length ) ; int [ ] ...
Increases the capacity if necessary .
9,887
private void ensureSorted ( ) { if ( sorted ) { return ; } ensureCapacity ( ) ; DataUtils . sort ( byBlockHash ) ; for ( int i = 0 ; i < size ; i ++ ) { resourceIdsIndex [ i ] = i ; } DataUtils . sort ( byResourceId ) ; sorted = true ; }
Performs sorting if necessary .
9,888
public boolean getBooleanProperty ( String key ) { requireNonNull ( key ) ; String value = properties . get ( key ) ; return value != null && Boolean . parseBoolean ( value ) ; }
Returns the value of the property for this resource type .
9,889
public boolean shouldExecute ( DefaultSensorDescriptor descriptor ) { if ( ! fsCondition ( descriptor ) ) { LOG . debug ( "'{}' skipped because there is no related file in current project" , descriptor . name ( ) ) ; return false ; } if ( ! activeRulesCondition ( descriptor ) ) { LOG . debug ( "'{}' skipped because the...
Decide if the given Sensor should be executed .
9,890
public Metric < G > merge ( final Metric with ) { this . description = with . description ; this . domain = with . domain ; this . enabled = with . enabled ; this . qualitative = with . qualitative ; this . worstValue = with . worstValue ; this . bestValue = with . bestValue ; this . optimizedBestValue = with . optimiz...
Merge with fields from other metric . All fields are copied except the id .
9,891
public List < SnapshotDto > selectFinishedByComponentUuidsAndFromDates ( DbSession dbSession , List < String > componentUuids , List < Long > fromDates ) { checkArgument ( componentUuids . size ( ) == fromDates . size ( ) , "The number of components (%s) and from dates (%s) must be the same." , String . valueOf ( compo...
Returned finished analysis from a list of projects and dates . Finished analysis means that the status in the CE_ACTIVITY table is SUCCESS = > the goal is to be sure that the CE task is completely finished .
9,892
public String formatDateTime ( Locale locale , Date date ) { return DateFormat . getDateTimeInstance ( DateFormat . DEFAULT , DateFormat . SHORT , locale ) . format ( date ) ; }
Format date for the given locale . JVM timezone is used .
9,893
String messageFromFile ( Locale locale , String filename , String relatedProperty ) { String result = null ; String bundleBase = propertyToBundles . get ( relatedProperty ) ; if ( bundleBase == null ) { return null ; } String filePath = bundleBase . replace ( '.' , '/' ) ; if ( ! "en" . equals ( locale . getLanguage ( ...
Only the given locale is searched . Contrary to java . util . ResourceBundle no strategy for locating the bundle is implemented in this method .
9,894
public RangeDistributionBuilder add ( Number value , int count ) { if ( greaterOrEqualsThan ( value , bottomLimits [ 0 ] ) ) { addValue ( value , count ) ; isEmpty = false ; } return this ; }
Increments an entry
9,895
static GroupWsRef fromId ( int id ) { checkArgument ( id > - 1 , "Group id must be positive: %s" , id ) ; return new GroupWsRef ( id , null , null ) ; }
Creates a reference to a group by its id . Virtual groups Anyone can t be returned as they can t be referenced by an id .
9,896
public static String createErrorMessage ( HttpException exception ) { String json = tryParseAsJsonError ( exception . content ( ) ) ; if ( json != null ) { return json ; } String msg = "HTTP code " + exception . code ( ) ; if ( isHtml ( exception . content ( ) ) ) { return msg ; } return msg + ": " + StringUtils . left...
Tries to form a short and relevant error message from the exception to be displayed in the console .
9,897
public static double parseNumber ( String number , Locale locale ) throws ParseException { if ( "" . equals ( number ) ) { return Double . NaN ; } return NumberFormat . getNumberInstance ( locale ) . parse ( number ) . doubleValue ( ) ; }
Parses a string with a locale and returns the corresponding number
9,898
public static double scaleValue ( double value , int decimals ) { BigDecimal bd = BigDecimal . valueOf ( value ) ; return bd . setScale ( decimals , RoundingMode . HALF_UP ) . doubleValue ( ) ; }
Scales a double value with decimals
9,899
public List < UserPermissionDto > selectUserPermissionsByQuery ( DbSession dbSession , PermissionQuery query , Collection < Integer > userIds ) { if ( userIds . isEmpty ( ) ) { return emptyList ( ) ; } checkArgument ( userIds . size ( ) <= DatabaseUtils . PARTITION_SIZE_FOR_ORACLE , "Maximum 1'000 users are accepted" )...
List of user permissions ordered by alphabetical order of user names . Pagination is NOT applied . No sort is done .