signature stringlengths 43 39.1k | implementation stringlengths 0 450k |
|---|---|
public class ObjectFactory { /** * Create an instance of { @ link JAXBElement } { @ code < } { @ link LogoType }
* { @ code > } */
@ XmlElementDecl ( namespace = "http://www.w3.org/2005/Atom" , name = "logo" , scope = SourceType . class ) public JAXBElement < LogoType > createSourceTypeLogo ( LogoType value ) { } } | return new JAXBElement < LogoType > ( FEED_TYPE_LOGO_QNAME , LogoType . class , SourceType . class , value ) ; |
public class Geomem { /** * Returns the { @ link Info } s where start < = time < finish and position is
* inside the geohash withinHash .
* @ param start
* start time inclusive
* @ param finish
* finish time exclusive
* @ param withinHash
* returned records are within hash
* @ return iterable */
private Iterable < Info < T , R > > find ( long start , long finish , String withinHash ) { } } | long key = Base32 . decodeBase32 ( withinHash ) ; SortedMap < Long , Info < T , R > > sortedByTime = mapByGeoHash . get ( key ) ; if ( sortedByTime == null ) return Collections . emptyList ( ) ; else return sortedByTime . subMap ( start , finish ) . values ( ) ; |
public class MlBaseState { /** * { @ inheritDoc } */
@ SuppressWarnings ( "rawtypes" ) @ Override public List < T > multiUpdate ( List < List < Object > > keys , List < ValueUpdater > updaters ) { } } | // 使用されないため 、 実装は行わない 。
return null ; |
public class GLMParams { /** * helper function */
static final double y_log_y ( double y , double mu ) { } } | if ( y == 0 ) return 0 ; if ( mu < Double . MIN_NORMAL ) mu = Double . MIN_NORMAL ; return y * Math . log ( y / mu ) ; |
public class Scope { /** * Construct a fresh scope within this scope , with new owner ,
* which shares its table with the outer scope . Used in connection with
* method leave if scope access is stack - like in order to avoid allocation
* of fresh tables . */
public Scope dup ( Symbol newOwner ) { } } | Scope result = new Scope ( this , newOwner , this . table , this . nelems ) ; shared ++ ; // System . out . println ( " = = = = > duping scope " + this . hashCode ( ) + " owned by " + newOwner + " to " + result . hashCode ( ) ) ;
// new Error ( ) . printStackTrace ( System . out ) ;
return result ; |
public class ConnectionInformation { /** * Creates a new { @ link ConnectionInformation } instance for a { @ link Connection } which will be obtained via a
* { @ link PooledConnection }
* @ param pooledConnection the { @ link PooledConnection } which created the { @ link # connection }
* @ return a new { @ link ConnectionInformation } instance */
public static ConnectionInformation fromPooledConnection ( PooledConnection pooledConnection ) { } } | final ConnectionInformation connectionInformation = new ConnectionInformation ( ) ; connectionInformation . pooledConnection = pooledConnection ; return connectionInformation ; |
public class Action { /** * Sleeps so many milliseconds , emulating slow requests . */
public static Action delay ( final Integer delay ) { } } | return new Action ( input -> { try { Thread . sleep ( delay ) ; } catch ( InterruptedException e ) { Thread . currentThread ( ) . interrupt ( ) ; } return input ; } ) ; |
public class SpecRewriter { /** * Moves initialization of the given field to the given position of the first block of the given method . */
private void moveInitializer ( Field field , Method method , int position ) { } } | method . getFirstBlock ( ) . getAst ( ) . add ( position , new ExpressionStatement ( new FieldInitializationExpression ( field . getAst ( ) ) ) ) ; field . getAst ( ) . setInitialValueExpression ( null ) ; |
public class IOUtil { /** * 获取文件所在目录的路径
* @ param path
* @ return */
public static String dirname ( String path ) { } } | int index = path . lastIndexOf ( '/' ) ; if ( index == - 1 ) return path ; return path . substring ( 0 , index + 1 ) ; |
public class ExpressionBuilder { /** * Appends an OR expression to the RHS of the expression . The current RHS of the expression must be an Operand .
* @ return this ExpressionBuilder . */
public ExpressionBuilder or ( ) { } } | GroupExpression lastGroupExpression = stack . isEmpty ( ) ? null : stack . peek ( ) ; if ( lhsExpression == null ) { throw new SyntaxException ( "Syntax exception: OR missing LHS operand" ) ; } else if ( lastGroupExpression == null ) { GroupExpression or = new GroupExpression ( GroupExpression . Type . OR ) ; or . add ( lhsExpression ) ; stack . push ( or ) ; expression . setExpression ( or ) ; lhsExpression = null ; } else if ( lastGroupExpression . getType ( ) . equals ( GroupExpression . Type . OR ) ) { // Keep using the existing OR
lhsExpression = null ; return this ; } else if ( lastGroupExpression . getType ( ) . equals ( GroupExpression . Type . AND ) ) { // AND takes precedence over OR , so we wrap the AND
// by removing it from any parent expressions and inserting the OR in its place
GroupExpression and = stack . pop ( ) ; GroupExpression or = new GroupExpression ( GroupExpression . Type . OR ) ; if ( stack . isEmpty ( ) ) { expression . setExpression ( or ) ; or . add ( and ) ; } else { // need to get at the parent
GroupExpression parent = stack . pop ( ) ; parent . remove ( and ) ; parent . add ( or ) ; or . add ( and ) ; } stack . push ( and ) ; stack . push ( or ) ; lhsExpression = null ; } return this ; |
public class EventMention { /** * setter for anchor - sets
* @ generated
* @ param v value to set into the feature */
public void setAnchor ( Anchor v ) { } } | if ( EventMention_Type . featOkTst && ( ( EventMention_Type ) jcasType ) . casFeat_anchor == null ) jcasType . jcas . throwFeatMissing ( "anchor" , "de.julielab.jules.types.ace.EventMention" ) ; jcasType . ll_cas . ll_setRefValue ( addr , ( ( EventMention_Type ) jcasType ) . casFeatCode_anchor , jcasType . ll_cas . ll_getFSRef ( v ) ) ; |
public class BigIntegerUtils { /** * Read .
* @ param value the value
* @ return the big integer */
public static BigInteger read ( String value ) { } } | if ( ! StringUtils . hasText ( value ) ) return null ; return new BigInteger ( value ) ; |
public class TLSBuilder { /** * Builds a new ServerSocket
* @ return SSLServerSocket */
public SSLServerSocket buildServerSocket ( ) throws CertificateException , UnrecoverableKeyException , NoSuchAlgorithmException , KeyStoreException , KeyManagementException , IOException { } } | // Get socket
final SSLServerSocket s = ( SSLServerSocket ) build ( ) . getServerSocketFactory ( ) . createServerSocket ( port ) ; // Set protocols
s . setEnabledProtocols ( TLS . getUsable ( TLS . TLS_PROTOCOLS , s . getSupportedProtocols ( ) ) ) ; s . setEnabledCipherSuites ( TLS . getUsable ( TLS . TLS_CIPHER_SUITES , s . getSupportedCipherSuites ( ) ) ) ; return s ; |
public class BaseDaoEnabled { /** * A call through to the { @ link Dao # updateId ( Object , Object ) } . */
public int updateId ( ID newId ) throws SQLException { } } | checkForDao ( ) ; @ SuppressWarnings ( "unchecked" ) T t = ( T ) this ; return dao . updateId ( t , newId ) ; |
public class ReadStreamOld { /** * Fills the buffer with a non - blocking read .
* @ param timeout the timeout in milliseconds for the next data
* @ return true on data or end of file , false on timeout */
public int fillWithTimeout ( long timeout ) throws IOException { } } | if ( _readOffset < _readLength ) { return _readLength - _readOffset ; } if ( _readBuffer == null ) { _readOffset = 0 ; _readLength = 0 ; return - 1 ; } _readOffset = 0 ; StreamImpl source = _source ; if ( source == null ) { // return true on end of file
return - 1 ; } int readLength = source . readTimeout ( _readBuffer , 0 , _readBuffer . length , timeout ) ; if ( readLength > 0 ) { _readLength = readLength ; _position += readLength ; if ( _isEnableReadTime ) { _readTime = CurrentTime . currentTime ( ) ; } return readLength ; } else if ( readLength == READ_TIMEOUT ) { // timeout
_readLength = 0 ; return 0 ; } else { // return false on end of file
_readLength = 0 ; return - 1 ; } |
public class SeleniumDriverFixture { /** * < p > < code >
* | start browser | < i > firefox < / i > | on url | < i > http : / / localhost < / i > | using remote server on host | < i > localhost < / i > | on port | < i > 4444 < / i > |
* < / code > < / p >
* @ param browser
* @ param browserUrl
* @ param serverHost
* @ param serverPort
* @ deprecated This call requires a Selenium 1 server . It is advised to use WebDriver . */
public void startBrowserOnUrlUsingRemoteServerOnHostOnPort ( final String browser , final String browserUrl , final String serverHost , final int serverPort ) { } } | setCommandProcessor ( new HttpCommandProcessorAdapter ( new HttpCommandProcessor ( serverHost , serverPort , browser , removeAnchorTag ( browserUrl ) ) ) ) ; commandProcessor . start ( ) ; setTimeoutOnSelenium ( ) ; LOG . debug ( "Started HTML command processor" ) ; |
public class HBaseDataHandler { /** * On find key only .
* @ param filterList
* the filter list
* @ param isFindKeyOnly
* the is find key only
* @ return the filter list */
private FilterList onFindKeyOnly ( FilterList filterList , boolean isFindKeyOnly ) { } } | if ( isFindKeyOnly ) { if ( filterList == null ) { filterList = new FilterList ( ) ; } filterList . addFilter ( new KeyOnlyFilter ( ) ) ; } return filterList ; |
public class DefaultAuthenticationHandler { /** * Default implementation returns the user authentication associated with the auth token , if the token is provided . Otherwise , the consumer authentication
* is returned .
* @ param request The request that was successfully authenticated .
* @ param authentication The consumer authentication ( details about how the request was authenticated ) .
* @ param authToken The OAuth token associated with the authentication . This token MAY be null if no authenticated token was needed to successfully
* authenticate the request ( for example , in the case of 2 - legged OAuth ) .
* @ return The authentication . */
public Authentication createAuthentication ( HttpServletRequest request , ConsumerAuthentication authentication , OAuthAccessProviderToken authToken ) { } } | if ( authToken != null ) { Authentication userAuthentication = authToken . getUserAuthentication ( ) ; if ( userAuthentication instanceof AbstractAuthenticationToken ) { // initialize the details with the consumer that is actually making the request on behalf of the user .
( ( AbstractAuthenticationToken ) userAuthentication ) . setDetails ( new OAuthAuthenticationDetails ( request , authentication . getConsumerDetails ( ) ) ) ; } return userAuthentication ; } return authentication ; |
public class DefaultGroovyMethods { /** * Iterates through this Iterable transforming each entry into a new value using the < code > transform < / code > closure
* returning a list of transformed values .
* < pre class = " groovyTestCase " > assert [ 2,4,6 ] = = [ 1,2,3 ] . collect { it * 2 } < / pre >
* @ param self an Iterable
* @ param transform the closure used to transform each item of the collection
* @ return a List of the transformed values
* @ since 2.5.0 */
public static < S , T > List < T > collect ( Iterable < S > self , @ ClosureParams ( FirstParam . FirstGenericType . class ) Closure < T > transform ) { } } | return ( List < T > ) collect ( self . iterator ( ) , transform ) ; |
public class Utils { /** * Checks whether the elements of the given tuple are not negative ,
* and throws an < code > IllegalArgumentException < / code > if any of
* them is negative .
* @ param t The tuple
* @ throws NullPointerException If the given size is < code > null < / code >
* @ throws IllegalArgumentException If any element of the given tuple
* is negative */
public static void checkForNonNegativeElements ( IntTuple t ) { } } | for ( int i = 0 ; i < t . getSize ( ) ; i ++ ) { if ( t . get ( i ) < 0 ) { throw new IllegalArgumentException ( "Negative size: " + t ) ; } } |
public class FieldReferenceLookup { /** * Gives all fields of underlying inputs in order of those inputs and order of fields within input .
* @ return concatenated list of fields of all inputs . */
public List < FieldReferenceExpression > getAllInputFields ( ) { } } | return fieldReferences . stream ( ) . flatMap ( input -> input . values ( ) . stream ( ) ) . collect ( toList ( ) ) ; |
public class Char { /** * Encodes with backslash all illegal characters */
public static String encodeBackslash ( CharSequence s , Legal legal ) { } } | StringBuilder b = new StringBuilder ( ( int ) ( s . length ( ) * 1.5 ) ) ; for ( int i = 0 ; i < s . length ( ) ; i ++ ) { if ( legal . isLegal ( s . charAt ( i ) ) ) { b . append ( s . charAt ( i ) ) ; } else { if ( charToBackslash . containsKey ( s . charAt ( i ) ) ) { b . append ( charToBackslash . get ( s . charAt ( i ) ) ) ; continue ; } b . append ( "\\u" ) ; String hex = Integer . toHexString ( s . charAt ( i ) ) ; for ( int j = 0 ; j < 4 - hex . length ( ) ; j ++ ) b . append ( '0' ) ; b . append ( hex ) ; } } return ( b . toString ( ) ) ; |
public class ArrayUtils { /** * Make a copy for a 2D array
* @ param nums
* @ return */
public static int [ ] [ ] copyOf ( final int [ ] [ ] nums ) { } } | final int [ ] [ ] copy = new int [ nums . length ] [ ] ; for ( int i = 0 ; i < copy . length ; i ++ ) { final int [ ] member = new int [ nums [ i ] . length ] ; System . arraycopy ( nums [ i ] , 0 , member , 0 , nums [ i ] . length ) ; copy [ i ] = member ; } return copy ; |
public class CommercePriceListAccountRelPersistenceImpl { /** * Returns the commerce price list account rel where commerceAccountId = & # 63 ; and commercePriceListId = & # 63 ; or throws a { @ link NoSuchPriceListAccountRelException } if it could not be found .
* @ param commerceAccountId the commerce account ID
* @ param commercePriceListId the commerce price list ID
* @ return the matching commerce price list account rel
* @ throws NoSuchPriceListAccountRelException if a matching commerce price list account rel could not be found */
@ Override public CommercePriceListAccountRel findByC_C ( long commerceAccountId , long commercePriceListId ) throws NoSuchPriceListAccountRelException { } } | CommercePriceListAccountRel commercePriceListAccountRel = fetchByC_C ( commerceAccountId , commercePriceListId ) ; if ( commercePriceListAccountRel == null ) { StringBundler msg = new StringBundler ( 6 ) ; msg . append ( _NO_SUCH_ENTITY_WITH_KEY ) ; msg . append ( "commerceAccountId=" ) ; msg . append ( commerceAccountId ) ; msg . append ( ", commercePriceListId=" ) ; msg . append ( commercePriceListId ) ; msg . append ( "}" ) ; if ( _log . isDebugEnabled ( ) ) { _log . debug ( msg . toString ( ) ) ; } throw new NoSuchPriceListAccountRelException ( msg . toString ( ) ) ; } return commercePriceListAccountRel ; |
public class DynamicJasperHelper { /** * Compiles the report and applies the layout . < b > generatedParams < / b > MUST NOT BE NULL
* All the key objects from the generatedParams map that are String , will be registered as parameters of the report .
* @ param dr
* @ param layoutManager
* @ param generatedParams
* @ return
* @ throws JRException */
public static JasperReport generateJasperReport ( DynamicReport dr , LayoutManager layoutManager , Map generatedParams ) throws JRException { } } | log . info ( "generating JasperReport (DynamicReport dr, LayoutManager layoutManager, Map generatedParams)" ) ; return generateJasperReport ( dr , layoutManager , generatedParams , "r" ) ; |
public class Exceptions { /** * Render the exception text based on the display attributes .
* @ throws JspException if a JSP exception has occurred */
public void doTag ( ) throws JspException { } } | // First look for the exception in the pageflow / struts request attribute . If it ' s not there ,
// look for it in the request attribute the container provides for web . xml - configured error
// pages .
InternalStringBuilder results = new InternalStringBuilder ( 128 ) ; PageContext pageContext = getPageContext ( ) ; Throwable e = ( Throwable ) pageContext . getAttribute ( Globals . EXCEPTION_KEY , PageContext . REQUEST_SCOPE ) ; if ( e == null ) { ServletRequest req = pageContext . getRequest ( ) ; e = ( Throwable ) req . getAttribute ( "javax.servlet.error.exception" ) ; if ( e == null ) { e = ( Throwable ) req . getAttribute ( "javax.servlet.jsp.jspException" ) ; } } if ( ! _showStackTrace && _showDevModeStackTrace ) { boolean devMode = ! AdapterManager . getServletContainerAdapter ( pageContext . getServletContext ( ) ) . isInProductionMode ( ) ; if ( devMode ) _showStackTrace = true ; } if ( e != null ) { if ( _showMessage ) { String msg = e . getMessage ( ) ; // if we have message lets output the exception name and the name of the
if ( ( msg != null ) && ( msg . length ( ) > 0 ) ) { if ( ! _showStackTrace ) msg = e . getClass ( ) . getName ( ) + ": " + msg ; results . append ( HtmlExceptionFormatter . format ( msg , e , _showStackTrace ) ) ; } else { results . append ( HtmlExceptionFormatter . format ( e . getClass ( ) . getName ( ) , e , _showStackTrace ) ) ; } } else { results . append ( HtmlExceptionFormatter . format ( null , e , _showStackTrace ) ) ; } ResponseUtils . write ( pageContext , results . toString ( ) ) ; } |
public class FaceDetectionMarshaller { /** * Marshall the given parameter object . */
public void marshall ( FaceDetection faceDetection , ProtocolMarshaller protocolMarshaller ) { } } | if ( faceDetection == null ) { throw new SdkClientException ( "Invalid argument passed to marshall(...)" ) ; } try { protocolMarshaller . marshall ( faceDetection . getTimestamp ( ) , TIMESTAMP_BINDING ) ; protocolMarshaller . marshall ( faceDetection . getFace ( ) , FACE_BINDING ) ; } catch ( Exception e ) { throw new SdkClientException ( "Unable to marshall request to JSON: " + e . getMessage ( ) , e ) ; } |
public class MicroOptimization { /** * / graph is the more common way to specialize this class . */
protected void apply ( CompiledPlan plan , AbstractParsedStmt parsedStmt ) { } } | try { AbstractPlanNode planGraph = plan . rootPlanGraph ; planGraph = recursivelyApply ( planGraph , parsedStmt ) ; plan . rootPlanGraph = planGraph ; } catch ( Exception ex ) { ex . printStackTrace ( ) ; } |
public class ClassWriter { /** * Adds a double to the constant pool of the class being build . Does nothing
* if the constant pool already contains a similar item .
* @ param value the double value .
* @ return a new or already existing double item . */
Item newDouble ( final double value ) { } } | key . set ( value ) ; Item result = get ( key ) ; if ( result == null ) { pool . putByte ( DOUBLE ) . putLong ( key . longVal ) ; result = new Item ( index , key ) ; put ( result ) ; index += 2 ; } return result ; |
public class SparkUtils { /** * List of the files in the given directory ( path ) , as a { @ code JavaRDD < String > }
* @ param sc Spark context
* @ param path Path to list files in
* @ return Paths in the directory
* @ throws IOException If error occurs getting directory contents */
public static JavaRDD < String > listPaths ( JavaSparkContext sc , String path ) throws IOException { } } | return listPaths ( sc , path , false ) ; |
public class AbstractScope { /** * Get a unique Var object of the given implicit var type . */
private final V getImplicitVar ( ImplicitVar var , boolean allowDeclaredVars ) { } } | S scope = thisScope ( ) ; while ( scope != null ) { if ( var . isMadeByScope ( scope ) ) { V result = ( ( AbstractScope < S , V > ) scope ) . implicitVars . get ( var ) ; if ( result == null ) { ( ( AbstractScope < S , V > ) scope ) . implicitVars . put ( var , result = scope . makeImplicitVar ( var ) ) ; } return result ; } V result = allowDeclaredVars ? scope . getOwnSlot ( var . name ) : null ; if ( result != null ) { return result ; } // Recurse up the parent Scope
scope = scope . getParent ( ) ; } return null ; |
public class CmsSecurityManager { /** * Changes the resource type of a resource . < p >
* OpenCms handles resources according to the resource type ,
* not the file suffix . This is e . g . why a JSP in OpenCms can have the
* suffix " . html " instead of " . jsp " only . Changing the resource type
* makes sense e . g . if you want to make a plain text file a JSP resource ,
* or a binary file an image , etc . < p >
* @ param context the current request context
* @ param resource the resource to change the type for
* @ param type the new resource type for this resource
* @ throws CmsException if something goes wrong
* @ throws CmsSecurityException if the user has insufficient permission for the given resource ( ( { @ link CmsPermissionSet # ACCESS _ WRITE } required ) )
* @ see org . opencms . file . types . I _ CmsResourceType # chtype ( CmsObject , CmsSecurityManager , CmsResource , int )
* @ see CmsObject # chtype ( String , int ) */
@ SuppressWarnings ( "javadoc" ) public void chtype ( CmsRequestContext context , CmsResource resource , int type ) throws CmsException , CmsSecurityException { } } | CmsDbContext dbc = m_dbContextFactory . getDbContext ( context ) ; try { checkOfflineProject ( dbc ) ; checkPermissions ( dbc , resource , CmsPermissionSet . ACCESS_WRITE , true , CmsResourceFilter . ALL ) ; if ( CmsResourceTypeJsp . isJspTypeId ( type ) ) { // security check preventing the creation of a jsp file without permissions
checkRoleForResource ( dbc , CmsRole . VFS_MANAGER , resource ) ; } m_driverManager . chtype ( dbc , resource , type ) ; } catch ( Exception e ) { dbc . report ( null , Messages . get ( ) . container ( Messages . ERR_CHANGE_RESOURCE_TYPE_1 , context . getSitePath ( resource ) ) , e ) ; } finally { dbc . clear ( ) ; } |
public class ApiWrapper { /** * Sets schedulers for API calls observables and adds logging .
* @ param obs Observable to set schedulers for .
* @ param log Logger instance .
* @ param < E > Class of the service call result .
* @ return Observable for API call . */
< E > Observable < E > wrapObservable ( @ NonNull Observable < E > obs , @ NonNull Logger log , final String msg ) { } } | return obs . subscribeOn ( Schedulers . io ( ) ) . observeOn ( Schedulers . io ( ) ) . doOnNext ( r -> log ( log , ( ComapiResult ) r , msg ) ) . doOnError ( t -> log ( log , t , msg ) ) ; |
public class FSM { /** * Pasandole un array genera todas las transiciones posibles entre los
* estados . */
public void registerAllPossibleTransition ( Automaton [ ] states ) { } } | for ( int i = 0 ; i < states . length ; i ++ ) { for ( int j = i ; j < states . length ; j ++ ) { registerTransition ( states [ i ] , states [ j ] ) ; registerTransition ( states [ j ] , states [ i ] ) ; } } |
public class TextSimilarity { /** * 如果没有指定权重 , 则默认使用词频来标注词的权重
* 词频数据怎么来 ?
* 一个词在词列表1中出现了几次 , 它在词列表1中的权重就是几
* 一个词在词列表2中出现了几次 , 它在词列表2中的权重就是几
* 标注好的权重存储在Word类的weight字段中
* @ param words1 词列表1
* @ param words2 词列表2 */
protected void taggingWeightWithWordFrequency ( List < Word > words1 , List < Word > words2 ) { } } | if ( words1 . get ( 0 ) . getWeight ( ) != null || words2 . get ( 0 ) . getWeight ( ) != null ) { if ( LOGGER . isDebugEnabled ( ) ) { LOGGER . debug ( "词已经被指定权重,不再使用词频进行标注" ) ; } return ; } // 词频统计
Map < String , AtomicInteger > frequency1 = frequency ( words1 ) ; Map < String , AtomicInteger > frequency2 = frequency ( words2 ) ; // 输出词频统计信息
if ( LOGGER . isDebugEnabled ( ) ) { LOGGER . debug ( "词频统计1:\n{}" , formatWordsFrequency ( frequency1 ) ) ; LOGGER . debug ( "词频统计2:\n{}" , formatWordsFrequency ( frequency2 ) ) ; } // 权重标注
words1 . parallelStream ( ) . forEach ( word -> { word . setWeight ( frequency1 . get ( word . getText ( ) ) . floatValue ( ) ) ; } ) ; words2 . parallelStream ( ) . forEach ( word -> { word . setWeight ( frequency2 . get ( word . getText ( ) ) . floatValue ( ) ) ; } ) ; |
public class EventhubDataWriterBuilder { /** * Create an eventhub data writer , wrapped into a buffered async data writer */
public AsyncDataWriter getAsyncDataWriter ( Properties properties ) { } } | EventhubDataWriter eventhubDataWriter = new EventhubDataWriter ( properties ) ; EventhubBatchAccumulator accumulator = new EventhubBatchAccumulator ( properties ) ; BatchedEventhubDataWriter batchedEventhubDataWriter = new BatchedEventhubDataWriter ( accumulator , eventhubDataWriter ) ; return batchedEventhubDataWriter ; |
public class ScriptContainer { /** * Release any acquired resources . */
protected void localRelease ( ) { } } | super . localRelease ( ) ; _idScope = null ; _writeScript = false ; _genScope = false ; _writeId = false ; if ( _funcBlocks != null ) _funcBlocks . clear ( ) ; if ( _codeBefore != null ) _codeBefore . clear ( ) ; if ( _codeAfter != null ) _codeAfter . clear ( ) ; if ( _idMap != null ) _idMap . clear ( ) ; if ( _idToNameMap != null ) _idToNameMap . clear ( ) ; |
public class RuntimeExceptionsFactory { /** * Constructs and initializes a new { @ link UnsupportedOperationException } with the given { @ link String message }
* formatted with the given { @ link Object [ ] arguments } .
* @ param message { @ link String } describing the { @ link UnsupportedOperationException exception } .
* @ param args { @ link Object [ ] arguments } used to replace format placeholders in the { @ link String message } .
* @ return a new { @ link UnsupportedOperationException } with the given { @ link String message } .
* @ see # newUnsupportedOperationException ( String , Object . . . )
* @ see java . lang . UnsupportedOperationException */
public static UnsupportedOperationException newUnsupportedOperationException ( String message , Object ... args ) { } } | return newUnsupportedOperationException ( null , message , args ) ; |
public class CollapseProperties { /** * Updates the first initialization ( a . k . a " declaration " ) of a global name that occurs in a static
* MEMBER _ FUNCTION _ DEF in a class . See comment for { @ link # updateGlobalNameDeclaration } .
* @ param n A static MEMBER _ FUNCTION _ DEF in a class assigned to a global name ( e . g . ` a . b ` )
* @ param alias The new flattened name for ` n ` ( e . g . " a $ b " )
* @ param canCollapseChildNames whether properties of ` n ` are also collapsible , meaning that any
* properties only assigned locally need stub declarations */
private void updateGlobalNameDeclarationAtStaticMemberNode ( Name n , String alias , boolean canCollapseChildNames ) { } } | Ref declaration = n . getDeclaration ( ) ; Node classNode = declaration . getNode ( ) . getGrandparent ( ) ; checkState ( classNode . isClass ( ) , classNode ) ; Node enclosingStatement = NodeUtil . getEnclosingStatement ( classNode ) ; if ( canCollapseChildNames ) { addStubsForUndeclaredProperties ( n , alias , enclosingStatement . getParent ( ) , classNode ) ; } // detach ` static m ( ) { } ` from ` class Foo { static m ( ) { } } `
Node memberFn = declaration . getNode ( ) . detach ( ) ; Node fnNode = memberFn . getOnlyChild ( ) . detach ( ) ; checkForHosedThisReferences ( fnNode , memberFn . getJSDocInfo ( ) , n ) ; // add a var declaration , creating ` var Foo $ m = function ( ) { } ; class Foo { } `
Node varDecl = IR . var ( NodeUtil . newName ( compiler , alias , memberFn ) , fnNode ) . srcref ( memberFn ) ; enclosingStatement . getParent ( ) . addChildBefore ( varDecl , enclosingStatement ) ; compiler . reportChangeToEnclosingScope ( varDecl ) ; // collapsing this name ' s properties requires updating this Ref
n . updateRefNode ( declaration , varDecl . getFirstChild ( ) ) ; |
public class Cl { /** * ResultSet is not modified ( no rs . next called ) .
* @ param rs
* @ return */
static Cl map ( ResultSet rs , int colShift ) { } } | Cl tmp = new Cl ( ) ; try { tmp . id = rs . getInt ( 1 + colShift ) ; tmp . name = rs . getString ( 2 + colShift ) ; tmp . childFirst = rs . getBoolean ( 3 + colShift ) ; tmp . hiddenClasses = rs . getString ( 4 + colShift ) ; tmp . tracingEnabled = rs . getBoolean ( 5 + colShift ) ; tmp . persistent = rs . getBoolean ( 6 + colShift ) ; tmp . allowedRunners = rs . getString ( 7 + colShift ) ; } catch ( SQLException e ) { throw new DatabaseException ( e ) ; } return tmp ; |
public class SeekableStringReader { /** * Read everything until one the sentinel , which must exist in the string .
* Sentinel char is read but not returned in the result . */
public String readUntil ( char sentinel ) { } } | int i = str . indexOf ( sentinel , cursor ) ; if ( i >= 0 ) { int from = cursor ; cursor = i + 1 ; return str . substring ( from , i ) ; } throw new ParseException ( "terminator not found" ) ; |
public class Bundler { /** * Inserts a CharSequence value into the mapping of the underlying Bundle , replacing any existing
* value for the given key . Either key or value may be null .
* @ param key a String , or null
* @ param value a CharSequence , or null
* @ return this bundler instance to chain method calls */
public Bundler put ( String key , CharSequence value ) { } } | delegate . putCharSequence ( key , value ) ; return this ; |
public class PersonGroupPersonsImpl { /** * Delete a face from a person . Relative image for the persisted face will also be deleted .
* @ param personGroupId Id referencing a particular person group .
* @ param personId Id referencing a particular person .
* @ param persistedFaceId Id referencing a particular persistedFaceId of an existing face .
* @ throws IllegalArgumentException thrown if parameters fail the validation
* @ return the { @ link ServiceResponse } object if successful . */
public Observable < Void > deleteFaceAsync ( String personGroupId , UUID personId , UUID persistedFaceId ) { } } | return deleteFaceWithServiceResponseAsync ( personGroupId , personId , persistedFaceId ) . map ( new Func1 < ServiceResponse < Void > , Void > ( ) { @ Override public Void call ( ServiceResponse < Void > response ) { return response . body ( ) ; } } ) ; |
public class VaultLockPolicyMarshaller { /** * Marshall the given parameter object . */
public void marshall ( VaultLockPolicy vaultLockPolicy , ProtocolMarshaller protocolMarshaller ) { } } | if ( vaultLockPolicy == null ) { throw new SdkClientException ( "Invalid argument passed to marshall(...)" ) ; } try { protocolMarshaller . marshall ( vaultLockPolicy . getPolicy ( ) , POLICY_BINDING ) ; } catch ( Exception e ) { throw new SdkClientException ( "Unable to marshall request to JSON: " + e . getMessage ( ) , e ) ; } |
public class AbstractCasView { /** * Put cas response attributes into model .
* @ param model the model
* @ param attributes the attributes
* @ param registeredService the registered service
* @ param attributesRenderer the attributes renderer */
protected void putCasResponseAttributesIntoModel ( final Map < String , Object > model , final Map < String , Object > attributes , final RegisteredService registeredService , final CasProtocolAttributesRenderer attributesRenderer ) { } } | LOGGER . trace ( "Beginning to encode attributes for the response" ) ; val encodedAttributes = this . protocolAttributeEncoder . encodeAttributes ( attributes , registeredService ) ; LOGGER . debug ( "Encoded attributes for the response are [{}]" , encodedAttributes ) ; putIntoModel ( model , CasProtocolConstants . VALIDATION_CAS_MODEL_ATTRIBUTE_NAME_ATTRIBUTES , encodedAttributes ) ; val formattedAttributes = attributesRenderer . render ( encodedAttributes ) ; putIntoModel ( model , CasProtocolConstants . VALIDATION_CAS_MODEL_ATTRIBUTE_NAME_FORMATTED_ATTRIBUTES , formattedAttributes ) ; |
public class Interval { /** * Returns an Interval for the range of integers inclusively between from and to with the specified
* stepBy value . */
public static Interval fromToBy ( int from , int to , int stepBy ) { } } | if ( stepBy == 0 ) { throw new IllegalArgumentException ( "Cannot use a step by of 0" ) ; } if ( from > to && stepBy > 0 || from < to && stepBy < 0 ) { throw new IllegalArgumentException ( "Step by is incorrect for the range" ) ; } return new Interval ( from , to , stepBy ) ; |
public class OneOfTracker { /** * Check that each group is satisfied by one and only one field .
* @ param currentPath the json path to the element being checked */
public void checkAllGroupsSatisfied ( final String currentPath ) { } } | StringBuilder errors = new StringBuilder ( ) ; for ( OneOfGroup group : this . mapping . values ( ) ) { if ( group . satisfiedBy . isEmpty ( ) ) { errors . append ( "\n" ) ; errors . append ( "\t* The OneOf choice: " ) . append ( group . name ) . append ( " was not satisfied. One (and only one) of the " ) ; errors . append ( "following fields is required in the request data: " ) . append ( toNames ( group . choices ) ) ; } Collection < OneOfSatisfier > oneOfSatisfiers = Collections2 . filter ( group . satisfiedBy , input -> ! input . isCanSatisfy ) ; if ( oneOfSatisfiers . size ( ) > 1 ) { errors . append ( "\n" ) ; errors . append ( "\t* The OneOf choice: " ) . append ( group . name ) . append ( " was satisfied by too many fields. Only one choice " ) ; errors . append ( "may be in the request data. The fields found were: " ) . append ( toNames ( toFields ( group . satisfiedBy ) ) ) ; } } Assert . equals ( 0 , errors . length ( ) , "\nErrors were detected when analysing the @OneOf dependencies of '" + currentPath + "': \n" + errors ) ; |
public class OrderAction { /** * Swaps the currently selected entity with the entity located
* at the specified position . No other entities are affected by this operation .
* @ param swapPosition
* 0 based index of target position
* @ throws java . lang . IllegalStateException
* If no entity has been selected yet
* @ throws java . lang . IllegalArgumentException
* If the specified position is out - of - bounds
* @ return The current OrderAction sub - implementation instance */
@ SuppressWarnings ( "unchecked" ) public M swapPosition ( int swapPosition ) { } } | Checks . notNegative ( swapPosition , "Provided swapPosition" ) ; Checks . check ( swapPosition < orderList . size ( ) , "Provided swapPosition is too big and is out of bounds. swapPosition: " + swapPosition ) ; T selectedItem = orderList . get ( selectedPosition ) ; T swapItem = orderList . get ( swapPosition ) ; orderList . set ( swapPosition , selectedItem ) ; orderList . set ( selectedPosition , swapItem ) ; return ( M ) this ; |
public class Wro4jAutoConfiguration { /** * This is the default " Least recently used memory cache " strategy of Wro4j
* which will be configured per default .
* @ param < K > Type of the cache keys
* @ param < V > Type of the cache values
* @ return A default Wro4j cache strategy */
@ Bean @ ConditionalOnMissingBean ( CacheStrategy . class ) @ Order ( - 90 ) < K , V > CacheStrategy < K , V > defaultCacheStrategy ( ) { } } | LOGGER . debug ( "Creating cache strategy 'LruMemoryCacheStrategy'" ) ; return new LruMemoryCacheStrategy < > ( ) ; |
public class CsvTarget { /** * { @ inheritDoc } */
@ SuppressWarnings ( { } } | "unchecked" } ) public void importItem ( Object item ) { try { m_csvWriter . write ( ( Map < String , ? > ) item , m_propertyNames ) ; } catch ( IOException e ) { throw new RuntimeException ( e ) ; } |
public class QueryParameterAnnotationHandler { /** * Serializes the field value regardless of reflection errors . Fallback to the { @ link ToStringSerializer } .
* @ param paramMetadata
* the query parameter annotation
* @ param fieldValue
* the field value
* @ param fieldName
* the field name ( for logging purposes only )
* @ return the serialized value
* @ throws UnsupportedEncodingException
* UTF - 8 encoding issue */
private static String serialize ( final QueryParameter paramMetadata , final Object fieldValue , final String fieldName ) { } } | String paramValue ; try { paramValue = paramMetadata . serializer ( ) . newInstance ( ) . handle ( fieldValue ) ; } catch ( final InstantiationException e ) { LOGGER . error ( "Failure while serializing field {}" , new Object [ ] { fieldName , e } ) ; paramValue = new ToStringSerializer ( ) . handle ( fieldValue ) ; } catch ( final IllegalAccessException e ) { LOGGER . error ( "Failure while serializing field {}" , new Object [ ] { fieldName , e } ) ; paramValue = new ToStringSerializer ( ) . handle ( fieldValue ) ; } return paramValue ; |
public class RaftConfigurationLoader { /** * Validates a pre - existing { @ link io . libraft . agent . configuration . RaftConfiguration }
* instance . The following basic validation checks are performed :
* < ul >
* < li > All required configuration fields are present . < / li >
* < li > There are no unrecognized configuration elements . < / li >
* < li > Endpoints are specified in valid < em > " host : port " < / em > form . < / li >
* < li > All ports are in the valid port range . < / li >
* < li > All timeouts have values > = 0 . < / li >
* < / ul >
* If an optional configuration block is present , it too is validated using the rules above .
* More thorough validation is performed by components that use the configuration properties .
* @ param configuration instance of { @ code RaftConfiguration } to validate
* @ return { @ code configuration } ( useful if callers would like to method - chain )
* @ throws RaftConfigurationException if the configuration specified in { @ code configuration } has errors */
public static RaftConfiguration validate ( RaftConfiguration configuration ) { } } | // TODO ( AG ) : understand why the validator instance cannot be static final
Validator validator = Validation . buildDefaultValidatorFactory ( ) . getValidator ( ) ; Set < ConstraintViolation < RaftConfiguration > > violations = validator . validate ( configuration ) ; if ( ! violations . isEmpty ( ) ) { throw new RaftConfigurationException ( violations ) ; } return configuration ; |
public class AmazonCloudDirectoryClient { /** * Lists indices attached to the specified object .
* @ param listAttachedIndicesRequest
* @ return Result of the ListAttachedIndices operation returned by the service .
* @ throws InternalServiceException
* Indicates a problem that must be resolved by Amazon Web Services . This might be a transient error in
* which case you can retry your request until it succeeds . Otherwise , go to the < a
* href = " http : / / status . aws . amazon . com / " > AWS Service Health Dashboard < / a > site to see if there are any
* operational issues with the service .
* @ throws InvalidArnException
* Indicates that the provided ARN value is not valid .
* @ throws RetryableConflictException
* Occurs when a conflict with a previous successful write is detected . For example , if a write operation
* occurs on an object and then an attempt is made to read the object using “ SERIALIZABLE ” consistency , this
* exception may result . This generally occurs when the previous write did not have time to propagate to the
* host serving the current request . A retry ( with appropriate backoff logic ) is the recommended response to
* this exception .
* @ throws ValidationException
* Indicates that your request is malformed in some manner . See the exception message .
* @ throws LimitExceededException
* Indicates that limits are exceeded . See < a
* href = " https : / / docs . aws . amazon . com / clouddirectory / latest / developerguide / limits . html " > Limits < / a > for more
* information .
* @ throws AccessDeniedException
* Access denied . Check your permissions .
* @ throws DirectoryNotEnabledException
* Operations are only permitted on enabled directories .
* @ throws ResourceNotFoundException
* The specified resource could not be found .
* @ sample AmazonCloudDirectory . ListAttachedIndices
* @ see < a href = " http : / / docs . aws . amazon . com / goto / WebAPI / clouddirectory - 2017-01-11 / ListAttachedIndices "
* target = " _ top " > AWS API Documentation < / a > */
@ Override public ListAttachedIndicesResult listAttachedIndices ( ListAttachedIndicesRequest request ) { } } | request = beforeClientExecution ( request ) ; return executeListAttachedIndices ( request ) ; |
public class ObjectCountImpl { /** * < ! - - begin - user - doc - - >
* < ! - - end - user - doc - - >
* @ generated */
public void setSObjNum ( Integer newSObjNum ) { } } | Integer oldSObjNum = sObjNum ; sObjNum = newSObjNum ; if ( eNotificationRequired ( ) ) eNotify ( new ENotificationImpl ( this , Notification . SET , AfplibPackage . OBJECT_COUNT__SOBJ_NUM , oldSObjNum , sObjNum ) ) ; |
public class PubSubRealization { /** * Reconstitutes all durable subscriptions for this destination . Before this
* method is called , the durable subscriptions itemstream must have been
* recovered and setDurableSubscriptionResources ( ) must have been called .
* @ throws MessageStoreException
* @ throws SIDiscriminatorSyntaxException
* @ throws SIResourceException
* @ throws SISelectorSyntaxException */
private void reconstituteDurableSubscriptions ( ) throws MessageStoreException , SIDiscriminatorSyntaxException , SISelectorSyntaxException , SIResourceException { } } | if ( TraceComponent . isAnyTracingEnabled ( ) && tc . isEntryEnabled ( ) ) SibTr . entry ( tc , "reconstituteDurableSubscriptions" ) ; // First create a filter to locate subscriptions for this destination
DurableSubscriptionItemStream durableSub = null ; final SubscriptionStateFilter subStateFilter = new SubscriptionStateFilter ( ) ; /* * Get a browse cursor on the topicspace itemstream to allow us to search
* for all the persisted durable sub items . Find the first one . */
NonLockingCursor subCursor = _pubsubMessageItemStream . newNonLockingReferenceStreamCursor ( subStateFilter ) ; /* Find the first subscription in the itemstream */
durableSub = ( DurableSubscriptionItemStream ) subCursor . next ( ) ; /* Loop through the persisted durable subscriptions */
while ( durableSub != null ) { // we need to restore this item stream
durableSub . initializeNonPersistent ( _baseDestinationHandler ) ; // Increment the count of refStreams on the parentMsgStream
_pubsubMessageItemStream . incrementReferenceStreamCount ( ) ; boolean valid = checkDurableSubStillValid ( durableSub ) ; if ( valid ) { // Create a new ConsumerDispatcher for this durable subscription with the
// recovered state item
configureDurableSubscription ( durableSub ) ; // defect 257231
// we need to ensure that unrestored msgRefs ( due to in - doubt transactions )
// are initialized with the CD and RefStream call backs
Collection unrestoredMsgCollection = durableSub . clearUnrestoredMessages ( ) ; if ( unrestoredMsgCollection != null ) { Iterator indoubtMessages = unrestoredMsgCollection . iterator ( ) ; while ( indoubtMessages . hasNext ( ) ) { MessageItemReference itemRef = ( MessageItemReference ) _baseDestinationHandler . findById ( ( ( Long ) indoubtMessages . next ( ) ) . longValue ( ) ) ; if ( itemRef != null ) { durableSub . registerListeners ( itemRef ) ; } } } } /* Get the next subscription in the itemstream */
durableSub = ( DurableSubscriptionItemStream ) subCursor . next ( ) ; } // Loop round if more subscriptions to recover
subCursor . finished ( ) ; if ( TraceComponent . isAnyTracingEnabled ( ) && tc . isEntryEnabled ( ) ) SibTr . exit ( tc , "reconstituteDurableSubscriptions" ) ; |
public class MD5Checksum { /** * a byte array to a HEX string */
public static String getMD5Checksum ( Resource res ) throws Exception { } } | byte [ ] b = createChecksum ( res ) ; String result = "" ; for ( int i = 0 ; i < b . length ; i ++ ) { result += Integer . toString ( ( b [ i ] & 0xff ) + 0x100 , 16 ) . substring ( 1 ) ; } return result ; |
public class AbstractInvocationFuture { /** * this method should not be needed ; but there is a difference between client and server how it handles async throwables */
protected Throwable unwrap ( Throwable throwable ) { } } | if ( throwable instanceof ExecutionException && throwable . getCause ( ) != null ) { return throwable . getCause ( ) ; } return throwable ; |
public class ListInputsRequestMarshaller { /** * Marshall the given parameter object . */
public void marshall ( ListInputsRequest listInputsRequest , ProtocolMarshaller protocolMarshaller ) { } } | if ( listInputsRequest == null ) { throw new SdkClientException ( "Invalid argument passed to marshall(...)" ) ; } try { protocolMarshaller . marshall ( listInputsRequest . getMaxResults ( ) , MAXRESULTS_BINDING ) ; protocolMarshaller . marshall ( listInputsRequest . getNextToken ( ) , NEXTTOKEN_BINDING ) ; } catch ( Exception e ) { throw new SdkClientException ( "Unable to marshall request to JSON: " + e . getMessage ( ) , e ) ; } |
public class CacheManager { /** * Retrieve upper left and lower right points ( exclusive ) corresponding to the tiles coverage for
* the selected zoom level .
* @ param pBB the given bounding box
* @ param pZoomLevel the given zoom level
* @ return the { @ link Rect } reflecting the tiles coverage */
public static Rect getTilesRect ( final BoundingBox pBB , final int pZoomLevel ) { } } | final int mapTileUpperBound = 1 << pZoomLevel ; final int right = MapView . getTileSystem ( ) . getTileXFromLongitude ( pBB . getLonEast ( ) , pZoomLevel ) ; final int bottom = MapView . getTileSystem ( ) . getTileYFromLatitude ( pBB . getLatSouth ( ) , pZoomLevel ) ; final int left = MapView . getTileSystem ( ) . getTileXFromLongitude ( pBB . getLonWest ( ) , pZoomLevel ) ; final int top = MapView . getTileSystem ( ) . getTileYFromLatitude ( pBB . getLatNorth ( ) , pZoomLevel ) ; int width = right - left + 1 ; // handling the modulo
if ( width <= 0 ) { width += mapTileUpperBound ; } int height = bottom - top + 1 ; // handling the modulo
if ( height <= 0 ) { height += mapTileUpperBound ; } return new Rect ( left , top , left + width - 1 , top + height - 1 ) ; |
public class DynamicByteArray { /** * Write out a range of this dynamic array to an output stream .
* @ param out the stream to write to
* @ param offset the first offset to write
* @ param length the number of bytes to write
* @ throws IOException */
public void write ( OutputStream out , int offset , int length ) throws IOException { } } | data . getBytes ( offset , out , length ) ; |
public class CombinedWriter { /** * { @ inheritDoc } */
@ Override public UberBucket readUber ( ) throws TTIOException { } } | Future < UberBucket > secondReturn = mService . submit ( new Callable < UberBucket > ( ) { @ Override public UberBucket call ( ) throws Exception { return mSecondWriter . readUber ( ) ; } } ) ; UberBucket returnVal = mFirstWriter . readUber ( ) ; try { if ( returnVal == null ) { return secondReturn . get ( ) ; } else { return returnVal ; } } catch ( ExecutionException | InterruptedException exc ) { throw new TTIOException ( exc ) ; } |
public class SymmetryAxes { /** * Get the indices of participating repeats in cyclic form .
* Each inner list gives a set of equivalent repeats and should have length
* equal to the order of the axis ' operator .
* @ param level
* @ param firstRepeat
* @ return */
public List < List < Integer > > getRepeatsCyclicForm ( int level , int firstRepeat ) { } } | Axis axis = axes . get ( level ) ; int m = getNumRepeats ( level + 1 ) ; // size of the children
int d = axis . getOrder ( ) ; // degree of this node
int n = m * d ; // number of repeats included
if ( firstRepeat % n != 0 ) { throw new IllegalArgumentException ( String . format ( "Repeat %d cannot start a block at level %s of this tree" , firstRepeat , level ) ) ; } if ( axis . getSymmType ( ) == SymmetryType . OPEN ) { n -= m ; // leave off last child for open symm
} List < List < Integer > > repeats = new ArrayList < > ( m ) ; for ( int i = 0 ; i < m ; i ++ ) { List < Integer > cycle = new ArrayList < > ( d ) ; for ( int j = 0 ; j < d ; j ++ ) { cycle . add ( firstRepeat + i + j * m ) ; } repeats . add ( cycle ) ; } return repeats ; |
public class RollupConfig { /** * Makes sure each of the rollup tables exists
* @ param tsdb The TSDB to use for fetching the HBase client */
public void ensureTablesExist ( final TSDB tsdb ) { } } | final List < Deferred < Object > > deferreds = new ArrayList < Deferred < Object > > ( forward_intervals . size ( ) * 2 ) ; for ( RollupInterval interval : forward_intervals . values ( ) ) { deferreds . add ( tsdb . getClient ( ) . ensureTableExists ( interval . getTemporalTable ( ) ) ) ; deferreds . add ( tsdb . getClient ( ) . ensureTableExists ( interval . getGroupbyTable ( ) ) ) ; } try { Deferred . group ( deferreds ) . joinUninterruptibly ( ) ; } catch ( DeferredGroupException e ) { throw new RuntimeException ( e . getCause ( ) ) ; } catch ( InterruptedException e ) { LOG . warn ( "Interrupted" , e ) ; Thread . currentThread ( ) . interrupt ( ) ; } catch ( Exception e ) { throw new RuntimeException ( "Unexpected exception" , e ) ; } |
public class HashIntSet { /** * { @ inheritDoc } */
@ Override public boolean retainAll ( IntSet c ) { } } | if ( c == null || c . isEmpty ( ) ) { return false ; } boolean res = false ; for ( int i = 0 ; i < cells . length ; i ++ ) { if ( cells [ i ] >= 0 && ! c . contains ( cells [ i ] ) ) { cells [ i ] = REMOVED ; res = true ; size -- ; } } if ( res ) { modCount ++ ; } return res ; |
public class VersionsImpl { /** * Exports a LUIS application to JSON format .
* @ param appId The application ID .
* @ param versionId The version ID .
* @ throws IllegalArgumentException thrown if parameters fail the validation
* @ return the observable to the LuisApp object */
public Observable < ServiceResponse < LuisApp > > exportWithServiceResponseAsync ( UUID appId , String versionId ) { } } | if ( this . client . endpoint ( ) == null ) { throw new IllegalArgumentException ( "Parameter this.client.endpoint() is required and cannot be null." ) ; } if ( appId == null ) { throw new IllegalArgumentException ( "Parameter appId is required and cannot be null." ) ; } if ( versionId == null ) { throw new IllegalArgumentException ( "Parameter versionId is required and cannot be null." ) ; } String parameterizedHost = Joiner . on ( ", " ) . join ( "{Endpoint}" , this . client . endpoint ( ) ) ; return service . export ( appId , versionId , this . client . acceptLanguage ( ) , parameterizedHost , this . client . userAgent ( ) ) . flatMap ( new Func1 < Response < ResponseBody > , Observable < ServiceResponse < LuisApp > > > ( ) { @ Override public Observable < ServiceResponse < LuisApp > > call ( Response < ResponseBody > response ) { try { ServiceResponse < LuisApp > clientResponse = exportDelegate ( response ) ; return Observable . just ( clientResponse ) ; } catch ( Throwable t ) { return Observable . error ( t ) ; } } } ) ; |
public class WCheckBoxSelectExample { /** * WCheckBoxSelect layout options These examples show the various ways to lay out the options in a WCheckBoxSelect
* NOTE : the default ( if no buttonLayout is set ) is LAYOUT _ STACKED . adds a WCheckBoxSelect with LAYOUT _ FLAT */
private void addFlatSelectExample ( ) { } } | add ( new WHeading ( HeadingLevel . H3 , "WCheckBoxSelect with flat layout" ) ) ; add ( new ExplanatoryText ( "Setting the layout to FLAT will make thecheck boxes be rendered in a horizontal line. They will wrap when they reach" + " the edge of the parent container." ) ) ; final WCheckBoxSelect select = new WCheckBoxSelect ( "australian_state" ) ; select . setToolTip ( "Make a selection" ) ; select . setButtonLayout ( WCheckBoxSelect . LAYOUT_FLAT ) ; add ( select ) ; |
public class Configuration { /** * Constructs a mapping of configuration and includes all properties that
* start with the specified configuration prefix . Property names in the
* mapping are trimmed to remove the configuration prefix .
* @ param confPrefix configuration prefix
* @ return mapping of configuration properties with prefix stripped */
public Map < String , String > getPropsWithPrefix ( String confPrefix ) { } } | Properties props = getProps ( ) ; Enumeration e = props . propertyNames ( ) ; Map < String , String > configMap = new HashMap < > ( ) ; String name = null ; while ( e . hasMoreElements ( ) ) { name = ( String ) e . nextElement ( ) ; if ( name . startsWith ( confPrefix ) ) { String value = props . getProperty ( name ) ; name = name . substring ( confPrefix . length ( ) ) ; configMap . put ( name , value ) ; } } return configMap ; |
public class GenericBoJdbcDao { /** * Fetch list of existing BOs from storage by id .
* @ param conn
* @ param idList
* @ return
* @ since 0.8.1 */
@ SuppressWarnings ( "unchecked" ) protected T [ ] get ( Connection conn , BoId ... idList ) { } } | T [ ] result = ( T [ ] ) Array . newInstance ( typeClass , idList != null ? idList . length : 0 ) ; if ( idList != null ) { for ( int i = 0 ; i < idList . length ; i ++ ) { result [ i ] = get ( conn , idList [ i ] ) ; } } return result ; |
public class Fingerprint { /** * Trim off references to non - existent builds and jobs , thereby making the fingerprint smaller .
* @ return true
* if this record was modified .
* @ throws IOException Save failure */
public synchronized boolean trim ( ) throws IOException { } } | boolean modified = false ; for ( Entry < String , RangeSet > e : new Hashtable < > ( usages ) . entrySet ( ) ) { // copy because we mutate
Job j = Jenkins . getInstance ( ) . getItemByFullName ( e . getKey ( ) , Job . class ) ; if ( j == null ) { // no such job any more . recycle the record
modified = true ; usages . remove ( e . getKey ( ) ) ; continue ; } Run firstBuild = j . getFirstBuild ( ) ; if ( firstBuild == null ) { // no builds . recycle the whole record
modified = true ; usages . remove ( e . getKey ( ) ) ; continue ; } RangeSet cur = e . getValue ( ) ; // builds that are around without the keepLog flag on are normally clustered together ( in terms of build # )
// so our basic strategy is to discard everything up to the first ephemeral build , except those builds
// that are marked as kept
RangeSet kept = new RangeSet ( ) ; Run r = firstBuild ; while ( r != null && r . isKeepLog ( ) ) { kept . add ( r . getNumber ( ) ) ; r = r . getNextBuild ( ) ; } if ( r == null ) { // all the build records are permanently kept ones , so we ' ll just have to keep ' kept ' out of whatever currently in ' cur '
modified |= cur . retainAll ( kept ) ; } else { // otherwise we are ready to discard [ 0 , r . number ) except those marked as ' kept '
RangeSet discarding = new RangeSet ( new Range ( - 1 , r . getNumber ( ) ) ) ; discarding . removeAll ( kept ) ; modified |= cur . removeAll ( discarding ) ; } if ( cur . isEmpty ( ) ) { usages . remove ( e . getKey ( ) ) ; modified = true ; } } if ( modified ) { if ( logger . isLoggable ( Level . FINE ) ) { logger . log ( Level . FINE , "Saving trimmed {0}" , getFingerprintFile ( md5sum ) ) ; } save ( ) ; } return modified ; |
public class AbstractResilienceStrategy { /** * Called when the cache failed to recover from a failing store operation on a list of keys .
* @ param keys
* @ param because exception thrown by the failing operation
* @ param cleanup all the exceptions that occurred during cleanup */
protected void inconsistent ( Iterable < ? extends K > keys , StoreAccessException because , StoreAccessException ... cleanup ) { } } | pacedErrorLog ( "Ehcache keys {} in possible inconsistent state" , keys , because ) ; |
public class Partitioner { /** * Adjust a watermark based on watermark type
* @ param baseWatermark the original watermark
* @ param watermarkType Watermark Type
* @ return the adjusted watermark value */
private static long adjustWatermark ( String baseWatermark , WatermarkType watermarkType ) { } } | long result = ConfigurationKeys . DEFAULT_WATERMARK_VALUE ; switch ( watermarkType ) { case SIMPLE : result = SimpleWatermark . adjustWatermark ( baseWatermark , 0 ) ; break ; case DATE : result = DateWatermark . adjustWatermark ( baseWatermark , 0 ) ; break ; case HOUR : result = HourWatermark . adjustWatermark ( baseWatermark , 0 ) ; break ; case TIMESTAMP : result = TimestampWatermark . adjustWatermark ( baseWatermark , 0 ) ; break ; } return result ; |
public class DocumentSet { /** * Returns the index of the provided key in the document set , or - 1 if the document key is not
* present in the set ; */
int indexOf ( ResourcePath key ) { } } | QueryDocumentSnapshot document = keyIndex . get ( key ) ; if ( document == null ) { return - 1 ; } return sortedSet . indexOf ( document ) ; |
public class NioController { /** * Cancel selection key */
public void closeSelectionKey ( SelectionKey key ) { } } | if ( key . attachment ( ) instanceof Session ) { Session session = ( Session ) key . attachment ( ) ; if ( session != null ) { session . close ( ) ; } } |
public class Win32File { /** * Wraps a { @ code File } array , possibly pointing to Windows symbolic links
* ( { @ code . lnk } files ) in { @ code Win32Lnk } s .
* @ param pPaths an array of { @ code File } s , possibly pointing to Windows
* symbolic link files .
* May be { @ code null } , in which case { @ code null } is returned .
* @ return { @ code pPaths } , with any { @ code File } representing a Windows
* symbolic link ( { @ code . lnk } file ) wrapped in a { @ code Win32Lnk } . */
public static File [ ] wrap ( File [ ] pPaths ) { } } | if ( IS_WINDOWS ) { for ( int i = 0 ; pPaths != null && i < pPaths . length ; i ++ ) { pPaths [ i ] = wrap ( pPaths [ i ] ) ; } } return pPaths ; |
public class JMRandom { /** * Build random int stream int stream .
* @ param streamSize the stream size
* @ param random the random
* @ param exclusiveBound the exclusive bound
* @ return the int stream */
public static IntStream buildRandomIntStream ( int streamSize , Random random , int exclusiveBound ) { } } | return buildRandomIntStream ( streamSize , ( ) -> random . nextInt ( exclusiveBound ) ) ; |
public class DatabaseManager { /** * Loads the JDBC driver specified in { @ code jdbcDriver } and establishes a JBDC connection with the given { @ code connectionString } , { @ code username } and
* { @ code password } .
* @ param jdbcDriver The fully - qualified class name of the JDBC driver
* @ param connectionString The JDBC connection string
* @ param username The extractor username
* @ param password The extractor password
* @ return The established JDBc connection
* @ throws ClassNotFoundException Gets thrown when loading the driver fails
* @ throws SQLException Gets thrown when connection to the extractor fails */
public static Connection connectToDatabase ( final String jdbcDriver , final String connectionString , final String username , final String password ) throws ClassNotFoundException , SQLException { } } | // Load jdbc driver
try { LOG . debug ( "Trying to load jdbc driver " + jdbcDriver ) ; Class . forName ( jdbcDriver ) ; LOG . info ( "Successfully loaded jdbc driver" ) ; } catch ( ClassNotFoundException e ) { LOG . error ( "Could not load jdbc driver with name " + jdbcDriver ) ; throw e ; } // get connection
try { LOG . debug ( "Connecting to extractor " + connectionString ) ; final Connection conn = DriverManager . getConnection ( connectionString , username , password ) ; LOG . info ( "Successfully connected to extractor" ) ; return conn ; } catch ( SQLException e ) { LOG . error ( "Could not connect to extractor" , e ) ; throw e ; } |
public class LayoutRESTController { /** * A REST call to get a json feed of the current users layout . Intent was to provide a layout
* document without per - tab information for mobile device rendering .
* @ param request The servlet request . Utilized to get the users instance and eventually there
* layout
* @ param tab The tab name of which you would like to filter ; optional ; if not provided , will
* return entire layout .
* @ return json feed of the layout
* @ deprecated Use / api / v4-3 / dlm / layout . json . It has much more information about portlets and
* includes regions and breakout per tab */
@ Deprecated @ RequestMapping ( value = "/layoutDoc" , method = RequestMethod . GET ) public ModelAndView getRESTController ( HttpServletRequest request , @ RequestParam ( value = "tab" , required = false ) String tab ) { } } | final IPerson person = personManager . getPerson ( request ) ; List < LayoutPortlet > portlets = new ArrayList < LayoutPortlet > ( ) ; try { final IUserInstance ui = userInstanceManager . getUserInstance ( request ) ; final IUserPreferencesManager upm = ui . getPreferencesManager ( ) ; final IUserProfile profile = upm . getUserProfile ( ) ; final DistributedUserLayout userLayout = userLayoutStore . getUserLayout ( person , profile ) ; Document document = userLayout . getLayout ( ) ; NodeList portletNodes = null ; if ( tab != null ) { NodeList folders = document . getElementsByTagName ( "folder" ) ; for ( int i = 0 ; i < folders . getLength ( ) ; i ++ ) { Node node = folders . item ( i ) ; if ( tab . equalsIgnoreCase ( node . getAttributes ( ) . getNamedItem ( "name" ) . getNodeValue ( ) ) ) { TabListOfNodes tabNodes = new TabListOfNodes ( ) ; tabNodes . addAllChannels ( node . getChildNodes ( ) ) ; portletNodes = tabNodes ; break ; } } } else { portletNodes = document . getElementsByTagName ( "channel" ) ; } for ( int i = 0 ; i < portletNodes . getLength ( ) ; i ++ ) { try { NamedNodeMap attributes = portletNodes . item ( i ) . getAttributes ( ) ; IPortletDefinition def = portletDao . getPortletDefinitionByFname ( attributes . getNamedItem ( "fname" ) . getNodeValue ( ) ) ; LayoutPortlet portlet = new LayoutPortlet ( def ) ; portlet . setNodeId ( attributes . getNamedItem ( "ID" ) . getNodeValue ( ) ) ; // get alt max URL
String alternativeMaximizedLink = def . getAlternativeMaximizedLink ( ) ; if ( alternativeMaximizedLink != null ) { portlet . setUrl ( alternativeMaximizedLink ) ; portlet . setAltMaxUrl ( true ) ; } else { // get the maximized URL for this portlet
final IPortalUrlBuilder portalUrlBuilder = urlProvider . getPortalUrlBuilderByLayoutNode ( request , attributes . getNamedItem ( "ID" ) . getNodeValue ( ) , UrlType . RENDER ) ; final IPortletWindowId targetPortletWindowId = portalUrlBuilder . getTargetPortletWindowId ( ) ; if ( targetPortletWindowId != null ) { final IPortletUrlBuilder portletUrlBuilder = portalUrlBuilder . getPortletUrlBuilder ( targetPortletWindowId ) ; portletUrlBuilder . setWindowState ( WindowState . MAXIMIZED ) ; } portlet . setUrl ( portalUrlBuilder . getUrlString ( ) ) ; portlet . setAltMaxUrl ( false ) ; } portlets . add ( portlet ) ; } catch ( Exception e ) { log . warn ( "Exception construction JSON representation of mobile portlet" , e ) ; } } ModelAndView mv = new ModelAndView ( ) ; mv . addObject ( "layout" , portlets ) ; mv . setViewName ( "json" ) ; return mv ; } catch ( Exception e ) { log . error ( "Error retrieving user layout document" , e ) ; } return null ; |
public class DragonexBaseService { /** * current date in utc as http header */
protected static String utcNow ( ) { } } | Calendar calendar = Calendar . getInstance ( ) ; SimpleDateFormat dateFormat = new SimpleDateFormat ( "EEE, dd MMM yyyy HH:mm:ss z" , Locale . US ) ; dateFormat . setTimeZone ( TimeZone . getTimeZone ( "GMT" ) ) ; return dateFormat . format ( calendar . getTime ( ) ) ; // return java . time . format . DateTimeFormatter . RFC _ 1123 _ DATE _ TIME . format (
// ZonedDateTime . now ( ZoneOffset . UTC ) ) ; |
public class POIUtils { /** * セルに設定されている書式を取得する 。
* @ since 1.1
* @ param cell セルのインスタンス 。
* @ param cellFormatter セルのフォーマッタ
* @ return 書式が設定されていない場合は 、 空文字を返す 。
* cellがnullの場合も空文字を返す 。
* 標準の書式の場合も空文字を返す 。 */
public static String getCellFormatPattern ( final Cell cell , final CellFormatter cellFormatter ) { } } | if ( cell == null ) { return "" ; } String pattern = cellFormatter . getPattern ( cell ) ; if ( pattern . equalsIgnoreCase ( "general" ) ) { return "" ; } return pattern ; |
public class BindingManager { /** * Returns the { @ link MethodBuilder } that adds methods to the class spec */
MethodBuilder getMethoddBuilder ( Element element ) { } } | MethodBuilder methodBuilder = new MethodBuilder ( messager , element ) ; methodBuilder . setBindingManager ( this ) ; return methodBuilder ; |
public class AntClassLoader { /** * Finds a system class ( which should be loaded from the same classloader
* as the Ant core ) .
* For JDK 1.1 compatibility , this uses the findSystemClass method if
* no parent classloader has been specified .
* @ param name The name of the class to be loaded .
* Must not be < code > null < / code > .
* @ return the required Class object
* @ exception ClassNotFoundException if the requested class does not exist
* on this loader ' s classpath . */
private Class findBaseClass ( String name ) throws ClassNotFoundException { } } | return parent == null ? findSystemClass ( name ) : parent . loadClass ( name ) ; |
public class HarFileSystem { /** * / * this makes a path qualified in the har filesystem
* ( non - Javadoc )
* @ see org . apache . hadoop . fs . FilterFileSystem # makeQualified (
* org . apache . hadoop . fs . Path ) */
@ Override public Path makeQualified ( Path path ) { } } | // make sure that we just get the
// path component
Path fsPath = path ; if ( ! path . isAbsolute ( ) ) { fsPath = new Path ( archivePath , path ) ; } URI tmpURI = fsPath . toUri ( ) ; // change this to Har uri
return new Path ( uri . getScheme ( ) , harAuth , tmpURI . getPath ( ) ) ; |
public class KerberosTicketUtils { /** * TGS must have the server principal of the form " krbtgt / FOO @ FOO " .
* @ return true or false */
private static boolean isTicketGrantingServerPrincipal ( KerberosPrincipal principal ) { } } | if ( principal == null ) { return false ; } if ( principal . getName ( ) . equals ( "krbtgt/" + principal . getRealm ( ) + "@" + principal . getRealm ( ) ) ) { return true ; } return false ; |
public class FunctionTypeBuilder { /** * Check whether a type is resolvable in the future
* If this has a supertype that hasn ' t been resolved yet , then we can assume
* this type will be OK once the super type resolves .
* @ param objectType
* @ return true if objectType is resolvable in the future */
private static boolean hasMoreTagsToResolve ( ObjectType objectType ) { } } | checkArgument ( objectType . isUnknownType ( ) ) ; FunctionType ctor = objectType . getConstructor ( ) ; if ( ctor != null ) { // interface extends interfaces
for ( ObjectType interfaceType : ctor . getExtendedInterfaces ( ) ) { if ( ! interfaceType . isResolved ( ) ) { return true ; } } } if ( objectType . getImplicitPrototype ( ) != null ) { // constructor extends class
return ! objectType . getImplicitPrototype ( ) . isResolved ( ) ; } return false ; |
public class NestedMappingHandler { /** * Checks only get accessor of this field .
* @ param xml used to check xml configuration
* @ param aClass class where is the field with the nested mapping
* @ param nestedField field with nested mapping */
private static MappedField checkGetAccessor ( XML xml , Class < ? > aClass , Field nestedField ) { } } | MappedField field = new MappedField ( nestedField ) ; xml . fillMappedField ( aClass , field ) ; Annotation . fillMappedField ( aClass , field ) ; verifyGetterMethods ( aClass , field ) ; return field ; |
public class CommerceDiscountUsageEntryLocalServiceBaseImpl { /** * Adds the commerce discount usage entry to the database . Also notifies the appropriate model listeners .
* @ param commerceDiscountUsageEntry the commerce discount usage entry
* @ return the commerce discount usage entry that was added */
@ Indexable ( type = IndexableType . REINDEX ) @ Override public CommerceDiscountUsageEntry addCommerceDiscountUsageEntry ( CommerceDiscountUsageEntry commerceDiscountUsageEntry ) { } } | commerceDiscountUsageEntry . setNew ( true ) ; return commerceDiscountUsageEntryPersistence . update ( commerceDiscountUsageEntry ) ; |
public class SetPrefsTransformation { /** * / * ( non - Javadoc )
* @ see com . abubusoft . kripton . processor . sharedprefs . transform . AbstractGeneratedPrefsTransform # generateReadProperty ( com . squareup . javapoet . MethodSpec . Builder , java . lang . String , com . squareup . javapoet . TypeName , java . lang . String , com . abubusoft . kripton . processor . sharedprefs . model . PrefsProperty , boolean ) */
@ Override public void generateReadProperty ( Builder methodBuilder , String preferenceName , TypeName beanClass , String beanName , PrefsProperty property , boolean readAll , ReadType readType ) { } } | boolean isStringSet = isStringSet ( property ) ; String tempPre = "" ; String tempPost = "" ; String tempPreDefaultValue = "" ; String tempPostDefaultValue = "" ; if ( readAll ) { methodBuilder . beginControlFlow ( "" ) ; } if ( property . hasTypeAdapter ( ) ) { // this comment is needed to include $ T for PrefsTypeAdapterUtils
methodBuilder . addComment ( "Use $T to convert objects" , PrefsTypeAdapterUtils . class ) ; tempPre = String . format ( "%s.getAdapter(%s.class).toJava(" , PrefsTypeAdapterUtils . class . getSimpleName ( ) , TypeUtility . className ( property . typeAdapter . adapterClazz ) . simpleName ( ) ) ; tempPost = ")" ; tempPreDefaultValue = String . format ( "%s.getAdapter(%s.class).toData(" , PrefsTypeAdapterUtils . class . getSimpleName ( ) , TypeUtility . className ( property . typeAdapter . adapterClazz ) . simpleName ( ) ) ; tempPostDefaultValue = ")" ; } if ( isStringSet ) { methodBuilder . addStatement ( "$T<String> temp=$L.getStringSet($S, " + tempPreDefaultValue + DEFAULT_BEAN_NAME + "." + getter ( property ) + tempPostDefaultValue + ")" , Set . class , preferenceName , property . getPreferenceKey ( ) ) ; if ( readAll ) { methodBuilder . addCode ( setter ( beanClass , beanName , property ) + ( ! property . isPublicField ( ) && beanName != null ? "(" : "=" ) ) ; } switch ( readType ) { case NONE : break ; case RETURN : methodBuilder . addCode ( "return " ) ; break ; case VALUE : methodBuilder . addCode ( "$T _value=" , property . getPropertyType ( ) . getTypeName ( ) ) ; break ; } methodBuilder . addCode ( tempPre ) ; ParameterizedTypeName typeName ; if ( property . hasTypeAdapter ( ) ) { typeName = ( ParameterizedTypeName ) TypeUtility . typeName ( property . typeAdapter . dataType ) ; } else { typeName = ( ParameterizedTypeName ) TypeUtility . typeName ( property . getElement ( ) . asType ( ) ) ; } if ( TypeUtility . isEquals ( typeName . rawType , Set . class . getCanonicalName ( ) ) ) { methodBuilder . addCode ( "temp" ) ; } else { methodBuilder . addCode ( "new $T<String>(temp)" , typeName . rawType ) ; } methodBuilder . addCode ( tempPost ) ; if ( readAll ) { methodBuilder . addCode ( ( ! property . isPublicField ( ) ? ")" : "" ) ) ; } methodBuilder . addCode ( ";\n" ) ; } else { methodBuilder . addStatement ( "String temp=$L.getString($S, null)" , preferenceName , property . getPreferenceKey ( ) ) ; if ( readAll ) { methodBuilder . addCode ( setter ( beanClass , beanName , property ) + ( ! property . isPublicField ( ) ? "(" : "=" ) + "" ) ; } switch ( readType ) { case NONE : break ; case RETURN : methodBuilder . addCode ( "return " ) ; break ; case VALUE : methodBuilder . addCode ( "$T _value=" , property . getPropertyType ( ) . getTypeName ( ) ) ; break ; } methodBuilder . addCode ( "$T.hasText(temp) ? " , StringUtils . class ) ; methodBuilder . addCode ( "parse$L(temp)" , formatter . convert ( property . getName ( ) ) ) ; methodBuilder . addCode ( ": $L" , getter ( DEFAULT_BEAN_NAME , beanClass , property ) ) ; if ( readAll ) { methodBuilder . addCode ( ! property . isPublicField ( ) && beanName != null ? ")" : "" ) ; } methodBuilder . addCode ( ";\n" ) ; } if ( readAll ) { methodBuilder . endControlFlow ( ) ; } |
public class InputCaptionsMarshaller { /** * Marshall the given parameter object . */
public void marshall ( InputCaptions inputCaptions , ProtocolMarshaller protocolMarshaller ) { } } | if ( inputCaptions == null ) { throw new SdkClientException ( "Invalid argument passed to marshall(...)" ) ; } try { protocolMarshaller . marshall ( inputCaptions . getMergePolicy ( ) , MERGEPOLICY_BINDING ) ; protocolMarshaller . marshall ( inputCaptions . getCaptionSources ( ) , CAPTIONSOURCES_BINDING ) ; } catch ( Exception e ) { throw new SdkClientException ( "Unable to marshall request to JSON: " + e . getMessage ( ) , e ) ; } |
public class BinaryAttachment { /** * The attachment ' s data .
* @ return The attachment ' s data . */
public InputStream getData ( ) { } } | if ( data != null ) { return new ByteArrayInputStream ( data ) ; } else if ( dataStream != null ) { return dataStream ; } else { throw new IllegalStateException ( "Either the byte[] or the stream mustn't be null at this point." ) ; } |
public class Weld { /** * Bootstraps a new Weld SE container with the current container id ( generated value if not set through { @ link # containerId ( String ) } ) .
* The container must be shut down properly when an application is stopped . Applications are encouraged to use the try - with - resources statement or invoke
* { @ link WeldContainer # shutdown ( ) } explicitly .
* However , a shutdown hook is also registered during initialization so that all running containers are shut down automatically when a program exits or VM
* is terminated . This means that it ' s not necessary to implement the shutdown logic in a class where a main method is used to start the container .
* @ return the Weld container
* @ see # enableDiscovery ( )
* @ see WeldContainer # shutdown ( ) */
public WeldContainer initialize ( ) { } } | // If also building a synthetic bean archive or the implicit scan is enabled , the check for beans . xml is not necessary
if ( ! isSyntheticBeanArchiveRequired ( ) && ! isImplicitScanEnabled ( ) && resourceLoader . getResource ( WeldDeployment . BEANS_XML ) == null ) { throw CommonLogger . LOG . missingBeansXml ( ) ; } final WeldBootstrap bootstrap = new WeldBootstrap ( ) ; final Deployment deployment = createDeployment ( resourceLoader , bootstrap ) ; final ExternalConfigurationBuilder configurationBuilder = new ExternalConfigurationBuilder ( ) // weld - se uses CommonForkJoinPoolExecutorServices by default
. add ( EXECUTOR_THREAD_POOL_TYPE . get ( ) , COMMON . toString ( ) ) // weld - se uses relaxed construction by default
. add ( ConfigurationKey . RELAXED_CONSTRUCTION . get ( ) , true ) // allow optimized cleanup by default
. add ( ConfigurationKey . ALLOW_OPTIMIZED_CLEANUP . get ( ) , isEnabled ( ALLOW_OPTIMIZED_CLEANUP , true ) ) ; for ( Entry < String , Object > property : properties . entrySet ( ) ) { String key = property . getKey ( ) ; if ( SHUTDOWN_HOOK_SYSTEM_PROPERTY . equals ( key ) || ARCHIVE_ISOLATION_SYSTEM_PROPERTY . equals ( key ) || DEV_MODE_SYSTEM_PROPERTY . equals ( key ) || SCAN_CLASSPATH_ENTRIES_SYSTEM_PROPERTY . equals ( key ) || JAVAX_ENTERPRISE_INJECT_SCAN_IMPLICIT . equals ( key ) ) { continue ; } configurationBuilder . add ( key , property . getValue ( ) ) ; } deployment . getServices ( ) . add ( ExternalConfiguration . class , configurationBuilder . build ( ) ) ; final String containerId = this . containerId != null ? this . containerId : UUID . randomUUID ( ) . toString ( ) ; bootstrap . startContainer ( containerId , Environments . SE , deployment ) ; final WeldContainer weldContainer = WeldContainer . startInitialization ( containerId , deployment , bootstrap ) ; try { bootstrap . startInitialization ( ) ; bootstrap . deployBeans ( ) ; bootstrap . validateBeans ( ) ; bootstrap . endInitialization ( ) ; WeldContainer . endInitialization ( weldContainer , isEnabled ( SHUTDOWN_HOOK_SYSTEM_PROPERTY , true ) ) ; initializedContainers . put ( containerId , weldContainer ) ; } catch ( Throwable e ) { // Discard the container if a bootstrap problem occurs , e . g . validation error
WeldContainer . discard ( weldContainer . getId ( ) ) ; throw e ; } return weldContainer ; |
public class PgStatement { /** * Returns true if query is unlikely to be reused .
* @ param cachedQuery to check ( null if current query )
* @ return true if query is unlikely to be reused */
protected boolean isOneShotQuery ( CachedQuery cachedQuery ) { } } | if ( cachedQuery == null ) { return true ; } cachedQuery . increaseExecuteCount ( ) ; if ( ( mPrepareThreshold == 0 || cachedQuery . getExecuteCount ( ) < mPrepareThreshold ) && ! getForceBinaryTransfer ( ) ) { return true ; } return false ; |
public class MailAccountManager { /** * Gets the set of reserved mail accounts for the current thread .
* @ return the set of reserved mail accounts */
public Set < MailAccount > getReservedMailAccountsForCurrentThread ( ) { } } | lock . lock ( ) ; try { Map < MailAccount , ThreadReservationKeyWrapper > accountsForThread = filterValues ( usedAccounts , new CurrentThreadWrapperPredicate ( ) ) ; return ImmutableSet . copyOf ( accountsForThread . keySet ( ) ) ; } finally { lock . unlock ( ) ; } |
public class ProducerService { /** * Returns a producer of the specified class .
* @ param clazz Class of the producer sought .
* @ return The producer , or null if not found . */
private IMessageProducer findRegisteredProducer ( Class < ? > clazz ) { } } | for ( IMessageProducer producer : producers ) { if ( clazz . isInstance ( producer ) ) { return producer ; } } return null ; |
public class ResultSetIterator { @ Override public boolean hasNext ( ) { } } | try { if ( this . resultSet == null ) return false ; else if ( ! this . resultSet . next ( ) ) { this . dispose ( ) ; return false ; } return true ; } catch ( SQLException e ) { dispose ( ) ; throw new CommunicationException ( e . getMessage ( ) , e ) ; } |
public class Ifc4PackageImpl { /** * < ! - - begin - user - doc - - >
* < ! - - end - user - doc - - >
* @ generated */
@ Override public EClass getIfcShadingDevice ( ) { } } | if ( ifcShadingDeviceEClass == null ) { ifcShadingDeviceEClass = ( EClass ) EPackage . Registry . INSTANCE . getEPackage ( Ifc4Package . eNS_URI ) . getEClassifiers ( ) . get ( 593 ) ; } return ifcShadingDeviceEClass ; |
public class DateUtil { /** * 修改日期为某个时间字段四舍五入时间
* @ param calendar { @ link Calendar }
* @ param dateField 时间字段
* @ return 原 { @ link Calendar }
* @ since 4.5.7 */
public static Calendar round ( Calendar calendar , DateField dateField ) { } } | return DateModifier . modify ( calendar , dateField . getValue ( ) , ModifyType . ROUND ) ; |
public class MPDServerStatistics { /** * Returns the statistics of the requested statistics element .
* See < code > StatList < / code > for a list of possible items returned
* by getServerStat .
* @ param stat the statistic desired
* @ return the requested statistic */
private Number getStat ( StatList stat ) { } } | LocalDateTime now = this . clock . now ( ) ; if ( now . minusSeconds ( this . expiryInterval ) . isAfter ( this . responseDate ) ) { this . responseDate = now ; this . cachedResponse = commandExecutor . sendCommand ( serverProperties . getStats ( ) ) ; } for ( String line : cachedResponse ) { if ( line . startsWith ( stat . getStatPrefix ( ) ) ) { try { return ( NumberFormat . getInstance ( ) ) . parse ( line . substring ( stat . getStatPrefix ( ) . length ( ) ) . trim ( ) ) ; } catch ( ParseException e ) { LOGGER . warn ( "Could not parse server statistic" , e ) ; return 0 ; } } } return 0 ; |
public class UIViewRoot { /** * < p class = " changed _ added _ 2_0 " > < span
* class = " changed _ deleted _ 2_0 _ rev _ a
* changed _ modified _ 2_1 " > Return < / span > an unmodifiable
* < code > List < / code > of { @ link UIComponent } s for the provided
* < code > target < / code > agrument . Each < code > component < / code > in the
* < code > List < / code > is assumed to represent a resource
* instance . < / p >
* < div class = " changed _ added _ 2_0 " >
* < p > The default implementation must use an algorithm equivalent to the
* the following . < / p >
* < ul >
* < li > Locate the facet for the < code > component < / code > by calling < code > getFacet ( ) < / code > using
* < code > target < / code > as the argument . < / li >
* < li > If the facet is not found , create the facet by calling
* < code > context . getApplication ( ) . createComponent ( ) . < / code > < span
* class = " changed _ modified _ 2_0 _ rev _ a " > The argument to this method
* must refer to a component that extends { @ link UIPanel } and
* overrides the < code > encodeAll ( ) < / code > method to take no action .
* This is necessary to prevent component resources from being
* inadvertently rendered . < / span > < / li >
* < ul >
* < li class = " changed _ modified _ 2_1 " > Set the < code > id < / code > of the
* facet to be a string created by prepending the literal string
* & # 8220 ; < code > javax _ faces _ location _ < / code > & # 8221 ; ( without the
* quotes ) to the value of the < code > target < / code > argument < / li >
* < li > Add the facet to the facets < code > Map < / code > using < code > target < / code > as the key < / li >
* < / ul >
* < li > return the children of the facet < / li >
* < / ul >
* < / div >
* @ param target The name of the facet for which the components will be returned .
* @ return A < code > List < / code > of { @ link UIComponent } children of
* the facet with the name < code > target < / code > . If no children are
* found for the facet , return < code > Collections . emptyList ( ) < / code > .
* @ throws NullPointerException if < code > target < / code > or
* < code > context < / code > is < code > null < / code >
* @ since 2.0 */
public List < UIComponent > getComponentResources ( FacesContext context , String target ) { } } | if ( target == null ) { throw new NullPointerException ( ) ; } List < UIComponent > resources = getComponentResources ( context , target , false ) ; return ( ( resources != null ) ? resources : Collections . < UIComponent > emptyList ( ) ) ; |
public class ReflectionUtils { /** * Get inherited fields of a given type .
* @ param type the type to introspect
* @ return list of inherited fields */
public static List < Field > getInheritedFields ( Class < ? > type ) { } } | List < Field > inheritedFields = new ArrayList < > ( ) ; while ( type . getSuperclass ( ) != null ) { Class < ? > superclass = type . getSuperclass ( ) ; inheritedFields . addAll ( asList ( superclass . getDeclaredFields ( ) ) ) ; type = superclass ; } return inheritedFields ; |
public class H2ONode { /** * Stop tracking a remote task , because we got an ACKACK . */
void remove_task_tracking ( int task ) { } } | RPC . RPCCall rpc = _work . get ( task ) ; if ( rpc == null ) return ; // Already stopped tracking
// Atomically attempt to remove the ' dt ' . If we win , we are the sole
// thread running the dt . onAckAck . Also helps GC : the ' dt ' is done ( sent
// to client and we received the ACKACK ) , but the rpc might need to stick
// around a long time - and the dt might be big .
DTask dt = rpc . _dt ; // The existing DTask , if any
if ( dt != null && RPC . RPCCall . CAS_DT . compareAndSet ( rpc , dt , null ) ) { assert rpc . _computed : "Still not done #" + task + " " + dt . getClass ( ) + " from " + rpc . _client ; AckAckTimeOutThread . PENDING . remove ( rpc ) ; dt . onAckAck ( ) ; // One - time call on stop - tracking
} // Roll - up as many done RPCs as we can , into the _ removed _ task _ ids list
while ( true ) { int t = _removed_task_ids . get ( ) ; // Last already - removed ID
RPC . RPCCall rpc2 = _work . get ( t + 1 ) ; // RPC of 1st not - removed ID
if ( rpc2 == null || rpc2 . _dt != null || ! _removed_task_ids . compareAndSet ( t , t + 1 ) ) break ; // Stop when we hit in - progress tasks
_work . remove ( t + 1 ) ; // Else we can remove the tracking now
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.