signature
stringlengths
43
39.1k
implementation
stringlengths
0
450k
public class Model { /** * Single row scoring , on a compatible Frame . */ public final float [ ] score ( Frame fr , boolean exact , int row ) { } }
double tmp [ ] = new double [ fr . numCols ( ) ] ; for ( int i = 0 ; i < tmp . length ; i ++ ) tmp [ i ] = fr . vecs ( ) [ i ] . at ( row ) ; return score ( fr . names ( ) , fr . domains ( ) , exact , tmp ) ;
public class EJSHome { /** * Activates and returns the remote < code > EJBObject < / code > associated * with the specified primary key for this home . < p > * If the bean defined by primaryKey is already active then returns * the active instance . Otherwise , the bean is activated ( ejbActivate ) * and loaded ( ejbLoad ) . < p > * This method is intended to be called by the deployed / generated * findByPrimaryKey method on the home . This applies to BMP , * CMP 2 . x ( with and without inheritance ) and CMP 1 . x ( without * inheritance ) . < p > * For CMP 1 . x with inheritance , refer to getBean ( key , data ) and * getBean ( type , key , data ) . < p > * @ param primaryKey the < code > Object < / code > containing the primary * key of the < code > EJBObject < / code > to return . * @ return the < code > EJBObject < / code > associated with the specified * primary key . * @ exception FinderException thrown if a finder - specific * error occurs ( such as no object with corresponding * primary key ) . * @ exception RemoteException thrown if a system exception occurs while * trying to locate the < code > EJBObject < / code > instance * corresponding to the primary key . */ @ Override public EJBObject activateBean ( Object primaryKey ) throws FinderException , RemoteException { } }
EJSWrapperCommon wrappers = null ; // d215317 // Single - object ejbSelect methods may result in a null value , // and since this code path also supports ejbSelect , null must // be tolerated and returned . d149627 if ( primaryKey == null ) { if ( TraceComponent . isAnyTracingEnabled ( ) && tc . isDebugEnabled ( ) ) Tr . debug ( tc , "activateBean : key = null, returning null" ) ; return null ; } // If noLocalCopies and allowPrimaryKeyMutation are true then we // must create a deep copy of the primaryKey object to avoid data // corruption . PQ62081 d138865 // The copy will actually be made in activateBean _ Common only if the // primary key is used to insert into the cache , but the determination // must be done here , as it is different for local and remote . d215317 // " Primary Key " should not be copied for a StatefulSession bean . d247634 boolean pkeyCopyRequired = false ; if ( noLocalCopies && allowPrimaryKeyMutation && ! statefulSessionHome ) { pkeyCopyRequired = true ; } wrappers = ivEntityHelper . activateBean_Common ( this , primaryKey , pkeyCopyRequired ) ; return wrappers . getRemoteWrapper ( ) ; // f111627
public class ClassNodeResolver { /** * Search for classes using class loading */ private static LookupResult findByClassLoading ( String name , CompilationUnit compilationUnit , GroovyClassLoader loader ) { } }
Class cls ; try { // NOTE : it ' s important to do no lookup against script files // here since the GroovyClassLoader would create a new CompilationUnit cls = loader . loadClass ( name , false , true ) ; } catch ( ClassNotFoundException cnfe ) { LookupResult lr = tryAsScript ( name , compilationUnit , null ) ; return lr ; } catch ( CompilationFailedException cfe ) { throw new GroovyBugError ( "The lookup for " + name + " caused a failed compilation. There should not have been any compilation from this call." , cfe ) ; } // TODO : the case of a NoClassDefFoundError needs a bit more research // a simple recompilation is not possible it seems . The current class // we are searching for is there , so we should mark that somehow . // Basically the missing class needs to be completely compiled before // we can again search for the current name . /* catch ( NoClassDefFoundError ncdfe ) { cachedClasses . put ( name , SCRIPT ) ; return false ; */ if ( cls == null ) return null ; // NOTE : we might return false here even if we found a class , // because we want to give a possible script a chance to // recompile . This can only be done if the loader was not // the instance defining the class . ClassNode cn = ClassHelper . make ( cls ) ; if ( cls . getClassLoader ( ) != loader ) { return tryAsScript ( name , compilationUnit , cn ) ; } return new LookupResult ( null , cn ) ;
public class BondMaker { /** * Creates bond objects from a LinkRecord as parsed from a PDB file * @ param linkRecord */ public void formLinkRecordBond ( LinkRecord linkRecord ) { } }
// only work with atoms that aren ' t alternate locations if ( linkRecord . getAltLoc1 ( ) . equals ( " " ) || linkRecord . getAltLoc2 ( ) . equals ( " " ) ) return ; try { Map < Integer , Atom > a = getAtomFromRecord ( linkRecord . getName1 ( ) , linkRecord . getAltLoc1 ( ) , linkRecord . getResName1 ( ) , linkRecord . getChainID1 ( ) , linkRecord . getResSeq1 ( ) , linkRecord . getiCode1 ( ) ) ; Map < Integer , Atom > b = getAtomFromRecord ( linkRecord . getName2 ( ) , linkRecord . getAltLoc2 ( ) , linkRecord . getResName2 ( ) , linkRecord . getChainID2 ( ) , linkRecord . getResSeq2 ( ) , linkRecord . getiCode2 ( ) ) ; for ( int i = 0 ; i < structure . nrModels ( ) ; i ++ ) { if ( a . containsKey ( i ) && b . containsKey ( i ) ) { // TODO determine what the actual bond order of this bond is ; for // now , we ' re assuming they ' re single bonds if ( ! a . get ( i ) . equals ( b . get ( i ) ) ) { new BondImpl ( a . get ( i ) , b . get ( i ) , 1 ) ; } } } } catch ( StructureException e ) { // Note , in Calpha only mode the link atoms may not be present . if ( ! params . isParseCAOnly ( ) ) { logger . warn ( "Could not find atoms specified in LINK record: {}" , linkRecord . toString ( ) ) ; } else { logger . debug ( "Could not find atoms specified in LINK record while parsing in parseCAonly mode." ) ; } }
public class Maps { /** * Computes the difference between two sorted maps , using the comparator of * the left map , or { @ code Ordering . natural ( ) } if the left map uses the * natural ordering of its elements . This difference is an immutable snapshot * of the state of the maps at the time this method is called . It will never * change , even if the maps change at a later time . * < p > Since this method uses { @ code TreeMap } instances internally , the keys of * the right map must all compare as distinct according to the comparator * of the left map . * < p > < b > Note : < / b > If you only need to know whether two sorted maps have the * same mappings , call { @ code left . equals ( right ) } instead of this method . * @ param left the map to treat as the " left " map for purposes of comparison * @ param right the map to treat as the " right " map for purposes of comparison * @ return the difference between the two maps * @ since 11.0 */ public static < K , V > SortedMapDifference < K , V > difference ( SortedMap < K , ? extends V > left , Map < ? extends K , ? extends V > right ) { } }
checkNotNull ( left ) ; checkNotNull ( right ) ; Comparator < ? super K > comparator = orNaturalOrder ( left . comparator ( ) ) ; SortedMap < K , V > onlyOnLeft = Maps . newTreeMap ( comparator ) ; SortedMap < K , V > onlyOnRight = Maps . newTreeMap ( comparator ) ; onlyOnRight . putAll ( right ) ; // will whittle it down SortedMap < K , V > onBoth = Maps . newTreeMap ( comparator ) ; SortedMap < K , MapDifference . ValueDifference < V > > differences = Maps . newTreeMap ( comparator ) ; doDifference ( left , right , Equivalence . equals ( ) , onlyOnLeft , onlyOnRight , onBoth , differences ) ; return new SortedMapDifferenceImpl < K , V > ( onlyOnLeft , onlyOnRight , onBoth , differences ) ;
public class AuthorizationHandler { /** * Checks if any of the given strings is blank * @ param subject The subject to validate * @ param resource The resource to validate * @ param operation The operation to validate * @ return True if all strings are not blank , false otherwise */ private boolean isNotBlank ( String subject , String resource , String operation ) { } }
return StringUtils . isNotBlank ( subject ) && StringUtils . isNotBlank ( resource ) && StringUtils . isNotBlank ( operation ) ;
public class MatchExptScript { /** * Load commands from a file and execute them . */ public void runScript ( String configFileName ) { } }
int lineNum = 0 ; try { BufferedReader in = new BufferedReader ( new FileReader ( configFileName ) ) ; String line ; while ( ( line = in . readLine ( ) ) != null ) { lineNum ++ ; if ( ! line . startsWith ( "#" ) ) { String command = null ; List args = new ArrayList ( ) ; StringTokenizer tok = new StringTokenizer ( line ) ; if ( tok . hasMoreTokens ( ) ) { command = tok . nextToken ( ) ; } while ( tok . hasMoreTokens ( ) ) { args . add ( tok . nextToken ( ) ) ; } if ( command != null ) { if ( echoCommands ) System . out . println ( "exec: " + line ) ; execCommand ( command , args ) ; } } } } catch ( Exception e ) { System . out . println ( "Error: " + configFileName + " line " + lineNum + ": " + e . toString ( ) ) ; e . printStackTrace ( ) ; return ; }
public class BaseValidatingInterceptor { /** * Note : May return null */ protected ValidationResult validate ( T theRequest , RequestDetails theRequestDetails ) { } }
FhirValidator validator = theRequestDetails . getServer ( ) . getFhirContext ( ) . newValidator ( ) ; if ( myValidatorModules != null ) { for ( IValidatorModule next : myValidatorModules ) { validator . registerValidatorModule ( next ) ; } } if ( theRequest == null ) { return null ; } ValidationResult validationResult ; try { validationResult = doValidate ( validator , theRequest ) ; } catch ( Exception e ) { if ( myIgnoreValidatorExceptions ) { ourLog . warn ( "Validator threw an exception during validation" , e ) ; return null ; } if ( e instanceof BaseServerResponseException ) { throw ( BaseServerResponseException ) e ; } throw new InternalErrorException ( e ) ; } if ( myAddResponseIssueHeaderOnSeverity != null ) { boolean found = false ; for ( SingleValidationMessage next : validationResult . getMessages ( ) ) { if ( next . getSeverity ( ) . ordinal ( ) >= myAddResponseIssueHeaderOnSeverity ) { addResponseIssueHeader ( theRequestDetails , next ) ; found = true ; } } if ( ! found ) { if ( isNotBlank ( myResponseIssueHeaderValueNoIssues ) ) { theRequestDetails . getResponse ( ) . addHeader ( myResponseIssueHeaderName , myResponseIssueHeaderValueNoIssues ) ; } } } if ( myFailOnSeverity != null ) { for ( SingleValidationMessage next : validationResult . getMessages ( ) ) { if ( next . getSeverity ( ) . ordinal ( ) >= myFailOnSeverity ) { postProcessResultOnFailure ( theRequestDetails , validationResult ) ; fail ( theRequestDetails , validationResult ) ; return validationResult ; } } } if ( myAddResponseOutcomeHeaderOnSeverity != null ) { IBaseOperationOutcome outcome = null ; for ( SingleValidationMessage next : validationResult . getMessages ( ) ) { if ( next . getSeverity ( ) . ordinal ( ) >= myAddResponseOutcomeHeaderOnSeverity ) { outcome = validationResult . toOperationOutcome ( ) ; break ; } } if ( outcome == null && myAddResponseOutcomeHeaderOnSeverity != null && myAddResponseOutcomeHeaderOnSeverity == ResultSeverityEnum . INFORMATION . ordinal ( ) ) { FhirContext ctx = theRequestDetails . getServer ( ) . getFhirContext ( ) ; outcome = OperationOutcomeUtil . newInstance ( ctx ) ; OperationOutcomeUtil . addIssue ( ctx , outcome , "information" , "No issues detected" , "" , "informational" ) ; } if ( outcome != null ) { IParser parser = theRequestDetails . getServer ( ) . getFhirContext ( ) . newJsonParser ( ) . setPrettyPrint ( false ) ; String encoded = parser . encodeResourceToString ( outcome ) ; if ( encoded . length ( ) > getMaximumHeaderLength ( ) ) { encoded = encoded . substring ( 0 , getMaximumHeaderLength ( ) - 3 ) + "..." ; } theRequestDetails . getResponse ( ) . addHeader ( myResponseOutcomeHeaderName , encoded ) ; } } postProcessResult ( theRequestDetails , validationResult ) ; return validationResult ;
public class VirtualMachinesInner { /** * Captures the VM by copying virtual hard disks of the VM and outputs a template that can be used to create similar VMs . * @ param resourceGroupName The name of the resource group . * @ param vmName The name of the virtual machine . * @ param parameters Parameters supplied to the Capture Virtual Machine operation . * @ throws IllegalArgumentException thrown if parameters fail the validation * @ return the observable for the request */ public Observable < ServiceResponse < VirtualMachineCaptureResultInner > > captureWithServiceResponseAsync ( String resourceGroupName , String vmName , VirtualMachineCaptureParameters parameters ) { } }
if ( resourceGroupName == null ) { throw new IllegalArgumentException ( "Parameter resourceGroupName is required and cannot be null." ) ; } if ( vmName == null ) { throw new IllegalArgumentException ( "Parameter vmName is required and cannot be null." ) ; } if ( this . client . subscriptionId ( ) == null ) { throw new IllegalArgumentException ( "Parameter this.client.subscriptionId() is required and cannot be null." ) ; } if ( parameters == null ) { throw new IllegalArgumentException ( "Parameter parameters is required and cannot be null." ) ; } if ( this . client . apiVersion ( ) == null ) { throw new IllegalArgumentException ( "Parameter this.client.apiVersion() is required and cannot be null." ) ; } Validator . validate ( parameters ) ; Observable < Response < ResponseBody > > observable = service . capture ( resourceGroupName , vmName , this . client . subscriptionId ( ) , parameters , this . client . apiVersion ( ) , this . client . acceptLanguage ( ) , this . client . userAgent ( ) ) ; return client . getAzureClient ( ) . getPostOrDeleteResultAsync ( observable , new TypeToken < VirtualMachineCaptureResultInner > ( ) { } . getType ( ) ) ;
public class TimeSpinnerTimer { /** * tick , This is called once each time that the timer fires . ( Every 20 milliseconds ) . * However , the value in the time picker will only be changed once for every certain number of * calls to the tick ( ) function . The number of calls which is required is controlled by the * " divisorList " array values . * The amount of time that is spent using each divisorList array value is controlled by the * " millisForIndexList " . */ private void tick ( ) { } }
if ( startedIndexTimeStamp == 0 ) { startedIndexTimeStamp = System . currentTimeMillis ( ) ; } long timeElapsedSinceIndexStartMilliseconds = System . currentTimeMillis ( ) - startedIndexTimeStamp ; int maximumIndex = divisorList . length - 1 ; int currentDivisor = divisorList [ currentIndex ] ; if ( ticksSinceIndexChange % currentDivisor == 0 ) { timePicker . zInternalTryChangeTimeByIncrement ( changeAmountMinutes ) ; // System . out . println ( " \ nMillis : " + System . currentTimeMillis ( ) ) ; // System . out . println ( " Divisor : " + divisor ) ; // System . out . println ( " Value : " + timePicker . getTime ( ) ) ; if ( ( currentIndex < maximumIndex ) && ( timeElapsedSinceIndexStartMilliseconds > millisForDivisorList [ currentIndex ] ) ) { ticksSinceIndexChange = 0 ; ++ currentIndex ; startedIndexTimeStamp = System . currentTimeMillis ( ) ; } } ++ ticksSinceIndexChange ;
public class DeliveryChannelMarshaller { /** * Marshall the given parameter object . */ public void marshall ( DeliveryChannel deliveryChannel , ProtocolMarshaller protocolMarshaller ) { } }
if ( deliveryChannel == null ) { throw new SdkClientException ( "Invalid argument passed to marshall(...)" ) ; } try { protocolMarshaller . marshall ( deliveryChannel . getName ( ) , NAME_BINDING ) ; protocolMarshaller . marshall ( deliveryChannel . getS3BucketName ( ) , S3BUCKETNAME_BINDING ) ; protocolMarshaller . marshall ( deliveryChannel . getS3KeyPrefix ( ) , S3KEYPREFIX_BINDING ) ; protocolMarshaller . marshall ( deliveryChannel . getSnsTopicARN ( ) , SNSTOPICARN_BINDING ) ; protocolMarshaller . marshall ( deliveryChannel . getConfigSnapshotDeliveryProperties ( ) , CONFIGSNAPSHOTDELIVERYPROPERTIES_BINDING ) ; } catch ( Exception e ) { throw new SdkClientException ( "Unable to marshall request to JSON: " + e . getMessage ( ) , e ) ; }
public class MemcachedSessionService { /** * Specifies the memcached protocol to use , either " text " ( default ) or " binary " . * @ param memcachedProtocol one of " text " or " binary " . */ public void setMemcachedProtocol ( final String memcachedProtocol ) { } }
if ( ! PROTOCOL_TEXT . equals ( memcachedProtocol ) && ! PROTOCOL_BINARY . equals ( memcachedProtocol ) ) { _log . warn ( "Illegal memcachedProtocol " + memcachedProtocol + ", using default (" + _memcachedProtocol + ")." ) ; return ; } _memcachedProtocol = memcachedProtocol ;
public class CommerceShipmentItemPersistenceImpl { /** * Returns the first commerce shipment item in the ordered set where commerceShipmentId = & # 63 ; . * @ param commerceShipmentId the commerce shipment ID * @ param orderByComparator the comparator to order the set by ( optionally < code > null < / code > ) * @ return the first matching commerce shipment item , or < code > null < / code > if a matching commerce shipment item could not be found */ @ Override public CommerceShipmentItem fetchByCommerceShipment_First ( long commerceShipmentId , OrderByComparator < CommerceShipmentItem > orderByComparator ) { } }
List < CommerceShipmentItem > list = findByCommerceShipment ( commerceShipmentId , 0 , 1 , orderByComparator ) ; if ( ! list . isEmpty ( ) ) { return list . get ( 0 ) ; } return null ;
public class Partition { /** * Merges the given components and returns the representative of the new component */ public V merge ( V a , V b ) { } }
final V aHead = componentOf ( a ) ; final V bHead = componentOf ( b ) ; if ( aHead . equals ( bHead ) ) return aHead ; // add the shorter tree underneath the taller tree final int aRank = ranks . getOrDefault ( aHead , 0 ) ; final int bRank = ranks . getOrDefault ( bHead , 0 ) ; if ( aRank > bRank ) { parents . put ( bHead , aHead ) ; return aHead ; } else if ( bRank > aRank ) { parents . put ( aHead , bHead ) ; return bHead ; } else { // whoops , the tree got taller parents . put ( bHead , aHead ) ; ranks . put ( aHead , aRank + 1 ) ; return aHead ; }
public class CliClient { /** * Delete a keyspace * @ param statement - a token tree representing current statement * @ throws TException - exception * @ throws InvalidRequestException - exception * @ throws NotFoundException - exception * @ throws SchemaDisagreementException */ private void executeDelKeySpace ( Tree statement ) throws TException , InvalidRequestException , NotFoundException , SchemaDisagreementException { } }
if ( ! CliMain . isConnected ( ) ) return ; String keyspaceName = CliCompiler . getKeySpace ( statement , thriftClient . describe_keyspaces ( ) ) ; String version = thriftClient . system_drop_keyspace ( keyspaceName ) ; sessionState . out . println ( version ) ; if ( keyspaceName . equals ( keySpace ) ) // we just deleted the keyspace we were authenticated too keySpace = null ;
public class Jdk8Methods { /** * Safely adds two int values . * @ param a the first value * @ param b the second value * @ return the result * @ throws ArithmeticException if the result overflows an int */ public static int safeAdd ( int a , int b ) { } }
int sum = a + b ; // check for a change of sign in the result when the inputs have the same sign if ( ( a ^ sum ) < 0 && ( a ^ b ) >= 0 ) { throw new ArithmeticException ( "Addition overflows an int: " + a + " + " + b ) ; } return sum ;
public class ThrottlingHttpService { /** * Creates a new decorator using the specified { @ link ThrottlingStrategy } instance . * @ param strategy The { @ link ThrottlingStrategy } instance to be used */ public static Function < Service < HttpRequest , HttpResponse > , ThrottlingHttpService > newDecorator ( ThrottlingStrategy < HttpRequest > strategy ) { } }
requireNonNull ( strategy , "strategy" ) ; return delegate -> new ThrottlingHttpService ( delegate , strategy ) ;
public class ContinuousBackupsDescriptionMarshaller { /** * Marshall the given parameter object . */ public void marshall ( ContinuousBackupsDescription continuousBackupsDescription , ProtocolMarshaller protocolMarshaller ) { } }
if ( continuousBackupsDescription == null ) { throw new SdkClientException ( "Invalid argument passed to marshall(...)" ) ; } try { protocolMarshaller . marshall ( continuousBackupsDescription . getContinuousBackupsStatus ( ) , CONTINUOUSBACKUPSSTATUS_BINDING ) ; protocolMarshaller . marshall ( continuousBackupsDescription . getPointInTimeRecoveryDescription ( ) , POINTINTIMERECOVERYDESCRIPTION_BINDING ) ; } catch ( Exception e ) { throw new SdkClientException ( "Unable to marshall request to JSON: " + e . getMessage ( ) , e ) ; }
public class GrailsHibernateTemplate { /** * Prepare the given Criteria object , applying cache settings and / or a * transaction timeout . * @ param criteria the Criteria object to prepare * @ deprecated Deprecated because Hibernate Criteria are deprecated */ @ Deprecated protected void prepareCriteria ( Criteria criteria ) { } }
if ( cacheQueries ) { criteria . setCacheable ( true ) ; } if ( shouldPassReadOnlyToHibernate ( ) ) { criteria . setReadOnly ( true ) ; } SessionHolder sessionHolder = ( SessionHolder ) TransactionSynchronizationManager . getResource ( sessionFactory ) ; if ( sessionHolder != null && sessionHolder . hasTimeout ( ) ) { criteria . setTimeout ( sessionHolder . getTimeToLiveInSeconds ( ) ) ; }
public class SlicedFileConsumer { /** * Sets a video decoder configuration ; some codecs require this , such as AVC . * @ param decoderConfig * video codec configuration */ public void setVideoDecoderConfiguration ( IRTMPEvent decoderConfig ) { } }
if ( decoderConfig instanceof IStreamData ) { IoBuffer data = ( ( IStreamData < ? > ) decoderConfig ) . getData ( ) . asReadOnlyBuffer ( ) ; videoConfigurationTag = ImmutableTag . build ( decoderConfig . getDataType ( ) , 0 , data , 0 ) ; }
public class SingleInputGate { /** * Retriggers a partition request . */ public void retriggerPartitionRequest ( IntermediateResultPartitionID partitionId ) throws IOException , InterruptedException { } }
synchronized ( requestLock ) { if ( ! isReleased ) { final InputChannel ch = inputChannels . get ( partitionId ) ; checkNotNull ( ch , "Unknown input channel with ID " + partitionId ) ; LOG . debug ( "{}: Retriggering partition request {}:{}." , owningTaskName , ch . partitionId , consumedSubpartitionIndex ) ; if ( ch . getClass ( ) == RemoteInputChannel . class ) { final RemoteInputChannel rch = ( RemoteInputChannel ) ch ; rch . retriggerSubpartitionRequest ( consumedSubpartitionIndex ) ; } else if ( ch . getClass ( ) == LocalInputChannel . class ) { final LocalInputChannel ich = ( LocalInputChannel ) ch ; if ( retriggerLocalRequestTimer == null ) { retriggerLocalRequestTimer = new Timer ( true ) ; } ich . retriggerSubpartitionRequest ( retriggerLocalRequestTimer , consumedSubpartitionIndex ) ; } else { throw new IllegalStateException ( "Unexpected type of channel to retrigger partition: " + ch . getClass ( ) ) ; } } }
public class FxFlowableTransformers { /** * Performs an action on onError with the provided emission count * @ param onError * @ param < T > */ public static < T > FlowableTransformer < T , T > doOnErrorCount ( Consumer < Integer > onError ) { } }
return obs -> obs . lift ( new FlowableEmissionCounter < > ( new CountObserver ( null , null , onError ) ) ) ;
public class ForkJoinPool { /** * Signals and releases worker v if it is top of idle worker * stack . This performs a one - shot version of signalWork only if * there is ( apparently ) at least one idle worker . * @ param c incoming ctl value * @ param v if non - null , a worker * @ param inc the increment to active count ( zero when compensating ) * @ return true if successful */ private boolean tryRelease ( long c , WorkQueue v , long inc ) { } }
int sp = ( int ) c , ns = sp & ~ UNSIGNALLED ; if ( v != null ) { int vs = v . scanState ; long nc = ( v . stackPred & SP_MASK ) | ( UC_MASK & ( c + inc ) ) ; if ( sp == vs && U . compareAndSwapLong ( this , CTL , c , nc ) ) { v . scanState = ns ; LockSupport . unpark ( v . parker ) ; return true ; } } return false ;
public class CxxIssuesReportSensor { /** * Saves code violation only if it wasn ' t already saved * @ param sensorContext * @ param issue */ public void saveUniqueViolation ( SensorContext sensorContext , CxxReportIssue issue ) { } }
if ( uniqueIssues . add ( issue ) ) { saveViolation ( sensorContext , issue ) ; }
public class CollectionManager { /** * Inspect the supplied object and cast type to delegates . * @ param obj the value to iterate of unknown type . * @ return the bsh iterator */ public Iterator < ? > getBshIterator ( final Object obj ) { } }
if ( obj == null ) return this . emptyIt ( ) ; if ( obj instanceof Primitive ) return this . getBshIterator ( Primitive . unwrap ( obj ) ) ; if ( obj . getClass ( ) . isArray ( ) ) return this . arrayIt ( obj ) ; if ( obj instanceof Iterable ) return this . getBshIterator ( ( Iterable < ? > ) obj ) ; if ( obj instanceof Iterator ) return this . getBshIterator ( ( Iterator < ? > ) obj ) ; if ( obj instanceof Enumeration ) return this . getBshIterator ( ( Enumeration < ? > ) obj ) ; if ( obj instanceof CharSequence ) return this . getBshIterator ( ( CharSequence ) obj ) ; if ( obj instanceof Number ) return this . getBshIterator ( ( Number ) obj ) ; if ( obj instanceof Character ) return this . getBshIterator ( ( Character ) obj ) ; if ( obj instanceof String ) return this . getBshIterator ( ( String ) obj ) ; return this . reflectNames ( obj ) . iterator ( ) ;
public class DateFormat { /** * Specifies whether date / time parsing is to be lenient . With * lenient parsing , the parser may use heuristics to interpret inputs that * do not precisely match this object ' s format . Without lenient parsing , * inputs must match this object ' s format more closely . * < br > < br > * < b > Note : < / b > ICU 53 introduced finer grained control of leniency ( and added * new control points ) making the preferred method a combination of * setCalendarLenient ( ) & amp ; setBooleanAttribute ( ) calls . * This method supports prior functionality but may not support all * future leniency control & amp ; behavior of DateFormat . For control of pre 53 leniency , * Calendar and DateFormat whitespace & amp ; numeric tolerance , this method is safe to * use . However , mixing leniency control via this method and modification of the * newer attributes via setBooleanAttribute ( ) may produce undesirable * results . * @ param lenient True specifies date / time interpretation to be lenient . * @ see android . icu . util . Calendar # setLenient * @ see # setBooleanAttribute ( BooleanAttribute , boolean ) * @ see # setCalendarLenient ( boolean ) */ public void setLenient ( boolean lenient ) { } }
calendar . setLenient ( lenient ) ; setBooleanAttribute ( BooleanAttribute . PARSE_ALLOW_NUMERIC , lenient ) ; setBooleanAttribute ( BooleanAttribute . PARSE_ALLOW_WHITESPACE , lenient ) ;
public class PiElectronegativityDescriptor { /** * The method calculates the pi electronegativity of a given atom * It is needed to call the addExplicitHydrogensToSatisfyValency method from the class tools . HydrogenAdder . * @ param atom The IAtom for which the DescriptorValue is requested * @ param atomContainer AtomContainer * @ return return the pi electronegativity */ @ Override public DescriptorValue calculate ( IAtom atom , IAtomContainer atomContainer ) { } }
IAtomContainer clone ; IAtom localAtom ; try { clone = ( IAtomContainer ) atomContainer . clone ( ) ; AtomContainerManipulator . percieveAtomTypesAndConfigureAtoms ( clone ) ; if ( lpeChecker ) { LonePairElectronChecker lpcheck = new LonePairElectronChecker ( ) ; lpcheck . saturate ( atomContainer ) ; } localAtom = clone . getAtom ( atomContainer . indexOf ( atom ) ) ; } catch ( CloneNotSupportedException e ) { return new DescriptorValue ( getSpecification ( ) , getParameterNames ( ) , getParameters ( ) , new DoubleResult ( Double . NaN ) , NAMES , null ) ; } catch ( CDKException e ) { return new DescriptorValue ( getSpecification ( ) , getParameterNames ( ) , getParameters ( ) , new DoubleResult ( Double . NaN ) , NAMES , null ) ; } if ( maxIterations != - 1 && maxIterations != 0 ) electronegativity . setMaxIterations ( maxIterations ) ; if ( maxResonStruc != - 1 && maxResonStruc != 0 ) electronegativity . setMaxResonStruc ( maxResonStruc ) ; double result = electronegativity . calculatePiElectronegativity ( clone , localAtom ) ; return new DescriptorValue ( getSpecification ( ) , getParameterNames ( ) , getParameters ( ) , new DoubleResult ( result ) , NAMES ) ;
public class CmsFlexResponse { /** * Sets the cache key for this response , which is calculated * from the provided parameters . < p > * @ param resourcename the target resource for which to create the cache key * @ param cacheDirectives the cache directives of the resource ( value of the property " cache " ) * @ param online indicates if this resource is online or offline * @ return the generated cache key * @ throws CmsFlexCacheException in case the value String had a parse error */ CmsFlexCacheKey setCmsCacheKey ( String resourcename , String cacheDirectives , boolean online ) throws CmsFlexCacheException { } }
m_key = new CmsFlexCacheKey ( resourcename , cacheDirectives , online ) ; if ( m_key . hadParseError ( ) ) { // We throw the exception here to make sure this response has a valid key ( cache = never ) throw new CmsFlexCacheException ( Messages . get ( ) . container ( Messages . LOG_FLEXRESPONSE_PARSE_ERROR_IN_CACHE_KEY_2 , cacheDirectives , resourcename ) ) ; } return m_key ;
public class ScrollablePanel { /** * documentation inherited from interface */ public int getScrollableBlockIncrement ( Rectangle visibleRect , int orientation , int direction ) { } }
if ( orientation == SwingConstants . HORIZONTAL ) { return visibleRect . width ; } else { return visibleRect . height ; }
public class AbstractReplicator { /** * Set the given DocumentReplicationListener to the this replicator . * @ param listener */ @ NonNull public ListenerToken addDocumentReplicationListener ( Executor executor , @ NonNull DocumentReplicationListener listener ) { } }
if ( listener == null ) { throw new IllegalArgumentException ( "listener cannot be null." ) ; } synchronized ( lock ) { setProgressLevel ( ReplicatorProgressLevel . PER_DOCUMENT ) ; final DocumentReplicationListenerToken token = new DocumentReplicationListenerToken ( executor , listener ) ; docEndedListenerTokens . add ( token ) ; return token ; }
public class SetElement { /** * Tests if this value is newer than the specified SetElement . * @ param other the value to be compared * @ return true if this value is newer than other */ public boolean isNewerThan ( SetElement other ) { } }
if ( other == null ) { return true ; } return this . timestamp . isNewerThan ( other . timestamp ) ;
public class DancingLinks { /** * Find the column with the fewest choices . * @ return The column header */ private ColumnHeader < ColumnName > findBestColumn ( ) { } }
int lowSize = Integer . MAX_VALUE ; ColumnHeader < ColumnName > result = null ; ColumnHeader < ColumnName > current = ( ColumnHeader < ColumnName > ) head . right ; while ( current != head ) { if ( current . size < lowSize ) { lowSize = current . size ; result = current ; } current = ( ColumnHeader < ColumnName > ) current . right ; } return result ;
public class AuthorizerMarshaller { /** * Marshall the given parameter object . */ public void marshall ( Authorizer authorizer , ProtocolMarshaller protocolMarshaller ) { } }
if ( authorizer == null ) { throw new SdkClientException ( "Invalid argument passed to marshall(...)" ) ; } try { protocolMarshaller . marshall ( authorizer . getAuthorizerCredentialsArn ( ) , AUTHORIZERCREDENTIALSARN_BINDING ) ; protocolMarshaller . marshall ( authorizer . getAuthorizerId ( ) , AUTHORIZERID_BINDING ) ; protocolMarshaller . marshall ( authorizer . getAuthorizerResultTtlInSeconds ( ) , AUTHORIZERRESULTTTLINSECONDS_BINDING ) ; protocolMarshaller . marshall ( authorizer . getAuthorizerType ( ) , AUTHORIZERTYPE_BINDING ) ; protocolMarshaller . marshall ( authorizer . getAuthorizerUri ( ) , AUTHORIZERURI_BINDING ) ; protocolMarshaller . marshall ( authorizer . getIdentitySource ( ) , IDENTITYSOURCE_BINDING ) ; protocolMarshaller . marshall ( authorizer . getIdentityValidationExpression ( ) , IDENTITYVALIDATIONEXPRESSION_BINDING ) ; protocolMarshaller . marshall ( authorizer . getName ( ) , NAME_BINDING ) ; protocolMarshaller . marshall ( authorizer . getProviderArns ( ) , PROVIDERARNS_BINDING ) ; } catch ( Exception e ) { throw new SdkClientException ( "Unable to marshall request to JSON: " + e . getMessage ( ) , e ) ; }
public class Repartitioner { /** * Within a single zone , swaps one random partition on one random node with * another random partition on different random node . * @ param nextCandidateCluster * @ param zoneId Zone ID within which to shuffle partitions * @ return updated cluster */ public static Cluster swapRandomPartitionsWithinZone ( final Cluster nextCandidateCluster , final int zoneId ) { } }
Cluster returnCluster = Cluster . cloneCluster ( nextCandidateCluster ) ; Random r = new Random ( ) ; List < Integer > nodeIdsInZone = new ArrayList < Integer > ( nextCandidateCluster . getNodeIdsInZone ( zoneId ) ) ; if ( nodeIdsInZone . size ( ) == 0 ) { return returnCluster ; } // Select random stealer node int stealerNodeOffset = r . nextInt ( nodeIdsInZone . size ( ) ) ; Integer stealerNodeId = nodeIdsInZone . get ( stealerNodeOffset ) ; // Select random stealer partition List < Integer > stealerPartitions = returnCluster . getNodeById ( stealerNodeId ) . getPartitionIds ( ) ; if ( stealerPartitions . size ( ) == 0 ) { return nextCandidateCluster ; } int stealerPartitionOffset = r . nextInt ( stealerPartitions . size ( ) ) ; int stealerPartitionId = stealerPartitions . get ( stealerPartitionOffset ) ; // Select random donor node List < Integer > donorNodeIds = new ArrayList < Integer > ( ) ; donorNodeIds . addAll ( nodeIdsInZone ) ; donorNodeIds . remove ( stealerNodeId ) ; if ( donorNodeIds . isEmpty ( ) ) { // No donor nodes ! return returnCluster ; } int donorIdOffset = r . nextInt ( donorNodeIds . size ( ) ) ; Integer donorNodeId = donorNodeIds . get ( donorIdOffset ) ; // Select random donor partition List < Integer > donorPartitions = returnCluster . getNodeById ( donorNodeId ) . getPartitionIds ( ) ; int donorPartitionOffset = r . nextInt ( donorPartitions . size ( ) ) ; int donorPartitionId = donorPartitions . get ( donorPartitionOffset ) ; return swapPartitions ( returnCluster , stealerNodeId , stealerPartitionId , donorNodeId , donorPartitionId ) ;
public class BeforeBuilder { /** * Build a precedence constraint . * @ param t the current tree * @ param args can be a non - empty set of vms ( { @ see Precedence } constraint ) or * a timestamp string ( { @ see Deadline } constraint ) * @ return a constraint */ @ Override public List < ? extends SatConstraint > buildConstraint ( BtrPlaceTree t , List < BtrpOperand > args ) { } }
if ( ! checkConformance ( t , args ) ) { return Collections . emptyList ( ) ; } // Get the first parameter @ SuppressWarnings ( "unchecked" ) List < VM > s = ( List < VM > ) params [ 0 ] . transform ( this , t , args . get ( 0 ) ) ; if ( s == null ) { return Collections . emptyList ( ) ; } // Get param ' OneOf ' Object obj = params [ 1 ] . transform ( this , t , args . get ( 1 ) ) ; if ( obj == null ) { return Collections . emptyList ( ) ; } if ( obj instanceof List ) { @ SuppressWarnings ( "unchecked" ) List < VM > s2 = ( List < VM > ) obj ; if ( s2 . isEmpty ( ) ) { t . ignoreError ( "Parameter '" + params [ 1 ] . getName ( ) + "' expects a non-empty list of VMs" ) ; return Collections . emptyList ( ) ; } return Precedence . newPrecedence ( s , s2 ) ; } else if ( obj instanceof String ) { String timestamp = ( String ) obj ; if ( "" . equals ( timestamp ) ) { t . ignoreError ( "Parameter '" + params [ 1 ] . getName ( ) + "' expects a non-empty string" ) ; return Collections . emptyList ( ) ; } return Deadline . newDeadline ( s , timestamp ) ; } else { return Collections . emptyList ( ) ; }
public class PatternFlattener { /** * Try to create a date filler if the given parameter is a date parameter . * @ return created date filler , or null if the given parameter is not a date parameter */ static DateFiller parseDateParameter ( String wrappedParameter , String trimmedParameter ) { } }
if ( trimmedParameter . startsWith ( PARAMETER_DATE + " " ) && trimmedParameter . length ( ) > PARAMETER_DATE . length ( ) + 1 ) { String dateFormat = trimmedParameter . substring ( PARAMETER_DATE . length ( ) + 1 ) ; return new DateFiller ( wrappedParameter , trimmedParameter , dateFormat ) ; } else if ( trimmedParameter . equals ( PARAMETER_DATE ) ) { return new DateFiller ( wrappedParameter , trimmedParameter , DEFAULT_DATE_FORMAT ) ; } return null ;
public class AWSGreengrassClient { /** * Associates a role with your account . AWS IoT Greengrass will use the role to access your Lambda functions and AWS * IoT resources . This is necessary for deployments to succeed . The role must have at least minimum permissions in * the policy ' ' AWSGreengrassResourceAccessRolePolicy ' ' . * @ param associateServiceRoleToAccountRequest * @ return Result of the AssociateServiceRoleToAccount operation returned by the service . * @ throws BadRequestException * invalid request * @ throws InternalServerErrorException * server error * @ sample AWSGreengrass . AssociateServiceRoleToAccount * @ see < a href = " http : / / docs . aws . amazon . com / goto / WebAPI / greengrass - 2017-06-07 / AssociateServiceRoleToAccount " * target = " _ top " > AWS API Documentation < / a > */ @ Override public AssociateServiceRoleToAccountResult associateServiceRoleToAccount ( AssociateServiceRoleToAccountRequest request ) { } }
request = beforeClientExecution ( request ) ; return executeAssociateServiceRoleToAccount ( request ) ;
public class Device { /** * Command the device to update * @ param url The URL to update from * @ param md5 The MD5 Checksum for the update * @ return True if the command has been received . This does not mean that the update was successful . * @ throws CommandExecutionException When there has been a error during the communication or the response was invalid . */ public boolean update ( String url , String md5 ) throws CommandExecutionException { } }
if ( url == null || md5 == null ) throw new CommandExecutionException ( CommandExecutionException . Error . INVALID_PARAMETERS ) ; if ( md5 . length ( ) != 32 ) throw new CommandExecutionException ( CommandExecutionException . Error . INVALID_PARAMETERS ) ; JSONObject params = new JSONObject ( ) ; params . put ( "mode" , "normal" ) ; params . put ( "install" , "1" ) ; params . put ( "app_url" , url ) ; params . put ( "file_md5" , md5 ) ; params . put ( "proc" , "dnld install" ) ; return sendOk ( "miIO.ota" , params ) ;
public class StatsUtils { /** * Find an operation statistic attached ( as a children ) to this context that matches the statistic name and type * @ param context the context of the query * @ param type type of the operation statistic * @ param statName statistic name * @ param < T > type of the operation statistic content * @ return the operation statistic searched for * @ throws RuntimeException if 0 or more than 1 result is found */ public static < T extends Enum < T > > OperationStatistic < T > findOperationStatisticOnChildren ( Object context , Class < T > type , String statName ) { } }
@ SuppressWarnings ( "unchecked" ) Query query = queryBuilder ( ) . children ( ) . filter ( context ( attributes ( Matchers . allOf ( hasAttribute ( "name" , statName ) , hasAttribute ( "type" , type ) ) ) ) ) . build ( ) ; Set < TreeNode > result = query . execute ( Collections . singleton ( ContextManager . nodeFor ( context ) ) ) ; if ( result . size ( ) > 1 ) { throw new RuntimeException ( "result must be unique" ) ; } if ( result . isEmpty ( ) ) { throw new RuntimeException ( "result must not be null" ) ; } @ SuppressWarnings ( "unchecked" ) OperationStatistic < T > statistic = ( OperationStatistic < T > ) result . iterator ( ) . next ( ) . getContext ( ) . attributes ( ) . get ( "this" ) ; return statistic ;
public class Base64Codec { /** * Encodes the provided raw data using base64. * @ param rawData The raw data to encode . It must not be < CODE > null < / CODE > . * @ return The base64 - encoded representation of the provided raw data . */ public static String encode ( byte [ ] rawData ) { } }
StringBuilder buffer = new StringBuilder ( 4 * rawData . length / 3 ) ; int pos = 0 ; int iterations = rawData . length / 3 ; for ( int i = 0 ; i < iterations ; i ++ ) { int value = ( ( rawData [ pos ++ ] & 0xFF ) << 16 ) | ( ( rawData [ pos ++ ] & 0xFF ) << 8 ) | ( rawData [ pos ++ ] & 0xFF ) ; buffer . append ( BASE64_ALPHABET [ ( value >>> 18 ) & 0x3F ] ) ; buffer . append ( BASE64_ALPHABET [ ( value >>> 12 ) & 0x3F ] ) ; buffer . append ( BASE64_ALPHABET [ ( value >>> 6 ) & 0x3F ] ) ; buffer . append ( BASE64_ALPHABET [ value & 0x3F ] ) ; } switch ( rawData . length % 3 ) { case 1 : buffer . append ( BASE64_ALPHABET [ ( rawData [ pos ] >>> 2 ) & 0x3F ] ) ; buffer . append ( BASE64_ALPHABET [ ( rawData [ pos ] << 4 ) & 0x3F ] ) ; buffer . append ( "==" ) ; break ; case 2 : int value = ( ( rawData [ pos ++ ] & 0xFF ) << 8 ) | ( rawData [ pos ] & 0xFF ) ; buffer . append ( BASE64_ALPHABET [ ( value >>> 10 ) & 0x3F ] ) ; buffer . append ( BASE64_ALPHABET [ ( value >>> 4 ) & 0x3F ] ) ; buffer . append ( BASE64_ALPHABET [ ( value << 2 ) & 0x3F ] ) ; buffer . append ( "=" ) ; break ; } return buffer . toString ( ) ;
public class FindingReplacing { /** * Sets the given lookups string as the search string * < B > May multiple substring matched . < / B > * @ param left * @ return */ public S lookups ( String ... lookups ) { } }
for ( String lookup : checkNotNull ( lookups ) ) { lookup ( lookup ) . late ( ) ; } return THIS ( ) ;
public class AbstractParamContainerPanel { /** * Tells whether or not the given param panel , or one of its child panels , is selected . * @ param panelName the name of the panel to check , should not be { @ code null } . * @ return { @ code true } if the panel or one of its child panels is selected , { @ code false } otherwise . * @ since TODO add version * @ see # isParamPanelSelected ( String ) */ public boolean isParamPanelOrChildSelected ( String panelName ) { } }
DefaultMutableTreeNode node = getTreeNodeFromPanelName ( panelName ) ; if ( node != null ) { TreePath panelPath = new TreePath ( node . getPath ( ) ) ; if ( getTreeParam ( ) . isPathSelected ( panelPath ) ) { return true ; } TreePath selectedPath = getTreeParam ( ) . getSelectionPath ( ) ; return selectedPath != null && panelPath . equals ( selectedPath . getParentPath ( ) ) ; } return false ;
public class DeviceStore { /** * Internal method to add an actual device to the store . * @ param device The device to add . * @ throws AndroidDeviceException */ protected synchronized void addDeviceToStore ( AndroidDevice device ) throws AndroidDeviceException { } }
if ( androidDevices . containsKey ( device . getTargetPlatform ( ) ) ) { List < AndroidDevice > platformDevices = androidDevices . get ( device . getTargetPlatform ( ) ) ; if ( ! platformDevices . contains ( device ) ) { platformDevices . add ( device ) ; } } else { androidDevices . put ( device . getTargetPlatform ( ) , Lists . newArrayList ( device ) ) ; }
public class CharTrie { /** * Reduce simple char trie . * @ param z the z * @ param fn the fn * @ return the char trie */ public CharTrie reduceSimple ( CharTrie z , BiFunction < Long , Long , Long > fn ) { } }
return reduce ( z , ( left , right ) -> { TreeMap < Character , ? extends TrieNode > leftChildren = null == left ? new TreeMap < > ( ) : left . getChildrenMap ( ) ; TreeMap < Character , ? extends TrieNode > rightChildren = null == right ? new TreeMap < > ( ) : right . getChildrenMap ( ) ; Map < Character , Long > map = Stream . of ( rightChildren . keySet ( ) , leftChildren . keySet ( ) ) . flatMap ( x -> x . stream ( ) ) . distinct ( ) . collect ( Collectors . toMap ( c -> c , ( Character c ) -> { assert ( null != leftChildren ) ; assert ( null != rightChildren ) ; assert ( null != c ) ; TrieNode leftChild = leftChildren . get ( c ) ; Long l = null == leftChild ? null : leftChild . getCursorCount ( ) ; TrieNode rightChild = rightChildren . get ( c ) ; Long r = null == rightChild ? null : rightChild . getCursorCount ( ) ; return fn . apply ( l , r ) ; } ) ) ; return new TreeMap < > ( map ) ; } ) ;
public class ValidStorageOptions { /** * The valid range of Provisioned IOPS to gibibytes of storage multiplier . For example , 3-10 , which means that * provisioned IOPS can be between 3 and 10 times storage . * @ return The valid range of Provisioned IOPS to gibibytes of storage multiplier . For example , 3-10 , which means * that provisioned IOPS can be between 3 and 10 times storage . */ public java . util . List < DoubleRange > getIopsToStorageRatio ( ) { } }
if ( iopsToStorageRatio == null ) { iopsToStorageRatio = new com . amazonaws . internal . SdkInternalList < DoubleRange > ( ) ; } return iopsToStorageRatio ;
public class StringFixture { /** * Extracts a whole number for a string using a regular expression . * @ param value input string . * @ param regEx regular expression to match against value . * @ param groupIndex index of group in regular expression containing the number . * @ return extracted number . */ public Integer extractIntFromUsingGroup ( String value , String regEx , int groupIndex ) { } }
Integer result = null ; if ( value != null ) { Matcher matcher = getMatcher ( regEx , value ) ; if ( matcher . matches ( ) ) { String intStr = matcher . group ( groupIndex ) ; result = convertToInt ( intStr ) ; } } return result ;
public class MapLabelSetterFactory { /** * フィールドによるラベル情報を格納する場合 。 * < p > { @ code < フィールド名 > + Label } のメソッド名 < / p > * @ param beanClass フィールドが定義してあるクラスのインスタンス * @ param fieldName フィールド名 * @ return ラベル情報の設定用クラス */ private Optional < MapLabelSetter > createField ( final Class < ? > beanClass , final String fieldName ) { } }
final String labelFieldName = fieldName + "Label" ; final Field labelField ; try { labelField = beanClass . getDeclaredField ( labelFieldName ) ; labelField . setAccessible ( true ) ; } catch ( NoSuchFieldException | SecurityException e ) { return Optional . empty ( ) ; } if ( ! Map . class . isAssignableFrom ( labelField . getType ( ) ) ) { return Optional . empty ( ) ; } final ParameterizedType type = ( ParameterizedType ) labelField . getGenericType ( ) ; final Class < ? > keyType = ( Class < ? > ) type . getActualTypeArguments ( ) [ 0 ] ; final Class < ? > valueType = ( Class < ? > ) type . getActualTypeArguments ( ) [ 1 ] ; if ( keyType . equals ( String . class ) && valueType . equals ( String . class ) ) { return Optional . of ( new MapLabelSetter ( ) { @ SuppressWarnings ( "unchecked" ) @ Override public void set ( final Object beanObj , final String label , final String key ) { ArgUtils . notNull ( beanObj , "beanObj" ) ; ArgUtils . notEmpty ( label , "label" ) ; try { Map < String , String > labelMapObj = ( Map < String , String > ) labelField . get ( beanObj ) ; if ( labelMapObj == null ) { labelMapObj = new LinkedHashMap < > ( ) ; labelField . set ( beanObj , labelMapObj ) ; } labelMapObj . put ( key , label ) ; } catch ( IllegalArgumentException | IllegalAccessException e ) { throw new RuntimeException ( "fail access label field." , e ) ; } } } ) ; } return Optional . empty ( ) ;
public class SftpClient { /** * Download the remote file to the local computer . If the paths provided are * not absolute the current working directory is used . * @ param remote * the path / name of the remote file * @ param local * the path / name to place the file on the local computer * @ param progress * @ param resume * attempt to resume an interrupted download * @ return the downloaded file ' s attributes * @ throws SftpStatusException * @ throws FileNotFoundException * @ throws SshException * @ throws TransferCancelledException */ @ SuppressWarnings ( "resource" ) public SftpFileAttributes get ( String remote , String local , FileTransferProgress progress , boolean resume ) throws FileNotFoundException , SftpStatusException , SshException , TransferCancelledException { } }
// Moved here to ensure that stream is closed in finally OutputStream out = null ; SftpFileAttributes attrs = null ; // Perform local file operations first , then if it throws an exception // the server hasn ' t been unnecessarily loaded . File localPath = resolveLocalPath ( local ) ; if ( ! localPath . exists ( ) ) { File parent = new File ( localPath . getParent ( ) ) ; parent . mkdirs ( ) ; } if ( localPath . isDirectory ( ) ) { int idx ; if ( ( idx = remote . lastIndexOf ( '/' ) ) > - 1 ) { localPath = new File ( localPath , remote . substring ( idx ) ) ; } else { localPath = new File ( localPath , remote ) ; } } // Check that file exists before we create a file stat ( remote ) ; long position = 0 ; try { // if resuming and the local file exists , then open as random access // file and seek to end of the file ready to continue writing if ( resume && localPath . exists ( ) ) { position = localPath . length ( ) ; RandomAccessFile file = new RandomAccessFile ( localPath , "rw" ) ; file . seek ( position ) ; out = new RandomAccessFileOutputStream ( file ) ; } else { out = new FileOutputStream ( localPath ) ; } if ( transferMode == MODE_TEXT ) { // Default text mode handling for versions 3 - of the SFTP // protocol int inputStyle = eolMode ; int outputStyle = EOLProcessor . TEXT_SYSTEM ; byte [ ] nl = null ; if ( sftp . getVersion ( ) <= 3 && sftp . getExtension ( "newline@vandyke.com" ) != null ) { nl = sftp . getExtension ( "newline@vandyke.com" ) ; } else if ( sftp . getVersion ( ) > 3 ) { nl = sftp . getCanonicalNewline ( ) ; } // Setup text mode correctly if were using version 4 + of the // SFTP protocol if ( nl != null ) { switch ( nl . length ) { case 1 : if ( nl [ 0 ] == '\r' ) inputStyle = EOLProcessor . TEXT_CR ; else if ( nl [ 0 ] == '\n' ) inputStyle = EOLProcessor . TEXT_LF ; else throw new SftpStatusException ( SftpStatusException . INVALID_HANDLE , "Unsupported text mode: invalid newline character" ) ; break ; case 2 : if ( nl [ 0 ] == '\r' && nl [ 1 ] == '\n' ) inputStyle = EOLProcessor . TEXT_CRLF ; else throw new SftpStatusException ( SftpStatusException . INVALID_HANDLE , "Unsupported text mode: invalid newline characters" ) ; break ; default : throw new SftpStatusException ( SftpStatusException . INVALID_HANDLE , "Unsupported text mode: newline length > 2" ) ; } } out = EOLProcessor . createOutputStream ( inputStyle , outputStyle , out ) ; } attrs = get ( remote , out , progress , position ) ; return attrs ; } catch ( IOException ex ) { throw new SftpStatusException ( SftpStatusException . SSH_FX_FAILURE , "Failed to open outputstream to " + local ) ; } finally { try { if ( out != null ) out . close ( ) ; // Try to set the last modified time on file using reflection so // that // the class is compatible with JDK 1.1 if ( attrs != null ) { Method m = localPath . getClass ( ) . getMethod ( "setLastModified" , new Class [ ] { long . class } ) ; m . invoke ( localPath , new Object [ ] { new Long ( attrs . getModifiedTime ( ) . longValue ( ) * 1000 ) } ) ; } } catch ( Throwable ex ) { // NOTE : should we ignore this ? } }
public class AuthorizationRequestManager { /** * Initializes the collection of expected challenge answers . * @ param realms List of realms */ private void setExpectedAnswers ( ArrayList < String > realms ) { } }
if ( answers == null ) { return ; } for ( String realm : realms ) { try { answers . put ( realm , "" ) ; } catch ( JSONException t ) { logger . error ( "setExpectedAnswers failed with exception: " + t . getLocalizedMessage ( ) , t ) ; } }
public class CrosstabNavigator { /** * Puts the given value to the navigated position in the crosstab . * @ param value * the value to put . * @ param createCategories * if true , the chosen categories will automatically be created * if they do not already exists in the dimensions of the * crosstab . * @ throws IllegalArgumentException * if the position or value is invalid , typically because one or * more dimensions lacks a specified category or the value type * is not acceptable ( typically because of class casting issues ) * @ throws NullPointerException * if some of the specified categories are null */ public void put ( E value , boolean createCategories ) throws IllegalArgumentException , NullPointerException { } }
if ( createCategories ) { for ( int i = 0 ; i < categories . length ; i ++ ) { String category = categories [ i ] ; CrosstabDimension dimension = crosstab . getDimension ( i ) ; dimension . addCategory ( category ) ; } } crosstab . putValue ( value , categories ) ;
public class InstanceValidator { private boolean passesCodeWhitespaceRules ( String v ) { } }
if ( ! v . trim ( ) . equals ( v ) ) return false ; boolean lastWasSpace = true ; for ( char c : v . toCharArray ( ) ) { if ( c == ' ' ) { if ( lastWasSpace ) return false ; else lastWasSpace = true ; } else if ( Character . isWhitespace ( c ) ) return false ; else lastWasSpace = false ; } return true ;
public class TransmitMessage { /** * / * ( non - Javadoc ) * @ see com . ibm . ws . sib . processor . runtime . SIMPRemoteMessageControllable # removeMessage ( boolean ) */ public void moveMessage ( boolean discard ) throws SIMPControllableNotFoundException , SIMPRuntimeOperationFailedException { } }
if ( TraceComponent . isAnyTracingEnabled ( ) && tc . isEntryEnabled ( ) ) SibTr . entry ( tc , "moveMessage" , Boolean . valueOf ( discard ) ) ; assertValidControllable ( ) ; // remove the message from the MessageStore QueuedMessage queuedMessage = null ; try { queuedMessage = ( QueuedMessage ) getSIMPMessage ( ) . getControlAdapter ( ) ; } catch ( SIResourceException e ) { // No FFDC code needed SibTr . exception ( tc , e ) ; if ( TraceComponent . isAnyTracingEnabled ( ) && tc . isEntryEnabled ( ) ) SibTr . exit ( tc , "moveMessage" , e ) ; throw new SIMPRuntimeOperationFailedException ( e ) ; } // A null message implies it ' s already gone from the MsgStore if ( queuedMessage != null ) { queuedMessage . moveMessage ( discard ) ; // Remove message from the source stream try { _stream . writeSilenceForced ( _tick ) ; } catch ( SIException e ) { FFDCFilter . processException ( e , "com.ibm.ws.sib.processor.runtime.TransmitMessage.moveMessage" , "1:245:1.42" , this ) ; SIMPRuntimeOperationFailedException finalE = new SIMPRuntimeOperationFailedException ( nls . getFormattedMessage ( "INTERNAL_MESSAGING_ERROR_CWSIP0003" , new Object [ ] { "TransmitMessage.moveMessage" , "1:253:1.42" , e , new Long ( _tick ) } , null ) , e ) ; SibTr . exception ( tc , finalE ) ; if ( TraceComponent . isAnyTracingEnabled ( ) && tc . isEntryEnabled ( ) ) SibTr . exit ( tc , "moveMessage" , finalE ) ; throw finalE ; } } if ( TraceComponent . isAnyTracingEnabled ( ) && tc . isEntryEnabled ( ) ) SibTr . exit ( tc , "moveMessage" ) ;
public class WxCryptUtil { /** * 对明文进行加密 . * @ param plainText 需要加密的明文 * @ return 加密后base64编码的字符串 */ protected String encrypt ( String randomStr , String plainText ) { } }
ByteGroup byteCollector = new ByteGroup ( ) ; byte [ ] randomStringBytes = randomStr . getBytes ( CHARSET ) ; byte [ ] plainTextBytes = plainText . getBytes ( CHARSET ) ; byte [ ] bytesOfSizeInNetworkOrder = number2BytesInNetworkOrder ( plainTextBytes . length ) ; byte [ ] appIdBytes = appidOrCorpid . getBytes ( CHARSET ) ; // randomStr + networkBytesOrder + text + appid byteCollector . addBytes ( randomStringBytes ) ; byteCollector . addBytes ( bytesOfSizeInNetworkOrder ) ; byteCollector . addBytes ( plainTextBytes ) ; byteCollector . addBytes ( appIdBytes ) ; // . . . + pad : 使用自定义的填充方式对明文进行补位填充 byte [ ] padBytes = PKCS7Encoder . encode ( byteCollector . size ( ) ) ; byteCollector . addBytes ( padBytes ) ; // 获得最终的字节流 , 未加密 byte [ ] unencrypted = byteCollector . toBytes ( ) ; try { // 设置加密模式为AES的CBC模式 Cipher cipher = Cipher . getInstance ( "AES/CBC/NoPadding" ) ; SecretKeySpec keySpec = new SecretKeySpec ( aesKey , "AES" ) ; IvParameterSpec iv = new IvParameterSpec ( aesKey , 0 , 16 ) ; cipher . init ( Cipher . ENCRYPT_MODE , keySpec , iv ) ; // 加密 byte [ ] encrypted = cipher . doFinal ( unencrypted ) ; // 使用BASE64对加密后的字符串进行编码 String base64Encrypted = base64 . encodeToString ( encrypted ) ; return base64Encrypted ; } catch ( Exception e ) { throw new RuntimeException ( e ) ; }
public class RepositoryOptionImpl { /** * Returns the full repository url . * @ return the full repository as given plus eventual snapshot / release tags ( cannot be null or * empty ) * @ throws IllegalStateException * - if both snapshots and releases are not allowed */ public String getRepository ( ) { } }
if ( ! allowReleases && ! allowSnapshots ) { throw new IllegalStateException ( "Does not make sense to disallow both releases and snapshots." ) ; } // start with a plus to append default repositories from settings . xml and Maven Cental // to the list of repositories defined by options final StringBuilder url = new StringBuilder ( "+" ) ; url . append ( this . repositoryUrl ) ; if ( allowSnapshots ) { url . append ( "@snapshots" ) ; } if ( ! allowReleases ) { url . append ( "@noreleases" ) ; } if ( id != null ) { url . append ( "@id=" ) ; url . append ( id ) ; } return url . toString ( ) ;
public class OClassImpl { /** * Adds a base class to the current one . It adds also the base class cluster ids to the polymorphic cluster ids array . * @ param iBaseClass * The base class to add . */ private OClass addBaseClasses ( final OClass iBaseClass ) { } }
if ( baseClasses == null ) baseClasses = new ArrayList < OClass > ( ) ; if ( baseClasses . contains ( iBaseClass ) ) return this ; baseClasses . add ( iBaseClass ) ; // ADD CLUSTER IDS OF BASE CLASS TO THIS CLASS AND ALL SUPER - CLASSES OClassImpl currentClass = this ; while ( currentClass != null ) { currentClass . addPolymorphicClusterIds ( ( OClassImpl ) iBaseClass ) ; currentClass = ( OClassImpl ) currentClass . getSuperClass ( ) ; } return this ;
public class TimedTextMarkupLanguageParser { /** * Build the Subtitle objects from TTML content . */ @ SuppressWarnings ( "deprecation" ) private void buildFilmList ( ) throws Exception { } }
final NodeList subtitleData = doc . getElementsByTagName ( "tt:p" ) ; for ( int i = 0 ; i < subtitleData . getLength ( ) ; i ++ ) { final Subtitle subtitle = new Subtitle ( ) ; final Node subnode = subtitleData . item ( i ) ; if ( subnode . hasAttributes ( ) ) { // retrieve the begin and end attributes . . . final NamedNodeMap attrMap = subnode . getAttributes ( ) ; final Node beginNode = attrMap . getNamedItem ( "begin" ) ; final Node endNode = attrMap . getNamedItem ( "end" ) ; if ( beginNode != null && endNode != null ) { subtitle . begin = ttmlFormat . parse ( beginNode . getNodeValue ( ) ) ; // HACK : : Don ́t know why this is set like this . . . // but we have to subract 10 hours from the XML if ( subtitle . begin . getHours ( ) >= 10 ) { subtitle . begin . setHours ( subtitle . begin . getHours ( ) - 10 ) ; } subtitle . end = ttmlFormat . parse ( endNode . getNodeValue ( ) ) ; if ( subtitle . end . getHours ( ) >= 10 ) { subtitle . end . setHours ( subtitle . end . getHours ( ) - 10 ) ; } } } final NodeList childNodes = subnode . getChildNodes ( ) ; for ( int j = 0 ; j < childNodes . getLength ( ) ; j ++ ) { final Node node = childNodes . item ( j ) ; if ( node . getNodeName ( ) . equalsIgnoreCase ( "tt:span" ) ) { // retrieve the text and color information . . . final NamedNodeMap attrMap = node . getAttributes ( ) ; final Node styleNode = attrMap . getNamedItem ( "style" ) ; final StyledString textContent = new StyledString ( ) ; textContent . setText ( node . getTextContent ( ) ) ; final String col = colorMap . get ( styleNode . getNodeValue ( ) ) ; if ( col == null ) { textContent . setColor ( color ) ; // gabs beim BR } else { textContent . setColor ( colorMap . get ( styleNode . getNodeValue ( ) ) ) ; } subtitle . listOfStrings . add ( textContent ) ; } } subtitleList . add ( subtitle ) ; }
public class UserStorageMetadataMarshaller { /** * Marshall the given parameter object . */ public void marshall ( UserStorageMetadata userStorageMetadata , ProtocolMarshaller protocolMarshaller ) { } }
if ( userStorageMetadata == null ) { throw new SdkClientException ( "Invalid argument passed to marshall(...)" ) ; } try { protocolMarshaller . marshall ( userStorageMetadata . getStorageUtilizedInBytes ( ) , STORAGEUTILIZEDINBYTES_BINDING ) ; protocolMarshaller . marshall ( userStorageMetadata . getStorageRule ( ) , STORAGERULE_BINDING ) ; } catch ( Exception e ) { throw new SdkClientException ( "Unable to marshall request to JSON: " + e . getMessage ( ) , e ) ; }
public class ExtendedMockito { /** * Make an existing object a spy . * < p > This does < u > not < / u > clone the existing objects . If a method is stubbed on a spy * converted by this method all references to the already existing object will be affected by * the stubbing . * @ param toSpy The existing object to convert into a spy */ @ UnstableApi @ SuppressWarnings ( "CheckReturnValue" ) public static void spyOn ( Object toSpy ) { } }
if ( onSpyInProgressInstance . get ( ) != null ) { throw new IllegalStateException ( "Cannot set up spying on an existing object while " + "setting up spying for another existing object" ) ; } onSpyInProgressInstance . set ( toSpy ) ; try { spy ( toSpy ) ; } finally { onSpyInProgressInstance . remove ( ) ; }
public class BatchedTimeoutManager { /** * Start the BatchedTimeoutManager */ public void startTimer ( ) { } }
if ( TraceComponent . isAnyTracingEnabled ( ) && tc . isEntryEnabled ( ) ) SibTr . entry ( tc , "startTimer" ) ; btmLockManager . lockExclusive ( ) ; try { // only start if currently stopped if ( isStopped ) { // set stopped to false isStopped = false ; // iterate over the entries currently in the active list LinkedListEntry entry = ( LinkedListEntry ) activeEntries . getFirst ( ) ; while ( entry != null && activeEntries . contains ( entry ) ) { // start an alarm for each entry startNewAlarm ( entry ) ; entry = ( LinkedListEntry ) entry . getNext ( ) ; } } } finally { btmLockManager . unlockExclusive ( ) ; } if ( TraceComponent . isAnyTracingEnabled ( ) && tc . isEntryEnabled ( ) ) SibTr . exit ( tc , "startTimer" ) ;
public class WhileMatchFilterAdapter { /** * { @ inheritDoc } * Adapt { @ link WhileMatchFilter } as follow : * label ( ' id - in ' ) wrappedFilter . filter ( ) * sink ( ) + - - - - - + - - - - - + * label ( ' id - out ' ) all ( ) * sink ( ) | * The above implementation gives enough information from the server side to determine whether the * remaining rows should be filtered out . For each { @ link WhileMatchFilter } instance , an unique ID * is generated for labeling . The input label is the unique ID suffixed by " - in " and the output * label is the unique ID suffixed by " - out " . When { @ code wrappedFilter } decides to filter out the * rest of rows , there is no out label ( " id - out " ) applied in the output . In other words , when * there is a missing " id - out " for an input " id - in " , { @ link * WhileMatchFilter # filterAllRemaining ( ) } returns { @ code true } . Since the server continues to send * result even though { @ link * WhileMatchFilter # filterAllRemaining ( ) } returns { @ code true } , we need to replace this { @ link * WhileMatchFilter } instance with a " block all " filter and rescan from the next row . */ @ Override public Filters . Filter adapt ( FilterAdapterContext context , WhileMatchFilter filter ) throws IOException { } }
// We need to eventually support more than one { @ link WhileMatchFilter } s soon . Checking the size // of a list of { @ link WhileMatchFilter } s makes more sense than verifying a single boolean flag . checkArgument ( context . getNumberOfWhileMatchFilters ( ) == 0 , "More than one WhileMatchFilter is not supported." ) ; checkNotNull ( filter . getFilter ( ) , "The wrapped filter for a WhileMatchFilter cannot be null." ) ; Optional < Filters . Filter > wrappedFilter = subFilterAdapter . adaptFilter ( context , filter . getFilter ( ) ) ; checkArgument ( wrappedFilter . isPresent ( ) , "Unable to adapted the wrapped filter: " + filter . getFilter ( ) ) ; String whileMatchFilterId = context . getNextUniqueId ( ) ; Filters . Filter inLabel = FILTERS . label ( whileMatchFilterId + IN_LABEL_SUFFIX ) ; Filters . Filter inLabelAndSink = FILTERS . chain ( ) . filter ( inLabel ) . filter ( FILTERS . sink ( ) ) ; Filters . Filter outLabel = FILTERS . label ( whileMatchFilterId + OUT_LABEL_SUFFIX ) ; Filters . Filter outLabelAndSink = FILTERS . chain ( ) . filter ( outLabel ) . filter ( FILTERS . sink ( ) ) ; Filters . Filter outInterleave = FILTERS . interleave ( ) . filter ( outLabelAndSink ) . filter ( FILTERS . pass ( ) ) ; Filters . Filter outChain = FILTERS . chain ( ) . filter ( wrappedFilter . get ( ) ) . filter ( outInterleave ) ; Filters . Filter finalFilter = FILTERS . interleave ( ) . filter ( inLabelAndSink ) . filter ( outChain ) ; context . addWhileMatchFilter ( filter ) ; return finalFilter ;
public class ApiConnection { /** * Returns a user - readable message for a given API response . * @ deprecated to be migrated to { @ class PasswordApiConnection } * @ param loginResult * a API login request result string other than * { @ link # LOGIN _ RESULT _ SUCCESS } * @ return error message */ @ Deprecated String getLoginErrorMessage ( String loginResult ) { } }
switch ( loginResult ) { case ApiConnection . LOGIN_WRONG_PASS : return loginResult + ": Wrong Password." ; case ApiConnection . LOGIN_WRONG_PLUGIN_PASS : return loginResult + ": Wrong Password. An authentication plugin rejected the password." ; case ApiConnection . LOGIN_NOT_EXISTS : return loginResult + ": Username does not exist." ; case ApiConnection . LOGIN_BLOCKED : return loginResult + ": User is blocked." ; case ApiConnection . LOGIN_EMPTY_PASS : return loginResult + ": Password is empty." ; case ApiConnection . LOGIN_NO_NAME : return loginResult + ": No user name given." ; case ApiConnection . LOGIN_CREATE_BLOCKED : return loginResult + ": The wiki tried to automatically create a new account for you, " + "but your IP address has been blocked from account creation." ; case ApiConnection . LOGIN_ILLEGAL : return loginResult + ": Username is illegal." ; case ApiConnection . LOGIN_THROTTLED : return loginResult + ": Too many login attempts in a short time." ; case ApiConnection . LOGIN_WRONG_TOKEN : return loginResult + ": Token is wrong." ; case ApiConnection . LOGIN_NEEDTOKEN : return loginResult + ": Token or session ID is missing." ; default : return "Login Error: " + loginResult ; }
public class MACAddressSection { /** * Writes this address as a single hexadecimal value with always the exact same number of characters , with or without a preceding 0x prefix . */ @ Override public String toHexString ( boolean with0xPrefix ) { } }
String result ; if ( hasNoStringCache ( ) || ( result = ( with0xPrefix ? stringCache . hexStringPrefixed : stringCache . hexString ) ) == null ) { result = toHexString ( with0xPrefix , null ) ; if ( with0xPrefix ) { stringCache . hexStringPrefixed = result ; } else { stringCache . hexString = result ; } } return result ;
public class ObjectParameter { /** * Parse a file definition by using canonical path . * @ param serializedObject the full file path * @ return the File object */ private Object parseFileParameter ( final String serializedObject ) { } }
final File res = new File ( serializedObject ) ; if ( ! res . exists ( ) ) { throw new CoreRuntimeException ( "Impossible to load file " + serializedObject ) ; } return res ;
public class ListResourceBundle { /** * Returns an < code > Enumeration < / code > of the keys contained in * this < code > ResourceBundle < / code > and its parent bundles . * @ return an < code > Enumeration < / code > of the keys contained in * this < code > ResourceBundle < / code > and its parent bundles . * @ see # keySet ( ) */ public Enumeration < String > getKeys ( ) { } }
// lazily load the lookup hashtable . if ( lookup == null ) { loadLookup ( ) ; } ResourceBundle parent = this . parent ; return new ResourceBundleEnumeration ( lookup . keySet ( ) , ( parent != null ) ? parent . getKeys ( ) : null ) ;
public class DefaultSizeRollingConfigurator { /** * Parse the maxLogSize parameter to a < code > long < / code > . Defaults to { @ link SizeRollingFileHandler # DEFAULT _ LOG _ SIZE _ BOUND } * @ param maxLogSizeStr * @ return */ long parseMaxLogSize ( String maxLogSizeStr ) { } }
long maxLogSize = SizeRollingFileHandler . DEFAULT_LOG_SIZE_BOUND ; if ( maxLogSizeStr != null ) { maxLogSizeStr = maxLogSizeStr . trim ( ) . toUpperCase ( ) ; if ( maxLogSizeStr . endsWith ( "T" ) ) { maxLogSizeStr = maxLogSizeStr . substring ( 0 , maxLogSizeStr . length ( ) - 1 ) ; try { maxLogSize = Long . parseLong ( maxLogSizeStr ) * 1024L * 1024L * 1024L * 1024L ; } catch ( NumberFormatException ex ) { LogHelperDebug . printError ( "Could not parse a long in " + maxLogSizeStr , ex , false ) ; } } else if ( maxLogSizeStr . endsWith ( "G" ) ) { maxLogSizeStr = maxLogSizeStr . substring ( 0 , maxLogSizeStr . length ( ) - 1 ) ; try { maxLogSize = Long . parseLong ( maxLogSizeStr ) * 1024L * 1024L * 1024L ; } catch ( NumberFormatException ex ) { LogHelperDebug . printError ( "Could not parse a long in " + maxLogSizeStr , ex , false ) ; } } else if ( maxLogSizeStr . endsWith ( "M" ) ) { maxLogSizeStr = maxLogSizeStr . substring ( 0 , maxLogSizeStr . length ( ) - 1 ) ; try { maxLogSize = Long . parseLong ( maxLogSizeStr ) * 1024L * 1024L ; } catch ( NumberFormatException ex ) { LogHelperDebug . printError ( "Could not parse a long in " + maxLogSizeStr , ex , false ) ; } } else if ( maxLogSizeStr . endsWith ( "K" ) ) { maxLogSizeStr = maxLogSizeStr . substring ( 0 , maxLogSizeStr . length ( ) - 1 ) ; try { maxLogSize = Long . parseLong ( maxLogSizeStr ) * 1024L ; } catch ( NumberFormatException ex ) { LogHelperDebug . printError ( "Could not parse a long in " + maxLogSizeStr , ex , false ) ; } } else { try { maxLogSize = Long . parseLong ( maxLogSizeStr ) ; } catch ( NumberFormatException ex ) { LogHelperDebug . printError ( "Could not parse a long in " + maxLogSizeStr , ex , false ) ; } } } return maxLogSize ;
public class DoublesUnionImpl { /** * Returns a Heap DoublesUnion object that has been initialized with the data from the given * sketch . * @ param sketch A DoublesSketch to be used as a source of data only and will not be modified . * @ return a DoublesUnion object */ static DoublesUnionImpl heapifyInstance ( final DoublesSketch sketch ) { } }
final int k = sketch . getK ( ) ; final DoublesUnionImpl union = new DoublesUnionImpl ( k ) ; union . maxK_ = k ; union . gadget_ = copyToHeap ( sketch ) ; return union ;
public class AutumnApplication { /** * Invoked before context initiation . * @ param initializer should be used to registered default components , created with plain old Java . */ protected void addDefaultComponents ( final ContextInitializer initializer ) { } }
initializer . addComponents ( // PROCESSORS . // Assets : new AssetService ( ) , new SkinAssetAnnotationProcessor ( ) , // Locale : new LocaleService ( ) , // SFX : new MusicEnabledAnnotationProcessor ( ) , new MusicVolumeAnnotationProcessor ( ) , new SoundEnabledAnnotationProcessor ( ) , new SoundVolumeAnnotationProcessor ( ) , // Settings : new I18nBundleAnnotationProcessor ( ) , new PreferenceAnnotationProcessor ( ) , new SkinAnnotationProcessor ( ) , new StageViewportAnnotationProcessor ( ) , new PreferencesService ( ) , // Interface : new ViewAnnotationProcessor ( ) , new ViewDialogAnnotationProcessor ( ) , new ViewActionContainerAnnotationProcessor ( ) , new ViewStageAnnotationProcessor ( ) , new LmlMacroAnnotationProcessor ( ) , new LmlParserSyntaxAnnotationProcessor ( ) , new AvailableLocalesAnnotationProcessor ( ) , // COMPONENTS . // SFX : new MusicService ( ) , // Interface : interfaceService , new SkinService ( ) ) ;
public class Ifc2x3tc1PackageImpl { /** * < ! - - begin - user - doc - - > * < ! - - end - user - doc - - > * @ generated */ public EEnum getIfcLightEmissionSourceEnum ( ) { } }
if ( ifcLightEmissionSourceEnumEEnum == null ) { ifcLightEmissionSourceEnumEEnum = ( EEnum ) EPackage . Registry . INSTANCE . getEPackage ( Ifc2x3tc1Package . eNS_URI ) . getEClassifiers ( ) . get ( 854 ) ; } return ifcLightEmissionSourceEnumEEnum ;
public class SwipeBack { /** * Attaches the SwipeBack to the Activity * @ param activity * @ param type * @ param position * @ param dragMode * The dragMode which is { @ link # DRAG _ CONTENT } or * { @ link # DRAG _ WINDOW } * @ return The created SwipeBack instance */ public static SwipeBack attach ( Activity activity , Type type , Position position , int dragMode ) { } }
return attach ( activity , type , position , dragMode , new DefaultSwipeBackTransformer ( ) ) ;
public class AbstractResourceBundleTag { /** * Returns the resource handler * @ param context * the FacesContext * @ return the resource handler */ protected ResourceBundlesHandler getResourceBundlesHandler ( FacesContext context ) { } }
Object handler = context . getExternalContext ( ) . getApplicationMap ( ) . get ( getResourceBundlesHandlerAttributeName ( ) ) ; if ( null == handler ) throw new IllegalStateException ( "ResourceBundlesHandler not present in servlet context. Initialization of Jawr either failed or never occurred." ) ; ResourceBundlesHandler rsHandler = ( ResourceBundlesHandler ) handler ; return rsHandler ;
public class MetadataTemplate { /** * Returns all metadata templates within a user ' s scope . Currently only the enterprise scope is supported . * @ param scope the scope of the metadata templates . * @ param api the API connection to be used . * @ param fields the fields to retrieve . * @ return the metadata template returned from the server . */ public static Iterable < MetadataTemplate > getEnterpriseMetadataTemplates ( String scope , BoxAPIConnection api , String ... fields ) { } }
return getEnterpriseMetadataTemplates ( ENTERPRISE_METADATA_SCOPE , DEFAULT_ENTRIES_LIMIT , api , fields ) ;
public class PStmAssistantInterpreter { /** * Find a statement starting on the given line . Single statements just compare their location to lineno , but block * statements and statements with sub - statements iterate over their branches . * @ param stm * the statement * @ param lineno * The line number to locate . * @ return A statement starting on the line , or null . */ public PStm findStatement ( PStm stm , int lineno ) { } }
try { return stm . apply ( af . getStatementFinder ( ) , lineno ) ; // FIXME : should we handle exceptions like this } catch ( AnalysisException e ) { return null ; // Most have none }
public class Utility { /** * Post Lollipop Devices require permissions on Runtime ( Risky Ones ) , even though it has been * specified in the uses - permission tag of manifest . checkStorageAccessPermissions * method checks whether the READ EXTERNAL STORAGE permission has been granted to * the Application . * @ return a boolean value notifying whether the permission is granted or not . */ public static boolean checkStorageAccessPermissions ( Context context ) { } }
// Only for Android M and above . if ( android . os . Build . VERSION . SDK_INT >= android . os . Build . VERSION_CODES . M ) { String permission = "android.permission.READ_EXTERNAL_STORAGE" ; int res = context . checkCallingOrSelfPermission ( permission ) ; return ( res == PackageManager . PERMISSION_GRANTED ) ; } else { // Pre Marshmallow can rely on Manifest defined permissions . return true ; }
public class Table { /** * Update record in the table using table ' s primary key to locate record in * the table and values of fields of specified object < I > obj < / I > to alter * record fields . Only the fields marked as modified in the supplied field * mask will be updated in the database . * @ param obj object specifying value of primary key and new values of * updated record fields * @ param mask a { @ link FieldMask } instance configured to indicate which of * the object ' s fields are modified and should be written to the database . * @ return number of objects actually updated */ public synchronized int update ( Connection conn , T obj , FieldMask mask ) throws SQLException { } }
int nUpdated = 0 ; String sql = "update " + name + " set " + ( mask != null ? buildListOfAssignments ( mask ) : listOfAssignments ) + buildUpdateWhere ( ) ; PreparedStatement ustmt = conn . prepareStatement ( sql ) ; int column = bindUpdateVariables ( ustmt , obj , mask ) ; for ( int i = 0 ; i < primaryKeys . length ; i ++ ) { int fidx = primaryKeyIndices [ i ] ; fields [ fidx ] . bindVariable ( ustmt , obj , column + i + 1 ) ; } nUpdated = ustmt . executeUpdate ( ) ; ustmt . close ( ) ; return nUpdated ;
public class StackBenchmarkParameterized { /** * Bench for pushing the data to the { @ link FastIntStack } . */ @ Bench ( dataProvider = "generateData" ) void benchFastIntPush ( final List < Integer > intData ) { } }
fastInt = new FastIntStack ( ) ; for ( final Object i : intData ) { fastInt . push ( ( Integer ) i ) ; }
public class ManCommand { /** * / * ( non - Javadoc ) * @ see org . telegram . telegrambots . extensions . bots . commandbot . commands . helpCommand . IManCommand # toMan ( ) */ @ Override public String toMan ( ) { } }
StringBuilder sb = new StringBuilder ( toString ( ) ) ; sb . append ( System . lineSeparator ( ) ) . append ( "-----------------" ) . append ( System . lineSeparator ( ) ) ; if ( getExtendedDescription ( ) != null ) sb . append ( getExtendedDescription ( ) ) ; return sb . toString ( ) ;
public class string { /** * Turns a camel case string into an underscored one , e . g . " HelloWorld " * becomes " hello _ world " . * @ param camelCaseString the string to underscore * @ return the underscored string */ public static String underscore ( String camelCaseString ) { } }
String [ ] words = splitByCharacterTypeCamelCase ( camelCaseString ) ; return TextUtils . join ( "_" , words ) . toLowerCase ( ) ;
public class RevisionDecoder { /** * Decodes a Delete operation . * @ param blockSize _ S * length of a S block * @ param blockSize _ E * length of a E block * @ return DiffPart , Delete operation * @ throws DecodingException * if the decoding failed */ private DiffPart decodeDelete ( final int blockSize_S , final int blockSize_E ) throws DecodingException { } }
if ( blockSize_S < 1 || blockSize_E < 1 ) { throw new DecodingException ( "Invalid value for blockSize_S: " + blockSize_S + " or blockSize_E: " + blockSize_E ) ; } int s = r . read ( blockSize_S ) ; int e = r . read ( blockSize_E ) ; DiffPart part = new DiffPart ( DiffAction . DELETE ) ; part . setStart ( s ) ; part . setLength ( e ) ; r . skip ( ) ; return part ;
public class Query { /** * < pre > * { $ and : [ expressions ] } * { $ or : [ expressions ] } * < / pre > */ public static Query logical ( LogOp op , Query ... expressions ) { } }
return logical ( op , Arrays . asList ( expressions ) ) ;
public class GifAnimationBackend { /** * Measures the source , and sets the size based on them . Maintains aspect ratio of source , and * ensures that screen is filled in at least one dimension . * < p > Adapted from com . facebook . cameracore . common . RenderUtil # calculateFitRect * @ param viewPortWidth the width of the display * @ param viewPortHeight the height of the display * @ param sourceWidth the width of the video * @ param sourceHeight the height of the video */ private void scale ( int viewPortWidth , int viewPortHeight , int sourceWidth , int sourceHeight ) { } }
float inputRatio = ( ( float ) sourceWidth ) / sourceHeight ; float outputRatio = ( ( float ) viewPortWidth ) / viewPortHeight ; int scaledWidth = viewPortWidth ; int scaledHeight = viewPortHeight ; if ( outputRatio > inputRatio ) { // Not enough width to fill the output . ( Black bars on left and right . ) scaledWidth = ( int ) ( viewPortHeight * inputRatio ) ; scaledHeight = viewPortHeight ; } else if ( outputRatio < inputRatio ) { // Not enough height to fill the output . ( Black bars on top and bottom . ) scaledHeight = ( int ) ( viewPortWidth / inputRatio ) ; scaledWidth = viewPortWidth ; } float scale = scaledWidth / ( float ) sourceWidth ; mMidX = ( ( viewPortWidth - scaledWidth ) / 2f ) / scale ; mMidY = ( ( viewPortHeight - scaledHeight ) / 2f ) / scale ;
public class CamelCommandsHelper { /** * Populates the details for the given component , returning a Result if it fails . */ public static Result loadCamelComponentDetails ( CamelCatalog camelCatalog , String camelComponentName , CamelComponentDetails details ) { } }
String json = camelCatalog . componentJSonSchema ( camelComponentName ) ; if ( json == null ) { return Results . fail ( "Could not find catalog entry for component name: " + camelComponentName ) ; } List < Map < String , String > > data = JSonSchemaHelper . parseJsonSchema ( "component" , json , false ) ; for ( Map < String , String > row : data ) { String javaType = row . get ( "javaType" ) ; if ( ! Strings . isNullOrEmpty ( javaType ) ) { details . setComponentClassQName ( javaType ) ; } String groupId = row . get ( "groupId" ) ; if ( ! Strings . isNullOrEmpty ( groupId ) ) { details . setGroupId ( groupId ) ; } String artifactId = row . get ( "artifactId" ) ; if ( ! Strings . isNullOrEmpty ( artifactId ) ) { details . setArtifactId ( artifactId ) ; } String version = row . get ( "version" ) ; if ( ! Strings . isNullOrEmpty ( version ) ) { details . setVersion ( version ) ; } } if ( Strings . isNullOrEmpty ( details . getComponentClassQName ( ) ) ) { return Results . fail ( "Could not find fully qualified class name in catalog for component name: " + camelComponentName ) ; } return null ;
public class Utils { /** * Formats a collection of elements as a string . * @ param items a non - null list of items * @ param separator a string to separate items * @ return a non - null string */ public static String format ( Collection < String > items , String separator ) { } }
StringBuilder sb = new StringBuilder ( ) ; for ( Iterator < String > it = items . iterator ( ) ; it . hasNext ( ) ; ) { sb . append ( it . next ( ) ) ; if ( it . hasNext ( ) ) sb . append ( separator ) ; } return sb . toString ( ) ;
public class CmsClientUserSettingConverter { /** * Saves the given user preference values . < p > * @ param settings the user preference values to save * @ throws Exception if something goes wrong */ public void saveSettings ( Map < String , String > settings ) throws Exception { } }
for ( Map . Entry < String , String > entry : settings . entrySet ( ) ) { String key = entry . getKey ( ) ; String value = entry . getValue ( ) ; saveSetting ( key , value ) ; } m_currentPreferences . save ( m_cms ) ; CmsWorkplace . updateUserPreferences ( m_cms , m_request ) ;
public class Blog { /** * Get the submissions for this blog * @ param options the options ( or null ) * @ return a List of posts */ public List < Post > submissions ( Map < String , ? > options ) { } }
return client . blogSubmissions ( name , options ) ;
public class BaseLexicon { /** * TODO : this used to actually score things based on the original trees */ public final void tune ( ) { } }
double bestScore = Double . NEGATIVE_INFINITY ; double [ ] bestSmooth = { 0.0 , 0.0 } ; for ( smooth [ 0 ] = 1 ; smooth [ 0 ] <= 1 ; smooth [ 0 ] *= 2.0 ) { // 64 for ( smooth [ 1 ] = 0.2 ; smooth [ 1 ] <= 0.2 ; smooth [ 1 ] *= 2.0 ) { // for ( smooth [ 0 ] = 0.5 ; smooth [ 0 ] < = 64 ; smooth [ 0 ] * = 2.0 ) { / / 64 // for ( smooth [ 1 ] = 0.1 ; smooth [ 1 ] < = 12.8 ; smooth [ 1 ] * = 2.0 ) { / / 3 double score = 0.0 ; // score = scoreAll ( trees ) ; if ( testOptions . verbose ) { System . err . println ( "Tuning lexicon: s0 " + smooth [ 0 ] + " s1 " + smooth [ 1 ] + " is " + score ) ; } if ( score > bestScore ) { System . arraycopy ( smooth , 0 , bestSmooth , 0 , smooth . length ) ; bestScore = score ; } } } System . arraycopy ( bestSmooth , 0 , smooth , 0 , bestSmooth . length ) ; if ( smartMutation ) { smooth [ 0 ] = 8.0 ; // smooth [ 1 ] = 1.6; // smooth [ 0 ] = 0.5; smooth [ 1 ] = 0.1 ; } if ( testOptions . unseenSmooth > 0.0 ) { smooth [ 0 ] = testOptions . unseenSmooth ; } if ( testOptions . verbose ) { System . err . println ( "Tuning selected smoothUnseen " + smooth [ 0 ] + " smoothSeen " + smooth [ 1 ] + " at " + bestScore ) ; }
public class BoxResource { /** * Resolves { @ link BoxResourceType } for a provided { @ link BoxResource } { @ link Class } . * @ param clazz * { @ link BoxResource } type * @ return resolved { @ link BoxResourceType # value ( ) } */ public static String getResourceType ( Class < ? extends BoxResource > clazz ) { } }
BoxResourceType resource = clazz . getAnnotation ( BoxResourceType . class ) ; if ( resource == null ) { throw new IllegalArgumentException ( "Provided BoxResource type does not have @BoxResourceType annotation." ) ; } return resource . value ( ) ;
public class HiveSQLException { /** * Converts the specified { @ link Exception } object into a { @ link TStatus } object * @ param e a { @ link Exception } object * @ return a { @ link TStatus } object */ public static TStatus toTStatus ( Exception e ) { } }
if ( e instanceof HiveSQLException ) { return ( ( HiveSQLException ) e ) . toTStatus ( ) ; } TStatus tStatus = new TStatus ( TStatusCode . ERROR_STATUS ) ; tStatus . setErrorMessage ( e . getMessage ( ) ) ; tStatus . setInfoMessages ( toString ( e ) ) ; return tStatus ;
public class CsvDataSource { /** * CSV files are not loaded here , this is done on - access ( lazy loading ) . */ protected Map < String , CsvFile > getCsvFiles ( ) { } }
if ( csvFiles == null ) { String fileName = null ; csvFiles = Maps . newHashMap ( ) ; Set < String > keys = configuration . keySet ( ) ; String prefix = "dataSource." + getName ( ) + "." ; for ( String key : keys ) { if ( key . startsWith ( prefix ) ) { String dataKey = key . substring ( key . indexOf ( prefix ) + prefix . length ( ) ) ; fileName = configuration . get ( key ) ; if ( StringUtils . isEmpty ( fileName ) ) { // no CSV file configured continue ; } log . debug ( "Loading file " + fileName + " for dataKey=" + dataKey ) ; CsvFile csvFile = new CsvFile ( fileName ) ; csvFiles . put ( dataKey , csvFile ) ; } } if ( csvFiles . isEmpty ( ) ) { log . warn ( "CsvDataSource can only be used when CSV files are correctly configured" ) ; } } return csvFiles ;
public class ThriftServiceUtils { /** * Retrieves thrift service names of { @ code service } using reflection . */ static Set < String > serviceNames ( Service < HttpRequest , HttpResponse > service ) { } }
if ( thriftServiceClass == null || entriesMethod == null || interfacesMethod == null ) { return ImmutableSet . of ( ) ; } return service . as ( thriftServiceClass ) . map ( s -> { @ SuppressWarnings ( "unchecked" ) final Map < String , ? > entries = ( Map < String , ? > ) invokeMethod ( entriesMethod , s ) ; assert entries != null ; return toServiceName ( entries . values ( ) ) ; } ) . orElse ( ImmutableSet . of ( ) ) ;
public class AvatarZKShell { /** * This method tries to update the information in ZooKeeper For every address * of the NameNode it is being run for ( fs . default . name , * dfs . namenode . dn - address , dfs . namenode . http . address ) if they are present . It * also creates information for aliases in ZooKeeper for lists of strings in * fs . default . name . aliases , dfs . namenode . dn - address . aliases and * dfs . namenode . http . address . aliases * Each address it transformed to the address of the zNode to be created by * substituting all . and : characters to / . The slash is also added in the * front to make it a valid zNode address . So dfs . domain . com : 9000 will be * / dfs / domain / com / 9000 * If any part of the path does not exist it is created automatically */ public void updateZooKeeper ( boolean force , boolean toOverwrite , String serviceName , String primary ) throws IOException { } }
if ( ! force ) { initAvatarRPC ( ) ; Avatar avatar = avatarnode . getAvatar ( ) ; if ( avatar != Avatar . ACTIVE ) { throw new IOException ( "Cannot update ZooKeeper information to point to " + "the AvatarNode in Standby mode" ) ; } } AvatarNodeZkUtil . updateZooKeeper ( originalConf , conf , toOverwrite , serviceName , primary ) ;
public class SSLConfigManager { /** * This method checks if the client supports / requires SSL client * authentication . Returns false if both required and supported are false . * @ return boolean */ public synchronized boolean isClientAuthenticationEnabled ( ) { } }
if ( TraceComponent . isAnyTracingEnabled ( ) && tc . isEntryEnabled ( ) ) Tr . entry ( tc , "isClientAuthenticationEnabled" ) ; boolean auth = false ; if ( TraceComponent . isAnyTracingEnabled ( ) && tc . isEntryEnabled ( ) ) Tr . exit ( tc , "isClientAuthenticationEnabled" , Boolean . valueOf ( auth ) ) ; return auth ;
public class AbstractWSingleSelectList { /** * Determines which selection has been included in the given request . * @ param request the current request * @ return the selected option in the given request */ protected Object getNewSelection ( final Request request ) { } }
String paramValue = request . getParameter ( getId ( ) ) ; if ( paramValue == null ) { return null ; } // Figure out which option has been selected . List < ? > options = getOptions ( ) ; if ( options == null || options . isEmpty ( ) ) { if ( ! isEditable ( ) ) { // User could not have made a selection . return null ; } options = Collections . EMPTY_LIST ; } int optionIndex = 0 ; for ( Object option : options ) { if ( option instanceof OptionGroup ) { List < ? > groupOptions = ( ( OptionGroup ) option ) . getOptions ( ) ; if ( groupOptions != null ) { for ( Object nestedOption : groupOptions ) { if ( paramValue . equals ( optionToCode ( nestedOption , optionIndex ++ ) ) ) { return nestedOption ; } } } } else if ( paramValue . equals ( optionToCode ( option , optionIndex ++ ) ) ) { return option ; } } // Option not found , but if editable , user entered text if ( isEditable ( ) ) { return paramValue ; } // Invalid option . Ignore and use the current selection LOG . warn ( "Option \"" + paramValue + "\" on the request is not a valid option. Will be ignored." ) ; Object currentOption = getValue ( ) ; return currentOption ;
public class Sanitizer { /** * Sanitize the given value if necessary . * @ param key the key to sanitize * @ param value the value * @ return the potentially sanitized value */ public Object sanitize ( String key , Object value ) { } }
if ( value == null ) { return null ; } for ( Pattern pattern : this . keysToSanitize ) { if ( pattern . matcher ( key ) . matches ( ) ) { return "******" ; } } return value ;
public class CPDefinitionLocalizationPersistenceImpl { /** * Removes the cp definition localization with the primary key from the database . Also notifies the appropriate model listeners . * @ param primaryKey the primary key of the cp definition localization * @ return the cp definition localization that was removed * @ throws NoSuchCPDefinitionLocalizationException if a cp definition localization with the primary key could not be found */ @ Override public CPDefinitionLocalization remove ( Serializable primaryKey ) throws NoSuchCPDefinitionLocalizationException { } }
Session session = null ; try { session = openSession ( ) ; CPDefinitionLocalization cpDefinitionLocalization = ( CPDefinitionLocalization ) session . get ( CPDefinitionLocalizationImpl . class , primaryKey ) ; if ( cpDefinitionLocalization == null ) { if ( _log . isDebugEnabled ( ) ) { _log . debug ( _NO_SUCH_ENTITY_WITH_PRIMARY_KEY + primaryKey ) ; } throw new NoSuchCPDefinitionLocalizationException ( _NO_SUCH_ENTITY_WITH_PRIMARY_KEY + primaryKey ) ; } return remove ( cpDefinitionLocalization ) ; } catch ( NoSuchCPDefinitionLocalizationException nsee ) { throw nsee ; } catch ( Exception e ) { throw processException ( e ) ; } finally { closeSession ( session ) ; }
public class LookupBinding { /** * Get / create the button to open the dataEditor in selection mode */ protected AbstractButton getDataEditorButton ( ) { } }
if ( dataEditorButton == null ) { dataEditorButton = getDataEditorCommand ( ) . createButton ( ) ; dataEditorButton . setFocusable ( false ) ; // dataEditorButton . addFocusListener ( createFocusListener ( ) ) ; } return dataEditorButton ;
public class Eval { /** * General object type evaluation . * < ul > * < li > return < code > false < / code > if the object instance is < code > null < / code > < / li > * < li > return < code > false < / code > if the object instance is an empty { @ link java . util . Collection } or { @ link java . util . Map } < / li > * < li > if object is type of Character , Float , Double then use its primitive value to evaluate < / li > * < li > if object is any other type of Number , then use it ' s { @ link Number # intValue ( ) } to evaluate < / li > * < / ul > * @ param condition * @ return boolean result */ public static boolean eval ( Object condition ) { } }
if ( condition == null ) { return false ; } else if ( condition instanceof String ) { return eval ( ( String ) condition ) ; } else if ( condition instanceof Boolean ) { return ( Boolean ) condition ; } else if ( condition instanceof Collection ) { return eval ( ( Collection ) condition ) ; } else if ( condition instanceof Map ) { return eval ( ( Map ) condition ) ; } else if ( condition instanceof Double ) { return eval ( ( Double ) condition ) ; } else if ( condition instanceof Float ) { return eval ( ( Float ) condition ) ; } else if ( condition instanceof Long ) { return eval ( ( Long ) condition ) ; } else if ( condition . getClass ( ) . isArray ( ) ) { return Array . getLength ( condition ) > 0 ; } else if ( condition instanceof Number ) { return eval ( ( Number ) condition ) ; } return true ;
public class KvStateSerializer { /** * Deserializes all kv pairs with the given serializer . * @ param serializedValue Serialized value of type Map & lt ; UK , UV & gt ; * @ param keySerializer Serializer for UK * @ param valueSerializer Serializer for UV * @ param < UK > Type of the key * @ param < UV > Type of the value . * @ return Deserialized map or < code > null < / code > if the serialized value * is < code > null < / code > * @ throws IOException On failure during deserialization */ public static < UK , UV > Map < UK , UV > deserializeMap ( byte [ ] serializedValue , TypeSerializer < UK > keySerializer , TypeSerializer < UV > valueSerializer ) throws IOException { } }
if ( serializedValue != null ) { DataInputDeserializer in = new DataInputDeserializer ( serializedValue , 0 , serializedValue . length ) ; Map < UK , UV > result = new HashMap < > ( ) ; while ( in . available ( ) > 0 ) { UK key = keySerializer . deserialize ( in ) ; boolean isNull = in . readBoolean ( ) ; UV value = isNull ? null : valueSerializer . deserialize ( in ) ; result . put ( key , value ) ; } return result ; } else { return null ; }
public class SipServletResponseImpl { /** * ( non - Javadoc ) * @ see javax . servlet . sip . SipServletResponse # createAck ( ) */ @ SuppressWarnings ( "unchecked" ) public SipServletRequest createAck ( ) { } }
final Response response = getResponse ( ) ; if ( logger . isDebugEnabled ( ) ) { logger . debug ( "transaction " + getTransaction ( ) ) ; logger . debug ( "originalRequest " + originalRequest ) ; } // transaction can be null in case of forking if ( ( ( getTransaction ( ) == null && originalRequest != null && ! Request . INVITE . equals ( getMethod ( ) ) && ! Request . INVITE . equals ( originalRequest . getMethod ( ) ) ) ) || ( getTransaction ( ) != null && ! Request . INVITE . equals ( ( ( SIPTransaction ) getTransaction ( ) ) . getMethod ( ) ) ) || ( response . getStatusCode ( ) >= 100 && response . getStatusCode ( ) < 200 ) || isAckGenerated ) { if ( logger . isDebugEnabled ( ) ) { logger . debug ( "transaction state " + ( ( SIPTransaction ) getTransaction ( ) ) . getMethod ( ) + " status code " + response . getStatusCode ( ) + " isAckGenerated " + isAckGenerated ) ; } throw new IllegalStateException ( "the transaction state is such that it doesn't allow an ACK to be sent now, e.g. the original request was not an INVITE, or this response is provisional only, or an ACK has already been generated" ) ; } final MobicentsSipSession session = getSipSession ( ) ; Dialog dialog = session . getSessionCreatingDialog ( ) ; CSeqHeader cSeqHeader = ( CSeqHeader ) response . getHeader ( CSeqHeader . NAME ) ; SipServletRequestImpl sipServletAckRequest = null ; try { if ( logger . isDebugEnabled ( ) ) { logger . debug ( "dialog to create the ack Request " + dialog ) ; } Request ackRequest = dialog . createAck ( cSeqHeader . getSeqNumber ( ) ) ; // Workaround wrong UA stack for Issue 1802 ackRequest . removeHeader ( ViaHeader . NAME ) ; if ( logger . isInfoEnabled ( ) ) { logger . info ( "ackRequest just created " + ackRequest ) ; } // Application Routing to avoid going through the same app that created the ack ListIterator < RouteHeader > routeHeaders = ackRequest . getHeaders ( RouteHeader . NAME ) ; ackRequest . removeHeader ( RouteHeader . NAME ) ; while ( routeHeaders . hasNext ( ) ) { RouteHeader routeHeader = routeHeaders . next ( ) ; String serverId = ( ( SipURI ) routeHeader . getAddress ( ) . getURI ( ) ) . getParameter ( MessageDispatcher . RR_PARAM_SERVER_NAME ) ; String routeAppNameHashed = ( ( SipURI ) routeHeader . getAddress ( ) . getURI ( ) ) . getParameter ( MessageDispatcher . RR_PARAM_APPLICATION_NAME ) ; String routeAppName = null ; if ( routeAppNameHashed != null ) { routeAppName = sipFactoryImpl . getSipApplicationDispatcher ( ) . getApplicationNameFromHash ( routeAppNameHashed ) ; } if ( routeAppName == null || ! sipFactoryImpl . getSipApplicationDispatcher ( ) . getApplicationServerId ( ) . equalsIgnoreCase ( serverId ) || ! routeAppName . equals ( getSipSession ( ) . getKey ( ) . getApplicationName ( ) ) ) { ackRequest . addHeader ( routeHeader ) ; } } sipServletAckRequest = ( SipServletRequestImpl ) sipFactoryImpl . getMobicentsSipServletMessageFactory ( ) . createSipServletRequest ( ackRequest , this . getSipSession ( ) , this . getTransaction ( ) , dialog , false ) ; isAckGenerated = true ; } catch ( InvalidArgumentException e ) { logger . error ( "Impossible to create the ACK" , e ) ; } catch ( SipException e ) { logger . error ( "Impossible to create the ACK" , e ) ; } return sipServletAckRequest ;
public class Rational { /** * Remove the fractional part . * @ return The integer rounded towards zero . */ public BigInteger trunc ( ) { } }
/* is already integer : return the numerator */ if ( b . compareTo ( BigInteger . ONE ) == 0 ) { return a ; } else { return a . divide ( b ) ; }
public class ShutdownHookProcessDestroyer { /** * Removes this < code > ProcessDestroyer < / code > as a shutdown hook , uses * reflection to ensure pre - JDK 1.3 compatibility */ private void removeShutdownHook ( ) { } }
if ( added && ! running ) { boolean removed = Runtime . getRuntime ( ) . removeShutdownHook ( destroyProcessThread ) ; if ( ! removed ) { log . error ( "Could not remove shutdown hook" ) ; } /* * start the hook thread , a unstarted thread may not be eligible for * garbage collection Cf . : http : / / developer . java . sun . com / developer / * bugParade / bugs / 4533087 . html */ destroyProcessThread . setShouldDestroy ( false ) ; destroyProcessThread . start ( ) ; // this should return quickly , since it basically is a NO - OP . try { destroyProcessThread . join ( 20000 ) ; } catch ( InterruptedException ie ) { // the thread didn ' t die in time // it should not kill any processes unexpectedly } destroyProcessThread = null ; added = false ; }