signature stringlengths 43 39.1k | implementation stringlengths 0 450k |
|---|---|
public class DObject { /** * Commits the transaction in which this distributed object is involved .
* @ see CompoundEvent # commit */
public void commitTransaction ( ) { } } | if ( _tevent == null ) { String errmsg = "Cannot commit: not involved in a transaction [dobj=" + this + "]" ; throw new IllegalStateException ( errmsg ) ; } // if we are nested , we decrement our nesting count rather than committing the transaction
if ( _tcount > 0 ) { _tcount -- ; } else { // we may actually be doing our final commit after someone already cancelled this
// transaction , so we need to perform the appropriate action at this point
if ( _tcancelled ) { _tevent . cancel ( ) ; } else { _tevent . commit ( ) ; } } |
public class AWSMobileClient { /** * Generates customized software development kit ( SDK ) and or tool packages used to integrate mobile web or mobile
* app clients with backend AWS resources .
* @ param exportBundleRequest
* Request structure used to request generation of custom SDK and tool packages required to integrate mobile
* web or app clients with backed AWS resources .
* @ return Result of the ExportBundle operation returned by the service .
* @ throws InternalFailureException
* The service has encountered an unexpected error condition which prevents it from servicing the request .
* @ throws ServiceUnavailableException
* The service is temporarily unavailable . The request should be retried after some time delay .
* @ throws UnauthorizedException
* Credentials of the caller are insufficient to authorize the request .
* @ throws TooManyRequestsException
* Too many requests have been received for this AWS account in too short a time . The request should be
* retried after some time delay .
* @ throws BadRequestException
* The request cannot be processed because some parameter is not valid or the project state prevents the
* operation from being performed .
* @ throws NotFoundException
* No entity can be found with the specified identifier .
* @ sample AWSMobile . ExportBundle
* @ see < a href = " http : / / docs . aws . amazon . com / goto / WebAPI / mobile - 2017-07-01 / ExportBundle " target = " _ top " > AWS API
* Documentation < / a > */
@ Override public ExportBundleResult exportBundle ( ExportBundleRequest request ) { } } | request = beforeClientExecution ( request ) ; return executeExportBundle ( request ) ; |
public class GlobalEventDispatcher { /** * Initialize after setting all requisite properties . */
public void init ( ) { } } | IUser user = SecurityUtil . getAuthenticatedUser ( ) ; publisherInfo . setUserId ( user == null ? null : user . getLogicalId ( ) ) ; publisherInfo . setUserName ( user == null ? "" : user . getFullName ( ) ) ; publisherInfo . setAppName ( getAppName ( ) ) ; publisherInfo . setConsumerId ( consumer . getNodeId ( ) ) ; publisherInfo . setProducerId ( producer . getNodeId ( ) ) ; publisherInfo . setSessionId ( sessionId ) ; localEventDispatcher . setGlobalEventDispatcher ( this ) ; pingEventHandler = new PingEventHandler ( ( IEventManager ) localEventDispatcher , publisherInfo ) ; pingEventHandler . init ( ) ; |
public class Pair { /** * If first and second are Strings , then this returns an MutableInternedPair
* where the Strings have been interned , and if this Pair is serialized
* and then deserialized , first and second are interned upon
* deserialization .
* @ param p A pair of Strings
* @ return MutableInternedPair , with same first and second as this . */
public static Pair < String , String > stringIntern ( Pair < String , String > p ) { } } | return new MutableInternedPair ( p ) ; |
public class ICalParameters { /** * Checks the parameters for data consistency problems or deviations from
* the specification .
* These problems will not prevent the iCalendar object from being written
* to a data stream * , but may prevent it from being parsed correctly by the
* consuming application .
* * With a few exceptions : One thing this method does is check for illegal
* characters . There are certain characters that will break the iCalendar
* syntax if written ( such as a newline character in a parameter name ) . If
* one of these characters is present , it WILL prevent the iCalendar object
* from being written .
* @ param version the version to validate against
* @ return a list of warnings or an empty list if no problems were found */
public List < ValidationWarning > validate ( ICalVersion version ) { } } | List < ValidationWarning > warnings = new ArrayList < ValidationWarning > ( 0 ) ; SyntaxStyle syntax ; switch ( version ) { case V1_0 : syntax = SyntaxStyle . OLD ; break ; default : syntax = SyntaxStyle . NEW ; break ; } /* * Check for invalid characters in names and values . */
for ( Map . Entry < String , List < String > > entry : this ) { String name = entry . getKey ( ) ; // check the parameter name
if ( ! VObjectValidator . validateParameterName ( name , syntax , true ) ) { if ( syntax == SyntaxStyle . OLD ) { AllowedCharacters notAllowed = VObjectValidator . allowedCharactersParameterName ( syntax , true ) . flip ( ) ; warnings . add ( new ValidationWarning ( 57 , name , notAllowed . toString ( true ) ) ) ; } else { warnings . add ( new ValidationWarning ( 54 , name ) ) ; } } // check the parameter value ( s )
List < String > values = entry . getValue ( ) ; for ( String value : values ) { if ( ! VObjectValidator . validateParameterValue ( value , syntax , false , true ) ) { AllowedCharacters notAllowed = VObjectValidator . allowedCharactersParameterValue ( syntax , false , true ) . flip ( ) ; int code = ( syntax == SyntaxStyle . OLD ) ? 58 : 53 ; warnings . add ( new ValidationWarning ( code , name , value , notAllowed . toString ( true ) ) ) ; } } } final int nonStandardCode = 1 , deprecated = 47 ; String value = first ( RSVP ) ; if ( value != null ) { value = value . toLowerCase ( ) ; List < String > validValues = Arrays . asList ( "true" , "false" , "yes" , "no" ) ; if ( ! validValues . contains ( value ) ) { warnings . add ( new ValidationWarning ( nonStandardCode , RSVP , value , validValues ) ) ; } } value = first ( CUTYPE ) ; if ( value != null && CalendarUserType . find ( value ) == null ) { warnings . add ( new ValidationWarning ( nonStandardCode , CUTYPE , value , CalendarUserType . all ( ) ) ) ; } value = first ( ENCODING ) ; if ( value != null && Encoding . find ( value ) == null ) { warnings . add ( new ValidationWarning ( nonStandardCode , ENCODING , value , Encoding . all ( ) ) ) ; } value = first ( FBTYPE ) ; if ( value != null && FreeBusyType . find ( value ) == null ) { warnings . add ( new ValidationWarning ( nonStandardCode , FBTYPE , value , FreeBusyType . all ( ) ) ) ; } value = first ( PARTSTAT ) ; if ( value != null && ParticipationStatus . find ( value ) == null ) { warnings . add ( new ValidationWarning ( nonStandardCode , PARTSTAT , value , ParticipationStatus . all ( ) ) ) ; } value = first ( RANGE ) ; if ( value != null ) { Range range = Range . find ( value ) ; if ( range == null ) { warnings . add ( new ValidationWarning ( nonStandardCode , RANGE , value , Range . all ( ) ) ) ; } if ( range == Range . THIS_AND_PRIOR && version == ICalVersion . V2_0 ) { warnings . add ( new ValidationWarning ( deprecated , RANGE , value ) ) ; } } value = first ( RELATED ) ; if ( value != null && Related . find ( value ) == null ) { warnings . add ( new ValidationWarning ( nonStandardCode , RELATED , value , Related . all ( ) ) ) ; } value = first ( RELTYPE ) ; if ( value != null && RelationshipType . find ( value ) == null ) { warnings . add ( new ValidationWarning ( nonStandardCode , RELTYPE , value , RelationshipType . all ( ) ) ) ; } value = first ( ROLE ) ; if ( value != null && Role . find ( value ) == null ) { warnings . add ( new ValidationWarning ( nonStandardCode , ROLE , value , Role . all ( ) ) ) ; } value = first ( VALUE ) ; if ( value != null && ICalDataType . find ( value ) == null ) { warnings . add ( new ValidationWarning ( nonStandardCode , VALUE , value , ICalDataType . all ( ) ) ) ; } return warnings ; |
public class AbstractRule { /** * Sets the identifier for this Rule .
* @ param id a value of type T assigned as this object ' s unique identifier .
* @ see org . cp . elements . lang . Identifiable # setId ( Comparable )
* @ throws NullPointerException if the identifier for this Rule is null . */
public final void setId ( final ID id ) { } } | Assert . notNull ( id , "The identifier for Rule ({0}) cannot be null!" , getClass ( ) . getName ( ) ) ; this . id = id ; |
public class RecommendationsInner { /** * Reset all recommendation opt - out settings for a subscription .
* Reset all recommendation opt - out settings for a subscription .
* @ throws IllegalArgumentException thrown if parameters fail the validation
* @ return the { @ link ServiceResponse } object if successful . */
public Observable < Void > resetAllFiltersAsync ( ) { } } | return resetAllFiltersWithServiceResponseAsync ( ) . map ( new Func1 < ServiceResponse < Void > , Void > ( ) { @ Override public Void call ( ServiceResponse < Void > response ) { return response . body ( ) ; } } ) ; |
public class XWikiExtensionRepository { /** * ExtensionRepository */
@ Override public Extension resolve ( ExtensionId extensionId ) throws ResolveException { } } | try { return resolve ( extensionId . getId ( ) , extensionId . getVersion ( ) ) ; } catch ( ResourceNotFoundException e ) { throw new ExtensionNotFoundException ( "Could not find extension [" + extensionId + "]" , e ) ; } catch ( Exception e ) { throw new ResolveException ( "Failed to create extension object for extension [" + extensionId + "]" , e ) ; } |
public class GeoPackageOverlayFactory { /** * Get a map tile from the GeoPackage tile
* @ param geoPackageTile GeoPackage tile
* @ return tile */
public static Tile getTile ( GeoPackageTile geoPackageTile ) { } } | Tile tile = null ; if ( geoPackageTile != null ) { tile = new Tile ( geoPackageTile . getWidth ( ) , geoPackageTile . getHeight ( ) , geoPackageTile . getData ( ) ) ; } return tile ; |
public class FactoryUtils { /** * Creates a { @ link TypeName } from a { @ link TypeMirror } . */
@ Requires ( "type != null" ) @ Ensures ( "result == null || result.getDeclaredName().equals(type.toString())" ) TypeName getTypeNameForType ( TypeMirror type ) { } } | switch ( type . getKind ( ) ) { case NONE : return null ; default : return new TypeName ( type . toString ( ) ) ; } |
public class AdminSetUserMFAPreferenceRequestMarshaller { /** * Marshall the given parameter object . */
public void marshall ( AdminSetUserMFAPreferenceRequest adminSetUserMFAPreferenceRequest , ProtocolMarshaller protocolMarshaller ) { } } | if ( adminSetUserMFAPreferenceRequest == null ) { throw new SdkClientException ( "Invalid argument passed to marshall(...)" ) ; } try { protocolMarshaller . marshall ( adminSetUserMFAPreferenceRequest . getSMSMfaSettings ( ) , SMSMFASETTINGS_BINDING ) ; protocolMarshaller . marshall ( adminSetUserMFAPreferenceRequest . getSoftwareTokenMfaSettings ( ) , SOFTWARETOKENMFASETTINGS_BINDING ) ; protocolMarshaller . marshall ( adminSetUserMFAPreferenceRequest . getUsername ( ) , USERNAME_BINDING ) ; protocolMarshaller . marshall ( adminSetUserMFAPreferenceRequest . getUserPoolId ( ) , USERPOOLID_BINDING ) ; } catch ( Exception e ) { throw new SdkClientException ( "Unable to marshall request to JSON: " + e . getMessage ( ) , e ) ; } |
public class ModelBuilderSchema { /** * Generic filling from the impl */
@ Override public S fillFromImpl ( B builder ) { } } | // DO NOT , because it can already be running : builder . init ( false ) ; / / check params
this . algo = builder . _parms . algoName ( ) . toLowerCase ( ) ; this . algo_full_name = builder . _parms . fullName ( ) ; this . supervised = builder . isSupervised ( ) ; this . can_build = builder . can_build ( ) ; this . visibility = builder . builderVisibility ( ) ; job = builder . _job == null ? null : new JobV3 ( builder . _job ) ; // In general , you can ask about a builder in - progress , and the error
// message list can be growing - so you have to be prepared to read it
// racily . Common for Grid searches exploring with broken parameter
// choices .
final ModelBuilder . ValidationMessage [ ] msgs = builder . _messages ; // Racily growing ; read only once
if ( msgs != null ) { this . messages = new ValidationMessageV3 [ msgs . length ] ; int i = 0 ; for ( ModelBuilder . ValidationMessage vm : msgs ) { if ( vm != null ) this . messages [ i ++ ] = new ValidationMessageV3 ( ) . fillFromImpl ( vm ) ; // TODO : version / / Note : does default field _ name mapping
} // default fieldname hacks
ValidationMessageV3 . mapValidationMessageFieldNames ( this . messages , new String [ ] { "_train" , "_valid" } , new String [ ] { "training_frame" , "validation_frame" } ) ; } this . error_count = builder . error_count ( ) ; parameters = createParametersSchema ( ) ; parameters . fillFromImpl ( builder . _parms ) ; parameters . model_id = builder . dest ( ) == null ? null : new KeyV3 . ModelKeyV3 ( builder . dest ( ) ) ; return ( S ) this ; |
public class DiameterConfiguration { /** * < xsi : element ref = " Extensions " minOccurs = " 0 " maxOccurs = " 1 " / > */
private void updateFromStack ( Stack stack ) { } } | long startTime = System . currentTimeMillis ( ) ; // Update LocalPeer
Peer sLocalPeer = stack . getMetaData ( ) . getLocalPeer ( ) ; localPeer . setUri ( sLocalPeer . getUri ( ) . toString ( ) ) ; for ( InetAddress ipAddress : sLocalPeer . getIPAddresses ( ) ) { localPeer . addIpAddress ( ipAddress . getHostAddress ( ) ) ; } localPeer . setRealm ( sLocalPeer . getRealmName ( ) ) ; localPeer . setVendorId ( sLocalPeer . getVendorId ( ) ) ; localPeer . setProductName ( sLocalPeer . getProductName ( ) ) ; localPeer . setFirmwareRev ( sLocalPeer . getFirmware ( ) ) ; for ( org . jdiameter . api . ApplicationId appId : sLocalPeer . getCommonApplications ( ) ) { if ( appId . getAuthAppId ( ) != org . jdiameter . api . ApplicationId . UNDEFINED_VALUE ) { localPeer . addDefaultApplication ( ApplicationIdJMX . createAuthApplicationId ( appId . getVendorId ( ) , appId . getAuthAppId ( ) ) ) ; } else { localPeer . addDefaultApplication ( ApplicationIdJMX . createAcctApplicationId ( appId . getVendorId ( ) , appId . getAcctAppId ( ) ) ) ; } } HashMap < String , DiameterStatistic > lpStats = new HashMap < String , DiameterStatistic > ( ) ; for ( StatisticRecord stat : ( ( IPeer ) sLocalPeer ) . getStatistic ( ) . getRecords ( ) ) { lpStats . put ( stat . getName ( ) , new DiameterStatistic ( stat . getName ( ) , stat . getDescription ( ) , stat . toString ( ) ) ) ; } localPeer . setStatistics ( lpStats ) ; MutableConfiguration config = ( MutableConfiguration ) stack . getMetaData ( ) . getConfiguration ( ) ; // Update Parameters
this . parameters = new ParametersImpl ( config ) ; // Update Network . . .
// . . . Peers ( config )
for ( Configuration curPeer : config . getChildren ( PeerTable . ordinal ( ) ) ) { String name = curPeer . getStringValue ( PeerName . ordinal ( ) , "" ) ; Boolean attemptConnect = curPeer . getBooleanValue ( PeerAttemptConnection . ordinal ( ) , false ) ; Integer rating = curPeer . getIntValue ( PeerRating . ordinal ( ) , 0 ) ; String ip = curPeer . getStringValue ( PeerIp . ordinal ( ) , null ) ; String portRange = curPeer . getStringValue ( PeerLocalPortRange . ordinal ( ) , "" ) ; Integer portRangeLow = null ; Integer portRangeHigh = null ; if ( portRange != null && ! portRange . equals ( "" ) ) { String [ ] rng = portRange . trim ( ) . split ( "-" ) ; portRangeLow = Integer . parseInt ( rng [ 0 ] ) ; portRangeHigh = Integer . parseInt ( rng [ 1 ] ) ; } String securityRef = curPeer . getStringValue ( SecurityRef . ordinal ( ) , "" ) ; network . addPeer ( new NetworkPeerImpl ( name , attemptConnect , rating , ip , portRangeLow , portRangeHigh , securityRef ) ) ; } // . . . More Peers ( mutable )
try { MutablePeerTable peerTable ; peerTable = stack . unwrap ( MutablePeerTable . class ) ; // Peer p = n . addPeer ( " aaa : / / 127.0.0.1:13868 " , " mobicents . org " , true ) ;
for ( Peer peer : peerTable . getPeerTable ( ) ) { PeerImpl p = ( PeerImpl ) peer ; NetworkPeerImpl nPeer = new NetworkPeerImpl ( p . getUri ( ) . toString ( ) , p . isAttemptConnection ( ) , p . getRating ( ) , null , null , null , null ) ; HashMap < String , DiameterStatistic > npStats = new HashMap < String , DiameterStatistic > ( ) ; for ( StatisticRecord stat : p . getStatistic ( ) . getRecords ( ) ) { npStats . put ( stat . getName ( ) , new DiameterStatistic ( stat . getName ( ) , stat . getDescription ( ) , stat . toString ( ) ) ) ; } nPeer . setStatistics ( npStats ) ; network . addPeer ( nPeer ) ; } } catch ( InternalException e ) { logger . error ( "Failed to update Diameter Configuration from Stack Mutable Peer Table" , e ) ; } // . . . Realms ( configuration )
/* for ( Configuration realmTable : config . getChildren ( RealmTable . ordinal ( ) ) ) {
for ( Configuration curRealm : realmTable . getChildren ( RealmEntry . ordinal ( ) ) ) {
String name = curRealm . getStringValue ( RealmName . ordinal ( ) , " " ) ;
String hosts = curRealm . getStringValue ( RealmHosts . ordinal ( ) , " localhost " ) ;
ArrayList < String > peers = new ArrayList < String > ( ) ;
for ( String peer : hosts . split ( " , " ) ) {
peers . add ( peer . trim ( ) ) ;
String localAction = curRealm . getStringValue ( RealmLocalAction . ordinal ( ) , " LOCAL " ) ;
Boolean dynamic = curRealm . getBooleanValue ( RealmEntryIsDynamic . ordinal ( ) , false ) ;
Long expTime = curRealm . getLongValue ( RealmEntryExpTime . ordinal ( ) , 0 ) ;
Configuration [ ] sAppIds = curRealm . getChildren ( ApplicationId . ordinal ( ) ) ;
ArrayList < ApplicationIdJMX > appIds = new ArrayList < ApplicationIdJMX > ( ) ;
for ( Configuration appId : sAppIds ) {
Long acctAppId = appId . getLongValue ( AcctApplId . ordinal ( ) , 0 ) ;
Long authAppId = appId . getLongValue ( AuthApplId . ordinal ( ) , 0 ) ;
Long vendorId = appId . getLongValue ( VendorId . ordinal ( ) , 0 ) ;
if ( authAppId ! = 0 ) {
appIds . add ( ApplicationIdJMX . createAuthApplicationId ( vendorId , authAppId ) ) ;
else if ( acctAppId ! = 0 ) {
appIds . add ( ApplicationIdJMX . createAcctApplicationId ( vendorId , acctAppId ) ) ;
network . addRealm ( new RealmImpl ( appIds , name , peers , localAction , dynamic , expTime ) ) ; */
// . . . Realms ( mutable )
try { MutablePeerTableImpl mpt = ( MutablePeerTableImpl ) stack . unwrap ( PeerTable . class ) ; for ( org . jdiameter . api . Realm realm : mpt . getAllRealms ( ) ) { IRealm irealm = null ; if ( realm instanceof IRealm ) { irealm = ( IRealm ) realm ; } ArrayList < ApplicationIdJMX > x = new ArrayList < ApplicationIdJMX > ( ) ; x . add ( ApplicationIdJMX . fromApplicationId ( realm . getApplicationId ( ) ) ) ; network . addRealm ( new RealmImpl ( x , realm . getName ( ) , new ArrayList < String > ( Arrays . asList ( ( ( IRealm ) realm ) . getPeerNames ( ) ) ) , realm . getLocalAction ( ) . toString ( ) , irealm != null ? irealm . getAgentConfiguration ( ) : null , realm . isDynamic ( ) , realm . getExpirationTime ( ) ) ) ; } } catch ( Exception e ) { logger . error ( "Failed to update Diameter Configuration from Stack Mutable Peer Table" , e ) ; } long endTime = System . currentTimeMillis ( ) ; logger . debug ( "Info gathered in {}ms" , ( endTime - startTime ) ) ; |
public class ExpressRouteGatewaysInner { /** * Lists ExpressRoute gateways under a given subscription .
* @ return the PagedList < ExpressRouteGatewayInner > object if successful . */
public PagedList < ExpressRouteGatewayInner > list ( ) { } } | PageImpl1 < ExpressRouteGatewayInner > page = new PageImpl1 < > ( ) ; page . setItems ( listWithServiceResponseAsync ( ) . toBlocking ( ) . single ( ) . body ( ) ) ; page . setNextPageLink ( null ) ; return new PagedList < ExpressRouteGatewayInner > ( page ) { @ Override public Page < ExpressRouteGatewayInner > nextPage ( String nextPageLink ) { return null ; } } ; |
public class Cql2ElmVisitor { /** * Determine if the right - hand side of an < code > IncludedIn < / code > expression can be refactored into the date range
* of a < code > Retrieve < / code > . Currently , refactoring is only supported when the RHS is a literal
* DateTime interval , a literal DateTime , a parameter representing a DateTime interval or a DateTime , or an
* expression reference representing a DateTime interval or a DateTime .
* @ param rhs the right - hand side of the < code > IncludedIn < / code > to test for potential optimization
* @ return < code > true < / code > if the RHS supports refactoring to a < code > Retrieve < / code > , < code > false < / code >
* otherwise . */
private boolean isRHSEligibleForDateRangeOptimization ( Expression rhs ) { } } | return rhs . getResultType ( ) . isSubTypeOf ( libraryBuilder . resolveTypeName ( "System" , "DateTime" ) ) || rhs . getResultType ( ) . isSubTypeOf ( new IntervalType ( libraryBuilder . resolveTypeName ( "System" , "DateTime" ) ) ) ; // BTR : The only requirement for the optimization is that the expression be of type DateTime or Interval < DateTime >
// Whether or not the expression can be statically evaluated ( literal , in the loose sense of the word ) is really
// a function of the engine in determining the " initial " data requirements , versus subsequent data requirements
// Element targetElement = rhs ;
// if ( rhs instanceof ParameterRef ) {
// String paramName = ( ( ParameterRef ) rhs ) . getName ( ) ;
// for ( ParameterDef def : getLibrary ( ) . getParameters ( ) . getDef ( ) ) {
// if ( paramName . equals ( def . getName ( ) ) ) {
// targetElement = def . getParameterTypeSpecifier ( ) ;
// if ( targetElement = = null ) {
// targetElement = def . getDefault ( ) ;
// break ;
// } else if ( rhs instanceof ExpressionRef & & ! ( rhs instanceof FunctionRef ) ) {
// / / TODO : Support forward declaration , if necessary
// String expName = ( ( ExpressionRef ) rhs ) . getName ( ) ;
// for ( ExpressionDef def : getLibrary ( ) . getStatements ( ) . getDef ( ) ) {
// if ( expName . equals ( def . getName ( ) ) ) {
// targetElement = def . getExpression ( ) ;
// boolean isEligible = false ;
// if ( targetElement instanceof DateTime ) {
// isEligible = true ;
// } else if ( targetElement instanceof Interval ) {
// Interval ivl = ( Interval ) targetElement ;
// isEligible = ( ivl . getLow ( ) ! = null & & ivl . getLow ( ) instanceof DateTime ) | | ( ivl . getHigh ( ) ! = null & & ivl . getHigh ( ) instanceof DateTime ) ;
// } else if ( targetElement instanceof IntervalTypeSpecifier ) {
// IntervalTypeSpecifier spec = ( IntervalTypeSpecifier ) targetElement ;
// isEligible = isDateTimeTypeSpecifier ( spec . getPointType ( ) ) ;
// } else if ( targetElement instanceof NamedTypeSpecifier ) {
// isEligible = isDateTimeTypeSpecifier ( targetElement ) ;
// return isEligible ; |
public class UTF8String { /** * Levenshtein distance is a metric for measuring the distance of two strings . The distance is
* defined by the minimum number of single - character edits ( i . e . insertions , deletions or
* substitutions ) that are required to change one of the strings into the other . */
public int levenshteinDistance ( UTF8String other ) { } } | // Implementation adopted from org . apache . common . lang3 . StringUtils . getLevenshteinDistance
int n = numChars ( ) ; int m = other . numChars ( ) ; if ( n == 0 ) { return m ; } else if ( m == 0 ) { return n ; } UTF8String s , t ; if ( n <= m ) { s = this ; t = other ; } else { s = other ; t = this ; int swap ; swap = n ; n = m ; m = swap ; } int [ ] p = new int [ n + 1 ] ; int [ ] d = new int [ n + 1 ] ; int [ ] swap ; int i , i_bytes , j , j_bytes , num_bytes_j , cost ; for ( i = 0 ; i <= n ; i ++ ) { p [ i ] = i ; } for ( j = 0 , j_bytes = 0 ; j < m ; j_bytes += num_bytes_j , j ++ ) { num_bytes_j = numBytesForFirstByte ( t . getByte ( j_bytes ) ) ; d [ 0 ] = j + 1 ; for ( i = 0 , i_bytes = 0 ; i < n ; i_bytes += numBytesForFirstByte ( s . getByte ( i_bytes ) ) , i ++ ) { if ( s . getByte ( i_bytes ) != t . getByte ( j_bytes ) || num_bytes_j != numBytesForFirstByte ( s . getByte ( i_bytes ) ) ) { cost = 1 ; } else { cost = ( ByteArrayMethods . arrayEquals ( t . base , t . offset + j_bytes , s . base , s . offset + i_bytes , num_bytes_j ) ) ? 0 : 1 ; } d [ i + 1 ] = Math . min ( Math . min ( d [ i ] + 1 , p [ i + 1 ] + 1 ) , p [ i ] + cost ) ; } swap = p ; p = d ; d = swap ; } return p [ n ] ; |
public class AfplibPackageImpl { /** * < ! - - begin - user - doc - - >
* < ! - - end - user - doc - - >
* @ generated */
public EClass getDescriptorPosition ( ) { } } | if ( descriptorPositionEClass == null ) { descriptorPositionEClass = ( EClass ) EPackage . Registry . INSTANCE . getEPackage ( AfplibPackage . eNS_URI ) . getEClassifiers ( ) . get ( 353 ) ; } return descriptorPositionEClass ; |
public class CommentAPI { /** * Used to retrieve all the comments that have been made on an object of the
* given type and with the given id . It returns a list of all the comments
* sorted in ascending order by time created .
* @ param reference
* The reference to the object from which the comments should be
* retrieved
* @ return The comments on the object */
public List < Comment > getComments ( Reference reference ) { } } | return getResourceFactory ( ) . getApiResource ( "/comment/" + reference . getType ( ) + "/" + reference . getId ( ) ) . get ( new GenericType < List < Comment > > ( ) { } ) ; |
public class Config { /** * Read config object stored in JSON format from < code > Reader < / code >
* @ param reader object
* @ return config
* @ throws IOException error */
public static Config fromJSON ( Reader reader ) throws IOException { } } | ConfigSupport support = new ConfigSupport ( ) ; return support . fromJSON ( reader , Config . class ) ; |
public class ProjectApi { /** * Get a specific project , which is owned by the authentication user .
* < pre > < code > GET / projects / : id < / code > < / pre >
* @ param projectIdOrPath the project in the form of an Integer ( ID ) , String ( path ) , or Project instance
* @ param includeStatistics include project statistics
* @ return the specified project
* @ throws GitLabApiException if any exception occurs */
public Project getProject ( Object projectIdOrPath , Boolean includeStatistics ) throws GitLabApiException { } } | Form formData = new GitLabApiForm ( ) . withParam ( "statistics" , includeStatistics ) ; Response response = get ( Response . Status . OK , formData . asMap ( ) , "projects" , this . getProjectIdOrPath ( projectIdOrPath ) ) ; return ( response . readEntity ( Project . class ) ) ; |
public class CommerceNotificationQueueEntryPersistenceImpl { /** * Returns the first commerce notification queue entry in the ordered set where groupId = & # 63 ; .
* @ param groupId the group ID
* @ param orderByComparator the comparator to order the set by ( optionally < code > null < / code > )
* @ return the first matching commerce notification queue entry
* @ throws NoSuchNotificationQueueEntryException if a matching commerce notification queue entry could not be found */
@ Override public CommerceNotificationQueueEntry findByGroupId_First ( long groupId , OrderByComparator < CommerceNotificationQueueEntry > orderByComparator ) throws NoSuchNotificationQueueEntryException { } } | CommerceNotificationQueueEntry commerceNotificationQueueEntry = fetchByGroupId_First ( groupId , orderByComparator ) ; if ( commerceNotificationQueueEntry != null ) { return commerceNotificationQueueEntry ; } StringBundler msg = new StringBundler ( 4 ) ; msg . append ( _NO_SUCH_ENTITY_WITH_KEY ) ; msg . append ( "groupId=" ) ; msg . append ( groupId ) ; msg . append ( "}" ) ; throw new NoSuchNotificationQueueEntryException ( msg . toString ( ) ) ; |
public class PathFragment { /** * Constructs path fragments corresponding to the provided filters .
* @ param filters the filters to create path fragments from
* @ return the path fragments */
public static PathFragment [ ] from ( Filter ... filters ) { } } | PathFragment [ ] ret = new PathFragment [ filters . length ] ; Arrays . setAll ( ret , ( i ) -> new PathFragment ( filters [ i ] ) ) ; return ret ; |
public class AnnotatedHttpServiceFactory { /** * Returns the list of { @ link Path } annotated methods . */
private static List < Method > requestMappingMethods ( Object object ) { } } | return getAllMethods ( object . getClass ( ) , withModifier ( Modifier . PUBLIC ) ) . stream ( ) // Lookup super classes just in case if the object is a proxy .
. filter ( m -> getAnnotations ( m , FindOption . LOOKUP_SUPER_CLASSES ) . stream ( ) . map ( Annotation :: annotationType ) . anyMatch ( a -> a == Path . class || HTTP_METHOD_MAP . containsKey ( a ) ) ) . sorted ( Comparator . comparingInt ( AnnotatedHttpServiceFactory :: order ) ) . collect ( toImmutableList ( ) ) ; |
public class BaseScreen { /** * Process the " Login " toolbar command .
* @ return true if successful . */
public boolean onLogin ( ) { } } | SStaticString sfStaticField = null ; String strUserName = null ; String strPassword = null ; for ( int i = 0 ; i < this . getSFieldCount ( ) ; i ++ ) { ScreenField sField = this . getSField ( i ) ; if ( sfStaticField == null ) if ( sField instanceof SStaticString ) sfStaticField = ( SStaticString ) sField ; if ( sField . getConverter ( ) != null ) if ( DBParams . USER_NAME . equalsIgnoreCase ( sField . getConverter ( ) . getFieldName ( ) ) ) strUserName = sField . getConverter ( ) . getField ( ) . toString ( ) ; if ( sField . getConverter ( ) != null ) if ( DBParams . PASSWORD . equalsIgnoreCase ( sField . getConverter ( ) . getFieldName ( ) ) ) strPassword = sField . getConverter ( ) . getField ( ) . toString ( ) ; } if ( strUserName == null ) return false ; App application = this . getTask ( ) . getApplication ( ) ; int iErrorCode = application . login ( this . getTask ( ) , strUserName , strPassword , this . getProperty ( DBParams . DOMAIN ) ) ; if ( iErrorCode == DBConstants . NORMAL_RETURN ) { String strLastCommand = null ; BasePanel parent = this . getParentScreen ( ) ; int iUseSameWindow = ScreenConstants . USE_SAME_WINDOW | ScreenConstants . PUSH_TO_BROWSER ; if ( parent != null ) { strLastCommand = parent . popHistory ( 1 , false ) ; iUseSameWindow = ScreenConstants . USE_SAME_WINDOW | ScreenConstants . DONT_PUSH_TO_BROWSER ; } else strLastCommand = this . getScreenURL ( ) ; this . handleCommand ( strLastCommand , this , iUseSameWindow ) ; // Process the last command
} else { String strError = this . getTask ( ) . getLastError ( iErrorCode ) ; if ( strError != null ) if ( sfStaticField != null ) sfStaticField . setString ( strError ) ; try { Thread . sleep ( 3000 ) ; // Wait 3 seconds if bad password
} catch ( InterruptedException ex ) { ex . printStackTrace ( ) ; // Never
} } return ( iErrorCode == DBConstants . NORMAL_RETURN ) ; // Handled |
public class ObjectFactory { /** * Create an instance of { @ link JAXBElement } { @ code < } { @ link LogbaseType } { @ code > } } */
@ XmlElementDecl ( namespace = "http://www.w3.org/1998/Math/MathML" , name = "logbase" ) public JAXBElement < LogbaseType > createLogbase ( LogbaseType value ) { } } | return new JAXBElement < LogbaseType > ( _Logbase_QNAME , LogbaseType . class , null , value ) ; |
public class SentryClient { /** * Sends a message to the Sentry server .
* The message will be logged at the { @ link Event . Level # INFO } level .
* @ param message message to send to Sentry . */
public void sendMessage ( String message ) { } } | EventBuilder eventBuilder = new EventBuilder ( ) . withMessage ( message ) . withLevel ( Event . Level . INFO ) ; sendEvent ( eventBuilder ) ; |
public class ObjectFactory { /** * Create an instance of { @ link JAXBElement } { @ code < } { @ link ConversionRefType } { @ code > }
* @ param value
* Java instance representing xml element ' s value .
* @ return
* the new instance of { @ link JAXBElement } { @ code < } { @ link ConversionRefType } { @ code > } */
@ XmlElementDecl ( namespace = "http://www.opengis.net/gml" , name = "conversionRef" ) public JAXBElement < ConversionRefType > createConversionRef ( ConversionRefType value ) { } } | return new JAXBElement < ConversionRefType > ( _ConversionRef_QNAME , ConversionRefType . class , null , value ) ; |
public class BitChromosome { /** * Returns the two ' s - complement binary representation of this
* large integer . The output array is in < i > big - endian < / i >
* byte - order : the most significant byte is at the offset position .
* < p > Note : This representation is consistent with { @ code java . lang . BigInteger
* } byte array representation and can be used for conversion
* between the two classes . < / p >
* @ param bytes the bytes to hold the binary representation
* ( two ' s - complement ) of this large integer .
* @ return the number of bytes written .
* @ throws IndexOutOfBoundsException
* if { @ code bytes . length < ( int ) Math . ceil ( length ( ) / 8.0 ) }
* @ throws NullPointerException it the give array is { @ code null } . */
public int toByteArray ( final byte [ ] bytes ) { } } | if ( bytes . length < _genes . length ) { throw new IndexOutOfBoundsException ( ) ; } System . arraycopy ( _genes , 0 , bytes , 0 , _genes . length ) ; return _genes . length ; |
public class JmxBuilderModelMBean { /** * Registers listeners for operation calls ( i . e . method , getter , and setter calls ) when
* invoked on this bean from the MBeanServer . Descriptor should contain a map with layout
* { @ code item - > [ Map [ methodListener : [ target : " " , tpe : " " , callback : & Closure ] , . . . , ] ] }
* @ param descriptor MetaMap descriptor containing description of operation call listeners */
public void addOperationCallListeners ( Map < String , Map < String , Map < String , Object > > > descriptor ) { } } | if ( descriptor == null ) return ; for ( Map . Entry < String , Map < String , Map < String , Object > > > item : descriptor . entrySet ( ) ) { // set up method listeners ( such as attributeListener and Operation Listeners )
// item - > [ Map [ methodListener : [ target : " " , tpe : " " , callback : & Closure ] , . . . , ] ]
if ( item . getValue ( ) . containsKey ( "methodListener" ) ) { Map < String , Object > listener = item . getValue ( ) . get ( "methodListener" ) ; String target = ( String ) listener . get ( "target" ) ; methodListeners . add ( target ) ; String listenerType = ( String ) listener . get ( "type" ) ; listener . put ( "managedObject" , this . managedObject ) ; // register an attribute change notification listener with model mbean
if ( listenerType . equals ( "attributeChangeListener" ) ) { try { this . addAttributeChangeNotificationListener ( AttributeChangedListener . getListener ( ) , ( String ) listener . get ( "attribute" ) , listener ) ; } catch ( MBeanException e ) { throw new JmxBuilderException ( e ) ; } } if ( listenerType . equals ( "operationCallListener" ) ) { String eventType = "jmx.operation.call." + target ; NotificationFilterSupport filter = new NotificationFilterSupport ( ) ; filter . enableType ( eventType ) ; this . addNotificationListener ( JmxEventListener . getListener ( ) , filter , listener ) ; } } } |
public class Functions { /** * Bind the input of a Procedure to the result of an function , returning a new Procedure .
* @ param delegate The Procedure to delegate the invocation to .
* @ param function The Function that will create the input for the delegate
* @ return A new Procedure */
public static < T1 , T2 > Procedure < T1 > bind ( Procedure < ? super T2 > delegate , Function < ? super T1 , T2 > function ) { } } | return new BindProcedure < T1 , T2 > ( delegate , function ) ; |
public class Scheduler { /** * Schedules the given task on this Scheduler without any time delay .
* This method is safe to be called from multiple threads but there are no
* ordering or non - overlapping guarantees between tasks .
* @ param run the task to execute
* @ return the Disposable instance that let ' s one cancel this particular task .
* @ since 2.0 */
@ NonNull public Disposable scheduleDirect ( @ NonNull Runnable run ) { } } | return scheduleDirect ( run , 0L , TimeUnit . NANOSECONDS ) ; |
public class RuntimeModelIo { /** * Loads instances from a file .
* @ param instancesFile the file definition of the instances ( can have imports )
* @ param rootDirectory the root directory that contains instance definitions , used to resolve imports
* @ param graph the graph to use to resolve instances
* @ param applicationName the application name
* @ return a non - null result */
public static InstancesLoadResult loadInstances ( File instancesFile , File rootDirectory , Graphs graph , String applicationName ) { } } | InstancesLoadResult result = new InstancesLoadResult ( ) ; INST : { if ( ! instancesFile . exists ( ) ) { RoboconfError error = new RoboconfError ( ErrorCode . PROJ_MISSING_INSTANCE_EP ) ; error . setDetails ( expected ( instancesFile . getAbsolutePath ( ) ) ) ; result . loadErrors . add ( error ) ; break INST ; } FromInstanceDefinition fromDef = new FromInstanceDefinition ( rootDirectory ) ; Collection < Instance > instances = fromDef . buildInstances ( graph , instancesFile ) ; result . getParsedFiles ( ) . addAll ( fromDef . getProcessedImports ( ) ) ; if ( ! fromDef . getErrors ( ) . isEmpty ( ) ) { result . loadErrors . addAll ( fromDef . getErrors ( ) ) ; break INST ; } Collection < ModelError > errors = RuntimeModelValidator . validate ( instances ) ; result . loadErrors . addAll ( errors ) ; result . objectToSource . putAll ( fromDef . getObjectToSource ( ) ) ; result . getRootInstances ( ) . addAll ( instances ) ; } for ( Instance rootInstance : result . rootInstances ) rootInstance . data . put ( Instance . APPLICATION_NAME , applicationName ) ; return result ; |
public class VisJsComponent { /** * Implements the getHighlightingColor method of the org . corpus _ tools . salt . util . StyleImporter interface . */
@ Override public String setHighlightingColor ( SNode node ) { } } | String color = null ; SFeature featMatched = node . getFeature ( ANNIS_NS , FEAT_MATCHEDNODE ) ; Long matchRaw = featMatched == null ? null : featMatched . getValue_SNUMERIC ( ) ; // token is matched
if ( matchRaw != null ) { color = MatchedNodeColors . getHTMLColorByMatch ( matchRaw ) ; return color ; } return color ; |
public class TemplateServerServlet { /** * Retrieves all the templates that are newer that the timestamp specified
* by the client . The pathInfo from the request specifies which templates
* are desired . QueryString parameters " timeStamp " and ? ? ? provide */
public void doGet ( HttpServletRequest req , HttpServletResponse res ) { } } | getTemplateData ( req , res , req . getPathInfo ( ) ) ; |
public class SimplePluginRegistry { /** * ( non - Javadoc )
* @ see org . springframework . plugin . core . PluginRegistry # getPluginFor ( java . lang . Object ) */
@ Override public Optional < T > getPluginFor ( S delimiter ) { } } | Assert . notNull ( delimiter , "Delimiter must not be null!" ) ; return super . getPlugins ( ) . stream ( ) . filter ( it -> it . supports ( delimiter ) ) . findFirst ( ) ; |
public class AbstractPrintQuery { /** * Add an select to the PrintQuery . A select is something like :
* < code > class [ Emperador _ Products _ ClassFloorLaminate ] . linkto [ SurfaceAttrId ] . attribute [ Value ] < / code >
* < br >
* The use of the key words like " class " etc is mandatory . Contrary to
* { @ link # addPhrase ( String , String ) } the values will not be parsed ! The
* values will not be editable .
* @ param _ selectBldrs selectBuilder to be added
* @ return this PrintQuery
* @ throws EFapsException on error */
public AbstractPrintQuery addSelect ( final SelectBuilder ... _selectBldrs ) throws EFapsException { } } | if ( isMarked4execute ( ) ) { for ( final SelectBuilder selectBldr : _selectBldrs ) { addSelect ( selectBldr . toString ( ) ) ; } } return this ; |
public class Record { /** * Builds a new Record from its textual representation
* @ param name The owner name of the record .
* @ param type The record ' s type .
* @ param dclass The record ' s class .
* @ param ttl The record ' s time to live .
* @ param s The textual representation of the rdata .
* @ param origin The default origin to be appended to relative domain names .
* @ return The new record
* @ throws IOException The text format was invalid . */
public static Record fromString ( Name name , int type , int dclass , long ttl , String s , Name origin ) throws IOException { } } | return fromString ( name , type , dclass , ttl , new Tokenizer ( s ) , origin ) ; |
public class RippleView { /** * Create Ripple animation centered at x , y
* @ param x Horizontal position of the ripple center
* @ param y Vertical position of the ripple center */
private void createAnimation ( final float x , final float y ) { } } | if ( this . isEnabled ( ) && ! animationRunning ) { if ( hasToZoom ) this . startAnimation ( scaleAnimation ) ; radiusMax = Math . max ( WIDTH , HEIGHT ) ; if ( rippleType != 2 ) radiusMax /= 2 ; radiusMax -= ripplePadding ; if ( isCentered || rippleType == 1 ) { this . x = getMeasuredWidth ( ) / 2 ; this . y = getMeasuredHeight ( ) / 2 ; } else { this . x = x ; this . y = y ; } animationRunning = true ; if ( rippleType == 1 && originBitmap == null ) originBitmap = getDrawingCache ( true ) ; invalidate ( ) ; } |
public class OnExitScriptTypeImpl { /** * < ! - - begin - user - doc - - >
* < ! - - end - user - doc - - >
* @ generated */
@ Override public boolean eIsSet ( int featureID ) { } } | switch ( featureID ) { case DroolsPackage . ON_EXIT_SCRIPT_TYPE__SCRIPT : return SCRIPT_EDEFAULT == null ? script != null : ! SCRIPT_EDEFAULT . equals ( script ) ; case DroolsPackage . ON_EXIT_SCRIPT_TYPE__SCRIPT_FORMAT : return SCRIPT_FORMAT_EDEFAULT == null ? scriptFormat != null : ! SCRIPT_FORMAT_EDEFAULT . equals ( scriptFormat ) ; } return super . eIsSet ( featureID ) ; |
public class RtpPacket { /** * Returns the length of the extensions currently added to this packet .
* @ return the length of the extensions currently added to this packet . */
public int getExtensionLength ( ) { } } | if ( ! getExtensionBit ( ) ) return 0 ; // the extension length comes after the RTP header , the CSRC list , and
// after two bytes in the extension header called " defined by profile "
int extLenIndex = FIXED_HEADER_SIZE + getCsrcCount ( ) * 4 + 2 ; return ( ( buffer . get ( extLenIndex ) << 8 ) | buffer . get ( extLenIndex + 1 ) * 4 ) ; |
public class MirageUtil { /** * Returns the { @ link SqlContext } instance .
* @ param beanDescFactory the bean descriptor factory
* @ param param the parameter object
* @ return { @ link SqlContext } instance */
public static SqlContext getSqlContext ( BeanDescFactory beanDescFactory , Object param ) { } } | SqlContext context = new SqlContextImpl ( ) ; if ( param != null ) { BeanDesc beanDesc = beanDescFactory . getBeanDesc ( param ) ; for ( int i = 0 ; i < beanDesc . getPropertyDescSize ( ) ; i ++ ) { PropertyDesc pd = beanDesc . getPropertyDesc ( i ) ; context . addArg ( pd . getPropertyName ( ) , pd . getValue ( param ) , pd . getPropertyType ( ) ) ; } } return context ; |
public class Predicates { /** * Creates a < b > greater than < / b > predicate that will pass items if the value stored under the given
* item { @ code attribute } is greater than the given { @ code value } .
* See also < i > Special Attributes < / i > , < i > Attribute Paths < / i > , < i > Handling of { @ code null } < / i > and
* < i > Implicit Type Conversion < / i > sections of { @ link Predicates } .
* @ param attribute the left - hand side attribute to fetch the value for comparison from .
* @ param value the right - hand side value to compare the attribute value against .
* @ return the created < b > greater than < / b > predicate .
* @ throws IllegalArgumentException if the { @ code attribute } does not exist . */
public static Predicate greaterThan ( String attribute , Comparable value ) { } } | return new GreaterLessPredicate ( attribute , value , false , false ) ; |
public class CompilerResults { /** * Prints out the formatted results . Errors are printed to the standard
* error stream and the summary ( if requested ) on standard output .
* @ param verbose
* whether or not to print verbose compiler output
* @ return true if there are no errors ; false otherwise */
public boolean print ( boolean verbose ) { } } | String errors = formatErrors ( ) ; if ( errors != null ) { System . err . println ( errors ) ; } if ( verbose ) { System . out . println ( formatStats ( ) ) ; } return ( errors != null ) ; |
public class DOMConfigurator { /** * Used internally to configure the log4j framework by parsing a DOM
* tree of XML elements based on < a
* href = " doc - files / log4j . dtd " > log4j . dtd < / a > . */
protected void parse ( Element element ) { } } | String rootElementName = element . getTagName ( ) ; if ( ! rootElementName . equals ( CONFIGURATION_TAG ) ) { if ( rootElementName . equals ( OLD_CONFIGURATION_TAG ) ) { LogLog . warn ( "The <" + OLD_CONFIGURATION_TAG + "> element has been deprecated." ) ; LogLog . warn ( "Use the <" + CONFIGURATION_TAG + "> element instead." ) ; } else { LogLog . error ( "DOM element is - not a <" + CONFIGURATION_TAG + "> element." ) ; return ; } } String debugAttrib = subst ( element . getAttribute ( INTERNAL_DEBUG_ATTR ) ) ; LogLog . debug ( "debug attribute= \"" + debugAttrib + "\"." ) ; // if the log4j . dtd is not specified in the XML file , then the
// " debug " attribute is returned as the empty string .
if ( ! debugAttrib . equals ( "" ) && ! debugAttrib . equals ( "null" ) ) { LogLog . setInternalDebugging ( OptionConverter . toBoolean ( debugAttrib , true ) ) ; } else { LogLog . debug ( "Ignoring " + INTERNAL_DEBUG_ATTR + " attribute." ) ; } // reset repository before configuration if reset = " true "
// on configuration element .
String resetAttrib = subst ( element . getAttribute ( RESET_ATTR ) ) ; LogLog . debug ( "reset attribute= \"" + resetAttrib + "\"." ) ; if ( ! ( "" . equals ( resetAttrib ) ) && OptionConverter . toBoolean ( resetAttrib , false ) ) { repository . resetConfiguration ( ) ; } String confDebug = subst ( element . getAttribute ( CONFIG_DEBUG_ATTR ) ) ; if ( ! confDebug . equals ( "" ) && ! confDebug . equals ( "null" ) ) { LogLog . warn ( "The \"" + CONFIG_DEBUG_ATTR + "\" attribute is deprecated." ) ; LogLog . warn ( "Use the \"" + INTERNAL_DEBUG_ATTR + "\" attribute instead." ) ; LogLog . setInternalDebugging ( OptionConverter . toBoolean ( confDebug , true ) ) ; } String thresholdStr = subst ( element . getAttribute ( THRESHOLD_ATTR ) ) ; LogLog . debug ( "Threshold =\"" + thresholdStr + "\"." ) ; if ( ! "" . equals ( thresholdStr ) && ! "null" . equals ( thresholdStr ) ) { repository . setThreshold ( thresholdStr ) ; } // Hashtable appenderBag = new Hashtable ( 11 ) ;
/* Building Appender objects , placing them in a local namespace
for future reference */
// First configure each category factory under the root element .
// Category factories need to be configured before any of
// categories they support .
String tagName = null ; Element currentElement = null ; Node currentNode = null ; NodeList children = element . getChildNodes ( ) ; final int length = children . getLength ( ) ; for ( int loop = 0 ; loop < length ; loop ++ ) { currentNode = children . item ( loop ) ; if ( currentNode . getNodeType ( ) == Node . ELEMENT_NODE ) { currentElement = ( Element ) currentNode ; tagName = currentElement . getTagName ( ) ; if ( tagName . equals ( CATEGORY_FACTORY_TAG ) || tagName . equals ( LOGGER_FACTORY_TAG ) ) { parseCategoryFactory ( currentElement ) ; } } } for ( int loop = 0 ; loop < length ; loop ++ ) { currentNode = children . item ( loop ) ; if ( currentNode . getNodeType ( ) == Node . ELEMENT_NODE ) { currentElement = ( Element ) currentNode ; tagName = currentElement . getTagName ( ) ; if ( tagName . equals ( CATEGORY ) || tagName . equals ( LOGGER ) ) { parseCategory ( currentElement ) ; } else if ( tagName . equals ( ROOT_TAG ) ) { parseRoot ( currentElement ) ; } else if ( tagName . equals ( RENDERER_TAG ) ) { parseRenderer ( currentElement ) ; } else if ( ! ( tagName . equals ( APPENDER_TAG ) || tagName . equals ( CATEGORY_FACTORY_TAG ) || tagName . equals ( LOGGER_FACTORY_TAG ) ) ) { quietParseUnrecognizedElement ( repository , currentElement , props ) ; } } } |
public class PackageManagerUtils { /** * Checks if the device has a touch screen .
* @ param manager the package manager .
* @ return { @ code true } if the device has a touch screen . */
@ TargetApi ( Build . VERSION_CODES . FROYO ) public static boolean hasTouchScreenFeature ( PackageManager manager ) { } } | return manager . hasSystemFeature ( PackageManager . FEATURE_TOUCHSCREEN ) ; |
public class AdminWhitelistRule { /** * Approves specific callables by their names . */
@ RequirePOST public HttpResponse doApprove ( @ QueryParameter String value ) throws IOException { } } | whitelisted . append ( value ) ; return HttpResponses . ok ( ) ; |
public class JSoupMatchers { /** * Creates a { @ link Matcher } for a JSoup { @ link Elements } containing { @ link Element } s with the given { @ code texts }
* as their own text content . The order of the elements is important .
* @ param texts The texts for which the { @ link Element } s content should match
* @ return a { @ link Matcher } for a JSoup { @ link Elements } containing { @ link Element } s with the given { @ code texts }
* as their own text content
* @ deprecated in favour of { @ link Matchers # contains ( List ) } */
@ Deprecated public static Matcher < Elements > containingElementsWithOwnTexts ( final String ... texts ) { } } | Matcher [ ] elementWithTextMatchers = new Matcher [ texts . length ] ; for ( int i = 0 ; i < elementWithTextMatchers . length ; i ++ ) { elementWithTextMatchers [ i ] = ElementWithOwnText . hasOwnText ( texts [ i ] ) ; } return Matchers . contains ( elementWithTextMatchers ) ; |
public class AstUtils { /** * Determine if a { @ link ClassNode } has one or more of the specified annotations on
* the class or any of its methods . N . B . the type names are not normally fully
* qualified .
* @ param node the class to examine
* @ param annotations the annotations to look for
* @ return { @ code true } if at least one of the annotations is found , otherwise
* { @ code false } */
public static boolean hasAtLeastOneAnnotation ( ClassNode node , String ... annotations ) { } } | if ( hasAtLeastOneAnnotation ( ( AnnotatedNode ) node , annotations ) ) { return true ; } for ( MethodNode method : node . getMethods ( ) ) { if ( hasAtLeastOneAnnotation ( method , annotations ) ) { return true ; } } return false ; |
public class CassandraJavaPairRDD { /** * Produces the empty CassandraRDD which has the same signature and properties , but it does not
* perform any validation and it does not even try to return any rows . */
public CassandraJavaPairRDD < K , V > toEmptyCassandraRDD ( ) { } } | CassandraRDD < Tuple2 < K , V > > newRDD = rdd ( ) . toEmptyCassandraRDD ( ) ; return wrap ( newRDD ) ; |
public class PrimaveraPMFileReader { /** * Process activity code data .
* @ param apibo global activity code data
* @ param project project - specific activity code data */
private void processActivityCodes ( APIBusinessObjects apibo , ProjectType project ) { } } | ActivityCodeContainer container = m_projectFile . getActivityCodes ( ) ; Map < Integer , ActivityCode > map = new HashMap < Integer , ActivityCode > ( ) ; List < ActivityCodeTypeType > types = new ArrayList < ActivityCodeTypeType > ( ) ; types . addAll ( apibo . getActivityCodeType ( ) ) ; types . addAll ( project . getActivityCodeType ( ) ) ; for ( ActivityCodeTypeType type : types ) { ActivityCode code = new ActivityCode ( type . getObjectId ( ) , type . getName ( ) ) ; container . add ( code ) ; map . put ( code . getUniqueID ( ) , code ) ; } List < ActivityCodeType > typeValues = new ArrayList < ActivityCodeType > ( ) ; typeValues . addAll ( apibo . getActivityCode ( ) ) ; typeValues . addAll ( project . getActivityCode ( ) ) ; for ( ActivityCodeType typeValue : typeValues ) { ActivityCode code = map . get ( typeValue . getCodeTypeObjectId ( ) ) ; if ( code != null ) { ActivityCodeValue value = code . addValue ( typeValue . getObjectId ( ) , typeValue . getCodeValue ( ) , typeValue . getDescription ( ) ) ; m_activityCodeMap . put ( value . getUniqueID ( ) , value ) ; } } |
public class SchemaConfiguration { /** * getJoinColumn method return ColumnInfo for the join column
* @ param columnType
* @ param String
* joinColumnName .
* @ return ColumnInfo object columnInfo . */
private ColumnInfo getJoinColumn ( TableInfo tableInfo , String joinColumnName , Class columnType ) { } } | ColumnInfo columnInfo = new ColumnInfo ( ) ; columnInfo . setColumnName ( joinColumnName ) ; columnInfo . setIndexable ( true ) ; IndexInfo indexInfo = new IndexInfo ( joinColumnName ) ; tableInfo . addToIndexedColumnList ( indexInfo ) ; columnInfo . setType ( columnType ) ; return columnInfo ; |
public class Graph { /** * Returns a new Graph after transitive reduction */
public Graph < T > reduce ( ) { } } | Builder < T > builder = new Builder < > ( ) ; nodes . stream ( ) . forEach ( u -> { builder . addNode ( u ) ; edges . get ( u ) . stream ( ) . filter ( v -> ! pathExists ( u , v , false ) ) . forEach ( v -> builder . addEdge ( u , v ) ) ; } ) ; return builder . build ( ) ; |
public class PharmacophoreUtils { /** * Write out one or more pharmacophore queries in the CDK XML format .
* @ param query The pharmacophore queries
* @ param out The OutputStream to write to
* @ throws IOException if there is a problem writing the XML document */
public static void writePharmacophoreDefinition ( PharmacophoreQuery query , OutputStream out ) throws IOException { } } | writePharmacophoreDefinition ( new PharmacophoreQuery [ ] { query } , out ) ; |
public class dnsnameserver { /** * Use this API to delete dnsnameserver resources . */
public static base_responses delete ( nitro_service client , dnsnameserver resources [ ] ) throws Exception { } } | base_responses result = null ; if ( resources != null && resources . length > 0 ) { dnsnameserver deleteresources [ ] = new dnsnameserver [ resources . length ] ; for ( int i = 0 ; i < resources . length ; i ++ ) { deleteresources [ i ] = new dnsnameserver ( ) ; deleteresources [ i ] . ip = resources [ i ] . ip ; deleteresources [ i ] . dnsvservername = resources [ i ] . dnsvservername ; } result = delete_bulk_request ( client , deleteresources ) ; } return result ; |
public class UpdateEventConfigurationsRequestMarshaller { /** * Marshall the given parameter object . */
public void marshall ( UpdateEventConfigurationsRequest updateEventConfigurationsRequest , ProtocolMarshaller protocolMarshaller ) { } } | if ( updateEventConfigurationsRequest == null ) { throw new SdkClientException ( "Invalid argument passed to marshall(...)" ) ; } try { protocolMarshaller . marshall ( updateEventConfigurationsRequest . getEventConfigurations ( ) , EVENTCONFIGURATIONS_BINDING ) ; } catch ( Exception e ) { throw new SdkClientException ( "Unable to marshall request to JSON: " + e . getMessage ( ) , e ) ; } |
public class DFSOutputStream { /** * Setup the Append pipeline , the length of current pipeline will shrink
* if any datanodes are dead during the process . */
private boolean setupPipelineForAppend ( LocatedBlock lastBlock ) throws IOException { } } | if ( nodes == null || nodes . length == 0 ) { String msg = "Could not get block locations. " + "Source file \"" + src + "\" - Aborting..." ; DFSClient . LOG . warn ( msg ) ; setLastException ( new IOException ( msg ) ) ; closed = true ; if ( streamer != null ) streamer . close ( ) ; return false ; } boolean success = createBlockOutputStream ( nodes , dfsClient . clientName , false , true ) ; long oldGenerationStamp = ( ( LocatedBlockWithOldGS ) lastBlock ) . getOldGenerationStamp ( ) ; if ( success ) { // bump up the generation stamp in NN .
Block newBlock = lastBlock . getBlock ( ) ; Block oldBlock = new Block ( newBlock . getBlockId ( ) , newBlock . getNumBytes ( ) , oldGenerationStamp ) ; dfsClient . namenode . updatePipeline ( dfsClient . clientName , oldBlock , newBlock , nodes ) ; } else { DFSClient . LOG . warn ( "Fall back to block recovery process when trying" + " to setup the append pipeline for file " + src ) ; // set the old generation stamp
block . setGenerationStamp ( oldGenerationStamp ) ; // fall back the block recovery
while ( processDatanodeError ( true , true ) ) { try { Thread . sleep ( 1000 ) ; } catch ( InterruptedException e ) { lastException = new IOException ( e ) ; break ; } } } return success ; |
public class CommerceNotificationAttachmentLocalServiceUtil { /** * Creates a new commerce notification attachment with the primary key . Does not add the commerce notification attachment to the database .
* @ param commerceNotificationAttachmentId the primary key for the new commerce notification attachment
* @ return the new commerce notification attachment */
public static com . liferay . commerce . notification . model . CommerceNotificationAttachment createCommerceNotificationAttachment ( long commerceNotificationAttachmentId ) { } } | return getService ( ) . createCommerceNotificationAttachment ( commerceNotificationAttachmentId ) ; |
public class Config { /** * Registers a timer event that executes periodically
* @ param conf the map with the existing topology configs
* @ param name the name of the timer
* @ param interval the frequency in which to run the task
* @ param task the task to run */
@ SuppressWarnings ( "unchecked" ) public static void registerTopologyTimerEvents ( Map < String , Object > conf , String name , Duration interval , Runnable task ) { } } | if ( interval . isZero ( ) || interval . isNegative ( ) ) { throw new IllegalArgumentException ( "Timer duration needs to be positive" ) ; } if ( ! conf . containsKey ( Config . TOPOLOGY_TIMER_EVENTS ) ) { conf . put ( Config . TOPOLOGY_TIMER_EVENTS , new HashMap < String , Pair < Duration , Runnable > > ( ) ) ; } Map < String , Pair < Duration , Runnable > > timers = ( Map < String , Pair < Duration , Runnable > > ) conf . get ( Config . TOPOLOGY_TIMER_EVENTS ) ; if ( timers . containsKey ( name ) ) { throw new IllegalArgumentException ( "Timer with name " + name + " already exists" ) ; } timers . put ( name , Pair . of ( interval , task ) ) ; |
public class AddressConfiguration { /** * A map of custom attributes to attributes to be attached to the message for this address . This payload is added to
* the push notification ' s ' data . pinpoint ' object or added to the email / sms delivery receipt event attributes .
* @ param context
* A map of custom attributes to attributes to be attached to the message for this address . This payload is
* added to the push notification ' s ' data . pinpoint ' object or added to the email / sms delivery receipt event
* attributes .
* @ return Returns a reference to this object so that method calls can be chained together . */
public AddressConfiguration withContext ( java . util . Map < String , String > context ) { } } | setContext ( context ) ; return this ; |
public class CapacitySchedulerConf { /** * Sets the maxCapacity of the given queue .
* @ param queue name of the queue
* @ param maxCapacity percent of the cluster for the queue . */
public void setMaxCapacity ( String queue , float maxCapacity ) { } } | rmConf . setFloat ( toFullPropertyName ( queue , MAX_CAPACITY_PROPERTY ) , maxCapacity ) ; |
public class XmlSchemaParser { /** * Helper function that uses a default value when value not set .
* @ param elementNode that should have the attribute
* @ param attrName that is to be looked up
* @ param defValue String to return if not set
* @ return value of the attribute or defValue */
public static String getAttributeValue ( final Node elementNode , final String attrName , final String defValue ) { } } | final Node attrNode = elementNode . getAttributes ( ) . getNamedItemNS ( null , attrName ) ; if ( attrNode == null ) { return defValue ; } return attrNode . getNodeValue ( ) ; |
public class Zips { /** * Unzips the given input stream of a ZIP to the given directory */
public static void unzip ( InputStream in , File toDir ) throws IOException { } } | ZipInputStream zis = new ZipInputStream ( new BufferedInputStream ( in ) ) ; try { ZipEntry entry = zis . getNextEntry ( ) ; while ( entry != null ) { if ( ! entry . isDirectory ( ) ) { String entryName = entry . getName ( ) ; File toFile = new File ( toDir , entryName ) ; toFile . getParentFile ( ) . mkdirs ( ) ; OutputStream os = new FileOutputStream ( toFile ) ; try { try { copy ( zis , os ) ; } finally { zis . closeEntry ( ) ; } } finally { closeQuietly ( os ) ; } } entry = zis . getNextEntry ( ) ; } } finally { closeQuietly ( zis ) ; } |
public class ElasticSearchIndex { /** * Configure ElasticSearchIndex ' s ES client according to 0.4 . x - 0.5.0 semantics .
* This checks local - mode first . If local - mode is true , then it creates a Node that
* uses JVM local transport and can ' t talk over the network . If local - mode is
* false , then it creates a TransportClient that can talk over the network and
* uses { @ link com . thinkaurelius . titan . graphdb . configuration . GraphDatabaseConfiguration # INDEX _ HOSTS }
* as the server addresses . Note that this configuration method
* does not allow creating a Node that talks over the network .
* This is activated by < b > not < / b > setting an explicit value for { @ link # INTERFACE } in the
* Titan configuration .
* @ see # interfaceConfiguration ( com . thinkaurelius . titan . diskstorage . configuration . Configuration )
* @ param config a config passed to ElasticSearchIndex ' s constructor
* @ return a node and client object open and ready for use */
private ElasticSearchSetup . Connection legacyConfiguration ( Configuration config ) { } } | Node node ; Client client ; if ( config . get ( LOCAL_MODE ) ) { log . debug ( "Configuring ES for JVM local transport" ) ; boolean clientOnly = config . get ( CLIENT_ONLY ) ; boolean local = config . get ( LOCAL_MODE ) ; NodeBuilder builder = NodeBuilder . nodeBuilder ( ) ; Preconditions . checkArgument ( config . has ( INDEX_CONF_FILE ) || config . has ( INDEX_DIRECTORY ) , "Must either configure configuration file or base directory" ) ; if ( config . has ( INDEX_CONF_FILE ) ) { String configFile = config . get ( INDEX_CONF_FILE ) ; ImmutableSettings . Builder sb = ImmutableSettings . settingsBuilder ( ) ; log . debug ( "Configuring ES from YML file [{}]" , configFile ) ; FileInputStream fis = null ; try { fis = new FileInputStream ( configFile ) ; sb . loadFromStream ( configFile , fis ) ; builder . settings ( sb . build ( ) ) ; } catch ( FileNotFoundException e ) { throw new TitanException ( e ) ; } finally { IOUtils . closeQuietly ( fis ) ; } } else { String dataDirectory = config . get ( INDEX_DIRECTORY ) ; log . debug ( "Configuring ES with data directory [{}]" , dataDirectory ) ; File f = new File ( dataDirectory ) ; if ( ! f . exists ( ) ) f . mkdirs ( ) ; ImmutableSettings . Builder b = ImmutableSettings . settingsBuilder ( ) ; for ( String sub : DATA_SUBDIRS ) { String subdir = dataDirectory + File . separator + sub ; f = new File ( subdir ) ; if ( ! f . exists ( ) ) f . mkdirs ( ) ; b . put ( "path." + sub , subdir ) ; } b . put ( "script.disable_dynamic" , false ) ; b . put ( "indices.ttl.interval" , "5s" ) ; builder . settings ( b . build ( ) ) ; String clustername = config . get ( CLUSTER_NAME ) ; Preconditions . checkArgument ( StringUtils . isNotBlank ( clustername ) , "Invalid cluster name: %s" , clustername ) ; builder . clusterName ( clustername ) ; } node = builder . client ( clientOnly ) . data ( ! clientOnly ) . local ( local ) . node ( ) ; client = node . client ( ) ; } else { log . debug ( "Configuring ES for network transport" ) ; ImmutableSettings . Builder settings = ImmutableSettings . settingsBuilder ( ) ; if ( config . has ( CLUSTER_NAME ) ) { String clustername = config . get ( CLUSTER_NAME ) ; Preconditions . checkArgument ( StringUtils . isNotBlank ( clustername ) , "Invalid cluster name: %s" , clustername ) ; settings . put ( "cluster.name" , clustername ) ; } else { settings . put ( "client.transport.ignore_cluster_name" , true ) ; } log . debug ( "Transport sniffing enabled: {}" , config . get ( CLIENT_SNIFF ) ) ; settings . put ( "client.transport.sniff" , config . get ( CLIENT_SNIFF ) ) ; settings . put ( "script.disable_dynamic" , false ) ; TransportClient tc = new TransportClient ( settings . build ( ) ) ; int defaultPort = config . has ( INDEX_PORT ) ? config . get ( INDEX_PORT ) : HOST_PORT_DEFAULT ; for ( String host : config . get ( INDEX_HOSTS ) ) { String [ ] hostparts = host . split ( ":" ) ; String hostname = hostparts [ 0 ] ; int hostport = defaultPort ; if ( hostparts . length == 2 ) hostport = Integer . parseInt ( hostparts [ 1 ] ) ; log . info ( "Configured remote host: {} : {}" , hostname , hostport ) ; tc . addTransportAddress ( new InetSocketTransportAddress ( hostname , hostport ) ) ; } client = tc ; node = null ; } return new ElasticSearchSetup . Connection ( node , client ) ; |
public class AbstractCLA { /** * { @ inheritDoc } */
@ Override public Object asEnum ( final String name , final Object [ ] possibleConstants ) throws ParseException { } } | throw new ParseException ( "invalid to store " + this . toString ( ) + " in an Enum" , 0 ) ; |
public class WsLogger { /** * @ see java . util . logging . Logger # finest ( java . lang . String ) */
@ Override public void finest ( String msg ) { } } | if ( isLoggable ( Level . FINEST ) ) { log ( Level . FINEST , msg ) ; } |
public class KeySnapshot { /** * Get the user keys from this node only .
* @ param homeOnly - exclude the non - local ( cached ) keys if set
* @ return KeySnapshot containing keys from the local K / V . */
public static KeySnapshot localSnapshot ( boolean homeOnly ) { } } | Object [ ] kvs = H2O . STORE . raw_array ( ) ; ArrayList < KeyInfo > res = new ArrayList < > ( ) ; for ( int i = 2 ; i < kvs . length ; i += 2 ) { Object ok = kvs [ i ] ; if ( ! ( ok instanceof Key ) ) continue ; // Ignore tombstones and Primes and null ' s
Key key = ( Key ) ok ; if ( ! key . user_allowed ( ) ) continue ; if ( homeOnly && ! key . home ( ) ) continue ; // Raw array can contain regular and also wrapped values into Prime marker class :
// - if we see Value object , create instance of KeyInfo
// - if we do not see Value object directly ( it can be wrapped in Prime marker class ) ,
// try to unwrap it via calling STORE . get ( ~ H2O . get ) and then
// look at wrapped value again .
Value val = Value . STORE_get ( key ) ; if ( val == null ) continue ; res . add ( new KeyInfo ( key , val ) ) ; } final KeyInfo [ ] arr = res . toArray ( new KeyInfo [ res . size ( ) ] ) ; Arrays . sort ( arr ) ; return new KeySnapshot ( arr ) ; |
public class CmisConnector { /** * Converts CMIS object to JCR node .
* @ param id the identifier of the CMIS object
* @ return JCR node document . */
private Document cmisObject ( String id ) { } } | CmisObject cmisObject ; try { cmisObject = session . getObject ( id ) ; } catch ( CmisObjectNotFoundException e ) { return null ; } // object does not exist ? return null
if ( cmisObject == null ) { return null ; } // converting CMIS object to JCR node
switch ( cmisObject . getBaseTypeId ( ) ) { case CMIS_FOLDER : return cmisFolder ( cmisObject ) ; case CMIS_DOCUMENT : return cmisDocument ( cmisObject ) ; case CMIS_POLICY : case CMIS_RELATIONSHIP : case CMIS_SECONDARY : case CMIS_ITEM : } // unexpected object type
return null ; |
public class SortedRanges { /** * Add the range indices . It is ensured that the added range
* doesn ' t overlap the existing ranges . If it overlaps , the
* existing overlapping ranges are removed and a single range
* having the superset of all the removed ranges and this range
* is added .
* If the range is of 0 length , doesn ' t do anything .
* @ param range Range to be added . */
synchronized void add ( Range range ) { } } | if ( range . isEmpty ( ) ) { return ; } long startIndex = range . getStartIndex ( ) ; long endIndex = range . getEndIndex ( ) ; // make sure that there are no overlapping ranges
SortedSet < Range > headSet = ranges . headSet ( range ) ; if ( headSet . size ( ) > 0 ) { Range previousRange = headSet . last ( ) ; LOG . debug ( "previousRange " + previousRange ) ; if ( startIndex < previousRange . getEndIndex ( ) ) { // previousRange overlaps this range
// remove the previousRange
if ( ranges . remove ( previousRange ) ) { indicesCount -= previousRange . getLength ( ) ; } // expand this range
startIndex = previousRange . getStartIndex ( ) ; endIndex = endIndex >= previousRange . getEndIndex ( ) ? endIndex : previousRange . getEndIndex ( ) ; } } Iterator < Range > tailSetIt = ranges . tailSet ( range ) . iterator ( ) ; while ( tailSetIt . hasNext ( ) ) { Range nextRange = tailSetIt . next ( ) ; LOG . debug ( "nextRange " + nextRange + " startIndex:" + startIndex + " endIndex:" + endIndex ) ; if ( endIndex >= nextRange . getStartIndex ( ) ) { // nextRange overlaps this range
// remove the nextRange
tailSetIt . remove ( ) ; indicesCount -= nextRange . getLength ( ) ; if ( endIndex < nextRange . getEndIndex ( ) ) { // expand this range
endIndex = nextRange . getEndIndex ( ) ; break ; } } else { break ; } } add ( startIndex , endIndex ) ; |
public class OperationHandler { /** * This method calculates and loads the lists relating to the operations to be performed .
* @ param dynamicMethodsToWrite methods to generate */
public void loadStructures ( Set < Method > dynamicMethodsToWrite ) { } } | for ( Field configuredField : getListOfFields ( configuredClass ) ) { String targetFieldName = configReader . retrieveTargetFieldName ( configuredField ) ; if ( targetFieldName == THE_FIELD_IS_NOT_CONFIGURED ) continue ; boolean isNestedMapping = isNestedMapping ( targetFieldName ) ; Field targetField = null ; NestedMappingInfo nestedMappingInfo = null ; if ( isNestedMapping ) try { nestedMappingInfo = loadNestedMappingInformation ( xml , targetClass , targetFieldName , sourceClass , destinationClass , configuredField ) ; targetField = nestedMappingInfo . getLastNestedField ( ) ; } catch ( InvalidNestedMappingException e ) { // catch and rethrown the exception with more information
Error . invalidNestedMapping ( configuredClass , configuredField , targetClass , e . getMessage ( ) , e . getMessages ( ) . get ( InvalidNestedMappingException . FIELD ) ) ; } else targetField = retrieveField ( targetClass , targetFieldName ) ; MappedField configuredMappedField = new MappedField ( configuredField ) ; MappedField targetMappedField = isNestedMapping ? nestedMappingInfo . getLastNestedMappedField ( ) : new MappedField ( targetField ) ; MappedField destinationMappedField = isDestConfigured ? configuredMappedField : targetMappedField ; MappedField sourceMappedField = isDestConfigured ? targetMappedField : configuredMappedField ; Field destinationField = isDestConfigured ? configuredField : targetField ; Field sourceField = isDestConfigured ? targetField : configuredField ; // load and check the get / set custom methods of destination and source fields
if ( isNestedMapping ) configReader . loadAccessors ( nestedMappingInfo . getLastNestedClass ( ) , configuredMappedField , targetMappedField ) ; else configReader . loadAccessors ( configuredMappedField , targetMappedField ) ; boolean isUndefined = false ; try { isUndefined = operationAnalyzer . isUndefined ( destinationField , sourceField ) ; } catch ( Exception e ) { // catch and rethrown the exception with more information
Error . badConversion ( destinationField , destinationClass , sourceField , sourceClass , e . getMessage ( ) ) ; } if ( isUndefined ) Error . undefinedMapping ( destinationField , destinationClass , sourceField , sourceClass ) ; InfoOperation info = operationAnalyzer . getInfo ( ) ; OperationType operationType = info . getOperationType ( ) ; AGeneralOperation operation = OperationFactory . getOperation ( operationType ) ; if ( operationType . isBasic ( ) ) simpleOperations . add ( ( ASimpleOperation ) operation ) ; if ( operationType . isComplex ( ) ) complexOperations . add ( ( ( AComplexOperation ) operation ) . setDestinationClass ( defineStructure ( destinationMappedField . getValue ( ) , sourceMappedField . getValue ( ) ) ) ) ; if ( operationType . isRecursive ( ) ) ( ( ARecursiveOperation ) operation ) . setDynamicMethodsToWrite ( dynamicMethodsToWrite ) . setXml ( xml ) . setConfigChosen ( isNull ( info . getConfigChosen ( ) ) // if both classes are configured
? configurationChosen // returns the configuration chosen
: info . getConfigChosen ( ) ) ; // else returns the configuration retrieved
// common settings
operation . setDestinationField ( destinationMappedField ) . setSourceField ( sourceMappedField ) . setInfoOperation ( info ) . setNestedMappingInfo ( nestedMappingInfo ) ; boolean isAvoidSet = false ; boolean isConversion = info . getOperationType ( ) . isAConversion ( ) ; if ( isConversion ) isAvoidSet = conversionAnalyzer . getMethod ( ) . isAvoidSet ( ) ; // verifies destination accessors only if isn ' t a nested field
if ( ! isNestedMapping || ! targetClass . equals ( destinationClass ) ) if ( isAvoidSet ) verifyGetterMethods ( destinationClass , destinationMappedField ) ; else verifiesAccessorMethods ( destinationClass , destinationMappedField ) ; // verifies source accessors only if isn ' t a nested field
if ( ! isNestedMapping || ! targetClass . equals ( sourceClass ) ) verifyGetterMethods ( sourceClass , sourceMappedField ) ; findSetterMethods ( sourceClass , sourceMappedField ) ; operation . avoidDestinationSet ( isAvoidSet ) ; if ( isConversion ) { conversionHandler . load ( conversionAnalyzer ) . from ( sourceMappedField ) . to ( destinationMappedField ) ; // in case of dynamic conversion
if ( conversionHandler . toBeCreated ( ) ) dynamicMethodsToWrite . add ( conversionHandler . loadMethod ( ) ) ; operation . setConversionMethod ( conversionHandler . getMethod ( ) ) . setMemberShip ( conversionHandler . getMembership ( ) ) ; } } // checks if there isn ' t a correspondence between classes
if ( simpleOperations . isEmpty ( ) && complexOperations . isEmpty ( ) ) Error . absentRelationship ( configuredClass , targetClass ) ; |
public class CheerleaderClient { /** * " Cache " the tracks list of the supported artist retrieved from network in RAM
* to avoid requesting SoundCloud API for next call .
* @ return { @ link rx . functions . Func1 } used to save the retrieved tracks list */
private Func1 < ArrayList < SoundCloudTrack > , ArrayList < SoundCloudTrack > > cacheTracks ( ) { } } | return new Func1 < ArrayList < SoundCloudTrack > , ArrayList < SoundCloudTrack > > ( ) { @ Override public ArrayList < SoundCloudTrack > call ( ArrayList < SoundCloudTrack > soundCloudTracks ) { if ( soundCloudTracks . size ( ) > 0 ) { mCacheRam . tracks = soundCloudTracks ; } return soundCloudTracks ; } } ; |
public class AbstractCompare { /** * Get the value to use in the compare .
* It will return the same " value " the client would have used in its subordinate logic .
* The compare value will either be ( i ) a date formatted String for WDateFields , ( ii ) a BigDecimal for WNumberFields
* or ( iii ) a String value .
* @ return the value to be used for the compare . */
protected Object getCompareValue ( ) { } } | // Date Compare ( Use Date Formatted String - YYYY - MM - DD )
if ( trigger instanceof WDateField ) { return value == null ? null : new SimpleDateFormat ( INTERNAL_DATE_FORMAT ) . format ( value ) ; } else if ( trigger instanceof WNumberField ) { // Number Compare ( Use Number Object )
return value ; } else if ( trigger instanceof AbstractWSelectList ) { // String Compare - List ( Use the Option ' s Code )
final AbstractWSelectList listTrigger = ( AbstractWSelectList ) trigger ; final List < ? > options = listTrigger . getOptions ( ) ; // No options , just return the compare value ( so that a test against null works correctly )
if ( options == null || options . isEmpty ( ) ) { return value == null ? null : value . toString ( ) ; } // Check if the value is a valid option allowing for " Legacy " matching
if ( SelectListUtil . containsOptionWithMatching ( options , value ) ) { Object option = SelectListUtil . getOptionWithMatching ( options , value ) ; String code = listTrigger . optionToCode ( option ) ; return code ; } // Return the value as a String - Treat empty the same as null
return ( value == null || Util . empty ( value . toString ( ) ) ) ? null : value . toString ( ) ; } else if ( trigger instanceof RadioButtonGroup && value instanceof WRadioButton ) { // String Compare for RadioButtonGroup and value is WRadioButton ( Use the button value )
// Note - This is only for backward compatibility where projects have used a radio button
// in the trigger . Projects should use the value expected , not the radio button .
// If the radio button passed into the compare is used in a repeater , then this compare will not work .
String data = ( ( WRadioButton ) value ) . getValue ( ) ; // Treat empty the same as null
return Util . empty ( data ) ? null : data ; } else { // String Compare
// Treat empty the same as null
return ( value == null || Util . empty ( value . toString ( ) ) ) ? null : value . toString ( ) ; } |
public class NetworkInterfaceMarshaller { /** * Marshall the given parameter object . */
public void marshall ( NetworkInterface networkInterface , ProtocolMarshaller protocolMarshaller ) { } } | if ( networkInterface == null ) { throw new SdkClientException ( "Invalid argument passed to marshall(...)" ) ; } try { protocolMarshaller . marshall ( networkInterface . getSubnetId ( ) , SUBNETID_BINDING ) ; protocolMarshaller . marshall ( networkInterface . getNetworkInterfaceId ( ) , NETWORKINTERFACEID_BINDING ) ; } catch ( Exception e ) { throw new SdkClientException ( "Unable to marshall request to JSON: " + e . getMessage ( ) , e ) ; } |
public class JettyBootstrap { /** * Add an exploded ( not packaged ) War application from the current classpath , specifying the context path .
* @ param explodedWar
* the exploded war path
* @ param descriptor
* the web . xml descriptor path
* @ param contextPath
* the path ( base URL ) to make the resource available
* @ return WebAppContext
* @ throws JettyBootstrapException
* on failed */
public WebAppContext addExplodedWarAppFromClasspath ( String explodedWar , String descriptor , String contextPath ) throws JettyBootstrapException { } } | ExplodedWarAppJettyHandler explodedWarAppJettyHandler = new ExplodedWarAppJettyHandler ( getInitializedConfiguration ( ) ) ; explodedWarAppJettyHandler . setWebAppBaseFromClasspath ( explodedWar ) ; explodedWarAppJettyHandler . setDescriptor ( descriptor ) ; explodedWarAppJettyHandler . setContextPath ( contextPath ) ; WebAppContext webAppContext = explodedWarAppJettyHandler . getHandler ( ) ; handlers . addHandler ( webAppContext ) ; return webAppContext ; |
public class PlaybackService { /** * Seek to the precise track position .
* The current playing state of the SoundCloud player will be kept .
* If playing it remains playing , if paused it remains paused .
* @ param context context from which the service will be started .
* @ param clientId SoundCloud api client id .
* @ param milli time in milli of the position . */
public static void seekTo ( Context context , String clientId , int milli ) { } } | Intent intent = new Intent ( context , PlaybackService . class ) ; intent . setAction ( ACTION_SEEK_TO ) ; intent . putExtra ( BUNDLE_KEY_SOUND_CLOUD_CLIENT_ID , clientId ) ; intent . putExtra ( BUNDLE_KEY_SOUND_CLOUD_TRACK_POSITION , milli ) ; context . startService ( intent ) ; |
public class NorwegianDateUtil { /** * Add the given number of days to the calendar and convert to Date .
* @ param calendar
* The calendar to add to .
* @ param days
* The number of days to add .
* @ return The date object given by the modified calendar . */
private static Date rollGetDate ( Calendar calendar , int days ) { } } | Calendar easterSunday = ( Calendar ) calendar . clone ( ) ; easterSunday . add ( Calendar . DATE , days ) ; return easterSunday . getTime ( ) ; |
public class SoundLoader { /** * Get the cached Config . */
protected Config getConfig ( String packagePath ) { } } | Config c = _configs . get ( packagePath ) ; if ( c == null ) { Properties props = new Properties ( ) ; String propFilename = packagePath + Sounds . PROP_NAME + ".properties" ; try { props = ConfigUtil . loadInheritedProperties ( propFilename , _rmgr . getClassLoader ( ) ) ; } catch ( IOException ioe ) { log . warning ( "Failed to load sound properties" , "filename" , propFilename , ioe ) ; } c = new Config ( props ) ; _configs . put ( packagePath , c ) ; } return c ; |
public class PMML4UnitImpl { /** * Retrieves a Map with entries that consist of
* key - > a model identifier
* value - > the PMML4Model object that the key refers to
* where the PMML4Model does not indicate a parent model ( i . e . the
* model is not a child model )
* @ return The Map of model identifiers and their corresponding PMML4Model objects */
@ Override public Map < String , PMML4Model > getRootModels ( ) { } } | Map < String , PMML4Model > rootModels = new HashMap < > ( ) ; for ( PMML4Model model : this . modelsMap . values ( ) ) { if ( model . getParentModel ( ) == null ) { rootModels . put ( model . getModelId ( ) , model ) ; } } return rootModels ; |
public class CoronaJobInProgress { /** * Job state change must happen thru this call */
private void changeStateTo ( int newState ) { } } | synchronized ( lockObject ) { int oldState = this . status . getRunState ( ) ; if ( oldState == newState ) { return ; // old and new states are same
} this . status . setRunState ( newState ) ; } |
public class LargeList { /** * Return size of list .
* @ return size of list . */
public int size ( ) { } } | Record record = client . operate ( this . policy , this . key , ListOperation . size ( this . binNameString ) ) ; if ( record != null ) { return record . getInt ( this . binNameString ) ; } return 0 ; |
public class MessageUtils { /** * Retrieve the message from a specific bundle . It does not look on application message bundle
* or default message bundle . If it is required to look on those bundles use getMessageFromBundle instead
* @ param bundleBaseName baseName of ResourceBundle to load localized messages
* @ param locale current locale
* @ param messageId id of message
* @ param params parameters to set at localized message
* @ return generated FacesMessage */
public static FacesMessage getMessage ( String bundleBaseName , Locale locale , String messageId , Object params [ ] ) { } } | if ( bundleBaseName == null ) { throw new NullPointerException ( "Unable to locate ResourceBundle: bundle is null" ) ; } ResourceBundle bundle = ResourceBundle . getBundle ( bundleBaseName , locale ) ; return getMessage ( bundle , messageId , params ) ; |
public class CmsPublishProject { /** * Returns the html for the confirmation message . < p >
* @ return the html for the confirmation message */
public String buildConfirmation ( ) { } } | StringBuffer result = new StringBuffer ( 512 ) ; result . append ( "<p><div id='conf-msg'>\n" ) ; if ( ! isDirectPublish ( ) ) { result . append ( key ( Messages . GUI_PUBLISH_PROJECT_CONFIRMATION_1 , new Object [ ] { getProjectname ( ) } ) ) ; } else { boolean isFolder = false ; if ( ! isMultiOperation ( ) ) { try { isFolder = getCms ( ) . readResource ( getParamResource ( ) , CmsResourceFilter . ALL ) . isFolder ( ) ; } catch ( CmsException e ) { // ignore
} } if ( isMultiOperation ( ) || isFolder || ( hasSiblings ( ) && hasCorrectLockstate ( ) ) ) { result . append ( key ( Messages . GUI_PUBLISH_MULTI_CONFIRMATION_0 ) ) ; } else { result . append ( key ( Messages . GUI_PUBLISH_CONFIRMATION_0 ) ) ; } } result . append ( "\n</div></p>\n" ) ; return result . toString ( ) ; |
public class AmazonApiGatewayManagementApiClient { /** * Sends the provided data to the specified connection .
* @ param postToConnectionRequest
* @ return Result of the PostToConnection operation returned by the service .
* @ throws GoneException
* The connection with the provided id no longer exists .
* @ throws LimitExceededException
* The client is sending more than the allowed number of requests per unit of time .
* @ throws PayloadTooLargeException
* The data has exceeded the maximum size allowed .
* @ throws ForbiddenException
* The caller is not authorized to invoke this operation .
* @ sample AmazonApiGatewayManagementApi . PostToConnection
* @ see < a href = " http : / / docs . aws . amazon . com / goto / WebAPI / apigatewaymanagementapi - 2018-11-29 / PostToConnection "
* target = " _ top " > AWS API Documentation < / a > */
@ Override public PostToConnectionResult postToConnection ( PostToConnectionRequest request ) { } } | request = beforeClientExecution ( request ) ; return executePostToConnection ( request ) ; |
public class BackendConnection { /** * Get connections of current thread datasource .
* @ param connectionMode connection mode
* @ param dataSourceName data source name
* @ param connectionSize size of connections to be get
* @ return connections
* @ throws SQLException SQL exception */
public List < Connection > getConnections ( final ConnectionMode connectionMode , final String dataSourceName , final int connectionSize ) throws SQLException { } } | if ( stateHandler . isInTransaction ( ) ) { return getConnectionsWithTransaction ( connectionMode , dataSourceName , connectionSize ) ; } else { return getConnectionsWithoutTransaction ( connectionMode , dataSourceName , connectionSize ) ; } |
public class DialogPreference { /** * Obtains the message of the dialog , which is shown by the preference , from a specific typed
* array .
* @ param typedArray
* The typed array , the message should be obtained from , as an instance of the class
* { @ link TypedArray } . The typed array may not be null */
private void obtainDialogMessage ( @ NonNull final TypedArray typedArray ) { } } | setDialogMessage ( typedArray . getText ( R . styleable . DialogPreference_android_dialogMessage ) ) ; |
public class ThreadedBulkJSONDataESSink { /** * ( non - Javadoc )
* @ see com . sematext . ag . sink . AbstractHttpSink # execute ( org . apache . http . client . methods . HttpRequestBase ) */
@ Override public boolean execute ( HttpRequestBase request ) { } } | DataSenderThread senderThread = new DataSenderThread ( HTTP_CLIENT_INSTANCE , request ) ; senderThread . run ( ) ; return true ; |
public class SepaUtil { /** * Erzeugt ein neues XMLCalender - Objekt .
* @ param isoDate optional . Das zu verwendende Datum .
* Wird es weggelassen , dann wird das aktuelle Datum ( mit Uhrzeit ) verwendet .
* @ return das XML - Calendar - Objekt .
* @ throws Exception */
public static XMLGregorianCalendar createCalendar ( String isoDate ) throws Exception { } } | if ( isoDate == null ) { SimpleDateFormat format = new SimpleDateFormat ( DATETIME_FORMAT ) ; isoDate = format . format ( new Date ( ) ) ; } DatatypeFactory df = DatatypeFactory . newInstance ( ) ; return df . newXMLGregorianCalendar ( isoDate ) ; |
public class ApiOvhXdsl { /** * List of incidents
* REST : GET / xdsl / incidents
* @ param creationDate [ required ] Filter the value of creationDate property ( > )
* @ param endDate [ required ] Filter the value of endDate property ( < ) */
public ArrayList < Long > incidents_GET ( Date creationDate , Date endDate ) throws IOException { } } | String qPath = "/xdsl/incidents" ; StringBuilder sb = path ( qPath ) ; query ( sb , "creationDate" , creationDate ) ; query ( sb , "endDate" , endDate ) ; String resp = execN ( qPath , "GET" , sb . toString ( ) , null ) ; return convertTo ( resp , t15 ) ; |
public class ControllerRegistry { /** * Register the controller methods as routes .
* @ param controllerMethods
* @ param controller */
private void registerControllerMethods ( Map < Method , Class < ? extends Annotation > > controllerMethods , Controller controller ) { } } | List < Route > controllerRoutes = createControllerRoutes ( controllerMethods ) ; for ( Route controllerRoute : controllerRoutes ) { if ( controller != null ) { ( ( ControllerHandler ) controllerRoute . getRouteHandler ( ) ) . setController ( controller ) ; controllerRoute . bind ( "__controller" , controller ) ; } } this . routes . addAll ( controllerRoutes ) ; |
public class FacesMessages { /** * Returns style matching the severity error .
* @ param clientId
* @ return */
public static String getErrorSeverityClass ( String clientId ) { } } | String [ ] levels = { "bf-no-message has-success" , "bf-info" , "bf-warning has-warning" , "bf-error has-error" , "bf-fatal has-error" } ; int level = 0 ; Iterator < FacesMessage > messages = FacesContext . getCurrentInstance ( ) . getMessages ( clientId ) ; if ( null != messages ) { if ( ! messages . hasNext ( ) ) { return "" ; } while ( messages . hasNext ( ) ) { FacesMessage message = messages . next ( ) ; if ( message . getSeverity ( ) . equals ( FacesMessage . SEVERITY_INFO ) ) if ( level < 1 ) level = 1 ; if ( message . getSeverity ( ) . equals ( FacesMessage . SEVERITY_WARN ) ) if ( level < 2 ) level = 2 ; if ( message . getSeverity ( ) . equals ( FacesMessage . SEVERITY_ERROR ) ) if ( level < 3 ) level = 3 ; if ( message . getSeverity ( ) . equals ( FacesMessage . SEVERITY_FATAL ) ) if ( level < 4 ) level = 4 ; } return levels [ level ] ; } return "" ; |
public class PageRequest { /** * Creates a new unsorted { @ link PageRequest } .
* @ param page zero - based page index .
* @ param size the size of the page to be returned .
* @ since 2.0 */
public static PageRequest of ( final int page , final int size ) { } } | return PageRequest . of ( page , size , Sort . unsorted ( ) ) ; |
public class Topicspace { /** * / * ( non - Javadoc )
* @ see com . ibm . ws . sib . processor . runtime . SIMPTopicSpaceControllable # getRemoteTopicSpaceIterator ( ) */
public SIMPIterator getRemoteTopicSpaceIterator ( ) { } } | if ( TraceComponent . isAnyTracingEnabled ( ) && tc . isEntryEnabled ( ) ) SibTr . entry ( tc , "getRemoteTopicSpaceIterator" ) ; // we get the hashmap of all PSOHs
// these are keyed by SIB8Uuid of the remote ME
Map pubsubOutHandlers = baseDest . cloneAllPubSubOutputHandlers ( ) ; // we get a corresponding list of AIHs , also keyed by remote ME uuid
Map aihMap = baseDest . getPseudoDurableAIHMap ( ) ; Map pairings = new HashMap ( ) ; // first we go through the list of psoh
Iterator psOHIterator = pubsubOutHandlers . values ( ) . iterator ( ) ; while ( psOHIterator . hasNext ( ) ) { PubSubOutputHandler psoh = ( PubSubOutputHandler ) psOHIterator . next ( ) ; SIBUuid8 uuid = psoh . getTargetMEUuid ( ) ; // add a new pairing
RemoteTopicSpaceIterator . PublishConsumePairing pairing = new RemoteTopicSpaceIterator . PublishConsumePairing ( psoh , null ) ; pairings . put ( uuid , pairing ) ; } // now we go through the map adding in AIHs to existing
// pairing where appropriate , or creating new pairings
// for new additions
Iterator aihIterator = aihMap . values ( ) . iterator ( ) ; while ( aihIterator . hasNext ( ) ) { AnycastInputHandler aih = ( AnycastInputHandler ) aihIterator . next ( ) ; SIBUuid8 uuid = aih . getLocalisationUuid ( ) ; Object existingPairing = pairings . get ( uuid ) ; if ( existingPairing != null ) { ( ( RemoteTopicSpaceIterator . PublishConsumePairing ) existingPairing ) . setAnycastInputHandler ( aih ) ; } else { // create a new pairing for just the AIH
RemoteTopicSpaceIterator . PublishConsumePairing pairing = new RemoteTopicSpaceIterator . PublishConsumePairing ( null , aih ) ; pairings . put ( uuid , pairing ) ; } } // these pairings are now used by the iterator
SIMPIterator itr = new RemoteTopicSpaceIterator ( pairings . values ( ) . iterator ( ) ) ; if ( TraceComponent . isAnyTracingEnabled ( ) && tc . isEntryEnabled ( ) ) SibTr . exit ( tc , "getRemoteTopicSpaceIterator" , itr ) ; return itr ; |
public class TaskClient { /** * Perform a batch poll for tasks by task type . Batch size is configurable by count .
* Returns an iterator that streams tasks as they become available through GRPC .
* @ param taskType Type of task to poll for
* @ param workerId Name of the client worker . Used for logging .
* @ param count Maximum number of tasks to be returned . Actual number of tasks returned can be less than this number .
* @ param timeoutInMillisecond Long poll wait timeout .
* @ return Iterator of tasks awaiting to be executed . */
public Iterator < Task > batchPollTasksByTaskTypeAsync ( String taskType , String workerId , int count , int timeoutInMillisecond ) { } } | Preconditions . checkArgument ( StringUtils . isNotBlank ( taskType ) , "Task type cannot be blank" ) ; Preconditions . checkArgument ( StringUtils . isNotBlank ( workerId ) , "Worker id cannot be blank" ) ; Preconditions . checkArgument ( count > 0 , "Count must be greater than 0" ) ; Iterator < TaskPb . Task > it = stub . batchPoll ( TaskServicePb . BatchPollRequest . newBuilder ( ) . setTaskType ( taskType ) . setWorkerId ( workerId ) . setCount ( count ) . setTimeout ( timeoutInMillisecond ) . build ( ) ) ; return Iterators . transform ( it , protoMapper :: fromProto ) ; |
public class JcrLockManager { /** * Attempt to obtain a lock on the supplied node .
* @ param node the node ; may not be null
* @ param isDeep true if the lock should be a deep lock
* @ param isSessionScoped true if the lock should be scoped to the session
* @ param timeoutHint desired lock timeout in seconds ( servers are free to ignore this value ) ; specify { @ link Long # MAX _ VALUE }
* for no timeout .
* @ param ownerInfo a string containing owner information supplied by the client , and recorded on the lock ; if null , then the
* session ' s user ID will be used
* @ return the lock ; never null
* @ throws AccessDeniedException if the caller does not have privilege to lock the node
* @ throws InvalidItemStateException if the node has been modified and cannot be locked
* @ throws LockException if the lock could not be obtained
* @ throws RepositoryException if an error occurs updating the graph state */
public Lock lock ( AbstractJcrNode node , boolean isDeep , boolean isSessionScoped , long timeoutHint , String ownerInfo ) throws LockException , AccessDeniedException , InvalidItemStateException , RepositoryException { } } | if ( ! node . isLockable ( ) ) { throw new LockException ( JcrI18n . nodeNotLockable . text ( node . location ( ) ) ) ; } if ( node . isLocked ( ) ) { throw new LockException ( JcrI18n . alreadyLocked . text ( node . location ( ) ) ) ; } if ( node . isNew ( ) || node . isModified ( ) ) { throw new InvalidItemStateException ( JcrI18n . changedNodeCannotBeLocked . text ( node . location ( ) ) ) ; } // Try to obtain the lock . . .
ModeShapeLock lock = lockManager . lock ( session , node . node ( ) , isDeep , isSessionScoped , timeoutHint , ownerInfo ) ; String token = lock . getLockToken ( ) ; lockTokens . add ( token ) ; return lock . lockFor ( session ) ; |
public class CachingPersonAttributeDaoImpl { /** * Used to specify the placeholder object to put in the cache for null results . Defaults to a minimal Set . Most
* installations will not need to set this .
* @ param nullResultsObject the nullResultsObject to set */
@ JsonIgnore public void setNullResultsObject ( final Set < IPersonAttributes > nullResultsObject ) { } } | if ( nullResultsObject == null ) { throw new IllegalArgumentException ( "nullResultsObject may not be null" ) ; } this . nullResultsObject = nullResultsObject ; |
public class DataReader { /** * Recursively parse the zone labels until we get to a zone info object . */
private List < TimeZoneInfo > parseTimeZoneInfo ( JsonObject root , List < String > prefix ) { } } | List < TimeZoneInfo > zones = new ArrayList < > ( ) ; for ( String label : objectKeys ( root ) ) { JsonObject value = resolve ( root , label ) ; List < String > zone = new ArrayList < > ( prefix ) ; zone . add ( label ) ; if ( isTimeZone ( value ) ) { TimeZoneInfo info = parseTimeZoneObject ( value , zone ) ; zones . add ( info ) ; } else { zones . addAll ( parseTimeZoneInfo ( value , zone ) ) ; } } return zones ; |
public class RecordConverter { /** * Convert a set of records in to a matrix
* @ param records the records ot convert
* @ return the matrix for the records */
public static INDArray toMatrix ( List < List < Writable > > records ) { } } | List < INDArray > toStack = new ArrayList < > ( ) ; for ( List < Writable > l : records ) { toStack . add ( toArray ( l ) ) ; } return Nd4j . vstack ( toStack ) ; |
public class NodeIdAwareSocketAddressSupplier { /** * Set the id prefix of the preferred node .
* @ param preferredNodeIdPrefix the id prefix of the preferred node */
public void setPreferredNodeIdPrefix ( String preferredNodeIdPrefix ) { } } | LettuceAssert . notNull ( preferredNodeIdPrefix , "preferredNodeIdPrefix must not be null" ) ; boolean resetRoundRobin = false ; if ( this . preferredNodeIdPrefix == null || ! preferredNodeIdPrefix . equals ( this . preferredNodeIdPrefix ) ) { resetRoundRobin = true ; } this . preferredNodeIdPrefix = preferredNodeIdPrefix ; if ( resetRoundRobin ) { resetRoundRobin ( preferredNodeIdPrefix ) ; } |
public class JavaModelUtils { /** * The Java APT throws an internal exception { code com . sun . tools . javac . code . Symbol $ CompletionFailure } if a class is missing from the classpath and { @ link Element # getKind ( ) } is called . This method
* handles exceptions when calling the getKind ( ) method to avoid this scenario and should be used instead of { @ link Element # getKind ( ) } .
* @ param element The element
* @ return The kind if it is resolvable */
public static Optional < ElementKind > resolveKind ( Element element ) { } } | if ( element != null ) { try { final ElementKind kind = element . getKind ( ) ; return Optional . of ( kind ) ; } catch ( Exception e ) { // ignore and fall through to empty
} } return Optional . empty ( ) ; |
public class ElemTemplateElement { /** * Send endPrefixMapping events to the result tree handler
* for all declared prefix mappings in the stylesheet .
* @ param transformer non - null reference to the the current transform - time state .
* @ param ignorePrefix string prefix to not endPrefixMapping
* @ throws TransformerException */
void unexecuteNSDecls ( TransformerImpl transformer , String ignorePrefix ) throws TransformerException { } } | try { if ( null != m_prefixTable ) { SerializationHandler rhandler = transformer . getResultTreeHandler ( ) ; int n = m_prefixTable . size ( ) ; for ( int i = 0 ; i < n ; i ++ ) { XMLNSDecl decl = ( XMLNSDecl ) m_prefixTable . get ( i ) ; if ( ! decl . getIsExcluded ( ) && ! ( null != ignorePrefix && decl . getPrefix ( ) . equals ( ignorePrefix ) ) ) { rhandler . endPrefixMapping ( decl . getPrefix ( ) ) ; } } } } catch ( org . xml . sax . SAXException se ) { throw new TransformerException ( se ) ; } |
public class Types { /** * Tries to " read " a { @ link TypeVariable } from an object instance , taking into account { @ link BindTypeVariable } and
* { @ link Typed } before falling back to basic type .
* @ param o
* @ param var
* @ param variablesMap prepopulated map for efficiency
* @ return Type resolved or { @ code null } */
public static Type resolveAt ( Object o , TypeVariable < ? > var , Map < TypeVariable < ? > , Type > variablesMap ) { } } | final Class < ? > rt = Validate . notNull ( o , "null target" ) . getClass ( ) ; Validate . notNull ( var , "no variable to read" ) ; final GenericDeclaration genericDeclaration = var . getGenericDeclaration ( ) ; Validate . isInstanceOf ( Class . class , genericDeclaration , "%s is not declared by a Class" , TypeUtils . toLongString ( var ) ) ; final Class < ? > declaring = ( Class < ? > ) genericDeclaration ; Validate . isInstanceOf ( declaring , o , "%s does not belong to %s" , TypeUtils . toLongString ( var ) , rt ) ; return unrollVariables ( variablesMap , var , o ) ; |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.