signature stringlengths 43 39.1k | implementation stringlengths 0 450k |
|---|---|
public class GeometryExpression { /** * Returns a geometric object that represents the Point set intersection of this geometric
* object with anotherGeometry .
* @ param geometry other geometry
* @ return intersection of this and the other geometry */
public GeometryExpression < Geometry > intersection ( Expression < ? extends Geometry > geometry ) { } } | return GeometryExpressions . geometryOperation ( SpatialOps . INTERSECTION , mixin , geometry ) ; |
public class ColorChooserFrame { /** * < / editor - fold > / / GEN - END : initComponents */
private void okButtonActionPerformed ( java . awt . event . ActionEvent evt ) { } } | // GEN - FIRST : event _ okButtonActionPerformed
feedback = UserFeedback . Ok ; synchronized ( WAITER_LOCK ) { okButton . setEnabled ( false ) ; cancelButton . setEnabled ( false ) ; WAITER_LOCK . notifyAll ( ) ; } |
public class BoxRequestCommentAdd { /** * Sets the id of the item used in the request to add a comment to .
* @ param id id of the item to add a comment to .
* @ return request with the updated item id . */
protected R setItemId ( String id ) { } } | JsonObject object = new JsonObject ( ) ; if ( mBodyMap . containsKey ( BoxComment . FIELD_ITEM ) ) { BoxEntity item = ( BoxEntity ) mBodyMap . get ( BoxComment . FIELD_ITEM ) ; object = item . toJsonObject ( ) ; } object . add ( BoxEntity . FIELD_ID , id ) ; BoxEntity item = new BoxEntity ( object ) ; mBodyMap . put ( BoxComment . FIELD_ITEM , item ) ; return ( R ) this ; |
public class MavenJDOMWriter { /** * Method updateReportSet .
* @ param value
* @ param element
* @ param counter
* @ param xmlTag */
protected void updateReportSet ( ReportSet value , String xmlTag , Counter counter , Element element ) { } } | Element root = element ; Counter innerCount = new Counter ( counter . getDepth ( ) + 1 ) ; findAndReplaceSimpleElement ( innerCount , root , "id" , value . getId ( ) , "default" ) ; findAndReplaceXpp3DOM ( innerCount , root , "configuration" , ( Xpp3Dom ) value . getConfiguration ( ) ) ; findAndReplaceSimpleElement ( innerCount , root , "inherited" , value . getInherited ( ) , null ) ; findAndReplaceSimpleLists ( innerCount , root , value . getReports ( ) , "reports" , "report" ) ; |
public class HMangr { /** * Reuse the same service . This is helpful for multiple calls that change service side cached data so that
* there is not a speed issue .
* If the service goes down , another service will be substituted , if available .
* @ param access
* @ param loc
* @ param ss
* @ param item
* @ param retryable
* @ return
* @ throws URISyntaxException
* @ throws Exception */
public < RET > RET same ( SecuritySetter < HttpURLConnection > ss , Retryable < RET > retryable ) throws APIException , CadiException , LocatorException { } } | RET ret = null ; boolean retry = true ; int retries = 0 ; Rcli < HttpURLConnection > client = retryable . lastClient ( ) ; try { do { // if no previous state , get the best
if ( retryable . item ( ) == null ) { retryable . item ( loc . best ( ) ) ; retryable . lastClient = null ; } if ( client == null ) { Item item = retryable . item ( ) ; URI uri = loc . get ( item ) ; if ( uri == null ) { loc . invalidate ( retryable . item ( ) ) ; if ( loc . hasItems ( ) ) { retryable . item ( loc . next ( retryable . item ( ) ) ) ; continue ; } else { throw new LocatorException ( "No clients available for " + loc . toString ( ) ) ; } } client = new HRcli ( this , uri , item , ss ) . connectionTimeout ( connectionTimeout ) . readTimeout ( readTimeout ) . apiVersion ( apiVersion ) ; } else { client . setSecuritySetter ( ss ) ; } retry = false ; try { ret = retryable . code ( client ) ; } catch ( APIException | CadiException e ) { Item item = retryable . item ( ) ; loc . invalidate ( item ) ; retryable . item ( loc . next ( item ) ) ; try { Throwable ec = e . getCause ( ) ; if ( ec instanceof java . net . ConnectException ) { if ( client != null && ++ retries < 2 ) { access . log ( Level . WARN , "Connection refused, trying next available service" ) ; retry = true ; } else { throw new CadiException ( "Connection refused, no more available connections to try" ) ; } } else if ( ec instanceof SSLHandshakeException ) { retryable . item ( null ) ; throw e ; } else if ( ec instanceof SocketException ) { if ( "java.net.SocketException: Connection reset" . equals ( ec . getMessage ( ) ) ) { access . log ( Level . ERROR , ec . getMessage ( ) , " can mean Certificate Expiration or TLS Protocol issues" ) ; } retryable . item ( null ) ; throw e ; } else { retryable . item ( null ) ; throw e ; } } finally { client = null ; } } catch ( ConnectException e ) { Item item = retryable . item ( ) ; loc . invalidate ( item ) ; retryable . item ( loc . next ( item ) ) ; } } while ( retry ) ; } finally { retryable . lastClient = client ; } return ret ; |
public class MailClientHandler { /** * This is synchronized to ensure that we process the queue serially . */
private synchronized void complete ( String message ) { } } | // This is a weird problem with writing stuff while idling . Need to investigate it more , but
// for now just ignore it .
if ( MESSAGE_COULDNT_BE_FETCHED_REGEX . matcher ( message ) . matches ( ) ) { log . warn ( "Some messages in the batch could not be fetched for {}\n" + "---cmd---\n{}\n---wire---\n{}\n---end---\n" , new Object [ ] { config . getUsername ( ) , getCommandTrace ( ) , getWireTrace ( ) } ) ; errorStack . push ( new Error ( completions . peek ( ) , message , wireTrace . list ( ) ) ) ; final CommandCompletion completion = completions . peek ( ) ; String errorMsg = "Some messages in the batch could not be fetched for user " + config . getUsername ( ) ; RuntimeException ex = new RuntimeException ( errorMsg ) ; if ( completion != null ) { completion . error ( errorMsg , new MailHandlingException ( getWireTrace ( ) , errorMsg , ex ) ) ; completions . poll ( ) ; } else { throw ex ; } } CommandCompletion completion = completions . peek ( ) ; if ( completion == null ) { if ( "+ idling" . equalsIgnoreCase ( message ) ) { synchronized ( idleMutex ) { idler . idleStart ( ) ; log . trace ( "IDLE entered." ) ; idleAcknowledged . set ( true ) ; } } else { log . error ( "Could not find the completion for message {} (Was it ever issued?)" , message ) ; errorStack . push ( new Error ( null , "No completion found!" , wireTrace . list ( ) ) ) ; } return ; } if ( completion . complete ( message ) ) { completions . poll ( ) ; } |
public class Reflect { /** * Find the best match for signature idealMatch .
* It is assumed that the methods array holds only valid candidates
* ( e . g . method name and number of args already matched ) .
* This method currently does not take into account Java 5 covariant
* return types . . . which I think will require that we find the most
* derived return type of otherwise identical best matches .
* @ see # findMostSpecificSignature ( Class [ ] , Class [ ] [ ] )
* @ param methods the set of candidate method which differ only in the
* types of their arguments . */
public static Invocable findMostSpecificInvocable ( Class < ? > [ ] idealMatch , List < Invocable > methods ) { } } | // copy signatures into array for findMostSpecificMethod ( )
List < Class < ? > [ ] > candidateSigs = new ArrayList < > ( ) ; List < Invocable > methodList = new ArrayList < > ( ) ; for ( Invocable method : methods ) { Class < ? > [ ] parameterTypes = method . getParameterTypes ( ) ; methodList . add ( method ) ; candidateSigs . add ( parameterTypes ) ; if ( method . isVarArgs ( ) && idealMatch . length >= parameterTypes . length ) { Class < ? > [ ] candidateSig = new Class [ idealMatch . length ] ; System . arraycopy ( parameterTypes , 0 , candidateSig , 0 , parameterTypes . length - 1 ) ; Arrays . fill ( candidateSig , parameterTypes . length - 1 , idealMatch . length , method . getVarArgsComponentType ( ) ) ; methodList . add ( method ) ; candidateSigs . add ( candidateSig ) ; } } int match = findMostSpecificSignature ( idealMatch , candidateSigs . toArray ( new Class [ candidateSigs . size ( ) ] [ ] ) ) ; return match == - 1 ? null : methodList . get ( match ) ; |
public class MathExpressions { /** * Create a { @ code sinh ( num ) } expression
* < p > Returns the hyperbolic sine of num radians . < / p >
* @ param num numeric expression
* @ return sinh ( num ) */
public static < A extends Number & Comparable < ? > > NumberExpression < Double > sinh ( Expression < A > num ) { } } | return Expressions . numberOperation ( Double . class , Ops . MathOps . SINH , num ) ; |
public class MagicMimeEntry { /** * Traverse and print .
* @ param tabs the tabs */
public void traverseAndPrint ( final String tabs ) { } } | logger . info ( tabs + toString ( ) ) ; final int len = this . subEntries . size ( ) ; for ( int i = 0 ; i < len ; i ++ ) { final MagicMimeEntry me = this . subEntries . get ( i ) ; me . traverseAndPrint ( tabs + "\t" ) ; } |
public class JobClient { /** * Internal method for submitting jobs to the system .
* @ param job the configuration to submit
* @ return a proxy object for the running job
* @ throws FileNotFoundException
* @ throws ClassNotFoundException
* @ throws InterruptedException
* @ throws IOException */
public RunningJob submitJobInternal ( JobConf job ) throws FileNotFoundException , ClassNotFoundException , InterruptedException , IOException { } } | /* * configure the command line options correctly on the submitting dfs */
boolean shared = job . getBoolean ( "mapred.cache.shared.enabled" , false ) ; JobID jobId = jobSubmitClient . getNewJobId ( ) ; Path submitJobDir = new Path ( getSystemDir ( ) , jobId . toString ( ) ) ; Path sharedFilesDir = new Path ( getSystemDir ( ) , jobSubmitClient . CAR ) ; Path submitSplitFile = new Path ( submitJobDir , "job.split" ) ; getFs ( ) ; if ( jobSubmitClient instanceof LocalJobRunner ) { symLinkAndConfigureFiles ( job ) ; } else { copyAndConfigureFiles ( job , ( shared ) ? sharedFilesDir : submitJobDir , shared ) ; } Path submitJobFile = new Path ( submitJobDir , "job.xml" ) ; int reduces = job . getNumReduceTasks ( ) ; JobContext context = new JobContext ( job , jobId ) ; // Check the output specification
if ( reduces == 0 ? job . getUseNewMapper ( ) : job . getUseNewReducer ( ) ) { org . apache . hadoop . mapreduce . OutputFormat < ? , ? > output = ReflectionUtils . newInstance ( context . getOutputFormatClass ( ) , job ) ; output . checkOutputSpecs ( context ) ; } else { job . getOutputFormat ( ) . checkOutputSpecs ( fs , job ) ; } // Create the splits for the job
LOG . debug ( "Creating splits at " + fs . makeQualified ( submitSplitFile ) ) ; List < RawSplit > maps ; if ( job . getUseNewMapper ( ) ) { maps = computeNewSplits ( context ) ; } else { maps = computeOldSplits ( job ) ; } job . setNumMapTasks ( maps . size ( ) ) ; if ( ! isJobTrackerInProc ) { JobConf conf = null ; if ( job . getUseNewMapper ( ) ) { conf = context . getJobConf ( ) ; } else { conf = job ; } writeComputedSplits ( conf , maps , submitSplitFile ) ; job . set ( "mapred.job.split.file" , submitSplitFile . toString ( ) ) ; } else { synchronized ( JobClient . jobSplitCache ) { if ( JobClient . jobSplitCache . containsKey ( jobId ) ) { throw new IOException ( "Job split already cached " + jobId ) ; } JobClient . jobSplitCache . put ( jobId , maps ) ; } synchronized ( JobClient . jobConfCache ) { if ( JobClient . jobConfCache . containsKey ( jobId ) ) { throw new IOException ( "Job conf already cached " + jobId ) ; } jobConfCache . put ( jobId , job ) ; } } // Write job file to JobTracker ' s fs
FSDataOutputStream out = FileSystem . create ( fs , submitJobFile , new FsPermission ( JOB_FILE_PERMISSION ) ) ; try { job . writeXml ( out ) ; } finally { out . close ( ) ; } // Now , actually submit the job ( using the submit name )
JobStatus status = jobSubmitClient . submitJob ( jobId ) ; if ( status != null ) { return new NetworkedJob ( status ) ; } else { throw new IOException ( "Could not launch job" ) ; } |
public class LocalDeviceMgmtAdapter { /** * Sends a reset request to the KNXnet / IP server . A successful reset request causes the KNXnet / IP server to close
* the KNXnet / IP device management connection .
* @ throws KNXConnectionClosedException on closed connection
* @ throws KNXTimeoutException if a timeout regarding a response message was encountered
* @ throws InterruptedException on thread interrupt */
public void reset ( ) throws KNXConnectionClosedException , KNXTimeoutException , InterruptedException { } } | send ( new CEMIDevMgmt ( CEMIDevMgmt . MC_RESET_REQ ) , BlockingMode . WaitForAck ) ; |
public class AbstractCorsFilter { /** * Interception method .
* It checks whether or not the request requires CORS support or not . It also checks whether the requests is allowed
* or not .
* @ param route the router
* @ param context the filter context
* @ return the result , containing the CORS headers as defined in the recommendation
* @ throws Exception if the result cannot be handled correctly . */
public Result call ( Route route , RequestContext context ) throws Exception { } } | // Is CORS required ?
String originHeader = context . request ( ) . getHeader ( ORIGIN ) ; if ( originHeader != null ) { originHeader = originHeader . toLowerCase ( ) ; } // If not Preflight
if ( route . getHttpMethod ( ) != HttpMethod . OPTIONS ) { return retrieveAndReturnResult ( context , originHeader ) ; } // OPTIONS route exists , don ' t use filter ! ( might manually implement
// CORS ? )
if ( ! route . isUnbound ( ) ) { return context . proceed ( ) ; } // Try " Preflight "
// Find existing methods for other routes
Collection < Route > routes = router . getRoutes ( ) ; List < String > methods = new ArrayList < > ( 4 ) ; // expect POST PUT GET DELETE
for ( Route r : routes ) { if ( r . matches ( r . getHttpMethod ( ) , route . getUrl ( ) ) ) { methods . add ( r . getHttpMethod ( ) . name ( ) ) ; } } // If there ' s none , proceed to 404
if ( methods . isEmpty ( ) ) { return context . proceed ( ) ; } String requestMethod = context . request ( ) . getHeader ( ACCESS_CONTROL_REQUEST_METHOD ) ; // If it ' s not a CORS request , just proceed !
if ( originHeader == null || requestMethod == null ) { return context . proceed ( ) ; } Result res = Results . ok ( ) ; // setup result
if ( ! methods . contains ( requestMethod . toUpperCase ( ) ) ) { res = Results . unauthorized ( "No such method for this route" ) ; } Integer maxAge = getMaxAge ( ) ; if ( maxAge != null ) { res = res . with ( ACCESS_CONTROL_MAX_AGE , String . valueOf ( maxAge ) ) ; } // Otherwise we should be return OK with the appropriate headers .
String exposedHeaders = getExposedHeadersHeader ( ) ; String allowedHosts = getAllowedHostsHeader ( originHeader ) ; String allowedMethods = Joiner . on ( ", " ) . join ( methods ) ; Result result = res . with ( ACCESS_CONTROL_ALLOW_ORIGIN , allowedHosts ) . with ( ACCESS_CONTROL_ALLOW_METHODS , allowedMethods ) . with ( ACCESS_CONTROL_ALLOW_HEADERS , exposedHeaders ) ; if ( getAllowCredentials ( ) ) { result = result . with ( ACCESS_CONTROL_ALLOW_CREDENTIALS , "true" ) ; } return result ; |
public class StartAndStopSQL { /** * / * ( non - Javadoc )
* @ see org . springframework . context . Lifecycle # start ( ) */
public void start ( ) { } } | if ( state . compareAndSet ( UNKNOWN , STARTING ) ) { log . debug ( "Starting..." ) ; if ( ( StringUtils . isBlank ( startSqlCondition ) || isInCondition ( startSqlCondition ) ) && ( StringUtils . isBlank ( startSqlConditionResource ) || isInConditionResource ( startSqlConditionResource ) ) ) { if ( StringUtils . isNotBlank ( startSQL ) ) { executeSQL ( startSQL ) ; } else if ( StringUtils . isNotBlank ( startSqlResource ) ) { executeSqlResource ( startSqlResource ) ; } } state . set ( RUNNING ) ; } else { log . warn ( "Start request ignored. Current state is: " + stateNames [ state . get ( ) ] ) ; } |
public class MarkLogicRepositoryConnection { /** * sets transaction isolationlevel ( only IsolationLevels . SNAPSHOT supported )
* @ param level
* @ throws IllegalStateException */
@ Override public void setIsolationLevel ( IsolationLevel level ) throws IllegalStateException { } } | if ( level != IsolationLevels . SNAPSHOT ) { throw new IllegalStateException ( "Only IsolationLevels.SNAPSHOT level supported." ) ; } else { super . setIsolationLevel ( level ) ; } |
public class SimpleBitfinexApiBroker { /** * Handle a command callback */
private void handleCommandCallback ( final String message ) { } } | // JSON callback
final JSONObject jsonObject = new JSONObject ( message ) ; final String eventType = jsonObject . getString ( "event" ) ; final CommandCallbackHandler commandCallbackHandler = commandCallbacks . get ( eventType ) ; if ( commandCallbackHandler == null ) { logger . error ( "Unknown event: {}" , message ) ; return ; } try { commandCallbackHandler . handleChannelData ( jsonObject ) ; } catch ( final BitfinexClientException e ) { logger . error ( "Got an exception while handling callback" ) ; } |
public class ABITrace { /** * Utility method to return an int beginning at < code > pointer < / code > in the TraceData array .
* @ param pointer - beginning of trace array
* @ return - int beginning at pointer in trace array */
private int getIntAt ( int pointer ) { } } | int out = 0 ; byte [ ] temp = new byte [ 4 ] ; getSubArray ( temp , pointer ) ; try { DataInputStream dis = new DataInputStream ( new ByteArrayInputStream ( temp ) ) ; out = dis . readInt ( ) ; } catch ( IOException e ) // This shouldn ' t happen . If it does something must be seriously wrong .
{ throw new IllegalStateException ( "Unexpected IOException encountered while manipulating internal streams." ) ; } return out ; |
public class DBObject { /** * Add the given value to the field with the given name . For a system field , its
* existing value , if any , is replaced . If a null or empty field is added for an
* SV scalar , the field is nullified .
* @ param fieldName Name of a field .
* @ param value Value to add to field . Ignored if null or empty . */
public void addFieldValue ( String fieldName , String value ) { } } | Utils . require ( ! Utils . isEmpty ( fieldName ) , "fieldName" ) ; if ( fieldName . charAt ( 0 ) == '_' ) { setSystemField ( fieldName , value ) ; } else { List < String > currValues = m_valueMap . get ( fieldName ) ; if ( currValues == null ) { currValues = new ArrayList < > ( ) ; m_valueMap . put ( fieldName , currValues ) ; } currValues . add ( value ) ; } |
public class SystemParameter { /** * < pre >
* Define the HTTP header name to use for the parameter . It is case
* insensitive .
* < / pre >
* < code > string http _ header = 2 ; < / code > */
public com . google . protobuf . ByteString getHttpHeaderBytes ( ) { } } | java . lang . Object ref = httpHeader_ ; if ( ref instanceof java . lang . String ) { com . google . protobuf . ByteString b = com . google . protobuf . ByteString . copyFromUtf8 ( ( java . lang . String ) ref ) ; httpHeader_ = b ; return b ; } else { return ( com . google . protobuf . ByteString ) ref ; } |
public class CommerceOrderNoteLocalServiceBaseImpl { /** * Returns the commerce order note with the matching external reference code and company .
* @ param companyId the primary key of the company
* @ param externalReferenceCode the commerce order note ' s external reference code
* @ return the matching commerce order note , or < code > null < / code > if a matching commerce order note could not be found */
@ Override public CommerceOrderNote fetchCommerceOrderNoteByReferenceCode ( long companyId , String externalReferenceCode ) { } } | return commerceOrderNotePersistence . fetchByC_ERC ( companyId , null ) ; |
public class LdapTemplate { /** * { @ inheritDoc } */
@ Override public void bind ( DirContextOperations ctx ) { } } | Name dn = ctx . getDn ( ) ; if ( dn != null && ! ctx . isUpdateMode ( ) ) { bind ( dn , ctx , null ) ; } else { throw new IllegalStateException ( "The DirContextOperations instance needs to be properly initialized." ) ; } |
public class WebJaxWsModuleInfoBuilder { /** * Get all the Servlet name and className pairs from web . xml
* @ param webAppConfig
* @ return
* @ throws UnableToAdaptException */
private Map < String , String > getServletNameClassPairsInWebXML ( Container containerToAdapt ) throws UnableToAdaptException { } } | Map < String , String > nameClassPairs = new HashMap < String , String > ( ) ; WebAppConfig webAppConfig = containerToAdapt . adapt ( WebAppConfig . class ) ; Iterator < IServletConfig > cfgIter = webAppConfig . getServletInfos ( ) ; while ( cfgIter . hasNext ( ) ) { IServletConfig servletCfg = cfgIter . next ( ) ; if ( servletCfg . getClassName ( ) == null ) { continue ; } nameClassPairs . put ( servletCfg . getServletName ( ) , servletCfg . getClassName ( ) ) ; } return nameClassPairs ; |
public class SqlSubstitutionFragment { /** * Get the parameter values from this fragment and its children . An SqlSubstitutionFragment
* only contains parameters if one of its children has a complex value type .
* @ param context A ControlBeanContext instance
* @ param m The annotated method
* @ param args The method parameters
* @ return Array of objects . */
protected Object [ ] getParameterValues ( ControlBeanContext context , Method m , Object [ ] args ) { } } | ArrayList < Object > paramValues = new ArrayList < Object > ( ) ; for ( SqlFragment frag : _children ) { if ( frag . hasComplexValue ( context , m , args ) ) { paramValues . addAll ( Arrays . asList ( frag . getParameterValues ( context , m , args ) ) ) ; } } return paramValues . toArray ( ) ; |
public class X500Name { /** * Returns a string form of the X . 500 distinguished name
* using the algorithm defined in RFC 1779 . Attribute type
* keywords defined in RFC 1779 are emitted , as well as additional
* keywords contained in the OID / keyword map . */
public String getRFC1779Name ( Map < String , String > oidMap ) throws IllegalArgumentException { } } | if ( oidMap . isEmpty ( ) ) { // return cached result
if ( rfc1779Dn != null ) { return rfc1779Dn ; } else { rfc1779Dn = generateRFC1779DN ( oidMap ) ; return rfc1779Dn ; } } return generateRFC1779DN ( oidMap ) ; |
public class BatchDeleteScheduledActionResult { /** * The names of the scheduled actions that could not be deleted , including an error message .
* @ return The names of the scheduled actions that could not be deleted , including an error message . */
public java . util . List < FailedScheduledUpdateGroupActionRequest > getFailedScheduledActions ( ) { } } | if ( failedScheduledActions == null ) { failedScheduledActions = new com . amazonaws . internal . SdkInternalList < FailedScheduledUpdateGroupActionRequest > ( ) ; } return failedScheduledActions ; |
public class JsonResponse { @ SuppressWarnings ( "unchecked" ) public static < OBJ > JsonResponse < OBJ > asEmptyBody ( ) { } } | // user interface
return ( JsonResponse < OBJ > ) new JsonResponse < Object > ( DUMMY ) . ofEmptyBody ( ) ; |
public class KiteConnect { /** * Kills the session by invalidating the access token .
* @ return JSONObject which contains status
* @ throws KiteException is thrown for all Kite trade related errors .
* @ throws IOException is thrown when there is connection related error . */
public JSONObject invalidateAccessToken ( ) throws IOException , KiteException , JSONException { } } | String url = routes . get ( "api.token" ) ; Map < String , Object > params = new HashMap < > ( ) ; params . put ( "api_key" , apiKey ) ; params . put ( "access_token" , accessToken ) ; return new KiteRequestHandler ( proxy ) . deleteRequest ( url , params , apiKey , accessToken ) ; |
public class StubGenerator { /** * Invokes the stubbed behavior of the given method . */
public static Object invoke ( Class < ? > returnType , String className , String methodName ) { } } | // If we have an explicit implementation for this method , invoke it
if ( STUB_METHODS . containsKey ( new ClassAndMethod ( className , methodName ) ) ) { return STUB_METHODS . get ( new ClassAndMethod ( className , methodName ) ) . invoke ( ) ; } // Otherwise return an appropriate basic type
if ( returnType == String . class ) { return "" ; } else if ( returnType == Boolean . class ) { return false ; } else if ( returnType == Byte . class ) { return ( byte ) 0 ; } else if ( returnType == Character . class ) { return ( char ) 0 ; } else if ( returnType == Double . class ) { return ( double ) 0 ; } else if ( returnType == Integer . class ) { return ( int ) 0 ; } else if ( returnType == Float . class ) { return ( float ) 0 ; } else if ( returnType == Long . class ) { return ( long ) 0 ; } else if ( returnType == Short . class ) { return ( short ) 0 ; } else { return Mockito . mock ( returnType , new ReturnsCustomMocks ( ) ) ; } |
public class CSP2SourceList { /** * Add a scheme
* @ param sScheme
* Scheme in the format < code > scheme " : " < / code >
* @ return this */
@ Nonnull public CSP2SourceList addScheme ( @ Nonnull @ Nonempty final String sScheme ) { } } | ValueEnforcer . notEmpty ( sScheme , "Scheme" ) ; ValueEnforcer . isTrue ( sScheme . length ( ) > 1 && sScheme . endsWith ( ":" ) , ( ) -> "Passed scheme '" + sScheme + "' is invalid!" ) ; m_aList . add ( sScheme ) ; return this ; |
public class Semaphore { /** * Acquires the given number of permits from this semaphore , if all
* become available within the given waiting time and the current
* thread has not been { @ linkplain Thread # interrupt interrupted } .
* < p > Acquires the given number of permits , if they are available and
* returns immediately , with the value { @ code true } ,
* reducing the number of available permits by the given amount .
* < p > If insufficient permits are available then
* the current thread becomes disabled for thread scheduling
* purposes and lies dormant until one of three things happens :
* < ul >
* < li > Some other thread invokes one of the { @ link # release ( ) release }
* methods for this semaphore and the current thread is next to be assigned
* permits and the number of available permits satisfies this request ; or
* < li > Some other thread { @ linkplain Thread # interrupt interrupts }
* the current thread ; or
* < li > The specified waiting time elapses .
* < / ul >
* < p > If the permits are acquired then the value { @ code true } is returned .
* < p > If the current thread :
* < ul >
* < li > has its interrupted status set on entry to this method ; or
* < li > is { @ linkplain Thread # interrupt interrupted } while waiting
* to acquire the permits ,
* < / ul >
* then { @ link InterruptedException } is thrown and the current thread ' s
* interrupted status is cleared .
* Any permits that were to be assigned to this thread , are instead
* assigned to other threads trying to acquire permits , as if
* the permits had been made available by a call to { @ link # release ( ) } .
* < p > If the specified waiting time elapses then the value { @ code false }
* is returned . If the time is less than or equal to zero , the method
* will not wait at all . Any permits that were to be assigned to this
* thread , are instead assigned to other threads trying to acquire
* permits , as if the permits had been made available by a call to
* { @ link # release ( ) } .
* @ param permits the number of permits to acquire
* @ param timeout the maximum time to wait for the permits
* @ param unit the time unit of the { @ code timeout } argument
* @ return { @ code true } if all permits were acquired and { @ code false }
* if the waiting time elapsed before all permits were acquired
* @ throws InterruptedException if the current thread is interrupted
* @ throws IllegalArgumentException if { @ code permits } is negative */
public boolean tryAcquire ( int permits , long timeout , TimeUnit unit ) throws InterruptedException { } } | if ( permits < 0 ) throw new IllegalArgumentException ( ) ; return sync . tryAcquireSharedNanos ( permits , unit . toNanos ( timeout ) ) ; |
public class PassthroughReceiver { /** * A receiver is started with a Listener and a threading model . */
@ SuppressWarnings ( "unchecked" ) @ Override public void start ( final Listener < ? > listener , final Infrastructure infra ) throws MessageTransportException { } } | this . listener = ( Listener < Object > ) listener ; |
public class ntpserver { /** * Use this API to add ntpserver resources . */
public static base_responses add ( nitro_service client , ntpserver resources [ ] ) throws Exception { } } | base_responses result = null ; if ( resources != null && resources . length > 0 ) { ntpserver addresources [ ] = new ntpserver [ resources . length ] ; for ( int i = 0 ; i < resources . length ; i ++ ) { addresources [ i ] = new ntpserver ( ) ; addresources [ i ] . serverip = resources [ i ] . serverip ; addresources [ i ] . servername = resources [ i ] . servername ; addresources [ i ] . minpoll = resources [ i ] . minpoll ; addresources [ i ] . maxpoll = resources [ i ] . maxpoll ; addresources [ i ] . autokey = resources [ i ] . autokey ; addresources [ i ] . key = resources [ i ] . key ; } result = add_bulk_request ( client , addresources ) ; } return result ; |
public class ServerSchemaGenCommand { /** * Main method , which wraps the instance logic and registers
* the known tasks .
* @ param args */
public static void main ( String [ ] args ) { } } | ServerSchemaGenCommand util = new ServerSchemaGenCommand ( ) ; int rc = util . generateServerSchema ( args ) ; System . exit ( rc ) ; |
public class Values { /** * Find all the values of the requested type .
* @ param valueTypeToFind the type of the value to return .
* @ param < T > the type of the value to find .
* @ return the key , value pairs found . */
@ SuppressWarnings ( "unchecked" ) public < T > Map < String , T > find ( final Class < T > valueTypeToFind ) { } } | return ( Map < String , T > ) this . values . entrySet ( ) . stream ( ) . filter ( input -> valueTypeToFind . isInstance ( input . getValue ( ) ) ) . collect ( Collectors . toMap ( Map . Entry :: getKey , Map . Entry :: getValue ) ) ; |
public class DeleteCACertificateRequestMarshaller { /** * Marshall the given parameter object . */
public void marshall ( DeleteCACertificateRequest deleteCACertificateRequest , ProtocolMarshaller protocolMarshaller ) { } } | if ( deleteCACertificateRequest == null ) { throw new SdkClientException ( "Invalid argument passed to marshall(...)" ) ; } try { protocolMarshaller . marshall ( deleteCACertificateRequest . getCertificateId ( ) , CERTIFICATEID_BINDING ) ; } catch ( Exception e ) { throw new SdkClientException ( "Unable to marshall request to JSON: " + e . getMessage ( ) , e ) ; } |
public class LogViewer { /** * The main method .
* @ param args
* - command line arguments to LogViewer */
public static void main ( String [ ] args ) { } } | LogViewer logViewer = new LogViewer ( ) ; int code = logViewer . execute ( args ) ; if ( code > 0 ) { System . err . println ( getLocalizedString ( "CWTRA0029I" ) ) ; } System . exit ( code ) ; |
public class AgentScheduler { /** * The properties file will be loaded and the keys will be prepended with the QUARTZ _ PREFIX . < br / >
* If a value contains the literal PACKAGE _ PLACEHOLDER the literal will be replaced with the QUARTZ _ PREFIX .
* @ return The modified quartz properties with aligned packagenames in keys and values . */
private Properties loadQuartzProperties ( ) { } } | InputStream resourceStream = AgentScheduler . class . getResourceAsStream ( "/logspace-quartz.properties" ) ; try { Properties properties = new Properties ( ) ; properties . load ( resourceStream ) ; List < Object > keys = new ArrayList < Object > ( properties . keySet ( ) ) ; for ( Object eachKey : keys ) { String key = eachKey . toString ( ) ; properties . put ( QUARTZ_PREFIX + key , this . replacePackagePlaceholderIfNecessary ( properties . get ( key ) ) ) ; properties . remove ( key ) ; } return properties ; } catch ( Exception e ) { throw new AgentControllerInitializationException ( "Error loading logspace-quartz.properties." , e ) ; } finally { try { resourceStream . close ( ) ; } catch ( IOException e ) { // do nothing
} } |
public class LocalSymbolTableAsStruct { /** * NOT SYNCHRONIZED ! Call only from a synch ' d method .
* @ return a new struct , not null . */
private IonStruct makeIonRepresentation ( ValueFactory factory ) { } } | IonStruct ionRep = factory . newEmptyStruct ( ) ; ionRep . addTypeAnnotation ( ION_SYMBOL_TABLE ) ; SymbolTable [ ] importedTables = getImportedTablesNoCopy ( ) ; if ( importedTables . length > 1 ) { IonList importsList = factory . newEmptyList ( ) ; for ( int i = 1 ; i < importedTables . length ; i ++ ) { SymbolTable importedTable = importedTables [ i ] ; IonStruct importStruct = factory . newEmptyStruct ( ) ; importStruct . add ( NAME , factory . newString ( importedTable . getName ( ) ) ) ; importStruct . add ( VERSION , factory . newInt ( importedTable . getVersion ( ) ) ) ; importStruct . add ( MAX_ID , factory . newInt ( importedTable . getMaxId ( ) ) ) ; importsList . add ( importStruct ) ; } ionRep . add ( IMPORTS , importsList ) ; } if ( mySymbolsCount > 0 ) { int sid = myFirstLocalSid ; for ( int offset = 0 ; offset < mySymbolsCount ; offset ++ , sid ++ ) { String symbolName = mySymbolNames [ offset ] ; recordLocalSymbolInIonRep ( ionRep , symbolName , sid ) ; } } return ionRep ; |
public class SimpleExcelFlinkFileInputFormat { /** * Store currently processed sheet and row as well as infered schema */
@ Override public Tuple3 < Long , Long , GenericDataType [ ] > getCurrentState ( ) throws IOException { } } | return new Tuple3 < > ( this . getOfficeReader ( ) . getCurrentParser ( ) . getCurrentSheet ( ) , this . getOfficeReader ( ) . getCurrentParser ( ) . getCurrentRow ( ) , this . converter . getSchemaRow ( ) ) ; |
public class RemoteDomainConnection { /** * Connect and register at the remote domain controller .
* @ return connection the established connection
* @ throws IOException */
protected Connection openConnection ( ) throws IOException { } } | // Perhaps this can just be done once ?
CallbackHandler callbackHandler = null ; SSLContext sslContext = null ; if ( realm != null ) { sslContext = realm . getSSLContext ( ) ; CallbackHandlerFactory handlerFactory = realm . getSecretCallbackHandlerFactory ( ) ; if ( handlerFactory != null ) { String username = this . username != null ? this . username : localHostName ; callbackHandler = handlerFactory . getCallbackHandler ( username ) ; } } final ProtocolConnectionConfiguration config = ProtocolConnectionConfiguration . copy ( configuration ) ; config . setCallbackHandler ( callbackHandler ) ; config . setSslContext ( sslContext ) ; config . setUri ( uri ) ; AuthenticationContext authenticationContext = this . authenticationContext != null ? this . authenticationContext : AuthenticationContext . captureCurrent ( ) ; // Connect
try { return authenticationContext . run ( ( PrivilegedExceptionAction < Connection > ) ( ) -> ProtocolConnectionUtils . connectSync ( config ) ) ; } catch ( PrivilegedActionException e ) { if ( e . getCause ( ) instanceof IOException ) { throw ( IOException ) e . getCause ( ) ; } throw new IOException ( e ) ; } |
public class OptionGroup { /** * Indicates what options are available in the option group .
* @ return Indicates what options are available in the option group . */
public java . util . List < Option > getOptions ( ) { } } | if ( options == null ) { options = new com . amazonaws . internal . SdkInternalList < Option > ( ) ; } return options ; |
public class JobGraphLink { /** * Gets the label ( if any ) to show towards the user in the { @ link JobGraph } .
* @ return */
public String getLinkLabel ( ) { } } | final FilterOutcome filterOutcome = getFilterOutcome ( ) ; if ( filterOutcome != null ) { return filterOutcome . getCategory ( ) + "" ; } final ComponentRequirement req = getRequirement ( ) ; if ( req != null ) { return req . getSimpleName ( ) ; } final OutputDataStream outputDataStream = getOutputDataStream ( ) ; if ( outputDataStream != null ) { return outputDataStream . getName ( ) ; } return null ; |
public class BasicMDCAdapter { /** * Clear all entries in the MDC . */
public void clear ( ) { } } | Map < String , String > map = inheritableThreadLocal . get ( ) ; if ( map != null ) { map . clear ( ) ; inheritableThreadLocal . remove ( ) ; } |
public class StringUtil { /** * Returns a string on the same format as { @ code Object . toString ( ) } .
* @ param pObject the object
* @ return the object as a { @ code String } on the format of
* { @ code Object . toString ( ) } */
public static String identityToString ( Object pObject ) { } } | if ( pObject == null ) { return null ; } else { return pObject . getClass ( ) . getName ( ) + '@' + Integer . toHexString ( System . identityHashCode ( pObject ) ) ; } |
public class ViewFetcher { /** * Returns views from the shown DecorViews .
* @ param onlySufficientlyVisible if only sufficiently visible views should be returned
* @ return all the views contained in the DecorViews */
public ArrayList < View > getAllViews ( boolean onlySufficientlyVisible ) { } } | final View [ ] views = getWindowDecorViews ( ) ; final ArrayList < View > allViews = new ArrayList < View > ( ) ; final View [ ] nonDecorViews = getNonDecorViews ( views ) ; View view = null ; if ( nonDecorViews != null ) { for ( int i = 0 ; i < nonDecorViews . length ; i ++ ) { view = nonDecorViews [ i ] ; try { addChildren ( allViews , ( ViewGroup ) view , onlySufficientlyVisible ) ; } catch ( Exception ignored ) { } if ( view != null ) allViews . add ( view ) ; } } if ( views != null && views . length > 0 ) { view = getRecentDecorView ( views ) ; try { addChildren ( allViews , ( ViewGroup ) view , onlySufficientlyVisible ) ; } catch ( Exception ignored ) { } if ( view != null ) allViews . add ( view ) ; } return allViews ; |
public class SampleSummaryStatistics { /** * Combine two { @ code SampleSummaryStatistics } statistic objects .
* @ param other the other { @ code SampleSummaryStatistics } statistics to
* combine with { @ code this } one .
* @ return { @ code this } statistics object
* @ throws IllegalArgumentException if the { @ code parameterCount } of the
* { @ code other } statistics object is different to { @ code this } one
* @ throws NullPointerException if the other statistical summary is
* { @ code null } . */
public SampleSummaryStatistics combine ( final SampleSummaryStatistics other ) { } } | if ( other . _parameterCount != _parameterCount ) { throw new IllegalArgumentException ( format ( "Expected sample size of %d, but got %d." , _parameterCount , other . _parameterCount ) ) ; } for ( int i = 0 ; i < _parameterCount ; ++ i ) { _moments . get ( i ) . combine ( other . _moments . get ( i ) ) ; _quantiles . get ( i ) . combine ( other . _quantiles . get ( i ) ) ; } return this ; |
public class AccessTimeoutTypeImpl { /** * Returns the < code > timeout < / code > element
* @ return the node defined for the element < code > timeout < / code > */
public Integer getTimeout ( ) { } } | if ( childNode . getTextValueForPatternName ( "timeout" ) != null && ! childNode . getTextValueForPatternName ( "timeout" ) . equals ( "null" ) ) { return Integer . valueOf ( childNode . getTextValueForPatternName ( "timeout" ) ) ; } return null ; |
public class PacketParserUtils { /** * Parses stream error packets .
* @ param parser the XML parser .
* @ param outerXmlEnvironment the outer XML environment ( optional ) .
* @ return an stream error packet .
* @ throws IOException
* @ throws XmlPullParserException
* @ throws SmackParsingException */
public static StreamError parseStreamError ( XmlPullParser parser , XmlEnvironment outerXmlEnvironment ) throws XmlPullParserException , IOException , SmackParsingException { } } | final int initialDepth = parser . getDepth ( ) ; List < ExtensionElement > extensions = new ArrayList < > ( ) ; Map < String , String > descriptiveTexts = null ; StreamError . Condition condition = null ; String conditionText = null ; XmlEnvironment streamErrorXmlEnvironment = XmlEnvironment . from ( parser , outerXmlEnvironment ) ; outerloop : while ( true ) { int eventType = parser . next ( ) ; switch ( eventType ) { case XmlPullParser . START_TAG : String name = parser . getName ( ) ; String namespace = parser . getNamespace ( ) ; switch ( namespace ) { case StreamError . NAMESPACE : switch ( name ) { case "text" : descriptiveTexts = parseDescriptiveTexts ( parser , descriptiveTexts ) ; break ; default : // If it ' s not a text element , that is qualified by the StreamError . NAMESPACE ,
// then it has to be the stream error code
condition = StreamError . Condition . fromString ( name ) ; if ( ! parser . isEmptyElementTag ( ) ) { conditionText = parser . nextText ( ) ; } break ; } break ; default : PacketParserUtils . addExtensionElement ( extensions , parser , name , namespace , streamErrorXmlEnvironment ) ; break ; } break ; case XmlPullParser . END_TAG : if ( parser . getDepth ( ) == initialDepth ) { break outerloop ; } break ; } } return new StreamError ( condition , conditionText , descriptiveTexts , extensions ) ; |
public class StorePackageImpl { /** * < ! - - begin - user - doc - - >
* < ! - - end - user - doc - - >
* @ generated */
@ Override public EClass getServerSettings ( ) { } } | if ( serverSettingsEClass == null ) { serverSettingsEClass = ( EClass ) EPackage . Registry . INSTANCE . getEPackage ( StorePackage . eNS_URI ) . getEClassifiers ( ) . get ( 9 ) ; } return serverSettingsEClass ; |
public class TypeCheck { /** * Checks enum aliases .
* < p > We verify that the enum element type of the enum used for initialization is a subtype of the
* enum element type of the enum the value is being copied in .
* < p > Example :
* < pre > var myEnum = myOtherEnum ; < / pre >
* < p > Enum aliases are irregular , so we need special code for this : (
* @ param valueType the type of the value used for initialization of the enum
* @ param nodeToWarn the node on which to issue warnings on */
private void checkEnumAlias ( NodeTraversal t , JSDocInfo declInfo , JSType valueType , Node nodeToWarn ) { } } | if ( declInfo == null || ! declInfo . hasEnumParameterType ( ) ) { return ; } if ( ! valueType . isEnumType ( ) ) { return ; } EnumType valueEnumType = valueType . toMaybeEnumType ( ) ; JSType valueEnumPrimitiveType = valueEnumType . getElementsType ( ) . getPrimitiveType ( ) ; validator . expectCanAssignTo ( nodeToWarn , valueEnumPrimitiveType , declInfo . getEnumParameterType ( ) . evaluate ( t . getTypedScope ( ) , typeRegistry ) , "incompatible enum element types" ) ; |
public class Hyperalgo { /** * Computes the adjoints of the hyperedge weights .
* INPUT : scores . alpha , scores . beta , scores . alphaAdj , scores . betaAdj .
* OUTPUT : scores . weightsAdj .
* @ param graph The hypergraph
* @ param w The potential function .
* @ param s The semiring .
* @ param scores Input and output struct . */
private static void weightAdjoint ( final Hypergraph graph , final Hyperpotential w , final Algebra s , final Scores scores , boolean backOutside ) { } } | final double [ ] weightAdj = new double [ graph . getNumEdges ( ) ] ; HyperedgeDoubleFn lambda = new HyperedgeDoubleFn ( ) { public void apply ( Hyperedge e , double val ) { weightAdj [ e . getId ( ) ] = val ; } } ; weightAdjoint ( graph , w , s , scores , lambda , backOutside ) ; scores . weightAdj = weightAdj ; |
public class AbstractAmazonSNSAsync { /** * Simplified method form for invoking the GetSubscriptionAttributes operation with an AsyncHandler .
* @ see # getSubscriptionAttributesAsync ( GetSubscriptionAttributesRequest , com . amazonaws . handlers . AsyncHandler ) */
@ Override public java . util . concurrent . Future < GetSubscriptionAttributesResult > getSubscriptionAttributesAsync ( String subscriptionArn , com . amazonaws . handlers . AsyncHandler < GetSubscriptionAttributesRequest , GetSubscriptionAttributesResult > asyncHandler ) { } } | return getSubscriptionAttributesAsync ( new GetSubscriptionAttributesRequest ( ) . withSubscriptionArn ( subscriptionArn ) , asyncHandler ) ; |
public class Searcher { /** * Checks if there is any match for the given pattern if search starts from the given element .
* @ param p pattern to search for
* @ param ele element to start from
* @ return true if there is a match */
public boolean hasSolution ( Pattern p , BioPAXElement ... ele ) { } } | Match m = new Match ( p . size ( ) ) ; for ( int i = 0 ; i < ele . length ; i ++ ) { m . set ( ele [ i ] , i ) ; } return ! search ( m , p ) . isEmpty ( ) ; |
public class AWSFMSClient { /** * Returns detailed compliance information about the specified member account . Details include resources that are in
* and out of compliance with the specified policy . Resources are considered non - compliant if the specified policy
* has not been applied to them .
* @ param getComplianceDetailRequest
* @ return Result of the GetComplianceDetail operation returned by the service .
* @ throws ResourceNotFoundException
* The specified resource was not found .
* @ throws InternalErrorException
* The operation failed because of a system problem , even though the request was valid . Retry your request .
* @ sample AWSFMS . GetComplianceDetail
* @ see < a href = " http : / / docs . aws . amazon . com / goto / WebAPI / fms - 2018-01-01 / GetComplianceDetail " target = " _ top " > AWS API
* Documentation < / a > */
@ Override public GetComplianceDetailResult getComplianceDetail ( GetComplianceDetailRequest request ) { } } | request = beforeClientExecution ( request ) ; return executeGetComplianceDetail ( request ) ; |
public class WindowStateSettingsStAXComponent { /** * / * ( non - Javadoc )
* @ see org . apereo . portal . rendering . PipelineComponent # getEventReader ( javax . servlet . http . HttpServletRequest , javax . servlet . http . HttpServletResponse ) */
@ Override public PipelineEventReader < XMLEventReader , XMLEvent > getEventReader ( HttpServletRequest request , HttpServletResponse response ) { } } | final PipelineEventReader < XMLEventReader , XMLEvent > pipelineEventReader = this . wrappedComponent . getEventReader ( request , response ) ; final XMLEventReader eventReader = pipelineEventReader . getEventReader ( ) ; final IStylesheetDescriptor stylesheetDescriptor = stylesheetAttributeSource . getStylesheetDescriptor ( request ) ; final IPortalRequestInfo portalRequestInfo = this . urlSyntaxProvider . getPortalRequestInfo ( request ) ; final XMLEventReader filteredEventReader ; if ( portalRequestInfo . getTargetedPortletWindowId ( ) == null ) { final IStylesheetParameterDescriptor defaultWindowStateParam = stylesheetDescriptor . getStylesheetParameterDescriptor ( "dashboardForcedWindowState" ) ; if ( defaultWindowStateParam != null ) { // Set all window states to the specified default
final WindowState windowState = PortletUtils . getWindowState ( defaultWindowStateParam . getDefaultValue ( ) ) ; filteredEventReader = new SinglePortletWindowStateSettingXMLEventReader ( request , eventReader , windowState ) ; } else { // Make sure there aren ' t any portlets in a " targeted " window state
filteredEventReader = new NonTargetedPortletWindowStateSettingXMLEventReader ( request , eventReader ) ; } } else { // Not mobile , don ' t bother filtering
filteredEventReader = eventReader ; } final Map < String , String > outputProperties = pipelineEventReader . getOutputProperties ( ) ; return new PipelineEventReaderImpl < XMLEventReader , XMLEvent > ( filteredEventReader , outputProperties ) ; |
public class UIComponentClassicTagBase { /** * Appends a counter to the passed in < code > id < / code > and stores the
* < code > id < / code > and counter information in request scope .
* @ return String < code > id < / code > with a counter appended to it . */
private String generateIncrementedId ( String componentId ) { } } | Integer serialNum = ( Integer ) context . getAttributes ( ) . get ( componentId ) ; if ( null == serialNum ) { serialNum = 1 ; } else { serialNum = serialNum . intValue ( ) + 1 ; } context . getAttributes ( ) . put ( componentId , serialNum ) ; componentId = componentId + UNIQUE_ID_PREFIX + serialNum . intValue ( ) ; return componentId ; |
public class URLUtils { /** * We can make this tighter but IPAddressUtil is in a sun package sadly */
public static boolean hasLiteralIPAddress ( URI resource ) { } } | String host = resource . getHost ( ) ; if ( host == null || host . isEmpty ( ) ) { return false ; } // basic check for a ' . ' - separated numeric string for now
return host . matches ( "([0-9A-Fa-f]|\\.){4,16}" ) ; |
public class BoneCPDataSource { /** * { @ inheritDoc }
* @ see javax . sql . DataSource # getConnection ( ) */
public Connection getConnection ( ) throws SQLException { } } | FinalWrapper < BoneCP > wrapper = this . pool ; if ( wrapper == null ) { synchronized ( this ) { if ( this . pool == null ) { try { if ( this . getDriverClass ( ) != null ) { loadClass ( this . getDriverClass ( ) ) ; } logger . debug ( this . toString ( ) ) ; this . pool = new FinalWrapper < BoneCP > ( new BoneCP ( this ) ) ; } catch ( ClassNotFoundException e ) { throw new SQLException ( PoolUtil . stringifyException ( e ) ) ; } } wrapper = this . pool ; } } return wrapper . value . getConnection ( ) ; |
public class InterceptorComponent { /** * Utility method for replacing an individual interceptor within an existing chain .
* @ param match the type of the interceptor to be replaced .
* @ param replacement the new interceptor to be used as a replacement .
* @ param chain the existing interceptor chain in which the replacement will take place .
* @ return the modified interceptor chain . If no match was found , the existing interceptor chain is returned
* unchanged . */
public static InterceptorComponent replaceInterceptor ( final Class match , final InterceptorComponent replacement , final InterceptorComponent chain ) { } } | if ( chain == null ) { return null ; } InterceptorComponent current = chain ; InterceptorComponent previous = null ; InterceptorComponent updatedChain = null ; while ( updatedChain == null ) { if ( match . isInstance ( current ) ) { // Found the interceptor that needs to be replaced .
replacement . setBackingComponent ( current . getBackingComponent ( ) ) ; if ( previous == null ) { updatedChain = replacement ; } else { previous . setBackingComponent ( replacement ) ; updatedChain = chain ; } } else { previous = current ; WebComponent next = current . getBackingComponent ( ) ; if ( next instanceof InterceptorComponent ) { current = ( InterceptorComponent ) next ; } else { // Reached the end of the chain . No replacement done .
updatedChain = chain ; } } } return updatedChain ; |
public class CmsRequestContext { /** * Gets the value of an attribute from the OpenCms request context attribute list . < p >
* @ param attributeName the attribute name
* @ return Object the attribute value , or < code > null < / code > if the attribute was not found */
public Object getAttribute ( String attributeName ) { } } | if ( m_attributeMap == null ) { return null ; } return m_attributeMap . get ( attributeName ) ; |
public class CSSColorHelper { /** * Check if the passed string is any color value .
* @ param sValue
* The value to check . May be < code > null < / code > .
* @ return < code > true < / code > if the passed value is not < code > null < / code > , not
* empty and a valid CSS color value .
* @ see # isRGBColorValue ( String )
* @ see # isRGBAColorValue ( String )
* @ see # isHSLColorValue ( String )
* @ see # isHSLAColorValue ( String )
* @ see # isHexColorValue ( String )
* @ see ECSSColor # isDefaultColorName ( String )
* @ see ECSSColorName # isDefaultColorName ( String )
* @ see CCSSValue # CURRENTCOLOR */
public static boolean isColorValue ( @ Nullable final String sValue ) { } } | final String sRealValue = StringHelper . trim ( sValue ) ; if ( StringHelper . hasNoText ( sRealValue ) ) return false ; return isRGBColorValue ( sRealValue ) || isRGBAColorValue ( sRealValue ) || isHSLColorValue ( sRealValue ) || isHSLAColorValue ( sRealValue ) || isHexColorValue ( sRealValue ) || ECSSColor . isDefaultColorName ( sRealValue ) || ECSSColorName . isDefaultColorName ( sRealValue ) || sRealValue . equals ( CCSSValue . CURRENTCOLOR ) || sRealValue . equals ( CCSSValue . TRANSPARENT ) ; |
public class SipSessionImpl { /** * check if the ack has been received for the cseq in param
* it may happen that the ackReceived has been removed already if that ' s the case it will return true
* @ param cSeq CSeq number to check if the ack has already been received
* @ return */
protected boolean isAckReceived ( long cSeq ) { } } | if ( acksReceived == null ) { // http : / / code . google . com / p / sipservlets / issues / detail ? id = 152
// if there is no map , it means that the session was already destroyed and it is a retransmission
return true ; } Boolean ackReceived = acksReceived . get ( cSeq ) ; if ( logger . isDebugEnabled ( ) ) { logger . debug ( "isAckReceived for CSeq " + cSeq + " : " + ackReceived ) ; } if ( ackReceived == null ) { // if there is no value for it it means that it is a retransmission
return true ; } return ackReceived ; |
public class ProxyGeneratorAmp { /** * T foo ( X a1 , Y a2)
* new AmpQueryMessageActorCompletion ( _ _ caucho _ getCurrentContext ( ) ,
* cont ,
* timeout ,
* _ methodRef ,
* new Object [ ] { a1 , a2 } ) . send ( ) ; */
private void createQueryFutureMethod ( JavaClass jClass , Method method ) { } } | Class < ? > [ ] parameterTypes = method . getParameterTypes ( ) ; Annotation [ ] [ ] parameterAnns = method . getParameterAnnotations ( ) ; int paramLength = parameterTypes . length ; addMethod ( method ) ; CodeWriterAttribute code = createMethodHeader ( jClass , method ) ; code . setMaxLocals ( 1 + 2 * parameterTypes . length ) ; code . setMaxStack ( 10 + 2 * parameterTypes . length ) ; code . pushObjectVar ( 0 ) ; code . getField ( jClass . getThisClass ( ) , "_messageFactory" , MessageFactoryAmp . class ) ; // code . pushObjectVar ( getLength ( parameterTypes , resultOffset ) + 1 ) ;
Timeout timeoutAnn = method . getAnnotation ( Timeout . class ) ; if ( timeoutAnn != null ) { long timeout = timeoutAnn . unit ( ) . toMillis ( timeoutAnn . value ( ) ) ; code . pushConstant ( timeout ) ; } code . pushObjectVar ( 0 ) ; code . getField ( jClass . getThisClass ( ) , "_serviceRef" , ServiceRefAmp . class ) ; code . pushObjectVar ( 0 ) ; code . getField ( jClass . getThisClass ( ) , fieldName ( method ) , MethodAmp . class ) ; partitionMethod ( code , parameterTypes , parameterAnns ) ; pushParameters ( code , parameterTypes , parameterAnns , 1 , 0 , paramLength , - 1 ) ; if ( timeoutAnn != null ) { code . invokeInterface ( MessageFactoryAmp . class , "queryFuture" , Object . class , // QueryWithResultMessage . class ,
long . class , ServiceRefAmp . class , MethodAmp . class , Object [ ] . class ) ; } else { code . invokeInterface ( MessageFactoryAmp . class , "queryFuture" , Object . class , // QueryWithResultMessage . class ,
ServiceRefAmp . class , MethodAmp . class , Object [ ] . class ) ; } popReturn ( code , method . getReturnType ( ) ) ; code . close ( ) ; |
public class BaseDestinationHandler { /** * Takes a pseudo destination name of the form
* ' meUuid # # subscriptionName '
* and returns a String of the form ' subscriptionName '
* @ param pseudoDestinationName */
public String getSubNameFromPseudoDestination ( String pseudoDestinationName ) { } } | if ( TraceComponent . isAnyTracingEnabled ( ) && tc . isEntryEnabled ( ) ) SibTr . entry ( tc , "getSubNameFromPseudoDestination" , pseudoDestinationName ) ; String strippedSubName = pseudoDestinationName . substring ( pseudoDestinationName . indexOf ( "##" ) + 2 ) ; if ( TraceComponent . isAnyTracingEnabled ( ) && tc . isEntryEnabled ( ) ) SibTr . exit ( tc , "getSubNameFromPseudoDestination" , strippedSubName ) ; return strippedSubName ; |
public class DateUtil { /** * 获取指定日期的指定格式的字符串 , 指定时区
* @ param format 日期格式
* @ param date 指定日期
* @ param zoneId 时区ID , 例如GMT
* @ return 指定日期的指定格式的字符串 */
public static String getFormatDate ( String format , Date date , String zoneId ) { } } | DateTimeFormatter dateTimeFormatter = DateTimeFormatter . ofPattern ( format ) ; return dateTimeFormatter . format ( date . toInstant ( ) . atZone ( ZoneId . of ( zoneId ) ) . toLocalDateTime ( ) ) ; |
public class BasicPasswordCredentials { /** * Converts to credentials for use in Grgit .
* @ return { @ code null } if both username and password are { @ code null } ,
* otherwise returns credentials in Grgit format . */
public Credentials toGrgit ( ) { } } | if ( username != null && password != null ) { return new Credentials ( username , password ) ; } else { return null ; } |
public class ListPhrase { /** * Entry point into this API .
* @ param separator separator for all elements */
public static ListPhrase from ( @ NonNull CharSequence separator ) { } } | checkNotNull ( "separator" , separator ) ; return ListPhrase . from ( separator , separator , separator ) ; |
public class PluginInstanceGenerator { /** * Instantiates a plugin implementation and initializes it . The configuration class is introspected from
* the instance type . The config parameter should be a JSON map - model of the configuration object ; this will
* be converted to the configuration class . If the plugin does not require any configuration then use { @ link Void }
* as the configuration class . In this case the configuration object passed to init ( ) will always be null .
* There are two pre - requisites for this method to work correctly . First , the initialization class must have a
* publicly - available no - argument constructor , otherwise it will fail to create an instance .
* Second , there are certain cases where introspecting the configuration class won ' t work , notably when the
* implementation class indirectly declares the configuration class . For the most part this is uncommon and easily
* refactored . For example Sample1 ' s configuration class from the following example will be successfully
* introspected :
* < code >
* public class Sample1 implements ServerStartedListener < ConfigurationType > {
* < / code >
* Sample2 ' s configuration class from the following example will fail to be introspected :
* < code >
* public class BaseImplementation < T > implements ServerStartedListener < T > {
* public class Sample2 < ConfigurationType > extends BaseImplementation {
* < / code > */
@ SuppressWarnings ( { } } | "unchecked" , "ConstantConditions" } ) public static < T extends Plugin > T generateInstance ( String className , Class < T > instanceType , Map < String , Object > config , Environment environment , PluginServerMetadata metadata ) { try { checkNotNull ( className , "className" ) ; checkNotNull ( instanceType , "instanceType" ) ; // Verify the class exists
Class < ? > clazz = Class . forName ( className ) ; // Verify the instance ' s class implements the required interface .
checkArgument ( instanceType . isAssignableFrom ( clazz ) , "Class {} does not implement or extend {}" , clazz , instanceType ) ; // Locate the Plugin configuration type .
Class < ? > configClass = null ; Class < ? > c = clazz ; do { for ( Type type : c . getGenericInterfaces ( ) ) { if ( type instanceof ParameterizedType && ( ( ParameterizedType ) type ) . getRawType ( ) . equals ( instanceType ) ) { Type [ ] actualTypes = ( ( ParameterizedType ) type ) . getActualTypeArguments ( ) ; if ( actualTypes . length == 1 ) { // Sanity check ; should always be true
Type actualType = actualTypes [ 0 ] ; if ( actualType instanceof ParameterizedType ) { configClass = ( Class < ? > ) ( ( ParameterizedType ) actualType ) . getRawType ( ) ; } else { configClass = ( Class < ? > ) actualType ; } } } } c = c . getSuperclass ( ) ; } while ( configClass == null ) ; // Attempt to create an instance using a no - argument constructor
T instance = ( T ) clazz . newInstance ( ) ; // Get the initialization method .
Method init = clazz . getMethod ( "init" , Environment . class , PluginServerMetadata . class , configClass ) ; Object configImpl = null ; if ( ! configClass . equals ( Void . class ) ) { // Determine the type for the configuration class
final Type type = init . getGenericParameterTypes ( ) [ 2 ] ; // Use Jackson to convert the configuration map to type
configImpl = JsonHelper . convert ( config , new TypeReference < Object > ( ) { @ Override public Type getType ( ) { return type ; } } ) ; } // Initialize the instance
instance . init ( environment , metadata , configImpl ) ; return instance ; } catch ( Throwable t ) { throw Throwables . propagate ( t ) ; } |
public class Props { /** * Gets the string from the Props . If it doesn ' t exist , throw and UndefinedPropertiesException */
public String getString ( final String key ) { } } | if ( containsKey ( key ) ) { return get ( key ) ; } else { throw new UndefinedPropertyException ( "Missing required property '" + key + "'" ) ; } |
public class TitlePaneMenuButtonPainter { /** * Create the mark border shape .
* @ param width the width .
* @ param height the height .
* @ return the shape of the mark border . */
private Shape decodeMarkBorder ( int width , int height ) { } } | double left = width / 2.0 - 4 ; double top = height / 2.0 - 4 ; path . reset ( ) ; path . moveTo ( left + 0 , top + 0 ) ; path . lineTo ( left + 8 , top ) ; path . lineTo ( left + 4 , top + 6 ) ; path . closePath ( ) ; return path ; |
public class ContentUriChecker { /** * Prepare uri .
* @ param input the input
* @ return the pair */
private Pair < ParserRuleContext , CommonTokenStream > prepareUri ( final String input ) { } } | UriLexer lexer = new UriLexer ( CharStreams . fromString ( input ) ) ; CommonTokenStream tokens = new CommonTokenStream ( lexer ) ; UriParser parser = new UriParser ( tokens ) ; parser . removeErrorListeners ( ) ; parser . addErrorListener ( new ContentUriBaseErrorListener ( ) { @ Override public void syntaxError ( Recognizer < ? , ? > recognizer , Object offendingSymbol , int line , int charPositionInLine , String msg , RecognitionException e ) { AssertKripton . assertTrue ( false , "unespected char at pos %s of URI '%s'" , charPositionInLine , input ) ; } @ Override public void reportAmbiguity ( Parser recognizer , DFA dfa , int startIndex , int stopIndex , boolean exact , BitSet ambigAlts , ATNConfigSet configs ) { AssertKripton . assertTrue ( false , "ambiguity syntax at pos %s of URI '%s'" , startIndex , input ) ; } @ Override public void reportAttemptingFullContext ( Parser recognizer , DFA dfa , int startIndex , int stopIndex , BitSet conflictingAlts , ATNConfigSet configs ) { AssertKripton . assertTrue ( false , "error at pos %s of URI '%s'" , startIndex , input ) ; } @ Override public void reportContextSensitivity ( Parser recognizer , DFA dfa , int startIndex , int stopIndex , int prediction , ATNConfigSet configs ) { AssertKripton . assertTrue ( false , "context eror at pos %s of URI '%s'" , startIndex , input ) ; } } ) ; ParserRuleContext context = parser . uri ( ) ; return new Pair < > ( context , tokens ) ; |
public class ComplexImg { /** * Calculates , stores and returns the power at the specified index .
* The power is the squared magnitude of the complex number ( cmplx = a + bi power = a * a + b * b ) .
* Subsequent calls to e . g . { @ link # getValueP _ atIndex ( int ) } will return the stored result .
* @ param idx index
* @ return power of pixel at index */
public double computePower ( int idx ) { } } | double r = real [ idx ] ; double i = imag [ idx ] ; power [ idx ] = r * r + i * i ; return power [ idx ] ; |
public class DateGapAnalyzerResultSwingRenderer { /** * A main method that will display the results of a few example value
* distributions . Useful for tweaking the charts and UI .
* @ param args
* @ throws Throwable */
public static void main ( final String [ ] args ) throws Throwable { } } | LookAndFeelManager . get ( ) . init ( ) ; final Injector injector = Guice . createInjector ( new DCModuleImpl ( VFSUtils . getFileSystemManager ( ) . resolveFile ( "." ) , null ) ) ; // run a small job
final AnalysisJobBuilder ajb = injector . getInstance ( AnalysisJobBuilder . class ) ; final Datastore ds = injector . getInstance ( DatastoreCatalog . class ) . getDatastore ( "orderdb" ) ; ajb . setDatastore ( ds ) ; final DataCleanerConfiguration conf = injector . getInstance ( DataCleanerConfiguration . class ) ; final AnalysisRunner runner = new AnalysisRunnerImpl ( conf ) ; final DatastoreConnection con = ds . openConnection ( ) ; final Table table = con . getSchemaNavigator ( ) . convertToTable ( "PUBLIC.ORDERS" ) ; ajb . addSourceColumn ( table . getColumnByName ( "ORDERDATE" ) ) ; ajb . addSourceColumn ( table . getColumnByName ( "SHIPPEDDATE" ) ) ; ajb . addSourceColumn ( table . getColumnByName ( "CUSTOMERNUMBER" ) ) ; @ SuppressWarnings ( "unchecked" ) final InputColumn < Date > orderDateColumn = ( InputColumn < Date > ) ajb . getSourceColumnByName ( "ORDERDATE" ) ; @ SuppressWarnings ( "unchecked" ) final InputColumn < Date > shippedDateColumn = ( InputColumn < Date > ) ajb . getSourceColumnByName ( "SHIPPEDDATE" ) ; @ SuppressWarnings ( "unchecked" ) final InputColumn < Integer > customerNumberColumn = ( InputColumn < Integer > ) ajb . getSourceColumnByName ( "CUSTOMERNUMBER" ) ; @ SuppressWarnings ( "unchecked" ) final MutableInputColumn < String > customerNumberAsStringColumn = ( MutableInputColumn < String > ) ajb . addTransformer ( ConvertToStringTransformer . class ) . addInputColumn ( customerNumberColumn ) . getOutputColumns ( ) . get ( 0 ) ; final DateGapAnalyzer dga = ajb . addAnalyzer ( DateGapAnalyzer . class ) . getComponentInstance ( ) ; dga . setFromColumn ( orderDateColumn ) ; dga . setToColumn ( shippedDateColumn ) ; dga . setGroupColumn ( customerNumberAsStringColumn ) ; final AnalysisResultFuture resultFuture = runner . run ( ajb . toAnalysisJob ( ) ) ; if ( resultFuture . isErrornous ( ) ) { throw resultFuture . getErrors ( ) . get ( 0 ) ; } final List < AnalyzerResult > list = Collections . emptyList ( ) ; final RendererFactory rendererFactory = new RendererFactory ( conf ) ; final DetailsResultWindow window = new DetailsResultWindow ( "Example" , list , injector . getInstance ( WindowContext . class ) , rendererFactory ) ; window . setDefaultCloseOperation ( JFrame . EXIT_ON_CLOSE ) ; final List < AnalyzerResult > results = resultFuture . getResults ( ) ; for ( final AnalyzerResult analyzerResult : results ) { final JComponent renderedResult = new DateGapAnalyzerResultSwingRenderer ( ) . render ( ( DateGapAnalyzerResult ) analyzerResult ) ; window . addRenderedResult ( renderedResult ) ; } window . repaint ( ) ; window . setPreferredSize ( new Dimension ( 800 , 600 ) ) ; window . setVisible ( true ) ; |
public class JSONObject { /** * Get the JSONObject value associated with a key .
* @ param key A key string .
* @ return A JSONObject which is the value .
* @ throws JSONException if the key is not found or if the value is not a
* JSONObject . */
public JSONObject getJSONObject ( String key ) { } } | verifyIsNull ( ) ; Object o = get ( key ) ; if ( JSONNull . getInstance ( ) . equals ( o ) ) { return new JSONObject ( true ) ; } else if ( o instanceof JSONObject ) { return ( JSONObject ) o ; } throw new JSONException ( "JSONObject[" + JSONUtils . quote ( key ) + "] is not a JSONObject." ) ; |
public class GMeans { /** * Calculates the Anderson - Darling statistic for one - dimensional normality test .
* @ param x the samples to test if drawn from a Gaussian distribution . */
private static double AndersonDarling ( double [ ] x ) { } } | int n = x . length ; Arrays . sort ( x ) ; for ( int i = 0 ; i < n ; i ++ ) { x [ i ] = GaussianDistribution . getInstance ( ) . cdf ( x [ i ] ) ; // in case overflow when taking log later .
if ( x [ i ] == 0 ) x [ i ] = 0.0000001 ; if ( x [ i ] == 1 ) x [ i ] = 0.9999999 ; } double A = 0.0 ; for ( int i = 0 ; i < n ; i ++ ) { A -= ( 2 * i + 1 ) * ( Math . log ( x [ i ] ) + Math . log ( 1 - x [ n - i - 1 ] ) ) ; } A = A / n - n ; A *= ( 1 + 4.0 / n - 25.0 / ( n * n ) ) ; return A ; |
public class DescriptionResolver { /** * Thanks to http : / / stackoverflow . com / a / 37962230/19219 */
public String resolve ( String expression ) { } } | if ( isEmpty ( expression ) ) { return expression ; } // Check if the expression is already been parsed
if ( cache . containsKey ( expression ) ) { return cache . get ( expression ) ; } // If the expression does not start with $ , then no need to do PATTERN
if ( ! expression . startsWith ( "$" ) ) { // Add to the mapping with key and value as expression
cache . put ( expression , expression ) ; // If no match , then return the expression as it is
return expression ; } // Create the matcher
Matcher matcher = PATTERN . matcher ( expression ) ; // If the matching is there , then add it to the map and return the value
if ( matcher . find ( ) ) { // Store the value
String key = matcher . group ( 1 ) ; // Get the value
String value = environment . getProperty ( key ) ; // Store the value in the setting
if ( value != null ) { // Store in the map
cache . put ( expression , value ) ; // return the value
return value ; } } // Add to the mapping with key and value as expression
cache . put ( expression , expression ) ; // If no match , then return the expression as it is
return expression ; |
public class ListClustersRequestMarshaller { /** * Marshall the given parameter object . */
public void marshall ( ListClustersRequest listClustersRequest , ProtocolMarshaller protocolMarshaller ) { } } | if ( listClustersRequest == null ) { throw new SdkClientException ( "Invalid argument passed to marshall(...)" ) ; } try { protocolMarshaller . marshall ( listClustersRequest . getCreatedAfter ( ) , CREATEDAFTER_BINDING ) ; protocolMarshaller . marshall ( listClustersRequest . getCreatedBefore ( ) , CREATEDBEFORE_BINDING ) ; protocolMarshaller . marshall ( listClustersRequest . getClusterStates ( ) , CLUSTERSTATES_BINDING ) ; protocolMarshaller . marshall ( listClustersRequest . getMarker ( ) , MARKER_BINDING ) ; } catch ( Exception e ) { throw new SdkClientException ( "Unable to marshall request to JSON: " + e . getMessage ( ) , e ) ; } |
public class AWSSimpleSystemsManagementClient { /** * Runs commands on one or more managed instances .
* @ param sendCommandRequest
* @ return Result of the SendCommand operation returned by the service .
* @ throws DuplicateInstanceIdException
* You cannot specify an instance ID in more than one association .
* @ throws InternalServerErrorException
* An error occurred on the server side .
* @ throws InvalidInstanceIdException
* The following problems can cause this exception : < / p >
* You do not have permission to access the instance .
* SSM Agent is not running . On managed instances and Linux instances , verify that the SSM Agent is running .
* On EC2 Windows instances , verify that the EC2Config service is running .
* SSM Agent or EC2Config service is not registered to the SSM endpoint . Try reinstalling SSM Agent or
* EC2Config service .
* The instance is not in valid state . Valid states are : Running , Pending , Stopped , Stopping . Invalid states
* are : Shutting - down and Terminated .
* @ throws InvalidDocumentException
* The specified document does not exist .
* @ throws InvalidDocumentVersionException
* The document version is not valid or does not exist .
* @ throws InvalidOutputFolderException
* The S3 bucket does not exist .
* @ throws InvalidParametersException
* You must specify values for all required parameters in the Systems Manager document . You can only supply
* values to parameters defined in the Systems Manager document .
* @ throws UnsupportedPlatformTypeException
* The document does not support the platform type of the given instance ID ( s ) . For example , you sent an
* document for a Windows instance to a Linux instance .
* @ throws MaxDocumentSizeExceededException
* The size limit of a document is 64 KB .
* @ throws InvalidRoleException
* The role name can ' t contain invalid characters . Also verify that you specified an IAM role for
* notifications that includes the required trust policy . For information about configuring the IAM role for
* Run Command notifications , see < a
* href = " http : / / docs . aws . amazon . com / systems - manager / latest / userguide / rc - sns - notifications . html " > Configuring
* Amazon SNS Notifications for Run Command < / a > in the < i > AWS Systems Manager User Guide < / i > .
* @ throws InvalidNotificationConfigException
* One or more configuration items is not valid . Verify that a valid Amazon Resource Name ( ARN ) was provided
* for an Amazon SNS topic .
* @ sample AWSSimpleSystemsManagement . SendCommand
* @ see < a href = " http : / / docs . aws . amazon . com / goto / WebAPI / ssm - 2014-11-06 / SendCommand " target = " _ top " > AWS API
* Documentation < / a > */
@ Override public SendCommandResult sendCommand ( SendCommandRequest request ) { } } | request = beforeClientExecution ( request ) ; return executeSendCommand ( request ) ; |
public class Condition { /** * Checks HTTP method , URI and enables AutoDiscovery */
private static ConditionWithApplicables methodWithUriAndAutoDiscovery ( final Method m , String uri ) { } } | try { final URL resource = new SmartDiscoverer ( "restito" ) . discoverResource ( m , uri ) ; return new ConditionWithApplicables ( composite ( method ( m ) , uri ( uri ) ) , resourceContent ( resource ) ) ; } catch ( IllegalArgumentException e ) { logger . debug ( "Can not auto-discover resource for URI [{}]" , uri ) ; } return new ConditionWithApplicables ( composite ( method ( m ) , uri ( uri ) ) , Action . noop ( ) ) ; |
public class GenericResponseResourceTransformer { /** * Transforms the given interface , creating a duplicate interface with return types
* { @ link GenericResponse } replaced with { @ link Response } . */
< T > Class < ? > transform ( Class < T > proxyInterface ) { } } | try { String packageName = proxyInterface . getPackage ( ) . getName ( ) ; String genericProxyInterfaceName = packageName + "." + PROXY_PREFIX + proxyInterface . getSimpleName ( ) ; try { return Class . forName ( genericProxyInterfaceName ) ; } catch ( ClassNotFoundException e ) { pool . insertClassPath ( new ClassClassPath ( proxyInterface ) ) ; CtClass copy = pool . getAndRename ( proxyInterface . getName ( ) , genericProxyInterfaceName ) ; replaceGenericResponseMethods ( copy ) ; return copy . toClass ( this . getClass ( ) . getClassLoader ( ) , this . getClass ( ) . getProtectionDomain ( ) ) ; } } catch ( NotFoundException e ) { throw new RuntimeException ( e ) ; } catch ( CannotCompileException e ) { throw new RuntimeException ( e ) ; } catch ( BadBytecode e ) { throw new RuntimeException ( e ) ; } |
public class BreakpointMessageHandler2 { /** * Do not call if in { @ link Mode # safe } .
* @ param aMessage
* @ param onlyIfInScope
* @ return False if message should be dropped . */
public boolean handleMessageReceivedFromClient ( Message aMessage , boolean onlyIfInScope ) { } } | if ( ! isBreakpoint ( aMessage , true , onlyIfInScope ) ) { return true ; } // Do this outside of the semaphore loop so that the ' continue ' button can apply to all queued break points
// but be reset when the next break point is hit
breakMgmt . breakpointHit ( ) ; BreakEventPublisher . getPublisher ( ) . publishHitEvent ( aMessage ) ; synchronized ( SEMAPHORE ) { if ( breakMgmt . isHoldMessage ( aMessage ) ) { BreakEventPublisher . getPublisher ( ) . publishActiveEvent ( aMessage ) ; setBreakDisplay ( aMessage , true ) ; waitUntilContinue ( aMessage , true ) ; BreakEventPublisher . getPublisher ( ) . publishInactiveEvent ( aMessage ) ; } } breakMgmt . clearAndDisableRequest ( ) ; return ! breakMgmt . isToBeDropped ( ) ; |
public class BaseController { /** * OK : 列表数据
* @ param value
* @ param totalCount
* @ param < T >
* @ return */
protected < T > JsonObjectBase buildListSuccess ( List < ? > value , int totalCount ) { } } | return JsonObjectUtils . buildListSuccess ( value , totalCount , null ) ; |
public class CommerceTierPriceEntryUtil { /** * Returns the commerce tier price entry where uuid = & # 63 ; and groupId = & # 63 ; or returns < code > null < / code > if it could not be found , optionally using the finder cache .
* @ param uuid the uuid
* @ param groupId the group ID
* @ param retrieveFromCache whether to retrieve from the finder cache
* @ return the matching commerce tier price entry , or < code > null < / code > if a matching commerce tier price entry could not be found */
public static CommerceTierPriceEntry fetchByUUID_G ( String uuid , long groupId , boolean retrieveFromCache ) { } } | return getPersistence ( ) . fetchByUUID_G ( uuid , groupId , retrieveFromCache ) ; |
public class JobDriver { /** * Run the test with this method .
* @ param input input { @ link String } { @ link List } or { @ link Record } { @ link List }
* @ param output result of { @ link Record } { @ link List }
* @ param stdout whether to output the execution results to stdout .
* @ throws InstantiationException
* @ throws IllegalAccessException
* @ throws ClassNotFoundException
* @ throws IOException
* @ throws URISyntaxException */
@ SuppressWarnings ( { } } | "unchecked" , "rawtypes" } ) public void run ( List < ? > input , List < Record > output , boolean stdout ) throws InstantiationException , IllegalAccessException , ClassNotFoundException , IOException , URISyntaxException { if ( input == null || input . isEmpty ( ) ) { fail ( "input is empty" ) ; } List < Pair < WritableComparable , Writable > > actual = null ; Object o = input . get ( 0 ) ; if ( o instanceof String ) { actual = runString ( ( List < String > ) input ) ; } else if ( o instanceof Record ) { actual = runRecord ( ( List < Record > ) input ) ; } else { fail ( "input object is miss match" ) ; } if ( stdout ) { for ( Pair < WritableComparable , Writable > pair : actual ) { System . out . println ( pair ) ; } } assertEquals ( output . size ( ) , actual . size ( ) ) ; if ( output != null ) { for ( int i = 0 ; i < output . size ( ) ; i ++ ) { Pair < WritableComparable , Writable > pair = actual . get ( i ) ; Record r = output . get ( i ) ; String s = String . format ( OUTPUT , r . getKey ( ) . toString ( ) , r . getValue ( ) . toString ( ) ) ; assertEquals ( s , pair . toString ( ) ) ; } } |
public class Script { /** * Add a VM or a node to the script .
* @ param el the element to add
* @ return { @ code true } if the was was added */
public boolean add ( BtrpElement el ) { } } | switch ( el . type ( ) ) { case VM : if ( ! this . vms . add ( ( VM ) el . getElement ( ) ) ) { return false ; } break ; case NODE : if ( ! this . nodes . add ( ( Node ) el . getElement ( ) ) ) { return false ; } break ; default : return false ; } return true ; |
public class JSONParserString { /** * use to return Primitive Type , or String , Or JsonObject or JsonArray
* generated by a ContainerFactory */
public Object parse ( String in ) throws ParseException { } } | return parse ( in , JSONValue . defaultReader . DEFAULT ) ; |
public class AbstractExtraLanguageGenerator { /** * Load a property file from the resources .
* This function is able to get the resource from an OSGi bundles if it is specified ,
* or from the application classpath .
* @ param filename the name of the resource , without the starting slash character .
* @ param bundledPlugin the plugin that is able to provide the bundle that contains the resources , or { @ code null }
* to use the application classpath .
* @ param readerClass the class that has called this function . It is used for obtaining the resource if
* the bundled plugin is not provided .
* @ param statusBuilder the builder of a status that takes the exception as parameter and creates a status object .
* This builder is used only if the { @ code bundledPlugin } is not { @ code null } .
* @ return the loaded resources . */
public static List < Pair < String , String > > loadPropertyFile ( String filename , Plugin bundledPlugin , Class < ? > readerClass , Function1 < IOException , IStatus > statusBuilder ) { } } | final URL url ; if ( bundledPlugin != null ) { url = FileLocator . find ( bundledPlugin . getBundle ( ) , Path . fromPortableString ( filename ) , null ) ; } else { url = readerClass . getClassLoader ( ) . getResource ( filename ) ; } if ( url == null ) { return Lists . newArrayList ( ) ; } final OrderedProperties properties = new OrderedProperties ( ) ; try ( InputStream is = url . openStream ( ) ) { properties . load ( is ) ; } catch ( IOException exception ) { if ( bundledPlugin != null ) { bundledPlugin . getLog ( ) . log ( statusBuilder . apply ( exception ) ) ; } else { throw new RuntimeException ( exception ) ; } } return properties . getOrderedProperties ( ) ; |
public class LazyMultiLoaderWithInclude { /** * Loads the specified ids . */
@ Override public < T > Lazy < Map < String , T > > load ( Class < T > clazz , String ... ids ) { } } | return _session . lazyLoadInternal ( clazz , ids , _includes . toArray ( new String [ 0 ] ) , null ) ; |
public class OcAgentNodeUtils { /** * Creates service info with the given service name . */
@ VisibleForTesting static ServiceInfo getServiceInfo ( String serviceName ) { } } | return ServiceInfo . newBuilder ( ) . setName ( serviceName ) . build ( ) ; |
public class AbstractSettings { /** * / * ( non - Javadoc )
* @ see nyla . solutions . core . util . Settings # getPropertyLong ( java . lang . Class , java . lang . String ) */
@ Override public Long getPropertyLong ( Class < ? > aClass , String key ) { } } | return getPropertyLong ( new StringBuilder ( aClass . getName ( ) ) . append ( "." ) . append ( key ) . toString ( ) ) ; |
public class FaxClientSpiFactory { /** * This function returns the internal logger for the fax4j framework .
* @ return The logger */
private static Logger getLogger ( ) { } } | if ( FaxClientSpiFactory . logger == null ) { synchronized ( FaxClientSpiFactory . class ) { if ( FaxClientSpiFactory . logger == null ) { // get logger manager
LoggerManager loggerManager = LoggerManager . getInstance ( ) ; // get logger
Logger localLogger = loggerManager . getLogger ( ) ; // print product info
localLogger . logDebug ( new Object [ ] { ProductInfo . getProductInfoPrintout ( ) } , null ) ; // keep reference
FaxClientSpiFactory . logger = localLogger ; } } } return FaxClientSpiFactory . logger ; |
public class OkCoinExchange { /** * Extract contract used by spec */
public static FuturesContract futuresContractOfConfig ( ExchangeSpecification exchangeSpecification ) { } } | FuturesContract contract ; if ( exchangeSpecification . getExchangeSpecificParameters ( ) . containsKey ( "Futures_Contract" ) ) { contract = ( FuturesContract ) exchangeSpecification . getExchangeSpecificParameters ( ) . get ( "Futures_Contract" ) ; } else if ( exchangeSpecification . getExchangeSpecificParameters ( ) . containsKey ( "Futures_Contract_String" ) ) { contract = FuturesContract . valueOfIgnoreCase ( FuturesContract . class , ( String ) exchangeSpecification . getExchangeSpecificParameters ( ) . get ( "Futures_Contract_String" ) ) ; } else { throw new RuntimeException ( "`Futures_Contract` or `Futures_Contract_String` not defined in exchange specific parameters." ) ; } return contract ; |
public class ReplayInputStream { /** * ( non - Javadoc )
* @ see java . io . InputStream # read ( byte [ ] , int , int ) */
public int read ( byte [ ] b , int off , int len ) throws IOException { } } | if ( position == size ) { return - 1 ; // EOF
} if ( position < buffer . length ) { int toCopy = ( int ) Math . min ( size - position , Math . min ( len , buffer . length - position ) ) ; System . arraycopy ( buffer , ( int ) position , b , off , toCopy ) ; if ( toCopy > 0 ) { position += toCopy ; } return toCopy ; } // into disk zone
int read = diskStream . read ( b , off , len ) ; if ( read > 0 ) { position += read ; } return read ; |
public class DomImpl { /** * Adds a new attribute in the given name - space to an element .
* There is an exception when using Internet Explorer ! For Internet Explorer the attribute of type " namespace : attr "
* will be set .
* @ param ns
* The name - space to be used in the element creation .
* @ param element
* The element to which the attribute is to be set .
* @ param attr
* The name of the attribute .
* @ param value
* The new value for the attribute . */
public void setElementAttributeNS ( String ns , Element element , String attr , String value ) { } } | setNameSpaceAttribute ( ns , element , attr , value ) ; |
public class URI { /** * Get the basename of the path .
* @ return the basename string
* @ throws URIException incomplete trailing escape pattern or unsupported
* character encoding
* @ see # decode */
public String getName ( ) throws URIException { } } | char [ ] basename = getRawName ( ) ; return ( basename == null ) ? null : decode ( getRawName ( ) , getProtocolCharset ( ) ) ; |
public class MapFuncSup { /** * define a function to deal with each element in the map
* @ param predicate a function takes in each element from map and returns
* true or false ( or null )
* @ param func a function returns ' last loop result '
* @ return return ' last loop value ' . < br >
* check
* < a href = " https : / / github . com / wkgcass / Style / " > tutorial < / a > for
* more info about ' last loop value '
* @ see IteratorInfo */
public < R > R forThose ( RFunc2 < Boolean , K , V > predicate , def < R > func ) { } } | Iterator < K > it = map . keySet ( ) . iterator ( ) ; IteratorInfo < R > info = new IteratorInfo < > ( ) ; ptr < Integer > i = Style . ptr ( 0 ) ; return Style . While ( it :: hasNext , ( loopInfo ) -> { K k = it . next ( ) ; V v = map . get ( k ) ; try { return If ( predicate . apply ( k , v ) , ( ) -> { return func . apply ( k , v , info . setValues ( i . item - 1 , i . item + 1 , i . item != 0 , it . hasNext ( ) , loopInfo . currentIndex , loopInfo . effectiveIndex , loopInfo . lastRes ) ) ; } ) . Else ( ( ) -> null ) ; } catch ( Throwable err ) { StyleRuntimeException sErr = Style . $ ( err ) ; Throwable t = sErr . origin ( ) ; if ( t instanceof Remove ) { it . remove ( ) ; } else { throw sErr ; } } finally { i . item += 1 ; } return null ; |
public class TableWriterServiceImpl { /** * Flushes the stream after a batch of writes .
* If the writes included a blob write , the segment must be fsynced because
* the blob is not saved in the journal . */
@ AfterBatch public void afterDeliver ( ) { } } | SegmentStream nodeStream = _nodeStream ; if ( nodeStream != null ) { if ( _isBlobDirty ) { _isBlobDirty = false ; // nodeStream . flush ( null ) ;
nodeStream . fsync ( Result . ignore ( ) ) ; } else { nodeStream . flush ( Result . ignore ( ) ) ; } } /* if ( blobWriter ! = null ) {
try {
blobWriter . flushSegment ( ) ;
} catch ( IOException e ) {
e . printStackTrace ( ) ; */ |
public class CheckBase { /** * Please override the
* { @ link # doVisitAnnotation ( JavaAnnotationElement , JavaAnnotationElement ) }
* instead .
* @ see Check # visitAnnotation ( JavaAnnotationElement , JavaAnnotationElement ) */
@ Nullable @ Override public final List < Difference > visitAnnotation ( @ Nullable JavaAnnotationElement oldAnnotation , @ Nullable JavaAnnotationElement newAnnotation ) { } } | depth ++ ; List < Difference > ret = doVisitAnnotation ( oldAnnotation , newAnnotation ) ; depth -- ; return ret ; |
public class TenantServiceClient { /** * Creates a new tenant entity .
* < p > Sample code :
* < pre > < code >
* try ( TenantServiceClient tenantServiceClient = TenantServiceClient . create ( ) ) {
* ProjectName parent = ProjectName . of ( " [ PROJECT ] " ) ;
* Tenant tenant = Tenant . newBuilder ( ) . build ( ) ;
* Tenant response = tenantServiceClient . createTenant ( parent . toString ( ) , tenant ) ;
* < / code > < / pre >
* @ param parent Required .
* < p > Resource name of the project under which the tenant is created .
* < p > The format is " projects / { project _ id } " , for example , " projects / api - test - project " .
* @ param tenant Required .
* < p > The tenant to be created .
* @ throws com . google . api . gax . rpc . ApiException if the remote call fails */
public final Tenant createTenant ( String parent , Tenant tenant ) { } } | CreateTenantRequest request = CreateTenantRequest . newBuilder ( ) . setParent ( parent ) . setTenant ( tenant ) . build ( ) ; return createTenant ( request ) ; |
public class JMPathOperation { /** * Create temp dir path as opt optional .
* @ param path the path
* @ return the optional */
public static Optional < Path > createTempDirPathAsOpt ( Path path ) { } } | debug ( log , "createTempDirPathAsOpt" , path ) ; try { return Optional . of ( Files . createTempDirectory ( path . toString ( ) ) ) . filter ( JMPath . ExistFilter ) . map ( JMPathOperation :: deleteOnExit ) ; } catch ( Exception e ) { return JMExceptionManager . handleExceptionAndReturnEmptyOptional ( log , e , "createTempDirPathAsOpt" , path ) ; } |
public class MtasFieldsConsumer { /** * Store tree .
* @ param node
* the node
* @ param isSinglePoint
* the is single point
* @ param storeAdditionalInformation
* the store additional information
* @ param out
* the out
* @ param nodeRefApproxOffset
* the node ref approx offset
* @ param refApproxOffset
* the ref approx offset
* @ return the long
* @ throws IOException
* Signals that an I / O exception has occurred . */
private Long storeTree ( MtasTreeNode < ? > node , boolean isSinglePoint , boolean storeAdditionalInformation , IndexOutput out , Long nodeRefApproxOffset , long refApproxOffset ) throws IOException { } } | Long localNodeRefApproxOffset = nodeRefApproxOffset ; if ( node != null ) { Boolean isRoot = false ; if ( localNodeRefApproxOffset == null ) { localNodeRefApproxOffset = out . getFilePointer ( ) ; isRoot = true ; } Long fpIndexObjectPositionLeftChild ; Long fpIndexObjectPositionRightChild ; if ( node . leftChild != null ) { fpIndexObjectPositionLeftChild = storeTree ( node . leftChild , isSinglePoint , storeAdditionalInformation , out , localNodeRefApproxOffset , refApproxOffset ) ; } else { fpIndexObjectPositionLeftChild = ( long ) 0 ; // tmp
} if ( node . rightChild != null ) { fpIndexObjectPositionRightChild = storeTree ( node . rightChild , isSinglePoint , storeAdditionalInformation , out , localNodeRefApproxOffset , refApproxOffset ) ; } else { fpIndexObjectPositionRightChild = ( long ) 0 ; // tmp
} Long fpIndexObjectPosition = out . getFilePointer ( ) ; if ( node . leftChild == null ) { fpIndexObjectPositionLeftChild = fpIndexObjectPosition ; } if ( node . rightChild == null ) { fpIndexObjectPositionRightChild = fpIndexObjectPosition ; } if ( isRoot ) { assert localNodeRefApproxOffset >= 0 : "nodeRefApproxOffset < 0 : " + localNodeRefApproxOffset ; out . writeVLong ( localNodeRefApproxOffset ) ; byte flag = 0 ; if ( isSinglePoint ) { flag |= MtasTree . SINGLE_POSITION_TREE ; } if ( storeAdditionalInformation ) { flag |= MtasTree . STORE_ADDITIONAL_ID ; } out . writeByte ( flag ) ; } assert node . left >= 0 : "node.left < 0 : " + node . left ; out . writeVInt ( node . left ) ; assert node . right >= 0 : "node.right < 0 : " + node . right ; out . writeVInt ( node . right ) ; assert node . max >= 0 : "node.max < 0 : " + node . max ; out . writeVInt ( node . max ) ; assert fpIndexObjectPositionLeftChild >= localNodeRefApproxOffset : "fpIndexObjectPositionLeftChild<nodeRefApproxOffset : " + fpIndexObjectPositionLeftChild + " and " + localNodeRefApproxOffset ; out . writeVLong ( ( fpIndexObjectPositionLeftChild - localNodeRefApproxOffset ) ) ; assert fpIndexObjectPositionRightChild >= localNodeRefApproxOffset : "fpIndexObjectPositionRightChild<nodeRefApproxOffset" + fpIndexObjectPositionRightChild + " and " + localNodeRefApproxOffset ; out . writeVLong ( ( fpIndexObjectPositionRightChild - localNodeRefApproxOffset ) ) ; if ( ! isSinglePoint ) { out . writeVInt ( node . ids . size ( ) ) ; } HashMap < Integer , MtasTreeNodeId > ids = node . ids ; Long objectRefCorrected ; long objectRefCorrectedPrevious = 0 ; // sort refs
List < MtasTreeNodeId > nodeIds = new ArrayList < > ( ids . values ( ) ) ; Collections . sort ( nodeIds ) ; if ( isSinglePoint && ( nodeIds . size ( ) != 1 ) ) { throw new IOException ( "singlePoint tree, but missing single point..." ) ; } int counter = 0 ; for ( MtasTreeNodeId nodeId : nodeIds ) { counter ++ ; objectRefCorrected = ( nodeId . ref - refApproxOffset ) ; assert objectRefCorrected >= objectRefCorrectedPrevious : "objectRefCorrected<objectRefCorrectedPrevious : " + objectRefCorrected + " and " + objectRefCorrectedPrevious ; out . writeVLong ( ( objectRefCorrected - objectRefCorrectedPrevious ) ) ; objectRefCorrectedPrevious = objectRefCorrected ; if ( storeAdditionalInformation ) { assert nodeId . additionalId >= 0 : "nodeId.additionalId < 0 for item " + counter + " : " + nodeId . additionalId ; out . writeVInt ( nodeId . additionalId ) ; assert nodeId . additionalRef >= 0 : "nodeId.additionalRef < 0 for item " + counter + " : " + nodeId . additionalRef ; out . writeVLong ( nodeId . additionalRef ) ; } } return fpIndexObjectPosition ; } else { return null ; } |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.