signature stringlengths 43 39.1k | implementation stringlengths 0 450k |
|---|---|
public class TypeCheck { /** * Checks whether class has overridden toString ( ) method . All objects has native toString ( )
* method but we ignore it as it is not useful so we need user - provided toString ( ) method . */
private boolean classHasToString ( ObjectType type ) { } } | Property toStringProperty = type . getOwnSlot ( "toString" ) ; if ( toStringProperty != null ) { return toStringProperty . getType ( ) . isFunctionType ( ) ; } ObjectType parent = type . getImplicitPrototype ( ) ; if ( parent != null && ! parent . isNativeObjectType ( ) ) { return classHasToString ( parent ) ; } return false ; |
public class StylesheetRoot { /** * Create the default rule if needed .
* @ throws TransformerException */
private void initDefaultRule ( ErrorListener errorListener ) throws TransformerException { } } | // Then manufacture a default
m_defaultRule = new ElemTemplate ( ) ; m_defaultRule . setStylesheet ( this ) ; XPath defMatch = new XPath ( "*" , this , this , XPath . MATCH , errorListener ) ; m_defaultRule . setMatch ( defMatch ) ; ElemApplyTemplates childrenElement = new ElemApplyTemplates ( ) ; childrenElement . setIsDefaultTemplate ( true ) ; childrenElement . setSelect ( m_selectDefault ) ; m_defaultRule . appendChild ( childrenElement ) ; m_startRule = m_defaultRule ; m_defaultTextRule = new ElemTemplate ( ) ; m_defaultTextRule . setStylesheet ( this ) ; defMatch = new XPath ( "text() | @*" , this , this , XPath . MATCH , errorListener ) ; m_defaultTextRule . setMatch ( defMatch ) ; ElemValueOf elemValueOf = new ElemValueOf ( ) ; m_defaultTextRule . appendChild ( elemValueOf ) ; XPath selectPattern = new XPath ( "." , this , this , XPath . SELECT , errorListener ) ; elemValueOf . setSelect ( selectPattern ) ; m_defaultRootRule = new ElemTemplate ( ) ; m_defaultRootRule . setStylesheet ( this ) ; defMatch = new XPath ( "/" , this , this , XPath . MATCH , errorListener ) ; m_defaultRootRule . setMatch ( defMatch ) ; childrenElement = new ElemApplyTemplates ( ) ; childrenElement . setIsDefaultTemplate ( true ) ; m_defaultRootRule . appendChild ( childrenElement ) ; childrenElement . setSelect ( m_selectDefault ) ; |
public class CommerceDiscountUsageEntryLocalServiceBaseImpl { /** * Returns the number of rows matching the dynamic query .
* @ param dynamicQuery the dynamic query
* @ param projection the projection to apply to the query
* @ return the number of rows matching the dynamic query */
@ Override public long dynamicQueryCount ( DynamicQuery dynamicQuery , Projection projection ) { } } | return commerceDiscountUsageEntryPersistence . countWithDynamicQuery ( dynamicQuery , projection ) ; |
public class AmazonSageMakerClient { /** * Gets a list of < a > TrainingJobSummary < / a > objects that describe the training jobs that a hyperparameter tuning job
* launched .
* @ param listTrainingJobsForHyperParameterTuningJobRequest
* @ return Result of the ListTrainingJobsForHyperParameterTuningJob operation returned by the service .
* @ throws ResourceNotFoundException
* Resource being access is not found .
* @ sample AmazonSageMaker . ListTrainingJobsForHyperParameterTuningJob
* @ see < a
* href = " http : / / docs . aws . amazon . com / goto / WebAPI / sagemaker - 2017-07-24 / ListTrainingJobsForHyperParameterTuningJob "
* target = " _ top " > AWS API Documentation < / a > */
@ Override public ListTrainingJobsForHyperParameterTuningJobResult listTrainingJobsForHyperParameterTuningJob ( ListTrainingJobsForHyperParameterTuningJobRequest request ) { } } | request = beforeClientExecution ( request ) ; return executeListTrainingJobsForHyperParameterTuningJob ( request ) ; |
public class LineParserBuffer { /** * private void doReceive ( ReceiveEvt evt )
* TODO : Handle partial receives .
* ByteArrayInputStream bis = new ByteArrayInputStream ( evt . getData ( ) , evt . getOffset ( ) , evt . getLength ( ) ) ;
* InputStreamReader isr = new InputStreamReader ( bis ) ;
* BufferedReader reader = new BufferedReader ( isr ) ;
* String line ;
* try
* while ( ( line = reader . readLine ( ) ) ! = null )
* log . info ( " The line = { } " , line ) ;
* ircDataProc . onReceiveLine ( line ) ;
* catch ( IOException e )
* TODO Auto - generated catch block
* throw new UnsupportedOperationException ( " OGTE TODO ! " , e ) ; */
private void doReceiveBuffer ( ReceiveEvt evt ) { } } | log . trace ( "BEFORE PUT: The buf={}" , buf ) ; buf . put ( evt . getData ( ) , evt . getOffset ( ) , evt . getLength ( ) ) ; log . trace ( "AFTER PUT: The buf={}" , buf ) ; buf . flip ( ) ; log . trace ( "AFTER FLIP: The buf={}" , buf ) ; boolean foundCrLf = false ; while ( buf . hasRemaining ( ) ) { foundCrLf = false ; boolean foundCr = false ; // TODO : Don ' t collect the bytes as we go , rather find the end index and get the
// the whole string at once . Will be more efficient than growing the stringbuilder .
StringBuilder sBuf = new StringBuilder ( ) ; log . trace ( "BEFORE MARK: The buf={}" , buf ) ; buf . mark ( ) ; log . trace ( "AFTER MARK: The buf={}" , buf ) ; while ( ! foundCrLf && buf . hasRemaining ( ) ) { byte b = buf . get ( ) ; if ( b == '\r' ) { foundCr = ! foundCr ; } else if ( b == '\n' ) { if ( foundCr ) { foundCrLf = true ; } else foundCr = false ; } else { foundCr = false ; } // This is intended to allow stray CRs or LFs to be added to the line .
// Can it ever happen ?
if ( ! foundCr ) sBuf . append ( ( char ) b ) ; // TODO Is this the right way to convert > 127 bytes ?
} if ( foundCrLf ) { log . trace ( "FOUND CRLF: The buf={}" , buf ) ; String line = sBuf . toString ( ) ; log . debug ( "The line={}" , line ) ; // ircDataProc . onReceiveLine ( line ) ;
try { receiver . onReceive ( new ReceiveEvt ( line . getBytes ( ) , evt . getSource ( ) ) ) ; } catch ( Exception e ) { // If there is an exception while processing the line , then log it and
// keep going in case there is more data in the buffer .
log . error ( "Trouble processing line=" + line , e ) ; } } } if ( foundCrLf ) { log . trace ( "BEFORE CLEAR: The buf={}" , buf ) ; buf . clear ( ) ; log . trace ( "AFTER CLEAR: The buf={}" , buf ) ; } else { log . trace ( "NOT FOUND CRLF: The buf={}" , buf ) ; buf . reset ( ) ; log . trace ( "AFTER RESET: The buf={}" , buf ) ; buf . compact ( ) ; log . trace ( "AFTER COMPACT: The buf={}" , buf ) ; // throw new UnsupportedOperationException ( " TODO " ) ;
} log . trace ( "ALL DONE: The buf={}" , buf ) ; |
public class ImgUtil { /** * 写出图像为JPG格式
* @ param image { @ link Image }
* @ param out 写出到的目标流
* @ throws IORuntimeException IO异常
* @ since 4.0.10 */
public static void writeJpg ( Image image , OutputStream out ) throws IORuntimeException { } } | write ( image , IMAGE_TYPE_JPG , out ) ; |
public class KrakenImpl { /** * Maps results to a method callback . */
public void map ( MethodRef method , String sql , Object [ ] args ) { } } | QueryBuilderKraken builder = QueryParserKraken . parse ( this , sql ) ; if ( builder . isTableLoaded ( ) ) { QueryKraken query = builder . build ( ) ; query . map ( method , args ) ; } else { String tableName = builder . getTableName ( ) ; _tableService . loadTable ( tableName , Result . of ( t -> builder . build ( ) . map ( method , args ) ) ) ; } |
public class JoinDomainRequest { /** * List of IPv4 addresses , NetBIOS names , or host names of your domain server . If you need to specify the port
* number include it after the colon ( “ : ” ) . For example , < code > mydc . mydomain . com : 389 < / code > .
* @ param domainControllers
* List of IPv4 addresses , NetBIOS names , or host names of your domain server . If you need to specify the
* port number include it after the colon ( “ : ” ) . For example , < code > mydc . mydomain . com : 389 < / code > . */
public void setDomainControllers ( java . util . Collection < String > domainControllers ) { } } | if ( domainControllers == null ) { this . domainControllers = null ; return ; } this . domainControllers = new com . amazonaws . internal . SdkInternalList < String > ( domainControllers ) ; |
public class FLACEncoder { /** * Attempt to Encode a certain number of samples . Encodes as close to count
* as possible .
* @ param count number of samples to attempt to encode . Actual number
* encoded may be greater or less if count does not end on a block boundary .
* @ param end true to finalize stream after encode , false otherwise . If set
* to true , and return value is greater than or equal to given count , no
* more encoding must be attempted until a new stream is began .
* @ return number of samples encoded . This may be greater or less than
* requested count if count does not end on a block boundary . This is NOT an
* error condition . If end was set " true " , and returned count is less than
* requested count , then end was NOT done , if you still wish to end stream ,
* call this again with end true and a count of of & le ; samplesAvailableToEncode ( )
* @ throws IOException if there was an error writing the results to file . */
public int encodeSamples ( int count , final boolean end ) throws IOException { } } | int encodedCount = 0 ; streamLock . lock ( ) ; try { checkForThreadErrors ( ) ; int channels = streamConfig . getChannelCount ( ) ; boolean encodeError = false ; while ( count > 0 && preparedRequests . size ( ) > 0 && ! encodeError ) { BlockEncodeRequest ber = preparedRequests . peek ( ) ; int encodedSamples = encodeRequest ( ber , channels ) ; if ( encodedSamples < 0 ) { // ERROR ! Return immediately . Do not add results to output .
System . err . println ( "FLACEncoder::encodeSamples : Error in encoding" ) ; encodeError = true ; break ; } preparedRequests . poll ( ) ; // pop top off now that we ' ve written .
encodedCount += encodedSamples ; count -= encodedSamples ; } // handle " end " setting
if ( end ) { if ( threadManager != null ) threadManager . stop ( ) ; // if ( end & & ! encodeError & & this . samplesAvailableToEncode ( ) > = count ) {
if ( count > 0 && unfilledRequest != null && unfilledRequest . count >= count ) { // handle remaining count
BlockEncodeRequest ber = unfilledRequest ; int encodedSamples = encodeRequest ( ber , channels ) ; if ( encodedSamples < 0 ) { // ERROR ! Return immediately . Do not add results to output .
System . err . println ( "FLACEncoder::encodeSamples : (end)Error in encoding" ) ; count = - 1 ; } else { count -= encodedSamples ; encodedCount += encodedSamples ; unfilledRequest = null ; } } if ( count <= 0 ) { // close stream if all requested were written .
closeFLACStream ( ) ; } } else if ( end == true ) { if ( DEBUG_LEV > 30 ) System . err . println ( "End set but not done. Error possible. " + "This can also happen if number of samples requested to " + "encode exeeds available samples" ) ; } } finally { streamLock . unlock ( ) ; } return encodedCount ; |
public class BatchDeleteImportDataRequestMarshaller { /** * Marshall the given parameter object . */
public void marshall ( BatchDeleteImportDataRequest batchDeleteImportDataRequest , ProtocolMarshaller protocolMarshaller ) { } } | if ( batchDeleteImportDataRequest == null ) { throw new SdkClientException ( "Invalid argument passed to marshall(...)" ) ; } try { protocolMarshaller . marshall ( batchDeleteImportDataRequest . getImportTaskIds ( ) , IMPORTTASKIDS_BINDING ) ; } catch ( Exception e ) { throw new SdkClientException ( "Unable to marshall request to JSON: " + e . getMessage ( ) , e ) ; } |
public class StringFormatter { /** * Access a localized string associated with key from the ResourceBundle ,
* likely the UI . properties file .
* @ param key to lookup in the ResourceBundle
* @ return localized String version of key argument , or key itself if
* something goes wrong . . . */
public String getLocalized ( String key ) { } } | if ( bundle != null ) { try { return bundle . getString ( key ) ; // String localized = bundle . getString ( key ) ;
// if ( ( localized ! = null ) & & ( localized . length ( ) > 0 ) ) {
// return localized ;
} catch ( Exception e ) { } } return key ; |
public class FeedItemServiceLocator { /** * For the given interface , get the stub implementation .
* If this service has no port for the given interface ,
* then ServiceException is thrown . */
public java . rmi . Remote getPort ( Class serviceEndpointInterface ) throws javax . xml . rpc . ServiceException { } } | try { if ( com . google . api . ads . adwords . axis . v201809 . cm . FeedItemServiceInterface . class . isAssignableFrom ( serviceEndpointInterface ) ) { com . google . api . ads . adwords . axis . v201809 . cm . FeedItemServiceSoapBindingStub _stub = new com . google . api . ads . adwords . axis . v201809 . cm . FeedItemServiceSoapBindingStub ( new java . net . URL ( FeedItemServiceInterfacePort_address ) , this ) ; _stub . setPortName ( getFeedItemServiceInterfacePortWSDDServiceName ( ) ) ; return _stub ; } } catch ( java . lang . Throwable t ) { throw new javax . xml . rpc . ServiceException ( t ) ; } throw new javax . xml . rpc . ServiceException ( "There is no stub implementation for the interface: " + ( serviceEndpointInterface == null ? "null" : serviceEndpointInterface . getName ( ) ) ) ; |
public class ChargingStationEventListener { /** * Updates the charging station ' s availability .
* @ param chargingStationId the charging station ' s id .
* @ param availability the charging station ' s new availability . */
private void updateChargingStationAvailability ( ChargingStationId chargingStationId , Availability availability ) { } } | ChargingStation chargingStation = repository . findOne ( chargingStationId . getId ( ) ) ; if ( chargingStation != null ) { chargingStation . setAvailability ( availability ) ; repository . createOrUpdate ( chargingStation ) ; } |
public class UserAction { /** * 删除一个或多个用户 */
public String remove ( ) { } } | Long [ ] userIds = getLongIds ( "user" ) ; User creator = userService . get ( SecurityUtils . getUsername ( ) ) ; List < User > toBeRemoved = securityHelper . getUserService ( ) . getUsers ( userIds ) ; StringBuilder sb = new StringBuilder ( ) ; User removed = null ; int success = 0 ; int expected = toBeRemoved . size ( ) ; try { for ( User one : toBeRemoved ) { removed = one ; // 不能删除自己
if ( ! one . getId ( ) . equals ( creator . getId ( ) ) ) { securityHelper . getUserService ( ) . removeUser ( creator , one ) ; success ++ ; } else { addFlashError ( "security.info.cannotRemoveSelf" ) ; expected -- ; } } } catch ( Exception e ) { sb . append ( ',' ) . append ( removed . getName ( ) ) ; } if ( sb . length ( ) > 0 ) { sb . deleteCharAt ( 0 ) ; addFlashMessage ( "security.info.userRemovePartial" , success , sb ) ; } else if ( expected == success && success > 0 ) { addFlashMessage ( "info.remove.success" ) ; } return redirect ( "search" ) ; |
public class GCMRegistrar { /** * Checks that the application manifest is properly configured .
* A proper configuration means :
* < ol >
* < li > It creates a custom permission called
* { @ code PACKAGE _ NAME . permission . C2D _ MESSAGE } .
* < li > It defines at least one { @ link BroadcastReceiver } with category
* { @ code PACKAGE _ NAME } .
* < li > The { @ link BroadcastReceiver } ( s ) uses the
* { @ value GCMConstants # PERMISSION _ GCM _ INTENTS } permission .
* < li > The { @ link BroadcastReceiver } ( s ) handles the 2 GCM intents
* ( { @ value GCMConstants # INTENT _ FROM _ GCM _ MESSAGE } and
* { @ value GCMConstants # INTENT _ FROM _ GCM _ REGISTRATION _ CALLBACK } ) .
* < / ol >
* . . . where { @ code PACKAGE _ NAME } is the application package .
* This method should be used during development time to verify that the
* manifest is properly set up , but it doesn ' t need to be called once the
* application is deployed to the users ' devices .
* @ param context application context .
* @ throws IllegalStateException if any of the conditions above is not met . */
public static void checkManifest ( Context context ) { } } | PackageManager packageManager = context . getPackageManager ( ) ; String packageName = context . getPackageName ( ) ; String permissionName = packageName + ".permission.C2D_MESSAGE" ; // check permission
try { packageManager . getPermissionInfo ( permissionName , PackageManager . GET_PERMISSIONS ) ; } catch ( NameNotFoundException e ) { throw new IllegalStateException ( "Application does not define permission " + permissionName ) ; } // check receivers
PackageInfo receiversInfo ; try { receiversInfo = packageManager . getPackageInfo ( packageName , PackageManager . GET_RECEIVERS ) ; } catch ( NameNotFoundException e ) { throw new IllegalStateException ( "Could not get receivers for package " + packageName ) ; } ActivityInfo [ ] receivers = receiversInfo . receivers ; if ( receivers == null || receivers . length == 0 ) { throw new IllegalStateException ( "No receiver for package " + packageName ) ; } if ( Log . isLoggable ( TAG , Log . VERBOSE ) ) { Log . v ( TAG , "number of receivers for " + packageName + ": " + receivers . length ) ; } Set < String > allowedReceivers = new HashSet < String > ( ) ; for ( ActivityInfo receiver : receivers ) { if ( GCMConstants . PERMISSION_GCM_INTENTS . equals ( receiver . permission ) ) { allowedReceivers . add ( receiver . name ) ; } } if ( allowedReceivers . isEmpty ( ) ) { throw new IllegalStateException ( "No receiver allowed to receive " + GCMConstants . PERMISSION_GCM_INTENTS ) ; } checkReceiver ( context , allowedReceivers , GCMConstants . INTENT_FROM_GCM_REGISTRATION_CALLBACK ) ; checkReceiver ( context , allowedReceivers , GCMConstants . INTENT_FROM_GCM_MESSAGE ) ; |
public class ModClusterContainer { /** * Register a new node .
* @ param config the node configuration
* @ param balancerConfig the balancer configuration
* @ param ioThread the associated I / O thread
* @ param bufferPool the buffer pool
* @ return whether the node could be created or not */
public synchronized boolean addNode ( final NodeConfig config , final Balancer . BalancerBuilder balancerConfig , final XnioIoThread ioThread , final ByteBufferPool bufferPool ) { } } | final String jvmRoute = config . getJvmRoute ( ) ; final Node existing = nodes . get ( jvmRoute ) ; if ( existing != null ) { if ( config . getConnectionURI ( ) . equals ( existing . getNodeConfig ( ) . getConnectionURI ( ) ) ) { // TODO better check if they are the same
existing . resetState ( ) ; return true ; } else { existing . markRemoved ( ) ; removeNode ( existing ) ; if ( ! existing . isInErrorState ( ) ) { return false ; // replies with MNODERM error
} } } final String balancerRef = config . getBalancer ( ) ; Balancer balancer = balancers . get ( balancerRef ) ; if ( balancer != null ) { UndertowLogger . ROOT_LOGGER . debugf ( "Balancer %s already exists, replacing" , balancerRef ) ; } balancer = balancerConfig . build ( ) ; balancers . put ( balancerRef , balancer ) ; final Node node = new Node ( config , balancer , ioThread , bufferPool , this ) ; nodes . put ( jvmRoute , node ) ; // Schedule the health check
scheduleHealthCheck ( node , ioThread ) ; // Reset the load factor periodically
if ( updateLoadTask . cancelKey == null ) { updateLoadTask . cancelKey = ioThread . executeAtInterval ( updateLoadTask , modCluster . getHealthCheckInterval ( ) , TimeUnit . MILLISECONDS ) ; } // Remove from the failover groups
failoverDomains . remove ( node . getJvmRoute ( ) ) ; UndertowLogger . ROOT_LOGGER . registeringNode ( jvmRoute , config . getConnectionURI ( ) ) ; return true ; |
public class DiscoverInputSchemaResult { /** * Stream data that was modified by the processor specified in the < code > InputProcessingConfiguration < / code >
* parameter .
* @ param processedInputRecords
* Stream data that was modified by the processor specified in the < code > InputProcessingConfiguration < / code >
* parameter . */
public void setProcessedInputRecords ( java . util . Collection < String > processedInputRecords ) { } } | if ( processedInputRecords == null ) { this . processedInputRecords = null ; return ; } this . processedInputRecords = new java . util . ArrayList < String > ( processedInputRecords ) ; |
public class ZipUtil { /** * 对文件或文件目录进行压缩
* @ param zipFile 生成的Zip文件 , 包括文件名 。 注意 : zipPath不能是srcPath路径下的子文件夹
* @ param charset 编码
* @ param withSrcDir 是否包含被打包目录 , 只针对压缩目录有效 。 若为false , 则只压缩目录下的文件或目录 , 为true则将本目录也压缩
* @ param srcFiles 要压缩的源文件或目录 。 如果压缩一个文件 , 则为该文件的全路径 ; 如果压缩一个目录 , 则为该目录的顶层目录路径
* @ return 压缩文件
* @ throws UtilException IO异常 */
public static File zip ( File zipFile , Charset charset , boolean withSrcDir , File ... srcFiles ) throws UtilException { } } | validateFiles ( zipFile , srcFiles ) ; try ( ZipOutputStream out = getZipOutputStream ( zipFile , charset ) ) { String srcRootDir ; for ( File srcFile : srcFiles ) { if ( null == srcFile ) { continue ; } // 如果只是压缩一个文件 , 则需要截取该文件的父目录
srcRootDir = srcFile . getCanonicalPath ( ) ; if ( srcFile . isFile ( ) || withSrcDir ) { // 若是文件 , 则将父目录完整路径都截取掉 ; 若设置包含目录 , 则将上级目录全部截取掉 , 保留本目录名
srcRootDir = srcFile . getCanonicalFile ( ) . getParentFile ( ) . getCanonicalPath ( ) ; } // 调用递归压缩方法进行目录或文件压缩
zip ( srcFile , srcRootDir , out ) ; out . flush ( ) ; } } catch ( IOException e ) { throw new UtilException ( e ) ; } return zipFile ; |
public class SecureLogging { /** * Main method to initialize the combined { @ link Marker } s provided by this class . */
private static void initMarkers ( ) { } } | if ( initialized ) return ; Class < ? > cExtClass = findExtClass ( EXT_CLASS ) ; if ( cExtClass . isAssignableFrom ( String . class ) ) { createDefaultMarkers ( ) ; } else { createMultiMarkers ( cExtClass ) ; } if ( ! initialized ) LOG . warn ( "SecureLogging Markers could not be initialized!" ) ; else LOG . debug ( "SecureLogging Markers created: '{}', ..." , markerSecurSuccConfid . getName ( ) ) ; return ; |
public class CapabilityResolutionContext { /** * Attaches an arbitrary object to this context only if the object was not already attached . If a value has already
* been attached with the key provided , the current value associated with the key is returned .
* @ param key they attachment key used to ensure uniqueness and used for retrieval of the value .
* @ param value the value to store .
* @ param < V > the value type of the attachment .
* @ return the previous value associated with the key or { @ code null } if there was no previous value . */
public < V > V attachIfAbsent ( final AttachmentKey < V > key , final V value ) { } } | assert key != null ; return key . cast ( contextAttachments . putIfAbsent ( key , value ) ) ; |
public class Neo4JVertex { /** * { @ inheritDoc } */
@ Override public void remove ( ) { } } | // transaction should be ready for io operations
graph . tx ( ) . readWrite ( ) ; // remove all edges
outEdges . forEach ( edge -> session . removeEdge ( edge , false ) ) ; // remove vertex on session
session . removeVertex ( this ) ; |
public class Caster { /** * cast a Object to a Byte Object ( reference type )
* @ param o Object to cast
* @ param defaultValue
* @ return casted Byte Object */
public static Short toShort ( Object o , Short defaultValue ) { } } | if ( o instanceof Short ) return ( Short ) o ; if ( defaultValue != null ) return Short . valueOf ( toShortValue ( o , defaultValue . shortValue ( ) ) ) ; short res = toShortValue ( o , Short . MIN_VALUE ) ; if ( res == Short . MIN_VALUE ) return defaultValue ; return Short . valueOf ( res ) ; |
public class CmAgent { /** * Check returns Error Codes , so that Scripts can know what to do
* 0 - Check Complete , nothing to do
* 1 - General Error
* 2 - Error for specific Artifact - read check . msg
* 10 - Certificate Updated - check . msg is email content
* @ param trans
* @ param aafcon
* @ param cmds
* @ return
* @ throws Exception */
private static int check ( Trans trans , AAFCon < ? > aafcon , Deque < String > cmds ) throws Exception { } } | int exitCode = 1 ; String mechID = mechID ( cmds ) ; String machine = machine ( cmds ) ; TimeTaken tt = trans . start ( "Check Certificate" , Env . REMOTE ) ; try { Future < Artifacts > acf = aafcon . client ( CM_VER ) . read ( "/cert/artifacts/" + mechID + '/' + machine , artifactsDF ) ; if ( acf . get ( TIMEOUT ) ) { // Have to wait for JDK 1.7 source . . .
// switch ( artifact . getType ( ) ) {
if ( acf . value . getArtifact ( ) == null || acf . value . getArtifact ( ) . isEmpty ( ) ) { AAFSSO . cons . printf ( "No Artifacts found for %s on %s" , mechID , machine ) ; } else { String id = aafcon . defID ( ) ; GregorianCalendar now = new GregorianCalendar ( ) ; for ( Artifact a : acf . value . getArtifact ( ) ) { if ( id . equals ( a . getMechid ( ) ) ) { File dir = new File ( a . getDir ( ) ) ; Properties props = new Properties ( ) ; FileInputStream fis = new FileInputStream ( new File ( dir , a . getAppName ( ) + ".props" ) ) ; try { props . load ( fis ) ; } finally { fis . close ( ) ; } String prop ; File f ; if ( ( prop = props . getProperty ( Config . CADI_KEYFILE ) ) == null || ! ( f = new File ( prop ) ) . exists ( ) ) { trans . error ( ) . printf ( "Keyfile must exist to check Certificates for %s on %s" , a . getMechid ( ) , a . getMachine ( ) ) ; } else { String ksf = props . getProperty ( Config . CADI_KEYSTORE ) ; String ksps = props . getProperty ( Config . CADI_KEYSTORE_PASSWORD ) ; if ( ksf == null || ksps == null ) { trans . error ( ) . printf ( "Properties %s and %s must exist to check Certificates for %s on %s" , Config . CADI_KEYSTORE , Config . CADI_KEYSTORE_PASSWORD , a . getMechid ( ) , a . getMachine ( ) ) ; } else { KeyStore ks = KeyStore . getInstance ( "JKS" ) ; Symm symm = Symm . obtain ( f ) ; fis = new FileInputStream ( ksf ) ; try { ks . load ( fis , symm . depass ( ksps ) . toCharArray ( ) ) ; } finally { fis . close ( ) ; } X509Certificate cert = ( X509Certificate ) ks . getCertificate ( mechID ) ; String msg = null ; if ( cert == null ) { msg = String . format ( "X509Certificate does not exist for %s on %s in %s" , a . getMechid ( ) , a . getMachine ( ) , ksf ) ; trans . error ( ) . log ( msg ) ; exitCode = 2 ; } else { GregorianCalendar renew = new GregorianCalendar ( ) ; renew . setTime ( cert . getNotAfter ( ) ) ; renew . add ( GregorianCalendar . DAY_OF_MONTH , - 1 * a . getRenewDays ( ) ) ; if ( renew . after ( now ) ) { msg = String . format ( "X509Certificate for %s on %s has been checked on %s. It expires on %s; it will not be renewed until %s.\n" , a . getMechid ( ) , a . getMachine ( ) , Chrono . dateOnlyStamp ( now ) , cert . getNotAfter ( ) , Chrono . dateOnlyStamp ( renew ) ) ; trans . info ( ) . log ( msg ) ; exitCode = 0 ; // OK
} else { trans . info ( ) . printf ( "X509Certificate for %s on %s expiration, %s, needs Renewal.\n" , a . getMechid ( ) , a . getMachine ( ) , cert . getNotAfter ( ) ) ; cmds . offerLast ( mechID ) ; cmds . offerLast ( machine ) ; if ( placeCerts ( trans , aafcon , cmds ) ) { msg = String . format ( "X509Certificate for %s on %s has been renewed. Ensure services using are refreshed.\n" , a . getMechid ( ) , a . getMachine ( ) ) ; exitCode = 10 ; // Refreshed
} else { msg = String . format ( "X509Certificate for %s on %s attempted renewal, but failed. Immediate Investigation is required!\n" , a . getMechid ( ) , a . getMachine ( ) ) ; exitCode = 1 ; // Error Renewing
} } } if ( msg != null ) { FileOutputStream fos = new FileOutputStream ( a . getDir ( ) + '/' + a . getAppName ( ) + ".msg" ) ; try { fos . write ( msg . getBytes ( ) ) ; } finally { fos . close ( ) ; } } } } } } } } else { trans . error ( ) . log ( errMsg . toMsg ( acf ) ) ; exitCode = 1 ; } } finally { tt . done ( ) ; } return exitCode ; |
public class BlocksMap { /** * Check if the replica at the given datanode exists in map */
boolean contains ( Block block , DatanodeDescriptor datanode ) { } } | BlockInfo info = blocks . get ( block ) ; if ( info == null ) return false ; if ( - 1 == info . findDatanode ( datanode ) ) return false ; return true ; |
public class DefaultValidationResultsModel { /** * Add a validationResultsModel as a child to this one . Attach listeners and
* if it already has messages , fire events .
* @ param validationResultsModel */
public void add ( ValidationResultsModel validationResultsModel ) { } } | if ( children . add ( validationResultsModel ) ) { validationResultsModel . addValidationListener ( this ) ; validationResultsModel . addPropertyChangeListener ( HAS_ERRORS_PROPERTY , this ) ; validationResultsModel . addPropertyChangeListener ( HAS_WARNINGS_PROPERTY , this ) ; validationResultsModel . addPropertyChangeListener ( HAS_INFO_PROPERTY , this ) ; if ( ( validationResultsModel . getMessageCount ( ) > 0 ) ) fireChangedEvents ( ) ; } |
public class FileEncryptor { /** * Encrypt the contents of an input stream and write the encrypted data to
* the output stream .
* @ param clearInputStream
* Input stream containing the data to be encrypted .
* @ param encryptedOutputStream
* Output stream which the encrypted data will be written to .
* @ throws IOException
* @ throws MissingParameterException */
public void encryptStream ( InputStream clearInputStream , OutputStream encryptedOutputStream ) throws IOException , MissingParameterException { } } | byte [ ] clearBytes = IOUtils . toByteArray ( clearInputStream ) ; byte [ ] cipherBytes = encryptionProvider . encrypt ( clearBytes ) ; // encryptedOutputStream = new ByteArrayOutputStream ( 1000 ) ;
encryptedOutputStream . write ( cipherBytes ) ; encryptedOutputStream . flush ( ) ; encryptedOutputStream . close ( ) ; |
public class TcpListener { /** * / * ( non - Javadoc )
* @ see net . timewalker . ffmq4 . listeners . AbstractListener # start ( ) */
@ Override public synchronized void start ( ) throws JMSException { } } | if ( started ) return ; log . info ( "Starting listener [" + getName ( ) + "]" ) ; stopRequired = false ; initServerSocket ( ) ; listenerThread = new Thread ( this , "FFMQ-TCP-Server-" + serverSocket . getLocalPort ( ) ) ; listenerThread . start ( ) ; started = true ; |
public class SDMath { /** * Boolean AND operation : elementwise ( x ! = 0 ) & & ( y ! = 0 ) < br >
* If x and y arrays have equal shape , the output shape is the same as these inputs . < br >
* Note : supports broadcasting if x and y have different shapes and are broadcastable . < br >
* Returns an array with values 1 where condition is satisfied , or value 0 otherwise .
* @ param x Input 1
* @ param y Input 2
* @ return Output SDVariable with values 0 and 1 based on where the condition is satisfied */
public SDVariable and ( SDVariable x , SDVariable y ) { } } | return and ( null , x , y ) ; |
public class LockManager { /** * Dump internal state of lock manager . */
public void dump ( ) { } } | if ( ! tc . isDumpEnabled ( ) ) { return ; } Enumeration vEnum = lockTable . keys ( ) ; Tr . dump ( tc , "-- Lock Manager Dump --" ) ; while ( vEnum . hasMoreElements ( ) ) { Object key = vEnum . nextElement ( ) ; Tr . dump ( tc , "lock table entry" , new Object [ ] { key , lockTable . get ( key ) } ) ; } |
public class CalendarThinTableModel { /** * Constructor . */
public void init ( FieldTable table , String strStartDateTimeField , String strEndDateTimeField , String strDescriptionField , String strStatusField ) { } } | super . init ( table ) ; m_strStartDateTimeField = strStartDateTimeField ; m_strEndDateTimeField = strEndDateTimeField ; m_strDescriptionField = strDescriptionField ; m_strStatusField = strStatusField ; |
public class MicroHessianOutput { /** * Writes a byte array to the stream .
* The array will be written with the following syntax :
* < code > < pre >
* B b16 b18 bytes
* < / pre > < / code >
* If the value is null , it will be written as
* < code > < pre >
* < / pre > < / code >
* @ param value the string value to write . */
public void writeBytes ( byte [ ] buffer , int offset , int length ) throws IOException { } } | if ( buffer == null ) { os . write ( 'N' ) ; } else { os . write ( 'B' ) ; os . write ( length << 8 ) ; os . write ( length ) ; os . write ( buffer , offset , length ) ; } |
public class RemoteConnection { /** * / * ( non - Javadoc )
* @ see net . timewalker . ffmq4 . common . connection . AbstractConnection # deleteTemporaryQueue ( java . lang . String ) */
@ Override public final void deleteTemporaryQueue ( String queueName ) throws JMSException { } } | DeleteTemporaryQueueQuery query = new DeleteTemporaryQueueQuery ( ) ; query . setQueueName ( queueName ) ; transportEndpoint . blockingRequest ( query ) ; |
public class JSONConverter { /** * serialize Serializable class
* @ param serializable
* @ param sb
* @ param serializeQueryByColumns
* @ param done
* @ throws ConverterException */
private void _serializeClass ( PageContext pc , Set test , Class clazz , Object obj , StringBuilder sb , boolean serializeQueryByColumns , Set < Object > done ) throws ConverterException { } } | Struct sct = new StructImpl ( Struct . TYPE_LINKED ) ; if ( test == null ) test = new HashSet ( ) ; // Fields
Field [ ] fields = clazz . getFields ( ) ; Field field ; for ( int i = 0 ; i < fields . length ; i ++ ) { field = fields [ i ] ; if ( obj != null || ( field . getModifiers ( ) & Modifier . STATIC ) > 0 ) try { sct . setEL ( field . getName ( ) , testRecusrion ( test , field . get ( obj ) ) ) ; } catch ( Exception e ) { SystemOut . printDate ( e ) ; } } if ( obj != null ) { // setters
Method [ ] setters = Reflector . getSetters ( clazz ) ; for ( int i = 0 ; i < setters . length ; i ++ ) { sct . setEL ( setters [ i ] . getName ( ) . substring ( 3 ) , NULL ) ; } // getters
Method [ ] getters = Reflector . getGetters ( clazz ) ; for ( int i = 0 ; i < getters . length ; i ++ ) { try { sct . setEL ( getters [ i ] . getName ( ) . substring ( 3 ) , testRecusrion ( test , getters [ i ] . invoke ( obj , ArrayUtil . OBJECT_EMPTY ) ) ) ; } catch ( Exception e ) { } } } test . add ( clazz ) ; _serializeStruct ( pc , test , sct , sb , serializeQueryByColumns , true , done ) ; |
public class EasyBind { /** * Sync the content of the { @ code target } list with the { @ code source } list .
* @ return a subscription that can be used to stop syncing the lists . */
public static < T > Subscription listBind ( List < ? super T > target , ObservableList < ? extends T > source ) { } } | target . clear ( ) ; target . addAll ( source ) ; ListChangeListener < ? super T > listener = change -> { while ( change . next ( ) ) { int from = change . getFrom ( ) ; int to = change . getTo ( ) ; if ( change . wasPermutated ( ) ) { target . subList ( from , to ) . clear ( ) ; target . addAll ( from , source . subList ( from , to ) ) ; } else { target . subList ( from , from + change . getRemovedSize ( ) ) . clear ( ) ; target . addAll ( from , source . subList ( from , from + change . getAddedSize ( ) ) ) ; } } } ; source . addListener ( listener ) ; return ( ) -> source . removeListener ( listener ) ; |
public class TomcatBoot { public void close ( ) { } } | if ( server == null ) { throw new IllegalStateException ( "server has not been started." ) ; } try { server . stop ( ) ; } catch ( Exception e ) { throw new IllegalStateException ( "Failed to stop the Tomcat." , e ) ; } |
public class Security { /** * Encrypt a string value .
* @ param value Value to encrypt .
* @ return Encrypted value . */
protected static String encrypt ( String value , String cipherKey ) { } } | String [ ] cipher = CipherRegistry . getCipher ( cipherKey ) ; int associatorIndex = randomIndex ( cipher . length ) ; int identifierIndex ; do { identifierIndex = randomIndex ( cipher . length ) ; } while ( associatorIndex == identifierIndex ) ; return ( ( char ) ( associatorIndex + 32 ) ) + StrUtil . xlate ( value , cipher [ associatorIndex ] , cipher [ identifierIndex ] ) + ( ( char ) ( identifierIndex + 32 ) ) ; |
public class WebConfigParamUtils { /** * Gets the int init parameter value from the specified context . If the parameter was not specified , the default
* value is used instead .
* @ param context
* the application ' s external context
* @ param names
* the init parameter ' s names
* @ param defaultValue
* the default value to return in case the parameter was not set
* @ return the init parameter value as a int
* @ throws NullPointerException
* if context or name is < code > null < / code > */
public static int getIntegerInitParameter ( ExternalContext context , String [ ] names , int defaultValue ) { } } | if ( names == null ) { throw new NullPointerException ( ) ; } String param = null ; for ( String name : names ) { if ( name == null ) { throw new NullPointerException ( ) ; } param = getStringInitParameter ( context , name ) ; if ( param != null ) { break ; } } if ( param == null ) { return defaultValue ; } else { return Integer . parseInt ( param . toLowerCase ( ) ) ; } |
public class SocketWrapperBar { /** * Returns the client certificate . */
@ Override public X509Certificate getClientCertificate ( ) throws CertificateException { } } | X509Certificate [ ] certs = getClientCertificates ( ) ; if ( certs == null || certs . length == 0 ) return null ; else return certs [ 0 ] ; |
public class StopProcessApplicationsStep { /** * < p > Stops a process application . Exceptions are logged but not re - thrown ) .
* @ param processApplicationReference */
protected void stopProcessApplication ( ProcessApplicationReference processApplicationReference ) { } } | try { // unless the user has overridden the stop behavior ,
// this causes the process application to remove its services
// ( triggers nested undeployment operation )
ProcessApplicationInterface processApplication = processApplicationReference . getProcessApplication ( ) ; processApplication . undeploy ( ) ; } catch ( Throwable t ) { LOG . exceptionWhileStopping ( "Process Application" , processApplicationReference . getName ( ) , t ) ; } |
public class X509CRLEntryImpl { /** * Encodes the revoked certificate to an output stream .
* @ param outStrm an output stream to which the encoded revoked
* certificate is written .
* @ exception CRLException on encoding errors . */
public void encode ( DerOutputStream outStrm ) throws CRLException { } } | try { if ( revokedCert == null ) { DerOutputStream tmp = new DerOutputStream ( ) ; // sequence { serialNumber , revocationDate , extensions }
serialNumber . encode ( tmp ) ; if ( revocationDate . getTime ( ) < YR_2050 ) { tmp . putUTCTime ( revocationDate ) ; } else { tmp . putGeneralizedTime ( revocationDate ) ; } if ( extensions != null ) extensions . encode ( tmp , isExplicit ) ; DerOutputStream seq = new DerOutputStream ( ) ; seq . write ( DerValue . tag_Sequence , tmp ) ; revokedCert = seq . toByteArray ( ) ; } outStrm . write ( revokedCert ) ; } catch ( IOException e ) { throw new CRLException ( "Encoding error: " + e . toString ( ) ) ; } |
public class CmsGalleryField { /** * On text box blur . < p >
* @ param event the event */
@ UiHandler ( "m_textbox" ) void onBlur ( BlurEvent event ) { } } | setFaded ( ( m_textbox . getValue ( ) . length ( ) * 6.88 ) > m_textbox . getOffsetWidth ( ) ) ; setTitle ( m_textbox . getValue ( ) ) ; |
public class BatchingAuditTrail { /** * returns immediately after queueing the log message
* @ param e
* the AuditTrailEvent to be logged
* @ param cb
* callback called when logging succeeded or failed . */
public void asynchLog ( final AuditTrailEvent e , final AuditTrailCallback cb ) { } } | CommandCallback < BatchInsertIntoAutoTrail . Command > callback = new CommandCallback < BatchInsertIntoAutoTrail . Command > ( ) { @ Override public void commandCompleted ( ) { cb . done ( ) ; } @ Override public void unhandledException ( Exception e ) { cb . error ( e ) ; } } ; doLog ( e , false , callback ) ; |
public class RepositoryConfiguration { /** * Read the supplied stream containing a JSON file , and parse into a { @ link RepositoryConfiguration } .
* @ param stream the file ; may not be null
* @ param name the name of the resource ; may not be null
* @ return the parsed repository configuration ; never null
* @ throws ParsingException if the content could not be parsed as a valid JSON document
* @ throws FileNotFoundException if the file could not be found */
public static RepositoryConfiguration read ( InputStream stream , String name ) throws ParsingException , FileNotFoundException { } } | CheckArg . isNotNull ( stream , "stream" ) ; CheckArg . isNotNull ( name , "name" ) ; Document doc = Json . read ( stream ) ; return new RepositoryConfiguration ( doc , withoutExtension ( name ) ) ; |
public class XmlSchemaParser { /** * Helper function that throws an exception when the attribute is not set .
* @ param elementNode that should have the attribute
* @ param attrName that is to be looked up
* @ return value of the attribute
* @ throws IllegalArgumentException if the attribute is not present */
public static String getAttributeValue ( final Node elementNode , final String attrName ) { } } | final Node attrNode = elementNode . getAttributes ( ) . getNamedItemNS ( null , attrName ) ; if ( attrNode == null || "" . equals ( attrNode . getNodeValue ( ) ) ) { throw new IllegalStateException ( "Element '" + elementNode . getNodeName ( ) + "' has empty or missing attribute: " + attrName ) ; } return attrNode . getNodeValue ( ) ; |
public class SockJsFrame { /** * < p > messageFrame . < / p >
* @ param codec a { @ link ameba . websocket . sockjs . frame . SockJsMessageCodec } object .
* @ param messages a { @ link java . lang . String } object .
* @ return a { @ link ameba . websocket . sockjs . frame . SockJsFrame } object . */
public static SockJsFrame messageFrame ( SockJsMessageCodec codec , String ... messages ) { } } | String encoded = codec . encode ( messages ) ; return new SockJsFrame ( encoded ) ; |
public class WaveBase { /** * { @ inheritDoc } */
@ Override public Wave status ( final Status status ) { } } | synchronized ( this ) { if ( this . statusProperty . get ( ) == status ) { throw new CoreRuntimeException ( "The status " + status . toString ( ) + " has been already set for this wave " + toString ( ) ) ; } else { this . statusProperty . set ( status ) ; fireStatusChanged ( ) ; } } return this ; |
public class SychronizeFXWebsocketServer { /** * Pass { @ link OnClose } events of the Websocket API to this method to handle the event of a disconnected client .
* @ param session The client that has disconnected .
* @ throws IllegalArgumentException If the client passed as argument isn ' t registered in any channel . */
public void onClose ( final Session session ) { } } | final Optional < SynchronizeFXWebsocketChannel > channel ; synchronized ( channels ) { channel = getChannel ( session ) ; clients . remove ( session ) ; } // Maybe this is the response for a server side close .
if ( channel . isPresent ( ) ) { channel . get ( ) . connectionCloses ( session ) ; } |
public class RuleClassifier { /** * This function creates a rule */
public void createRule ( Instance inst ) { } } | int remainder = ( int ) Double . MAX_VALUE ; int numInstanciaObservers = ( int ) this . observedClassDistribution . sumOfValues ( ) ; if ( numInstanciaObservers != 0 && this . gracePeriodOption . getValue ( ) != 0 ) { remainder = ( numInstanciaObservers ) % ( this . gracePeriodOption . getValue ( ) ) ; } if ( remainder == 0 ) { this . saveBestValGlobalEntropy = new ArrayList < ArrayList < Double > > ( ) ; this . saveBestGlobalEntropy = new DoubleVector ( ) ; this . saveTheBest = new ArrayList < Double > ( ) ; this . minEntropyTemp = Double . MAX_VALUE ; this . minEntropyNominalAttrib = Double . MAX_VALUE ; theBestAttributes ( inst , this . attributeObservers ) ; boolean HB = checkBestAttrib ( numInstanciaObservers , this . attributeObservers , this . observedClassDistribution ) ; if ( HB == true ) { // System . out . print ( " this . saveTheBest " + this . saveTheBest + " \ n " ) ;
double attributeValue = this . saveTheBest . get ( 3 ) ; double symbol = this . saveTheBest . get ( 2 ) ; // = , < = , > : ( 0.0 , - 1.0 , 1.0 ) .
double value = this . saveTheBest . get ( 0 ) ; // Value of the attribute
this . pred = new Predicates ( attributeValue , symbol , value ) ; RuleClassification Rl = new RuleClassification ( ) ; // Create RuleClassification .
Rl . predicateSet . add ( pred ) ; this . ruleSet . add ( Rl ) ; if ( Rl . predicateSet . get ( 0 ) . getSymbol ( ) == - 1.0 || Rl . predicateSet . get ( 0 ) . getSymbol ( ) == 1.0 ) { double posClassDouble = this . saveTheBest . get ( 4 ) ; this . ruleClassIndex . setValue ( this . ruleSet . size ( ) - 1 , posClassDouble ) ; } else { this . ruleClassIndex . setValue ( ruleSet . size ( ) - 1 , 0.0 ) ; } this . observedClassDistribution = new DoubleVector ( ) ; this . attributeObservers = new AutoExpandVector < AttributeClassObserver > ( ) ; this . attributeObserversGauss = new AutoExpandVector < AttributeClassObserver > ( ) ; } } |
public class Cursor { /** * Store by cursor .
* This function stores key / data pairs into the database .
* @ param key key to store
* @ param val data to store
* @ param op options for this operation
* @ return true if the value was put , false if MDB _ NOOVERWRITE or
* MDB _ NODUPDATA were set and the key / value existed already . */
public boolean put ( final T key , final T val , final PutFlags ... op ) { } } | if ( SHOULD_CHECK ) { requireNonNull ( key ) ; requireNonNull ( val ) ; checkNotClosed ( ) ; txn . checkReady ( ) ; txn . checkWritesAllowed ( ) ; } kv . keyIn ( key ) ; kv . valIn ( val ) ; final int mask = mask ( op ) ; final int rc = LIB . mdb_cursor_put ( ptrCursor , kv . pointerKey ( ) , kv . pointerVal ( ) , mask ) ; if ( rc == MDB_KEYEXIST ) { if ( isSet ( mask , MDB_NOOVERWRITE ) ) { kv . valOut ( ) ; // marked as in , out in LMDB C docs
} else if ( ! isSet ( mask , MDB_NODUPDATA ) ) { checkRc ( rc ) ; } return false ; } checkRc ( rc ) ; return true ; |
public class S { /** * Alias of { @ link # isEqual ( String , String , int ) }
* @ param s1
* @ param s2
* @ param modifier
* @ return true if o1 ' s str equals o2 ' s str */
public static boolean eq ( String s1 , String s2 , int modifier ) { } } | return isEqual ( s1 , s2 , modifier ) ; |
public class ComputeNodeDisableSchedulingHeaders { /** * Set the time at which the resource was last modified .
* @ param lastModified the lastModified value to set
* @ return the ComputeNodeDisableSchedulingHeaders object itself . */
public ComputeNodeDisableSchedulingHeaders withLastModified ( DateTime lastModified ) { } } | if ( lastModified == null ) { this . lastModified = null ; } else { this . lastModified = new DateTimeRfc1123 ( lastModified ) ; } return this ; |
public class StartupSettings { /** * Parse the settings for the gossip service from a JSON file .
* @ param jsonFile
* The file object which refers to the JSON config file .
* @ return The StartupSettings object with the settings from the config file .
* @ throws JSONException
* Thrown when the file is not well - formed JSON .
* @ throws FileNotFoundException
* Thrown when the file cannot be found .
* @ throws IOException
* Thrown when reading the file gives problems . */
public static StartupSettings fromJSONFile ( File jsonFile ) throws JSONException , FileNotFoundException , IOException { } } | // Read the file to a String .
StringBuffer buffer = new StringBuffer ( ) ; try ( BufferedReader br = new BufferedReader ( new FileReader ( jsonFile ) ) ) { String line ; while ( ( line = br . readLine ( ) ) != null ) { buffer . append ( line . trim ( ) ) ; } } JSONObject jsonObject = new JSONArray ( buffer . toString ( ) ) . getJSONObject ( 0 ) ; int port = jsonObject . getInt ( "port" ) ; String id = jsonObject . getString ( "id" ) ; int gossipInterval = jsonObject . getInt ( "gossip_interval" ) ; int cleanupInterval = jsonObject . getInt ( "cleanup_interval" ) ; String cluster = jsonObject . getString ( "cluster" ) ; if ( cluster == null ) { throw new IllegalArgumentException ( "cluster was null. It is required" ) ; } StartupSettings settings = new StartupSettings ( id , port , new GossipSettings ( gossipInterval , cleanupInterval ) , cluster ) ; // Now iterate over the members from the config file and add them to the settings .
String configMembersDetails = "Config-members [" ; JSONArray membersJSON = jsonObject . getJSONArray ( "members" ) ; for ( int i = 0 ; i < membersJSON . length ( ) ; i ++ ) { JSONObject memberJSON = membersJSON . getJSONObject ( i ) ; RemoteGossipMember member = new RemoteGossipMember ( memberJSON . getString ( "cluster" ) , memberJSON . getString ( "host" ) , memberJSON . getInt ( "port" ) , "" ) ; settings . addGossipMember ( member ) ; configMembersDetails += member . getAddress ( ) ; if ( i < ( membersJSON . length ( ) - 1 ) ) configMembersDetails += ", " ; } log . info ( configMembersDetails + "]" ) ; // Return the created settings object .
return settings ; |
public class AbstractHibernateCriteriaBuilder { /** * Applys a " in " contrain on the specified property
* @ param propertyName The property name
* @ param values A collection of values
* @ return A Criterion instance */
public org . grails . datastore . mapping . query . api . Criteria in ( String propertyName , Object [ ] values ) { } } | if ( ! validateSimpleExpression ( ) ) { throwRuntimeException ( new IllegalArgumentException ( "Call to [in] with propertyName [" + propertyName + "] and values [" + values + "] not allowed here." ) ) ; } propertyName = calculatePropertyName ( propertyName ) ; addToCriteria ( Restrictions . in ( propertyName , values ) ) ; return this ; |
public class MediaHandlerImpl { /** * Resolves the media request
* @ param mediaRequest Media request
* @ return Media metadata ( never null ) */
@ SuppressWarnings ( { } } | "null" , "unused" } ) @ NotNull Media processRequest ( @ NotNull final MediaRequest mediaRequest ) { // detect media source
MediaSource mediaSource = null ; List < Class < ? extends MediaSource > > mediaSources = mediaHandlerConfig . getSources ( ) ; if ( mediaSources == null || mediaSources . isEmpty ( ) ) { throw new RuntimeException ( "No media sources defined." ) ; } MediaSource firstMediaSource = null ; for ( Class < ? extends MediaSource > candidateMediaSourceClass : mediaSources ) { MediaSource candidateMediaSource = AdaptTo . notNull ( adaptable , candidateMediaSourceClass ) ; if ( candidateMediaSource . accepts ( mediaRequest ) ) { mediaSource = candidateMediaSource ; break ; } else if ( firstMediaSource == null ) { firstMediaSource = candidateMediaSource ; } } // if no media source was detected use first media resource defined
if ( mediaSource == null ) { mediaSource = firstMediaSource ; } Media media = new Media ( mediaSource , mediaRequest ) ; // resolve media format names to media formats
MediaFormatResolver mediaFormatResolver = new MediaFormatResolver ( mediaFormatHandler ) ; if ( ! mediaFormatResolver . resolve ( mediaRequest . getMediaArgs ( ) ) ) { media . setMediaInvalidReason ( MediaInvalidReason . INVALID_MEDIA_FORMAT ) ; return media ; } // if only downloads are accepted prepare media format filter set which only contains download media formats
if ( ! resolveDownloadMediaFormats ( mediaRequest . getMediaArgs ( ) ) ) { media . setMediaInvalidReason ( MediaInvalidReason . INVALID_MEDIA_FORMAT ) ; return media ; } // apply defaults to media args
if ( mediaRequest . getMediaArgs ( ) . isIncludeAssetWebRenditions ( ) == null ) { mediaRequest . getMediaArgs ( ) . includeAssetWebRenditions ( mediaHandlerConfig . includeAssetWebRenditionsByDefault ( ) ) ; } // preprocess media request before resolving
List < Class < ? extends MediaProcessor > > mediaPreProcessors = mediaHandlerConfig . getPreProcessors ( ) ; if ( mediaPreProcessors != null ) { for ( Class < ? extends MediaProcessor > processorClass : mediaPreProcessors ) { MediaProcessor processor = AdaptTo . notNull ( adaptable , processorClass ) ; media = processor . process ( media ) ; if ( media == null ) { throw new RuntimeException ( "MediaPreProcessor '" + processor + "' returned null, request: " + mediaRequest ) ; } } } // resolve media request
media = mediaSource . resolveMedia ( media ) ; if ( media == null ) { throw new RuntimeException ( "MediaType '" + mediaSource + "' returned null, request: " + mediaRequest ) ; } // generate markup ( if markup builder is available ) - first accepting wins
List < Class < ? extends MediaMarkupBuilder > > mediaMarkupBuilders = mediaHandlerConfig . getMarkupBuilders ( ) ; if ( mediaMarkupBuilders != null ) { for ( Class < ? extends MediaMarkupBuilder > mediaMarkupBuilderClass : mediaMarkupBuilders ) { MediaMarkupBuilder mediaMarkupBuilder = AdaptTo . notNull ( adaptable , mediaMarkupBuilderClass ) ; if ( mediaMarkupBuilder . accepts ( media ) ) { media . setElement ( mediaMarkupBuilder . build ( media ) ) ; break ; } } } // postprocess media request after resolving
List < Class < ? extends MediaProcessor > > mediaPostProcessors = mediaHandlerConfig . getPostProcessors ( ) ; if ( mediaPostProcessors != null ) { for ( Class < ? extends MediaProcessor > processorClass : mediaPostProcessors ) { MediaProcessor processor = AdaptTo . notNull ( adaptable , processorClass ) ; media = processor . process ( media ) ; if ( media == null ) { throw new RuntimeException ( "MediaPostProcessor '" + processor + "' returned null, request: " + mediaRequest ) ; } } } return media ; |
public class NetworkAddress { /** * Verify if a given string is a valid dotted quad notation IP Address
* @ param networkAddress The address string
* @ return true if its valid , false otherwise */
public static boolean isValidIPAddress ( String networkAddress ) { } } | if ( networkAddress != null ) { String [ ] split = networkAddress . split ( "\\." ) ; if ( split . length == 4 ) { int [ ] octets = new int [ 4 ] ; for ( int i = 0 ; i < 4 ; i ++ ) { try { octets [ i ] = Integer . parseInt ( split [ i ] ) ; } catch ( NumberFormatException e ) { return false ; } if ( octets [ i ] < 0 || octets [ i ] > 255 ) { return false ; } } return true ; } } return false ; |
public class VirtualNetworkTapsInner { /** * Gets information about the specified virtual network tap .
* @ param resourceGroupName The name of the resource group .
* @ param tapName The name of virtual network tap .
* @ param serviceCallback the async ServiceCallback to handle successful and failed responses .
* @ throws IllegalArgumentException thrown if parameters fail the validation
* @ return the { @ link ServiceFuture } object */
public ServiceFuture < VirtualNetworkTapInner > getByResourceGroupAsync ( String resourceGroupName , String tapName , final ServiceCallback < VirtualNetworkTapInner > serviceCallback ) { } } | return ServiceFuture . fromResponse ( getByResourceGroupWithServiceResponseAsync ( resourceGroupName , tapName ) , serviceCallback ) ; |
import java . math . * ; public class Main { /** * Calculates the total number of binary sequences of length 2 * bit _ length where
* the sum of the first ' bit _ length ' bits equals the sum of the last ' bit _ length ' bits .
* Args :
* bit _ length ( int ) : The length of one half of the binary sequence .
* Returns :
* float : The total number of sequences that fulfill the condition .
* Examples :
* > > > count _ equal _ sum _ binary _ sequences ( 1)
* 2.0
* > > > count _ equal _ sum _ binary _ sequences ( 2)
* 6.0
* > > > count _ equal _ sum _ binary _ sequences ( 3)
* 20.0 */
public static float countEqualSumBinarySequences ( int bit_length ) { } // Driver code
public static void main ( String args [ ] ) { System . out . println ( countEqualSumBinarySequences ( 1 ) ) ; // Should output 2.0
System . out . println ( countEqualSumBinarySequences ( 2 ) ) ; // Should output 6.0
System . out . println ( countEqualSumBinarySequences ( 3 ) ) ; // Should output 20.0
} } | double combination = 1 ; double sequence_count = 1 ; for ( int r = 1 ; r <= bit_length ; r ++ ) { combination = ( combination * ( bit_length + 1 - r ) ) / r ; sequence_count += Math . pow ( combination , 2 ) ; } return ( float ) sequence_count ; |
public class BlacklistTagsFilterInterceptor { /** * { @ inheritDoc }
* @ return true if the tag of the log is in the blacklist , false otherwise */
@ Override protected boolean reject ( LogItem log ) { } } | if ( blacklistTags != null ) { for ( String disabledTag : blacklistTags ) { if ( log . tag . equals ( disabledTag ) ) { return true ; } } } return false ; |
public class PaymentChannelClientState { /** * < p > Stores this channel ' s state in the wallet as a part of a { @ link StoredPaymentChannelClientStates } wallet
* extension and keeps it up - to - date each time payment is incremented . This allows the
* { @ link StoredPaymentChannelClientStates } object to keep track of timeouts and broadcast the refund transaction
* when the channel expires . < / p >
* < p > A channel may only be stored after it has fully opened ( ie state = = State . READY ) . The wallet provided in the
* constructor must already have a { @ link StoredPaymentChannelClientStates } object in its extensions set . < / p >
* @ param id A hash providing this channel with an id which uniquely identifies this server . It does not have to be
* unique . */
public synchronized void storeChannelInWallet ( Sha256Hash id ) { } } | stateMachine . checkState ( State . SAVE_STATE_IN_WALLET ) ; checkState ( id != null ) ; if ( storedChannel != null ) { checkState ( storedChannel . id . equals ( id ) ) ; return ; } doStoreChannelInWallet ( id ) ; try { wallet . commitTx ( getContractInternal ( ) ) ; } catch ( VerificationException e ) { throw new RuntimeException ( e ) ; // We created it
} stateMachine . transition ( State . PROVIDE_MULTISIG_CONTRACT_TO_SERVER ) ; |
public class PolicyDefinitionsInner { /** * Deletes a policy definition at management group level .
* @ param policyDefinitionName The name of the policy definition to delete .
* @ param managementGroupId The ID of the management group .
* @ throws IllegalArgumentException thrown if parameters fail the validation
* @ throws CloudException thrown if the request is rejected by server
* @ throws RuntimeException all other wrapped checked exceptions if the request fails to be sent */
public void deleteAtManagementGroup ( String policyDefinitionName , String managementGroupId ) { } } | deleteAtManagementGroupWithServiceResponseAsync ( policyDefinitionName , managementGroupId ) . toBlocking ( ) . single ( ) . body ( ) ; |
public class PrcRefreshHndlI18n { /** * < p > Process refresh request . < / p >
* @ param pAddParam additional param
* @ param pRequestData Request Data
* @ throws Exception - an exception */
@ Override public final void process ( final Map < String , Object > pAddParam , final IRequestData pRequestData ) throws Exception { } } | this . i18nRequestHandler . handleDataChanged ( ) ; |
public class CqlPrepareHandler { /** * blocking , the preparation will be retried later on that node . Simply warn and move on . */
private CompletionStage < Void > prepareOnOtherNode ( Node node ) { } } | LOG . trace ( "[{}] Repreparing on {}" , logPrefix , node ) ; DriverChannel channel = session . getChannel ( node , logPrefix ) ; if ( channel == null ) { LOG . trace ( "[{}] Could not get a channel to reprepare on {}, skipping" , logPrefix , node ) ; return CompletableFuture . completedFuture ( null ) ; } else { ThrottledAdminRequestHandler handler = new ThrottledAdminRequestHandler ( channel , message , request . getCustomPayload ( ) , timeout , throttler , session . getMetricUpdater ( ) , logPrefix , message . toString ( ) ) ; return handler . start ( ) . handle ( ( result , error ) -> { if ( error == null ) { LOG . trace ( "[{}] Successfully reprepared on {}" , logPrefix , node ) ; } else { Loggers . warnWithException ( LOG , "[{}] Error while repreparing on {}" , node , logPrefix , error ) ; } return null ; } ) ; } |
public class FileResourceBundle { /** * Specifies the directory in which our temporary resource files should be stored . */
public static void setCacheDir ( File tmpdir ) { } } | String rando = Long . toHexString ( ( long ) ( Math . random ( ) * Long . MAX_VALUE ) ) ; _tmpdir = new File ( tmpdir , "narcache_" + rando ) ; if ( ! _tmpdir . exists ( ) ) { if ( _tmpdir . mkdirs ( ) ) { log . debug ( "Created narya temp cache directory '" + _tmpdir + "'." ) ; } else { log . warning ( "Failed to create temp cache directory '" + _tmpdir + "'." ) ; } } // add a hook to blow away the temp directory when we exit
Runtime . getRuntime ( ) . addShutdownHook ( new Thread ( ) { @ Override public void run ( ) { log . info ( "Clearing narya temp cache '" + _tmpdir + "'." ) ; FileUtil . recursiveDelete ( _tmpdir ) ; } } ) ; |
public class PluginUtils { /** * Gets the user ' s local m2 directory or null if not found .
* @ return user ' s M2 repo */
public static File getUserM2Repository ( ) { } } | // if there is m2override system propery , use it .
String m2Override = System . getProperty ( "apiman.gateway.m2-repository-path" ) ; // $ NON - NLS - 1 $
if ( m2Override != null ) { return new File ( m2Override ) . getAbsoluteFile ( ) ; } String userHome = System . getProperty ( "user.home" ) ; // $ NON - NLS - 1 $
if ( userHome != null ) { File userHomeDir = new File ( userHome ) ; if ( userHomeDir . isDirectory ( ) ) { File m2Dir = new File ( userHome , ".m2/repository" ) ; // $ NON - NLS - 1 $
if ( m2Dir . isDirectory ( ) ) { return m2Dir ; } } } return null ; |
public class ServiceDiscoveryManager { /** * Returns the discovered items of a given XMPP entity addressed by its JID .
* @ param entityID the address of the XMPP entity .
* @ return the discovered information .
* @ throws XMPPErrorException if the operation failed for some reason .
* @ throws NoResponseException if there was no response from the server .
* @ throws NotConnectedException
* @ throws InterruptedException */
public DiscoverItems discoverItems ( Jid entityID ) throws NoResponseException , XMPPErrorException , NotConnectedException , InterruptedException { } } | return discoverItems ( entityID , null ) ; |
public class ExecutionVertex { /** * Simply forward this notification . */
void notifyStateTransition ( Execution execution , ExecutionState newState , Throwable error ) { } } | // only forward this notification if the execution is still the current execution
// otherwise we have an outdated execution
if ( currentExecution == execution ) { getExecutionGraph ( ) . notifyExecutionChange ( execution , newState , error ) ; } |
public class ASTNode { /** * Sets the node meta data .
* @ param key - the meta data key
* @ param value - the meta data value
* @ throws GroovyBugError if key is null or there is already meta
* data under that key */
public void setNodeMetaData ( Object key , Object value ) { } } | if ( key == null ) throw new GroovyBugError ( "Tried to set meta data with null key on " + this + "." ) ; if ( metaDataMap == null ) { metaDataMap = new ListHashMap ( ) ; } Object old = metaDataMap . put ( key , value ) ; if ( old != null ) throw new GroovyBugError ( "Tried to overwrite existing meta data " + this + "." ) ; |
public class ServiceDiscoveryImpl { /** * The discovery must be started before use
* @ throws Exception errors */
@ Override public void start ( ) throws Exception { } } | try { reRegisterServices ( ) ; } catch ( KeeperException e ) { log . error ( "Could not register instances - will try again later" , e ) ; } client . getConnectionStateListenable ( ) . addListener ( connectionStateListener ) ; |
public class StrictLineReader { /** * Reads new input data into the buffer . Call only with pos = = end or end = = - 1,
* depending on the desired outcome if the function throws . */
private void fillBuf ( ) throws IOException { } } | int result = in . read ( buf , 0 , buf . length ) ; if ( result == - 1 ) { throw new EOFException ( ) ; } pos = 0 ; end = result ; |
public class TagKey { /** * Determines whether the given { @ code String } is a valid tag key .
* @ param name the tag key name to be validated .
* @ return whether the name is valid . */
private static boolean isValid ( String name ) { } } | return ! name . isEmpty ( ) && name . length ( ) <= MAX_LENGTH && StringUtils . isPrintableString ( name ) ; |
public class DateUtil { /** * Add days to a date
* @ param d date
* @ param days days
* @ return new date */
public static Date addDays ( Date d , int days ) { } } | Calendar cal = Calendar . getInstance ( ) ; cal . setTime ( d ) ; cal . add ( Calendar . DAY_OF_YEAR , days ) ; return cal . getTime ( ) ; |
public class AwsSecurityFindingFilters { /** * The date / time that the process was terminated .
* < b > NOTE : < / b > This method appends the values to the existing list ( if any ) . Use
* { @ link # setProcessTerminatedAt ( java . util . Collection ) } or { @ link # withProcessTerminatedAt ( java . util . Collection ) }
* if you want to override the existing values .
* @ param processTerminatedAt
* The date / time that the process was terminated .
* @ return Returns a reference to this object so that method calls can be chained together . */
public AwsSecurityFindingFilters withProcessTerminatedAt ( DateFilter ... processTerminatedAt ) { } } | if ( this . processTerminatedAt == null ) { setProcessTerminatedAt ( new java . util . ArrayList < DateFilter > ( processTerminatedAt . length ) ) ; } for ( DateFilter ele : processTerminatedAt ) { this . processTerminatedAt . add ( ele ) ; } return this ; |
public class ClientAuthenticationService { /** * Authenticating on the client will only create a " dummy " basic auth subject and does not
* truly authenticate anything . This subject is sent to the server ove CSIv2 where the real
* authentication happens .
* @ param callbackHandler the callbackhandler to get the authentication data from , must not be < null >
* @ param subject the partial subject , can be null
* @ return a basic auth subject with a basic auth credential
* @ throws WSLoginFailedException if a callback handler is not specified
* @ throws CredentialException if there was a problem creating the WSCredential
* @ throws IOException if there is an I / O error */
public Subject authenticate ( CallbackHandler callbackHandler , Subject subject ) throws WSLoginFailedException , CredentialException { } } | if ( callbackHandler == null ) { throw new WSLoginFailedException ( TraceNLS . getFormattedMessage ( this . getClass ( ) , TraceConstants . MESSAGE_BUNDLE , "JAAS_LOGIN_NO_CALLBACK_HANDLER" , new Object [ ] { } , "CWWKS1170E: The login on the client application failed because the CallbackHandler implementation is null. Ensure a valid CallbackHandler implementation is specified either in the LoginContext constructor or in the client application's deployment descriptor." ) ) ; } CallbackHandlerAuthenticationData cAuthData = new CallbackHandlerAuthenticationData ( callbackHandler ) ; AuthenticationData authenticationData = null ; try { authenticationData = cAuthData . createAuthenticationData ( ) ; } catch ( IOException e ) { throw new WSLoginFailedException ( TraceNLS . getFormattedMessage ( this . getClass ( ) , TraceConstants . MESSAGE_BUNDLE , "JAAS_LOGIN_UNEXPECTED_EXCEPTION" , new Object [ ] { e . getLocalizedMessage ( ) } , "CWWKS1172E: The login on the client application failed because of an unexpected exception. Review the logs to understand the cause of the exception. The exception is: " + e . getLocalizedMessage ( ) ) ) ; } catch ( UnsupportedCallbackException e ) { throw new WSLoginFailedException ( TraceNLS . getFormattedMessage ( this . getClass ( ) , TraceConstants . MESSAGE_BUNDLE , "JAAS_LOGIN_UNEXPECTED_EXCEPTION" , new Object [ ] { e . getLocalizedMessage ( ) } , "CWWKS1172E: The login on the client application failed because of an unexpected exception. Review the logs to understand the cause of the exception. The exception is: " + e . getLocalizedMessage ( ) ) ) ; } return createBasicAuthSubject ( authenticationData , subject ) ; |
public class FEELCodeMarshaller { /** * Marshalls the given value into FEEL code that can be executed to
* reconstruct the value . For instance , here are some examples of the marshalling process :
* * number 10 marshalls as : 10
* * string foo marshalls as : " foo "
* * duration P1D marshalls as : duration ( " P1D " )
* * context { x : 10 , y : foo } marshalls as : { x : 10 , y : " foo " }
* @ param value the FEEL value to be marshalled
* @ return a string representing the FEEL code that needs to be executed to reconstruct the value */
@ Override public String marshall ( Object value ) { } } | if ( value == null ) { return "null" ; } return KieExtendedDMNFunctions . getFunction ( CodeFunction . class ) . invoke ( value ) . cata ( justNull ( ) , Function . identity ( ) ) ; |
public class ShrinkWrapPath { /** * { @ inheritDoc }
* @ see java . nio . file . Path # relativize ( java . nio . file . Path ) */
@ Override public Path relativize ( final Path other ) { } } | if ( other == null ) { throw new IllegalArgumentException ( "other path must be specified" ) ; } if ( ! ( other instanceof ShrinkWrapPath ) ) { throw new IllegalArgumentException ( "Can only relativize paths of type " + ShrinkWrapPath . class . getSimpleName ( ) ) ; } // Equal paths , return empty Path
if ( this . equals ( other ) ) { return new ShrinkWrapPath ( "" , this . fileSystem ) ; } // Recursive relativization
final Path newPath = relativizeCommonRoot ( this , this , other , other , 0 ) ; return newPath ; |
public class PlanNode { /** * Get the node ' s value for this supplied property , casting the result to a { @ link List } of the supplied type .
* @ param < ValueType > the type of the value expected
* @ param propertyId the property identifier
* @ param type the class denoting the type of value expected ; may not be null
* @ return the value , or null if there is no property on this node */
@ SuppressWarnings ( "unchecked" ) public < ValueType > List < ValueType > getPropertyAsList ( Property propertyId , Class < ValueType > type ) { } } | if ( nodeProperties == null ) return null ; Object property = nodeProperties . get ( propertyId ) ; if ( property instanceof List ) { return ( List < ValueType > ) property ; } if ( property == null ) return null ; List < ValueType > result = new ArrayList < ValueType > ( ) ; result . add ( ( ValueType ) property ) ; return result ; |
public class ComponentPrint { /** * Set the current Y location and change the current component information to match .
* @ param targetPageIndex The page to position to .
* @ param targetLocationOnPage The location in the current page to position in .
* @ return True if this is the last component and it is finished on this page . */
public boolean setCurrentYLocation ( int targetPageIndex , int targetLocationOnPage ) { } } | // ? if ( ( targetPageIndex ! = currentPageIndex ) | | ( targetLocationOnPage ! = currentLocationOnPage ) )
this . resetAll ( ) ; // If I ' m not using the cached values , reset to start
boolean pageDone = false ; while ( pageDone == false ) { if ( currentComponent == null ) break ; componentPageHeight = this . calcComponentPageHeight ( ) ; if ( currentPageIndex > targetPageIndex ) break ; if ( currentPageIndex == targetPageIndex ) if ( currentLocationOnPage >= targetLocationOnPage ) break ; // Target location reached . Return this current component , stats
remainingComponentHeight = remainingComponentHeight + this . checkComponentHeight ( ) ; if ( remainingComponentHeight < remainingPageHeight ) { // This component will fit on this page .
currentLocationOnPage = currentLocationOnPage + remainingComponentHeight ; remainingPageHeight = remainingPageHeight - remainingComponentHeight ; componentIndex ++ ; currentComponent = this . getComponent ( componentIndex ) ; componentStartYLocation = 0 ; if ( currentComponent != null ) remainingComponentHeight = currentComponent . getHeight ( ) ; } else { // This component goes past the end of the page
componentStartYLocation = componentStartYLocation + componentPageHeight ; if ( targetPageIndex == currentPageIndex ) pageDone = true ; // The target page is completely scanned
currentPageIndex ++ ; currentLocationOnPage = 0 ; remainingComponentHeight = remainingComponentHeight - componentPageHeight ; remainingPageHeight = pageHeight ; } } return pageDone ; // Page done |
public class CQLTranslator { /** * Build where clause with @ EQ _ CLAUSE } clause .
* @ param builder
* the builder
* @ param field
* the field
* @ param member
* the member
* @ param entity
* the entity */
public void buildWhereClause ( StringBuilder builder , String field , Field member , Object entity ) { } } | // builder = ensureCase ( builder , field , false ) ;
// builder . append ( EQ _ CLAUSE ) ;
// appendColumnValue ( builder , entity , member ) ;
// builder . append ( AND _ CLAUSE ) ;
Object value = PropertyAccessorHelper . getObject ( entity , member ) ; buildWhereClause ( builder , member . getType ( ) , field , value , EQ_CLAUSE , false ) ; |
public class Stream { /** * Zip together the iterators until one of them runs out of values .
* Each array of values is combined into a single value using the supplied zipFunction function .
* @ param c
* @ param zipFunction
* @ return */
@ SuppressWarnings ( "resource" ) public static < R > Stream < R > zip ( final Collection < ? extends ShortStream > c , final ShortNFunction < R > zipFunction ) { } } | if ( N . isNullOrEmpty ( c ) ) { return Stream . empty ( ) ; } final int len = c . size ( ) ; final ShortIterator [ ] iters = new ShortIterator [ len ] ; int i = 0 ; for ( ShortStream s : c ) { iters [ i ++ ] = s . iteratorEx ( ) ; } return new IteratorStream < > ( new ObjIteratorEx < R > ( ) { @ Override public boolean hasNext ( ) { for ( int i = 0 ; i < len ; i ++ ) { if ( iters [ i ] . hasNext ( ) == false ) { return false ; } } return true ; } @ Override public R next ( ) { final short [ ] args = new short [ len ] ; for ( int i = 0 ; i < len ; i ++ ) { args [ i ] = iters [ i ] . nextShort ( ) ; } return zipFunction . apply ( args ) ; } } ) . onClose ( newCloseHandler ( c ) ) ; |
public class BaseStreamWriter { /** * @ param name Name of the property to set
* @ param value Value to set property to .
* @ return True , if the specified property was < b > succesfully < / b >
* set to specified value ; false if its value was not changed */
@ Override public boolean setProperty ( String name , Object value ) { } } | /* Note : can not call local method , since it ' ll return false for
* recognized but non - mutable properties */
return mConfig . setProperty ( name , value ) ; |
public class SObject { /** * Construct an SObject with specified key , file and attributes
* specified in { @ link Map }
* @ see # of ( String , File , String . . . ) */
public static SObject of ( String key , File file , Map < String , String > attributes ) { } } | SObject sobj = of ( key , $ . requireNotNull ( file ) ) ; sobj . setAttributes ( attributes ) ; return sobj ; |
public class PublishingServiceRepository { /** * region > findQueued */
@ Programmatic public List < PublishedEvent > findQueued ( ) { } } | return repositoryService . allMatches ( new QueryDefault < > ( PublishedEvent . class , "findByStateOrderByTimestamp" , "state" , PublishedEvent . State . QUEUED ) ) ; |
public class CmsEditorBase { /** * Returns the formated message . < p >
* @ param key the message key
* @ param args the parameters to insert into the placeholders
* @ return the formated message */
public static String getMessageForKey ( String key , Object ... args ) { } } | String result = null ; if ( hasDictionary ( ) ) { result = m_dictionary . get ( key ) ; if ( ( result != null ) && ( args != null ) && ( args . length > 0 ) ) { for ( int i = 0 ; i < args . length ; i ++ ) { result = result . replace ( "{" + i + "}" , String . valueOf ( args [ i ] ) ) ; } } } if ( result == null ) { result = "" ; } return result ; |
public class Ifc4PackageImpl { /** * < ! - - begin - user - doc - - >
* < ! - - end - user - doc - - >
* @ generated */
@ Override public EClass getIfcProfileDef ( ) { } } | if ( ifcProfileDefEClass == null ) { ifcProfileDefEClass = ( EClass ) EPackage . Registry . INSTANCE . getEPackage ( Ifc4Package . eNS_URI ) . getEClassifiers ( ) . get ( 457 ) ; } return ifcProfileDefEClass ; |
public class TldVarianceFilter { /** * Integral image of pixel value squared . floating point */
public static void transformSq ( final GrayF32 input , final GrayF64 transformed ) { } } | int indexSrc = input . startIndex ; int indexDst = transformed . startIndex ; int end = indexSrc + input . width ; double total = 0 ; for ( ; indexSrc < end ; indexSrc ++ ) { float value = input . data [ indexSrc ] ; transformed . data [ indexDst ++ ] = total += value * value ; } for ( int y = 1 ; y < input . height ; y ++ ) { indexSrc = input . startIndex + input . stride * y ; indexDst = transformed . startIndex + transformed . stride * y ; int indexPrev = indexDst - transformed . stride ; end = indexSrc + input . width ; total = 0 ; for ( ; indexSrc < end ; indexSrc ++ ) { float value = input . data [ indexSrc ] ; total += value * value ; transformed . data [ indexDst ++ ] = transformed . data [ indexPrev ++ ] + total ; } } |
public class Observance { /** * Sets the date that the timezone observance starts .
* @ param date the start date or null to remove
* @ return the property that was created
* @ see < a href = " http : / / tools . ietf . org / html / rfc5545 # page - 97 " > RFC 5545
* p . 97-8 < / a >
* @ see < a href = " http : / / tools . ietf . org / html / rfc2445 # page - 93 " > RFC 2445
* p . 93-4 < / a > */
public DateStart setDateStart ( ICalDate date ) { } } | DateStart prop = ( date == null ) ? null : new DateStart ( date ) ; setDateStart ( prop ) ; return prop ; |
public class Results { /** * Connection . abort ( ) has been called , abort remaining active result - set
* @ throws SQLException exception */
public void abort ( ) throws SQLException { } } | if ( fetchSize != 0 ) { fetchSize = 0 ; if ( resultSet != null ) { resultSet . abort ( ) ; } else { SelectResultSet firstResult = executionResults . peekFirst ( ) ; if ( firstResult != null ) { firstResult . abort ( ) ; } } } |
public class AbstractAnnotationVisitor { /** * Get the array of referenced values .
* @ return The array of referenced values . */
private List < ValueDescriptor < ? > > getArrayValue ( ) { } } | List < ValueDescriptor < ? > > values = arrayValueDescriptor . getValue ( ) ; if ( values == null ) { values = new LinkedList < > ( ) ; arrayValueDescriptor . setValue ( values ) ; } return values ; |
public class UIForm { /** * < p class = " changed _ modified _ 2_2 " > Generate an identifier for a component . The identifier
* will be prefixed with UNIQUE _ ID _ PREFIX , and will be unique
* within this component - container . Optionally , a unique seed value can
* be supplied by component creators which should be
* included in the generated unique id . < / p >
* < p class = " changed _ added _ 2_2 " >
* If the < code > prependId < / code > property has the value < code > false < / code > ,
* this method must call < code > createUniqueId < / code > on the next ancestor
* < code > UniqueIdVendor < / code > .
* @ param context FacesContext
* @ param seed an optional seed value - e . g . based on the position of the component in the VDL - template
* @ return a unique - id in this component - container */
public String createUniqueId ( FacesContext context , String seed ) { } } | if ( isPrependId ( ) ) { Integer i = ( Integer ) getStateHelper ( ) . get ( PropertyKeys . lastId ) ; int lastId = ( ( i != null ) ? i : 0 ) ; getStateHelper ( ) . put ( PropertyKeys . lastId , ++ lastId ) ; return UIViewRoot . UNIQUE_ID_PREFIX + ( seed == null ? lastId : seed ) ; } else { UIComponent ancestorNamingContainer = ( getParent ( ) == null ) ? null : getParent ( ) . getNamingContainer ( ) ; String uid = null ; if ( null != ancestorNamingContainer && ancestorNamingContainer instanceof UniqueIdVendor ) { uid = ( ( UniqueIdVendor ) ancestorNamingContainer ) . createUniqueId ( context , seed ) ; } else { uid = context . getViewRoot ( ) . createUniqueId ( context , seed ) ; } return uid ; } |
public class StrSubstitutor { /** * Replaces all the occurrences of variables within the given source buffer
* with their matching values from the resolver .
* The buffer is updated with the result .
* @ param source the buffer to replace in , updated , null returns zero
* @ return true if altered
* @ since 3.2 */
public boolean replaceIn ( final StringBuilder source ) { } } | if ( source == null ) { return false ; } return replaceIn ( source , 0 , source . length ( ) ) ; |
public class AfplibPackageImpl { /** * < ! - - begin - user - doc - - >
* < ! - - end - user - doc - - >
* @ generated */
public EClass getObjectByteExtent ( ) { } } | if ( objectByteExtentEClass == null ) { objectByteExtentEClass = ( EClass ) EPackage . Registry . INSTANCE . getEPackage ( AfplibPackage . eNS_URI ) . getEClassifiers ( ) . get ( 509 ) ; } return objectByteExtentEClass ; |
public class DistributedException { /** * Get a specific exception in a possible chain of exceptions .
* If there are multiple exceptions in the chain , the most recent
* one thrown will be returned .
* If the exceptions does not exist or no exceptions have been chained ,
* null will be returned .
* @ exception com . ibm . websphere . exception . ExceptionInstantiationException
* An exception occurred while trying to instantiate the exception object .
* If this exception is thrown , the relevant information can be retrieved
* by using the getExceptionInfo ( ) method followed by recursively using
* the getPreviousExceptionInfo ( ) method on the DistributedExceptionInfo
* object .
* @ param String exceptionClassName the class name of the specific exception .
* @ return java . lang . Throwable The specific exception in a chain of
* exceptions . If no exceptions have been chained , null will be returned . */
public Throwable getException ( String exceptionClassName ) throws ExceptionInstantiationException { } } | if ( exceptionClassName == null ) { return null ; } Throwable ex = exceptionInfo . getException ( exceptionClassName ) ; return ex ; |
public class AbstractSetTypeConverter { /** * Do the actual reverse conversion of one object .
* @ param jTransfo jTransfo instance in use
* @ param domainObject domain object
* @ param toField field definition on the transfer object
* @ param toType configured to type for list
* @ param tags tags which indicate which fields can be converted based on { @ link MapOnly } annotations .
* @ return domain object
* @ throws JTransfoException oops , cannot convert */
public Object doReverseOne ( JTransfo jTransfo , Object domainObject , SyntheticField toField , Class < ? > toType , String ... tags ) throws JTransfoException { } } | return jTransfo . convertTo ( domainObject , jTransfo . getToSubType ( toType , domainObject ) , tags ) ; |
public class UndoRedoHandler { /** * Detach this handler from the text component . This will remove all
* listeners that have been attached to the text component , its
* document , and the elements of its input - and action maps . */
public void detach ( ) { } } | textComponent . removePropertyChangeListener ( documentPropertyChangeListener ) ; Document document = textComponent . getDocument ( ) ; document . removeUndoableEditListener ( undoableEditListener ) ; textComponent . getInputMap ( ) . remove ( undoKeyStroke ) ; textComponent . getActionMap ( ) . remove ( DO_UNDO_NAME ) ; textComponent . getInputMap ( ) . remove ( redoKeyStroke ) ; textComponent . getActionMap ( ) . remove ( DO_REDO_NAME ) ; |
public class GroupService { /** * Create snapshot of servers groups
* @ param expirationDays expiration days ( must be between 1 and 10)
* @ param groupFilter search servers criteria by group filter
* @ return OperationFuture wrapper for Server list */
public OperationFuture < List < Server > > createSnapshot ( Integer expirationDays , GroupFilter groupFilter ) { } } | return serverService ( ) . createSnapshot ( expirationDays , getServerSearchCriteria ( groupFilter ) ) ; |
public class FluentCursor { /** * Transforms Cursor to LazyCursorList of T applying given function
* WARNING : This method doesn ' t close cursor . You are responsible for calling close ( )
* on returned list or on backing Cursor .
* @ param singleRowTransform Function to apply on every single row of this cursor
* @ param < T > Type of List ' s single element
* @ return Transformed list */
public < T > LazyCursorList < T > toLazyCursorList ( Function < ? super Cursor , T > singleRowTransform ) { } } | return new LazyCursorList < > ( this , singleRowTransform ) ; |
public class BoneCP { /** * Physically close off the internal connection .
* @ param conn */
protected void destroyConnection ( ConnectionHandle conn ) { } } | postDestroyConnection ( conn ) ; conn . setInReplayMode ( true ) ; // we ' re dead , stop attempting to replay anything
try { conn . internalClose ( ) ; } catch ( SQLException e ) { logger . error ( "Error in attempting to close connection" , e ) ; } |
public class VLinkedPagedList { /** * Similar to listIterator ( LK linearKey , boolean next ) except with the
* addition of the hint " pageId " which specifies the first page to look for
* the key .
* Runtime : up to O ( n ) gets , unless a good hint page is provided , then it
* could be 1 - 2 gets .
* @ param linearKey
* @ param next
* @ param pageId
* @ return */
public MappedListIterator < VLinkedPagedKey , LK > listIterator ( LK linearKey , boolean next , Integer pageId ) { } } | return new VLinkedPagedListIterator < I , LK > ( _index , _serializer , linearKey , next , pageId ) ; |
public class RTree { /** * This description is from the original paper .
* AT1 . [ Initialize ] . Set N = L . If L was split previously , set NN to be the resulting second node .
* AT2 . [ Check if done ] . If N is the root , stop .
* AT3 . [ Adjust covering rectangle in parent entry ] . Let P be the parent node of N , and let Ev ( N ) I be N ' s entry in P .
* Adjust Ev ( N ) I so that it tightly encloses all entry rectangles in N .
* AT4 . [ Propagate node split upward ] . If N has a partner NN resulting from an earlier split , create a new entry
* Ev ( NN ) with Ev ( NN ) p pointing to NN and Ev ( NN ) I enclosing all rectangles in NN . Add Ev ( NN ) to p is there is room .
* Otherwise , invoke { @ link SplitStrategy } split to product p and pp containing Ev ( NN ) and all p ' s old entries .
* @ param n - first node to adjust
* @ param nn - optional second node to adjust */
private void adjustTree ( Node n , Node nn ) { } } | // special case for root
if ( n == root ) { if ( nn != null ) { root = buildRoot ( false ) ; root . addChild ( n ) ; root . addChild ( nn ) ; } root . enclose ( ) ; return ; } boolean updateParent = n . enclose ( ) ; if ( nn != null ) { nn . enclose ( ) ; updateParent = true ; if ( splitStrategy . needToSplit ( n . getParent ( ) ) ) { Node [ ] groups = splitStrategy . split ( n . getParent ( ) ) ; adjustTree ( groups [ 0 ] , groups [ 1 ] ) ; } } if ( n . getParent ( ) != null && updateParent ) { adjustTree ( n . getParent ( ) , null ) ; } |
public class RequestedModuleNames { /** * / * ( non - Javadoc )
* @ see com . ibm . jaggr . core . transport . IRequestedModuleNames # getPreloads ( ) */
@ Override public List < String > getPreloads ( ) { } } | final String sourceMethod = "getPreloads" ; // $ NON - NLS - 1 $
if ( isTraceLogging ) { log . entering ( RequestedModuleNames . class . getName ( ) , sourceMethod ) ; log . exiting ( RequestedModuleNames . class . getName ( ) , sourceMethod , preloads ) ; } return preloads ; |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.