idx
int64
0
165k
question
stringlengths
73
4.15k
target
stringlengths
5
918
len_question
int64
21
890
len_target
int64
3
255
42,200
public void saveAll ( PGConnection connection , Stream < TEntity > entities ) throws SQLException { try ( PgBinaryWriter bw = new PgBinaryWriter ( configuration . getBufferSize ( ) ) ) { // Wrap the CopyOutputStream in our own Writer: bw . open ( new PGCopyOutputStream ( connection , mapping . getCopyCommand ( ) , 1 ) ...
Save stream of entities
115
4
42,201
static String capitalizeFirstWordAsciiOnly ( String s ) { if ( s == null || s . isEmpty ( ) ) { return s ; } int secondWordStart = s . length ( ) ; for ( int i = 1 ; i < s . length ( ) ; i ++ ) { if ( ! isLowerCaseAsciiOnly ( s . charAt ( i ) ) ) { secondWordStart = i ; break ; } } return toUpperCaseAsciiOnly ( s . sub...
fooBar - > FOOBar FooBar - > FOOBar foo - > FOO
127
19
42,202
@ Nullable static ExecutableElement findLargestPublicConstructor ( TypeElement typeElement ) { List < ExecutableElement > constructors = FluentIterable . from ( ElementFilter . constructorsIn ( typeElement . getEnclosedElements ( ) ) ) . filter ( FILTER_NON_PUBLIC ) . toList ( ) ; if ( constructors . size ( ) == 0 ) { ...
Returns the public constructor in a given class with the largest number of arguments or null if there are no public constructors .
109
24
42,203
static boolean isSingleton ( Types types , TypeElement element ) { return isSingleton ( types , element , element . asType ( ) ) ; }
A singleton is defined by a class with a public static final field named INSTANCE with a type assignable from itself .
32
25
42,204
static boolean isParcelable ( Elements elements , Types types , TypeMirror type ) { TypeMirror parcelableType = elements . getTypeElement ( PARCELABLE_CLASS_NAME ) . asType ( ) ; return types . isAssignable ( type , parcelableType ) ; }
Returns true if a type implements Parcelable
63
9
42,205
@ Nullable static AnnotationMirror getAnnotationWithSimpleName ( Element element , String name ) { for ( AnnotationMirror mirror : element . getAnnotationMirrors ( ) ) { String annotationName = mirror . getAnnotationType ( ) . asElement ( ) . getSimpleName ( ) . toString ( ) ; if ( name . equals ( annotationName ) ) { ...
Finds an annotation with the given name on the given element or null if not found .
90
18
42,206
private static boolean extractAndLoadLibraryFile ( String libFolderForCurrentOS , String libraryFileName , String targetFolder ) { String nativeLibraryFilePath = libFolderForCurrentOS + "/" + libraryFileName ; // Include architecture name in temporary filename in order to avoid conflicts // when multiple JVMs with diff...
Extracts and loads the specified library file to the target folder
601
13
42,207
private static boolean loadNativeLibrary ( String path , String name ) { File libPath = new File ( path , name ) ; if ( libPath . exists ( ) ) { try { System . load ( new File ( path , name ) . getAbsolutePath ( ) ) ; return true ; } catch ( UnsatisfiedLinkError e ) { System . err . println ( "Failed to load native lib...
Loads native library using the given path and name of the library .
132
14
42,208
private static void loadSecp256k1NativeLibrary ( ) throws Exception { if ( extracted ) { return ; } // Try loading library from fr.acinq.secp256k1.lib.path library path */ String secp256k1NativeLibraryPath = System . getProperty ( "fr.acinq.secp256k1.lib.path" ) ; String secp256k1NativeLibraryName = System . getPropert...
Loads secp256k1 native library using given path and name of the library .
627
18
42,209
public static String absoluteHrefOf ( final String path ) { try { return fromCurrentServletMapping ( ) . path ( path ) . build ( ) . toString ( ) ; } catch ( final IllegalStateException e ) { return path ; } }
Returns an absolute URL for the specified path .
54
9
42,210
@ Override public void disable ( final String jobType , final String comment ) { setValue ( jobType , KEY_DISABLED , comment != null ? comment : "" ) ; }
Disables a job type i . e . prevents it from being started
39
14
42,211
@ Override public Set < String > findAllJobTypes ( ) { return stream ( collection . find ( ) . maxTime ( 500 , TimeUnit . MILLISECONDS ) . spliterator ( ) , false ) . map ( doc -> doc . getString ( ID ) ) . collect ( toSet ( ) ) ; }
Returns all job types having state information .
69
8
42,212
public boolean update ( final V value , final long maxTime , final TimeUnit timeUnit ) { final K key = keyOf ( value ) ; if ( key != null ) { return collectionWithWriteTimeout ( maxTime , timeUnit ) . replaceOne ( byId ( key ) , encode ( value ) ) . getModifiedCount ( ) == 1 ; } else { throw new IllegalArgumentExceptio...
Updates the document if it is already present in the repository .
95
13
42,213
public void delete ( final K key , final long maxTime , final TimeUnit timeUnit ) { collectionWithWriteTimeout ( maxTime , timeUnit ) . deleteOne ( byId ( key ) ) ; }
Deletes the document identified by key .
43
8
42,214
protected Document byId ( final K key ) { if ( key != null ) { return new Document ( ID , key . toString ( ) ) ; } else { throw new NullPointerException ( "Key must not be null" ) ; } }
Returns a query that is selecting documents by ID .
52
10
42,215
@ Override public JobMeta getJobMeta ( String jobType ) { final Map < String , String > document = map . get ( jobType ) ; if ( document != null ) { final Map < String , String > meta = document . keySet ( ) . stream ( ) . filter ( key -> ! key . startsWith ( "_e_" ) ) . collect ( toMap ( key -> key , document :: get )...
Returns the current state of the specified job type .
186
10
42,216
public static ServiceType serviceType ( final String type , final Criticality criticality , final String disasterImpact ) { return new ServiceType ( type , criticality , disasterImpact ) ; }
Creates a ServiceType .
40
6
42,217
public static EdisonApplicationProperties edisonApplicationProperties ( final String title , final String group , final String environment , final String description ) { final EdisonApplicationProperties edisonApplicationProperties = new EdisonApplicationProperties ( ) ; edisonApplicationProperties . setTitle ( title )...
Only used in tests .
122
5
42,218
public StatusDetail statusDetail ( final JobDefinition jobDefinition ) { try { final List < JobInfo > jobs = jobRepository . findLatestBy ( jobDefinition . jobType ( ) , numberOfJobs + 1 ) ; return jobs . isEmpty ( ) ? statusDetailWhenNoJobAvailable ( jobDefinition ) : toStatusDetail ( jobs , jobDefinition ) ; } catch ...
Returns a StatusDetail for a JobDefinition . The Status of the StatusDetail is calculated using the last job executions and depends on the configuration of the calculator .
158
33
42,219
protected StatusDetail toStatusDetail ( final List < JobInfo > jobInfos , final JobDefinition jobDefinition ) { final Status status ; final String message ; final JobInfo currentJob = jobInfos . get ( 0 ) ; final JobInfo lastJob = ( ! currentJob . getStopped ( ) . isPresent ( ) && currentJob . getStatus ( ) == JobStatu...
Calculates the StatusDetail from the last job executions .
519
13
42,220
protected final long getNumFailedJobs ( final List < JobInfo > jobInfos ) { return jobInfos . stream ( ) . filter ( job -> JobStatus . ERROR . equals ( job . getStatus ( ) ) ) . count ( ) ; }
Returns the number of failed jobs .
55
7
42,221
protected Map < String , String > runningDetailsFor ( final JobInfo jobInfo ) { final Map < String , String > details = new HashMap <> ( ) ; details . put ( "Started" , ISO_DATE_TIME . format ( jobInfo . getStarted ( ) ) ) ; if ( jobInfo . getStopped ( ) . isPresent ( ) ) { details . put ( "Stopped" , ISO_DATE_TIME . f...
Returns additional information like job uri running state started and stopped timestamps .
119
16
42,222
protected boolean jobTooOld ( final JobInfo jobInfo , final JobDefinition jobDefinition ) { final Optional < OffsetDateTime > stopped = jobInfo . getStopped ( ) ; if ( stopped . isPresent ( ) && jobDefinition . maxAge ( ) . isPresent ( ) ) { final OffsetDateTime deadlineToRerun = stopped . get ( ) . plus ( jobDefinitio...
Calculates whether or not the last job execution is too old .
113
14
42,223
@ Scheduled ( fixedRate = KEEP_LAST_JOBS_CLEANUP_INTERVAL ) public void doCleanUp ( ) { final List < JobInfo > jobs = jobRepository . findAllJobInfoWithoutMessages ( ) ; findJobsToDelete ( jobs ) . forEach ( jobInfo -> jobRepository . removeIfStopped ( jobInfo . getJobId ( ) ) ) ; }
Execute the cleanup of the given repository .
89
9
42,224
public Optional < JobDefinition > getJobDefinition ( final String jobType ) { return jobDefinitions . stream ( ) . filter ( ( j ) - > j . jobType ( ) . equalsIgnoreCase ( jobType ) ) . findAny ( ) ; }
Returns an optional JobDefinition matching the given jobType .
55
11
42,225
public Optional < String > startAsyncJob ( String jobType ) { try { final JobRunnable jobRunnable = findJobRunnable ( jobType ) ; final JobInfo jobInfo = createJobInfo ( jobType ) ; jobMetaService . aquireRunLock ( jobInfo . getJobId ( ) , jobInfo . getJobType ( ) ) ; jobRepository . createOrUpdate ( jobInfo ) ; return...
Starts a job asynchronously in the background .
149
11
42,226
public List < JobInfo > findJobs ( final Optional < String > type , final int count ) { if ( type . isPresent ( ) ) { return jobRepository . findLatestBy ( type . get ( ) , count ) ; } else { return jobRepository . findLatest ( count ) ; } }
Find the latest jobs optionally restricted to jobs of a specified type .
66
13
42,227
private void clearRunLocks ( ) { jobMetaService . runningJobs ( ) . forEach ( ( RunningJob runningJob ) -> { final Optional < JobInfo > jobInfoOptional = jobRepository . findOne ( runningJob . jobId ) ; if ( jobInfoOptional . isPresent ( ) && jobInfoOptional . get ( ) . isStopped ( ) ) { jobMetaService . releaseRunLock...
Checks all run locks and releases the lock if the job is stopped .
178
15
42,228
public static VersionInfoProperties versionInfoProperties ( final String version , final String commit , final String urlTemplate ) { final VersionInfoProperties p = new VersionInfoProperties ( ) ; p . version = version ; p . commit = commit ; p . urlTemplate = urlTemplate ; return p ; }
Used for testing purposes .
64
5
42,229
public StatusDetail withDetail ( final String key , final String value ) { final LinkedHashMap < String , String > newDetails = new LinkedHashMap <> ( details ) ; newDetails . put ( key , value ) ; return statusDetail ( name , status , message , newDetails ) ; }
Create a copy of this StatusDetail add a detail and return the new StatusDetail .
67
19
42,230
public StatusDetail withoutDetail ( final String key ) { final LinkedHashMap < String , String > newDetails = new LinkedHashMap <> ( details ) ; newDetails . remove ( key ) ; return statusDetail ( name , status , message , newDetails ) ; }
Create a copy of this StatusDetail remove a detail and return the new StatusDetail .
61
19
42,231
public static DatasourceDependencyBuilder mongoDependency ( final List < Datasource > datasources ) { return new DatasourceDependencyBuilder ( ) . withDatasources ( datasources ) . withType ( DatasourceDependency . TYPE_DB ) . withSubtype ( DatasourceDependency . SUBTYPE_MONGODB ) ; }
Creates a ServiceDependencyBuilder with type = db and subtype = MongoDB .
83
19
42,232
public static DatasourceDependencyBuilder redisDependency ( final List < Datasource > datasources ) { return new DatasourceDependencyBuilder ( ) . withDatasources ( datasources ) . withType ( DatasourceDependency . TYPE_DB ) . withSubtype ( DatasourceDependency . SUBTYPE_REDIS ) ; }
Creates a ServiceDependencyBuilder with type = db and subtype = Redis .
81
19
42,233
public static DatasourceDependencyBuilder cassandraDependency ( final List < Datasource > datasources ) { return new DatasourceDependencyBuilder ( ) . withDatasources ( datasources ) . withType ( DatasourceDependency . TYPE_DB ) . withSubtype ( DatasourceDependency . SUBTYPE_CASSANDRA ) ; }
Creates a ServiceDependencyBuilder with type = db and subtype = Cassandra .
83
18
42,234
public static DatasourceDependencyBuilder elasticSearchDependency ( final List < Datasource > datasources ) { return new DatasourceDependencyBuilder ( ) . withDatasources ( datasources ) . withType ( DatasourceDependency . TYPE_DB ) . withSubtype ( DatasourceDependency . SUBTYPE_ELASTICSEARCH ) ; }
Creates a ServiceDependencyBuilder with type = db and subtype = ElasticSearch .
84
19
42,235
public static DatasourceDependencyBuilder kafkaDependency ( final List < Datasource > datasources ) { return new DatasourceDependencyBuilder ( ) . withDatasources ( datasources ) . withType ( DatasourceDependency . TYPE_QUEUE ) . withSubtype ( DatasourceDependency . SUBTYPE_KAFKA ) ; }
Creates a ServiceDependencyBuilder with type = queue and subtype = Kafka .
85
18
42,236
public static LdapProperties ldapProperties ( final String host , final int port , final List < String > baseDn , final String roleBaseDn , final String rdnIdentifier , final List < String > prefix , final EncryptionType encryptionType , final String ... whitelistedPaths ) { final LdapProperties ldap = new LdapProperti...
Creates Ldap properties . Primarily used in tests .
216
13
42,237
public static ServiceDependencyBuilder restServiceDependency ( final String url ) { return new ServiceDependencyBuilder ( ) . withUrl ( url ) . withType ( ServiceDependency . TYPE_SERVICE ) . withSubtype ( ServiceDependency . SUBTYPE_REST ) . withMethods ( singletonList ( "GET" ) ) . withMediaTypes ( singletonList ( "a...
Creates a ServiceDependencyBuilder with type = service and subtype = REST .
94
18
42,238
public static ServiceDependencyBuilder serviceDependency ( final String url ) { return new ServiceDependencyBuilder ( ) . withUrl ( url ) . withType ( ServiceDependency . TYPE_SERVICE ) . withSubtype ( ServiceDependency . SUBTYPE_OTHER ) ; }
Creates a generic ServiceDependencyBuilder with type = service and subtype = OTHER .
63
19
42,239
public static Datasource datasource ( final String node , final int port , final String resource ) { return new Datasource ( node , port , resource ) ; }
Creates a Datasource from node port and resource descriptors .
35
14
42,240
public static JobDefinition manuallyTriggerableJobDefinition ( final String jobType , final String jobName , final String description , final int restarts , final Optional < Duration > maxAge ) { return new DefaultJobDefinition ( jobType , jobName , description , maxAge , Optional . empty ( ) , Optional . empty ( ) , r...
Create a JobDefinition for a job that will not be triggered automatically by a job trigger .
80
18
42,241
@ Override public byte [ ] getData ( ) { byte [ ] data = new byte [ frameData . length + 2 ] ; int first2 = ( FRAME_SYNC << 2 ) ; if ( blockSizeVariable ) first2 ++ ; IOUtils . putInt2BE ( data , 0 , first2 ) ; System . arraycopy ( frameData , 0 , data , 2 , frameData . length ) ; return data ; }
Returns the contents including the sync header
94
7
42,242
public void setUtc ( String utc ) { if ( utc == null ) { this . utc = null ; } else { if ( utc . length ( ) != 20 ) { throw new IllegalArgumentException ( "Must be of the form YYYYMMDDTHHMMSS.sssZ" ) ; } } }
Sets the ISO - 8601 UTC time of the file which must be YYYYMMDDTHHMMSS . sssZ or null
73
30
42,243
public void processPacket ( OggPacket packet ) { SkeletonPacket skel = SkeletonPacketFactory . create ( packet ) ; // First packet must be the head if ( packet . isBeginningOfStream ( ) ) { fishead = ( SkeletonFishead ) skel ; } else if ( skel instanceof SkeletonFisbone ) { SkeletonFisbone bone = ( SkeletonFisbone ) sk...
Processes and tracks the next packet for the stream
197
10
42,244
public SkeletonFisbone addBoneForStream ( int sid ) { SkeletonFisbone bone = new SkeletonFisbone ( ) ; bone . setSerialNumber ( sid ) ; fisbones . add ( bone ) ; if ( sid == - 1 || bonesByStream . containsKey ( sid ) ) { throw new IllegalArgumentException ( "Invalid / duplicate sid " + sid ) ; } bonesByStream . put ( s...
Adds a new fisbone for the given stream
100
10
42,245
protected int addPacket ( OggPacket packet , int offset ) { if ( packet . isBeginningOfStream ( ) ) { isBOS = true ; } if ( packet . isEndOfStream ( ) ) { isEOS = true ; } // Add on in 255 byte chunks int size = packet . getData ( ) . length ; for ( int i = numLVs ; i < 255 ; i ++ ) { int remains = size - offset ; int ...
Adds as much of the packet s data as we can do .
178
13
42,246
public boolean isChecksumValid ( ) { if ( checksum == 0 ) return true ; int crc = CRCUtils . getCRC ( getHeader ( ) ) ; if ( data != null && data . length > 0 ) { crc = CRCUtils . getCRC ( data , crc ) ; } return ( checksum == crc ) ; }
Is the checksum for the page valid?
79
9
42,247
protected boolean hasSpaceFor ( int bytes ) { // Do we have enough lvs spare? // (Each LV holds up to 255 bytes, and we're // not allowed more than 255 of them) int reqLVs = ( int ) Math . ceil ( bytes / 255.0 ) ; if ( numLVs + reqLVs > 255 ) { return false ; } return true ; }
Does this Page have space for the given number of bytes?
82
12
42,248
public int getDataSize ( ) { // Data size is given by lvs int size = 0 ; for ( int i = 0 ; i < numLVs ; i ++ ) { size += IOUtils . toInt ( lvs [ i ] ) ; } return size ; }
How big is the page excluding headers?
60
8
42,249
protected byte [ ] getHeader ( ) { byte [ ] header = new byte [ MINIMUM_PAGE_SIZE + numLVs ] ; header [ 0 ] = ( byte ) ' ' ; header [ 1 ] = ( byte ) ' ' ; header [ 2 ] = ( byte ) ' ' ; header [ 3 ] = ( byte ) ' ' ; header [ 4 ] = 0 ; // Version byte flags = 0 ; if ( isContinue ) { flags += 1 ; } if ( isBOS ) { flags +=...
Gets the header but with a blank CRC field
239
10
42,250
protected OggStreamPacket createNext ( OggPacket packet ) { if ( type == OggStreamIdentifier . OGG_VORBIS ) { return VorbisPacketFactory . create ( packet ) ; } else if ( type == OggStreamIdentifier . SPEEX_AUDIO ) { return SpeexPacketFactory . create ( packet ) ; } else if ( type == OggStreamIdentifier . OPUS_AUDIO ) ...
Creates an appropriate high level packet
163
7
42,251
public boolean populate ( OggPacket packet ) { // TODO Finish the flac support properly if ( type == OggStreamIdentifier . OGG_FLAC ) { if ( tags == null ) { tags = new FlacTags ( packet ) ; return true ; } else { // TODO Finish FLAC support return false ; } } OggStreamPacket sPacket = createNext ( packet ) ; if ( sPac...
Populates with the next header
210
6
42,252
public static long readUE7 ( InputStream stream ) throws IOException { int i ; long v = 0 ; while ( ( i = stream . read ( ) ) >= 0 ) { v = v << 7 ; if ( ( i & 128 ) == 128 ) { // Continues v += ( i & 127 ) ; } else { // Last value v += i ; break ; } } return v ; }
Gets the integer value that is stored in UTF - 8 like fashion in Big Endian but with the high bit on each number indicating if it continues or not
84
32
42,253
public static String removeNullPadding ( String str ) { int idx = str . indexOf ( 0 ) ; if ( idx == - 1 ) { return str ; } return str . substring ( 0 , idx ) ; }
Strips off any null padding if any from the string
50
12
42,254
public static void writeUTF8 ( OutputStream out , String str ) throws IOException { byte [ ] s = str . getBytes ( UTF8 ) ; out . write ( s ) ; }
Writes the string out as UTF - 8
40
9
42,255
public static boolean byteRangeMatches ( byte [ ] wanted , byte [ ] within , int withinOffset ) { for ( int i = 0 ; i < wanted . length ; i ++ ) { if ( wanted [ i ] != within [ i + withinOffset ] ) return false ; } return true ; }
Checks to see if the wanted byte pattern is found in the within bytes from the given offset
63
19
42,256
protected static MediaType toMediaType ( OggStreamType type ) { if ( type == OggStreamIdentifier . UNKNOWN ) { // We don't have a specific type available to return return OGG_GENERAL ; } else { // Say it's the specific type we found return MediaType . parse ( type . mimetype ) ; } }
Converts from our type to Tika s type
74
10
42,257
public int addSoundtrack ( OggAudioHeaders audio ) { if ( w == null ) { throw new IllegalStateException ( "Not in write mode" ) ; } // If it doesn't have a sid yet, get it one OggPacketWriter aw = null ; if ( audio . getSid ( ) == - 1 ) { aw = ogg . getPacketWriter ( ) ; // TODO How to tell the OggAudioHeaders the new ...
Adds a new soundtrack to the video
264
7
42,258
public OggStreamAudioVisualData getNextAudioVisualPacket ( Set < Integer > sids ) throws IOException { OggStreamAudioVisualData data = null ; while ( data == null && ! pendingPackets . isEmpty ( ) ) { AudioVisualDataAndSid avd = pendingPackets . removeFirst ( ) ; if ( sids == null || sids . contains ( avd . sid ) ) { d...
Returns the next audio or video packet from any of the specified streams or null if no more remain
313
19
42,259
public void close ( ) throws IOException { if ( r != null ) { r = null ; ogg . close ( ) ; ogg = null ; } if ( w != null ) { // First, write the initial packet of each stream // Skeleton (if present) goes first, then video, then audio(s) OggPacketWriter sw = null ; if ( skeleton != null ) { sw = ogg . getPacketWriter (...
In Reading mode will close the underlying ogg file and free its resources . In Writing mode will write out the Info Comment Tags objects and then the video and audio data .
729
34
42,260
public int getNumberOfCodebooks ( ) { byte [ ] data = getData ( ) ; int number = - 1 ; if ( data != null && data . length >= 10 ) { number = IOUtils . toInt ( data [ 8 ] ) ; } return ( number + 1 ) ; }
Example first bit of decoding
64
5
42,261
@ Override public void populateMetadataHeader ( byte [ ] b , int dataLength ) { b [ 0 ] = FlacMetadataBlock . VORBIS_COMMENT ; IOUtils . putInt3BE ( b , 1 , dataLength ) ; }
Type plus three byte length
58
5
42,262
public void calculate ( ) throws IOException { OggStreamAudioData data ; // Calculate the headers sizing OggAudioInfoHeader info = headers . getInfo ( ) ; handleHeader ( info ) ; handleHeader ( headers . getTags ( ) ) ; handleHeader ( headers . getSetup ( ) ) ; // Have each audio packet handled, tracking at least granu...
Calculate the statistics
210
5
42,263
public void setGranulePosition ( long position ) { currentGranulePosition = position ; for ( OggPage p : buffer ) { p . setGranulePosition ( position ) ; } }
Sets the current granule position . The granule position will be applied to all un - flushed packets and all future packets . As such you should normally either call a flush just before or just after this call .
43
43
42,264
public void bufferPacket ( OggPacket packet , long granulePosition ) { if ( closed ) { throw new IllegalStateException ( "Can't buffer packets on a closed stream!" ) ; } if ( ! doneFirstPacket ) { packet . setIsBOS ( ) ; doneFirstPacket = true ; } int size = packet . getData ( ) . length ; boolean emptyPacket = ( size ...
Buffers the given packet up ready for writing to the stream but doesn t write it to disk yet . The granule position is updated on the page . If writing the packet requires a new page then the updated granule position only applies to the new page
203
51
42,265
public int getCurrentPageSize ( ) { if ( buffer . isEmpty ( ) ) return OggPage . getMinimumPageSize ( ) ; OggPage p = buffer . get ( buffer . size ( ) - 1 ) ; return p . getPageSize ( ) ; }
Returns the size of the page currently being written to including its headers . For a new stream or a stream that has just been flushed will return zero .
58
30
42,266
public void flush ( ) throws IOException { if ( closed ) { throw new IllegalStateException ( "Can't flush packets on a closed stream!" ) ; } // Write in one go OggPage [ ] pages = buffer . toArray ( new OggPage [ buffer . size ( ) ] ) ; file . writePages ( pages ) ; // Get ready for next time! buffer . clear ( ) ; }
Writes all pending packets to the stream splitting across pages as needed .
85
14
42,267
public void close ( ) throws IOException { if ( buffer . size ( ) > 0 ) { buffer . get ( buffer . size ( ) - 1 ) . setIsEOS ( ) ; } else { OggPacket p = new OggPacket ( new byte [ 0 ] ) ; p . setIsEOS ( ) ; bufferPacket ( p ) ; } flush ( ) ; closed = true ; }
Writes all pending packets to the stream with the last one containing the End Of Stream Flag and then closes down .
88
23
42,268
public OggPacketWriter getPacketWriter ( int sid ) { if ( ! writing ) { throw new IllegalStateException ( "Can only write to a file opened with an OutputStream" ) ; } seenSIDs . add ( sid ) ; return new OggPacketWriter ( this , sid ) ; }
Creates a new Logical Bit Stream in the file and returns a Writer for putting data into it .
66
21
42,269
protected int getUnusedSerialNumber ( ) { while ( true ) { int sid = ( int ) ( Math . random ( ) * Short . MAX_VALUE ) ; if ( ! seenSIDs . contains ( sid ) ) { return sid ; } } }
Returns a random but previously un - used serial number for use by a new stream
54
16
42,270
public static FlacFile open ( File f ) throws IOException , FileNotFoundException { // Open, in a way that we can skip backwards a few bytes InputStream inp = new BufferedInputStream ( new FileInputStream ( f ) , 8 ) ; FlacFile file = open ( inp ) ; return file ; }
Opens the given file for reading
70
7
42,271
public List < String > getComments ( String tag ) { List < String > c = comments . get ( normaliseTag ( tag ) ) ; if ( c == null ) { return new ArrayList < String > ( ) ; } else { return c ; } }
Returns all comments for a given tag in file order . Will return an empty list for tags which aren t present .
55
23
42,272
public void addComment ( String tag , String comment ) { String nt = normaliseTag ( tag ) ; if ( ! comments . containsKey ( nt ) ) { comments . put ( nt , new ArrayList < String > ( ) ) ; } comments . get ( nt ) . add ( comment ) ; }
Adds a comment for a given tag
68
7
42,273
public void setComments ( String tag , List < String > comments ) { String nt = normaliseTag ( tag ) ; if ( this . comments . containsKey ( nt ) ) { this . comments . remove ( nt ) ; } this . comments . put ( nt , comments ) ; }
Removes any existing comments for a given tag and replaces them with the supplied list
64
16
42,274
static List < MethodParameter > extract ( String path ) { List < MethodParameter > output = new ArrayList <> ( ) ; List < String > items = split ( path ) ; if ( items . size ( ) > 0 ) { int pathIndex = 0 ; int index = 0 ; for ( String item : items ) { MethodParameter param = getParamFromPath ( item , index , pathIndex ...
Extract method argument parameters from path definition
121
8
42,275
private static String convertSub ( String path ) { if ( isRestEasyPath ( path ) ) { // remove {} path = path . substring ( 1 , path . length ( ) - 1 ) ; int index = path . lastIndexOf ( ":" ) ; // check for regular expression if ( index > 0 && index + 1 < path . length ( ) ) { return path . substring ( index + 1 ) ; //...
Converts from RestEasy to Vert . X format if necessary
170
12
42,276
private static String removeMatrixFromPath ( String path , RouteDefinition definition ) { // simple removal ... we don't care what matrix attributes were given if ( definition . hasMatrixParams ( ) ) { int index = path . indexOf ( ";" ) ; if ( index > 0 ) { return path . substring ( 0 , index ) ; } } return path ; }
Removes matrix params from path
77
6
42,277
public static < T > Object constructType ( Class < T > type , String fromValue ) throws ClassFactoryException { Assert . notNull ( type , "Missing type!" ) ; // a primitive or "simple" type if ( isSimpleType ( type ) ) { return stringToPrimitiveType ( fromValue , type ) ; } // have a constructor that accepts a single a...
Aims to construct given type utilizing a constructor that takes String or other primitive type values
331
17
42,278
private static < T > List < Method > getMethods ( Class < T > type , String ... names ) { Assert . notNull ( type , "Missing class to search for methods!" ) ; Assert . notNullOrEmpty ( names , "Missing method names to search for!" ) ; Map < String , Method > candidates = new HashMap <> ( ) ; for ( Method method : type ...
Get methods in order desired to invoke them one by one until match or fail
227
15
42,279
@ SafeVarargs public final RestBuilder errorHandler ( Class < ? extends ExceptionHandler > ... handlers ) { Assert . notNullOrEmpty ( handlers , "Missing exception handler(s)!" ) ; exceptionHandlers . addAll ( Arrays . asList ( handlers ) ) ; return this ; }
Registeres one or more exception handler classes
63
9
42,280
public < T > RestBuilder provide ( ContextProvider < T > provider ) { Assert . notNull ( provider , "Missing context provider!" ) ; contextProviders . add ( provider ) ; return this ; }
Creates a provider handler into routing
44
7
42,281
private static MediaType parse ( String mediaType ) { Assert . notNullOrEmptyTrimmed ( mediaType , "Missing media type!" ) ; String type = null ; String subType = null ; Map < String , String > params = new HashMap <> ( ) ; String [ ] parts = mediaType . split ( ";" ) ; for ( int i = 0 ; i < parts . length ; i ++ ) { S...
Simple parsing utility to get MediaType
328
7
42,282
public ValueReader get ( MethodParameter parameter , Class < ? extends ValueReader > byMethodDefinition , InjectionProvider provider , RoutingContext context , MediaType ... mediaTypes ) { // by type Class < ? > readerType = null ; try { // reader parameter as given Assert . notNull ( parameter , "Missing parameter!" )...
Step over all possibilities to provide desired reader
280
8
42,283
public void register ( Class < ? extends ValueReader > reader ) { Assert . notNull ( reader , "Missing reader class!" ) ; boolean registered = false ; Consumes found = reader . getAnnotation ( Consumes . class ) ; if ( found != null ) { MediaType [ ] consumes = MediaTypeHelper . getMediaTypes ( found . value ( ) ) ; if...
Takes media type from
150
5
42,284
public static Map < RouteDefinition , Method > get ( Class clazz ) { Map < RouteDefinition , Method > out = new HashMap <> ( ) ; Map < RouteDefinition , Method > candidates = collect ( clazz ) ; // Final check if definitions are OK for ( RouteDefinition definition : candidates . keySet ( ) ) { if ( definition . getMeth...
Extracts all JAX - RS annotated methods from class and all its subclasses and interfaces
442
20
42,285
private static RouteDefinition find ( Map < RouteDefinition , Method > add , Method method ) { if ( add == null || add . size ( ) == 0 ) { return null ; } for ( RouteDefinition additional : add . keySet ( ) ) { Method match = add . get ( additional ) ; if ( isMatching ( method , match ) ) { return additional ; } } retu...
Find mathing definition for same method ...
83
8
42,286
private static Map < RouteDefinition , Method > getDefinitions ( Class clazz ) { Assert . notNull ( clazz , "Missing class with JAX-RS annotations!" ) ; // base RouteDefinition root = new RouteDefinition ( clazz ) ; // go over methods ... Map < RouteDefinition , Method > output = new LinkedHashMap <> ( ) ; for ( Method...
Checks class for JAX - RS annotations and returns a list of route definitions to build routes upon
177
20
42,287
public static Object provideContext ( Class < ? > type , String defaultValue , RoutingContext context ) throws ContextException { // vert.x context if ( type . isAssignableFrom ( HttpServerResponse . class ) ) { return context . response ( ) ; } if ( type . isAssignableFrom ( HttpServerRequest . class ) ) { return cont...
Provides vertx context of desired type if possible
409
10
42,288
private static void checkWriterCompatibility ( RouteDefinition definition ) { try { // no way to know the accept content at this point getWriter ( injectionProvider , definition . getReturnType ( ) , definition , null , GenericResponseWriter . class ) ; } catch ( ClassFactoryException e ) { // ignoring instance creatio...
Check writer compatibility if possible
74
5
42,289
public static void notFound ( Router router , Class < ? extends NotFoundResponseWriter > notFound ) { notFound ( router , null , notFound ) ; }
Handles not found route for all requests
34
8
42,290
public static void notFound ( Router router , String regExPath , Class < ? extends NotFoundResponseWriter > notFound ) { Assert . notNull ( router , "Missing router!" ) ; Assert . notNull ( notFound , "Missing not found handler!" ) ; addLastHandler ( router , regExPath , getNotFoundHandler ( notFound ) ) ; }
Handles not found route in case request regExPath mathes given regExPath prefix
79
18
42,291
public static void addProvider ( Class < ? extends ContextProvider > provider ) { Class clazz = ( Class ) ClassFactory . getGenericType ( provider ) ; addProvider ( clazz , provider ) ; }
Registers a context provider for given type of class
43
10
42,292
public HttpResponseWriter getResponseWriter ( Class returnType , RouteDefinition definition , InjectionProvider provider , RoutingContext routeContext , MediaType accept ) { try { HttpResponseWriter writer = null ; if ( accept != null ) { writer = get ( returnType , definition . getWriter ( ) , provider , routeContext ...
Finds assigned response writer or tries to assign a writer according to produces annotation and result type
239
18
42,293
private static String createMessage ( RouteDefinition definition , Set < ? extends ConstraintViolation < ? > > constraintViolations ) { List < String > messages = new ArrayList <> ( ) ; for ( ConstraintViolation < ? > violation : constraintViolations ) { StringBuilder message = new StringBuilder ( ) ; for ( Path . Node...
Tries to produce some sensible message to make some informed decision
357
12
42,294
public static < T > Set < T > subSet ( Set < T > original , int from , int to ) { List < T > list = new ArrayList <> ( original ) ; if ( to == - 1 ) { to = original . size ( ) ; } return new LinkedHashSet <> ( list . subList ( from , to ) ) ; }
Get sub - set of a set .
78
8
42,295
public static < T > Collection < T > intersect ( Collection < T > first , Collection < T > second ) { E . checkNotNull ( first , "first" ) ; E . checkNotNull ( second , "second" ) ; HashSet < T > results = null ; if ( first instanceof HashSet ) { @ SuppressWarnings ( "unchecked" ) HashSet < T > clone = ( HashSet < T > ...
Find the intersection of two collections the original collections will not be modified
140
13
42,296
public static < T > Collection < T > intersectWithModify ( Collection < T > first , Collection < T > second ) { E . checkNotNull ( first , "first" ) ; E . checkNotNull ( second , "second" ) ; first . retainAll ( second ) ; return first ; }
Find the intersection of two collections note that the first collection will be modified and store the results
65
18
42,297
public final Lock lock ( Object key ) { Lock lock = this . locks . get ( key ) ; lock . lock ( ) ; return lock ; }
Lock an object
31
3
42,298
public final List < Lock > lockAll ( Object ... keys ) { List < Lock > locks = new ArrayList <> ( keys . length ) ; for ( Object key : keys ) { Lock lock = this . locks . get ( key ) ; locks . add ( lock ) ; } Collections . sort ( locks , ( a , b ) -> { int diff = a . hashCode ( ) - b . hashCode ( ) ; if ( diff == 0 &&...
Lock a list of object with sorted order
173
8
42,299
public final void unlockAll ( List < Lock > locks ) { for ( int i = locks . size ( ) ; i > 0 ; i -- ) { assert this . indexOf ( locks . get ( i - 1 ) ) != - 1 ; locks . get ( i - 1 ) . unlock ( ) ; } }
Unlock a list of object
66
6