signature stringlengths 43 39.1k | implementation stringlengths 0 450k |
|---|---|
public class CacheControlHandlerInterceptor { /** * Returns an expires header value generated from the given
* { @ link CacheControl } annotation .
* @ param cacheControl the < code > CacheControl < / code > annotation from which to
* create the returned expires header value
* @ return the expires header value */
protected final long createExpiresHeader ( final CacheControl cacheControl ) { } } | final Calendar expires = new GregorianCalendar ( TimeZone . getTimeZone ( "GMT" ) ) ; if ( cacheControl . maxAge ( ) >= 0 ) { expires . add ( Calendar . SECOND , cacheControl . maxAge ( ) ) ; } return expires . getTime ( ) . getTime ( ) ; |
public class XsdAsmElements { /** * Generates the methods in a given class for a given child that the class is allowed to have .
* @ param classWriter The { @ link ClassWriter } where the method will be written .
* @ param childName The child name that represents a method .
* @ param classType The type of the class which contains the children elements .
* @ param apiName The name of the generated fluent interface .
* @ param annotationsDesc An array with annotation names to apply to the generated method . */
static void generateMethodsForElement ( ClassWriter classWriter , String childName , String classType , String apiName , String [ ] annotationsDesc ) { } } | childName = firstToLower ( getCleanName ( childName ) ) ; String childCamelName = firstToUpper ( childName ) ; String childType = getFullClassTypeName ( childCamelName , apiName ) ; String childTypeDesc = getFullClassTypeNameDesc ( childCamelName , apiName ) ; MethodVisitor mVisitor = classWriter . visitMethod ( ACC_PUBLIC , childName , "()" + childTypeDesc , "()L" + childType + "<TT;>;" , null ) ; for ( String annotationDesc : annotationsDesc ) { mVisitor . visitAnnotation ( annotationDesc , true ) ; } mVisitor . visitCode ( ) ; mVisitor . visitTypeInsn ( NEW , childType ) ; mVisitor . visitInsn ( DUP ) ; mVisitor . visitVarInsn ( ALOAD , 0 ) ; mVisitor . visitMethodInsn ( INVOKEINTERFACE , classType , "self" , "()" + elementTypeDesc , true ) ; mVisitor . visitMethodInsn ( INVOKESPECIAL , childType , CONSTRUCTOR , "(" + elementTypeDesc + ")V" , false ) ; mVisitor . visitInsn ( ARETURN ) ; mVisitor . visitMaxs ( 3 , 1 ) ; mVisitor . visitEnd ( ) ; |
public class GreenPepperXmlRpcClient { /** * { @ inheritDoc } */
@ SuppressWarnings ( "unchecked" ) public Set < Repository > getSpecificationRepositoriesOfAssociatedProject ( Repository repository , String identifier ) throws GreenPepperServerException { } } | Vector params = CollectionUtil . toVector ( repository . marshallize ( ) ) ; log . debug ( "Retrieving Specification repositories for Associated project. (Repo UID: " + repository . getUid ( ) + ")" ) ; Vector < Object > repositoriesParams = ( Vector < Object > ) execute ( XmlRpcMethodName . getSpecificationRepositoriesOfAssociatedProject , params , identifier ) ; return XmlRpcDataMarshaller . toRepositoryList ( repositoriesParams ) ; |
public class Condition { /** * 获取符合Hibernate的条件
* @ return */
public Criterion getCriterion ( Class < ? > persistentClass ) { } } | Expression exp = Expression . valueOf ( expression ) ; // 表达式为 : in , between ( 输入值为多个值 )
List < Expression > multivalueExpres = Arrays . asList ( Expression . in , Expression . nin , Expression . between , Expression . nbetween ) ; if ( multivalueExpres . contains ( exp ) ) { Object [ ] vals = null ; Class < ? extends Object > vType = value . getClass ( ) ; if ( vType . isArray ( ) ) { // value是数组类型
vals = ( Object [ ] ) value ; } else if ( Collection . class . isAssignableFrom ( vType ) ) { // value是集合类型
vals = ( ( Collection < ? > ) value ) . toArray ( ) ; } else if ( String . class . isAssignableFrom ( vType ) ) { // value值字符串类型 , 需要判断属性的类型 , 来包装
String [ ] strs = value . toString ( ) . split ( "," ) ; Class < ? > fieldType = Reflections . getDeclaredField ( persistentClass , property ) . getType ( ) ; if ( String . class . isAssignableFrom ( fieldType ) ) { vals = strs ; } try { if ( Number . class . isAssignableFrom ( fieldType ) ) { Method m = fieldType . getMethod ( "valueOf" , String . class ) ; vals = new Object [ strs . length ] ; for ( int i = 0 ; i < strs . length ; i ++ ) { vals [ i ] = m . invoke ( null , strs [ i ] . trim ( ) ) ; } } } catch ( Exception e ) { e . printStackTrace ( ) ; } } if ( null == vals ) { throw new RuntimeException ( "不支持的字段解析类型:" + vType + ", 对于表达式:" + exp + "的输入值" ) ; } switch ( exp ) { case in : return Restrictions . in ( property , vals ) ; case nin : return Restrictions . not ( Restrictions . in ( property , vals ) ) ; case between : return Restrictions . between ( property , vals [ 0 ] , vals [ 1 ] ) ; case nbetween : return Restrictions . not ( Restrictions . between ( property , vals [ 0 ] , vals [ 1 ] ) ) ; default : return null ; } } // 表达式为 : isNull , isEmpty , isNotNull , isNotEmpty , isNullOrIsEmpty ( 没有输入值 )
List < Expression > nullvalueExpres = Arrays . asList ( Expression . isNull , Expression . isNotNull , Expression . isEmpty , Expression . isNotEmpty , Expression . isNullOrIsEmpty ) ; if ( nullvalueExpres . contains ( exp ) ) { switch ( exp ) { case isNull : return Restrictions . isNull ( property ) ; case isNotNull : return Restrictions . isNotNull ( property ) ; case isEmpty : return Restrictions . isEmpty ( property ) ; case isNotEmpty : return Restrictions . isNotEmpty ( property ) ; case isNullOrIsEmpty : return Restrictions . or ( Restrictions . isNull ( property ) , Restrictions . isEmpty ( property ) ) ; default : return null ; } } // 获取属性的真实值
Object fieldValue = getFieldValue ( persistentClass , property , value . toString ( ) ) ; String fieldStringValue = fieldValue . toString ( ) ; switch ( exp ) { // 等于 , 不等于 , 大于 , 大于等于 , 小于 , 小于等于 ( 当使用属性比较时 , fieldStringValue 代表的就是另外一个属性了 )
case eq : return Restrictions . eq ( property , fieldValue ) ; case eqProperty : return Restrictions . eqProperty ( property , fieldStringValue ) ; case eqOrIsNull : return Restrictions . eqOrIsNull ( property , fieldValue ) ; case ne : return Restrictions . ne ( property , fieldValue ) ; case neProperty : return Restrictions . neProperty ( property , fieldStringValue ) ; case neOrIsNotNull : return Restrictions . neOrIsNotNull ( property , fieldValue ) ; case gt : return Restrictions . gt ( property , fieldValue ) ; case gtProperty : return Restrictions . gtProperty ( property , fieldStringValue ) ; case ge : return Restrictions . ge ( property , fieldValue ) ; case geProperty : return Restrictions . geProperty ( property , fieldStringValue ) ; case lt : return Restrictions . lt ( property , fieldValue ) ; case ltProperty : return Restrictions . ltProperty ( property , fieldStringValue ) ; case le : return Restrictions . le ( property , fieldValue ) ; case leProperty : return Restrictions . leProperty ( property , fieldStringValue ) ; // id等于
case idEq : return Restrictions . idEq ( fieldValue ) ; // 属性非空判断
case isEmpty : return Restrictions . isEmpty ( property ) ; case isNotEmpty : return Restrictions . isNotEmpty ( property ) ; case isNull : return Restrictions . isNull ( property ) ; case isNotNull : return Restrictions . isNotNull ( property ) ; // like , ilike
case like : return Restrictions . like ( property , fieldValue ) ; case alike : return Restrictions . like ( property , fieldStringValue , MatchMode . ANYWHERE ) ; case slike : return Restrictions . like ( property , fieldStringValue , MatchMode . START ) ; case elike : return Restrictions . like ( property , fieldStringValue , MatchMode . END ) ; case exlike : return Restrictions . like ( property , fieldStringValue , MatchMode . EXACT ) ; case nlike : return Restrictions . not ( Restrictions . like ( property , fieldValue ) ) ; case nalike : return Restrictions . not ( Restrictions . like ( property , fieldStringValue , MatchMode . ANYWHERE ) ) ; case nslike : return Restrictions . not ( Restrictions . like ( property , fieldStringValue , MatchMode . START ) ) ; case nelike : return Restrictions . not ( Restrictions . like ( property , fieldStringValue , MatchMode . END ) ) ; case nexlike : return Restrictions . not ( Restrictions . like ( property , fieldStringValue , MatchMode . EXACT ) ) ; case ilike : return Restrictions . ilike ( property , fieldValue ) ; case ailike : return Restrictions . ilike ( property , fieldStringValue , MatchMode . ANYWHERE ) ; case silike : return Restrictions . ilike ( property , fieldStringValue , MatchMode . START ) ; case eilike : return Restrictions . ilike ( property , fieldStringValue , MatchMode . END ) ; case exilike : return Restrictions . ilike ( property , fieldStringValue , MatchMode . EXACT ) ; case nilike : return Restrictions . not ( Restrictions . ilike ( property , fieldValue ) ) ; case nailike : return Restrictions . not ( Restrictions . ilike ( property , fieldStringValue , MatchMode . ANYWHERE ) ) ; case nsilike : return Restrictions . not ( Restrictions . ilike ( property , fieldStringValue , MatchMode . START ) ) ; case neilike : return Restrictions . not ( Restrictions . ilike ( property , fieldStringValue , MatchMode . END ) ) ; case nexilike : return Restrictions . not ( Restrictions . ilike ( property , fieldStringValue , MatchMode . EXACT ) ) ; default : return null ; } |
public class A_CmsXmlDocument { /** * Creates a partial deep element copy according to the set of element paths . < p >
* Only elements contained in that set will be copied .
* @ param parentPath the path of the parent element or < code > null < / code > , initially
* @ param parent the parent element
* @ param element the element to copy
* @ param copyElements the set of paths for elements to copy
* @ return a partial deep copy of < code > element < / code > */
private Element createDeepElementCopyInternal ( String parentPath , Element parent , Element element , Set < String > copyElements ) { } } | String elName = element . getName ( ) ; if ( parentPath != null ) { Element first = element . getParent ( ) . element ( elName ) ; int elIndex = ( element . getParent ( ) . indexOf ( element ) - first . getParent ( ) . indexOf ( first ) ) + 1 ; elName = parentPath + ( parentPath . length ( ) > 0 ? "/" : "" ) + elName . concat ( "[" + elIndex + "]" ) ; } if ( ( parentPath == null ) || copyElements . contains ( elName ) ) { // this is a content element we want to copy
Element copy = element . createCopy ( ) ; // copy . detach ( ) ;
if ( parentPath != null ) { parent . add ( copy ) ; } // check if we need to copy subelements , too
boolean copyNested = ( parentPath == null ) ; for ( Iterator < String > i = copyElements . iterator ( ) ; ! copyNested && i . hasNext ( ) ; ) { String path = i . next ( ) ; copyNested = ! elName . equals ( path ) && path . startsWith ( elName ) ; } if ( copyNested ) { copy . clearContent ( ) ; for ( Iterator < Element > i = CmsXmlGenericWrapper . elementIterator ( element ) ; i . hasNext ( ) ; ) { Element el = i . next ( ) ; createDeepElementCopyInternal ( ( parentPath == null ) ? "" : elName , copy , el , copyElements ) ; } } return copy ; } else { return null ; } |
public class Triple { /** * Creates a triple with the specified values . */
public static < A , B , C > Triple < A , B , C > newTriple ( A a , B b , C c ) { } } | return new Triple < A , B , C > ( a , b , c ) ; |
public class TrelloImpl { /** * / * Action */
@ Override public Action getAction ( String actionId , Argument ... args ) { } } | Action action = get ( createUrl ( GET_ACTION ) . params ( args ) . asString ( ) , Action . class , actionId ) ; action . setInternalTrello ( this ) ; return action ; |
public class EventParser { /** * Parse fights of an old event */
private List < Fight > parseEventFights ( Elements trs , Event event ) { } } | SherdogBaseObject sEvent = new SherdogBaseObject ( ) ; sEvent . setName ( event . getName ( ) ) ; sEvent . setSherdogUrl ( event . getSherdogUrl ( ) ) ; List < Fight > fights = new ArrayList < > ( ) ; if ( trs . size ( ) > 0 ) { trs . remove ( 0 ) ; trs . forEach ( tr -> { Fight fight = new Fight ( ) ; fight . setEvent ( sEvent ) ; fight . setDate ( event . getDate ( ) ) ; Elements tds = tr . select ( "td" ) ; fight . setFighter1 ( getFighter ( tds . get ( FIGHTER1_COLUMN ) ) ) ; fight . setFighter2 ( getFighter ( tds . get ( FIGHTER2_COLUMN ) ) ) ; // parsing old fight , we can get the result
if ( tds . size ( ) == 7 ) { fight . setResult ( getResult ( tds . get ( FIGHTER1_COLUMN ) ) ) ; fight . setWinMethod ( getMethod ( tds . get ( METHOD_COLUMN ) ) ) ; fight . setWinRound ( getRound ( tds . get ( ROUND_COLUMN ) ) ) ; fight . setWinTime ( getTime ( tds . get ( TIME_COLUMN ) ) ) ; } fights . add ( fight ) ; logger . info ( "Fight added: {}" , fight ) ; } ) ; } return fights ; |
public class OntologyTagServiceImpl { /** * The attribute just got updated , but the entity does not know this yet . To reindex this document
* in elasticsearch , update it .
* @ param entity name of the entity
* @ param attribute the name of the attribute that got changed
* @ param attributeEntity the entity of the attribute that got changed */
private void updateEntityTypeEntityWithNewAttributeEntity ( String entity , String attribute , Entity attributeEntity ) { } } | EntityType entityEntity = dataService . getEntityType ( entity ) ; Iterable < Attribute > attributes = entityEntity . getOwnAllAttributes ( ) ; entityEntity . set ( ATTRIBUTES , stream ( attributes ) . map ( att -> att . getName ( ) . equals ( attribute ) ? attributeEntity : att ) . collect ( Collectors . toList ( ) ) ) ; dataService . update ( ENTITY_TYPE_META_DATA , entityEntity ) ; |
public class GetSigningProfileRequestMarshaller { /** * Marshall the given parameter object . */
public void marshall ( GetSigningProfileRequest getSigningProfileRequest , ProtocolMarshaller protocolMarshaller ) { } } | if ( getSigningProfileRequest == null ) { throw new SdkClientException ( "Invalid argument passed to marshall(...)" ) ; } try { protocolMarshaller . marshall ( getSigningProfileRequest . getProfileName ( ) , PROFILENAME_BINDING ) ; } catch ( Exception e ) { throw new SdkClientException ( "Unable to marshall request to JSON: " + e . getMessage ( ) , e ) ; } |
public class Coercions { /** * Returns true if the given class is of a floating point type */
public static boolean isFloatingPointType ( Class pClass ) { } } | return pClass == Float . class || pClass == Float . TYPE || pClass == Double . class || pClass == Double . TYPE ; |
public class MemcachedClient { /** * Shut down this client gracefully .
* @ param timeout the amount of time time for shutdown
* @ param unit the TimeUnit for the timeout
* @ return result of the shutdown request */
@ Override public boolean shutdown ( long timeout , TimeUnit unit ) { } } | // Guard against double shutdowns ( bug 8 ) .
if ( shuttingDown ) { getLogger ( ) . info ( "Suppressing duplicate attempt to shut down" ) ; return false ; } shuttingDown = true ; String baseName = mconn . getName ( ) ; mconn . setName ( baseName + " - SHUTTING DOWN" ) ; boolean rv = true ; if ( connFactory . isDefaultExecutorService ( ) ) { try { executorService . shutdown ( ) ; } catch ( Exception ex ) { getLogger ( ) . warn ( "Failed shutting down the ExecutorService: " , ex ) ; } } try { // Conditionally wait
if ( timeout > 0 ) { mconn . setName ( baseName + " - SHUTTING DOWN (waiting)" ) ; rv = waitForQueues ( timeout , unit ) ; } } finally { // But always begin the shutdown sequence
try { mconn . setName ( baseName + " - SHUTTING DOWN (telling client)" ) ; mconn . shutdown ( ) ; mconn . setName ( baseName + " - SHUTTING DOWN (informed client)" ) ; tcService . shutdown ( ) ; // terminate all pending Auth Threads
authMonitor . interruptAllPendingAuth ( ) ; } catch ( IOException e ) { getLogger ( ) . warn ( "exception while shutting down" , e ) ; } } return rv ; |
public class JDBCDriver { /** * Gets information about the possible properties for this driver . < p >
* The getPropertyInfo method is intended to allow a generic GUI tool
* to discover what properties it should prompt a human for in order to
* get enough information to connect to a database . Note that depending
* on the values the human has supplied so far , additional values may
* become necessary , so it may be necessary to iterate though several
* calls to getPropertyInfo . < p >
* < ! - - start release - specific documentation - - >
* < div class = " ReleaseSpecificDocumentation " >
* < h3 > HSQLDB - Specific Information : < / h3 > < p >
* HSQLDB uses the values submitted in info to set the value for
* each DriverPropertyInfo object returned . It does not use the default
* value that it would use for the property if the value is null . < p >
* < / div > < ! - - end release - specific documentation - - >
* @ param url the URL of the database to which to connect
* @ param info a proposed list of tag / value pairs that will be sent on
* connect open
* @ return an array of DriverPropertyInfo objects describing possible
* properties . This array may be an empty array if no properties
* are required . */
public DriverPropertyInfo [ ] getPropertyInfo ( String url , Properties info ) { } } | if ( ! acceptsURL ( url ) ) { return new DriverPropertyInfo [ 0 ] ; } String [ ] choices = new String [ ] { "true" , "false" } ; DriverPropertyInfo [ ] pinfo = new DriverPropertyInfo [ 6 ] ; DriverPropertyInfo p ; if ( info == null ) { info = new Properties ( ) ; } p = new DriverPropertyInfo ( "user" , null ) ; p . value = info . getProperty ( "user" ) ; p . required = true ; pinfo [ 0 ] = p ; p = new DriverPropertyInfo ( "password" , null ) ; p . value = info . getProperty ( "password" ) ; p . required = true ; pinfo [ 1 ] = p ; p = new DriverPropertyInfo ( "get_column_name" , null ) ; p . value = info . getProperty ( "get_column_name" , "true" ) ; p . required = false ; p . choices = choices ; pinfo [ 2 ] = p ; p = new DriverPropertyInfo ( "ifexists" , null ) ; p . value = info . getProperty ( "ifexists" , "false" ) ; p . required = false ; p . choices = choices ; pinfo [ 3 ] = p ; p = new DriverPropertyInfo ( "default_schema" , null ) ; p . value = info . getProperty ( "default_schema" , "false" ) ; p . required = false ; p . choices = choices ; pinfo [ 4 ] = p ; p = new DriverPropertyInfo ( "shutdown" , null ) ; p . value = info . getProperty ( "shutdown" , "false" ) ; p . required = false ; p . choices = choices ; pinfo [ 5 ] = p ; return pinfo ; |
public class CustomApi { /** * ( asynchronously )
* @ param runmode ( required )
* @ param bundlesIgnored ( optional )
* @ param bundlesIgnoredTypeHint ( optional )
* @ param callback The callback to be executed when the API call finishes
* @ return The request call
* @ throws ApiException If fail to process the API call , e . g . serializing the request body object */
public com . squareup . okhttp . Call postConfigAemHealthCheckServletAsync ( String runmode , List < String > bundlesIgnored , String bundlesIgnoredTypeHint , final ApiCallback < Void > callback ) throws ApiException { } } | ProgressResponseBody . ProgressListener progressListener = null ; ProgressRequestBody . ProgressRequestListener progressRequestListener = null ; if ( callback != null ) { progressListener = new ProgressResponseBody . ProgressListener ( ) { @ Override public void update ( long bytesRead , long contentLength , boolean done ) { callback . onDownloadProgress ( bytesRead , contentLength , done ) ; } } ; progressRequestListener = new ProgressRequestBody . ProgressRequestListener ( ) { @ Override public void onRequestProgress ( long bytesWritten , long contentLength , boolean done ) { callback . onUploadProgress ( bytesWritten , contentLength , done ) ; } } ; } com . squareup . okhttp . Call call = postConfigAemHealthCheckServletValidateBeforeCall ( runmode , bundlesIgnored , bundlesIgnoredTypeHint , progressListener , progressRequestListener ) ; apiClient . executeAsync ( call , callback ) ; return call ; |
public class SAXiTextHandler { /** * This method gets called when characters are encountered .
* @ param ch
* an array of characters
* @ param start
* the start position in the array
* @ param length
* the number of characters to read from the array */
public void characters ( char [ ] ch , int start , int length ) { } } | if ( ignore ) return ; String content = new String ( ch , start , length ) ; // System . err . println ( " ' " + content + " ' " ) ;
if ( content . trim ( ) . length ( ) == 0 && content . indexOf ( ' ' ) < 0 ) { return ; } StringBuffer buf = new StringBuffer ( ) ; int len = content . length ( ) ; char character ; boolean newline = false ; for ( int i = 0 ; i < len ; i ++ ) { switch ( character = content . charAt ( i ) ) { case ' ' : if ( ! newline ) { buf . append ( character ) ; } break ; case '\n' : if ( i > 0 ) { newline = true ; buf . append ( ' ' ) ; } break ; case '\r' : break ; case '\t' : break ; default : newline = false ; buf . append ( character ) ; } } if ( currentChunk == null ) { if ( bf == null ) { currentChunk = new Chunk ( buf . toString ( ) ) ; } else { currentChunk = new Chunk ( buf . toString ( ) , new Font ( this . bf ) ) ; } } else { currentChunk . append ( buf . toString ( ) ) ; } |
public class CallOptions { /** * Returns a new { @ code CallOptions } with the given absolute deadline .
* < p > This is mostly used for propagating an existing deadline . { @ link # withDeadlineAfter } is the
* recommended way of setting a new deadline ,
* @ param deadline the deadline or { @ code null } for unsetting the deadline . */
public CallOptions withDeadline ( @ Nullable Deadline deadline ) { } } | CallOptions newOptions = new CallOptions ( this ) ; newOptions . deadline = deadline ; return newOptions ; |
public class LogMetadata { /** * Updates the current version of the metadata .
* @ param value The new metadata version .
* @ return This instance . */
LogMetadata withUpdateVersion ( int value ) { } } | Preconditions . checkArgument ( value >= this . updateVersion . get ( ) , "versions must increase" ) ; this . updateVersion . set ( value ) ; return this ; |
public class JsonReader { /** * Returns a < a href = " http : / / goessner . net / articles / JsonPath / " > JsonPath < / a > to
* the current location in the JSON value . */
public String getPath ( ) { } } | StringBuilder result = new StringBuilder ( ) . append ( '$' ) ; for ( int i = 0 , size = stackSize ; i < size ; i ++ ) { switch ( stack [ i ] ) { case JsonScope . EMPTY_ARRAY : case JsonScope . NONEMPTY_ARRAY : result . append ( '[' ) . append ( pathIndices [ i ] ) . append ( ']' ) ; break ; case JsonScope . EMPTY_OBJECT : case JsonScope . DANGLING_NAME : case JsonScope . NONEMPTY_OBJECT : result . append ( '.' ) ; if ( pathNames [ i ] != null ) { result . append ( pathNames [ i ] ) ; } break ; case JsonScope . NONEMPTY_DOCUMENT : case JsonScope . EMPTY_DOCUMENT : case JsonScope . CLOSED : break ; } } return result . toString ( ) ; |
public class TriangleBatch { /** * Prepares to add primitives with the specified tint and transform . This configures
* { @ link # stableAttrs } with all of the attributes that are the same for every vertex . */
public void prepare ( int tint , AffineTransform xf ) { } } | prepare ( tint , xf . m00 , xf . m01 , xf . m10 , xf . m11 , xf . tx , xf . ty ) ; |
public class Graphite { /** * The graphite protocol is a " one - way " streaming protocol and as such there is no easy way
* to check that we are sending the output to the wrong place . We can aim the graphite writer
* at any listening socket and it will never care if the data is being correctly handled . By
* logging any returned bytes we can help make it obvious that it ' s talking to the wrong
* server / socket . In particular if its aimed at the web port of a
* graphite server this will make it print out the HTTP error message .
* @ param socket Socket
* @ throws IOException e */
private void checkNoReturnedData ( Socket socket ) throws IOException { } } | final InputStream input = socket . getInputStream ( ) ; if ( input . available ( ) > 0 ) { final byte [ ] bytes = new byte [ 1000 ] ; final int toRead = Math . min ( input . available ( ) , bytes . length ) ; final int read = input . read ( bytes , 0 , toRead ) ; if ( read > 0 ) { final String msg = "Data returned by graphite server when expecting no response! " + "Probably aimed at wrong socket or server. Make sure you " + "are publishing to the data port, not the dashboard port. First " + read + " bytes of response: " + new String ( bytes , 0 , read , "UTF-8" ) ; LOG . warn ( msg , new IOException ( msg ) ) ; } } |
public class InjectionConfiguration { /** * Define a class using a custom object factory .
* @ param classDefinition The class to use .
* @ param factory The object factory responsible for instantiating the given class . */
public < T > void define ( Class < T > classDefinition , ObjectFactory < T > factory ) { } } | injectorConfiguration = injectorConfiguration . withFactory ( classDefinition , factory ) ; |
public class AXMLParser { /** * Closes parser :
* * closes ( and nulls ) underlying stream
* * nulls dynamic data
* * moves object to ' closed ' state , where methods
* return invalid values and next ( ) throws IOException . */
public final void close ( ) { } } | if ( m_stream == null ) { return ; } try { m_stream . close ( ) ; } catch ( IOException e ) { } if ( m_nextException == null ) { m_nextException = new IOException ( "Closed." ) ; } m_stream = null ; resetState ( ) ; |
public class SupplementaryMaterial { /** * Gets the value of the altTextOrLongDescOrEmail property .
* This accessor method returns a reference to the live list ,
* not a snapshot . Therefore any modification you make to the
* returned list will be present inside the JAXB object .
* This is why there is not a < CODE > set < / CODE > method for the altTextOrLongDescOrEmail property .
* For example , to add a new item , do as follows :
* < pre >
* getAltTextOrLongDescOrEmail ( ) . add ( newItem ) ;
* < / pre >
* Objects of the following type ( s ) are allowed in the list
* { @ link AltText }
* { @ link LongDesc }
* { @ link Email }
* { @ link ExtLink }
* { @ link Uri } */
public java . util . List < Object > getAltTextOrLongDescOrEmail ( ) { } } | if ( altTextOrLongDescOrEmail == null ) { altTextOrLongDescOrEmail = new ArrayList < Object > ( ) ; } return this . altTextOrLongDescOrEmail ; |
public class Image { /** * Sets the color values to this Image .
* @ param colors
* < < < < < HEAD
* The array of Color which size is width * height of this Image .
* The array of Color which size is width * height of this Image .
* > > > > > 16121fd9fe4eeaef3cb56619769a3119a9e6531a */
public final void setColors ( Color [ ] colors ) { } } | int [ ] pixels = ( ( DataBufferInt ) img . getRaster ( ) . getDataBuffer ( ) ) . getData ( ) ; for ( int y = 0 ; y < height ; ++ y ) { for ( int x = 0 ; x < width ; ++ x ) { int idx = x + y * width ; if ( colors . length <= idx ) break ; int red = ( int ) ( colors [ idx ] . getRed ( ) * 255.0 ) ; int green = ( int ) ( colors [ idx ] . getGreen ( ) * 255.0 ) ; int blue = ( int ) ( colors [ idx ] . getBlue ( ) * 255.0 ) ; int alpha = ( int ) ( colors [ idx ] . getAlpha ( ) * 255.0 ) ; pixels [ idx ] = alpha << 24 | red << 16 | green << 8 | blue ; } } |
public class Jenkins { /** * Called in response to { @ link Job # doDoDelete ( StaplerRequest , StaplerResponse ) } */
public void onDeleted ( TopLevelItem item ) throws IOException { } } | ItemListener . fireOnDeleted ( item ) ; items . remove ( item . getName ( ) ) ; // For compatibility with old views :
for ( View v : views ) v . onJobRenamed ( item , item . getName ( ) , null ) ; |
public class GeneratePluginConfigMBean { /** * Subcommand for creating the plugin - cfg . xml file at runtime using the
* user provided Plugin install root and Plugin server name .
* @ param root Plugin install root directory
* @ param name The server name
* @ param utilityRequest True if plugin config creation is being done automatically or via the pluginUtility , False if it is being done because of a call to the mbean
* @ param writeDirectory The directory to write the plugin - cfg . xml file to */
public synchronized void generatePluginConfig ( String root , String serverName , boolean utilityRequest , File writeDirectory ) { } } | if ( TraceComponent . isAnyTracingEnabled ( ) && tc . isEntryEnabled ( ) ) { Tr . entry ( tc , "generatePluginConfig" , "server is stopping = " + serverIsStopping ) ; } try { // Method is synchronized so only one generate can be in progress at a time .
generateInProgress = true ; if ( ! serverIsStopping ) { PluginGenerator generator = pluginGenerator ; if ( generator == null ) { // Process the updated configuration
generator = pluginGenerator = new PluginGenerator ( this . config , locMgr , bundleContext ) ; } generator . generateXML ( root , serverName , ( WebContainer ) webContainer , smgr , dynVhostMgr , locMgr , utilityRequest , writeDirectory ) ; } } catch ( Throwable t ) { FFDCFilter . processException ( t , getClass ( ) . getName ( ) , "generatePluginConfig" ) ; if ( TraceComponent . isAnyTracingEnabled ( ) && tc . isEventEnabled ( ) ) { Tr . event ( tc , "Error generate plugin xml: " + t . getMessage ( ) ) ; } } finally { generateInProgress = false ; } if ( TraceComponent . isAnyTracingEnabled ( ) && tc . isEntryEnabled ( ) ) { Tr . exit ( tc , "generatePluginConfig" , "server is stopping = " + serverIsStopping ) ; } |
public class LibertyJaxWsCompatibleWSDLGetInterceptor { /** * Extend from the base class and just customize the response to 404 */
@ Override public void handleMessage ( Message message ) throws Fault { } } | String method = ( String ) message . get ( Message . HTTP_REQUEST_METHOD ) ; String query = ( String ) message . get ( Message . QUERY_STRING ) ; if ( ! "GET" . equals ( method ) || StringUtils . isEmpty ( query ) ) { return ; } String baseUri = ( String ) message . get ( Message . REQUEST_URL ) ; String ctx = ( String ) message . get ( Message . PATH_INFO ) ; // cannot have two wsdl ' s being written for the same endpoint at the same
// time as the addresses may get mixed up
synchronized ( message . getExchange ( ) . getEndpoint ( ) ) { Map < String , String > map = UrlUtils . parseQueryString ( query ) ; if ( isRecognizedQuery ( map , baseUri , ctx , message . getExchange ( ) . getEndpoint ( ) . getEndpointInfo ( ) ) ) { try { Conduit c = message . getExchange ( ) . getDestination ( ) . getBackChannel ( message , null , null ) ; Message mout = new MessageImpl ( ) ; mout . setExchange ( message . getExchange ( ) ) ; message . getExchange ( ) . setOutMessage ( mout ) ; // Customize the response to 404
mout . put ( Message . RESPONSE_CODE , HttpURLConnection . HTTP_NOT_FOUND ) ; mout . put ( Message . CONTENT_TYPE , "text/xml" ) ; c . prepare ( mout ) ; OutputStream os = mout . getContent ( OutputStream . class ) ; Document doc = getDocument ( message , baseUri , map , ctx , message . getExchange ( ) . getEndpoint ( ) . getEndpointInfo ( ) ) ; String enc = null ; try { enc = doc . getXmlEncoding ( ) ; } catch ( Exception ex ) { // ignore - not dom level 3
} if ( enc == null ) { enc = "utf-8" ; } XMLStreamWriter writer = null ; try { writer = StaxUtils . createXMLStreamWriter ( os , enc ) ; StaxUtils . writeNode ( doc , writer , true ) ; message . getInterceptorChain ( ) . abort ( ) ; writer . flush ( ) ; os . flush ( ) ; } catch ( IOException ex ) { if ( TraceComponent . isAnyTracingEnabled ( ) && tc . isInfoEnabled ( ) ) { Tr . info ( tc , "error.write.wsdl.stream" , ex ) ; } // LOG . log ( Level . FINE , " Failure writing full wsdl to the stream " , ex ) ;
// we can ignore this . Likely , whatever has requested the WSDL
// has closed the connection before reading the entire wsdl .
// WSDL4J has a tendency to not read the closing tags and such
// and thus can sometimes hit this . In anycase , it ' s
// pretty much ignorable and nothing we can do about it ( cannot
// send a fault or anything anyway
} finally { if ( writer != null ) { try { writer . close ( ) ; } catch ( Exception e ) { } } try { os . close ( ) ; } catch ( Exception e ) { } } } catch ( IOException e ) { throw new Fault ( e ) ; } catch ( XMLStreamException e ) { throw new Fault ( e ) ; } finally { message . getExchange ( ) . setOutMessage ( null ) ; } } } |
public class RouteBuilder { /** * Specifies that this route is mapped to HTTP OPTIONS method .
* @ return instance of { @ link RouteBuilder } . */
public RouteBuilder options ( ) { } } | if ( ! methods . contains ( HttpMethod . OPTIONS ) ) { methods . add ( HttpMethod . OPTIONS ) ; } return this ; |
public class AWSAppMeshClient { /** * Updates an existing virtual service in a specified service mesh .
* @ param updateVirtualServiceRequest
* @ return Result of the UpdateVirtualService operation returned by the service .
* @ throws BadRequestException
* The request syntax was malformed . Check your request syntax and try again .
* @ throws ConflictException
* The request contains a client token that was used for a previous update resource call with different
* specifications . Try the request again with a new client token .
* @ throws ForbiddenException
* You don ' t have permissions to perform this action .
* @ throws InternalServerErrorException
* The request processing has failed because of an unknown error , exception , or failure .
* @ throws LimitExceededException
* You have exceeded a service limit for your account . For more information , see < a
* href = " https : / / docs . aws . amazon . com / app - mesh / latest / userguide / service _ limits . html " > Service Limits < / a > in
* the < i > AWS App Mesh User Guide < / i > .
* @ throws NotFoundException
* The specified resource doesn ' t exist . Check your request syntax and try again .
* @ throws ServiceUnavailableException
* The request has failed due to a temporary failure of the service .
* @ throws TooManyRequestsException
* The maximum request rate permitted by the App Mesh APIs has been exceeded for your account . For best
* results , use an increasing or variable sleep interval between requests .
* @ sample AWSAppMesh . UpdateVirtualService
* @ see < a href = " http : / / docs . aws . amazon . com / goto / WebAPI / appmesh - 2019-01-25 / UpdateVirtualService " target = " _ top " > AWS
* API Documentation < / a > */
@ Override public UpdateVirtualServiceResult updateVirtualService ( UpdateVirtualServiceRequest request ) { } } | request = beforeClientExecution ( request ) ; return executeUpdateVirtualService ( request ) ; |
public class RXTXPort { /** * Remove the serial port event listener */
public void removeEventListener ( ) { } } | logger . fine ( "RXTXPort:removeEventListener() called" ) ; waitForTheNativeCodeSilly ( ) ; // if ( monThread ! = null & & monThread . isAlive ( ) )
if ( monThreadisInterrupted == true ) { logger . fine ( " RXTXPort:removeEventListener() already interrupted" ) ; monThread = null ; SPEventListener = null ; return ; } else if ( monThread != null && monThread . isAlive ( ) ) { logger . fine ( " RXTXPort:Interrupt=true" ) ; monThreadisInterrupted = true ; /* Notify all threads in this PID that something is up
They will call back to see if its their thread
using isInterrupted ( ) . */
logger . fine ( " RXTXPort:calling interruptEventLoop" ) ; interruptEventLoop ( ) ; logger . fine ( " RXTXPort:calling monThread.join()" ) ; try { // wait a reasonable moment for the death of the monitor thread
monThread . join ( 3000 ) ; } catch ( InterruptedException ex ) { // somebody called interrupt ( ) on us ( ie wants us to abort )
// we dont propagate InterruptedExceptions so lets re - set the flag
Thread . currentThread ( ) . interrupt ( ) ; return ; } { logger . fine ( " MonThread is still alive!" ) ; } } monThread = null ; SPEventListener = null ; MonitorThreadLock = false ; MonitorThreadAlive = false ; monThreadisInterrupted = true ; logger . fine ( "RXTXPort:removeEventListener() returning" ) ; |
public class PageFlowController { /** * Called from { @ link FlowController # execute } . */
void savePreviousActionInfo ( ActionForm form , HttpServletRequest request , ActionMapping mapping , ServletContext servletContext ) { } } | // If previous - action is disabled ( unused in this pageflow ) , just return .
if ( isPreviousActionInfoDisabled ( ) ) return ; String actionURI = InternalUtils . getDecodedServletPath ( request ) ; _previousActionInfo = new PreviousActionInfo ( form , actionURI , request . getQueryString ( ) ) ; |
public class UploadOfflineData { /** * Hash a string using SHA - 256 hashing algorithm .
* @ param str the string to hash .
* @ return the SHA - 256 hash string representation .
* @ throws UnsupportedEncodingException If UTF - 8 charset is not supported . */
private static String toSHA256String ( String str ) throws UnsupportedEncodingException { } } | // Normalize the string before hashing .
byte [ ] hash = digest . digest ( toNormalizedString ( str ) . getBytes ( "UTF-8" ) ) ; StringBuilder result = new StringBuilder ( ) ; for ( byte b : hash ) { result . append ( String . format ( "%02x" , b ) ) ; } return result . toString ( ) ; |
public class DataFindRequest { /** * Use { @ link # select ( List , Integer , Integer ) } or
* { @ link # select ( Projection [ ] , Integer , Integer ) } .
* @ param begin - the ' from ' parameter to send to lightblue .
* @ param end - the ' to ' parameter to send to lightblue . */
@ Deprecated public DataFindRequest range ( Integer begin , Integer end ) { } } | this . begin = begin ; if ( end != null ) { // ' maxResults ' should be 1 greater than a ' to ' value .
maxResults = end - ( begin == null ? 0 : begin ) + 1 ; } return this ; |
public class SparkLineTileSkin { /** * * * * * * Resizing * * * * * */
@ Override protected void resizeDynamicText ( ) { } } | double maxWidth = unitText . isVisible ( ) ? width - size * 0.275 : width - size * 0.1 ; double fontSize = size * 0.24 ; valueText . setFont ( Fonts . latoRegular ( fontSize ) ) ; if ( valueText . getLayoutBounds ( ) . getWidth ( ) > maxWidth ) { Helper . adjustTextSize ( valueText , maxWidth , fontSize ) ; } maxWidth = width - size * 0.7 ; fontSize = size * 0.06 ; averageText . setFont ( Fonts . latoRegular ( fontSize ) ) ; if ( averageText . getLayoutBounds ( ) . getWidth ( ) > maxWidth ) { Helper . adjustTextSize ( averageText , maxWidth , fontSize ) ; } if ( averageLine . getStartY ( ) < graphBounds . getY ( ) + graphBounds . getHeight ( ) * 0.5 ) { averageText . setY ( averageLine . getStartY ( ) + ( size * 0.0425 ) ) ; } else { averageText . setY ( averageLine . getStartY ( ) - ( size * 0.0075 ) ) ; } highText . setFont ( Fonts . latoRegular ( fontSize ) ) ; if ( highText . getLayoutBounds ( ) . getWidth ( ) > maxWidth ) { Helper . adjustTextSize ( highText , maxWidth , fontSize ) ; } highText . setY ( graphBounds . getY ( ) - size * 0.0125 ) ; lowText . setFont ( Fonts . latoRegular ( fontSize ) ) ; if ( lowText . getLayoutBounds ( ) . getWidth ( ) > maxWidth ) { Helper . adjustTextSize ( lowText , maxWidth , fontSize ) ; } lowText . setY ( height - size * 0.1 ) ; maxWidth = width - size * 0.25 ; fontSize = size * 0.06 ; text . setFont ( Fonts . latoRegular ( fontSize ) ) ; if ( text . getLayoutBounds ( ) . getWidth ( ) > maxWidth ) { Helper . adjustTextSize ( text , maxWidth , fontSize ) ; } text . relocate ( width - size * 0.05 - text . getLayoutBounds ( ) . getWidth ( ) , height - size * 0.1 ) ; maxWidth = width - size * 0.25 ; fontSize = size * 0.06 ; timeSpanText . setFont ( Fonts . latoRegular ( fontSize ) ) ; if ( timeSpanText . getLayoutBounds ( ) . getWidth ( ) > maxWidth ) { Helper . adjustTextSize ( timeSpanText , maxWidth , fontSize ) ; } timeSpanText . relocate ( ( width - timeSpanText . getLayoutBounds ( ) . getWidth ( ) ) * 0.5 , height - size * 0.1 ) ; |
public class PresentsServer { /** * Inits and runs the PresentsServer bound in the given modules . This blocks until the server
* is shut down . */
public static void runServer ( Module ... modules ) { } } | Injector injector = Guice . createInjector ( modules ) ; PresentsServer server = injector . getInstance ( PresentsServer . class ) ; try { // initialize the server
server . init ( injector ) ; // check to see if we should load and invoke a test module before running the server
String testmod = System . getProperty ( "test_module" ) ; if ( testmod != null ) { try { log . info ( "Invoking test module" , "mod" , testmod ) ; Class < ? > tmclass = Class . forName ( testmod ) ; Runnable trun = ( Runnable ) tmclass . newInstance ( ) ; trun . run ( ) ; } catch ( Exception e ) { log . warning ( "Unable to invoke test module '" + testmod + "'." , e ) ; } } // start the server to running ( this method call won ' t return until the server is shut
// down )
server . run ( ) ; } catch ( Throwable t ) { log . warning ( "Unable to initialize server." , t ) ; System . exit ( - 1 ) ; } |
public class WaybackRequest { /** * create WaybackRequet for URL - Query request .
* @ param url target URL
* @ param start start timestamp ( 14 - digit )
* @ param end end timestamp ( 14 - digit )
* @ return WaybackRequest */
public static WaybackRequest createUrlQueryRequest ( String url , String start , String end ) { } } | WaybackRequest r = new WaybackRequest ( ) ; r . setUrlQueryRequest ( ) ; r . setRequestUrl ( url ) ; r . setStartTimestamp ( start ) ; r . setEndTimestamp ( end ) ; return r ; |
public class ResourceGroovyMethods { /** * Write the text to the File .
* @ param file a File
* @ param text the text to write to the File
* @ throws IOException if an IOException occurs .
* @ since 1.0 */
public static void write ( File file , String text ) throws IOException { } } | Writer writer = null ; try { writer = new FileWriter ( file ) ; writer . write ( text ) ; writer . flush ( ) ; Writer temp = writer ; writer = null ; temp . close ( ) ; } finally { closeWithWarning ( writer ) ; } |
public class Rect { /** * If the rectangle specified by left , top , right , bottom intersects this
* rectangle , return true and set this rectangle to that intersection ,
* otherwise return false and do not change this rectangle . No check is
* performed to see if either rectangle is empty . Note : To just test for
* intersection , use { @ link # intersects ( Rect , Rect ) } .
* @ param left The left side of the rectangle being intersected with this
* rectangle
* @ param top The top of the rectangle being intersected with this rectangle
* @ param right The right side of the rectangle being intersected with this
* rectangle .
* @ param bottom The bottom of the rectangle being intersected with this
* rectangle .
* @ return true if the specified rectangle and this rectangle intersect
* ( and this rectangle is then set to that intersection ) else
* return false and do not change this rectangle . */
public boolean intersect ( int left , int top , int right , int bottom ) { } } | if ( this . left < right && left < this . right && this . top < bottom && top < this . bottom ) { if ( this . left < left ) { this . left = left ; } if ( this . top < top ) { this . top = top ; } if ( this . right > right ) { this . right = right ; } if ( this . bottom > bottom ) { this . bottom = bottom ; } return true ; } return false ; |
public class FileServersInner { /** * Gets a list of File Servers associated with the specified workspace .
* @ param nextPageLink The NextLink from the previous successful call to List operation .
* @ throws IllegalArgumentException thrown if parameters fail the validation
* @ return the observable to the PagedList & lt ; FileServerInner & gt ; object */
public Observable < Page < FileServerInner > > listByWorkspaceNextAsync ( final String nextPageLink ) { } } | return listByWorkspaceNextWithServiceResponseAsync ( nextPageLink ) . map ( new Func1 < ServiceResponse < Page < FileServerInner > > , Page < FileServerInner > > ( ) { @ Override public Page < FileServerInner > call ( ServiceResponse < Page < FileServerInner > > response ) { return response . body ( ) ; } } ) ; |
public class ParaClient { /** * Search for { @ link com . erudika . para . core . Address } objects in a radius of X km from a given point .
* @ param < P > type of the object
* @ param type the type of object to search for . See { @ link com . erudika . para . core . ParaObject # getType ( ) }
* @ param query the query string
* @ param radius the radius of the search circle
* @ param lat latitude
* @ param lng longitude
* @ param pager a { @ link com . erudika . para . utils . Pager }
* @ return a list of objects found */
public < P extends ParaObject > List < P > findNearby ( String type , String query , int radius , double lat , double lng , Pager ... pager ) { } } | MultivaluedMap < String , String > params = new MultivaluedHashMap < > ( ) ; params . putSingle ( "latlng" , lat + "," + lng ) ; params . putSingle ( "radius" , Integer . toString ( radius ) ) ; params . putSingle ( "q" , query ) ; params . putSingle ( Config . _TYPE , type ) ; params . putAll ( pagerToParams ( pager ) ) ; return getItems ( find ( "nearby" , params ) , pager ) ; |
public class GetResourceShareInvitationsRequest { /** * The Amazon Resource Names ( ARN ) of the resource shares .
* < b > NOTE : < / b > This method appends the values to the existing list ( if any ) . Use
* { @ link # setResourceShareArns ( java . util . Collection ) } or { @ link # withResourceShareArns ( java . util . Collection ) } if
* you want to override the existing values .
* @ param resourceShareArns
* The Amazon Resource Names ( ARN ) of the resource shares .
* @ return Returns a reference to this object so that method calls can be chained together . */
public GetResourceShareInvitationsRequest withResourceShareArns ( String ... resourceShareArns ) { } } | if ( this . resourceShareArns == null ) { setResourceShareArns ( new java . util . ArrayList < String > ( resourceShareArns . length ) ) ; } for ( String ele : resourceShareArns ) { this . resourceShareArns . add ( ele ) ; } return this ; |
public class DockerRule { /** * Starts a docker container with the given configuration .
* This method is particularly useful when you want to start a container dynamically .
* @ param config
* container configuration
* @ param stopOthers
* true to stop other running containers ; useful to limit the amount of memory that a
* series of unit tests will consume .
* @ return a { @ link Container } representing the started container .
* @ throws Exception
* if the container cannot be started */
public static Container start ( final DockerConfig config , final boolean stopOthers ) throws Exception { } } | Preconditions . checkArgument ( config != null , "config must be non-null" ) ; if ( stopOthers ) { getRegisteredContainers ( ) . stream ( ) . filter ( container -> { return container . isStarted ( ) && container . getRefCount ( ) == 0 && ! StringUtils . equals ( config . getName ( ) , container . getConfig ( ) . getName ( ) ) ; } ) . forEach ( container -> container . stop ( ) ) ; } final Container container = register ( config ) ; container . start ( ) ; return container ; |
public class MXBeanNotificationListenersCleanUp { /** * Unregister { @ link NotificationListener } s from subclass of { @ link NotificationBroadcasterSupport } , if listener ,
* filter or handback is loaded by the protected ClassLoader . */
protected void unregisterNotificationListeners ( ClassLoaderLeakPreventor preventor , NotificationBroadcasterSupport mBean , final Class < ? > listenerWrapperClass ) { } } | final Field listenerListField = preventor . findField ( NotificationBroadcasterSupport . class , "listenerList" ) ; if ( listenerListField != null ) { final Class < ? > listenerInfoClass = preventor . findClass ( "javax.management.NotificationBroadcasterSupport$ListenerInfo" ) ; final List < ? /* javax . management . NotificationBroadcasterSupport . ListenerInfo */
> listenerList = preventor . getFieldValue ( listenerListField , mBean ) ; if ( listenerList != null ) { final Field listenerField = preventor . findField ( listenerInfoClass , "listener" ) ; final Field filterField = preventor . findField ( listenerInfoClass , "filter" ) ; final Field handbackField = preventor . findField ( listenerInfoClass , "handback" ) ; for ( Object listenerInfo : listenerList ) { final NotificationListener listener = preventor . getFieldValue ( listenerField , listenerInfo ) ; final NotificationListener rawListener = unwrap ( preventor , listenerWrapperClass , listener ) ; final NotificationFilter filter = preventor . getFieldValue ( filterField , listenerInfo ) ; final Object handback = preventor . getFieldValue ( handbackField , listenerInfo ) ; if ( preventor . isLoadedInClassLoader ( rawListener ) || preventor . isLoadedInClassLoader ( filter ) || preventor . isLoadedInClassLoader ( handback ) ) { preventor . warn ( ( ( listener == rawListener ) ? "Listener '" : "Wrapped listener '" ) + listener + "' (or its filter or handback) of MBean " + mBean + " was loaded in protected ClassLoader; removing" ) ; // This is safe , as the implementation works with a copy , not altering the original
try { mBean . removeNotificationListener ( listener , filter , handback ) ; } catch ( ListenerNotFoundException e ) { // Should never happen
preventor . error ( e ) ; } } } } } |
public class ClientService { /** * This function updates the data of a client . To change only a specific attribute you can set this attribute in the update
* request . All other attributes that should not be edited are not inserted . You can only edit the description , email and credit
* card . The subscription can not be changed by updating the client data . This has to be done in the subscription call .
* @ param client
* A { @ link Client } with Id . */
public void update ( Client client ) { } } | RestfulUtils . update ( ClientService . PATH , client , Client . class , super . httpClient ) ; |
public class GetLifecyclePoliciesResult { /** * Summary information about the lifecycle policies .
* @ param policies
* Summary information about the lifecycle policies . */
public void setPolicies ( java . util . Collection < LifecyclePolicySummary > policies ) { } } | if ( policies == null ) { this . policies = null ; return ; } this . policies = new java . util . ArrayList < LifecyclePolicySummary > ( policies ) ; |
public class InternationalFixedChronology { /** * Obtains a International Fixed zoned date - time from another date - time object .
* @ param temporal the date - time object to convert , not null
* @ return the International Fixed zoned date - time , not null
* @ throws DateTimeException if unable to create the date - time */
@ Override @ SuppressWarnings ( "unchecked" ) public ChronoZonedDateTime < InternationalFixedDate > zonedDateTime ( TemporalAccessor temporal ) { } } | return ( ChronoZonedDateTime < InternationalFixedDate > ) super . zonedDateTime ( temporal ) ; |
public class PropertyListSerialization { /** * Serialize an object using the best available element .
* @ param obj
* object to serialize .
* @ param handler
* destination of serialization events .
* @ throws SAXException
* if exception during serialization . */
private static void serializeObject ( final Object obj , final ContentHandler handler ) throws SAXException { } } | if ( obj instanceof Map ) { serializeMap ( ( Map ) obj , handler ) ; } else if ( obj instanceof List ) { serializeList ( ( List ) obj , handler ) ; } else if ( obj instanceof Number ) { if ( obj instanceof Double || obj instanceof Float ) { serializeReal ( ( Number ) obj , handler ) ; } else { serializeInteger ( ( Number ) obj , handler ) ; } } else if ( obj instanceof Boolean ) { serializeBoolean ( ( Boolean ) obj , handler ) ; } else { serializeString ( String . valueOf ( obj ) , handler ) ; } |
public class UrlIO { /** * Evaluate XPath on the url document .
* @ param xpath
* @ return xpath evaluator
* @ see org . xmlbeam . evaluation . CanEvaluate # evalXPath ( java . lang . String ) */
@ Override @ Scope ( DocScope . IO ) public XPathEvaluator evalXPath ( final String xpath ) { } } | return new DefaultXPathEvaluator ( projector , new DocumentResolver ( ) { @ Override public Document resolve ( final Class < ? > ... resourceAwareClasses ) throws IOException { return IOHelper . getDocumentFromURL ( projector . config ( ) . createDocumentBuilder ( ) , url , requestProperties , resourceAwareClasses ) ; } } , xpath ) ; |
public class S3Discovery { /** * Do the set - up that ' s needed to access Amazon S3. */
private void init ( ) { } } | validatePreSignedUrls ( ) ; try { conn = new AWSAuthConnection ( access_key , secret_access_key ) ; // Determine the bucket name if prefix is set or if pre - signed URLs are being used
if ( prefix != null && prefix . length ( ) > 0 ) { ListAllMyBucketsResponse bucket_list = conn . listAllMyBuckets ( null ) ; List buckets = bucket_list . entries ; if ( buckets != null ) { boolean found = false ; for ( Object tmp : buckets ) { if ( tmp instanceof Bucket ) { Bucket bucket = ( Bucket ) tmp ; if ( bucket . name . startsWith ( prefix ) ) { location = bucket . name ; found = true ; } } } if ( ! found ) { location = prefix + "-" + java . util . UUID . randomUUID ( ) . toString ( ) ; } } } if ( usingPreSignedUrls ( ) ) { PreSignedUrlParser parsedPut = new PreSignedUrlParser ( pre_signed_put_url ) ; location = parsedPut . getBucket ( ) ; } if ( ! conn . checkBucketExists ( location ) ) { conn . createBucket ( location , AWSAuthConnection . LOCATION_DEFAULT , null ) . connection . getResponseMessage ( ) ; } } catch ( Exception e ) { throw HostControllerLogger . ROOT_LOGGER . cannotAccessS3Bucket ( location , e . getLocalizedMessage ( ) ) ; } |
public class ObjectFactory { /** * Create an instance of { @ link JAXBElement } { @ code < } { @ link StringOrRefType } { @ code > }
* @ param value
* Java instance representing xml element ' s value .
* @ return
* the new instance of { @ link JAXBElement } { @ code < } { @ link StringOrRefType } { @ code > } */
@ XmlElementDecl ( namespace = "http://www.opengis.net/gml" , name = "LocationString" ) public JAXBElement < StringOrRefType > createLocationString ( StringOrRefType value ) { } } | return new JAXBElement < StringOrRefType > ( _LocationString_QNAME , StringOrRefType . class , null , value ) ; |
public class CliqueTree { /** * This is a key step in message passing . When we are calculating a message , we want to marginalize out all variables
* not relevant to the recipient of the message . This function does that .
* @ param message the message to marginalize
* @ param relevant the variables that are relevant
* @ return the marginalized message */
private TableFactor marginalizeMessage ( TableFactor message , int [ ] relevant , MarginalizationMethod marginalize ) { } } | TableFactor result = message ; for ( int i : message . neighborIndices ) { boolean contains = false ; for ( int j : relevant ) { if ( i == j ) { contains = true ; break ; } } if ( ! contains ) { switch ( marginalize ) { case SUM : result = result . sumOut ( i ) ; break ; case MAX : result = result . maxOut ( i ) ; break ; } } } return result ; |
public class JobTracker { /** * A tracker wants to know if any of its Tasks have been
* closed ( because the job completed , whether successfully or not ) */
synchronized List < TaskTrackerAction > getTasksToKill ( String taskTracker ) { } } | Set < TaskAttemptIDWithTip > taskset = trackerToTaskMap . get ( taskTracker ) ; List < TaskTrackerAction > killList = new ArrayList < TaskTrackerAction > ( ) ; if ( taskset != null ) { for ( TaskAttemptIDWithTip onetask : taskset ) { TaskAttemptID killTaskId = onetask . attemptId ; TaskInProgress tip = onetask . tip ; if ( tip == null ) { continue ; } if ( tip . shouldClose ( killTaskId ) ) { // This is how the JobTracker ends a task at the TaskTracker .
// It may be successfully completed , or may be killed in
// mid - execution .
if ( ! ( ( JobInProgress ) tip . getJob ( ) ) . isComplete ( ) ) { killList . add ( new KillTaskAction ( killTaskId ) ) ; LOG . debug ( taskTracker + " -> KillTaskAction: " + killTaskId ) ; } } } } // add the stray attempts for uninited jobs
synchronized ( trackerToTasksToCleanup ) { Set < TaskAttemptID > set = trackerToTasksToCleanup . remove ( taskTracker ) ; if ( set != null ) { for ( TaskAttemptID id : set ) { killList . add ( new KillTaskAction ( id ) ) ; } } } return killList ; |
public class Ring { /** * Draws this slice .
* @ param context */
@ Override protected boolean prepare ( final Context2D context , final Attributes attr , final double alpha ) { } } | final double ord = attr . getOuterRadius ( ) ; final double ird = attr . getInnerRadius ( ) ; if ( ( ord > 0 ) && ( ird > 0 ) && ( ord > ird ) ) { context . beginPath ( ) ; context . arc ( 0 , 0 , ord , 0 , Math . PI * 2 , false ) ; context . arc ( 0 , 0 , ird , 0 , Math . PI * 2 , true ) ; context . closePath ( ) ; return true ; } return false ; |
public class RythmConfiguration { /** * Get { @ link RythmConfigurationKey # I18N _ MESSAGE _ SOURCES } without lookup */
public List < String > messageSources ( ) { } } | if ( null == _messageSources ) { _messageSources = Arrays . asList ( get ( I18N_MESSAGE_SOURCES ) . toString ( ) . split ( "[, \\t]+" ) ) ; } return _messageSources ; |
public class AbstractConverter { /** * Determines whether the { @ link Type } is a generic , parameterized { @ link Converter } { @ link Class type } , such as
* by implementing the { @ link Converter } interface or extending the { @ link AbstractConverter } base class .
* @ param type { @ link Type } to evaluate .
* @ return a boolean if the { @ link Type } represents a generic , parameterized { @ link Converter } { @ link Class type } .
* @ see java . lang . reflect . Type */
@ NullSafe protected boolean isParameterizedFunctionType ( Type type ) { } } | return Optional . ofNullable ( type ) . filter ( it -> it instanceof ParameterizedType ) . map ( it -> { Class < ? > rawType = safeGetValue ( ( ) -> ClassUtils . toRawType ( it ) , Object . class ) ; return isAssignableTo ( rawType , Converter . class , Function . class ) ; } ) . orElse ( false ) ; |
public class RandomText { /** * Generates a random text that consists of random number of random words separated by spaces .
* @ param min ( optional ) a minimum number of words .
* @ param max a maximum number of words .
* @ return a random text . */
public static String words ( int min , int max ) { } } | StringBuilder result = new StringBuilder ( ) ; int count = RandomInteger . nextInteger ( min , max ) ; for ( int i = 0 ; i < count ; i ++ ) result . append ( RandomString . pick ( _allWords ) ) ; return result . toString ( ) ; |
public class SurtPrefixSet { /** * For SURT comparisons - - prefixes or candidates being checked against
* those prefixes - - we treat https URIs as if they were http .
* @ param u string to coerce if it has https scheme
* @ return string converted to http scheme , or original if not necessary */
private static String coerceFromHttpsForComparison ( String u ) { } } | if ( u . startsWith ( "https://" ) ) { u = "http" + u . substring ( "https" . length ( ) ) ; } return u ; |
public class SimpleNodeListProvider { /** * Pass a System Property of format
* < EVCACHE _ APP > - NODES = setname0 = instance01 : port , instance02 : port ,
* instance03 : port ; setname1 = instance11 : port , instance12 : port , instance13 : port ;
* setname2 = instance21 : port , instance22 : port , instance23 : port */
@ Override public Map < ServerGroup , EVCacheServerGroupConfig > discoverInstances ( String appName ) throws IOException { } } | final String propertyName = appName + "-NODES" ; final String nodeListString = EVCacheConfig . getInstance ( ) . getDynamicStringProperty ( propertyName , "" ) . get ( ) ; if ( log . isDebugEnabled ( ) ) log . debug ( "List of Nodes = " + nodeListString ) ; if ( nodeListString != null && nodeListString . length ( ) > 0 ) return bootstrapFromSystemProperty ( nodeListString ) ; if ( env != null && region != null ) return bootstrapFromEureka ( appName ) ; return Collections . < ServerGroup , EVCacheServerGroupConfig > emptyMap ( ) ; |
public class CpnlElFunctions { /** * Returns the escaped text of a rich text value ( reduced HTML escaping ) .
* @ param value the rich text value to escape
* @ return the escaped HTML code of the value */
public static String rich ( SlingHttpServletRequest request , String value ) { } } | if ( value != null ) { // ensure that a rich text value is always enclosed with a HTML paragraph tag
if ( StringUtils . isNotBlank ( value ) && ! value . trim ( ) . startsWith ( "<p>" ) ) { value = "<p>" + value + "</p>" ; } // transform embedded resource links ( paths ) to mapped URLs
value = map ( request , value ) ; value = escapeRichText ( value ) ; } return value ; |
public class InputMapTemplate { /** * Shorthand for { @ link # sequence ( InputMapTemplate [ ] ) } sequence ( this , that ) } */
public final InputMapTemplate < S , E > orElse ( InputMapTemplate < S , ? extends E > that ) { } } | return sequence ( this , that ) ; |
public class CmsDefaultUsers { /** * Checks if a given user name is the name of the admin user . < p >
* @ param userName the user name to check
* @ return < code > true < / code > if a given user name is the name of the admin user */
public boolean isUserAdmin ( String userName ) { } } | if ( CmsStringUtil . isEmptyOrWhitespaceOnly ( userName ) ) { return false ; } return m_userAdmin . equals ( userName ) ; |
public class InstaLomoFilter { /** * NOTE : This is a PoC , and not good code . . . */
public BufferedImage filter ( BufferedImage src , BufferedImage dest ) { } } | if ( dest == null ) { dest = createCompatibleDestImage ( src , null ) ; } // Make image faded / washed out / red - ish
// DARK WARM
float [ ] scales = new float [ ] { 2.2f , 2.0f , 1.55f } ; float [ ] offsets = new float [ ] { - 20.0f , - 90.0f , - 110.0f } ; // BRIGHT NATURAL
// float [ ] scales = new float [ ] { 1.1f , . 9f , . 7f } ;
// float [ ] offsets = new float [ ] { 20 , 30 , 80 } ;
// Faded , old - style
// float [ ] scales = new float [ ] { 1.1f , . 7f , . 3f } ;
// float [ ] offsets = new float [ ] { 20 , 30 , 80 } ;
// float [ ] scales = new float [ ] { 1.2f , . 4f , . 4f } ;
// float [ ] offsets = new float [ ] { 0 , 120 , 120 } ;
// BRIGHT WARM
// float [ ] scales = new float [ ] { 1.1f , . 8f , 1.6f } ;
// float [ ] offsets = new float [ ] { 60 , 70 , - 80 } ;
BufferedImage image = new RescaleOp ( scales , offsets , getRenderingHints ( ) ) . filter ( src , null ) ; // Blur
image = ImageUtil . blur ( image , 2.5f ) ; Graphics2D g = dest . createGraphics ( ) ; try { g . setRenderingHint ( RenderingHints . KEY_ANTIALIASING , RenderingHints . VALUE_ANTIALIAS_ON ) ; g . setRenderingHint ( RenderingHints . KEY_COLOR_RENDERING , RenderingHints . VALUE_COLOR_RENDER_QUALITY ) ; g . drawImage ( image , 0 , 0 , null ) ; // Rotate it slightly for a more analogue feeling
double angle = .0055 ; g . rotate ( angle ) ; // Scratches
g . setComposite ( AlphaComposite . SrcOver . derive ( .025f ) ) ; for ( int i = 0 ; i < 100 ; i ++ ) { g . setColor ( random . nextBoolean ( ) ? Color . WHITE : Color . BLACK ) ; g . setStroke ( new BasicStroke ( random . nextFloat ( ) * 2f ) ) ; int x = random . nextInt ( image . getWidth ( ) ) ; int off = random . nextInt ( 100 ) ; for ( int j = random . nextInt ( 3 ) ; j > 0 ; j -- ) { g . drawLine ( x + j , 0 , x + off - 50 + j , image . getHeight ( ) ) ; } } // Vignette / border
g . setComposite ( AlphaComposite . SrcOver . derive ( .75f ) ) ; int focus = Math . min ( image . getWidth ( ) / 8 , image . getHeight ( ) / 8 ) ; g . setPaint ( new RadialGradientPaint ( new Point ( image . getWidth ( ) / 2 , image . getHeight ( ) / 2 ) , Math . max ( image . getWidth ( ) , image . getHeight ( ) ) / 1.6f , new Point ( focus , focus ) , new float [ ] { 0 , .3f , .9f , 1f } , new Color [ ] { new Color ( 0x99FFFFFF , true ) , new Color ( 0x00FFFFFF , true ) , new Color ( 0x0 , true ) , Color . BLACK } , MultipleGradientPaint . CycleMethod . NO_CYCLE ) ) ; g . fillRect ( - 2 , - 2 , image . getWidth ( ) + 4 , image . getHeight ( ) + 4 ) ; g . rotate ( - angle ) ; g . setComposite ( AlphaComposite . SrcOver . derive ( .35f ) ) ; g . setPaint ( new RadialGradientPaint ( new Point ( image . getWidth ( ) / 2 , image . getHeight ( ) / 2 ) , Math . max ( image . getWidth ( ) , image . getHeight ( ) ) / 1.65f , new Point ( image . getWidth ( ) / 2 , image . getHeight ( ) / 2 ) , new float [ ] { 0 , .85f , 1f } , new Color [ ] { new Color ( 0x0 , true ) , new Color ( 0x0 , true ) , Color . BLACK } , MultipleGradientPaint . CycleMethod . NO_CYCLE ) ) ; g . fillRect ( 0 , 0 , image . getWidth ( ) , image . getHeight ( ) ) ; // Highlight
g . setComposite ( AlphaComposite . SrcOver . derive ( .35f ) ) ; g . setPaint ( new RadialGradientPaint ( new Point ( image . getWidth ( ) , image . getHeight ( ) ) , Math . max ( image . getWidth ( ) , image . getHeight ( ) ) * 1.1f , new Point ( image . getWidth ( ) / 2 , image . getHeight ( ) / 2 ) , new float [ ] { 0 , .75f , 1f } , new Color [ ] { new Color ( 0x00FFFFFF , true ) , new Color ( 0x00FFFFFF , true ) , Color . PINK } , MultipleGradientPaint . CycleMethod . NO_CYCLE ) ) ; g . fillRect ( 0 , 0 , image . getWidth ( ) , image . getHeight ( ) ) ; } finally { g . dispose ( ) ; } // Noise
NoiseFilter noise = new NoiseFilter ( ) ; noise . setAmount ( 10 ) ; noise . setDensity ( 2 ) ; dest = noise . filter ( dest , dest ) ; // Round corners
BufferedImage foo = new BufferedImage ( image . getWidth ( ) , image . getHeight ( ) , BufferedImage . TYPE_INT_ARGB ) ; Graphics2D graphics = foo . createGraphics ( ) ; try { graphics . setRenderingHint ( RenderingHints . KEY_ANTIALIASING , RenderingHints . VALUE_ANTIALIAS_ON ) ; graphics . setRenderingHint ( RenderingHints . KEY_COLOR_RENDERING , RenderingHints . VALUE_COLOR_RENDER_QUALITY ) ; graphics . setColor ( Color . WHITE ) ; double angle = ( random . nextDouble ( ) * .01 ) - .005 ; graphics . rotate ( angle ) ; graphics . fillRoundRect ( 4 , 4 , image . getWidth ( ) - 8 , image . getHeight ( ) - 8 , 20 , 20 ) ; } finally { graphics . dispose ( ) ; } noise . setAmount ( 20 ) ; noise . setDensity ( 1 ) ; noise . setMonochrome ( true ) ; foo = noise . filter ( foo , foo ) ; foo = ImageUtil . blur ( foo , 4.5f ) ; // Compose image into rounded corners
graphics = foo . createGraphics ( ) ; try { graphics . setComposite ( AlphaComposite . SrcIn ) ; graphics . drawImage ( dest , 0 , 0 , null ) ; } finally { graphics . dispose ( ) ; } // Draw it all back to dest
g = dest . createGraphics ( ) ; try { if ( dest . getTransparency ( ) != Transparency . OPAQUE ) { g . setComposite ( AlphaComposite . Clear ) ; } g . setColor ( Color . WHITE ) ; g . fillRect ( 0 , 0 , image . getWidth ( ) , image . getHeight ( ) ) ; g . setComposite ( AlphaComposite . SrcOver ) ; g . drawImage ( foo , 0 , 0 , null ) ; } finally { g . dispose ( ) ; } return dest ; |
public class JsonRpcServerHandler { /** * In charge of validating all the transport - related aspects of the incoming
* HTTP request .
* < p > The checks include : < / p >
* < ul >
* < li > that the request ' s path matches that of this handler ; < / li >
* < li > that the request ' s method is { @ code POST } ; < / li >
* < li > that the request ' s content - type is { @ code application / json } ; < / li >
* < / ul >
* @ param request the received HTTP request
* @ return { @ code null } if the request passes the transport checks , an error
* to return to the client otherwise .
* @ throws URISyntaxException if the URI of the request cannot be parsed */
private JsonRpcError validateTransport ( HttpRequest request ) throws URISyntaxException , JsonRpcError { } } | URI uri = new URI ( request . getUri ( ) ) ; JsonRpcError error = null ; if ( ! uri . getPath ( ) . equals ( rpcPath ) ) { error = new JsonRpcError ( HttpResponseStatus . NOT_FOUND , "Not Found" ) ; } if ( ! request . getMethod ( ) . equals ( HttpMethod . POST ) ) { error = new JsonRpcError ( HttpResponseStatus . METHOD_NOT_ALLOWED , "Method not allowed" ) ; } if ( ! request . headers ( ) . get ( HttpHeaders . Names . CONTENT_TYPE ) . equals ( JsonRpcProtocol . CONTENT_TYPE ) ) { error = new JsonRpcError ( HttpResponseStatus . UNSUPPORTED_MEDIA_TYPE , "Unsupported media type" ) ; } return error ; |
public class GraphqlController { /** * GET end point */
@ RequestMapping ( method = RequestMethod . GET ) @ Transactional public Callable < ResponseEntity < JsonNode > > get ( @ RequestParam String query , @ RequestParam ( required = false ) String variables , @ RequestParam ( required = false ) String operationName ) throws IOException { } } | return ( ) -> { // Parses the arguments
Map < String , Object > arguments = decodeIntoMap ( variables ) ; // Runs the query
return ResponseEntity . ok ( requestAsJson ( new Request ( query , arguments , operationName ) ) ) ; } ; |
public class RPTree { /** * Build the tree with the given input data
* @ param x */
public void buildTree ( INDArray x ) { } } | this . X = x ; for ( int i = 0 ; i < x . rows ( ) ; i ++ ) { root . getIndices ( ) . add ( i ) ; } RPUtils . buildTree ( this , root , rpHyperPlanes , x , maxSize , 0 , similarityFunction ) ; |
public class HrefOperator { /** * Execute HREF operator . Uses property path to extract content value , convert it to string and set < em > href < / em > attribute .
* @ param element context element , unused ,
* @ param scope scope object ,
* @ param propertyPath property path ,
* @ param arguments optional arguments , unused .
* @ return always returns null for void .
* @ throws TemplateException if requested content value is undefined . */
@ Override protected Object doExec ( Element element , Object scope , String propertyPath , Object ... arguments ) throws TemplateException { } } | if ( ! propertyPath . equals ( "." ) && ConverterRegistry . hasType ( scope . getClass ( ) ) ) { throw new TemplateException ( "Operand is property path but scope is not an object." ) ; } Object value = content . getObject ( scope , propertyPath ) ; if ( value == null ) { return null ; } if ( value instanceof URL ) { value = ( ( URL ) value ) . toExternalForm ( ) ; } if ( ! ( value instanceof String ) ) { throw new TemplateException ( "Invalid element |%s|. HREF operand should be URL or string." , element ) ; } return new AttrImpl ( "href" , ( String ) value ) ; |
public class AbstractFormModel { /** * Remove a child FormModel . Dirty and committable listeners are removed .
* When child was dirty , remove the formModel from the dirty list and update
* the dirty state .
* @ param child FormModel to remove from childlist . */
public void removeChild ( HierarchicalFormModel child ) { } } | Assert . notNull ( child , "child" ) ; child . removeParent ( ) ; children . remove ( child ) ; child . removePropertyChangeListener ( DIRTY_PROPERTY , childStateChangeHandler ) ; child . removePropertyChangeListener ( COMMITTABLE_PROPERTY , childStateChangeHandler ) ; // when dynamically adding / removing childModels take care of
// dirtymessages :
// removing child that was dirty : remove from dirty map and update dirty
// state
if ( dirtyValueAndFormModels . remove ( child ) ) dirtyUpdated ( ) ; |
public class ConfigurationsInner { /** * Updates a configuration of a server .
* @ param resourceGroupName The name of the resource group that contains the resource . You can obtain this value from the Azure Resource Manager API or the portal .
* @ param serverName The name of the server .
* @ param configurationName The name of the server configuration .
* @ param parameters The required parameters for updating a server configuration .
* @ throws IllegalArgumentException thrown if parameters fail the validation
* @ throws CloudException thrown if the request is rejected by server
* @ throws RuntimeException all other wrapped checked exceptions if the request fails to be sent
* @ return the ConfigurationInner object if successful . */
public ConfigurationInner createOrUpdate ( String resourceGroupName , String serverName , String configurationName , ConfigurationInner parameters ) { } } | return createOrUpdateWithServiceResponseAsync ( resourceGroupName , serverName , configurationName , parameters ) . toBlocking ( ) . last ( ) . body ( ) ; |
public class JarCacheStorage { /** * Get all of the { @ code jarcache . json } resources that exist on the
* classpath
* @ return A cached list of jarcache . json classpath resources as
* { @ link URL } s
* @ throws IOException
* If there was an IO error while scanning the classpath */
private List < URL > getResources ( ) throws IOException { } } | final ClassLoader cl = getClassLoader ( ) ; // ConcurrentHashMap doesn ' t support null keys , so substitute a pseudo
// key
final Object key = cl == null ? NULL_CLASS_LOADER : cl ; // computeIfAbsent requires unchecked exceptions for the creation
// process , so we
// cannot easily use it directly , instead using get and putIfAbsent
List < URL > newValue = cachedResourceList . get ( key ) ; if ( newValue != null ) { return newValue ; } if ( cl != null ) { newValue = Collections . unmodifiableList ( Collections . list ( cl . getResources ( JARCACHE_JSON ) ) ) ; } else { newValue = Collections . unmodifiableList ( Collections . list ( ClassLoader . getSystemResources ( JARCACHE_JSON ) ) ) ; } final List < URL > oldValue = cachedResourceList . putIfAbsent ( key , newValue ) ; // We are not synchronising access to the ConcurrentMap , so if there
// were
// multiple classpath scans , we always choose the first one
return oldValue != null ? oldValue : newValue ; |
public class JDBC4PreparedStatement { /** * Sets the designated parameter to the given java . sql . Timestamp value . */
@ Override public void setTimestamp ( int parameterIndex , Timestamp x ) throws SQLException { } } | checkParameterBounds ( parameterIndex ) ; this . parameters [ parameterIndex - 1 ] = x == null ? VoltType . NULL_TIMESTAMP : x ; |
public class CloudantClient { /** * Provides access to Cloudant < tt > replication < / tt > APIs .
* @ return Replication object for configuration and triggering
* @ see com . cloudant . client . api . Replication
* @ see < a target = " _ blank "
* href = " https : / / console . bluemix . net / docs / services / Cloudant / api / advanced _ replication . html # the - _ replicate - endpoint " >
* Replication - the _ replicate endpoint < / a > */
public com . cloudant . client . api . Replication replication ( ) { } } | Replication couchDbReplication = couchDbClient . replication ( ) ; com . cloudant . client . api . Replication replication = new com . cloudant . client . api . Replication ( couchDbReplication ) ; return replication ; |
public class AppliedDiscountUrl { /** * Get Resource Url for RemoveCoupon
* @ param checkoutId The unique identifier of the checkout .
* @ param couponCode Code associated with the coupon to remove from the cart .
* @ return String Resource Url */
public static MozuUrl removeCouponUrl ( String checkoutId , String couponCode ) { } } | UrlFormatter formatter = new UrlFormatter ( "/api/commerce/checkouts/{checkoutId}/coupons/{couponcode}" ) ; formatter . formatUrl ( "checkoutId" , checkoutId ) ; formatter . formatUrl ( "couponCode" , couponCode ) ; return new MozuUrl ( formatter . getResourceUrl ( ) , MozuUrl . UrlLocation . TENANT_POD ) ; |
public class Gram { /** * Submits a GramJob to specified gatekeeper as an
* interactive job . Performs limited delegation .
* @ throws GramException if an error occurs during submisson
* @ param resourceManagerContact resource manager contact
* @ param job gram job */
public static void request ( String resourceManagerContact , GramJob job ) throws GramException , GSSException { } } | request ( resourceManagerContact , job , false ) ; |
public class ErrorMessage { /** * < p > parseMessage . < / p >
* @ param status a int .
* @ return a { @ link java . lang . String } object . */
public static String parseMessage ( int status ) { } } | String msg = null ; if ( status < 500 ) { if ( status == 402 || ( status > 417 && status < 421 ) || status > 424 ) { msg = ErrorMessage . getLocaleMessage ( 400 ) ; } else { msg = ErrorMessage . getLocaleMessage ( status ) ; } } else { switch ( status ) { case 501 : msg = ErrorMessage . getLocaleMessage ( status ) ; break ; } } if ( msg == null ) { msg = ErrorMessage . getLocaleMessage ( ) ; } return msg ; |
public class RequestTemplate { /** * Append the value to the template .
* This method is poorly named and is used primarily to store the relative uri for the request . It
* has been replaced by { @ link RequestTemplate # uri ( String ) } and will be removed in a future
* release .
* @ param value to append .
* @ return a RequestTemplate for chaining .
* @ deprecated see { @ link RequestTemplate # uri ( String , boolean ) } */
@ Deprecated public RequestTemplate append ( CharSequence value ) { } } | /* proxy to url */
if ( this . uriTemplate != null ) { return this . uri ( value . toString ( ) , true ) ; } return this . uri ( value . toString ( ) ) ; |
public class QNMinimizer { /** * computeDir ( )
* This function will calculate an approximation of the inverse hessian based
* off the seen s , y vector pairs . This particular approximation uses the BFGS
* update . */
private void computeDir ( double [ ] dir , double [ ] fg , QNInfo qn ) throws SurpriseConvergence { } } | System . arraycopy ( fg , 0 , dir , 0 , fg . length ) ; int mmm = qn . size ( ) ; double [ ] as = new double [ mmm ] ; for ( int i = mmm - 1 ; i >= 0 ; i -- ) { as [ i ] = qn . getRho ( i ) * ArrayMath . innerProduct ( qn . getS ( i ) , dir ) ; plusAndConstMult ( dir , qn . getY ( i ) , - as [ i ] , dir ) ; } // multiply by hessian approximation
qn . applyInitialHessian ( dir ) ; for ( int i = 0 ; i < mmm ; i ++ ) { double b = qn . getRho ( i ) * ArrayMath . innerProduct ( qn . getY ( i ) , dir ) ; plusAndConstMult ( dir , qn . getS ( i ) , as [ i ] - b , dir ) ; } ArrayMath . multiplyInPlace ( dir , - 1 ) ; |
public class RateLimitedLogger { /** * It is a very bad idea to use this when the message changes all the time .
* It ' s also a cache and only makes a best effort to enforce the rate limit . */
public static void tryLogForMessage ( long now , final long maxLogInterval , final TimeUnit maxLogIntervalUnit , final VoltLogger logger , final Level level , String format , Object ... parameters ) { } } | Callable < RateLimitedLogger > builder = new Callable < RateLimitedLogger > ( ) { @ Override public RateLimitedLogger call ( ) throws Exception { return new RateLimitedLogger ( maxLogIntervalUnit . toMillis ( maxLogInterval ) , logger , level ) ; } } ; final RateLimitedLogger rll ; try { rll = m_loggersCached . get ( format , builder ) ; rll . log ( now , level , null , format , parameters ) ; } catch ( ExecutionException ex ) { Throwables . propagate ( Throwables . getRootCause ( ex ) ) ; } |
public class BlockReader { /** * Read the block length information from data stream
* @ throws IOException */
private synchronized void readBlockSizeInfo ( ) throws IOException { } } | if ( ! transferBlockSize ) { return ; } blkLenInfoUpdated = true ; isBlockFinalized = in . readBoolean ( ) ; updatedBlockLength = in . readLong ( ) ; if ( dataTransferVersion >= DataTransferProtocol . READ_PROFILING_VERSION ) { readDataNodeProfilingData ( ) ; } if ( LOG . isDebugEnabled ( ) ) { LOG . debug ( "ifBlockComplete? " + isBlockFinalized + " block size: " + updatedBlockLength ) ; } |
public class ChainingParser { /** * Reads all iCalendar objects from the stream .
* @ return the parsed iCalendar objects
* @ throws IOException if there ' s an I / O problem */
public List < ICalendar > all ( ) throws IOException { } } | StreamReader reader = constructReader ( ) ; if ( index != null ) { reader . setScribeIndex ( index ) ; } try { List < ICalendar > icals = new ArrayList < ICalendar > ( ) ; ICalendar ical ; while ( ( ical = reader . readNext ( ) ) != null ) { if ( warnings != null ) { warnings . add ( reader . getWarnings ( ) ) ; } icals . add ( ical ) ; } return icals ; } finally { if ( closeWhenDone ( ) ) { reader . close ( ) ; } } |
public class HttpObjectFactory { /** * Return a response object to the factory for pooling .
* @ param response */
public void releaseResponse ( HttpResponseMessageImpl response ) { } } | if ( TraceComponent . isAnyTracingEnabled ( ) && tc . isDebugEnabled ( ) ) { Tr . debug ( tc , "releaseResponse: " + response ) ; } this . respPool . put ( response ) ; |
public class DiscreteCosineTransform { /** * 1 - D Forward Discrete Cosine Transform .
* @ param data Data . */
public static void Forward ( double [ ] data ) { } } | double [ ] result = new double [ data . length ] ; double sum ; double scale = Math . sqrt ( 2.0 / data . length ) ; for ( int f = 0 ; f < data . length ; f ++ ) { sum = 0 ; for ( int t = 0 ; t < data . length ; t ++ ) { double cos = Math . cos ( ( ( 2.0 * t + 1.0 ) * f * Math . PI ) / ( 2.0 * data . length ) ) ; sum += data [ t ] * cos * alpha ( f ) ; } result [ f ] = scale * sum ; } for ( int i = 0 ; i < data . length ; i ++ ) { data [ i ] = result [ i ] ; } |
public class CmsPreferences { /** * Sets the " workplace search result style " . < p >
* @ param style the " workplace search result style " to set */
public void setParamTabExWorkplaceSearchResult ( String style ) { } } | if ( style == null ) { style = OpenCms . getWorkplaceManager ( ) . getDefaultUserSettings ( ) . getWorkplaceSearchViewStyle ( ) . getMode ( ) ; } m_userSettings . setWorkplaceSearchViewStyle ( CmsSearchResultStyle . valueOf ( style ) ) ; |
public class AttributeProxy { public static void main ( String args [ ] ) { } } | String deviceName = "tango/admin/corvus/hoststate" ; try { AttributeProxy att = new AttributeProxy ( deviceName ) ; att . ping ( ) ; System . out . println ( att . name ( ) + " is alive" ) ; DbAttribute db_att = att . get_property ( ) ; for ( int i = 0 ; i < db_att . size ( ) ; i ++ ) { DbDatum datum = db_att . datum ( i ) ; System . out . println ( datum . name + " : " + datum . extractString ( ) ) ; } DeviceAttribute da = att . read ( ) ; System . out . println ( att . name ( ) + " : " + da . extractShort ( ) ) ; System . out . println ( att . name ( ) + " state : " + ApiUtil . stateName ( att . state ( ) ) ) ; System . out . println ( att . name ( ) + " status : " + att . status ( ) ) ; } catch ( DevFailed e ) { Except . print_exception ( e ) ; } |
public class SerializationUtil { /** * Writes a map to given { @ code ObjectDataOutput } .
* @ param map the map to serialize , can be { @ code null }
* @ param out the output to write the map to */
public static < K , V > void writeNullableMap ( Map < K , V > map , ObjectDataOutput out ) throws IOException { } } | // write true when the map is NOT null
out . writeBoolean ( map != null ) ; if ( map == null ) { return ; } writeMap ( map , out ) ; |
public class HessianProxyFactory { /** * Creates a new proxy with the specified URL . The returned object
* is a proxy with the interface specified by api .
* < pre >
* String url = " http : / / localhost : 8080 / ejb / hello " ) ;
* HelloHome hello = ( HelloHome ) factory . create ( HelloHome . class , url ) ;
* < / pre >
* @ param api the interface the proxy class needs to implement
* @ param url the URL where the client object is located .
* @ return a proxy to the object with the specified interface . */
public Object create ( Class api , String urlName ) throws MalformedURLException { } } | return create ( api , urlName , _loader ) ; |
public class ClassLoaderHelper { /** * Get all URLs of the passed resource using the specified class loader only .
* This is a sanity wrapper around
* < code > classLoader . getResources ( sPath ) < / code > .
* @ param aClassLoader
* The class loader to be used . May not be < code > null < / code > .
* @ param sPath
* The path to be resolved . May neither be < code > null < / code > nor empty .
* Internally it is ensured that the provided path does NOT start with
* a slash .
* @ return < code > null < / code > if the path could not be resolved using the
* specified class loader .
* @ throws IOException
* In case an internal error occurs . */
@ Nonnull public static Enumeration < URL > getResources ( @ Nonnull final ClassLoader aClassLoader , @ Nonnull @ Nonempty final String sPath ) throws IOException { } } | ValueEnforcer . notNull ( aClassLoader , "ClassLoader" ) ; ValueEnforcer . notEmpty ( sPath , "Path" ) ; // Ensure the path does NOT starts with a " / "
final String sPathWithoutSlash = _getPathWithoutLeadingSlash ( sPath ) ; // returns null if not found
return aClassLoader . getResources ( sPathWithoutSlash ) ; |
public class Ray { /** * Sets this Ray from the given start and end points .
* @ param start the starting point of this ray
* @ param end the starting point of this ray
* @ return this ray for chaining . */
public Ray < T > set ( T start , T end ) { } } | this . start . set ( start ) ; this . end . set ( end ) ; return this ; |
public class JSONAssert { /** * Asserts that the JSONObject provided matches the expected JSONObject . If it isn ' t it throws an
* { @ link AssertionError } .
* @ param message Error message to be displayed in case of assertion failure
* @ param expected Expected JSONObject
* @ param actual JSONObject to compare
* @ param compareMode Specifies which comparison mode to use
* @ throws JSONException JSON parsing error */
public static void assertEquals ( String message , JSONObject expected , JSONObject actual , JSONCompareMode compareMode ) throws JSONException { } } | JSONCompareResult result = JSONCompare . compareJSON ( expected , actual , compareMode ) ; if ( result . failed ( ) ) { throw new AssertionError ( getCombinedMessage ( message , result . getMessage ( ) ) ) ; } |
public class CmsAvailabilityDialog { /** * Performs the notification operations on a single resource . < p >
* @ param cms the CMS context
* @ param resName the VFS path of the resource
* @ param enableNotification if the notification is activated
* @ param notificationInterval the notification interval in days
* @ param modifySiblings flag indicating to include resource siblings
* @ throws CmsException if the availability and notification operations fail */
private void performSingleResourceNotification ( CmsObject cms , String resName , boolean enableNotification , int notificationInterval , boolean modifySiblings ) throws CmsException { } } | List < CmsResource > resources = new ArrayList < CmsResource > ( ) ; if ( modifySiblings ) { // modify all siblings of a resource
resources = cms . readSiblings ( resName , CmsResourceFilter . IGNORE_EXPIRATION ) ; } else { // modify only resource without siblings
resources . add ( cms . readResource ( resName , CmsResourceFilter . IGNORE_EXPIRATION ) ) ; } Iterator < CmsResource > i = resources . iterator ( ) ; while ( i . hasNext ( ) ) { CmsResource resource = i . next ( ) ; // lock resource if auto lock is enabled
CmsLockActionRecord lockRecord = CmsLockUtil . ensureLock ( cms , resource ) ; try { // write notification settings
writeProperty ( cms , resource , CmsPropertyDefinition . PROPERTY_NOTIFICATION_INTERVAL , String . valueOf ( notificationInterval ) ) ; writeProperty ( cms , resource , CmsPropertyDefinition . PROPERTY_ENABLE_NOTIFICATION , String . valueOf ( enableNotification ) ) ; } finally { if ( lockRecord . getChange ( ) == LockChange . locked ) { cms . unlockResource ( resource ) ; } } } |
public class LinkPubSubTransmitMessageControl { /** * / * ( non - Javadoc )
* @ see com . ibm . ws . sib . processor . runtime . LinkTransmitMessageControl # getTargetBus ( ) */
public String getTargetBus ( ) { } } | if ( TraceComponent . isAnyTracingEnabled ( ) && tc . isEntryEnabled ( ) ) SibTr . entry ( tc , "getTargetBus" ) ; String bus = null ; if ( parent instanceof LinkPublicationPointControl ) { LinkPublicationPointControl lppc = ( LinkPublicationPointControl ) parent ; bus = lppc . getTargetBusName ( ) ; } else { // parent is not an instance of LinkPublicationPointControl
SIErrorException finalE = new SIErrorException ( nls . getFormattedMessage ( "INTERNAL_MESSAGING_ERROR_CWSIP0005" , new Object [ ] { "LinkPubSubTransmitMessageControl.getTargetBus" , "1:149:1.7" , parent } , null ) ) ; // FFDC
FFDCFilter . processException ( finalE , "com.ibm.ws.sib.processor.runtime.LinkPubSubTransmitMessageControl.getTargetBus" , "1:157:1.7" , this ) ; SibTr . exception ( tc , finalE ) ; if ( TraceComponent . isAnyTracingEnabled ( ) && tc . isEntryEnabled ( ) ) SibTr . exit ( tc , "getTargetBus" , finalE ) ; throw finalE ; } if ( TraceComponent . isAnyTracingEnabled ( ) && tc . isEntryEnabled ( ) ) SibTr . exit ( tc , "getTargetBus" , bus ) ; return bus ; |
public class NumericRangeValueExpression { /** * / * ( non - Javadoc )
* @ see com . github . mkolisnyk . aerial . expressions . ValueExpression # validate ( ) */
@ Override public void validate ( ) throws Exception { } } | super . validate ( ) ; this . parse ( ) ; Assert . assertTrue ( String . format ( "Lower bound %d should be less than upper bound %d" , lower , upper ) , lower <= upper ) ; Assert . assertFalse ( "The range is empty" , ! this . includeLower && ! this . includeUpper && ( this . upper - this . lower ) <= 1 ) ; Assert . assertFalse ( "The range is empty" , ! ( this . includeLower && this . includeUpper ) && ( this . upper - this . lower ) < 1 ) ; |
public class AdminDictMappingAction { private static OptionalEntity < CharMappingItem > getEntity ( final CreateForm form ) { } } | switch ( form . crudMode ) { case CrudMode . CREATE : final CharMappingItem entity = new CharMappingItem ( 0 , StringUtil . EMPTY_STRINGS , StringUtil . EMPTY ) ; return OptionalEntity . of ( entity ) ; case CrudMode . EDIT : if ( form instanceof EditForm ) { return ComponentUtil . getComponent ( CharMappingService . class ) . getCharMappingItem ( form . dictId , ( ( EditForm ) form ) . id ) ; } break ; default : break ; } return OptionalEntity . empty ( ) ; |
public class Jdk8DateConverter { /** * 通过反射从字符串转java . time中的对象
* @ param value 字符串值
* @ return 日期对象 */
private Object parseFromCharSequence ( CharSequence value ) { } } | Method method ; if ( null != this . format ) { final Object dateTimeFormatter = getDateTimeFormatter ( ) ; method = ReflectUtil . getMethod ( this . targetType , "parse" , CharSequence . class , dateTimeFormatter . getClass ( ) ) ; return ReflectUtil . invokeStatic ( method , value , dateTimeFormatter ) ; } else { method = ReflectUtil . getMethod ( this . targetType , "parse" , CharSequence . class ) ; return ReflectUtil . invokeStatic ( method , value ) ; } |
public class Sets { /** * Returns a set backed by the specified map . The resulting set displays
* the same ordering , concurrency , and performance characteristics as the
* backing map . In essence , this factory method provides a { @ link Set }
* implementation corresponding to any { @ link Map } implementation . There is no
* need to use this method on a { @ link Map } implementation that already has a
* corresponding { @ link Set } implementation ( such as { @ link java . util . HashMap }
* or { @ link java . util . TreeMap } ) .
* < p > Each method invocation on the set returned by this method results in
* exactly one method invocation on the backing map or its { @ code keySet }
* view , with one exception . The { @ code addAll } method is implemented as a
* sequence of { @ code put } invocations on the backing map .
* < p > The specified map must be empty at the time this method is invoked ,
* and should not be accessed directly after this method returns . These
* conditions are ensured if the map is created empty , passed directly
* to this method , and no reference to the map is retained , as illustrated
* in the following code fragment : < pre > { @ code
* Set < Object > identityHashSet = Sets . newSetFromMap (
* new IdentityHashMap < Object , Boolean > ( ) ) ; } < / pre >
* < p > This method has the same behavior as the JDK 6 method
* { @ code Collections . newSetFromMap ( ) } . The returned set is serializable if
* the backing map is .
* @ param map the backing map
* @ return the set backed by the map
* @ throws IllegalArgumentException if { @ code map } is not empty */
public static < E > Set < E > newSetFromMap ( Map < E , Boolean > map ) { } } | return Platform . newSetFromMap ( map ) ; |
public class StreamingBaseHtmlProvider { /** * Get a FedoraResource for the subject of the graph , if it exists .
* @ param subjectUri the uri of the subject
* @ return FedoraResource if exists or null */
private FedoraResource getResourceFromSubject ( final String subjectUri ) { } } | final UriTemplate uriTemplate = new UriTemplate ( uriInfo . getBaseUriBuilder ( ) . clone ( ) . path ( FedoraLdp . class ) . toTemplate ( ) ) ; final Map < String , String > values = new HashMap < > ( ) ; uriTemplate . match ( subjectUri , values ) ; if ( values . containsKey ( "path" ) ) { try { return translator ( ) . convert ( translator ( ) . toDomain ( values . get ( "path" ) ) ) ; } catch ( final RuntimeException e ) { if ( e . getCause ( ) instanceof PathNotFoundException ) { // there is at least one case ( ie Time Map endpoints - aka / fcr : versions ) where the underlying jcr
// node will not exist while the end point is visible to the user .
return null ; } else { throw e ; } } } return null ; |
public class ContinuousDistributions { /** * Samples from Multinomial Normal Distribution .
* @ param mean
* @ param covariance
* @ return A multinomialGaussianSample from the Multinomial Normal Distribution */
public static double [ ] multinomialGaussianSample ( double [ ] mean , double [ ] [ ] covariance ) { } } | MultivariateNormalDistribution gaussian = new MultivariateNormalDistribution ( mean , covariance ) ; gaussian . reseedRandomGenerator ( RandomGenerator . getThreadLocalRandom ( ) . nextLong ( ) ) ; return gaussian . sample ( ) ; |
public class Classes { /** * Do the actual reflexive method invocation .
* @ param object object instance ,
* @ param method reflexive method ,
* @ param arguments variable number of arguments .
* @ return value returned by method execution .
* @ throws Exception if invocation fail for whatever reason including method internals . */
private static Object invoke ( Object object , Method method , Object ... arguments ) throws Exception { } } | Throwable cause = null ; try { method . setAccessible ( true ) ; return method . invoke ( object instanceof Class < ? > ? null : object , arguments ) ; } catch ( IllegalAccessException e ) { throw new BugError ( e ) ; } catch ( InvocationTargetException e ) { cause = e . getCause ( ) ; if ( cause instanceof Exception ) { throw ( Exception ) cause ; } if ( cause instanceof AssertionError ) { throw ( AssertionError ) cause ; } } throw new BugError ( "Method |%s| invocation fails: %s" , method , cause ) ; |
public class GeometryExpression { /** * TODO maybe move out */
public NumberExpression < Double > distanceSphere ( Expression < ? extends Geometry > geometry ) { } } | return Expressions . numberOperation ( Double . class , SpatialOps . DISTANCE_SPHERE , mixin , geometry ) ; |
public class CamelRouteActionBuilder { /** * Execute control bus Camel operations .
* @ return */
public CamelControlBusActionBuilder controlBus ( ) { } } | CamelControlBusAction camelControlBusAction = new CamelControlBusAction ( ) ; camelControlBusAction . setCamelContext ( getCamelContext ( ) ) ; action . setDelegate ( camelControlBusAction ) ; return new CamelControlBusActionBuilder ( camelControlBusAction ) ; |
public class RingBuffer { /** * Allows one user supplied argument .
* @ param translator The user specified translation for each event
* @ param batchStartsAt The first element of the array which is within the batch .
* @ param batchSize The actual size of the batch
* @ param arg0 An array of user supplied arguments , one element per event .
* @ return true if the value was published , false if there was insufficient capacity .
* @ see # tryPublishEvents ( EventTranslator [ ] ) */
public < A > boolean tryPublishEvents ( EventTranslatorOneArg < E , A > translator , int batchStartsAt , int batchSize , A [ ] arg0 ) { } } | checkBounds ( arg0 , batchStartsAt , batchSize ) ; try { final long finalSequence = sequencer . tryNext ( batchSize ) ; translateAndPublishBatch ( translator , arg0 , batchStartsAt , batchSize , finalSequence ) ; return true ; } catch ( InsufficientCapacityException e ) { return false ; } |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.