idx
int64 0
41.2k
| question
stringlengths 83
4.15k
| target
stringlengths 5
715
|
|---|---|---|
100
|
public void unmark ( ) { if ( marked ) { SimpleControl renderer = ( SimpleControl ) getField ( ) . getRenderer ( ) ; Node markNode = renderer . getFieldLabel ( ) ; markNode . getStyleClass ( ) . remove ( MARKED_STYLE_CLASS ) ; markNode . removeEventHandler ( MouseEvent . MOUSE_EXITED , unmarker ) ; marked = ! marked ; } }
|
Unmarks a setting . Is used for the search which marks and unmarks items depending on the match as a form of visual feedback .
|
101
|
private void loadLastWindowState ( ) { if ( persistWindowState ) { setPrefSize ( storageHandler . loadWindowWidth ( ) , storageHandler . loadWindowHeight ( ) ) ; getScene ( ) . getWindow ( ) . setX ( storageHandler . loadWindowPosX ( ) ) ; getScene ( ) . getWindow ( ) . setY ( storageHandler . loadWindowPosY ( ) ) ; model . setDividerPosition ( storageHandler . loadDividerPosition ( ) ) ; model . setDisplayedCategory ( model . loadSelectedCategory ( ) ) ; } else { setPrefSize ( Constants . DEFAULT_PREFERENCES_WIDTH , Constants . DEFAULT_PREFERENCES_HEIGHT ) ; getScene ( ) . getWindow ( ) . centerOnScreen ( ) ; } }
|
Loads last saved size and position of the window .
|
102
|
private void addI18nListener ( ) { model . translationServiceProperty ( ) . addListener ( ( observable , oldValue , newValue ) -> { if ( oldValue != newValue ) { form . i18n ( newValue ) ; newValue . addListener ( categoryModel :: updateGroupDescriptions ) ; if ( ! Objects . equals ( breadCrumbPresenter , null ) ) { newValue . addListener ( breadCrumbPresenter :: setupBreadCrumbBar ) ; } categoryModel . updateGroupDescriptions ( ) ; } } ) ; }
|
Updates the internal FormsFX form with the most current TranslationService . Makes sure the group descriptions are updated with changing locale .
|
103
|
public void translate ( String language ) { switch ( language ) { case "EN" : rootPane . rbs . changeLocale ( rootPane . rbEN ) ; break ; case "DE" : rootPane . rbs . changeLocale ( rootPane . rbDE ) ; break ; default : throw new IllegalArgumentException ( "Not a valid locale" ) ; } }
|
Sets the locale of the form .
|
104
|
public void mark ( ) { if ( ! marked ) { preferencesGroup . getRenderer ( ) . addStyleClass ( MARKED_STYLE_CLASS ) ; preferencesGroup . getRenderer ( ) . getTitleLabel ( ) . setOnMouseExited ( unmarker ) ; marked = ! marked ; } }
|
Marks this group in the GUI . Is used for the search which marks and unmarks items depending on the match as a form of visual feedback .
|
105
|
public void unmark ( ) { if ( marked ) { preferencesGroup . getRenderer ( ) . removeStyleClass ( MARKED_STYLE_CLASS ) ; preferencesGroup . getRenderer ( ) . getTitleLabel ( ) . removeEventHandler ( MouseEvent . MOUSE_EXITED , unmarker ) ; marked = ! marked ; } }
|
Unmarks this group in the GUI . Is used for the search which marks and unmarks items depending on the match as a form of visual feedback .
|
106
|
public boolean setView ( final Category category ) { LOGGER . trace ( "CategoryController, setView: " + category ) ; CategoryView categoryView = views . get ( category ) ; if ( categoryView != null ) { setContent ( categoryView ) ; categoryView . minWidthProperty ( ) . bind ( widthProperty ( ) . subtract ( SCROLLBAR_SUBTRACT ) ) ; displayedCategoryView . setValue ( categoryView ) ; displayedCategoryPresenter . setValue ( getPresenter ( category ) ) ; return true ; } else { LOGGER . info ( "Category " + category . getDescription ( ) + " hasn't been loaded!" ) ; return false ; } }
|
Sets the current view to the one of the respective category . This method can be called in the presenter to switch to a different CategoryView . Controls the way views are being transitioned from one to another .
|
107
|
public void addListener ( ReadOnlyObjectProperty < Category > categoryProperty ) { categoryProperty . addListener ( ( observable , oldCategory , newCategory ) -> { setView ( newCategory ) ; } ) ; }
|
Sets the view according to the current category in categoryProperty . Must ensure that the category is already loaded else it will fail .
|
108
|
public static List < Category > flattenCategories ( List < Category > categoryLst ) { if ( categoryLst == null ) { return null ; } List < Category > flatCategoryLst = new ArrayList < > ( ) ; flattenCategories ( flatCategoryLst , categoryLst ) ; return flatCategoryLst ; }
|
Puts all categories and their respective children recursively flattened into a list .
|
109
|
private static void flattenCategories ( List < Category > flatList , List < Category > categories ) { categories . forEach ( category -> { flatList . add ( category ) ; List < Category > children = category . getChildren ( ) ; if ( children != null ) { flattenCategories ( flatList , children ) ; } } ) ; }
|
Goes through the list of parent categories and adds each category it visists to the flatList .
|
110
|
protected void toggleTooltip ( Node reference ) { if ( reference instanceof Control ) { this . toggleTooltip ( reference , ( Control ) reference ) ; } }
|
Sets the error message as tooltip for the matching control and shows them below the same control .
|
111
|
protected void toggleTooltip ( Node reference , Control below ) { String fieldTooltip = field . getTooltip ( ) ; if ( ( reference . isFocused ( ) || reference . isHover ( ) ) && ( ! fieldTooltip . equals ( "" ) || field . getErrorMessages ( ) . size ( ) > 0 ) ) { tooltip . setText ( ( ! fieldTooltip . equals ( "" ) ? fieldTooltip + "\n" : "" ) + String . join ( "\n" , field . getErrorMessages ( ) ) ) ; if ( tooltip . isShowing ( ) ) { return ; } Point2D p = below . localToScene ( 0.0 , 0.0 ) ; tooltip . show ( reference . getScene ( ) . getWindow ( ) , p . getX ( ) + reference . getScene ( ) . getX ( ) + reference . getScene ( ) . getWindow ( ) . getX ( ) , p . getY ( ) + reference . getScene ( ) . getY ( ) + reference . getScene ( ) . getWindow ( ) . getY ( ) + below . getHeight ( ) + 5 ) ; } else { tooltip . hide ( ) ; } }
|
Sets the error message as tooltip for the matching control .
|
112
|
protected void updateStyle ( PseudoClass pseudo , boolean newValue ) { if ( node != null ) { node . pseudoClassStateChanged ( pseudo , newValue ) ; } if ( fieldLabel != null ) { fieldLabel . pseudoClassStateChanged ( pseudo , newValue ) ; } }
|
Sets the css style for the defined properties .
|
113
|
private Callable createListToObjectBinding ( ListProperty < P > listProperty ) { return ( ) -> { if ( ! isListChange ( ) && listProperty . get ( ) != null && listProperty . get ( ) . size ( ) != 0 ) { return listProperty . get ( ) . get ( 0 ) ; } return null ; } ; }
|
Creates a function which handles binding between a ListProperty and an ObjectProperty .
|
114
|
public boolean isRedundant ( ) { if ( isListChange ( ) ) { return Objects . equals ( oldList . get ( ) , newList . get ( ) ) ; } return oldValue . get ( ) . equals ( newValue . get ( ) ) ; }
|
Compares newValue and oldValue to see if they are the same . If this is the case this change is redundant since it doesn t represent a true change . This can happen on compounded changes .
|
115
|
public void setupBreadCrumbBar ( ) { String [ ] stringArr = model . getDisplayedCategory ( ) . getBreadcrumb ( ) . split ( BREADCRUMB_DELIMITER ) ; Category [ ] categories = new Category [ stringArr . length ] ; categories [ 0 ] = searchCategory ( stringArr [ 0 ] ) ; for ( int i = 1 ; i < stringArr . length ; ++ i ) { stringArr [ i ] = stringArr [ i - 1 ] + BREADCRUMB_DELIMITER + stringArr [ i ] ; categories [ i ] = searchCategory ( stringArr [ i ] ) ; } breadCrumbView . breadcrumbsItm = BreadCrumbBar . buildTreeModel ( categories ) ; breadCrumbView . breadCrumbBar . setSelectedCrumb ( breadCrumbView . breadcrumbsItm ) ; }
|
Sets up the BreadcrumbBar depending on the displayed category .
|
116
|
private Category searchCategory ( String breadcrumb ) { return model . getFlatCategoriesLst ( ) . stream ( ) . filter ( cat -> cat . getBreadcrumb ( ) . equals ( breadcrumb ) ) . findAny ( ) . orElse ( null ) ; }
|
Searches in all categories for the category that matches a breadcrumb .
|
117
|
public static Category of ( String description , Node itemIcon , Group ... groups ) { return new Category ( description , itemIcon , groups ) ; }
|
Creates a new category from groups .
|
118
|
public void createBreadcrumbs ( List < Category > categories ) { categories . forEach ( category -> { category . setBreadcrumb ( getBreadcrumb ( ) + BREADCRUMB_DELIMITER + category . getDescription ( ) ) ; if ( ! Objects . equals ( category . getGroups ( ) , null ) ) { category . getGroups ( ) . forEach ( group -> group . addToBreadcrumb ( getBreadcrumb ( ) ) ) ; } if ( ! Objects . equals ( category . getChildren ( ) , null ) ) { category . createBreadcrumbs ( category . getChildren ( ) ) ; } } ) ; }
|
Creates and defines all of the breadcrumbs for all of the categories .
|
119
|
public void translate ( TranslationService translationService ) { if ( translationService == null ) { description . setValue ( descriptionKey . getValue ( ) ) ; return ; } if ( ! Strings . isNullOrEmpty ( descriptionKey . get ( ) ) ) { description . setValue ( translationService . translate ( descriptionKey . get ( ) ) ) ; } }
|
This internal method is used as a callback for when the translation service or its locale changes . Also applies the translation to all contained sections .
|
120
|
public OverviewStats add ( OverviewStats other ) { this . addFeaturesFailed ( other . getFeaturesFailed ( ) ) ; this . addFeaturesKnown ( other . getFeaturesKnown ( ) ) ; this . addFeaturesPassed ( other . getFeaturesPassed ( ) ) ; this . addFeaturesUndefined ( other . getFeaturesUndefined ( ) ) ; this . addScenariosFailed ( other . getScenariosFailed ( ) ) ; this . addScenariosKnown ( other . getScenariosKnown ( ) ) ; this . addScenariosPassed ( other . getScenariosPassed ( ) ) ; this . addScenariosUndefined ( other . getScenariosUndefined ( ) ) ; this . addStepsFailed ( other . getStepsFailed ( ) ) ; this . addStepsKnown ( other . getStepsKnown ( ) ) ; this . addStepsPassed ( other . getStepsPassed ( ) ) ; this . addStepsUndefined ( other . getStepsUndefined ( ) ) ; return this ; }
|
Merges 2 overview statistic structures where all corresponding values are simply added to current object .
|
121
|
public OverviewStats valuate ( CucumberScenarioResult scenario ) { this . reset ( ) ; scenario . valuate ( ) ; this . addOverallDuration ( ( float ) scenario . getDuration ( ) ) ; this . addStepsPassed ( scenario . getPassed ( ) ) ; this . addStepsFailed ( scenario . getFailed ( ) ) ; this . addStepsKnown ( scenario . getKnown ( ) ) ; this . addStepsUndefined ( scenario . getUndefined ( ) + scenario . getSkipped ( ) ) ; return this ; }
|
Calculates overall statistics for specific scenario .
|
122
|
public OverviewStats valuate ( CucumberFeatureResult result ) { this . reset ( ) ; result . valuate ( ) ; this . addOverallDuration ( result . getDuration ( ) ) ; if ( result . getStatus ( ) . equals ( "passed" ) ) { this . addFeaturesPassed ( 1 ) ; } else if ( result . getStatus ( ) . equals ( "failed" ) ) { this . addFeaturesFailed ( 1 ) ; } else if ( result . getStatus ( ) . equals ( "known" ) ) { this . addFeaturesKnown ( 1 ) ; } else { this . addFeaturesUndefined ( 1 ) ; } this . addScenariosPassed ( result . getPassed ( ) ) ; this . addScenariosFailed ( result . getFailed ( ) ) ; this . addScenariosKnown ( result . getKnown ( ) ) ; this . addScenariosUndefined ( result . getUndefined ( ) + result . getSkipped ( ) ) ; for ( CucumberScenarioResult scenario : result . getElements ( ) ) { this . addStepsPassed ( scenario . getPassed ( ) ) ; this . addStepsFailed ( scenario . getFailed ( ) ) ; this . addStepsKnown ( scenario . getKnown ( ) ) ; this . addStepsUndefined ( scenario . getUndefined ( ) + scenario . getSkipped ( ) ) ; } return this ; }
|
Calculates run statistics for the single feature result .
|
123
|
public OverviewStats valuate ( CucumberFeatureResult [ ] results ) { this . reset ( ) ; for ( CucumberFeatureResult result : results ) { result . valuate ( ) ; this . addOverallDuration ( result . getDuration ( ) ) ; OverviewStats stats = new OverviewStats ( ) ; stats . valuate ( result ) ; this . add ( stats ) ; } return this ; }
|
Calculates overall statistics for the group of features .
|
124
|
public void put ( final E e , final long timeStamp ) throws InterruptedException { final ReentrantLock lock = this . lock ; lock . lockInterruptibly ( ) ; try { while ( timeStamp - this . timeStamp > mask ) newSpaceAvailable . await ( ) ; final int timeOffset = ( int ) ( timeStamp - this . timeStamp ) ; assert a [ start + timeOffset & mask ] == null : a [ start + timeOffset & mask ] ; a [ start + timeOffset & mask ] = e ; ++ count ; if ( timeOffset == 0 ) nextObjectReady . signal ( ) ; } finally { lock . unlock ( ) ; } }
|
Inserts an element with given timestamp waiting for space to become available if the timestamp of the element minus the current timestamp of the queue exceeds the queue capacity .
|
125
|
public E take ( ) throws InterruptedException { final ReentrantLock lock = this . lock ; lock . lockInterruptibly ( ) ; try { while ( a [ start ] == null ) nextObjectReady . await ( ) ; @ SuppressWarnings ( "unchecked" ) final E x = ( E ) a [ start ] ; a [ start ] = null ; start = start + 1 & mask ; -- count ; timeStamp ++ ; newSpaceAvailable . signalAll ( ) ; return x ; } finally { lock . unlock ( ) ; } }
|
Returns the element with the next timestamp waiting until it is available .
|
126
|
public static ArrayList < Parser < ? > > parsersFromSpecs ( String [ ] specs ) throws IllegalArgumentException , ClassNotFoundException , IllegalAccessException , InvocationTargetException , InstantiationException , NoSuchMethodException , IOException { final ArrayList < Parser < ? > > parsers = new ArrayList < > ( ) ; for ( final String spec : specs ) parsers . add ( ObjectParser . fromSpec ( spec , Parser . class , new String [ ] { "it.unimi.di.law.bubing.parser" } ) ) ; return parsers ; }
|
Given an array of parser specifications it returns the corresponding list of parsers ( only the correct specifications are put in the list .
|
127
|
private static Configuration append ( Configuration base , Configuration additional ) { final CompositeConfiguration result = new CompositeConfiguration ( ) ; result . addConfiguration ( additional ) ; result . addConfiguration ( base ) ; return result ; }
|
Takes two configuration and returns their union with the second overriding the first .
|
128
|
public int get ( final byte [ ] array , final int offset , final int length ) { final long hash = MurmurHash3 . hash ( array , offset , length ) ; final ReadLock readLock = lock [ ( int ) ( hash >>> shift ) ] . readLock ( ) ; try { readLock . lock ( ) ; return stripe [ ( int ) ( hash >>> shift ) ] . get ( array , offset , length , hash ) ; } finally { readLock . unlock ( ) ; } }
|
Gets the value of the counter associated with a given key .
|
129
|
public int addTo ( final byte [ ] array , final int offset , final int length , final int delta ) { final long hash = MurmurHash3 . hash ( array , offset , length ) ; final WriteLock writeLock = lock [ ( int ) ( hash >>> shift ) ] . writeLock ( ) ; try { writeLock . lock ( ) ; return stripe [ ( int ) ( hash >>> shift ) ] . addTo ( array , offset , length , hash , delta ) ; } finally { writeLock . unlock ( ) ; } }
|
Adds a value to the counter associated with a given key .
|
130
|
public int put ( final byte [ ] array , final int offset , final int length , final int value ) { final long hash = MurmurHash3 . hash ( array , offset , length ) ; final WriteLock writeLock = lock [ ( int ) ( hash >>> shift ) ] . writeLock ( ) ; try { writeLock . lock ( ) ; return stripe [ ( int ) ( hash >>> shift ) ] . put ( array , offset , length , hash , value ) ; } finally { writeLock . unlock ( ) ; } }
|
Sets the value associated with a given key .
|
131
|
public synchronized void add ( VisitState visitState ) { final boolean wasEntirelyBroken = isEntirelyBroken ( ) ; if ( visitState . lastExceptionClass != null ) brokenVisitStates ++ ; visitStates . add ( visitState ) ; assert brokenVisitStates <= visitStates . size ( ) ; if ( wasEntirelyBroken && ! isEntirelyBroken ( ) ) workbenchBroken . decrementAndGet ( ) ; if ( ! wasEntirelyBroken && isEntirelyBroken ( ) ) workbenchBroken . incrementAndGet ( ) ; }
|
Adds the given visit state to the visit - state queue .
|
132
|
public synchronized void setWorkbenchEntry ( final WorkbenchEntry workbenchEntry ) { assert ! acquired : this ; this . workbenchEntry = workbenchEntry ; if ( ! isEmpty ( ) ) workbenchEntry . add ( this , frontier . workbench ) ; }
|
Sets the workbench entry and put this visit state in its entry if it is nonempty .
|
133
|
public synchronized void putInEntryIfNotEmpty ( ) { assert workbenchEntry != null : this ; assert acquired : this ; assert workbenchEntry . acquired : workbenchEntry ; if ( ! isEmpty ( ) ) workbenchEntry . add ( this ) ; acquired = false ; }
|
Puts this visit state in its entry if it not empty .
|
134
|
public void enqueuePathQuery ( final byte [ ] pathQuery ) { synchronized ( this ) { if ( nextFetch == Long . MAX_VALUE ) return ; final boolean wasEmpty = pathQueries . isEmpty ( ) ; pathQueries . enqueue ( pathQuery ) ; if ( wasEmpty ) putInEntryIfNotAcquired ( ) ; } frontier . pathQueriesInQueues . incrementAndGet ( ) ; frontier . weightOfpathQueriesInQueues . addAndGet ( BURL . memoryUsageOf ( pathQuery ) ) ; }
|
Enqueues a path + query in byte - array representation possibly putting this visit state in its entry .
|
135
|
public byte [ ] dequeue ( ) { final byte [ ] array ; synchronized ( this ) { array = pathQueries . dequeue ( ) ; } if ( array != ROBOTS_PATH ) { frontier . pathQueriesInQueues . decrementAndGet ( ) ; frontier . weightOfpathQueriesInQueues . addAndGet ( - BURL . memoryUsageOf ( array ) ) ; } return array ; }
|
Removes the first path in the queue .
|
136
|
public int pathQueryLimit ( ) { final double delayRatio = Math . max ( 1 , ( frontier . rc . schemeAuthorityDelay + 1. ) / ( frontier . rc . ipDelay + 1. ) ) ; final double scalingFactor = workbenchEntry == null ? 1 : Math . max ( 1 , workbenchEntry . size ( ) / delayRatio ) ; return ( int ) Math . min ( 300000 / ( frontier . rc . schemeAuthorityDelay + 1 ) , Math . max ( 4 , ( long ) Math . ceil ( ( frontier . workbenchSizeInPathQueries / ( scalingFactor * frontier . requiredFrontSize . get ( ) ) ) ) ) ) ; }
|
Returns an estimate of the number of path + queries that this visit state should keep in memory .
|
137
|
@ SuppressWarnings ( "deprecation" ) public final static HashFunction forName ( final String messageDigest ) throws NoSuchAlgorithmException { if ( "" . equals ( messageDigest ) ) return null ; if ( "MD5" . equalsIgnoreCase ( messageDigest ) ) return Hashing . md5 ( ) ; if ( "MurmurHash3" . equalsIgnoreCase ( messageDigest ) ) return Hashing . murmur3_128 ( ) ; throw new NoSuchAlgorithmException ( "Unknown hash function " + messageDigest ) ; }
|
Return the hash function corresponding to a given message - digest algorithm given by name .
|
138
|
protected void writeEntry ( final GZIPArchive . Entry entry ) throws IOException { this . output . write ( GZIPArchive . GZIP_START ) ; writeLEInt ( this . output , entry . mtime ) ; this . output . write ( GZIPArchive . XFL_OS ) ; writeLEShort ( this . output , GZIPArchive . XLEN ) ; this . output . write ( GZIPArchive . SKIP_LEN ) ; writeLEShort ( this . output , GZIPArchive . SUB_LEN ) ; writeLEInt ( this . output , entry . compressedSkipLength ) ; writeLEInt ( this . output , entry . uncompressedSkipLength ) ; this . output . write ( entry . name ) ; this . output . write ( 0 ) ; this . output . write ( entry . comment ) ; this . output . write ( 0 ) ; this . output . write ( deflaterStream . array , 0 , deflaterStream . length ) ; writeLEInt ( this . output , entry . crc32 ) ; writeLEInt ( this . output , entry . uncompressedSkipLength ) ; }
|
Writes the entry on the underlying stream .
|
139
|
public GZIPArchive . WriteEntry getEntry ( final String name , final String comment , final Date creationDate ) { crc . reset ( ) ; deflater . reset ( ) ; deflaterStream . reset ( ) ; final GZIPArchive . WriteEntry entry = new GZIPArchive . WriteEntry ( ) ; entry . setName ( name ) ; entry . setComment ( comment ) ; entry . deflater = new FilterOutputStream ( new DeflaterOutputStream ( deflaterStream , deflater ) ) { private final byte [ ] oneCharBuffer = new byte [ 1 ] ; private long length = 0 ; public void write ( int b ) throws IOException { oneCharBuffer [ 0 ] = ( byte ) b ; this . out . write ( oneCharBuffer ) ; crc . update ( oneCharBuffer ) ; this . length ++ ; } public void write ( byte [ ] b , int off , int len ) throws IOException { this . out . write ( b , off , len ) ; crc . update ( b , off , len ) ; this . length += len ; } public void close ( ) throws IOException { this . out . flush ( ) ; ( ( DeflaterOutputStream ) this . out ) . finish ( ) ; entry . compressedSkipLength = GZIPArchive . FIX_LEN + ( entry . name . length + 1 ) + ( entry . comment . length + 1 ) + deflaterStream . length ; entry . uncompressedSkipLength = ( int ) ( this . length & 0xFFFFFFFF ) ; entry . mtime = ( int ) ( creationDate . getTime ( ) / 1000 ) ; entry . crc32 = ( int ) ( crc . getValue ( ) & 0xFFFFFFFF ) ; writeEntry ( entry ) ; } } ; return entry ; }
|
Returns an object that can be used to write an entry in the GZIP archive .
|
140
|
private static void writeLEInt ( OutputStream out , int i ) throws IOException { out . write ( ( byte ) i ) ; out . write ( ( byte ) ( ( i >> 8 ) & 0xFF ) ) ; out . write ( ( byte ) ( ( i >> 16 ) & 0xFF ) ) ; out . write ( ( byte ) ( ( i >> 24 ) & 0xFF ) ) ; }
|
Writes the given integer in little - endian on the stream .
|
141
|
private static void writeLEShort ( OutputStream out , short s ) throws IOException { out . write ( ( byte ) s ) ; out . write ( ( byte ) ( ( s >> 8 ) & 0xFF ) ) ; }
|
Writes the given short in little - endian on the stream .
|
142
|
public static < T > ObjectDiskQueue < T > createNew ( final File file , final int bufferSize , final boolean direct ) throws IOException { return new ObjectDiskQueue < > ( ByteDiskQueue . createNew ( file , bufferSize , direct ) ) ; }
|
Creates a new disk - based queue of objects .
|
143
|
public static < T > ObjectDiskQueue < T > createFromFile ( final long size , final File file , final int bufferSize , final boolean direct ) throws IOException { final ObjectDiskQueue < T > byteArrayDiskQueue = new ObjectDiskQueue < > ( ByteDiskQueue . createFromFile ( file , bufferSize , direct ) ) ; byteArrayDiskQueue . size = size ; return byteArrayDiskQueue ; }
|
Creates a new disk - based queue of objects using an existing file .
|
144
|
public synchronized void enqueue ( final T o ) throws IOException { assert o != null ; fbaos . reset ( ) ; BinIO . storeObject ( o , fbaos ) ; byteDiskQueue . enqueueInt ( fbaos . length ) ; byteDiskQueue . enqueue ( fbaos . array , 0 , fbaos . length ) ; size ++ ; }
|
Enqueues an object to this queue .
|
145
|
@ SuppressWarnings ( "unchecked" ) public synchronized T dequeue ( ) throws IOException { final int length = byteDiskQueue . dequeueInt ( ) ; fbaos . array = ByteArrays . grow ( fbaos . array , length ) ; byteDiskQueue . dequeue ( fbaos . array , 0 , length ) ; size -- ; try { return ( T ) BinIO . loadObject ( new FastByteArrayInputStream ( fbaos . array , 0 , length ) ) ; } catch ( final ClassNotFoundException e ) { throw new RuntimeException ( e . getMessage ( ) , e ) ; } }
|
Dequeues an object from the queue in FIFO fashion .
|
146
|
public void start ( long previousCrawlDuration ) { requestLogger . start ( previousCrawlDuration ) ; resourceLogger . start ( previousCrawlDuration ) ; transferredBytesLogger . start ( previousCrawlDuration ) ; receivedURLsLogger . start ( previousCrawlDuration ) ; }
|
Starst all progress loggers .
|
147
|
public void emit ( ) { requestLogger . setAndDisplay ( frontier . fetchedResources . get ( ) + frontier . fetchedRobots . get ( ) ) ; final long duplicates = frontier . duplicates . get ( ) ; final long archetypes = frontier . archetypes ( ) ; resourceLogger . setAndDisplay ( archetypes + duplicates ) ; transferredBytesLogger . setAndDisplay ( frontier . transferredBytes . get ( ) ) ; receivedURLsLogger . setAndDisplay ( frontier . numberOfReceivedURLs . get ( ) ) ; LOGGER . info ( "Duplicates: " + Util . format ( duplicates ) + " (" + Util . format ( 100.0 * duplicates / ( duplicates + archetypes ) ) + "%)" ) ; LOGGER . info ( "Archetypes 1XX/2XX/3XX/4XX/5XX/Other: " + Util . format ( frontier . archetypesStatus [ 1 ] . get ( ) ) + "/" + Util . format ( frontier . archetypesStatus [ 2 ] . get ( ) ) + "/" + Util . format ( frontier . archetypesStatus [ 3 ] . get ( ) ) + "/" + Util . format ( frontier . archetypesStatus [ 4 ] . get ( ) ) + "/" + Util . format ( frontier . archetypesStatus [ 5 ] . get ( ) ) + "/" + Util . format ( frontier . archetypesStatus [ 0 ] . get ( ) ) ) ; LOGGER . info ( "Outdegree stats: " + frontier . outdegree . toString ( ) ) ; LOGGER . info ( "External outdegree stats: " + frontier . externalOutdegree . toString ( ) ) ; LOGGER . info ( "Archetype content-length stats: " + frontier . contentLength . toString ( ) ) ; LOGGER . info ( "Archetypes text/image/application/other: " + Util . format ( frontier . contentTypeText . get ( ) ) + "/" + Util . format ( frontier . contentTypeImage . get ( ) ) + "/" + Util . format ( frontier . contentTypeApplication . get ( ) ) + "/" + Util . format ( frontier . contentTypeOthers . get ( ) ) ) ; LOGGER . info ( "Ready URLs: " + Util . format ( frontier . readyURLs . size64 ( ) ) ) ; LOGGER . info ( "FetchingThread waits: " + frontier . fetchingThreadWaits . get ( ) + "; total wait time: " + frontier . fetchingThreadWaitingTimeSum . get ( ) ) ; frontier . resetFetchingThreadsWaitingStats ( ) ; }
|
Emits the statistics .
|
148
|
private static int readLEInt ( InputStream in ) throws IOException { int i = in . read ( ) & 0xFF ; i |= ( in . read ( ) & 0xFF ) << 8 ; i |= ( in . read ( ) & 0xFF ) << 16 ; i |= ( in . read ( ) & 0xFF ) << 24 ; return i ; }
|
Reads an integer in little - endian from the stream .
|
149
|
private static short readLEShort ( InputStream in ) throws IOException { short s = ( byte ) in . read ( ) ; s |= ( byte ) in . read ( ) << 8 ; return s ; }
|
Reads a short in little - endian from the stream .
|
150
|
public static Header getFirstHeader ( final HeaderGroup headers , final WarcHeader . Name name ) { return headers . getFirstHeader ( name . value ) ; }
|
Returns the first header of given name .
|
151
|
public static boolean apply ( final char [ ] [ ] robotsFilter , final URI url ) { if ( robotsFilter . length == 0 ) return true ; final String pathQuery = BURL . pathAndQuery ( url ) ; int from = 0 ; int to = robotsFilter . length - 1 ; while ( from <= to ) { final int mid = ( from + to ) >>> 1 ; final int cmp = compare ( robotsFilter [ mid ] , pathQuery ) ; if ( cmp < 0 ) from = mid + 1 ; else if ( cmp > 0 ) to = mid - 1 ; else return false ; } return from == 0 ? true : doesNotStartsWith ( pathQuery , robotsFilter [ from - 1 ] ) ; }
|
Checks whether a specified URL passes a specified robots filter .
|
152
|
public boolean apply ( final HttpResponse httpResponse ) { try { final InputStream content = httpResponse . getEntity ( ) . getContent ( ) ; int count = 0 ; for ( int i = BINARY_CHECK_SCAN_LENGTH ; i -- != 0 ; ) { final int b = content . read ( ) ; if ( b == - 1 ) return false ; if ( b == 0 && ++ count == THRESHOLD ) return true ; } } catch ( final IOException shouldntReallyHappen ) { throw new RuntimeException ( shouldntReallyHappen ) ; } return false ; }
|
This method implements a simple heuristic for guessing whether a page is binary .
|
153
|
public ByteArrayList fromStream ( final InputStream is ) throws IOException { final int length = Util . readVByte ( is ) ; buffer . size ( length ) ; final int actual = is . read ( buffer . elements ( ) , 0 , length ) ; if ( actual != length ) throw new IOException ( "Asked for " + length + " but got " + actual ) ; return buffer ; }
|
A serializer - deserializer for byte arrays that write the array length using variable - length byte encoding and the writes the content of the array .
|
154
|
public boolean add ( final VisitState v ) { int pos = ( int ) ( MurmurHash3 . hash ( v . schemeAuthority ) & mask ) ; while ( visitState [ pos ] != null ) { if ( Arrays . equals ( visitState [ pos ] . schemeAuthority , v . schemeAuthority ) ) return false ; pos = ( pos + 1 ) & mask ; } visitState [ pos ] = v ; if ( ++ size >= maxFill && n < ( 1 << 30 ) ) rehash ( 2 * n ) ; return true ; }
|
Adds a visit state to the set if necessary .
|
155
|
public boolean remove ( final VisitState k ) { int pos = ( int ) ( MurmurHash3 . hash ( k . schemeAuthority ) & mask ) ; while ( visitState [ pos ] != null ) { if ( visitState [ pos ] == k ) { size -- ; shiftKeys ( pos ) ; return true ; } pos = ( pos + 1 ) & mask ; } return false ; }
|
Removes a given visit state .
|
156
|
protected void rehash ( final int newN ) { int i = 0 , pos ; final VisitState [ ] visitState = this . visitState ; final int newMask = newN - 1 ; final VisitState [ ] newVisitState = new VisitState [ newN ] ; for ( int j = size ; j -- != 0 ; ) { while ( visitState [ i ] == null ) i ++ ; VisitState v = visitState [ i ] ; pos = ( int ) ( MurmurHash3 . hash ( v . schemeAuthority ) & newMask ) ; while ( newVisitState [ pos ] != null ) pos = ( pos + 1 ) & newMask ; newVisitState [ pos ] = v ; i ++ ; } n = newN ; mask = newMask ; maxFill = 3 * ( n / 4 ) ; this . visitState = newVisitState ; }
|
Rehashes the state set to a new size .
|
157
|
public static ByteArrayDiskQueue createNew ( final File file , final int bufferSize , final boolean direct ) throws IOException { return new ByteArrayDiskQueue ( ByteDiskQueue . createNew ( file , bufferSize , direct ) ) ; }
|
Creates a new disk - based queue of byte arrays .
|
158
|
public static ByteArrayDiskQueue createFromFile ( final long size , final File file , final int bufferSize , final boolean direct ) throws IOException { final ByteArrayDiskQueue byteArrayDiskQueue = new ByteArrayDiskQueue ( ByteDiskQueue . createFromFile ( file , bufferSize , direct ) ) ; byteArrayDiskQueue . size = size ; return byteArrayDiskQueue ; }
|
Creates a new disk - based queue of byte arrays using an existing file .
|
159
|
public synchronized void enqueue ( final byte [ ] array ) throws IOException { assert array != null ; byteDiskQueue . enqueueInt ( array . length ) ; byteDiskQueue . enqueue ( array ) ; size ++ ; }
|
Enqueues a byte array to this queue .
|
160
|
public static < T > Filter < T > and ( final Filter < T > ... f ) { return new Filter < T > ( ) { public boolean apply ( final T x ) { for ( final Filter < T > filter : f ) if ( ! filter . apply ( x ) ) return false ; return true ; } public String toString ( ) { return "(" + StringUtils . join ( f , " and " ) + ")" ; } public Filter < T > copy ( ) { return Filters . and ( Filters . copy ( f ) ) ; } } ; }
|
Produces the conjunction of the given filters .
|
161
|
public static < T > Filter < T > not ( final Filter < T > filter ) { return new AbstractFilter < T > ( ) { public boolean apply ( final T x ) { return ! filter . apply ( x ) ; } public String toString ( ) { return "(not " + filter + ")" ; } public Filter < T > copy ( ) { return not ( filter . copy ( ) ) ; } } ; }
|
Produces the negation of the given filter .
|
162
|
@ SuppressWarnings ( "unchecked" ) public static < T > Filter < T > getFilterFromSpec ( String className , String spec , Class < T > tClass ) throws ParseException { String filterClassName ; if ( className . indexOf ( '.' ) >= 0 ) filterClassName = className ; else filterClassName = Filter . FILTER_PACKAGE_NAME + "." + className ; try { final Class < ? > c = Class . forName ( filterClassName ) ; if ( ! Filter . class . isAssignableFrom ( c ) ) throw new ParseException ( filterClassName + " is not a valid filter class" ) ; final Filter < T > filter = spec . length ( ) != 0 ? ( Filter < T > ) c . getMethod ( "valueOf" , String . class ) . invoke ( null , spec ) : ( Filter < T > ) c . getMethod ( "valueOf" ) . invoke ( null ) ; final Method method [ ] = filter . getClass ( ) . getMethods ( ) ; int i ; for ( i = 0 ; i < method . length ; i ++ ) if ( ! method [ i ] . isSynthetic ( ) && method [ i ] . getName ( ) . equals ( "apply" ) ) break ; if ( i == method . length ) throw new NoSuchMethodException ( "Could not find apply method in filter " + filter ) ; final Class < ? > [ ] parameterTypes = method [ i ] . getParameterTypes ( ) ; if ( parameterTypes . length != 1 ) throw new NoSuchMethodException ( "Could not find one-argument apply method in filter " + filter ) ; final Class < ? > toClass = parameterTypes [ 0 ] ; if ( toClass . equals ( tClass ) ) return filter ; else { Method adaptMethod ; try { adaptMethod = Filters . class . getMethod ( "adaptFilter" + toClass . getSimpleName ( ) + "2" + tClass . getSimpleName ( ) , Filter . class ) ; } catch ( final NoSuchMethodException e ) { throw new NoSuchMethodException ( "Cannot adapt a Filter<" + toClass . getSimpleName ( ) + "> into Filter<" + tClass . getSimpleName ( ) + ">" ) ; } return ( Filter < T > ) adaptMethod . invoke ( null , filter ) ; } } catch ( final ParseException e ) { throw e ; } catch ( final Exception e ) { throw new RuntimeException ( e ) ; } }
|
Creates a filter from a filter class name and an external form .
|
163
|
public static File createHierarchicalTempFile ( final File baseDirectory , final int pathElements , final String prefix , final String suffix ) throws IOException { if ( ! baseDirectory . isDirectory ( ) ) throw new IllegalArgumentException ( baseDirectory + " is not a directory." ) ; if ( pathElements < 0 || pathElements > 8 ) throw new IllegalArgumentException ( ) ; long x ; synchronized ( RND ) { x = RND . nextLong ( ) ; } final StringBuilder stringBuilder = new StringBuilder ( ) ; for ( int i = 0 ; i < pathElements ; i ++ ) { if ( i != 0 ) stringBuilder . append ( File . separatorChar ) ; stringBuilder . append ( Long . toHexString ( x & 0xF ) ) ; x >>= 4 ; stringBuilder . append ( Long . toHexString ( x & 0xF ) ) ; x >>= 4 ; } File directory = baseDirectory ; if ( pathElements > 0 ) { directory = new File ( baseDirectory , stringBuilder . toString ( ) ) ; synchronized ( CREATION_LOCK ) { if ( ( directory . exists ( ) && ! directory . isDirectory ( ) ) || ( ! directory . exists ( ) && ! directory . mkdirs ( ) ) ) throw new IOException ( "Cannot create directory " + directory ) ; } } return File . createTempFile ( prefix , suffix , directory ) ; }
|
Creates a temporary file with a random hierachical path .
|
164
|
public final static void writeByteArray ( final byte [ ] a , final ObjectOutputStream s ) throws IOException { writeVByte ( a . length , s ) ; s . write ( a ) ; }
|
Writes a byte array prefixed by its length encoded using vByte .
|
165
|
public final static byte [ ] readByteArray ( final ObjectInputStream s ) throws IOException { final byte [ ] a = new byte [ readVByte ( s ) ] ; s . readFully ( a ) ; return a ; }
|
Reads a byte array prefixed by its length encoded using vByte .
|
166
|
public static byte [ ] toByteArray ( final String s ) { final byte [ ] byteArray = new byte [ s . length ( ) ] ; for ( int i = s . length ( ) ; i -- != 0 ; ) { assert s . charAt ( i ) < ( char ) 0x80 : s . charAt ( i ) ; byteArray [ i ] = ( byte ) s . charAt ( i ) ; } return byteArray ; }
|
Returns a byte - array representation of an ASCII string .
|
167
|
public static OutputStream toOutputStream ( final String s , final OutputStream os ) throws IOException { final int length = s . length ( ) ; for ( int i = 0 ; i < length ; i ++ ) { assert s . charAt ( i ) < ( char ) 0x100 : s . charAt ( i ) ; os . write ( s . charAt ( i ) ) ; } return os ; }
|
Writes a string to an output stream discarding higher order bits .
|
168
|
public boolean add ( final WorkbenchEntry e ) { int pos = hashCode ( e . ipAddress ) & mask ; while ( workbenchEntry [ pos ] != null ) { if ( Arrays . equals ( workbenchEntry [ pos ] . ipAddress , e . ipAddress ) ) return false ; pos = ( pos + 1 ) & mask ; } workbenchEntry [ pos ] = e ; if ( ++ size >= maxFill && n < ( 1 << 30 ) ) rehash ( 2 * n ) ; return true ; }
|
Adds a workbench entry to the set if necessary .
|
169
|
public boolean remove ( final WorkbenchEntry e ) { int pos = hashCode ( e . ipAddress ) & mask ; while ( workbenchEntry [ pos ] != null ) { if ( workbenchEntry [ pos ] == e ) { size -- ; shiftKeys ( pos ) ; return true ; } pos = ( pos + 1 ) & mask ; } return false ; }
|
Removes a given workbench entry .
|
170
|
public WorkbenchEntry get ( final byte [ ] address ) { int pos = hashCode ( address ) & mask ; while ( workbenchEntry [ pos ] != null ) { if ( Arrays . equals ( workbenchEntry [ pos ] . ipAddress , address ) ) return workbenchEntry [ pos ] ; pos = ( pos + 1 ) & mask ; } return null ; }
|
Returns the entry for a given IP address .
|
171
|
protected void rehash ( final int newN ) { int i = 0 , pos ; final WorkbenchEntry [ ] workbenchEntry = this . workbenchEntry ; final int newMask = newN - 1 ; final WorkbenchEntry [ ] newWorkbenchEntry = new WorkbenchEntry [ newN ] ; for ( int j = size ; j -- != 0 ; ) { while ( workbenchEntry [ i ] == null ) i ++ ; WorkbenchEntry e = workbenchEntry [ i ] ; pos = hashCode ( e . ipAddress ) & newMask ; while ( newWorkbenchEntry [ pos ] != null ) pos = ( pos + 1 ) & newMask ; newWorkbenchEntry [ pos ] = e ; i ++ ; } n = newN ; mask = newMask ; maxFill = 3 * ( n / 4 ) ; this . workbenchEntry = newWorkbenchEntry ; }
|
Rehashes the set to a new size .
|
172
|
public int dequeuePathQueries ( final VisitState visitState , final int maxUrls ) throws IOException { if ( maxUrls == 0 ) return 0 ; final int dequeued = ( int ) Math . min ( maxUrls , byteArrayDiskQueues . count ( visitState ) ) ; for ( int i = dequeued ; i -- != 0 ; ) visitState . enqueuePathQuery ( byteArrayDiskQueues . dequeue ( visitState ) ) ; return dequeued ; }
|
Dequeues at most the given number of path + queries into the given visit state .
|
173
|
public void enqueueURL ( VisitState visitState , final ByteArrayList url ) throws IOException { final byte [ ] urlBuffer = url . elements ( ) ; final int pathQueryStart = BURL . startOfpathAndQuery ( urlBuffer ) ; byteArrayDiskQueues . enqueue ( visitState , urlBuffer , pathQueryStart , url . size ( ) - pathQueryStart ) ; }
|
Enqueues the given URL as a path + query associated to the scheme + authority of the given visit state .
|
174
|
public void collectIf ( final double threshold , final double targetRatio ) throws IOException { if ( byteArrayDiskQueues . ratio ( ) < threshold ) { LOGGER . info ( "Starting collection..." ) ; byteArrayDiskQueues . collect ( targetRatio ) ; LOGGER . info ( "Completed collection." ) ; } }
|
Performs a garbage collection if the space used is below a given threshold reaching a given target ratio .
|
175
|
public synchronized void add ( double x ) { final double oldA = a ; a += ( x - a ) / ++ size ; q += ( x - a ) * ( x - oldA ) ; min = Math . min ( min , x ) ; max = Math . max ( max , x ) ; }
|
Adds a value to the stream .
|
176
|
public void add ( WorkbenchEntry entry ) { assert ! entry . isEmpty ( ) : entry ; assert ! entry . acquired : entry ; entries . add ( entry ) ; approximatedSize . incrementAndGet ( ) ; }
|
Adds a nonempty not acquired workbench entry to the workbench .
|
177
|
public VisitState acquire ( ) throws InterruptedException { final WorkbenchEntry entry = entries . take ( ) ; assert ! entry . isEmpty ( ) ; assert ! entry . acquired ; entry . acquired = true ; final VisitState visitState = entry . remove ( ) ; assert visitState . workbenchEntry == entry ; assert ! visitState . isEmpty ( ) ; assert ! visitState . acquired ; visitState . acquired = true ; approximatedSize . decrementAndGet ( ) ; return visitState ; }
|
Acquires a visit state for a scheme + authority accessible by politeness . Note that this is a blocking method that will wait until such a state is available .
|
178
|
public boolean apply ( final WarcRecord x ) { Header messageType = x . getWarcHeader ( WarcHeader . Name . CONTENT_TYPE ) ; return ( x . getWarcType ( ) == WarcRecord . Type . RESPONSE ) && ( messageType != null && messageType . getValue ( ) . equals ( HttpResponseWarcRecord . HTTP_RESPONSE_MSGTYPE ) ) ; }
|
Apply the filter to a WarcRecord
|
179
|
public boolean apply ( final WarcRecord x ) { Header s = x . getWarcHeader ( WarcHeader . Name . WARC_PAYLOAD_DIGEST ) ; return s != null && Arrays . equals ( digest , Util . fromHexString ( s . getValue ( ) ) ) ; }
|
Apply the filter to a given WarcRecord
|
180
|
public boolean cancel ( boolean ignored ) { boolean cancelled = false ; if ( latch . getCount ( ) == 1 ) { latch . countDown ( ) ; output = null ; cancelled = true ; } return cancelled ; }
|
Cancel the command and notify any waiting consumers . This does not cause the redis server to stop executing the command .
|
181
|
public T get ( ) { try { latch . await ( ) ; return output . get ( ) ; } catch ( InterruptedException e ) { throw new RedisCommandInterruptedException ( e ) ; } }
|
Get the command output and if the command hasn t completed yet wait until it does .
|
182
|
public T get ( long timeout , TimeUnit unit ) throws TimeoutException { try { if ( ! latch . await ( timeout , unit ) ) { throw new TimeoutException ( "Command timed out" ) ; } } catch ( InterruptedException e ) { throw new RedisCommandInterruptedException ( e ) ; } return output . get ( ) ; }
|
Get the command output and if the command hasn t completed yet wait up to the specified time until it does .
|
183
|
protected static void writeInt ( ChannelBuffer buf , int value ) { if ( value < 10 ) { buf . writeByte ( '0' + value ) ; return ; } StringBuilder sb = new StringBuilder ( 8 ) ; while ( value > 0 ) { int digit = value % 10 ; sb . append ( ( char ) ( '0' + digit ) ) ; value /= 10 ; } for ( int i = sb . length ( ) - 1 ; i >= 0 ; i -- ) { buf . writeByte ( sb . charAt ( i ) ) ; } }
|
Write the textual value of a positive integer to the supplied buffer .
|
184
|
public static byte [ ] decode ( char [ ] src ) { byte [ ] dst = new byte [ src . length / 2 ] ; for ( int si = 0 , di = 0 ; di < dst . length ; di ++ ) { byte high = decode [ src [ si ++ ] & 0x7f ] ; byte low = decode [ src [ si ++ ] & 0x7f ] ; dst [ di ] = ( byte ) ( ( high << 4 ) + low ) ; } return dst ; }
|
Decode base16 chars to bytes .
|
185
|
public int getNumberBetween ( final int min , final int max ) { if ( max < min ) { throw new IllegalArgumentException ( String . format ( "Minimum must be less than minimum (min=%d, max=%d)" , min , max ) ) ; } if ( max == min ) { return min ; } return min + random . nextInt ( max - min ) ; }
|
Returns a number betwen min and max
|
186
|
public Date getDateBetween ( final Date minDate , final Date maxDate ) { long seconds = ( maxDate . getTime ( ) - minDate . getTime ( ) ) / 1000 ; seconds = ( long ) ( random . nextDouble ( ) * seconds ) ; Date result = new Date ( ) ; result . setTime ( minDate . getTime ( ) + ( seconds * 1000 ) ) ; return result ; }
|
Returns a random date between two dates . This method will alter the time component of the dates
|
187
|
public String getRandomText ( final int minLength , final int maxLength ) { validateMinMaxParams ( minLength , maxLength ) ; StringBuilder sb = new StringBuilder ( maxLength ) ; int length = minLength ; if ( maxLength != minLength ) { length = length + random . nextInt ( maxLength - minLength ) ; } while ( length > 0 ) { if ( sb . length ( ) != 0 ) { sb . append ( " " ) ; length -- ; } final double desiredWordLengthNormalDistributed = 1.0 + Math . abs ( random . nextGaussian ( ) ) * 6 ; int usedWordLength = ( int ) ( Math . min ( length , desiredWordLengthNormalDistributed ) ) ; String word = getRandomWord ( usedWordLength ) ; sb . append ( word ) ; length = length - word . length ( ) ; } return sb . toString ( ) ; }
|
Returns random text made up of english words
|
188
|
public String getRandomWord ( final int minLength , final int maxLength ) { validateMinMaxParams ( minLength , maxLength ) ; if ( maxLength == 1 ) { if ( chance ( 50 ) ) { return "a" ; } return "I" ; } String [ ] words = contentDataValues . getWords ( ) ; int pos = random . nextInt ( words . length ) ; for ( int i = 0 ; i < words . length ; i ++ ) { int idx = ( i + pos ) % words . length ; String test = words [ idx ] ; if ( test . length ( ) >= minLength && test . length ( ) <= maxLength ) { return test ; } } return getRandomChars ( minLength , maxLength ) ; }
|
Returns a valid word based on the length range passed in . The length will always be between the min and max length range inclusive .
|
189
|
public String getNumberText ( final int digits ) { String result = "" ; for ( int i = 0 ; i < digits ; i ++ ) { result = result + random . nextInt ( 10 ) ; } return result ; }
|
Returns a string containing a set of numbers with a fixed number of digits
|
190
|
public String getEmailAddress ( ) { int test = random . nextInt ( 100 ) ; String email = "" ; if ( test < 50 ) { email = getFirstName ( ) . charAt ( 0 ) + getLastName ( ) ; } else { email = getItem ( contentDataValues . getWords ( ) ) + getItem ( contentDataValues . getWords ( ) ) ; } if ( random . nextInt ( 100 ) > 80 ) { email = email + random . nextInt ( 100 ) ; } email = email + "@" + getItem ( contentDataValues . getEmailHosts ( ) ) + "." + getItem ( contentDataValues . getTlds ( ) ) ; return email . toLowerCase ( ) ; }
|
Generates an email address
|
191
|
public void setBinaryStream ( int parameterIndex , InputStream inputStream , int length ) throws SQLException { if ( length <= 0 ) { throw new SQLException ( "Invalid length " + length ) ; } if ( inputStream == null ) { throw new SQLException ( "Input Stream cannot be null" ) ; } final int bufferSize = 8192 ; byte [ ] buffer = new byte [ bufferSize ] ; ByteArrayOutputStream outputStream = null ; try { outputStream = new ByteArrayOutputStream ( ) ; int bytesRemaining = length ; int bytesRead ; int maxReadSize ; while ( bytesRemaining > 0 ) { maxReadSize = ( bytesRemaining > bufferSize ) ? bufferSize : bytesRemaining ; bytesRead = inputStream . read ( buffer , 0 , maxReadSize ) ; if ( bytesRead == - 1 ) { break ; } outputStream . write ( buffer , 0 , bytesRead ) ; bytesRemaining = bytesRemaining - bytesRead ; } setBytes ( parameterIndex , outputStream . toByteArray ( ) ) ; outputStream . close ( ) ; } catch ( IOException e ) { throw new SQLException ( e . getMessage ( ) ) ; } }
|
Set the parameter from the contents of a binary stream .
|
192
|
public void setBinaryStream ( int parameterIndex , InputStream inputStream , long length ) throws SQLException { if ( length > Integer . MAX_VALUE ) { throw new SQLException ( "SQLDroid does not allow input stream data greater than " + Integer . MAX_VALUE ) ; } setBinaryStream ( parameterIndex , inputStream , ( int ) length ) ; }
|
This is a pass through to the integer version of the same method . That is the long is downcast to an integer . If the length is greater than Integer . MAX_VALUE this method will throw a SQLException .
|
193
|
private String escape ( final String val ) { int len = val . length ( ) ; StringBuilder buf = new StringBuilder ( len ) ; for ( int i = 0 ; i < len ; i ++ ) { if ( val . charAt ( i ) == '\'' ) { buf . append ( '\'' ) ; } buf . append ( val . charAt ( i ) ) ; } return buf . toString ( ) ; }
|
Applies SQL escapes for special characters in a given string .
|
194
|
public void free ( ) throws SQLException { if ( freed ) { return ; } string = null ; if ( reader != null ) { reader . close ( ) ; } if ( inputStream != null ) { try { inputStream . close ( ) ; } catch ( IOException ioe ) { } } freed = true ; }
|
Free the Blob object and releases the resources that it holds . The object is invalid once the free method is called .
|
195
|
protected boolean isLockedException ( SQLiteException maybeLocked ) { try { if ( Class . forName ( "android.database.sqlite.SQLiteDatabaseLockedException" , false , getClass ( ) . getClassLoader ( ) ) . isAssignableFrom ( maybeLocked . getClass ( ) ) ) { return true ; } } catch ( ClassNotFoundException e ) { } return false ; }
|
Returns true if the exception is an instance of SQLiteDatabaseLockedException . Since this exception does not exist in APIs below 11 this code uses reflection to check the exception type .
|
196
|
public Cursor rawQuery ( String sql , String [ ] makeArgListQueryString ) throws SQLException { Log . v ( "SQLiteDatabase rawQuery: " + Thread . currentThread ( ) . getId ( ) + " \"" + Thread . currentThread ( ) . getName ( ) + "\" " + sql ) ; long timeNow = System . currentTimeMillis ( ) ; long delta = 0 ; do { try { Cursor cursor = sqliteDatabase . rawQuery ( sql , makeArgListQueryString ) ; Log . v ( "SQLiteDatabase rawQuery OK: " + Thread . currentThread ( ) . getId ( ) + " \"" + Thread . currentThread ( ) . getName ( ) + "\" " + sql ) ; return cursor ; } catch ( SQLiteException e ) { if ( isLockedException ( e ) ) { delta = System . currentTimeMillis ( ) - timeNow ; } else { throw SQLDroidConnection . chainException ( e ) ; } } } while ( delta < timeout ) ; throw new SQLException ( "Timeout Expired" ) ; }
|
Proxy for the rawQuery command .
|
197
|
public void execNoArgVoidMethod ( Transaction transaction ) throws SQLException { long timeNow = System . currentTimeMillis ( ) ; long delta = 0 ; do { try { switch ( transaction ) { case setTransactionSuccessful : sqliteDatabase . setTransactionSuccessful ( ) ; return ; case beginTransaction : sqliteDatabase . beginTransaction ( ) ; return ; case endTransaction : sqliteDatabase . endTransaction ( ) ; return ; case close : sqliteDatabase . close ( ) ; return ; } } catch ( SQLiteException e ) { if ( isLockedException ( e ) ) { delta = System . currentTimeMillis ( ) - timeNow ; } else { throw SQLDroidConnection . chainException ( e ) ; } } } while ( delta < timeout ) ; throw new SQLException ( "Timeout Expired" ) ; }
|
Executes one of the methods in the transactions enum . This just allows the timeout code to be combined in one method .
|
198
|
public int changedRowCount ( ) { if ( getChangedRowCount == null ) { try { getChangedRowCount = sqliteDatabase . getClass ( ) . getMethod ( "changedRowCount" , ( Class < ? > [ ] ) null ) ; } catch ( Exception any ) { try { getChangedRowCount = sqliteDatabase . getClass ( ) . getDeclaredMethod ( "lastChangeCount" , ( Class < ? > [ ] ) null ) ; getChangedRowCount . setAccessible ( true ) ; } catch ( Exception e ) { } } } if ( getChangedRowCount != null ) { try { return ( ( Integer ) getChangedRowCount . invoke ( sqliteDatabase , ( Object [ ] ) null ) ) . intValue ( ) ; } catch ( Exception e ) { } } return 1 ; }
|
The count of changed rows . On JNA platforms this is a call to sqlite3_changes On Android it s a convoluted call to a package - private method ( or if that fails the response is 1 .
|
199
|
public static SQLException chainException ( android . database . SQLException sqlException ) { if ( sqlThrowable < 0 || sqlThrowable >= 9 ) { try { sqlThrowable = 9 ; final Constructor < ? > c = SQLException . class . getDeclaredConstructor ( new Class [ ] { Throwable . class } ) ; return ( SQLException ) c . newInstance ( new Object [ ] { sqlException } ) ; } catch ( Exception e ) { sqlThrowable = 1 ; } } try { final Constructor < ? > c = SQLDroidConnection . class . getClassLoader ( ) . loadClass ( "org.sqldroid.SQLDroidSQLException" ) . getDeclaredConstructor ( new Class [ ] { android . database . SQLException . class } ) ; return ( SQLException ) c . newInstance ( new Object [ ] { sqlException } ) ; } catch ( Exception e ) { return new SQLException ( "Unable to Chain SQLException " + sqlException . getMessage ( ) ) ; } }
|
This will create and return an exception . For API levels less than 9 this will return a SQLDroidSQLException for later APIs it will return a SQLException .
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.