signature stringlengths 43 39.1k | implementation stringlengths 0 450k |
|---|---|
public class BoxApiFile { /** * Get the URL for uploading file a new version of a file in chunks
* @ param id id of file to retrieve info on
* @ return the upload sessions URL */
protected String getUploadSessionForNewFileVersionUrl ( final String id ) { } } | return String . format ( Locale . ENGLISH , "%s/files/%s/upload_sessions" , getBaseUploadUri ( ) , id ) ; |
public class Page { /** * Writes a constant value to the specified offset on the page .
* @ param offset
* the byte offset within the page
* @ param val
* the constant value to be written to the page */
public synchronized void setVal ( int offset , Constant val ) { } } | byte [ ] byteval = val . asBytes ( ) ; // Append the size of value if it is not fixed size
if ( ! val . getType ( ) . isFixedSize ( ) ) { // check the field capacity and value size
if ( offset + ByteHelper . INT_SIZE + byteval . length > BLOCK_SIZE ) throw new BufferOverflowException ( ) ; byte [ ] sizeBytes = ByteHelper . toBytes ( byteval . length ) ; contents . put ( offset , sizeBytes ) ; offset += sizeBytes . length ; } // Put bytes
contents . put ( offset , byteval ) ; |
public class ObjectAccessor { /** * ( non - Javadoc )
* @ see com . impetus . kundera . property . PropertyAccessor # fromBytes ( byte [ ] ) */
@ Override public final Object fromBytes ( Class targetClass , byte [ ] bytes ) { } } | try { if ( bytes == null ) { return null ; } if ( targetClass != null && targetClass . equals ( byte [ ] . class ) ) { return bytes ; } ObjectInputStream ois ; ois = new ObjectInputStream ( new ByteArrayInputStream ( bytes ) ) ; Object o = ois . readObject ( ) ; ois . close ( ) ; return o ; } catch ( IOException e ) { log . error ( "IO exception, Caused by {}." , e ) ; throw new PropertyAccessException ( e ) ; } catch ( ClassNotFoundException e ) { log . error ( "Class not found exception, Caused by {}." , e ) ; throw new PropertyAccessException ( e ) ; } |
public class SimpleHadoopFilesystemConfigStoreFactory { /** * This method determines the physical location of the { @ link SimpleHadoopFilesystemConfigStore } root directory on HDFS . It does
* this by taking the { @ link URI } given by the user and back - tracing the path . It checks if each parent directory
* contains the folder { @ link SimpleHadoopFilesystemConfigStore # CONFIG _ STORE _ NAME } . It the assumes this { @ link Path } is the root
* directory .
* If the given configKey does not have an authority , then this method assumes the given { @ link URI # getPath ( ) } does
* not contain the dataset root . In which case it uses the { @ link # getDefaultRootDir ( ) } as the root directory . If
* the default root dir does not contain the { @ link SimpleHadoopFilesystemConfigStore # CONFIG _ STORE _ NAME } then a
* { @ link ConfigStoreCreationException } is thrown . */
private URI getStoreRoot ( FileSystem fs , URI configKey ) throws ConfigStoreCreationException { } } | if ( Strings . isNullOrEmpty ( configKey . getAuthority ( ) ) ) { if ( getDefaultStoreURILazy ( ) != null ) { return getDefaultStoreURILazy ( ) ; } else if ( isAuthorityRequired ( ) ) { throw new ConfigStoreCreationException ( configKey , "No default store has been configured." ) ; } } Path path = new Path ( configKey . getPath ( ) ) ; while ( path != null ) { try { // the abs URI may point to an unexist path for
// 1 . phantom node
// 2 . as URI did not specify the version
if ( fs . exists ( path ) ) { for ( FileStatus fileStatus : fs . listStatus ( path ) ) { if ( fileStatus . isDirectory ( ) && fileStatus . getPath ( ) . getName ( ) . equals ( SimpleHadoopFilesystemConfigStore . CONFIG_STORE_NAME ) ) { return fs . getUri ( ) . resolve ( fileStatus . getPath ( ) . getParent ( ) . toUri ( ) ) ; } } } } catch ( IOException e ) { throw new ConfigStoreCreationException ( configKey , e ) ; } path = path . getParent ( ) ; } throw new ConfigStoreCreationException ( configKey , "Cannot find the store root!" ) ; |
public class TaskTrackerManager { /** * 删除节点
* @ param node */
public void removeNode ( Node node ) { } } | Set < TaskTrackerNode > taskTrackerNodes = NODE_MAP . get ( node . getGroup ( ) ) ; if ( taskTrackerNodes != null && taskTrackerNodes . size ( ) != 0 ) { TaskTrackerNode taskTrackerNode = new TaskTrackerNode ( node . getIdentity ( ) ) ; taskTrackerNode . setNodeGroup ( node . getGroup ( ) ) ; LOGGER . info ( "Remove TaskTracker node:{}" , taskTrackerNode ) ; taskTrackerNodes . remove ( taskTrackerNode ) ; } |
public class ListContainsAction { /** * This method checks to see if a list contains every element in another list .
* @ param sublist The contained list .
* @ param container The containing list .
* @ param delimiter A delimiter separating elements in the two lists . Default is a comma .
* @ param ignoreCase If set to ' True ' then the compare is not case sensitive . Default is True .
* @ return sublist is contained in container or not . */
@ Action ( name = "List Contains All" , outputs = { } } | @ Output ( RESPONSE_TEXT ) , @ Output ( RETURN_RESULT ) , @ Output ( RETURN_CODE ) , @ Output ( EXCEPTION ) } , responses = { @ Response ( text = SUCCESS , field = RETURN_CODE , value = RETURN_CODE_SUCCESS , matchType = MatchType . COMPARE_EQUAL ) , @ Response ( text = FAILURE , field = RETURN_CODE , value = RETURN_CODE_FAILURE , matchType = MatchType . COMPARE_EQUAL , isOnFail = true , isDefault = true ) } ) public Map < String , String > containsElement ( @ Param ( value = SUBLIST , required = true ) String sublist , @ Param ( value = CONTAINER , required = true ) String container , @ Param ( value = DELIMITER ) String delimiter , @ Param ( value = IGNORE_CASE ) String ignoreCase ) { Map < String , String > result = new HashMap < > ( ) ; try { delimiter = InputsUtils . getInputDefaultValue ( delimiter , Constants . DEFAULT_DELIMITER ) ; String [ ] subArray = sublist . split ( delimiter ) ; String [ ] containerArray = container . split ( delimiter ) ; String [ ] uncontainedArray = ListProcessor . getUncontainedArray ( subArray , containerArray , InputsUtils . toBoolean ( ignoreCase , true , IGNORE_CASE ) ) ; if ( ListProcessor . arrayElementsAreNull ( uncontainedArray ) ) { result . put ( RESPONSE_TEXT , TRUE ) ; result . put ( RETURN_RESULT , EMPTY_STRING ) ; result . put ( RETURN_CODE , RETURN_CODE_SUCCESS ) ; result . put ( EXCEPTION , EMPTY_STRING ) ; } else { result . put ( RESPONSE , FALSE ) ; result . put ( RETURN_CODE , RETURN_CODE_FAILURE ) ; result . put ( RETURN_RESULT , StringUtils . join ( uncontainedArray , delimiter ) ) ; result . put ( EXCEPTION , EMPTY_STRING ) ; } } catch ( Exception e ) { result . put ( RESPONSE , FAILURE ) ; result . put ( RETURN_RESULT , EMPTY_STRING ) ; result . put ( RETURN_CODE , RETURN_CODE_FAILURE ) ; result . put ( EXCEPTION , e . getMessage ( ) ) ; } return result ; |
public class XmlUtil { /** * Get the value of an element . We expect 1 child node otherwise we raise an
* exception .
* @ param el Node whose value we want
* @ param name String name to make exception messages more readable
* @ return String node value
* @ throws SAXException */
public static String getReqOneNodeVal ( final Node el , final String name ) throws SAXException { } } | String str = getOneNodeVal ( el , name ) ; if ( ( str == null ) || ( str . length ( ) == 0 ) ) { throw new SAXException ( "Missing property value: " + name ) ; } return str ; |
public class ByLabelClustering { /** * Run the actual clustering algorithm .
* @ param relation The data input we use */
public Clustering < Model > run ( Relation < ? > relation ) { } } | HashMap < String , DBIDs > labelMap = multiple ? multipleAssignment ( relation ) : singleAssignment ( relation ) ; ModifiableDBIDs noiseids = DBIDUtil . newArray ( ) ; Clustering < Model > result = new Clustering < > ( "By Label Clustering" , "bylabel-clustering" ) ; for ( Entry < String , DBIDs > entry : labelMap . entrySet ( ) ) { DBIDs ids = entry . getValue ( ) ; if ( ids . size ( ) <= 1 ) { noiseids . addDBIDs ( ids ) ; continue ; } // Build a cluster
Cluster < Model > c = new Cluster < Model > ( entry . getKey ( ) , ids , ClusterModel . CLUSTER ) ; if ( noisepattern != null && noisepattern . matcher ( entry . getKey ( ) ) . find ( ) ) { c . setNoise ( true ) ; } result . addToplevelCluster ( c ) ; } // Collected noise IDs .
if ( noiseids . size ( ) > 0 ) { Cluster < Model > c = new Cluster < Model > ( "Noise" , noiseids , ClusterModel . CLUSTER ) ; c . setNoise ( true ) ; result . addToplevelCluster ( c ) ; } return result ; |
public class CommerceWishListLocalServiceBaseImpl { /** * Adds the commerce wish list to the database . Also notifies the appropriate model listeners .
* @ param commerceWishList the commerce wish list
* @ return the commerce wish list that was added */
@ Indexable ( type = IndexableType . REINDEX ) @ Override public CommerceWishList addCommerceWishList ( CommerceWishList commerceWishList ) { } } | commerceWishList . setNew ( true ) ; return commerceWishListPersistence . update ( commerceWishList ) ; |
public class BitfinexApiCallbackListeners { /** * registers listener for notifications on connection state
* @ param listener of event
* @ return hook of this listener */
public Closeable onConnectionStateChange ( final Consumer < BitfinexConnectionStateEnum > listener ) { } } | connectionStateConsumers . offer ( listener ) ; return ( ) -> connectionStateConsumers . remove ( listener ) ; |
public class JavaScriptUtils { /** * Creates and returns a JavaScript line that sets a cookie with the specified name , value , and cookie properties . For
* example , a cookie name of " test " , value of " 123 " , and properties " HttpOnly " and " path = / " would return
* { @ code document . cookie = " test = 123 ; HttpOnly ; path = / ; " ; } . Note : The specified properties will be HTML - encoded but the cookie
* name and value will not . */
public String getUnencodedJavaScriptHtmlCookieString ( String name , String value , Map < String , String > cookieProperties ) { } } | return createJavaScriptHtmlCookieString ( name , value , cookieProperties , false ) ; |
public class Locale { /** * Sets the default locale for the specified Category for this instance
* of the Java Virtual Machine . This does not affect the host locale .
* If there is a security manager , its checkPermission method is called
* with a PropertyPermission ( " user . language " , " write " ) permission before
* the default locale is changed .
* The Java Virtual Machine sets the default locale during startup based
* on the host environment . It is used by many locale - sensitive methods
* if no locale is explicitly specified .
* Since changing the default locale may affect many different areas of
* functionality , this method should only be used if the caller is
* prepared to reinitialize locale - sensitive code running within the
* same Java Virtual Machine .
* @ param category - the specified category to set the default locale
* @ param newLocale - the new default locale
* @ throws SecurityException - if a security manager exists and its
* checkPermission method doesn ' t allow the operation .
* @ throws NullPointerException - if category and / or newLocale is null
* @ see SecurityManager # checkPermission ( java . security . Permission )
* @ see PropertyPermission
* @ see # getDefault ( Locale . Category )
* @ since 1.7 */
public static synchronized void setDefault ( Locale . Category category , Locale newLocale ) { } } | if ( category == null ) throw new NullPointerException ( "Category cannot be NULL" ) ; if ( newLocale == null ) throw new NullPointerException ( "Can't set default locale to NULL" ) ; /* J2ObjC removed .
SecurityManager sm = System . getSecurityManager ( ) ;
if ( sm ! = null ) sm . checkPermission ( new PropertyPermission
( " user . language " , " write " ) ) ; */
switch ( category ) { case DISPLAY : defaultDisplayLocale = newLocale ; break ; case FORMAT : defaultFormatLocale = newLocale ; break ; default : assert false : "Unknown Category" ; } |
public class MenuItemTransitionBuilder { /** * Creates a builder for a specific Toolbar { @ link MenuItem } .
* @ param menuId The ID of the MenuItem to have transition effect created .
* @ param toolbar
* @ return */
public static MenuItemTransitionBuilder transit ( @ IdRes int menuId , @ NonNull Toolbar toolbar ) { } } | return new MenuItemTransitionBuilder ( menuId , toolbar ) ; |
public class ApiOvhIpLoadbalancing { /** * Add a new TCP frontend on your IP Load Balancing
* REST : POST / ipLoadbalancing / { serviceName } / tcp / frontend
* @ param port [ required ] Port ( s ) attached to your frontend . Supports single port ( numerical value ) , range ( 2 dash - delimited increasing ports ) and comma - separated list of ' single port ' and / or ' range ' . Each port must be in the [ 1;49151 ] range .
* @ param disabled [ required ] Disable your frontend . Default : ' false '
* @ param defaultFarmId [ required ] Default TCP Farm of your frontend
* @ param displayName [ required ] Human readable name for your frontend , this field is for you
* @ param dedicatedIpfo [ required ] Only attach frontend on these ip . No restriction if null
* @ param ssl [ required ] SSL deciphering . Default : ' false '
* @ param zone [ required ] Zone of your frontend . Use " all " for all owned zone .
* @ param allowedSource [ required ] Restrict IP Load Balancing access to these ip block . No restriction if null
* @ param defaultSslId [ required ] Default ssl served to your customer
* @ param serviceName [ required ] The internal name of your IP load balancing */
public OvhFrontendTcp serviceName_tcp_frontend_POST ( String serviceName , String [ ] allowedSource , String [ ] dedicatedIpfo , Long defaultFarmId , Long defaultSslId , Boolean disabled , String displayName , String port , Boolean ssl , String zone ) throws IOException { } } | String qPath = "/ipLoadbalancing/{serviceName}/tcp/frontend" ; StringBuilder sb = path ( qPath , serviceName ) ; HashMap < String , Object > o = new HashMap < String , Object > ( ) ; addBody ( o , "allowedSource" , allowedSource ) ; addBody ( o , "dedicatedIpfo" , dedicatedIpfo ) ; addBody ( o , "defaultFarmId" , defaultFarmId ) ; addBody ( o , "defaultSslId" , defaultSslId ) ; addBody ( o , "disabled" , disabled ) ; addBody ( o , "displayName" , displayName ) ; addBody ( o , "port" , port ) ; addBody ( o , "ssl" , ssl ) ; addBody ( o , "zone" , zone ) ; String resp = exec ( qPath , "POST" , sb . toString ( ) , o ) ; return convertTo ( resp , OvhFrontendTcp . class ) ; |
public class OAuthProviderProcessingFilter { /** * Whether this filter is configured to process the specified request .
* @ param request The request .
* @ param response The response
* @ param filterChain The filter chain
* @ return Whether this filter is configured to process the specified request . */
protected boolean requiresAuthentication ( HttpServletRequest request , HttpServletResponse response , FilterChain filterChain ) { } } | // copied from org . springframework . security . ui . AbstractProcessingFilter . requiresAuthentication
String uri = request . getRequestURI ( ) ; int pathParamIndex = uri . indexOf ( ';' ) ; if ( pathParamIndex > 0 ) { // strip everything after the first semi - colon
uri = uri . substring ( 0 , pathParamIndex ) ; } if ( "" . equals ( request . getContextPath ( ) ) ) { return uri . endsWith ( filterProcessesUrl ) ; } boolean match = uri . endsWith ( request . getContextPath ( ) + filterProcessesUrl ) ; if ( log . isDebugEnabled ( ) ) { log . debug ( uri + ( match ? " matches " : " does not match " ) + filterProcessesUrl ) ; } return match ; |
public class JavaWriter { /** * Sets the source filename and line .
* @ param filename
* the filename of the source file .
* @ param line
* the line of the source file . */
public void setLocation ( String filename , int line ) throws IOException { } } | if ( _lineMap != null && filename != null && line >= 0 ) { _lineMap . add ( filename , line , _destLine , _isPreferLast ) ; } |
public class CentralDogmaBeanConfigBuilder { /** * Merges the properties of the specified { @ link CentralDogmaBeanConfig } into this builder . */
public CentralDogmaBeanConfigBuilder merge ( CentralDogmaBeanConfig config ) { } } | config . project ( ) . ifPresent ( this :: project ) ; config . repository ( ) . ifPresent ( this :: repository ) ; config . path ( ) . ifPresent ( this :: path ) ; config . jsonPath ( ) . ifPresent ( this :: jsonPath ) ; return this ; |
public class HttpMessage { /** * ZAP : New method checking if connection is a Server - Sent Events stream .
* @ return */
public boolean isEventStream ( ) { } } | boolean isEventStream = false ; if ( ! getResponseHeader ( ) . isEmpty ( ) ) { isEventStream = getResponseHeader ( ) . hasContentType ( "text/event-stream" ) ; } else { // response not available
// is request for event - stream ?
String acceptHeader = getRequestHeader ( ) . getHeader ( "Accept" ) ; if ( acceptHeader != null && acceptHeader . equals ( "text/event-stream" ) ) { // request is for an SSE stream
isEventStream = true ; } } return isEventStream ; |
public class BubbleChart { /** * Update a series by updating the X - Axis , Y - Axis and bubble data
* @ param seriesName
* @ param newXData - set null to be automatically generated as a list of increasing Integers
* starting from 1 and ending at the size of the new Y - Axis data list .
* @ param newYData
* @ param newBubbleData - set null if there are no error bars
* @ return */
public BubbleSeries updateBubbleSeries ( String seriesName , List < ? > newXData , List < ? extends Number > newYData , List < ? extends Number > newBubbleData ) { } } | return updateBubbleSeries ( seriesName , Utils . getDoubleArrayFromNumberList ( newXData ) , Utils . getDoubleArrayFromNumberList ( newYData ) , Utils . getDoubleArrayFromNumberList ( newBubbleData ) ) ; |
public class AnnotationUtil { /** * 找出所有标注了该annotation的公共属性 , 循环遍历父类 .
* 暂未支持Spring风格Annotation继承Annotation
* copy from org . unitils . util . AnnotationUtils */
public static < T extends Annotation > Set < Field > getAnnotatedPublicFields ( Class < ? extends Object > clazz , Class < T > annotation ) { } } | if ( Object . class . equals ( clazz ) ) { return Collections . emptySet ( ) ; } Set < Field > annotatedFields = new HashSet < Field > ( ) ; Field [ ] fields = clazz . getFields ( ) ; for ( Field field : fields ) { if ( field . getAnnotation ( annotation ) != null ) { annotatedFields . add ( field ) ; } } return annotatedFields ; |
public class ProcComm { /** * Entry point for running ProcComm .
* An IP host or port identifier has to be supplied , specifying the endpoint for the
* KNX network access . < br >
* To show the usage message of this tool on the console , supply the command line
* option - help ( or - h ) . < br >
* Command line options are treated case sensitive . Available options for the
* communication connection :
* < ul >
* < li > < code > - help - h < / code > show help message < / li >
* < li > < code > - version < / code > show tool / library version and exit < / li >
* < li > < code > - verbose - v < / code > enable verbose status output < / li >
* < li > < code > - localhost < / code > < i > id < / i > & nbsp ; local IP / host name < / li >
* < li > < code > - localport < / code > < i > number < / i > & nbsp ; local UDP port ( default system
* assigned ) < / li >
* < li > < code > - port - p < / code > < i > number < / i > & nbsp ; UDP port on host ( default 3671 ) < / li >
* < li > < code > - nat - n < / code > enable Network Address Translation < / li >
* < li > < code > - routing < / code > use KNXnet / IP routing < / li >
* < li > < code > - serial - s < / code > use FT1.2 serial communication < / li >
* < li > < code > - medium - m < / code > < i > id < / i > & nbsp ; KNX medium [ tp0 | tp1 | p110 | p132 | rf ]
* ( defaults to tp1 ) < / li >
* < / ul >
* Available commands for process communication :
* < ul >
* < li > < code > read < / code > < i > DPT & nbsp ; KNX - address < / i > & nbsp ; read from group
* address , using DPT value format < / li >
* < li > < code > write < / code > < i > DPT & nbsp ; value & nbsp ; KNX - address < / i > & nbsp ; write
* to group address , using DPT value format < / li >
* < / ul >
* For the more common datapoint types ( DPTs ) the following name aliases can be used
* instead of the general DPT number string :
* < ul >
* < li > < code > switch < / code > for DPT 1.001 < / li >
* < li > < code > bool < / code > for DPT 1.002 < / li >
* < li > < code > string < / code > for DPT 16.001 < / li >
* < li > < code > float < / code > for DPT 9.002 < / li >
* < li > < code > ucount < / code > for DPT 5.010 < / li >
* < li > < code > angle < / code > for DPT 5.003 < / li >
* < / ul >
* @ param args command line options for process communication */
public static void main ( String [ ] args ) { } } | try { final ProcComm pc = new ProcComm ( args , null ) ; // use a log writer for the console ( System . out ) , setting the user
// specified log level , if any
pc . w = new ConsoleWriter ( pc . options . containsKey ( "verbose" ) ) ; if ( pc . options . containsKey ( "read" ) == pc . options . containsKey ( "write" ) ) throw new IllegalArgumentException ( "do either read or write" ) ; try { pc . run ( null ) ; pc . readWrite ( ) ; } finally { pc . quit ( ) ; } } catch ( final Throwable t ) { if ( t . getMessage ( ) != null ) System . out . println ( t . getMessage ( ) ) ; } |
public class InternalXbaseWithAnnotationsParser { /** * InternalXbaseWithAnnotations . g : 933:1 : entryRuleXExpressionInClosure : ruleXExpressionInClosure EOF ; */
public final void entryRuleXExpressionInClosure ( ) throws RecognitionException { } } | try { // InternalXbaseWithAnnotations . g : 934:1 : ( ruleXExpressionInClosure EOF )
// InternalXbaseWithAnnotations . g : 935:1 : ruleXExpressionInClosure EOF
{ if ( state . backtracking == 0 ) { before ( grammarAccess . getXExpressionInClosureRule ( ) ) ; } pushFollow ( FOLLOW_1 ) ; ruleXExpressionInClosure ( ) ; state . _fsp -- ; if ( state . failed ) return ; if ( state . backtracking == 0 ) { after ( grammarAccess . getXExpressionInClosureRule ( ) ) ; } match ( input , EOF , FOLLOW_2 ) ; if ( state . failed ) return ; } } catch ( RecognitionException re ) { reportError ( re ) ; recover ( input , re ) ; } finally { } return ; |
public class DnsNameResolverBuilder { /** * Set the list of search domains of the resolver .
* @ param searchDomains the search domains
* @ return { @ code this } */
public DnsNameResolverBuilder searchDomains ( Iterable < String > searchDomains ) { } } | checkNotNull ( searchDomains , "searchDomains" ) ; final List < String > list = new ArrayList < String > ( 4 ) ; for ( String f : searchDomains ) { if ( f == null ) { break ; } // Avoid duplicate entries .
if ( list . contains ( f ) ) { continue ; } list . add ( f ) ; } this . searchDomains = list . toArray ( new String [ 0 ] ) ; return this ; |
public class HalfSerializer { /** * Emits the given value if possible and terminates if there was an onComplete or onError
* while emitting , drops the value otherwise .
* @ param < T > the value type
* @ param subscriber the target Subscriber to emit to
* @ param value the value to emit
* @ param wip the serialization work - in - progress counter / indicator
* @ param error the holder of Throwables
* @ return true if a terminal event was emitted to { @ code observer } , false if not */
public static < T > boolean onNext ( Subscriber < ? super T > subscriber , T value , AtomicInteger wip , AtomicThrowable error ) { } } | if ( wip . get ( ) == 0 && wip . compareAndSet ( 0 , 1 ) ) { subscriber . onNext ( value ) ; if ( wip . decrementAndGet ( ) != 0 ) { Throwable ex = error . terminate ( ) ; if ( ex != null ) { subscriber . onError ( ex ) ; } else { subscriber . onComplete ( ) ; } return true ; } } return false ; |
public class Maybe { /** * Convenience static factory method for creating a { @ link Maybe } from an { @ link Optional } .
* @ param optional the optional
* @ param < A > the optional parameter type
* @ return the equivalent Maybe instance */
public static < A > Maybe < A > fromOptional ( Optional < ? extends A > optional ) { } } | return optional . map ( Maybe :: < A > just ) . orElse ( Maybe . nothing ( ) ) ; |
public class Deflater { /** * Sets preset dictionary for compression . A preset dictionary is used
* when the history buffer can be predetermined . When the data is later
* uncompressed with Inflater . inflate ( ) , Inflater . getAdler ( ) can be called
* in order to get the Adler - 32 value of the dictionary required for
* decompression .
* @ param b the dictionary data bytes
* @ param off the start offset of the data
* @ param len the length of the data
* @ see Inflater # inflate
* @ see Inflater # getAdler */
public void setDictionary ( byte [ ] b , int off , int len ) { } } | if ( b == null ) { throw new NullPointerException ( ) ; } if ( off < 0 || len < 0 || off > b . length - len ) { throw new ArrayIndexOutOfBoundsException ( ) ; } synchronized ( zsRef ) { ensureOpen ( ) ; setDictionary ( zsRef . address ( ) , b , off , len ) ; } |
public class DeviceImpl { public void set_polled_cmd ( final String [ ] s ) { } } | for ( final String value : s ) { ext . polled_cmd . add ( value ) ; } |
public class ForkJoinPool { /** * Blocks until all tasks have completed execution after a
* shutdown request , or the timeout occurs , or the current thread
* is interrupted , whichever happens first . Because the { @ link
* # commonPool ( ) } never terminates until program shutdown , when
* applied to the common pool , this method is equivalent to { @ link
* # awaitQuiescence ( long , TimeUnit ) } but always returns { @ code false } .
* @ param timeout the maximum time to wait
* @ param unit the time unit of the timeout argument
* @ return { @ code true } if this executor terminated and
* { @ code false } if the timeout elapsed before termination
* @ throws InterruptedException if interrupted while waiting */
public boolean awaitTermination ( long timeout , TimeUnit unit ) throws InterruptedException { } } | if ( Thread . interrupted ( ) ) throw new InterruptedException ( ) ; if ( this == common ) { awaitQuiescence ( timeout , unit ) ; return false ; } long nanos = unit . toNanos ( timeout ) ; if ( isTerminated ( ) ) return true ; if ( nanos <= 0L ) return false ; long deadline = System . nanoTime ( ) + nanos ; synchronized ( this ) { for ( ; ; ) { if ( isTerminated ( ) ) return true ; if ( nanos <= 0L ) return false ; long millis = TimeUnit . NANOSECONDS . toMillis ( nanos ) ; wait ( millis > 0L ? millis : 1L ) ; nanos = deadline - System . nanoTime ( ) ; } } |
public class ItemVisitor { /** * Visits an { @ link ItemGroup } by visits the member items . */
public void onItemGroup ( ItemGroup < ? > group ) { } } | for ( Item i : group . getItems ( ) ) if ( i . hasPermission ( Item . READ ) ) onItem ( i ) ; |
public class DiscordianChronology { /** * Obtains a local date in Discordian calendar system from the
* era , year - of - era and day - of - year fields .
* @ param era the Discordian era , not null
* @ param yearOfEra the year - of - era
* @ param dayOfYear the day - of - year
* @ return the Discordian local date , not null
* @ throws DateTimeException if unable to create the date
* @ throws ClassCastException if the { @ code era } is not a { @ code DiscordianEra } */
@ Override public DiscordianDate dateYearDay ( Era era , int yearOfEra , int dayOfYear ) { } } | return dateYearDay ( prolepticYear ( era , yearOfEra ) , dayOfYear ) ; |
public class LdiSrl { /** * Extract rear sub - string by reverse index .
* < pre >
* rearstring ( " flute " , 2)
* returns " te "
* < / pre >
* @ param str The target string . ( NotNull )
* @ param reverseIndex The index from rear .
* @ return The rear string . ( NotNull ) */
public static String rearstring ( final String str , final int reverseIndex ) { } } | assertStringNotNull ( str ) ; if ( str . length ( ) < reverseIndex ) { String msg = "The length of the string was smaller than the index:" ; msg = msg + " str=" + str + " reverseIndex=" + reverseIndex ; throw new StringIndexOutOfBoundsException ( msg ) ; } return str . substring ( str . length ( ) - reverseIndex ) ; |
public class SwissGermanTagger { /** * / * ( non - Javadoc )
* @ see org . languagetool . tagging . de . GermanTagger # tag ( java . util . List , boolean ) */
@ Override public List < AnalyzedTokenReadings > tag ( List < String > sentenceTokens , boolean ignoreCase ) throws IOException { } } | List < AnalyzedTokenReadings > tokens = super . tag ( sentenceTokens , ignoreCase ) ; for ( int i = 0 ; i < tokens . size ( ) ; i ++ ) { AnalyzedTokenReadings reading = tokens . get ( i ) ; if ( reading != null && reading . getToken ( ) != null && reading . getToken ( ) . contains ( "ss" ) && ! reading . isTagged ( ) ) { AnalyzedTokenReadings replacementReading = lookup ( reading . getToken ( ) . replace ( "ss" , "ß" ) ) ; if ( replacementReading != null ) { for ( AnalyzedToken at : replacementReading . getReadings ( ) ) { reading . addReading ( new AnalyzedToken ( reading . getToken ( ) , at . getPOSTag ( ) , at . getLemma ( ) ) ) ; } } } } return tokens ; |
public class AbstractCalendarFactory { /** * The way calendars are stored in an MPP14 file means that there
* can be forward references between the base calendar unique ID for a
* derived calendar , and the base calendar itself . To get around this ,
* we initially populate the base calendar name attribute with the
* base calendar unique ID , and now in this method we can convert those
* ID values into the correct names .
* @ param baseCalendars list of calendars and base calendar IDs
* @ param map map of calendar ID values and calendar objects */
private void updateBaseCalendarNames ( List < Pair < ProjectCalendar , Integer > > baseCalendars , HashMap < Integer , ProjectCalendar > map ) { } } | for ( Pair < ProjectCalendar , Integer > pair : baseCalendars ) { ProjectCalendar cal = pair . getFirst ( ) ; Integer baseCalendarID = pair . getSecond ( ) ; ProjectCalendar baseCal = map . get ( baseCalendarID ) ; if ( baseCal != null && baseCal . getName ( ) != null ) { cal . setParent ( baseCal ) ; } else { // Remove invalid calendar to avoid serious problems later .
m_file . removeCalendar ( cal ) ; } } |
public class CDDB { /** * Extracts the track index of the supplied line ( the number immediately following the supplied
* prefix and preceding the equals sign ) or throws a CDDBException if the line contains no
* equals sign or track index . */
protected final int index ( String source , String prefix , int lineno ) throws CDDBException { } } | int eidx = source . indexOf ( "=" , prefix . length ( ) ) ; if ( eidx == - 1 ) { throw new CDDBException ( 500 , "Malformed line '" + source + "' number " + lineno ) ; } try { return Integer . parseInt ( source . substring ( prefix . length ( ) , eidx ) ) ; } catch ( NumberFormatException nfe ) { throw new CDDBException ( 500 , "Malformed line '" + source + "' number " + lineno ) ; } |
public class DatabaseTaskStore { /** * Remove all tasks that match the specified name pattern and the presence or absence
* ( as determined by the inState attribute ) of the specified state .
* For example , to remove all canceled tasks that have a name that starts with " PAYROLL _ TASK _ " ,
* taskStore . remove ( " PAYROLL \ \ _ TASK \ \ _ % " , ' \ \ ' , TaskState . CANCELED , true , " app1 " ) ;
* @ param pattern task name pattern similar to the LIKE clause in SQL ( % matches any characters , _ matches one character )
* @ param escape escape character that indicates when matching characters like % and _ should be interpreted literally .
* @ param state a task state . For example , TaskState . UNATTEMPTED .
* @ param inState indicates whether to remove tasks with or without the specified state
* @ param owner name of owner to match as the task submitter . Null to ignore .
* @ return count of tasks removed .
* @ throws Exception if an error occurs when attempting to update the persistent task store . */
@ Override public int remove ( String pattern , Character escape , TaskState state , boolean inState , String owner ) throws Exception { } } | StringBuilder delete = new StringBuilder ( 100 ) . append ( "DELETE FROM Task t" ) ; int i = 0 ; if ( owner != null ) delete . append ( ++ i == 1 ? " WHERE" : " AND" ) . append ( " t.OWNR=:o" ) ; if ( pattern != null ) { delete . append ( ++ i == 1 ? " WHERE" : " AND" ) . append ( " t.INAME LIKE :p" ) ; if ( escape != null ) delete . append ( " ESCAPE :e" ) ; } Map < String , Object > stateParams = null ; if ( ! TaskState . ANY . equals ( state ) ) stateParams = appendStateComparison ( delete . append ( ++ i == 1 ? " WHERE " : " AND " ) , state , inState ) ; else if ( ! inState ) return 0 ; // empty result if someone asks to remove tasks not in any state
final boolean trace = TraceComponent . isAnyTracingEnabled ( ) ; if ( trace && tc . isEntryEnabled ( ) ) Tr . entry ( this , tc , "remove" , pattern , escape , state + ":" + inState , owner , delete ) ; EntityManager em = getPersistenceServiceUnit ( ) . createEntityManager ( ) ; try { Query query = em . createQuery ( delete . toString ( ) ) ; if ( owner != null ) query . setParameter ( "o" , owner ) ; if ( pattern != null ) { query . setParameter ( "p" , pattern ) ; if ( escape != null ) query . setParameter ( "e" , escape ) ; } if ( stateParams != null ) for ( Map . Entry < String , Object > param : stateParams . entrySet ( ) ) query . setParameter ( param . getKey ( ) , param . getValue ( ) ) ; int count = query . executeUpdate ( ) ; if ( trace && tc . isEntryEnabled ( ) ) Tr . exit ( this , tc , "remove" , count ) ; return count ; } finally { em . close ( ) ; } |
public class TargetsApi { /** * Add a target that the agent recently used .
* @ param target The target to add .
* @ param media The media channel the where the target was recently used .
* @ param timestamp The timestamp for when the target was used . This value should be a number representing the milliseconds elapsed since the UNIX epoch . ( optional ) */
public void addRecentTarget ( Target target , String media , long timestamp ) throws WorkspaceApiException { } } | try { TargetsrecentsaddData data = new TargetsrecentsaddData ( ) ; data . setTarget ( toInformation ( target ) ) ; RecentData recentData = new RecentData ( ) ; recentData . setMedia ( media ) ; recentData . setTimeStamp ( new BigDecimal ( timestamp ) ) ; data . setRecentInformation ( recentData ) ; RecentTargetData recentTargetData = new RecentTargetData ( ) ; recentTargetData . setData ( data ) ; ApiSuccessResponse resp = targetsApi . addRecentTarget ( recentTargetData ) ; Util . throwIfNotOk ( resp ) ; } catch ( ApiException ex ) { throw new WorkspaceApiException ( "Cannot add recent target" , ex ) ; } |
public class DefaultSystemInfoProvider { /** * this method was partially derived from : : ( project ) jogamp / ( developer ) sgothel
* https : / / github . com / sgothel / gluegen / blob / master / src / java / jogamp / common / os / PlatformPropsImpl . java # L160
* https : / / github . com / sgothel / gluegen / blob / master / LICENSE . txt */
@ Override public boolean isHardFloatAbi ( ) throws UnsupportedOperationException { } } | return AccessController . doPrivileged ( new PrivilegedAction < Boolean > ( ) { private final String [ ] gnueabihf = new String [ ] { "gnueabihf" , "armhf" } ; public Boolean run ( ) { return ( StringUtil . contains ( System . getProperty ( "sun.boot.library.path" ) , gnueabihf ) || StringUtil . contains ( System . getProperty ( "java.library.path" ) , gnueabihf ) || StringUtil . contains ( System . getProperty ( "java.home" ) , gnueabihf ) || getBashVersionInfo ( ) . contains ( "gnueabihf" ) || hasReadElfTag ( "Tag_ABI_HardFP_use" ) ) ; } } ) ; |
public class ExternalContext { /** * < p class = " changed _ added _ 2_2 " > Return the id of the current session
* or the empty string if no session has been created and the
* < code > create < / code > parameter is < code > false < / code > . < / p >
* < div class = " changed _ added _ 2_2 " >
* < p > < em > Servlet : < / em > If < code > create < / code > is true , obtain
* a reference to the < code > HttpSession < / code > for the current request
* ( creating the session if necessary ) and return its id . If
* < code > create < / code > is < code > false < / code > , obtain a reference to the
* current session , if one exists , and return its id . If no session exists ,
* return the empty string . < / p >
* < / div >
* @ since 2.2
* @ param create Flag indicating whether or not a new session should be
* created if there is no session associated with the current request */
public String getSessionId ( boolean create ) { } } | String result = "" ; if ( defaultExternalContext != null ) { result = defaultExternalContext . getSessionId ( create ) ; } else { throw new UnsupportedOperationException ( ) ; } return result ; |
public class Predicate { /** * Remove non - matching elements from the specified collection . */
public < E extends T > void filter ( Collection < E > coll ) { } } | for ( Iterator < E > itr = coll . iterator ( ) ; itr . hasNext ( ) ; ) { if ( ! isMatch ( itr . next ( ) ) ) { itr . remove ( ) ; } } |
public class IconicsDrawable { /** * Sets the shadow for the icon
* This requires shadow support to be enabled on the view holding this ` IconicsDrawable `
* @ return The current IconicsDrawable for chaining .
* @ see Paint # setShadowLayer ( float , float , float , int )
* @ see # enableShadowSupport ( View ) */
@ NonNull public IconicsDrawable shadowRes ( @ DimenRes int radiusRes , @ DimenRes int dxRes , @ DimenRes int dyRes , @ ColorRes int colorResId ) { } } | return shadowPx ( mContext . getResources ( ) . getDimensionPixelSize ( radiusRes ) , mContext . getResources ( ) . getDimensionPixelSize ( dxRes ) , mContext . getResources ( ) . getDimensionPixelSize ( dyRes ) , ContextCompat . getColor ( mContext , colorResId ) ) ; |
public class SaltAnnotateExtractor { /** * Sets additional match ( global ) information about the matched nodes and
* annotations .
* This will add the { @ link AnnisConstants # FEAT _ MATCHEDIDS ) to all { @ link SDocument } elements of the
* salt project .
* @ param p The salt project to add the features to .
* @ param matchGroup A list of matches in the same order as the corpus graphs
* of the salt project . */
public static void addMatchInformation ( SaltProject p , MatchGroup matchGroup ) { } } | int matchIndex = 0 ; for ( Match m : matchGroup . getMatches ( ) ) { // get the corresponding SDocument of the salt project
SCorpusGraph corpusGraph = p . getCorpusGraphs ( ) . get ( matchIndex ) ; SDocument doc = corpusGraph . getDocuments ( ) . get ( 0 ) ; setMatchedIDs ( doc . getDocumentGraph ( ) , m ) ; matchIndex ++ ; } |
public class ByteBufUtil { /** * Fast - Path implementation */
static int writeAscii ( AbstractByteBuf buffer , int writerIndex , CharSequence seq , int len ) { } } | // We can use the _ set methods as these not need to do any index checks and reference checks .
// This is possible as we called ensureWritable ( . . . ) before .
for ( int i = 0 ; i < len ; i ++ ) { buffer . _setByte ( writerIndex ++ , AsciiString . c2b ( seq . charAt ( i ) ) ) ; } return len ; |
public class ClassGenericsUtil { /** * Instantiate a parameterizable class . When using this , consider using
* { @ link Parameterization # descend } !
* @ param < C > base type
* @ param r Base ( restriction ) class
* @ param c Class to instantiate
* @ param config Configuration to use for instantiation .
* @ return Instance
* @ throws ClassInstantiationException When a class cannot be instantiated . */
public static < C > C tryInstantiate ( Class < C > r , Class < ? > c , Parameterization config ) throws ClassInstantiationException { } } | if ( c == null ) { throw new ClassInstantiationException ( "Trying to instantiate 'null' class!" ) ; } try { // Try a V3 parameterization class
Parameterizer par = getParameterizer ( c ) ; if ( par instanceof AbstractParameterizer ) { return r . cast ( ( ( AbstractParameterizer ) par ) . make ( config ) ) ; } // Try a default constructor .
return r . cast ( c . getConstructor ( ) . newInstance ( ) ) ; } catch ( InstantiationException | InvocationTargetException | IllegalAccessException | NoSuchMethodException e ) { throw new ClassInstantiationException ( e ) ; } |
public class FileUtils { /** * Checks whether given name is valid for current user OS .
* @ param name that will be checked
* @ return true if name is valid , false otherwise */
public static boolean isValidFileName ( String name ) { } } | try { if ( OsUtils . isWindows ( ) ) { if ( name . contains ( ">" ) || name . contains ( "<" ) ) return false ; name = name . toLowerCase ( ) ; // Windows is case insensitive
} return new File ( name ) . getCanonicalFile ( ) . getName ( ) . equals ( name ) ; } catch ( Exception e ) { return false ; } |
public class PainterVisitor { /** * Retrieve the full list of painter for a specific type of paintable object .
* @ param paintable
* The type of object to retrieve painter for .
* @ return Return a list of painter , or null . */
public List < Painter > getPaintersForObject ( Paintable paintable ) { } } | String className = paintable . getClass ( ) . getName ( ) ; if ( painters . containsKey ( className ) ) { return painters . get ( className ) ; } return null ; |
public class ProjectApi { /** * Creates new project owned by the current user . The following properties on the Project instance
* are utilized in the creation of the project :
* name ( name or path are required ) - new project name
* path ( name or path are required ) - new project path
* defaultBranch ( optional ) - master by default
* description ( optional ) - short project description
* visibility ( optional ) - Limit by visibility public , internal , or private
* visibilityLevel ( optional )
* issuesEnabled ( optional ) - Enable issues for this project
* mergeMethod ( optional ) - Set the merge method used
* mergeRequestsEnabled ( optional ) - Enable merge requests for this project
* wikiEnabled ( optional ) - Enable wiki for this project
* snippetsEnabled ( optional ) - Enable snippets for this project
* jobsEnabled ( optional ) - Enable jobs for this project
* containerRegistryEnabled ( optional ) - Enable container registry for this project
* sharedRunnersEnabled ( optional ) - Enable shared runners for this project
* publicJobs ( optional ) - If true , jobs can be viewed by non - project - members
* onlyAllowMergeIfPipelineSucceeds ( optional ) - Set whether merge requests can only be merged with successful jobs
* onlyAllowMergeIfAllDiscussionsAreResolved ( optional ) - Set whether merge requests can only be merged when all the discussions are resolved
* lLfsEnabled ( optional ) - Enable LFS
* requestAccessEnabled ( optional ) - Allow users to request member access
* repositoryStorage ( optional ) - Which storage shard the repository is on . Available only to admins
* approvalsBeforeMerge ( optional ) - How many approvers should approve merge request by default
* printingMergeRequestLinkEnabled ( optional ) - Show link to create / view merge request when pushing from the command line
* resolveOutdatedDiffDiscussions ( optional ) - Automatically resolve merge request diffs discussions on lines changed with a push
* initialize _ with _ readme ( optional ) - Initialize project with README file
* packagesEnabled ( optional ) - Enable or disable mvn packages repository feature
* @ param project the Project instance with the configuration for the new project
* @ param importUrl the URL to import the repository from
* @ return a Project instance with the newly created project info
* @ throws GitLabApiException if any exception occurs */
public Project createProject ( Project project , String importUrl ) throws GitLabApiException { } } | if ( project == null ) { return ( null ) ; } String name = project . getName ( ) ; String path = project . getPath ( ) ; if ( ( name == null || name . trim ( ) . length ( ) == 0 ) && ( path == null || path . trim ( ) . length ( ) == 0 ) ) { return ( null ) ; } GitLabApiForm formData = new GitLabApiForm ( ) . withParam ( "name" , name ) . withParam ( "path" , path ) . withParam ( "default_branch" , project . getDefaultBranch ( ) ) . withParam ( "description" , project . getDescription ( ) ) . withParam ( "issues_enabled" , project . getIssuesEnabled ( ) ) . withParam ( "merge_method" , project . getMergeMethod ( ) ) . withParam ( "merge_requests_enabled" , project . getMergeRequestsEnabled ( ) ) . withParam ( "jobs_enabled" , project . getJobsEnabled ( ) ) . withParam ( "wiki_enabled" , project . getWikiEnabled ( ) ) . withParam ( "container_registry_enabled" , project . getContainerRegistryEnabled ( ) ) . withParam ( "snippets_enabled" , project . getSnippetsEnabled ( ) ) . withParam ( "shared_runners_enabled" , project . getSharedRunnersEnabled ( ) ) . withParam ( "public_jobs" , project . getPublicJobs ( ) ) . withParam ( "visibility_level" , project . getVisibilityLevel ( ) ) . withParam ( "only_allow_merge_if_pipeline_succeeds" , project . getOnlyAllowMergeIfPipelineSucceeds ( ) ) . withParam ( "only_allow_merge_if_all_discussions_are_resolved" , project . getOnlyAllowMergeIfAllDiscussionsAreResolved ( ) ) . withParam ( "lfs_enabled" , project . getLfsEnabled ( ) ) . withParam ( "request_access_enabled" , project . getRequestAccessEnabled ( ) ) . withParam ( "repository_storage" , project . getRepositoryStorage ( ) ) . withParam ( "approvals_before_merge" , project . getApprovalsBeforeMerge ( ) ) . withParam ( "import_url" , importUrl ) . withParam ( "printing_merge_request_link_enabled" , project . getPrintingMergeRequestLinkEnabled ( ) ) . withParam ( "resolve_outdated_diff_discussions" , project . getResolveOutdatedDiffDiscussions ( ) ) . withParam ( "initialize_with_readme" , project . getInitializeWithReadme ( ) ) . withParam ( "packages_enabled" , project . getPackagesEnabled ( ) ) ; if ( isApiVersion ( ApiVersion . V3 ) ) { boolean isPublic = ( project . getPublic ( ) != null ? project . getPublic ( ) : project . getVisibility ( ) == Visibility . PUBLIC ) ; formData . withParam ( "public" , isPublic ) ; if ( project . getTagList ( ) != null && ! project . getTagList ( ) . isEmpty ( ) ) { throw new IllegalArgumentException ( "GitLab API v3 does not support tag lists when creating projects" ) ; } } else { Visibility visibility = ( project . getVisibility ( ) != null ? project . getVisibility ( ) : project . getPublic ( ) == Boolean . TRUE ? Visibility . PUBLIC : null ) ; formData . withParam ( "visibility" , visibility ) ; if ( project . getTagList ( ) != null && ! project . getTagList ( ) . isEmpty ( ) ) { formData . withParam ( "tag_list" , String . join ( "," , project . getTagList ( ) ) ) ; } } if ( project . getNamespace ( ) != null ) { formData . withParam ( "namespace_id" , project . getNamespace ( ) . getId ( ) ) ; } Response response = post ( Response . Status . CREATED , formData , "projects" ) ; return ( response . readEntity ( Project . class ) ) ; |
public class BuilderUtils { /** * Checks if there is a default constructor available .
* @ param item The clazz to check .
* @ return True if default constructor is found , false otherwise . */
public static boolean hasDefaultConstructor ( TypeRef item ) { } } | DefinitionRepository repository = DefinitionRepository . getRepository ( ) ; TypeDef def = repository . getDefinition ( item ) ; if ( def == null && item instanceof ClassRef ) { def = ( ( ClassRef ) item ) . getDefinition ( ) ; } return hasDefaultConstructor ( def ) ; |
public class StreamsUtils { /** * < p > Generates a stream composed of the N greatest values of the provided stream , compared using the
* natural order . This method calls the < code > filteringMaxValues ( ) < / code > with the natural order comparator ,
* please refer to this javadoc for details . . < / p >
* < p > A < code > NullPointerException < / code > will be thrown if the provided stream . < / p >
* < p > An < code > IllegalArgumentException < / code > is thrown if N is lesser than 1 . < / p >
* @ param stream the processed stream
* @ param numberOfMaxes the number of different max values that should be returned . Note that the total number of
* values returned may be larger if there are duplicates in the stream
* @ param < E > the type of the provided stream
* @ return the filtered stream */
public static < E extends Comparable < ? super E > > Stream < E > filteringMaxValues ( Stream < E > stream , int numberOfMaxes ) { } } | return filteringMaxValues ( stream , numberOfMaxes , Comparator . naturalOrder ( ) ) ; |
public class StatementManager { /** * Compiles an SQL statement and returns a CompiledStatement Object
* @ param session the session
* @ throws Throwable
* @ return CompiledStatement */
synchronized Statement compile ( Session session , Result cmd ) throws Throwable { } } | String sql = cmd . getMainString ( ) ; long csid = getStatementID ( session . currentSchema , sql ) ; Statement cs = ( Statement ) csidMap . get ( csid ) ; if ( cs == null || ! cs . isValid ( ) || ! session . isAdmin ( ) ) { Session sys = database . sessionManager . getSysSession ( session . currentSchema . name , session . getUser ( ) ) ; cs = sys . compileStatement ( sql ) ; csid = registerStatement ( csid , cs ) ; } linkSession ( csid , session . getId ( ) ) ; return cs ; |
public class DefaultEntityResolve { /** * 处理字段
* @ param entityTable
* @ param field
* @ param config
* @ param style */
protected void processField ( EntityTable entityTable , EntityField field , Config config , Style style ) { } } | // 排除字段
if ( field . isAnnotationPresent ( Transient . class ) ) { return ; } // Id
EntityColumn entityColumn = new EntityColumn ( entityTable ) ; // 是否使用 { xx , javaType = xxx }
entityColumn . setUseJavaType ( config . isUseJavaType ( ) ) ; // 记录 field 信息 , 方便后续扩展使用
entityColumn . setEntityField ( field ) ; if ( field . isAnnotationPresent ( Id . class ) ) { entityColumn . setId ( true ) ; } // Column
String columnName = null ; if ( field . isAnnotationPresent ( Column . class ) ) { Column column = field . getAnnotation ( Column . class ) ; columnName = column . name ( ) ; entityColumn . setUpdatable ( column . updatable ( ) ) ; entityColumn . setInsertable ( column . insertable ( ) ) ; } // ColumnType
if ( field . isAnnotationPresent ( ColumnType . class ) ) { ColumnType columnType = field . getAnnotation ( ColumnType . class ) ; // 是否为 blob 字段
entityColumn . setBlob ( columnType . isBlob ( ) ) ; // column可以起到别名的作用
if ( StringUtil . isEmpty ( columnName ) && StringUtil . isNotEmpty ( columnType . column ( ) ) ) { columnName = columnType . column ( ) ; } if ( columnType . jdbcType ( ) != JdbcType . UNDEFINED ) { entityColumn . setJdbcType ( columnType . jdbcType ( ) ) ; } if ( columnType . typeHandler ( ) != UnknownTypeHandler . class ) { entityColumn . setTypeHandler ( columnType . typeHandler ( ) ) ; } } // 列名
if ( StringUtil . isEmpty ( columnName ) ) { columnName = StringUtil . convertByStyle ( field . getName ( ) , style ) ; } // 自动处理关键字
if ( StringUtil . isNotEmpty ( config . getWrapKeyword ( ) ) && SqlReservedWords . containsWord ( columnName ) ) { columnName = MessageFormat . format ( config . getWrapKeyword ( ) , columnName ) ; } entityColumn . setProperty ( field . getName ( ) ) ; entityColumn . setColumn ( columnName ) ; entityColumn . setJavaType ( field . getJavaType ( ) ) ; if ( field . getJavaType ( ) . isPrimitive ( ) ) { log . warn ( "通用 Mapper 警告信息: <[" + entityColumn + "]> 使用了基本类型,基本类型在动态 SQL 中由于存在默认值,因此任何时候都不等于 null,建议修改基本类型为对应的包装类型!" ) ; } // OrderBy
processOrderBy ( entityTable , field , entityColumn ) ; // 处理主键策略
processKeyGenerator ( entityTable , field , entityColumn ) ; entityTable . getEntityClassColumns ( ) . add ( entityColumn ) ; if ( entityColumn . isId ( ) ) { entityTable . getEntityClassPKColumns ( ) . add ( entityColumn ) ; } |
public class PlacesInterface { /** * Find Flickr Places information by Place ID .
* @ deprecated This method has been deprecated . It won ' t be removed but you should use { @ link # getInfo ( String , String ) } instead .
* @ param placeId
* @ return A Location
* @ throws FlickrException */
@ Deprecated public Location resolvePlaceId ( String placeId ) throws FlickrException { } } | Map < String , Object > parameters = new HashMap < String , Object > ( ) ; parameters . put ( "method" , METHOD_RESOLVE_PLACE_ID ) ; parameters . put ( "place_id" , placeId ) ; Response response = transportAPI . get ( transportAPI . getPath ( ) , parameters , apiKey , sharedSecret ) ; if ( response . isError ( ) ) { throw new FlickrException ( response . getErrorCode ( ) , response . getErrorMessage ( ) ) ; } Element locationElement = response . getPayload ( ) ; return parseLocation ( locationElement ) ; |
public class PaymentMethod { /** * Attaches a PaymentMethod object to a Customer . */
public PaymentMethod attach ( Map < String , Object > params ) throws StripeException { } } | return attach ( params , ( RequestOptions ) null ) ; |
public class WebSecurityScannerClient { /** * Lists ScanConfigs under a given project .
* < p > Sample code :
* < pre > < code >
* try ( WebSecurityScannerClient webSecurityScannerClient = WebSecurityScannerClient . create ( ) ) {
* ProjectName parent = ProjectName . of ( " [ PROJECT ] " ) ;
* for ( ScanConfig element : webSecurityScannerClient . listScanConfigs ( parent ) . iterateAll ( ) ) {
* / / doThingsWith ( element ) ;
* < / code > < / pre >
* @ param parent Required . The parent resource name , which should be a project resource name in
* the format ' projects / { projectId } ' .
* @ throws com . google . api . gax . rpc . ApiException if the remote call fails */
public final ListScanConfigsPagedResponse listScanConfigs ( ProjectName parent ) { } } | ListScanConfigsRequest request = ListScanConfigsRequest . newBuilder ( ) . setParent ( parent == null ? null : parent . toString ( ) ) . build ( ) ; return listScanConfigs ( request ) ; |
public class VisOdomQuadPnP { /** * Resets the algorithm into its original state */
public void reset ( ) { } } | featsLeft0 . reset ( ) ; featsLeft1 . reset ( ) ; featsRight0 . reset ( ) ; featsRight1 . reset ( ) ; for ( SetMatches m : setMatches ) m . reset ( ) ; newToOld . reset ( ) ; leftCamToWorld . reset ( ) ; first = true ; |
public class DBInstance { /** * The AWS Identity and Access Management ( IAM ) roles associated with the DB instance .
* @ return The AWS Identity and Access Management ( IAM ) roles associated with the DB instance . */
public java . util . List < DBInstanceRole > getAssociatedRoles ( ) { } } | if ( associatedRoles == null ) { associatedRoles = new com . amazonaws . internal . SdkInternalList < DBInstanceRole > ( ) ; } return associatedRoles ; |
public class SignatureUtil { /** * Scans the given string for a class type signature starting at the given
* index and returns the index of the last character .
* < pre >
* ClassTypeSignature :
* { < b > L < / b > | < b > Q < / b > } Identifier
* { { < b > / < / b > | < b > . < / b > Identifier [ < b > & lt ; < / b > TypeArgumentSignature * < b > & gt ; < / b > ] }
* < b > ; < / b >
* < / pre >
* Note that although all " / " - identifiers most come before " . " - identifiers ,
* there is no syntactic ambiguity . This method will accept them without
* complaint .
* @ param string the signature string
* @ param start the 0 - based character index of the first character
* @ return the 0 - based character index of the last character
* @ exception IllegalArgumentException if this is not a class type signature */
private static int scanClassTypeSignature ( String string , int start ) { } } | // need a minimum 3 chars " Lx ; "
if ( start >= string . length ( ) - 2 ) { throw new IllegalArgumentException ( ) ; } // must start in " L " or " Q "
char c = string . charAt ( start ) ; if ( c != C_RESOLVED && c != C_UNRESOLVED ) { return - 1 ; } int p = start + 1 ; while ( true ) { if ( p >= string . length ( ) ) { throw new IllegalArgumentException ( ) ; } c = string . charAt ( p ) ; if ( c == C_SEMICOLON ) { // all done
return p ; } else if ( c == C_GENERIC_START ) { int e = scanTypeArgumentSignatures ( string , p ) ; p = e ; } else if ( c == C_DOT || c == '/' ) { int id = scanIdentifier ( string , p + 1 ) ; p = id ; } p ++ ; } |
public class EvaluatorImpl { /** * Evaluates a selector tree without resolving identifiers ( usually applied only to
* Selector subtrees with numIds = = 0 ) .
* @ param sel the selector tree to evaluate
* @ return the result , which will be a String , a BooleanValue , a NumericValue , or null .
* Null is used for " missing " Numeric or String values . BooleanValue . NULL is used for
* missing Boolean values . */
public Object eval ( Selector sel ) { } } | try { return eval ( sel , MatchSpaceKey . DUMMY , EvalCache . DUMMY , null , false ) ; } catch ( BadMessageFormatMatchingException e ) { // No FFDC Code Needed .
// FFDC driven by wrapper class .
FFDC . processException ( this , cclass , "com.ibm.ws.sib.matchspace.selector.impl.Evaluator.eval" , e , "1:145:1.28" ) ; // TODO : Pass " sel " in FFDC or merely trace ?
// This truly does not happen ( see MatchSpaceKey . DUMMY )
throw new IllegalStateException ( ) ; } |
public class ProjectCalendarContainer { /** * This is a convenience method used to add a calendar called
* " Standard " to the project , and populate it with a default working week
* and default working hours .
* @ return a new default calendar */
public ProjectCalendar addDefaultBaseCalendar ( ) { } } | ProjectCalendar calendar = add ( ) ; calendar . setName ( ProjectCalendar . DEFAULT_BASE_CALENDAR_NAME ) ; calendar . setWorkingDay ( Day . SUNDAY , false ) ; calendar . setWorkingDay ( Day . MONDAY , true ) ; calendar . setWorkingDay ( Day . TUESDAY , true ) ; calendar . setWorkingDay ( Day . WEDNESDAY , true ) ; calendar . setWorkingDay ( Day . THURSDAY , true ) ; calendar . setWorkingDay ( Day . FRIDAY , true ) ; calendar . setWorkingDay ( Day . SATURDAY , false ) ; calendar . addDefaultCalendarHours ( ) ; return ( calendar ) ; |
public class CreateVolumePermissionModifications { /** * Removes the specified AWS account ID or group from the list .
* < b > NOTE : < / b > This method appends the values to the existing list ( if any ) . Use
* { @ link # setRemove ( java . util . Collection ) } or { @ link # withRemove ( java . util . Collection ) } if you want to override the
* existing values .
* @ param remove
* Removes the specified AWS account ID or group from the list .
* @ return Returns a reference to this object so that method calls can be chained together . */
public CreateVolumePermissionModifications withRemove ( CreateVolumePermission ... remove ) { } } | if ( this . remove == null ) { setRemove ( new com . amazonaws . internal . SdkInternalList < CreateVolumePermission > ( remove . length ) ) ; } for ( CreateVolumePermission ele : remove ) { this . remove . add ( ele ) ; } return this ; |
public class ProtoLexer { /** * $ ANTLR start " ID " */
public final void mID ( ) throws RecognitionException { } } | try { int _type = ID ; int _channel = DEFAULT_TOKEN_CHANNEL ; // com / dyuproject / protostuff / parser / ProtoLexer . g : 231:5 : ( ( ' a ' . . ' z ' | ' A ' . . ' Z ' | ' _ ' ) ( ' a ' . . ' z ' | ' A ' . . ' Z ' | ' 0 ' . . ' 9 ' | ' _ ' ) * )
// com / dyuproject / protostuff / parser / ProtoLexer . g : 231:9 : ( ' a ' . . ' z ' | ' A ' . . ' Z ' | ' _ ' ) ( ' a ' . . ' z ' | ' A ' . . ' Z ' | ' 0 ' . . ' 9 ' | ' _ ' ) *
{ if ( ( input . LA ( 1 ) >= 'A' && input . LA ( 1 ) <= 'Z' ) || input . LA ( 1 ) == '_' || ( input . LA ( 1 ) >= 'a' && input . LA ( 1 ) <= 'z' ) ) { input . consume ( ) ; } else { MismatchedSetException mse = new MismatchedSetException ( null , input ) ; recover ( mse ) ; throw mse ; } // com / dyuproject / protostuff / parser / ProtoLexer . g : 231:33 : ( ' a ' . . ' z ' | ' A ' . . ' Z ' | ' 0 ' . . ' 9 ' | ' _ ' ) *
loop2 : do { int alt2 = 2 ; switch ( input . LA ( 1 ) ) { case '0' : case '1' : case '2' : case '3' : case '4' : case '5' : case '6' : case '7' : case '8' : case '9' : case 'A' : case 'B' : case 'C' : case 'D' : case 'E' : case 'F' : case 'G' : case 'H' : case 'I' : case 'J' : case 'K' : case 'L' : case 'M' : case 'N' : case 'O' : case 'P' : case 'Q' : case 'R' : case 'S' : case 'T' : case 'U' : case 'V' : case 'W' : case 'X' : case 'Y' : case 'Z' : case '_' : case 'a' : case 'b' : case 'c' : case 'd' : case 'e' : case 'f' : case 'g' : case 'h' : case 'i' : case 'j' : case 'k' : case 'l' : case 'm' : case 'n' : case 'o' : case 'p' : case 'q' : case 'r' : case 's' : case 't' : case 'u' : case 'v' : case 'w' : case 'x' : case 'y' : case 'z' : { alt2 = 1 ; } break ; } switch ( alt2 ) { case 1 : // com / dyuproject / protostuff / parser / ProtoLexer . g :
{ if ( ( input . LA ( 1 ) >= '0' && input . LA ( 1 ) <= '9' ) || ( input . LA ( 1 ) >= 'A' && input . LA ( 1 ) <= 'Z' ) || input . LA ( 1 ) == '_' || ( input . LA ( 1 ) >= 'a' && input . LA ( 1 ) <= 'z' ) ) { input . consume ( ) ; } else { MismatchedSetException mse = new MismatchedSetException ( null , input ) ; recover ( mse ) ; throw mse ; } } break ; default : break loop2 ; } } while ( true ) ; } state . type = _type ; state . channel = _channel ; } finally { } |
public class Task { /** * Handle the change in a field value . Reset any cached calculated
* values affected by this change , pass on the event to any external
* listeners .
* @ param field field changed
* @ param oldValue old field value
* @ param newValue new field value */
private void fireFieldChangeEvent ( TaskField field , Object oldValue , Object newValue ) { } } | // Internal event handling
switch ( field ) { case UNIQUE_ID : { ProjectFile parent = getParentFile ( ) ; if ( oldValue != null ) { parent . getTasks ( ) . unmapUniqueID ( ( Integer ) oldValue ) ; } parent . getTasks ( ) . mapUniqueID ( ( Integer ) newValue , this ) ; break ; } case START : case BASELINE_START : { m_array [ TaskField . START_VARIANCE . getValue ( ) ] = null ; break ; } case FINISH : case BASELINE_FINISH : { m_array [ TaskField . FINISH_VARIANCE . getValue ( ) ] = null ; break ; } case COST : case BASELINE_COST : { m_array [ TaskField . COST_VARIANCE . getValue ( ) ] = null ; break ; } case DURATION : { m_array [ TaskField . DURATION_VARIANCE . getValue ( ) ] = null ; m_array [ TaskField . COMPLETE_THROUGH . getValue ( ) ] = null ; break ; } case BASELINE_DURATION : { m_array [ TaskField . DURATION_VARIANCE . getValue ( ) ] = null ; break ; } case WORK : case BASELINE_WORK : { m_array [ TaskField . WORK_VARIANCE . getValue ( ) ] = null ; break ; } case BCWP : case ACWP : { m_array [ TaskField . CV . getValue ( ) ] = null ; m_array [ TaskField . SV . getValue ( ) ] = null ; break ; } case BCWS : { m_array [ TaskField . SV . getValue ( ) ] = null ; break ; } case START_SLACK : case FINISH_SLACK : { m_array [ TaskField . TOTAL_SLACK . getValue ( ) ] = null ; m_array [ TaskField . CRITICAL . getValue ( ) ] = null ; break ; } case EARLY_FINISH : case LATE_FINISH : { m_array [ TaskField . FINISH_SLACK . getValue ( ) ] = null ; m_array [ TaskField . TOTAL_SLACK . getValue ( ) ] = null ; m_array [ TaskField . CRITICAL . getValue ( ) ] = null ; break ; } case EARLY_START : case LATE_START : { m_array [ TaskField . START_SLACK . getValue ( ) ] = null ; m_array [ TaskField . TOTAL_SLACK . getValue ( ) ] = null ; m_array [ TaskField . CRITICAL . getValue ( ) ] = null ; break ; } case ACTUAL_START : case PERCENT_COMPLETE : { m_array [ TaskField . COMPLETE_THROUGH . getValue ( ) ] = null ; break ; } default : { break ; } } // External event handling
if ( m_listeners != null ) { for ( FieldListener listener : m_listeners ) { listener . fieldChange ( this , field , oldValue , newValue ) ; } } |
public class CustomPostProcessorChainWrapper { /** * ( non - Javadoc )
* @ see net . jawr . web . resource . bundle . postprocess .
* AbstractChainedResourceBundlePostProcessor # doPostProcessBundle ( net . jawr .
* web . resource . bundle . postprocess . BundleProcessingStatus ,
* java . lang . StringBuffer ) */
@ Override protected StringBuffer doPostProcessBundle ( BundleProcessingStatus status , StringBuffer bundleData ) throws IOException { } } | return customPostProcessor . postProcessBundle ( status , bundleData ) ; |
public class Default { protected void writeHeaders ( HttpServletResponse response , Resource resource , long count ) throws IOException { } } | ResourceCache . ResourceMetaData metaData = _httpContext . getResourceMetaData ( resource ) ; response . setContentType ( metaData . getMimeType ( ) ) ; if ( count != - 1 ) { if ( count == resource . length ( ) && response instanceof ServletHttpResponse ) response . setHeader ( HttpFields . __ContentLength , metaData . getLength ( ) ) ; else response . setContentLength ( ( int ) count ) ; } response . setHeader ( HttpFields . __LastModified , metaData . getLastModified ( ) ) ; if ( _acceptRanges ) response . setHeader ( HttpFields . __AcceptRanges , "bytes" ) ; |
public class ExceptionWindow { /** * Build details message for an exception .
* @ param error error to build message for
* @ return HTML string with details message */
private String getDetails ( ExceptionDto error ) { } } | if ( null == error ) { return "" ; } StringBuilder content = new StringBuilder ( ) ; String header = error . getClassName ( ) ; if ( error . getExceptionCode ( ) != 0 ) { header += " (" + error . getExceptionCode ( ) + ")" ; } content . append ( HtmlBuilder . divStyle ( WidgetLayout . exceptionWindowDetailHeaderStyle , header ) ) ; for ( StackTraceElement el : error . getStackTrace ( ) ) { String style = WidgetLayout . exceptionWindowDetailTraceNormalStyle ; String line = el . toString ( ) ; if ( ( line . startsWith ( "org.geomajas." ) && ! line . startsWith ( "org.geomajas.example." ) ) || line . startsWith ( "org.springframework." ) || line . startsWith ( "org.hibernate." ) || line . startsWith ( "org.hibernatespatial." ) || line . startsWith ( "org.geotools." ) || line . startsWith ( "com.vividsolutions." ) || line . startsWith ( "org.mortbay.jetty." ) || line . startsWith ( "sun." ) || line . startsWith ( "java." ) || line . startsWith ( "javax." ) || line . startsWith ( "com.google." ) || line . startsWith ( "$Proxy" ) ) { style = WidgetLayout . exceptionWindowDetailTraceLessStyle ; } content . append ( HtmlBuilder . divStyle ( style , line ) ) ; } content . append ( getDetails ( error . getCause ( ) ) ) ; return content . toString ( ) ; |
public class VerifierFactory { /** * processes a schema into a Schema object , which is a compiled representation
* of a schema .
* The obtained schema object can then be used concurrently across multiple
* threads .
* @ paramstream
* A stream object that holds a schema . */
public Schema compileSchema ( InputStream stream ) throws VerifierConfigurationException , SAXException , IOException { } } | return compileSchema ( stream , null ) ; |
public class ApiOvhLicensevirtuozzo { /** * Will tell if the ip can accept the license
* REST : GET / license / virtuozzo / { serviceName } / canLicenseBeMovedTo
* @ param destinationIp [ required ] The Ip on which you want to move this license
* @ param serviceName [ required ] The name of your Virtuozzo license */
public OvhChangeIpStatus serviceName_canLicenseBeMovedTo_GET ( String serviceName , String destinationIp ) throws IOException { } } | String qPath = "/license/virtuozzo/{serviceName}/canLicenseBeMovedTo" ; StringBuilder sb = path ( qPath , serviceName ) ; query ( sb , "destinationIp" , destinationIp ) ; String resp = exec ( qPath , "GET" , sb . toString ( ) , null ) ; return convertTo ( resp , OvhChangeIpStatus . class ) ; |
public class ProcessUtils { /** * 拷贝分页对象
* @ param clazz 目标类型
* @ param pageResponse 原对象
* @ param biConsumer 回调函数
* @ param < T > 原数据类型
* @ param < R > 目标数据类型
* @ return 目标对象 */
public static < T , R > PageResponse < R > processPage ( Class < R > clazz , PageResponse < T > pageResponse , BiConsumer < R , T > biConsumer ) { } } | if ( pageResponse == null || pageResponse . isEmpty ( ) ) { return PageResponse . empty ( ) ; } return PageResponse . apply ( pageResponse . getTotal ( ) , processList ( clazz , pageResponse . getData ( ) , biConsumer ) ) ; |
public class TileBoundingBoxUtils { /** * Get the Projected tile bounding box from the Google Maps API tile grid
* and zoom level
* @ param projection
* projection
* @ param tileGrid
* tile grid
* @ param zoom
* zoom level
* @ return bounding box */
public static BoundingBox getProjectedBoundingBox ( Projection projection , TileGrid tileGrid , int zoom ) { } } | BoundingBox boundingBox = getWebMercatorBoundingBox ( tileGrid , zoom ) ; if ( projection != null ) { ProjectionTransform transform = webMercator . getTransformation ( projection ) ; boundingBox = boundingBox . transform ( transform ) ; } return boundingBox ; |
public class InternalUtilities { /** * generateDefaultFormatterCE , This returns a default formatter for the specified locale , that
* can be used for displaying or parsing AD dates . The formatter is generated from the default
* FormatStyle . LONG formatter in the specified locale . */
public static DateTimeFormatter generateDefaultFormatterCE ( Locale pickerLocale ) { } } | DateTimeFormatter formatCE = new DateTimeFormatterBuilder ( ) . parseLenient ( ) . parseCaseInsensitive ( ) . appendLocalized ( FormatStyle . LONG , null ) . toFormatter ( pickerLocale ) ; // Get the local language as a string .
String language = pickerLocale . getLanguage ( ) ; // Override the format for the turkish locale to remove the name of the weekday .
if ( "tr" . equals ( language ) ) { formatCE = PickerUtilities . createFormatterFromPatternString ( "dd MMMM yyyy" , pickerLocale ) ; } // Return the generated format .
return formatCE ; |
public class ToolArbitrateEvent { /** * 添加一个index节点 */
public void addRemedyIndex ( RemedyIndexEventData data ) { } } | String path = StagePathUtils . getRemedyRoot ( data . getPipelineId ( ) ) ; try { zookeeper . create ( path + "/" + RemedyIndexEventData . formatNodeName ( data ) , new byte [ ] { } , CreateMode . PERSISTENT ) ; } catch ( ZkNodeExistsException e ) { // ignore
} catch ( ZkException e ) { throw new ArbitrateException ( "addRemedyIndex" , data . getPipelineId ( ) . toString ( ) , e ) ; } |
public class ServerLogReaderUtil { /** * We would skip the transaction if its id is less than or equal to current
* transaction id . */
static boolean shouldSkipOp ( long currentTransactionId , FSEditLogOp op ) { } } | if ( currentTransactionId == - 1 || op . getTransactionId ( ) > currentTransactionId ) { return false ; } return true ; |
public class SmileEnvelopeEventDeserializer { /** * Extracts all events in the stream
* Note : Stream must be formatted as an array of ( serialized ) SmileEnvelopeEvents .
* @ param in InputStream containing events
* @ return A list of SmileEnvelopeEvents
* @ throws IOException generic I / O exception */
public static List < SmileEnvelopeEvent > extractEvents ( final InputStream in ) throws IOException { } } | final PushbackInputStream pbIn = new PushbackInputStream ( in ) ; final byte firstByte = ( byte ) pbIn . read ( ) ; // EOF ?
if ( firstByte == - 1 ) { return null ; } pbIn . unread ( firstByte ) ; SmileEnvelopeEventDeserializer deser = ( firstByte == SMILE_MARKER ) ? new SmileEnvelopeEventDeserializer ( pbIn , false ) : new SmileEnvelopeEventDeserializer ( pbIn , true ) ; final List < SmileEnvelopeEvent > events = new LinkedList < SmileEnvelopeEvent > ( ) ; while ( deser . hasNextEvent ( ) ) { SmileEnvelopeEvent event = deser . getNextEvent ( ) ; if ( event == null ) { // TODO : this is NOT expected , should warn
break ; } events . add ( event ) ; } return events ; |
public class GeometryPackageImpl { /** * < ! - - begin - user - doc - - >
* < ! - - end - user - doc - - >
* @ generated */
public EClass getVector3f ( ) { } } | if ( vector3fEClass == null ) { vector3fEClass = ( EClass ) EPackage . Registry . INSTANCE . getEPackage ( GeometryPackage . eNS_URI ) . getEClassifiers ( ) . get ( 1 ) ; } return vector3fEClass ; |
public class Tokenizer { /** * Detect quote characters .
* TODO : support more than one quote character , make sure opening and closing
* quotes match then .
* @ param index Position
* @ return { @ code 1 } when a quote character , { @ code 0 } otherwise . */
private char isQuote ( int index ) { } } | if ( index >= input . length ( ) ) { return 0 ; } char c = input . charAt ( index ) ; for ( int i = 0 ; i < quoteChars . length ; i ++ ) { if ( c == quoteChars [ i ] ) { return c ; } } return 0 ; |
public class BaselineProfile { /** * Check CIELab .
* @ param metadata the metadata
* @ param n the IFD number */
private void CheckCIELab ( IfdTags metadata , int n ) { } } | // BitsPerSample
if ( ! metadata . containsTagId ( TiffTags . getTagId ( "BitsPerSample" ) ) ) { validation . addErrorLoc ( "Missing BitsPerSample" , "IFD" + n ) ; } else { for ( abstractTiffType vi : metadata . get ( TiffTags . getTagId ( "BitsPerSample" ) ) . getValue ( ) ) { if ( vi . toInt ( ) != 8 ) { validation . addError ( "Invalid BitsPerSample" , "IFD" + n , vi . toInt ( ) ) ; break ; } } } |
public class ArgP { /** * Appends the usage to the given buffer .
* @ param buf The buffer to write to . */
public void addUsageTo ( final StringBuilder buf ) { } } | final ArrayList < String > names = new ArrayList < String > ( options . keySet ( ) ) ; Collections . sort ( names ) ; int max_length = 0 ; for ( final String name : names ) { final String [ ] opt = options . get ( name ) ; final int length = name . length ( ) + ( opt [ 0 ] == null ? 0 : opt [ 0 ] . length ( ) + 1 ) ; if ( length > max_length ) { max_length = length ; } } for ( final String name : names ) { final String [ ] opt = options . get ( name ) ; int length = name . length ( ) ; buf . append ( " " ) . append ( name ) ; if ( opt [ 0 ] != null ) { length += opt [ 0 ] . length ( ) + 1 ; buf . append ( '=' ) . append ( opt [ 0 ] ) ; } for ( int i = length ; i <= max_length ; i ++ ) { buf . append ( ' ' ) ; } buf . append ( opt [ 1 ] ) . append ( '\n' ) ; } |
public class JsonHash { /** * see { @ link Map # put ( Object , Object ) } .
* this method is alternative of { @ link # put ( String , Object , Type ) } call with { @ link Type # HASH } .
* @ param key
* @ param value
* @ return see { @ link Map # put ( Object , Object ) }
* @ since 1.4.12
* @ author vvakame */
public Object put ( String key , JsonHash value ) { } } | if ( value == null ) { stateMap . put ( key , Type . NULL ) ; } else { stateMap . put ( key , Type . HASH ) ; } return super . put ( key , value ) ; |
public class CmsContainerConfigurationCache { /** * Updates a resource in the cache . < p >
* @ param structureId the structure id of the resource
* @ param rootPath the root path of the resource
* @ param type the resource type
* @ param state the resource state */
protected void update ( CmsUUID structureId , String rootPath , int type , CmsResourceState state ) { } } | if ( ! isContainerConfiguration ( rootPath , type ) ) { return ; } m_updateSet . add ( structureId ) ; |
public class GroupApi { /** * Updates a project group . Available only for users who can create groups .
* < pre > < code > GitLab Endpoint : PUT / groups < / code > < / pre >
* @ param groupIdOrPath the group ID , path of the group , or a Group instance holding the group ID or path
* @ param name the name of the group to add
* @ param path the path for the group
* @ param description ( optional ) - The group ' s description
* @ param visibility ( optional ) - The group ' s visibility . Can be private , internal , or public .
* @ param lfsEnabled ( optional ) - Enable / disable Large File Storage ( LFS ) for the projects in this group
* @ param requestAccessEnabled ( optional ) - Allow users to request member access
* @ param parentId ( optional ) - The parent group id for creating nested group
* @ return the updated Group instance
* @ throws GitLabApiException if any exception occurs */
public Group updateGroup ( Object groupIdOrPath , String name , String path , String description , Visibility visibility , Boolean lfsEnabled , Boolean requestAccessEnabled , Integer parentId ) throws GitLabApiException { } } | Form formData = new GitLabApiForm ( ) . withParam ( "name" , name ) . withParam ( "path" , path ) . withParam ( "description" , description ) . withParam ( "visibility" , visibility ) . withParam ( "lfs_enabled" , lfsEnabled ) . withParam ( "request_access_enabled" , requestAccessEnabled ) . withParam ( "parent_id" , isApiVersion ( ApiVersion . V3 ) ? null : parentId ) ; Response response = put ( Response . Status . OK , formData . asMap ( ) , "groups" , getGroupIdOrPath ( groupIdOrPath ) ) ; return ( response . readEntity ( Group . class ) ) ; |
public class RegisterJobDefinitionRequestMarshaller { /** * Marshall the given parameter object . */
public void marshall ( RegisterJobDefinitionRequest registerJobDefinitionRequest , ProtocolMarshaller protocolMarshaller ) { } } | if ( registerJobDefinitionRequest == null ) { throw new SdkClientException ( "Invalid argument passed to marshall(...)" ) ; } try { protocolMarshaller . marshall ( registerJobDefinitionRequest . getJobDefinitionName ( ) , JOBDEFINITIONNAME_BINDING ) ; protocolMarshaller . marshall ( registerJobDefinitionRequest . getType ( ) , TYPE_BINDING ) ; protocolMarshaller . marshall ( registerJobDefinitionRequest . getParameters ( ) , PARAMETERS_BINDING ) ; protocolMarshaller . marshall ( registerJobDefinitionRequest . getContainerProperties ( ) , CONTAINERPROPERTIES_BINDING ) ; protocolMarshaller . marshall ( registerJobDefinitionRequest . getNodeProperties ( ) , NODEPROPERTIES_BINDING ) ; protocolMarshaller . marshall ( registerJobDefinitionRequest . getRetryStrategy ( ) , RETRYSTRATEGY_BINDING ) ; protocolMarshaller . marshall ( registerJobDefinitionRequest . getTimeout ( ) , TIMEOUT_BINDING ) ; } catch ( Exception e ) { throw new SdkClientException ( "Unable to marshall request to JSON: " + e . getMessage ( ) , e ) ; } |
public class Actors { /** * abbreviation for Promise creation to make code more concise */
public static < T > IPromise < T > complete ( T res , Object err ) { } } | return new Promise < > ( res , err ) ; |
public class AuthenticationFilter { /** * Implements token based authentication . This simply creates a principal from the { @ link AuthToken }
* and then calls doFilterChain .
* @ param token the token
* @ param request the request
* @ param response the response
* @ param chain the filterchain
* @ throws IOException when I / O failure occurs in filter chain
* @ throws ServletException when servlet exception occurs during auth */
protected void doTokenAuth ( AuthToken token , HttpServletRequest request , HttpServletResponse response , FilterChain chain ) throws IOException , ServletException { } } | AuthPrincipal principal = new AuthPrincipal ( token . getPrincipal ( ) ) ; principal . addRoles ( token . getRoles ( ) ) ; doFilterChain ( request , response , chain , principal ) ; |
public class RemoteServiceProxy { /** * Returns a string that encodes the result of a method invocation .
* Effectively , this just removes any headers from the encoded response .
* @ param encodedResponse
* @ return string that encodes the result of a method invocation */
private static String getEncodedInstance ( String encodedResponse ) { } } | if ( isReturnValue ( encodedResponse ) || isThrownException ( encodedResponse ) ) { return encodedResponse . substring ( 4 ) ; } return encodedResponse ; |
public class XMLResource { /** * This method returns a collection of available resources . An available
* resource can be either a particular XML resource or a collection containing
* further XML resources .
* @ param system
* The associated system with this request .
* @ param resource
* The name of the requested resource .
* @ param uri
* The context information due to the requested URI .
* @ param headers
* { @ link HttpHeaders } information .
* @ return A collection of available resources . */
@ GET public Response getResource ( @ PathParam ( JaxRxConstants . SYSTEM ) final String system , @ PathParam ( JaxRxConstants . RESOURCE ) final String resource , @ Context final UriInfo uri , @ Context final HttpHeaders headers ) { } } | return getResource ( system , uri , resource , headers ) ; |
public class AbstractRemoteClient { /** * { @ inheritDoc }
* @ throws org . openbase . jul . exception . CouldNotPerformException { @ inheritDoc }
* @ throws java . lang . InterruptedException { @ inheritDoc } */
@ Override public < R , T extends Object > R callMethod ( final String methodName , final T argument , final long timeout ) throws CouldNotPerformException , InterruptedException { } } | final String shortArgument = RPCHelper . argumentToString ( argument ) ; validateMiddleware ( ) ; long retryTimeout = METHOD_CALL_START_TIMEOUT ; long validTimeout = timeout ; try { logger . debug ( "Calling method [" + methodName + "(" + shortArgument + ")] on scope: " + remoteServer . getScope ( ) . toString ( ) ) ; if ( ! isConnected ( ) ) { waitForConnectionState ( CONNECTED , timeout ) ; } if ( timeout > - 1 ) { retryTimeout = Math . min ( METHOD_CALL_START_TIMEOUT , validTimeout ) ; } while ( true ) { if ( ! isActive ( ) ) { throw new InvalidStateException ( "Remote service is not active!" ) ; } try { logger . debug ( "Calling method [" + methodName + "(" + shortArgument + ")] on scope: " + remoteServer . getScope ( ) . toString ( ) ) ; remoteServerWatchDog . waitForServiceActivation ( timeout , TimeUnit . MILLISECONDS ) ; final R returnValue = remoteServer . call ( methodName , argument , retryTimeout ) ; if ( retryTimeout != METHOD_CALL_START_TIMEOUT && retryTimeout > 15000 ) { logger . info ( "Method[" + methodName + "(" + shortArgument + ")] returned! Continue processing..." ) ; } return returnValue ; } catch ( TimeoutException ex ) { // check if timeout is set and handle
if ( timeout != - 1 ) { validTimeout -= retryTimeout ; if ( validTimeout <= 0 ) { ExceptionPrinter . printHistory ( ex , logger , LogLevel . WARN ) ; throw new TimeoutException ( "Could not call remote Method[" + methodName + "(" + shortArgument + ")] on Scope[" + remoteServer . getScope ( ) + "] in Time[" + timeout + "ms]." ) ; } retryTimeout = Math . min ( generateTimeout ( retryTimeout ) , validTimeout ) ; } else { retryTimeout = generateTimeout ( retryTimeout ) ; } // only print warning if timeout is too long .
if ( retryTimeout > 15000 ) { ExceptionPrinter . printHistory ( ex , logger , LogLevel . WARN ) ; logger . warn ( "Waiting for RPCServer[" + remoteServer . getScope ( ) + "] to call method [" + methodName + "(" + shortArgument + ")]. Next retry timeout in " + ( int ) ( Math . floor ( retryTimeout / 1000 ) ) + " sec." ) ; } else { ExceptionPrinter . printHistory ( ex , logger , LogLevel . DEBUG ) ; logger . debug ( "Waiting for RPCServer[" + remoteServer . getScope ( ) + "] to call method [" + methodName + "(" + shortArgument + ")]. Next retry timeout in " + ( int ) ( Math . floor ( retryTimeout / 1000 ) ) + " sec." ) ; } Thread . yield ( ) ; } } } catch ( TimeoutException ex ) { throw ex ; } catch ( CouldNotPerformException ex ) { throw new CouldNotPerformException ( "Could not call remote Method[" + methodName + "(" + shortArgument + ")] on Scope[" + remoteServer . getScope ( ) + "]." , ex ) ; } |
public class Workdays { /** * Get Workdays by Contract
* @ param contract Contract ID
* @ param fromDate Start date
* @ param tillDate End date
* @ param params ( Optional ) Parameters
* @ throwsJSONException If error occurred
* @ return { @ link JSONObject } */
public JSONObject getByContract ( String contract , String fromDate , String tillDate , HashMap < String , String > params ) throws JSONException { } } | return oClient . get ( "/team/v3/workdays/contracts/" + contract + "/" + fromDate + "," + tillDate , params ) ; |
public class RetryOnFailureXSiteCommand { /** * It builds a new instance with the destination site , the command and the retry policy .
* @ param backup the destination site .
* @ param command the command to invoke remotely .
* @ param retryPolicy the retry policy .
* @ return the new instance .
* @ throws java . lang . NullPointerException if any parameter is { @ code null } */
public static RetryOnFailureXSiteCommand newInstance ( XSiteBackup backup , XSiteReplicateCommand command , RetryPolicy retryPolicy ) { } } | assertNotNull ( backup , "XSiteBackup" ) ; assertNotNull ( command , "XSiteReplicateCommand" ) ; assertNotNull ( retryPolicy , "RetryPolicy" ) ; return new RetryOnFailureXSiteCommand ( Collections . singletonList ( backup ) , command , retryPolicy ) ; |
public class AbstractApi { /** * Convenience method for adding query and form parameters to a get ( ) or post ( ) call .
* @ param formData the Form containing the name / value pairs
* @ param name the name of the field / attribute to add
* @ param value the value of the field / attribute to add */
protected void addFormParam ( Form formData , String name , Object value ) throws IllegalArgumentException { } } | addFormParam ( formData , name , value , false ) ; |
public class Notification { /** * Returns the cool down expiration time of the notification given a metric , trigger combination .
* @ param trigger The trigger
* @ param metric The metric
* @ return cool down expiration time in milliseconds */
public long getCooldownExpirationByTriggerAndMetric ( Trigger trigger , Metric metric ) { } } | String key = _hashTriggerAndMetric ( trigger , metric ) ; return this . cooldownExpirationByTriggerAndMetric . containsKey ( key ) ? this . cooldownExpirationByTriggerAndMetric . get ( key ) : 0 ; |
public class InstrumentsCommandLine { /** * Removes stale iphonesimulator launchds hanging in the system */
public void removeStaleSimulatorLaunchds ( ) { } } | // The instruments crashes sometimes by throwing the following error in the logs
// The below logs were taken from Xcode5.1.1
// sim [ 2430:303 ] Multiple instances of launchd _ sim detected , using com . apple . iphonesimulator . launchd . 3bd855a
// instead of com . apple . iphonesimulator . launchd . 59ef76ee .
List < String > launchctlCmd = Arrays . asList ( "launchctl" , "list" ) ; Command cmd = new Command ( launchctlCmd , false ) ; SimulatorLaunchd simLaunchd = new SimulatorLaunchd ( ) ; cmd . registerListener ( simLaunchd ) ; cmd . executeAndWait ( true ) ; // Retrieve the stale iphonesimulator launch IDs
Set < String > simIDs = simLaunchd . getLaunchdIDs ( ) ; if ( simIDs . size ( ) > 0 ) { if ( log . isLoggable ( Level . FINE ) ) { log . log ( Level . FINE , "Removing stale iphonesimulator launchds: " + simIDs ) ; } String iphoneSimulatorPrefix = "com.apple.iphonesimulator.launchd." ; for ( String id : simIDs ) { launchctlCmd = Arrays . asList ( "launchctl" , "remove" , iphoneSimulatorPrefix + id ) ; cmd = new Command ( launchctlCmd , false ) ; cmd . executeAndWait ( true ) ; } } |
public class LineReader { /** * Reads the { @ code in } buffer as much as it can and adds all the read lines into the { @ code out } list . < p >
* If there is any outstanding data that is not read , it is stored into a temporary buffer and the next decode will
* prepend this data to the newly read data . < p >
* { @ link # dispose ( ) } must be called when the associated { @ link ChannelHandler } is removed from the pipeline .
* @ param in Buffer to decode .
* @ param out List to add the read lines to .
* @ param allocator Allocator to allocate new buffers , if required . */
public void decode ( ByteBuf in , List < Object > out , ByteBufAllocator allocator ) { } } | while ( in . isReadable ( ) ) { final int startIndex = in . readerIndex ( ) ; int lastReadIndex = in . forEachByte ( LINE_END_FINDER ) ; if ( - 1 == lastReadIndex ) { // Buffer end without line termination
if ( null == incompleteBuffer ) { incompleteBuffer = allocator . buffer ( DEFAULT_INITIAL_CAPACITY , maxLineLength ) ; } /* Add to the incomplete buffer */
incompleteBuffer . ensureWritable ( in . readableBytes ( ) ) ; incompleteBuffer . writeBytes ( in ) ; } else { ByteBuf lineBuf = in . readSlice ( lastReadIndex - startIndex ) ; String line ; if ( null != incompleteBuffer ) { line = incompleteBuffer . toString ( encoding ) + lineBuf . toString ( encoding ) ; incompleteBuffer . release ( ) ; incompleteBuffer = null ; } else { line = lineBuf . toString ( encoding ) ; } out . add ( line ) ; in . skipBytes ( 1 ) ; // Skip new line character .
} } |
public class SearchPortletController { /** * Get the { @ link PortalSearchResults } for the specified query id from the session . If there are
* no results null is returned . */
private PortalSearchResults getPortalSearchResults ( PortletRequest request , String queryId ) { } } | final PortletSession session = request . getPortletSession ( ) ; @ SuppressWarnings ( "unchecked" ) final Cache < String , PortalSearchResults > searchResultsCache = ( Cache < String , PortalSearchResults > ) session . getAttribute ( SEARCH_RESULTS_CACHE_NAME ) ; if ( searchResultsCache == null ) { return null ; } return searchResultsCache . getIfPresent ( queryId ) ; |
public class TreeInfo { /** * If this tree is an identifier or a field , return its symbol ,
* otherwise return null . */
public static Symbol symbol ( JCTree tree ) { } } | tree = skipParens ( tree ) ; switch ( tree . getTag ( ) ) { case IDENT : return ( ( JCIdent ) tree ) . sym ; case SELECT : return ( ( JCFieldAccess ) tree ) . sym ; case TYPEAPPLY : return symbol ( ( ( JCTypeApply ) tree ) . clazz ) ; case ANNOTATED_TYPE : return symbol ( ( ( JCAnnotatedType ) tree ) . underlyingType ) ; case REFERENCE : return ( ( JCMemberReference ) tree ) . sym ; default : return null ; } |
public class Invariants { /** * < p > A version of { @ link # checkInvariant ( boolean , String ) } that constructs a
* description message from the given format string and arguments . < / p >
* < p > Note that the use of variadic arguments may entail allocating memory on
* virtual machines that fail to eliminate the allocations with < i > escape
* analysis < / i > . < / p >
* @ param value The value
* @ param condition The predicate
* @ param format The format string
* @ param objects The format string arguments
* @ param < T > The precise type of values
* @ return { @ code value }
* @ since 1.1.0 */
public static < T > T checkInvariantV ( final T value , final boolean condition , final String format , final Object ... objects ) { } } | if ( ! condition ) { final Violations violations = singleViolation ( String . format ( format , objects ) ) ; throw new InvariantViolationException ( failedMessage ( value , violations ) , null , violations . count ( ) ) ; } return value ; |
public class MapComposedElement { /** * Set the specified point at the given index .
* < p > If the < var > index < / var > is negative , it will corresponds
* to an index starting from the end of the list .
* @ param index is the index of the desired point
* @ param point is the new value of the point
* @ param canonize indicates if the function { @ link # canonize ( int ) } must be called .
* @ return < code > true < / code > if the point was set , < code > false < / code > if
* the specified coordinates correspond to the already existing point .
* @ throws IndexOutOfBoundsException in case of error . */
public final boolean setPointAt ( int index , Point2D < ? , ? > point , boolean canonize ) { } } | return setPointAt ( index , point . getX ( ) , point . getY ( ) , canonize ) ; |
public class IsoParsableDateFormatter { /** * Formatter for a date .
* @ param year [ 0 . . 9999 ] .
* @ param month [ 1 . . 12 ] .
* @ param day day of month [ 1 . . 31 ] .
* @ return the ISO formatted date . */
public static String format ( Integer year , Integer month , Integer day ) { } } | Object [ ] _args = { year , month , day } ; return SHORT__DATE . format ( _args ) ; |
public class SecurityAlertEvent { /** * Add an active participant for the user reporting the security alert
* @ param userId The User ID of the user reporting the failure */
public void addReportingUser ( String userId ) { } } | addActiveParticipant ( userId , null , null , true , null , null ) ; |
public class SearchDictionary { /** * String [ ] validTypes = new String [ ]
* { " application / xhtml + xml " ,
* " application / x - dtbncx + xml " , " text / css " } ; */
void buildCSSTypesDictionary ( ) { } } | String description ; String value ; TextSearchDictionaryEntry de ; // search eval ( ) expression
description = "text/css" ; value = "text/css" ; de = new TextSearchDictionaryEntry ( description , value , MessageId . CSS_009 ) ; v . add ( de ) ; |
public class CatalogLexer { /** * Searches the beginning ( 4096 bytes ) of the InputStream for a Gettext
* charset declaration , and returns the charset name . The InputStream must
* support " mark " . It will be reset to the beginning of the stream . If no
* charset is found , UTF - 8 will be assumed .
* As with the Gettext tools , this only works for ASCII - compatible charsets .
* UTF - 16 is not supported .
* @ param markableStream
* @ return
* @ throws IOException
* @ throws UnsupportedEncodingException */
static String readGettextCharset ( InputStream markableStream ) throws IOException , UnsupportedEncodingException { } } | String charset = "UTF-8" ; int limit = 4096 ; markableStream . mark ( limit ) ; byte [ ] buf = new byte [ limit ] ; int count = markableStream . read ( buf ) ; markableStream . reset ( ) ; if ( count < 0 ) { throw new RuntimeException ( ) ; } String s = new String ( buf , 0 , count , "ASCII" ) ; Pattern pat = Pattern . compile ( "\"Content-Type:.*charset=([^ \t\\\\]*)[ \t\\\\]" ) ; Matcher matcher = pat . matcher ( s ) ; if ( matcher . find ( ) ) { charset = matcher . group ( 1 ) ; } else { // this regex is more prone to false positives inside comments , so
// we try the more specific regex ( above ) first
pat = Pattern . compile ( "charset=([^ \t\\\\]*)[ \t\\\\]" ) ; if ( matcher . find ( ) ) { charset = matcher . group ( 1 ) ; } } if ( charset . equals ( "CHARSET" ) ) { charset = "ASCII" ; } return charset ; |
public class GrailsASTUtils { /** * Tests whether the ClasNode implements the specified method name .
* @ param classNode The ClassNode
* @ param methodName The method name
* @ return true if it does implement the method */
public static boolean implementsZeroArgMethod ( ClassNode classNode , String methodName ) { } } | MethodNode method = classNode . getDeclaredMethod ( methodName , Parameter . EMPTY_ARRAY ) ; return method != null && ( method . isPublic ( ) || method . isProtected ( ) ) && ! method . isAbstract ( ) ; |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.