idx int64 0 41.2k | question stringlengths 73 5.81k | target stringlengths 5 918 |
|---|---|---|
10,500 | public void addResponseCommitListener ( final ResponseCommitListener listener ) { addResponseWrapper ( new ConduitWrapper < StreamSinkConduit > ( ) { public StreamSinkConduit wrap ( ConduitFactory < StreamSinkConduit > factory , HttpServerExchange exchange ) { listener . beforeCommit ( exchange ) ; return factory . create ( ) ; } } ) ; } | Adds a listener that will be invoked on response commit |
10,501 | boolean runResumeReadWrite ( ) { boolean ret = false ; if ( anyAreSet ( state , FLAG_SHOULD_RESUME_WRITES ) ) { responseChannel . runResume ( ) ; ret = true ; } if ( anyAreSet ( state , FLAG_SHOULD_RESUME_READS ) ) { requestChannel . runResume ( ) ; ret = true ; } return ret ; } | Actually resumes reads or writes if the relevant method has been called . |
10,502 | public boolean evaluate ( Matcher rule , Matcher cond , Resolver resolver ) { String value = test . evaluate ( rule , cond , resolver ) ; if ( nocase ) { value = value . toLowerCase ( Locale . ENGLISH ) ; } Condition condition = this . condition . get ( ) ; if ( condition == null ) { if ( condPattern . startsWith ( "<" ) ) { LexicalCondition ncondition = new LexicalCondition ( ) ; ncondition . type = - 1 ; ncondition . condition = condPattern . substring ( 1 ) ; condition = ncondition ; } else if ( condPattern . startsWith ( ">" ) ) { LexicalCondition ncondition = new LexicalCondition ( ) ; ncondition . type = 1 ; ncondition . condition = condPattern . substring ( 1 ) ; condition = ncondition ; } else if ( condPattern . startsWith ( "=" ) ) { LexicalCondition ncondition = new LexicalCondition ( ) ; ncondition . type = 0 ; ncondition . condition = condPattern . substring ( 1 ) ; condition = ncondition ; } else if ( condPattern . equals ( "-d" ) ) { ResourceCondition ncondition = new ResourceCondition ( ) ; ncondition . type = 0 ; condition = ncondition ; } else if ( condPattern . equals ( "-f" ) ) { ResourceCondition ncondition = new ResourceCondition ( ) ; ncondition . type = 1 ; condition = ncondition ; } else if ( condPattern . equals ( "-s" ) ) { ResourceCondition ncondition = new ResourceCondition ( ) ; ncondition . type = 2 ; condition = ncondition ; } else { PatternCondition ncondition = new PatternCondition ( ) ; int flags = 0 ; if ( isNocase ( ) ) { flags |= Pattern . CASE_INSENSITIVE ; } ncondition . pattern = Pattern . compile ( condPattern , flags ) ; condition = ncondition ; } this . condition . set ( condition ) ; } if ( positive ) { return condition . evaluate ( value , resolver ) ; } else { return ! condition . evaluate ( value , resolver ) ; } } | Evaluate the condition based on the context |
10,503 | private void callbackSucceed ( ) { if ( mGranted != null ) { List < String > permissionList = asList ( mPermissions ) ; try { mGranted . onAction ( permissionList ) ; } catch ( Exception e ) { Log . e ( "AndPermission" , "Please check the onGranted() method body for bugs." , e ) ; if ( mDenied != null ) { mDenied . onAction ( permissionList ) ; } } } } | Callback acceptance status . |
10,504 | private static List < String > getDeniedPermissions ( PermissionChecker checker , Source source , String ... permissions ) { List < String > deniedList = new ArrayList < > ( 1 ) ; for ( String permission : permissions ) { if ( ! checker . hasPermission ( source . getContext ( ) , permission ) ) { deniedList . add ( permission ) ; } } return deniedList ; } | Get denied permissions . |
10,505 | static void requestInstall ( Source source ) { Intent intent = new Intent ( source . getContext ( ) , BridgeActivity . class ) ; intent . putExtra ( KEY_TYPE , BridgeRequest . TYPE_INSTALL ) ; source . startActivity ( intent ) ; } | Request for package install . |
10,506 | static void requestOverlay ( Source source ) { Intent intent = new Intent ( source . getContext ( ) , BridgeActivity . class ) ; intent . putExtra ( KEY_TYPE , BridgeRequest . TYPE_OVERLAY ) ; source . startActivity ( intent ) ; } | Request for overlay . |
10,507 | static void requestAlertWindow ( Source source ) { Intent intent = new Intent ( source . getContext ( ) , BridgeActivity . class ) ; intent . putExtra ( KEY_TYPE , BridgeRequest . TYPE_ALERT_WINDOW ) ; source . startActivity ( intent ) ; } | Request for alert window . |
10,508 | static void requestNotify ( Source source ) { Intent intent = new Intent ( source . getContext ( ) , BridgeActivity . class ) ; intent . putExtra ( KEY_TYPE , BridgeRequest . TYPE_NOTIFY ) ; source . startActivity ( intent ) ; } | Request for notify . |
10,509 | static void requestNotificationListener ( Source source ) { Intent intent = new Intent ( source . getContext ( ) , BridgeActivity . class ) ; intent . putExtra ( KEY_TYPE , BridgeRequest . TYPE_NOTIFY_LISTENER ) ; source . startActivity ( intent ) ; } | Request for notification listener . |
10,510 | static void requestWriteSetting ( Source source ) { Intent intent = new Intent ( source . getContext ( ) , BridgeActivity . class ) ; intent . putExtra ( KEY_TYPE , BridgeRequest . TYPE_WRITE_SETTING ) ; source . startActivity ( intent ) ; } | Request for write system setting . |
10,511 | private static boolean hasAlwaysDeniedPermission ( Source source , String ... deniedPermissions ) { for ( String permission : deniedPermissions ) { if ( ! source . isShowRationalePermission ( permission ) ) { return true ; } } return false ; } | Has always been denied permission . |
10,512 | final void install ( ) { Intent intent = new Intent ( Intent . ACTION_INSTALL_PACKAGE ) ; intent . setFlags ( Intent . FLAG_ACTIVITY_NEW_TASK ) ; intent . addFlags ( Intent . FLAG_GRANT_READ_URI_PERMISSION ) ; Uri uri = AndPermission . getFileUri ( mSource . getContext ( ) , mFile ) ; intent . setDataAndType ( uri , "application/vnd.android.package-archive" ) ; mSource . startActivity ( intent ) ; } | Start the installation . |
10,513 | public void show ( ) { if ( isShowing ) { Log . w ( "AlertWindow" , "AlertWindow is already displayed." ) ; } else { isShowing = true ; mWindowManager . addView ( mContentView , mParams ) ; } } | Display the alert window . |
10,514 | private static List < String > getRationalePermissions ( Source source , String ... permissions ) { List < String > rationaleList = new ArrayList < > ( 1 ) ; for ( String permission : permissions ) { if ( source . isShowRationalePermission ( permission ) ) { rationaleList . add ( permission ) ; } } return rationaleList ; } | Get permissions to show rationale . |
10,515 | private void checkPermissions ( String ... permissions ) { if ( sAppPermissions == null ) sAppPermissions = getManifestPermissions ( mSource . getContext ( ) ) ; if ( permissions . length == 0 ) { throw new IllegalArgumentException ( "Please enter at least one permission." ) ; } for ( String p : permissions ) { if ( ! sAppPermissions . contains ( p ) ) { if ( ! ( Permission . ADD_VOICEMAIL . equals ( p ) && sAppPermissions . contains ( Permission . ADD_VOICEMAIL_MANIFEST ) ) ) { throw new IllegalStateException ( String . format ( "The permission %1$s is not registered in manifest.xml" , p ) ) ; } } } } | Check if the permissions are valid and each permission has been registered in manifest . xml . This method will throw a exception if permissions are invalid or there is any permission which is not registered in manifest . xml . |
10,516 | private static List < String > getManifestPermissions ( Context context ) { try { PackageInfo packageInfo = context . getPackageManager ( ) . getPackageInfo ( context . getPackageName ( ) , PackageManager . GET_PERMISSIONS ) ; String [ ] permissions = packageInfo . requestedPermissions ; if ( permissions == null || permissions . length == 0 ) { throw new IllegalStateException ( "You did not register any permissions in the manifest.xml." ) ; } return Collections . unmodifiableList ( Arrays . asList ( permissions ) ) ; } catch ( PackageManager . NameNotFoundException e ) { throw new AssertionError ( "Package name cannot be found." ) ; } } | Get a list of permissions in the manifest . |
10,517 | public void showSettingDialog ( Context context , final List < String > permissions ) { List < String > permissionNames = Permission . transformText ( context , permissions ) ; String message = context . getString ( R . string . message_permission_always_failed , TextUtils . join ( "\n" , permissionNames ) ) ; new AlertDialog . Builder ( context ) . setCancelable ( false ) . setTitle ( R . string . title_dialog ) . setMessage ( message ) . setPositiveButton ( R . string . setting , new DialogInterface . OnClickListener ( ) { public void onClick ( DialogInterface dialog , int which ) { setPermission ( ) ; } } ) . setNegativeButton ( R . string . cancel , new DialogInterface . OnClickListener ( ) { public void onClick ( DialogInterface dialog , int which ) { } } ) . show ( ) ; } | Display setting dialog . |
10,518 | private void requestNotification ( ) { AndPermission . with ( this ) . notification ( ) . permission ( ) . rationale ( new NotifyRationale ( ) ) . onGranted ( new Action < Void > ( ) { public void onAction ( Void data ) { toast ( R . string . successfully ) ; } } ) . onDenied ( new Action < Void > ( ) { public void onAction ( Void data ) { toast ( R . string . failure ) ; } } ) . start ( ) ; } | Request notification permission . |
10,519 | private void requestNotificationListener ( ) { AndPermission . with ( this ) . notification ( ) . listener ( ) . rationale ( new NotifyListenerRationale ( ) ) . onGranted ( new Action < Void > ( ) { public void onAction ( Void data ) { toast ( R . string . successfully ) ; } } ) . onDenied ( new Action < Void > ( ) { public void onAction ( Void data ) { toast ( R . string . failure ) ; } } ) . start ( ) ; } | Request notification listener . |
10,520 | private void requestPermissionForInstallPackage ( ) { AndPermission . with ( this ) . runtime ( ) . permission ( Permission . Group . STORAGE ) . rationale ( new RuntimeRationale ( ) ) . onGranted ( new Action < List < String > > ( ) { public void onAction ( List < String > data ) { new WriteApkTask ( MainActivity . this , new Runnable ( ) { public void run ( ) { installPackage ( ) ; } } ) . execute ( ) ; } } ) . onDenied ( new Action < List < String > > ( ) { public void onAction ( List < String > data ) { toast ( R . string . message_install_failed ) ; } } ) . start ( ) ; } | Request to read and write external storage permissions . |
10,521 | private PopupMenu createMenu ( View v , String [ ] menuArray ) { PopupMenu popupMenu = new PopupMenu ( this , v ) ; Menu menu = popupMenu . getMenu ( ) ; for ( int i = 0 ; i < menuArray . length ; i ++ ) { String menuText = menuArray [ i ] ; menu . add ( 0 , i , i , menuText ) ; } return popupMenu ; } | Create menu . |
10,522 | public static byte [ ] generateContractAddress ( byte [ ] address , BigInteger nonce ) { List < RlpType > values = new ArrayList < > ( ) ; values . add ( RlpString . create ( address ) ) ; values . add ( RlpString . create ( nonce ) ) ; RlpList rlpList = new RlpList ( values ) ; byte [ ] encoded = RlpEncoder . encode ( rlpList ) ; byte [ ] hashed = Hash . sha3 ( encoded ) ; return Arrays . copyOfRange ( hashed , 12 , hashed . length ) ; } | Generate a smart contract address . This enables you to identify what address a smart contract will be deployed to on the network . |
10,523 | public static String generateMnemonic ( byte [ ] initialEntropy ) { validateEntropy ( initialEntropy ) ; final List < String > words = getWords ( ) ; int ent = initialEntropy . length * 8 ; int checksumLength = ent / 32 ; byte checksum = calculateChecksum ( initialEntropy ) ; boolean [ ] bits = convertToBits ( initialEntropy , checksum ) ; int iterations = ( ent + checksumLength ) / 11 ; StringBuilder mnemonicBuilder = new StringBuilder ( ) ; for ( int i = 0 ; i < iterations ; i ++ ) { int index = toInt ( nextElevenBits ( bits , i ) ) ; mnemonicBuilder . append ( words . get ( index ) ) ; boolean notLastIteration = i < iterations - 1 ; if ( notLastIteration ) { mnemonicBuilder . append ( " " ) ; } } return mnemonicBuilder . toString ( ) ; } | The mnemonic must encode entropy in a multiple of 32 bits . With more entropy security is improved but the sentence length increases . We refer to the initial entropy length as ENT . The allowed size of ENT is 128 - 256 bits . |
10,524 | public static byte [ ] generateEntropy ( String mnemonic ) { final BitSet bits = new BitSet ( ) ; final int size = mnemonicToBits ( mnemonic , bits ) ; if ( size == 0 ) { throw new IllegalArgumentException ( "Empty mnemonic" ) ; } final int ent = 32 * size / 33 ; if ( ent % 8 != 0 ) { throw new IllegalArgumentException ( "Wrong mnemonic size" ) ; } final byte [ ] entropy = new byte [ ent / 8 ] ; for ( int i = 0 ; i < entropy . length ; i ++ ) { entropy [ i ] = readByte ( bits , i ) ; } validateEntropy ( entropy ) ; final byte expectedChecksum = calculateChecksum ( entropy ) ; final byte actualChecksum = readByte ( bits , entropy . length ) ; if ( expectedChecksum != actualChecksum ) { throw new IllegalArgumentException ( "Wrong checksum" ) ; } return entropy ; } | Create entropy from the mnemonic . |
10,525 | public static ScheduledExecutorService defaultExecutorService ( ) { ScheduledExecutorService scheduledExecutorService = Executors . newScheduledThreadPool ( getCpuCount ( ) ) ; Runtime . getRuntime ( ) . addShutdownHook ( new Thread ( ( ) -> shutdown ( scheduledExecutorService ) ) ) ; return scheduledExecutorService ; } | Provide a new ScheduledExecutorService instance . |
10,526 | @ SuppressWarnings ( "unchecked" ) static < T extends Type > T decodeStaticArray ( String input , int offset , TypeReference < T > typeReference , int length ) { BiFunction < List < T > , String , T > function = ( elements , typeName ) -> { if ( elements . isEmpty ( ) ) { throw new UnsupportedOperationException ( "Zero length fixed array is invalid type" ) ; } else { return instantiateStaticArray ( typeReference , elements , length ) ; } } ; return decodeArrayElements ( input , offset , typeReference , length , function ) ; } | Static array length cannot be passed as a type . |
10,527 | public boolean isValid ( ) throws IOException { if ( contractBinary . equals ( BIN_NOT_PROVIDED ) ) { throw new UnsupportedOperationException ( "Contract binary not present in contract wrapper, " + "please generate your wrapper using -abiFile=<file>" ) ; } if ( contractAddress . equals ( "" ) ) { throw new UnsupportedOperationException ( "Contract binary not present, you will need to regenerate your smart " + "contract wrapper with web3j v2.2.0+" ) ; } EthGetCode ethGetCode = web3j . ethGetCode ( contractAddress , DefaultBlockParameterName . LATEST ) . send ( ) ; if ( ethGetCode . hasError ( ) ) { return false ; } String code = Numeric . cleanHexPrefix ( ethGetCode . getCode ( ) ) ; int metadataIndex = code . indexOf ( "a165627a7a72305820" ) ; if ( metadataIndex != - 1 ) { code = code . substring ( 0 , metadataIndex ) ; } return ! code . isEmpty ( ) && contractBinary . contains ( code ) ; } | Check that the contract deployed at the address associated with this smart contract wrapper is in fact the contract you believe it is . |
10,528 | private List < Type > executeCall ( Function function ) throws IOException { String encodedFunction = FunctionEncoder . encode ( function ) ; org . web3j . protocol . core . methods . response . EthCall ethCall = web3j . ethCall ( Transaction . createEthCallTransaction ( transactionManager . getFromAddress ( ) , contractAddress , encodedFunction ) , defaultBlockParameter ) . send ( ) ; String value = ethCall . getValue ( ) ; return FunctionReturnDecoder . decode ( value , function . getOutputParameters ( ) ) ; } | Execute constant function call - i . e . a call that does not change state of the contract |
10,529 | TransactionReceipt executeTransaction ( String data , BigInteger weiValue , String funcName ) throws TransactionException , IOException { TransactionReceipt receipt = send ( contractAddress , data , weiValue , gasProvider . getGasPrice ( funcName ) , gasProvider . getGasLimit ( funcName ) ) ; if ( ! receipt . isStatusOK ( ) ) { throw new TransactionException ( String . format ( "Transaction has failed with status: %s. " + "Gas used: %d. (not-enough gas?)" , receipt . getStatus ( ) , receipt . getGasUsed ( ) ) ) ; } return receipt ; } | Given the duration required to execute a transaction . |
10,530 | public static List < Type > decode ( String rawInput , List < TypeReference < Type > > outputParameters ) { String input = Numeric . cleanHexPrefix ( rawInput ) ; if ( Strings . isEmpty ( input ) ) { return Collections . emptyList ( ) ; } else { return build ( input , outputParameters ) ; } } | Decode ABI encoded return values from smart contract function call . |
10,531 | public PublicResolver obtainPublicResolver ( String ensName ) { if ( isValidEnsName ( ensName ) ) { try { if ( ! isSynced ( ) ) { throw new EnsResolutionException ( "Node is not currently synced" ) ; } else { return lookupResolver ( ensName ) ; } } catch ( Exception e ) { throw new EnsResolutionException ( "Unable to determine sync status of node" , e ) ; } } else { throw new EnsResolutionException ( "EnsName is invalid: " + ensName ) ; } } | Provides an access to a valid public resolver in order to access other API methods . |
10,532 | public RemoteCall < TransactionReceipt > sendFunds ( String toAddress , BigDecimal value , Convert . Unit unit ) { return new RemoteCall < > ( ( ) -> send ( toAddress , value , unit ) ) ; } | Execute the provided function as a transaction asynchronously . This is intended for one - off fund transfers . For multiple create an instance . |
10,533 | public static BigInteger signedMessageToKey ( byte [ ] message , SignatureData signatureData ) throws SignatureException { return signedMessageHashToKey ( Hash . sha3 ( message ) , signatureData ) ; } | Given an arbitrary piece of text and an Ethereum message signature encoded in bytes returns the public key that was used to sign it . This can then be compared to the expected public key to determine if the signature was correct . |
10,534 | public static BigInteger signedPrefixedMessageToKey ( byte [ ] message , SignatureData signatureData ) throws SignatureException { return signedMessageHashToKey ( getEthereumMessageHash ( message ) , signatureData ) ; } | Given an arbitrary message and an Ethereum message signature encoded in bytes returns the public key that was used to sign it . This can then be compared to the expected public key to determine if the signature was correct . |
10,535 | public static BigInteger publicKeyFromPrivate ( BigInteger privKey ) { ECPoint point = publicPointFromPrivate ( privKey ) ; byte [ ] encoded = point . getEncoded ( false ) ; return new BigInteger ( 1 , Arrays . copyOfRange ( encoded , 1 , encoded . length ) ) ; } | Returns public key from the given private key . |
10,536 | public void connect ( ) throws ConnectException { try { connectToWebSocket ( ) ; setWebSocketListener ( ) ; } catch ( InterruptedException e ) { Thread . currentThread ( ) . interrupt ( ) ; log . warn ( "Interrupted while connecting via WebSocket protocol" ) ; } } | Connect to a WebSocket server . |
10,537 | public static String sha3String ( String utf8String ) { return Numeric . toHexString ( sha3 ( utf8String . getBytes ( StandardCharsets . UTF_8 ) ) ) ; } | Keccak - 256 hash function that operates on a UTF - 8 encoded String . |
10,538 | public ECDSASignature sign ( byte [ ] transactionHash ) { ECDSASigner signer = new ECDSASigner ( new HMacDSAKCalculator ( new SHA256Digest ( ) ) ) ; ECPrivateKeyParameters privKey = new ECPrivateKeyParameters ( privateKey , Sign . CURVE ) ; signer . init ( true , privKey ) ; BigInteger [ ] components = signer . generateSignature ( transactionHash ) ; return new ECDSASignature ( components [ 0 ] , components [ 1 ] ) . toCanonicalised ( ) ; } | Sign a hash with the private key of this key pair . |
10,539 | public synchronized void pause ( ) { if ( paused ) { Util . w ( TAG , "require pause this queue(remain " + taskList . size ( ) + "), but" + "it has already been paused" ) ; return ; } paused = true ; if ( runningTask != null ) { runningTask . cancel ( ) ; taskList . add ( 0 , runningTask ) ; runningTask = null ; } } | Pause the queue . |
10,540 | public synchronized void resume ( ) { if ( ! paused ) { Util . w ( TAG , "require resume this queue(remain " + taskList . size ( ) + "), but it is" + " still running" ) ; return ; } paused = false ; if ( ! taskList . isEmpty ( ) && ! looping ) { looping = true ; startNewLooper ( ) ; } } | Resume the queue if the queue is paused . |
10,541 | public BreakpointInfo copyWithReplaceIdAndUrl ( int replaceId , String newUrl ) { final BreakpointInfo info = new BreakpointInfo ( replaceId , newUrl , parentFile , filenameHolder . get ( ) , taskOnlyProvidedParentPath ) ; info . chunked = this . chunked ; for ( BlockInfo blockInfo : blockInfoList ) { info . blockInfoList . add ( blockInfo . copy ( ) ) ; } return info ; } | You can use this method to replace url for using breakpoint info from another task . |
10,542 | public BreakpointInfo getInfo ( ) { if ( info == null ) info = OkDownload . with ( ) . breakpointStore ( ) . get ( id ) ; return info ; } | Get the breakpoint info of this task . |
10,543 | void trialHeadMethodForInstanceLength ( ) throws IOException { final DownloadConnection connection = OkDownload . with ( ) . connectionFactory ( ) . create ( task . getUrl ( ) ) ; final DownloadListener listener = OkDownload . with ( ) . callbackDispatcher ( ) . dispatch ( ) ; try { connection . setRequestMethod ( METHOD_HEAD ) ; final Map < String , List < String > > userHeader = task . getHeaderMapFields ( ) ; if ( userHeader != null ) Util . addUserRequestHeaderField ( userHeader , connection ) ; listener . connectTrialStart ( task , connection . getRequestProperties ( ) ) ; final DownloadConnection . Connected connectedForContentLength = connection . execute ( ) ; listener . connectTrialEnd ( task , connectedForContentLength . getResponseCode ( ) , connectedForContentLength . getResponseHeaderFields ( ) ) ; this . instanceLength = Util . parseContentLength ( connectedForContentLength . getResponseHeaderField ( CONTENT_LENGTH ) ) ; } finally { connection . release ( ) ; } } | right one . |
10,544 | public void start ( final DownloadListener listener , boolean isSerial ) { final long startTime = SystemClock . uptimeMillis ( ) ; Util . d ( TAG , "start " + isSerial ) ; started = true ; final DownloadListener targetListener ; if ( contextListener != null ) { targetListener = new DownloadListenerBunch . Builder ( ) . append ( listener ) . append ( new QueueAttachListener ( this , contextListener , tasks . length ) ) . build ( ) ; } else { targetListener = listener ; } if ( isSerial ) { final List < DownloadTask > scheduleTaskList = new ArrayList < > ( ) ; Collections . addAll ( scheduleTaskList , tasks ) ; Collections . sort ( scheduleTaskList ) ; executeOnSerialExecutor ( new Runnable ( ) { public void run ( ) { for ( DownloadTask task : scheduleTaskList ) { if ( ! isStarted ( ) ) { callbackQueueEndOnSerialLoop ( task . isAutoCallbackToUIThread ( ) ) ; break ; } task . execute ( targetListener ) ; } } } ) ; } else { DownloadTask . enqueue ( tasks , targetListener ) ; } Util . d ( TAG , "start finish " + isSerial + " " + ( SystemClock . uptimeMillis ( ) - startTime ) + "ms" ) ; } | Start queue . |
10,545 | public void syncCacheToDB ( List < Integer > idList ) throws IOException { final SQLiteDatabase database = sqLiteHelper . getWritableDatabase ( ) ; database . beginTransaction ( ) ; try { for ( Integer id : idList ) { syncCacheToDB ( id ) ; } database . setTransactionSuccessful ( ) ; } finally { database . endTransaction ( ) ; } } | following accept database operation what is controlled by helper . |
10,546 | public synchronized long getBytesPerSecondAndFlush ( ) { final long interval = nowMillis ( ) - timestamp ; if ( interval < 1000 && bytesPerSecond != 0 ) return bytesPerSecond ; if ( bytesPerSecond == 0 && interval < 500 ) return 0 ; return getInstantBytesPerSecondAndFlush ( ) ; } | Get bytes per - second and only if duration is greater than or equal to 1 second will flush and re - calculate speed . |
10,547 | public void showProgress ( final int id , final int sofar , final int total ) { final T notification = get ( id ) ; if ( notification == null ) { return ; } notification . updateStatus ( FileDownloadStatus . progress ) ; notification . update ( sofar , total ) ; } | Show the notification with the exact progress . |
10,548 | public void showIndeterminate ( final int id , int status ) { final BaseNotificationItem notification = get ( id ) ; if ( notification == null ) { return ; } notification . updateStatus ( status ) ; notification . show ( false ) ; } | Show the notification with indeterminate progress . |
10,549 | public void cancel ( final int id ) { final BaseNotificationItem notification = remove ( id ) ; if ( notification == null ) { return ; } notification . cancel ( ) ; } | Cancel the notification by notification id . |
10,550 | void addQueueTask ( final DownloadTaskAdapter task ) { if ( task . isMarkedAdded2List ( ) ) { Util . w ( TAG , "queue task: " + task + " has been marked" ) ; return ; } synchronized ( list ) { task . markAdded2List ( ) ; task . assembleDownloadTask ( ) ; list . add ( task ) ; Util . d ( TAG , "add list in all " + task + " " + list . size ( ) ) ; } } | This method generally used for enqueuing the task which will be assembled by a queue . |
10,551 | private String findSocketFile ( int pid ) { File f = new File ( tmpdir , ".java_pid" + pid ) ; if ( ! f . exists ( ) ) { return null ; } return f . getPath ( ) ; } | Return the socket file for the given process . |
10,552 | private File createAttachFile ( int pid ) throws IOException { String fn = ".attach_pid" + pid ; String path = "/proc/" + pid + "/cwd/" + fn ; File f = new File ( path ) ; try { f . createNewFile ( ) ; } catch ( IOException x ) { f = new File ( tmpdir , fn ) ; f . createNewFile ( ) ; } return f ; } | checks for the file . |
10,553 | public synchronized static void clear ( ) { newSubstitutions . clear ( ) ; classMocks . clear ( ) ; instanceMocks . clear ( ) ; objectsToAutomaticallyReplayAndVerify . clear ( ) ; additionalState . clear ( ) ; suppressConstructor . clear ( ) ; suppressMethod . clear ( ) ; substituteReturnValues . clear ( ) ; suppressField . clear ( ) ; suppressFieldTypes . clear ( ) ; methodProxies . clear ( ) ; for ( Runnable runnable : afterMethodRunners ) { runnable . run ( ) ; } afterMethodRunners . clear ( ) ; } | Clear all state of the mock repository except for static initializers . The reason for not clearing static initializers is that when running in a suite with many tests the clear method is invoked after each test . This means that before the test that needs to suppress the static initializer has been reach the state of the MockRepository would have been wiped out . This is generally not a problem because most state will be added again but suppression of static initializers are different because this state can only be set once per class per CL . That s why we cannot remove this state . |
10,554 | public static void remove ( Object mock ) { if ( mock instanceof Class < ? > ) { if ( newSubstitutions . containsKey ( mock ) ) { newSubstitutions . remove ( mock ) ; } if ( classMocks . containsKey ( mock ) ) { classMocks . remove ( mock ) ; } } else if ( instanceMocks . containsKey ( mock ) ) { instanceMocks . remove ( mock ) ; } } | Removes an object from the MockRepository if it exists . |
10,555 | public static synchronized Object putAdditionalState ( String key , Object value ) { return additionalState . put ( key , value ) ; } | When a mock framework API needs to store additional state not applicable for the other methods it may use this method to do so . |
10,556 | @ SuppressWarnings ( "unchecked" ) public static synchronized < T > T getAdditionalState ( String key ) { return ( T ) additionalState . get ( key ) ; } | Retrieve state based on the supplied key . |
10,557 | public static synchronized InvocationHandler putMethodProxy ( Method method , InvocationHandler invocationHandler ) { return methodProxies . put ( method , invocationHandler ) ; } | Set a proxy for a method . Whenever this method is called the invocation handler will be invoked instead . |
10,558 | private void addNewDeferConstructor ( final CtClass clazz ) throws CannotCompileException { final CtClass superClass ; try { superClass = clazz . getSuperclass ( ) ; } catch ( NotFoundException e1 ) { throw new IllegalArgumentException ( "Internal error: Failed to get superclass for " + clazz . getName ( ) + " when about to create a new default constructor." ) ; } ClassPool classPool = clazz . getClassPool ( ) ; final CtClass constructorType ; try { constructorType = classPool . get ( IndicateReloadClass . class . getName ( ) ) ; } catch ( NotFoundException e ) { throw new IllegalArgumentException ( "Internal error: failed to get the " + IndicateReloadClass . class . getName ( ) + " when added defer constructor." ) ; } clazz . defrost ( ) ; if ( superClass . getName ( ) . equals ( Object . class . getName ( ) ) ) { try { clazz . addConstructor ( CtNewConstructor . make ( new CtClass [ ] { constructorType } , new CtClass [ 0 ] , "{super();}" , clazz ) ) ; } catch ( DuplicateMemberException e ) { } } else { addNewDeferConstructor ( superClass ) ; try { clazz . addConstructor ( CtNewConstructor . make ( new CtClass [ ] { constructorType } , new CtClass [ 0 ] , "{super($$);}" , clazz ) ) ; } catch ( DuplicateMemberException e ) { } } } | Create a defer constructor in the class which will be called when the constructor is suppressed . |
10,559 | public void run ( RunNotifier notifier ) { Description description = getDescription ( ) ; try { super . run ( notifier ) ; } finally { try { Whitebox . setInternalState ( description , "fAnnotations" , new Annotation [ ] { } ) ; } catch ( RuntimeException err ) { if ( err . getCause ( ) instanceof java . lang . NoSuchFieldException && err . getCause ( ) . getMessage ( ) . equals ( "modifiers" ) ) { } else { throw err ; } } } } | Clean up some state to avoid OOM issues |
10,560 | @ SuppressWarnings ( { "unchecked" , "rawtypes" } ) public static Field getField ( Class < ? > type , String fieldName ) { LinkedList < Class < ? > > examine = new LinkedList < Class < ? > > ( ) ; examine . add ( type ) ; Set < Class < ? > > done = new HashSet < Class < ? > > ( ) ; while ( ! examine . isEmpty ( ) ) { Class < ? > thisType = examine . removeFirst ( ) ; done . add ( thisType ) ; final Field [ ] declaredField = thisType . getDeclaredFields ( ) ; for ( Field field : declaredField ) { if ( fieldName . equals ( field . getName ( ) ) ) { field . setAccessible ( true ) ; return field ; } } Set < Class < ? > > potential = new HashSet < Class < ? > > ( ) ; final Class < ? > clazz = thisType . getSuperclass ( ) ; if ( clazz != null ) { potential . add ( thisType . getSuperclass ( ) ) ; } potential . addAll ( ( Collection ) Arrays . asList ( thisType . getInterfaces ( ) ) ) ; potential . removeAll ( done ) ; examine . addAll ( potential ) ; } throwExceptionIfFieldWasNotFound ( type , fieldName , null ) ; return null ; } | Convenience method to get a field from a class type . |
10,561 | @ SuppressWarnings ( "unchecked" ) public static < T > T newInstance ( Class < T > classToInstantiate ) { int modifiers = classToInstantiate . getModifiers ( ) ; final Object object ; if ( Modifier . isInterface ( modifiers ) ) { object = Proxy . newProxyInstance ( WhiteboxImpl . class . getClassLoader ( ) , new Class < ? > [ ] { classToInstantiate } , new InvocationHandler ( ) { public Object invoke ( Object proxy , Method method , Object [ ] args ) throws Throwable { return TypeUtils . getDefaultValue ( method . getReturnType ( ) ) ; } } ) ; } else if ( classToInstantiate . isArray ( ) ) { object = Array . newInstance ( classToInstantiate . getComponentType ( ) , 0 ) ; } else if ( Modifier . isAbstract ( modifiers ) ) { throw new IllegalArgumentException ( "Cannot instantiate an abstract class. Please use the ConcreteClassGenerator in PowerMock support to generate a concrete class first." ) ; } else { Objenesis objenesis = new ObjenesisStd ( ) ; ObjectInstantiator thingyInstantiator = objenesis . getInstantiatorOf ( classToInstantiate ) ; object = thingyInstantiator . newInstance ( ) ; } return ( T ) object ; } | Create a new instance of a class without invoking its constructor . |
10,562 | public static void setInternalState ( Object object , String fieldName , Object value , Class < ? > where ) { if ( object == null || fieldName == null || fieldName . equals ( "" ) || fieldName . startsWith ( " " ) ) { throw new IllegalArgumentException ( "object, field name, and \"where\" must not be empty or null." ) ; } final Field field = getField ( fieldName , where ) ; try { field . set ( object , value ) ; } catch ( Exception e ) { throw new RuntimeException ( "Internal Error: Failed to set field in method setInternalState." , e ) ; } } | Set the value of a field using reflection . Use this method when you need to specify in which class the field is declared . This is useful if you have two fields in a class hierarchy that has the same name but you like to modify the latter . |
10,563 | private static Field findField ( Object object , FieldMatcherStrategy strategy , Class < ? > where ) { return findSingleFieldUsingStrategy ( strategy , object , false , where ) ; } | Find field . |
10,564 | private static Set < Field > findAllFieldsUsingStrategy ( FieldMatcherStrategy strategy , Object object , boolean checkHierarchy , Class < ? > startClass ) { assertObjectInGetInternalStateIsNotNull ( object ) ; final Set < Field > foundFields = new LinkedHashSet < Field > ( ) ; while ( startClass != null ) { final Field [ ] declaredFields = startClass . getDeclaredFields ( ) ; for ( Field field : declaredFields ) { if ( strategy . matches ( field ) && hasFieldProperModifier ( object , field ) ) { try { field . setAccessible ( true ) ; foundFields . add ( field ) ; } catch ( Exception ignored ) { } } } if ( ! checkHierarchy ) { break ; } startClass = startClass . getSuperclass ( ) ; } return Collections . unmodifiableSet ( foundFields ) ; } | Find all fields using strategy . |
10,565 | @ SuppressWarnings ( "unchecked" ) public static synchronized < T > T invokeMethod ( Object tested , Object ... arguments ) throws Exception { return ( T ) doInvokeMethod ( tested , null , null , arguments ) ; } | Invoke a private or inner class method without the need to specify the method name . This is thus a more refactor friendly version of the |
10,566 | @ SuppressWarnings ( "unchecked" ) public static synchronized < T > T invokeMethod ( Object tested , Class < ? > declaringClass , String methodToExecute , Object ... arguments ) throws Exception { return ( T ) doInvokeMethod ( tested , declaringClass , methodToExecute , arguments ) ; } | Invoke a private or inner class method in that is located in a subclass of the tested instance . This might be useful to test private methods . |
10,567 | @ SuppressWarnings ( "unchecked" ) public static synchronized < T > T invokeMethod ( Object object , Class < ? > declaringClass , String methodToExecute , Class < ? > [ ] parameterTypes , Object ... arguments ) throws Exception { if ( object == null ) { throw new IllegalArgumentException ( "object cannot be null" ) ; } final Method methodToInvoke = getMethod ( declaringClass , methodToExecute , parameterTypes ) ; return ( T ) performMethodInvocation ( object , methodToInvoke , arguments ) ; } | Invoke a private method in that is located in a subclass of an instance . This might be useful to test overloaded private methods . |
10,568 | @ SuppressWarnings ( "unchecked" ) private static < T > T doInvokeMethod ( Object tested , Class < ? > declaringClass , String methodToExecute , Object ... arguments ) throws Exception { Method methodToInvoke = findMethodOrThrowException ( tested , declaringClass , methodToExecute , arguments ) ; return ( T ) performMethodInvocation ( tested , methodToInvoke , arguments ) ; } | Do invoke method . |
10,569 | public static Method findMethodOrThrowException ( Object tested , Class < ? > declaringClass , String methodToExecute , Object [ ] arguments ) { if ( tested == null ) { throw new IllegalArgumentException ( "The object to perform the operation on cannot be null." ) ; } Class < ? > testedType = null ; if ( isClass ( tested ) ) { testedType = ( Class < ? > ) tested ; } else { testedType = tested . getClass ( ) ; } Method [ ] methods = null ; if ( declaringClass == null ) { methods = getAllMethods ( testedType ) ; } else { methods = declaringClass . getDeclaredMethods ( ) ; } Method potentialMethodToInvoke = null ; for ( Method method : methods ) { if ( methodToExecute == null || method . getName ( ) . equals ( methodToExecute ) ) { Class < ? > [ ] paramTypes = method . getParameterTypes ( ) ; if ( ( arguments != null && ( paramTypes . length == arguments . length ) ) ) { if ( paramTypes . length == 0 ) { potentialMethodToInvoke = method ; break ; } boolean methodFound = checkArgumentTypesMatchParameterTypes ( method . isVarArgs ( ) , paramTypes , arguments ) ; if ( methodFound ) { if ( potentialMethodToInvoke == null ) { potentialMethodToInvoke = method ; } else if ( potentialMethodToInvoke . getName ( ) . equals ( method . getName ( ) ) ) { if ( areAllArgumentsOfSameType ( arguments ) && potentialMethodToInvoke . getDeclaringClass ( ) != method . getDeclaringClass ( ) ) { return potentialMethodToInvoke ; } else { return getBestMethodCandidate ( getType ( tested ) , method . getName ( ) , getTypes ( arguments ) , false ) ; } } else { Method bestCandidateMethod = getMethodWithMostSpecificParameterTypes ( method , potentialMethodToInvoke ) ; if ( bestCandidateMethod != null ) { potentialMethodToInvoke = bestCandidateMethod ; continue ; } throwExceptionWhenMultipleMethodMatchesFound ( "argument parameter types" , new Method [ ] { potentialMethodToInvoke , method } ) ; } } } else if ( isPotentialVarArgsMethod ( method , arguments ) ) { if ( potentialMethodToInvoke == null ) { potentialMethodToInvoke = method ; } else { throwExceptionWhenMultipleMethodMatchesFound ( "argument parameter types" , new Method [ ] { potentialMethodToInvoke , method } ) ; } break ; } else if ( arguments != null && ( paramTypes . length != arguments . length ) ) { continue ; } else if ( arguments == null && paramTypes . length == 1 && ! paramTypes [ 0 ] . isPrimitive ( ) ) { potentialMethodToInvoke = method ; } } } WhiteboxImpl . throwExceptionIfMethodWasNotFound ( getType ( tested ) , methodToExecute , potentialMethodToInvoke , arguments ) ; return potentialMethodToInvoke ; } | Finds and returns a certain method . If the method couldn t be found this method delegates to |
10,570 | private static Class < ? > [ ] getTypes ( Object [ ] arguments ) { Class < ? > [ ] classes = new Class < ? > [ arguments . length ] ; for ( int i = 0 ; i < arguments . length ; i ++ ) { classes [ i ] = getType ( arguments [ i ] ) ; } return classes ; } | Gets the types . |
10,571 | public static Method getBestMethodCandidate ( Class < ? > cls , String methodName , Class < ? > [ ] signature , boolean exactParameterTypeMatch ) { final Method foundMethod ; final Method [ ] methods = getMethods ( cls , methodName , signature , exactParameterTypeMatch ) ; if ( methods . length == 1 ) { foundMethod = methods [ 0 ] ; } else { Arrays . sort ( methods , ComparatorFactory . createMethodComparator ( ) ) ; foundMethod = methods [ 0 ] ; } return foundMethod ; } | Gets the best method candidate . |
10,572 | static Constructor < ? > [ ] filterPowerMockConstructor ( Constructor < ? > [ ] declaredConstructors ) { Set < Constructor < ? > > constructors = new HashSet < Constructor < ? > > ( ) ; for ( Constructor < ? > constructor : declaredConstructors ) { final Class < ? > [ ] parameterTypes = constructor . getParameterTypes ( ) ; if ( parameterTypes . length >= 1 && parameterTypes [ parameterTypes . length - 1 ] . getName ( ) . equals ( "org.powermock.core.IndicateReloadClass" ) ) { continue ; } else { constructors . add ( constructor ) ; } } return constructors . toArray ( new Constructor < ? > [ constructors . size ( ) ] ) ; } | Filter power mock constructor . |
10,573 | public static Constructor < ? > findUniqueConstructorOrThrowException ( Class < ? > type , Object ... arguments ) { return new ConstructorFinder ( type , arguments ) . findConstructor ( ) ; } | Finds and returns a certain constructor . If the constructor couldn t be found this method delegates to |
10,574 | private static Class < ? > [ ] convertArgumentTypesToPrimitive ( Class < ? > [ ] paramTypes , Object [ ] arguments ) { Class < ? > [ ] types = new Class < ? > [ arguments . length ] ; for ( int i = 0 ; i < arguments . length ; i ++ ) { Class < ? > argumentType = null ; if ( arguments [ i ] == null ) { argumentType = paramTypes [ i ] ; } else { argumentType = getType ( arguments [ i ] ) ; } Class < ? > primitiveWrapperType = PrimitiveWrapper . getPrimitiveFromWrapperType ( argumentType ) ; if ( primitiveWrapperType == null ) { types [ i ] = argumentType ; } else { types [ i ] = primitiveWrapperType ; } } return types ; } | Convert argument types to primitive . |
10,575 | public static void throwExceptionIfMethodWasNotFound ( Class < ? > type , String methodName , Method methodToMock , Object ... arguments ) { if ( methodToMock == null ) { String methodNameData = "" ; if ( methodName != null ) { methodNameData = "with name '" + methodName + "' " ; } throw new MethodNotFoundException ( "No method found " + methodNameData + "with parameter types: [ " + getArgumentTypesAsString ( arguments ) + " ] in class " + getOriginalUnmockedType ( type ) . getName ( ) + "." ) ; } } | Throw exception if method was not found . |
10,576 | static void throwExceptionIfConstructorWasNotFound ( Class < ? > type , Constructor < ? > potentialConstructor , Object ... arguments ) { if ( potentialConstructor == null ) { String message = "No constructor found in class '" + getOriginalUnmockedType ( type ) . getName ( ) + "' with " + "parameter types: [ " + getArgumentTypesAsString ( arguments ) + " ]." ; throw new ConstructorNotFoundException ( message ) ; } } | Throw exception if constructor was not found . |
10,577 | static String getArgumentTypesAsString ( Object ... arguments ) { StringBuilder argumentsAsString = new StringBuilder ( ) ; final String noParameters = "<none>" ; if ( arguments != null && arguments . length != 0 ) { for ( int i = 0 ; i < arguments . length ; i ++ ) { String argumentName = null ; Object argument = arguments [ i ] ; if ( argument instanceof Class < ? > ) { argumentName = ( ( Class < ? > ) argument ) . getName ( ) ; } else if ( argument instanceof Class < ? > [ ] && arguments . length == 1 ) { Class < ? > [ ] argumentArray = ( Class < ? > [ ] ) argument ; if ( argumentArray . length > 0 ) { for ( int j = 0 ; j < argumentArray . length ; j ++ ) { appendArgument ( argumentsAsString , j , argumentArray [ j ] == null ? "null" : getUnproxyType ( argumentArray [ j ] ) . getName ( ) , argumentArray ) ; } return argumentsAsString . toString ( ) ; } else { argumentName = noParameters ; } } else if ( argument == null ) { argumentName = "null" ; } else { argumentName = getUnproxyType ( argument ) . getName ( ) ; } appendArgument ( argumentsAsString , i , argumentName , arguments ) ; } } else { argumentsAsString . append ( "<none>" ) ; } return argumentsAsString . toString ( ) ; } | Gets the argument types as string . |
10,578 | private static void appendArgument ( StringBuilder argumentsAsString , int index , String argumentName , Object [ ] arguments ) { argumentsAsString . append ( argumentName ) ; if ( index != arguments . length - 1 ) { argumentsAsString . append ( ", " ) ; } } | Append argument . |
10,579 | public static < T > T invokeConstructor ( Class < T > classThatContainsTheConstructorToTest , Object ... arguments ) throws Exception { if ( classThatContainsTheConstructorToTest == null ) { throw new IllegalArgumentException ( "The class should contain the constructor cannot be null." ) ; } Class < ? > [ ] argumentTypes = null ; if ( arguments == null ) { argumentTypes = new Class < ? > [ 0 ] ; } else { argumentTypes = new Class < ? > [ arguments . length ] ; for ( int i = 0 ; i < arguments . length ; i ++ ) { argumentTypes [ i ] = getType ( arguments [ i ] ) ; } } Constructor < T > constructor = null ; constructor = getBestCandidateConstructor ( classThatContainsTheConstructorToTest , argumentTypes , arguments ) ; return createInstance ( constructor , arguments ) ; } | Invoke a constructor . Useful for testing classes with a private constructor . |
10,580 | @ SuppressWarnings ( "unchecked" ) private static < T > Constructor < T > getPotentialVarArgsConstructor ( Class < T > classThatContainsTheConstructorToTest , Object ... arguments ) { Constructor < T > [ ] declaredConstructors = ( Constructor < T > [ ] ) classThatContainsTheConstructorToTest . getDeclaredConstructors ( ) ; for ( Constructor < T > possibleVarArgsConstructor : declaredConstructors ) { if ( possibleVarArgsConstructor . isVarArgs ( ) ) { if ( arguments == null || arguments . length == 0 ) { return possibleVarArgsConstructor ; } else { Class < ? > [ ] parameterTypes = possibleVarArgsConstructor . getParameterTypes ( ) ; if ( parameterTypes [ parameterTypes . length - 1 ] . getComponentType ( ) . isAssignableFrom ( getType ( arguments [ 0 ] ) ) ) { return possibleVarArgsConstructor ; } } } } return null ; } | Gets the potential var args constructor . |
10,581 | private static < T > T createInstance ( Constructor < T > constructor , Object ... arguments ) throws Exception { if ( constructor == null ) { throw new IllegalArgumentException ( "Constructor cannot be null" ) ; } constructor . setAccessible ( true ) ; T createdObject = null ; try { if ( constructor . isVarArgs ( ) ) { Class < ? > [ ] parameterTypes = constructor . getParameterTypes ( ) ; final int varArgsIndex = parameterTypes . length - 1 ; Class < ? > varArgsType = parameterTypes [ varArgsIndex ] . getComponentType ( ) ; Object varArgsArrayInstance = createAndPopulateVarArgsArray ( varArgsType , varArgsIndex , arguments ) ; Object [ ] completeArgumentList = new Object [ parameterTypes . length ] ; System . arraycopy ( arguments , 0 , completeArgumentList , 0 , varArgsIndex ) ; completeArgumentList [ completeArgumentList . length - 1 ] = varArgsArrayInstance ; createdObject = constructor . newInstance ( completeArgumentList ) ; } else { createdObject = constructor . newInstance ( arguments ) ; } } catch ( InvocationTargetException e ) { Throwable cause = e . getCause ( ) ; if ( cause instanceof Exception ) { throw ( Exception ) cause ; } else if ( cause instanceof Error ) { throw ( Error ) cause ; } } return createdObject ; } | Creates the instance . |
10,582 | private static Object createAndPopulateVarArgsArray ( Class < ? > varArgsType , int varArgsStartPosition , Object ... arguments ) { Object arrayInstance = Array . newInstance ( varArgsType , arguments . length - varArgsStartPosition ) ; for ( int i = varArgsStartPosition ; i < arguments . length ; i ++ ) { Array . set ( arrayInstance , i - varArgsStartPosition , arguments [ i ] ) ; } return arrayInstance ; } | Creates the and populate var args array . |
10,583 | static void throwExceptionWhenMultipleMethodMatchesFound ( String helpInfo , Method [ ] methods ) { if ( methods == null || methods . length < 2 ) { throw new IllegalArgumentException ( "Internal error: throwExceptionWhenMultipleMethodMatchesFound needs at least two methods." ) ; } StringBuilder sb = new StringBuilder ( ) ; sb . append ( "Several matching methods found, please specify the " ) ; sb . append ( helpInfo ) ; sb . append ( " so that PowerMock can determine which method you're referring to.\n" ) ; sb . append ( "Matching methods in class " ) . append ( methods [ 0 ] . getDeclaringClass ( ) . getName ( ) ) . append ( " were:\n" ) ; for ( Method method : methods ) { sb . append ( method . getReturnType ( ) . getName ( ) ) . append ( " " ) ; sb . append ( method . getName ( ) ) . append ( "( " ) ; final Class < ? > [ ] parameterTypes = method . getParameterTypes ( ) ; for ( Class < ? > paramType : parameterTypes ) { sb . append ( paramType . getName ( ) ) . append ( ".class " ) ; } sb . append ( ")\n" ) ; } throw new TooManyMethodsFoundException ( sb . toString ( ) ) ; } | Throw exception when multiple method matches found . |
10,584 | static void throwExceptionWhenMultipleConstructorMatchesFound ( Constructor < ? > [ ] constructors ) { if ( constructors == null || constructors . length < 2 ) { throw new IllegalArgumentException ( "Internal error: throwExceptionWhenMultipleConstructorMatchesFound needs at least two constructors." ) ; } StringBuilder sb = new StringBuilder ( ) ; sb . append ( "Several matching constructors found, please specify the argument parameter types so that PowerMock can determine which method you're referring to.\n" ) ; sb . append ( "Matching constructors in class " ) . append ( constructors [ 0 ] . getDeclaringClass ( ) . getName ( ) ) . append ( " were:\n" ) ; for ( Constructor < ? > constructor : constructors ) { sb . append ( constructor . getName ( ) ) . append ( "( " ) ; final Class < ? > [ ] parameterTypes = constructor . getParameterTypes ( ) ; for ( Class < ? > paramType : parameterTypes ) { sb . append ( paramType . getName ( ) ) . append ( ".class " ) ; } sb . append ( ")\n" ) ; } throw new TooManyConstructorsFoundException ( sb . toString ( ) ) ; } | Throw exception when multiple constructor matches found . |
10,585 | @ SuppressWarnings ( "all" ) public static Method findMethodOrThrowException ( Class < ? > type , String methodName , Class < ? > ... parameterTypes ) { Method methodToMock = findMethod ( type , methodName , parameterTypes ) ; throwExceptionIfMethodWasNotFound ( type , methodName , methodToMock , ( Object [ ] ) parameterTypes ) ; return methodToMock ; } | Find method or throw exception . |
10,586 | @ SuppressWarnings ( "unchecked" ) public static < T > T performMethodInvocation ( Object tested , Method methodToInvoke , Object ... arguments ) throws Exception { final boolean accessible = methodToInvoke . isAccessible ( ) ; if ( ! accessible ) { methodToInvoke . setAccessible ( true ) ; } try { if ( isPotentialVarArgsMethod ( methodToInvoke , arguments ) ) { Class < ? > [ ] parameterTypes = methodToInvoke . getParameterTypes ( ) ; final int varArgsIndex = parameterTypes . length - 1 ; Class < ? > varArgsType = parameterTypes [ varArgsIndex ] . getComponentType ( ) ; Object varArgsArrayInstance = createAndPopulateVarArgsArray ( varArgsType , varArgsIndex , arguments ) ; Object [ ] completeArgumentList = new Object [ parameterTypes . length ] ; System . arraycopy ( arguments , 0 , completeArgumentList , 0 , varArgsIndex ) ; completeArgumentList [ completeArgumentList . length - 1 ] = varArgsArrayInstance ; return ( T ) methodToInvoke . invoke ( tested , completeArgumentList ) ; } else { return ( T ) methodToInvoke . invoke ( tested , arguments == null ? new Object [ ] { arguments } : arguments ) ; } } catch ( InvocationTargetException e ) { Throwable cause = e . getCause ( ) ; if ( cause instanceof Exception ) { throw ( Exception ) cause ; } else if ( cause instanceof Error ) { throw ( Error ) cause ; } else { throw new MethodInvocationException ( cause ) ; } } finally { if ( ! accessible ) { methodToInvoke . setAccessible ( false ) ; } } } | Perform method invocation . |
10,587 | public static < T > Method [ ] getAllMethodExcept ( Class < T > type , String ... methodNames ) { List < Method > methodsToMock = new LinkedList < Method > ( ) ; Method [ ] methods = getAllMethods ( type ) ; iterateMethods : for ( Method method : methods ) { for ( String methodName : methodNames ) { if ( method . getName ( ) . equals ( methodName ) ) { continue iterateMethods ; } } methodsToMock . add ( method ) ; } return methodsToMock . toArray ( new Method [ 0 ] ) ; } | Gets the all method except . |
10,588 | public static < T > Method [ ] getAllMethodsExcept ( Class < T > type , String methodNameToExclude , Class < ? > [ ] argumentTypes ) { Method [ ] methods = getAllMethods ( type ) ; List < Method > methodList = new ArrayList < Method > ( ) ; outer : for ( Method method : methods ) { if ( method . getName ( ) . equals ( methodNameToExclude ) ) { if ( argumentTypes != null && argumentTypes . length > 0 ) { final Class < ? > [ ] args = method . getParameterTypes ( ) ; if ( args != null && args . length == argumentTypes . length ) { for ( int i = 0 ; i < args . length ; i ++ ) { if ( args [ i ] . isAssignableFrom ( getOriginalUnmockedType ( argumentTypes [ i ] ) ) ) { continue outer ; } } } } else { continue ; } } methodList . add ( method ) ; } return methodList . toArray ( new Method [ 0 ] ) ; } | Gets the all metods except . |
10,589 | public static boolean areAllMethodsStatic ( Method ... methods ) { for ( Method method : methods ) { if ( ! Modifier . isStatic ( method . getModifiers ( ) ) ) { return false ; } } return true ; } | Are all methods static . |
10,590 | static boolean areAllArgumentsOfSameType ( Object [ ] arguments ) { if ( arguments == null || arguments . length <= 1 ) { return true ; } int index = 0 ; Object object = null ; while ( object == null && index < arguments . length ) { object = arguments [ index ++ ] ; } if ( object == null ) { return true ; } final Class < ? > firstArgumentType = getType ( object ) ; for ( int i = index ; i < arguments . length ; i ++ ) { final Object argument = arguments [ i ] ; if ( argument != null && ! getType ( argument ) . isAssignableFrom ( firstArgumentType ) ) { return false ; } } return true ; } | Check if all arguments are of the same type . |
10,591 | static boolean checkArgumentTypesMatchParameterTypes ( boolean isVarArgs , Class < ? > [ ] parameterTypes , Object [ ] arguments ) { if ( parameterTypes == null ) { throw new IllegalArgumentException ( "parameter types cannot be null" ) ; } else if ( ! isVarArgs && arguments . length != parameterTypes . length ) { return false ; } for ( int i = 0 ; i < arguments . length ; i ++ ) { Object argument = arguments [ i ] ; if ( argument == null ) { final int index ; if ( i >= parameterTypes . length ) { index = parameterTypes . length - 1 ; } else { index = i ; } final Class < ? > type = parameterTypes [ index ] ; if ( type . isPrimitive ( ) ) { return false ; } else { continue ; } } else if ( i >= parameterTypes . length ) { if ( isAssignableFrom ( parameterTypes [ parameterTypes . length - 1 ] , getType ( argument ) ) ) { continue ; } else { return false ; } } else { boolean assignableFrom = isAssignableFrom ( parameterTypes [ i ] , getType ( argument ) ) ; final boolean isClass = parameterTypes [ i ] . equals ( Class . class ) && isClass ( argument ) ; if ( ! assignableFrom && ! isClass ) { return false ; } } } return true ; } | Check argument types match parameter types . |
10,592 | @ SuppressWarnings ( "unchecked" ) public static Class < Object > getInnerClassType ( Class < ? > declaringClass , String name ) throws ClassNotFoundException { return ( Class < Object > ) Class . forName ( declaringClass . getName ( ) + "$" + name ) ; } | Get an inner class type . |
10,593 | public static Set < Field > getAllInstanceFields ( Object object ) { return findAllFieldsUsingStrategy ( new AllFieldsMatcherStrategy ( ) , object , true , getUnproxyType ( object ) ) ; } | Get all instance fields for a particular object . It returns all fields regardless of the field modifier and regardless of where in the class hierarchy a field is located . |
10,594 | public static Set < Field > getAllStaticFields ( Class < ? > type ) { final Set < Field > fields = new LinkedHashSet < Field > ( ) ; final Field [ ] declaredFields = type . getDeclaredFields ( ) ; for ( Field field : declaredFields ) { if ( Modifier . isStatic ( field . getModifiers ( ) ) ) { field . setAccessible ( true ) ; fields . add ( field ) ; } } return fields ; } | Get all static fields for a particular type . |
10,595 | public static boolean checkIfParameterTypesAreSame ( boolean isVarArgs , Class < ? > [ ] expectedParameterTypes , Class < ? > [ ] actualParameterTypes ) { return new ParameterTypesMatcher ( isVarArgs , expectedParameterTypes , actualParameterTypes ) . match ( ) ; } | Check if parameter types are same . |
10,596 | private static Field findFieldOrThrowException ( Class < ? > fieldType , Class < ? > where ) { if ( fieldType == null || where == null ) { throw new IllegalArgumentException ( "fieldType and where cannot be null" ) ; } Field field = null ; for ( Field currentField : where . getDeclaredFields ( ) ) { currentField . setAccessible ( true ) ; if ( currentField . getType ( ) . equals ( fieldType ) ) { field = currentField ; break ; } } if ( field == null ) { throw new FieldNotFoundException ( "Cannot find a field of type " + fieldType + "in where." ) ; } return field ; } | Find field or throw exception . |
10,597 | private static String concatenateStrings ( String ... stringsToConcatenate ) { StringBuilder builder = new StringBuilder ( ) ; final int stringsLength = stringsToConcatenate . length ; for ( int i = 0 ; i < stringsLength ; i ++ ) { if ( i == stringsLength - 1 && stringsLength != 1 ) { builder . append ( " or " ) ; } else if ( i != 0 ) { builder . append ( ", " ) ; } builder . append ( stringsToConcatenate [ i ] ) ; } return builder . toString ( ) ; } | Concatenate strings . |
10,598 | private static boolean isPotentialVarArgsMethod ( Method method , Object [ ] arguments ) { return doesParameterTypesMatchForVarArgsInvocation ( method . isVarArgs ( ) , method . getParameterTypes ( ) , arguments ) ; } | Checks if is potential var args method . |
10,599 | static boolean doesParameterTypesMatchForVarArgsInvocation ( boolean isVarArgs , Class < ? > [ ] parameterTypes , Object [ ] arguments ) { if ( isVarArgs && arguments != null && arguments . length >= 1 && parameterTypes != null && parameterTypes . length >= 1 ) { final Class < ? > componentType = parameterTypes [ parameterTypes . length - 1 ] . getComponentType ( ) ; final Object lastArgument = arguments [ arguments . length - 1 ] ; if ( lastArgument != null ) { final Class < ? > lastArgumentTypeAsPrimitive = getTypeAsPrimitiveIfWrapped ( lastArgument ) ; final Class < ? > varArgsParameterTypeAsPrimitive = getTypeAsPrimitiveIfWrapped ( componentType ) ; isVarArgs = varArgsParameterTypeAsPrimitive . isAssignableFrom ( lastArgumentTypeAsPrimitive ) ; } } return isVarArgs && checkArgumentTypesMatchParameterTypes ( isVarArgs , parameterTypes , arguments ) ; } | Does parameter types match for var args invocation . |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.