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 ] ; Enumeration entries = jf . entries ( ) ; while ( entries . hasMoreElements ( ) ) { JarEntry je = ( JarEntry ) entries . nextElement ( ) ; entriesVec . addElement ( je ) ; InputStream is = jf . getInputStream ( je ) ; int n ; while ( ( n = is . read ( buffer , 0 , buffer . length ) ) != - 1 ) { } is . close ( ) ; } jf . close ( ) ; Enumeration e = entriesVec . elements ( ) ; while ( e . hasMoreElements ( ) ) { JarEntry je = ( JarEntry ) e . nextElement ( ) ; if ( je . isDirectory ( ) ) { continue ; } Certificate [ ] certs = je . getCertificates ( ) ; if ( ( certs == null ) || ( certs . length == 0 ) ) { if ( ! je . getName ( ) . startsWith ( "META-INF" ) ) { throw new VerifierException ( "The JAR file has unsigned files." ) ; } } else { Certificate [ ] chainRoots = getChainRoots ( certs ) ; boolean signedAsExpected = false ; for ( int i = 0 ; i < chainRoots . length ; i ++ ) { if ( isTrusted ( ( X509Certificate ) chainRoots [ i ] , trustedCaCerts ) ) { signedAsExpected = true ; break ; } } if ( ! signedAsExpected ) { throw new VerifierException ( "The JAR file is not signed by a trusted signer" ) ; } } } } | 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 expandTokens ) throws NodeStepException { final String filename ; if ( null != scriptString ) { filename = "dispatch-script.tmp" ; } else if ( null != serverScriptFilePath ) { filename = new File ( serverScriptFilePath ) . getName ( ) ; } else { filename = "dispatch-script.tmp" ; } String ident = null != context . getDataContext ( ) && null != context . getDataContext ( ) . get ( "job" ) ? context . getDataContext ( ) . get ( "job" ) . get ( "execid" ) : null ; String filepath = fileCopierUtil . generateRemoteFilepathForNode ( node , context . getFramework ( ) . getFrameworkProjectMgr ( ) . getFrameworkProject ( context . getFrameworkProject ( ) ) , context . getFramework ( ) , filename , fileExtension , ident ) ; try { File temp = writeScriptToTempFile ( context , node , scriptString , serverScriptFilePath , scriptAsStream , expandTokens ) ; try { filepath = executionService . fileCopyFile ( context , temp , node , filepath ) ; } finally { ScriptfileUtils . releaseTempFile ( temp ) ; } } catch ( FileCopierException e ) { throw new NodeStepException ( e . getMessage ( ) , e , e . getFailureReason ( ) , node . getNodename ( ) ) ; } catch ( ExecutionException e ) { throw new NodeStepException ( e . getMessage ( ) , e , e . getFailureReason ( ) , node . getNodename ( ) ) ; } return executeRemoteScript ( context , context . getFramework ( ) , node , args , filepath , scriptInterpreter , quoted ) ; } | 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 , null , scriptString , node , expandTokens ) ; } else if ( null != serverScriptFilePath ) { temp = new File ( serverScriptFilePath ) ; } else { temp = fileCopierUtil . writeScriptTempFile ( context , null , scriptAsStream , null , node , expandTokens ) ; } return temp ; } | 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 ) ; if ( null == excludes || excludes . isBlank ( ) ) { return ! includesMatch ; } else if ( null == includes || includes . isBlank ( ) ) { return excludesMatch ; } else if ( null != includes && includes . isDominant ( ) ) { return ! includesMatch && excludesMatch ; } else { return ! includesMatch || excludesMatch ; } } | 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 pathForRelativeFilepath ( filePath . substring ( rootPath . length ( ) ) ) ; } | 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 { return new BasicSource ( nodeAuthentication . getSudoPassword ( prefix ) ) ; } } | 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 ) { pool . shutdownNow ( ) ; Thread . currentThread ( ) . interrupt ( ) ; } } | 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 StorageConverterPluginAdapter ( "builtin:timestamp" , new StorageTimestamperConverter ( ) ) ) ; } if ( null != defaultConverters && defaultConverters . contains ( "KeyStorageLayer" ) ) { logger . debug ( "Configuring base converter: KeyStorageLayer" ) ; builder = builder . convert ( new StorageConverterPluginAdapter ( "builtin:ssh-storage" , new KeyStorageLayer ( ) ) , PathUtil . asPath ( "/keys" ) ) ; } return builder ; } | 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_EVENTS_LOGGER_NAME ; } logger . debug ( "Add log4j logger for storage with name: " + loggerName ) ; return builder . listen ( new StorageLogger ( loggerName ) ) ; } | 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 ( getBaseStorageType ( ) , config1 , storagePluginProviderService ) ; if ( null == base ) { throw new IllegalArgumentException ( "Plugin could not be loaded: " + getBaseStorageType ( ) ) ; } return builder . base ( base ) ; } | 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 ; String selectorProp = pref1 + SEP + RESOURCE_SELECTOR ; String path = configProps . get ( pathProp ) ; String selector = configProps . get ( selectorProp ) ; if ( null == path && null == selector ) { throw new IllegalArgumentException ( "Converter plugin [" + index + "] specified by " + ( pref1 ) + " MUST " + "define one of: " + pathProp + " OR " + selectorProp ) ; } Map < String , String > config = subPropertyMap ( pref1 + SEP + CONFIG + SEP , configProps ) ; config = expandConfig ( config ) ; logger . debug ( "Add Converter[" + index + "]:" + ( null != path ? path : "/" ) + "[" + ( null != selector ? selector : "*" ) + "]" + " " + pluginType + ", config: " + config ) ; return buildConverterPlugin ( builder , pluginType , path , selector , config ) ; } | 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 . convert ( new StorageConverterPluginAdapter ( pluginType , converterPlugin ) , null != path ? PathUtil . asPath ( path . trim ( ) ) : null , null != selector ? PathUtil . < ResourceMeta > resourceSelector ( selector ) : null ) ; } | 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 ( configPrefix . length ( ) ) ; config . put ( conf , propertiesMap . get ( key ) . toString ( ) ) ; } } return config ; } | 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 removePathPrefix = Boolean . parseBoolean ( configProps . get ( pref1 + SEP + REMOVE_PATH_PREFIX ) ) ; Map < String , String > config = subPropertyMap ( pref1 + SEP + CONFIG + SEP , configProps ) ; config = expandConfig ( config ) ; Tree < ResourceMeta > resourceMetaTree = loadPlugin ( pluginType , config , storagePluginProviderService ) ; if ( index == 1 && PathUtil . isRoot ( path ) ) { logger . debug ( "New base Storage[" + index + "]:" + path + " " + pluginType + ", config: " + config ) ; builder . base ( resourceMetaTree ) ; } else { logger . debug ( "Subtree Storage[" + index + "]:" + path + " " + pluginType + ", config: " + config ) ; builder . subTree ( PathUtil . asPath ( path . trim ( ) ) , resourceMetaTree , ! removePathPrefix ) ; } } | 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 scriptfile ; } | 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 ) , writer , style ) ; } else if ( null != reader ) { ScriptfileUtils . writeReader ( reader , writer , style ) ; } else if ( null != stream ) { ScriptfileUtils . writeStream ( stream , writer , style ) ; } else { throw new IllegalArgumentException ( "no script source argument" ) ; } } } | 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 . isHaltOnError ( ) ) { throw e ; } else { logger . error ( "Exception thrown while getting DocID" , e ) ; return - 1 ; } } if ( ( result == OperationStatus . SUCCESS ) && ( value . getData ( ) . length > 0 ) ) { return Util . byteArray2Int ( value . getData ( ) ) ; } return - 1 ; } } | 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 = 4096 ; } readBufferLength = Math . min ( readBufferLength , maxBytes ) ; ByteArrayBuffer buffer = new ByteArrayBuffer ( readBufferLength ) ; byte [ ] tmpBuff = new byte [ 4096 ] ; int dataLength ; while ( ( dataLength = is . read ( tmpBuff ) ) != - 1 ) { if ( maxBytes > 0 && ( buffer . length ( ) + dataLength ) > maxBytes ) { truncated = true ; dataLength = maxBytes - buffer . length ( ) ; } buffer . append ( tmpBuff , 0 , dataLength ) ; if ( truncated ) { break ; } } return buffer . toByteArray ( ) ; } } | 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 = encoding . getValue ( ) ; } Charset charset ; try { charset = ContentType . getOrDefault ( entity ) . getCharset ( ) ; } catch ( Exception e ) { logger . warn ( "parse charset failed: {}" , e . getMessage ( ) ) ; charset = Charset . forName ( "UTF-8" ) ; } if ( charset != null ) { contentCharset = charset . displayName ( ) ; } contentData = toByteArray ( entity , maxBytes ) ; } | 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 Exception ( "Maximum crawl depth should be either a positive number or -1 for unlimited depth" + "." ) ; } if ( maxDepthOfCrawling > Short . MAX_VALUE ) { throw new Exception ( "Maximum value for crawl depth is " + Short . MAX_VALUE ) ; } } | 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 ( directives != null && directives . needsRefetch ( ) ) { synchronized ( host2directivesCache ) { host2directivesCache . remove ( host ) ; directives = null ; } } if ( directives == null ) { directives = fetchDirectives ( url ) ; } return directives . allows ( path ) ; } catch ( MalformedURLException e ) { logger . error ( "Bad URL in Robots.txt: " + webURL . getURL ( ) , e ) ; } logger . warn ( "RobotstxtServer: default: allow" , webURL . getURL ( ) ) ; return true ; } | 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 && ! ignoreUADisc ) { break ; } result = ua . checkAccess ( path , userAgent ) ; if ( result != DISALLOWED || ( ! ua . isWildcard ( ) || ! ignoreUADisc ) ) { break ; } } return result ; } | 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 pair : pairs ) { if ( pair . isEmpty ( ) ) { continue ; } String [ ] tokens = pair . split ( "=" , 2 ) ; switch ( tokens . length ) { case 1 : if ( pair . charAt ( 0 ) == '=' ) { params . put ( "" , tokens [ 0 ] ) ; } else { params . put ( tokens [ 0 ] , "" ) ; } break ; case 2 : params . put ( tokens [ 0 ] , tokens [ 1 ] ) ; break ; } } return new LinkedHashMap < > ( params ) ; } | 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 ( ) ; this . frontier = crawlController . getFrontier ( ) ; this . parser = crawlController . getParser ( ) ; this . myController = crawlController ; this . isWaitingForNewURLs = false ; this . batchReadSize = crawlController . getConfig ( ) . getBatchReadSize ( ) ; } | 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 ( "Unhandled exception while fetching {}: {}" , urlStr , e . getMessage ( ) ) ; logger . info ( "Stacktrace: " , e ) ; } } | 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 ( ) ) . getMetaTagValue ( "robots" ) . contains ( "nofollow" ) ) || url . getAttribute ( "rel" ) . contains ( "nofollow" ) ) ; } return true ; } | 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 ) t ; } else { throw new RuntimeException ( "error on monitor thread" , t ) ; } } } if ( finished ) { return ; } try { waitingLock . wait ( ) ; } catch ( InterruptedException e ) { logger . error ( "Error occurred" , e ) ; } } } } | 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 ( canonicalUrl ) ; if ( docId > 0 ) { logger . trace ( "This URL is already seen." ) ; return ; } docId = docIdServer . getNewDocID ( canonicalUrl ) ; } else { try { docIdServer . addUrlAndDocId ( canonicalUrl , docId ) ; } catch ( RuntimeException e ) { if ( config . isHaltOnError ( ) ) { throw e ; } else { logger . error ( "Could not add seed: {}" , e . getMessage ( ) ) ; } } } WebURL webUrl = new WebURL ( ) ; webUrl . setTldList ( tldList ) ; webUrl . setURL ( canonicalUrl ) ; webUrl . setDocid ( docId ) ; webUrl . setDepth ( ( short ) 0 ) ; if ( robotstxtServer . allows ( webUrl ) ) { frontier . schedule ( webUrl ) ; } else { logger . warn ( "Robots.txt does not allow this seed: {}" , pageUrl ) ; } } } | 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 the next URL that is found during the crawl will get a doc id of 8 . Also you need to ensure to add seeds in increasing order of document ids . |
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 , docId ) ; } catch ( RuntimeException e ) { if ( config . isHaltOnError ( ) ) { throw e ; } else { logger . error ( "Could not add seen url: {}" , e . getMessage ( ) ) ; } } } } | 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 . getLocalHost ( ) . getHostName ( ) , authInfo . getDomain ( ) ) ; credentialsMap . put ( new AuthScope ( authInfo . getHost ( ) , authInfo . getPort ( ) ) , credentials ) ; } catch ( UnknownHostException e ) { logger . error ( "Error creating NT credentials" , e ) ; } } | 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 true ; } return false ; } | 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 ) { return dx * dx + dy * dy > mTouchSlop * mTouchSlop ; } else if ( checkHorizontal ) { return Math . abs ( dx ) > mTouchSlop ; } else if ( checkVertical ) { return Math . abs ( dy ) > mTouchSlop ; } return false ; } | 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 dx = mLastMotionX [ pointerId ] - mInitialMotionX [ pointerId ] ; final float dy = mLastMotionY [ pointerId ] - mInitialMotionY [ pointerId ] ; if ( checkHorizontal && checkVertical ) { return dx * dx + dy * dy > mTouchSlop * mTouchSlop ; } else if ( checkHorizontal ) { return Math . abs ( dx ) > mTouchSlop ; } else if ( checkVertical ) { return Math . abs ( dy ) > mTouchSlop ; } return false ; } | 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 . getChildAt ( 0 ) ; return ( child . getBottom ( ) - ( sv . getHeight ( ) + sv . getScrollY ( ) ) ) ; } } else if ( scrollableView instanceof ListView && ( ( ListView ) scrollableView ) . getChildCount ( ) > 0 ) { ListView lv = ( ( ListView ) scrollableView ) ; if ( lv . getAdapter ( ) == null ) return 0 ; if ( isSlidingUp ) { View firstChild = lv . getChildAt ( 0 ) ; return lv . getFirstVisiblePosition ( ) * firstChild . getHeight ( ) - firstChild . getTop ( ) ; } else { View lastChild = lv . getChildAt ( lv . getChildCount ( ) - 1 ) ; return ( lv . getAdapter ( ) . getCount ( ) - lv . getLastVisiblePosition ( ) - 1 ) * lastChild . getHeight ( ) + lastChild . getBottom ( ) - lv . getBottom ( ) ; } } else if ( scrollableView instanceof RecyclerView && ( ( RecyclerView ) scrollableView ) . getChildCount ( ) > 0 ) { RecyclerView rv = ( ( RecyclerView ) scrollableView ) ; RecyclerView . LayoutManager lm = rv . getLayoutManager ( ) ; if ( rv . getAdapter ( ) == null ) return 0 ; if ( isSlidingUp ) { View firstChild = rv . getChildAt ( 0 ) ; return rv . getChildLayoutPosition ( firstChild ) * lm . getDecoratedMeasuredHeight ( firstChild ) - lm . getDecoratedTop ( firstChild ) ; } else { View lastChild = rv . getChildAt ( rv . getChildCount ( ) - 1 ) ; return ( rv . getAdapter ( ) . getItemCount ( ) - 1 ) * lm . getDecoratedMeasuredHeight ( lastChild ) + lm . getDecoratedBottom ( lastChild ) - rv . getBottom ( ) ; } } else { return 0 ; } } | 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 state cannot be null or DRAGGING." ) ; } if ( ! isEnabled ( ) || ( ! mFirstLayout && mSlideableView == null ) || state == mSlideState || mSlideState == PanelState . DRAGGING ) return ; if ( mFirstLayout ) { setPanelStateInternal ( state ) ; } else { if ( mSlideState == PanelState . HIDDEN ) { mSlideableView . setVisibility ( View . VISIBLE ) ; requestLayout ( ) ; } switch ( state ) { case ANCHORED : smoothSlideTo ( mAnchorPoint , 0 ) ; break ; case COLLAPSED : smoothSlideTo ( 0 , 0 ) ; break ; case EXPANDED : smoothSlideTo ( 1.0f , 0 ) ; break ; case HIDDEN : int newTop = computePanelTopPosition ( 0.0f ) + ( mIsSlidingUp ? + mPanelHeight : - mPanelHeight ) ; smoothSlideTo ( computeSlideOffset ( newTop ) , 0 ) ; break ; } } } | 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 byteCount ; } | 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 ( ) ) . createMarshaller ( ) ; marshaller . setProperty ( Marshaller . JAXB_FORMATTED_OUTPUT , true ) ; marshaller . setProperty ( CharacterEscapeHandler . class . getName ( ) , new CharacterEscapeHandler ( ) { public void escape ( char [ ] ac , int i , int j , boolean flag , Writer writer ) throws IOException { writer . write ( ac , i , j ) ; } } ) ; StringWriter stringWriter = new StringWriter ( ) ; marshaller . marshal ( object , stringWriter ) ; return stringWriter . getBuffer ( ) . toString ( ) ; } catch ( Exception e ) { logger . error ( "" , e ) ; } return null ; } | 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 . qualityGateDao ( ) . selectById ( dbSession , qualityGateId ) ) . map ( qualityGateDto -> new QualityGateData ( qualityGateDto , false ) ) ; if ( res . isPresent ( ) ) { return res ; } return ofNullable ( dbClient . qualityGateDao ( ) . selectByOrganizationAndUuid ( dbSession , organization , organization . getDefaultQualityGateUuid ( ) ) ) . map ( qualityGateDto -> new QualityGateData ( qualityGateDto , true ) ) ; } | 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 removedKey : removedKeys ) { pluginInfosByKeys . remove ( removedKey ) ; } } while ( ! removedKeys . isEmpty ( ) ) ; } | 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 ( ! getPluginFile ( info ) . exists ( ) ) { LOG . info ( "Plugin already uninstalled: {} [{}]" , info . getName ( ) , info . getKey ( ) ) ; continue ; } LOG . info ( "Uninstalling plugin {} [{}]" , info . getName ( ) , info . getKey ( ) ) ; File masterFile = getPluginFile ( info ) ; moveFileToDirectory ( masterFile , uninstallDir , true ) ; } catch ( IOException e ) { throw new IllegalStateException ( format ( "Fail to uninstall plugin %s [%s]" , info . getName ( ) , info . getKey ( ) ) , e ) ; } } } | 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 ( ) . equals ( pluginKey ) ) { appendTo . add ( otherPlugin . getKey ( ) ) ; appendDependentPluginKeys ( otherPlugin . getKey ( ) , appendTo ) ; } } } } } | 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 , duplicated . get ( i ) . getId ( ) ) ; } } | 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 ] ) ; ClonePart part = new ClonePart ( firstBlock . getResourceId ( ) , firstBlock . getIndexInFile ( ) , firstBlock . getStartLine ( ) , lastBlock . getEndLine ( ) ) ; if ( originResourceId . equals ( part . getResourceId ( ) ) ) { if ( origin == null ) { origin = part ; builder . setLengthInUnits ( lastBlock . getEndUnit ( ) - firstBlock . getStartUnit ( ) + 1 ) ; } else if ( part . getUnitStart ( ) < origin . getUnitStart ( ) ) { origin = part ; } } parts . add ( part ) ; } Collections . sort ( parts , ContainsInComparator . CLONEPART_COMPARATOR ) ; builder . setOrigin ( origin ) . setParts ( parts ) ; filter ( builder . build ( ) ) ; reset ( ) ; } | 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 to find an available port on " + address ) ; } | 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 ( ) ; postCommit ( dbSession , items ) ; } | 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 , value . toString ( ) ) ) ; } return Optional . empty ( ) ; } | 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 , entry . getValue ( ) . toString ( ) ) ; } } return props ; } | 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.username=sonar. Got: %s" , arg ) ) ; } String key = StringUtils . substringBefore ( arg , "=" ) . substring ( 2 ) ; String value = StringUtils . substringAfter ( arg , "=" ) ; props . setProperty ( key , value ) ; } return props ; } | 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 [ ] oldBlockData = blockData ; blockData = new int [ newCapacity * blockInts ] ; System . arraycopy ( oldBlockData , 0 , blockData , 0 , oldBlockData . length ) ; resourceIdsIndex = new int [ newCapacity ] ; sorted = false ; } | 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 there is no related rule activated in the quality profile" , descriptor . name ( ) ) ; return false ; } if ( ! settingsCondition ( descriptor ) ) { LOG . debug ( "'{}' skipped because one of the required properties is missing" , descriptor . name ( ) ) ; return false ; } return true ; } | 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 . optimizedBestValue ; this . direction = with . direction ; this . key = with . key ; this . type = with . type ; this . name = with . name ; this . userManaged = with . userManaged ; this . hidden = with . hidden ; this . deleteHistoricalData = with . deleteHistoricalData ; return this ; } | 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 ( componentUuids . size ( ) ) , String . valueOf ( fromDates . size ( ) ) ) ; List < ComponentUuidFromDatePair > componentUuidFromDatePairs = IntStream . range ( 0 , componentUuids . size ( ) ) . mapToObj ( i -> new ComponentUuidFromDatePair ( componentUuids . get ( i ) , fromDates . get ( i ) ) ) . collect ( MoreCollectors . toList ( componentUuids . size ( ) ) ) ; return executeLargeInputs ( componentUuidFromDatePairs , partition -> mapper ( dbSession ) . selectFinishedByComponentUuidsAndFromDates ( partition ) , i -> i / 2 ) ; } | 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 ( ) ) ) { filePath += "_" + locale . getLanguage ( ) ; } filePath += "/" + filename ; InputStream input = classloader . getResourceAsStream ( filePath ) ; if ( input != null ) { result = readInputStream ( filePath , input ) ; } return result ; } | 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 ( exception . content ( ) , MAX_ERROR_MSG_LEN ) ; } | 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" ) ; return mapper ( dbSession ) . selectUserPermissionsByQueryAndUserIds ( query , userIds ) ; } | List of user permissions ordered by alphabetical order of user names . Pagination is NOT applied . No sort is done . |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.