idx
int64
0
165k
question
stringlengths
73
4.15k
target
stringlengths
5
918
len_question
int64
21
890
len_target
int64
3
255
11,400
@ Override public void contextInitialized ( ServletContextEvent event ) { _registry . put ( INSTANCE , new Pair < Service , Persistence > ( this , null ) ) ; _context = event . getServletContext ( ) ; _application = _context . getContextPath ( ) ; _logger . config ( "application: " + _application ) ; if ( _application . charAt ( 0 ) == ' ' ) _application = _application . substring ( 1 ) ; try { ManagementFactory . getPlatformMBeanServer ( ) . setAttribute ( new ObjectName ( "Catalina:host=localhost,name=AccessLogValve,type=Valve" ) , new Attribute ( "condition" , "intrinsic" ) ) ; } catch ( Exception x ) { } }
Initializes the servlet context .
173
7
11,401
final public void plugInterfaces ( RobotAction newControl , RobotStatus newStatus , WorldInfo newWorld ) { SecurityManager sm = System . getSecurityManager ( ) ; if ( sm != null ) { sm . checkPermission ( new GamePermission ( "connectBank" ) ) ; } control = newControl ; info = newStatus ; world = newWorld ; }
Attaches a control to a bank
77
7
11,402
final public void setTeamId ( int newId ) { if ( teamId != - 1 ) { throw new IllegalStateException ( "Team Id cannot be modified" ) ; } SecurityManager sm = System . getSecurityManager ( ) ; if ( sm != null ) { sm . checkPermission ( new GamePermission ( "setTeamId" ) ) ; } teamId = newId ; }
Sets the team id . Can only be called once otherwise it will throw an exception
83
17
11,403
public static String stringFor ( int m ) { if ( m == CUFFT_COMPATIBILITY_NATIVE ) { return "CUFFT_COMPATIBILITY_NATIVE" ; } if ( ( m & CUFFT_COMPATIBILITY_FFTW_ALL ) == CUFFT_COMPATIBILITY_FFTW_ALL ) { return "CUFFT_COMPATIBILITY_FFTW_ALL" ; } StringBuilder sb = new StringBuilder ( ) ; if ( ( m & CUFFT_COMPATIBILITY_FFTW_PADDING ) != 0 ) { sb . append ( "CUFFT_COMPATIBILITY_FFTW_PADDING " ) ; } if ( ( m & CUFFT_COMPATIBILITY_FFTW_ASYMMETRIC ) != 0 ) { sb . append ( "CUFFT_COMPATIBILITY_FFTW_ASYMMETRIC " ) ; } return sb . toString ( ) ; }
Returns the String identifying the given cufftCompatibility
228
10
11,404
static public String getFormattedBytes ( long bytes , String units , String format ) { double num = bytes ; String [ ] prefix = { "" , "K" , "M" , "G" , "T" } ; int count = 0 ; while ( num >= 1024.0 ) { num = num / 1024.0 ; ++ count ; } DecimalFormat f = new DecimalFormat ( format ) ; return f . format ( num ) + " " + prefix [ count ] + units ; }
Returns the given bytes number formatted as KBytes MBytes or GBytes as appropriate .
106
17
11,405
static public String getFormattedDate ( long dt ) { String ret = "" ; SimpleDateFormat df = null ; try { if ( dt > 0 ) { df = formatPool . getFormat ( DATE_FORMAT ) ; df . setTimeZone ( DateUtilities . getCurrentTimeZone ( ) ) ; ret = df . format ( new Date ( dt ) ) ; } } catch ( Exception e ) { } if ( df != null ) formatPool . release ( df ) ; return ret ; }
Returns the given date parsed using dd - MM - yyyy .
109
14
11,406
static public String getLongFormattedDays ( long dt ) { StringBuffer ret = new StringBuffer ( ) ; long days = dt / 86400000L ; long millis = dt - ( days * 86400000L ) ; if ( days > 0 ) { ret . append ( Long . toString ( days ) ) ; ret . append ( " day" ) ; if ( days > 1 ) ret . append ( "s" ) ; } long hours = millis / 3600000L ; millis = millis - ( hours * 3600000L ) ; if ( hours > 0 ) { if ( ret . length ( ) > 0 ) ret . append ( " " ) ; ret . append ( Long . toString ( hours ) ) ; ret . append ( " hour" ) ; if ( hours > 1 ) ret . append ( "s" ) ; } long minutes = millis / 60000L ; millis = millis - ( minutes * 60000L ) ; if ( minutes > 0 ) { if ( ret . length ( ) > 0 ) ret . append ( " " ) ; ret . append ( Long . toString ( minutes ) ) ; ret . append ( " minute" ) ; if ( minutes > 1 ) ret . append ( "s" ) ; } long seconds = millis / 1000L ; if ( seconds > 0 ) { if ( ret . length ( ) > 0 ) ret . append ( " " ) ; ret . append ( Long . toString ( seconds ) ) ; ret . append ( " second" ) ; if ( seconds > 1 ) ret . append ( "s" ) ; } return ret . toString ( ) ; }
Returns the given time formatted as a number of days hours and minutes .
351
14
11,407
public ClassDocImpl loadClass ( String name ) { try { ClassSymbol c = reader . loadClass ( names . fromString ( name ) ) ; return getClassDoc ( c ) ; } catch ( CompletionFailure ex ) { chk . completionError ( null , ex ) ; return null ; } }
Load ClassDoc by qualified name .
65
7
11,408
protected void buildProfileIndexFile ( String title , boolean includeScript ) throws IOException { String windowOverview = configuration . getText ( title ) ; Content body = getBody ( includeScript , getWindowTitle ( windowOverview ) ) ; addNavigationBarHeader ( body ) ; addOverviewHeader ( body ) ; addIndex ( body ) ; addOverview ( body ) ; addNavigationBarFooter ( body ) ; printHtmlDocument ( configuration . metakeywords . getOverviewMetaKeywords ( title , configuration . doctitle ) , includeScript , body ) ; }
Generate and prints the contents in the profile index file . Call appropriate methods from the sub - class in order to generate Frame or Non Frame format .
119
30
11,409
protected void buildProfilePackagesIndexFile ( String title , boolean includeScript , String profileName ) throws IOException { String windowOverview = configuration . getText ( title ) ; Content body = getBody ( includeScript , getWindowTitle ( windowOverview ) ) ; addNavigationBarHeader ( body ) ; addOverviewHeader ( body ) ; addProfilePackagesIndex ( body , profileName ) ; addOverview ( body ) ; addNavigationBarFooter ( body ) ; printHtmlDocument ( configuration . metakeywords . getOverviewMetaKeywords ( title , configuration . doctitle ) , includeScript , body ) ; }
Generate and prints the contents in the profile packages index file . Call appropriate methods from the sub - class in order to generate Frame or Non Frame format .
131
31
11,410
protected void addIndex ( Content body ) { addIndexContents ( profiles , "doclet.Profile_Summary" , configuration . getText ( "doclet.Member_Table_Summary" , configuration . getText ( "doclet.Profile_Summary" ) , configuration . getText ( "doclet.profiles" ) ) , body ) ; }
Adds the frame or non - frame profile index to the documentation tree .
74
14
11,411
protected void addProfilePackagesIndex ( Content body , String profileName ) { addProfilePackagesIndexContents ( profiles , "doclet.Profile_Summary" , configuration . getText ( "doclet.Member_Table_Summary" , configuration . getText ( "doclet.Profile_Summary" ) , configuration . getText ( "doclet.profiles" ) ) , body , profileName ) ; }
Adds the frame or non - frame profile packages index to the documentation tree .
87
15
11,412
protected void addIndexContents ( Profiles profiles , String text , String tableSummary , Content body ) { if ( profiles . getProfileCount ( ) > 0 ) { HtmlTree div = new HtmlTree ( HtmlTag . DIV ) ; div . addStyle ( HtmlStyle . indexHeader ) ; addAllClassesLink ( div ) ; addAllPackagesLink ( div ) ; body . addContent ( div ) ; addProfilesList ( profiles , text , tableSummary , body ) ; } }
Adds profile index contents . Call appropriate methods from the sub - classes . Adds it to the body HtmlTree
108
22
11,413
protected void addProfilePackagesIndexContents ( Profiles profiles , String text , String tableSummary , Content body , String profileName ) { HtmlTree div = new HtmlTree ( HtmlTag . DIV ) ; div . addStyle ( HtmlStyle . indexHeader ) ; addAllClassesLink ( div ) ; addAllPackagesLink ( div ) ; addAllProfilesLink ( div ) ; body . addContent ( div ) ; addProfilePackagesList ( profiles , text , tableSummary , body , profileName ) ; }
Adds profile packages index contents . Call appropriate methods from the sub - classes . Adds it to the body HtmlTree
114
23
11,414
public Iterable < DContact > queryByBirthday ( Object parent , java . util . Date birthday ) { return queryByField ( parent , DContactMapper . Field . BIRTHDAY . getFieldName ( ) , birthday ) ; }
query - by method for field birthday
52
7
11,415
public Iterable < DContact > queryByCompanyName ( Object parent , java . lang . String companyName ) { return queryByField ( parent , DContactMapper . Field . COMPANYNAME . getFieldName ( ) , companyName ) ; }
query - by method for field companyName
53
8
11,416
public Iterable < DContact > queryByEmail ( Object parent , java . lang . String email ) { return queryByField ( parent , DContactMapper . Field . EMAIL . getFieldName ( ) , email ) ; }
query - by method for field email
50
7
11,417
public Iterable < DContact > queryByFacebook ( Object parent , java . lang . String facebook ) { return queryByField ( parent , DContactMapper . Field . FACEBOOK . getFieldName ( ) , facebook ) ; }
query - by method for field facebook
49
7
11,418
public Iterable < DContact > queryByHomePhone ( Object parent , java . lang . String homePhone ) { return queryByField ( parent , DContactMapper . Field . HOMEPHONE . getFieldName ( ) , homePhone ) ; }
query - by method for field homePhone
55
8
11,419
public Iterable < DContact > queryByLatitude ( Object parent , java . lang . Float latitude ) { return queryByField ( parent , DContactMapper . Field . LATITUDE . getFieldName ( ) , latitude ) ; }
query - by method for field latitude
52
7
11,420
public Iterable < DContact > queryByLinkedIn ( Object parent , java . lang . String linkedIn ) { return queryByField ( parent , DContactMapper . Field . LINKEDIN . getFieldName ( ) , linkedIn ) ; }
query - by method for field linkedIn
52
8
11,421
public Iterable < DContact > queryByLongitude ( Object parent , java . lang . Float longitude ) { return queryByField ( parent , DContactMapper . Field . LONGITUDE . getFieldName ( ) , longitude ) ; }
query - by method for field longitude
54
8
11,422
public Iterable < DContact > queryByMobilePhone ( Object parent , java . lang . String mobilePhone ) { return queryByField ( parent , DContactMapper . Field . MOBILEPHONE . getFieldName ( ) , mobilePhone ) ; }
query - by method for field mobilePhone
55
8
11,423
public Iterable < DContact > queryByOtherEmail ( Object parent , java . lang . String otherEmail ) { return queryByField ( parent , DContactMapper . Field . OTHEREMAIL . getFieldName ( ) , otherEmail ) ; }
query - by method for field otherEmail
53
8
11,424
public Iterable < DContact > queryByOtherPhone ( Object parent , java . lang . String otherPhone ) { return queryByField ( parent , DContactMapper . Field . OTHERPHONE . getFieldName ( ) , otherPhone ) ; }
query - by method for field otherPhone
53
8
11,425
public Iterable < DContact > queryByPrimaryCustomIndex ( Object parent , java . lang . String primaryCustomIndex ) { return queryByField ( parent , DContactMapper . Field . PRIMARYCUSTOMINDEX . getFieldName ( ) , primaryCustomIndex ) ; }
query - by method for field primaryCustomIndex
61
9
11,426
public Iterable < DContact > queryBySecondaryCustomIndex ( Object parent , java . lang . String secondaryCustomIndex ) { return queryByField ( parent , DContactMapper . Field . SECONDARYCUSTOMINDEX . getFieldName ( ) , secondaryCustomIndex ) ; }
query - by method for field secondaryCustomIndex
62
9
11,427
public Iterable < DContact > queryByTags ( Object parent , java . lang . Object tags ) { return queryByField ( parent , DContactMapper . Field . TAGS . getFieldName ( ) , tags ) ; }
query - by method for field tags
49
7
11,428
public Iterable < DContact > queryByTwitter ( Object parent , java . lang . String twitter ) { return queryByField ( parent , DContactMapper . Field . TWITTER . getFieldName ( ) , twitter ) ; }
query - by method for field twitter
50
7
11,429
public DContact findByUniqueTag ( Object parent , java . lang . String uniqueTag ) { return queryUniqueByField ( parent , DContactMapper . Field . UNIQUETAG . getFieldName ( ) , uniqueTag ) ; }
find - by method for unique field uniqueTag
52
9
11,430
public Iterable < DContact > queryByWebPage ( Object parent , java . lang . String webPage ) { return queryByField ( parent , DContactMapper . Field . WEBPAGE . getFieldName ( ) , webPage ) ; }
query - by method for field webPage
54
8
11,431
public Iterable < DContact > queryByWorkPhone ( Object parent , java . lang . String workPhone ) { return queryByField ( parent , DContactMapper . Field . WORKPHONE . getFieldName ( ) , workPhone ) ; }
query - by method for field workPhone
53
8
11,432
public static int string2int ( String s , int radix ) throws NumberFormatException { if ( radix == 10 ) { return Integer . parseInt ( s , radix ) ; } else { char [ ] cs = s . toCharArray ( ) ; int limit = Integer . MAX_VALUE / ( radix / 2 ) ; int n = 0 ; for ( int i = 0 ; i < cs . length ; i ++ ) { int d = Character . digit ( cs [ i ] , radix ) ; if ( n < 0 || n > limit || n * radix > Integer . MAX_VALUE - d ) throw new NumberFormatException ( ) ; n = n * radix + d ; } return n ; } }
Convert string to integer .
155
6
11,433
public static long string2long ( String s , int radix ) throws NumberFormatException { if ( radix == 10 ) { return Long . parseLong ( s , radix ) ; } else { char [ ] cs = s . toCharArray ( ) ; long limit = Long . MAX_VALUE / ( radix / 2 ) ; long n = 0 ; for ( int i = 0 ; i < cs . length ; i ++ ) { int d = Character . digit ( cs [ i ] , radix ) ; if ( n < 0 || n > limit || n * radix > Long . MAX_VALUE - d ) throw new NumberFormatException ( ) ; n = n * radix + d ; } return n ; } }
Convert string to long integer .
155
7
11,434
public static String getResponseMaybe ( SocketManager socketManager , String message ) throws IOException { try { return socketManager . sendAndWait ( message ) ; } catch ( ResponseTimeoutException e ) { /* * If the timeout was hit in the previous send-and-wait, then the * socket manager will be expecting the next message that arrives to * be an orphan connected to this command that didn't come back in * time. To get things back in sync, a throwaway command (help) will * be sent. */ socketManager . send ( "help" ) ; return "" ; } }
Send a message and wait for a short period for a response . If no response comes in that time it is assumed that there will be no response from the frontend . This is useful for commands that get a response when there is data available and silence otherwise .
123
52
11,435
public static String parsePropertyName ( Method method ) { String name = method . getName ( ) ; int i = 0 ; if ( name . startsWith ( "get" ) || name . startsWith ( "set" ) ) { i = 3 ; } else if ( name . startsWith ( "is" ) ) { i = 2 ; } return Character . toLowerCase ( name . charAt ( i ) ) + name . substring ( i + 1 ) ; }
Parses the method name to return a property name if it is a getter or a setter .
100
22
11,436
public static < E > OptionalFunction < Selection < Method > , E > invoke ( Object ... args ) { return OptionalFunction . of ( selection -> factory . createInvoker ( selection . result ( ) ) . on ( selection . target ( ) ) . withArgs ( args ) ) ; }
Returns a function that invokes a selected method .
60
10
11,437
public static < E > OptionalFunction < Selection < Constructor < ? > > , E > instantiate ( Object ... args ) { return OptionalFunction . of ( selection -> factory . createInvoker ( selection . result ( ) ) . withArgs ( args ) ) ; }
Returns a function that invokes a selected constructor .
56
10
11,438
public static < E > OptionalFunction < Selection < Field > , E > getValue ( ) { return OptionalFunction . of ( selection -> factory . createHandler ( selection . result ( ) ) . on ( selection . target ( ) ) . getValue ( ) ) ; }
Returns a function that gets the value of a selected field .
56
12
11,439
public static Consumer < Selection < Field > > setValue ( Object newValue ) { return selection -> factory . createHandler ( selection . result ( ) ) . on ( selection . target ( ) ) . setValue ( newValue ) ; }
Returns a consumer that sets the value of a selected field .
49
12
11,440
public Object users ( ) { return new ArrayList < Map < String , Object > > ( ) { { add ( new HashMap < String , Object > ( ) { { put ( "username" , "testUser1" ) ; put ( "groups" , Arrays . asList ( "group1" ) ) ; put ( "password" , "thisMechWillChange" ) ; } } ) ; add ( new HashMap < String , Object > ( ) { { put ( "username" , "testUser2" ) ; put ( "groups" , Arrays . asList ( "group2" ) ) ; put ( "password" , "thisMechWillChange" ) ; } } ) ; } } ; }
Avoiding adding extra dependencies so using hash map .
154
10
11,441
@ Override public boolean nextKeyValue ( ) throws IOException , InterruptedException { if ( ! deserializer . hasNextEvent ( ) ) { return false ; } else { value = deserializer . getNextEvent ( ) ; key = value . getEventDateTime ( ) ; return true ; } }
Read the next key value pair .
66
7
11,442
@ Override public float getProgress ( ) throws IOException , InterruptedException { if ( start == end ) { return 0.0f ; } else { return Math . min ( 1.0f , ( pos - start ) / ( float ) ( end - start ) ) ; } }
The current progress of the record reader through its data .
61
11
11,443
public void addAttr ( HtmlAttr attrName , String attrValue ) { if ( attrs . isEmpty ( ) ) attrs = new LinkedHashMap < HtmlAttr , String > ( 3 ) ; attrs . put ( nullCheck ( attrName ) , escapeHtmlChars ( attrValue ) ) ; }
Adds an attribute for the HTML tag .
76
8
11,444
public void addContent ( Content tagContent ) { if ( tagContent instanceof ContentBuilder ) { for ( Content content : ( ( ContentBuilder ) tagContent ) . contents ) { addContent ( content ) ; } } else if ( tagContent == HtmlTree . EMPTY || tagContent . isValid ( ) ) { if ( content . isEmpty ( ) ) content = new ArrayList < Content > ( ) ; content . add ( tagContent ) ; } }
Adds content for the HTML tag .
97
7
11,445
public static HtmlTree A_NAME ( String name , Content body ) { HtmlTree htmltree = HtmlTree . A_NAME ( name ) ; htmltree . addContent ( nullCheck ( body ) ) ; return htmltree ; }
Generates an HTML anchor tag with name attribute and content .
57
12
11,446
public static HtmlTree A_NAME ( String name ) { HtmlTree htmltree = new HtmlTree ( HtmlTag . A ) ; htmltree . addAttr ( HtmlAttr . NAME , nullCheck ( name ) ) ; return htmltree ; }
Generates an HTML anchor tag with name attribute .
63
10
11,447
public static HtmlTree FRAME ( String src , String name , String title , String scrolling ) { HtmlTree htmltree = new HtmlTree ( HtmlTag . FRAME ) ; htmltree . addAttr ( HtmlAttr . SRC , nullCheck ( src ) ) ; htmltree . addAttr ( HtmlAttr . NAME , nullCheck ( name ) ) ; htmltree . addAttr ( HtmlAttr . TITLE , nullCheck ( title ) ) ; if ( scrolling != null ) htmltree . addAttr ( HtmlAttr . SCROLLING , scrolling ) ; return htmltree ; }
Generates a FRAME tag .
148
7
11,448
public static HtmlTree FRAME ( String src , String name , String title ) { return FRAME ( src , name , title , null ) ; }
Generates a Frame tag .
32
6
11,449
public static HtmlTree FRAMESET ( String cols , String rows , String title , String onload ) { HtmlTree htmltree = new HtmlTree ( HtmlTag . FRAMESET ) ; if ( cols != null ) htmltree . addAttr ( HtmlAttr . COLS , cols ) ; if ( rows != null ) htmltree . addAttr ( HtmlAttr . ROWS , rows ) ; htmltree . addAttr ( HtmlAttr . TITLE , nullCheck ( title ) ) ; htmltree . addAttr ( HtmlAttr . ONLOAD , nullCheck ( onload ) ) ; return htmltree ; }
Generates a FRAMESET tag .
156
8
11,450
public static HtmlTree TABLE ( HtmlStyle styleClass , int border , int cellPadding , int cellSpacing , String summary , Content body ) { HtmlTree htmltree = new HtmlTree ( HtmlTag . TABLE , nullCheck ( body ) ) ; if ( styleClass != null ) htmltree . addStyle ( styleClass ) ; htmltree . addAttr ( HtmlAttr . BORDER , Integer . toString ( border ) ) ; htmltree . addAttr ( HtmlAttr . CELLPADDING , Integer . toString ( cellPadding ) ) ; htmltree . addAttr ( HtmlAttr . CELLSPACING , Integer . toString ( cellSpacing ) ) ; htmltree . addAttr ( HtmlAttr . SUMMARY , nullCheck ( summary ) ) ; return htmltree ; }
Generates a Table tag with style class border cell padding cellspacing and summary attributes and some content .
199
21
11,451
public static String execute ( final boolean withResponse , final String ... command ) throws IOException { final List < String > commands = new ArrayList <> ( ) ; commands . add ( "bash" ) ; commands . add ( "-c" ) ; commands . addAll ( Arrays . asList ( command ) ) ; String response = "" ; final ProcessBuilder pb = new ProcessBuilder ( commands ) ; pb . redirectErrorStream ( true ) ; final Process shell = pb . start ( ) ; if ( withResponse ) { try ( InputStream shellIn = shell . getInputStream ( ) ) { response = toString ( shellIn ) ; } } return response ; }
Execute the given commands and return the result .
143
10
11,452
private static int checkResult ( int result ) { if ( exceptionsEnabled && result != cufftResult . CUFFT_SUCCESS ) { throw new CudaException ( cufftResult . stringFor ( result ) ) ; } return result ; }
If the given result is different to cufftResult . CUFFT_SUCCESS and exceptions have been enabled this method will throw a CudaException with an error message that corresponds to the given result code . Otherwise the given result is simply returned .
52
51
11,453
@ Override public Object invoke ( Object proxy , Method method , Object [ ] args ) throws Throwable { return connectionHandler . remoteInvocation ( proxy , method , args ) ; }
Delegates call to this proxy to it s ConnectionHandler
38
11
11,454
public static ImageReader getImageReader ( final Object sourceImage ) throws IOException { ImageInputStream imageInputStream = ImageIO . createImageInputStream ( sourceImage ) ; Iterator < ImageReader > imageReaders = ImageIO . getImageReaders ( imageInputStream ) ; ImageReader destinationImageReader = null ; if ( imageReaders . hasNext ( ) ) { destinationImageReader = imageReaders . next ( ) ; setImageReaderHaveInputStream ( destinationImageReader , imageInputStream ) ; } return destinationImageReader ; }
Get image reader from given source image .
114
8
11,455
public static ImageReader getImageReaderFromHttpImage ( final String sourceImageHttpURL ) throws IOException { InputStream inputStream = new URL ( sourceImageHttpURL ) . openConnection ( ) . getInputStream ( ) ; return getImageReader ( inputStream ) ; }
Get image reader from given web image .
57
8
11,456
public < T > T get ( Key < T > key ) { checkState ( ht ) ; Object o = ht . get ( key ) ; if ( o instanceof Factory < ? > ) { Factory < ? > fac = ( Factory < ? > ) o ; o = fac . make ( this ) ; if ( o instanceof Factory < ? > ) throw new AssertionError ( "T extends Context.Factory" ) ; Assert . check ( ht . get ( key ) == o ) ; } /* The following cast can't fail unless there was * cheating elsewhere, because of the invariant on ht. * Since we found a key of type Key<T>, the value must * be of type T. */ return Context . < T > uncheckedCast ( o ) ; }
Get the value for the key in this context .
167
10
11,457
protected void configure ( Properties p ) { _properties = p ; _host = ( String ) p . remove ( HOST ) ; if ( _host == null ) throw new NoSuchElementException ( HOST ) ; _path = ( String ) p . remove ( PATH ) ; if ( _path == null ) throw new NoSuchElementException ( PATH ) ; }
Configures the RemoteServiceChannel with given properties .
76
10
11,458
public < T > RemoteService . Response call ( long pause , Functor < T , String > reporter ) throws Exception { String message = null ; while ( true ) { RemoteService . Response response = _caller . call ( ) ; String news = response . params . get ( "message" ) ; if ( news == null ) { if ( _state != null && message != null ) { _state . param = null ; _state . markAttempt ( ) ; } return response ; } else { if ( ! news . equals ( message ) ) { if ( _state != null ) { if ( reporter != null ) reporter . invoke ( "Attempting " + _state . state + ": " + news ) ; _state . param = Progressive . State . clean ( news ) ; _state . markAttempt ( ) ; } else { if ( reporter != null ) reporter . invoke ( news ) ; } message = news ; } Thread . sleep ( pause < PAUSE_BETWEEN_RETRIES ? PAUSE_BETWEEN_RETRIES : pause ) ; } } }
Calls the remote service continuously until a final response is received reporting progress messages via the reporter .
230
19
11,459
public synchronized V invalidate ( K key ) { Singleton < V > singleton = _cache . get ( key ) ; if ( singleton != null ) { return singleton . clear ( ) ; } else { return null ; } }
Invalidates an entry in the cache . This operation does not constitute a cache replacement .
50
17
11,460
public List < Attribute . Compound > getRawAttributes ( ) { return ( metadata == null ) ? List . < Attribute . Compound > nil ( ) : metadata . getDeclarationAttributes ( ) ; }
An accessor method for the attributes of this symbol . Attributes of class symbols should be accessed through the accessor method to make sure that the class symbol is loaded .
45
33
11,461
public List < Attribute . TypeCompound > getRawTypeAttributes ( ) { return ( metadata == null ) ? List . < Attribute . TypeCompound > nil ( ) : metadata . getTypeAttributes ( ) ; }
An accessor method for the type attributes of this symbol . Attributes of class symbols should be accessed through the accessor method to make sure that the class symbol is loaded .
47
34
11,462
public ClassSymbol enclClass ( ) { Symbol c = this ; while ( c != null && ( ( c . kind & TYP ) == 0 || ! c . type . hasTag ( CLASS ) ) ) { c = c . owner ; } return ( ClassSymbol ) c ; }
The closest enclosing class of this symbol s declaration .
61
11
11,463
public static int floor ( int n , int m ) { return n >= 0 ? ( n / m ) * m : ( ( n - m + 1 ) / m ) * m ; }
Rounds n down to the nearest multiple of m
40
10
11,464
public static int ceiling ( int n , int m ) { return n >= 0 ? ( ( n + m - 1 ) / m ) * m : ( n / m ) * m ; }
Rounds n up to the nearest multiple of m
40
10
11,465
public void add ( Collection < PluginComponent > components ) { for ( PluginComponent component : components ) this . components . put ( component . getId ( ) , component ) ; }
Adds the plugin component list to the plugin components for the account .
37
13
11,466
private void checkIndex ( ) throws IOException { boolean isUpToDate = true ; if ( ! isUpToDate ( ) ) { closeFile ( ) ; isUpToDate = false ; } if ( zipRandomFile != null || isUpToDate ) { lastReferenceTimeStamp = System . currentTimeMillis ( ) ; return ; } hasPopulatedData = true ; if ( readIndex ( ) ) { lastReferenceTimeStamp = System . currentTimeMillis ( ) ; return ; } directories = Collections . < RelativeDirectory , DirectoryEntry > emptyMap ( ) ; allDirs = Collections . < RelativeDirectory > emptySet ( ) ; try { openFile ( ) ; long totalLength = zipRandomFile . length ( ) ; ZipDirectory directory = new ZipDirectory ( zipRandomFile , 0L , totalLength , this ) ; directory . buildIndex ( ) ; } finally { if ( zipRandomFile != null ) { closeFile ( ) ; } } lastReferenceTimeStamp = System . currentTimeMillis ( ) ; }
Here we need to make sure that the ZipFileIndex is valid . Check the timestamp of the file and if its the same as the one at the time the index was build we don t need to reopen anything .
220
43
11,467
synchronized Entry getZipIndexEntry ( RelativePath path ) { try { checkIndex ( ) ; DirectoryEntry de = directories . get ( path . dirname ( ) ) ; String lookFor = path . basename ( ) ; return ( de == null ) ? null : de . getEntry ( lookFor ) ; } catch ( IOException e ) { return null ; } }
Returns the ZipFileIndexEntry for a path if there is one .
79
14
11,468
public synchronized com . sun . tools . javac . util . List < String > getFiles ( RelativeDirectory path ) { try { checkIndex ( ) ; DirectoryEntry de = directories . get ( path ) ; com . sun . tools . javac . util . List < String > ret = de == null ? null : de . getFiles ( ) ; if ( ret == null ) { return com . sun . tools . javac . util . List . < String > nil ( ) ; } return ret ; } catch ( IOException e ) { return com . sun . tools . javac . util . List . < String > nil ( ) ; } }
Returns a javac List of filenames within a directory in the ZipFileIndex .
140
19
11,469
public synchronized boolean contains ( RelativePath path ) { try { checkIndex ( ) ; return getZipIndexEntry ( path ) != null ; } catch ( IOException e ) { return false ; } }
Tests if a specific path exists in the zip . This method will return true for file entries and directories .
41
22
11,470
public static List < Event > fromFile ( final File file ) throws IOException , ClassNotFoundException { return fromInputStream ( new FileInputStream ( file ) ) ; }
Given a file written by the serialization - writer library extract all events . This assumes the file was written using ObjectOutputStream .
37
26
11,471
public boolean add ( String field , List < RDFNode > result ) { this . result . put ( field , result ) ; return true ; }
Add a new result
31
4
11,472
public boolean add ( String field , RDFNode result ) { if ( ! this . result . containsKey ( field ) ) { this . result . put ( field , new ArrayList < RDFNode > ( ) ) ; } this . result . get ( field ) . add ( result ) ; return true ; }
Add a single result
66
4
11,473
public Manifest getManifest ( MavenProject project , ManifestConfiguration config ) throws ManifestException , DependencyResolutionRequiredException { // Added basic entries Manifest m = new Manifest ( ) ; Manifest . Attribute buildAttr = new Manifest . Attribute ( "Built-By" , System . getProperty ( "user.name" ) ) ; m . addConfiguredAttribute ( buildAttr ) ; Manifest . Attribute createdAttr = new Manifest . Attribute ( "Created-By" , "Apache Maven" ) ; m . addConfiguredAttribute ( createdAttr ) ; if ( config . getPackageName ( ) != null ) { Manifest . Attribute packageAttr = new Manifest . Attribute ( "Package" , config . getPackageName ( ) ) ; m . addConfiguredAttribute ( packageAttr ) ; } Manifest . Attribute buildJdkAttr = new Manifest . Attribute ( "Build-Jdk" , System . getProperty ( "java.version" ) ) ; m . addConfiguredAttribute ( buildJdkAttr ) ; if ( config . isAddClasspath ( ) ) { StringBuffer classpath = new StringBuffer ( ) ; List artifacts = project . getRuntimeClasspathElements ( ) ; String classpathPrefix = config . getClasspathPrefix ( ) ; for ( Iterator iter = artifacts . iterator ( ) ; iter . hasNext ( ) ; ) { File f = new File ( ( String ) iter . next ( ) ) ; if ( f . isFile ( ) ) { if ( classpath . length ( ) > 0 ) { classpath . append ( " " ) ; } classpath . append ( classpathPrefix ) ; classpath . append ( f . getName ( ) ) ; } } if ( classpath . length ( ) > 0 ) { Manifest . Attribute classpathAttr = new Manifest . Attribute ( "Class-Path" , classpath . toString ( ) ) ; m . addConfiguredAttribute ( classpathAttr ) ; } } String mainClass = config . getMainClass ( ) ; if ( mainClass != null && ! "" . equals ( mainClass ) ) { Manifest . Attribute mainClassAttr = new Manifest . Attribute ( "Main-Class" , mainClass ) ; m . addConfiguredAttribute ( mainClassAttr ) ; } return m ; }
Return a pre - configured manifest
503
6
11,474
@ SuppressWarnings ( "unchecked" ) public Map marshal ( ) { HashMap map = new HashMap ( ) ; map . put ( "jsonrpc" , "2.0" ) ; if ( id != null ) map . put ( "id" , id ) ; if ( error != null ) map . put ( "error" , error . toMap ( ) ) ; else map . put ( "result" , result ) ; return map ; }
Marshals this response to a Map that can be serialized
101
12
11,475
public static void scan ( ServletContext c , Set < String > jars , Functor < Void , ServiceModule > collector , Logger logger ) { for ( String j : jars ) { logger . config ( "... " + j ) ; try ( JarInputStream jis = new JarInputStream ( j . startsWith ( "/" ) ? c . getResourceAsStream ( j ) : new URL ( j ) . openStream ( ) ) ) { Attributes attrs = jis . getManifest ( ) . getMainAttributes ( ) ; String d = attrs . getValue ( DOMAIN_NAME ) , n = attrs . getValue ( MODULE_NAME ) , s = attrs . getValue ( SIMPLE_NAME ) ; if ( d != null && n != null && s != null ) { collector . invoke ( new ServiceModule ( d , n , s , attrs . getValue ( MODULE_BASE ) , j ) ) ; } } catch ( IOException x ) { logger . log ( Level . WARNING , "Unexpected error during jar inspection, ignored" , x ) ; } catch ( Exception x ) { logger . config ( "Unknown resource ignored" ) ; } } }
Scans a collection of jar files passing recognized Xillium application modules as ServiceModule objects to a collector .
252
22
11,476
public void writeToJsonGenerator ( final JsonGenerator gen ) throws IOException { // writes '{eventName:<name>,payload:{<data>}}' --it's kind of silly but ultimately inconsequential to nest them like this. gen . writeStartObject ( ) ; gen . writeStringField ( "eventName" , eventName ) ; gen . writeFieldName ( "payload" ) ; /* Note: output format used depends completely on generator we are being passed * and NOT on which mapper we use -- mappers are format independent and rely * on underlying JsonParser/JsonGenerator for low-level handling. */ getObjectMapper ( ) . writeTree ( gen , root ) ; gen . writeEndObject ( ) ; }
having to know all the events ahead of time .
163
10
11,477
public synchronized boolean waitForValidValues ( ) throws IOException , FileNotFoundException { for ( int tries = 0 ; tries < 50 ; tries ++ ) { lock ( ) ; getValues ( ) ; unlock ( ) ; if ( containsPortInfo ) { Log . debug ( "Found valid values in port file after waiting " + ( tries * 100 ) + "ms" ) ; return true ; } try { Thread . sleep ( 100 ) ; } catch ( InterruptedException e ) { } } Log . debug ( "Gave up waiting for valid values in port file" ) ; return false ; }
Wait for the port file to contain values that look valid . Return true if a - ok false if the valid values did not materialize within 5 seconds .
125
31
11,478
public synchronized boolean stillMyValues ( ) throws IOException , FileNotFoundException { for ( ; ; ) { try { lock ( ) ; getValues ( ) ; unlock ( ) ; if ( containsPortInfo ) { if ( serverPort == myServerPort && serverCookie == myServerCookie ) { // Everything is ok. return true ; } // Someone has overwritten the port file. // Probably another javac server, lets quit. return false ; } // Something else is wrong with the portfile. Lets quit. return false ; } catch ( FileLockInterruptionException e ) { continue ; } catch ( ClosedChannelException e ) { // The channel has been closed since sjavac is exiting. return false ; } } }
Check if the portfile still contains my values assuming that I am the server .
155
16
11,479
@ SuppressWarnings ( "unchecked" ) public static < T > T instantiateDefault ( Class < T > someClass ) { if ( someClass . isArray ( ) ) { return ( T ) Array . newInstance ( someClass . getComponentType ( ) , 0 ) ; } else { if ( boolean . class . equals ( someClass ) || Boolean . class . equals ( someClass ) ) { return ( T ) Boolean . FALSE ; } else if ( int . class . equals ( someClass ) || Integer . class . equals ( someClass ) ) { return ( T ) Integer . valueOf ( 0 ) ; } else if ( long . class . equals ( someClass ) || Long . class . equals ( someClass ) ) { return ( T ) Long . valueOf ( 0L ) ; } else if ( short . class . equals ( someClass ) || Short . class . equals ( someClass ) ) { return ( T ) Short . valueOf ( ( short ) 0 ) ; } else if ( float . class . equals ( someClass ) || Float . class . equals ( someClass ) ) { return ( T ) Float . valueOf ( 0f ) ; } else if ( double . class . equals ( someClass ) || Double . class . equals ( someClass ) ) { return ( T ) Double . valueOf ( 0d ) ; } else if ( byte . class . equals ( someClass ) || Byte . class . equals ( someClass ) ) { return ( T ) Byte . valueOf ( ( byte ) 0 ) ; } else if ( char . class . equals ( someClass ) || Character . class . equals ( someClass ) ) { return ( T ) Character . valueOf ( ( char ) 0 ) ; } else { try { Constructor < T > defaultConstructor = someClass . getDeclaredConstructor ( ) ; defaultConstructor . setAccessible ( true ) ; return defaultConstructor . newInstance ( ) ; } catch ( Exception e ) { throw ShedException . wrap ( e , ShedErrorCode . UNABLE_TO_INSTANTIATE_CLASS ) . put ( "class" , someClass ) ; } } } }
Instantiate a class by invoking its default constructor . If the specified class denotes an array an empty array of the correct component type is created . If the specified class denotes a primitive the primitive is created with its default value .
460
44
11,480
@ SuppressWarnings ( "unchecked" ) public static < T > Optional < Class < T > > optional ( String dependency ) { try { return Optional . of ( ( Class < T > ) Class . forName ( dependency ) ) ; } catch ( ClassNotFoundException | NoClassDefFoundError e ) { return Optional . empty ( ) ; } }
Checks if a class exists in the classpath .
77
11
11,481
@ Transactional ( readOnly = true ) public List < Permission > loadRolesAndPermissions ( ) throws Exception { return _persistence . getResults ( _qRoleAuthorizations , null ) ; }
Loads all role permissions into memory .
45
8
11,482
public static AbstractConfiguration [ ] execute ( String applicationNamespace , ClassLoader loader , Logger log ) throws Exception { String packageName = "de.jiac.micro.internal.latebind" ; MicroJIACToolContext context = new MicroJIACToolContext ( loader ) ; ConfigurationGenerator generator = new ConfigurationGenerator ( context . getLoader ( ) , log ) ; MergedConfiguration conf = context . createResolver ( ) . resolveAndMerge ( applicationNamespace ) ; CheckerResult checkerResult = context . createChecker ( ) . flattenAndCheck ( conf ) ; // first print the warnings for ( String warning : checkerResult . warnings ) { log . warn ( warning ) ; } // print errors for ( String error : checkerResult . errors ) { log . error ( error ) ; } if ( checkerResult . hasErrors ( ) ) { throw new GeneratorException ( "checker has found errors" ) ; } return generator . generate ( packageName , conf ) ; }
Return the array of generated node configurations .
215
8
11,483
public static void generate ( ConfigurationImpl configuration , String profileName ) { ProfilePackageIndexFrameWriter profpackgen ; DocPath filename = DocPaths . profileFrame ( profileName ) ; try { profpackgen = new ProfilePackageIndexFrameWriter ( configuration , filename ) ; profpackgen . buildProfilePackagesIndexFile ( "doclet.Window_Overview" , false , profileName ) ; profpackgen . close ( ) ; } catch ( IOException exc ) { configuration . standardmessage . error ( "doclet.exception_encountered" , exc . toString ( ) , filename ) ; throw new DocletAbortException ( exc ) ; } }
Generate the profile package index file .
140
8
11,484
static String getTypeString ( DocEnv env , Type t , boolean full ) { // TODO: should annotations be included here? if ( t . isAnnotated ( ) ) { t = t . unannotatedType ( ) ; } switch ( t . getTag ( ) ) { case ARRAY : StringBuilder s = new StringBuilder ( ) ; while ( t . hasTag ( ARRAY ) ) { s . append ( "[]" ) ; t = env . types . elemtype ( t ) ; } s . insert ( 0 , getTypeString ( env , t , full ) ) ; return s . toString ( ) ; case CLASS : return ParameterizedTypeImpl . parameterizedTypeToString ( env , ( ClassType ) t , full ) ; case WILDCARD : Type . WildcardType a = ( Type . WildcardType ) t ; return WildcardTypeImpl . wildcardTypeToString ( env , a , full ) ; default : return t . tsym . getQualifiedName ( ) . toString ( ) ; } }
Return the string representation of a type use . Bounds of type variables are not included ; bounds of wildcard types are . Class names are qualified if full is true .
226
34
11,485
public static String getWebProjectPath ( Object currentObject ) { Class < ? extends Object > class1 = currentObject . getClass ( ) ; ClassLoader classLoader = class1 . getClassLoader ( ) ; URL resource = classLoader . getResource ( "/" ) ; String path = resource . getPath ( ) ; int webRootIndex = StringUtils . indexOfIgnoreCase ( path , "WEB-INF" ) ; if ( path . indexOf ( ":/" ) > 0 ) { return path . substring ( 1 , webRootIndex ) ; } else { return path . substring ( 0 , webRootIndex ) ; } }
The parameter currentObject recommend to user this because of can not be a object which build by manually with new ;
139
22
11,486
public void flattenPackagesSourcesAndArtifacts ( Map < String , Module > m ) { modules = m ; // Extract all the found packages. for ( Module i : modules . values ( ) ) { for ( Map . Entry < String , Package > j : i . packages ( ) . entrySet ( ) ) { Package p = packages . get ( j . getKey ( ) ) ; // Check that no two different packages are stored under same name. assert ( p == null || p == j . getValue ( ) ) ; if ( p == null ) { p = j . getValue ( ) ; packages . put ( j . getKey ( ) , j . getValue ( ) ) ; } for ( Map . Entry < String , Source > k : p . sources ( ) . entrySet ( ) ) { Source s = sources . get ( k . getKey ( ) ) ; // Check that no two different sources are stored under same name. assert ( s == null || s == k . getValue ( ) ) ; if ( s == null ) { s = k . getValue ( ) ; sources . put ( k . getKey ( ) , k . getValue ( ) ) ; } } for ( Map . Entry < String , File > g : p . artifacts ( ) . entrySet ( ) ) { File f = artifacts . get ( g . getKey ( ) ) ; // Check that no two artifacts are stored under the same file. assert ( f == null || f == g . getValue ( ) ) ; if ( f == null ) { f = g . getValue ( ) ; artifacts . put ( g . getKey ( ) , g . getValue ( ) ) ; } } } } }
Store references to all packages sources and artifacts for all modules into the build state . I . e . flatten the module tree structure into global maps stored in the BuildState for easy access .
360
38
11,487
public void checkInternalState ( String msg , boolean linkedOnly , Map < String , Source > srcs ) { boolean baad = false ; Map < String , Source > original = new HashMap < String , Source > ( ) ; Map < String , Source > calculated = new HashMap < String , Source > ( ) ; for ( String s : sources . keySet ( ) ) { Source ss = sources . get ( s ) ; if ( ss . isLinkedOnly ( ) == linkedOnly ) { calculated . put ( s , ss ) ; } } for ( String s : srcs . keySet ( ) ) { Source ss = srcs . get ( s ) ; if ( ss . isLinkedOnly ( ) == linkedOnly ) { original . put ( s , ss ) ; } } if ( original . size ( ) != calculated . size ( ) ) { Log . error ( "INTERNAL ERROR " + msg + " original and calculated are not the same size!" ) ; baad = true ; } if ( ! original . keySet ( ) . equals ( calculated . keySet ( ) ) ) { Log . error ( "INTERNAL ERROR " + msg + " original and calculated do not have the same domain!" ) ; baad = true ; } if ( ! baad ) { for ( String s : original . keySet ( ) ) { Source s1 = original . get ( s ) ; Source s2 = calculated . get ( s ) ; if ( s1 == null || s2 == null || ! s1 . equals ( s2 ) ) { Log . error ( "INTERNAL ERROR " + msg + " original and calculated have differing elements for " + s ) ; } baad = true ; } } if ( baad ) { for ( String s : original . keySet ( ) ) { Source ss = original . get ( s ) ; Source sss = calculated . get ( s ) ; if ( sss == null ) { Log . error ( "The file " + s + " does not exist in calculated tree of sources." ) ; } } for ( String s : calculated . keySet ( ) ) { Source ss = calculated . get ( s ) ; Source sss = original . get ( s ) ; if ( sss == null ) { Log . error ( "The file " + s + " does not exist in original set of found sources." ) ; } } } }
Verify that the setModules method above did the right thing when running through the module - > package - > source structure .
508
26
11,488
public RepositoryAdmin getRepositoryAdmin ( BundleContext context , ObrClassFinderService autoStartNotify ) throws InvalidSyntaxException { RepositoryAdmin admin = null ; ServiceReference [ ] ref = context . getServiceReferences ( RepositoryAdmin . class . getName ( ) , null ) ; if ( ( ref != null ) && ( ref . length > 0 ) ) admin = ( RepositoryAdmin ) context . getService ( ref [ 0 ] ) ; if ( admin == null ) if ( autoStartNotify != null ) if ( waitingForRepositoryAdmin == false ) { // Wait until the repository service is up until I start servicing clients context . addServiceListener ( new RepositoryAdminServiceListener ( autoStartNotify , context ) , "(" + Constants . OBJECTCLASS + "=" + RepositoryAdmin . class . getName ( ) + ")" ) ; waitingForRepositoryAdmin = true ; } return admin ; }
Get the repository admin service .
201
6
11,489
public void addBootstrapRepository ( RepositoryAdmin repositoryAdmin , BundleContext context ) { if ( repositoryAdmin == null ) return ; String repository = context . getProperty ( "jbundle.repository.url" ) ; if ( repository != null ) if ( repository . length ( ) > 0 ) this . addRepository ( repositoryAdmin , repository ) ; //repository = "file:" + System.getProperty("user.home") + File.separator + ".m2" + File.separator + "full-repository.xml"; //this.addRepository(repositoryAdmin, repository); }
Add the standard obr repository so I can get the bundles that I need .
135
16
11,490
public void addRepository ( RepositoryAdmin repositoryAdmin , String repository ) { try { if ( repository != null ) { boolean duplicate = false ; for ( Repository repo : repositoryAdmin . listRepositories ( ) ) { if ( repository . equalsIgnoreCase ( repo . getURI ( ) ) ) duplicate = true ; } if ( ! duplicate ) { Repository repo = repositoryAdmin . addRepository ( repository ) ; if ( repo == null ) repositoryAdmin . removeRepository ( repository ) ; // Ignore repos not found } } } catch ( Exception e ) { // Ignore exception e.printStackTrace(); } }
Add this repository to my available repositories .
131
8
11,491
public boolean startClassFinderActivator ( BundleContext context ) { if ( ClassFinderActivator . getClassFinder ( context , 0 ) == this ) return true ; // Already up! // If the repository is not up, but the bundle is deployed, this will find it String packageName = ClassFinderActivator . getPackageName ( ClassFinderActivator . class . getName ( ) , false ) ; Bundle bundle = this . findBundle ( null , context , packageName , null ) ; if ( bundle == null ) { Resource resource = ( Resource ) this . deployThisResource ( packageName , null , false ) ; // Get the bundle info from the repos bundle = this . findBundle ( resource , context , packageName , null ) ; } if ( bundle != null ) { if ( ( ( bundle . getState ( ) & Bundle . ACTIVE ) == 0 ) && ( ( bundle . getState ( ) & Bundle . STARTING ) == 0 ) ) { try { bundle . start ( ) ; } catch ( BundleException e ) { e . printStackTrace ( ) ; } } ClassFinderActivator . setClassFinder ( this ) ; return true ; // Success } return false ; // Error! Where is my bundle? }
Convenience method to start the class finder utility service . If admin service is not up yet this starts it .
268
24
11,492
public Object deployThisResource ( String packageName , String versionRange , boolean start ) { int options = 0 ; //?if (start) //? options = Resolver.START; if ( repositoryAdmin == null ) return null ; DataModelHelper helper = repositoryAdmin . getHelper ( ) ; if ( this . getResourceFromCache ( packageName ) != null ) return this . getResourceFromCache ( packageName ) ; String filter = "(package=" + packageName + ")" ; filter = ClassFinderActivator . addVersionFilter ( filter , versionRange ) ; Requirement requirement = helper . requirement ( "package" , filter ) ; Requirement [ ] requirements = { requirement } ; // repositoryAdmin Resource [ ] resources = repositoryAdmin . discoverResources ( requirements ) ; Resource bestResource = null ; if ( resources != null ) { Version bestVersion = null ; for ( Resource resource : resources ) { Version resourceVersion = resource . getVersion ( ) ; if ( ! isValidVersion ( resourceVersion , versionRange ) ) continue ; if ( ( bestVersion == null ) || ( resourceVersion . compareTo ( bestVersion ) >= 0 ) ) { bestVersion = resourceVersion ; // Use the highest version number bestResource = resource ; } } } if ( bestResource != null ) { this . deployResource ( bestResource , options ) ; Bundle bundle = this . findBundle ( bestResource , bundleContext , packageName , versionRange ) ; if ( start ) this . startBundle ( bundle ) ; this . addResourceToCache ( packageName , bestResource ) ; } return bestResource ; }
Find this resource in the repository then deploy and optionally start it .
334
13
11,493
public void deployResources ( Resource [ ] resources , int options ) { if ( resources != null ) { for ( Resource resource : resources ) { this . deployResource ( resource , options ) ; } } }
Deploy this list of resources .
42
6
11,494
public void deployResource ( Resource resource , int options ) { String name = resource . getSymbolicName ( ) + "/" + resource . getVersion ( ) ; Lock lock = this . getLock ( name ) ; try { boolean acquired = lock . tryLock ( ) ; if ( acquired ) { // Good, deploy this resource try { Resolver resolver = repositoryAdmin . resolver ( ) ; resolver . add ( resource ) ; int resolveAttempt = 5 ; while ( resolveAttempt -- > 0 ) { try { if ( resolver . resolve ( options ) ) { resolver . deploy ( options ) ; break ; // Resolve successful, exception thrown on previous instruction if not } else { Reason [ ] reqs = resolver . getUnsatisfiedRequirements ( ) ; for ( int i = 0 ; i < reqs . length ; i ++ ) { ClassServiceUtility . log ( bundleContext , LogService . LOG_ERROR , "Unable to resolve: " + reqs [ i ] ) ; } break ; // Resolve unsuccessful, but it did finish } } catch ( IllegalStateException e ) { // If resolve unsuccessful, try again if ( resolveAttempt == 0 ) e . printStackTrace ( ) ; } } } finally { lock . unlock ( ) ; } } else { // Lock was not acquired, wait until it is unlocked and return (resource should be deployed by then) acquired = lock . tryLock ( secondsToWait , TimeUnit . SECONDS ) ; if ( acquired ) { try { // Success } finally { lock . unlock ( ) ; } } else { // failure code here } } } catch ( InterruptedException e ) { e . printStackTrace ( ) ; } finally { this . removeLock ( name ) ; } }
Deploy this resource .
372
4
11,495
public boolean isResourceBundleMatch ( Object objResource , Bundle bundle ) { Resource resource = ( Resource ) objResource ; return ( ( bundle . getSymbolicName ( ) . equals ( resource . getSymbolicName ( ) ) ) && ( isValidVersion ( bundle . getVersion ( ) , resource . getVersion ( ) . toString ( ) ) ) ) ; }
Does this resource match this bundle?
80
7
11,496
@ SuppressWarnings ( "unchecked" ) public List < RpcResponse > request ( List < RpcRequest > reqList ) { List < RpcResponse > respList = new ArrayList < RpcResponse > ( ) ; List < Map > marshaledReqs = new ArrayList < Map > ( ) ; Map < String , RpcRequest > byReqId = new HashMap < String , RpcRequest > ( ) ; for ( RpcRequest req : reqList ) { try { marshaledReqs . add ( req . marshal ( contract ) ) ; byReqId . put ( req . getId ( ) , req ) ; } catch ( RpcException e ) { respList . add ( new RpcResponse ( req , e ) ) ; } } InputStream is = null ; try { ByteArrayOutputStream bos = new ByteArrayOutputStream ( ) ; serializer . write ( marshaledReqs , bos ) ; bos . close ( ) ; byte [ ] data = bos . toByteArray ( ) ; is = requestRaw ( data ) ; List < Map > responses = serializer . readList ( is ) ; for ( Map map : responses ) { String id = ( String ) map . get ( "id" ) ; if ( id != null ) { RpcRequest req = byReqId . get ( id ) ; if ( req == null ) { // TODO: ?? log error? } else { byReqId . remove ( id ) ; respList . add ( unmarshal ( req , map ) ) ; } } else { // TODO: ?? log error? } } if ( byReqId . size ( ) > 0 ) { for ( RpcRequest req : byReqId . values ( ) ) { String msg = "No response in batch for request " + req . getId ( ) ; RpcException exc = RpcException . Error . INVALID_RESP . exc ( msg ) ; RpcResponse resp = new RpcResponse ( req , exc ) ; respList . add ( resp ) ; } } } catch ( IOException e ) { String msg = "IOException requesting batch " + " from: " + endpoint + " - " + e . getMessage ( ) ; RpcException exc = RpcException . Error . INTERNAL . exc ( msg ) ; respList . add ( new RpcResponse ( null , exc ) ) ; } finally { closeQuietly ( is ) ; } return respList ; }
Makes JSON - RPC batch request against the remote server as a single HTTP request .
534
17
11,497
public URLConnection createURLConnection ( URL url ) throws IOException { URLConnection conn = url . openConnection ( ) ; return conn ; }
Returns an URLConnection for the given URL . Subclasses may override this and customize the connection with custom timeouts headers etc .
29
25
11,498
public Content getSignature ( MethodDoc method ) { Content pre = new HtmlTree ( HtmlTag . PRE ) ; writer . addAnnotationInfo ( method , pre ) ; addModifiers ( method , pre ) ; addTypeParameters ( method , pre ) ; addReturnType ( method , pre ) ; if ( configuration . linksource ) { Content methodName = new StringContent ( method . name ( ) ) ; writer . addSrcLink ( method , methodName , pre ) ; } else { addName ( method . name ( ) , pre ) ; } int indent = pre . charCount ( ) ; addParameters ( method , pre , indent ) ; addExceptions ( method , pre , indent ) ; return pre ; }
Get the signature for the given method .
154
8
11,499
public String generateTemporaryToken ( String key , int secondsToLive , Object context ) { checkNotNull ( key ) ; String token = tokenGenerator . generate ( ) ; tokenCache . put ( key , Triplet . of ( token , DateTime . now ( ) . plusSeconds ( secondsToLive ) . getMillis ( ) , context ) ) ; return token ; }
Same as above but will also store a context that can be retried later .
81
16