signature stringlengths 43 39.1k | implementation stringlengths 0 450k |
|---|---|
public class DisassociateNodeRequestMarshaller { /** * Marshall the given parameter object . */
public void marshall ( DisassociateNodeRequest disassociateNodeRequest , ProtocolMarshaller protocolMarshaller ) { } } | if ( disassociateNodeRequest == null ) { throw new SdkClientException ( "Invalid argument passed to marshall(...)" ) ; } try { protocolMarshaller . marshall ( disassociateNodeRequest . getServerName ( ) , SERVERNAME_BINDING ) ; protocolMarshaller . marshall ( disassociateNodeRequest . getNodeName ( ) , NODENAME_BINDING ) ; protocolMarshaller . marshall ( disassociateNodeRequest . getEngineAttributes ( ) , ENGINEATTRIBUTES_BINDING ) ; } catch ( Exception e ) { throw new SdkClientException ( "Unable to marshall request to JSON: " + e . getMessage ( ) , e ) ; } |
public class TextToSpeech { /** * List custom models .
* Lists metadata such as the name and description for all custom voice models that are owned by an instance of the
* service . Specify a language to list the voice models for that language only . To see the words in addition to the
* metadata for a specific voice model , use the * * List a custom model * * method . You must use credentials for the
* instance of the service that owns a model to list information about it .
* * * Note : * * This method is currently a beta release .
* * * See also : * * [ Querying all custom
* models ] ( https : / / cloud . ibm . com / docs / services / text - to - speech / custom - models . html # cuModelsQueryAll ) .
* @ param listVoiceModelsOptions the { @ link ListVoiceModelsOptions } containing the options for the call
* @ return a { @ link ServiceCall } with a response type of { @ link VoiceModels } */
public ServiceCall < VoiceModels > listVoiceModels ( ListVoiceModelsOptions listVoiceModelsOptions ) { } } | String [ ] pathSegments = { "v1/customizations" } ; RequestBuilder builder = RequestBuilder . get ( RequestBuilder . constructHttpUrl ( getEndPoint ( ) , pathSegments ) ) ; Map < String , String > sdkHeaders = SdkCommon . getSdkHeaders ( "text_to_speech" , "v1" , "listVoiceModels" ) ; for ( Entry < String , String > header : sdkHeaders . entrySet ( ) ) { builder . header ( header . getKey ( ) , header . getValue ( ) ) ; } builder . header ( "Accept" , "application/json" ) ; if ( listVoiceModelsOptions != null ) { if ( listVoiceModelsOptions . language ( ) != null ) { builder . query ( "language" , listVoiceModelsOptions . language ( ) ) ; } } return createServiceCall ( builder . build ( ) , ResponseConverterUtils . getObject ( VoiceModels . class ) ) ; |
public class JobSchedulesImpl { /** * Adds a job schedule to the specified account .
* @ param cloudJobSchedule The job schedule to be added .
* @ param jobScheduleAddOptions Additional parameters for the operation
* @ throws IllegalArgumentException thrown if parameters fail the validation
* @ throws BatchErrorException thrown if the request is rejected by server
* @ throws RuntimeException all other wrapped checked exceptions if the request fails to be sent */
public void add ( JobScheduleAddParameter cloudJobSchedule , JobScheduleAddOptions jobScheduleAddOptions ) { } } | addWithServiceResponseAsync ( cloudJobSchedule , jobScheduleAddOptions ) . toBlocking ( ) . single ( ) . body ( ) ; |
public class Files { /** * Reads a { @ link File } and returns the data as a byte array */
public static byte [ ] readBytes ( File file ) throws IOException { } } | FileInputStream fis = null ; ByteArrayOutputStream bos = null ; if ( file == null ) { throw new FileNotFoundException ( "No file specified" ) ; } try { fis = new FileInputStream ( file ) ; bos = new ByteArrayOutputStream ( ) ; byte [ ] buffer = new byte [ BUFFER_SIZE ] ; int remaining ; while ( ( remaining = fis . read ( buffer ) ) > 0 ) { bos . write ( buffer , 0 , remaining ) ; } return bos . toByteArray ( ) ; } finally { Closeables . closeQuietly ( fis ) ; Closeables . closeQuietly ( bos ) ; } |
public class AbstractCollectionView { /** * ( non - Javadoc )
* @ see com . ibm . ws . objectManager . Collection # contains ( com . ibm . ws . objectManager . Token , com . ibm . ws . objectManager . Transaction ) */
public boolean contains ( Token token , Transaction transaction ) throws ObjectManagerException { } } | try { for ( Iterator iterator = iterator ( ) ; iterator . next ( transaction ) != token ; ) ; return true ; } catch ( java . util . NoSuchElementException exception ) { // No FFDC code needed .
return false ; } // try . |
public class GuiStandardUtils { /** * If aLabel has text which is longer than MAX _ LABEL _ LENGTH , then truncate
* the label text and place an ellipsis at the end ; the original text is
* placed in a tooltip .
* This is particularly useful for displaying file names , whose length can
* vary widely between deployments .
* @ param label
* The label to truncate if length ( ) > MAX _ LABEL _ LENGTH . */
public static void truncateLabelIfLong ( JLabel label ) { } } | String originalText = label . getText ( ) ; if ( originalText . length ( ) > UIConstants . MAX_LABEL_LENGTH ) { label . setToolTipText ( originalText ) ; String truncatedText = originalText . substring ( 0 , UIConstants . MAX_LABEL_LENGTH ) + "..." ; label . setText ( truncatedText ) ; } |
public class NotificationManager { /** * Search for notifications of interaction type that match the given class name .
* @ param interaction
* the class that defines the interaction type of desired notifications .
* @ return
* a List with the notifications founded that match the given class name . */
public List < Notification > getByInteraction ( String interaction ) { } } | List < Notification > found = new ArrayList < Notification > ( ) ; for ( Notification n : NotificationManager . notifications ) if ( ( ( InteractionNotification ) n ) . getInteraction ( ) . equals ( interaction ) ) { logger . fine ( "...found a match for getByInteraction query. With interaction: " + interaction ) ; found . add ( n ) ; } if ( found . size ( ) > 0 ) return found ; return null ; |
public class ModelsImpl { /** * Create an entity role for an entity in the application .
* @ param appId The application ID .
* @ param versionId The version ID .
* @ param cEntityId The composite entity extractor ID .
* @ param createCompositeEntityRoleOptionalParameter the object representing the optional parameters to be set before calling this API
* @ throws IllegalArgumentException thrown if parameters fail the validation
* @ throws ErrorResponseException thrown if the request is rejected by server
* @ throws RuntimeException all other wrapped checked exceptions if the request fails to be sent
* @ return the UUID object if successful . */
public UUID createCompositeEntityRole ( UUID appId , String versionId , UUID cEntityId , CreateCompositeEntityRoleOptionalParameter createCompositeEntityRoleOptionalParameter ) { } } | return createCompositeEntityRoleWithServiceResponseAsync ( appId , versionId , cEntityId , createCompositeEntityRoleOptionalParameter ) . toBlocking ( ) . single ( ) . body ( ) ; |
public class CmsJspResourceWrapper { /** * Reads a resource , suppressing possible exceptions . < p >
* @ param sitePath the site path of the resource to read .
* @ return the resource of < code > null < / code > on case an exception occurred while reading */
private CmsJspResourceWrapper readResource ( String sitePath ) { } } | CmsJspResourceWrapper result = null ; try { result = new CmsJspResourceWrapper ( m_cms , m_cms . readResource ( sitePath ) ) ; } catch ( CmsException e ) { if ( LOG . isDebugEnabled ( ) ) { LOG . debug ( e . getMessage ( ) , e ) ; } } return result ; |
public class FrameUtils { /** * Parse given set of URIs and produce a frame ' s key representing output .
* @ param okey key for ouput frame . Can be null
* @ param uris array of URI ( file : / / , hdfs : / / , s3n : / / , s3a : / / , s3 : / / , http : / / , https : / / . . . ) to parse
* @ return a frame which is saved into DKV under okey
* @ throws IOException in case of parse error . */
public static Frame parseFrame ( Key okey , URI ... uris ) throws IOException { } } | return parseFrame ( okey , null , uris ) ; |
public class HelpDoclet { /** * Handles javadoc command line options . The first entry in the { @ code options } array is the
* option name . Subsequent entries contain the option ' s arguments , the number of which is
* determined by the value returned from { @ link # optionLength ( String ) } for that option .
* < p > Custom Barclay doclets that want to have custom command line options should override this
* method , and also provide an implementation of the static method { @ link # optionLength } ) .
* Both methods should handle the custom options , and then delegate back to the base class
* methods defined here to allow default handling of builtin options .
* @ param options Options to parse .
* @ return True if { @ code options } was parsed , False otherwise . */
protected boolean parseOption ( final String [ ] options ) { } } | boolean hasParsedOption = false ; if ( options [ 0 ] . equals ( SETTINGS_DIR_OPTION ) ) { settingsDir = new File ( options [ 1 ] ) ; isSettingsDirSet = true ; hasParsedOption = true ; } else if ( options [ 0 ] . equals ( DESTINATION_DIR_OPTION ) ) { destinationDir = new File ( options [ 1 ] ) ; hasParsedOption = true ; } else if ( options [ 0 ] . equals ( BUILD_TIMESTAMP_OPTION ) ) { buildTimestamp = options [ 1 ] ; hasParsedOption = true ; } else if ( options [ 0 ] . equals ( ABSOLUTE_VERSION_OPTION ) ) { absoluteVersion = options [ 1 ] ; hasParsedOption = true ; } else if ( options [ 0 ] . equals ( INCLUDE_HIDDEN_OPTION ) ) { showHiddenFeatures = true ; hasParsedOption = true ; } else if ( options [ 0 ] . equals ( OUTPUT_FILE_EXTENSION_OPTION ) ) { outputFileExtension = options [ 1 ] ; hasParsedOption = true ; } else if ( options [ 0 ] . equals ( INDEX_FILE_EXTENSION_OPTION ) ) { indexFileExtension = options [ 1 ] ; hasParsedOption = true ; } else if ( options [ 0 ] . equals ( USE_DEFAULT_TEMPLATES_OPTION ) ) { useDefaultTemplates = true ; hasParsedOption = true ; } return hasParsedOption ; |
public class ResourceRequestInfo { /** * This method writes the ResourceRequestInfo instance to disk
* @ param jsonGenerator The JsonGenerator instance being used to write the
* JSON to disk
* @ throws IOException */
public void write ( JsonGenerator jsonGenerator ) throws IOException { } } | // We neither need the list of RequestedNodes , nodes , nor excludedHosts ,
// because we can reconstruct them from the request object
jsonGenerator . writeStartObject ( ) ; jsonGenerator . writeObjectField ( "request" , request ) ; jsonGenerator . writeEndObject ( ) ; |
public class PhoneNumberUtil { /** * format phone number in E123 national format .
* @ param pphoneNumber phone number to format
* @ param pcountryCode iso code of country
* @ return formated phone number as String */
public final String formatE123National ( final String pphoneNumber , final String pcountryCode ) { } } | return this . formatE123National ( this . parsePhoneNumber ( pphoneNumber , pcountryCode ) ) ; |
public class AdHocCommandManager { /** * Responds an error with an specific condition .
* @ param response the response to send .
* @ param condition the condition of the error .
* @ throws NotConnectedException */
private static IQ respondError ( AdHocCommandData response , StanzaError . Condition condition ) { } } | return respondError ( response , StanzaError . getBuilder ( condition ) ) ; |
public class CqlDataReaderDAO { /** * Converts a TimeUUID set of endpoints into a { @ link Range } . of { @ link RangeTimeUUID } s . Both end points
* are considered closed ; that is , they are included in the range . */
private Range < RangeTimeUUID > toRange ( @ Nullable UUID start , @ Nullable UUID end , boolean reversed ) { } } | // If the range is reversed then start and end will also be reversed and must therefore be swapped .
if ( reversed ) { UUID tmp = start ; start = end ; end = tmp ; } if ( start == null ) { if ( end == null ) { return Range . all ( ) ; } else { return Range . atMost ( new RangeTimeUUID ( end ) ) ; } } else if ( end == null ) { return Range . atLeast ( new RangeTimeUUID ( start ) ) ; } return Range . closed ( new RangeTimeUUID ( start ) , new RangeTimeUUID ( end ) ) ; |
public class FitLinesToContour { /** * All the corners should be in increasing order from the first anchor . */
boolean sanityCheckCornerOrder ( int numLines , GrowQueue_I32 corners ) { } } | int contourAnchor0 = corners . get ( anchor0 ) ; int previous = 0 ; for ( int i = 1 ; i < numLines ; i ++ ) { int contourIndex = corners . get ( CircularIndex . addOffset ( anchor0 , i , corners . size ( ) ) ) ; int pixelsFromAnchor0 = CircularIndex . distanceP ( contourAnchor0 , contourIndex , contour . size ( ) ) ; if ( pixelsFromAnchor0 < previous ) { return false ; } else { previous = pixelsFromAnchor0 ; } } return true ; |
public class AbucoinsAccountServiceRaw { /** * Corresponds to < code > GET / payment - methods < / code >
* @ return
* @ throws IOException */
public AbucoinsPaymentMethod [ ] getPaymentMethods ( ) throws IOException { } } | AbucoinsPaymentMethods paymentMethods = abucoinsAuthenticated . getPaymentMethods ( exchange . getExchangeSpecification ( ) . getApiKey ( ) , signatureCreator , exchange . getExchangeSpecification ( ) . getPassword ( ) , timestamp ( ) ) ; if ( paymentMethods . getPaymentMethods ( ) . length == 1 && paymentMethods . getPaymentMethods ( ) [ 0 ] . getMessage ( ) != null ) throw new ExchangeException ( paymentMethods . getPaymentMethods ( ) [ 0 ] . getMessage ( ) ) ; return paymentMethods . getPaymentMethods ( ) ; |
public class ETAPrinter { /** * Initializes a progress bar .
* @ param totalElementsToProcess the total number of items that are going to be processed .
* @ param stream the { @ link java . io . OutputStream } where the progress bar will be printed
* @ param closeStream true if the stream has to be closed at the end of the process
* @ return the initialized { @ link com . vdurmont . etaprinter . ETAPrinter } */
public static ETAPrinter init ( long totalElementsToProcess , OutputStream stream , boolean closeStream ) { } } | return init ( null , totalElementsToProcess , stream , closeStream ) ; |
public class ClassLoaderUtils { /** * Finds files within a given directory and its subdirectories
* @ param classLoader
* @ param rootPath the root directory , for example org / sonar / sqale
* @ return a list of relative paths , for example { " org / sonar / sqale / foo / bar . txt } . Never null . */
public static Collection < String > listFiles ( ClassLoader classLoader , String rootPath ) { } } | return listResources ( classLoader , rootPath , path -> ! StringUtils . endsWith ( path , "/" ) ) ; |
public class DurableInputHandler { /** * Attempt to create a durable subscription on a remote ME .
* @ param MP The MessageProcessor .
* @ param subState State describing the subscription to create .
* @ param remoteME The ME where the subscription should be created . */
public static void createRemoteDurableSubscription ( MessageProcessor MP , ConsumerDispatcherState subState , SIBUuid8 remoteMEUuid , SIBUuid12 destinationID ) throws SIDurableSubscriptionAlreadyExistsException , SIResourceException { } } | if ( TraceComponent . isAnyTracingEnabled ( ) && tc . isEntryEnabled ( ) ) SibTr . entry ( tc , "createRemoteDurableSubscription" , new Object [ ] { MP , subState , remoteMEUuid , destinationID } ) ; // Issue the request via the DurableInputHandler
int status = issueCreateDurableRequest ( MP , subState , remoteMEUuid , destinationID ) ; switch ( status ) { case DurableConstants . STATUS_SUB_ALREADY_EXISTS : { if ( TraceComponent . isAnyTracingEnabled ( ) && tc . isEntryEnabled ( ) ) SibTr . exit ( tc , "createRemoteDurableSubscription" , "SIDurableSubscriptionAlreadyExistsException" ) ; throw new SIDurableSubscriptionAlreadyExistsException ( nls . getFormattedMessage ( "SUBSCRIPTION_ALREADY_EXISTS_ERROR_CWSIP0143" , new Object [ ] { subState . getSubscriberID ( ) , subState . getDurableHome ( ) } , null ) ) ; } case DurableConstants . STATUS_SUB_GENERAL_ERROR : { // Problem on other side which should be logged , best we
// can do is throw an exception here .
if ( TraceComponent . isAnyTracingEnabled ( ) && tc . isEntryEnabled ( ) ) SibTr . exit ( tc , "createRemoteDurableSubscription" , "SIErrorException" ) ; SibTr . error ( tc , "INTERNAL_MESSAGING_ERROR_CWSIP0001" , new Object [ ] { "com.ibm.ws.sib.processor.impl.DurableInputHandler" , "1:955:1.52.1.1" } ) ; throw new SIErrorException ( nls . getFormattedMessage ( "INTERNAL_MESSAGING_ERROR_CWSIP0001" , new Object [ ] { "com.ibm.ws.sib.processor.impl.DurableInputHandler" , "1:962:1.52.1.1" } , null ) ) ; } } if ( TraceComponent . isAnyTracingEnabled ( ) && tc . isEntryEnabled ( ) ) SibTr . exit ( tc , "createRemoteDurableSubscription" ) ; |
public class ElementMatchers { /** * Matches { @ link MethodDescription } s that match a matched method ' s return type .
* @ param matcher A matcher to apply onto a matched method ' s return type .
* @ param < T > The type of the matched object .
* @ return An element matcher that matches a given return type against another { @ code matcher } . */
public static < T extends MethodDescription > ElementMatcher . Junction < T > returnsGeneric ( ElementMatcher < ? super TypeDescription . Generic > matcher ) { } } | return new MethodReturnTypeMatcher < T > ( matcher ) ; |
public class NamespaceMap { /** * Add a replica ' s meta information into the map
* @ param replicaInfo
* a replica ' s meta information
* @ return previous meta information of the replica
* @ throws IllegalArgumentException
* if the input parameter is null */
DatanodeBlockInfo addBlockInfo ( Block block , DatanodeBlockInfo replicaInfo ) { } } | return getBlockBucket ( block ) . addBlockInfo ( block , replicaInfo ) ; |
public class CPDefinitionLocalizationUtil { /** * Returns the last cp definition localization in the ordered set where CPDefinitionId = & # 63 ; .
* @ param CPDefinitionId the cp definition ID
* @ param orderByComparator the comparator to order the set by ( optionally < code > null < / code > )
* @ return the last matching cp definition localization , or < code > null < / code > if a matching cp definition localization could not be found */
public static CPDefinitionLocalization fetchByCPDefinitionId_Last ( long CPDefinitionId , OrderByComparator < CPDefinitionLocalization > orderByComparator ) { } } | return getPersistence ( ) . fetchByCPDefinitionId_Last ( CPDefinitionId , orderByComparator ) ; |
public class DependencyTable { /** * SKS - O */
public boolean removeEntry ( Object dependency , Object entry ) { } } | // SKS - O
boolean found = false ; ValueSet valueSet = ( ValueSet ) dependencyToEntryTable . get ( dependency ) ; if ( valueSet == null ) { return found ; } found = valueSet . remove ( entry ) ; if ( valueSet . size ( ) == 0 ) removeDependency ( dependency ) ; return found ; |
public class Roster { /** * Fires roster presence changed event to roster listeners .
* @ param presence the presence change . */
private void fireRosterPresenceEvent ( final Presence presence ) { } } | synchronized ( rosterListenersAndEntriesLock ) { for ( RosterListener listener : rosterListeners ) { listener . presenceChanged ( presence ) ; } } |
public class RolesInner { /** * Lists all the roles configured in a data box edge / gateway device .
* @ param deviceName The device name .
* @ param resourceGroupName The resource group name .
* @ throws IllegalArgumentException thrown if parameters fail the validation
* @ return the observable to the PagedList & lt ; RoleInner & gt ; object */
public Observable < Page < RoleInner > > listByDataBoxEdgeDeviceAsync ( final String deviceName , final String resourceGroupName ) { } } | return listByDataBoxEdgeDeviceWithServiceResponseAsync ( deviceName , resourceGroupName ) . map ( new Func1 < ServiceResponse < Page < RoleInner > > , Page < RoleInner > > ( ) { @ Override public Page < RoleInner > call ( ServiceResponse < Page < RoleInner > > response ) { return response . body ( ) ; } } ) ; |
public class InternalEventBusSkill { /** * This function runs the initialization of the agent .
* @ param event the { @ link Initialize } occurrence . */
private void runInitializationStage ( Event event ) { } } | // Immediate synchronous dispatching of Initialize event
try { setOwnerState ( OwnerState . INITIALIZING ) ; try { this . eventDispatcher . immediateDispatch ( event ) ; } finally { setOwnerState ( OwnerState . ALIVE ) ; } this . agentAsEventListener . fireEnqueuedEvents ( this ) ; if ( this . agentAsEventListener . isKilled . get ( ) ) { this . agentAsEventListener . killOwner ( InternalEventBusSkill . this ) ; } } catch ( Exception e ) { // Log the exception
final Logging loggingCapacity = getLoggingSkill ( ) ; if ( loggingCapacity != null ) { loggingCapacity . error ( Messages . InternalEventBusSkill_3 , e ) ; } else { final LogRecord record = new LogRecord ( Level . SEVERE , Messages . InternalEventBusSkill_3 ) ; this . logger . getKernelLogger ( ) . log ( this . logger . prepareLogRecord ( record , this . logger . getKernelLogger ( ) . getName ( ) , Throwables . getRootCause ( e ) ) ) ; } // If we have an exception within the agent ' s initialization , we kill the agent .
setOwnerState ( OwnerState . ALIVE ) ; // Asynchronous kill of the event .
this . agentAsEventListener . killOrMarkAsKilled ( ) ; } |
public class ExpressionParser { /** * Parses the { @ literal < semver - expr > } non - terminal .
* < pre >
* { @ literal
* < semver - expr > : : = " ( " < semver - expr > " ) "
* | " ! " " ( " < semver - expr > " ) "
* | < semver - expr > < boolean - expr >
* | < expr >
* < / pre >
* @ return the expression AST */
private Expression parseSemVerExpression ( ) { } } | Expression expr ; if ( tokens . positiveLookahead ( NOT ) ) { tokens . consume ( ) ; consumeNextToken ( LEFT_PAREN ) ; expr = new Not ( parseSemVerExpression ( ) ) ; consumeNextToken ( RIGHT_PAREN ) ; } else if ( tokens . positiveLookahead ( LEFT_PAREN ) ) { consumeNextToken ( LEFT_PAREN ) ; expr = parseSemVerExpression ( ) ; consumeNextToken ( RIGHT_PAREN ) ; } else { expr = parseExpression ( ) ; } return parseBooleanExpression ( expr ) ; |
public class IntegerExtensions { /** * The binary < code > signed left shift < / code > operator . This is the equivalent to the java < code > & lt ; & lt ; < / code > operator .
* Fills in a zero as the least significant bit .
* @ param a
* an integer .
* @ param distance
* the number of times to shift .
* @ return < code > a & lt ; & lt ; distance < / code >
* @ deprecated use { @ link # operator _ doubleLessThan ( int , int ) } instead */
@ Pure @ Inline ( value = "($1 << $2)" , constantExpression = true ) @ Deprecated public static int shiftLeft ( int a , int distance ) { } } | return a << distance ; |
public class HtmlDoctype { /** * < p > Set the value of the < code > public < / code > property . < / p > */
public void setPublic ( java . lang . String _public ) { } } | getStateHelper ( ) . put ( PropertyKeys . publicVal , _public ) ; handleAttribute ( "public" , _public ) ; |
public class WFieldLayout { /** * Sets the label width .
* @ param labelWidth the percentage width , or & lt ; = 0 to use the default field width . */
public void setLabelWidth ( final int labelWidth ) { } } | if ( labelWidth > 100 ) { throw new IllegalArgumentException ( "labelWidth (" + labelWidth + ") cannot be greater than 100 percent." ) ; } getOrCreateComponentModel ( ) . labelWidth = Math . max ( 0 , labelWidth ) ; |
public class RecoveryInterceptor { /** * Resolves a fallback for the given execution context and exception .
* @ param context The context
* @ param exception The exception
* @ return Returns the fallback value or throws the original exception */
protected Object resolveFallback ( MethodInvocationContext < Object , Object > context , RuntimeException exception ) { } } | if ( exception instanceof NoAvailableServiceException ) { NoAvailableServiceException nase = ( NoAvailableServiceException ) exception ; if ( LOG . isErrorEnabled ( ) ) { LOG . debug ( nase . getMessage ( ) , nase ) ; LOG . error ( "Type [{}] attempting to resolve fallback for unavailable service [{}]" , context . getTarget ( ) . getClass ( ) . getName ( ) , nase . getServiceID ( ) ) ; } } else { if ( LOG . isErrorEnabled ( ) ) { LOG . error ( "Type [" + context . getTarget ( ) . getClass ( ) . getName ( ) + "] executed with error: " + exception . getMessage ( ) , exception ) ; } } Optional < ? extends MethodExecutionHandle < ? , Object > > fallback = findFallbackMethod ( context ) ; if ( fallback . isPresent ( ) ) { MethodExecutionHandle < ? , Object > fallbackMethod = fallback . get ( ) ; try { if ( LOG . isDebugEnabled ( ) ) { LOG . debug ( "Type [{}] resolved fallback: {}" , context . getTarget ( ) . getClass ( ) . getName ( ) , fallbackMethod ) ; } return fallbackMethod . invoke ( context . getParameterValues ( ) ) ; } catch ( Exception e ) { throw new FallbackException ( "Error invoking fallback for type [" + context . getTarget ( ) . getClass ( ) . getName ( ) + "]: " + e . getMessage ( ) , e ) ; } } else { throw exception ; } |
public class AbstractUserSession { /** * Naive implementation , to be overridden if needed */
protected List < ComponentDto > doKeepAuthorizedComponents ( String permission , Collection < ComponentDto > components ) { } } | boolean allowPublicComponent = PUBLIC_PERMISSIONS . contains ( permission ) ; return components . stream ( ) . filter ( c -> ( allowPublicComponent && ! c . isPrivate ( ) ) || hasComponentPermission ( permission , c ) ) . collect ( MoreCollectors . toList ( ) ) ; |
public class Misc { /** * Check that a string parameter is not null or empty and throw IllegalArgumentException with a
* message of errorMessagePrefix + " must not be empty . " if it is empty , defaulting to
* " Parameter must not be empty " .
* @ param param the string to check
* @ param errorMessagePrefix the prefix of the error message to use for the
* IllegalArgumentException if the parameter was null or empty
* @ throws IllegalArgumentException if the string is null or empty */
public static void checkNotNullOrEmpty ( String param , String errorMessagePrefix ) throws IllegalArgumentException { } } | checkNotNull ( param , errorMessagePrefix ) ; checkArgument ( ! param . isEmpty ( ) , ( errorMessagePrefix != null ? errorMessagePrefix : "Parameter" ) + " must not be empty." ) ; |
public class Scope { /** * Return the broadcast scope for a given name
* @ param name
* name
* @ return broadcast scope or null if not found */
public IBroadcastScope getBroadcastScope ( String name ) { } } | return ( IBroadcastScope ) children . getBasicScope ( ScopeType . BROADCAST , name ) ; |
public class MultisetUtils { /** * Returns the partial { @ link Ordering } over { @ link Multiset . Entry } s resulting from applying
* the supplied { @ code comparator } to the multiset elements . */
public static < ElementType > Ordering < Multiset . Entry < ElementType > > byElementOrdering ( Comparator < ? super ElementType > comparator ) { } } | return Ordering . from ( comparator ) . onResultOf ( MultisetUtils . < ElementType > elementOnly ( ) ) ; |
public class ChangeSetAdapter { /** * Handle the change of a node .
* @ param workspaceName the workspace in which the node information should be available ; may not be null
* @ param key the unique key for the node ; may not be null
* @ param path the path of the node ; may not be null
* @ param primaryType the primary type of the node ; may not be null
* @ param mixinTypes the mixin types for the node ; may not be null but may be empty */
protected void changeNode ( String workspaceName , NodeKey key , Path path , Name primaryType , Set < Name > mixinTypes ) { } } | |
public class TimestampFilterUtil { /** * Converts a [ startMs , endMs ) timestamps to a Cloud Bigtable [ startMicros , endMicros ) filter .
* @ param hbaseStartTimestamp a long value .
* @ param hbaseEndTimestamp a long value .
* @ return a { @ link Filter } object . */
public static Filter hbaseToTimestampRangeFilter ( long hbaseStartTimestamp , long hbaseEndTimestamp ) { } } | return toTimestampRangeFilter ( TimestampConverter . hbase2bigtable ( hbaseStartTimestamp ) , TimestampConverter . hbase2bigtable ( hbaseEndTimestamp ) ) ; |
public class SeaGlassIcon { /** * Scale a size based on the " JComponent . sizeVariant " client property of the
* component that is using this icon
* @ param context The synthContext to get the component from
* @ param size The size to scale
* @ return The scaled size or original if " JComponent . sizeVariant " is not
* set */
private int scale ( SynthContext context , int size ) { } } | if ( context == null || context . getComponent ( ) == null ) { return size ; } // The key " JComponent . sizeVariant " is used to match Apple ' s LAF
String scaleKey = SeaGlassStyle . getSizeVariant ( context . getComponent ( ) ) ; if ( scaleKey != null ) { if ( SeaGlassStyle . LARGE_KEY . equals ( scaleKey ) ) { size *= SeaGlassStyle . LARGE_SCALE ; } else if ( SeaGlassStyle . SMALL_KEY . equals ( scaleKey ) ) { size *= SeaGlassStyle . SMALL_SCALE ; } else if ( SeaGlassStyle . MINI_KEY . equals ( scaleKey ) ) { // mini is not quite as small for icons as full mini is
// just too tiny
size *= SeaGlassStyle . MINI_SCALE + 0.07 ; } } return size ; |
public class VarTupleSet { /** * Returns input tuples already used in a test case that bind the given variable , considering
* only tuples that are ( not ) once - only */
public Iterator < Tuple > getUsed ( VarDef var , final boolean onceOnly ) { } } | return getBinds ( IteratorUtils . filteredIterator ( getUsed ( ) , tuple -> tuple . isOnce ( ) == onceOnly ) , var ) ; |
public class ListUsersInGroupResult { /** * The users returned in the request to list users .
* @ param users
* The users returned in the request to list users . */
public void setUsers ( java . util . Collection < UserType > users ) { } } | if ( users == null ) { this . users = null ; return ; } this . users = new java . util . ArrayList < UserType > ( users ) ; |
public class AWSSimpleSystemsManagementClient { /** * Retrieve parameters in a specific hierarchy . For more information , see < a
* href = " http : / / docs . aws . amazon . com / systems - manager / latest / userguide / sysman - paramstore - working . html " > Working with
* Systems Manager Parameters < / a > in the < i > AWS Systems Manager User Guide < / i > .
* Request results are returned on a best - effort basis . If you specify < code > MaxResults < / code > in the request , the
* response includes information up to the limit specified . The number of items returned , however , can be between
* zero and the value of < code > MaxResults < / code > . If the service reaches an internal limit while processing the
* results , it stops the operation and returns the matching values up to that point and a < code > NextToken < / code > .
* You can specify the < code > NextToken < / code > in a subsequent call to get the next set of results .
* < note >
* This API action doesn ' t support filtering by tags .
* < / note >
* @ param getParametersByPathRequest
* @ return Result of the GetParametersByPath operation returned by the service .
* @ throws InternalServerErrorException
* An error occurred on the server side .
* @ throws InvalidFilterKeyException
* The specified key is not valid .
* @ throws InvalidFilterOptionException
* The specified filter option is not valid . Valid options are Equals and BeginsWith . For Path filter , valid
* options are Recursive and OneLevel .
* @ throws InvalidFilterValueException
* The filter value is not valid . Verify the value and try again .
* @ throws InvalidKeyIdException
* The query key ID is not valid .
* @ throws InvalidNextTokenException
* The specified token is not valid .
* @ sample AWSSimpleSystemsManagement . GetParametersByPath
* @ see < a href = " http : / / docs . aws . amazon . com / goto / WebAPI / ssm - 2014-11-06 / GetParametersByPath " target = " _ top " > AWS API
* Documentation < / a > */
@ Override public GetParametersByPathResult getParametersByPath ( GetParametersByPathRequest request ) { } } | request = beforeClientExecution ( request ) ; return executeGetParametersByPath ( request ) ; |
public class SoapServlet { /** * Allow version specific factory passed in TODO : allow specifying response
* headers */
protected String createSoapResponse ( String soapVersion , String xml ) throws SOAPException { } } | try { SOAPMessage soapMessage = getSoapMessageFactory ( soapVersion ) . createMessage ( ) ; SOAPBody soapBody = soapMessage . getSOAPBody ( ) ; soapBody . addDocument ( DomHelper . toDomDocument ( xml ) ) ; return DomHelper . toXml ( soapMessage . getSOAPPart ( ) . getDocumentElement ( ) ) ; } catch ( Exception ex ) { throw new SOAPException ( ex . getMessage ( ) , ex ) ; } |
public class UriTemplate { /** * Append a uri fragment to the template .
* @ param uriTemplate to append to .
* @ param fragment to append .
* @ return a new UriTemplate with the fragment appended . */
public static UriTemplate append ( UriTemplate uriTemplate , String fragment ) { } } | return new UriTemplate ( uriTemplate . toString ( ) + fragment , uriTemplate . encodeSlash ( ) , uriTemplate . getCharset ( ) ) ; |
public class ForkJoinTask { /** * Returns an estimate of the number of tasks that have been forked by the current worker thread
* but not yet executed . This value may be useful for heuristic decisions about whether to fork
* other tasks .
* @ return the number of tasks */
public static int getQueuedTaskCount ( ) { } } | Thread t ; ForkJoinPool . WorkQueue q ; if ( ( t = Thread . currentThread ( ) ) instanceof ForkJoinWorkerThread ) q = ( ( ForkJoinWorkerThread ) t ) . workQueue ; else q = ForkJoinPool . commonSubmitterQueue ( ) ; return ( q == null ) ? 0 : q . queueSize ( ) ; |
public class Convert { /** * 十六进制转换字符串
* @ param hexStr Byte字符串 ( Byte之间无分隔符 如 : [ 616C6B ] )
* @ param charset 编码 { @ link Charset }
* @ return 对应的字符串
* @ see HexUtil # decodeHexStr ( String , Charset )
* @ deprecated 请使用 { @ link # hexToStr ( String , Charset ) } */
@ Deprecated public static String hexStrToStr ( String hexStr , Charset charset ) { } } | return hexToStr ( hexStr , charset ) ; |
public class SequenceQuality { /** * Factory method for the SequenceQualityPhred object . It performs all necessary range checks if required .
* @ param format format of encoded quality values
* @ param data byte with encoded quality values
* @ param check determines whether range check is required
* @ return quality line object
* @ throws WrongQualityFormat if encoded value are out of range and checking is enabled */
public static SequenceQuality create ( QualityFormat format , byte [ ] data , boolean check ) { } } | return create ( format , data , 0 , data . length , check ) ; |
public class DomainsInner { /** * Get all domains in a subscription .
* Get all domains in a subscription .
* @ throws IllegalArgumentException thrown if parameters fail the validation
* @ return the observable to the PagedList & lt ; DomainInner & gt ; object */
public Observable < Page < DomainInner > > listAsync ( ) { } } | return listWithServiceResponseAsync ( ) . map ( new Func1 < ServiceResponse < Page < DomainInner > > , Page < DomainInner > > ( ) { @ Override public Page < DomainInner > call ( ServiceResponse < Page < DomainInner > > response ) { return response . body ( ) ; } } ) ; |
public class VoltTable { /** * Return a " pretty print " representation of this table with or without column names .
* Output will be formatted in a tabular textual format suitable for display .
* @ param includeColumnNames Flag to control if column names should be included or not .
* @ return A string containing a pretty - print formatted representation of this table . */
public String toFormattedString ( boolean includeColumnNames ) { } } | final int MAX_PRINTABLE_CHARS = 30 ; // chose print width for geography column such that it can print polygon in
// aligned manner with geography column for a polygon up to :
// a polygon composed of 4 vertices + 1 repeat vertex ,
// one ring , each coordinate of vertex having 5 digits space including the sign of lng / lat
final int MAX_PRINTABLE_CHARS_GEOGRAPHY = 74 ; final String ELLIPSIS = "..." ; final String DECIMAL_FORMAT = "%01.12f" ; StringBuffer sb = new StringBuffer ( ) ; int columnCount = getColumnCount ( ) ; int [ ] padding = new int [ columnCount ] ; String [ ] fmt = new String [ columnCount ] ; // start with minimum padding based on length of column names . this gets
// increased later as needed
for ( int i = 0 ; i < columnCount ; i ++ ) { padding [ i ] = getColumnName ( i ) . length ( ) ; // min value to be increased later
} resetRowPosition ( ) ; // Compute the padding needed for each column of the table ( note : must
// visit every row )
while ( advanceRow ( ) ) { for ( int i = 0 ; i < columnCount ; i ++ ) { VoltType colType = getColumnType ( i ) ; Object value = get ( i , colType ) ; int width ; if ( wasNull ( ) ) { width = 4 ; } else if ( colType == VoltType . DECIMAL ) { BigDecimal bd = ( BigDecimal ) value ; String valueStr = String . format ( DECIMAL_FORMAT , bd . doubleValue ( ) ) ; width = valueStr . length ( ) ; } // crop long strings and such
else { if ( colType == VoltType . VARBINARY ) { width = ( ( byte [ ] ) value ) . length * 2 ; } else { width = value . toString ( ) . length ( ) ; } if ( ( ( colType == VoltType . GEOGRAPHY ) && ( width > MAX_PRINTABLE_CHARS_GEOGRAPHY ) ) || ( ( colType != VoltType . GEOGRAPHY ) && ( width > MAX_PRINTABLE_CHARS ) ) ) { width = ( colType == VoltType . GEOGRAPHY ) ? MAX_PRINTABLE_CHARS_GEOGRAPHY : MAX_PRINTABLE_CHARS ; } } // Adjust the max width for each column
if ( width > padding [ i ] ) { padding [ i ] = width ; } } } String pad = "" ; // no pad before first column header .
// calculate formating space based on columns .
// Append column names and separator line to buffer
for ( int i = 0 ; i < columnCount ; i ++ ) { padding [ i ] += 1 ; // Determine the formatting string for each column
VoltType colType = getColumnType ( i ) ; String justification = ( colType . isVariableLength ( ) || colType == VoltType . TIMESTAMP || colType == VoltType . GEOGRAPHY_POINT ) ? "-" : "" ; fmt [ i ] = "%1$" + justification + padding [ i ] + "s" ; if ( includeColumnNames ) { // Serialize the column headers
sb . append ( pad ) . append ( String . format ( "%1$-" + padding [ i ] + "s" , getColumnName ( i ) ) ) ; pad = " " ; } } if ( includeColumnNames ) { // construct separator to be used between column name header and table values
sb . append ( "\n" ) ; // Serialize the separator between the column headers and the rows of data
pad = "" ; for ( int i = 0 ; i < columnCount ; i ++ ) { char [ ] underline_array = new char [ padding [ i ] ] ; Arrays . fill ( underline_array , '-' ) ; sb . append ( pad ) . append ( new String ( underline_array ) ) ; pad = " " ; } sb . append ( "\n" ) ; } // Serialize each formatted row of data .
resetRowPosition ( ) ; while ( advanceRow ( ) ) { pad = "" ; for ( int i = 0 ; i < columnCount ; i ++ ) { VoltType colType = getColumnType ( i ) ; Object value = get ( i , colType ) ; String valueStr ; if ( wasNull ( ) ) { valueStr = "NULL" ; } else if ( colType == VoltType . DECIMAL ) { BigDecimal bd = ( BigDecimal ) value ; valueStr = String . format ( DECIMAL_FORMAT , bd . doubleValue ( ) ) ; } else { if ( colType == VoltType . VARBINARY ) { valueStr = Encoder . hexEncode ( ( byte [ ] ) value ) ; // crop long varbinaries
if ( valueStr . length ( ) > MAX_PRINTABLE_CHARS ) { valueStr = valueStr . substring ( 0 , MAX_PRINTABLE_CHARS - ELLIPSIS . length ( ) ) + ELLIPSIS ; } } else { valueStr = value . toString ( ) ; } } sb . append ( pad ) . append ( String . format ( fmt [ i ] , valueStr ) ) ; pad = " " ; } sb . append ( "\n" ) ; } // Idempotent . Reset the row position for the next guy . . .
resetRowPosition ( ) ; return sb . toString ( ) ; |
public class AbstractResourceBundleHandler { /** * Initialize the temporary directories
* @ param tempDirRoot
* the temporary directory root
* @ param createTempSubDir
* the flag indicating if we should create the temporary
* directory . */
private void initTempDirectory ( String tempDirRoot , boolean createTempSubDir ) { } } | tempDirPath = tempDirRoot ; // In windows , pathnames with spaces are returned as % 20
if ( tempDirPath . contains ( "%20" ) ) tempDirPath = tempDirPath . replaceAll ( "%20" , " " ) ; this . textDirPath = tempDirPath + File . separator + TEMP_TEXT_SUBDIR ; this . gzipDirPath = tempDirPath + File . separator + TEMP_GZIP_SUBDIR ; this . cssClasspathDirPath = tempDirPath + File . separator + TEMP_CSS_CLASSPATH_SUBDIR ; if ( createTempSubDir ) { try { createDir ( tempDirPath ) ; createDir ( textDirPath ) ; createDir ( gzipDirPath ) ; createDir ( cssClasspathDirPath ) ; } catch ( IOException e ) { throw new BundlingProcessException ( "Unexpected IOException creating temporary jawr directory" , e ) ; } } |
public class SessionContext { /** * puts the key , value into the map . a null value will remove the key from the map
* @ param key
* @ param value */
public void set ( String key , Object value ) { } } | if ( value != null ) put ( key , value ) ; else remove ( key ) ; |
public class SpringMVCAttribute { /** * TODO : fix the isInFk for pureMany2Many */
public String getTagName ( ) { } } | if ( attribute . isHidden ( ) && ! attribute . isFile ( ) ) { return "hidden" ; } else if ( attribute . isInFk ( ) && attribute . hasXToOneRelation ( ) ) { return "select" ; } else if ( attribute . isFile ( ) ) { return "file" ; } else if ( attribute . isPassword ( ) ) { return "password" ; } else if ( attribute . isString ( ) && ( attribute . getColumnConfig ( ) . getSize ( ) > 256 || attribute . getColumnConfig ( ) . getSize ( ) == - 1 ) ) { return "textarea" ; } else if ( attribute . isBoolean ( ) ) { return "checkbox" ; } else { return "input" ; } |
public class GeometricSearchPanel { public void geometryUpdate ( Geometry oldGeometry , Geometry newGeometry ) { } } | if ( oldGeometry != null ) { geometries . remove ( oldGeometry ) ; } if ( newGeometry != null ) { geometries . add ( newGeometry ) ; } if ( geometries . size ( ) == 0 ) { searchGeometry = null ; updateGeometryOnMap ( ) ; } else if ( geometries . size ( ) == 1 ) { searchGeometry = geometries . get ( 0 ) ; updateGeometryOnMap ( ) ; } else { SearchCommService . mergeGeometries ( geometries , new DataCallback < Geometry > ( ) { public void execute ( Geometry result ) { searchGeometry = result ; updateGeometryOnMap ( ) ; } } ) ; } |
public class HCCSSNodeDetector { /** * Check if the passed node is a CSS node after unwrapping .
* @ param aNode
* The node to be checked - may be < code > null < / code > .
* @ return < code > true < / code > if the node implements { @ link HCStyle } or
* { @ link HCLink } ( and not a special case ) . */
public static boolean isCSSNode ( @ Nullable final IHCNode aNode ) { } } | final IHCNode aUnwrappedNode = HCHelper . getUnwrappedNode ( aNode ) ; return isDirectCSSNode ( aUnwrappedNode ) ; |
public class UnionFlattenerImpl { /** * TODO : why a fix point ? */
@ Override public IQ optimize ( IQ query ) { } } | TreeTransformer treeTransformer = new TreeTransformer ( query . getVariableGenerator ( ) ) ; IQ prev ; do { prev = query ; query = iqFactory . createIQ ( query . getProjectionAtom ( ) , query . getTree ( ) . acceptTransformer ( treeTransformer ) ) ; } while ( ! prev . equals ( query ) ) ; return query ; |
public class nssavedconfig { /** * Use this API to fetch all the nssavedconfig resources that are configured on netscaler . */
public static nssavedconfig get ( nitro_service service ) throws Exception { } } | nssavedconfig obj = new nssavedconfig ( ) ; nssavedconfig [ ] response = ( nssavedconfig [ ] ) obj . get_resources ( service ) ; return response [ 0 ] ; |
public class WriteExcelUtils { /** * 向某一WorkBook中写入多个Bean
* @ param workbook 指定工作簿
* @ param _ titleRow 指定写入的标题在第几行 , 0 - based
* @ param count 指定每个Sheet写入几个bean
* @ param beans 指定写入的Beans ( 或者泛型为Map )
* @ param properties 指定写入的bean的属性
* @ param titles 指定写入的标题
* @ param dateFormat 日期格式
* @ return 返回传入的WorkBook */
public static < T > Workbook writeWorkBook ( Workbook workbook , int _titleRow , int count , List < T > beans , List < String > properties , List < String > titles , String dateFormat ) { } } | int sheetNum = beans . size ( ) % count == 0 ? beans . size ( ) / count : ( beans . size ( ) / count + 1 ) ; for ( int i = 0 ; i < sheetNum ; i ++ ) { WriteExcelUtils . writePerSheet ( workbook . createSheet ( ) , _titleRow , i * count , i * count + count , beans , properties , titles , dateFormat ) ; } return workbook ; |
public class AsyncAssembly { /** * Runs intermediate check on the Assembly status until it is finished executing ,
* then returns it as a response .
* @ return { @ link AssemblyResponse }
* @ throws LocalOperationException if something goes wrong while running non - http operations .
* @ throws RequestException if request to Transloadit server fails . */
protected AssemblyResponse watchStatus ( ) throws LocalOperationException , RequestException { } } | AssemblyResponse response ; do { response = getClient ( ) . getAssemblyByUrl ( url ) ; try { Thread . sleep ( 1000 ) ; } catch ( InterruptedException e ) { throw new LocalOperationException ( e ) ; } } while ( ! response . isFinished ( ) ) ; setState ( State . FINISHED ) ; return response ; |
public class AJP13InputStream { public long skip ( long n ) throws IOException { } } | if ( _closed ) return - 1 ; for ( int i = 0 ; i < n ; i ++ ) if ( read ( ) < 0 ) return i == 0 ? - 1 : i ; return n ; |
public class HammingCode { /** * Is prefix free code boolean .
* @ param keySet the key set
* @ return the boolean */
public static boolean isPrefixFreeCode ( final Set < Bits > keySet ) { } } | final TreeSet < Bits > check = new TreeSet < Bits > ( ) ; for ( final Bits code : keySet ) { final Bits ceiling = check . ceiling ( code ) ; if ( null != ceiling && ( ceiling . startsWith ( code ) || code . startsWith ( ceiling ) ) ) { return false ; } final Bits floor = check . floor ( code ) ; if ( null != floor && ( floor . startsWith ( code ) || code . startsWith ( floor ) ) ) { return false ; } check . add ( code ) ; } return true ; |
public class AppServiceEnvironmentsInner { /** * Get properties of a multi - role pool .
* Get properties of a multi - role pool .
* @ param resourceGroupName Name of the resource group to which the resource belongs .
* @ param name Name of the App Service Environment .
* @ throws IllegalArgumentException thrown if parameters fail the validation
* @ return the observable to the WorkerPoolResourceInner object */
public Observable < WorkerPoolResourceInner > getMultiRolePoolAsync ( String resourceGroupName , String name ) { } } | return getMultiRolePoolWithServiceResponseAsync ( resourceGroupName , name ) . map ( new Func1 < ServiceResponse < WorkerPoolResourceInner > , WorkerPoolResourceInner > ( ) { @ Override public WorkerPoolResourceInner call ( ServiceResponse < WorkerPoolResourceInner > response ) { return response . body ( ) ; } } ) ; |
public class FreePool { /** * Return a mcWrapper . Create one if the
* maximum connection limit has not been reached . If the maximum had been reached ,
* queue the request .
* @ throws ResourceAllocationException */
protected MCWrapper createManagedConnectionWithMCWrapper ( ManagedConnectionFactory managedConnectionFactory , Subject subject , ConnectionRequestInfo cri , boolean connectionSharing , int hashCode ) throws ResourceAllocationException { } } | // This method is called within a synchronize block
if ( TraceComponent . isAnyTracingEnabled ( ) && tc . isEntryEnabled ( ) ) { Tr . entry ( this , tc , "createManagedConnectionWithMCWrapper" ) ; } ManagedConnection mc = null ; MCWrapper mcWrapper = null ; try { if ( TraceComponent . isAnyTracingEnabled ( ) && tc . isDebugEnabled ( ) ) Tr . debug ( this , tc , "raClassLoader" , raClassLoader ) ; JcaServiceUtilities jcasu = new JcaServiceUtilities ( ) ; if ( raClassLoader == null ) { mc = managedConnectionFactory . createManagedConnection ( subject , cri ) ; } else { ClassLoader previousClassLoader = jcasu . beginContextClassLoader ( raClassLoader ) ; try { mc = managedConnectionFactory . createManagedConnection ( subject , cri ) ; } finally { jcasu . endContextClassLoader ( raClassLoader , previousClassLoader ) ; } } mcWrapper = new com . ibm . ejs . j2c . MCWrapper ( pm , gConfigProps ) ; mcWrapper . setManagedConnection ( mc ) ; /* * Many threads can hit the following code at the same time . What I a
* expect to happen is that several threads will hit the synchronized
* call until the checkForNoPoolingException is set to false . */
if ( pm . gConfigProps . checkManagedConnectionInstanceof ) { /* * Allow only one thread at a time through the following code */
/* * Double - checked locking works for 32 - bit primitive values . I am
* using a boolean primitive value . */
synchronized ( pm . gConfigProps . checkManagedConnectionInstanceofLock ) { if ( pm . gConfigProps . checkManagedConnectionInstanceof ) { /* * Call matchManagedConnections */
Set < ManagedConnection > s = new HashSet < ManagedConnection > ( ) ; s . add ( mc ) ; try { int poolState = mcWrapper . getPoolState ( ) ; mcWrapper . setPoolState ( 50 ) ; managedConnectionFactory . matchManagedConnections ( s , subject , cri ) ; mcWrapper . setPoolState ( poolState ) ; } catch ( NotSupportedException e ) { /* * If we catch a the NotSupportedException , we need
* to turn off connection pooling . */
gConfigProps . setConnectionPoolingEnabled ( false ) ; } if ( mc instanceof DissociatableManagedConnection ) { /* * set smart handle supported */
pm . gConfigProps . setSmartHandleSupport ( true ) ; pm . createParkedConnection = false ; pm . gConfigProps . setInstanceOfDissociatableManagedConnection ( true ) ; } if ( mc instanceof DissociatableManagedConnection ) { if ( TraceComponent . isAnyTracingEnabled ( ) && tc . isDebugEnabled ( ) ) { Tr . debug ( this , tc , "Managed connection is an instance of DissociatableManagedConnection" ) ; } pm . gConfigProps . setInstanceOfDissociatableManagedConnection ( true ) ; } /* * Deferred enlistment */
if ( mc instanceof LazyEnlistableManagedConnection ) { if ( TraceComponent . isAnyTracingEnabled ( ) && tc . isDebugEnabled ( ) ) { Tr . debug ( this , tc , "Managed connection is an instance of LazyEnlistableManagedConnection" ) ; } pm . gConfigProps . setDynamicEnlistmentSupported ( true ) ; } /* * Create the writer for the managed connection . */
pm . writer = new TraceWriter ( mc . getClass ( ) . getName ( ) ) ; pm . traceWriter = ( TraceWriter ) pm . writer ; pm . printWriter = new PrintWriter ( pm . writer ) ; /* * We only want to execute this code once
* Set this value last in this synchronized block . */
pm . gConfigProps . setCheckManagedConnectionInstanceof ( false ) ; } // moved brace to include above call to setCheckManagedConnectionInstanceof
} // end synchronize
} if ( tc . isDebugEnabled ( ) ) { ++ freePoolCreateManagedConnection ; } mcWrapper . setFatalErrorValue ( fatalErrorNotificationTime + 1 ) ; mcWrapper . setSubjectCRIHashCode ( hashCode ) ; mcWrapper . setSubject ( subject ) ; ( ( com . ibm . ejs . j2c . MCWrapper ) mcWrapper ) . set_managedConnectionFactory ( managedConnectionFactory ) ; mcWrapper . setCRI ( cri ) ; mcWrapper . setSupportsReAuth ( gConfigProps . raSupportsReauthentication ) ; mcWrapper . setConnectionSynchronizationProvider ( gConfigProps . connectionSynchronizationProvider ) ; /* * Check to see if trace has been turned on for
* the managed connection . */
if ( TraceComponent . isAnyTracingEnabled ( ) && tc . isDebugEnabled ( ) ) { Tr . debug ( this , tc , "pm = " , pm ) ; Tr . debug ( this , tc , "traceWriter = " , pm . traceWriter ) ; } if ( pm . traceWriter . isTraceEnabled ( ) ) { /* * Set the log writer on mc */
mc . setLogWriter ( pm . printWriter ) ; mcWrapper . setLogWriterSet ( true ) ; } /* * Make sure conneciton pooling is enabled . The reaper is not needed for
* non poolable resource adapters .
* First check to see if reaper time is set . We will not be starting the reaper thread unless
* its set .
* Next , check to see if its already running . */
if ( gConfigProps . isConnectionPoolingEnabled ( ) ) { if ( ( pm . reapTime > 0 ) ) { if ( pm . alarmThreadCounter . get ( ) == 0 ) { synchronized ( pm . amLockObject ) { if ( pm . alarmThreadCounter . get ( ) == 0 ) { /* * If totalConnectionCount is > minConnections and agedTimeout is not set , start
* the reaper thread .
* If agedTimeout is set and totalConnectionCount is > 0 start the reaper
* thread . */
if ( pm . agedTimeout < 1 ) { if ( ( pm . totalConnectionCount . get ( ) > pm . minConnections ) ) { if ( pm . nonDeferredReaperAlarm ) { if ( TraceComponent . isAnyTracingEnabled ( ) && tc . isDebugEnabled ( ) ) { Tr . debug ( this , tc , "Creating non-deferrable alarm for reaper" ) ; } pm . alarmThreadCounter . incrementAndGet ( ) ; try { pm . am = pm . connectorSvc . nonDeferrableSchedXSvcRef . getServiceWithException ( ) . schedule ( pm , pm . reapTime , TimeUnit . SECONDS ) ; } catch ( Exception e ) { pm . alarmThreadCounter . decrementAndGet ( ) ; throw e ; } } else { if ( TraceComponent . isAnyTracingEnabled ( ) && tc . isDebugEnabled ( ) ) { Tr . debug ( this , tc , "Creating deferrable alarm for reaper" ) ; } pm . alarmThreadCounter . incrementAndGet ( ) ; try { pm . am = pm . connectorSvc . deferrableSchedXSvcRef . getServiceWithException ( ) . schedule ( pm , pm . reapTime , TimeUnit . SECONDS ) ; } catch ( Exception e ) { pm . alarmThreadCounter . decrementAndGet ( ) ; throw e ; } } } } else { if ( pm . totalConnectionCount . get ( ) > 0 ) { if ( pm . nonDeferredReaperAlarm ) { if ( TraceComponent . isAnyTracingEnabled ( ) && tc . isDebugEnabled ( ) ) { Tr . debug ( this , tc , "Creating non-deferrable alarm for reaper" ) ; } pm . alarmThreadCounter . incrementAndGet ( ) ; try { pm . am = pm . connectorSvc . nonDeferrableSchedXSvcRef . getServiceWithException ( ) . schedule ( pm , pm . reapTime , TimeUnit . SECONDS ) ; } catch ( Exception e ) { pm . alarmThreadCounter . decrementAndGet ( ) ; throw e ; } } else { if ( TraceComponent . isAnyTracingEnabled ( ) && tc . isDebugEnabled ( ) ) { Tr . debug ( this , tc , "Creating deferrable alarm for reaper" ) ; } pm . alarmThreadCounter . incrementAndGet ( ) ; try { pm . am = pm . connectorSvc . deferrableSchedXSvcRef . getServiceWithException ( ) . schedule ( pm , pm . reapTime , TimeUnit . SECONDS ) ; } catch ( Exception e ) { pm . alarmThreadCounter . decrementAndGet ( ) ; throw e ; } } } } } } } } } } catch ( ResourceException exn ) { com . ibm . ws . ffdc . FFDCFilter . processException ( exn , "com.ibm.ejs.j2c.poolmanager.FreePool.createManagedConnectionWithMCWrapper" , "199" , this ) ; // call exceptionList method to print stack traces of current and linked exceptions
Object [ ] parms = new Object [ ] { "createManagedConnectionWithMCWrapper" , CommonFunction . exceptionList ( exn ) , "ResourceAllocationException" , gConfigProps . cfName } ; if ( TraceComponent . isAnyTracingEnabled ( ) && tc . isDebugEnabled ( ) ) { Tr . debug ( this , tc , "POOL_MANAGER_EXCP_CCF2_0002_J2CA0046" , parms ) ; } ResourceAllocationException throwMe = new ResourceAllocationException ( exn . getMessage ( ) , exn . getErrorCode ( ) ) ; throwMe . initCause ( exn . getCause ( ) ) ; pm . activeRequest . decrementAndGet ( ) ; if ( TraceComponent . isAnyTracingEnabled ( ) && tc . isEntryEnabled ( ) ) Tr . exit ( this , tc , "createManagedConnectionWithMCWrapper" , throwMe ) ; throw ( throwMe ) ; } catch ( Exception e ) { com . ibm . ws . ffdc . FFDCFilter . processException ( e , "com.ibm.ejs.j2c.poolmanager.FreePool.createManagedConnectionWithMCWrapper" , "545" , this ) ; // call exceptionList method to print stack traces of current and linked exceptions
Object [ ] parms = new Object [ ] { "createManagedConnectionWithMCWrapper" , CommonFunction . exceptionList ( e ) , "ResourceAllocationException" , gConfigProps . cfName } ; Tr . error ( tc , "POOL_MANAGER_EXCP_CCF2_0002_J2CA0046" , parms ) ; ResourceAllocationException throwMe = new ResourceAllocationException ( e . getMessage ( ) ) ; throwMe . initCause ( e ) ; pm . activeRequest . decrementAndGet ( ) ; if ( TraceComponent . isAnyTracingEnabled ( ) && tc . isEntryEnabled ( ) ) Tr . exit ( this , tc , "createManagedConnectionWithMCWrapper" , throwMe ) ; throw ( throwMe ) ; } if ( TraceComponent . isAnyTracingEnabled ( ) && tc . isEntryEnabled ( ) ) { Tr . exit ( this , tc , "createManagedConnectionWithMCWrapper" , mcWrapper ) ; } return mcWrapper ; |
public class Jar { /** * Returns an attribute ' s list value from a non - main section of this JAR ' s manifest .
* The attributes string value will be split on whitespace into the returned list .
* The returned list may be safely modified .
* @ param section the manifest ' s section
* @ param name the attribute ' s name */
public List < String > getListAttribute ( String section , String name ) { } } | return split ( getAttribute ( section , name ) ) ; |
public class DirectionsPane { /** * Adds a handler for a state type event on the map .
* We could allow this to handle any state event by adding a parameter
* JavascriptObject obj , but we would then need to loosen up the event type
* and either accept a String value , or fill an enum with all potential
* state events .
* @ param type Type of the event to register against .
* @ param h Handler that will be called when the event occurs . */
public void addStateEventHandler ( MapStateEventType type , StateEventHandler h ) { } } | String key = registerEventHandler ( h ) ; String mcall = "google.maps.event.addListener(" + getVariableName ( ) + ", '" + type . name ( ) + "', " + "function() {document.jsHandlers.handleStateEvent('" + key + "');});" ; // System . out . println ( " addStateEventHandler mcall : " + mcall ) ;
runtime . execute ( mcall ) ; |
public class Order { /** * Add values for PaymentExecutionDetail , return this .
* @ param paymentExecutionDetail
* New values to add .
* @ return This instance . */
public Order withPaymentExecutionDetail ( PaymentExecutionDetailItem ... values ) { } } | List < PaymentExecutionDetailItem > list = getPaymentExecutionDetail ( ) ; for ( PaymentExecutionDetailItem value : values ) { list . add ( value ) ; } return this ; |
public class RelationalOperations { /** * Returns true if polygon _ a touches envelope _ b . */
private static boolean polygonTouchesEnvelope_ ( Polygon polygon_a , Envelope envelope_b , double tolerance , ProgressTracker progress_tracker ) { } } | // Quick rasterize test to see whether the the geometries are disjoint ,
// or if one is contained in the other .
int relation = tryRasterizedContainsOrDisjoint_ ( polygon_a , envelope_b , tolerance , false ) ; if ( relation == Relation . disjoint || relation == Relation . contains || relation == Relation . within ) return false ; Envelope2D env_a = new Envelope2D ( ) , env_b = new Envelope2D ( ) ; polygon_a . queryEnvelope2D ( env_a ) ; envelope_b . queryEnvelope2D ( env_b ) ; if ( envelopeInfContainsEnvelope_ ( env_b , env_a , tolerance ) ) return false ; if ( env_b . getWidth ( ) <= tolerance && env_b . getHeight ( ) <= tolerance ) { // treat
// as
// point
Point2D pt_b = envelope_b . getCenterXY ( ) ; return polygonTouchesPointImpl_ ( polygon_a , pt_b , tolerance , progress_tracker ) ; } if ( env_b . getWidth ( ) <= tolerance || env_b . getHeight ( ) <= tolerance ) { // treat
// as
// polyline
Polyline polyline_b = new Polyline ( ) ; Point p = new Point ( ) ; envelope_b . queryCornerByVal ( 0 , p ) ; polyline_b . startPath ( p ) ; envelope_b . queryCornerByVal ( 2 , p ) ; polyline_b . lineTo ( p ) ; return polygonTouchesPolylineImpl_ ( polygon_a , polyline_b , tolerance , progress_tracker ) ; } // treat as polygon
Polygon polygon_b = new Polygon ( ) ; polygon_b . addEnvelope ( envelope_b , false ) ; return polygonTouchesPolygonImpl_ ( polygon_a , polygon_b , tolerance , progress_tracker ) ; |
public class LinkedList { /** * Returns the first element which contains ' object ' starting from the head .
* @ param object Object which is being searched for
* @ return First element which contains object or null if none can be found */
public Element < T > find ( T object ) { } } | Element < T > e = first ; while ( e != null ) { if ( e . object == object ) { return e ; } e = e . next ; } return null ; |
public class EndpointDelegate { /** * { @ inheritDoc } */
@ Override public void onClose ( Session session , CloseReason closeReason ) { } } | meta . onClose ( session , closeReason ) ; |
public class MPGroup { /** * Returns true if the passed principal is a member of the group .
* This method does a recursive search , so if a principal belongs to a
* group which is a member of this group , true is returned .
* @ param member the principal whose membership is to be checked .
* @ return true if the principal is a member of this group ,
* false otherwise . */
public boolean isMember ( Principal member ) { } } | if ( TraceComponent . isAnyTracingEnabled ( ) && tc . isEntryEnabled ( ) ) SibTr . entry ( tc , "isMember" , "is: " + member + ", a member of: " + this ) ; boolean result = false ; if ( member instanceof MPPrincipal ) { List theGroups = ( ( MPPrincipal ) member ) . getGroups ( ) ; if ( theGroups != null ) result = theGroups . contains ( getName ( ) ) ; } if ( TraceComponent . isAnyTracingEnabled ( ) && tc . isEntryEnabled ( ) ) SibTr . exit ( tc , "isMember" , new Boolean ( result ) ) ; return result ; |
public class OneForOneStreamManager { /** * Registers a stream of ManagedBuffers which are served as individual chunks one at a time to
* callers . Each ManagedBuffer will be release ( ) ' d after it is transferred on the wire . If a
* client connection is closed before the iterator is fully drained , then the remaining buffers
* will all be release ( ) ' d .
* If an app ID is provided , only callers who ' ve authenticated with the given app ID will be
* allowed to fetch from this stream .
* This method also associates the stream with a single client connection , which is guaranteed
* to be the only reader of the stream . Once the connection is closed , the stream will never
* be used again , enabling cleanup by ` connectionTerminated ` . */
public long registerStream ( String appId , Iterator < ManagedBuffer > buffers , Channel channel ) { } } | long myStreamId = nextStreamId . getAndIncrement ( ) ; streams . put ( myStreamId , new StreamState ( appId , buffers , channel ) ) ; return myStreamId ; |
public class ComputerVisionImpl { /** * This operation generates a description of an image in human readable language with complete sentences . The description is based on a collection of content tags , which are also returned by the operation . More than one description can be generated for each image . Descriptions are ordered by their confidence score . All descriptions are in English . Two input methods are supported - - ( 1 ) Uploading an image or ( 2 ) specifying an image URL . A successful response will be returned in JSON . If the request failed , the response will contain an error code and a message to help understand what went wrong .
* @ param image An image stream .
* @ param describeImageInStreamOptionalParameter the object representing the optional parameters to be set before calling this API
* @ throws IllegalArgumentException thrown if parameters fail the validation
* @ return the observable to the ImageDescription object */
public Observable < ImageDescription > describeImageInStreamAsync ( byte [ ] image , DescribeImageInStreamOptionalParameter describeImageInStreamOptionalParameter ) { } } | return describeImageInStreamWithServiceResponseAsync ( image , describeImageInStreamOptionalParameter ) . map ( new Func1 < ServiceResponse < ImageDescription > , ImageDescription > ( ) { @ Override public ImageDescription call ( ServiceResponse < ImageDescription > response ) { return response . body ( ) ; } } ) ; |
public class SqlPkStatement { /** * Generate a where clause for a prepared Statement .
* Only primary key and locking fields are used in this where clause
* @ param cld the ClassDescriptor
* @ param useLocking true if locking fields should be included
* @ param stmt the StatementBuffer */
protected void appendWhereClause ( ClassDescriptor cld , boolean useLocking , StringBuffer stmt ) { } } | FieldDescriptor [ ] pkFields = cld . getPkFields ( ) ; FieldDescriptor [ ] fields ; fields = pkFields ; if ( useLocking ) { FieldDescriptor [ ] lockingFields = cld . getLockingFields ( ) ; if ( lockingFields . length > 0 ) { fields = new FieldDescriptor [ pkFields . length + lockingFields . length ] ; System . arraycopy ( pkFields , 0 , fields , 0 , pkFields . length ) ; System . arraycopy ( lockingFields , 0 , fields , pkFields . length , lockingFields . length ) ; } } appendWhereClause ( fields , stmt ) ; |
public class WyilFile { /** * Create a simple binding function from two tuples representing the key set and
* value set respectively .
* @ param variables
* @ param arguments
* @ return */
public static < T extends SyntacticItem > java . util . function . Function < Identifier , SyntacticItem > bindingFunction ( Tuple < Template . Variable > variables , Tuple < T > arguments ) { } } | return ( Identifier var ) -> { for ( int i = 0 ; i != variables . size ( ) ; ++ i ) { if ( var . equals ( variables . get ( i ) . getName ( ) ) ) { return arguments . get ( i ) ; } } return null ; } ; |
public class ValueConstraintsMatcher { /** * Check given value on compatibility with a given type .
* @ param value ValueData
* @ param type int , property type
* @ return boolean true if the value matches the type , false otherwise
* @ throws RepositoryException if gathering of match conditions meets errors ( IOException or ItemNotFoundException ) */
public boolean match ( ValueData value , int type ) throws RepositoryException { } } | if ( constraints == null || constraints . length <= 0 ) { return true ; } boolean invalid = true ; // do not use getString because of string consuming
ValueData valueData = value ; if ( type == PropertyType . STRING ) { String strVal = ValueDataUtil . getString ( valueData ) ; for ( int i = 0 ; invalid && i < constraints . length ; i ++ ) { String constrString = constraints [ i ] ; if ( strVal . matches ( constrString ) ) { invalid = false ; } } } else if ( type == PropertyType . NAME ) { NameValue nameVal ; try { nameVal = new NameValue ( valueData , locator ) ; } catch ( IOException e ) { throw new RepositoryException ( e ) ; } for ( int i = 0 ; invalid && i < constraints . length ; i ++ ) { String constrString = constraints [ i ] ; InternalQName constrName = locator . parseJCRName ( constrString ) . getInternalName ( ) ; if ( nameVal . getQName ( ) . equals ( constrName ) ) { invalid = false ; } } } else if ( type == PropertyType . PATH ) { PathValue pathVal ; try { pathVal = new PathValue ( valueData , locator ) ; } catch ( IOException e ) { throw new RepositoryException ( e ) ; } for ( int i = 0 ; invalid && i < constraints . length ; i ++ ) { JCRPathMatcher constrPath = parsePathMatcher ( locator , constraints [ i ] ) ; if ( constrPath . match ( pathVal . getQPath ( ) ) ) { invalid = false ; } } } else if ( type == PropertyType . REFERENCE ) { try { ReferenceValue refVal = new ReferenceValue ( valueData ) ; NodeData refNode = ( NodeData ) itemDataConsumer . getItemData ( refVal . getIdentifier ( ) . getString ( ) ) ; for ( int i = 0 ; invalid && i < constraints . length ; i ++ ) { String constrString = constraints [ i ] ; InternalQName constrName = locator . parseJCRName ( constrString ) . getInternalName ( ) ; if ( nodeTypeDataManager . isNodeType ( constrName , refNode . getPrimaryTypeName ( ) , refNode . getMixinTypeNames ( ) ) ) { invalid = false ; } } } catch ( ItemNotFoundException e ) { if ( LOG . isDebugEnabled ( ) ) { LOG . debug ( "Reference constraint node is not found: " + e . getMessage ( ) ) ; } // But if it ' s a versionHisroy ref property for add mix : versionable . . .
// we haven ' t a versionHisroy created until save method will be called
// on this
// session / item . . .
// it ' s transient state here .
invalid = false ; // so , value is matched , we hope . . .
} catch ( RepositoryException e ) { LOG . error ( "Reference constraint error: " + e . getMessage ( ) , e ) ; // [ PN ] Posible trouble is session . getNodeByUUID ( ) call result ,
// till bug can be found in version restore operation .
invalid = true ; } catch ( IOException e ) { LOG . error ( "Reference constraint error: " + e . getMessage ( ) , e ) ; invalid = true ; } } else if ( type == PropertyType . BINARY ) { long valueLength = valueData . getLength ( ) ; for ( int i = 0 ; invalid && i < constraints . length ; i ++ ) { String constrString = constraints [ i ] ; boolean minInvalid = true ; boolean maxInvalid = true ; MinMaxConstraint constraint = parseAsMinMax ( constrString ) ; long min = constraint . getMin ( ) . getThreshold ( ) . length ( ) > 0 ? new Long ( constraint . getMin ( ) . getThreshold ( ) ) : Long . MIN_VALUE ; if ( constraint . getMin ( ) . isExclusive ( ) ) { if ( valueLength > min ) { minInvalid = false ; } } else { if ( valueLength >= min ) { minInvalid = false ; } } long max = constraint . getMax ( ) . getThreshold ( ) . length ( ) > 0 ? new Long ( constraint . getMax ( ) . getThreshold ( ) ) : Long . MAX_VALUE ; if ( constraint . getMax ( ) . isExclusive ( ) ) { if ( valueLength < max ) maxInvalid = false ; } else { if ( valueLength <= max ) maxInvalid = false ; } invalid = maxInvalid | minInvalid ; } } else if ( type == PropertyType . DATE ) { Calendar valueCalendar ; try { valueCalendar = new DateValue ( valueData ) . getDate ( ) ; } catch ( IOException e ) { throw new RepositoryException ( e ) ; } for ( int i = 0 ; invalid && i < constraints . length ; i ++ ) { boolean minInvalid = true ; boolean maxInvalid = true ; MinMaxConstraint constraint = parseAsMinMax ( constraints [ i ] ) ; try { if ( constraint . getMin ( ) . getThreshold ( ) . length ( ) > 0 ) { Calendar min = JCRDateFormat . parse ( constraint . getMin ( ) . getThreshold ( ) ) ; if ( constraint . getMin ( ) . isExclusive ( ) ) { if ( valueCalendar . compareTo ( min ) > 0 ) { minInvalid = false ; } } else { if ( valueCalendar . compareTo ( min ) >= 0 ) { minInvalid = false ; } } } else { minInvalid = false ; } } catch ( ValueFormatException e ) { minInvalid = false ; } try { if ( constraint . getMax ( ) . getThreshold ( ) . length ( ) > 0 ) { Calendar max = JCRDateFormat . parse ( constraint . getMax ( ) . getThreshold ( ) ) ; if ( constraint . getMax ( ) . isExclusive ( ) ) { if ( valueCalendar . compareTo ( max ) < 0 ) maxInvalid = false ; } else { if ( valueCalendar . compareTo ( max ) <= 0 ) maxInvalid = false ; } } else { maxInvalid = false ; } } catch ( ValueFormatException e ) { maxInvalid = false ; } invalid = maxInvalid | minInvalid ; } } else if ( type == PropertyType . LONG || type == PropertyType . DOUBLE ) { // will be compared as double in any case
Number valueNumber ; try { valueNumber = new DoubleValue ( valueData ) . getDouble ( ) ; } catch ( IOException e ) { throw new RepositoryException ( e ) ; } for ( int i = 0 ; invalid && i < constraints . length ; i ++ ) { boolean minInvalid = true ; boolean maxInvalid = true ; MinMaxConstraint constraint = parseAsMinMax ( constraints [ i ] ) ; Number min = constraint . getMin ( ) . getThreshold ( ) . length ( ) > 0 ? new Double ( constraint . getMin ( ) . getThreshold ( ) ) : Double . MIN_VALUE ; if ( constraint . getMin ( ) . isExclusive ( ) ) { if ( valueNumber . doubleValue ( ) > min . doubleValue ( ) ) { minInvalid = false ; } } else { if ( valueNumber . doubleValue ( ) >= min . doubleValue ( ) ) { minInvalid = false ; } } Number max = constraint . getMax ( ) . getThreshold ( ) . length ( ) > 0 ? new Double ( constraint . getMax ( ) . getThreshold ( ) ) : Double . MAX_VALUE ; if ( constraint . getMax ( ) . isExclusive ( ) ) { if ( valueNumber . doubleValue ( ) < max . doubleValue ( ) ) { maxInvalid = false ; } } else { if ( valueNumber . doubleValue ( ) <= max . doubleValue ( ) ) { maxInvalid = false ; } } invalid = maxInvalid | minInvalid ; } } else if ( type == PropertyType . BOOLEAN ) { boolean bvalue = ValueDataUtil . getBoolean ( valueData ) ; for ( int i = 0 ; invalid && i < constraints . length ; i ++ ) { if ( Boolean . parseBoolean ( constraints [ i ] ) == bvalue ) { invalid = false ; } } } return ! invalid ; |
public class TypeSerializerSerializationUtil { /** * Reads from a data input view a { @ link TypeSerializer } that was previously
* written using { @ link # writeSerializer ( DataOutputView , TypeSerializer ) } .
* < p > If deserialization fails for any reason ( corrupted serializer bytes , serializer class
* no longer in classpath , serializer class no longer valid , etc . ) , an { @ link IOException } is thrown .
* @ param in the data input view .
* @ param userCodeClassLoader the user code class loader to use .
* @ param < T > Data type of the serializer .
* @ return the deserialized serializer . */
public static < T > TypeSerializer < T > tryReadSerializer ( DataInputView in , ClassLoader userCodeClassLoader ) throws IOException { } } | return tryReadSerializer ( in , userCodeClassLoader , false ) ; |
public class SimpleDocumentDbRepository { /** * delete one document per id without configuring partition key value
* @ param id */
@ Override public void deleteById ( ID id ) { } } | Assert . notNull ( id , "id to be deleted should not be null" ) ; operation . deleteById ( information . getCollectionName ( ) , id , null ) ; |
public class EmbedVaadinServerBuilder { /** * Loads a configuration file from the specified location . Fails if the
* specified < tt > path < / tt > does not exist .
* @ param path the location of a properties file in the classpath
* @ return this
* @ throws IllegalStateException if no such properties file is found */
public B withConfigPath ( String path ) { } } | assertNotNull ( path , "path could not be null." ) ; withConfigProperties ( EmbedVaadinConfig . loadProperties ( path ) ) ; return self ( ) ; |
public class Permute { /** * This will permute the list once */
public boolean next ( ) { } } | if ( indexes . length <= 1 || permutation >= total - 1 ) return false ; int N = indexes . length - 2 ; int k = N ; swap ( k , counters [ k ] ++ ) ; while ( counters [ k ] == indexes . length ) { k -= 1 ; swap ( k , counters [ k ] ++ ) ; } swap ( counters [ k ] , k ) ; // before
while ( k < indexes . length - 1 ) { k ++ ; counters [ k ] = k ; } permutation ++ ; return true ; |
public class EntitiesDetectionJobPropertiesMarshaller { /** * Marshall the given parameter object . */
public void marshall ( EntitiesDetectionJobProperties entitiesDetectionJobProperties , ProtocolMarshaller protocolMarshaller ) { } } | if ( entitiesDetectionJobProperties == null ) { throw new SdkClientException ( "Invalid argument passed to marshall(...)" ) ; } try { protocolMarshaller . marshall ( entitiesDetectionJobProperties . getJobId ( ) , JOBID_BINDING ) ; protocolMarshaller . marshall ( entitiesDetectionJobProperties . getJobName ( ) , JOBNAME_BINDING ) ; protocolMarshaller . marshall ( entitiesDetectionJobProperties . getJobStatus ( ) , JOBSTATUS_BINDING ) ; protocolMarshaller . marshall ( entitiesDetectionJobProperties . getMessage ( ) , MESSAGE_BINDING ) ; protocolMarshaller . marshall ( entitiesDetectionJobProperties . getSubmitTime ( ) , SUBMITTIME_BINDING ) ; protocolMarshaller . marshall ( entitiesDetectionJobProperties . getEndTime ( ) , ENDTIME_BINDING ) ; protocolMarshaller . marshall ( entitiesDetectionJobProperties . getEntityRecognizerArn ( ) , ENTITYRECOGNIZERARN_BINDING ) ; protocolMarshaller . marshall ( entitiesDetectionJobProperties . getInputDataConfig ( ) , INPUTDATACONFIG_BINDING ) ; protocolMarshaller . marshall ( entitiesDetectionJobProperties . getOutputDataConfig ( ) , OUTPUTDATACONFIG_BINDING ) ; protocolMarshaller . marshall ( entitiesDetectionJobProperties . getLanguageCode ( ) , LANGUAGECODE_BINDING ) ; protocolMarshaller . marshall ( entitiesDetectionJobProperties . getDataAccessRoleArn ( ) , DATAACCESSROLEARN_BINDING ) ; protocolMarshaller . marshall ( entitiesDetectionJobProperties . getVolumeKmsKeyId ( ) , VOLUMEKMSKEYID_BINDING ) ; } catch ( Exception e ) { throw new SdkClientException ( "Unable to marshall request to JSON: " + e . getMessage ( ) , e ) ; } |
public class HtmlForm { /** * < p > Return the value of the < code > onsubmit < / code > property . < / p >
* < p > Contents : Javascript code executed when this form is submitted . */
public java . lang . String getOnsubmit ( ) { } } | return ( java . lang . String ) getStateHelper ( ) . eval ( PropertyKeys . onsubmit ) ; |
public class Task { /** * / * - - - - - [ drainInputs ] - - - - - */
protected boolean drainInput ( boolean close ) throws IOException { } } | if ( buffer == null ) buffer = allocator . allocate ( ) ; try { while ( true ) { int read ; if ( in instanceof BufferInput ) { ( ( BufferInput ) in ) . drainBuffer ( ) ; read = - 1 ; } else read = in . read ( buffer ) ; if ( read == 0 ) { in . addReadInterest ( ) ; return false ; } else if ( read == - 1 ) { if ( close ) in . close ( ) ; drainDone ( ) ; return true ; } else buffer . clear ( ) ; } } catch ( Throwable thr ) { drainDone ( ) ; throw thr ; } |
public class LinearClassifierFactory { /** * Given the path to a file representing the text based serialization of a
* Linear Classifier , reconstitutes and returns that LinearClassifier .
* TODO : Leverage Index */
public Classifier < String , String > loadFromFilename ( String file ) { } } | try { File tgtFile = new File ( file ) ; BufferedReader in = new BufferedReader ( new FileReader ( tgtFile ) ) ; // Format : read indicies first , weights , then thresholds
Index < String > labelIndex = HashIndex . loadFromReader ( in ) ; Index < String > featureIndex = HashIndex . loadFromReader ( in ) ; double [ ] [ ] weights = new double [ featureIndex . size ( ) ] [ labelIndex . size ( ) ] ; String line = in . readLine ( ) ; int currLine = 1 ; while ( line != null && line . length ( ) > 0 ) { String [ ] tuples = line . split ( LinearClassifier . TEXT_SERIALIZATION_DELIMITER ) ; if ( tuples . length != 3 ) { throw new Exception ( "Error: incorrect number of tokens in weight specifier, line=" + currLine + " in file " + tgtFile . getAbsolutePath ( ) ) ; } currLine ++ ; int feature = Integer . valueOf ( tuples [ 0 ] ) ; int label = Integer . valueOf ( tuples [ 1 ] ) ; double value = Double . valueOf ( tuples [ 2 ] ) ; weights [ feature ] [ label ] = value ; line = in . readLine ( ) ; } // First line in thresholds is the number of thresholds
int numThresholds = Integer . valueOf ( in . readLine ( ) ) ; double [ ] thresholds = new double [ numThresholds ] ; int curr = 0 ; while ( ( line = in . readLine ( ) ) != null ) { double tval = Double . valueOf ( line . trim ( ) ) ; thresholds [ curr ++ ] = tval ; } in . close ( ) ; LinearClassifier < String , String > classifier = new LinearClassifier < String , String > ( weights , featureIndex , labelIndex ) ; return classifier ; } catch ( Exception e ) { System . err . println ( "Error in LinearClassifierFactory, loading from file=" + file ) ; e . printStackTrace ( ) ; return null ; } |
public class MtasDataDoubleOperations { /** * ( non - Javadoc )
* @ see
* mtas . codec . util . DataCollector . MtasDataOperations # exp2 ( java . lang . Number ) */
@ Override public Double exp2 ( Double arg1 ) { } } | if ( arg1 == null ) { return Double . NaN ; } else { return Math . exp ( arg1 ) ; } |
public class GrammarAccessFragment2 { /** * Returns all grammars from the hierarchy that are used from rules of this grammar . */
protected List < Grammar > getEffectivelyUsedGrammars ( final Grammar grammar ) { } } | final Function1 < AbstractRule , Grammar > _function = ( AbstractRule it ) -> { return GrammarUtil . getGrammar ( it ) ; } ; final Function1 < Grammar , Boolean > _function_1 = ( Grammar it ) -> { return Boolean . valueOf ( ( it != grammar ) ) ; } ; return IterableExtensions . < Grammar > toList ( IterableExtensions . < Grammar > toSet ( IterableExtensions . < Grammar > filter ( ListExtensions . < AbstractRule , Grammar > map ( GrammarUtil . allRules ( grammar ) , _function ) , _function_1 ) ) ) ; |
public class LocationListEntryMarshaller { /** * Marshall the given parameter object . */
public void marshall ( LocationListEntry locationListEntry , ProtocolMarshaller protocolMarshaller ) { } } | if ( locationListEntry == null ) { throw new SdkClientException ( "Invalid argument passed to marshall(...)" ) ; } try { protocolMarshaller . marshall ( locationListEntry . getLocationArn ( ) , LOCATIONARN_BINDING ) ; protocolMarshaller . marshall ( locationListEntry . getLocationUri ( ) , LOCATIONURI_BINDING ) ; } catch ( Exception e ) { throw new SdkClientException ( "Unable to marshall request to JSON: " + e . getMessage ( ) , e ) ; } |
public class DatabaseTableConfig { /** * Extract and return the table name for a class . */
public static < T > String extractTableName ( DatabaseType databaseType , Class < T > clazz ) { } } | DatabaseTable databaseTable = clazz . getAnnotation ( DatabaseTable . class ) ; String name = null ; if ( databaseTable != null && databaseTable . tableName ( ) != null && databaseTable . tableName ( ) . length ( ) > 0 ) { name = databaseTable . tableName ( ) ; } if ( name == null && javaxPersistenceConfigurer != null ) { name = javaxPersistenceConfigurer . getEntityName ( clazz ) ; } if ( name == null ) { // if the name isn ' t specified , it is the class name lowercased
if ( databaseType == null ) { // database - type is optional so if it is not specified we just use english
name = clazz . getSimpleName ( ) . toLowerCase ( Locale . ENGLISH ) ; } else { name = databaseType . downCaseString ( clazz . getSimpleName ( ) , true ) ; } } return name ; |
public class SerialArrayList { /** * Set .
* @ param i the
* @ param value the value */
public void set ( int i , U value ) { } } | ensureCapacity ( ( i + 1 ) * unitSize ) ; ByteBuffer view = getView ( i ) ; try { factory . write ( view , value ) ; } catch ( IOException e ) { throw new RuntimeException ( e ) ; } |
public class AbstractFaxClientSpi { /** * This function will suspend an existing fax job .
* @ param faxJob
* The fax job object containing the needed information */
public void suspendFaxJob ( FaxJob faxJob ) { } } | // validate fax job ID
this . invokeFaxJobIDValidation ( faxJob ) ; // invoke action
this . suspendFaxJobImpl ( faxJob ) ; // fire event
this . fireFaxEvent ( FaxClientActionEventID . SUSPEND_FAX_JOB , faxJob ) ; |
public class BOGD { /** * Guesses the distribution to use for the Regularization parameter
* @ param d the dataset to get the guess for
* @ return the guess for the Regularization parameter
* @ see # setRegularization ( double ) */
public static Distribution guessRegularization ( DataSet d ) { } } | double T2 = d . size ( ) ; T2 *= T2 ; return new LogUniform ( Math . pow ( 2 , - 3 ) / T2 , Math . pow ( 2 , 3 ) / T2 ) ; |
public class NfsFileBase { /** * ( non - Javadoc )
* @ see com . emc . ecs . nfsclient . nfs . NfsFile # readdir ( long , long , int ) */
public NfsReaddirResponse readdir ( long cookie , long cookieverf , int count ) throws IOException { } } | return getNfs ( ) . wrapped_getReaddir ( makeReaddirRequest ( cookie , cookieverf , count ) ) ; |
public class JoiningSequenceReader { /** * Iterator implementation which attempts to move through the 2D structure
* attempting to skip onto the next sequence as & when it is asked to */
@ Override public Iterator < C > iterator ( ) { } } | final List < Sequence < C > > localSequences = sequences ; return new Iterator < C > ( ) { private Iterator < C > currentSequenceIterator = null ; private int currentPosition = 0 ; @ Override public boolean hasNext ( ) { // If the current iterator is null then see if the Sequences object has anything
if ( currentSequenceIterator == null ) { return ! localSequences . isEmpty ( ) ; } // See if we had any compounds
boolean hasNext = currentSequenceIterator . hasNext ( ) ; if ( ! hasNext ) { hasNext = currentPosition < sequences . size ( ) ; } return hasNext ; } @ Override public C next ( ) { if ( currentSequenceIterator == null ) { if ( localSequences . isEmpty ( ) ) { throw new NoSuchElementException ( "No sequences to iterate over; make sure you call hasNext() before next()" ) ; } currentSequenceIterator = localSequences . get ( currentPosition ) . iterator ( ) ; currentPosition ++ ; } if ( ! currentSequenceIterator . hasNext ( ) ) { currentSequenceIterator = localSequences . get ( currentPosition ) . iterator ( ) ; currentPosition ++ ; } return currentSequenceIterator . next ( ) ; } @ Override public void remove ( ) throws UnsupportedOperationException { throw new UnsupportedOperationException ( "Cannot remove from this Sequence" ) ; } } ; |
public class UndertowReactiveWebServerFactory { /** * Add { @ link UndertowBuilderCustomizer } s that should be used to customize the
* Undertow { @ link io . undertow . Undertow . Builder Builder } .
* @ param customizers the customizers to add */
@ Override public void addBuilderCustomizers ( UndertowBuilderCustomizer ... customizers ) { } } | Assert . notNull ( customizers , "Customizers must not be null" ) ; this . builderCustomizers . addAll ( Arrays . asList ( customizers ) ) ; |
public class Groups { /** * 创建分组
* @ param name 分组名
* @ return */
public Group create ( String name ) { } } | String url = WxEndpoint . get ( "url.group.create" ) ; String json = String . format ( "{\"group\":{\"name\":\"%s\"}}" , name ) ; logger . debug ( "create group: {}" , json ) ; String response = wxClient . post ( url , json ) ; return JsonMapper . defaultUnwrapRootMapper ( ) . fromJson ( response , Group . class ) ; |
public class MergedContextSource { /** * Creates a unified context source for all those passed in . An Exception
* may be thrown if the call to a source ' s getContextType ( ) method throws
* an exception . */
public void init ( ClassLoader loader , ContextSource [ ] contextSources , String [ ] prefixes , boolean profilingEnabled ) throws Exception { } } | mSources = contextSources ; int len = contextSources . length ; ArrayList < Class < ? > > contextList = new ArrayList < Class < ? > > ( len ) ; ArrayList < ClassLoader > delegateList = new ArrayList < ClassLoader > ( len ) ; for ( int j = 0 ; j < contextSources . length ; j ++ ) { Class < ? > type = contextSources [ j ] . getContextType ( ) ; if ( type != null ) { contextList . add ( type ) ; ClassLoader scout = type . getClassLoader ( ) ; if ( scout != null && ! delegateList . contains ( scout ) ) { delegateList . add ( scout ) ; } } } mContextsInOrder = contextList . toArray ( new Class [ contextList . size ( ) ] ) ; ClassLoader [ ] delegateLoaders = delegateList . toArray ( new ClassLoader [ delegateList . size ( ) ] ) ; mInjector = new ClassInjector ( new DelegateClassLoader ( loader , delegateLoaders ) ) ; mProfilingEnabled = profilingEnabled ; int observerMode = profilingEnabled ? MergedClass . OBSERVER_ENABLED | MergedClass . OBSERVER_EXTERNAL : MergedClass . OBSERVER_ENABLED ; // temporarily include interface for UtilityContext for backwards
// compatibility with old code relying on it .
Class < ? > [ ] interfaces = { UtilityContext . class } ; mConstr = MergedClass . getConstructor2 ( mInjector , mContextsInOrder , prefixes , interfaces , observerMode ) ; |
public class MessageItem { /** * Returns an estimated in memory size for the Message that we have . */
@ Override public int getInMemoryDataSize ( ) { } } | if ( TraceComponent . isAnyTracingEnabled ( ) && tc . isEntryEnabled ( ) ) SibTr . entry ( this , tc , "getInMemoryDataSize" ) ; JsMessage localMsg = getJSMessage ( true ) ; int msgSize = localMsg . getInMemorySize ( ) ; if ( TraceComponent . isAnyTracingEnabled ( ) && tc . isEntryEnabled ( ) ) SibTr . exit ( this , tc , "getInMemoryDataSize" , Integer . valueOf ( msgSize ) ) ; return msgSize ; |
public class FSNamesystem { /** * Returned information is a JSON representation of map with host name as the
* key and value is a map of live node attribute keys to its values */
@ Override // NameNodeMXBean
public String getLiveNodes ( ) { } } | final Map < String , Map < String , Object > > info = new HashMap < String , Map < String , Object > > ( ) ; try { final ArrayList < DatanodeDescriptor > liveNodeList = new ArrayList < DatanodeDescriptor > ( ) ; final ArrayList < DatanodeDescriptor > deadNodeList = new ArrayList < DatanodeDescriptor > ( ) ; DFSNodesStatus ( liveNodeList , deadNodeList ) ; removeDecommissionedNodeFromList ( liveNodeList ) ; for ( DatanodeDescriptor node : liveNodeList ) { final Map < String , Object > innerinfo = new HashMap < String , Object > ( ) ; innerinfo . put ( "lastContact" , getLastContact ( node ) ) ; innerinfo . put ( "usedSpace" , getDfsUsed ( node ) ) ; innerinfo . put ( "adminState" , node . getAdminState ( ) . toString ( ) ) ; innerinfo . put ( "excluded" , this . inExcludedHostsList ( node , null ) ) ; info . put ( node . getHostName ( ) + ":" + node . getPort ( ) , innerinfo ) ; } } catch ( Exception e ) { LOG . error ( "Exception:" , e ) ; } return JSON . toString ( info ) ; |
public class GoogleDrive { /** * Create a folder without creating any higher level intermediate folders , and returned id of created folder .
* @ param path
* @ param parentId
* @ return id of created folder */
private String rawCreateFolder ( CPath path , String parentId ) { } } | JSONObject body = new JSONObject ( ) ; body . put ( "title" , path . getBaseName ( ) ) ; body . put ( "mimeType" , MIME_TYPE_DIRECTORY ) ; JSONArray ids = new JSONArray ( ) ; JSONObject idObj = new JSONObject ( ) ; idObj . put ( "id" , parentId ) ; ids . put ( idObj ) ; body . put ( "parents" , ids ) ; HttpPost request = new HttpPost ( FILES_ENDPOINT + "?fields=id" ) ; request . setEntity ( new JSONEntity ( body ) ) ; RequestInvoker < CResponse > ri = getApiRequestInvoker ( request , path ) ; JSONObject jresp = retryStrategy . invokeRetry ( ri ) . asJSONObject ( ) ; return jresp . getString ( "id" ) ; |
public class ScribeIndex { /** * Gets the appropriate property scribe for a given property instance .
* @ param property the property instance
* @ return the property scribe or null if not found */
public ICalPropertyScribe < ? extends ICalProperty > getPropertyScribe ( ICalProperty property ) { } } | if ( property instanceof RawProperty ) { RawProperty raw = ( RawProperty ) property ; return new RawPropertyScribe ( raw . getName ( ) ) ; } return getPropertyScribe ( property . getClass ( ) ) ; |
public class EventIDFilter { /** * Informs the filter that a receivable service is now inactive .
* For the events related with the service , if there are no other
* services bound , then events of such event type should be filtered
* @ param receivableService */
public void serviceInactive ( ReceivableService receivableService ) { } } | for ( ReceivableEvent receivableEvent : receivableService . getReceivableEvents ( ) ) { Set < ServiceID > servicesReceivingEvent = eventID2serviceIDs . get ( receivableEvent . getEventType ( ) ) ; if ( servicesReceivingEvent != null ) { synchronized ( servicesReceivingEvent ) { servicesReceivingEvent . remove ( receivableService . getService ( ) ) ; } if ( servicesReceivingEvent . isEmpty ( ) ) { eventID2serviceIDs . remove ( receivableEvent . getEventType ( ) ) ; } } } |
public class Ifc2x3tc1FactoryImpl { /** * < ! - - begin - user - doc - - >
* < ! - - end - user - doc - - >
* @ generated */
public IfcLogicalOperatorEnum createIfcLogicalOperatorEnumFromString ( EDataType eDataType , String initialValue ) { } } | IfcLogicalOperatorEnum result = IfcLogicalOperatorEnum . get ( initialValue ) ; if ( result == null ) throw new IllegalArgumentException ( "The value '" + initialValue + "' is not a valid enumerator of '" + eDataType . getName ( ) + "'" ) ; return result ; |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.