signature stringlengths 43 39.1k | implementation stringlengths 0 450k |
|---|---|
public class Observation { /** * Returns the number of occurrences of the given value .
* @ param value The value for which the number of occurrences is desired
* @ return The number of occurrences of the given value
* @ throws IllegalArgumentException if there are no occurrences of < code > value < / code > */
public Integer getOccurrencesOf ( Double value ) { } } | if ( ! insertStat . containsKey ( value ) ) throw new IllegalArgumentException ( "No occurrences of value \"" + value + "\"" ) ; return insertStat . get ( value ) ; |
public class ListJobsByPipelineRequestMarshaller { /** * Marshall the given parameter object . */
public void marshall ( ListJobsByPipelineRequest listJobsByPipelineRequest , ProtocolMarshaller protocolMarshaller ) { } } | if ( listJobsByPipelineRequest == null ) { throw new SdkClientException ( "Invalid argument passed to marshall(...)" ) ; } try { protocolMarshaller . marshall ( listJobsByPipelineRequest . getPipelineId ( ) , PIPELINEID_BINDING ) ; protocolMarshaller . marshall ( listJobsByPipelineRequest . getAscending ( ) , ASCENDING_BINDING ) ; protocolMarshaller . marshall ( listJobsByPipelineRequest . getPageToken ( ) , PAGETOKEN_BINDING ) ; } catch ( Exception e ) { throw new SdkClientException ( "Unable to marshall request to JSON: " + e . getMessage ( ) , e ) ; } |
public class MariaDbStatement { /** * Releases this < code > Statement < / code > object ' s database and JDBC resources immediately instead
* of waiting for this to happen when it is automatically closed . It is generally good practice to
* release resources as soon as you are finished with them to avoid tying up database resources .
* Calling the method < code > close < / code > on a < code > Statement < / code > object that is already closed
* has no effect . < B > Note : < / B > When a
* < code > Statement < / code > object is closed , its current < code > ResultSet < / code > object , if one
* exists , is also closed .
* @ throws SQLException if a database access error occurs */
public void close ( ) throws SQLException { } } | lock . lock ( ) ; try { closed = true ; if ( results != null ) { if ( results . getFetchSize ( ) != 0 ) { skipMoreResults ( ) ; } results . close ( ) ; } protocol = null ; if ( connection == null || connection . pooledConnection == null || connection . pooledConnection . noStmtEventListeners ( ) ) { return ; } connection . pooledConnection . fireStatementClosed ( this ) ; } finally { lock . unlock ( ) ; } |
public class Ifc4PackageImpl { /** * < ! - - begin - user - doc - - >
* < ! - - end - user - doc - - >
* @ generated */
@ Override public EClass getIfcCondenserType ( ) { } } | if ( ifcCondenserTypeEClass == null ) { ifcCondenserTypeEClass = ( EClass ) EPackage . Registry . INSTANCE . getEPackage ( Ifc4Package . eNS_URI ) . getEClassifiers ( ) . get ( 118 ) ; } return ifcCondenserTypeEClass ; |
public class ProtoClient { /** * TODO : Document this somewhere proper . */
private byte [ ] encode ( Message msg , String apiVersion , String kind ) { } } | // It is unfortunate that we have to include apiVersion and kind ,
// since we should be able to extract it from the Message , but
// for now at least , those fields are missing from the proto - buffer .
Unknown u = Unknown . newBuilder ( ) . setTypeMeta ( TypeMeta . newBuilder ( ) . setApiVersion ( apiVersion ) . setKind ( kind ) ) . setRaw ( msg . toByteString ( ) ) . build ( ) ; return Bytes . concat ( MAGIC , u . toByteArray ( ) ) ; |
public class RemoteAdministrationThread { /** * Ask the thread to stop */
public void pleaseStop ( ) { } } | if ( stopRequired ) return ; stopRequired = true ; try { if ( receiver != null ) receiver . close ( ) ; } catch ( JMSException e ) { ErrorTools . log ( e , log ) ; } |
public class DefaultPlaceholderId { /** * Creates a new dynamic id based on the factories associated with this id
* and whatever additions are made by the specified consumer .
* @ param consumer
* lambda that can update the sorter with additional tag factories
* @ return
* the newly created id */
private DefaultPlaceholderId createNewId ( Consumer < FactorySorterAndDeduplicator > consumer ) { } } | FactorySorterAndDeduplicator sorter = new FactorySorterAndDeduplicator ( tagFactories ) ; consumer . accept ( sorter ) ; return new DefaultPlaceholderId ( name , sorter . asCollection ( ) , registry ) ; |
public class ArrayUtil { /** * sum of all values of a array , only work when all values are numeric
* @ param array Array
* @ return sum of all values
* @ throws ExpressionException */
public static double sum ( Array array ) throws ExpressionException { } } | if ( array . getDimension ( ) > 1 ) throw new ExpressionException ( "can only get sum/avg from 1 dimensional arrays" ) ; double rtn = 0 ; int len = array . size ( ) ; // try {
for ( int i = 1 ; i <= len ; i ++ ) { rtn += _toDoubleValue ( array , i ) ; } /* * } catch ( PageException e ) { throw new
* ExpressionException ( " exception while execute array operation : " + e . getMessage ( ) ) ; } */
return rtn ; |
public class MultiChoiceListPreference { /** * Sets the current values of the preference . By setting values , they will be persisted .
* @ param values
* A set , which contains the values , which should be set , as an instance of the type
* { @ link Set } */
public final void setValues ( @ Nullable final Set < String > values ) { } } | if ( values != null && ! values . equals ( this . values ) ) { this . values = values ; persistSet ( this . values ) ; notifyChanged ( ) ; } |
public class ParameterUtil { /** * Fetches the supplied parameter from the request . If the parameter does not exist ,
* < code > defval < / code > is returned . */
public static String getParameter ( HttpServletRequest req , String name , String defval ) { } } | String value = req . getParameter ( name ) ; return StringUtil . isBlank ( value ) ? defval : value . trim ( ) ; |
public class DirectoryScanner { /** * Add a pattern to the default excludes unless it is already a
* default exclude .
* @ param s A string to add as an exclude pattern .
* @ return < code > true < / code > if the string was added ;
* < code > false < / code > if it already existed .
* @ since Ant 1.6 */
public static boolean addDefaultExclude ( String s ) { } } | if ( defaultExcludes . indexOf ( s ) == - 1 ) { defaultExcludes . add ( s ) ; return true ; } return false ; |
public class ServerContentHelper { /** * Builds a list of server content and publishes a service to let the launcher obtain them . .
* < em > ONLY < / em > takes effect if the Launcher has set the magic server content property */
void processServerContentRequest ( ) { } } | File installRoot = new File ( locationService . resolveString ( "${wlp.install.dir}" ) ) ; final Set < String > absPathsForLibertyContent = new HashSet < String > ( ) ; final Map < String , List < String > > specificPlatformPathsByPlatform = new HashMap < String , List < String > > ( ) ; Set < String > discoveredFeatures = new HashSet < String > ( ) ; Collection < FeatureResource > fixes = new ArrayList < FeatureResource > ( ) ; // We need ALL Kernel features ( even the ones that aren ' t active in the system )
// as well as all installed features .
List < ProvisioningFeatureDefinition > allFeatureDefs = new ArrayList < ProvisioningFeatureDefinition > ( ) ; allFeatureDefs . addAll ( KernelFeatureDefinitionImpl . getAllKernelFeatures ( bundleContext , locationService ) ) ; allFeatureDefs . addAll ( featureResolver . getInstalledFeatureDefinitions ( ) ) ; // keep a list of product extensions being used in the server
List < String > extensionRepos = new ArrayList < String > ( ) ; for ( ProvisioningFeatureDefinition fd : allFeatureDefs ) { BundleRepositoryHolder brh = BundleRepositoryRegistry . getRepositoryHolder ( fd . getBundleRepositoryType ( ) ) ; ContentBasedLocalBundleRepository br = brh . getBundleRepository ( ) ; Collection < FeatureResource > frs = fd . getConstituents ( null ) ; /* * lib / fixes processing needs to happen here , to filter the xml down to just the current in use set .
* made slightly more complex , because the locations tracked for minify are absolute , so we have to identify and trim installroot
* to identify lib / fixes / * content , which we process afterward */
File libFixes = new File ( installRoot , "lib/fixes" ) ; for ( FeatureResource fr : frs ) { switch ( fr . getType ( ) ) { case FEATURE_TYPE : { // type = feature , no paths to worry about , we are processing the list of all installed features
// which will include nested features .
discoveredFeatures . add ( fr . getSymbolicName ( ) ) ; break ; } case BUNDLE_TYPE : case JAR_TYPE : case BOOT_JAR_TYPE : { // type = bundle , need to query the bundle repository for this feature def , to find which
// files are being used .
// type = jar , basically same as type = bundle . . for minify purposes .
// type = boot . jar , basically same as type = bundle . . for minify purposes .
File b = br . selectBundle ( fr . getLocation ( ) , fr . getSymbolicName ( ) , fr . getVersionRange ( ) ) ; File bb = br . selectBaseBundle ( fr . getLocation ( ) , fr . getSymbolicName ( ) , fr . getVersionRange ( ) ) ; // b & bb will be the same bundle if the base was the selected . .
if ( b != null && bb != null ) { boolean pathsSame = b . getAbsolutePath ( ) . equals ( bb . getAbsolutePath ( ) ) ; absPathsForLibertyContent . add ( b . getAbsolutePath ( ) ) ; if ( ! pathsSame ) { absPathsForLibertyContent . add ( bb . getAbsolutePath ( ) ) ; } List < String > osList = fr . getOsList ( ) ; if ( osList != null ) { for ( String os : osList ) { List < String > pathsForOs = specificPlatformPathsByPlatform . get ( os ) ; if ( pathsForOs == null ) { pathsForOs = new ArrayList < String > ( ) ; specificPlatformPathsByPlatform . put ( os , pathsForOs ) ; } pathsForOs . add ( b . getAbsolutePath ( ) ) ; if ( ! pathsSame ) { pathsForOs . add ( bb . getAbsolutePath ( ) ) ; } } } } else { // b & bb were null , we have no match for this resource . .
// maybe the resource was minfiied out ?
List < String > osList = fr . getOsList ( ) ; if ( osList != null ) { // ignore the missing resource , as the file is tagged for specific os ' s ,
// and will be reported missing based on the os filters later .
// ( if the user has no os filter set , they meant ' all currently supported by the install ' )
// ( so this can still be ignored ) .
} else { // use match string for error message , it provides best chance for being helpful .
Tr . warning ( tc , "ERROR_MISSING_FEATURE_RESOURCE" , new Object [ ] { fd . getFeatureName ( ) , fr . getMatchString ( ) } ) ; } } break ; } case FILE_TYPE : { // file uses loc as a relative path from install root .
String locString = fr . getLocation ( ) ; if ( locString != null ) { String [ ] locs ; if ( locString . contains ( "," ) ) { locs = locString . split ( "," ) ; } else { locs = new String [ ] { locString } ; } for ( String loc : locs ) { File test = new File ( loc ) ; if ( ! test . isAbsolute ( ) ) { test = new File ( brh . getInstallDir ( ) , loc ) ; } loc = test . getAbsolutePath ( ) ; // filter fixes content into the fixes set , all other content is remembered .
if ( loc . startsWith ( libFixes . getAbsolutePath ( ) + File . separator ) ) { fixes . add ( fr ) ; } else { absPathsForLibertyContent . add ( loc ) ; } List < String > osList = fr . getOsList ( ) ; if ( osList != null ) { for ( String os : osList ) { List < String > pathsForOs = specificPlatformPathsByPlatform . get ( os ) ; if ( pathsForOs == null ) { pathsForOs = new ArrayList < String > ( ) ; specificPlatformPathsByPlatform . put ( os , pathsForOs ) ; } pathsForOs . add ( loc ) ; } } } } else { // a file type without a loc is bad , means misuse of the type .
Tr . warning ( tc , "ERROR_UNKNOWN_FEATURE_RESOURCE_TYPE" , new Object [ ] { fd . getFeatureName ( ) , fr . getSymbolicName ( ) , "file" } ) ; } break ; } case UNKNOWN : { // if its not jar , bundle , feature , or file . . then something is wrong .
Tr . warning ( tc , "ERROR_UNKNOWN_FEATURE_RESOURCE_TYPE" , new Object [ ] { fd . getFeatureName ( ) , fr . getSymbolicName ( ) , fr . getRawType ( ) } ) ; // we assume that other types will use the location field as something useful .
String loc = fr . getLocation ( ) ; if ( loc != null ) { File test = new File ( loc ) ; if ( ! test . isAbsolute ( ) ) { test = new File ( installRoot , loc ) ; } absPathsForLibertyContent . add ( test . getAbsolutePath ( ) ) ; List < String > osList = fr . getOsList ( ) ; if ( osList != null ) { for ( String os : osList ) { List < String > pathsForOs = specificPlatformPathsByPlatform . get ( os ) ; if ( pathsForOs == null ) { pathsForOs = new ArrayList < String > ( ) ; specificPlatformPathsByPlatform . put ( os , pathsForOs ) ; } pathsForOs . add ( test . getAbsolutePath ( ) ) ; } } } break ; } default : break ; } } // add in ( all ) the NLS files for this featuredef . . if any . .
for ( File nls : fd . getLocalizationFiles ( ) ) { if ( nls . exists ( ) ) { absPathsForLibertyContent . add ( nls . getAbsolutePath ( ) ) ; } } // add in the manifest for the feature itself . .
File featureFile = fd . getFeatureDefinitionFile ( ) ; if ( featureFile != null ) { absPathsForLibertyContent . add ( featureFile . getAbsolutePath ( ) ) ; } File checksumFile = fd . getFeatureChecksumFile ( ) ; if ( checksumFile != null ) { absPathsForLibertyContent . add ( checksumFile . getAbsolutePath ( ) ) ; } String repoType = fd . getBundleRepositoryType ( ) ; // work out if this content is a product extension and if it is include its properties file
if ( repoType != null && ! ExtensionConstants . CORE_EXTENSION . equals ( repoType ) && ! ExtensionConstants . USER_EXTENSION . equals ( repoType ) ) { // not core or user , must be a product extension
extensionRepos . add ( repoType ) ; } // Add in any Icon files
File featureDefinitionFile = fd . getFeatureDefinitionFile ( ) ; if ( featureDefinitionFile != null ) { File featureDefinitionParent = featureDefinitionFile . getParentFile ( ) ; Collection < String > expectedIcons = fd . getIcons ( ) ; if ( featureDefinitionParent != null && expectedIcons != null ) { File iconsFolder = new File ( featureDefinitionParent , "icons/" + fd . getSymbolicName ( ) ) ; scanFolderForIcons ( absPathsForLibertyContent , iconsFolder . getAbsolutePath ( ) , iconsFolder , expectedIcons ) ; } } } // if there are any extensions in use we need to bring their wlp / etc / extensions / * . properties file along
for ( String extensionRepo : extensionRepos ) { WsResource extensionProperties = locationService . getRuntimeResource ( "etc/extensions/" + extensionRepo + ".properties" ) ; absPathsForLibertyContent . add ( locationService . resolveResource ( extensionProperties . toRepositoryPath ( ) ) . asFile ( ) . getAbsolutePath ( ) ) ; } // this odd looking bit of code will take the current list of files identified ,
// and if any are jars , will look in them to see if they have manifest classpaths
// if so , the jars referenced by the manifest classpaths are added to the manifestJars
// argument .
// We have to start by passing both args as the current set of content ( but using different set instances ) .
Set < String > manifestJars = new HashSet < String > ( ) ; manifestJars . addAll ( absPathsForLibertyContent ) ; gatherManifestClasspathJars ( absPathsForLibertyContent , manifestJars ) ; manifestJars . removeAll ( absPathsForLibertyContent ) ; // now manifestJars contains any jars that we didn ' t already know about , discovered via manifests .
absPathsForLibertyContent . addAll ( manifestJars ) ; // process the fixes set of fix xml ' s , and add the required ones to the set of files to keep .
addRequiredFixFiles ( installRoot , absPathsForLibertyContent , fixes ) ; final String OS_REMOVE_CHAR = "-" ; // publish the service that will be used by the launcher to read back the data .
final Dictionary < String , Object > d = new Hashtable < String , Object > ( ) ; final String [ ] pathArray = absPathsForLibertyContent . toArray ( new String [ ] { } ) ; bundleContext . registerService ( ServerContent . class , new ServerContent ( ) { @ Override public String [ ] getServerContentPaths ( String osRequest ) throws IOException { if ( osRequest == null || osRequest . isEmpty ( ) || "all" . equals ( osRequest ) ) return pathArray ; else { // filter paths as required . . then return them . .
String [ ] osNames = osRequest . split ( "," ) ; boolean add = true ; // check if this is an add , or a remove .
// if both are specified , remove wins ; p
for ( String osName : osNames ) { if ( osName . startsWith ( OS_REMOVE_CHAR ) ) { add = false ; } } if ( add ) { // someone has named an os ( or os ' s ) they want
// so we remove everything , and add back just those os ' s .
for ( Map . Entry < String , List < String > > me : specificPlatformPathsByPlatform . entrySet ( ) ) { absPathsForLibertyContent . removeAll ( me . getValue ( ) ) ; } for ( String osName : osNames ) { if ( ! osName . startsWith ( OS_REMOVE_CHAR ) ) { List < String > osPaths = specificPlatformPathsByPlatform . get ( osName ) ; if ( osPaths != null && ! osPaths . isEmpty ( ) ) { absPathsForLibertyContent . addAll ( osPaths ) ; // verify the requested paths File . exists . . otherwise
// this could be an error ?
for ( String osPath : osPaths ) { if ( ! FileUtils . fileExists ( new File ( osPath ) ) ) { throw new FileNotFoundException ( osPath ) ; } } } } } } else { // user request ' all except this platform ' type filter . .
for ( String osName : osNames ) { if ( osName . startsWith ( OS_REMOVE_CHAR ) ) { osName = osName . substring ( 1 ) ; List < String > osPaths = specificPlatformPathsByPlatform . get ( osName ) ; if ( osPaths != null && ! osPaths . isEmpty ( ) ) { absPathsForLibertyContent . removeAll ( osPaths ) ; // in this kind of filter , we don ' t need to test at all .
} } else { List < String > osPaths = specificPlatformPathsByPlatform . get ( osName ) ; if ( osPaths != null && ! osPaths . isEmpty ( ) ) { // verify the requested paths File . exists . . otherwise
// this could be an error .
for ( String osPath : osPaths ) { if ( ! FileUtils . fileExists ( new File ( osPath ) ) ) { throw new FileNotFoundException ( osPath ) ; } } } } } } // return newly filtered data
return absPathsForLibertyContent . toArray ( new String [ ] { } ) ; } } } , d ) ; // we ' re done here . . let liberty proceed to declare itself ' started ' = ) |
public class AbstractProjectWriter { /** * { @ inheritDoc } */
@ Override public void write ( ProjectFile projectFile , String fileName ) throws IOException { } } | FileOutputStream fos = new FileOutputStream ( fileName ) ; write ( projectFile , fos ) ; fos . flush ( ) ; fos . close ( ) ; |
public class ContextUtils { /** * < p > Takes the generic { @ link Object } of a context and discovers
* the actual { @ link Context } instance . It takes an additional set
* of { @ link Class } and limits context discovery to those .
* @ param context
* the { @ link Object } whose { @ link Context } instance is
* to be discovered
* < br > < br >
* @ param subset
* the { @ link Class } es which are to be considered for this
* context discovery . If this array is { @ code null } or empty
* all entries in { @ link # contexts } are considered applicable
* < br > < br >
* @ return the { @ link Context } instance of the given { @ link Object }
* < br > < br >
* @ throws ContextNotFoundException
* if the { @ link Context } cannot be resolved from the given object
* < br > < br >
* @ since 1.0.0 */
public static Context discover ( Object context , Class < ? > ... subset ) { } } | Set < Class < ? > > contextSubset = ( subset == null || subset . length == 0 ) ? contexts . keySet ( ) : new HashSet < Class < ? > > ( Arrays . asList ( subset ) ) ; Set < Class < ? > > contextClasses = contexts . keySet ( ) ; for ( Class < ? > contextClass : contextClasses ) { if ( ! contextSubset . contains ( contextClass ) ) continue ; if ( contextClass . isAssignableFrom ( context . getClass ( ) ) ) { return contexts . get ( contextClass ) . resolve ( context ) ; } } throw new ContextNotFoundException ( context . getClass ( ) ) ; |
public class CommerceOrderPaymentLocalServiceBaseImpl { /** * Returns the number of rows matching the dynamic query .
* @ param dynamicQuery the dynamic query
* @ param projection the projection to apply to the query
* @ return the number of rows matching the dynamic query */
@ Override public long dynamicQueryCount ( DynamicQuery dynamicQuery , Projection projection ) { } } | return commerceOrderPaymentPersistence . countWithDynamicQuery ( dynamicQuery , projection ) ; |
public class WSJdbcTracer { /** * Returns the underlying object .
* @ param obj an object that might be a proxy .
* @ return the underlying object , or , if not a proxy , then the original object . */
public static final Object getImpl ( Object obj ) { } } | InvocationHandler handler ; return Proxy . isProxyClass ( obj . getClass ( ) ) && ( handler = Proxy . getInvocationHandler ( obj ) ) instanceof WSJdbcTracer ? ( ( WSJdbcTracer ) handler ) . impl : obj ; |
public class CredentialsMarshaller { /** * Marshall the given parameter object . */
public void marshall ( Credentials credentials , ProtocolMarshaller protocolMarshaller ) { } } | if ( credentials == null ) { throw new SdkClientException ( "Invalid argument passed to marshall(...)" ) ; } try { protocolMarshaller . marshall ( credentials . getAccessKeyId ( ) , ACCESSKEYID_BINDING ) ; protocolMarshaller . marshall ( credentials . getSecretKey ( ) , SECRETKEY_BINDING ) ; protocolMarshaller . marshall ( credentials . getSessionToken ( ) , SESSIONTOKEN_BINDING ) ; protocolMarshaller . marshall ( credentials . getExpiration ( ) , EXPIRATION_BINDING ) ; } catch ( Exception e ) { throw new SdkClientException ( "Unable to marshall request to JSON: " + e . getMessage ( ) , e ) ; } |
public class DaoUnit { /** * judge whether we need to begin the transaction .
* If there are more than one non - query sql actions in this dao unit , a new transaction will be begun .
* if a transaction is already begun , a nested transaction will be begun .
* Else no transaction will be begun .
* @ return true if this unit is transacitonal false otherwise . */
private boolean isTransactional ( SqlAction [ ] sqlActions , XianTransaction transaction ) { } } | int count = 0 ; for ( SqlAction sqlAction : sqlActions ) { if ( ! ( sqlAction instanceof ISelect ) ) { count ++ ; } } return count > 1 || transaction . isBegun ( ) ; |
public class StringPath { /** * Method to construct the not equals expression for string
* @ param value the string value
* @ return Expression */
public Expression < String > neq ( String value ) { } } | String valueString = "'" + value + "'" ; return new Expression < String > ( this , Operation . neq , valueString ) ; |
public class BugsnagAppender { /** * Checks to see if a stack trace came from the Bugsnag library
* ( prevent possible infinite reporting loops )
* @ param throwable the exception to check
* @ return true if the stacktrace contains a frame from the Bugsnag library */
private boolean detectLogFromBugsnag ( Throwable throwable ) { } } | // Check all places that LOGGER is called with an exception in the Bugsnag library
for ( StackTraceElement element : throwable . getStackTrace ( ) ) { for ( String excludedClass : EXCLUDED_CLASSES ) { if ( element . getClassName ( ) . startsWith ( excludedClass ) ) { return true ; } } } return false ; |
public class WebDriverTool { /** * Asserts that the element is not covered by any other element .
* @ param by
* the { @ link By } used to locate the element .
* @ throws WebElementException
* if the element cannot be located or moved into the viewport .
* @ throws AssertionError
* if the element is covered by some other element . */
public void assertTopmostElement ( By by ) { } } | if ( ! isTopmostElementCheckApplicable ( by ) ) { LOGGER . warn ( "The element identified by '{}' is not a leaf node in the " + "document tree. Thus, it cannot be checked if the element is topmost. " + "The topmost element check cannot be performed and is skipped." , by ) ; return ; } LOGGER . info ( "Checking whether the element identified by '{}' is the topmost element." , by ) ; WebElement topmostElement = findTopmostElement ( by ) ; WebElement element = findElement ( by ) ; if ( ! element . equals ( topmostElement ) ) { throw new AssertionError ( format ( "The element '%s' identified by '%s' is covered by '%s'." , outerHtmlPreview ( element ) , by , outerHtmlPreview ( topmostElement ) ) ) ; } |
public class SipContextConfig { /** * Adjust docBase . */
protected void fixDocBase ( ) throws IOException { } } | Host host = ( Host ) context . getParent ( ) ; File appBase = host . getAppBaseFile ( ) ; String docBase = context . getDocBase ( ) ; if ( docBase == null ) { // Trying to guess the docBase according to the path
String path = context . getPath ( ) ; if ( path == null ) { return ; } ContextName cn = new ContextName ( path , context . getWebappVersion ( ) ) ; docBase = cn . getBaseName ( ) ; } File file = new File ( docBase ) ; if ( ! file . isAbsolute ( ) ) { docBase = ( new File ( appBase , docBase ) ) . getPath ( ) ; } else { docBase = file . getCanonicalPath ( ) ; } file = new File ( docBase ) ; String origDocBase = docBase ; ContextName cn = new ContextName ( context . getPath ( ) , context . getWebappVersion ( ) ) ; String pathName = cn . getBaseName ( ) ; boolean unpackWARs = true ; if ( host instanceof StandardHost ) { unpackWARs = ( ( StandardHost ) host ) . isUnpackWARs ( ) ; if ( unpackWARs && context instanceof StandardContext ) { unpackWARs = ( ( StandardContext ) context ) . getUnpackWAR ( ) ; } } if ( ( docBase . toLowerCase ( Locale . ENGLISH ) . endsWith ( ".sar" ) || docBase . toLowerCase ( Locale . ENGLISH ) . endsWith ( ".war" ) ) && ! file . isDirectory ( ) ) { if ( unpackWARs ) { URL war = new URL ( "jar:" + ( new File ( docBase ) ) . toURI ( ) . toURL ( ) + "!/" ) ; docBase = ExpandWar . expand ( host , war , pathName ) ; file = new File ( docBase ) ; docBase = file . getCanonicalPath ( ) ; if ( context instanceof StandardContext ) { ( ( StandardContext ) context ) . setOriginalDocBase ( origDocBase ) ; } } else { URL war = new URL ( "jar:" + ( new File ( docBase ) ) . toURI ( ) . toURL ( ) + "!/" ) ; ExpandWar . validate ( host , war , pathName ) ; } } else { File docDir = new File ( docBase ) ; if ( ! docDir . exists ( ) ) { String [ ] extensions = new String [ ] { ".sar" , ".war" } ; for ( String extension : extensions ) { File archiveFile = new File ( docBase + extension ) ; if ( archiveFile . exists ( ) ) { URL war = new URL ( "jar:" + archiveFile . toURI ( ) . toURL ( ) + "!/" ) ; if ( unpackWARs ) { docBase = ExpandWar . expand ( host , war , context . getPath ( ) ) ; file = new File ( docBase ) ; docBase = file . getCanonicalPath ( ) ; } else { docBase = archiveFile . getCanonicalPath ( ) ; ExpandWar . validate ( host , war , pathName ) ; } break ; } } if ( context instanceof StandardContext ) { ( ( StandardContext ) context ) . setOriginalDocBase ( origDocBase ) ; } } } if ( docBase . startsWith ( appBase . getPath ( ) + File . separatorChar ) ) { docBase = docBase . substring ( appBase . getPath ( ) . length ( ) ) ; docBase = docBase . replace ( File . separatorChar , '/' ) ; if ( docBase . startsWith ( "/" ) ) { docBase = docBase . substring ( 1 ) ; } } else { docBase = docBase . replace ( File . separatorChar , '/' ) ; } context . setDocBase ( docBase ) ; |
public class AppServiceEnvironmentsInner { /** * Get all worker pools of an App Service Environment .
* Get all worker pools of an App Service Environment .
* @ param resourceGroupName Name of the resource group to which the resource belongs .
* @ param name Name of the App Service Environment .
* @ param serviceCallback the async ServiceCallback to handle successful and failed responses .
* @ throws IllegalArgumentException thrown if parameters fail the validation
* @ return the { @ link ServiceFuture } object */
public ServiceFuture < List < WorkerPoolResourceInner > > listWorkerPoolsAsync ( final String resourceGroupName , final String name , final ListOperationCallback < WorkerPoolResourceInner > serviceCallback ) { } } | return AzureServiceFuture . fromPageResponse ( listWorkerPoolsSinglePageAsync ( resourceGroupName , name ) , new Func1 < String , Observable < ServiceResponse < Page < WorkerPoolResourceInner > > > > ( ) { @ Override public Observable < ServiceResponse < Page < WorkerPoolResourceInner > > > call ( String nextPageLink ) { return listWorkerPoolsNextSinglePageAsync ( nextPageLink ) ; } } , serviceCallback ) ; |
public class AbstractPathFinder { /** * Concatenate arrays { @ code nodes1 } and { @ code nodes2 } .
* @ param nodes1 KAM nodes
* @ param nodes2 KAM nodes
* @ return KamNode [ ] */
KamNode [ ] concat ( KamNode [ ] nodes1 , KamNode [ ] nodes2 ) { } } | KamNode [ ] ret = new KamNode [ nodes1 . length + nodes2 . length ] ; arraycopy ( nodes1 , 0 , ret , 0 , nodes1 . length ) ; arraycopy ( nodes2 , 0 , ret , nodes1 . length , nodes2 . length ) ; return ret ; |
public class MappingServiceController { /** * Creates the integrated entity for a mapping project ' s target
* @ param mappingProjectId ID of the mapping project
* @ param targetEntityTypeId ID of the target entity to create or update
* @ param label label of the target entity to create
* @ param packageId ID of the package to put the newly created entity in
* @ return redirect URL to the data explorer displaying the newly generated entity */
@ PostMapping ( "/createIntegratedEntity" ) public String createIntegratedEntity ( @ RequestParam String mappingProjectId , @ RequestParam String targetEntityTypeId , @ RequestParam ( required = false ) String label , @ RequestParam ( required = false , name = "package" ) String packageId , @ RequestParam ( required = false ) Boolean addSourceAttribute ) { } } | if ( label != null && label . trim ( ) . isEmpty ( ) ) { label = null ; } String mappingJobExecutionHref = submitMappingJob ( mappingProjectId , targetEntityTypeId , addSourceAttribute , packageId , label ) . getBody ( ) ; return format ( "redirect:{0}" , jobsController . createJobExecutionViewHref ( mappingJobExecutionHref , 1000 ) ) ; |
public class ReflectionUtil { /** * Create an MetricCollector from its fully qualified class name .
* The class passed in by name must be assignable to MetricCollector .
* See the secor . monitoring . metrics . collector . class config option .
* @ param className The class name of a subclass of MetricCollector
* @ return a MetricCollector with the runtime type of the class passed by name
* @ throws ClassNotFoundException if class with the { @ code className } is not found in classpath
* @ throws IllegalAccessException if the class or its nullary
* constructor is not accessible .
* @ throws InstantiationException if this { @ code Class } represents an abstract class ,
* an interface , an array class , a primitive type , or void ;
* or if the class has no nullary constructor ;
* or if the instantiation fails for some other reason . */
public static MetricCollector createMetricCollector ( String className ) throws ClassNotFoundException , IllegalAccessException , InstantiationException { } } | Class < ? > clazz = Class . forName ( className ) ; if ( ! MetricCollector . class . isAssignableFrom ( clazz ) ) { throw new IllegalArgumentException ( String . format ( "The class '%s' is not assignable to '%s'." , className , MetricCollector . class . getName ( ) ) ) ; } return ( MetricCollector ) clazz . newInstance ( ) ; |
public class CreateMapProcessor { /** * If requested , adjust the bounds to the nearest scale and the map size .
* @ param mapValues Map parameters .
* @ param paintArea The size of the painting area .
* @ param bounds The map bounds .
* @ param dpi the DPI . */
public static MapBounds adjustBoundsToScaleAndMapSize ( final GenericMapAttributeValues mapValues , final Rectangle paintArea , final MapBounds bounds , final double dpi ) { } } | MapBounds newBounds = bounds ; if ( mapValues . isUseNearestScale ( ) ) { newBounds = newBounds . adjustBoundsToNearestScale ( mapValues . getZoomLevels ( ) , mapValues . getZoomSnapTolerance ( ) , mapValues . getZoomLevelSnapStrategy ( ) , mapValues . getZoomSnapGeodetic ( ) , paintArea , dpi ) ; } newBounds = new BBoxMapBounds ( newBounds . toReferencedEnvelope ( paintArea ) ) ; if ( mapValues . isUseAdjustBounds ( ) ) { newBounds = newBounds . adjustedEnvelope ( paintArea ) ; } return newBounds ; |
public class Node { /** * Add ' child ' after ' node ' . */
public void addChildAfter ( Node newChild , Node node ) { } } | if ( newChild . next != null ) throw new RuntimeException ( "newChild had siblings in addChildAfter" ) ; newChild . next = node . next ; node . next = newChild ; if ( last == node ) last = newChild ; |
public class UserSearchManager { /** * Returns the form to fill out to perform a search .
* @ param searchService the search service to query .
* @ return the form to fill out to perform a search .
* @ throws XMPPErrorException
* @ throws NoResponseException
* @ throws NotConnectedException
* @ throws InterruptedException */
public Form getSearchForm ( DomainBareJid searchService ) throws NoResponseException , XMPPErrorException , NotConnectedException , InterruptedException { } } | return userSearch . getSearchForm ( con , searchService ) ; |
public class FullscreenVideoView { /** * VideoView method ( setVideoPath ) */
public void setVideoPath ( String path ) throws IOException , IllegalStateException , SecurityException , IllegalArgumentException , RuntimeException { } } | Log . d ( TAG , "setVideoPath" ) ; if ( mediaPlayer != null ) { if ( currentState != State . IDLE ) throw new IllegalStateException ( "FullscreenVideoView Invalid State: " + currentState ) ; this . videoPath = path ; this . videoUri = null ; this . mediaPlayer . setDataSource ( path ) ; this . currentState = State . INITIALIZED ; prepare ( ) ; } else throw new RuntimeException ( "Media Player is not initialized" ) ; |
public class Node { /** * 函数具体逻辑
* @ param scope 上下文
* @ return 计算好的节点 */
@ Override public XValue call ( Scope scope ) { } } | Elements context = new Elements ( ) ; for ( Element el : scope . context ( ) ) { context . addAll ( el . children ( ) ) ; String txt = el . ownText ( ) ; if ( StringUtils . isNotBlank ( txt ) ) { Element et = new Element ( "" ) ; et . appendText ( txt ) ; context . add ( et ) ; } } return XValue . create ( context ) ; |
public class FieldInfo { /** * Maximum string length .
* @ return The max field length . */
public int getMaxLength ( ) { } } | if ( m_iMaxLength == Constants . DEFAULT_FIELD_LENGTH ) { m_iMaxLength = 20 ; if ( m_classData == Short . class ) m_iMaxLength = 4 ; else if ( m_classData == Integer . class ) m_iMaxLength = 8 ; else if ( m_classData == Float . class ) m_iMaxLength = 8 ; else if ( m_classData == Double . class ) m_iMaxLength = 15 ; else if ( m_classData == java . util . Date . class ) m_iMaxLength = 15 ; else if ( m_classData == String . class ) m_iMaxLength = 30 ; else if ( m_classData == Boolean . class ) m_iMaxLength = 10 ; } return m_iMaxLength ; |
public class IntegralImageOps { /** * Converts a regular image into an integral image .
* @ param input Regular image . Not modified .
* @ param transformed Integral image . If null a new image will be created . Modified .
* @ return Integral image . */
public static GrayS32 transform ( GrayU8 input , GrayS32 transformed ) { } } | transformed = InputSanityCheck . checkDeclare ( input , transformed , GrayS32 . class ) ; ImplIntegralImageOps . transform ( input , transformed ) ; return transformed ; |
public class TextBuilder { /** * Create a link in the current paragraph .
* @ param text the text
* @ param ref the destination
* @ return this for fluent style */
public TextBuilder link ( final String text , final String ref ) { } } | this . curParagraphBuilder . link ( text , ref ) ; return this ; |
public class StatelessBeanO { /** * Destroy this < code > BeanO < / code > instance . Note , the discard method
* must be called instead of this method if bean needs to be destroyed
* as a result of a unchecked or system exception . The discard method
* ensures that no lifecycle callbacks will occur on the bean instance
* if the bean is being discarded ( as required by EJB spec ) . < p >
* This method must be called whenever this BeanO instance is no
* longer valid . It transitions the BeanO to the DESTROYED state ,
* transitions the associated session bean ( if any ) to the
* does not exist state , and releases the reference to the
* associated session bean . < p > */
@ Override public final synchronized void destroy ( ) { } } | final boolean isTraceOn = TraceComponent . isAnyTracingEnabled ( ) ; if ( isTraceOn && tc . isEntryEnabled ( ) ) // d367572.4
{ Tr . entry ( tc , "destroy" ) ; } if ( state == DESTROYED ) { return ; } // For Stateless , ' destroy ' is where the bean is removed and destroyed .
// Remove time should include calling any lifecycle callbacks . d626533.1
long removeStartTime = - 1 ; if ( pmiBean != null ) { removeStartTime = pmiBean . initialTime ( EJBPMICollaborator . REMOVE_RT ) ; } allowRollbackOnly = false ; if ( ivCallbackKind != CallbackKind . None ) { // d367572.4 start of change .
String lifeCycle = null ; CallbackContextHelper contextHelper = new CallbackContextHelper ( this ) ; // d399469 , d630940
BeanMetaData bmd = home . beanMetaData ; try { // Suspend UOW to ensure everything in this method runs
// in a unspecified TX context if this bean is in a EJB 3.0
// module . We are not doing for older modules to ensure we do
// break existing working applications .
// Pre - Destroy is allowed to access java : comp / env , so all contexts
// must be established around the Pre - Destroy calls . This must be done
// for Stateless beans since they are often destroyed outside the scope
// of a method invocation . d546031
contextHelper . begin ( CallbackContextHelper . Tx . CompatLTC , CallbackContextHelper . Contexts . All ) ; // d367572.1 start
// Invoke either ejbRemove or PreDestroy lifecycle callback if necessary .
if ( ivCallbackKind == CallbackKind . SessionBean ) { if ( isTraceOn && // d527372
TEBeanLifeCycleInfo . isTraceEnabled ( ) ) { lifeCycle = "ejbRemove" ; TEBeanLifeCycleInfo . traceEJBCallEntry ( lifeCycle ) ; // d161864
} // pre - EJB3 SLSB , so invoke ejbRemove .
sessionBean . ejbRemove ( ) ; } else if ( ivCallbackKind == CallbackKind . InvocationContext ) { // Invoke the PreDestroy interceptor methods .
if ( isTraceOn && // d527372
TEBeanLifeCycleInfo . isTraceEnabled ( ) ) { lifeCycle = "preDestroy" ; TEBeanLifeCycleInfo . traceEJBCallEntry ( lifeCycle ) ; // d161864
} InterceptorMetaData imd = home . beanMetaData . ivInterceptorMetaData ; InterceptorProxy [ ] proxies = imd . ivPreDestroyInterceptors ; if ( proxies != null ) { if ( isTraceOn && tc . isDebugEnabled ( ) ) { Tr . debug ( tc , "invoking PreDestroy interceptors" ) ; } InvocationContextImpl < ? > inv = getInvocationContext ( ) ; inv . doLifeCycle ( proxies , bmd . _moduleMetaData ) ; // d450431 , F743-14982
} } // d367572.1 end
} catch ( Exception ex ) { FFDCFilter . processException ( ex , CLASS_NAME + ".destroy" , "164" , this ) ; // Just trace this event and continue so that BeanO is transitioned
// to the DESTROYED state . No other lifecycle callbacks on this bean
// instance will occur once in the DESTROYED state , which is the same
// affect as if bean was discarded as result of this exception .
if ( isTraceOn && tc . isEventEnabled ( ) ) { Tr . event ( tc , "destroy caught exception: " , new Object [ ] { this , ex } ) ; // d402681
} } finally { if ( isTraceOn && // d527372
TEBeanLifeCycleInfo . isTraceEnabled ( ) ) { if ( lifeCycle != null ) { TEBeanLifeCycleInfo . traceEJBCallExit ( lifeCycle ) ; // d161864
} } try { contextHelper . complete ( true ) ; } catch ( Throwable t ) { FFDCFilter . processException ( t , CLASS_NAME + ".destroy" , "505" , this ) ; // Just trace this event and continue so that BeanO is transitioned
// to the DESTROYED state . No other lifecycle callbacks on this bean
// instance will occur once in the DESTROYED state , which is the same
// affect as if bean was discarded as result of this exception .
if ( isTraceOn && tc . isEventEnabled ( ) ) { Tr . event ( tc , "destroy caught exception: " , new Object [ ] { this , t } ) ; } } } // d367572.4 end of change .
} setState ( DESTROYED ) ; destroyHandleList ( ) ; // Release any JCDI creational contexts that may exist . F743-29174
releaseManagedObjectContext ( ) ; // For Stateless , ' destroy ' is where the bean is removed and destroyed .
// Update both counters and end remove time . d626533.1
if ( pmiBean != null ) { pmiBean . beanRemoved ( ) ; // d647928.4
pmiBean . beanDestroyed ( ) ; pmiBean . finalTime ( EJBPMICollaborator . REMOVE_RT , removeStartTime ) ; } // If the number of allowed bean instances is limited , then the number
// of created instances needs to be decremented when an instance is
// destroyed , and the next thread that may be waiting for an instance
// must be notified . PK20648
if ( ivNumberOfBeansLimited ) { synchronized ( beanPool ) { -- home . ivNumberBeansCreated ; if ( isTraceOn && tc . isDebugEnabled ( ) ) Tr . debug ( tc , "destroy: BeanPool(" + home . ivNumberBeansCreated + "/" + home . beanMetaData . ivMaxCreation + ")" ) ; beanPool . notify ( ) ; } } allowRollbackOnly = true ; if ( isTraceOn && tc . isEntryEnabled ( ) ) // d367572.4
{ Tr . exit ( tc , "destroy" ) ; } |
public class JsonModelCoder { /** * Attempts to parse the given data as { @ link List } of objects .
* Accepts { @ link OnJsonObjectAddListener } ; allows you to peek various intermittent instances as parsing goes .
* @ param stream JSON - formatted data
* @ param listener { @ link OnJsonObjectAddListener } to notify
* @ return { @ link List } of objects
* @ throws IOException
* @ throws JsonFormatException The given data is malformed , or its type is unexpected */
public List < T > getList ( InputStream stream , OnJsonObjectAddListener listener ) throws IOException , JsonFormatException { } } | JsonPullParser parser = JsonPullParser . newParser ( stream ) ; return getList ( parser , listener ) ; |
public class VersionUtilImpl { /** * @ see # createFormatter ( String , boolean )
* @ param scanner is the { @ link CharSequenceScanner } .
* @ param formatPattern is the format pattern .
* @ param infixBuffer is a { @ link StringBuilder } containing the current infix .
* @ param status is the { @ link FormatPatternStatus } .
* @ return the sub { @ link Formatter } or { @ code null } to continue parsing the infix . */
protected Formatter < VersionIdentifier > parseSubFormatter ( CharSequenceScanner scanner , String formatPattern , StringBuilder infixBuffer , FormatPatternStatus status ) { } } | char c = scanner . next ( ) ; if ( c == 'V' ) { char segment = scanner . forceNext ( ) ; if ( segment == '\0' ) { throw new IllegalStateException ( formatPattern + "<separator>" ) ; } String segmentSeparator = Character . toString ( segment ) ; int minimumSegmentCount = 0 ; int maximumSegmentCount = Integer . MAX_VALUE ; int segmentPadding = 0 ; if ( scanner . expect ( '{' ) ) { minimumSegmentCount = ( int ) scanner . readLong ( 10 ) ; scanner . require ( ',' ) ; maximumSegmentCount = ( int ) scanner . readLong ( 10 ) ; scanner . require ( ',' ) ; segmentPadding = ( int ) scanner . readLong ( 10 ) ; scanner . require ( '}' ) ; } status . versionSegmentsCount ++ ; return new VersionIdentifierFormatterVersionSegments ( infixBuffer . toString ( ) , segmentSeparator , minimumSegmentCount , maximumSegmentCount , segmentPadding ) ; } else if ( ( c == 'P' ) || ( c == 'A' ) || ( c == 'L' ) ) { int maximumLength = 0 ; if ( scanner . expect ( '{' ) ) { maximumLength = ( int ) scanner . readLong ( 10 ) ; scanner . require ( '}' ) ; } if ( c == 'P' ) { status . phaseCount ++ ; return new VersionIdentifierFormatterPhase ( infixBuffer . toString ( ) , maximumLength ) ; } else if ( c == 'A' ) { status . phaseCount ++ ; return new VersionIdentifierFormatterPhaseAlias ( infixBuffer . toString ( ) , maximumLength ) ; } else { return new VersionIdentifierFormatterLabel ( infixBuffer . toString ( ) , maximumLength ) ; } } else if ( ( c == 'R' ) || ( c == 'N' ) ) { int padding = 0 ; if ( scanner . expect ( '{' ) ) { padding = ( int ) scanner . readLong ( 10 ) ; scanner . require ( '}' ) ; } if ( c == 'R' ) { return new VersionIdentifierFormatterRevision ( infixBuffer . toString ( ) , padding ) ; } else { status . phaseNumberCount ++ ; return new VersionIdentifierFormatterPhaseNumber ( infixBuffer . toString ( ) , padding ) ; } } else if ( c == 'T' ) { DateFormat dateFormat = null ; if ( scanner . expect ( '{' ) ) { String datePattern = scanner . readUntil ( '}' , false ) ; if ( datePattern == null ) { scanner . require ( '}' ) ; } dateFormat = new SimpleDateFormat ( datePattern ) ; } return new VersionIdentifierFormatterTimestamp ( this . iso8601Util , dateFormat , infixBuffer . toString ( ) ) ; } else if ( c == 'S' ) { String snapshotIndicator = VersionIdentifier . SNAPSHOT ; if ( scanner . expect ( '{' ) ) { snapshotIndicator = scanner . readUntil ( '}' , false ) ; if ( snapshotIndicator == null ) { scanner . require ( '}' ) ; } } status . snapshotCount ++ ; infixBuffer . append ( snapshotIndicator ) ; return new VersionIdentifierFormatterSnapshot ( infixBuffer . toString ( ) ) ; } else if ( c == '$' ) { return new StaticFormatter < > ( infixBuffer . toString ( ) ) ; } else if ( ( c == '(' ) && ( ! status . inBrace ) ) { status . inBrace = true ; return null ; } else if ( ( c == ')' ) && ( status . inBrace ) ) { status . inBrace = false ; return null ; } else { throw new IllegalStateException ( Character . toString ( c ) ) ; } |
public class NonVoltDBBackend { /** * Returns all primary key column names for the specified table , in the
* order defined in the DDL . */
protected List < String > getPrimaryKeys ( String tableName ) { } } | List < String > pkCols = new ArrayList < String > ( ) ; try { // Lower - case table names are required for PostgreSQL ; we might need to
// alter this if we use another comparison database ( besides HSQL ) someday
ResultSet rs = dbconn . getMetaData ( ) . getPrimaryKeys ( null , null , tableName . toLowerCase ( ) ) ; while ( rs . next ( ) ) { pkCols . add ( rs . getString ( 4 ) ) ; } } catch ( SQLException e ) { printCaughtException ( "In NonVoltDBBackend.getPrimaryKeys, caught SQLException: " + e ) ; } return pkCols ; |
public class MovingAverage { /** * * * * * * Methods * * * * * */
public void addData ( final Data DATA ) { } } | sum += DATA . getValue ( ) ; window . add ( DATA ) ; if ( window . size ( ) > numberPeriod ) { sum -= window . remove ( ) . getValue ( ) ; } |
public class Step { /** * Display message ( list of elements ) at the beginning of method in logs .
* @ param methodName
* is name of java method
* @ param concernedElements
* is a list of concerned elements ( example : authorized activities ) */
protected void displayConcernedElementsAtTheBeginningOfMethod ( String methodName , List < String > concernedElements ) { } } | logger . debug ( "{}: with {} concernedElements" , methodName , concernedElements . size ( ) ) ; int i = 0 ; for ( final String element : concernedElements ) { i ++ ; logger . debug ( " element N°{}={}" , i , element ) ; } |
public class MapEntryLite { /** * Serializes the provided key and value as though they were wrapped by a { @ link MapEntryLite } to the output stream .
* This helper method avoids allocation of a { @ link MapEntryLite } built with a key and value and is called from
* generated code directly .
* @ param output the output
* @ param fieldNumber the field number
* @ param key the key
* @ param value the value
* @ throws IOException Signals that an I / O exception has occurred . */
public void serializeTo ( CodedOutputStream output , int fieldNumber , K key , V value ) throws IOException { } } | output . writeTag ( fieldNumber , WireFormat . WIRETYPE_LENGTH_DELIMITED ) ; output . writeUInt32NoTag ( computeSerializedSize ( metadata , key , value ) ) ; writeTo ( output , metadata , key , value ) ; |
public class EncodingUtils { /** * Generates an appsecret _ proof for facebook .
* See https : / / developers . facebook . com / docs / graph - api / securing - requests for more info
* @ param appSecret
* The facebook application secret
* @ param accessToken
* The facebook access token
* @ return A Hex encoded SHA256 Hash as a String */
public static String encodeAppSecretProof ( String appSecret , String accessToken ) { } } | try { byte [ ] key = appSecret . getBytes ( StandardCharsets . UTF_8 ) ; SecretKeySpec signingKey = new SecretKeySpec ( key , "HmacSHA256" ) ; Mac mac = Mac . getInstance ( "HmacSHA256" ) ; mac . init ( signingKey ) ; byte [ ] raw = mac . doFinal ( accessToken . getBytes ( ) ) ; byte [ ] hex = encodeHex ( raw ) ; return new String ( hex , StandardCharsets . UTF_8 ) ; } catch ( Exception e ) { throw new IllegalStateException ( "Creation of appsecret_proof has failed" , e ) ; } |
public class ClassLoaders { /** * Find the classpath that contains the given resource . */
private static URL getClassPathURL ( String resourceName , URL resourceURL ) { } } | try { if ( "file" . equals ( resourceURL . getProtocol ( ) ) ) { String path = resourceURL . getFile ( ) ; // Compute the directory container the class .
int endIdx = path . length ( ) - resourceName . length ( ) ; if ( endIdx > 1 ) { // If it is not the root directory , return the end index to remove the trailing ' / ' .
endIdx -- ; } return new URL ( "file" , "" , - 1 , path . substring ( 0 , endIdx ) ) ; } if ( "jar" . equals ( resourceURL . getProtocol ( ) ) ) { String path = resourceURL . getFile ( ) ; return URI . create ( path . substring ( 0 , path . indexOf ( "!/" ) ) ) . toURL ( ) ; } } catch ( MalformedURLException e ) { throw Throwables . propagate ( e ) ; } throw new IllegalStateException ( "Unsupported class URL: " + resourceURL ) ; |
public class HexDecoder { /** * Encodes given sequence of nibbles into a sequence of octets .
* @ param input the nibbles to decode .
* @ return the decoded octets . */
public static byte [ ] decodeMultiple ( final byte [ ] input ) { } } | if ( input == null ) { throw new NullPointerException ( "input" ) ; } final byte [ ] output = new byte [ input . length >> 1 ] ; decodeMultiple ( input , 0 , output , 0 , output . length ) ; return output ; |
public class FessMessages { /** * Add the created action message for the key ' success . crud _ delete _ crud _ table ' with parameters .
* < pre >
* message : Deleted data .
* < / pre >
* @ param property The property name for the message . ( NotNull )
* @ return this . ( NotNull ) */
public FessMessages addSuccessCrudDeleteCrudTable ( String property ) { } } | assertPropertyNotNull ( property ) ; add ( property , new UserMessage ( SUCCESS_crud_delete_crud_table ) ) ; return this ; |
public class AeronNDArrayResponder { /** * Launch a background thread
* that subscribes to the aeron context
* @ throws Exception */
public void launch ( ) throws Exception { } } | if ( init . get ( ) ) return ; // Register a SIGINT handler for graceful shutdown .
if ( ! init . get ( ) ) init ( ) ; log . info ( "Subscribing to " + channel + " on stream Id " + streamId ) ; // Register a SIGINT handler for graceful shutdown .
SigInt . register ( ( ) -> running . set ( false ) ) ; // Create an Aeron instance with client - provided context configuration , connect to the
// media driver , and add a subscription for the given channel and stream using the supplied
// dataHandler method , which will be called with new messages as they are received .
// The Aeron and Subscription classes implement AutoCloseable , and will automatically
// clean up resources when this try block is finished .
// Note here that we are either creating 1 or 2 subscriptions .
// The first one is a normal 1 subscription listener .
// The second one is when we want to send responses
boolean started = false ; int numTries = 0 ; while ( ! started && numTries < 3 ) { try { try ( final Subscription subscription = aeron . addSubscription ( channel , streamId ) ) { log . info ( "Beginning subscribe on channel " + channel + " and stream " + streamId ) ; AeronUtil . subscriberLoop ( new FragmentAssembler ( NDArrayResponseFragmentHandler . builder ( ) . aeron ( aeron ) . context ( ctx ) . streamId ( responseStreamId ) . holder ( ndArrayHolder ) . build ( ) ) , fragmentLimitCount , running , launched ) . accept ( subscription ) ; started = true ; } } catch ( Exception e ) { numTries ++ ; log . warn ( "Failed to connect..trying again" , e ) ; } } if ( numTries >= 3 ) throw new IllegalStateException ( "Was unable to start responder after " + numTries + "tries" ) ; |
public class WhitelistingApi { /** * Get the status of a uploaded CSV file .
* Get the status of a uploaded CSV file .
* @ param dtid Device type id related to the uploaded CSV file . ( required )
* @ param uploadId Upload id related to the uploaded CSV file . ( required )
* @ return ApiResponse & lt ; UploadStatusEnvelope & gt ;
* @ throws ApiException If fail to call the API , e . g . server error or cannot deserialize the response body */
public ApiResponse < UploadStatusEnvelope > getUploadStatusWithHttpInfo ( String dtid , String uploadId ) throws ApiException { } } | com . squareup . okhttp . Call call = getUploadStatusValidateBeforeCall ( dtid , uploadId , null , null ) ; Type localVarReturnType = new TypeToken < UploadStatusEnvelope > ( ) { } . getType ( ) ; return apiClient . execute ( call , localVarReturnType ) ; |
public class Instant { /** * Returns a copy of this instant with the specified duration added .
* This instance is immutable and unaffected by this method call .
* @ param secondsToAdd the seconds to add , positive or negative
* @ param nanosToAdd the nanos to add , positive or negative
* @ return an { @ code Instant } based on this instant with the specified seconds added , not null
* @ throws DateTimeException if the result exceeds the maximum or minimum instant
* @ throws ArithmeticException if numeric overflow occurs */
private Instant plus ( long secondsToAdd , long nanosToAdd ) { } } | if ( ( secondsToAdd | nanosToAdd ) == 0 ) { return this ; } long epochSec = Math . addExact ( seconds , secondsToAdd ) ; epochSec = Math . addExact ( epochSec , nanosToAdd / NANOS_PER_SECOND ) ; nanosToAdd = nanosToAdd % NANOS_PER_SECOND ; long nanoAdjustment = nanos + nanosToAdd ; // safe int + NANOS _ PER _ SECOND
return ofEpochSecond ( epochSec , nanoAdjustment ) ; |
public class DeltaFIFO { /** * Pop deltas .
* @ param func the func
* @ return the deltas
* @ throws Exception the exception */
public Deque < MutablePair < DeltaType , Object > > pop ( Consumer < Deque < MutablePair < DeltaType , Object > > > func ) throws InterruptedException { } } | lock . writeLock ( ) . lock ( ) ; try { while ( true ) { while ( queue . isEmpty ( ) ) { notEmpty . await ( ) ; } // there should have data now
String id = this . queue . removeFirst ( ) ; if ( this . initialPopulationCount > 0 ) { this . initialPopulationCount -- ; } if ( ! this . items . containsKey ( id ) ) { // Item may have been deleted subsequently .
continue ; } Deque < MutablePair < DeltaType , Object > > deltas = this . items . get ( id ) ; this . items . remove ( id ) ; func . accept ( deltas ) ; // Don ' t make any copyDeltas here
return deltas ; } } finally { lock . writeLock ( ) . unlock ( ) ; } |
public class AccountsInner { /** * Lists the Data Lake Store accounts within a specific resource group . The response includes a link to the next page of results , if any .
* @ param resourceGroupName The name of the Azure resource group .
* @ throws IllegalArgumentException thrown if parameters fail the validation
* @ return the observable to the PagedList & lt ; DataLakeStoreAccountBasicInner & gt ; object */
public Observable < Page < DataLakeStoreAccountBasicInner > > listByResourceGroupAsync ( final String resourceGroupName ) { } } | return listByResourceGroupWithServiceResponseAsync ( resourceGroupName ) . map ( new Func1 < ServiceResponse < Page < DataLakeStoreAccountBasicInner > > , Page < DataLakeStoreAccountBasicInner > > ( ) { @ Override public Page < DataLakeStoreAccountBasicInner > call ( ServiceResponse < Page < DataLakeStoreAccountBasicInner > > response ) { return response . body ( ) ; } } ) ; |
public class HyperParameterTuningJobSummaryMarshaller { /** * Marshall the given parameter object . */
public void marshall ( HyperParameterTuningJobSummary hyperParameterTuningJobSummary , ProtocolMarshaller protocolMarshaller ) { } } | if ( hyperParameterTuningJobSummary == null ) { throw new SdkClientException ( "Invalid argument passed to marshall(...)" ) ; } try { protocolMarshaller . marshall ( hyperParameterTuningJobSummary . getHyperParameterTuningJobName ( ) , HYPERPARAMETERTUNINGJOBNAME_BINDING ) ; protocolMarshaller . marshall ( hyperParameterTuningJobSummary . getHyperParameterTuningJobArn ( ) , HYPERPARAMETERTUNINGJOBARN_BINDING ) ; protocolMarshaller . marshall ( hyperParameterTuningJobSummary . getHyperParameterTuningJobStatus ( ) , HYPERPARAMETERTUNINGJOBSTATUS_BINDING ) ; protocolMarshaller . marshall ( hyperParameterTuningJobSummary . getStrategy ( ) , STRATEGY_BINDING ) ; protocolMarshaller . marshall ( hyperParameterTuningJobSummary . getCreationTime ( ) , CREATIONTIME_BINDING ) ; protocolMarshaller . marshall ( hyperParameterTuningJobSummary . getHyperParameterTuningEndTime ( ) , HYPERPARAMETERTUNINGENDTIME_BINDING ) ; protocolMarshaller . marshall ( hyperParameterTuningJobSummary . getLastModifiedTime ( ) , LASTMODIFIEDTIME_BINDING ) ; protocolMarshaller . marshall ( hyperParameterTuningJobSummary . getTrainingJobStatusCounters ( ) , TRAININGJOBSTATUSCOUNTERS_BINDING ) ; protocolMarshaller . marshall ( hyperParameterTuningJobSummary . getObjectiveStatusCounters ( ) , OBJECTIVESTATUSCOUNTERS_BINDING ) ; protocolMarshaller . marshall ( hyperParameterTuningJobSummary . getResourceLimits ( ) , RESOURCELIMITS_BINDING ) ; } catch ( Exception e ) { throw new SdkClientException ( "Unable to marshall request to JSON: " + e . getMessage ( ) , e ) ; } |
public class AreaSizeConversions { /** * Convert an area size .
* @ param a The area size
* @ param < S > A phantom type parameter indicating the coordinate space of the
* area size
* @ return An area size */
public static < S > PAreaSizeBD < S > toPAreaSizeBD ( final AreaSizeBD a ) { } } | Objects . requireNonNull ( a , "area size" ) ; return PAreaSizeBD . of ( a . sizeX ( ) , a . sizeY ( ) ) ; |
public class TexturedButtonPainter { /** * { @ inheritDoc } */
public Paint getCommonInteriorPaint ( Shape s , CommonControlState type ) { } } | TwoColors colors = getTexturedButtonInteriorColors ( type ) ; return createVerticalGradient ( s , new TwoColors ( colors . top , colors . bottom ) ) ; |
public class NodeManager { /** * Find allocation for a resource type .
* @ param type The resource type .
* @ return The allocation . */
public int getAllocatedCpuForType ( ResourceType type ) { } } | int total = 0 ; for ( ClusterNode node : nameToNode . values ( ) ) { synchronized ( node ) { if ( node . deleted ) { continue ; } total += node . getAllocatedCpuForType ( type ) ; } } return total ; |
public class Font { /** * Gets the familyname as a String .
* @ return the familyname */
public String getFamilyname ( ) { } } | String tmp = "unknown" ; switch ( getFamily ( ) ) { case Font . COURIER : return FontFactory . COURIER ; case Font . HELVETICA : return FontFactory . HELVETICA ; case Font . TIMES_ROMAN : return FontFactory . TIMES_ROMAN ; case Font . SYMBOL : return FontFactory . SYMBOL ; case Font . ZAPFDINGBATS : return FontFactory . ZAPFDINGBATS ; default : if ( baseFont != null ) { String [ ] [ ] names = baseFont . getFamilyFontName ( ) ; for ( int i = 0 ; i < names . length ; i ++ ) { if ( "0" . equals ( names [ i ] [ 2 ] ) ) { return names [ i ] [ 3 ] ; } if ( "1033" . equals ( names [ i ] [ 2 ] ) ) { tmp = names [ i ] [ 3 ] ; } if ( "" . equals ( names [ i ] [ 2 ] ) ) { tmp = names [ i ] [ 3 ] ; } } } } return tmp ; |
public class MiniJPEContentHandler { /** * { @ inheritDoc } */
public Object addFeatureToCollection ( Object featureCollection , Object feature ) { } } | JTSFeature feat = ( JTSFeature ) feature ; try { if ( feat . getGeometry ( ) . getGeometry ( ) . getCoordinate ( ) . x == 0 && feat . getGeometry ( ) . getGeometry ( ) . getCoordinate ( ) . y == 0 ) { // return featureCollection ;
} } catch ( BaseException e ) { e . printStackTrace ( ) ; return featureCollection ; } ( ( ArrayList ) featureCollection ) . add ( feature ) ; return featureCollection ; |
public class ConsumerLogMessages { /** * Logs the status of the consumer .
* @ param logger
* reference to the logger
* @ param startTime
* start time
* @ param sleepingTime
* time the consumer has slept
* @ param workingTime
* time the consumer was working */
public static void logStatus ( final Logger logger , final long startTime , final long sleepingTime , final long workingTime ) { } } | logger . logMessage ( Level . DEBUG , "Consumer-Status-Report [" + Time . toClock ( System . currentTimeMillis ( ) - startTime ) + "]" + "\tEFFICIENCY\t " + MathUtilities . percentPlus ( workingTime , sleepingTime ) + "\tWORK [" + Time . toClock ( workingTime ) + "]" + "\tSLEEP [" + Time . toClock ( sleepingTime ) + "]" ) ; |
public class DFACaches { /** * Creates a prefix - closed cache oracle for a DFA learning setup , using a tree for internal cache organization .
* @ param alphabet
* the alphabet containing the symbols of possible queries
* @ param mqOracle
* the oracle to delegate queries to , in case of a cache - miss .
* @ param < I >
* input symbol type
* @ return the cached { @ link DFACacheOracle } .
* @ see IncrementalPCDFATreeBuilder */
public static < I > DFACacheOracle < I > createTreePCCache ( Alphabet < I > alphabet , MembershipOracle < I , Boolean > mqOracle ) { } } | return DFACacheOracle . createTreePCCacheOracle ( alphabet , mqOracle ) ; |
public class QuickDrawContext { /** * Drawing Ovals : */
private static Ellipse2D . Double toOval ( final Rectangle2D pRectangle ) { } } | Ellipse2D . Double ellipse = new Ellipse2D . Double ( ) ; ellipse . setFrame ( pRectangle ) ; return ellipse ; |
public class Analysis { /** * Get the number of additional burn - in runs that will be performed for the search with the given ID .
* If no specific number of burn - in runs has been set for this search using { @ link # setNumBurnIn ( String , int ) } ,
* the global value obtained from { @ link # getNumBurnIn ( ) } is returned . Burn - in runs are executed before the
* actual search runs and not registered in the results , to " warm up " the analysis in order to reduce the
* influence of just in time compilation ( JIT ) and on the fly optimizations performed by the JVM .
* @ param searchID ID of the search
* @ return number of additional burn - in runs that will be performed for this search
* @ throws UnknownIDException if no search with this ID has been added */
public int getNumBurnIn ( String searchID ) { } } | if ( ! searches . containsKey ( searchID ) ) { throw new UnknownIDException ( "No search with ID " + searchID + " has been added." ) ; } return searchNumBurnIn . getOrDefault ( searchID , getNumBurnIn ( ) ) ; |
public class EntityJsonParser { /** * / * package */
IEntityJsonSchemaContext validate ( URL schemaUrl , Object instanceSource , Reader in ) throws SchemaValidationException , InvalidInstanceException , NoSchemaException , InvalidSchemaException { } } | IEntityJsonContext context = EntityJsonContext . newInstance ( ) ; return validate ( context . withInstance ( instanceSource , getInstanceJsonNode ( context , in ) ) . withSchema ( schemaUrl , getSchemaJsonNode ( context , schemaUrl ) ) ) ; |
public class SearchParamExtractorDstu2 { /** * ( non - Javadoc )
* @ see ca . uhn . fhir . jpa . dao . ISearchParamExtractor # extractSearchParamNumber ( ca . uhn . fhir . jpa . entity . ResourceTable ,
* ca . uhn . fhir . model . api . IResource ) */
@ Override public HashSet < ResourceIndexedSearchParamNumber > extractSearchParamNumber ( ResourceTable theEntity , IBaseResource theResource ) { } } | HashSet < ResourceIndexedSearchParamNumber > retVal = new HashSet < ResourceIndexedSearchParamNumber > ( ) ; Collection < RuntimeSearchParam > searchParams = getSearchParams ( theResource ) ; for ( RuntimeSearchParam nextSpDef : searchParams ) { if ( nextSpDef . getParamType ( ) != RestSearchParameterTypeEnum . NUMBER ) { continue ; } String nextPath = nextSpDef . getPath ( ) ; if ( isBlank ( nextPath ) ) { continue ; } for ( Object nextObject : extractValues ( nextPath , theResource ) ) { if ( nextObject == null || ( ( IDatatype ) nextObject ) . isEmpty ( ) ) { continue ; } String resourceName = nextSpDef . getName ( ) ; boolean multiType = false ; if ( nextPath . endsWith ( "[x]" ) ) { multiType = true ; } if ( nextObject instanceof DurationDt ) { DurationDt nextValue = ( DurationDt ) nextObject ; if ( nextValue . getValueElement ( ) . isEmpty ( ) ) { continue ; } if ( new UriDt ( SearchParamConstants . UCUM_NS ) . equals ( nextValue . getSystemElement ( ) ) ) { if ( isNotBlank ( nextValue . getCode ( ) ) ) { Unit < ? extends Quantity > unit = Unit . valueOf ( nextValue . getCode ( ) ) ; javax . measure . converter . UnitConverter dayConverter = unit . getConverterTo ( NonSI . DAY ) ; double dayValue = dayConverter . convert ( nextValue . getValue ( ) . doubleValue ( ) ) ; DurationDt newValue = new DurationDt ( ) ; newValue . setSystem ( SearchParamConstants . UCUM_NS ) ; newValue . setCode ( NonSI . DAY . toString ( ) ) ; newValue . setValue ( dayValue ) ; nextValue = newValue ; /* * @ SuppressWarnings ( " unchecked " ) PhysicsUnit < ? extends
* org . unitsofmeasurement . quantity . Quantity < ? > > unit = ( PhysicsUnit < ? extends
* org . unitsofmeasurement . quantity . Quantity < ? > > )
* UCUMFormat . getCaseInsensitiveInstance ( ) . parse ( nextValue . getCode ( ) . getValue ( ) , null ) ; if
* ( unit . isCompatible ( UCUM . DAY ) ) {
* @ SuppressWarnings ( " unchecked " ) PhysicsUnit < org . unitsofmeasurement . quantity . Time > timeUnit =
* ( PhysicsUnit < Time > ) unit ; UnitConverter conv = timeUnit . getConverterTo ( UCUM . DAY ) ; double
* dayValue = conv . convert ( nextValue . getValue ( ) . getValue ( ) . doubleValue ( ) ) ; DurationDt newValue =
* new DurationDt ( ) ; newValue . setSystem ( UCUM _ NS ) ; newValue . setCode ( UCUM . DAY . getSymbol ( ) ) ;
* newValue . setValue ( dayValue ) ; nextValue = newValue ; } */
} } ResourceIndexedSearchParamNumber nextEntity = new ResourceIndexedSearchParamNumber ( resourceName , nextValue . getValue ( ) ) ; nextEntity . setResource ( theEntity ) ; retVal . add ( nextEntity ) ; } else if ( nextObject instanceof QuantityDt ) { QuantityDt nextValue = ( QuantityDt ) nextObject ; if ( nextValue . getValueElement ( ) . isEmpty ( ) ) { continue ; } ResourceIndexedSearchParamNumber nextEntity = new ResourceIndexedSearchParamNumber ( resourceName , nextValue . getValue ( ) ) ; nextEntity . setResource ( theEntity ) ; retVal . add ( nextEntity ) ; } else if ( nextObject instanceof IntegerDt ) { IntegerDt nextValue = ( IntegerDt ) nextObject ; if ( nextValue . getValue ( ) == null ) { continue ; } ResourceIndexedSearchParamNumber nextEntity = new ResourceIndexedSearchParamNumber ( resourceName , new BigDecimal ( nextValue . getValue ( ) ) ) ; nextEntity . setResource ( theEntity ) ; retVal . add ( nextEntity ) ; } else if ( nextObject instanceof DecimalDt ) { DecimalDt nextValue = ( DecimalDt ) nextObject ; if ( nextValue . getValue ( ) == null ) { continue ; } ResourceIndexedSearchParamNumber nextEntity = new ResourceIndexedSearchParamNumber ( resourceName , nextValue . getValue ( ) ) ; nextEntity . setResource ( theEntity ) ; retVal . add ( nextEntity ) ; } else { if ( ! multiType ) { throw new ConfigurationException ( "Search param " + resourceName + " is of unexpected datatype: " + nextObject . getClass ( ) ) ; } else { continue ; } } } } return retVal ; |
public class PropertiesEscape { /** * Perform a Java Properties Value level 2 ( basic set and all non - ASCII chars ) < strong > escape < / strong > operation
* on a < tt > String < / tt > input , writing results to a < tt > Writer < / tt > .
* < em > Level 2 < / em > means this method will escape :
* < ul >
* < li > The Java Properties basic escape set :
* < ul >
* < li > The < em > Single Escape Characters < / em > :
* < tt > & # 92 ; t < / tt > ( < tt > U + 0009 < / tt > ) ,
* < tt > & # 92 ; n < / tt > ( < tt > U + 000A < / tt > ) ,
* < tt > & # 92 ; f < / tt > ( < tt > U + 000C < / tt > ) ,
* < tt > & # 92 ; r < / tt > ( < tt > U + 000D < / tt > ) and
* < tt > & # 92 ; & # 92 ; < / tt > ( < tt > U + 005C < / tt > ) .
* < / li >
* < li >
* Two ranges of non - displayable , control characters ( some of which are already part of the
* < em > single escape characters < / em > list ) : < tt > U + 0000 < / tt > to < tt > U + 001F < / tt >
* and < tt > U + 007F < / tt > to < tt > U + 009F < / tt > .
* < / li >
* < / ul >
* < / li >
* < li > All non ASCII characters . < / li >
* < / ul >
* This escape will be performed by using the Single Escape Chars whenever possible . For escaped
* characters that do not have an associated SEC , default to < tt > & # 92 ; uFFFF < / tt >
* Hexadecimal Escapes .
* This method calls { @ link # escapePropertiesValue ( String , Writer , PropertiesValueEscapeLevel ) }
* with the following preconfigured values :
* < ul >
* < li > < tt > level < / tt > :
* { @ link PropertiesValueEscapeLevel # LEVEL _ 2 _ ALL _ NON _ ASCII _ PLUS _ BASIC _ ESCAPE _ SET } < / li >
* < / ul >
* This method is < strong > thread - safe < / strong > .
* @ param text the < tt > String < / tt > to 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 > .
* @ throws IOException if an input / output exception occurs
* @ since 1.1.2 */
public static void escapePropertiesValue ( final String text , final Writer writer ) throws IOException { } } | escapePropertiesValue ( text , writer , PropertiesValueEscapeLevel . LEVEL_2_ALL_NON_ASCII_PLUS_BASIC_ESCAPE_SET ) ; |
public class Gauge { /** * Sets the sections to the given list of Section objects . The
* sections will be used to colorize areas with a special
* meaning such as the red area in a rpm gauge .
* Areas in the Medusa library usually are more
* eye - catching than Sections .
* @ param AREAS */
public void setAreas ( final List < Section > AREAS ) { } } | areas . setAll ( AREAS ) ; Collections . sort ( areas , new SectionComparator ( ) ) ; fireUpdateEvent ( SECTION_EVENT ) ; |
public class ExcelUtils { /** * 读取Excel操作基于注解映射成绑定的java对象
* @ param excelPath 待导出Excel的路径
* @ param clazz 待绑定的类 ( 绑定属性注解 { @ link com . github . crab2died . annotation . ExcelField } )
* @ param offsetLine Excel表头行 ( 默认是0)
* @ param limitLine 最大读取行数 ( 默认表尾 )
* @ param sheetIndex Sheet索引 ( 默认0)
* @ param < T > 绑定的数据类
* @ return 返回转换为设置绑定的java对象集合
* @ throws Excel4JException 异常
* @ throws IOException 异常
* @ throws InvalidFormatException 异常
* @ author Crab2Died */
public < T > List < T > readExcel2Objects ( String excelPath , Class < T > clazz , int offsetLine , int limitLine , int sheetIndex ) throws Excel4JException , IOException , InvalidFormatException { } } | try ( Workbook workbook = WorkbookFactory . create ( new FileInputStream ( new File ( excelPath ) ) ) ) { return readExcel2ObjectsHandler ( workbook , clazz , offsetLine , limitLine , sheetIndex ) ; } |
public class Ifc2x3tc1PackageImpl { /** * < ! - - begin - user - doc - - >
* < ! - - end - user - doc - - >
* @ generated */
public EClass getIfcEquipmentStandard ( ) { } } | if ( ifcEquipmentStandardEClass == null ) { ifcEquipmentStandardEClass = ( EClass ) EPackage . Registry . INSTANCE . getEPackage ( Ifc2x3tc1Package . eNS_URI ) . getEClassifiers ( ) . get ( 210 ) ; } return ifcEquipmentStandardEClass ; |
public class AbstractItem { /** * Request that the receiver prints its xml representation
* ( recursively ) onto the given writer ) .
* @ param writer
* @ throws IOException
* @ throws NotInMessageStore */
public final void xmlRequestWriteOn ( FormattedWriter writer ) throws IOException , NotInMessageStore { } } | Membership membership = _getMembership ( ) ; if ( null == membership ) { throw new NotInMessageStore ( ) ; } if ( null != membership ) { membership . requestXmlWriteOn ( writer ) ; writer . flush ( ) ; } |
public class Parsys { /** * Checks if the given paragraph is valid .
* @ param resource Resource
* @ return if the return value is empty there is no model associated with this resource , or
* it does not support validation via { @ link ParsysItem } interface . Otherwise it contains the valid status . */
private Optional < @ NotNull Boolean > isParagraphValid ( Resource resource ) { } } | // use reflection to access the method " getModelFromResource " from ModelFactory , as it is not present in earlier version
// but we want still to support earlier versions of AEM as well which do not contain this method
// validation is disabled in this case
Method getModelFromResourceMethod ; try { getModelFromResourceMethod = ModelFactory . class . getDeclaredMethod ( "getModelFromResource" , Resource . class ) ; } catch ( NoSuchMethodException | SecurityException ex ) { // seems to be an earlier version of AEM / Sling models not supporting this method
log . debug ( "ModelFactory does not support method 'getModelFromResource' - skip paragraph validation." ) ; return Optional . empty ( ) ; } try { // try to get model associated with the resource , and check if it implements the ParsysItem interface
Object model = getModelFromResourceMethod . invoke ( modelFactory , resource ) ; if ( model instanceof ParsysItem ) { return Optional . of ( ( ( ParsysItem ) model ) . isValid ( ) ) ; } } catch ( ModelClassException ex ) { // ignore if no model was registered for this resource type
} catch ( InvocationTargetException ex ) { if ( ex . getCause ( ) instanceof ModelClassException ) { // ignore if no model was registered for this resource type
} else { log . warn ( "Unable to invoke ModelFactory.getModelFromResource." , ex ) ; } } catch ( IllegalAccessException ex ) { log . warn ( "Unable to access ModelFactory.getModelFromResource." , ex ) ; } return Optional . empty ( ) ; |
public class CLI { /** * Create the parameters available for evaluation . */
private void loadDocevalParameters ( ) { } } | this . docevalParser . addArgument ( "-m" , "--model" ) . required ( false ) . setDefault ( Flags . DEFAULT_EVALUATE_MODEL ) . help ( "Pass the model to evaluate as a parameter.\n" ) ; this . docevalParser . addArgument ( "-t" , "--testset" ) . required ( true ) . help ( "The test or reference corpus.\n" ) ; this . docevalParser . addArgument ( "--clearFeatures" ) . required ( false ) . choices ( "yes" , "no" , "docstart" ) . setDefault ( Flags . DEFAULT_FEATURE_FLAG ) . help ( "Reset the adaptive features; defaults to 'no'.\n" ) ; this . docevalParser . addArgument ( "--evalReport" ) . required ( false ) . choices ( "brief" , "detailed" ) . help ( "Choose level of detail of evaluation report; it defaults to detailed evaluation.\n" ) ; |
public class IntentsClient { /** * Deletes intents in the specified agent .
* < p > Operation & lt ; response : [ google . protobuf . Empty ] [ google . protobuf . Empty ] & gt ;
* < p > Sample code :
* < pre > < code >
* try ( IntentsClient intentsClient = IntentsClient . create ( ) ) {
* ProjectAgentName parent = ProjectAgentName . of ( " [ PROJECT ] " ) ;
* List & lt ; Intent & gt ; intents = new ArrayList & lt ; & gt ; ( ) ;
* intentsClient . batchDeleteIntentsAsync ( parent . toString ( ) , intents ) . get ( ) ;
* < / code > < / pre >
* @ param parent Required . The name of the agent to delete all entities types for . Format :
* ` projects / & lt ; Project ID & gt ; / agent ` .
* @ param intents Required . The collection of intents to delete . Only intent ` name ` must be filled
* in .
* @ throws com . google . api . gax . rpc . ApiException if the remote call fails */
@ BetaApi ( "The surface for long-running operations is not stable yet and may change in the future." ) public final OperationFuture < Empty , Struct > batchDeleteIntentsAsync ( String parent , List < Intent > intents ) { } } | BatchDeleteIntentsRequest request = BatchDeleteIntentsRequest . newBuilder ( ) . setParent ( parent ) . addAllIntents ( intents ) . build ( ) ; return batchDeleteIntentsAsync ( request ) ; |
public class IteratorExecutor { /** * Log failures in the output of { @ link # executeAndGetResults ( ) } .
* @ param results output of { @ link # executeAndGetResults ( ) }
* @ param useLogger logger to log the messages into .
* @ param atMost will log at most this many errors . */
public static < T > void logFailures ( List < Either < T , ExecutionException > > results , Logger useLogger , int atMost ) { } } | Logger actualLogger = useLogger == null ? log : useLogger ; Iterator < Either < T , ExecutionException > > it = results . iterator ( ) ; int printed = 0 ; while ( it . hasNext ( ) ) { Either < T , ExecutionException > nextResult = it . next ( ) ; if ( nextResult instanceof Either . Right ) { ExecutionException exc = ( ( Either . Right < T , ExecutionException > ) nextResult ) . getRight ( ) ; actualLogger . error ( "Iterator executor failure." , exc ) ; printed ++ ; if ( printed >= atMost ) { return ; } } } |
public class TypesREST { /** * Get the relationship definition by it ' s name ( unique )
* @ param name relationship name
* @ return relationship definition
* @ throws AtlasBaseException
* @ HTTP 200 On successful lookup of the the relationship definition by it ' s name
* @ HTTP 404 On Failed lookup for the given name */
@ GET @ Path ( "/relationshipdef/name/{name}" ) @ Produces ( Servlets . JSON_MEDIA_TYPE ) public AtlasRelationshipDef getRelationshipDefByName ( @ PathParam ( "name" ) String name ) throws AtlasBaseException { } } | AtlasRelationshipDef ret = typeDefStore . getRelationshipDefByName ( name ) ; return ret ; |
public class Calendar { /** * Converts the current field values in < code > fields [ ] < / code > to the
* millisecond time value < code > time < / code > . */
protected void computeTime ( ) { } } | if ( ! isLenient ( ) ) { validateFields ( ) ; } // Compute the Julian day
int julianDay = computeJulianDay ( ) ; long millis = julianDayToMillis ( julianDay ) ; int millisInDay ; // We only use MILLISECONDS _ IN _ DAY if it has been set by the user .
// This makes it possible for the caller to set the calendar to a
// time and call clear ( MONTH ) to reset the MONTH to January . This
// is legacy behavior . Without this , clear ( MONTH ) has no effect ,
// since the internally set JULIAN _ DAY is used .
if ( stamp [ MILLISECONDS_IN_DAY ] >= MINIMUM_USER_STAMP && newestStamp ( AM_PM , MILLISECOND , UNSET ) <= stamp [ MILLISECONDS_IN_DAY ] ) { millisInDay = internalGet ( MILLISECONDS_IN_DAY ) ; } else { millisInDay = computeMillisInDay ( ) ; } if ( stamp [ ZONE_OFFSET ] >= MINIMUM_USER_STAMP || stamp [ DST_OFFSET ] >= MINIMUM_USER_STAMP ) { time = millis + millisInDay - ( internalGet ( ZONE_OFFSET ) + internalGet ( DST_OFFSET ) ) ; } else { // Compute the time zone offset and DST offset . There are two potential
// ambiguities here . We ' ll assume a 2:00 am ( wall time ) switchover time
// for discussion purposes here .
// 1 . The positive offset change such as transition into DST .
// Here , a designated time of 2:00 am - 2:59 am does not actually exist .
// For this case , skippedWallTime option specifies the behavior .
// For example , 2:30 am is interpreted as ;
// - WALLTIME _ LAST ( default ) : 3:30 am ( DST ) ( interpreting 2:30 am as 31 minutes after 1:59 am ( STD ) )
// - WALLTIME _ FIRST : 1:30 am ( STD ) ( interpreting 2:30 am as 30 minutes before 3:00 am ( DST ) )
// - WALLTIME _ NEXT _ VALID : 3:00 am ( DST ) ( next valid time after 2:30 am on a wall clock )
// 2 . The negative offset change such as transition out of DST .
// Here , a designated time of 1:00 am - 1:59 am can be in standard or DST . Both are valid
// representations ( the rep jumps from 1:59:59 DST to 1:00:00 Std ) .
// For this case , repeatedWallTime option specifies the behavior .
// For example , 1:30 am is interpreted as ;
// - WALLTIME _ LAST ( default ) : 1:30 am ( STD ) - latter occurrence
// - WALLTIME _ FIRST : 1:30 am ( DST ) - former occurrence
// In addition to above , when calendar is strict ( not default ) , wall time falls into
// the skipped time range will be processed as an error case .
// These special cases are mostly handled in # computeZoneOffset ( long ) , except WALLTIME _ NEXT _ VALID
// at positive offset change . The protected method computeZoneOffset ( long ) is exposed to Calendar
// subclass implementations and marked as @ stable . Strictly speaking , WALLTIME _ NEXT _ VALID
// should be also handled in the same place , but we cannot change the code flow without deprecating
// the protected method .
// We use the TimeZone object , unless the user has explicitly set the ZONE _ OFFSET
// or DST _ OFFSET fields ; then we use those fields .
if ( ! lenient || skippedWallTime == WALLTIME_NEXT_VALID ) { // When strict , invalidate a wall time falls into a skipped wall time range .
// When lenient and skipped wall time option is WALLTIME _ NEXT _ VALID ,
// the result time will be adjusted to the next valid time ( on wall clock ) .
int zoneOffset = computeZoneOffset ( millis , millisInDay ) ; long tmpTime = millis + millisInDay - zoneOffset ; int zoneOffset1 = zone . getOffset ( tmpTime ) ; // zoneOffset ! = zoneOffset1 only when the given wall time fall into
// a skipped wall time range caused by positive zone offset transition .
if ( zoneOffset != zoneOffset1 ) { if ( ! lenient ) { throw new IllegalArgumentException ( "The specified wall time does not exist due to time zone offset transition." ) ; } assert skippedWallTime == WALLTIME_NEXT_VALID : skippedWallTime ; // Adjust time to the next valid wall clock time .
// At this point , tmpTime is on or after the zone offset transition causing
// the skipped time range .
Long immediatePrevTransition = getImmediatePreviousZoneTransition ( tmpTime ) ; if ( immediatePrevTransition == null ) { throw new RuntimeException ( "Could not locate a time zone transition before " + tmpTime ) ; } time = immediatePrevTransition ; } else { time = tmpTime ; } } else { time = millis + millisInDay - computeZoneOffset ( millis , millisInDay ) ; } } |
public class Fraction { /** * < p > Reduce the fraction to the smallest values for the numerator and
* denominator , returning the result . < / p >
* < p > For example , if this fraction represents 2/4 , then the result
* will be 1/2 . < / p >
* @ return a new reduced fraction instance , or this if no simplification possible */
public Fraction reduce ( ) { } } | if ( numerator == 0 ) { return equals ( ZERO ) ? this : ZERO ; } final int gcd = greatestCommonDivisor ( Math . abs ( numerator ) , denominator ) ; if ( gcd == 1 ) { return this ; } return Fraction . getFraction ( numerator / gcd , denominator / gcd ) ; |
public class AtlasHook { /** * Returns the user . Order of preference :
* 1 . Given userName
* 2 . ugi . getShortUserName ( )
* 3 . UserGroupInformation . getCurrentUser ( ) . getShortUserName ( )
* 4 . System . getProperty ( " user . name " ) */
public static String getUser ( String userName , UserGroupInformation ugi ) { } } | if ( StringUtils . isNotEmpty ( userName ) ) { if ( LOG . isDebugEnabled ( ) ) { LOG . debug ( "Returning userName {}" , userName ) ; } return userName ; } if ( ugi != null && StringUtils . isNotEmpty ( ugi . getShortUserName ( ) ) ) { if ( LOG . isDebugEnabled ( ) ) { LOG . debug ( "Returning ugi.getShortUserName {}" , userName ) ; } return ugi . getShortUserName ( ) ; } try { return UserGroupInformation . getCurrentUser ( ) . getShortUserName ( ) ; } catch ( IOException e ) { LOG . warn ( "Failed for UserGroupInformation.getCurrentUser() " , e ) ; return System . getProperty ( "user.name" ) ; } |
public class ODataLocalHole { /** * Fills the holes information into OPhysicalPosition object given as parameter .
* @ return true , if it ' s a valid hole , otherwise false
* @ throws IOException */
public synchronized ODataHoleInfo getHole ( final int iPosition ) { } } | final ODataHoleInfo hole = availableHolesList . get ( iPosition ) ; if ( hole . dataOffset == - 1 ) return null ; return hole ; |
public class ApiOvhIpLoadbalancing { /** * Get this object properties
* REST : GET / ipLoadbalancing / { serviceName } / vrack / network / { vrackNetworkId }
* @ param serviceName [ required ] The internal name of your IP load balancing
* @ param vrackNetworkId [ required ] Internal Load Balancer identifier of the vRack private network description
* API beta */
public OvhVrackNetwork serviceName_vrack_network_vrackNetworkId_GET ( String serviceName , Long vrackNetworkId ) throws IOException { } } | String qPath = "/ipLoadbalancing/{serviceName}/vrack/network/{vrackNetworkId}" ; StringBuilder sb = path ( qPath , serviceName , vrackNetworkId ) ; String resp = exec ( qPath , "GET" , sb . toString ( ) , null ) ; return convertTo ( resp , OvhVrackNetwork . class ) ; |
public class IoUtil { /** * Reads the contents characters from the file .
* @ param file
* the input file .
* @ return
* the read string .
* @ throws IOException */
public static String readCharacters ( final File file ) throws IOException { } } | Reader reader = new BufferedReader ( new InputStreamReader ( new FileInputStream ( file ) , Charset . forName ( "UTF-8" ) ) ) ; // Note :
// The character set should be specified to parse XML
// containing Japanese characters .
StringWriter sw = new StringWriter ( ) ; Writer writer = new BufferedWriter ( sw ) ; copy ( reader , writer ) ; String characters = sw . toString ( ) ; return characters ; |
public class HiveAvroORCQueryGenerator { /** * Check if the Avro Schema is of type OPTION
* ie . [ null , TYPE ] or [ TYPE , null ]
* @ param schema Avro Schema to check
* @ return Optional Avro Typed data if schema is of type OPTION */
private static Optional < Schema > isOfOptionType ( Schema schema ) { } } | Preconditions . checkNotNull ( schema ) ; // If not of type UNION , cant be an OPTION
if ( ! Schema . Type . UNION . equals ( schema . getType ( ) ) ) { return Optional . < Schema > absent ( ) ; } // If has more than two members , can ' t be an OPTION
List < Schema > types = schema . getTypes ( ) ; if ( null != types && types . size ( ) == 2 ) { Schema first = types . get ( 0 ) ; Schema second = types . get ( 1 ) ; // One member should be of type NULL and other of non NULL type
if ( Schema . Type . NULL . equals ( first . getType ( ) ) && ! Schema . Type . NULL . equals ( second . getType ( ) ) ) { return Optional . of ( second ) ; } else if ( ! Schema . Type . NULL . equals ( first . getType ( ) ) && Schema . Type . NULL . equals ( second . getType ( ) ) ) { return Optional . of ( first ) ; } } return Optional . < Schema > absent ( ) ; |
public class CertificatePathValidator { /** * Here revocation status checking is started from one below the root certificate in the chain ( certChain ) .
* Since ssl implementation ensures that at least one certificate in the chain is trusted ,
* we can logically say that the root is trusted . */
private void init ( X509Certificate [ ] certChainArray ) { } } | X509Certificate [ ] partCertChainArray = new X509Certificate [ certChainArray . length - 1 ] ; System . arraycopy ( certChainArray , 0 , partCertChainArray , 0 , partCertChainArray . length ) ; certChain = Arrays . asList ( partCertChainArray ) ; fullCertChain = Arrays . asList ( certChainArray ) ; |
public class Utils { /** * Sorts the given list using the given comparator . The algorithm is
* stable which means equal elements don ' t get reordered .
* @ throws ClassCastException if any element does not implement { @ code Comparable } ,
* or if { @ code compareTo } throws for any pair of elements . */
@ SuppressWarnings ( "unchecked" ) public static < T > List < T > sorted ( List < T > list , Comparator < ? super T > comparator ) { } } | List < T > result = new ArrayList < > ( list ) ; Collections . sort ( result , comparator ) ; return result ; |
public class ColumnarBatch { /** * Returns an iterator over the rows in this batch . */
public Iterator < InternalRow > rowIterator ( ) { } } | final int maxRows = numRows ; final MutableColumnarRow row = new MutableColumnarRow ( columns ) ; return new Iterator < InternalRow > ( ) { int rowId = 0 ; @ Override public boolean hasNext ( ) { return rowId < maxRows ; } @ Override public InternalRow next ( ) { if ( rowId >= maxRows ) { throw new NoSuchElementException ( ) ; } row . rowId = rowId ++ ; return row ; } @ Override public void remove ( ) { throw new UnsupportedOperationException ( ) ; } } ; |
public class DefaultJiraClient { /** * / / / / / Helper Methods / / / / / */
private ResponseEntity < String > makeRestCall ( String url ) throws HygieiaException { } } | String jiraAccess = featureSettings . getJiraCredentials ( ) ; if ( StringUtils . isEmpty ( jiraAccess ) ) { return restOperations . exchange ( url , HttpMethod . GET , null , String . class ) ; } else { String jiraAccessBase64 = new String ( Base64 . decodeBase64 ( jiraAccess ) ) ; String [ ] parts = jiraAccessBase64 . split ( ":" ) ; if ( parts . length != 2 ) { throw new HygieiaException ( "Invalid Jira credentials" , HygieiaException . INVALID_CONFIGURATION ) ; } return restOperations . exchange ( url , HttpMethod . GET , new HttpEntity < > ( createHeaders ( parts [ 0 ] , parts [ 1 ] ) ) , String . class ) ; } |
public class AuthGUI { /** * Start up AuthzAPI as DME2 Service
* @ param env
* @ param props
* @ throws DME2Exception
* @ throws CadiException */
public void startDME2 ( Properties props ) throws DME2Exception , CadiException { } } | DME2Manager dme2 = new DME2Manager ( "AAF GUI DME2Manager" , props ) ; DME2ServiceHolder svcHolder ; List < DME2ServletHolder > slist = new ArrayList < DME2ServletHolder > ( ) ; svcHolder = new DME2ServiceHolder ( ) ; String serviceName = env . getProperty ( "DMEServiceName" , null ) ; if ( serviceName != null ) { svcHolder . setServiceURI ( serviceName ) ; svcHolder . setManager ( dme2 ) ; svcHolder . setContext ( "/" ) ; DME2ServletHolder srvHolder = new DME2ServletHolder ( this , new String [ ] { "/gui" } ) ; srvHolder . setContextPath ( "/*" ) ; slist . add ( srvHolder ) ; EnumSet < RequestDispatcherType > edlist = EnumSet . of ( RequestDispatcherType . REQUEST , RequestDispatcherType . FORWARD , RequestDispatcherType . ASYNC ) ; // Apply Filters
List < DME2FilterHolder > flist = new ArrayList < DME2FilterHolder > ( ) ; // Secure all GUI interactions with AuthzTransFilter
flist . add ( new DME2FilterHolder ( new AuthzTransFilter ( env , aafCon , new AAFTrustChecker ( env . getProperty ( Config . CADI_TRUST_PROP , Config . CADI_USER_CHAIN ) , Define . ROOT_NS + ".mechid|" + Define . ROOT_COMPANY + "|trust" ) ) , "/gui/*" , edlist ) ) ; // Don ' t need security for display Artifacts or login page
AuthzTransOnlyFilter atof ; flist . add ( new DME2FilterHolder ( atof = new AuthzTransOnlyFilter ( env ) , "/theme/*" , edlist ) ) ; flist . add ( new DME2FilterHolder ( atof , "/js/*" , edlist ) ) ; flist . add ( new DME2FilterHolder ( atof , "/login/*" , edlist ) ) ; svcHolder . setFilters ( flist ) ; svcHolder . setServletHolders ( slist ) ; DME2Server dme2svr = dme2 . getServer ( ) ; // dme2svr . setGracefulShutdownTimeMs ( 1000 ) ;
env . init ( ) . log ( "Starting AAF GUI with Jetty/DME2 server..." ) ; dme2svr . start ( ) ; DME2ServerProperties dsprops = dme2svr . getServerProperties ( ) ; try { // if ( env . getProperty ( " NO _ REGISTER " , null ) ! = null )
dme2 . bindService ( svcHolder ) ; env . init ( ) . log ( "DME2 is available as HTTP" + ( dsprops . isSslEnable ( ) ? "/S" : "" ) , "on port:" , dsprops . getPort ( ) ) ; while ( true ) { // Per DME2 Examples . . .
Thread . sleep ( 5000 ) ; } } catch ( InterruptedException e ) { env . init ( ) . log ( "AAF Jetty Server interrupted!" ) ; } catch ( Exception e ) { // Error binding service doesn ' t seem to stop DME2 or Process
env . init ( ) . log ( e , "DME2 Initialization Error" ) ; dme2svr . stop ( ) ; System . exit ( 1 ) ; } } else { env . init ( ) . log ( "Properties must contain DMEServiceName" ) ; } |
public class TagTypeSet { /** * Gets all of the tags matching the specified type .
* @ param type
* Type of tag .
* @ return All tags of that type or an empty set if none are found . */
@ SuppressWarnings ( "unchecked" ) public < T extends Tag > Set < T > getOfType ( final Class < T > type ) { } } | read . lock ( ) ; try { final Set < T > tagsOfType = ( Set < T > ) tags . get ( type ) ; return tagsOfType != null ? Collections . unmodifiableSet ( tagsOfType ) : Collections . emptySet ( ) ; } finally { read . unlock ( ) ; } |
public class FileOutputCollector { /** * Write to the output collector
* @ param output data to write
* @ exception MapReduceException map reduce exception */
@ Override public void write ( String output ) throws MapReduceException { } } | try { writer . write ( output + DataUtilDefaults . lineTerminator ) ; } catch ( IOException e ) { throw new MapReduceException ( "Failed to write to the output collector" , e ) ; } |
public class AccountClient { /** * Update an entity remotely
* @ param entity
* class
* @ param entity
* id
* @ param entity
* attributes to update
* @ return updated entity
* @ throws AuthenticationException
* @ throws ApiException
* @ throws InvalidRequestException */
public T update ( String entityId , Map < String , Object > hash ) throws AuthenticationException , ApiException , InvalidRequestException { } } | return update ( entityId , hash , getAuthenticatedClient ( ) ) ; |
public class DefaultQueryParamsParser { /** * < strong > Important ! < / strong > Katharsis implementation differs form JSON API
* < a href = " http : / / jsonapi . org / format / # fetching - includes " > definition of includes < / a >
* in order to fit standard query parameter serializing strategy and maximize effective processing of data .
* Included field set params can be send with following format : < br >
* < strong > include [ ResourceType ] = " property ( . property ) * " < / strong > < br >
* Examples of accepted sparse field sets of resources :
* < ul >
* < li > { @ code GET / tasks / ? include [ tasks ] = author } < / li >
* < li > { @ code GET / tasks / ? include [ tasks ] [ ] = author & include [ tasks ] [ ] = comments } < / li >
* < li > { @ code GET / projects / ? include [ projects ] = task & include [ tasks ] = comments } < / li >
* < / ul >
* @ param context Don ' t know , didn ' t write the code
* @ return { @ link TypedParams } Map of sparse field set params passed to a request grouped by type of resource */
protected TypedParams < IncludedRelationsParams > parseIncludedRelationsParameters ( QueryParamsParserContext context ) { } } | String includeKey = RestrictedQueryParamsMembers . include . name ( ) ; Map < String , Set < String > > inclusions = filterQueryParamsByKey ( context , includeKey ) ; Map < String , Set < Inclusion > > temporaryInclusionsMap = new LinkedHashMap < > ( ) ; for ( Map . Entry < String , Set < String > > entry : inclusions . entrySet ( ) ) { List < String > propertyList = buildPropertyListFromEntry ( entry , includeKey ) ; if ( propertyList . size ( ) > 1 ) { throw new ParametersDeserializationException ( "Exceeded maximum level of nesting of 'include' " + "parameter (1)" ) ; } String resourceType = propertyList . get ( 0 ) ; Set < Inclusion > resourceParams ; if ( temporaryInclusionsMap . containsKey ( resourceType ) ) { resourceParams = temporaryInclusionsMap . get ( resourceType ) ; } else { resourceParams = new LinkedHashSet < > ( ) ; } for ( String path : entry . getValue ( ) ) { resourceParams . add ( new Inclusion ( path ) ) ; } temporaryInclusionsMap . put ( resourceType , resourceParams ) ; } Map < String , IncludedRelationsParams > decodedInclusions = new LinkedHashMap < > ( ) ; for ( Map . Entry < String , Set < Inclusion > > resourceTypesMap : temporaryInclusionsMap . entrySet ( ) ) { Set < Inclusion > inclusionSet = Collections . unmodifiableSet ( resourceTypesMap . getValue ( ) ) ; decodedInclusions . put ( resourceTypesMap . getKey ( ) , new IncludedRelationsParams ( inclusionSet ) ) ; } return new TypedParams < > ( Collections . unmodifiableMap ( decodedInclusions ) ) ; |
public class CmsSearchResourcesCollector { /** * Returns a new search parameters object from the request parameters . < p >
* @ param params the parameter map
* @ return a search parameters object */
private CmsSearchParameters getSearchParameters ( Map < String , String > params ) { } } | CmsSearchParameters searchParams = new CmsSearchParameters ( ) ; searchParams . setQuery ( params . get ( PARAM_QUERY ) ) ; if ( CmsStringUtil . isNotEmptyOrWhitespaceOnly ( params . get ( PARAM_SORT ) ) ) { searchParams . setSortName ( params . get ( PARAM_SORT ) ) ; } if ( CmsStringUtil . isNotEmptyOrWhitespaceOnly ( params . get ( PARAM_MINCREATIONDATE ) ) ) { searchParams . setMinDateCreated ( Long . parseLong ( params . get ( PARAM_MINCREATIONDATE ) ) ) ; } if ( CmsStringUtil . isNotEmptyOrWhitespaceOnly ( params . get ( PARAM_MAXCREATIONDATE ) ) ) { searchParams . setMaxDateCreated ( Long . parseLong ( params . get ( PARAM_MAXCREATIONDATE ) ) ) ; } if ( CmsStringUtil . isNotEmptyOrWhitespaceOnly ( params . get ( PARAM_MINLASTMODIFICATIONDATE ) ) ) { searchParams . setMinDateLastModified ( Long . parseLong ( params . get ( PARAM_MINLASTMODIFICATIONDATE ) ) ) ; } if ( CmsStringUtil . isNotEmptyOrWhitespaceOnly ( params . get ( PARAM_MAXLASTMODIFICATIONDATE ) ) ) { searchParams . setMaxDateLastModified ( Long . parseLong ( params . get ( PARAM_MAXLASTMODIFICATIONDATE ) ) ) ; } if ( CmsStringUtil . isNotEmptyOrWhitespaceOnly ( params . get ( PARAM_INDEXNAME ) ) ) { searchParams . setIndex ( params . get ( PARAM_INDEXNAME ) ) ; } List < String > fields = CmsStringUtil . splitAsList ( params . get ( PARAM_FIELDS ) , ',' ) ; searchParams . setFields ( fields ) ; searchParams . setSearchPage ( Integer . parseInt ( params . get ( I_CmsListResourceCollector . PARAM_PAGE ) ) ) ; return searchParams ; |
public class CharacterCaseUtil { /** * Of the characters in the string that have an uppercase form , how many are uppercased ?
* @ param input Input string .
* @ return The fraction of uppercased characters , with { @ code 0.0d } meaning that all uppercasable characters are in
* lowercase and { @ code 1.0d } that all of them are in uppercase . */
public static double fractionOfStringUppercase ( String input ) { } } | if ( input == null ) { return 0 ; } double upperCasableCharacters = 0 ; double upperCount = 0 ; for ( int i = 0 ; i < input . length ( ) ; i ++ ) { char c = input . charAt ( i ) ; char uc = Character . toUpperCase ( c ) ; char lc = Character . toLowerCase ( c ) ; // If both the upper and lowercase version of a character are the same , then the character has
// no distinct uppercase form ( e . g . , a digit or punctuation ) . Ignore these .
if ( c == uc && c == lc ) { continue ; } upperCasableCharacters ++ ; if ( c == uc ) { upperCount ++ ; } } return upperCasableCharacters == 0 ? 0 : upperCount / upperCasableCharacters ; |
public class Template { /** * Reflectively instantiate the package - private { @ code MethodResolutionPhase } enum . */
private static Object newMethodResolutionPhase ( boolean autoboxing ) { } } | for ( Class < ? > c : Resolve . class . getDeclaredClasses ( ) ) { if ( ! c . getName ( ) . equals ( "com.sun.tools.javac.comp.Resolve$MethodResolutionPhase" ) ) { continue ; } for ( Object e : c . getEnumConstants ( ) ) { if ( e . toString ( ) . equals ( autoboxing ? "BOX" : "BASIC" ) ) { return e ; } } } return null ; |
public class ServicesInner { /** * Stop service .
* The services resource is the top - level resource that represents the Data Migration Service . This action stops the service and the service cannot be used for data migration . The service owner won ' t be billed when the service is stopped .
* @ param groupName Name of the resource group
* @ param serviceName Name of the service
* @ throws IllegalArgumentException thrown if parameters fail the validation
* @ return the observable for the request */
public Observable < Void > stopAsync ( String groupName , String serviceName ) { } } | return stopWithServiceResponseAsync ( groupName , serviceName ) . map ( new Func1 < ServiceResponse < Void > , Void > ( ) { @ Override public Void call ( ServiceResponse < Void > response ) { return response . body ( ) ; } } ) ; |
public class GroupOf { /** * Sets this group ' s shear
* @ param offset
* @ return T */
@ Override public C setShear ( final double x , final double y ) { } } | getAttributes ( ) . setShear ( x , y ) ; return cast ( ) ; |
public class xen_hotfix { /** * < pre >
* Use this operation to get xen hotfix .
* < / pre > */
public static xen_hotfix [ ] get ( nitro_service client ) throws Exception { } } | xen_hotfix resource = new xen_hotfix ( ) ; resource . validate ( "get" ) ; return ( xen_hotfix [ ] ) resource . get_resources ( client ) ; |
public class LoggingFraction { /** * Add a new PatternFormatter to this Logger
* @ param name the name of the formatter
* @ param pattern the pattern string
* @ return This fraction . */
public LoggingFraction formatter ( String name , String pattern ) { } } | patternFormatter ( new PatternFormatter ( name ) . pattern ( pattern ) ) ; return this ; |
public class Types { /** * Types that accept precision params in column definition or casts .
* CHAR , VARCHAR and VARCHAR _ IGNORECASE params
* are ignored when the sql . enforce _ strict _ types is false . */
public static boolean acceptsPrecision ( int type ) { } } | switch ( type ) { case Types . SQL_BINARY : case Types . SQL_BIT : case Types . SQL_BIT_VARYING : case Types . SQL_BLOB : case Types . SQL_CHAR : case Types . SQL_NCHAR : case Types . SQL_CLOB : case Types . NCLOB : case Types . SQL_VARBINARY : case Types . SQL_VARCHAR : case Types . SQL_NVARCHAR : case Types . VARCHAR_IGNORECASE : case Types . SQL_DECIMAL : case Types . SQL_NUMERIC : case Types . SQL_FLOAT : case Types . SQL_TIME : case Types . SQL_TIMESTAMP : case Types . SQL_INTERVAL_YEAR : case Types . SQL_INTERVAL_YEAR_TO_MONTH : case Types . SQL_INTERVAL_MONTH : case Types . SQL_INTERVAL_DAY : case Types . SQL_INTERVAL_DAY_TO_HOUR : case Types . SQL_INTERVAL_DAY_TO_MINUTE : case Types . SQL_INTERVAL_DAY_TO_SECOND : case Types . SQL_INTERVAL_HOUR : case Types . SQL_INTERVAL_HOUR_TO_MINUTE : case Types . SQL_INTERVAL_HOUR_TO_SECOND : case Types . SQL_INTERVAL_MINUTE : case Types . SQL_INTERVAL_MINUTE_TO_SECOND : case Types . SQL_INTERVAL_SECOND : case Types . VOLT_GEOGRAPHY : return true ; default : return false ; } |
public class SqlExecutor { /** * 批量执行非查询语句 < br >
* 语句包括 插入 、 更新 、 删除 < br >
* 此方法不会关闭Connection
* @ param conn 数据库连接对象
* @ param sql SQL
* @ param paramsBatch 批量的参数
* @ return 每个SQL执行影响的行数
* @ throws SQLException SQL执行异常 */
public static int [ ] executeBatch ( Connection conn , String sql , Object [ ] ... paramsBatch ) throws SQLException { } } | return executeBatch ( conn , sql , new ArrayIter < Object [ ] > ( paramsBatch ) ) ; |
public class PyExpressionGenerator { /** * Generate the given object .
* @ param block the block expression .
* @ param it the target for the generated content .
* @ param context the context .
* @ return the last expression in the block or { @ code null } . */
protected XExpression _generate ( XBlockExpression block , IAppendable it , IExtraLanguageGeneratorContext context ) { } } | XExpression last = block ; if ( block . getExpressions ( ) . isEmpty ( ) ) { it . append ( "pass" ) ; // $ NON - NLS - 1 $
} else { it . openScope ( ) ; if ( context . getExpectedExpressionType ( ) == null ) { boolean first = true ; for ( final XExpression expression : block . getExpressions ( ) ) { if ( first ) { first = false ; } else { it . newLine ( ) ; } last = generate ( expression , it , context ) ; } } else { final List < XExpression > exprs = block . getExpressions ( ) ; if ( ! exprs . isEmpty ( ) ) { for ( int i = 0 ; i < exprs . size ( ) - 1 ; ++ i ) { if ( i > 0 ) { it . newLine ( ) ; } last = generate ( exprs . get ( i ) , it , context ) ; } last = generate ( exprs . get ( exprs . size ( ) - 1 ) , context . getExpectedExpressionType ( ) , it , context ) ; } } it . closeScope ( ) ; } return last ; |
public class HlsCdnSettingsMarshaller { /** * Marshall the given parameter object . */
public void marshall ( HlsCdnSettings hlsCdnSettings , ProtocolMarshaller protocolMarshaller ) { } } | if ( hlsCdnSettings == null ) { throw new SdkClientException ( "Invalid argument passed to marshall(...)" ) ; } try { protocolMarshaller . marshall ( hlsCdnSettings . getHlsAkamaiSettings ( ) , HLSAKAMAISETTINGS_BINDING ) ; protocolMarshaller . marshall ( hlsCdnSettings . getHlsBasicPutSettings ( ) , HLSBASICPUTSETTINGS_BINDING ) ; protocolMarshaller . marshall ( hlsCdnSettings . getHlsMediaStoreSettings ( ) , HLSMEDIASTORESETTINGS_BINDING ) ; protocolMarshaller . marshall ( hlsCdnSettings . getHlsWebdavSettings ( ) , HLSWEBDAVSETTINGS_BINDING ) ; } catch ( Exception e ) { throw new SdkClientException ( "Unable to marshall request to JSON: " + e . getMessage ( ) , e ) ; } |
public class UriUtils { /** * Uri Encode a Query Fragment .
* @ param query containing the query fragment
* @ param charset to use .
* @ return the encoded query fragment . */
public static String queryEncode ( String query , Charset charset ) { } } | return encodeReserved ( query , FragmentType . QUERY , charset ) ; /* spaces will be encoded as ' plus ' symbols here , we want them pct - encoded */
// return encoded . replaceAll ( " \ \ + " , " % 20 " ) ; |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.