signature stringlengths 43 39.1k | implementation stringlengths 0 450k |
|---|---|
public class FJIterate { /** * Same effect as { @ link Iterate # groupBy ( Iterable , Function ) } ,
* but executed in parallel batches , and writing output into a SynchronizedPutFastListMultimap . */
public static < K , V , R extends MutableMultimap < K , V > > MutableMultimap < K , V > groupBy ( Iterable < V > iterable , Function < ? super V , ? extends K > function , R concurrentMultimap ) { } } | return FJIterate . groupBy ( iterable , function , concurrentMultimap , FJIterate . DEFAULT_MIN_FORK_SIZE ) ; |
public class ClassDescriptor { /** * add an Extent class to the current descriptor
* @ param newExtentClassName name of the class to add */
public void addExtentClass ( String newExtentClassName ) { } } | extentClassNames . add ( newExtentClassName ) ; if ( m_repository != null ) m_repository . addExtent ( newExtentClassName , this ) ; |
public class GedDocumentMongoToGedObjectConverterVisitor { /** * { @ inheritDoc } */
@ Override public void visit ( final RootDocumentMongo document ) { } } | final Root root = new Root ( "Root" ) ; root . setFilename ( document . getFilename ( ) ) ; root . setDbName ( document . getDbName ( ) ) ; setGedObject ( root ) ; |
public class AbstractParamContainerPanel { /** * This method initializes jPanel1
* @ return javax . swing . JPanel */
private JPanel getJPanel1 ( ) { } } | if ( jPanel1 == null ) { jPanel1 = new JPanel ( ) ; jPanel1 . setLayout ( new CardLayout ( ) ) ; jPanel1 . setBorder ( javax . swing . BorderFactory . createEmptyBorder ( 0 , 0 , 0 , 0 ) ) ; jPanel1 . add ( getJScrollPane1 ( ) , getJScrollPane1 ( ) . getName ( ) ) ; } return jPanel1 ; |
public class FilePublisher { /** * Unregisters all instances of fileSubscriber found .
* @ param fileSubscriber the fileSubscriber to unregister */
public void unregister ( FileSubscriber fileSubscriber ) { } } | for ( IdentificationSet < FileSubscriber > subList : fileSubscribers . values ( ) ) { subList . remove ( fileSubscriber ) ; } defaultFileSubscribers . remove ( fileSubscriber ) ; |
public class QueryColumnImpl { /** * touch the given line on the column at given row
* @ param row
* @ return new row or existing
* @ throws DatabaseException */
public Object touch ( int row ) { } } | if ( row < 1 || row > size ) return NullSupportHelper . full ( ) ? null : "" ; Object o = data [ row - 1 ] ; if ( o != null ) return o ; return setEL ( row , new StructImpl ( ) ) ; |
public class SimpleDateFormat { /** * Override readObject .
* See http : / / docs . oracle . com / javase / 6 / docs / api / java / io / ObjectInputStream . html */
private void readObject ( ObjectInputStream stream ) throws IOException , ClassNotFoundException { } } | stream . defaultReadObject ( ) ; int capitalizationSettingValue = ( serialVersionOnStream > 1 ) ? stream . readInt ( ) : - 1 ; // / CLOVER : OFF
// don ' t have old serial data to test with
if ( serialVersionOnStream < 1 ) { // didn ' t have defaultCenturyStart field
defaultCenturyBase = System . currentTimeMillis ( ) ; } // / CLOVER : ON
else { // fill in dependent transient field
parseAmbiguousDatesAsAfter ( defaultCenturyStart ) ; } serialVersionOnStream = currentSerialVersion ; locale = getLocale ( ULocale . VALID_LOCALE ) ; if ( locale == null ) { // ICU4J 3.6 or older versions did not have UFormat locales
// in the serialized data . This is just for preventing the
// worst case scenario . . .
locale = ULocale . getDefault ( Category . FORMAT ) ; } initLocalZeroPaddingNumberFormat ( ) ; setContext ( DisplayContext . CAPITALIZATION_NONE ) ; if ( capitalizationSettingValue >= 0 ) { for ( DisplayContext context : DisplayContext . values ( ) ) { if ( context . value ( ) == capitalizationSettingValue ) { setContext ( context ) ; break ; } } } // if serialized pre - 56 update & turned off partial match switch to new enum value
if ( getBooleanAttribute ( DateFormat . BooleanAttribute . PARSE_PARTIAL_MATCH ) == false ) { setBooleanAttribute ( DateFormat . BooleanAttribute . PARSE_PARTIAL_LITERAL_MATCH , false ) ; } parsePattern ( ) ; |
public class SSHLauncher { /** * Called to terminate the SSH connection . Used liberally when we back out from an error . */
private void cleanupConnection ( TaskListener listener ) { } } | // we might be called multiple times from multiple finally / catch block ,
if ( connection != null ) { connection . close ( ) ; connection = null ; listener . getLogger ( ) . println ( Messages . SSHLauncher_ConnectionClosed ( getTimestamp ( ) ) ) ; } |
public class IndexingConfiguration { /** * Check if the indexes can be shared . Currently only " ram " based indexes don ' t allow any sort of
* sharing .
* @ return false if the index is ram only and thus not shared */
public boolean indexShareable ( ) { } } | TypedProperties properties = properties ( ) ; boolean hasRamDirectoryProvider = false ; for ( Object objKey : properties . keySet ( ) ) { String key = ( String ) objKey ; if ( key . endsWith ( DIRECTORY_PROVIDER_KEY ) ) { String directoryImplementationName = String . valueOf ( properties . get ( key ) ) . trim ( ) ; if ( LOCAL_HEAP_DIRECTORY_PROVIDER . equalsIgnoreCase ( directoryImplementationName ) || RAM_DIRECTORY_PROVIDER . equalsIgnoreCase ( directoryImplementationName ) || LOCAL_HEAP_DIRECTORY_PROVIDER_FQN . equals ( directoryImplementationName ) ) { hasRamDirectoryProvider = true ; } else { return true ; } } } return ! hasRamDirectoryProvider ; |
public class EnvironmentsInner { /** * List environments in a given environment setting .
* @ param nextPageLink The NextLink from the previous successful call to List operation .
* @ throws IllegalArgumentException thrown if parameters fail the validation
* @ return the observable to the PagedList & lt ; EnvironmentInner & gt ; object */
public Observable < Page < EnvironmentInner > > listNextAsync ( final String nextPageLink ) { } } | return listNextWithServiceResponseAsync ( nextPageLink ) . map ( new Func1 < ServiceResponse < Page < EnvironmentInner > > , Page < EnvironmentInner > > ( ) { @ Override public Page < EnvironmentInner > call ( ServiceResponse < Page < EnvironmentInner > > response ) { return response . body ( ) ; } } ) ; |
public class RestClient { /** * Returns the contents of an attachment
* @ param assetId
* The ID of the asset owning the attachment
* @ param attachmentId
* The ID of the attachment
* @ return The input stream for the attachment
* @ throws IOException
* @ throws RequestFailureException */
@ Override public InputStream getAttachment ( final Asset asset , final Attachment attachment ) throws IOException , BadVersionException , RequestFailureException { } } | // accept license for type CONTENT
HttpURLConnection connection ; if ( attachment . getType ( ) == AttachmentType . CONTENT ) { connection = createHttpURLConnection ( attachment . getUrl ( ) + "?license=agree" ) ; } else { connection = createHttpURLConnection ( attachment . getUrl ( ) ) ; } // If the attachment was a link and we have a basic auth userid + password specified
// we are attempting to access the files staged from a protected site so authorise for it
if ( attachment . getLinkType ( ) == AttachmentLinkType . DIRECT ) { if ( ( loginInfo . getAttachmentBasicAuthUserId ( ) != null ) && ( loginInfo . getAttachmentBasicAuthPassword ( ) != null ) ) { String userpass = loginInfo . getAttachmentBasicAuthUserId ( ) + ":" + loginInfo . getAttachmentBasicAuthPassword ( ) ; String basicAuth = "Basic " + encode ( userpass . getBytes ( Charset . forName ( "UTF-8" ) ) ) ; connection . setRequestProperty ( "Authorization" , basicAuth ) ; } } connection . setRequestMethod ( "GET" ) ; testResponseCode ( connection ) ; return connection . getInputStream ( ) ; |
public class NavMeshQuery { /** * Gets the path leading to the specified end node . */
private List < Long > getPathToNode ( Node endNode ) { } } | List < Long > path = new ArrayList < > ( ) ; // Reverse the path .
Node curNode = endNode ; do { path . add ( 0 , curNode . id ) ; curNode = m_nodePool . getNodeAtIdx ( curNode . pidx ) ; } while ( curNode != null ) ; return path ; |
public class ChannelWrapper { /** * Initialize a digest on this channel .
* @ param algorithm the digest algorithm to use in computing the hash
* @ return reference to the new key added to the consumers
* @ throws NoSuchAlgorithmException if the given algorithm does not exist */
public Key < byte [ ] > start ( final String algorithm ) throws NoSuchAlgorithmException { } } | final MessageDigest digest = MessageDigest . getInstance ( algorithm ) ; final Key < byte [ ] > object = new Key < byte [ ] > ( ) ; consumers . put ( object , new Consumer < byte [ ] > ( ) { public void consume ( final ByteBuffer buffer ) { try { digest . update ( buffer ) ; } catch ( Exception e ) { throw new RuntimeException ( e ) ; } } public byte [ ] finish ( ) { try { return digest . digest ( ) ; } catch ( Exception e ) { throw new RuntimeException ( e ) ; } } } ) ; return object ; |
public class CommerceOrderNotePersistenceImpl { /** * Returns the commerce order note with the primary key or returns < code > null < / code > if it could not be found .
* @ param primaryKey the primary key of the commerce order note
* @ return the commerce order note , or < code > null < / code > if a commerce order note with the primary key could not be found */
@ Override public CommerceOrderNote fetchByPrimaryKey ( Serializable primaryKey ) { } } | Serializable serializable = entityCache . getResult ( CommerceOrderNoteModelImpl . ENTITY_CACHE_ENABLED , CommerceOrderNoteImpl . class , primaryKey ) ; if ( serializable == nullModel ) { return null ; } CommerceOrderNote commerceOrderNote = ( CommerceOrderNote ) serializable ; if ( commerceOrderNote == null ) { Session session = null ; try { session = openSession ( ) ; commerceOrderNote = ( CommerceOrderNote ) session . get ( CommerceOrderNoteImpl . class , primaryKey ) ; if ( commerceOrderNote != null ) { cacheResult ( commerceOrderNote ) ; } else { entityCache . putResult ( CommerceOrderNoteModelImpl . ENTITY_CACHE_ENABLED , CommerceOrderNoteImpl . class , primaryKey , nullModel ) ; } } catch ( Exception e ) { entityCache . removeResult ( CommerceOrderNoteModelImpl . ENTITY_CACHE_ENABLED , CommerceOrderNoteImpl . class , primaryKey ) ; throw processException ( e ) ; } finally { closeSession ( session ) ; } } return commerceOrderNote ; |
public class GrailsClassUtils { /** * Checks to see if a class is marked with @ grails . artefact . Enhanced and if the enhancedFor
* attribute of the annotation contains a specific feature name
* @ param controllerClass The class to inspect
* @ param featureName The name of a feature to check for
* @ return true if controllerClass is marked with Enhanced and the enhancedFor attribute includes featureName , otherwise returns false
* @ see Enhanced
* @ see Enhanced # enhancedFor ( ) */
public static Boolean hasBeenEnhancedForFeature ( final Class < ? > controllerClass , final String featureName ) { } } | boolean hasBeenEnhanced = false ; final Enhanced enhancedAnnotation = controllerClass . getAnnotation ( Enhanced . class ) ; if ( enhancedAnnotation != null ) { final String [ ] enhancedFor = enhancedAnnotation . enhancedFor ( ) ; if ( enhancedFor != null ) { hasBeenEnhanced = GrailsArrayUtils . contains ( enhancedFor , featureName ) ; } } return hasBeenEnhanced ; |
public class VirtualMachineScaleSetExtensionsInner { /** * The operation to create or update an extension .
* @ param resourceGroupName The name of the resource group .
* @ param vmScaleSetName The name of the VM scale set where the extension should be create or updated .
* @ param vmssExtensionName The name of the VM scale set extension .
* @ param extensionParameters Parameters supplied to the Create VM scale set Extension operation .
* @ throws IllegalArgumentException thrown if parameters fail the validation
* @ throws CloudException thrown if the request is rejected by server
* @ throws RuntimeException all other wrapped checked exceptions if the request fails to be sent
* @ return the VirtualMachineScaleSetExtensionInner object if successful . */
public VirtualMachineScaleSetExtensionInner beginCreateOrUpdate ( String resourceGroupName , String vmScaleSetName , String vmssExtensionName , VirtualMachineScaleSetExtensionInner extensionParameters ) { } } | return beginCreateOrUpdateWithServiceResponseAsync ( resourceGroupName , vmScaleSetName , vmssExtensionName , extensionParameters ) . toBlocking ( ) . single ( ) . body ( ) ; |
public class FaceDetail { /** * The emotions detected on the face , and the confidence level in the determination . For example , HAPPY , SAD , and
* ANGRY .
* @ param emotions
* The emotions detected on the face , and the confidence level in the determination . For example , HAPPY , SAD ,
* and ANGRY . */
public void setEmotions ( java . util . Collection < Emotion > emotions ) { } } | if ( emotions == null ) { this . emotions = null ; return ; } this . emotions = new java . util . ArrayList < Emotion > ( emotions ) ; |
public class ActionSupport { /** * 获得action消息 < br > */
public final List < String > getActionMessages ( ) { } } | Flash flash = getFlash ( ) ; ActionMessages messages = ( ActionMessages ) flash . get ( Flash . MESSAGES ) ; if ( null == messages ) return Collections . emptyList ( ) ; else return messages . getMessages ( ) ; |
public class CouchbaseManager { /** * Creates a { @ link Pair } containing a { @ link PasswordAuthenticator } and a { @ link List } of ( cluster ) nodes from configuration properties or a URI
* This method verifies if the variable hostOrKey has " couchbase " as a scheme if not then it consider hostOrKey as a configuration key
* If it ' s a URI then the credentials should be defined according to the URI specifications
* @ param hostOrKey a configuration key ( in the neo4j . conf file ) or a URI
* @ return */
protected static Pair < PasswordAuthenticator , List < String > > getConnectionObjectsFromHostOrKey ( String hostOrKey ) { } } | // Check if hostOrKey is really a host , if it ' s a host , then we let only one host ! !
URI singleHostURI = checkAndGetURI ( hostOrKey ) ; // No scheme defined so it ' s considered a configuration key
if ( singleHostURI == null || singleHostURI . getScheme ( ) == null ) { return getConnectionObjectsFromConfigurationKey ( hostOrKey ) ; } else { return getConnectionObjectsFromHost ( singleHostURI ) ; } |
public class ExcelDataProviderImpl { /** * This method fetches a specific row from an excel sheet which can be identified using a key and returns the data
* as an Object which can be cast back into the user ' s actual data type .
* @ param userObj
* An Object into which data is to be packed into
* @ param key
* A string that represents a key to search for in the excel sheet
* @ param isExternalCall
* A boolean that helps distinguish internally if the call is being made internally or by the user . For
* external calls the index of the row would need to be bumped up , because the first row is to be ignored
* always .
* @ return An Object which can be cast into the user ' s actual data type . */
protected Object getSingleExcelRow ( Object userObj , String key , boolean isExternalCall ) { } } | logger . entering ( new Object [ ] { userObj , key , isExternalCall } ) ; Class < ? > cls ; try { cls = Class . forName ( userObj . getClass ( ) . getName ( ) ) ; } catch ( ClassNotFoundException e ) { throw new DataProviderException ( "Unable to find class of type + '" + userObj . getClass ( ) . getName ( ) + "'" , e ) ; } int rowIndex = excelReader . getRowIndex ( cls . getSimpleName ( ) , key ) ; if ( rowIndex == - 1 ) { throw new DataProviderException ( "Row with key '" + key + "' is not found" ) ; } Object object = getSingleExcelRow ( userObj , rowIndex , isExternalCall ) ; logger . exiting ( object ) ; return object ; |
public class Types { /** * Get the simple name of a possibly nested { @ link Class } .
* @ param type
* @ param separator
* @ return String */
public static String getSimpleName ( Class < ? > type , String separator ) { } } | final StringBuilder buf = new StringBuilder ( ) ; Class < ? > c = type ; while ( c != null ) { if ( buf . length ( ) > 0 && separator != null ) { buf . insert ( 0 , separator ) ; } buf . insert ( 0 , c . getSimpleName ( ) ) ; c = c . getEnclosingClass ( ) ; } return buf . toString ( ) ; |
public class IntegerRadixSortExperimental { /** * From https : / / github . com / gorset / radix / blob / master / Radix . java */
public static void sort ( final int [ ] array , int offset , int end , int shift , final Queue < Future < ? > > futures ) { } } | final int BITS_PER_PASS ; if ( ENABLE_CONCURRENCY && ( shift + R_BITS_PER_PASS ) == 32 ) { BITS_PER_PASS = FIRST_BITS_PER_PASS ; } else { BITS_PER_PASS = R_BITS_PER_PASS ; } final int PASS_SIZE = 1 << BITS_PER_PASS ; final int PASS_MASK = PASS_SIZE - 1 ; int [ ] last = new int [ PASS_SIZE ] ; final int [ ] pointer = new int [ PASS_SIZE ] ; for ( int x = offset ; x < end ; ++ x ) { ++ last [ ( ( array [ x ] + UNSIGNED_OFFSET ) >> shift ) & PASS_MASK ] ; } last [ 0 ] += offset ; pointer [ 0 ] = offset ; for ( int x = 1 ; x < PASS_SIZE ; ++ x ) { pointer [ x ] = last [ x - 1 ] ; last [ x ] += last [ x - 1 ] ; } for ( int x = 0 ; x < PASS_SIZE ; ++ x ) { while ( pointer [ x ] != last [ x ] ) { int value = array [ pointer [ x ] ] ; int y = ( ( value + UNSIGNED_OFFSET ) >> shift ) & PASS_MASK ; while ( x != y ) { int temp = array [ pointer [ y ] ] ; array [ pointer [ y ] ++ ] = value ; value = temp ; y = ( ( value + UNSIGNED_OFFSET ) >> shift ) & PASS_MASK ; } array [ pointer [ x ] ++ ] = value ; } } if ( shift > 0 ) { // TODO : Additional criteria
shift -= BITS_PER_PASS ; for ( int x = 0 ; x < PASS_SIZE ; ++ x ) { final int size = x > 0 ? ( pointer [ x ] - pointer [ x - 1 ] ) : ( pointer [ 0 ] - offset ) ; if ( size > 64 ) { final int newOffset = pointer [ x ] - size ; final int newEnd = pointer [ x ] ; if ( ENABLE_CONCURRENCY && ( newEnd - newOffset ) >= MIN_CONCURRENCY_SIZE ) { final int finalShift = shift ; futures . add ( executor . submit ( new Runnable ( ) { @ Override public void run ( ) { sort ( array , newOffset , newEnd , finalShift , futures ) ; } } ) ) ; } else { sort ( array , newOffset , newEnd , shift , futures ) ; } } else if ( size > 1 ) { insertionSort ( array , pointer [ x ] - size , pointer [ x ] ) ; // Arrays . sort ( array , pointer [ x ] - size , pointer [ x ] ) ;
} } } |
public class HFClient { /** * Create a new orderer .
* @ param name name of Orderer .
* @ param grpcURL url location of orderer grpc or grpcs protocol .
* @ param properties < p >
* Supported properties
* < ul >
* < li > pemFile - File location for x509 pem certificate for SSL . < / li >
* < li > pemBytes - byte array for x509 pem certificates for SSL < / li >
* < li > trustServerCertificate - boolean ( true / false ) override CN to match pemFile certificate - - for development only .
* If the pemFile has the target server ' s certificate ( instead of a CA Root certificate ) ,
* instruct the TLS client to trust the CN value of the certificate in the pemFile ,
* useful in development to get past default server hostname verification during
* TLS handshake , when the server host name does not match the certificate .
* < / li >
* < li > clientKeyFile - File location for private key pem for mutual TLS < / li >
* < li > clientCertFile - File location for x509 pem certificate for mutual TLS < / li >
* < li > clientKeyBytes - Private key pem bytes for mutual TLS < / li >
* < li > clientCertBytes - x509 pem certificate bytes for mutual TLS < / li >
* < li > sslProvider - Specify the SSL provider , openSSL or JDK . < / li >
* < li > negotiationType - Specify the type of negotiation , TLS or plainText . < / li >
* < li > hostnameOverride - Specify the certificates CN - - for development only .
* If the pemFile does not represent the server certificate , use this property to specify the URI authority
* ( a . k . a hostname ) expected in the target server ' s certificate . This is required to get past default server
* hostname verifications during TLS handshake .
* < / li >
* < li >
* grpc . NettyChannelBuilderOption . & lt ; methodName & gt ; where methodName is any method on
* grpc ManagedChannelBuilder . If more than one argument to the method is needed then the
* parameters need to be supplied in an array of Objects .
* < / li >
* < li >
* ordererWaitTimeMilliSecs Time to wait in milliseconds for the
* Orderer to accept requests before timing out . The default is two seconds .
* < / li >
* < / ul >
* @ return The orderer .
* @ throws InvalidArgumentException */
public Orderer newOrderer ( String name , String grpcURL , Properties properties ) throws InvalidArgumentException { } } | clientCheck ( ) ; return Orderer . createNewInstance ( name , grpcURL , properties ) ; |
public class JwtAccessTokenConverter { /** * Get the verification key for the token signatures .
* @ return the key used to verify tokens */
public Map < String , String > getKey ( ) { } } | Map < String , String > result = new LinkedHashMap < String , String > ( ) ; result . put ( "alg" , signer . algorithm ( ) ) ; result . put ( "value" , verifierKey ) ; return result ; |
public class Option { /** * If the option requires access to a port , then this DB security group allows access to the port .
* @ return If the option requires access to a port , then this DB security group allows access to the port . */
public java . util . List < DBSecurityGroupMembership > getDBSecurityGroupMemberships ( ) { } } | if ( dBSecurityGroupMemberships == null ) { dBSecurityGroupMemberships = new com . amazonaws . internal . SdkInternalList < DBSecurityGroupMembership > ( ) ; } return dBSecurityGroupMemberships ; |
public class FaxServiceImp { /** * ( non - Javadoc )
* @ see com . popbill . api . FaxService # cancelReserveRN ( java . lang . String , java . lang . String ) */
@ Override public Response cancelReserveRN ( String corpNum , String requestNum ) throws PopbillException { } } | return cancelReserveRN ( corpNum , requestNum , null ) ; |
public class RestXPathProcessor { /** * Getting part of the XML based on a XPath query
* @ param resourceName
* where the content should be extracted
* @ param query
* contains XPath query
* @ param rId
* To response the resource with a restid for each node ( < code > true < / code > ) or without (
* < code > false < / code > ) .
* @ param doRevision
* The revision of the requested resource . If < code > null < / code > ,
* than response the latest revision .
* @ param output
* The OutputStream reference which have to be modified and
* returned
* @ param doNodeId
* specifies whether node id should be shown
* @ param doWrap
* output of result elements
* @ throws TTException */
public void getXpathResource ( final String resourceName , final long rId , final String query , final boolean doNodeId , final Long doRevision , final OutputStream output , final boolean doWrap ) throws TTException { } } | // work around because of query root char ' / '
String qQuery = query ; if ( query . charAt ( 0 ) == '/' ) qQuery = "." . concat ( query ) ; ISession session = null ; INodeReadTrx rtx = null ; try { if ( mDatabase . existsResource ( resourceName ) ) { session = mDatabase . getSession ( new SessionConfiguration ( resourceName , StandardSettings . KEY ) ) ; // Creating a transaction
if ( doRevision == null ) { rtx = new NodeReadTrx ( session . beginBucketRtx ( session . getMostRecentVersion ( ) ) ) ; } else { rtx = new NodeReadTrx ( session . beginBucketRtx ( doRevision ) ) ; } final boolean exist = rtx . moveTo ( rId ) ; if ( exist ) { final AbsAxis axis = new XPathAxis ( rtx , qQuery ) ; if ( doWrap ) { output . write ( beginResult . getBytes ( ) ) ; for ( final long key : axis ) { WorkerHelper . serializeXML ( session , output , false , doNodeId , key , doRevision ) . call ( ) ; } output . write ( endResult . getBytes ( ) ) ; } else { for ( final long key : axis ) { WorkerHelper . serializeXML ( session , output , false , doNodeId , key , doRevision ) . call ( ) ; } } } else { throw new WebApplicationException ( 404 ) ; } } } catch ( final Exception globExcep ) { throw new WebApplicationException ( globExcep , Response . Status . INTERNAL_SERVER_ERROR ) ; } |
public class ArgUtils { /** * 値がnullでないかどうか検証する 。
* @ param arg 検証対象の値
* @ param name 検証対象の引数の名前
* @ throws IllegalArgumentException { @ literal arg = = null . } */
public static void notNull ( final Object arg , final String name ) { } } | if ( arg == null ) { throw new IllegalArgumentException ( String . format ( "%s should not be null." , name ) ) ; } |
public class Ifc2x3tc1PackageImpl { /** * < ! - - begin - user - doc - - >
* < ! - - end - user - doc - - >
* @ generated */
public EClass getIfcRelFlowControlElements ( ) { } } | if ( ifcRelFlowControlElementsEClass == null ) { ifcRelFlowControlElementsEClass = ( EClass ) EPackage . Registry . INSTANCE . getEPackage ( Ifc2x3tc1Package . eNS_URI ) . getEClassifiers ( ) . get ( 474 ) ; } return ifcRelFlowControlElementsEClass ; |
public class ImageVerifyCode { /** * 得到验证码byte array
* @ param width
* @ param high
* @ param verifyCode
* @ return
* @ throws IOException */
public static byte [ ] encode2ByteArray ( int width , int high , String verifyCode ) throws IOException { } } | width = width < 1 ? defaultWidth : width ; high = high < 1 ? defaultHigh : high ; ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream ( ) ; outputImage ( width , high , byteArrayOutputStream , verifyCode ) ; return byteArrayOutputStream . toByteArray ( ) ; |
public class lbvserver { /** * Use this API to fetch lbvserver resource of given name . */
public static lbvserver get ( nitro_service service , String name ) throws Exception { } } | lbvserver obj = new lbvserver ( ) ; obj . set_name ( name ) ; lbvserver response = ( lbvserver ) obj . get_resource ( service ) ; return response ; |
public class EpollDatagramChannelConfig { /** * If { @ code true } is used < a href = " http : / / man7 . org / linux / man - pages / man7 / ip . 7 . html " > IP _ FREEBIND < / a > is enabled ,
* { @ code false } for disable it . Default is disabled . */
public EpollDatagramChannelConfig setFreeBind ( boolean freeBind ) { } } | try { ( ( EpollDatagramChannel ) channel ) . socket . setIpFreeBind ( freeBind ) ; return this ; } catch ( IOException e ) { throw new ChannelException ( e ) ; } |
public class TransactionalProtocolHandlers { /** * Execute blocking for a prepared result .
* @ param operation the operation to execute
* @ param client the protocol client
* @ return the prepared operation
* @ throws IOException
* @ throws InterruptedException */
public static TransactionalProtocolClient . PreparedOperation < TransactionalProtocolClient . Operation > executeBlocking ( final ModelNode operation , TransactionalProtocolClient client ) throws IOException , InterruptedException { } } | final BlockingQueueOperationListener < TransactionalProtocolClient . Operation > listener = new BlockingQueueOperationListener < > ( ) ; client . execute ( listener , operation , OperationMessageHandler . DISCARD , OperationAttachments . EMPTY ) ; return listener . retrievePreparedOperation ( ) ; |
public class GrokParser { /** * Parses the given XML stream and returns the contained assembly data .
* @ param inputStream an InputStream containing assembly data
* @ return the assembly data
* @ throws GrokParseException thrown if the XML cannot be parsed */
public AssemblyData parse ( InputStream inputStream ) throws GrokParseException { } } | try ( InputStream schema = FileUtils . getResourceAsStream ( GROK_SCHEMA ) ) { final GrokHandler handler = new GrokHandler ( ) ; final SAXParser saxParser = XmlUtils . buildSecureSaxParser ( schema ) ; final XMLReader xmlReader = saxParser . getXMLReader ( ) ; xmlReader . setErrorHandler ( new GrokErrorHandler ( ) ) ; xmlReader . setContentHandler ( handler ) ; try ( Reader reader = new InputStreamReader ( inputStream , StandardCharsets . UTF_8 ) ) { final InputSource in = new InputSource ( reader ) ; xmlReader . parse ( in ) ; return handler . getAssemblyData ( ) ; } } catch ( ParserConfigurationException | FileNotFoundException ex ) { LOGGER . debug ( "" , ex ) ; throw new GrokParseException ( ex ) ; } catch ( SAXException ex ) { if ( ex . getMessage ( ) . contains ( "Cannot find the declaration of element 'assembly'." ) ) { throw new GrokParseException ( "Malformed grok xml?" , ex ) ; } else { LOGGER . debug ( "" , ex ) ; throw new GrokParseException ( ex ) ; } } catch ( IOException ex ) { LOGGER . debug ( "" , ex ) ; throw new GrokParseException ( ex ) ; } |
public class PtrFrameLayout { /** * please DO REMEMBER resume the hook
* @ param hook */
public void setRefreshCompleteHook ( PtrUIHandlerHook hook ) { } } | mRefreshCompleteHook = hook ; hook . setResumeAction ( new Runnable ( ) { @ Override public void run ( ) { if ( DEBUG ) { PtrCLog . d ( LOG_TAG , "mRefreshCompleteHook resume." ) ; } notifyUIRefreshComplete ( true ) ; } } ) ; |
public class AmazonTranscribeClient { /** * Returns information about a transcription job . To see the status of the job , check the
* < code > TranscriptionJobStatus < / code > field . If the status is < code > COMPLETED < / code > , the job is finished and you
* can find the results at the location specified in the < code > TranscriptionFileUri < / code > field .
* @ param getTranscriptionJobRequest
* @ return Result of the GetTranscriptionJob operation returned by the service .
* @ throws BadRequestException
* Your request didn ' t pass one or more validation tests . For example , if the transcription you ' re trying to
* delete doesn ' t exist or if it is in a non - terminal state ( for example , it ' s " in progress " ) . See the
* exception < code > Message < / code > field for more information .
* @ throws LimitExceededException
* Either you have sent too many requests or your input file is too long . Wait before you resend your
* request , or use a smaller file and resend the request .
* @ throws InternalFailureException
* There was an internal error . Check the error message and try your request again .
* @ throws NotFoundException
* We can ' t find the requested resource . Check the name and try your request again .
* @ sample AmazonTranscribe . GetTranscriptionJob
* @ see < a href = " http : / / docs . aws . amazon . com / goto / WebAPI / transcribe - 2017-10-26 / GetTranscriptionJob " target = " _ top " > AWS
* API Documentation < / a > */
@ Override public GetTranscriptionJobResult getTranscriptionJob ( GetTranscriptionJobRequest request ) { } } | request = beforeClientExecution ( request ) ; return executeGetTranscriptionJob ( request ) ; |
public class CPDefinitionPersistenceImpl { /** * Removes all the cp definitions where groupId = & # 63 ; from the database .
* @ param groupId the group ID */
@ Override public void removeByGroupId ( long groupId ) { } } | for ( CPDefinition cpDefinition : findByGroupId ( groupId , QueryUtil . ALL_POS , QueryUtil . ALL_POS , null ) ) { remove ( cpDefinition ) ; } |
public class AmazonECSClient { /** * Create or update an attribute on an Amazon ECS resource . If the attribute does not exist , it is created . If the
* attribute exists , its value is replaced with the specified value . To delete an attribute , use
* < a > DeleteAttributes < / a > . For more information , see < a
* href = " https : / / docs . aws . amazon . com / AmazonECS / latest / developerguide / task - placement - constraints . html # attributes "
* > Attributes < / a > in the < i > Amazon Elastic Container Service Developer Guide < / i > .
* @ param putAttributesRequest
* @ return Result of the PutAttributes operation returned by the service .
* @ throws ClusterNotFoundException
* The specified cluster could not be found . You can view your available clusters with < a > ListClusters < / a > .
* Amazon ECS clusters are Region - specific .
* @ throws TargetNotFoundException
* The specified target could not be found . You can view your available container instances with
* < a > ListContainerInstances < / a > . Amazon ECS container instances are cluster - specific and Region - specific .
* @ throws AttributeLimitExceededException
* You can apply up to 10 custom attributes per resource . You can view the attributes of a resource with
* < a > ListAttributes < / a > . You can remove existing attributes on a resource with < a > DeleteAttributes < / a > .
* @ throws InvalidParameterException
* The specified parameter is invalid . Review the available parameters for the API request .
* @ sample AmazonECS . PutAttributes
* @ see < a href = " http : / / docs . aws . amazon . com / goto / WebAPI / ecs - 2014-11-13 / PutAttributes " target = " _ top " > AWS API
* Documentation < / a > */
@ Override public PutAttributesResult putAttributes ( PutAttributesRequest request ) { } } | request = beforeClientExecution ( request ) ; return executePutAttributes ( request ) ; |
public class PreparedDeleteCollectionOfObjects { /** * Creates { @ link io . reactivex . Flowable } which will perform Delete Operation and send result to observer .
* Returned { @ link io . reactivex . Flowable } will be " Cold Flowable " , which means that it performs
* delete only after subscribing to it . Also , it emits the result once .
* < dl >
* < dt > < b > Scheduler : < / b > < / dt >
* < dd > Operates on { @ link StorIOSQLite # defaultRxScheduler ( ) } if not { @ code null } . < / dd >
* < / dl >
* @ return non - null { @ link io . reactivex . Flowable } which will perform Delete Operation .
* and send result to observer . */
@ NonNull @ CheckResult @ Override public Flowable < DeleteResults < T > > asRxFlowable ( @ NonNull BackpressureStrategy backpressureStrategy ) { } } | return RxJavaUtils . createFlowable ( storIOSQLite , this , backpressureStrategy ) ; |
public class AbstractSimon { /** * Adds child to this Simon with setting the parent of the child .
* @ param simon future child of this Simon */
final void addChild ( AbstractSimon simon ) { } } | children . add ( simon ) ; simon . setParent ( this ) ; simon . enabled = enabled ; |
public class PseudoWordDependencyContextExtractor { /** * { @ inheritDoc } */
public void processDocument ( BufferedReader document , Wordsi wordsi ) { } } | try { // Handle the context header , if one exists . Context headers are
// assumed to be the first line in a document and to contain an
// integer specifying which line the focus word is on . .
String contextHeader = handleContextHeader ( document ) ; String [ ] contextTokens = contextHeader . split ( "\\s+" ) ; int focusIndex = Integer . parseInt ( contextTokens [ 3 ] ) ; // Extract the dependency trees and skip any that are empty .
DependencyTreeNode [ ] nodes = extractor . readNextTree ( document ) ; if ( nodes . length == 0 ) return ; DependencyTreeNode focusNode = nodes [ focusIndex ] ; // Get the focus word , i . e . , the primary key , and the secondary key .
String focusWord = getPrimaryKey ( focusNode ) ; String secondarykey = pseudoWordMap . get ( focusWord ) ; // Ignore any focus words that have no mapping .
if ( secondarykey == null ) return ; // Ignore any focus words that are unaccepted by Wordsi .
if ( ! acceptWord ( focusNode , contextTokens [ 1 ] , wordsi ) ) return ; // Create a new context vector and send it to the Wordsi model .
SparseDoubleVector focusMeaning = generator . generateContext ( nodes , focusIndex ) ; wordsi . handleContextVector ( secondarykey , focusWord , focusMeaning ) ; // Close up the document .
document . close ( ) ; } catch ( IOException ioe ) { throw new IOError ( ioe ) ; } |
public class JacksonConfiguration { /** * Sets the object mapper features to use .
* @ param mapper The object mapper features */
public void setMapper ( Map < MapperFeature , Boolean > mapper ) { } } | if ( CollectionUtils . isNotEmpty ( mapper ) ) { this . mapper = mapper ; } |
public class PDFDomTree { /** * Generate the global CSS style for the whole document .
* @ return the CSS code used in the generated document header */
protected String createGlobalStyle ( ) { } } | StringBuilder ret = new StringBuilder ( ) ; ret . append ( createFontFaces ( ) ) ; ret . append ( "\n" ) ; ret . append ( defaultStyle ) ; return ret . toString ( ) ; |
public class ActionHandler { /** * 抽取出该方法是为了缩短 handle 方法中的代码量 , 确保获得 JIT 优化 ,
* 方法长度超过 8000 个字节码时 , 将不会被 JIT 编译成二进制码
* 通过开启 java 的 - XX : + PrintCompilation 启动参数得知 , handle ( . . . )
* 方法 ( 73 行代码 ) 已被 JIT 优化 , 优化后的字节码长度为 593 个字节 , 相当于
* 每行代码产生 8.123 个字节 */
private void handleActionException ( String target , HttpServletRequest request , HttpServletResponse response , Action action , ActionException e ) { } } | int errorCode = e . getErrorCode ( ) ; String msg = null ; if ( errorCode == 404 ) { msg = "404 Not Found: " ; } else if ( errorCode == 400 ) { msg = "400 Bad Request: " ; } else if ( errorCode == 401 ) { msg = "401 Unauthorized: " ; } else if ( errorCode == 403 ) { msg = "403 Forbidden: " ; } if ( msg != null ) { if ( log . isWarnEnabled ( ) ) { String qs = request . getQueryString ( ) ; msg = msg + ( qs == null ? target : target + "?" + qs ) ; if ( e . getMessage ( ) != null ) { msg = msg + "\n" + e . getMessage ( ) ; } log . warn ( msg ) ; } } else { if ( log . isErrorEnabled ( ) ) { String qs = request . getQueryString ( ) ; log . error ( errorCode + " Error: " + ( qs == null ? target : target + "?" + qs ) , e ) ; } } e . getErrorRender ( ) . setContext ( request , response , action . getViewPath ( ) ) . render ( ) ; |
public class QueryService { /** * Helper function to return a specification for filtering on one - to - many or many - to - many reference . Usage :
* < pre >
* Specification & lt ; Employee & gt ; specByEmployeeId = buildReferringEntitySpecification ( criteria . getEmployeId ( ) ,
* Project _ . employees , Employee _ . id ) ;
* Specification & lt ; Employee & gt ; specByEmployeeName = buildReferringEntitySpecification ( criteria . getEmployeName ( ) ,
* Project _ . project , Project _ . name ) ;
* < / pre >
* @ param filter the filter object which contains a value , which needs to match or a flag if emptiness is
* checked .
* @ param reference the attribute of the static metamodel for the referring entity .
* @ param valueField the attribute of the static metamodel of the referred entity , where the equality should be
* checked .
* @ param < OTHER > The type of the referenced entity .
* @ param < X > The type of the attribute which is filtered .
* @ return a Specification */
protected < OTHER , X > Specification < ENTITY > buildReferringEntitySpecification ( Filter < X > filter , SetAttribute < ENTITY , OTHER > reference , SingularAttribute < OTHER , X > valueField ) { } } | if ( filter . getEquals ( ) != null ) { return equalsSetSpecification ( reference , valueField , filter . getEquals ( ) ) ; } else if ( filter . getSpecified ( ) != null ) { return byFieldSpecified ( reference , filter . getSpecified ( ) ) ; } return null ; |
public class XMLConfigurationProvider { /** * This method will find all the parameters under this
* < code > paramsElement < / code > and return them as Map < String , String > . For
* example ,
* < pre >
* < result . . . >
* < param name = " param1 " > value1 < / param >
* < param name = " param2 " > value2 < / param >
* < param name = " param3 " > value3 < / param >
* < / result >
* < / pre >
* will returns a Map < String , String > with the following key , value pairs : -
* < ul >
* < li > param1 - value1 < / li >
* < li > param2 - value2 < / li >
* < li > param3 - value3 < / li >
* < / ul >
* @ param paramsElement
* @ return */
private Map < String , Object > getParams ( Element paramsElement ) { } } | LinkedHashMap < String , Object > params = new LinkedHashMap < String , Object > ( ) ; if ( paramsElement == null ) { return params ; } NodeList childNodes = paramsElement . getChildNodes ( ) ; for ( int i = 0 ; i < childNodes . getLength ( ) ; i ++ ) { Node childNode = childNodes . item ( i ) ; if ( ( childNode . getNodeType ( ) == Node . ELEMENT_NODE ) && "param" . equals ( childNode . getNodeName ( ) ) ) { Element paramElement = ( Element ) childNode ; String paramName = paramElement . getAttribute ( "name" ) ; String val = getContent ( paramElement ) ; if ( val . length ( ) > 0 ) { char startChar = val . charAt ( 0 ) ; char endChar = val . charAt ( val . length ( ) - 1 ) ; if ( startChar == '{' && endChar == '}' ) { try { JSONObject o = JSON . parseObject ( val ) ; params . put ( paramName , o ) ; } catch ( JSONException e ) { params . put ( paramName , val ) ; } } else if ( startChar == '[' && endChar == ']' ) { try { JSONArray array = JSON . parseArray ( val ) ; params . put ( paramName , array ) ; } catch ( JSONException e ) { params . put ( paramName , val ) ; } } else { params . put ( paramName , val ) ; } } } } return params ; |
public class SpiderSession { /** * Get the object with the given ID from the given table . Null is returned if there is
* no such object .
* @ param tableName Name of table to get object from . It must belong to this
* session ' s application .
* @ param objectID Object ' s ID .
* @ return { @ link DBObject } containing all of the object ' s scalar and link
* field values , or null if the object does not exist . */
public DBObject getObject ( String tableName , String objectID ) { } } | Utils . require ( ! Utils . isEmpty ( tableName ) , "tableName" ) ; Utils . require ( ! Utils . isEmpty ( objectID ) , "objectID" ) ; TableDefinition tableDef = m_appDef . getTableDef ( tableName ) ; Utils . require ( tableDef != null , "Unknown table for application '%s': %s" , m_appDef . getAppName ( ) , tableName ) ; try { // Send a GET request to " / { application } / { table } / { object ID } "
StringBuilder uri = new StringBuilder ( Utils . isEmpty ( m_restClient . getApiPrefix ( ) ) ? "" : "/" + m_restClient . getApiPrefix ( ) ) ; uri . append ( "/" ) ; uri . append ( Utils . urlEncode ( m_appDef . getAppName ( ) ) ) ; uri . append ( "/" ) ; uri . append ( Utils . urlEncode ( tableName ) ) ; uri . append ( "/" ) ; uri . append ( Utils . urlEncode ( objectID ) ) ; RESTResponse response = m_restClient . sendRequest ( HttpMethod . GET , uri . toString ( ) ) ; m_logger . debug ( "getObject() response: {}" , response . toString ( ) ) ; // If the response is not " OK " , return null .
if ( response . getCode ( ) != HttpCode . OK ) { return null ; } return new DBObject ( ) . parse ( getUNodeResult ( response ) ) ; } catch ( Exception e ) { throw new RuntimeException ( e ) ; } |
public class MoneyAmountStyle { /** * Returns a copy of this style with the specified absolute value setting .
* If this is set to true , the absolute ( unsigned ) value will be output .
* If this is set to false , the signed value will be output .
* Note that when parsing , signs are accepted .
* @ param absValue true to output the absolute value , false for the signed value
* @ return the new instance for chaining , never null */
public MoneyAmountStyle withAbsValue ( boolean absValue ) { } } | if ( this . absValue == absValue ) { return this ; } return new MoneyAmountStyle ( zeroCharacter , positiveCharacter , negativeCharacter , decimalPointCharacter , groupingStyle , groupingCharacter , groupingSize , extendedGroupingSize , forceDecimalPoint , absValue ) ; |
public class AbstractConcept { /** * Default { @ link Comparable # compareTo ( Object ) } implementation that calls
* { @ link # compareToWhenHashCodesEqual ( AbstractConcept ) } if and only if the
* { @ link # hashCode ( ) } values of { @ code this } and { @ code other } are equal .
* @ return a negative integer , zero , or a positive integer as this object is
* less than , equal to , or greater than the specified object . */
public int compareTo ( AbstractConcept other ) { } } | // Need to sort by concrete subclass first , and then by object hashCode
final int meta = getClass ( ) . hashCode ( ) - other . getClass ( ) . hashCode ( ) ; final int quickCompare = hashCode ( ) - other . hashCode ( ) ; int result = 0 == meta ? ( 0 == quickCompare ? compareToWhenHashCodesEqual ( other ) : quickCompare ) : meta ; // If compare result is 0 , then the objects must be equal ( )
assert 0 != result || this . equals ( other ) ; return result ; |
public class VFS { /** * Create and mount a temporary file system , returning a single handle which will unmount and close the filesystem
* when closed .
* @ param mountPoint the point at which the filesystem should be mounted
* @ param tempFileProvider the temporary file provider
* @ return a handle
* @ throws IOException if an error occurs */
public static Closeable mountTemp ( VirtualFile mountPoint , TempFileProvider tempFileProvider ) throws IOException { } } | boolean ok = false ; final TempDir tempDir = tempFileProvider . createTempDir ( "tmpfs" ) ; try { final MountHandle handle = doMount ( new RealFileSystem ( tempDir . getRoot ( ) ) , mountPoint , tempDir ) ; ok = true ; return handle ; } finally { if ( ! ok ) { VFSUtils . safeClose ( tempDir ) ; } } |
public class WTree { /** * Return the item ids that have been expanded .
* Note - Only used for when the tree is in LAZY mode
* @ return the previously expanded item ids */
protected Set < String > getPrevExpandedRows ( ) { } } | Set < String > prev = getComponentModel ( ) . prevExpandedRows ; if ( prev == null ) { return Collections . emptySet ( ) ; } else { return Collections . unmodifiableSet ( prev ) ; } |
public class ZoneRegion { /** * Obtains an instance of { @ code ZoneId } from an identifier .
* @ param zoneId the time - zone ID , not null
* @ param checkAvailable whether to check if the zone ID is available
* @ return the zone ID , not null
* @ throws DateTimeException if the ID format is invalid
* @ throws DateTimeException if checking availability and the ID cannot be found */
static ZoneRegion ofId ( String zoneId , boolean checkAvailable ) { } } | Jdk8Methods . requireNonNull ( zoneId , "zoneId" ) ; if ( zoneId . length ( ) < 2 || PATTERN . matcher ( zoneId ) . matches ( ) == false ) { throw new DateTimeException ( "Invalid ID for region-based ZoneId, invalid format: " + zoneId ) ; } ZoneRules rules = null ; try { // always attempt load for better behavior after deserialization
rules = ZoneRulesProvider . getRules ( zoneId , true ) ; } catch ( ZoneRulesException ex ) { // special case as removed from data file
if ( zoneId . equals ( "GMT0" ) ) { rules = ZoneOffset . UTC . getRules ( ) ; } else if ( checkAvailable ) { throw ex ; } } return new ZoneRegion ( zoneId , rules ) ; |
public class ExternalContextUtils { /** * Returns the name of the underlying context or < code > null < / code > if something
* went wrong in trying to retrieve the context .
* @ param ec the current external context
* @ return a String containing the context name */
public static String getContextName ( ExternalContext ec ) { } } | try { if ( isPortlet ( ec ) ) { return ( String ) _runMethod ( ec . getContext ( ) , "getPortletContextName" ) ; } else { return ( ( ServletContext ) ec . getContext ( ) ) . getServletContextName ( ) ; } } catch ( final ClassCastException e ) { _LOG . severe ( e . getMessage ( ) ) ; } return null ; |
public class StandardSubjectBuilder { /** * Triggers the failure strategy with the given failure message */
public final void fail ( @ NullableDecl String format , Object /* @ NullableDeclType */
... args ) { } } | doFail ( lenientFormat ( format , args ) ) ; |
public class GrowingSparseMatrix { /** * Returns a { @ link DoubleVector } of the contents of the column .
* @ param column { @ inheritDoc }
* @ return { @ inheritDoc } */
public SparseDoubleVector getColumnVector ( int column ) { } } | SparseDoubleVector values = new SparseHashDoubleVector ( rows ) ; for ( int row = 0 ; row < rows ; ++ row ) { double d = get ( row , column ) ; if ( d != 0 ) values . set ( row , d ) ; } return values ; |
public class CPInstanceLocalServiceUtil { /** * Returns the cp instance matching the UUID and group .
* @ param uuid the cp instance ' s UUID
* @ param groupId the primary key of the group
* @ return the matching cp instance , or < code > null < / code > if a matching cp instance could not be found */
public static com . liferay . commerce . product . model . CPInstance fetchCPInstanceByUuidAndGroupId ( String uuid , long groupId ) { } } | return getService ( ) . fetchCPInstanceByUuidAndGroupId ( uuid , groupId ) ; |
public class ByteBuf { /** * Returns a { @ code String } created from this { @ code ByteBuf } using given charset .
* Does not recycle this { @ code ByteBuf } .
* @ param charset charset which is used to create { @ code String } from this { @ code ByteBuf } .
* @ return { @ code String } from this { @ code ByteBuf } in a given charset . */
@ Contract ( pure = true ) public String getString ( @ NotNull Charset charset ) { } } | return new String ( array , head , readRemaining ( ) , charset ) ; |
public class ArticleConsumerLogMessages { /** * Logs the status of the article consumer .
* @ param logger
* reference to the logger
* @ param articleReader
* reference to the ArticleReader
* @ param startTime
* start time
* @ param sleepingTime
* time the consumer has slept
* @ param workingTime
* time the consumer was working */
public static void logStatus ( final Logger logger , final ArticleReaderInterface articleReader , final long startTime , final long sleepingTime , final long workingTime ) { } } | String message = "Consumer-Status-Report [" + Time . toClock ( System . currentTimeMillis ( ) - startTime ) + "]" ; if ( articleReader != null ) { message += "\tPOSITION <" + articleReader . getBytePosition ( ) + ">" ; } message += "\tEFFICIENCY\t " + MathUtilities . percentPlus ( workingTime , sleepingTime ) + "\tWORK [" + Time . toClock ( workingTime ) + "]" + "\tSLEEP [" + Time . toClock ( sleepingTime ) + "]" ; logger . logMessage ( Level . DEBUG , message ) ; |
public class EasyRandomParameters { /** * Set the date range .
* @ param min date
* @ param max date
* @ return the current { @ link EasyRandomParameters } instance for method chaining */
public EasyRandomParameters dateRange ( final LocalDate min , final LocalDate max ) { } } | if ( min . isAfter ( max ) ) { throw new IllegalArgumentException ( "Min date should be before max date" ) ; } setDateRange ( new Range < > ( min , max ) ) ; return this ; |
public class DefaultExceptionContext { /** * { @ inheritDoc } */
@ Override public Object getFirstContextValue ( final String label ) { } } | for ( final Pair < String , Object > pair : contextValues ) { if ( StringUtils . equals ( label , pair . getKey ( ) ) ) { return pair . getValue ( ) ; } } return null ; |
public class CHFWBundle { /** * Access the scheduled event service .
* @ return ScheduledEventService - null if not found */
public static ScheduledEventService getScheduleService ( ) { } } | CHFWBundle c = instance . get ( ) . get ( ) ; if ( null != c ) { return c . scheduler ; } return null ; |
public class StorePackageImpl { /** * < ! - - begin - user - doc - - >
* < ! - - end - user - doc - - >
* @ generated */
@ Override public EClass getRevisionSummary ( ) { } } | if ( revisionSummaryEClass == null ) { revisionSummaryEClass = ( EClass ) EPackage . Registry . INSTANCE . getEPackage ( StorePackage . eNS_URI ) . getEClassifiers ( ) . get ( 32 ) ; } return revisionSummaryEClass ; |
public class PutObjectUiProgressBar { /** * uploadFile ( fileName ) uploads to configured object storage upon reading
* a local file , while asynchronously updating the progress bar UI
* as well . This function is involed when user clicks on the UI */
private void uploadFile ( String fileName ) throws IOException , NoSuchAlgorithmException , InvalidKeyException , XmlPullParserException , InvalidEndpointException , InvalidPortException , InvalidBucketNameException , InsufficientDataException , NoResponseException , ErrorResponseException , InternalException , InvalidArgumentException { } } | /* play . min . io for test and development . */
MinioClient minioClient = new MinioClient ( "https://play.min.io:9000" , "Q3AM3UQ867SPQQA43P2F" , "zuf+tfteSlswRu7BJ86wekitnifILbZam1KYY3TG" ) ; /* Amazon S3: */
// MinioClient minioClient = new MinioClient ( " https : / / s3 . amazonaws . com " ,
// " YOUR - ACCESSKEYID " ,
// " YOUR - SECRETACCESSKEY " ) ;
File file = new File ( fileName ) ; try ( BufferedInputStream bis = new BufferedInputStream ( new FileInputStream ( file ) ) ) { ProgressMonitorInputStream pmis = new ProgressMonitorInputStream ( this , "Uploading... " + file . getAbsolutePath ( ) , bis ) ; pmis . getProgressMonitor ( ) . setMillisToPopup ( 10 ) ; minioClient . putObject ( "bank" , "my-objectname" , pmis , bis . available ( ) , "application/octet-stream" ) ; System . out . println ( "my-objectname is uploaded successfully" ) ; } catch ( FileNotFoundException e ) { // TODO Auto - generated catch block
e . printStackTrace ( ) ; } catch ( IOException e ) { // TODO Auto - generated catch block
e . printStackTrace ( ) ; } |
public class EbeanExprInvoker { /** * { @ inheritDoc } */
@ SuppressWarnings ( "unchecked" ) @ Override protected Val < Expression > expr ( String field , String op , Val < Expression > [ ] args , QueryExprMeta parent ) { } } | Iterable < ExprTransformer > transformers = getTransformer ( ExprTransformer . class ) ; for ( ExprTransformer < Expression , EbeanExprInvoker > transformer : transformers ) { Transformed < Val < Expression > > transformed = transformer . transform ( field , op , args , this , parent ) ; if ( transformed . success ( ) ) { return transformed . result ( ) ; } } throw new QuerySyntaxException ( Messages . get ( "dsl.transform.err" , field , op , Arrays . toString ( args ) ) ) ; |
public class ExpectedConditions { /** * An expectation for checking WebElement with given locator has attribute with a specific value
* @ param locator used to find the element
* @ param attribute used to define css or html attribute
* @ param value used as expected attribute value
* @ return Boolean true when element has css or html attribute with the value */
public static ExpectedCondition < Boolean > attributeToBe ( final By locator , final String attribute , final String value ) { } } | return new ExpectedCondition < Boolean > ( ) { private String currentValue = null ; @ Override public Boolean apply ( WebDriver driver ) { WebElement element = driver . findElement ( locator ) ; currentValue = element . getAttribute ( attribute ) ; if ( currentValue == null || currentValue . isEmpty ( ) ) { currentValue = element . getCssValue ( attribute ) ; } return value . equals ( currentValue ) ; } @ Override public String toString ( ) { return String . format ( "element found by %s to have value \"%s\". Current value: \"%s\"" , locator , value , currentValue ) ; } } ; |
public class SqlParserImpl { /** * バインド変数解析 */
protected void parseBindVariable ( ) { } } | String expr = tokenizer . getToken ( ) ; peek ( ) . addChild ( new BindVariableNode ( this . position , expr , null , outputBindComment ) ) ; this . position = this . tokenizer . getPosition ( ) ; |
public class SessionManager { /** * Get a map of pool infos to average wait times for first
* resource of a resource type .
* @ param type Resource type
* @ return Map of pools into average first resource time */
public Map < PoolInfo , Long > getTypePoolInfoAveFirstWaitMs ( ResourceType type ) { } } | Map < PoolInfo , WaitCount > poolInfoWaitCount = new HashMap < PoolInfo , WaitCount > ( ) ; for ( Session session : sessions . values ( ) ) { synchronized ( session ) { if ( ! session . isDeleted ( ) ) { Long wait = session . getTypeFirstWaitMs ( type ) ; if ( wait == null ) { continue ; } WaitCount waitCount = poolInfoWaitCount . get ( session . getPoolInfo ( ) ) ; if ( waitCount == null ) { poolInfoWaitCount . put ( session . getPoolInfo ( ) , new WaitCount ( wait ) ) ; } else { waitCount . addWaitMsecs ( wait ) ; } } } } Map < PoolInfo , Long > poolInfoWaitMs = new HashMap < PoolInfo , Long > ( poolInfoWaitCount . size ( ) ) ; for ( Map . Entry < PoolInfo , WaitCount > entry : poolInfoWaitCount . entrySet ( ) ) { poolInfoWaitMs . put ( entry . getKey ( ) , entry . getValue ( ) . getAverageWait ( ) ) ; } return poolInfoWaitMs ; |
public class DataFactory { /** * Returns a string containing a set of numbers with a fixed number of digits
* @ param digits number of digits in the final number
* @ return Random number as a string with a fixed length */
public String getNumberText ( final int digits ) { } } | String result = "" ; for ( int i = 0 ; i < digits ; i ++ ) { result = result + random . nextInt ( 10 ) ; } return result ; |
public class DataProvider { /** * Build cache key
* @ param keys Entity keys
* @ return Cache key */
final long buildHashCode ( Object ... keys ) { } } | ArrayList < Object > keyList = new ArrayList < > ( ) ; Collections . addAll ( keyList , keys ) ; return buildHashCode ( keyList ) ; |
public class StripeJsonUtils { /** * Calls through to { @ link JSONObject # optInt ( String ) } only in the case that the
* key exists . This returns { @ code null } if the key is not in the object .
* @ param jsonObject the input object
* @ param fieldName the required field name
* @ return the value stored in the requested field , or { @ code null } if the key is not present */
@ Nullable static Integer optInteger ( @ NonNull JSONObject jsonObject , @ NonNull @ Size ( min = 1 ) String fieldName ) { } } | if ( ! jsonObject . has ( fieldName ) ) { return null ; } return jsonObject . optInt ( fieldName ) ; |
public class GalaxyProperties { /** * Determines if this is a pre - 2014.10.06 release of Galaxy .
* @ param galaxyRoot The root directory of Galaxy .
* @ return True if this is a pre - 2014.10.06 release of Galaxy , false otherwise . */
public boolean isPre20141006Release ( File galaxyRoot ) { } } | if ( galaxyRoot == null ) { throw new IllegalArgumentException ( "galaxyRoot is null" ) ; } else if ( ! galaxyRoot . exists ( ) ) { throw new IllegalArgumentException ( "galaxyRoot=" + galaxyRoot . getAbsolutePath ( ) + " does not exist" ) ; } File configDirectory = new File ( galaxyRoot , CONFIG_DIR_NAME ) ; return ! ( new File ( configDirectory , "galaxy.ini.sample" ) ) . exists ( ) ; |
public class WhileyFileParser { /** * Parse an < i > access expression < / i > , which has the form :
* < pre >
* AccessExpr : : = PrimaryExpr
* | AccessExpr ' [ ' AdditiveExpr ' ] '
* | AccessExpr ' [ ' AdditiveExpr " . . " AdditiveExpr ' ] '
* | AccessExpr ' . ' Identifier
* | AccessExpr ' . ' Identifier ' ( ' [ Expr ( ' , ' Expr ) * ] ' ) '
* | AccessExpr " - > " Identifier
* < / pre >
* Access expressions are challenging for several reasons . First , they are
* < i > left - recursive < / i > , making them more difficult to parse correctly .
* Secondly , there are several different forms above and , of these , some
* generate multiple AST nodes as well ( see below ) .
* This parser attempts to construct the most accurate AST possible and this
* requires disambiguating otherwise identical forms . For example , an
* expression of the form " aaa . bbb . ccc " can correspond to either a field
* access , or a constant expression ( e . g . with a package / module specifier ) .
* Likewise , an expression of the form " aaa . bbb . ccc ( ) " can correspond to an
* indirect function / method call , or a direct function / method call with a
* package / module specifier . To disambiguate these forms , the parser relies
* on the fact any sequence of field - accesses must begin with a local
* variable .
* @ param scope
* The enclosing scope for this statement , which determines the
* set of visible ( i . e . declared ) variables and also the current
* indentation level .
* @ param terminated
* This indicates that the expression is known to be terminated
* ( or not ) . An expression that ' s known to be terminated is one
* which is guaranteed to be followed by something . This is
* important because it means that we can ignore any newline
* characters encountered in parsing this expression , and that
* we ' ll never overrun the end of the expression ( i . e . because
* there ' s guaranteed to be something which terminates this
* expression ) . A classic situation where terminated is true is
* when parsing an expression surrounded in braces . In such case ,
* we know the right - brace will always terminate this expression .
* @ return */
private Expr parseAccessExpression ( EnclosingScope scope , boolean terminated ) { } } | int start = index ; Expr lhs = parseTermExpression ( scope , terminated ) ; Token token ; while ( ( token = tryAndMatchOnLine ( LeftSquare ) ) != null || ( token = tryAndMatch ( terminated , Dot , MinusGreater , ColonColon ) ) != null ) { switch ( token . kind ) { case LeftSquare : // NOTE : expression guaranteed to be terminated by ' ] ' .
Expr rhs = parseAdditiveExpression ( scope , true ) ; // This is a plain old array access expression
match ( RightSquare ) ; lhs = new Expr . ArrayAccess ( Type . Void , lhs , rhs ) ; break ; case MinusGreater : lhs = new Expr . Dereference ( Type . Void , lhs ) ; // Fall through
case Dot : // At this point , we could have a field access , or a
// method / function invocation . Therefore , we start by
// parsing the field access and then check whether or not its an
// invocation .
lhs = parseDotAccess ( lhs , scope , terminated ) ; break ; case ColonColon : // At this point , we have a qualified access .
index = start ; lhs = parseQualifiedAccess ( scope , terminated ) ; break ; } // Attached source information
lhs = annotateSourceLocation ( lhs , start ) ; } return lhs ; |
public class Domain { /** * Convenience method to get information about a specific Domain .
* @ param id the domain id .
* @ param description the description
* @ return information about a specific Domain
* @ throws AppPlatformException API Exception
* @ throws ParseException Error parsing data
* @ throws IOException unexpected error
* @ throws Exception error */
public static Domain update ( final String id , final String description ) throws AppPlatformException , ParseException , IOException , Exception { } } | final BandwidthClient client = BandwidthClient . getInstance ( ) ; final Map < String , Object > params = new HashMap < String , Object > ( ) ; if ( description != null ) { params . put ( "description" , description ) ; } return update ( client , id , params ) ; |
public class SocketFactory { /** * Creates the socket and the writer to go with it . */
@ Override public Socket makeObject ( InetSocketAddress address ) throws Exception { } } | Socket socket = new Socket ( address . getHostName ( ) , address . getPort ( ) ) ; socket . setKeepAlive ( true ) ; return socket ; |
public class JMThread { /** * Start with executor service executor service .
* @ param executorService the executor service
* @ param message the message
* @ param runnable the runnable
* @ return the executor service */
public static ExecutorService startWithExecutorService ( ExecutorService executorService , String message , Runnable runnable ) { } } | runAsync ( ( ) -> { JMLog . info ( log , "startWithExecutorService" , message ) ; runnable . run ( ) ; } , executorService ) ; return executorService ; |
public class ReverseMap { /** * Creates a reverse map name corresponding to an address contained in
* an array of 4 bytes ( for an IPv4 address ) or 16 bytes ( for an IPv6 address ) .
* @ param addr The address from which to build a name .
* @ return The name corresponding to the address in the reverse map . */
public static Name fromAddress ( byte [ ] addr ) { } } | if ( addr . length != 4 && addr . length != 16 ) throw new IllegalArgumentException ( "array must contain " + "4 or 16 elements" ) ; StringBuffer sb = new StringBuffer ( ) ; if ( addr . length == 4 ) { for ( int i = addr . length - 1 ; i >= 0 ; i -- ) { sb . append ( addr [ i ] & 0xFF ) ; if ( i > 0 ) sb . append ( "." ) ; } } else { int [ ] nibbles = new int [ 2 ] ; for ( int i = addr . length - 1 ; i >= 0 ; i -- ) { nibbles [ 0 ] = ( addr [ i ] & 0xFF ) >> 4 ; nibbles [ 1 ] = ( addr [ i ] & 0xFF ) & 0xF ; for ( int j = nibbles . length - 1 ; j >= 0 ; j -- ) { sb . append ( Integer . toHexString ( nibbles [ j ] ) ) ; if ( i > 0 || j > 0 ) sb . append ( "." ) ; } } } try { if ( addr . length == 4 ) return Name . fromString ( sb . toString ( ) , inaddr4 ) ; else return Name . fromString ( sb . toString ( ) , inaddr6 ) ; } catch ( TextParseException e ) { throw new IllegalStateException ( "name cannot be invalid" ) ; } |
public class OneStepDistributedRowLock { /** * Fill a mutation with the lock column . This may be used when the mutation
* is executed externally but should be used with extreme caution to ensure
* the lock is properly released
* @ param m
* @ param time
* @ param ttl */
public C fillLockMutation ( MutationBatch m , Long time , Integer ttl ) { } } | if ( lockColumn != null ) { if ( ! lockColumn . equals ( columnStrategy . generateLockColumn ( ) ) ) throw new IllegalStateException ( "Can't change prefix or lockId after acquiring the lock" ) ; } else { lockColumn = columnStrategy . generateLockColumn ( ) ; } Long timeoutValue = ( time == null ) ? new Long ( 0 ) : time + TimeUnit . MICROSECONDS . convert ( timeout , timeoutUnits ) ; m . withRow ( columnFamily , key ) . putColumn ( lockColumn , generateTimeoutValue ( timeoutValue ) , ttl ) ; return lockColumn ; |
public class Condition { /** * URI starts with */
public static Condition startsWithUri ( final String uri ) { } } | return new Condition ( input -> input . getUri ( ) . startsWith ( uri ) ) ; |
public class UpdateDevEndpointRequest { /** * The list of public keys to be deleted from the DevEndpoint .
* < b > NOTE : < / b > This method appends the values to the existing list ( if any ) . Use
* { @ link # setDeletePublicKeys ( java . util . Collection ) } or { @ link # withDeletePublicKeys ( java . util . Collection ) } if you
* want to override the existing values .
* @ param deletePublicKeys
* The list of public keys to be deleted from the DevEndpoint .
* @ return Returns a reference to this object so that method calls can be chained together . */
public UpdateDevEndpointRequest withDeletePublicKeys ( String ... deletePublicKeys ) { } } | if ( this . deletePublicKeys == null ) { setDeletePublicKeys ( new java . util . ArrayList < String > ( deletePublicKeys . length ) ) ; } for ( String ele : deletePublicKeys ) { this . deletePublicKeys . add ( ele ) ; } return this ; |
public class SelectiveCsvEncoder { /** * { @ inheritDoc } */
public String encode ( final String input , final CsvContext context , final CsvPreference preference ) { } } | return columnNumbers . contains ( context . getColumnNumber ( ) ) ? super . encode ( input , context , preference ) : input ; |
public class CholeskyDecomposition { /** * Solve A * X = b
* @ param b A column vector with as many rows as A .
* @ return X so that L * L ^ T * X = b
* @ exception IllegalArgumentException Matrix row dimensions must agree .
* @ exception RuntimeException Matrix is not symmetric positive definite . */
public double [ ] solve ( double [ ] b ) { } } | if ( b . length != L . length ) { throw new IllegalArgumentException ( ERR_MATRIX_DIMENSIONS ) ; } if ( ! isspd ) { throw new ArithmeticException ( ERR_MATRIX_NOT_SPD ) ; } // Work on a copy !
return solveLtransposed ( solveLInplace ( copy ( b ) ) ) ; |
public class NotificationManager { /** * Delete server - side notifications , represented by the 3 - tuple { source mbean , listener mbean , registration ID } .
* Called from direct HTTP users . */
public void deleteServerRegistrationHTTP ( RESTRequest request , int clientID , ServerNotificationRegistration serverNotificationRegistration , String registrationID , JSONConverter converter ) { } } | // Get the client area
ClientNotificationArea clientArea = getInboxIfAvailable ( clientID , null ) ; if ( registrationID != null ) { String [ ] artifacts = registrationID . split ( "_" ) ; int filterID = Integer . parseInt ( artifacts [ 0 ] ) ; int handbackID = Integer . parseInt ( artifacts [ 1 ] ) ; // Since this is not coming from our java client , the registration object will not have any IDs on them . So set the IDs before continuing .
serverNotificationRegistration . filterID = filterID ; serverNotificationRegistration . handbackID = handbackID ; } clientArea . removeServerNotificationListener ( request , serverNotificationRegistration , serverNotificationRegistration . operation == Operation . RemoveAll , converter , true ) ; |
public class CredentialReader { /** * Make the request to the Twilio API to perform the read .
* @ param client TwilioRestClient with which to make the request
* @ return Credential ResourceSet */
@ Override public ResourceSet < Credential > read ( final TwilioRestClient client ) { } } | return new ResourceSet < > ( this , client , firstPage ( client ) ) ; |
public class CommonsArrayList { /** * Create a new array list that contains a subset of the provided
* iterable . < br >
* Note : this method is a static factory method because the compiler sometimes
* cannot deduce between { @ link Predicate } and { @ link Function } and the
* mapping case occurs more often .
* @ param aValues
* The iterable from which the elements are copied from . May be
* < code > null < / code > .
* @ param aFilter
* The filter to be applied to check if the element should be added or
* not .
* @ return The created array list . Never < code > null < / code > .
* @ see # addAll ( Iterable , Predicate ) */
@ Nonnull @ ReturnsMutableCopy public static < ELEMENTTYPE > CommonsArrayList < ELEMENTTYPE > createFiltered ( @ Nullable final Iterable < ? extends ELEMENTTYPE > aValues , @ Nullable final Predicate < ? super ELEMENTTYPE > aFilter ) { } } | final CommonsArrayList < ELEMENTTYPE > ret = new CommonsArrayList < > ( ) ; ret . addAll ( aValues , aFilter ) ; return ret ; |
public class AbstractValidate { /** * Validate that the specified primitive value falls between the two exclusive values specified ; otherwise , throws an exception with the specified message .
* < pre > Validate . exclusiveBetween ( 0 , 2 , 1 , " Not in range " ) ; < / pre >
* @ param start
* the exclusive start value
* @ param end
* the exclusive end value
* @ param value
* the value to validate
* @ param message
* the exception message if invalid , not null
* @ return the value
* @ throws IllegalArgumentValidationException
* if the value falls outside the boundaries */
public long exclusiveBetween ( long start , long end , long value , String message ) { } } | if ( value <= start || value >= end ) { fail ( message ) ; } return value ; |
public class OneSelect { /** * Method used to append to the where part of an SQL statement .
* @ param _ select SQL select wrapper
* @ throws EFapsException on error */
public void append2SQLWhere ( final SQLSelect _select ) throws EFapsException { } } | for ( final ISelectPart part : this . selectParts ) { part . add2Where ( this , _select ) ; } |
public class ExtensionSpider { /** * Shows the spider dialogue with the given target , if not already visible .
* @ param target the target , might be { @ code null } .
* @ since TODO add version . */
public void showSpiderDialog ( Target target ) { } } | if ( spiderDialog == null ) { spiderDialog = new SpiderDialog ( this , View . getSingleton ( ) . getMainFrame ( ) , new Dimension ( 700 , 430 ) ) ; } if ( spiderDialog . isVisible ( ) ) { // Its behind you ! Actually not needed no the window is alwaysOnTop , but keeping in case we change that ; )
spiderDialog . toFront ( ) ; return ; } if ( target != null ) { spiderDialog . init ( target ) ; } else { // Keep the previous target
spiderDialog . init ( null ) ; } spiderDialog . setVisible ( true ) ; |
public class GeospatialUtils { /** * Checks if the specified latitude is correct .
* @ param name the name of the latitude field
* @ param latitude the value of the latitude field
* @ return the latitude */
public static Double checkLatitude ( String name , Double latitude ) { } } | if ( latitude == null ) { throw new IndexException ( "{} required" , name ) ; } else if ( latitude < MIN_LATITUDE || latitude > MAX_LATITUDE ) { throw new IndexException ( "{} must be in range [{}, {}], but found {}" , name , MIN_LATITUDE , MAX_LATITUDE , latitude ) ; } return latitude ; |
public class ContentResourceImpl { /** * Retrieves content from a space .
* @ param spaceID
* @ param contentID
* @ return InputStream which can be used to read content . */
@ Override public RetrievedContent getContent ( String spaceID , String contentID , String storeID , String range ) throws InvalidRequestException , ResourceException { } } | try { StorageProvider storage = storageProviderFactory . getStorageProvider ( storeID ) ; return storage . getContent ( spaceID , contentID , range ) ; } catch ( NotFoundException e ) { throw new ResourceNotFoundException ( "get content" , spaceID , contentID , e ) ; } catch ( StorageStateException e ) { throw new ResourceStateException ( "get content" , spaceID , contentID , e ) ; } catch ( IllegalArgumentException e ) { throw new InvalidRequestException ( e . getMessage ( ) ) ; } catch ( Exception e ) { storageProviderFactory . expireStorageProvider ( storeID ) ; throw new ResourceException ( "get content" , spaceID , contentID , e ) ; } |
public class HttpPredicate { /** * An alias for { @ link HttpPredicate # http } .
* Creates a { @ link Predicate } based on a URI template filtering .
* This will listen for HEAD Method .
* @ param uri The string to compile into a URI template and use for matching
* @ return The new { @ link Predicate } .
* @ see Predicate */
public static Predicate < HttpServerRequest > head ( String uri ) { } } | return http ( uri , null , HttpMethod . HEAD ) ; |
public class ConcurrentLinkedList { /** * ( non - Javadoc )
* @ see com . ibm . ws . objectManager . Collection # remove ( com . ibm . ws . objectManager . Token , com . ibm . ws . objectManager . Transaction ) */
public boolean remove ( Token token , Transaction transaction ) throws ObjectManagerException { } } | final String methodName = "remove" ; if ( Tracing . isAnyTracingEnabled ( ) && trace . isEntryEnabled ( ) ) trace . entry ( this , cclass , methodName , new Object [ ] { token , transaction } ) ; // Make an initial unsynchronized search for the link .
ConcurrentSubList . Link linkToRemove = findLink ( token , transaction ) ; boolean found = false ; if ( linkToRemove != null ) { // Was a candidate found found ?
// We did not take the synchronize lock on the subList , so it could
// have been modified .
// Take the lock on the relevant subList so that we can mark it for
// update .
synchronized ( headSequenceNumberLock ) { synchronized ( linkToRemove . list ) { if ( ( linkToRemove . state == ConcurrentSubList . Link . stateAdded ) || ( linkToRemove . state == ConcurrentSubList . Link . stateToBeAdded && linkToRemove . lockedBy ( transaction ) ) ) { linkToRemove . requestDelete ( transaction ) ; // Mark for deletion .
// If the link is available to all adjust list visible length available .
// In the case where we delete a link added by the same transaction we have no incremented
// the available size yet because we have not yet committed so we would not decrement it .
if ( ! linkToRemove . isLocked ( ) ) linkToRemove . list . decrementAvailableSize ( ) ; found = true ; // Update the headSequenceNumber if we just removed the head of the
// overall list .
if ( linkToRemove . sequenceNumber == headSequenceNumber ) { incrementHeadSequenceNumber ( linkToRemove ) ; } // if ( linkToRemove . sequenceNumber = = headSequenceNumber ) .
if ( LinkedList . gatherStatistics ) removeUncontendedCount ++ ; } // if ( linkToRemove . state = = ConcurrentSubList . Link . stateAdded ) .
} // synchronized ( linkToRemove . list ) .
} // synchronized ( headSequenceNumberLock ) .
// If the link was deleted meanwhile then have anothther look , but this
// time take a lock .
if ( ! found ) { synchronized ( headSequenceNumberLock ) { linkToRemove = findLink ( token , transaction ) ; if ( linkToRemove != null ) { synchronized ( linkToRemove . list ) { linkToRemove . requestDelete ( transaction ) ; // Mark for deletion .
// If the link is available to all adjust list visible length available .
// In the case where we delete a link added by the same transaction we have no incremented
// the available size yet because we have not yet committed so we would not decrement it .
if ( ! linkToRemove . isLocked ( ) ) linkToRemove . list . decrementAvailableSize ( ) ; found = true ; // Update the headSequenceNumber if we just removed the head of
// the overall list .
if ( linkToRemove . sequenceNumber == headSequenceNumber ) { incrementHeadSequenceNumber ( linkToRemove ) ; } // synchronized ( headSequenceNumberLock )
if ( LinkedList . gatherStatistics ) removeContendedCount ++ ; } // synchronized ( linkToRemove . list ) .
} // if ( linkToRemove ! = null ) .
} // synchronized ( headSequenceNumberLock ) .
} // if ( ! found )
} // if ( linkToRemove ! = null ) .
// We can release the synchronize lock on the list because we dont care if the
// link which we are going to delete is changed before we write the log record .
// Anyhow it is now marked as ToBeDeleted .
// Log what we intend to do . Reserve enough spare log space so that the eventual
// optimistic replace that removes the link from the list is certain to succeed
// in being written as well .
if ( linkToRemove != null ) { try { transaction . delete ( linkToRemove , ConcurrentSubList . logSpaceForDelete ( ) ) ; } catch ( LogFileFullException exception ) { // No FFDC Code Needed , transaction . delete ( ) has already done this .
linkToRemove . unRemove ( this ) ; if ( Tracing . isAnyTracingEnabled ( ) && trace . isEntryEnabled ( ) ) trace . exit ( this , cclass , methodName , exception ) ; throw exception ; // We should not see ObjectStoreFullException because we have preReserved
// the ObjectStore space .
// } catch ( ObjectStoreFullException exception ) {
// / / No FFDC Code Needed , transaction . delete ( ) has already done this .
// linkToRemove . unRemove ( this ) ;
// if ( Tracing . isAnyTracingEnabled ( ) & & trace . isEntryEnabled ( ) )
// trace . exit ( this , cclass , methodName , exception ) ;
// throw exception ;
} catch ( InvalidStateException exception ) { // No FFDC Code Needed .
ObjectManager . ffdc . processException ( this , cclass , methodName , exception , "1:912:1.26" ) ; linkToRemove . unRemove ( this ) ; if ( Tracing . isAnyTracingEnabled ( ) && trace . isEntryEnabled ( ) ) trace . exit ( this , cclass , methodName , exception ) ; throw exception ; } // catch ( LogFileFullException exception ) .
} // if ( linkToRemove ! = null )
if ( Tracing . isAnyTracingEnabled ( ) && trace . isEntryEnabled ( ) ) trace . exit ( this , cclass , methodName , new Object [ ] { new Boolean ( found ) } ) ; return found ; |
public class ScriptRuntime { /** * The instanceof operator .
* @ return a instanceof b */
public static boolean instanceOf ( Object a , Object b , Context cx ) { } } | // Check RHS is an object
if ( ! ( b instanceof Scriptable ) ) { throw typeError0 ( "msg.instanceof.not.object" ) ; } // for primitive values on LHS , return false
if ( ! ( a instanceof Scriptable ) ) return false ; return ( ( Scriptable ) b ) . hasInstance ( ( Scriptable ) a ) ; |
public class PropertiesField { /** * Load the properties from the string and parse them .
* @ return The java properties . */
public static Map < String , Object > stringToProperties ( String strProperties ) { } } | Properties properties = new Properties ( ) ; if ( ( strProperties != null ) && ( strProperties . length ( ) > 0 ) ) { ByteArrayOutputStream baOut = new ByteArrayOutputStream ( ) ; OutputStreamWriter osOut = new OutputStreamWriter ( baOut ) ; try { osOut . write ( strProperties ) ; // Char - > Byte
osOut . flush ( ) ; baOut . flush ( ) ; ByteArrayInputStream baIn = new ByteArrayInputStream ( baOut . toByteArray ( ) ) ; properties . load ( baIn ) ; } catch ( IOException ex ) { ex . printStackTrace ( ) ; } } Map < String , Object > map = Utility . propertiesToMap ( properties ) ; // This is okay .
return map ; |
public class HalFormsDocument { /** * Adds the given value as embedded one .
* @ param key must not be { @ literal null } or empty .
* @ param value must not be { @ literal null } .
* @ return */
public HalFormsDocument < T > andEmbedded ( HalLinkRelation key , Object value ) { } } | Assert . notNull ( key , "Embedded key must not be null!" ) ; Assert . notNull ( value , "Embedded value must not be null!" ) ; Map < HalLinkRelation , Object > embedded = new HashMap < > ( this . embedded ) ; embedded . put ( key , value ) ; return new HalFormsDocument < > ( resource , resources , embedded , pageMetadata , links , templates ) ; |
public class BounceProxySystemPropertyLoader { /** * Replaces a variable defined by < code > $ { variable } < / code > by a system
* property with the key < code > variable < / code > .
* @ param value
* a string with any number of variables defined
* @ return a string in which each occurrence of < code > $ { variable } < / code > is
* replaced by { @ link System # getProperty ( String ) } with
* < code > variable < / code > as property key .
* @ throws JoynrRuntimeException
* if the property key for the variable does not exist */
@ CheckForNull static String replaceVariableBySystemProperty ( String value ) { } } | if ( value == null ) return null ; int startVariableIndex = value . indexOf ( "${" ) ; while ( startVariableIndex >= 0 ) { int endVariableIndex = value . indexOf ( "}" , startVariableIndex ) ; String propertyName = value . substring ( startVariableIndex + 2 , endVariableIndex ) ; String systemProperty = System . getProperty ( propertyName ) ; if ( systemProperty == null ) { throw new JoynrRuntimeException ( "No value for system property '" + propertyName + "' set as defined in property file. Unable to start Bounce Proxy" ) ; } else { value = value . substring ( 0 , startVariableIndex ) + systemProperty + value . substring ( endVariableIndex + 1 ) ; } startVariableIndex = value . indexOf ( "${" ) ; } return value ; |
public class GosuStringUtil { /** * < p > Checks if String contains a search String irrespective of case ,
* handling < code > null < / code > . This method uses
* { @ link # contains ( String , String ) } . < / p >
* < p > A < code > null < / code > String will return < code > false < / code > . < / p >
* < pre >
* GosuStringUtil . contains ( null , * ) = false
* GosuStringUtil . contains ( * , null ) = false
* GosuStringUtil . contains ( " " , " " ) = true
* GosuStringUtil . contains ( " abc " , " " ) = true
* GosuStringUtil . contains ( " abc " , " a " ) = true
* GosuStringUtil . contains ( " abc " , " z " ) = false
* GosuStringUtil . contains ( " abc " , " A " ) = true
* GosuStringUtil . contains ( " abc " , " Z " ) = false
* < / pre >
* @ param str the String to check , may be null
* @ param searchStr the String to find , may be null
* @ return true if the String contains the search String irrespective of
* case or false if not or < code > null < / code > string input */
public static boolean containsIgnoreCase ( String str , String searchStr ) { } } | if ( str == null || searchStr == null ) { return false ; } return contains ( str . toUpperCase ( ) , searchStr . toUpperCase ( ) ) ; |
public class CdnClient { /** * Set the request authentication .
* @ param domain Name of the domain .
* @ param requestAuth The configuration of authentication . */
public void setRequestAuth ( String domain , RequestAuth requestAuth ) { } } | SetRequestAuthRequest request = new SetRequestAuthRequest ( ) . withDomain ( domain ) . withRequestAuth ( requestAuth ) ; setRequestAuth ( request ) ; |
public class TableDefinition { /** * Get the { @ link FieldDefinition } of the sharding - field for this table . If this table
* is not sharded , the sharding - field option has not yet been set , or the sharding
* field has not yet been defined , null is returned .
* @ return The { @ link FieldDefinition } of the sharding - field for this table or null
* if the table is not sharded or the sharding - field has not yet been defined . */
public FieldDefinition getShardingField ( ) { } } | if ( ! isSharded ( ) ) { return null ; } String shardingFieldNme = getOption ( CommonDefs . OPT_SHARDING_FIELD ) ; if ( shardingFieldNme == null ) { return null ; } return getFieldDef ( shardingFieldNme ) ; // may return null |
public class OpenAPIModelFilterAdapter { /** * { @ inheritDoc } */
@ Override public Schema visitSchema ( Context context , Schema schema ) { } } | visitor . visitSchema ( context , schema ) ; return schema ; |
public class TableColumnManager { /** * Show a hidden column in the table . The column will be positioned at its
* proper place in the view of the table .
* @ param column
* the TableColumn to be shown . */
private void showColumn ( TableColumn column ) { } } | // Ignore changes to the TableColumnModel made by the TableColumnManager
columnModel . removeColumnModelListener ( this ) ; // Add the column to the end of the table
columnModel . addColumn ( column ) ; // Move the column to its position before it was hidden .
// ( Multiple columns may be hidden so we need to find the first
// visible column before this column so the column can be moved
// to the appropriate position )
int position = allColumns . indexOf ( column ) ; int from = columnModel . getColumnCount ( ) - 1 ; int to = 0 ; for ( int i = position - 1 ; i > - 1 ; i -- ) { try { TableColumn visibleColumn = allColumns . get ( i ) ; to = columnModel . getColumnIndex ( visibleColumn . getHeaderValue ( ) ) + 1 ; break ; } catch ( IllegalArgumentException e ) { } } columnModel . moveColumn ( from , to ) ; columnModel . addColumnModelListener ( this ) ; |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.