signature stringlengths 43 39.1k | implementation stringlengths 0 450k |
|---|---|
public class Instance { /** * Gets the instance ' s id . */
@ SuppressWarnings ( "WeakerAccess" ) public String getId ( ) { } } | // Constructor ensures that name is not null
InstanceName fullName = Verify . verifyNotNull ( InstanceName . parse ( proto . getName ( ) ) , "Name can never be null" ) ; // noinspection ConstantConditions
return fullName . getInstance ( ) ; |
public class CmsADEConfigDataInternal { /** * Handle the ordering from the module configurations . < p > */
protected void processModuleOrdering ( ) { } } | Collections . sort ( m_ownResourceTypes , new Comparator < CmsResourceTypeConfig > ( ) { public int compare ( CmsResourceTypeConfig a , CmsResourceTypeConfig b ) { return ComparisonChain . start ( ) . compare ( a . getOrder ( ) , b . getOrder ( ) ) . compare ( a . getTypeName ( ) , b . getTypeName ( ) ) . result ( ) ; } } ) ; Collections . sort ( m_ownPropertyConfigurations , new Comparator < CmsPropertyConfig > ( ) { public int compare ( CmsPropertyConfig a , CmsPropertyConfig b ) { return ComparisonChain . start ( ) . compare ( a . getOrder ( ) , b . getOrder ( ) ) . compare ( a . getName ( ) , b . getName ( ) ) . result ( ) ; } } ) ; Collections . sort ( m_functionReferences , new Comparator < CmsFunctionReference > ( ) { public int compare ( CmsFunctionReference a , CmsFunctionReference b ) { return ComparisonChain . start ( ) . compare ( a . getOrder ( ) , b . getOrder ( ) ) . compare ( a . getName ( ) , b . getName ( ) ) . result ( ) ; } } ) ; |
public class CmsSecurityManager { /** * Returns all resources associated to a given principal via an ACE with the given permissions . < p >
* If the < code > includeAttr < / code > flag is set it returns also all resources associated to
* a given principal through some of following attributes . < p >
* < ul >
* < li > User Created < / li >
* < li > User Last Modified < / li >
* < / ul > < p >
* @ param context the current request context
* @ param principalId the id of the principal
* @ param permissions a set of permissions to match , can be < code > null < / code > for all ACEs
* @ param includeAttr a flag to include resources associated by attributes
* @ return a set of < code > { @ link CmsResource } < / code > objects
* @ throws CmsException if something goes wrong */
public Set < CmsResource > getResourcesForPrincipal ( CmsRequestContext context , CmsUUID principalId , CmsPermissionSet permissions , boolean includeAttr ) throws CmsException { } } | Set < CmsResource > dependencies ; CmsDbContext dbc = m_dbContextFactory . getDbContext ( context ) ; try { dependencies = m_driverManager . getResourcesForPrincipal ( dbc , dbc . currentProject ( ) , principalId , permissions , includeAttr ) ; } catch ( Exception e ) { dbc . report ( null , Messages . get ( ) . container ( Messages . ERR_READ_RESOURCES_FOR_PRINCIPAL_LOG_1 , principalId ) , e ) ; dependencies = new HashSet < CmsResource > ( ) ; } finally { dbc . clear ( ) ; } return dependencies ; |
public class RestorableMeter { /** * Mark the occurrence of a given number of events .
* @ param n the number of events */
public void mark ( long n ) { } } | tickIfNecessary ( ) ; count . addAndGet ( n ) ; m15Rate . update ( n ) ; m120Rate . update ( n ) ; |
public class SystemKeyspace { /** * This method is used to update the System Keyspace with the new tokens for this node */
public static synchronized void updateTokens ( Collection < Token > tokens ) { } } | assert ! tokens . isEmpty ( ) : "removeEndpoint should be used instead" ; String req = "INSERT INTO system.%s (key, tokens) VALUES ('%s', ?)" ; executeInternal ( String . format ( req , LOCAL_CF , LOCAL_KEY ) , tokensAsSet ( tokens ) ) ; forceBlockingFlush ( LOCAL_CF ) ; |
public class ImageMiscOps { /** * Inserts a single band into a multi - band image overwriting the original band
* @ param input Single band image
* @ param band Which band the image is to be inserted into
* @ param output The multi - band image which the input image is to be inserted into */
public static void insertBand ( GrayI8 input , int band , InterleavedI8 output ) { } } | final int numBands = output . numBands ; for ( int y = 0 ; y < input . height ; y ++ ) { int indexIn = input . getStartIndex ( ) + y * input . getStride ( ) ; int indexOut = output . getStartIndex ( ) + y * output . getStride ( ) + band ; int end = indexOut + output . width * numBands - band ; for ( ; indexOut < end ; indexOut += numBands , indexIn ++ ) { output . data [ indexOut ] = input . data [ indexIn ] ; } } |
public class Node { /** * Get the affiliations of this node .
* { @ code additionalExtensions } can be used e . g . to add a " Result Set Management " extension .
* { @ code returnedExtensions } will be filled with the stanza extensions found in the answer .
* @ param additionalExtensions additional { @ code PacketExtensions } add to the request
* @ param returnedExtensions a collection that will be filled with the returned packet
* extensions
* @ return List of { @ link Affiliation }
* @ throws NoResponseException
* @ throws XMPPErrorException
* @ throws NotConnectedException
* @ throws InterruptedException */
public List < Affiliation > getAffiliations ( List < ExtensionElement > additionalExtensions , Collection < ExtensionElement > returnedExtensions ) throws NoResponseException , XMPPErrorException , NotConnectedException , InterruptedException { } } | return getAffiliations ( AffiliationNamespace . basic , additionalExtensions , returnedExtensions ) ; |
public class AbstractFFmpegStreamBuilder { /** * Add metadata on output streams . Which keys are possible depends on the used codec .
* @ param key Metadata key , e . g . " comment "
* @ param value Value to set for key
* @ return this */
public T addMetaTag ( String key , String value ) { } } | checkValidKey ( key ) ; checkNotEmpty ( value , "value must not be empty" ) ; meta_tags . add ( "-metadata" ) ; meta_tags . add ( key + "=" + value ) ; return getThis ( ) ; |
public class StringUtils { /** * 判断字符串是否为空
* @ param str 待判断的字符串
* @ return 是否是空字符串 , true : 空字符串 ; false : 非空字符串 */
public static boolean isEmpty ( String str ) { } } | if ( str == null ) return true ; if ( "" . equals ( str . trim ( ) ) ) return true ; return str . isEmpty ( ) ; |
public class ObjectUtils { /** * Gets the value of a given property into a given bean .
* @ param < T >
* the property type .
* @ param < Q >
* the bean type .
* @ param bean
* the bean itself .
* @ param propertyName
* the property name .
* @ param propertyType
* the property type .
* @ return the property value .
* @ see PropertyAccessorFactory */
@ SuppressWarnings ( "unchecked" ) public static < T , Q > T getPropertyValue ( Q bean , String propertyName , Class < T > propertyType ) { } } | Assert . notNull ( bean , "bean" ) ; Assert . notNull ( propertyName , "propertyName" ) ; final PropertyAccessor propertyAccessor = PropertyAccessorFactory . forDirectFieldAccess ( bean ) ; try { Assert . isAssignable ( propertyType , propertyAccessor . getPropertyType ( propertyName ) ) ; } catch ( InvalidPropertyException e ) { throw new IllegalStateException ( "Invalid property \"" + propertyName + "\"" , e ) ; } return ( T ) propertyAccessor . getPropertyValue ( propertyName ) ; |
public class Timecode { /** * Goes through the system and sanitizes badly formed values : 00:00:60:00 will become
* 00:01:00:00 , etc . */
@ SuppressWarnings ( "all" ) public void normalize ( ) { } } | // Start on samples
int samplesPerFrame = ( int ) ( ( float ) getSamplesPerSecond ( ) / ( float ) getFramesPerSecond ( ) ) ; setFrames ( getFrames ( ) + ( int ) ( getSamples ( ) * ( 1.0f / samplesPerFrame ) ) ) ; setSamples ( getSamples ( ) % samplesPerFrame ) ; setSeconds ( getSeconds ( ) + ( int ) ( ( float ) getFrames ( ) / getFramesPerSecond ( ) ) ) ; setFrames ( ( int ) ( getFrames ( ) % getFramesPerSecond ( ) ) ) ; while ( getSeconds ( ) >= 60 ) { setSeconds ( getSeconds ( ) - 60 ) ; setMinutes ( getMinutes ( ) + 1 ) ; } while ( getMinutes ( ) >= 60 ) { setMinutes ( getMinutes ( ) - 60 ) ; setHours ( getHours ( ) + 1 ) ; } |
public class Stream { /** * Terminal operation storing the elements of this Stream in the supplied map as
* { @ code < key , value > } pairs computed using the supplied Functions . The supplied key and
* value Functions are called for each element , producing the keys and values to store in the
* Map . If a null key or value are produced , the element is discarded . If multiple values are
* mapped to the same key , only the most recently computed one will be stored . Use
* { @ link Functions # identity ( ) } in case no transformation is required to extract the key
* and / or the value .
* @ param keyFunction
* the key function
* @ param valueFunction
* the value function
* @ param map
* the Map where to store the extracted { @ code < key , value > } pairs
* @ param < K >
* the type of key
* @ param < V >
* the type of value
* @ param < M >
* the type of Map
* @ return the supplied Map */
public final < K , V , M extends Map < K , V > > M toMap ( final Function < ? super T , ? extends K > keyFunction , final Function < ? super T , ? extends V > valueFunction , final M map ) { } } | Preconditions . checkNotNull ( keyFunction ) ; Preconditions . checkNotNull ( valueFunction ) ; Preconditions . checkNotNull ( map ) ; toHandler ( new Handler < T > ( ) { @ Override public void handle ( final T element ) { if ( element != null ) { final K key = keyFunction . apply ( element ) ; final V value = valueFunction . apply ( element ) ; if ( key != null && value != null ) { map . put ( key , value ) ; } } } } ) ; return map ; |
public class MapRow { /** * Retrieve a timestamp field .
* @ param dateName field containing the date component
* @ param timeName field containing the time component
* @ return Date instance */
public Date getTimestamp ( FastTrackField dateName , FastTrackField timeName ) { } } | Date result = null ; Date date = getDate ( dateName ) ; if ( date != null ) { Calendar dateCal = DateHelper . popCalendar ( date ) ; Date time = getDate ( timeName ) ; if ( time != null ) { Calendar timeCal = DateHelper . popCalendar ( time ) ; dateCal . set ( Calendar . HOUR_OF_DAY , timeCal . get ( Calendar . HOUR_OF_DAY ) ) ; dateCal . set ( Calendar . MINUTE , timeCal . get ( Calendar . MINUTE ) ) ; dateCal . set ( Calendar . SECOND , timeCal . get ( Calendar . SECOND ) ) ; dateCal . set ( Calendar . MILLISECOND , timeCal . get ( Calendar . MILLISECOND ) ) ; DateHelper . pushCalendar ( timeCal ) ; } result = dateCal . getTime ( ) ; DateHelper . pushCalendar ( dateCal ) ; } return result ; |
public class ESHttpMarshaller { /** * Creates a single " application / vnd . eventstore . events + xml " entry .
* @ param registry
* Registry with known serializers .
* @ param targetContentType
* Type of content that will be created later on .
* @ param commonEvent
* Event to marshal .
* @ return Single event that has to be surrounded by " & lt ; Events & gt ; & lt ; / Events & gt ; " . */
private EscEvent createEscEvent ( final SerializerRegistry registry , final EnhancedMimeType targetContentType , final CommonEvent commonEvent ) { } } | Contract . requireArgNotNull ( "registry" , registry ) ; Contract . requireArgNotNull ( "targetContentType" , targetContentType ) ; Contract . requireArgNotNull ( "commonEvent" , commonEvent ) ; final EscMeta meta = EscSpiUtils . createEscMeta ( registry , targetContentType , commonEvent ) ; final String dataType = commonEvent . getDataType ( ) . asBaseType ( ) ; final SerializedDataType serDataType = new SerializedDataType ( dataType ) ; final Serializer dataSerializer = registry . getSerializer ( serDataType ) ; if ( dataSerializer . getMimeType ( ) . match ( targetContentType ) ) { return new EscEvent ( commonEvent . getId ( ) . asBaseType ( ) , dataType , new DataWrapper ( commonEvent . getData ( ) ) , new DataWrapper ( meta ) ) ; } final byte [ ] serData = dataSerializer . marshal ( commonEvent . getData ( ) , serDataType ) ; return new EscEvent ( commonEvent . getId ( ) . asBaseType ( ) , dataType , new DataWrapper ( new Base64Data ( serData ) ) , new DataWrapper ( meta ) ) ; |
public class ProxyFactory { /** * Returns an instance of a proxy class for the specified interfaces
* that dispatches method invocations to the specified invocation
* handler .
* @ paramloader the class loader to define the proxy class
* @ paramintf the interface for the proxy to implement
* @ param h the invocation handler to dispatch method invocations to
* @ returna proxy instance with the specified invocation handler of a
* proxy class that is defined by the specified class loader
* and that implements the specified interfaces
* @ throwsIllegalArgumentException if any of the restrictions on the
* parameters that may be passed to < code > getProxyClass < / code >
* are violated
* @ throwsNullPointerException if the < code > interfaces < / code > array
* argument or any of its elements are < code > null < / code > , or
* if the invocation handler , < code > h < / code > , is
* < code > null < / code > */
public static < T > T create ( ClassLoader loader , Class < T > intf , InvocationHandler h ) { } } | return ( T ) Proxy . newProxyInstance ( loader , new Class [ ] { intf } , h ) ; |
public class JaxWsUtils { /** * Check whether the regQName matches the targetQName
* Only the localPart of the regQName supports the * match , it means only the name space and prefix is all matched , then
* the localPart will be compared considering the *
* When the ignorePrefix is true , the prefix will be ignored .
* @ param regQName
* @ param targetQName
* @ param ignorePrefix
* @ return */
public static boolean matchesQName ( QName regQName , QName targetQName , boolean ignorePrefix ) { } } | if ( regQName == null || targetQName == null ) { return false ; } if ( "*" . equals ( getQNameString ( regQName ) ) ) { return true ; } // if the name space or the prefix is not equal , just return false ;
if ( ! ( regQName . getNamespaceURI ( ) . equals ( targetQName . getNamespaceURI ( ) ) ) || ! ( ignorePrefix || regQName . getPrefix ( ) . equals ( targetQName . getPrefix ( ) ) ) ) { return false ; } if ( regQName . getLocalPart ( ) . contains ( "*" ) ) { return Pattern . matches ( mapPattern ( regQName . getLocalPart ( ) ) , targetQName . getLocalPart ( ) ) ; } else if ( regQName . getLocalPart ( ) . equals ( targetQName . getLocalPart ( ) ) ) { return true ; } return false ; |
public class ReferenceResolvingVisitor { /** * Takes the MethodInvocation , and attempts to resolve the types of objects passed into the method invocation . */
public boolean visit ( MethodInvocation node ) { } } | if ( ! StringUtils . contains ( node . toString ( ) , "." ) ) { // it must be a local method . ignore .
return true ; } List < String > qualifiedInstances = new ArrayList < > ( ) ; List < String > argumentsQualified = new ArrayList < > ( ) ; // get qualified arguments of the method
IMethodBinding resolveTypeBinding = node . resolveMethodBinding ( ) ; final ResolutionStatus resolutionStatus ; int columnNumber = compilationUnit . getColumnNumber ( node . getName ( ) . getStartPosition ( ) ) ; int length = node . getName ( ) . getLength ( ) ; if ( resolveTypeBinding != null ) { resolutionStatus = ResolutionStatus . RESOLVED ; ITypeBinding [ ] argumentTypeBindings = resolveTypeBinding . getParameterTypes ( ) ; List < Expression > arguments = node . arguments ( ) ; int index = 0 ; for ( ITypeBinding type : argumentTypeBindings ) { argumentsQualified . add ( type . getQualifiedName ( ) ) ; if ( type . isEnum ( ) ) { // there is different number of passed arguments and possible arguments from declaration
if ( arguments . size ( ) > index ) { Expression expression = arguments . get ( index ) ; processTypeAsEnum ( type , expression , resolutionStatus , compilationUnit . getLineNumber ( node . getName ( ) . getStartPosition ( ) ) , columnNumber , length , extractDefinitionLine ( node . toString ( ) ) ) ; } index ++ ; } } // find the interface declaring the method
if ( resolveTypeBinding != null && resolveTypeBinding . getDeclaringClass ( ) != null ) { ITypeBinding declaringClass = resolveTypeBinding . getDeclaringClass ( ) ; qualifiedInstances . add ( declaringClass . getQualifiedName ( ) ) ; ITypeBinding [ ] interfaces = declaringClass . getInterfaces ( ) ; // Now find all the implemented interfaces having the method called .
for ( ITypeBinding possibleInterface : interfaces ) { IMethodBinding [ ] declaredMethods = possibleInterface . getDeclaredMethods ( ) ; if ( declaredMethods . length != 0 ) { for ( IMethodBinding interfaceMethod : declaredMethods ) { if ( interfaceMethod . getName ( ) . equals ( node . getName ( ) . toString ( ) ) ) { List < String > interfaceMethodArguments = new ArrayList < > ( ) ; for ( ITypeBinding type : interfaceMethod . getParameterTypes ( ) ) { interfaceMethodArguments . add ( type . getQualifiedName ( ) ) ; } if ( interfaceMethodArguments . equals ( argumentsQualified ) ) { qualifiedInstances . add ( possibleInterface . getQualifiedName ( ) ) ; } } } } } } } else { resolutionStatus = ResolutionStatus . RECOVERED ; String nodeName = StringUtils . removeStart ( node . toString ( ) , "this." ) ; String objRef = StringUtils . substringBefore ( nodeName , "." + node . getName ( ) . toString ( ) ) ; if ( state . getNameInstance ( ) . containsKey ( objRef ) ) { objRef = state . getNameInstance ( ) . get ( objRef ) ; } objRef = resolveClassname ( objRef ) . result ; @ SuppressWarnings ( "unchecked" ) List < Expression > arguments = node . arguments ( ) ; for ( Expression expression : arguments ) { ITypeBinding argumentBinding = expression . resolveTypeBinding ( ) ; if ( argumentBinding != null ) { argumentsQualified . add ( argumentBinding . getQualifiedName ( ) ) ; if ( argumentBinding . isEnum ( ) ) { // FIXME - - Test
String constantEnum = expression . toString ( ) ; if ( constantEnum != null ) { processTypeAsEnum ( argumentBinding , expression , ResolutionStatus . RESOLVED , compilationUnit . getLineNumber ( node . getName ( ) . getStartPosition ( ) ) , columnNumber , length , extractDefinitionLine ( node . toString ( ) ) ) ; } } } else { PackageAndClassName argumentQualifiedGuess = PackageAndClassName . parseFromQualifiedName ( expression . toString ( ) ) ; argumentsQualified . add ( argumentQualifiedGuess . toString ( ) ) ; } } qualifiedInstances . add ( objRef ) ; } for ( String qualifiedInstance : qualifiedInstances ) { PackageAndClassName packageAndClassName = PackageAndClassName . parseFromQualifiedName ( qualifiedInstance ) ; MethodType methodCall = new MethodType ( qualifiedInstance , packageAndClassName . packageName , packageAndClassName . className , node . getName ( ) . toString ( ) , argumentsQualified ) ; processMethod ( methodCall , resolutionStatus , TypeReferenceLocation . METHOD_CALL , compilationUnit . getLineNumber ( node . getName ( ) . getStartPosition ( ) ) , columnNumber , length , node . toString ( ) ) ; } return super . visit ( node ) ; |
public class PluginManager { /** * This method will initialize all the loaded plugins
* @ throws PluginException */
public void initAllLoadedPlugins ( ) throws PluginException { } } | LOGGER . debug ( "Initializig all loaded plugins" ) ; for ( Class < ? extends Plugin > pluginClass : implementations . keySet ( ) ) { Set < PluginContext > set = implementations . get ( pluginClass ) ; for ( PluginContext pluginContext : set ) { try { pluginContext . initialize ( pluginContext . getSystemSettings ( ) ) ; } catch ( Throwable e ) { LOGGER . error ( "" , e ) ; pluginContext . setEnabled ( false , false ) ; } } } |
public class UniformDataGenerator { /** * generates randomly N distinct integers from 0 to Max .
* @ param N
* number of integers to generate
* @ param Max
* bound on the value of integers
* @ return an array containing randomly selected integers */
public int [ ] generateUniform ( int N , int Max ) { } } | if ( N * 2 > Max ) { return negate ( generateUniform ( Max - N , Max ) , Max ) ; } if ( 2048 * N > Max ) return generateUniformBitmap ( N , Max ) ; return generateUniformHash ( N , Max ) ; |
public class MetaLocale { /** * Constructs a MetaLocale from a language tag string . */
public static MetaLocale fromLanguageTag ( String tag ) { } } | if ( tag . indexOf ( '_' ) != - 1 ) { tag = tag . replace ( '_' , SEP ) ; } return fromJavaLocale ( java . util . Locale . forLanguageTag ( tag ) ) ; |
public class HttpURLFeedFetcher { /** * Retrieve a feed over HTTP
* @ param feedUrl A non - null URL of a RSS / Atom feed to retrieve
* @ return A { @ link com . rometools . rome . feed . synd . SyndFeed } object
* @ throws IllegalArgumentException if the URL is null ;
* @ throws IOException if a TCP error occurs
* @ throws FeedException if the feed is not valid
* @ throws FetcherException if a HTTP error occurred */
@ Override public SyndFeed retrieveFeed ( final String userAgent , final URL feedUrl ) throws IllegalArgumentException , IOException , FeedException , FetcherException { } } | if ( feedUrl == null ) { throw new IllegalArgumentException ( "null is not a valid URL" ) ; } final URLConnection connection = feedUrl . openConnection ( ) ; if ( ! ( connection instanceof HttpURLConnection ) ) { throw new IllegalArgumentException ( feedUrl . toExternalForm ( ) + " is not a valid HTTP Url" ) ; } final HttpURLConnection httpConnection = ( HttpURLConnection ) connection ; if ( connectTimeout >= 0 ) { httpConnection . setConnectTimeout ( connectTimeout ) ; } // httpConnection . setInstanceFollowRedirects ( true ) ; / / this is true by default , but can be
// changed on a claswide basis
final FeedFetcherCache cache = getFeedInfoCache ( ) ; if ( cache != null ) { SyndFeedInfo syndFeedInfo = cache . getFeedInfo ( feedUrl ) ; setRequestHeaders ( connection , syndFeedInfo , userAgent ) ; httpConnection . connect ( ) ; try { fireEvent ( FetcherEvent . EVENT_TYPE_FEED_POLLED , connection ) ; if ( syndFeedInfo == null ) { // this is a feed that hasn ' t been retrieved
syndFeedInfo = new SyndFeedInfo ( ) ; retrieveAndCacheFeed ( feedUrl , syndFeedInfo , httpConnection ) ; } else { // check the response code
final int responseCode = httpConnection . getResponseCode ( ) ; if ( responseCode != HttpURLConnection . HTTP_NOT_MODIFIED ) { // the response code is not 304 NOT MODIFIED
// This is either because the feed server
// does not support condition gets
// or because the feed hasn ' t changed
retrieveAndCacheFeed ( feedUrl , syndFeedInfo , httpConnection ) ; } else { // the feed does not need retrieving
fireEvent ( FetcherEvent . EVENT_TYPE_FEED_UNCHANGED , connection ) ; } } return syndFeedInfo . getSyndFeed ( ) ; } finally { httpConnection . disconnect ( ) ; } } else { fireEvent ( FetcherEvent . EVENT_TYPE_FEED_POLLED , connection ) ; InputStream inputStream = null ; setRequestHeaders ( connection , null , userAgent ) ; httpConnection . connect ( ) ; try { inputStream = httpConnection . getInputStream ( ) ; return getSyndFeedFromStream ( inputStream , connection ) ; } catch ( final java . io . IOException e ) { handleErrorCodes ( ( ( HttpURLConnection ) connection ) . getResponseCode ( ) ) ; } finally { IO . close ( inputStream ) ; httpConnection . disconnect ( ) ; } // we will never actually get to this line
return null ; } |
public class BooleanConverter { /** * { @ inheritDoc } */
@ Override public Boolean convert ( String v ) { } } | if ( v == null ) { return null ; } if ( v . equalsIgnoreCase ( "true" ) || v . equalsIgnoreCase ( "yes" ) || v . equalsIgnoreCase ( "y" ) || v . equalsIgnoreCase ( "on" ) || v . equalsIgnoreCase ( "1" ) ) { return Boolean . TRUE ; } else { return Boolean . FALSE ; } |
public class WxCryptUtil { /** * 4个字节的网络字节序bytes数组还原成一个数字
* @ param bytesInNetworkOrder */
private int bytesNetworkOrder2Number ( byte [ ] bytesInNetworkOrder ) { } } | int sourceNumber = 0 ; for ( int i = 0 ; i < 4 ; i ++ ) { sourceNumber <<= 8 ; sourceNumber |= bytesInNetworkOrder [ i ] & 0xff ; } return sourceNumber ; |
public class StringUtility { /** * Splits a < code > String < / code > into a < code > String [ ] < / code > . */
public static int splitString ( String line , char [ ] [ ] [ ] buff ) { } } | int len = line . length ( ) ; int wordCount = 0 ; int pos = 0 ; while ( pos < len ) { // Skip past blank space
while ( pos < len && line . charAt ( pos ) <= ' ' ) pos ++ ; int start = pos ; // Skip to the next blank space
while ( pos < len && line . charAt ( pos ) > ' ' ) pos ++ ; if ( pos > start ) wordCount ++ ; } char [ ] [ ] words = buff [ 0 ] ; if ( words == null || words . length < wordCount ) buff [ 0 ] = words = new char [ wordCount ] [ ] ; int wordPos = 0 ; pos = 0 ; while ( pos < len ) { // Skip past blank space
while ( pos < len && line . charAt ( pos ) <= ' ' ) pos ++ ; int start = pos ; // Skip to the next blank space
while ( pos < len && line . charAt ( pos ) > ' ' ) pos ++ ; if ( pos > start ) { int chlen = pos - start ; char [ ] tch = words [ wordPos ++ ] = new char [ chlen ] ; System . arraycopy ( line . toCharArray ( ) , start , tch , 0 , chlen ) ; } } return wordCount ; |
public class ConstraintExceptionMapper { /** * Creates a constrainedBy link header with the appropriate RDF URL for the exception .
* @ param e ConstraintViolationException Exception which implements the buildContraintUri method .
* @ param context ServletContext ServletContext that we ' re running in .
* @ param uriInfo UriInfo UriInfo from the ExceptionMapper .
* @ return Link A http : / / www . w3 . org / ns / ldp # constrainedBy link header */
public static Link buildConstraintLink ( final ConstraintViolationException e , final ServletContext context , final UriInfo uriInfo ) { } } | String path = context . getContextPath ( ) ; if ( path . equals ( "/" ) ) { path = "" ; } final String constraintURI = uriInfo == null ? "" : String . format ( "%s://%s%s%s%s.rdf" , uriInfo . getBaseUri ( ) . getScheme ( ) , uriInfo . getBaseUri ( ) . getAuthority ( ) , path , CONSTRAINT_DIR , e . getClass ( ) . toString ( ) . substring ( e . getClass ( ) . toString ( ) . lastIndexOf ( '.' ) + 1 ) ) ; return Link . fromUri ( constraintURI ) . rel ( CONSTRAINED_BY . getURI ( ) ) . build ( ) ; |
public class SelectOption { /** * Release any acquired resources . */
protected void localRelease ( ) { } } | super . localRelease ( ) ; _state . clear ( ) ; _text = null ; _disabled = false ; _value = null ; _hasError = false ; |
public class CardAPI { /** * 核查code
* @ param accessToken accessToken
* @ param codeCheck codeCheck
* @ return result */
public static CodeCheckCodeResult codeCheckCode ( String accessToken , CodeCheckCode codeCheck ) { } } | return codeCheckCode ( accessToken , JsonUtil . toJSONString ( codeCheck ) ) ; |
public class PropertiesEscape { /** * Perform a ( configurable ) Java Properties Key < strong > escape < / strong > operation on a < tt > char [ ] < / tt > input .
* This method will perform an escape operation according to the specified
* { @ link org . unbescape . properties . PropertiesKeyEscapeLevel } argument value .
* All other < tt > String < / tt > - based < tt > escapePropertiesKey * ( . . . ) < / tt > methods call this one with
* preconfigured < tt > level < / tt > values .
* This method is < strong > thread - safe < / strong > .
* @ param text the < tt > char [ ] < / tt > to be escaped .
* @ param offset the position in < tt > text < / tt > at which the escape operation should start .
* @ param len the number of characters in < tt > text < / tt > that should be escaped .
* @ param writer the < tt > java . io . Writer < / tt > to which the escaped result will be written . Nothing will
* be written at all to this writer if input is < tt > null < / tt > .
* @ param level the escape level to be applied , see { @ link org . unbescape . properties . PropertiesKeyEscapeLevel } .
* @ throws IOException if an input / output exception occurs */
public static void escapePropertiesKey ( final char [ ] text , final int offset , final int len , final Writer writer , final PropertiesKeyEscapeLevel level ) throws IOException { } } | if ( writer == null ) { throw new IllegalArgumentException ( "Argument 'writer' cannot be null" ) ; } if ( level == null ) { throw new IllegalArgumentException ( "The 'level' argument cannot be null" ) ; } final int textLen = ( text == null ? 0 : text . length ) ; if ( offset < 0 || offset > textLen ) { throw new IllegalArgumentException ( "Invalid (offset, len). offset=" + offset + ", len=" + len + ", text.length=" + textLen ) ; } if ( len < 0 || ( offset + len ) > textLen ) { throw new IllegalArgumentException ( "Invalid (offset, len). offset=" + offset + ", len=" + len + ", text.length=" + textLen ) ; } PropertiesKeyEscapeUtil . escape ( text , offset , len , writer , level ) ; |
public class ClusTree { /** * XXX : Document the insertion when the final implementation is done . */
private Entry insertHere ( Entry newEntry , Node currentNode , Entry parentEntry , ClusKernel carriedBuffer , Budget budget , long timestamp ) { } } | int numFreeEntries = currentNode . numFreeEntries ( ) ; // Insert the buffer that we carry .
if ( ! carriedBuffer . isEmpty ( ) ) { Entry bufferEntry = new Entry ( this . numberDimensions , carriedBuffer , timestamp , parentEntry , currentNode ) ; if ( numFreeEntries <= 1 ) { // Distance from buffer to entries .
Entry nearestEntryToCarriedBuffer = currentNode . nearestEntry ( newEntry ) ; double distanceNearestEntryToBuffer = nearestEntryToCarriedBuffer . calcDistance ( newEntry ) ; // Distance between buffer and point to insert .
double distanceBufferNewEntry = newEntry . calcDistance ( carriedBuffer ) ; // Best distance between Entrys in the Node .
BestMergeInNode bestMergeInNode = calculateBestMergeInNode ( currentNode ) ; // See what the minimal distance is and do the correspoding
// action .
if ( distanceNearestEntryToBuffer <= distanceBufferNewEntry && distanceNearestEntryToBuffer <= bestMergeInNode . distance ) { // Aggregate buffer entry to nearest entry in node .
nearestEntryToCarriedBuffer . aggregateEntry ( bufferEntry , timestamp , this . negLambda ) ; } else if ( distanceBufferNewEntry <= distanceNearestEntryToBuffer && distanceBufferNewEntry <= bestMergeInNode . distance ) { newEntry . mergeWith ( bufferEntry ) ; } else { currentNode . mergeEntries ( bestMergeInNode . entryPos1 , bestMergeInNode . entryPos2 ) ; currentNode . addEntry ( bufferEntry , timestamp ) ; } } else { assert ( currentNode . isLeaf ( ) ) ; currentNode . addEntry ( bufferEntry , timestamp ) ; } } // Normally the insertion of the carries buffer does not change the
// number of free entries , but in case of future changes we calculate
// the number again .
numFreeEntries = currentNode . numFreeEntries ( ) ; // Search for an Entry with a weight under the threshold .
Entry irrelevantEntry = currentNode . getIrrelevantEntry ( this . weightThreshold ) ; if ( currentNode . isLeaf ( ) && irrelevantEntry != null ) { irrelevantEntry . overwriteOldEntry ( newEntry ) ; } else if ( numFreeEntries >= 1 ) { currentNode . addEntry ( newEntry , timestamp ) ; } else { if ( currentNode . isLeaf ( ) && ( this . hasMaximalSize ( ) || ! budget . hasMoreTime ( ) ) ) { mergeEntryWithoutSplit ( currentNode , newEntry , timestamp ) ; } else { // We have to split .
return split ( newEntry , currentNode , parentEntry , timestamp ) ; } } return null ; |
public class LookupManagerImpl { /** * { @ inheritDoc } */
@ Override public List < ServiceInstance > lookupInstances ( String serviceName ) throws ServiceException { } } | if ( ! isStarted ) { ServiceDirectoryError error = new ServiceDirectoryError ( ErrorCode . SERVICE_DIRECTORY_MANAGER_FACTORY_CLOSED ) ; throw new ServiceException ( error ) ; } List < ModelServiceInstance > modelSvc = getLookupService ( ) . getUPModelInstances ( serviceName ) ; if ( modelSvc == null || modelSvc . isEmpty ( ) ) { return Collections . emptyList ( ) ; } else { List < ServiceInstance > instances = new ArrayList < ServiceInstance > ( ) ; for ( ModelServiceInstance modelInstance : modelSvc ) { instances . add ( ServiceInstanceUtils . transferFromModelServiceInstance ( modelInstance ) ) ; } return instances ; } |
public class AFactoryAppBeans { /** * < p > Get SrvNumberToString in lazy mode . < / p >
* @ return SrvNumberToString - SrvNumberToString
* @ throws Exception - an exception */
public final SrvNumberToString lazyGetSrvNumberToString ( ) throws Exception { } } | String beanName = getSrvNumberToStringName ( ) ; SrvNumberToString srvDate = ( SrvNumberToString ) this . beansMap . get ( beanName ) ; if ( srvDate == null ) { srvDate = new SrvNumberToString ( ) ; this . beansMap . put ( beanName , srvDate ) ; lazyGetLogger ( ) . info ( null , AFactoryAppBeans . class , beanName + " has been created." ) ; } return srvDate ; |
public class CmsXmlContentEditor { /** * Returns the HTML for the element operation buttons add , move , remove . < p >
* @ param value the value for which the buttons are generated
* @ param addElement if true , the button to add an element is shown
* @ param removeElement if true , the button to remove an element is shown
* @ return the HTML for the element operation buttons */
private String buildElementButtons ( I_CmsXmlContentValue value , boolean addElement , boolean removeElement ) { } } | StringBuffer jsCall = new StringBuffer ( 512 ) ; String elementName = CmsXmlUtils . removeXpathIndex ( value . getPath ( ) ) ; // indicates if at least one button is active
boolean buttonPresent = false ; int index = value . getIndex ( ) ; jsCall . append ( "showElementButtons('" ) ; jsCall . append ( elementName ) ; jsCall . append ( "', " ) ; jsCall . append ( index ) ; jsCall . append ( ", " ) ; // build the remove element button if required
if ( removeElement ) { jsCall . append ( Boolean . TRUE ) ; buttonPresent = true ; } else { jsCall . append ( Boolean . FALSE ) ; } jsCall . append ( ", " ) ; // build the move down button ( move down in API is move up for content editor )
if ( index > 0 ) { // build active move down button
jsCall . append ( Boolean . TRUE ) ; buttonPresent = true ; } else { jsCall . append ( Boolean . FALSE ) ; } jsCall . append ( ", " ) ; // build the move up button ( move up in API is move down for content editor )
int indexCount = m_content . getIndexCount ( elementName , getElementLocale ( ) ) ; if ( index < ( indexCount - 1 ) ) { // build active move up button
jsCall . append ( Boolean . TRUE ) ; buttonPresent = true ; } else { jsCall . append ( Boolean . FALSE ) ; } jsCall . append ( ", " ) ; // build the add element button if required
if ( addElement ) { jsCall . append ( Boolean . TRUE ) ; buttonPresent = true ; } else { jsCall . append ( Boolean . FALSE ) ; } jsCall . append ( ", " ) ; JSONArray newElements = buildElementChoices ( elementName , value . isChoiceType ( ) , true ) ; jsCall . append ( "'" ) . append ( CmsEncoder . escape ( newElements . toString ( ) , CmsEncoder . ENCODING_UTF_8 ) ) . append ( "'" ) ; jsCall . append ( ");" ) ; String result ; if ( buttonPresent ) { // at least one button active , create mouseover button
String btIcon = "xmledit.png" ; String btAction = jsCall . toString ( ) ; // determine icon to use and if a direct click action is possible
if ( addElement && removeElement ) { btIcon = "xmledit_del_add.png" ; } else if ( addElement ) { btIcon = "xmledit_add.png" ; // create button action to add element on button click
StringBuffer action = new StringBuffer ( 128 ) ; action . append ( "addElement('" ) ; action . append ( elementName ) ; action . append ( "', " ) ; action . append ( index ) ; action . append ( ", '" ) . append ( CmsEncoder . escape ( newElements . toString ( ) , CmsEncoder . ENCODING_UTF_8 ) ) . append ( "'" ) ; action . append ( ");" ) ; btAction = action . toString ( ) ; } else if ( removeElement ) { btIcon = "xmledit_del.png" ; // create button action to remove element on button click
StringBuffer action = new StringBuffer ( 128 ) ; action . append ( "removeElement('" ) ; action . append ( elementName ) ; action . append ( "', " ) ; action . append ( index ) ; action . append ( ");" ) ; btAction = action . toString ( ) ; } StringBuffer href = new StringBuffer ( 512 ) ; href . append ( "javascript:" ) ; href . append ( btAction ) ; href . append ( "\" onmouseover=\"" ) ; href . append ( jsCall ) ; href . append ( "checkElementButtons(true);\" onmouseout=\"checkElementButtons(false);\" id=\"btimg." ) ; href . append ( elementName ) . append ( "." ) . append ( index ) ; result = button ( href . toString ( ) , null , btIcon , Messages . GUI_EDITOR_XMLCONTENT_ELEMENT_BUTTONS_0 , 0 ) ; } else { // no active button , create a spacer
result = buttonBarSpacer ( 1 ) ; } return result ; |
public class RTMPConnection { /** * { @ inheritDoc } */
public void ping ( ) { } } | long newPingTime = System . currentTimeMillis ( ) ; if ( log . isDebugEnabled ( ) ) { log . debug ( "Send Ping: session=[{}], currentTime=[{}], lastPingTime=[{}]" , new Object [ ] { getSessionId ( ) , newPingTime , lastPingSentOn . get ( ) } ) ; } if ( lastPingSentOn . get ( ) == 0 ) { lastPongReceivedOn . set ( newPingTime ) ; } Ping pingRequest = new Ping ( ) ; pingRequest . setEventType ( Ping . PING_CLIENT ) ; lastPingSentOn . set ( newPingTime ) ; int now = ( int ) ( newPingTime & 0xffffffffL ) ; pingRequest . setValue2 ( now ) ; ping ( pingRequest ) ; |
public class Grefenstette { /** * { @ inheritDoc } */
public Vector getVector ( String word ) { } } | word = word . toLowerCase ( ) ; if ( objectTable . containsKey ( word ) ) { int wordIndex = objectTable . get ( word ) ; if ( wordIndex < syntacticCooccurrence . rows ( ) ) { return syntacticCooccurrence . getRowVector ( wordIndex ) ; } // At this section , several exception handlers were removed . These
// may have been superfluous , or the code may have relied on them
// being caught .
} return null ; |
public class LazyUserTransaction { public static List < IndependentProcessor > getLazyProcessList ( ) { } } | // not null , empty allowed
final String lazyKey = generateLazyProcessListKey ( ) ; final List < IndependentProcessor > lazyList = ThreadCacheContext . getObject ( lazyKey ) ; return lazyList != null ? lazyList : Collections . emptyList ( ) ; |
public class DefaultObjectCreator { /** * 根据XML构造体在对象中填入属性 */
@ SuppressWarnings ( { } } | "rawtypes" , "unchecked" } ) private void setAttribute ( NodeConfig nodeConfig , Object targetObject ) throws UnmarshalException { Class targetClass = targetObject . getClass ( ) ; List attributes = nodeConfig . getAttribute ( ) ; if ( attributes != null && attributes . size ( ) > 0 ) { for ( Iterator iterAttr = attributes . iterator ( ) ; iterAttr . hasNext ( ) ; ) { AttributeConfig attribute = ( AttributeConfig ) iterAttr . next ( ) ; String methodName = Constant . SET_PREFIX + StringUtils . capitalize ( attribute . getName ( ) ) ; try { Method method = targetClass . getMethod ( methodName , String . class ) ; if ( method != null ) { setMethod ( method , targetObject , attribute . getValue ( ) ) ; } } catch ( NoSuchMethodException e ) { if ( validation ) { throw new UnmarshalException ( e ) ; } } } } |
public class JsonParserLax { /** * Decodes a number from a JSON value . If at any point it is determined that
* the value is not a valid number the value is treated as a { @ code String } .
* @ param minus indicate whether the number is negative
* @ return a number , or { @ code String } if not a valid number */
protected final Value decodeNumberLax ( boolean minus ) { } } | char [ ] array = charArray ; final int startIndex = __index ; int index = __index ; char currentChar ; boolean doubleFloat = false ; boolean foundDot = false ; boolean foundSign = false ; boolean foundExp = false ; if ( minus && index + 1 < array . length ) { index ++ ; } while ( true ) { currentChar = array [ index ] ; if ( isNumberDigit ( currentChar ) ) { // noop
} else if ( currentChar <= 32 ) { // white
break ; } else if ( isDelimiter ( currentChar ) ) { break ; } else if ( isDecimalChar ( currentChar ) ) { switch ( currentChar ) { case DECIMAL_POINT : if ( foundDot || foundExp ) { return decodeStringLax ( ) ; } foundDot = true ; break ; case LETTER_E : case LETTER_BIG_E : if ( foundExp ) { return decodeStringLax ( ) ; } foundExp = true ; break ; case MINUS : case PLUS : if ( foundSign || ! foundExp ) { return decodeStringLax ( ) ; } if ( foundExp && array [ index - 1 ] != LETTER_E && array [ index - 1 ] != LETTER_BIG_E ) { return decodeStringLax ( ) ; } foundSign = true ; break ; } doubleFloat = true ; } else { return decodeStringLax ( ) ; } index ++ ; if ( index >= array . length ) break ; } // Handle the case where the exponential number ends without the actual exponent
if ( foundExp ) { char prevChar = array [ index - 1 ] ; if ( prevChar == LETTER_E || prevChar == LETTER_BIG_E || prevChar == MINUS || prevChar == PLUS ) { return decodeStringLax ( ) ; } } __index = index ; __currentChar = currentChar ; Type type = doubleFloat ? Type . DOUBLE : Type . INTEGER ; return new NumberValue ( chop , type , startIndex , __index , this . charArray ) ; |
public class SunburstChart { /** * Defines if tthe color of all chart segments in one group should be filled with the color
* of the groups root node or by the color defined in the chart data elements
* @ param USE */
public void setUseColorFromParent ( final boolean USE ) { } } | if ( null == useColorFromParent ) { _useColorFromParent = USE ; redraw ( ) ; } else { useColorFromParent . set ( USE ) ; } |
public class LogChannel { /** * This method will only be called AFTER affirming that we should be logging */
void log ( SessionLogEntry entry , String formattedMessage ) { } } | int level = entry . getLevel ( ) ; Throwable loggedException = entry . getException ( ) ; String msgParm ; if ( ( formattedMessage == null || formattedMessage . equals ( "" ) ) && loggedException != null ) { msgParm = loggedException . toString ( ) ; } else { msgParm = formattedMessage ; } switch ( level ) { case 8 : return ; case 7 : // SEVERE
// With the persistence service , only errors will be logged . The rest will be debug .
String errMsg = Tr . formatMessage ( _stc , "PROVIDER_ERROR_CWWKD0292E" , msgParm ) ; Tr . error ( _tc , errMsg ) ; break ; case 6 : // WARN
String wrnMsg = Tr . formatMessage ( _stc , "PROVIDER_WARNING_CWWKD0291W" , msgParm ) ; Tr . debug ( _tc , wrnMsg ) ; // 170432 - move warnings to debug
break ; case 3 : // FINE
case 2 : // FINER
case 1 : // FINEST
case 0 : // TRACE
Tr . debug ( _tc , formattedMessage ) ; break ; } // end switch
// if there is an exception - only log it to trace
if ( _tc . isDebugEnabled ( ) && loggedException != null ) { Tr . debug ( _tc , "throwable" , loggedException ) ; } |
public class PolymerClassRewriter { /** * For any strings returned in the array from the Polymer static observers property , parse the
* method call and path arguments and replace them with property reflection calls .
* < p > Returns a list of property sink statements to guard against dead code elimination since the
* compiler may not see these methods as being used . */
private List < Node > addComplexObserverReflectionCalls ( final PolymerClassDefinition cls ) { } } | List < Node > propertySinkStatements = new ArrayList < > ( ) ; Node classMembers = NodeUtil . getClassMembers ( cls . definition ) ; Node getter = NodeUtil . getFirstGetterMatchingKey ( classMembers , "observers" ) ; if ( getter != null ) { Node complexObservers = null ; for ( Node child : NodeUtil . getFunctionBody ( getter . getFirstChild ( ) ) . children ( ) ) { if ( child . isReturn ( ) ) { if ( child . hasChildren ( ) && child . getFirstChild ( ) . isArrayLit ( ) ) { complexObservers = child . getFirstChild ( ) ; break ; } } } if ( complexObservers != null ) { for ( Node complexObserver : complexObservers . children ( ) ) { if ( complexObserver . isString ( ) ) { propertySinkStatements . addAll ( replaceMethodStringWithReflectedCalls ( cls . target , complexObserver ) ) ; } } } } return propertySinkStatements ; |
public class xen_hotfix { /** * Use this operation to apply new xen hotfixes . */
public static xen_hotfix apply ( nitro_service client , xen_hotfix resource ) throws Exception { } } | return ( ( xen_hotfix [ ] ) resource . perform_operation ( client , "apply" ) ) [ 0 ] ; |
public class AlphabetFactory { /** * 构造特征词典
* @ param name 词典名称
* @ return 特征词典 */
public IFeatureAlphabet buildFeatureAlphabet ( String name , Type type ) { } } | IAlphabet alphabet = null ; if ( ! maps . containsKey ( name ) ) { IFeatureAlphabet fa ; if ( type == Type . String ) fa = new StringFeatureAlphabet ( ) ; else if ( type == Type . Integer ) fa = new HashFeatureAlphabet ( ) ; else return null ; maps . put ( name , fa ) ; alphabet = maps . get ( name ) ; } else { alphabet = maps . get ( name ) ; if ( ! ( alphabet instanceof IFeatureAlphabet ) ) { throw new ClassCastException ( ) ; } } return ( IFeatureAlphabet ) alphabet ; |
public class WxPayApi { /** * 分账请求
* @ param params
* 请求参数
* @ param certPath
* 证书文件目录
* @ param certPass
* 证书密码
* @ return { String } */
public static String profitsharing ( Map < String , String > params , String certPath , String certPassword ) { } } | return doPostSSL ( PROFITSHARING_URL , params , certPath , certPassword ) ; |
public class StaticTypeCheckingVisitor { /** * Stores the inferred return type of a closure or a method . We are using a separate key to store
* inferred return type because the inferred type of a closure is { @ link Closure } , which is different
* from the inferred type of the code of the closure .
* @ param node a { @ link ClosureExpression } or a { @ link MethodNode }
* @ param type the inferred return type of the code
* @ return the old value of the inferred type */
protected ClassNode storeInferredReturnType ( final ASTNode node , final ClassNode type ) { } } | if ( ! ( node instanceof ClosureExpression ) ) { throw new IllegalArgumentException ( "Storing inferred return type is only allowed on closures but found " + node . getClass ( ) ) ; } return ( ClassNode ) node . putNodeMetaData ( StaticTypesMarker . INFERRED_RETURN_TYPE , type ) ; |
public class Streams { /** * Group a Stream until the supplied predicate holds
* @ see ReactiveSeq # groupedUntil ( Predicate )
* @ param stream Stream to group
* @ param predicate Predicate to determine grouping
* @ return Stream grouped into Lists determined by predicate */
public final static < T > Stream < Seq < T > > groupedUntil ( final Stream < T > stream , final Predicate < ? super T > predicate ) { } } | return groupedWhile ( stream , predicate . negate ( ) ) ; |
public class GZIPArchiveWriter { /** * Returns an object that can be used to write an entry in the GZIP archive .
* In order to write the actual entry , one must write the entry content on the { @ link GZIPArchive . WriteEntry # deflater } and ,
* at the end , call its < code > close ( ) < / code > method ( to actually write the compressed content ) .
* @ param name the name of the entry .
* @ param comment the comment of the entry .
* @ param creationDate the date in which the entry has been created . */
public GZIPArchive . WriteEntry getEntry ( final String name , final String comment , final Date creationDate ) { } } | crc . reset ( ) ; deflater . reset ( ) ; deflaterStream . reset ( ) ; final GZIPArchive . WriteEntry entry = new GZIPArchive . WriteEntry ( ) ; entry . setName ( name ) ; entry . setComment ( comment ) ; entry . deflater = new FilterOutputStream ( new DeflaterOutputStream ( deflaterStream , deflater ) ) { private final byte [ ] oneCharBuffer = new byte [ 1 ] ; private long length = 0 ; @ Override public void write ( int b ) throws IOException { // This avoids byte - array creation in DeflaterOutputStream . write ( )
oneCharBuffer [ 0 ] = ( byte ) b ; this . out . write ( oneCharBuffer ) ; crc . update ( oneCharBuffer ) ; this . length ++ ; } @ Override public void write ( byte [ ] b , int off , int len ) throws IOException { this . out . write ( b , off , len ) ; crc . update ( b , off , len ) ; this . length += len ; } @ Override public void close ( ) throws IOException { this . out . flush ( ) ; ( ( DeflaterOutputStream ) this . out ) . finish ( ) ; entry . compressedSkipLength = GZIPArchive . FIX_LEN + ( entry . name . length + 1 ) + ( entry . comment . length + 1 ) + deflaterStream . length ; entry . uncompressedSkipLength = ( int ) ( this . length & 0xFFFFFFFF ) ; entry . mtime = ( int ) ( creationDate . getTime ( ) / 1000 ) ; entry . crc32 = ( int ) ( crc . getValue ( ) & 0xFFFFFFFF ) ; writeEntry ( entry ) ; } } ; return entry ; |
public class URBridge { /** * Get the information about Users and Groups from the underlying User Registry
* @ param root Input object containing set identifiers of objects to be fetched ,
* and optionally control objects .
* @ throws WIMException improper control objects are in the input datagraph ,
* invalid properties are in a propertyControl object , or the underlying
* user registry throws an exception .
* @ return A Root object containing the required Person ( s ) or Group ( s ) */
@ Override public Root get ( Root root ) throws WIMException { } } | Root returnRoot = new Root ( ) ; String uniqueName = null ; String auditName = null ; AuditManager auditManager = new AuditManager ( ) ; try { List < String > attrList = null ; List < String > grpMbrAttrs = null ; List < String > grpMbrshipAttrs = null ; // Retrieve control objects
Map < String , Control > ctrlMap = ControlsHelper . getControlMap ( root ) ; PropertyControl propertyCtrl = ( PropertyControl ) ctrlMap . get ( Service . DO_PROPERTY_CONTROL ) ; GroupMemberControl grpMbrCtrl = ( GroupMemberControl ) ctrlMap . get ( SchemaConstants . DO_GROUP_MEMBER_CONTROL ) ; GroupMembershipControl grpMbrshipCtrl = ( GroupMembershipControl ) ctrlMap . get ( SchemaConstants . DO_GROUP_MEMBERSHIP_CONTROL ) ; // Set attributes to retrieve for member and membership operations .
if ( grpMbrCtrl != null ) { grpMbrAttrs = getAttributes ( grpMbrCtrl , personAccountType ) ; } if ( grpMbrshipCtrl != null ) { grpMbrshipAttrs = getAttributes ( grpMbrshipCtrl , groupAccountType ) ; } // Get a list of all the entities .
List < Entity > entities = root . getEntities ( ) ; for ( Entity entity : entities ) { uniqueName = entity . getIdentifier ( ) . getUniqueName ( ) ; if ( uniqueName == null ) { // find a name that we can use for audit purposes
if ( entity . getIdentifier ( ) . getUniqueId ( ) != null ) { auditName = entity . getIdentifier ( ) . getUniqueId ( ) ; } else if ( entity . getIdentifier ( ) . getExternalName ( ) != null ) { auditName = entity . getIdentifier ( ) . getExternalName ( ) ; } else if ( entity . getIdentifier ( ) . getExternalId ( ) != null ) { auditName = entity . getIdentifier ( ) . getExternalId ( ) ; } } String memberType = validateEntity ( entity ) ; Entity returnEntity = null ; if ( Service . DO_GROUP . equalsIgnoreCase ( memberType ) ) returnEntity = new Group ( ) ; else returnEntity = new PersonAccount ( ) ; returnRoot . getEntities ( ) . add ( returnEntity ) ; IdentifierType identifier = new IdentifierType ( ) ; identifier . setRepositoryId ( reposId ) ; returnEntity . setIdentifier ( identifier ) ; // Wrap the entity in an object that provides functionality to the entity .
URBridgeEntityFactory osEntityFactory = new URBridgeEntityFactory ( ) ; URBridgeEntity osEntity = osEntityFactory . createObject ( returnEntity , this , propsMap , baseEntryName , entityConfigMap ) ; osEntity . setSecurityNameProp ( uniqueName ) ; // Get the attributes and populate the entity .
attrList = getAttributes ( propertyCtrl , memberType ) ; if ( attrList != null ) { osEntity . populateEntity ( attrList ) ; } // If it ' s a group and there is a GroupMemberControl object , find the members .
if ( Service . DO_GROUP . equalsIgnoreCase ( memberType ) && grpMbrCtrl != null && grpMbrAttrs != null ) { int limit = 0 ; if ( grpMbrCtrl . isSetCountLimit ( ) ) { limit = grpMbrCtrl . getCountLimit ( ) ; } osEntity . getUsersForGroup ( grpMbrAttrs , limit ) ; } // If it ' s a user and there is a GroupMembershipControl object , find the groups .
else if ( ( Service . DO_LOGIN_ACCOUNT . equalsIgnoreCase ( memberType ) || Service . DO_PERSON_ACCOUNT . equalsIgnoreCase ( memberType ) ) && grpMbrshipCtrl != null && grpMbrshipAttrs != null ) { int limit = 0 ; if ( grpMbrshipCtrl . isSetCountLimit ( ) ) { limit = grpMbrshipCtrl . getCountLimit ( ) ; } osEntity . getGroupsForUser ( grpMbrshipAttrs , limit ) ; } } } catch ( EntityNotFoundException e ) { Audit . audit ( Audit . EventID . SECURITY_MEMBER_MGMT_01 , auditManager . getRESTRequest ( ) , AuditConstants . GET_AUDIT , reposId , uniqueName == null ? auditName : uniqueName , userRegistry . getRealm ( ) , returnRoot , Integer . valueOf ( "212" ) , AuditConstants . URBRIDGE ) ; throw e ; } catch ( Exception e ) { throw new WIMException ( e ) ; } setReturnContext ( root , returnRoot ) ; auditManager . setRealm ( userRegistry . getRealm ( ) ) ; if ( returnRoot != null && ! returnRoot . getEntities ( ) . isEmpty ( ) ) { Audit . audit ( Audit . EventID . SECURITY_MEMBER_MGMT_01 , auditManager . getRESTRequest ( ) , AuditConstants . GET_AUDIT , reposId , uniqueName , userRegistry . getRealm ( ) , returnRoot , Integer . valueOf ( "200" ) , AuditConstants . URBRIDGE ) ; } return returnRoot ; |
public class SftpClient { /** * Sets the transfer mode for current operations . The valid modes are : < br >
* < br >
* { @ link # MODE _ BINARY } - Files are transferred in binary mode and no
* processing of text files is performed ( default mode ) . < br >
* < br >
* { @ link # MODE _ TEXT } - For servers supporting version 4 + of the SFTP
* protocol files are transferred in text mode . For earlier protocol
* versions the files are transfered in binary mode but the client performs
* processing of text ; if files are written to the remote server the client
* ensures that the line endings conform to the remote EOL mode set using
* { @ link setRemoteEOL ( int ) } . For files retrieved from the server the EOL
* policy is based upon System policy as defined by the " line . seperator "
* system property .
* @ param transferMode
* int */
public void setTransferMode ( int transferMode ) { } } | if ( transferMode != MODE_BINARY && transferMode != MODE_TEXT ) throw new IllegalArgumentException ( "Mode can only be either binary or text" ) ; this . transferMode = transferMode ; if ( Log . isDebugEnabled ( ) ) { Log . debug ( this , "Transfer mode set to " + ( transferMode == MODE_BINARY ? "binary" : "text" ) ) ; } |
public class StrBuffer { /** * Get the next field and fill it with data from this buffer .
* You must override this method .
* @ param field The field to set .
* @ param bDisplayOption The display option for setting the field .
* @ param iMoveMove The move mode for setting the field .
* @ return The error code . */
public int getNextField ( FieldInfo field , boolean bDisplayOption , int iMoveMode ) // Must be to call right Get calls
{ } } | String string = this . getNextString ( ) ; if ( string == null ) return Constants . ERROR_RETURN ; if ( string == DATA_SKIP ) return Constants . NORMAL_RETURN ; // Don ' t set this field
return field . setString ( string , bDisplayOption , iMoveMode ) ; |
public class ItemUtils { /** * Gets the { @ link ItemStack } matching the specified { @ link IBlockState }
* @ param state the state
* @ return the item stack from state */
public static ItemStack getItemStackFromState ( IBlockState state ) { } } | if ( state == null ) return null ; Item item = Item . getItemFromBlock ( state . getBlock ( ) ) ; if ( item == null ) return ItemStack . EMPTY ; return new ItemStack ( item , 1 , state . getBlock ( ) . damageDropped ( state ) ) ; |
public class JSModuleGraph { /** * If a weak module doesn ' t already exist , creates a weak module depending on every other module .
* < p > Does not move any sources into the weak module .
* @ return a new list of modules that includes the weak module , if it was newly created , or the
* same list if the weak module already existed
* @ throws IllegalStateException if a weak module already exists but doesn ' t fulfill the above
* conditions */
private List < JSModule > makeWeakModule ( List < JSModule > modulesInDepOrder ) { } } | boolean hasWeakModule = false ; for ( JSModule module : modulesInDepOrder ) { if ( module . getName ( ) . equals ( JSModule . WEAK_MODULE_NAME ) ) { hasWeakModule = true ; Set < JSModule > allOtherModules = new HashSet < > ( modulesInDepOrder ) ; allOtherModules . remove ( module ) ; checkState ( module . getAllDependencies ( ) . containsAll ( allOtherModules ) , "A weak module already exists but it does not depend on every other module." ) ; checkState ( module . getAllDependencies ( ) . size ( ) == allOtherModules . size ( ) , "The weak module cannot have extra dependencies." ) ; break ; } } if ( hasWeakModule ) { // All weak files ( and only weak files ) should be in the weak module .
for ( JSModule module : modulesInDepOrder ) { for ( CompilerInput input : module . getInputs ( ) ) { if ( module . getName ( ) . equals ( JSModule . WEAK_MODULE_NAME ) ) { checkState ( input . getSourceFile ( ) . isWeak ( ) , "A weak module already exists but strong sources were found in it." ) ; } else { checkState ( ! input . getSourceFile ( ) . isWeak ( ) , "A weak module already exists but weak sources were found in other modules." ) ; } } } } else { JSModule weakModule = new JSModule ( JSModule . WEAK_MODULE_NAME ) ; for ( JSModule module : modulesInDepOrder ) { weakModule . addDependency ( module ) ; } modulesInDepOrder = new ArrayList < > ( modulesInDepOrder ) ; modulesInDepOrder . add ( weakModule ) ; } return modulesInDepOrder ; |
public class TemplateSubPatternAssociation { /** * Return the mode associated with the template .
* @ param xctxt XPath context to use with this template
* @ param targetNode Target node
* @ param mode reference , which may be null , to the < a href = " http : / / www . w3 . org / TR / xslt # modes " > current mode < / a > .
* @ return The mode associated with the template .
* @ throws TransformerException */
public boolean matches ( XPathContext xctxt , int targetNode , QName mode ) throws TransformerException { } } | double score = m_stepPattern . getMatchScore ( xctxt , targetNode ) ; return ( XPath . MATCH_SCORE_NONE != score ) && matchModes ( mode , m_template . getMode ( ) ) ; |
public class LayerImpl { /** * / * ( non - Javadoc )
* @ see com . ibm . jaggr . service . layer . ILayer # getLastModified ( javax . servlet . http . HttpServletRequest ) */
@ SuppressWarnings ( "unchecked" ) @ Override public long getLastModified ( HttpServletRequest request ) throws IOException { } } | long lastModified = _lastModified ; IAggregator aggregator = ( IAggregator ) request . getAttribute ( IAggregator . AGGREGATOR_REQATTRNAME ) ; IOptions options = aggregator . getOptions ( ) ; // Don ' t check last modified dates of source files on every request in production mode
// for performance reasons . _ validateLastModified is a transient that gets initialize
// to true whenever this object is de - serialized ( i . e . on server startup ) .
if ( lastModified == - 1 || _validateLastModified . getAndSet ( false ) || options . isDevelopmentMode ( ) ) { // see if we already determined the last modified time for this request
Object obj = request . getAttribute ( LAST_MODIFIED_PROPNAME ) ; if ( obj == null ) { // Determine latest last - modified time from source files in moduleList
ModuleList moduleFiles = getModules ( request ) ; lastModified = getLastModified ( aggregator , moduleFiles ) ; // Get last - modified date of config file
lastModified = Math . max ( lastModified , aggregator . getConfig ( ) . lastModified ( ) ) ; List < String > cacheInfoReport = null ; if ( _isReportCacheInfo ) { cacheInfoReport = ( List < String > ) request . getAttribute ( LAYERCACHEINFO_PROPNAME ) ; } synchronized ( this ) { if ( _lastModified == - 1 ) { // Initialize value of instance property
_lastModified = lastModified ; if ( cacheInfoReport != null ) { cacheInfoReport . add ( "update_lastmod1" ) ; // $ NON - NLS - 1 $
} } } request . setAttribute ( LAST_MODIFIED_PROPNAME , lastModified ) ; if ( log . isLoggable ( Level . FINER ) ) { log . finer ( "Returning calculated last modified " // $ NON - NLS - 1 $
+ lastModified + " for layer " + // $ NON - NLS - 1 $
request . getAttribute ( IHttpTransport . REQUESTEDMODULENAMES_REQATTRNAME ) . toString ( ) ) ; } } else { lastModified = ( Long ) obj ; if ( log . isLoggable ( Level . FINER ) ) { log . finer ( "Returning last modified " // $ NON - NLS - 1 $
+ lastModified + " from request for layer " + // $ NON - NLS - 1 $
request . getAttribute ( IHttpTransport . REQUESTEDMODULENAMES_REQATTRNAME ) . toString ( ) ) ; } } } else { if ( log . isLoggable ( Level . FINER ) ) { log . finer ( "Returning cached last modified " // $ NON - NLS - 1 $
+ lastModified + " for layer " + // $ NON - NLS - 1 $
request . getAttribute ( IHttpTransport . REQUESTEDMODULENAMES_REQATTRNAME ) . toString ( ) ) ; } } return lastModified ; |
public class AbstractSecurityService { /** * Logout out the current page instance .
* @ param force If true , force logout without user interaction .
* @ param target Optional target url for next login .
* @ param message Optional message to indicate reason for logout . */
@ Override public void logout ( boolean force , String target , String message ) { } } | log . trace ( "Logging Out" ) ; IContextManager contextManager = ContextManager . getInstance ( ) ; if ( contextManager == null ) { logout ( target , message ) ; } else { contextManager . reset ( force , ( response ) -> { if ( force || ! response . rejected ( ) ) { logout ( target , message ) ; } } ) ; |
public class ZWaveController { /** * Handles the response of the SerialApiGetInitData request .
* @ param incomingMlivessage the response message to process . */
private void handleSerialApiGetInitDataResponse ( SerialMessage incomingMessage ) { } } | logger . debug ( String . format ( "Got MessageSerialApiGetInitData response." ) ) ; this . isConnected = true ; int nodeBytes = incomingMessage . getMessagePayloadByte ( 2 ) ; if ( nodeBytes != NODE_BYTES ) { logger . error ( "Invalid number of node bytes = {}" , nodeBytes ) ; return ; } int nodeId = 1 ; // loop bytes
for ( int i = 3 ; i < 3 + nodeBytes ; i ++ ) { int incomingByte = incomingMessage . getMessagePayloadByte ( i ) ; // loop bits in byte
for ( int j = 0 ; j < 8 ; j ++ ) { int b1 = incomingByte & ( int ) Math . pow ( 2.0D , j ) ; int b2 = ( int ) Math . pow ( 2.0D , j ) ; if ( b1 == b2 ) { logger . info ( String . format ( "Found node id = %d" , nodeId ) ) ; // Place nodes in the local ZWave Controller
this . zwaveNodes . put ( nodeId , new ZWaveNode ( this . homeId , nodeId , this ) ) ; this . getNode ( nodeId ) . advanceNodeStage ( ) ; } nodeId ++ ; } } logger . info ( "------------Number of Nodes Found Registered to ZWave Controller------------" ) ; logger . info ( String . format ( "# Nodes = %d" , this . zwaveNodes . size ( ) ) ) ; logger . info ( "----------------------------------------------------------------------------" ) ; // Advance node stage for the first node . |
public class BeansDescriptorImpl { /** * Returns all < code > scan < / code > elements
* @ return list of < code > scan < / code > */
public List < Scan < BeansDescriptor > > getAllScan ( ) { } } | List < Scan < BeansDescriptor > > list = new ArrayList < Scan < BeansDescriptor > > ( ) ; List < Node > nodeList = model . get ( "scan" ) ; for ( Node node : nodeList ) { Scan < BeansDescriptor > type = new ScanImpl < BeansDescriptor > ( this , "scan" , model , node ) ; list . add ( type ) ; } return list ; |
public class ViewPropertyAnimatorPreHC { /** * Utility function , called by animateProperty ( ) and animatePropertyBy ( ) , which handles the
* details of adding a pending animation and posting the request to start the animation .
* @ param constantName The specifier for the property being animated
* @ param startValue The starting value of the property
* @ param byValue The amount by which the property will change */
private void animatePropertyBy ( int constantName , float startValue , float byValue ) { } } | // First , cancel any existing animations on this property
if ( mAnimatorMap . size ( ) > 0 ) { Animator animatorToCancel = null ; Set < Animator > animatorSet = mAnimatorMap . keySet ( ) ; for ( Animator runningAnim : animatorSet ) { PropertyBundle bundle = mAnimatorMap . get ( runningAnim ) ; if ( bundle . cancel ( constantName ) ) { // property was canceled - cancel the animation if it ' s now empty
// Note that it ' s safe to break out here because every new animation
// on a property will cancel a previous animation on that property , so
// there can only ever be one such animation running .
if ( bundle . mPropertyMask == NONE ) { // the animation is no longer changing anything - cancel it
animatorToCancel = runningAnim ; break ; } } } if ( animatorToCancel != null ) { animatorToCancel . cancel ( ) ; } } NameValuesHolder nameValuePair = new NameValuesHolder ( constantName , startValue , byValue ) ; mPendingAnimations . add ( nameValuePair ) ; View v = mView . get ( ) ; if ( v != null ) { v . removeCallbacks ( mAnimationStarter ) ; v . post ( mAnimationStarter ) ; } |
public class LdapConnection { /** * Check the attributes cache for the attributes on the distinguished name .
* If any of the attributes are missing , a call to the LDAP server will be made to retrieve them .
* @ param name The distinguished name to look up the attributes in the cache for .
* @ param attrIds The attributes to retrieve .
* @ return The { @ link Attributes } .
* @ throws WIMException If a call to the LDAP server was necessary and failed . */
public Attributes checkAttributesCache ( String name , String [ ] attrIds ) throws WIMException { } } | final String METHODNAME = "checkAttributesCache" ; Attributes attributes = null ; // If attribute cache is available , look up cache first
if ( getAttributesCache ( ) != null ) { String key = toKey ( name ) ; Object cached = getAttributesCache ( ) . get ( key ) ; // Cache entry found
if ( cached != null && ( cached instanceof Attributes ) ) { List < String > missAttrIdList = new ArrayList < String > ( attrIds . length ) ; Attributes cachedAttrs = ( Attributes ) cached ; attributes = new BasicAttributes ( true ) ; for ( int i = 0 ; i < attrIds . length ; i ++ ) { Attribute attr = LdapHelper . getIngoreCaseAttribute ( cachedAttrs , attrIds [ i ] ) ; if ( attr != null ) { attributes . put ( attr ) ; } else { missAttrIdList . add ( attrIds [ i ] ) ; } } // If no missed attributes , nothing need to do .
// Otherwise , retrieve missed attributes and add back to cache
if ( missAttrIdList . size ( ) > 0 ) { String [ ] missAttrIds = missAttrIdList . toArray ( new String [ 0 ] ) ; if ( tc . isDebugEnabled ( ) ) { Tr . debug ( tc , METHODNAME + " Miss cache: " + key + " " + WIMTraceHelper . printObjectArray ( missAttrIds ) ) ; } Attributes missAttrs = getAttributes ( name , missAttrIds ) ; // Add missed attributes to attributes .
addAttributes ( missAttrs , attributes ) ; // Add missed attributes to cache .
updateAttributesCache ( key , missAttrs , cachedAttrs , missAttrIds ) ; } else { if ( tc . isDebugEnabled ( ) ) { Tr . debug ( tc , METHODNAME + " Hit cache: " + key ) ; } } } // No cache entry , call LDAP to retrieve all request attributes .
else { if ( tc . isDebugEnabled ( ) ) { Tr . debug ( tc , METHODNAME + " Miss cache: " + key ) ; } attributes = getAttributes ( name , attrIds ) ; // Add attributes to cache .
updateAttributesCache ( key , attributes , null , attrIds ) ; } } else { // Attribute cache is not available , directly call LDAP server
attributes = getAttributes ( name , attrIds ) ; } return attributes ; |
public class LoggerFactory { /** * 获取日志输出器
* @ param key 分类键
* @ return 日志输出器 , 后验条件 : 不返回null . */
public static Logger getLogger ( Class < ? > key ) { } } | FailsafeLogger logger = LOGGERS . get ( key . getName ( ) ) ; if ( logger == null ) { LOGGERS . putIfAbsent ( key . getName ( ) , new FailsafeLogger ( LOGGER_ADAPTER . getLogger ( key ) ) ) ; logger = LOGGERS . get ( key . getName ( ) ) ; } return logger ; |
public class CmsListItemWidget { /** * Sets the extra info text , and hides or displays the extra info label depending on whether
* the text is null or not null . < p >
* @ param text the text to put into the subtitle suffix */
public void setExtraInfo ( String text ) { } } | if ( text == null ) { if ( m_shortExtraInfoLabel . getParent ( ) != null ) { m_shortExtraInfoLabel . removeFromParent ( ) ; } } else { if ( m_shortExtraInfoLabel . getParent ( ) == null ) { m_titleBox . add ( m_shortExtraInfoLabel ) ; } m_shortExtraInfoLabel . setText ( text ) ; } updateTruncation ( ) ; |
public class CounterAspect { /** * Implementation for the @ Count pointcut .
* @ param pjp ProceedingJoinPoint .
* @ param aProducerId producerId from annotation .
* @ param aSubsystem subsystem configured by annotation -
* @ param aCategory category configured by annotation .
* @ return
* @ throws Throwable */
private Object count ( ProceedingJoinPoint pjp , String aProducerId , String aSubsystem , String aCategory ) throws Throwable { } } | return perform ( false , getMethodStatName ( pjp . getSignature ( ) ) , pjp , aProducerId , aCategory , aSubsystem ) ; |
public class Types { /** * Does t have a result that is a subtype of the result type of s ,
* suitable for covariant returns ? It is assumed that both types
* are ( possibly polymorphic ) method types . Monomorphic method
* types are handled in the obvious way . Polymorphic method types
* require renaming all type variables of one to corresponding
* type variables in the other , where correspondence is by
* position in the type parameter list . */
public boolean resultSubtype ( Type t , Type s , Warner warner ) { } } | List < Type > tvars = t . getTypeArguments ( ) ; List < Type > svars = s . getTypeArguments ( ) ; Type tres = t . getReturnType ( ) ; Type sres = subst ( s . getReturnType ( ) , svars , tvars ) ; return covariantReturnType ( tres , sres , warner ) ; |
public class Gram { /** * Performs ping operation on the gatekeeper with
* specified user credentials .
* Verifies if the user is authorized to submit a job
* to that gatekeeper .
* @ throws GramException if an error occurs or user in unauthorized
* @ param cred user credentials
* @ param resourceManagerContact resource manager contact */
public static void ping ( GSSCredential cred , String resourceManagerContact ) throws GramException , GSSException { } } | ResourceManagerContact rmc = new ResourceManagerContact ( resourceManagerContact ) ; Socket socket = gatekeeperConnect ( cred , rmc , false , false ) ; HttpResponse hd = null ; try { OutputStream out = socket . getOutputStream ( ) ; InputStream in = socket . getInputStream ( ) ; String msg = GRAMProtocol . PING ( rmc . getServiceName ( ) , rmc . getHostName ( ) ) ; // send message
out . write ( msg . getBytes ( ) ) ; out . flush ( ) ; debug ( "PG SENT:" , msg ) ; // receive reply
hd = new HttpResponse ( in ) ; } catch ( IOException e ) { throw new GramException ( GramException . ERROR_PROTOCOL_FAILED , e ) ; } finally { try { socket . close ( ) ; } catch ( Exception e ) { } } debug ( "PG RECEIVED:" , hd ) ; checkHttpReply ( hd . httpCode ) ; |
public class XCostExtension { /** * Assigns ( to the given event ) multiple cost types given their keys .
* Note that as a side effect this method
* creates attributes when it does not find an attribute with the proper
* key .
* @ see # assignAmounts ( XEvent , Map )
* @ param event
* Event to assign the cost types to .
* @ param types
* Mapping from keys to cost types which are to be assigned . */
public void assignTypes ( XEvent event , Map < List < String > , String > types ) { } } | XCostType . instance ( ) . assignNestedValues ( event , types ) ; |
public class HtmlRendererUtils { /** * Render an attribute taking into account the passed event ,
* the component property and the passed attribute value for the component
* property . The event will be rendered on the selected htmlAttrName .
* @ param facesContext
* @ param writer
* @ param componentProperty
* @ param component
* @ param eventName
* @ param clientBehaviors
* @ param htmlAttrName
* @ param attributeValue
* @ return
* @ throws IOException */
public static boolean renderBehaviorizedAttribute ( FacesContext facesContext , ResponseWriter writer , String componentProperty , UIComponent component , String eventName , Collection < ClientBehaviorContext . Parameter > eventParameters , Map < String , List < ClientBehavior > > clientBehaviors , String htmlAttrName , String attributeValue ) throws IOException { } } | return renderBehaviorizedAttribute ( facesContext , writer , componentProperty , component , component . getClientId ( facesContext ) , eventName , eventParameters , clientBehaviors , htmlAttrName , attributeValue ) ; |
public class QueryParameters { /** * Returns value by searching key assigned to that position
* @ param position Position which would be searched
* @ return Value
* @ throws NoSuchFieldException */
public Object getValueByPosition ( Integer position ) throws NoSuchFieldException { } } | String name = null ; Object value = null ; name = this . getNameByPosition ( position ) ; if ( name != null ) { value = this . getValue ( name ) ; } else { throw new NoSuchFieldException ( ) ; } return value ; |
public class HierarchicalTable { /** * Make the record represented by this DataRecord current .
* @ param dataRecord tour . db . DataRecord The datarecord to try to recreate .
* @ return true if successful . */
public boolean setDataRecord ( DataRecord dataRecord ) { } } | boolean success = super . setDataRecord ( dataRecord ) ; if ( this . getCurrentTable ( ) != this . getNextTable ( ) ) this . syncRecordToBase ( this . getRecord ( ) , this . getCurrentTable ( ) . getRecord ( ) , false ) ; return success ; |
public class ObjectFactory { /** * Create an instance of { @ link JAXBElement } { @ code < } { @ link MovingObjectStatusType } { @ code > }
* @ param value
* Java instance representing xml element ' s value .
* @ return
* the new instance of { @ link JAXBElement } { @ code < } { @ link MovingObjectStatusType } { @ code > } */
@ XmlElementDecl ( namespace = "http://www.opengis.net/gml" , name = "MovingObjectStatus" , substitutionHeadNamespace = "http://www.opengis.net/gml" , substitutionHeadName = "_TimeSlice" ) public JAXBElement < MovingObjectStatusType > createMovingObjectStatus ( MovingObjectStatusType value ) { } } | return new JAXBElement < MovingObjectStatusType > ( _MovingObjectStatus_QNAME , MovingObjectStatusType . class , null , value ) ; |
public class DOM2DTM { /** * Given a node handle , return its XPath - style localname .
* ( As defined in Namespaces , this is the portion of the name after any
* colon character ) .
* @ param nodeHandle the id of the node .
* @ return String Local name of this node . */
public String getLocalName ( int nodeHandle ) { } } | if ( JJK_NEWCODE ) { int id = makeNodeIdentity ( nodeHandle ) ; if ( NULL == id ) return null ; Node newnode = ( Node ) m_nodes . elementAt ( id ) ; String newname = newnode . getLocalName ( ) ; if ( null == newname ) { // XSLT treats PIs , and possibly other things , as having QNames .
String qname = newnode . getNodeName ( ) ; if ( '#' == qname . charAt ( 0 ) ) { // Match old default for this function
// This conversion may or may not be necessary
newname = "" ; } else { int index = qname . indexOf ( ':' ) ; newname = ( index < 0 ) ? qname : qname . substring ( index + 1 ) ; } } return newname ; } else { String name ; short type = getNodeType ( nodeHandle ) ; switch ( type ) { case DTM . ATTRIBUTE_NODE : case DTM . ELEMENT_NODE : case DTM . ENTITY_REFERENCE_NODE : case DTM . NAMESPACE_NODE : case DTM . PROCESSING_INSTRUCTION_NODE : { Node node = getNode ( nodeHandle ) ; // assume not null .
name = node . getLocalName ( ) ; if ( null == name ) { String qname = node . getNodeName ( ) ; int index = qname . indexOf ( ':' ) ; name = ( index < 0 ) ? qname : qname . substring ( index + 1 ) ; } } break ; default : name = "" ; } return name ; } |
public class SignerInfo { /** * Copied from com . sun . crypto . provider . OAEPParameters . */
private static String convertToStandardName ( String internalName ) { } } | if ( internalName . equals ( "SHA" ) ) { return "SHA-1" ; } else if ( internalName . equals ( "SHA224" ) ) { return "SHA-224" ; } else if ( internalName . equals ( "SHA256" ) ) { return "SHA-256" ; } else if ( internalName . equals ( "SHA384" ) ) { return "SHA-384" ; } else if ( internalName . equals ( "SHA512" ) ) { return "SHA-512" ; } else { return internalName ; } |
public class DataExportUtility { /** * Command line entry point .
* @ param argv command line arguments */
public static void main ( String [ ] argv ) { } } | if ( argv . length != 2 ) { System . out . println ( "DataExport <filename> <output directory>" ) ; } else { Connection connection = null ; try { Class . forName ( "sun.jdbc.odbc.JdbcOdbcDriver" ) ; String url = "jdbc:odbc:DRIVER=Microsoft Access Driver (*.mdb);DBQ=" + argv [ 0 ] ; connection = DriverManager . getConnection ( url ) ; DataExportUtility dx = new DataExportUtility ( ) ; dx . process ( connection , argv [ 1 ] ) ; } catch ( Exception ex ) { ex . printStackTrace ( ) ; } finally { if ( connection != null ) { try { connection . close ( ) ; } catch ( SQLException ex ) { // silently ignore exceptions when closing connection
} } } } |
public class JsonAttributeMappings { /** * Re - expands a flattened json representation from a collection of attributes back into a raw
* nested json string . */
public static String toJsonString ( Collection < Attribute > attributeCollection , ObjectMapper objectMapper ) throws JsonProcessingException { } } | return objectMapper . writeValueAsString ( toObject ( attributeCollection ) ) ; |
public class BatchCSVRecord { /** * Return a batch record based on a dataset
* @ param dataSet the dataset to get the batch record for
* @ return the batch record */
public static BatchCSVRecord fromDataSet ( DataSet dataSet ) { } } | BatchCSVRecord batchCSVRecord = new BatchCSVRecord ( ) ; for ( int i = 0 ; i < dataSet . numExamples ( ) ; i ++ ) { batchCSVRecord . add ( SingleCSVRecord . fromRow ( dataSet . get ( i ) ) ) ; } return batchCSVRecord ; |
public class EmailAddressValidator { /** * Checks if a value is a valid e - mail address . Depending on the global value
* for the MX record check the check is performed incl . the MX record check or
* without .
* @ param sEmail
* The value validation is being performed on . A < code > null < / code >
* value is considered invalid .
* @ return < code > true < / code > if the email address is valid , < code > false < / code >
* otherwise .
* @ see # isPerformMXRecordCheck ( )
* @ see # setPerformMXRecordCheck ( boolean ) */
public static boolean isValid ( @ Nullable final String sEmail ) { } } | return s_aPerformMXRecordCheck . get ( ) ? isValidWithMXCheck ( sEmail ) : EmailAddressHelper . isValid ( sEmail ) ; |
public class TargetStreamManager { /** * Handle a filtered message by inserting it in to the
* appropriate target stream as Silence .
* Since we only need to do this on exisiting TargetStreams , if the
* streamSet or stream are null we give up
* @ param msgItem
* @ throws SIResourceException */
public void handleSilence ( MessageItem msgItem ) throws SIResourceException { } } | if ( TraceComponent . isAnyTracingEnabled ( ) && tc . isEntryEnabled ( ) ) SibTr . entry ( this , tc , "handleSilence" , new Object [ ] { msgItem } ) ; JsMessage jsMsg = msgItem . getMessage ( ) ; int priority = jsMsg . getPriority ( ) . intValue ( ) ; Reliability reliability = jsMsg . getReliability ( ) ; StreamSet streamSet = getStreamSetForMessage ( jsMsg ) ; if ( streamSet != null ) { TargetStream targetStream = null ; synchronized ( streamSet ) { targetStream = ( TargetStream ) streamSet . getStream ( priority , reliability ) ; } if ( targetStream != null ) { // Update the stateStream with Silence
targetStream . writeSilence ( msgItem ) ; } } if ( TraceComponent . isAnyTracingEnabled ( ) && tc . isEntryEnabled ( ) ) SibTr . exit ( tc , "handleSilence" ) ; |
public class Configuration { /** * Set the value of the < code > name < / code > property to the name of a
* < code > theClass < / code > implementing the given interface < code > xface < / code > .
* An exception is thrown if < code > theClass < / code > does not implement the
* interface < code > xface < / code > .
* @ param name property name .
* @ param theClass property value .
* @ param xface the interface implemented by the named class . */
public void setClass ( String name , Class < ? > theClass , Class < ? > xface ) { } } | if ( ! xface . isAssignableFrom ( theClass ) ) throw new RuntimeException ( theClass + " does not implement " + xface . getName ( ) ) ; set ( name , theClass . getName ( ) ) ; |
public class BinaryFormatImplBenchmark { /** * This benchmark attempts to measure performance of { @ link BinaryFormat # fromBinaryValue ( byte [ ] ) } . */
@ Benchmark @ BenchmarkMode ( Mode . SampleTime ) @ OutputTimeUnit ( TimeUnit . NANOSECONDS ) public SpanContext fromBinarySpanContext ( Data data ) throws SpanContextParseException { } } | return data . binaryFormat . fromByteArray ( data . spanContextBinary ) ; |
public class VariableImpl { /** * outputs a empty Variable , only scope Example : pc . formScope ( ) ;
* @ param adapter
* @ throws TemplateException */
private Type _writeOutEmpty ( BytecodeContext bc ) throws TransformerException { } } | if ( ignoredFirstMember && ( scope == Scope . SCOPE_LOCAL || scope == Scope . SCOPE_VAR ) ) return Types . VOID ; GeneratorAdapter adapter = bc . getAdapter ( ) ; adapter . loadArg ( 0 ) ; Method m ; Type t = Types . PAGE_CONTEXT ; if ( scope == Scope . SCOPE_ARGUMENTS ) { getFactory ( ) . TRUE ( ) . writeOut ( bc , MODE_VALUE ) ; m = TypeScope . METHOD_ARGUMENT_BIND ; } else if ( scope == Scope . SCOPE_LOCAL ) { t = Types . PAGE_CONTEXT ; getFactory ( ) . TRUE ( ) . writeOut ( bc , MODE_VALUE ) ; m = TypeScope . METHOD_LOCAL_BIND ; } else if ( scope == Scope . SCOPE_VAR ) { t = Types . PAGE_CONTEXT ; getFactory ( ) . TRUE ( ) . writeOut ( bc , MODE_VALUE ) ; m = TypeScope . METHOD_VAR_BIND ; } else m = TypeScope . METHODS [ scope ] ; TypeScope . invokeScope ( adapter , m , t ) ; return m . getReturnType ( ) ; |
public class AnyValueMap { /** * Appends new elements to this map .
* @ param map a map with elements to be added . */
public void append ( Map < ? , ? > map ) { } } | if ( map == null || map . size ( ) == 0 ) return ; for ( Map . Entry < ? , ? > entry : map . entrySet ( ) ) { String key = StringConverter . toString ( entry . getKey ( ) ) ; Object value = entry . getValue ( ) ; super . put ( key , value ) ; } |
public class Any { /** * Optional string encoded content for non - binary media types . If this is filled
* in , then the & # 39 ; bin & # 39 ; field is not needed .
* @ return Optional of the < code > text < / code > field value . */
@ javax . annotation . Nonnull public java . util . Optional < String > optionalText ( ) { } } | return java . util . Optional . ofNullable ( mText ) ; |
public class XMLHelper { /** * Helper program : Extracts the specified XPATH expression
* from an XML - String .
* @ param node the node
* @ param xPath the x path
* @ return NodeList
* @ throws XPathExpressionException the x path expression exception */
public static Node getElementB ( Node node , XPathExpression xPath ) throws XPathExpressionException { } } | return getElementsB ( node , xPath ) . item ( 0 ) ; |
public class Queue { /** * Add a single data point to the queue
* If the queue is a bounded queue and is full , will return false
* @ param data Data to add
* @ return true if successfully added . */
public boolean add ( final T data ) { } } | try { final boolean result = queue . add ( ( T ) nullSafe ( data ) ) ; if ( result ) { if ( sizeSignal != null ) this . sizeSignal . set ( queue . size ( ) ) ; } return result ; } catch ( final IllegalStateException e ) { return false ; } |
public class SecStrucCalc { /** * Calculate HBond energy of two groups in cal / mol
* see Creighton page 147 f
* Jeffrey , George A . , An introduction to hydrogen bonding ,
* Oxford University Press , 1997.
* categorizes hbonds with donor - acceptor distances of
* 2.2-2.5 & aring ; as " strong , mostly covalent " ,
* 2.5-3.2 & aring ; as " moderate , mostly electrostatic " ,
* 3.2-4.0 & aring ; as " weak , electrostatic " .
* Energies are given as 40-14 , 15-4 , and < 4 kcal / mol respectively . */
private static double calculateHBondEnergy ( SecStrucGroup one , SecStrucGroup two ) { } } | Atom N = one . getN ( ) ; Atom H = one . getH ( ) ; Atom O = two . getO ( ) ; Atom C = two . getC ( ) ; double dno = Calc . getDistance ( O , N ) ; double dhc = Calc . getDistance ( C , H ) ; double dho = Calc . getDistance ( O , H ) ; double dnc = Calc . getDistance ( C , N ) ; logger . debug ( " cccc: {} {} {} {} O ({})..N ({}):{} | ho:{} - hc:{} + nc:{} - no:{}" , one . getResidueNumber ( ) , one . getPDBName ( ) , two . getResidueNumber ( ) , two . getPDBName ( ) , O . getPDBserial ( ) , N . getPDBserial ( ) , dno , dho , dhc , dnc , dno ) ; // there seems to be a contact !
if ( ( dno < MINDIST ) || ( dhc < MINDIST ) || ( dnc < MINDIST ) || ( dno < MINDIST ) ) { return HBONDLOWENERGY ; } double e1 = Q / dho - Q / dhc ; double e2 = Q / dnc - Q / dno ; double energy = e1 + e2 ; logger . debug ( " N ({}) O({}): {} : {} " , N . getPDBserial ( ) , O . getPDBserial ( ) , ( float ) dno , energy ) ; // Avoid too strong energy
if ( energy > HBONDLOWENERGY ) return energy ; return HBONDLOWENERGY ; |
public class TouchImageView { /** * When transitioning from zooming from focus to zoom from center ( or vice versa )
* the image can become unaligned within the view . This is apparent when zooming
* quickly . When the content size is less than the view size , the content will often
* be centered incorrectly within the view . fixScaleTrans first calls fixTrans ( ) and
* then makes sure the image is centered correctly within the view . */
private void fixScaleTrans ( ) { } } | fixTrans ( ) ; matrix . getValues ( m ) ; if ( getImageWidth ( ) < viewWidth ) { m [ Matrix . MTRANS_X ] = ( viewWidth - getImageWidth ( ) ) / 2 ; } if ( getImageHeight ( ) < viewHeight ) { m [ Matrix . MTRANS_Y ] = ( viewHeight - getImageHeight ( ) ) / 2 ; } matrix . setValues ( m ) ; |
public class AIStream { /** * A ControlRequestAck message tells the RME to slow down its get repetition timeout since we now know that the
* DME has received the request . */
public void processRequestAck ( long tick , long dmeVersion ) { } } | if ( TraceComponent . isAnyTracingEnabled ( ) && tc . isEntryEnabled ( ) ) SibTr . entry ( tc , "processRequestAck" , new Object [ ] { Long . valueOf ( tick ) , Long . valueOf ( dmeVersion ) } ) ; // Only consider non - stale request acks
if ( dmeVersion >= _latestDMEVersion ) { _targetStream . setCursor ( tick ) ; TickRange tickRange = _targetStream . getNext ( ) ; // Make sure that we still have a Q / G
if ( tickRange . type == TickRange . Requested ) { AIRequestedTick airt = ( AIRequestedTick ) tickRange . value ; // serialize with get repetition and request timeouts
synchronized ( airt ) { // Set the request timer to slow , but only if it is not already slowed
if ( ! airt . isSlowed ( ) ) { _eagerGetTOM . removeTimeoutEntry ( airt ) ; airt . setSlowed ( true ) ; airt . setAckingDMEVersion ( dmeVersion ) ; long to = airt . getTimeout ( ) ; if ( to > 0 || to == _mp . getCustomProperties ( ) . get_infinite_timeout ( ) ) { _slowedGetTOM . addTimeoutEntry ( airt ) ; } } } } else { // This can happen if the request ack got in too late and the Q / G was timed out and rejected
} } if ( TraceComponent . isAnyTracingEnabled ( ) && tc . isEntryEnabled ( ) ) SibTr . exit ( tc , "processRequestAck" ) ; |
public class IPSettings { /** * returns the cumulative settings for a given address
* @ param addr
* @ return */
public Map getSettings ( String addr ) { } } | try { return this . getSettings ( InetAddress . getByName ( addr ) ) ; } catch ( Throwable t ) { ExceptionUtil . rethrowIfNecessary ( t ) ; } return EMPTY ; |
public class HiveSource { /** * Convert createTime from seconds to milliseconds */
protected static long getCreateTime ( Table table ) { } } | return TimeUnit . MILLISECONDS . convert ( table . getTTable ( ) . getCreateTime ( ) , TimeUnit . SECONDS ) ; |
public class LogImpl { /** * / * ( non - Javadoc )
* @ see org . apache . commons . logging . Log # fatal ( java . lang . Object , java . lang . Throwable ) */
public void fatal ( Object arg0 , Throwable arg1 ) { } } | message ( FAIL , new Object [ ] { arg0 , arg1 } , new Frame ( 1 ) ) ; |
public class LocalDateIMMDateCalculator { private LocalDate calculateIMMMonth ( final boolean requestNextIMM , final LocalDate startDate , final int month ) { } } | int monthOffset ; LocalDate date = startDate ; switch ( month ) { case MARCH : case JUNE : case SEPTEMBER : case DECEMBER : final LocalDate immDate = calculate3rdWednesday ( date ) ; if ( requestNextIMM && ! date . isBefore ( immDate ) ) { date = date . plusMonths ( MONTHS_IN_QUARTER ) ; } else if ( ! requestNextIMM && ! date . isAfter ( immDate ) ) { date = date . minusMonths ( MONTHS_IN_QUARTER ) ; } break ; default : if ( requestNextIMM ) { monthOffset = ( MONTH_IN_YEAR - month ) % MONTHS_IN_QUARTER ; date = date . plusMonths ( monthOffset ) ; } else { monthOffset = month % MONTHS_IN_QUARTER ; date = date . minusMonths ( monthOffset ) ; } break ; } return date ; |
public class HystrixMetricsPublisherFactory { /** * / * package */
HystrixMetricsPublisherThreadPool getPublisherForThreadPool ( HystrixThreadPoolKey threadPoolKey , HystrixThreadPoolMetrics metrics , HystrixThreadPoolProperties properties ) { } } | // attempt to retrieve from cache first
HystrixMetricsPublisherThreadPool publisher = threadPoolPublishers . get ( threadPoolKey . name ( ) ) ; if ( publisher != null ) { return publisher ; } // it doesn ' t exist so we need to create it
publisher = HystrixPlugins . getInstance ( ) . getMetricsPublisher ( ) . getMetricsPublisherForThreadPool ( threadPoolKey , metrics , properties ) ; // attempt to store it ( race other threads )
HystrixMetricsPublisherThreadPool existing = threadPoolPublishers . putIfAbsent ( threadPoolKey . name ( ) , publisher ) ; if ( existing == null ) { // we won the thread - race to store the instance we created so initialize it
publisher . initialize ( ) ; // done registering , return instance that got cached
return publisher ; } else { // we lost so return ' existing ' and let the one we created be garbage collected
// without calling initialize ( ) on it
return existing ; } |
public class TransformMojo { /** * Called by Maven to run the plugin . */
public void execute ( ) throws MojoExecutionException , MojoFailureException { } } | if ( isSkipping ( ) ) { getLog ( ) . debug ( "Skipping execution, as demanded by user." ) ; return ; } if ( transformationSets == null || transformationSets . length == 0 ) { throw new MojoFailureException ( "No TransformationSets configured." ) ; } checkCatalogHandling ( ) ; Object oldProxySettings = activateProxy ( ) ; try { Resolver resolver = getResolver ( ) ; for ( int i = 0 ; i < transformationSets . length ; i ++ ) { TransformationSet transformationSet = transformationSets [ i ] ; resolver . setXincludeAware ( transformationSet . isXincludeAware ( ) ) ; resolver . setValidating ( transformationSet . isValidating ( ) ) ; transform ( resolver , transformationSet ) ; } } finally { passivateProxy ( oldProxySettings ) ; } |
public class JspFactory { /** * Returns the default factory for this implementation .
* @ return the default factory for this implementation */
public static synchronized JspFactory getDefaultFactory ( ) { } } | if ( deflt == null ) { try { Class factory = Class . forName ( "org.apache.jasper.runtime.JspFactoryImpl" ) ; if ( factory != null ) { deflt = ( JspFactory ) factory . newInstance ( ) ; } } catch ( Exception ex ) { } } return deflt ; |
public class GeoServiceBounds { /** * Build a bounding box feature .
* In this case , it has a name but is empty .
* @ param id the ID string
* @ return the Feature for the new bounds */
public static Feature createBounds ( final String id ) { } } | final Feature feature = new Feature ( ) ; feature . setId ( id ) ; feature . setGeometry ( new Polygon ( ) ) ; return feature ; |
public class BridgeHeadTypeRegistry { /** * Registers the given bridge factory and its bridge head types .
* @ param bridgeFactory The bridge factory to register */
public void register ( BridgeFactory bridgeFactory ) { } } | Class < ? > nearType = bridgeFactory . getNearType ( ) ; Class < ? > farType = bridgeFactory . getFarType ( ) ; logger . trace ( display ( nearType ) + ": " + display ( farType ) ) ; nearToFarType . put ( nearType , farType ) ; farToNearType . put ( farType , nearType ) ; nearTypeToFactory . put ( nearType , bridgeFactory ) ; farTypeToFactory . put ( farType , bridgeFactory ) ; if ( accessors . containsKey ( nearType ) ) { for ( FactoryAccessor < ? > accessor : accessors . get ( nearType ) ) { injectInto ( accessor ) ; } accessors . remove ( nearType ) ; } |
public class GeoPackageManager { /** * Open a GeoPackage
* @ param name
* GeoPackage name
* @ param file
* GeoPackage file
* @ return GeoPackage
* @ since 3.0.2 */
public static GeoPackage open ( String name , File file ) { } } | // Validate or add the file extension
if ( GeoPackageIOUtils . hasFileExtension ( file ) ) { GeoPackageValidate . validateGeoPackageExtension ( file ) ; } else { file = GeoPackageIOUtils . addFileExtension ( file , GeoPackageConstants . GEOPACKAGE_EXTENSION ) ; } // Create the GeoPackage Connection and table creator
GeoPackageConnection connection = connect ( file ) ; GeoPackageTableCreator tableCreator = new GeoPackageTableCreator ( connection ) ; // Create a GeoPackage
GeoPackage geoPackage = new GeoPackageImpl ( name , file , connection , tableCreator ) ; // Validate the GeoPackage has the minimum required tables
try { GeoPackageValidate . validateMinimumTables ( geoPackage ) ; } catch ( RuntimeException e ) { geoPackage . close ( ) ; throw e ; } return geoPackage ; |
public class FieldAccess { /** * called in ' in ' access */
@ Override public void setData ( FieldContent data ) { } } | // allow setting in field once only .
// cannot have multiple sources for one @ In !
if ( this . data != null ) { throw new ComponentException ( "Attempt to set @In field twice: " + comp + "." + field . getName ( ) ) ; } this . data = data ; |
public class KeyManager { /** * Returns the decrypted Data Protection Key ( DPK ) from the { @ link SharedPreferences } .
* @ param password Password used to decrypt the DPK
* @ return The DPK */
public EncryptionKey loadKeyUsingPassword ( String password ) { } } | if ( password == null || password . equals ( "" ) ) { throw new IllegalArgumentException ( "password is required to be a non-null/non-empty " + "string" ) ; } KeyData data = this . storage . getEncryptionKeyData ( ) ; if ( data == null || ! validateEncryptionKeyData ( data ) ) { return null ; } EncryptionKey dpk = null ; SecretKey aesKey = null ; try { aesKey = pbkdf2DerivedKeyForPassword ( password , data . getSalt ( ) , data . iterations , ENCRYPTION_KEYCHAIN_AES_KEY_SIZE ) ; byte [ ] dpkBytes = DPKEncryptionUtil . decryptAES ( aesKey , data . getIv ( ) , data . getEncryptedDPK ( ) ) ; dpk = new EncryptionKey ( dpkBytes ) ; } catch ( NoSuchAlgorithmException e ) { throw new DPKException ( "Failed to decrypt DPK" , e ) ; } catch ( InvalidKeySpecException e ) { throw new DPKException ( "Failed to decrypt DPK" , e ) ; } catch ( IllegalBlockSizeException e ) { throw new DPKException ( "Failed to decrypt DPK" , e ) ; } catch ( InvalidKeyException e ) { throw new DPKException ( "Failed to decrypt DPK" , e ) ; } catch ( BadPaddingException e ) { throw new DPKException ( "Failed to decrypt DPK" , e ) ; } catch ( InvalidAlgorithmParameterException e ) { throw new DPKException ( "Failed to decrypt DPK" , e ) ; } catch ( NoSuchPaddingException e ) { throw new DPKException ( "Failed to decrypt DPK" , e ) ; } return dpk ; |
public class WrapSeekable { /** * A helper for the common use case . */
public static WrapSeekable < FSDataInputStream > openPath ( FileSystem fs , Path p ) throws IOException { } } | return new WrapSeekable < FSDataInputStream > ( fs . open ( p ) , fs . getFileStatus ( p ) . getLen ( ) , p ) ; |
public class FileSystemState { /** * Registers the given resource to be closed when the file system is closed . Should be called when
* the resource is opened . */
public < C extends Closeable > C register ( C resource ) { } } | // Initial open check to avoid incrementing registering if we already know it ' s closed .
// This is to prevent any possibility of a weird pathalogical situation where the do / while
// loop in close ( ) keeps looping as register ( ) is called repeatedly from multiple threads .
checkOpen ( ) ; registering . incrementAndGet ( ) ; try { // Need to check again after marking registration in progress to avoid a potential race .
// ( close ( ) could have run completely between the first checkOpen ( ) and
// registering . incrementAndGet ( ) . )
checkOpen ( ) ; resources . add ( resource ) ; return resource ; } finally { registering . decrementAndGet ( ) ; } |
public class SRTServletRequest { /** * Begin 256836 */
public void removeQSFromList ( ) { } } | // 321485
if ( TraceComponent . isAnyTracingEnabled ( ) && logger . isLoggable ( Level . FINE ) ) { // 306998.15
logger . logp ( Level . FINE , CLASS_NAME , "removeQSFromList" , "entry" ) ; } if ( WCCustomProperties . CHECK_REQUEST_OBJECT_IN_USE ) { checkRequestObjectInUse ( ) ; } SRTServletRequestThreadData reqData = SRTServletRequestThreadData . getInstance ( ) ; LinkedList queryStringList = reqData . getQueryStringList ( ) ; if ( queryStringList != null && ! queryStringList . isEmpty ( ) ) { Map _tmpParameters = reqData . getParameters ( ) ; // Save off reference to current parameters
popParameterStack ( ) ; if ( reqData . getParameters ( ) == null && _tmpParameters != null ) // Parameters above current inluce / forward were never parsed
{ reqData . setParameters ( _tmpParameters ) ; Hashtable tmpQueryParams = ( ( QSListItem ) queryStringList . getLast ( ) ) . _qsHashtable ; if ( tmpQueryParams == null ) { tmpQueryParams = RequestUtils . parseQueryString ( ( ( QSListItem ) queryStringList . getLast ( ) ) . _qs , getReaderEncoding ( true ) ) ; } removeQueryParams ( tmpQueryParams ) ; } queryStringList . removeLast ( ) ; } else { // We need to pop parameter stack regardless of whether queryStringList is null
// because the queryString parameters could have been added directly to parameter list without
// adding ot the queryStringList
popParameterStack ( ) ; } |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.