signature stringlengths 43 39.1k | implementation stringlengths 0 450k |
|---|---|
public class GrailsPlugin { /** * called by the modified code */
public static void recordInstance ( Object obj ) { } } | // obj will be a ClassPropertyFetcher instance
System . err . println ( "new instance queued " + System . identityHashCode ( obj ) ) ; // TODO urgent - race condition here , can create Co - modification problem if adding whilst another thread is processing
classPropertyFetcherInstances . add ( new WeakReference < Object > ( obj , rq ) ) ; |
public class RubyObject { /** * Executes a method of any Object by Java reflection .
* @ param o
* an Object
* @ param methodName
* name of the method
* @ param arg
* a Byte
* @ return the result of the method called */
public static < E > E send ( Object o , String methodName , Byte arg ) { } } | return send ( o , methodName , ( Object ) arg ) ; |
public class CmsJspImageBean { /** * Returns a lazy initialized Map that provides access to width scaled instances of this image bean . < p >
* @ return a lazy initialized Map that provides access to width scaled instances of this image bean */
public Map < String , CmsJspImageBean > getScaleWidth ( ) { } } | if ( m_scaleWidth == null ) { m_scaleWidth = CmsCollectionsGenericWrapper . createLazyMap ( new CmsScaleWidthTransformer ( ) ) ; } return m_scaleWidth ; |
public class AddMessages { /** * Add BugCategory elements .
* @ param bugCategorySet
* all bug categories referenced in the BugCollection */
private void addBugCategories ( Set < String > bugCategorySet ) { } } | Element root = document . getRootElement ( ) ; for ( String category : bugCategorySet ) { Element element = root . addElement ( "BugCategory" ) ; element . addAttribute ( "category" , category ) ; Element description = element . addElement ( "Description" ) ; description . setText ( I18N . instance ( ) . getBugCategoryDescription ( category ) ) ; BugCategory bc = DetectorFactoryCollection . instance ( ) . getBugCategory ( category ) ; if ( bc != null ) { // shouldn ' t be null
String s = bc . getAbbrev ( ) ; if ( s != null ) { Element abbrev = element . addElement ( "Abbreviation" ) ; abbrev . setText ( s ) ; } s = bc . getDetailText ( ) ; if ( s != null ) { Element details = element . addElement ( "Details" ) ; details . setText ( s ) ; } } } |
public class AbstractCommand { /** * Performs initialisation and validation of this instance after its
* dependencies have been set . If subclasses override this method , they
* should begin by calling { @ code super . afterPropertiesSet ( ) } . */
public void afterPropertiesSet ( ) { } } | if ( getId ( ) == null ) { logger . info ( "Command " + this + " has no set id; note: anonymous commands cannot be used in registries." ) ; } if ( this instanceof ActionCommand && ! isFaceConfigured ( ) ) { logger . info ( "The face descriptor property is not yet set for action command '" + getId ( ) + "'; configuring" ) ; } |
public class UriEscaper { /** * Returns whether or not this character is illegal in the given state */
private boolean isIllegal ( final char c , final State state ) { } } | switch ( state ) { case FRAGMENT : return ( strict ? STRICT_ILLEGAL_IN_FRAGMENT : ILLEGAL_IN_FRAGMENT ) . matches ( c ) ; case QUERY : return ( strict ? STRICT_ILLEGAL_IN_QUERY : ILLEGAL_IN_QUERY ) . matches ( c ) ; case QUERY_PARAM : return ( strict ? STRICT_ILLEGAL_IN_QUERY_PARAM : ILLEGAL_IN_QUERY_PARAM ) . matches ( c ) ; case PATH : return ( strict ? STRICT_ILLEGAL_IN_PATH : ILLEGAL_IN_PATH ) . matches ( c ) ; case HOST : return ILLEGAL_IN_HOST . matches ( c ) ; default : throw new AssertionError ( state ) ; } |
public class CollectionNumbers { /** * Copies the content of the collection to an array .
* @ param coll the collection
* @ return the array */
public static double [ ] doubleArrayCopyOf ( CollectionNumber coll ) { } } | double [ ] data = new double [ coll . size ( ) ] ; IteratorNumber iter = coll . iterator ( ) ; int index = 0 ; while ( iter . hasNext ( ) ) { data [ index ] = iter . nextDouble ( ) ; index ++ ; } return data ; |
public class BinaryTreeNode { /** * Clear the tree .
* < p > Caution : this method also destroyes the
* links between the child nodes inside the tree .
* If you want to unlink the first - level
* child node with
* this node but leave the rest of the tree
* unchanged , please call < code > setChildAt ( i , null ) < / code > . */
@ Override public void clear ( ) { } } | if ( this . left != null ) { final N child = this . left ; setLeftChild ( null ) ; child . clear ( ) ; } if ( this . right != null ) { final N child = this . right ; setRightChild ( null ) ; child . clear ( ) ; } removeAllUserData ( ) ; |
public class ListViewCompat { /** * Measures the height of the given range of children ( inclusive ) and returns the height
* with this ListView ' s padding and divider heights included . If maxHeight is provided , the
* measuring will stop when the current height reaches maxHeight .
* @ param widthMeasureSpec The width measure spec to be given to a child ' s
* { @ link View # measure ( int , int ) } .
* @ param startPosition The position of the first child to be shown .
* @ param endPosition The ( inclusive ) position of the last child to be
* shown . Specify { @ link # NO _ POSITION } if the last child
* should be the last available child from the adapter .
* @ param maxHeight The maximum height that will be returned ( if all the
* children don ' t fit in this value , this value will be
* returned ) .
* @ param disallowPartialChildPosition In general , whether the returned height should only
* contain entire children . This is more powerful - - it is
* the first inclusive position at which partial
* children will not be allowed . Example : it looks nice
* to have at least 3 completely visible children , and
* in portrait this will most likely fit ; but in
* landscape there could be times when even 2 children
* can not be completely shown , so a value of 2
* ( remember , inclusive ) would be good ( assuming
* startPosition is 0 ) .
* @ return The height of this ListView with the given children . */
public int measureHeightOfChildrenCompat ( int widthMeasureSpec , int startPosition , int endPosition , final int maxHeight , int disallowPartialChildPosition ) { } } | final int paddingTop = getListPaddingTop ( ) ; final int paddingBottom = getListPaddingBottom ( ) ; final int paddingLeft = getListPaddingLeft ( ) ; final int paddingRight = getListPaddingRight ( ) ; final int reportedDividerHeight = getDividerHeight ( ) ; final Drawable divider = getDivider ( ) ; final ListAdapter adapter = getAdapter ( ) ; if ( adapter == null ) { return paddingTop + paddingBottom ; } // Include the padding of the list
int returnedHeight = paddingTop + paddingBottom ; final int dividerHeight = ( ( reportedDividerHeight > 0 ) && divider != null ) ? reportedDividerHeight : 0 ; // The previous height value that was less than maxHeight and contained
// no partial children
int prevHeightWithoutPartialChild = 0 ; View child = null ; int viewType = 0 ; int count = adapter . getCount ( ) ; for ( int i = 0 ; i < count ; i ++ ) { int newType = adapter . getItemViewType ( i ) ; if ( newType != viewType ) { child = null ; viewType = newType ; } child = adapter . getView ( i , child , this ) ; // Compute child height spec
int heightMeasureSpec ; ViewGroup . LayoutParams childLp = child . getLayoutParams ( ) ; if ( childLp == null ) { childLp = generateDefaultLayoutParams ( ) ; child . setLayoutParams ( childLp ) ; } if ( childLp . height > 0 ) { heightMeasureSpec = MeasureSpec . makeMeasureSpec ( childLp . height , MeasureSpec . EXACTLY ) ; } else { heightMeasureSpec = MeasureSpec . makeMeasureSpec ( 0 , MeasureSpec . UNSPECIFIED ) ; } child . measure ( widthMeasureSpec , heightMeasureSpec ) ; // Since this view was measured directly aginst the parent measure
// spec , we must measure it again before reuse .
child . forceLayout ( ) ; if ( i > 0 ) { // Count the divider for all but one child
returnedHeight += dividerHeight ; } returnedHeight += child . getMeasuredHeight ( ) ; if ( returnedHeight >= maxHeight ) { // We went over , figure out which height to return . If returnedHeight >
// maxHeight , then the i ' th position did not fit completely .
return ( disallowPartialChildPosition >= 0 ) // Disallowing is enabled ( > - 1)
&& ( i > disallowPartialChildPosition ) // We ' ve past the min pos
&& ( prevHeightWithoutPartialChild > 0 ) // We have a prev height
&& ( returnedHeight != maxHeight ) // i ' th child did not fit completely
? prevHeightWithoutPartialChild : maxHeight ; } if ( ( disallowPartialChildPosition >= 0 ) && ( i >= disallowPartialChildPosition ) ) { prevHeightWithoutPartialChild = returnedHeight ; } } // At this point , we went through the range of children , and they each
// completely fit , so return the returnedHeight
return returnedHeight ; |
public class NodeRegisterImpl { /** * { @ inheritDoc } */
public synchronized void handlePingInRegister ( ArrayList < Node > ping ) { } } | for ( Node pingNode : ping ) { if ( pingNode . getIp ( ) == null ) { // https : / / telestax . atlassian . net / browse / LB - 9 Prevent Routing of Requests to Nodes that exposed null IP address
logger . warn ( "[" + pingNode + "] not added as its IP is null, the node is sending bad information" ) ; } else { Boolean isIpV6 = LbUtils . isValidInet6Address ( pingNode . getIp ( ) ) ; Boolean isIpV4 = InetAddressValidator . getInstance ( ) . isValidInet4Address ( pingNode . getIp ( ) ) ; if ( ! isIpV4 && ! isIpV6 ) logger . warn ( "[" + pingNode + "] not added as its IP is null, the node is sending bad information" ) ; else { String version = pingNode . getProperties ( ) . get ( "version" ) ; if ( version == null ) version = "0" ; InvocationContext ctx = balancerRunner . getInvocationContext ( version ) ; // if bad node changed sessioId it means that the node was restarted so we remove it from map of bad nodes
KeySip keySip = new KeySip ( pingNode , isIpV6 ) ; if ( ctx . sipNodeMap ( isIpV6 ) . get ( keySip ) != null && ctx . sipNodeMap ( isIpV6 ) . get ( keySip ) . isBad ( ) ) { if ( ctx . sipNodeMap ( isIpV6 ) . get ( keySip ) . getProperties ( ) . get ( "sessionId" ) . equals ( pingNode . getProperties ( ) . get ( "sessionId" ) ) ) continue ; else { ctx . sipNodeMap ( isIpV6 ) . get ( keySip ) . setBad ( false ) ; String instanseId = pingNode . getProperties ( ) . get ( Protocol . RESTCOMM_INSTANCE_ID ) ; if ( instanseId != null ) ctx . httpNodeMap . get ( new KeyHttp ( instanseId ) ) . setBad ( false ) ; } } pingNode . updateTimerStamp ( ) ; // logger . info ( " Pingnode updated " + pingNode ) ;
if ( pingNode . getProperties ( ) . get ( "jvmRoute" ) != null ) { // Let it leak , we will have 10-100 nodes , not a big deal if it leaks .
// We need info about inactive nodes to do the failover
balancerRunner . balancerContext . jvmRouteToSipNode . put ( pingNode . getProperties ( ) . get ( "jvmRoute" ) , pingNode ) ; } Node nodePresent = ctx . sipNodeMap ( isIpV6 ) . get ( keySip ) ; // adding done afterwards to avoid ConcurrentModificationException when adding the node while going through the iterator
if ( nodePresent != null ) { nodePresent . updateTimerStamp ( ) ; if ( logger . isTraceEnabled ( ) ) { logger . trace ( "Ping " + nodePresent . getTimeStamp ( ) ) ; } if ( pingNode . getProperties ( ) . get ( "GRACEFUL_SHUTDOWN" ) != null && pingNode . getProperties ( ) . get ( "GRACEFUL_SHUTDOWN" ) . equals ( "true" ) ) { logger . info ( "LB will exclude node " + nodePresent + " for new calls because of GRACEFUL_SHUTDOWN" ) ; ctx . sipNodeMap ( isIpV6 ) . get ( keySip ) . setGracefulShutdown ( true ) ; String instanseId = pingNode . getProperties ( ) . get ( Protocol . RESTCOMM_INSTANCE_ID ) ; if ( instanseId != null ) ctx . httpNodeMap . get ( new KeyHttp ( instanseId ) ) . setGracefulShutdown ( true ) ; } } else if ( pingNode . getProperties ( ) . get ( "GRACEFUL_SHUTDOWN" ) != null && pingNode . getProperties ( ) . get ( "GRACEFUL_SHUTDOWN" ) . equals ( "true" ) ) { if ( logger . isDebugEnabled ( ) ) logger . debug ( "Ping from node which LB exclude because of GRACEFUL_SHUTDOWN : " + pingNode ) ; } else { Integer current = Integer . parseInt ( version ) ; Integer latest = Integer . parseInt ( latestVersion ) ; latestVersion = Math . max ( current , latest ) + "" ; balancerRunner . balancerContext . aliveNodes . add ( pingNode ) ; ctx . sipNodeMap ( isIpV6 ) . put ( keySip , pingNode ) ; String instanceId = pingNode . getProperties ( ) . get ( "Restcomm-Instance-Id" ) ; if ( instanceId != null ) ctx . httpNodeMap . put ( new KeyHttp ( instanceId ) , pingNode ) ; Integer smppPort = null ; if ( pingNode . getProperties ( ) . get ( "smppPort" ) != null ) { smppPort = Integer . parseInt ( pingNode . getProperties ( ) . get ( "smppPort" ) ) ; ctx . smppNodeMap . put ( new KeySmpp ( pingNode ) , pingNode ) ; } ctx . balancerAlgorithm . nodeAdded ( pingNode ) ; balancerRunner . balancerContext . allNodesEver . add ( pingNode ) ; pingNode . updateTimerStamp ( ) ; if ( logger . isInfoEnabled ( ) ) { logger . info ( "NodeExpirationTimerTask Run NSync[" + pingNode + "] added" ) ; } } } } } |
public class Grego { /** * Convenient method for formatting time to ISO 8601 style
* date string .
* @ param time long time
* @ return ISO - 8601 date string */
public static String timeToString ( long time ) { } } | int [ ] fields = timeToFields ( time , null ) ; int millis = fields [ 5 ] ; int hour = millis / MILLIS_PER_HOUR ; millis = millis % MILLIS_PER_HOUR ; int min = millis / MILLIS_PER_MINUTE ; millis = millis % MILLIS_PER_MINUTE ; int sec = millis / MILLIS_PER_SECOND ; millis = millis % MILLIS_PER_SECOND ; return String . format ( ( Locale ) null , "%04d-%02d-%02dT%02d:%02d:%02d.%03dZ" , fields [ 0 ] , fields [ 1 ] + 1 , fields [ 2 ] , hour , min , sec , millis ) ; |
public class LUDecomposition { /** * Return lower triangular factor
* @ return L */
public Matrix getL ( ) { } } | Matrix X = new Matrix ( m , n ) ; double [ ] [ ] L = X . getArray ( ) ; for ( int i = 0 ; i < m ; i ++ ) { for ( int j = 0 ; j < n ; j ++ ) { if ( i > j ) { L [ i ] [ j ] = LU [ i ] [ j ] ; } else if ( i == j ) { L [ i ] [ j ] = 1.0 ; } else { L [ i ] [ j ] = 0.0 ; } } } return X ; |
public class ForallDescr { /** * Returns the remaining patterns from the forall CE
* @ return */
public List < BaseDescr > getRemainingPatterns ( ) { } } | if ( this . patterns . size ( ) > 1 ) { return this . patterns . subList ( 1 , this . patterns . size ( ) ) ; } else if ( this . patterns . size ( ) == 1 ) { // in case there is only one pattern , we do a rewrite , so :
// forall ( Cheese ( type = = " stilton " ) )
// becomes
// forall ( BASE _ IDENTIFIER : Cheese ( ) Cheese ( this = = BASE _ IDENTIFIER , type = = " stilton " ) )
PatternDescr original = ( PatternDescr ) this . patterns . get ( 0 ) ; PatternDescr remaining = ( PatternDescr ) original . clone ( ) ; remaining . addConstraint ( new ExprConstraintDescr ( "this == " + BASE_IDENTIFIER ) ) ; remaining . setResource ( original . getResource ( ) ) ; return Collections . singletonList ( ( BaseDescr ) remaining ) ; } return Collections . emptyList ( ) ; |
public class BaseMessageFilter { /** * Update this object ' s filter with this new map information .
* @ param propFilter New filter information ( ie , bookmark = 345 ) pass null to sync the local and remote filters . */
public final void updateFilterMap ( Map < String , Object > propFilter ) { } } | if ( propFilter == null ) propFilter = new HashMap < String , Object > ( ) ; // Then handleUpdateFilterMap can modify the filter
propFilter = this . handleUpdateFilterMap ( propFilter ) ; // Update this object ' s local filter .
this . setFilterMap ( propFilter ) ; // Update any remote copy of this . |
public class JStormUtils { /** * If it is backend , please set resultHandler , such as DefaultExecuteResultHandler
* If it is frontend , ByteArrayOutputStream . toString will return the calling result
* This function will ignore whether the command is successfully executed or not
* @ param command command to be executed
* @ param environment env vars
* @ param workDir working directory
* @ param resultHandler exec result handler
* @ return output stream
* @ throws IOException */
@ Deprecated public static ByteArrayOutputStream launchProcess ( String command , final Map environment , final String workDir , ExecuteResultHandler resultHandler ) throws IOException { } } | String [ ] cmdlist = command . split ( " " ) ; CommandLine cmd = new CommandLine ( cmdlist [ 0 ] ) ; for ( String cmdItem : cmdlist ) { if ( ! StringUtils . isBlank ( cmdItem ) ) { cmd . addArgument ( cmdItem ) ; } } DefaultExecutor executor = new DefaultExecutor ( ) ; executor . setExitValue ( 0 ) ; if ( ! StringUtils . isBlank ( workDir ) ) { executor . setWorkingDirectory ( new File ( workDir ) ) ; } ByteArrayOutputStream out = new ByteArrayOutputStream ( ) ; PumpStreamHandler streamHandler = new PumpStreamHandler ( out , out ) ; executor . setStreamHandler ( streamHandler ) ; try { if ( resultHandler == null ) { executor . execute ( cmd , environment ) ; } else { executor . execute ( cmd , environment , resultHandler ) ; } } catch ( ExecuteException ignored ) { } return out ; |
public class ZWaveMultiInstanceCommandClass { /** * Handles Multi Channel Encapsulation message . Decapsulates
* an Application Command message and handles it using the right
* endpoint .
* @ param serialMessage the serial message to process .
* @ param offset the offset at which to start procesing . */
private void handleMultiChannelEncapResponse ( SerialMessage serialMessage , int offset ) { } } | logger . trace ( "Process Multi-channel Encapsulation" ) ; CommandClass commandClass ; ZWaveCommandClass zwaveCommandClass ; int endpointId = serialMessage . getMessagePayloadByte ( offset ) ; int commandClassCode = serialMessage . getMessagePayloadByte ( offset + 2 ) ; commandClass = CommandClass . getCommandClass ( commandClassCode ) ; if ( commandClass == null ) { logger . error ( String . format ( "Unsupported command class 0x%02x" , commandClassCode ) ) ; return ; } logger . debug ( String . format ( "Node %d Requested Command Class = %s (0x%02x)" , this . getNode ( ) . getNodeId ( ) , commandClass . getLabel ( ) , commandClassCode ) ) ; ZWaveEndpoint endpoint = this . endpoints . get ( endpointId ) ; if ( endpoint == null ) { logger . error ( "Endpoint {} not found on node {}. Cannot set command classes." , endpoint , this . getNode ( ) . getNodeId ( ) ) ; return ; } zwaveCommandClass = endpoint . getCommandClass ( commandClass ) ; if ( zwaveCommandClass == null ) { logger . warn ( String . format ( "CommandClass %s (0x%02x) not implemented by endpoint %d, fallback to main node." , commandClass . getLabel ( ) , commandClassCode , endpointId ) ) ; zwaveCommandClass = this . getNode ( ) . getCommandClass ( commandClass ) ; } if ( zwaveCommandClass == null ) { logger . error ( String . format ( "CommandClass %s (0x%02x) not implemented by node %d." , commandClass . getLabel ( ) , commandClassCode , this . getNode ( ) . getNodeId ( ) ) ) ; return ; } logger . debug ( String . format ( "Node %d, Endpoint = %d, calling handleApplicationCommandRequest." , this . getNode ( ) . getNodeId ( ) , endpointId ) ) ; zwaveCommandClass . handleApplicationCommandRequest ( serialMessage , offset + 3 , endpointId ) ; |
public class StpConnection { /** * Queues up an STP / 0 message sent from another thread and wakes up selector to register it to the
* key .
* @ param message to add to the request queue */
private void send ( String message ) { } } | String scopeMessage = message . length ( ) + " " + message ; logger . finest ( "WRITE : " + scopeMessage ) ; byte [ ] bytes = null ; try { bytes = scopeMessage . getBytes ( "UTF-16BE" ) ; } catch ( UnsupportedEncodingException e ) { close ( ) ; connectionHandler . onException ( e ) ; return ; } ByteBuffer buffer = ByteBuffer . allocate ( bytes . length ) ; buffer . put ( bytes ) ; requests . add ( buffer ) ; monitor . modify ( socketChannel , this , SelectionKey . OP_READ | SelectionKey . OP_WRITE ) ; |
public class AWSLogsClient { /** * Deletes the specified log stream and permanently deletes all the archived log events associated with the log
* stream .
* @ param deleteLogStreamRequest
* @ return Result of the DeleteLogStream operation returned by the service .
* @ throws InvalidParameterException
* A parameter is specified incorrectly .
* @ throws ResourceNotFoundException
* The specified resource does not exist .
* @ throws OperationAbortedException
* Multiple requests to update the same resource were in conflict .
* @ throws ServiceUnavailableException
* The service cannot complete the request .
* @ sample AWSLogs . DeleteLogStream
* @ see < a href = " http : / / docs . aws . amazon . com / goto / WebAPI / logs - 2014-03-28 / DeleteLogStream " target = " _ top " > AWS API
* Documentation < / a > */
@ Override public DeleteLogStreamResult deleteLogStream ( DeleteLogStreamRequest request ) { } } | request = beforeClientExecution ( request ) ; return executeDeleteLogStream ( request ) ; |
public class JobInProgress { /** * Find a non - running task in the passed list of TIPs
* @ param tips a collection of TIPs
* @ param ttStatus the status of tracker that has requested a task to run
* @ param numUniqueHosts number of unique hosts that run trask trackers
* @ param removeFailedTip whether to remove the failed tips */
private synchronized TaskInProgress findTaskFromList ( Collection < TaskInProgress > tips , TaskTrackerStatus ttStatus , int numUniqueHosts , boolean removeFailedTip ) { } } | Iterator < TaskInProgress > iter = tips . iterator ( ) ; while ( iter . hasNext ( ) ) { TaskInProgress tip = iter . next ( ) ; // Select a tip if
// 1 . runnable : still needs to be run and is not completed
// 2 . ~ running : no other node is running it
// 3 . earlier attempt failed : has not failed on this host
// and has failed on all the other hosts
// A TIP is removed from the list if
// (1 ) this tip is scheduled
// (2 ) if the passed list is a level 0 ( host ) cache
// (3 ) when the TIP is non - schedulable ( running , killed , complete )
if ( tip . isRunnable ( ) && ! tip . isRunning ( ) ) { // check if the tip has failed on this host
if ( ! tip . hasFailedOnMachine ( ttStatus . getHost ( ) ) || tip . getNumberOfFailedMachines ( ) >= numUniqueHosts ) { // check if the tip has failed on all the nodes
iter . remove ( ) ; return tip ; } else if ( removeFailedTip ) { // the case where we want to remove a failed tip from the host cache
// point # 3 in the TIP removal logic above
iter . remove ( ) ; } } else { // see point # 3 in the comment above for TIP removal logic
iter . remove ( ) ; } } return null ; |
public class DescribeServicesResult { /** * A JSON - formatted list of AWS services .
* @ param services
* A JSON - formatted list of AWS services . */
public void setServices ( java . util . Collection < Service > services ) { } } | if ( services == null ) { this . services = null ; return ; } this . services = new com . amazonaws . internal . SdkInternalList < Service > ( services ) ; |
public class VirtualRouterSpecMarshaller { /** * Marshall the given parameter object . */
public void marshall ( VirtualRouterSpec virtualRouterSpec , ProtocolMarshaller protocolMarshaller ) { } } | if ( virtualRouterSpec == null ) { throw new SdkClientException ( "Invalid argument passed to marshall(...)" ) ; } try { protocolMarshaller . marshall ( virtualRouterSpec . getListeners ( ) , LISTENERS_BINDING ) ; } catch ( Exception e ) { throw new SdkClientException ( "Unable to marshall request to JSON: " + e . getMessage ( ) , e ) ; } |
public class SearchIO { /** * This method is declared private because it is the default action of constructor
* when file exists
* @ throws java . io . IOException for file access related issues
* @ throws java . text . ParseException for file format related issues */
private void readResults ( ) throws IOException , ParseException { } } | factory . setFile ( file ) ; results = factory . createObjects ( evalueThreshold ) ; |
public class SnsAPI { /** * code 换取 session _ key ( 微信小程序 )
* @ since 2.8.3
* @ param appid appid
* @ param secret secret
* @ param js _ code js _ code
* @ return result */
public static Jscode2sessionResult jscode2session ( String appid , String secret , String js_code ) { } } | HttpUriRequest httpUriRequest = RequestBuilder . get ( ) . setUri ( BASE_URI + "/sns/jscode2session" ) . addParameter ( "appid" , appid ) . addParameter ( "secret" , secret ) . addParameter ( "js_code" , js_code ) . addParameter ( "grant_type" , "authorization_code" ) . build ( ) ; return LocalHttpClient . executeJsonResult ( httpUriRequest , Jscode2sessionResult . class ) ; |
public class CmsStaticResourceHandler { /** * Returns the URL to a static resource . < p >
* @ param resourcePath the static resource path
* @ return the resource URL */
public static URL getStaticResourceURL ( String resourcePath ) { } } | URL resourceURL = null ; if ( isStaticResourceUri ( resourcePath ) ) { String path = removeStaticResourcePrefix ( resourcePath ) ; path = CmsStringUtil . joinPaths ( OPENCMS_PATH_PREFIX , path ) ; resourceURL = OpenCms . getSystemInfo ( ) . getClass ( ) . getClassLoader ( ) . getResource ( path ) ; } return resourceURL ; |
public class TextImporter { /** * Opens a file for reading , handling gzipped files .
* @ param path The file to open .
* @ return A buffered reader to read the file , decompressing it if needed .
* @ throws IOException when shit happens . */
private static BufferedReader open ( final String path ) throws IOException { } } | if ( path . equals ( "-" ) ) { return new BufferedReader ( new InputStreamReader ( System . in ) ) ; } InputStream is = new FileInputStream ( path ) ; if ( path . endsWith ( ".gz" ) ) { is = new GZIPInputStream ( is ) ; } // I < 3 Java ' s IO library .
return new BufferedReader ( new InputStreamReader ( is ) ) ; |
public class HashFunctions { /** * Fowler - Noll - Vo 32 bit hash ( FNV - 1a ) for integer key . This is big - endian version ( native endianess of JVM ) . < br / >
* < p / > < h3 > Algorithm < / h3 > < p / >
* < pre >
* hash = offset _ basis
* for each octet _ of _ data to be hashed
* hash = hash xor octet _ of _ data
* hash = hash * FNV _ prime
* return hash < / pre >
* < h3 > Links < / h3 > < a href = " http : / / www . isthe . com / chongo / tech / comp / fnv / " > http : / / www . isthe . com / chongo / tech / comp / fnv / < / a > < br / >
* < a href = " http : / / en . wikipedia . org / wiki / Fowler % E2%80%93Noll % E2%80%93Vo _ hash _ function " > http : / / en . wikipedia . org / wiki / Fowler % E2%80%93Noll % E2%80%93Vo _ hash _ function < / a > < br / >
* @ param c integer key to be hashed
* @ return hash 32 bit hash */
public static int FVN32hash ( int c ) { } } | long hash = FNV_BASIS ; hash ^= c >>> 24 ; hash *= FNV_PRIME_32 ; hash ^= 0xFF & ( c >>> 16 ) ; hash *= FNV_PRIME_32 ; hash ^= 0xFF & ( c >>> 8 ) ; hash *= FNV_PRIME_32 ; hash ^= 0xFF & c ; hash *= FNV_PRIME_32 ; return ( int ) hash ; |
public class ArmeriaCentralDogma { /** * Encodes the specified { @ link JsonNode } into a byte array . */
private static byte [ ] toBytes ( JsonNode content ) { } } | try { return Jackson . writeValueAsBytes ( content ) ; } catch ( JsonProcessingException e ) { // Should never reach here .
throw new Error ( e ) ; } |
public class UpdateDeploymentGroupResult { /** * If the output contains no data , and the corresponding deployment group contained at least one Auto Scaling group ,
* AWS CodeDeploy successfully removed all corresponding Auto Scaling lifecycle event hooks from the AWS account . If
* the output contains data , AWS CodeDeploy could not remove some Auto Scaling lifecycle event hooks from the AWS
* account .
* @ param hooksNotCleanedUp
* If the output contains no data , and the corresponding deployment group contained at least one Auto Scaling
* group , AWS CodeDeploy successfully removed all corresponding Auto Scaling lifecycle event hooks from the
* AWS account . If the output contains data , AWS CodeDeploy could not remove some Auto Scaling lifecycle
* event hooks from the AWS account . */
public void setHooksNotCleanedUp ( java . util . Collection < AutoScalingGroup > hooksNotCleanedUp ) { } } | if ( hooksNotCleanedUp == null ) { this . hooksNotCleanedUp = null ; return ; } this . hooksNotCleanedUp = new com . amazonaws . internal . SdkInternalList < AutoScalingGroup > ( hooksNotCleanedUp ) ; |
public class OverviewPlot { /** * Refresh the overview plot . */
private synchronized void reinitialize ( ) { } } | if ( plot == null ) { initializePlot ( ) ; } else { final ActionEvent ev = new ActionEvent ( this , ActionEvent . ACTION_PERFORMED , OVERVIEW_REFRESHING ) ; for ( ActionListener actionListener : actionListeners ) { actionListener . actionPerformed ( ev ) ; } } // Detach existing elements :
for ( Pair < Element , Visualization > pair : vistoelem . values ( ) ) { SVGUtil . removeFromParent ( pair . first ) ; } plotmap = arrangeVisualizations ( ratio , 1.0 ) ; recalcViewbox ( ) ; final int thumbsize = ( int ) Math . max ( screenwidth / plotmap . getWidth ( ) , screenheight / plotmap . getHeight ( ) ) ; // TODO : cancel pending thumbnail requests !
// Replace the layer map
LayerMap oldlayers = vistoelem ; vistoelem = new LayerMap ( ) ; // Redo main layers
SVGUtil . removeFromParent ( plotlayer ) ; SVGUtil . removeFromParent ( hoverlayer ) ; plotlayer = plot . svgElement ( SVGConstants . SVG_G_TAG ) ; hoverlayer = plot . svgElement ( SVGConstants . SVG_G_TAG ) ; hoverlayer . setAttribute ( SVGPlot . NO_EXPORT_ATTRIBUTE , SVGPlot . NO_EXPORT_ATTRIBUTE ) ; // Redo the layout
for ( Entry < PlotItem , double [ ] > e : plotmap . entrySet ( ) ) { final double basex = e . getValue ( ) [ 0 ] ; final double basey = e . getValue ( ) [ 1 ] ; for ( Iterator < PlotItem > iter = e . getKey ( ) . itemIterator ( ) ; iter . hasNext ( ) ; ) { PlotItem it = iter . next ( ) ; boolean hasDetails = false ; // Container element for main plot item
Element g = plot . svgElement ( SVGConstants . SVG_G_TAG ) ; SVGUtil . setAtt ( g , SVGConstants . SVG_TRANSFORM_ATTRIBUTE , "translate(" + ( basex + it . x ) + " " + ( basey + it . y ) + ")" ) ; plotlayer . appendChild ( g ) ; vistoelem . put ( it , null , g , null ) ; // Add the actual tasks :
for ( VisualizationTask task : it . tasks ) { if ( ! visibleInOverview ( task ) ) { continue ; } hasDetails |= ! task . has ( RenderFlag . NO_DETAIL ) ; Pair < Element , Visualization > pair = oldlayers . remove ( it , task ) ; if ( pair == null ) { pair = new Pair < > ( plot . svgElement ( SVGConstants . SVG_G_TAG ) , null ) ; } if ( pair . second == null ) { pair . second = embedOrThumbnail ( thumbsize , it , task , pair . first ) ; } g . appendChild ( pair . first ) ; vistoelem . put ( it , task , pair ) ; } // When needed , add a hover effect
if ( hasDetails && ! single ) { Element hover = plot . svgRect ( basex + it . x , basey + it . y , it . w , it . h ) ; SVGUtil . addCSSClass ( hover , selcss . getName ( ) ) ; // link hoverer .
EventTarget targ = ( EventTarget ) hover ; targ . addEventListener ( SVGConstants . SVG_MOUSEOVER_EVENT_TYPE , hoverer , false ) ; targ . addEventListener ( SVGConstants . SVG_MOUSEOUT_EVENT_TYPE , hoverer , false ) ; targ . addEventListener ( SVGConstants . SVG_CLICK_EVENT_TYPE , hoverer , false ) ; targ . addEventListener ( SVGConstants . SVG_CLICK_EVENT_TYPE , ( evt ) -> triggerSubplotSelectEvent ( it ) , false ) ; hoverlayer . appendChild ( hover ) ; } } } for ( Pair < Element , Visualization > pair : oldlayers . values ( ) ) { if ( pair . second != null ) { pair . second . destroy ( ) ; } } plot . getRoot ( ) . appendChild ( plotlayer ) ; plot . getRoot ( ) . appendChild ( hoverlayer ) ; plot . updateStyleElement ( ) ; // Notify listeners .
final ActionEvent ev = new ActionEvent ( this , ActionEvent . ACTION_PERFORMED , OVERVIEW_REFRESHED ) ; for ( ActionListener actionListener : actionListeners ) { actionListener . actionPerformed ( ev ) ; } |
public class Highlights { /** * Return the first highlight that match in any value of this instance with
* some of the highlights values .
* @ param entity The entity
* @ param instance The instance
* @ return The Highlinght */
public Highlight getHighlight ( Entity entity , Object instance ) { } } | for ( Highlight highlight : highlights ) { if ( highlight . getScope ( ) . equals ( INSTANCE ) ) { for ( Field field : entity . getOrderedFields ( ) ) { if ( match ( instance , field , highlight ) ) { return highlight ; } } } } return null ; |
public class DiskClient { /** * Sets the access control policy on the specified resource . Replaces any existing policy .
* < p > Sample code :
* < pre > < code >
* try ( DiskClient diskClient = DiskClient . create ( ) ) {
* ProjectZoneDiskResourceName resource = ProjectZoneDiskResourceName . of ( " [ PROJECT ] " , " [ ZONE ] " , " [ RESOURCE ] " ) ;
* ZoneSetPolicyRequest zoneSetPolicyRequestResource = ZoneSetPolicyRequest . newBuilder ( ) . build ( ) ;
* Policy response = diskClient . setIamPolicyDisk ( resource . toString ( ) , zoneSetPolicyRequestResource ) ;
* < / code > < / pre >
* @ param resource Name or id of the resource for this request .
* @ param zoneSetPolicyRequestResource
* @ throws com . google . api . gax . rpc . ApiException if the remote call fails */
@ BetaApi public final Policy setIamPolicyDisk ( String resource , ZoneSetPolicyRequest zoneSetPolicyRequestResource ) { } } | SetIamPolicyDiskHttpRequest request = SetIamPolicyDiskHttpRequest . newBuilder ( ) . setResource ( resource ) . setZoneSetPolicyRequestResource ( zoneSetPolicyRequestResource ) . build ( ) ; return setIamPolicyDisk ( request ) ; |
public class TagValue { /** * Gets the name of the tag .
* @ return the name */
public String getName ( ) { } } | String name = "" + id ; if ( TiffTags . hasTag ( id ) ) name = TiffTags . getTag ( id ) . getName ( ) ; return name ; |
public class EntityManagerProvider { /** * Allows to pass in overriding Properties that may be specific to the JPA Vendor .
* @ param unitName unit name
* @ param overridingPersistenceProps properties to override persistence . xml props or define additions to them
* @ return EntityManagerProvider instance */
public static synchronized EntityManagerProvider instance ( String unitName , Map < String , String > overridingPersistenceProps ) { } } | overridingProperties = overridingPersistenceProps ; return instance ( unitName ) ; |
public class ClassUtil { /** * Call registerXMLBindingClassForPropGetSetMethod first to retrieve the property
* getter / setter method for the class / bean generated / wrote by JAXB
* specificatio
* @ param cls
* @ return */
public static Map < String , Method > getPropGetMethodList ( final Class < ? > cls ) { } } | Map < String , Method > getterMethodList = entityDeclaredPropGetMethodPool . get ( cls ) ; if ( getterMethodList == null ) { loadPropGetSetMethodList ( cls ) ; getterMethodList = entityDeclaredPropGetMethodPool . get ( cls ) ; } return getterMethodList ; |
public class WebJarsLocatorPathResolver { /** * List assets within a folder .
* @ param folder
* the root path to the folder .
* @ return a set of folder paths that match . */
public Set < String > getResourceNames ( String folder ) { } } | String path = super . getResourcePath ( folder ) ; Set < String > assets = locator . listAssets ( path ) ; Set < String > resourceNames = new HashSet < > ( ) ; for ( String asset : assets ) { int idx = asset . indexOf ( path ) ; if ( idx != - 1 ) { String name = asset . substring ( idx + path . length ( ) ) ; idx = name . indexOf ( JawrConstant . URL_SEPARATOR ) ; if ( idx != - 1 ) { name = name . substring ( 0 , idx + 1 ) ; } resourceNames . add ( name ) ; } } return resourceNames ; |
public class Ifc2x3tc1PackageImpl { /** * < ! - - begin - user - doc - - >
* < ! - - end - user - doc - - >
* @ generated */
public EClass getIfcBoundaryEdgeCondition ( ) { } } | if ( ifcBoundaryEdgeConditionEClass == null ) { ifcBoundaryEdgeConditionEClass = ( EClass ) EPackage . Registry . INSTANCE . getEPackage ( Ifc2x3tc1Package . eNS_URI ) . getEClassifiers ( ) . get ( 46 ) ; } return ifcBoundaryEdgeConditionEClass ; |
public class MethodFinder { /** * Basis of { @ link # findConstructor } and { @ link # findMethod } . The member list fed to this
* method will be either all { @ link Constructor } objects or all { @ link Method } objects . */
protected Member findMemberIn ( List < Member > memberList , Class < ? > [ ] parameterTypes ) throws NoSuchMethodException { } } | List < Member > matchingMembers = new ArrayList < Member > ( ) ; for ( Iterator < Member > it = memberList . iterator ( ) ; it . hasNext ( ) ; ) { Member member = it . next ( ) ; Class < ? > [ ] methodParamTypes = _paramMap . get ( member ) ; // check for exactly equal method signature
if ( Arrays . equals ( methodParamTypes , parameterTypes ) ) { return member ; } if ( ClassUtil . compatibleClasses ( methodParamTypes , parameterTypes ) ) { matchingMembers . add ( member ) ; } } if ( matchingMembers . isEmpty ( ) ) { throw new NoSuchMethodException ( "No member in " + _clazz . getName ( ) + " matching given args" ) ; } if ( matchingMembers . size ( ) == 1 ) { return matchingMembers . get ( 0 ) ; } return findMostSpecificMemberIn ( matchingMembers ) ; |
public class GVRBoundsPicker { /** * Get a collidabled based on its index ( as returned
* by # addCollidable ) .
* @ param index index of collidable to get
* @ returns { @ link GVRSceneObject } or null if not found */
public GVRSceneObject getCollidable ( int index ) { } } | synchronized ( mCollidables ) { if ( ( index < 0 ) || ( index >= mCollidables . size ( ) ) ) { return null ; } return mCollidables . get ( index ) ; } |
public class AppiumElementLocator { /** * This methods makes sets some settings of the { @ link By } according to
* the given instance of { @ link SearchContext } . If there is some { @ link ContentMappedBy }
* then it is switched to the searching for some html or native mobile element .
* Otherwise nothing happens there .
* @ param currentBy is some locator strategy
* @ param currentContent is an instance of some subclass of the { @ link SearchContext } .
* @ return the corrected { @ link By } for the further searching */
private static By getBy ( By currentBy , SearchContext currentContent ) { } } | if ( ! ContentMappedBy . class . isAssignableFrom ( currentBy . getClass ( ) ) ) { return currentBy ; } return ContentMappedBy . class . cast ( currentBy ) . useContent ( getCurrentContentType ( currentContent ) ) ; |
public class ProcessableDetectorStream { /** * @ see DetectorStreamProcessor # process ( net . sf . mmm . util . io . api . spi . DetectorStreamBuffer , Map , boolean )
* @ param buffer is the next part of the streamed data .
* @ param eos - { @ code true } if the end of the stream has been reached and the given { @ code buffer } has to be
* @ throws IOException in case of an Input / Output error . Should only be used internally . */
public void processInternal ( ByteArray buffer , boolean eos ) throws IOException { } } | if ( buffer != null ) { this . firstBuffer . append ( buffer ) ; } this . firstBuffer . process ( getMutableMetadata ( ) , eos ) ; if ( eos ) { setDone ( ) ; } |
public class ConstantsSummaryWriterImpl { /** * Get the class name in the table caption and the table header .
* @ param classStr the class name to print .
* @ return the table caption and header */
protected Content getClassName ( Content classStr ) { } } | Content table = HtmlTree . TABLE ( HtmlStyle . constantsSummary , 0 , 3 , 0 , constantsTableSummary , getTableCaption ( classStr ) ) ; table . addContent ( getSummaryTableHeader ( constantsTableHeader , "col" ) ) ; return table ; |
public class WriteRender { /** * ( non - Javadoc )
* @ see com . alibaba . simpleimage . ImageRender # render ( ) */
@ Override public ImageWrapper render ( ) throws SimpleImageException { } } | try { if ( image == null ) { image = imageRender . render ( ) ; } ImageWriteHelper . write ( image , stream , outputFormat , param ) ; } catch ( Exception e ) { throw new SimpleImageException ( e ) ; } return null ; |
public class I18nUtils { /** * Given a string representing a Locale , returns the Locale object for that string .
* @ return A Locale object built from the string provided */
public static Locale parseLocale ( String localeString ) { } } | if ( localeString == null ) { return Locale . US ; } String [ ] groups = localeString . split ( "[-_]" ) ; switch ( groups . length ) { case 1 : return new Locale ( groups [ 0 ] ) ; case 2 : return new Locale ( groups [ 0 ] , Ascii . toUpperCase ( groups [ 1 ] ) ) ; case 3 : return new Locale ( groups [ 0 ] , Ascii . toUpperCase ( groups [ 1 ] ) , groups [ 2 ] ) ; default : throw new IllegalArgumentException ( "Malformed localeString: " + localeString ) ; } |
public class Petite { /** * Get component or bean by type .
* @ param < T >
* @ param type
* @ return Component */
@ SuppressWarnings ( "unchecked" ) public < T > T get ( final Class < T > type ) { } } | T bean = ( T ) components . get ( type ) ; if ( bean != null ) { return bean ; } return ( T ) get ( type . getName ( ) ) ; |
public class XmlWriter { /** * Convenience method , same as doing a startLineElement ( ) , writeText ( text ) ,
* endLineElement ( ) . */
public void writeLineElement ( String name , Object text ) { } } | startLineElement ( name ) ; writeText ( text ) ; endLineElement ( name ) ; |
public class CassandraTableScanJavaRDD { /** * Selects a subset of columns mapped to the key of a JavaPairRDD .
* The selected columns must be available in the CassandraRDD .
* If no selected columns are given , all available columns are selected .
* @ param rrf row reader factory to convert the key to desired type K
* @ param rwf row writer factory for creating a partitioner for key type K
* @ param keyClassTag class tag of K , required to construct the result JavaPairRDD
* @ param columns list of columns passed to the rrf to create the row reader ,
* useful when the key is mapped to a tuple or a single value */
public < K > CassandraJavaPairRDD < K , R > keyBy ( ClassTag < K > keyClassTag , RowReaderFactory < K > rrf , RowWriterFactory < K > rwf , ColumnRef ... columns ) { } } | Seq < ColumnRef > columnRefs = JavaApiHelper . toScalaSeq ( columns ) ; CassandraRDD < Tuple2 < K , R > > resultRDD = columns . length == 0 ? rdd ( ) . keyBy ( keyClassTag , rrf , rwf ) : rdd ( ) . keyBy ( columnRefs , keyClassTag , rrf , rwf ) ; return new CassandraJavaPairRDD < > ( resultRDD , keyClassTag , classTag ( ) ) ; |
public class GeopaparazziUtilities { /** * Get the map of metadata of the project .
* @ param connection the db connection .
* @ return the map of metadata .
* @ throws SQLException */
public static LinkedHashMap < String , String > getProjectMetadata ( IHMConnection connection ) throws Exception { } } | LinkedHashMap < String , String > metadataMap = new LinkedHashMap < > ( ) ; try ( IHMStatement statement = connection . createStatement ( ) ) { statement . setQueryTimeout ( 30 ) ; // set timeout to 30 sec .
String sql = "select " + MetadataTableFields . COLUMN_KEY . getFieldName ( ) + ", " + MetadataTableFields . COLUMN_VALUE . getFieldName ( ) + " from " + TABLE_METADATA ; IHMResultSet rs = statement . executeQuery ( sql ) ; while ( rs . next ( ) ) { String key = rs . getString ( MetadataTableFields . COLUMN_KEY . getFieldName ( ) ) ; String value = rs . getString ( MetadataTableFields . COLUMN_VALUE . getFieldName ( ) ) ; if ( ! key . endsWith ( "ts" ) ) { metadataMap . put ( key , value ) ; } else { try { long ts = Long . parseLong ( value ) ; String dateTimeString = ETimeUtilities . INSTANCE . TIME_FORMATTER_LOCAL . format ( new Date ( ts ) ) ; metadataMap . put ( key , dateTimeString ) ; } catch ( Exception e ) { metadataMap . put ( key , value ) ; } } } } return metadataMap ; |
public class NetworkInterface { /** * Get a List of all or a subset of the < code > InterfaceAddresses < / code >
* of this network interface .
* If there is a security manager , its < code > checkConnect < / code >
* method is called with the InetAddress for each InterfaceAddress .
* Only InterfaceAddresses where the < code > checkConnect < / code > doesn ' t throw
* a SecurityException will be returned in the List .
* @ return a < code > List < / code > object with all or a subset of the
* InterfaceAddresss of this network interface
* @ since 1.6 */
public java . util . List < InterfaceAddress > getInterfaceAddresses ( ) { } } | java . util . List < InterfaceAddress > lst = new java . util . ArrayList < InterfaceAddress > ( 1 ) ; SecurityManager sec = System . getSecurityManager ( ) ; for ( int j = 0 ; j < bindings . length ; j ++ ) { try { if ( sec != null ) { sec . checkConnect ( bindings [ j ] . getAddress ( ) . getHostAddress ( ) , - 1 ) ; } lst . add ( bindings [ j ] ) ; } catch ( SecurityException e ) { } } return lst ; |
public class AssertContains { /** * Asserts that the element ' s options contains the provided expected
* option . If the element isn ' t present or a select , this will constitute a
* failure , same as a mismatch . This information will be logged and
* recorded , with a screenshot for traceability and added debugging support .
* @ param expectedOption the option expected in the list */
public void selectOption ( String expectedOption ) { } } | String [ ] options = checkSelectOption ( expectedOption , 0 , 0 ) ; String reason = NO_ELEMENT_FOUND ; if ( options == null && getElement ( ) . is ( ) . present ( ) ) { reason = ELEMENT_NOT_SELECT ; } assertNotNull ( reason , options ) ; assertTrue ( "Option not found: element options of '" + String . join ( "," , options ) + DOES_NOT_CONTAIN + expectedOption + "'" , Arrays . asList ( options ) . contains ( expectedOption ) ) ; |
public class BaseCrashReportDialog { /** * Send crash report given user ' s comment and email address .
* @ param comment Comment ( may be null ) provided by the user .
* @ param userEmail Email address ( may be null ) provided by the client . */
protected final void sendCrash ( @ Nullable String comment , @ Nullable String userEmail ) { } } | new Thread ( ( ) -> { final CrashReportPersister persister = new CrashReportPersister ( ) ; try { if ( ACRA . DEV_LOGGING ) ACRA . log . d ( LOG_TAG , "Add user comment to " + reportFile ) ; final CrashReportData crashData = persister . load ( reportFile ) ; crashData . put ( USER_COMMENT , comment == null ? "" : comment ) ; crashData . put ( USER_EMAIL , userEmail == null ? "" : userEmail ) ; persister . store ( crashData , reportFile ) ; } catch ( IOException | JSONException e ) { ACRA . log . w ( LOG_TAG , "User comment not added: " , e ) ; } // Start the report sending task
new SchedulerStarter ( this , config ) . scheduleReports ( reportFile , false ) ; } ) . start ( ) ; |
public class ViewDragHelper { /** * Attempt to capture the view with the given pointer ID . The callback will be involved .
* This will put us into the " dragging " state . If we ' ve already captured this view with
* this pointer this method will immediately return true without consulting the callback .
* @ param toCapture View to capture
* @ param pointerId Pointer to capture with
* @ return true if capture was successful */
boolean tryCaptureViewForDrag ( View toCapture , int pointerId ) { } } | if ( toCapture == mCapturedView && mActivePointerId == pointerId ) { // Already done !
return true ; } if ( toCapture != null && mCallback . tryCaptureView ( toCapture , pointerId ) ) { mActivePointerId = pointerId ; captureChildView ( toCapture , pointerId ) ; return true ; } return false ; |
public class DefaultWarpRequestSpecifier { /** * ( non - Javadoc )
* @ see org . jboss . arquillian . warp . client . execution . FilterSpecifier # filter ( java . lang . Class ) */
@ Override public SingleInspectionSpecifier observe ( Class < ? extends RequestObserver > what ) { } } | initializeSingleGroup ( ) ; singleGroup . observe ( createFilterInstance ( what ) ) ; return this ; |
public class DescribeUserPoolRequestMarshaller { /** * Marshall the given parameter object . */
public void marshall ( DescribeUserPoolRequest describeUserPoolRequest , ProtocolMarshaller protocolMarshaller ) { } } | if ( describeUserPoolRequest == null ) { throw new SdkClientException ( "Invalid argument passed to marshall(...)" ) ; } try { protocolMarshaller . marshall ( describeUserPoolRequest . getUserPoolId ( ) , USERPOOLID_BINDING ) ; } catch ( Exception e ) { throw new SdkClientException ( "Unable to marshall request to JSON: " + e . getMessage ( ) , e ) ; } |
public class OutputUtil { /** * Appends all elements of < code > list < / code > to buffer , separated by delimiter
* @ param < T > Type of elements stored in < code > list < / code >
* @ param sb StringBuilder to be modified
* @ param list List of elements
* @ param delimiter Delimiter to separate elements
* @ return Modified < code > sb < / code > to allow chaining */
public static < T > StringBuilder appendList ( StringBuilder sb , List < T > list , String delimiter ) { } } | boolean firstRun = true ; for ( T elem : list ) { if ( ! firstRun ) sb . append ( delimiter ) ; else firstRun = false ; sb . append ( elem . toString ( ) ) ; } return sb ; |
public class IniFile { /** * Returns the specified date property from the specified section .
* @ param pstrSection the INI section name .
* @ param pstrProp the property to be retrieved .
* @ return the date property value . */
public Date getTimestampProperty ( String pstrSection , String pstrProp ) { } } | Timestamp tsRet = null ; Date dtTmp = null ; String strVal = null ; DateFormat dtFmt = null ; INIProperty objProp = null ; INISection objSec = null ; objSec = ( INISection ) this . mhmapSections . get ( pstrSection ) ; if ( objSec != null ) { objProp = objSec . getProperty ( pstrProp ) ; try { if ( objProp != null ) strVal = objProp . getPropValue ( ) ; if ( strVal != null ) { dtFmt = new SimpleDateFormat ( this . mstrDateFmt ) ; dtTmp = dtFmt . parse ( strVal ) ; tsRet = new Timestamp ( dtTmp . getTime ( ) ) ; } } catch ( ParseException PExIgnore ) { } catch ( IllegalArgumentException IAEx ) { } finally { if ( objProp != null ) objProp = null ; } objSec = null ; } return tsRet ; |
public class ConfigElement { /** * Uses the server configuration to resolve a variable into a string .
* For example , with this in server config : { @ code < variable name = " key " value = " val " / > }
* Calling < code > expandVariable ( config , " $ { key } " ) ; < / code > would return " val "
* @ param config The server configuration
* @ param value The raw value of a variable with brackets
* @ return The value of the expanded string . */
public static String expand ( ServerConfiguration config , String value ) { } } | if ( value == null ) return null ; if ( ! value . startsWith ( "${" ) || ! value . endsWith ( "}" ) ) return value ; String variableName = value . substring ( 2 , value . length ( ) - 1 ) ; Variable var = config . getVariables ( ) . getBy ( "name" , variableName ) ; return var . getValue ( ) ; |
public class ConnectionManager { /** * Lazy Connection Association Optimization ( smart handles ) */
@ Override public void associateConnection ( Object connection , ManagedConnectionFactory mcf , ConnectionRequestInfo cri ) throws ResourceException { } } | final boolean isTraceOn = TraceComponent . isAnyTracingEnabled ( ) ; if ( isTraceOn && tc . isEntryEnabled ( ) ) { Tr . entry ( this , tc , "associateConnection" ) ; } /* * Get the subject information */
Subject subject = ( containerManagedAuth ? getFinalSubject ( cri , mcf , this ) : null ) ; // Give the security helper a chance to finalize what subject
// should be used . When ThreadIdentitySupport = NOTALLOWED the
// original subject will be unchanged .
// subject = securityHelper . finalizeSubject ( subject , cri , inuseCM . cmConfig ) ;
/* * Call associate connection */
associateConnection ( mcf , subject , cri , connection ) ; if ( isTraceOn && tc . isEntryEnabled ( ) ) { Tr . exit ( this , tc , "associateConnection" ) ; } |
public class Javadoc { /** * For tags like " @ return good things " where
* tagName is " return " ,
* and the rest is content . */
public Javadoc addBlockTag ( String tagName , String content ) { } } | return addBlockTag ( new JavadocBlockTag ( tagName , content ) ) ; |
public class WMultiTextField { /** * The string is a comma seperated list of the string inputs .
* @ return A string concatenation of the string inputs . */
@ Override public String getValueAsString ( ) { } } | String result = null ; String [ ] inputs = getValue ( ) ; if ( inputs != null && inputs . length > 0 ) { StringBuffer stringValues = new StringBuffer ( ) ; for ( int i = 0 ; i < inputs . length ; i ++ ) { if ( i > 0 ) { stringValues . append ( ", " ) ; } stringValues . append ( inputs [ i ] ) ; } result = stringValues . toString ( ) ; } return result ; |
public class DefaultGroovyMethods { /** * Round the value
* @ param number a Double
* @ param precision the number of decimal places to keep
* @ return the Double rounded to the number of decimal places specified by precision
* @ since 1.6.4 */
public static double round ( Double number , int precision ) { } } | return Math . floor ( number * Math . pow ( 10 , precision ) + 0.5 ) / Math . pow ( 10 , precision ) ; |
public class IdGenerator { /** * Generate Id when given table generation strategy .
* @ param m
* @ param client
* @ param keyValue
* @ param e */
private Object onTableGenerator ( EntityMetadata m , Client < ? > client , IdDiscriptor keyValue , Object e ) { } } | Object tablegenerator = getAutoGenClazz ( client ) ; if ( tablegenerator instanceof TableGenerator ) { Object generatedId = ( ( TableGenerator ) tablegenerator ) . generate ( keyValue . getTableDiscriptor ( ) , ( ClientBase ) client , m . getIdAttribute ( ) . getJavaType ( ) . getSimpleName ( ) ) ; try { generatedId = PropertyAccessorHelper . fromSourceToTargetClass ( m . getIdAttribute ( ) . getJavaType ( ) , generatedId . getClass ( ) , generatedId ) ; PropertyAccessorHelper . setId ( e , m , generatedId ) ; return generatedId ; } catch ( IllegalArgumentException iae ) { log . error ( "Unknown integral data type for ids : " + m . getIdAttribute ( ) . getJavaType ( ) ) ; throw new KunderaException ( "Unknown integral data type for ids : " + m . getIdAttribute ( ) . getJavaType ( ) , iae ) ; } } throw new IllegalArgumentException ( GenerationType . class . getSimpleName ( ) + "." + GenerationType . TABLE + " Strategy not supported by this client :" + client . getClass ( ) . getName ( ) ) ; |
public class ProtoUtil { /** * Returns java package name . */
public static String getPackage ( Proto proto ) { } } | DynamicMessage . Value javaPackage = proto . getOptions ( ) . get ( OPTION_JAVA_PACKAGE ) ; if ( javaPackage != null ) { return javaPackage . getString ( ) ; } return proto . getPackage ( ) . getValue ( ) ; |
public class EventHubSpout { /** * This is a extracted method that is easy to test
* @ param config
* @ param totalTasks
* @ param taskIndex
* @ param collector
* @ throws Exception */
public void preparePartitions ( Map config , int totalTasks , int taskIndex , SpoutOutputCollector collector ) throws Exception { } } | this . collector = collector ; if ( stateStore == null ) { String zkEndpointAddress = eventHubConfig . getZkConnectionString ( ) ; if ( zkEndpointAddress == null || zkEndpointAddress . length ( ) == 0 ) { // use storm ' s zookeeper servers if not specified .
@ SuppressWarnings ( "unchecked" ) List < String > zkServers = ( List < String > ) config . get ( Config . STORM_ZOOKEEPER_SERVERS ) ; Integer zkPort = ( ( Number ) config . get ( Config . STORM_ZOOKEEPER_PORT ) ) . intValue ( ) ; StringBuilder sb = new StringBuilder ( ) ; for ( String zk : zkServers ) { if ( sb . length ( ) > 0 ) { sb . append ( ',' ) ; } sb . append ( zk + ":" + zkPort ) ; } zkEndpointAddress = sb . toString ( ) ; } stateStore = new ZookeeperStateStore ( zkEndpointAddress , ( Integer ) config . get ( Config . STORM_ZOOKEEPER_RETRY_TIMES ) , ( Integer ) config . get ( Config . STORM_ZOOKEEPER_RETRY_INTERVAL ) ) ; } stateStore . open ( ) ; partitionCoordinator = new StaticPartitionCoordinator ( eventHubConfig , taskIndex , totalTasks , stateStore , pmFactory , recvFactory ) ; for ( IPartitionManager partitionManager : partitionCoordinator . getMyPartitionManagers ( ) ) { partitionManager . open ( ) ; } |
public class Database { /** * Create a placeholder for SQL query syntax e . g . " ( ? , ? , ? ) " .
* @ param length Number of values that will be inserted to the placeholder .
* @ return A placeholder for SQL query syntax . */
private String queryPlaceholder ( int length ) { } } | StringBuilder sb = new StringBuilder ( length * 2 + 1 ) ; sb . append ( "(?" ) ; for ( int i = 1 ; i < length ; i ++ ) { sb . append ( ",?" ) ; } sb . append ( ")" ) ; return sb . toString ( ) ; |
public class ObjectIdentifierAndLinkNameTupleMarshaller { /** * Marshall the given parameter object . */
public void marshall ( ObjectIdentifierAndLinkNameTuple objectIdentifierAndLinkNameTuple , ProtocolMarshaller protocolMarshaller ) { } } | if ( objectIdentifierAndLinkNameTuple == null ) { throw new SdkClientException ( "Invalid argument passed to marshall(...)" ) ; } try { protocolMarshaller . marshall ( objectIdentifierAndLinkNameTuple . getObjectIdentifier ( ) , OBJECTIDENTIFIER_BINDING ) ; protocolMarshaller . marshall ( objectIdentifierAndLinkNameTuple . getLinkName ( ) , LINKNAME_BINDING ) ; } catch ( Exception e ) { throw new SdkClientException ( "Unable to marshall request to JSON: " + e . getMessage ( ) , e ) ; } |
public class AptUtil { /** * Returns the package name of the given element .
* NB : This method requires the given element has the kind of { @ link ElementKind # CLASS } .
* @ param elementUtils
* @ param element
* @ return the package name
* @ author vvakame */
public static String getPackageName ( Elements elementUtils , Element element ) { } } | return elementUtils . getPackageOf ( element ) . getQualifiedName ( ) . toString ( ) ; |
public class DefaultPayload { /** * Static factory method for a text payload . Mainly looks better than " new DefaultPayload ( data ) "
* @ param data the data of the payload .
* @ return a payload . */
public static Payload create ( CharSequence data ) { } } | return create ( StandardCharsets . UTF_8 . encode ( CharBuffer . wrap ( data ) ) , null ) ; |
public class MpMessages { /** * 群发视频消息给所有人
* @ param mediaId
* @ param title
* @ param desc
* @ return */
public long video ( String mediaId , String title , String desc ) { } } | return video ( new Filter ( true , null ) , null , mediaId , title , desc ) ; |
public class BrowserSessionProxy { /** * f169897.2 added */
public void reset ( ) throws SISessionUnavailableException , SISessionDroppedException , SIConnectionUnavailableException , SIConnectionDroppedException , SIResourceException , SIConnectionLostException , SIErrorException { } } | if ( tc . isEntryEnabled ( ) ) SibTr . entry ( this , tc , "reset" ) ; checkAlreadyClosed ( ) ; synchronized ( lock ) { try { closeLock . readLock ( ) . lockInterruptibly ( ) ; try { proxyQueue . reset ( ) ; } finally { closeLock . readLock ( ) . unlock ( ) ; } } catch ( InterruptedException e ) { // No FFDC code needed
if ( tc . isDebugEnabled ( ) ) SibTr . debug ( this , tc , "interrupted exception" ) ; } } if ( tc . isEntryEnabled ( ) ) SibTr . exit ( this , tc , "reset" ) ; |
public class UserManager { /** * Check if the passed combination of user ID and password matches .
* @ param sUserID
* The ID of the user
* @ param sPlainTextPassword
* The plan text password to validate .
* @ return < code > true < / code > if the password hash matches the stored hash for
* the specified user , < code > false < / code > otherwise . */
public boolean areUserIDAndPasswordValid ( @ Nullable final String sUserID , @ Nullable final String sPlainTextPassword ) { } } | // No password is not allowed
if ( sPlainTextPassword == null ) return false ; // Is there such a user ?
final IUser aUser = getOfID ( sUserID ) ; if ( aUser == null ) return false ; // Now compare the hashes
final String sPasswordHashAlgorithm = aUser . getPasswordHash ( ) . getAlgorithmName ( ) ; final IPasswordSalt aSalt = aUser . getPasswordHash ( ) . getSalt ( ) ; final PasswordHash aPasswordHash = GlobalPasswordSettings . createUserPasswordHash ( sPasswordHashAlgorithm , aSalt , sPlainTextPassword ) ; return aUser . getPasswordHash ( ) . equals ( aPasswordHash ) ; |
public class URLCoder { /** * Decodes { @ code x - www - form - urlencoded } string into Java string .
* @ param encoded encoded value
* @ return decoded value
* @ see URLDecoder # decode ( String , String ) */
public static String decode ( String encoded ) { } } | try { return URLDecoder . decode ( encoded , ENCODING_FOR_URL ) ; } catch ( UnsupportedEncodingException e ) { throw new IllegalStateException ( "Unable to decode URL entry via " + ENCODING_FOR_URL + ". This should not happen" , e ) ; } |
public class TldLearning { /** * Mark regions which were local maximums and had high confidence as negative . These regions were
* candidates for the tracker but were not selected */
protected void learnAmbiguousNegative ( Rectangle2D_F64 targetRegion ) { } } | TldHelperFunctions . convertRegion ( targetRegion , targetRegion_I32 ) ; if ( detection . isSuccess ( ) ) { TldRegion best = detection . getBest ( ) ; // see if it found the correct solution
double overlap = helper . computeOverlap ( best . rect , targetRegion_I32 ) ; if ( overlap <= config . overlapLower ) { template . addDescriptor ( false , best . rect ) ; // fern . learnFernNoise ( false , best . rect ) ;
} // mark all ambiguous regions as bad
List < ImageRectangle > ambiguous = detection . getAmbiguousRegions ( ) ; for ( ImageRectangle r : ambiguous ) { overlap = helper . computeOverlap ( r , targetRegion_I32 ) ; if ( overlap <= config . overlapLower ) { fern . learnFernNoise ( false , r ) ; template . addDescriptor ( false , r ) ; } } } |
public class SaveEditingAction { /** * Saves editing , and also removes the { @ link FeatureTransaction } object from the map .
* @ param event
* The { @ link MenuItemClickEvent } from clicking the action . */
public void onClick ( MenuItemClickEvent event ) { } } | FeatureTransaction featureTransaction = mapModel . getFeatureEditor ( ) . getFeatureTransaction ( ) ; if ( featureTransaction != null ) { List < Activity > activities = new ArrayList < Activity > ( ) ; activities . add ( new ValidationActivity ( ) ) ; activities . add ( new CommitActivity ( ) ) ; WorkflowProcessor processor = new SequenceProcessor ( new MapModelWorkflowContext ( ) ) ; processor . setDefaultErrorHandler ( new WorkflowErrorHandler ( ) { public void handleError ( WorkflowContext context , Throwable throwable ) { SC . warn ( I18nProvider . getGlobal ( ) . saveEditingAborted ( ) + throwable . getMessage ( ) ) ; } } ) ; processor . setActivities ( activities ) ; processor . doActivities ( mapModel ) ; // Cleaning up duties : controller and MapWidget ( if they ' re present )
if ( controller != null ) { controller . cleanup ( ) ; } if ( mapWidget != null ) { mapWidget . render ( featureTransaction , RenderGroup . VECTOR , RenderStatus . DELETE ) ; } mapModel . getFeatureEditor ( ) . stopEditing ( ) ; } |
import java . util . ArrayList ; import java . util . Collections ; import java . util . HashSet ; import java . util . List ; class FindCommonElements { /** * This function returns a sorted list of unique common elements between two lists .
* @ param list1 The first list .
* @ param list2 The second list .
* @ return A sorted list of common elements .
* Example :
* > > > find _ common _ elements ( [ 1 , 4 , 3 , 34 , 653 , 2 , 5 ] , [ 5 , 7 , 1 , 5 , 9 , 653 , 121 ] )
* [ 1 , 5 , 653]
* > > > find _ common _ elements ( [ 5 , 3 , 2 , 8 ] , [ 3 , 2 ] )
* [ 2 , 3] */
public static List < Integer > findCommonElements ( List < Integer > list1 , List < Integer > list2 ) { } } | HashSet < Integer > set1 = new HashSet < > ( list1 ) ; set1 . retainAll ( new HashSet < > ( list2 ) ) ; List < Integer > commonElements = new ArrayList < > ( set1 ) ; Collections . sort ( commonElements ) ; return commonElements ; |
public class Prefs { /** * Reloads this preference file from the hard disk */
public void reload ( ) { } } | try { if ( file . exists ( ) ) { try ( FileReader fileReader = new FileReader ( file ) ) { props . load ( fileReader ) ; } } } catch ( IOException e ) { FOKLogger . log ( Prefs . class . getName ( ) , Level . SEVERE , FOKLogger . DEFAULT_ERROR_TEXT , e ) ; } |
public class MapperFactory { /** * Creates a mapper for the given class .
* @ param clazz
* the class
* @ return the mapper for the given class . */
private Mapper createMapper ( Class < ? > clazz ) { } } | Mapper mapper ; if ( Enum . class . isAssignableFrom ( clazz ) ) { mapper = new EnumMapper ( clazz ) ; } else if ( Map . class . isAssignableFrom ( clazz ) ) { mapper = new MapMapper ( clazz ) ; } else if ( clazz . isAnnotationPresent ( Embeddable . class ) ) { mapper = new EmbeddedObjectMapper ( clazz ) ; } else { throw new NoSuitableMapperException ( String . format ( "No mapper found for class %s" , clazz . getName ( ) ) ) ; } return mapper ; |
public class CmsSqlManager { /** * Attempts to close the connection , statement and result set after a statement has been executed . < p >
* @ param dbc the current database context
* @ param con the JDBC connection
* @ param stmnt the statement
* @ param res the result set */
public void closeAll ( CmsDbContext dbc , Connection con , Statement stmnt , ResultSet res ) { } } | // NOTE : we have to close Connections / Statements that way , because a dbcp PoolablePreparedStatement
// is not a DelegatedStatement ; for that reason its not removed from the trace of the connection when it is closed .
// So , the connection tries to close it again when the connection is closed itself ;
// as a result there is an error that forces the connection to be destroyed and not pooled
if ( dbc == null ) { LOG . error ( Messages . get ( ) . getBundle ( ) . key ( Messages . LOG_NULL_DB_CONTEXT_0 ) ) ; } try { // first , close the result set
if ( res != null ) { res . close ( ) ; } } catch ( SQLException e ) { LOG . debug ( e . getLocalizedMessage ( ) , e ) ; } finally { res = null ; } try { // close the statement
if ( stmnt != null ) { stmnt . close ( ) ; } } catch ( SQLException e ) { LOG . debug ( e . getLocalizedMessage ( ) , e ) ; } finally { stmnt = null ; } try { // close the connection
if ( ( con != null ) && ! con . isClosed ( ) ) { con . close ( ) ; } } catch ( SQLException e ) { LOG . debug ( e . getLocalizedMessage ( ) , e ) ; } finally { con = null ; } |
public class MessageBatch { /** * Returns the number of non - null messages */
public int size ( ) { } } | int retval = 0 ; for ( int i = 0 ; i < index ; i ++ ) if ( messages [ i ] != null ) retval ++ ; return retval ; |
public class SerializerFactory { /** * Set true if the collection serializer should send the java type . */
public void setSendCollectionType ( boolean isSendType ) { } } | if ( _collectionSerializer == null ) _collectionSerializer = new CollectionSerializer ( ) ; _collectionSerializer . setSendJavaType ( isSendType ) ; if ( _mapSerializer == null ) _mapSerializer = new MapSerializer ( ) ; _mapSerializer . setSendJavaType ( isSendType ) ; |
public class MediaClient { /** * Create a preset which help to convert audio files on be played in a wide range of devices .
* @ param presetName The name of the new preset .
* @ param container The container type for the output file . Valid values include mp4 , flv , hls , mp3 , m4a .
* @ param clip The clip property of the preset .
* @ param audio Specify the audio format of target file .
* @ param encryption Specify the encryption property of target file . */
public CreatePresetResponse createPreset ( String presetName , String container , Clip clip , Audio audio , Encryption encryption ) { } } | return createPreset ( presetName , null , container , false , clip , audio , null , encryption , null ) ; |
public class ApptentiveTaskManager { /** * region PayloadSender . Listener */
@ Override public void onFinishSending ( PayloadSender sender , PayloadData payload , boolean cancelled , String errorMessage , int responseCode , JSONObject responseData ) { } } | ApptentiveNotificationCenter . defaultCenter ( ) . postNotification ( NOTIFICATION_PAYLOAD_DID_FINISH_SEND , NOTIFICATION_KEY_PAYLOAD , payload , NOTIFICATION_KEY_SUCCESSFUL , errorMessage == null && ! cancelled ? TRUE : FALSE , NOTIFICATION_KEY_RESPONSE_CODE , responseCode , NOTIFICATION_KEY_RESPONSE_DATA , responseData ) ; if ( cancelled ) { ApptentiveLog . v ( PAYLOADS , "Payload sending was cancelled: %s" , payload ) ; return ; // don ' t remove cancelled payloads from the queue
} if ( errorMessage != null ) { ApptentiveLog . e ( PAYLOADS , "Payload sending failed: %s\n%s" , payload , errorMessage ) ; if ( appInBackground ) { ApptentiveLog . v ( PAYLOADS , "The app went to the background so we won't remove the payload from the queue" ) ; retrySending ( 5000 ) ; return ; } else if ( responseCode == - 1 ) { ApptentiveLog . v ( PAYLOADS , "Payload failed to send due to a connection error." ) ; retrySending ( 5000 ) ; return ; } else if ( responseCode >= 500 ) { ApptentiveLog . v ( PAYLOADS , "Payload failed to send due to a server error." ) ; retrySending ( 5000 ) ; return ; } } else { ApptentiveLog . v ( PAYLOADS , "Payload was successfully sent: %s" , payload ) ; } // Only let the payload be deleted if it was successfully sent , or got an unrecoverable client error .
deletePayload ( payload . getNonce ( ) ) ; |
public class ReportClean { /** * Remove the report directory . */
@ Override protected void runUnsafe ( ) throws Exception { } } | Path reportDirectory = getReportDirectoryPath ( ) ; Files . walkFileTree ( reportDirectory , new DeleteVisitor ( ) ) ; LOGGER . info ( "Report directory <{}> was successfully cleaned." , reportDirectory ) ; |
public class CaduceusProgram { /** * Read Caduceus program .
* @ param resource the resource
* @ return the lyre program
* @ throws IOException the io exception */
public static CaduceusProgram read ( @ NonNull Resource resource ) throws IOException { } } | CaduceusProgram program = new CaduceusProgram ( ) ; try ( Reader reader = resource . reader ( ) ) { List < Object > rules = ensureList ( new Yaml ( ) . load ( reader ) , "Caduceus rules should be specified in a list" ) ; for ( Object entry : rules ) { Map < String , Object > ruleMap = ensureMap ( entry , "Rule entry should be a map" ) ; String ruleName = Val . of ( ruleMap . get ( "name" ) ) . asString ( ) ; String pattern = Val . of ( ruleMap . get ( "pattern" ) ) . asString ( ) ; if ( StringUtils . isNullOrBlank ( pattern ) ) { throw new IOException ( "No pattern specified: " + entry ) ; } if ( StringUtils . isNullOrBlank ( ruleName ) ) { throw new IOException ( "No rule name specified: " + entry ) ; } List < CaduceusAnnotationProvider > annotationProviders = new LinkedList < > ( ) ; if ( ruleMap . containsKey ( "annotations" ) ) { List < Object > annotationList = ensureList ( ruleMap . get ( "annotations" ) , "Annotations should be specified as a list." ) ; for ( Object o : annotationList ) { annotationProviders . add ( CaduceusAnnotationProvider . fromMap ( ensureMap ( o , "Annotation entries should be specified as a map." ) , resource . descriptor ( ) , ruleName ) ) ; } } List < CaduceusRelationProvider > relationProviders = new LinkedList < > ( ) ; if ( ruleMap . containsKey ( "relations" ) ) { List < Object > relations = ensureList ( ruleMap . get ( "relations" ) , "Relations should be specified as a list." ) ; for ( Object o : relations ) { relationProviders . add ( CaduceusRelationProvider . fromMap ( ensureMap ( o , "Relation entries should be specified as a map." ) ) ) ; } } try { program . rules . add ( new CaduceusRule ( resource . descriptor ( ) , ruleName , TokenRegex . compile ( pattern ) , annotationProviders , relationProviders ) ) ; } catch ( ParseException e ) { throw new IOException ( "Invalid pattern for rule " + ruleName ) ; } } } return program ; |
public class BouncyCastleUtil { /** * Returns certificate type of the given TBS certificate . < BR >
* The certificate type is { @ link GSIConstants # CA GSIConstants . CA }
* < B > only < / B > if the certificate contains a
* BasicConstraints extension and it is marked as CA . < BR >
* A certificate is a GSI - 2 proxy when the subject DN of the certificate
* ends with < I > " CN = proxy " < / I > ( certificate type { @ link
* GSIConstants # GSI _ 2 _ PROXY GSIConstants . GSI _ 2 _ PROXY } ) or
* < I > " CN = limited proxy " < / I > ( certificate type { @ link
* GSIConstants # GSI _ 2 _ LIMITED _ PROXY GSIConstants . LIMITED _ PROXY } ) component
* and the issuer DN of the certificate matches the subject DN without
* the last proxy < I > CN < / I > component . < BR >
* A certificate is a GSI - 3 proxy when the subject DN of the certificate
* ends with a < I > CN < / I > component , the issuer DN of the certificate
* matches the subject DN without the last < I > CN < / I > component and
* the certificate contains { @ link ProxyCertInfo ProxyCertInfo } critical
* extension .
* The certificate type is { @ link GSIConstants # GSI _ 3 _ IMPERSONATION _ PROXY
* GSIConstants . GSI _ 3 _ IMPERSONATION _ PROXY } if the policy language of
* the { @ link ProxyCertInfo ProxyCertInfo } extension is set to
* { @ link ProxyPolicy # IMPERSONATION ProxyPolicy . IMPERSONATION } OID .
* The certificate type is { @ link GSIConstants # GSI _ 3 _ LIMITED _ PROXY
* GSIConstants . GSI _ 3 _ LIMITED _ PROXY } if the policy language of
* the { @ link ProxyCertInfo ProxyCertInfo } extension is set to
* { @ link ProxyPolicy # LIMITED ProxyPolicy . LIMITED } OID .
* The certificate type is { @ link GSIConstants # GSI _ 3 _ INDEPENDENT _ PROXY
* GSIConstants . GSI _ 3 _ INDEPENDENT _ PROXY } if the policy language of
* the { @ link ProxyCertInfo ProxyCertInfo } extension is set to
* { @ link ProxyPolicy # INDEPENDENT ProxyPolicy . INDEPENDENT } OID .
* The certificate type is { @ link GSIConstants # GSI _ 3 _ RESTRICTED _ PROXY
* GSIConstants . GSI _ 3 _ RESTRICTED _ PROXY } if the policy language of
* the { @ link ProxyCertInfo ProxyCertInfo } extension is set to
* any other OID then the above . < BR >
* The certificate type is { @ link GSIConstants # EEC GSIConstants . EEC }
* if the certificate is not a CA certificate or a GSI - 2 or GSI - 3 proxy .
* @ param crt the TBS certificate to get the type of .
* @ return the certificate type . The certificate type is determined
* by rules described above .
* @ exception IOException if something goes wrong .
* @ exception CertificateException for proxy certificates , if
* the issuer DN of the certificate does not match
* the subject DN of the certificate without the
* last < I > CN < / I > component . Also , for GSI - 3 proxies
* when the < code > ProxyCertInfo < / code > extension is
* not marked as critical . */
private static GSIConstants . CertificateType getCertificateType ( TBSCertificateStructure crt ) throws CertificateException , IOException { } } | X509Extensions extensions = crt . getExtensions ( ) ; X509Extension ext = null ; if ( extensions != null ) { ext = extensions . getExtension ( X509Extension . basicConstraints ) ; if ( ext != null ) { BasicConstraints basicExt = BasicConstraints . getInstance ( ext ) ; if ( basicExt . isCA ( ) ) { return GSIConstants . CertificateType . CA ; } } } GSIConstants . CertificateType type = GSIConstants . CertificateType . EEC ; // does not handle multiple AVAs
X500Name subject = crt . getSubject ( ) ; ASN1Set entry = X509NameHelper . getLastNameEntry ( subject ) ; ASN1Sequence ava = ( ASN1Sequence ) entry . getObjectAt ( 0 ) ; if ( BCStyle . CN . equals ( ava . getObjectAt ( 0 ) ) ) { String value = ( ( ASN1String ) ava . getObjectAt ( 1 ) ) . getString ( ) ; if ( value . equalsIgnoreCase ( "proxy" ) ) { type = GSIConstants . CertificateType . GSI_2_PROXY ; } else if ( value . equalsIgnoreCase ( "limited proxy" ) ) { type = GSIConstants . CertificateType . GSI_2_LIMITED_PROXY ; } else if ( extensions != null ) { boolean gsi4 = true ; // GSI _ 4
ext = extensions . getExtension ( ProxyCertInfo . OID ) ; if ( ext == null ) { // GSI _ 3
ext = extensions . getExtension ( ProxyCertInfo . OLD_OID ) ; gsi4 = false ; } if ( ext != null ) { if ( ext . isCritical ( ) ) { ProxyCertInfo proxyCertExt = getProxyCertInfo ( ext ) ; ProxyPolicy proxyPolicy = proxyCertExt . getProxyPolicy ( ) ; ASN1ObjectIdentifier oid = proxyPolicy . getPolicyLanguage ( ) ; if ( ProxyPolicy . IMPERSONATION . equals ( oid ) ) { if ( gsi4 ) { type = GSIConstants . CertificateType . GSI_4_IMPERSONATION_PROXY ; } else { type = GSIConstants . CertificateType . GSI_3_IMPERSONATION_PROXY ; } } else if ( ProxyPolicy . INDEPENDENT . equals ( oid ) ) { if ( gsi4 ) { type = GSIConstants . CertificateType . GSI_4_INDEPENDENT_PROXY ; } else { type = GSIConstants . CertificateType . GSI_3_INDEPENDENT_PROXY ; } } else if ( ProxyPolicy . LIMITED . equals ( oid ) ) { if ( gsi4 ) { type = GSIConstants . CertificateType . GSI_4_LIMITED_PROXY ; } else { type = GSIConstants . CertificateType . GSI_3_LIMITED_PROXY ; } } else { if ( gsi4 ) { type = GSIConstants . CertificateType . GSI_4_RESTRICTED_PROXY ; } else { type = GSIConstants . CertificateType . GSI_3_RESTRICTED_PROXY ; } } } else { String err = i18n . getMessage ( "proxyCertCritical" ) ; throw new CertificateException ( err ) ; } } } if ( ProxyCertificateUtil . isProxy ( type ) ) { X509NameHelper iss = new X509NameHelper ( crt . getIssuer ( ) ) ; iss . add ( ( ASN1Set ) BouncyCastleUtil . duplicate ( entry ) ) ; X509Name issuer = iss . getAsName ( ) ; if ( ! issuer . equals ( X509Name . getInstance ( subject ) ) ) { String err = i18n . getMessage ( "proxyDNErr" ) ; throw new CertificateException ( err ) ; } } } return type ; |
public class PRJUtil { /** * Return the SRID value stored in a prj file
* If the the prj file
* - is null ,
* - is empty
* then a default srid equals to 0 is added .
* @ param prjFile
* @ return
* @ throws IOException */
public static int getSRID ( File prjFile ) throws IOException { } } | int srid = 0 ; if ( prjFile == null ) { log . debug ( "This prj file is null. \n A default srid equals to 0 will be added." ) ; } else { PrjParser parser = new PrjParser ( ) ; String prjString = readPRJFile ( prjFile ) ; if ( ! prjString . isEmpty ( ) ) { Map < String , String > p = parser . getParameters ( prjString ) ; String authorityWithCode = p . get ( PrjKeyParameters . REFNAME ) ; if ( authorityWithCode != null ) { String [ ] authorityNameWithKey = authorityWithCode . split ( ":" ) ; srid = Integer . valueOf ( authorityNameWithKey [ 1 ] ) ; } } else { log . debug ( "The prj is empty. \n A default srid equals to 0 will be added." ) ; } } return srid ; |
public class OSchemaHelper { /** * Create { @ link OIndex } on a set of fields if required
* @ param name name of an index
* @ param type type of an index
* @ param fields fields to create index on
* @ return this helper */
public OSchemaHelper oIndex ( String name , INDEX_TYPE type , String ... fields ) { } } | checkOClass ( ) ; lastIndex = lastClass . getClassIndex ( name ) ; if ( lastIndex == null ) { lastIndex = lastClass . createIndex ( name , type , fields ) ; } else { // We can ' t do something to change type and fields if required
} return this ; |
public class ScanResult { /** * Index { @ link Resource } and { @ link ClassInfo } objects . */
private void indexResourcesAndClassInfo ( ) { } } | // Add backrefs from Info objects back to this ScanResult
final Collection < ClassInfo > allClassInfo = classNameToClassInfo . values ( ) ; for ( final ClassInfo classInfo : allClassInfo ) { classInfo . setScanResult ( this ) ; } // If inter - class dependencies are enabled , create placeholder ClassInfo objects for any referenced
// classes that were not scanned
if ( scanSpec . enableInterClassDependencies ) { for ( final ClassInfo ci : new ArrayList < > ( classNameToClassInfo . values ( ) ) ) { final Set < ClassInfo > refdClasses = new HashSet < > ( ) ; for ( final String refdClassName : ci . findReferencedClassNames ( ) ) { // Don ' t add circular dependencies
if ( ! ci . getName ( ) . equals ( refdClassName ) ) { // Get ClassInfo object for the named class , or create one if it doesn ' t exist
final ClassInfo refdClassInfo = ClassInfo . getOrCreateClassInfo ( refdClassName , /* classModifiers are unknown */
0 , classNameToClassInfo ) ; refdClassInfo . setScanResult ( this ) ; if ( ! refdClassInfo . isExternalClass ( ) || scanSpec . enableExternalClasses ) { // Only add class to result if it is whitelisted , or external classes are enabled
refdClasses . add ( refdClassInfo ) ; } } } ci . setReferencedClasses ( new ClassInfoList ( refdClasses , /* sortByName = */
true ) ) ; } } |
public class Cache { /** * Delete the object .
* @ param obj the obj */
@ Override public void delete ( ApiType obj ) { } } | String key = keyFunc . apply ( obj ) ; lock . lock ( ) ; try { boolean exists = this . items . containsKey ( key ) ; if ( exists ) { this . deleteFromIndices ( this . items . get ( key ) , key ) ; this . items . remove ( key ) ; } } finally { lock . unlock ( ) ; } |
public class URLConnection { /** * Returns the value of the named field parsed as a number .
* This form of < code > getHeaderField < / code > exists because some
* connection types ( e . g . , < code > http - ng < / code > ) have pre - parsed
* headers . Classes for that connection type can override this method
* and short - circuit the parsing .
* @ param name the name of the header field .
* @ param Default the default value .
* @ return the value of the named field , parsed as an integer . The
* < code > Default < / code > value is returned if the field is
* missing or malformed . */
public int getHeaderFieldInt ( String name , int Default ) { } } | String value = getHeaderField ( name ) ; try { return Integer . parseInt ( value ) ; } catch ( Exception e ) { } return Default ; |
public class BootstrapContextImpl { /** * DS method to deactivate this component .
* Best practice : this should be a protected method , not public or private
* @ param context for this component instance
* @ throws Exception if the attempt to stop the resource adapter fails */
protected void deactivate ( ComponentContext context ) throws Exception { } } | contextProviders . deactivate ( context ) ; bvalRef . deactivate ( context ) ; tranInflowManagerRef . deactivate ( context ) ; tranSyncRegistryRef . deactivate ( context ) ; jcaSecurityContextRef . deactivate ( context ) ; latch . countDown ( ) ; latches . remove ( resourceAdapterID , latch ) ; FutureMonitor futureMonitor = futureMonitorSvc ; Future < Boolean > future = appsStoppedFuture . getAndSet ( null ) ; if ( futureMonitor != null && future != null ) { futureMonitor . onCompletion ( future , new CompletionListener < Boolean > ( ) { @ Override public void successfulCompletion ( Future < Boolean > future , Boolean result ) { stopResourceAdapter ( ) ; } @ Override public void failedCompletion ( Future < Boolean > future , Throwable t ) { stopResourceAdapter ( ) ; } } ) ; } else { stopResourceAdapter ( ) ; } |
public class PackageTransformer { /** * Read the manifest from supplied input stream , which is closed before return . */
private static Manifest getManifest ( final RegisteredResource rsrc ) throws IOException { } } | try ( final InputStream ins = rsrc . getInputStream ( ) ) { if ( ins != null ) { try ( JarInputStream jis = new JarInputStream ( ins ) ) { return jis . getManifest ( ) ; } } else { return null ; } } |
public class ReplyFactory { /** * Adds an Airline Itinerary Template to the response .
* @ param introMessage
* the message to send before the template . It can ' t be empty .
* @ param locale
* the current locale . It can ' t be empty and must be in format
* [ a - z ] { 2 } _ [ A - Z ] { 2 } . Locale must be in format [ a - z ] { 2 } _ [ A - Z ] { 2 } .
* For more information see < a href =
* " https : / / developers . facebook . com / docs / internationalization # locales "
* > Facebook ' s locale support < / a > .
* @ param pnrNumber
* the Passenger Name Record number ( Booking Number ) . It can ' t be
* empty .
* @ param totalPrice
* the total price of the itinerary .
* @ param currency
* the currency for the price . It can ' t be empty . The currency
* must be a three digit ISO - 4217-3 code in format [ A - Z ] { 3 } . For
* more information see < a href =
* " https : / / developers . facebook . com / docs / payments / reference / supportedcurrencies "
* > Facebook ' s currency support < / a >
* @ return a builder for the response .
* @ see < a href =
* " https : / / developers . facebook . com / docs / messenger - platform / send - api - reference / airline - itinerary - template "
* > Facebook ' s Messenger Platform Airline Itinerary Template
* Documentation < / a > */
public static AirlineItineraryTemplateBuilder addAirlineItineraryTemplate ( String introMessage , String locale , String pnrNumber , BigDecimal totalPrice , String currency ) { } } | return new AirlineItineraryTemplateBuilder ( introMessage , locale , pnrNumber , totalPrice , currency ) ; |
public class CommerceWarehouseItemUtil { /** * Returns all the commerce warehouse items where CProductId = & # 63 ; and CPInstanceUuid = & # 63 ; .
* @ param CProductId the c product ID
* @ param CPInstanceUuid the cp instance uuid
* @ return the matching commerce warehouse items */
public static List < CommerceWarehouseItem > findByCPI_CPIU ( long CProductId , String CPInstanceUuid ) { } } | return getPersistence ( ) . findByCPI_CPIU ( CProductId , CPInstanceUuid ) ; |
public class Slf4jMDCAdapter { /** * For all the methods that operate against the context , return true if the MDC should use the PaxContext object from the PaxLoggingManager ,
* or if the logging manager is not set , or does not have its context available yet , use a default context local to this MDC .
* @ return m _ context if the MDC should use the PaxContext object from the PaxLoggingManager ,
* or m _ defaultContext if the logging manager is not set , or does not have its context available yet . */
private static PaxContext getContext ( ) { } } | if ( m_context == null && m_paxLogging != null ) { m_context = ( m_paxLogging . getPaxLoggingService ( ) != null ) ? m_paxLogging . getPaxLoggingService ( ) . getPaxContext ( ) : null ; } return m_context != null ? m_context : m_defaultContext ; |
public class PrecisionRecallCurve { /** * Get the point ( index , threshold , precision , recall ) at the given precision . < br >
* Specifically , return the points at the lowest threshold that has precision equal to or greater than the
* requested precision .
* @ param precision Precision to get the point for
* @ return point ( index , threshold , precision , recall ) at ( or closest exceeding ) the given precision */
public Point getPointAtPrecision ( double precision ) { } } | // Find the LOWEST threshold that gives the specified precision
for ( int i = 0 ; i < this . precision . length ; i ++ ) { if ( this . precision [ i ] >= precision ) { return new Point ( i , threshold [ i ] , this . precision [ i ] , recall [ i ] ) ; } } // Not found , return last point . Should never happen though . . .
int i = threshold . length - 1 ; return new Point ( i , threshold [ i ] , this . precision [ i ] , this . recall [ i ] ) ; |
public class OutputControllerManager { /** * Returns a { @ link Optional } object that may or may not contain the desired { @ link OutputControllerModel } ,
* depending on whether it was registered with Izou or not .
* @ param identifiable The ID of the OutputController that should be retrieved .
* @ return The { @ link Optional } object that may or may not contain the desired { @ link OutputControllerModel } ,
* depending on whether it was registered with Izou or not . */
public Optional < OutputControllerModel > getOutputController ( Identifiable identifiable ) { } } | return outputControllers . stream ( ) . filter ( outputController -> outputController . getID ( ) . equals ( identifiable . getID ( ) ) ) . findFirst ( ) ; |
public class Node { /** * Sets the child for a given index .
* @ param idx
* the alphabet symbol index
* @ param alphabetSize
* the overall alphabet size ; this is needed if a new children array needs to be created
* @ param child
* the new child */
public void setChild ( int idx , int alphabetSize , Node < I > child ) { } } | if ( children == null ) { children = new ResizingArrayStorage < > ( Node . class , alphabetSize ) ; } children . array [ idx ] = child ; |
public class CommerceShippingFixedOptionUtil { /** * Returns the commerce shipping fixed options before and after the current commerce shipping fixed option in the ordered set where commerceShippingMethodId = & # 63 ; .
* @ param commerceShippingFixedOptionId the primary key of the current commerce shipping fixed option
* @ param commerceShippingMethodId the commerce shipping method ID
* @ param orderByComparator the comparator to order the set by ( optionally < code > null < / code > )
* @ return the previous , current , and next commerce shipping fixed option
* @ throws NoSuchShippingFixedOptionException if a commerce shipping fixed option with the primary key could not be found */
public static CommerceShippingFixedOption [ ] findByCommerceShippingMethodId_PrevAndNext ( long commerceShippingFixedOptionId , long commerceShippingMethodId , OrderByComparator < CommerceShippingFixedOption > orderByComparator ) throws com . liferay . commerce . shipping . engine . fixed . exception . NoSuchShippingFixedOptionException { } } | return getPersistence ( ) . findByCommerceShippingMethodId_PrevAndNext ( commerceShippingFixedOptionId , commerceShippingMethodId , orderByComparator ) ; |
public class ResolvingXMLConfiguration { /** * Resolve the IP address from a URL .
* @ param url and URL that will return an IP address
* @ param name the name of the variable
* @ return the result from the HTTP GET operations or null of an error */
private String ipAddressFromURL ( String url , String name ) { } } | String ipAddr = null ; if ( _urlValidator . isValid ( url ) ) { WebTarget resolver = ClientBuilder . newClient ( ) . target ( url ) ; try { ipAddr = resolver . request ( ) . get ( String . class ) ; } catch ( Exception e ) { warn ( "URL Cannot Resolve for resolveIP named [" + name + "]. The requested URL is invalid [" + url + "]." ) ; } } else { warn ( "The requested URL for resolveIP named [" + name + "] is invalid [" + url + "]." ) ; } return ipAddr ; |
public class CountedCompleter { /** * Regardless of pending count , invokes { @ link # onCompletion } ,
* marks this task as complete with a { @ code null } return value ,
* and further triggers { @ link # tryComplete } on this task ' s
* completer , if one exists . This method may be useful when
* forcing completion as soon as any one ( versus all ) of several
* subtask results are obtained .
* @ param mustBeNull the { @ code null } completion value */
public void complete ( Void mustBeNull ) { } } | CountedCompleter p ; onCompletion ( this ) ; quietlyComplete ( ) ; if ( ( p = completer ) != null ) p . tryComplete ( ) ; |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.