signature stringlengths 43 39.1k | implementation stringlengths 0 450k |
|---|---|
public class ColorStateDrawable { /** * Given a particular color , adjusts its value by a multiplier . */
private int getPressedColor ( int color ) { } } | float [ ] hsv = new float [ 3 ] ; Color . colorToHSV ( color , hsv ) ; hsv [ 2 ] = hsv [ 2 ] * PRESSED_STATE_MULTIPLIER ; return Color . HSVToColor ( hsv ) ; |
public class LatchedObserver { /** * Create a LatchedObserver with the given callback function ( s ) . */
public static < T > LatchedObserver < T > create ( Action1 < ? super T > onNext , Action1 < ? super Throwable > onError ) { } } | return create ( onNext , onError , new CountDownLatch ( 1 ) ) ; |
public class GlobalTrafficShapingHandler { /** * Create the global TrafficCounter . */
void createGlobalTrafficCounter ( ScheduledExecutorService executor ) { } } | if ( executor == null ) { throw new NullPointerException ( "executor" ) ; } TrafficCounter tc = new TrafficCounter ( this , executor , "GlobalTC" , checkInterval ) ; setTrafficCounter ( tc ) ; tc . start ( ) ; |
public class WebSiteManagementClientImpl { /** * Gets list of available geo regions plus ministamps .
* Gets list of available geo regions plus ministamps .
* @ throws IllegalArgumentException thrown if parameters fail the validation
* @ return the observable to the DeploymentLocationsInner object */
public Observable < DeploymentLocationsInner > getSubscriptionDeploymentLocationsAsync ( ) { } } | return getSubscriptionDeploymentLocationsWithServiceResponseAsync ( ) . map ( new Func1 < ServiceResponse < DeploymentLocationsInner > , DeploymentLocationsInner > ( ) { @ Override public DeploymentLocationsInner call ( ServiceResponse < DeploymentLocationsInner > response ) { return response . body ( ) ; } } ) ; |
public class PortTcp { /** * Starts the port listening . */
public void start ( ) throws Exception { } } | if ( _port < 0 && _unixPath == null ) { return ; } if ( ! _lifecycle . toStarting ( ) ) return ; boolean isValid = false ; try { bind ( ) ; postBind ( ) ; enable ( ) ; _acceptTask = new AcceptTcp ( this , _serverSocket ) ; _threadPool . execute ( _acceptTask ) ; // _ connThreadPool . start ( ) ;
_suspendAlarm = new Alarm ( new SuspendReaper ( ) ) ; _suspendAlarm . runAfter ( _suspendReaperTimeout ) ; isValid = true ; } finally { if ( ! isValid ) { close ( ) ; } } |
public class MMFF94ParametersCall { /** * Gets the bond parameter set .
* @ param id1 atom1 id
* @ param id2 atom2 id
* @ return The distance value from the force field parameter set
* @ exception Exception Description of the Exception */
public List getBondData ( String code , String id1 , String id2 ) throws Exception { } } | String dkey = "" ; if ( pSet . containsKey ( ( "bond" + code + ";" + id1 + ";" + id2 ) ) ) { dkey = "bond" + code + ";" + id1 + ";" + id2 ; } else if ( pSet . containsKey ( ( "bond" + code + ";" + id2 + ";" + id1 ) ) ) { dkey = "bond" + code + ";" + id2 + ";" + id1 ; } /* * else { System . out . println ( " KEYError : Unknown distance key in pSet : "
* + code + " ; " + id2 + " ; " + id1 + " take default bon length : " +
* DEFAULT _ BOND _ LENGTH ) ; return DEFAULT _ BOND _ LENGTH ; } */
// logger . debug ( " dkey = " + dkey ) ;
return ( List ) pSet . get ( dkey ) ; |
public class Check { /** * Check if < code > a < / code > is superior to < code > b < / code > .
* @ param a The parameter to test .
* @ param b The parameter to compare to .
* @ throws LionEngineException If check failed . */
public static void superiorOrEqual ( double a , double b ) { } } | if ( a < b ) { throw new LionEngineException ( ERROR_ARGUMENT + String . valueOf ( a ) + ERROR_SUPERIOR + String . valueOf ( b ) ) ; } |
public class Flowable { /** * Mirrors the Publisher ( current or provided ) that first either emits an item or sends a termination
* notification .
* < img width = " 640 " height = " 385 " src = " https : / / raw . github . com / wiki / ReactiveX / RxJava / images / rx - operators / amb . png " alt = " " >
* < dl >
* < dt > < b > Backpressure : < / b > < / dt >
* < dd > The operator itself doesn ' t interfere with backpressure which is determined by the winning
* { @ code Publisher } ' s backpressure behavior . < / dd >
* < dt > < b > Scheduler : < / b > < / dt >
* < dd > { @ code ambWith } does not operate by default on a particular { @ link Scheduler } . < / dd >
* < / dl >
* @ param other
* a Publisher competing to react first . A subscription to this provided Publisher will occur after subscribing
* to the current Publisher .
* @ return a Flowable that emits the same sequence as whichever of the source Publishers first
* emitted an item or sent a termination notification
* @ see < a href = " http : / / reactivex . io / documentation / operators / amb . html " > ReactiveX operators documentation : Amb < / a > */
@ SuppressWarnings ( "unchecked" ) @ CheckReturnValue @ BackpressureSupport ( BackpressureKind . FULL ) @ SchedulerSupport ( SchedulerSupport . NONE ) public final Flowable < T > ambWith ( Publisher < ? extends T > other ) { } } | ObjectHelper . requireNonNull ( other , "other is null" ) ; return ambArray ( this , other ) ; |
public class TinkerpopBackend { /** * Updates the properties of the element , disregarding any changes of the disallowed properties
* < p > The list of the disallowed properties will usually come from
* { @ link Constants . Type # getMappedProperties ( ) } .
* @ param e the element to update properties of
* @ param properties the properties to update
* @ param disallowedProperties the list of properties that are not allowed to change . */
static void updateProperties ( Element e , Map < String , Object > properties , String [ ] disallowedProperties ) { } } | if ( properties == null ) { return ; } Set < String > disallowed = new HashSet < > ( Arrays . asList ( disallowedProperties ) ) ; // remove all non - mapped properties , that are not in the update
Spliterator < Property < ? > > sp = Spliterators . spliteratorUnknownSize ( e . properties ( ) , Spliterator . NONNULL & Spliterator . IMMUTABLE ) ; Property < ? > [ ] toRemove = StreamSupport . stream ( sp , false ) . filter ( ( p ) -> ! disallowed . contains ( p . key ( ) ) && ! properties . containsKey ( p . key ( ) ) ) . toArray ( Property [ ] :: new ) ; for ( Property < ? > p : toRemove ) { p . remove ( ) ; } // update and add new the properties
properties . forEach ( ( p , v ) -> { if ( ! disallowed . contains ( p ) ) { e . property ( p , v ) ; } } ) ; |
public class ReflectionUtils { /** * Calls the method with the specified name on the given object . This method assumes the " method " to invoke
* is an instance ( object ) member method .
* @ param obj the Object on which the method to invoke is defined .
* @ param methodName a String indicating the name of the method to invoke .
* @ throws IllegalArgumentException if the method with the specified name is not declared and defined
* on the given object ' s class type .
* @ throws MethodInvocationException if the method invocation ( call ) fails to be executed successfully .
* @ see # invoke ( Object , String , Class [ ] , Object [ ] , Class ) */
public static void invoke ( Object obj , String methodName ) { } } | invoke ( obj , methodName , null , null , Void . class ) ; |
public class FindingReplacing { /** * Sets the substring in the beginning and given right index as the search string
* @ see Indexer # before ( int )
* @ param rightIndex
* @ return */
public NegateMultiPos < S , Integer , Integer > before ( int rightIndex ) { } } | return new NegateMultiPos < S , Integer , Integer > ( 0 , rightIndex ) { @ Override protected S result ( ) { return aQueue ( 'J' , left , right , pos , position , null , plusminus , filltgt ) ; } } ; |
public class ReflectUtil { /** * 尝试遍历并调用此类的所有构造方法 , 直到构造成功并返回
* @ param < T > 对象类型
* @ param beanClass 被构造的类
* @ return 构造后的对象 */
public static < T > T newInstanceIfPossible ( Class < T > beanClass ) { } } | Assert . notNull ( beanClass ) ; try { return newInstance ( beanClass ) ; } catch ( Exception e ) { // ignore
// 默认构造不存在的情况下查找其它构造
} final Constructor < T > [ ] constructors = getConstructors ( beanClass ) ; Class < ? > [ ] parameterTypes ; for ( Constructor < T > constructor : constructors ) { parameterTypes = constructor . getParameterTypes ( ) ; if ( 0 == parameterTypes . length ) { continue ; } constructor . setAccessible ( true ) ; try { return constructor . newInstance ( ClassUtil . getDefaultValues ( parameterTypes ) ) ; } catch ( Exception e ) { // 构造出错时继续尝试下一种构造方式
continue ; } } return null ; |
public class Main { /** * Entry point for embedded applications . This method attaches
* to the given { @ link ContextFactory } with the given scope . No
* I / O redirection is performed as with { @ link # main ( String [ ] ) } . */
public static Main mainEmbedded ( ContextFactory factory , ScopeProvider scopeProvider , String title ) { } } | return mainEmbeddedImpl ( factory , scopeProvider , title ) ; |
public class JDBCResultSet { /** * < ! - - start generic documentation - - >
* Updates the designated column with a < code > java . sql . Timestamp < / code >
* value .
* The updater methods are used to update column values in the
* current row or the insert row . The updater methods do not
* update the underlying database ; instead the < code > updateRow < / code > or
* < code > insertRow < / code > methods are called to update the database .
* < ! - - end generic documentation - - >
* < ! - - start release - specific documentation - - >
* < div class = " ReleaseSpecificDocumentation " >
* < h3 > HSQLDB - Specific Information : < / h3 > < p >
* HSQLDB supports this feature . < p >
* < / div >
* < ! - - end release - specific documentation - - >
* @ param columnIndex the first column is 1 , the second is 2 , . . .
* @ param x the new column value
* @ exception SQLException if a database access error occurs ,
* the result set concurrency is < code > CONCUR _ READ _ ONLY < / code >
* or this method is called on a closed result set
* @ exception SQLFeatureNotSupportedException if the JDBC driver does not support
* this method
* @ since JDK 1.2 ( JDK 1.1 . x developers : read the overview for
* JDBCResultSet ) */
public void updateTimestamp ( int columnIndex , Timestamp x ) throws SQLException { } } | startUpdate ( columnIndex ) ; preparedStatement . setParameter ( columnIndex , x ) ; |
public class ClusterSecurityGroup { /** * A list of EC2 security groups that are permitted to access clusters associated with this cluster security group .
* @ return A list of EC2 security groups that are permitted to access clusters associated with this cluster security
* group . */
public java . util . List < EC2SecurityGroup > getEC2SecurityGroups ( ) { } } | if ( eC2SecurityGroups == null ) { eC2SecurityGroups = new com . amazonaws . internal . SdkInternalList < EC2SecurityGroup > ( ) ; } return eC2SecurityGroups ; |
public class KerasModelImport { /** * Load Keras Sequential model for which the configuration and weights were
* saved separately using calls to model . to _ json ( ) and model . save _ weights ( . . . ) .
* @ param modelJsonFilename path to JSON file storing Keras Sequential model configuration
* @ param weightsHdf5Filename path to HDF5 archive storing Keras model weights
* @ param enforceTrainingConfig whether to enforce training configuration options
* @ return MultiLayerNetwork
* @ throws IOException IO exception
* @ see MultiLayerNetwork */
public static MultiLayerNetwork importKerasSequentialModelAndWeights ( String modelJsonFilename , String weightsHdf5Filename , boolean enforceTrainingConfig ) throws IOException , InvalidKerasConfigurationException , UnsupportedKerasConfigurationException { } } | KerasSequentialModel kerasModel = new KerasSequentialModel ( ) . modelBuilder ( ) . modelJsonFilename ( modelJsonFilename ) . weightsHdf5FilenameNoRoot ( weightsHdf5Filename ) . enforceTrainingConfig ( enforceTrainingConfig ) . buildSequential ( ) ; return kerasModel . getMultiLayerNetwork ( ) ; |
public class FileEventStore { /** * Gets an array containing all of the files in the given directory .
* @ param dir A directory .
* @ return An array containing all of the files in the given directory . */
private File [ ] getFilesInDir ( File dir ) { } } | return dir . listFiles ( new FileFilter ( ) { public boolean accept ( File file ) { return file . isFile ( ) && ! file . getName ( ) . equals ( ATTEMPTS_JSON_FILE_NAME ) ; } } ) ; |
public class MessageReader { /** * Extracts the message body and interprets it
* as the given number ( e . g . Integer ) .
* @ param type The number type
* @ return The message body as the specified number */
@ SuppressWarnings ( "unchecked" ) public < T extends Number > T readBodyAsNumber ( Class < T > type ) { } } | String messageContent = readBodyAndValidateForNumber ( ) ; if ( type . equals ( BigDecimal . class ) ) { return ( T ) new BigDecimal ( messageContent ) ; } else if ( type . equals ( BigInteger . class ) ) { return ( T ) new BigInteger ( messageContent ) ; } else if ( type . equals ( Byte . class ) ) { return ( T ) Byte . valueOf ( messageContent ) ; } else if ( type . equals ( Short . class ) ) { return ( T ) Short . valueOf ( messageContent ) ; } else if ( type . equals ( Integer . class ) ) { return ( T ) Integer . valueOf ( messageContent ) ; } else if ( type . equals ( Long . class ) ) { return ( T ) Long . valueOf ( messageContent ) ; } else { throw new RuntimeException ( "Unsupported number format: " + type ) ; } |
public class StreamExecutionEnvironment { /** * Creates a data stream from the given iterator .
* < p > Because the iterator will remain unmodified until the actual execution happens ,
* the type of data returned by the iterator must be given explicitly in the form of the type
* class ( this is due to the fact that the Java compiler erases the generic type information ) .
* < p > Note that this operation will result in a non - parallel data stream source , i . e . ,
* a data stream source with a parallelism of one .
* @ param data
* The iterator of elements to create the data stream from
* @ param type
* The class of the data produced by the iterator . Must not be a generic class .
* @ param < OUT >
* The type of the returned data stream
* @ return The data stream representing the elements in the iterator
* @ see # fromCollection ( java . util . Iterator , org . apache . flink . api . common . typeinfo . TypeInformation ) */
public < OUT > DataStreamSource < OUT > fromCollection ( Iterator < OUT > data , Class < OUT > type ) { } } | return fromCollection ( data , TypeExtractor . getForClass ( type ) ) ; |
public class snmpalarm { /** * Use this API to fetch all the snmpalarm resources that are configured on netscaler . */
public static snmpalarm [ ] get ( nitro_service service ) throws Exception { } } | snmpalarm obj = new snmpalarm ( ) ; snmpalarm [ ] response = ( snmpalarm [ ] ) obj . get_resources ( service ) ; return response ; |
public class SecurityServiceImpl { /** * { @ inheritDoc } */
@ Override public UserRegistryService getUserRegistryService ( ) { } } | UserRegistryService service = userRegistryService . get ( ) ; if ( service == null ) { if ( isConfigurationDefinedInFile ( ) ) { String id = getEffectiveSecurityConfiguration ( ) . getUserRegistryServiceId ( ) ; service = getUserRegistryService ( id ) ; } else { service = autoDetectService ( KEY_USERREGISTRY , userRegistry ) ; } // remember the user registry
userRegistryService . set ( service ) ; } return service ; |
public class FactoryKernelGaussian { /** * Creates a floating point Gaussian kernel with the sigma and radius .
* If normalized is set to true then the elements in the kernel will sum up to one .
* @ param sigma Distributions standard deviation .
* @ param radius Kernel ' s radius .
* @ param odd Does the kernel have an even or add width
* @ param normalize If the kernel should be normalized to one or not . */
protected static Kernel1D_F32 gaussian1D_F32 ( double sigma , int radius , boolean odd , boolean normalize ) { } } | Kernel1D_F32 ret ; if ( odd ) { ret = new Kernel1D_F32 ( radius * 2 + 1 ) ; int index = 0 ; for ( int i = radius ; i >= - radius ; i -- ) { ret . data [ index ++ ] = ( float ) UtilGaussian . computePDF ( 0 , sigma , i ) ; } } else { ret = new Kernel1D_F32 ( radius * 2 ) ; int index = 0 ; for ( int i = radius ; i > - radius ; i -- ) { ret . data [ index ++ ] = ( float ) UtilGaussian . computePDF ( 0 , sigma , i - 0.5 ) ; } } if ( normalize ) { KernelMath . normalizeSumToOne ( ret ) ; } return ret ; |
public class CmsModelPageHelper { /** * Disables the given model page . < p >
* @ param sitemapConfig the configuration resource
* @ param structureId the model page id
* @ param disabled < code > true < / code > to disabe the entry
* @ throws CmsException if something goes wrong */
public void disableModelPage ( CmsResource sitemapConfig , CmsUUID structureId , boolean disabled ) throws CmsException { } } | CmsFile sitemapConfigFile = m_cms . readFile ( sitemapConfig ) ; CmsXmlContent content = CmsXmlContentFactory . unmarshal ( m_cms , sitemapConfigFile ) ; CmsConfigurationReader reader = new CmsConfigurationReader ( m_cms ) ; reader . parseConfiguration ( m_adeConfig . getBasePath ( ) , content ) ; List < CmsModelPageConfig > modelPageConfigs = reader . getModelPageConfigs ( ) ; int i = 0 ; for ( CmsModelPageConfig config : modelPageConfigs ) { if ( config . getResource ( ) . getStructureId ( ) . equals ( structureId ) ) { break ; } i += 1 ; } I_CmsXmlContentValue value ; if ( i < modelPageConfigs . size ( ) ) { value = content . getValue ( CmsConfigurationReader . N_MODEL_PAGE , Locale . ENGLISH , i ) ; } else { value = content . addValue ( m_cms , CmsConfigurationReader . N_MODEL_PAGE , Locale . ENGLISH , i ) ; String linkValuePath = value . getPath ( ) + "/" + CmsConfigurationReader . N_MODEL_PAGE ; I_CmsXmlContentValue linkValue = content . hasValue ( linkValuePath , Locale . ENGLISH ) ? content . getValue ( linkValuePath , Locale . ENGLISH ) : content . addValue ( m_cms , linkValuePath , Locale . ENGLISH , 0 ) ; CmsResource model = m_cms . readResource ( structureId , CmsResourceFilter . IGNORE_EXPIRATION ) ; linkValue . setStringValue ( m_cms , m_cms . getSitePath ( model ) ) ; } String disabledPath = value . getPath ( ) + "/" + CmsConfigurationReader . N_DISABLED ; I_CmsXmlContentValue disabledValue = content . hasValue ( disabledPath , Locale . ENGLISH ) ? content . getValue ( disabledPath , Locale . ENGLISH ) : content . addValue ( m_cms , disabledPath , Locale . ENGLISH , 0 ) ; disabledValue . setStringValue ( m_cms , Boolean . toString ( disabled ) ) ; writeSitemapConfig ( content , sitemapConfigFile ) ; |
public class GregorianMath { /** * / * [ deutsch ]
* < p > Ermittelt das modifizierte julianische Datum . < / p >
* @ param year proleptic iso year [ ( - 99999 ) - 99999]
* @ param month gregorian month ( 1-12)
* @ param dayOfMonth day of month in range ( 1-31)
* @ return days since [ 1858-11-17 ] ( modified Julian date )
* @ throws IllegalArgumentException if any argument is out of range */
public static long toMJD ( int year , int month , int dayOfMonth ) { } } | checkDate ( year , month , dayOfMonth ) ; long y = year ; int m = month ; if ( m < 3 ) { y -- ; m += 12 ; } long days = ( ( y * 365 ) + Math . floorDiv ( y , 4 ) + ( ( ( m + 1 ) * 153 ) / 5 ) - 123 + dayOfMonth ) ; if ( ( year >= 1901 ) && ( year < 2100 ) ) { days -= 15 ; } else { days = days - Math . floorDiv ( y , 100 ) + Math . floorDiv ( y , 400 ) ; } return days - OFFSET ; |
public class ProtoParser { /** * Defaults aren ' t options . This finds an option named " default " , removes , and returns it . Returns
* null if no default option is present . */
private @ Nullable String stripDefault ( List < OptionElement > options ) { } } | String result = null ; for ( Iterator < OptionElement > i = options . iterator ( ) ; i . hasNext ( ) ; ) { OptionElement option = i . next ( ) ; if ( option . getName ( ) . equals ( "default" ) ) { i . remove ( ) ; result = String . valueOf ( option . getValue ( ) ) ; // Defaults aren ' t options !
} } return result ; |
public class RunTime { /** * Add one run time to a specified detail record . < br >
* 给指定的详细记录增加一次RunTime 。
* @ param descDescription of the detail record . < br >
* 详细记录的Description
* @ param milliStartTimeStart time in milliseconds ( usually from System . currentTimeMillis ( ) )
* @ param nanoDurationTimeRun time duration in nanoseconds . */
public void addDetail ( String desc , long milliStartTime , long nanoDurationTime ) { } } | this . getDetail ( desc ) . add ( milliStartTime , nanoDurationTime ) ; |
public class CommandLineArgumentParser { /** * helper to deal with the case of special flags that are evaluated before the options are properly set */
private boolean isSpecialFlagSet ( final OptionSet parsedArguments , final String flagName ) { } } | if ( parsedArguments . has ( flagName ) ) { Object value = parsedArguments . valueOf ( flagName ) ; return ( value == null || ! value . equals ( "false" ) ) ; } else { return false ; } |
public class CassQuery { /** * Prepare index clause .
* @ param m
* the m
* @ param isQueryForInvertedIndex
* the is query for inverted index
* @ return the map */
Map < Boolean , List < IndexClause > > prepareIndexClause ( EntityMetadata m , boolean isQueryForInvertedIndex ) { } } | IndexClause indexClause = new IndexClause ( new ArrayList < IndexExpression > ( ) , ByteBufferUtil . EMPTY_BYTE_BUFFER , maxResult ) ; List < IndexClause > clauses = new ArrayList < IndexClause > ( ) ; List < IndexExpression > expr = new ArrayList < IndexExpression > ( ) ; Map < Boolean , List < IndexClause > > idxClauses = new HashMap < Boolean , List < IndexClause > > ( 1 ) ; // check if id column are mixed with other columns or not ?
String idColumn = ( ( AbstractAttribute ) m . getIdAttribute ( ) ) . getJPAColumnName ( ) ; boolean idPresent = false ; if ( log . isInfoEnabled ( ) ) { log . info ( "Preparing index clause for query {}" , getJPAQuery ( ) ) ; } for ( Object o : getKunderaQuery ( ) . getFilterClauseQueue ( ) ) { if ( o instanceof FilterClause ) { FilterClause clause = ( ( FilterClause ) o ) ; String fieldName = clause . getProperty ( ) ; // in case id column matches with field name , set it for first
// time .
if ( ! idPresent && idColumn . equalsIgnoreCase ( fieldName ) ) { idPresent = true ; } String condition = clause . getCondition ( ) ; List < Object > value = clause . getValue ( ) ; if ( value != null && value . size ( ) > 1 ) { log . error ( "IN clause is not enabled for thrift, use cql3." ) ; throw new QueryHandlerException ( "IN clause is not enabled for thrift, use cql3." ) ; } IndexOperator operator = getOperator ( condition , idPresent ) ; IndexExpression expression = new IndexExpression ( ByteBufferUtil . bytes ( fieldName ) , operator , getBytesValue ( fieldName , m , value . get ( 0 ) ) ) ; expr . add ( expression ) ; } else { // Case of AND and OR clause .
String opr = o . toString ( ) ; if ( opr . equalsIgnoreCase ( "or" ) ) { log . error ( "Support for OR clause is not enabled within cassandra." ) ; throw new QueryHandlerException ( "Unsupported clause " + opr + " for cassandra." ) ; } } } if ( ! StringUtils . isBlank ( getKunderaQuery ( ) . getFilter ( ) ) ) { indexClause . setExpressions ( expr ) ; clauses . add ( indexClause ) ; } idxClauses . put ( idPresent , clauses ) ; return idxClauses ; |
public class EvolutionResult { /** * Return a mapping function , which removes duplicate individuals from the
* population and replaces it with newly created one by the given genotype
* { @ code factory } .
* < pre > { @ code
* final Problem < Double , DoubleGene , Integer > problem = . . . ;
* final Engine < DoubleGene , Integer > engine = Engine . builder ( problem )
* . mapping ( EvolutionResult . toUniquePopulation ( problem . codec ( ) . encoding ( ) ) )
* . build ( ) ;
* final Genotype < DoubleGene > best = engine . stream ( )
* . limit ( 100 ) ;
* . collect ( EvolutionResult . toBestGenotype ( ) ) ;
* } < / pre >
* @ since 4.0
* @ see Engine . Builder # mapping ( Function )
* @ param factory the genotype factory which create new individuals
* @ param < G > the gene type
* @ param < C > the fitness function result type
* @ return a mapping function , which removes duplicate individuals from the
* population
* @ throws NullPointerException if the given genotype { @ code factory } is
* { @ code null } */
public static < G extends Gene < ? , G > , C extends Comparable < ? super C > > UnaryOperator < EvolutionResult < G , C > > toUniquePopulation ( final Factory < Genotype < G > > factory ) { } } | return toUniquePopulation ( factory , 100 ) ; |
public class CmsSitemapTreeNode { /** * Shows or hides the opener button . < p >
* @ param visible true if the opener should be shown , else false */
public void setOpenerVisible ( boolean visible ) { } } | if ( visible ) { m_opener . removeStyleName ( OpenCmsTheme . BUTTON_INVISIBLE ) ; } else { m_opener . addStyleName ( OpenCmsTheme . BUTTON_INVISIBLE ) ; } |
public class StandardSocketServer { /** * Starts the service . Instantiates a server socket and starts a thread that
* handles incoming client connections . */
public void start ( ) throws ConfigurationException { } } | if ( connectionFactory == null ) { throw new ConfigurationException ( "can not start without client socket factory" ) ; } try { server = new ServerSocket ( port ) ; } catch ( IOException e ) { System . out . println ( new LogEntry ( e . getMessage ( ) , e ) ) ; throw new ConfigurationException ( "Cannot start server at port " + port , e ) ; } System . out . println ( new LogEntry ( "starting socket server at port " + port ) ) ; serverThread = new Thread ( this ) ; serverThread . start ( ) ; |
public class TransactionOutPoint { /** * Returns the RedeemData identified in the connected output , for either P2PKH , P2WPKH , P2PK
* or P2SH scripts .
* If the script forms cannot be understood , throws ScriptException .
* @ return a RedeemData or null if the connected data cannot be found in the wallet . */
@ Nullable public RedeemData getConnectedRedeemData ( KeyBag keyBag ) throws ScriptException { } } | TransactionOutput connectedOutput = getConnectedOutput ( ) ; checkNotNull ( connectedOutput , "Input is not connected so cannot retrieve key" ) ; Script connectedScript = connectedOutput . getScriptPubKey ( ) ; if ( ScriptPattern . isP2PKH ( connectedScript ) ) { byte [ ] addressBytes = ScriptPattern . extractHashFromP2PKH ( connectedScript ) ; return RedeemData . of ( keyBag . findKeyFromPubKeyHash ( addressBytes , Script . ScriptType . P2PKH ) , connectedScript ) ; } else if ( ScriptPattern . isP2WPKH ( connectedScript ) ) { byte [ ] addressBytes = ScriptPattern . extractHashFromP2WH ( connectedScript ) ; return RedeemData . of ( keyBag . findKeyFromPubKeyHash ( addressBytes , Script . ScriptType . P2WPKH ) , connectedScript ) ; } else if ( ScriptPattern . isP2PK ( connectedScript ) ) { byte [ ] pubkeyBytes = ScriptPattern . extractKeyFromP2PK ( connectedScript ) ; return RedeemData . of ( keyBag . findKeyFromPubKey ( pubkeyBytes ) , connectedScript ) ; } else if ( ScriptPattern . isP2SH ( connectedScript ) ) { byte [ ] scriptHash = ScriptPattern . extractHashFromP2SH ( connectedScript ) ; return keyBag . findRedeemDataFromScriptHash ( scriptHash ) ; } else { throw new ScriptException ( ScriptError . SCRIPT_ERR_UNKNOWN_ERROR , "Could not understand form of connected output script: " + connectedScript ) ; } |
public class AfplibFactoryImpl { /** * < ! - - begin - user - doc - - >
* < ! - - end - user - doc - - >
* @ generated */
public FNCXUnitBase createFNCXUnitBaseFromString ( EDataType eDataType , String initialValue ) { } } | FNCXUnitBase result = FNCXUnitBase . get ( initialValue ) ; if ( result == null ) throw new IllegalArgumentException ( "The value '" + initialValue + "' is not a valid enumerator of '" + eDataType . getName ( ) + "'" ) ; return result ; |
public class PrimaveraPMFileReader { /** * Render a zero Double as null .
* @ param value double value
* @ return null if the double value is zero */
private Double zeroIsNull ( Double value ) { } } | if ( value != null && value . doubleValue ( ) == 0 ) { value = null ; } return value ; |
public class NamingUtils { /** * Converts snake case string ( lower or upper ) to camel case ,
* for example ' hello _ world ' or ' HELLO _ WORLD ' - > ' helloWorld ' or ' HelloWorld ' .
* @ param snake Input string .
* @ param upper True if result snake cased string should be upper cased like ' HelloWorld ' . */
public static String snakeToCamel ( String snake , boolean upper ) { } } | StringBuilder sb = new StringBuilder ( ) ; boolean firstWord = true ; for ( String word : snake . split ( "_" ) ) { if ( ! word . isEmpty ( ) ) { if ( firstWord && ! upper ) { sb . append ( word . toLowerCase ( ) ) ; } else { sb . append ( Character . toUpperCase ( word . charAt ( 0 ) ) ) . append ( word . substring ( 1 ) . toLowerCase ( ) ) ; } firstWord = false ; } } return sb . toString ( ) ; |
public class TimerNpImpl { /** * Returns the timer reference that was represented by a TimerHandle
* obtained from { @ link # getSerializableObject ( ) } . For non - persistent
* timers , a serialized TimerHandle always represents a Timer ; never
* a TimerHandle . < p >
* This method is intended for use by the Stateful passivation code , when
* a Stateful EJB is being passivated , and contains a Timer ( not a
* Serializable object ) . < p >
* Note : if the timer represented by the TimerHandle no longer
* exists , a destroyed timer will still be returned . < p >
* @ param taskId the TaskId from the requesting TimerHandle .
* @ return a reference to the Timer represented by the TaskId . */
protected static Timer getDeserializedTimer ( BeanId beanId , String taskId ) { } } | // Look first for existing timer ( in all 3 places )
// If not found , THEN new TimerNpImpl , but with new ctor to set
// ivDestroyed = true , since this timer will never run
// F743-22582
// A stateful session bean may have a reference to a non - persistent Timer .
// By definition , a non - persistent Timer only exists in the JVM its defined
// in , and so if the stateful bean is failed over to another server , the
// Timer is no longer valid .
// In the failover scenario , we still want to hydrate that instance variable
// in the stateful bean with a Timer instance ( ie , we don ' t want that variable
// to be null ) . . . but that Timer instance must be invalid , such that if the
// user invokes a method on it , they get a NoSuchObjectLocalException error .
// In the failover scenario , this code ( which is attempting to rehydrate the Timer )
// will be running on a different server than the one the TimerNpImpl instance
// was created on . Therefore , the TimerNpImpl instance we are looking for will
// not be in the server - specific map we are dealing with , and so we ' ll bring back
// a new TimerNpImpl instance which knows its not valid , and which produces the
// desired NoSuchObjectLocalException when a method is invoked on it .
Timer timer ; synchronized ( svActiveTimers ) { timer = svActiveTimers . get ( taskId ) ; if ( timer != null ) { if ( TraceComponent . isAnyTracingEnabled ( ) && tc . isDebugEnabled ( ) ) Tr . debug ( tc , "getDeserializedTimer: found in active timer map : " + timer ) ; return timer ; } } EJSHome home = ( EJSHome ) beanId . home ; ContainerTx containerTx = home . container . getCurrentContainerTx ( ) ; if ( containerTx != null ) { if ( containerTx . timersQueuedToStart != null ) { timer = containerTx . timersQueuedToStart . get ( taskId ) ; if ( timer != null ) { if ( TraceComponent . isAnyTracingEnabled ( ) && tc . isDebugEnabled ( ) ) Tr . debug ( tc , "getDeserializedTimer: found in timersQueuedToStart : " + timer ) ; return timer ; } } if ( containerTx . timersCanceled != null ) { timer = containerTx . timersCanceled . get ( taskId ) ; if ( timer != null ) { if ( TraceComponent . isAnyTracingEnabled ( ) && tc . isDebugEnabled ( ) ) Tr . debug ( tc , "getDeserializedTimer: found in timersCanceled : " + timer ) ; return timer ; } } } // Since timer was not found to exist , instantiate a dummy in the
// destroyed state that will fail as expected when accessed .
timer = new TimerNpImpl ( beanId , taskId ) ; if ( TraceComponent . isAnyTracingEnabled ( ) && tc . isDebugEnabled ( ) ) Tr . debug ( tc , "getDeserializedTimer: not found - returning destroyed Timer : " + timer ) ; return timer ; |
public class ResourceBundlesHandlerImpl { /** * ( non - Javadoc )
* @ see
* net . jawr . web . resource . bundle . handler . ResourceBundlesHandler # writeBundleTo
* ( java . lang . String , java . io . Writer ) */
@ Override public void writeBundleTo ( String bundlePath , Writer writer ) throws ResourceNotFoundException { } } | Reader rd = null ; try { // If debug mode is on , resources are retrieved one by one .
if ( config . isDebugModeOn ( ) ) { rd = resourceHandler . getResource ( null , bundlePath ) ; } else { for ( String prefix : bundlePrefixes ) { if ( bundlePath . startsWith ( prefix ) ) { bundlePath = bundlePath . substring ( prefix . length ( ) ) ; break ; } } // Prefixes are used only in production mode
String path = PathNormalizer . removeVariantPrefixFromPath ( bundlePath ) ; rd = resourceBundleHandler . getResourceBundleReader ( path ) ; if ( liveProcessBundles . contains ( path ) ) { rd = processInLive ( rd ) ; } } IOUtils . copy ( rd , writer ) ; writer . flush ( ) ; } catch ( IOException e ) { throw new BundlingProcessException ( "Unexpected IOException writing bundle[" + bundlePath + "]" , e ) ; } finally { IOUtils . close ( rd ) ; IOUtils . close ( writer ) ; } |
public class DeprecationStatus { /** * Returns the timestamp ( in milliseconds since epoch ) on or after which the deprecation state of
* this resource will be changed to { @ link Status # DEPRECATED } . Returns { @ code null } if not set .
* @ throws IllegalStateException if { @ link # getDeprecated ( ) } is not a valid date , time or datetime */
public Long getDeprecatedMillis ( ) { } } | try { return deprecated != null ? TIMESTAMP_FORMATTER . parse ( deprecated , Instant . FROM ) . toEpochMilli ( ) : null ; } catch ( DateTimeParseException ex ) { throw new IllegalStateException ( ex . getMessage ( ) , ex ) ; } |
public class TextAnalyticsImpl { /** * The API returns the detected language and a numeric score between 0 and 1.
* Scores close to 1 indicate 100 % certainty that the identified language is true . A total of 120 languages are supported .
* @ param documents the List & lt ; Input & gt ; value
* @ throws IllegalArgumentException thrown if parameters fail the validation
* @ return the observable to the LanguageBatchResult object */
public Observable < ServiceResponse < LanguageBatchResult > > detectLanguageWithServiceResponseAsync ( List < Input > documents ) { } } | if ( this . client . azureRegion ( ) == null ) { throw new IllegalArgumentException ( "Parameter this.client.azureRegion() is required and cannot be null." ) ; } Validator . validate ( documents ) ; BatchInput input = new BatchInput ( ) ; input . withDocuments ( documents ) ; String parameterizedHost = Joiner . on ( ", " ) . join ( "{AzureRegion}" , this . client . azureRegion ( ) ) ; return service . detectLanguage ( this . client . acceptLanguage ( ) , input , parameterizedHost , this . client . userAgent ( ) ) . flatMap ( new Func1 < Response < ResponseBody > , Observable < ServiceResponse < LanguageBatchResult > > > ( ) { @ Override public Observable < ServiceResponse < LanguageBatchResult > > call ( Response < ResponseBody > response ) { try { ServiceResponse < LanguageBatchResult > clientResponse = detectLanguageDelegate ( response ) ; return Observable . just ( clientResponse ) ; } catch ( Throwable t ) { return Observable . error ( t ) ; } } } ) ; |
public class Shortcode { /** * Parse an arbitrary string .
* @ param str The string .
* @ param handler The handler for parse events . */
public static void parse ( final String str , final ShortcodeParser . Handler handler ) { } } | ShortcodeParser . parse ( str , handler ) ; |
public class PropertiesWriter { /** * Appends a property to be written .
* @ param key key of property
* @ param value value of property
* @ return self for a fluent api
* @ throws NullArgumentException if key is null or empty */
public PropertiesWriter append ( final String key , final String value ) { } } | NullArgumentException . validateNotEmpty ( key , "Key" ) ; String valueToAdd = value ; if ( value == null ) { valueToAdd = "" ; } Integer position = m_positions . get ( key ) ; List < String > values = m_values . get ( key ) ; if ( values == null ) { values = new ArrayList < String > ( ) ; m_values . put ( key , values ) ; } values . add ( valueToAdd ) ; StringBuilder builder = new StringBuilder ( ) . append ( key ) . append ( "=" ) ; if ( values . size ( ) == 1 ) { builder . append ( valueToAdd ) ; } else { builder . append ( "\\\n" ) ; String trail = null ; for ( String storedValue : values ) { if ( trail != null ) { builder . append ( trail ) ; } builder . append ( storedValue ) ; trail = m_separator + "\\\n" ; } } if ( position == null ) { m_content . add ( builder . toString ( ) ) ; m_positions . put ( key , m_content . size ( ) - 1 ) ; } else { m_content . set ( position , builder . toString ( ) ) ; } return this ; |
public class MessageProcessor { /** * This lifecycle phase is implemented by invoking the { @ link Mp # shouldBeEvicted ( ) } method on the instance
* @ see MessageProcessorLifecycle # invokeEvictable ( Object ) */
@ Override public boolean invokeEvictable ( final Mp instance ) throws DempsyException { } } | try { return instance . shouldBeEvicted ( ) ; } catch ( final RuntimeException rte ) { throw new DempsyException ( rte , true ) ; } |
public class FodselsnummerCalculator { /** * Returns a List with valid Fodselsnummer instances for a given Date and gender . */
public static List < Fodselsnummer > getFodselsnummerForDateAndGender ( Date date , KJONN kjonn ) { } } | List < Fodselsnummer > result = getManyFodselsnummerForDate ( date ) ; splitByGender ( kjonn , result ) ; return result ; |
public class ObjectFactory { /** * Create an instance of { @ link JAXBElement } { @ code < } { @ link TimeTopologyComplexType } { @ code > }
* @ param value
* Java instance representing xml element ' s value .
* @ return
* the new instance of { @ link JAXBElement } { @ code < } { @ link TimeTopologyComplexType } { @ code > } */
@ XmlElementDecl ( namespace = "http://www.opengis.net/gml" , name = "TimeTopologyComplex" , substitutionHeadNamespace = "http://www.opengis.net/gml" , substitutionHeadName = "_TimeComplex" ) public JAXBElement < TimeTopologyComplexType > createTimeTopologyComplex ( TimeTopologyComplexType value ) { } } | return new JAXBElement < TimeTopologyComplexType > ( _TimeTopologyComplex_QNAME , TimeTopologyComplexType . class , null , value ) ; |
public class References { /** * Gets all component references that match specified locator and matching to
* the specified type .
* @ param type the Class type that defined the type of the result .
* @ param locator the locator to find references by .
* @ return a list with matching component references or empty list if nothing
* was found . */
public < T > List < T > getOptional ( Class < T > type , Object locator ) { } } | try { return find ( type , locator , false ) ; } catch ( Exception ex ) { return new ArrayList < T > ( ) ; } |
public class AbstractEviction { /** * Exceptions have the minimum weight . */
private long calculateWeight ( final Entry e , final Object v ) { } } | long _weight ; if ( v instanceof ExceptionWrapper ) { _weight = 1 ; } else { _weight = weigher . weigh ( e . getKey ( ) , v ) ; } if ( _weight < 0 ) { throw new IllegalArgumentException ( "weight must be positive." ) ; } return _weight ; |
public class PersistentExecutorImpl { /** * { @ inheritDoc } */
@ Override public boolean setProperty ( String name , String value ) { } } | if ( value == null || value . length ( ) == 0 ) throw new IllegalArgumentException ( "value: " + value ) ; boolean exists = false ; if ( name != null && name . length ( ) > 0 ) { TransactionController tranController = new TransactionController ( ) ; try { tranController . preInvoke ( ) ; exists = taskStore . setProperty ( name , value ) ; } catch ( Throwable x ) { tranController . setFailure ( x ) ; } finally { PersistentStoreException x = tranController . postInvoke ( PersistentStoreException . class ) ; if ( x != null ) throw x ; } } return exists ; |
public class BaseTransport { /** * Convert this encoded string back to a Java Object .
* @ param string The string to convert .
* @ return The java object . */
public Object stringToObject ( String string ) { } } | Object obj = BaseTransport . convertStringToObject ( string ) ; return obj ; |
public class Tuple5 { /** * Creates a new tuple and assigns the given values to the tuple ' s fields .
* This is more convenient than using the constructor , because the compiler can
* infer the generic type arguments implicitly . For example :
* { @ code Tuple3 . of ( n , x , s ) }
* instead of
* { @ code new Tuple3 < Integer , Double , String > ( n , x , s ) } */
public static < T0 , T1 , T2 , T3 , T4 > Tuple5 < T0 , T1 , T2 , T3 , T4 > of ( T0 value0 , T1 value1 , T2 value2 , T3 value3 , T4 value4 ) { } } | return new Tuple5 < > ( value0 , value1 , value2 , value3 , value4 ) ; |
public class MetricsUtil { /** * Escapes a user - supplied string value that is to be used as metrics key
* tag or value .
* Prefixes comma ( { @ code " , " } ) , equals sign ( { @ code " = " } ) and backslash
* ( { @ code " \ " } ) with another backslash . */
@ Nonnull public static String escapeMetricNamePart ( @ Nonnull String namePart ) { } } | int i = 0 ; int l = namePart . length ( ) ; while ( i < l ) { char ch = namePart . charAt ( i ) ; if ( ch == ',' || ch == '=' || ch == '\\' ) { break ; } i ++ ; } if ( i == l ) { return namePart ; } StringBuilder sb = new StringBuilder ( namePart . length ( ) + 3 ) ; sb . append ( namePart , 0 , i ) ; while ( i < l ) { char ch = namePart . charAt ( i ++ ) ; if ( ch == ',' || ch == '=' || ch == '\\' ) { sb . append ( '\\' ) ; } sb . append ( ch ) ; } return sb . toString ( ) ; |
public class GosuStringUtil { /** * < p > Find the first index of any of a set of potential substrings . < / p >
* < p > A < code > null < / code > String will return < code > - 1 < / code > .
* A < code > null < / code > or zero length search array will return < code > - 1 < / code > .
* A < code > null < / code > search array entry will be ignored , but a search
* array containing " " will return < code > 0 < / code > if < code > str < / code > is not
* null . This method uses { @ link String # indexOf ( String ) } . < / p >
* < pre >
* GosuStringUtil . indexOfAny ( null , * ) = - 1
* GosuStringUtil . indexOfAny ( * , null ) = - 1
* GosuStringUtil . indexOfAny ( * , [ ] ) = - 1
* GosuStringUtil . indexOfAny ( " zzabyycdxx " , [ " ab " , " cd " ] ) = 2
* GosuStringUtil . indexOfAny ( " zzabyycdxx " , [ " cd " , " ab " ] ) = 2
* GosuStringUtil . indexOfAny ( " zzabyycdxx " , [ " mn " , " op " ] ) = - 1
* GosuStringUtil . indexOfAny ( " zzabyycdxx " , [ " zab " , " aby " ] ) = 1
* GosuStringUtil . indexOfAny ( " zzabyycdxx " , [ " " ] ) = 0
* GosuStringUtil . indexOfAny ( " " , [ " " ] ) = 0
* GosuStringUtil . indexOfAny ( " " , [ " a " ] ) = - 1
* < / pre >
* @ param str the String to check , may be null
* @ param searchStrs the Strings to search for , may be null
* @ return the first index of any of the searchStrs in str , - 1 if no match */
public static int indexOfAny ( String str , String [ ] searchStrs ) { } } | if ( ( str == null ) || ( searchStrs == null ) ) { return - 1 ; } int sz = searchStrs . length ; // String ' s can ' t have a MAX _ VALUEth index .
int ret = Integer . MAX_VALUE ; int tmp = 0 ; for ( int i = 0 ; i < sz ; i ++ ) { String search = searchStrs [ i ] ; if ( search == null ) { continue ; } tmp = str . indexOf ( search ) ; if ( tmp == - 1 ) { continue ; } if ( tmp < ret ) { ret = tmp ; } } return ( ret == Integer . MAX_VALUE ) ? - 1 : ret ; |
public class StatusReference { /** * Start constructing a new { @ link StatusReference } .
* @ param statusUrl the status url for the job
* @ return partially constructed { @ link StatusReference } which
* must be completed with a status query token using
* { @ link StatusUrlContruction # withStatusQueryToken ( String ) . withStatusQueryToken ( token ) } */
public static StatusUrlContruction ofUrl ( final String statusUrl ) { } } | return new StatusUrlContruction ( ) { @ Override public StatusReference withStatusQueryToken ( String token ) { return new StatusReference ( statusUrl , token ) ; } } ; |
public class Fat { /** * Allocate a cluster for a new file
* @ return long the number of the newly allocated cluster
* @ throws IOException if there are no free clusters */
public long allocNew ( ) throws IOException { } } | int i ; int entryIndex = - 1 ; for ( i = lastAllocatedCluster ; i < lastClusterIndex ; i ++ ) { if ( isFreeCluster ( i ) ) { entryIndex = i ; break ; } } if ( entryIndex < 0 ) { for ( i = FIRST_CLUSTER ; i < lastAllocatedCluster ; i ++ ) { if ( isFreeCluster ( i ) ) { entryIndex = i ; break ; } } } if ( entryIndex < 0 ) { throw new IOException ( "FAT Full (" + ( lastClusterIndex - FIRST_CLUSTER ) + ", " + i + ")" ) ; // NOI18N
} entries [ entryIndex ] = fatType . getEofMarker ( ) ; lastAllocatedCluster = entryIndex % lastClusterIndex ; if ( lastAllocatedCluster < FIRST_CLUSTER ) lastAllocatedCluster = FIRST_CLUSTER ; return entryIndex ; |
public class SignatureUtil { /** * Scans the given string for a type argument signature starting at the given
* index and returns the index of the last character .
* < pre >
* TypeArgumentSignature :
* < b > & # 42 ; < / b >
* | < b > + < / b > TypeSignature
* | < b > - < / b > TypeSignature
* | TypeSignature
* < / pre >
* Note that although base types are not allowed in type arguments , there is
* no syntactic ambiguity . This method will accept them without complaint .
* @ param string the signature string
* @ param start the 0 - based character index of the first character
* @ return the 0 - based character index of the last character
* @ exception IllegalArgumentException if this is not a type argument signature */
static int scanTypeArgumentSignature ( String string , int start ) { } } | // need a minimum 1 char
if ( start >= string . length ( ) ) { throw new IllegalArgumentException ( ) ; } char c = string . charAt ( start ) ; switch ( c ) { case C_STAR : return start ; case C_EXTENDS : case C_SUPER : return scanTypeBoundSignature ( string , start ) ; default : return scanTypeSignature ( string , start ) ; } |
public class EventTimeTrigger { /** * If a watermark arrives , we need to check all pending windows .
* If any of the pending window suffices , we should fire immediately by registering a timer without delay .
* Otherwise we register a timer whose time is the window end plus max lag time */
@ Override public TriggerResult onElement ( Object element , long timestamp , TimeWindow window , TriggerContext ctx ) { } } | ctx . registerEventTimeTimer ( window . getEnd ( ) + ctx . getMaxLagMs ( ) , window ) ; return TriggerResult . CONTINUE ; |
public class MultiMEProxyHandler { /** * Adds a message back into the Pool of available messages .
* @ param messageHandler The message handler to add back to the pool */
void addMessageHandler ( SubscriptionMessageHandler messageHandler ) { } } | if ( TraceComponent . isAnyTracingEnabled ( ) && tc . isEntryEnabled ( ) ) SibTr . entry ( tc , "addMessageHandler" , messageHandler ) ; final boolean inserted = _subscriptionMessagePool . add ( messageHandler ) ; // If the message wasn ' t inserted , then the pool was exceeded
if ( ! inserted ) if ( TraceComponent . isAnyTracingEnabled ( ) && tc . isDebugEnabled ( ) ) SibTr . debug ( tc , "SubscriptionObjectPool size exceeded" ) ; if ( TraceComponent . isAnyTracingEnabled ( ) && tc . isEntryEnabled ( ) ) SibTr . exit ( tc , "addMessageHandler" ) ; |
public class WSEJBWrapper { /** * Performs all EJB Container processing required prior to invoking
* the specified EJB method . < p >
* This method will establish the proper EJB contexts for the method
* call ; including the Security context , Transaction context ,
* and Naming context ( java : comp / env ) , and the thread context
* classloader . < p >
* If this method fails ( exception thrown ) then the EJB contexts
* and environment has not been properly setup , and no attempt
* should be made to invoke the ejb , interceptors , or handlers . < p >
* The method ejbPostInvoke MUST be called after calling this method ;
* to remove the EJB contexts from the current thread . This is true
* even if this method fails with an exception . < p >
* Note that the method arguments would normally be required for
* EJB Container preInvoke processing , to properly determine JACC
* security authorization , except the JACC specification , in section
* 4.6.1.5 states the following : < p >
* All EJB containers must register a PolicyContextHandler whose
* getContext method returns an array of objects ( Object [ ] ) containing
* the arguments of the EJB method invocation ( in the same order as
* they appear in the method signature ) when invoked with the key
* " javax . ejb . arguments " . The context handler must return the value
* null when called in the context of a SOAP request that arrived at
* the ServiceEndpoint method interface . < p >
* @ param method A reflection Method object which provides the method
* name and signature of the EJB method that will be
* invoked . This may be a Method of either an EJB
* interface or the EJB implementation class .
* @ param context The MessageContext which should be returned when
* InvocationContext . getContextData ( ) is called .
* @ return an object which may be invoked as though it were an
* instance of the EJB . It will be a wrapper / proxy object
* when there are EJB interceptors .
* @ throws RemoteException when a system level error occurs . */
public Object ejbPreInvoke ( Method method , Map < String , Object > context ) throws RemoteException { } } | // Validate the state , and input parameters
if ( ivMethod != null ) { throw new IllegalStateException ( "WSEJBEndpointManager.ejbPreInvoke called previously : " + ivMethod . getName ( ) ) ; } if ( method == null ) { throw new IllegalArgumentException ( "WSEJBEndpointManager.ejbPreInvoke requires a method" ) ; } if ( TraceComponent . isAnyTracingEnabled ( ) && tc . isEntryEnabled ( ) ) Tr . entry ( tc , "ejbPreInvoke : " + method . getName ( ) ) ; Object [ ] args = null ; // per JACC spec , section 4.6.1.5
ivMethod = method ; ivMethodIndex = getMethodIndex ( method ) ; // Get the EJS Deployed Support and save the message context .
ivMethodContext = new EJSDeployedSupport ( ) ; ivMethodContext . ivContextData = context ; // d644886
// Perform normal EJB Container preInvoke processing
Object bean = container . EjbPreInvoke ( this , ivMethodIndex , ivMethodContext , args ) ; // If the bean has around invoke interceptors on any method , then
// instead of returning the bean instance , a JIT Deploy generated
// proxy object is returned , which knows how to invoke the around
// invoke interceptors , as needed . d497921
if ( bmd . ivWebServiceEndpointProxyClass != null ) { try { WSEJBProxy proxy = ( WSEJBProxy ) bmd . ivWebServiceEndpointProxyClass . newInstance ( ) ; proxy . ivContainer = container ; proxy . ivMethodContext = ivMethodContext ; proxy . ivEjbInstance = bean ; bean = proxy ; } catch ( Throwable ex ) { // This should never occur . . . only if JITDeploy generated a class
// that could be loaded , but not used . No sense logging an error ,
// this must be reported to service for a fix .
FFDCFilter . processException ( ex , CLASS_NAME + ".ejbPreInvoke" , "192" , this ) ; throw ExceptionUtil . EJBException ( "Failed to create proxy for Web service endpoint" , ex ) ; } } if ( TraceComponent . isAnyTracingEnabled ( ) && tc . isEntryEnabled ( ) ) Tr . exit ( tc , "ejbPreInvoke : " + ivMethod . getName ( ) + " : " + bean . getClass ( ) . getName ( ) ) ; return bean ; |
public class Replacer { /** * Takes all instances in text of the Pattern this was constructed with , and replaces them with substitution .
* @ param text a String , StringBuilder , or other CharSequence that may contain the text to replace
* @ return the post - replacement text */
public String replace ( CharSequence text ) { } } | TextBuffer tb = wrap ( new StringBuilder ( text . length ( ) ) ) ; replace ( pattern . matcher ( text ) , substitution , tb ) ; return tb . toString ( ) ; |
public class LinearControl { /** * Generates a FieldCase [ min , min + 1 , . . . , max - 1 , max ] for every value within the allowed
* range .
* @ return a list that contains a FieldCase for every allowed value */
@ Override protected List < FieldCase > createCases ( ) { } } | List < FieldCase > list = Lists . newArrayListWithExpectedSize ( range . getRange ( ) * 2 + 2 ) ; for ( int i = range . getMin ( ) ; i <= range . getMax ( ) ; i ++ ) { list . add ( new FieldCase ( i ) ) ; } return list ; |
public class DatabaseManagerSwing { /** * This stuff is all quick , except for the refreshTree ( ) .
* This unit can be kicked off in main Gui thread . The refreshTree
* will be backgrounded and this method will return . */
public void connect ( Connection c ) { } } | schemaFilter = null ; if ( c == null ) { return ; } if ( cConn != null ) { try { cConn . close ( ) ; } catch ( SQLException e ) { // Added : ( weconsultants @ users )
CommonSwing . errorMessage ( e ) ; } } cConn = c ; // Added : ( weconsultants @ users ) Need to barrow to get the table rowcounts
rowConn = c ; try { dMeta = cConn . getMetaData ( ) ; isOracle = ( dMeta . getDatabaseProductName ( ) . indexOf ( "Oracle" ) >= 0 ) ; sStatement = cConn . createStatement ( ) ; updateAutoCommitBox ( ) ; // Workaround for EXTREME SLOWNESS getting this info from O .
showIndexDetails = ! isOracle ; Driver driver = DriverManager . getDriver ( dMeta . getURL ( ) ) ; ConnectionSetting newSetting = new ConnectionSetting ( dMeta . getDatabaseProductName ( ) , driver . getClass ( ) . getName ( ) , dMeta . getURL ( ) , dMeta . getUserName ( ) . replaceAll ( "@localhost" , "" ) , "" ) ; Hashtable settings = ConnectionDialogCommon . loadRecentConnectionSettings ( ) ; ConnectionDialogCommon . addToRecentConnectionSettings ( settings , newSetting ) ; ConnectionDialogSwing . setConnectionSetting ( newSetting ) ; refreshTree ( ) ; clearResultPanel ( ) ; if ( fMain instanceof JApplet ) { getAppletContext ( ) . showStatus ( "JDBC Connection established to a " + dMeta . getDatabaseProductName ( ) + " v. " + dMeta . getDatabaseProductVersion ( ) + " database as '" + dMeta . getUserName ( ) + "'." ) ; } } catch ( SQLException e ) { // Added : ( weconsultants @ users )
CommonSwing . errorMessage ( e ) ; } catch ( IOException e ) { // Added : ( weconsultants @ users )
CommonSwing . errorMessage ( e ) ; } catch ( Exception e ) { CommonSwing . errorMessage ( e ) ; } |
public class FileExtractor { /** * Installs MicrosoftWebDriver . msi file as administrator in SELION _ HOME _ DIR and also deletes unwanted file and
* directory created by Msiexec .
* @ param msiFile
* the . msi file to extract
* @ return The path of installed MicrosoftWebDriver */
static String extractMsi ( String msiFile ) { } } | LOGGER . entering ( msiFile ) ; Process process = null ; String exeFilePath = null ; boolean isMsiExtracted = true ; try { process = Runtime . getRuntime ( ) . exec ( new String [ ] { "msiexec" , "/a" , msiFile , "/qn" , "TARGETDIR=" + SeLionConstants . SELION_HOME_DIR } ) ; process . waitFor ( ) ; } catch ( IOException e ) { LOGGER . log ( Level . SEVERE , "Could not find file " + msiFile , e ) ; isMsiExtracted = false ; } catch ( InterruptedException e ) { LOGGER . log ( Level . SEVERE , "Exception waiting for msiexec to be finished" , e ) ; isMsiExtracted = false ; } finally { process . destroy ( ) ; } if ( isMsiExtracted ) { moveExeFileToSeLionHomeAndDeleteExtras ( ) ; exeFilePath = FileUtils . getFile ( SeLionConstants . SELION_HOME_DIR + SeLionConstants . EDGE_DRIVER ) . getAbsolutePath ( ) ; } LOGGER . exiting ( exeFilePath ) ; return exeFilePath ; |
public class CreateDeploymentJobRequest { /** * A map that contains tag keys and tag values that are attached to the deployment job .
* @ param tags
* A map that contains tag keys and tag values that are attached to the deployment job .
* @ return Returns a reference to this object so that method calls can be chained together . */
public CreateDeploymentJobRequest withTags ( java . util . Map < String , String > tags ) { } } | setTags ( tags ) ; return this ; |
public class NoCompTreeMap { /** * right ( son = = 1 ) link . Returns the old value attached to node . */
private final V remove_node ( BinTreeNode < K , V > node , BinTreeNode < K , V > prev , int son ) { } } | if ( node . left == null ) return remove_semi_leaf ( node , prev , son , node . right ) ; if ( node . right == null ) return remove_semi_leaf ( node , prev , son , node . left ) ; // The BinTreeNode to replace node in the tree . This is either the
// next or the precedent node ( in the order of the hashCode ' s .
// We decide a bit randomly , to gain some balanceness .
BinTreeNode < K , V > m = ( node . keyHashCode % 2 == 0 ) ? extract_next ( node ) : extract_prev ( node ) ; return finish_removal ( node , prev , son , m ) ; |
public class LocalTransactionCurrentService { /** * { @ inheritDoc } */
@ Override public void beginShareable ( boolean arg0 , boolean arg1 , boolean arg2 ) throws IllegalStateException { } } | if ( ltc != null ) { ltc . beginShareable ( arg0 , arg1 , arg2 ) ; } |
public class BufferedRandomAccessFile { /** * Reads the next BUF _ SIZE bytes into the internal buffer . */
private int fillBuffer ( ) throws IOException { } } | int n = super . read ( buffer , 0 , BUF_SIZE ) ; if ( n >= 0 ) { real_pos += n ; buf_end = n ; buf_pos = 0 ; } return n ; |
public class BloomFilterTermsSet { /** * Serialize the list of terms to the { @ link StreamOutput } .
* < br >
* Given the low performance of { @ link org . elasticsearch . common . io . stream . BytesStreamOutput } when writing a large number
* of longs ( 5 to 10 times slower than writing directly to a byte [ ] ) , we use a small buffer of 8kb
* to optimise the throughput . 8kb seems to be the optimal buffer size , larger buffer size did not improve
* the throughput . */
@ Override public void writeTo ( StreamOutput out ) throws IOException { } } | // Encode flag
out . writeBoolean ( this . isPruned ( ) ) ; // Encode bloom filter
out . writeVInt ( set . numHashFunctions ) ; out . writeVInt ( set . hashing . type ( ) ) ; // hashType
out . writeVInt ( set . bits . data . length ) ; BytesRef buffer = new BytesRef ( new byte [ 1024 * 8 ] ) ; for ( long l : set . bits . data ) { Bytes . writeLong ( buffer , l ) ; if ( buffer . offset == buffer . length ) { out . write ( buffer . bytes , 0 , buffer . offset ) ; buffer . offset = 0 ; } } // flush the remaining bytes from the buffer
out . write ( buffer . bytes , 0 , buffer . offset ) ; |
public class ApacheHTTPClient { /** * This function creates the full URL from the provided values .
* @ param httpRequest
* The HTTP request to send
* @ param configuration
* HTTP client configuration
* @ return The full URL */
protected String createURL ( HTTPRequest httpRequest , HTTPClientConfiguration configuration ) { } } | // init buffer
StringBuilder buffer = new StringBuilder ( 100 ) ; // create URL
String resource = httpRequest . getResource ( ) ; this . appendBaseURL ( buffer , resource , configuration ) ; String parameters = httpRequest . getParametersText ( ) ; this . appendParameters ( buffer , parameters ) ; String url = buffer . toString ( ) ; return url ; |
public class SubscriberInspector { /** * Report the subscription methods declared on the subscriber . */
public Set < Method > subscriptionsOn ( Object subscriber ) { } } | SubscriptionMethodFilter filter = new SubscriptionMethodFilter ( ) ; Class < ? > subscriberClass = subscriber . getClass ( ) ; List < Method > methods = Arrays . asList ( subscriberClass . getMethods ( ) ) ; Set < Method > subscriptions = new HashSet < Method > ( ) ; for ( Method method : methods ) { if ( filter . accepts ( method ) ) { subscriptions . add ( method ) ; } } return subscriptions ; |
public class IconDao { /** * Query for the icon row from a style mapping row
* @ param styleMappingRow
* style mapping row
* @ return icon row */
public IconRow queryForRow ( StyleMappingRow styleMappingRow ) { } } | IconRow iconRow = null ; UserCustomRow userCustomRow = queryForIdRow ( styleMappingRow . getRelatedId ( ) ) ; if ( userCustomRow != null ) { iconRow = getRow ( userCustomRow ) ; } return iconRow ; |
public class ContentSpecParser { /** * Parse a Content Specification to put the string into usable objects that can then be validate .
* @ param contentSpec A string representation of the Content Specification .
* @ param mode The mode in which the Content Specification should be parsed .
* @ return True if everything was parsed successfully otherwise false . */
public ParserResults parse ( final String contentSpec , final ParsingMode mode ) { } } | return parse ( contentSpec , mode , false ) ; |
public class SubscriptionDefinitionImpl { /** * Returns the destination .
* @ return String */
public String getDestination ( ) { } } | if ( tc . isEntryEnabled ( ) ) { SibTr . entry ( tc , "getDestination" ) ; SibTr . exit ( tc , "getDestination" , destination ) ; } return destination ; |
public class MetadataContext { /** * Invokes { @ link DatabaseMetaData # getProcedures ( java . lang . String , java . lang . String , java . lang . String ) } with given
* arguments and returns bound information .
* @ param catalog the value for { @ code catalog } parameter
* @ param schemaPattern the value for { @ code schemaPattern } parameter
* @ param procedureNamePattern the value for { @ code procedureNamePattern } parameter
* @ return a list of procedures
* @ throws SQLException if a database error occurs . */
public List < Procedure > getProcedures ( final String catalog , final String schemaPattern , final String procedureNamePattern ) throws SQLException { } } | final List < Procedure > list = new ArrayList < > ( ) ; try ( ResultSet results = databaseMetadata . getProcedures ( catalog , schemaPattern , procedureNamePattern ) ) { if ( results != null ) { bind ( results , Procedure . class , list ) ; } } return list ; |
public class BatchUtils { /** * 批量处理切分的时候 , 返回第index个List */
private static < E > List < E > getBatchList ( Integer index , int batchSize , Collection < E > collection ) { } } | List < E > list = null ; if ( collection instanceof List ) { list = ( List < E > ) collection ; } else { list = new ArrayList < E > ( collection ) ; } if ( index == list . size ( ) / batchSize ) { return list . subList ( index * batchSize , list . size ( ) ) ; } else { return list . subList ( index * batchSize , ( index + 1 ) * batchSize ) ; } |
public class FtpClient { /** * Perform list files operation and provide file information as response .
* @ param list
* @ param context
* @ return */
protected FtpMessage listFiles ( ListCommand list , TestContext context ) { } } | String remoteFilePath = Optional . ofNullable ( list . getTarget ( ) ) . map ( ListCommand . Target :: getPath ) . map ( context :: replaceDynamicContentInString ) . orElse ( "" ) ; try { List < String > fileNames = new ArrayList < > ( ) ; FTPFile [ ] ftpFiles ; if ( StringUtils . hasText ( remoteFilePath ) ) { ftpFiles = ftpClient . listFiles ( remoteFilePath ) ; } else { ftpFiles = ftpClient . listFiles ( remoteFilePath ) ; } for ( FTPFile ftpFile : ftpFiles ) { fileNames . add ( ftpFile . getName ( ) ) ; } return FtpMessage . result ( ftpClient . getReplyCode ( ) , ftpClient . getReplyString ( ) , fileNames ) ; } catch ( IOException e ) { throw new CitrusRuntimeException ( String . format ( "Failed to list files in path '%s'" , remoteFilePath ) , e ) ; } |
public class QueryByCriteria { /** * Adds a groupby fieldName for ReportQueries .
* @ param fieldName The groupby to set */
public void addGroupBy ( String fieldName ) { } } | if ( fieldName != null ) { m_groupby . add ( new FieldHelper ( fieldName , false ) ) ; } |
public class Ifc2x3tc1FactoryImpl { /** * < ! - - begin - user - doc - - >
* < ! - - end - user - doc - - >
* @ generated */
public IfcAddressTypeEnum createIfcAddressTypeEnumFromString ( EDataType eDataType , String initialValue ) { } } | IfcAddressTypeEnum result = IfcAddressTypeEnum . get ( initialValue ) ; if ( result == null ) throw new IllegalArgumentException ( "The value '" + initialValue + "' is not a valid enumerator of '" + eDataType . getName ( ) + "'" ) ; return result ; |
public class Quicksort { /** * Routine that arranges the elements in ascending order around a pivot . This routine
* runs in O ( n ) time .
* @ param floatArray array that we want to sort
* @ param start index of the starting point to sort
* @ param end index of the end point to sort
* @ return an integer that represent the index of the pivot */
private static int partition ( float [ ] floatArray , int start , int end ) { } } | float pivot = floatArray [ end ] ; int index = start - 1 ; for ( int j = start ; j < end ; j ++ ) { if ( floatArray [ j ] <= pivot ) { index ++ ; TrivialSwap . swap ( floatArray , index , j ) ; } } TrivialSwap . swap ( floatArray , index + 1 , end ) ; return index + 1 ; |
public class DomainsInner { /** * Lists domain ownership identifiers .
* Lists domain ownership identifiers .
* @ param nextPageLink The NextLink from the previous successful call to List operation .
* @ throws IllegalArgumentException thrown if parameters fail the validation
* @ return the observable to the PagedList & lt ; DomainOwnershipIdentifierInner & gt ; object */
public Observable < ServiceResponse < Page < DomainOwnershipIdentifierInner > > > listOwnershipIdentifiersNextWithServiceResponseAsync ( final String nextPageLink ) { } } | return listOwnershipIdentifiersNextSinglePageAsync ( nextPageLink ) . concatMap ( new Func1 < ServiceResponse < Page < DomainOwnershipIdentifierInner > > , Observable < ServiceResponse < Page < DomainOwnershipIdentifierInner > > > > ( ) { @ Override public Observable < ServiceResponse < Page < DomainOwnershipIdentifierInner > > > call ( ServiceResponse < Page < DomainOwnershipIdentifierInner > > page ) { String nextPageLink = page . body ( ) . nextPageLink ( ) ; if ( nextPageLink == null ) { return Observable . just ( page ) ; } return Observable . just ( page ) . concatWith ( listOwnershipIdentifiersNextWithServiceResponseAsync ( nextPageLink ) ) ; } } ) ; |
public class FirstNonNullHelper { /** * Gets first result of function which is not null .
* @ param < T > type of values .
* @ param < R > element to return .
* @ param function function to apply to each value .
* @ param values all possible values to apply function to .
* @ return first result which was not null ,
* OR < code > null < / code > if either result for all values was < code > null < / code > or values was < code > null < / code > . */
public static < T , R > R firstNonNull ( Function < T , R > function , T [ ] values ) { } } | return values == null ? null : firstNonNull ( function , Stream . of ( values ) ) ; |
public class DroolsActivity { /** * Get knowledge base with no modifiers . */
protected KieBase getKnowledgeBase ( String name , String version ) throws ActivityException { } } | return getKnowledgeBase ( name , version , null ) ; |
public class DataUtil { /** * Method similar to { @ link # growArrayBy50Pct } , but it also ensures that
* the new size is at least as big as the specified minimum size . */
public static Object growArrayToAtLeast ( Object arr , int minLen ) { } } | if ( arr == null ) { throw new IllegalArgumentException ( NO_TYPE ) ; } Object old = arr ; int oldLen = Array . getLength ( arr ) ; int newLen = oldLen + ( ( oldLen + 1 ) >> 1 ) ; if ( newLen < minLen ) { newLen = minLen ; } arr = Array . newInstance ( arr . getClass ( ) . getComponentType ( ) , newLen ) ; System . arraycopy ( old , 0 , arr , 0 , oldLen ) ; return arr ; |
public class BaseActivity { /** * Set up a date time interpreter which will show short date values when in week view and long
* date values otherwise .
* @ param shortDate True if the date values should be short . */
private void setupDateTimeInterpreter ( final boolean shortDate ) { } } | mWeekView . setDateTimeInterpreter ( new DateTimeInterpreter ( ) { @ Override public String interpretDate ( Calendar date ) { SimpleDateFormat weekdayNameFormat = new SimpleDateFormat ( "EEE" , Locale . getDefault ( ) ) ; String weekday = weekdayNameFormat . format ( date . getTime ( ) ) ; SimpleDateFormat format = new SimpleDateFormat ( " M/d" , Locale . getDefault ( ) ) ; // All android api level do not have a standard way of getting the first letter of
// the week day name . Hence we get the first char programmatically .
// Details : http : / / stackoverflow . com / questions / 16959502 / get - one - letter - abbreviation - of - week - day - of - a - date - in - java # answer - 16959657
if ( shortDate ) weekday = String . valueOf ( weekday . charAt ( 0 ) ) ; return weekday . toUpperCase ( ) + format . format ( date . getTime ( ) ) ; } @ Override public String interpretTime ( int hour ) { return hour > 11 ? ( hour - 12 ) + " PM" : ( hour == 0 ? "12 AM" : hour + " AM" ) ; } } ) ; |
public class SensitiveUtil { /** * 初始化敏感词树
* @ param sensitiveWords 敏感词列表组成的字符串
* @ param isAsync 是否异步初始化
* @ param separator 分隔符 */
public static void init ( String sensitiveWords , char separator , boolean isAsync ) { } } | if ( StrUtil . isNotBlank ( sensitiveWords ) ) { init ( StrUtil . split ( sensitiveWords , separator ) , isAsync ) ; } |
public class BaseMessage { /** * Convert this external data format to the raw object and put it in the map .
* Typically overidden to return correctly converted data . */
public void put ( String strKey , Object strValue ) { } } | if ( this . getMessageFieldDesc ( strKey ) != null ) this . getMessageFieldDesc ( strKey ) . put ( strValue ) ; else this . putNative ( strKey , strValue ) ; |
public class AbstractCassandraStorage { /** * Deconstructs a composite type to a Tuple . */
protected Tuple composeComposite ( AbstractCompositeType comparator , ByteBuffer name ) throws IOException { } } | List < CompositeComponent > result = comparator . deconstruct ( name ) ; Tuple t = TupleFactory . getInstance ( ) . newTuple ( result . size ( ) ) ; for ( int i = 0 ; i < result . size ( ) ; i ++ ) setTupleValue ( t , i , cassandraToObj ( result . get ( i ) . comparator , result . get ( i ) . value ) ) ; return t ; |
public class DescribeScalingPlansRequestMarshaller { /** * Marshall the given parameter object . */
public void marshall ( DescribeScalingPlansRequest describeScalingPlansRequest , ProtocolMarshaller protocolMarshaller ) { } } | if ( describeScalingPlansRequest == null ) { throw new SdkClientException ( "Invalid argument passed to marshall(...)" ) ; } try { protocolMarshaller . marshall ( describeScalingPlansRequest . getScalingPlanNames ( ) , SCALINGPLANNAMES_BINDING ) ; protocolMarshaller . marshall ( describeScalingPlansRequest . getScalingPlanVersion ( ) , SCALINGPLANVERSION_BINDING ) ; protocolMarshaller . marshall ( describeScalingPlansRequest . getApplicationSources ( ) , APPLICATIONSOURCES_BINDING ) ; protocolMarshaller . marshall ( describeScalingPlansRequest . getMaxResults ( ) , MAXRESULTS_BINDING ) ; protocolMarshaller . marshall ( describeScalingPlansRequest . getNextToken ( ) , NEXTTOKEN_BINDING ) ; } catch ( Exception e ) { throw new SdkClientException ( "Unable to marshall request to JSON: " + e . getMessage ( ) , e ) ; } |
public class CommerceCountryPersistenceImpl { /** * Returns the commerce country where groupId = & # 63 ; and numericISOCode = & # 63 ; or returns < code > null < / code > if it could not be found , optionally using the finder cache .
* @ param groupId the group ID
* @ param numericISOCode the numeric iso code
* @ param retrieveFromCache whether to retrieve from the finder cache
* @ return the matching commerce country , or < code > null < / code > if a matching commerce country could not be found */
@ Override public CommerceCountry fetchByG_N ( long groupId , int numericISOCode , boolean retrieveFromCache ) { } } | Object [ ] finderArgs = new Object [ ] { groupId , numericISOCode } ; Object result = null ; if ( retrieveFromCache ) { result = finderCache . getResult ( FINDER_PATH_FETCH_BY_G_N , finderArgs , this ) ; } if ( result instanceof CommerceCountry ) { CommerceCountry commerceCountry = ( CommerceCountry ) result ; if ( ( groupId != commerceCountry . getGroupId ( ) ) || ( numericISOCode != commerceCountry . getNumericISOCode ( ) ) ) { result = null ; } } if ( result == null ) { StringBundler query = new StringBundler ( 4 ) ; query . append ( _SQL_SELECT_COMMERCECOUNTRY_WHERE ) ; query . append ( _FINDER_COLUMN_G_N_GROUPID_2 ) ; query . append ( _FINDER_COLUMN_G_N_NUMERICISOCODE_2 ) ; String sql = query . toString ( ) ; Session session = null ; try { session = openSession ( ) ; Query q = session . createQuery ( sql ) ; QueryPos qPos = QueryPos . getInstance ( q ) ; qPos . add ( groupId ) ; qPos . add ( numericISOCode ) ; List < CommerceCountry > list = q . list ( ) ; if ( list . isEmpty ( ) ) { finderCache . putResult ( FINDER_PATH_FETCH_BY_G_N , finderArgs , list ) ; } else { CommerceCountry commerceCountry = list . get ( 0 ) ; result = commerceCountry ; cacheResult ( commerceCountry ) ; } } catch ( Exception e ) { finderCache . removeResult ( FINDER_PATH_FETCH_BY_G_N , finderArgs ) ; throw processException ( e ) ; } finally { closeSession ( session ) ; } } if ( result instanceof List < ? > ) { return null ; } else { return ( CommerceCountry ) result ; } |
public class vpnglobal_intranetip_binding { /** * Use this API to fetch filtered set of vpnglobal _ intranetip _ binding resources .
* filter string should be in JSON format . eg : " port : 80 , servicetype : HTTP " . */
public static vpnglobal_intranetip_binding [ ] get_filtered ( nitro_service service , String filter ) throws Exception { } } | vpnglobal_intranetip_binding obj = new vpnglobal_intranetip_binding ( ) ; options option = new options ( ) ; option . set_filter ( filter ) ; vpnglobal_intranetip_binding [ ] response = ( vpnglobal_intranetip_binding [ ] ) obj . getfiltered ( service , option ) ; return response ; |
public class SwingGroovyMethods { /** * Allow MutableComboBoxModel to work with subscript operators . < p >
* < b > WARNING : < / b > this operation does not replace the item at the
* specified index , rather it inserts the item at that index , thus
* increasing the size of the model by 1.
* @ param self a MutableComboBoxModel
* @ param index an index
* @ param i the item to insert at the given index
* @ since 1.6.4 */
public static void putAt ( MutableComboBoxModel self , int index , Object i ) { } } | self . insertElementAt ( i , index ) ; |
public class ConnectionFactory { /** * Uses the provided connection to check the specified schema version within
* the database .
* @ param conn the database connection object
* @ throws DatabaseException thrown if the schema version is not compatible
* with this version of dependency - check */
private void ensureSchemaVersion ( Connection conn ) throws DatabaseException { } } | ResultSet rs = null ; PreparedStatement ps = null ; try { // TODO convert this to use DatabaseProperties
ps = conn . prepareStatement ( "SELECT value FROM properties WHERE id = 'version'" ) ; rs = ps . executeQuery ( ) ; if ( rs . next ( ) ) { final String dbSchemaVersion = settings . getString ( Settings . KEYS . DB_VERSION ) ; final DependencyVersion appDbVersion = DependencyVersionUtil . parseVersion ( dbSchemaVersion ) ; if ( appDbVersion == null ) { throw new DatabaseException ( "Invalid application database schema" ) ; } final DependencyVersion db = DependencyVersionUtil . parseVersion ( rs . getString ( 1 ) ) ; if ( db == null ) { throw new DatabaseException ( "Invalid database schema" ) ; } LOGGER . debug ( "DC Schema: {}" , appDbVersion . toString ( ) ) ; LOGGER . debug ( "DB Schema: {}" , db . toString ( ) ) ; if ( appDbVersion . compareTo ( db ) > 0 ) { updateSchema ( conn , appDbVersion , db ) ; if ( ++ callDepth < 10 ) { ensureSchemaVersion ( conn ) ; } } } else { throw new DatabaseException ( "Database schema is missing" ) ; } } catch ( SQLException ex ) { LOGGER . debug ( "" , ex ) ; throw new DatabaseException ( "Unable to check the database schema version" , ex ) ; } finally { DBUtils . closeResultSet ( rs ) ; DBUtils . closeStatement ( ps ) ; } |
public class UtcInstant { /** * Obtains an instance of { @ code UtcInstant } from a Modified Julian Day with
* a nanosecond fraction of day .
* Modified Julian Day is a simple incrementing count of days where day 0 is 1858-11-17.
* Nanosecond - of - day is a simple count of nanoseconds from the start of the day
* including any additional leap - second .
* This method validates the nanosecond - of - day value against the Modified Julian Day .
* The nanosecond - of - day value has a valid range from { @ code 0 } to
* { @ code 86,400,000,000,000 - 1 } on most days , and a larger or smaller range
* on leap - second days .
* The nanosecond value must be positive even for negative values of Modified
* Julian Day . One nanosecond before Modified Julian Day zero will be
* { @ code - 1 } days and the maximum nanosecond value .
* @ param mjDay the date as a Modified Julian Day ( number of days from the epoch of 1858-11-17)
* @ param nanoOfDay the nanoseconds within the day , including leap seconds
* @ return the UTC instant , not null
* @ throws IllegalArgumentException if nanoOfDay is out of range */
public static UtcInstant ofModifiedJulianDay ( long mjDay , long nanoOfDay ) { } } | UtcRules . system ( ) . validateModifiedJulianDay ( mjDay , nanoOfDay ) ; return new UtcInstant ( mjDay , nanoOfDay ) ; |
public class Enhancer { /** * Creates a new object that is enhanced .
* @ return new object */
public T newInstance ( ) { } } | try { return getEnhancedClass ( ) . newInstance ( ) ; } catch ( Exception e ) { logger . error ( "Could not instantiate enhanced object." , e ) ; throw ExceptionUtil . propagate ( e ) ; } |
public class TangramEngine { /** * { @ inheritDoc } */
@ Override public void replaceCard ( Card oldCard , Card newCard ) { } } | List < Card > groups = this . mGroupBasicAdapter . getGroups ( ) ; int index = groups . indexOf ( oldCard ) ; if ( index >= 0 ) { replaceData ( index , Collections . singletonList ( newCard ) ) ; } |
public class RequestPropertiesBuilder { /** * This method is used to validate and build the accept JSON version .
* @ param version
* { @ code String } version
* @ return { @ code String } the mounted header value */
private String acceptBuilder ( String version ) { } } | String acceptValue = "application/json" ; if ( version == "2.1" ) acceptValue += ";version=" + version ; return acceptValue ; |
public class NutchResourceIndex { /** * do an HTTP request , plus parse the result into an XML DOM */
protected synchronized Document getHttpDocument ( String url ) throws IOException , SAXException { } } | Document d = null ; d = this . builder . parse ( url ) ; return d ; |
public class HttpChannelConfig { /** * Check the input configuration for a maximum limit on the number of
* headers allowed per message .
* @ param props */
private void parseLimitNumberHeaders ( Map < Object , Object > props ) { } } | Object value = props . get ( HttpConfigConstants . PROPNAME_LIMIT_NUMHEADERS ) ; if ( null != value ) { try { this . limitNumHeaders = rangeLimit ( convertInteger ( value ) , HttpConfigConstants . MIN_LIMIT_NUMHEADERS , HttpConfigConstants . MAX_LIMIT_NUMHEADERS ) ; if ( TraceComponent . isAnyTracingEnabled ( ) && tc . isEventEnabled ( ) ) { Tr . event ( tc , "Config: Num hdrs limit is " + getLimitOnNumberOfHeaders ( ) ) ; } } catch ( NumberFormatException nfe ) { FFDCFilter . processException ( nfe , getClass ( ) . getName ( ) + ".parseLimitNumberHeaders" , "1" ) ; if ( TraceComponent . isAnyTracingEnabled ( ) && tc . isEventEnabled ( ) ) { Tr . event ( tc , "Config: Invalid number of headers limit; " + value ) ; } } } |
public class ManagementHttpRequestProcessor { /** * Notify all shutdown listeners that the shutdown completed . */
protected synchronized void handleCompleted ( ) { } } | latch . countDown ( ) ; for ( final ShutdownListener listener : listeners ) { listener . handleCompleted ( ) ; } listeners . clear ( ) ; |
public class StreamingJsonSerializer { /** * / * ( non - Javadoc )
* @ see org . ektorp . impl . JsonSerializer # asInputStream ( java . util . Collection , boolean ) */
public BulkOperation createBulkOperation ( final Collection < ? > objects , final boolean allOrNothing ) { } } | try { final PipedOutputStream out = new PipedOutputStream ( ) ; PipedInputStream in = new PipedInputStream ( out ) ; Future < ? > writeTask = executorService . submit ( new Runnable ( ) { public void run ( ) { try { bulkDocWriter . write ( objects , allOrNothing , out ) ; } catch ( Exception e ) { LOG . error ( "Caught exception while writing bulk document:" , e ) ; } } } ) ; return new BulkOperation ( writeTask , in ) ; } catch ( IOException e ) { throw Exceptions . propagate ( e ) ; } |
public class CommonOps_DDF2 { /** * Returns the value of the element in the vector that has the minimum value . < br >
* < br >
* Min { a < sub > i < / sub > } for all < br >
* @ param a A matrix . Not modified .
* @ return The value of element in the vector with the minimum value . */
public static double elementMin ( DMatrix2 a ) { } } | double min = a . a1 ; if ( a . a2 < min ) min = a . a2 ; return min ; |
public class Association { /** * Return the list of actions on the tuple . Operations are inherently deduplicated , i . e . there will be at most one
* operation for a specific row key .
* Note that the global CLEAR operation is put at the top of the list .
* @ return the operations to execute on the association , the global CLEAR operation is put at the top of the list */
public List < AssociationOperation > getOperations ( ) { } } | List < AssociationOperation > result = new ArrayList < AssociationOperation > ( currentState . size ( ) + 1 ) ; if ( cleared ) { result . add ( new AssociationOperation ( null , null , AssociationOperationType . CLEAR ) ) ; } result . addAll ( currentState . values ( ) ) ; return result ; |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.