idx int64 0 165k | question stringlengths 73 4.15k | target stringlengths 5 918 | len_question int64 21 890 | len_target int64 3 255 |
|---|---|---|---|---|
11,000 | private void getUploadUrl ( HttpServletRequest req , HttpServletResponse resp ) throws ServletException , IOException { LOGGER . debug ( "Get blobstore upload url" ) ; String callback = req . getParameter ( CALLBACK_PARAM ) ; if ( null == callback ) { callback = req . getRequestURI ( ) ; } String keepQueryParam = req . getParameter ( KEEP_QUERY_PARAM ) ; // Forward any existing query parameters, e.g. access_token if ( null != keepQueryParam ) { final String queryString = req . getQueryString ( ) ; callback = String . format ( "%s?%s" , callback , null != queryString ? queryString : "" ) ; } Map < String , String > response = ImmutableMap . of ( "uploadUrl" , blobstoreService . createUploadUrl ( callback ) ) ; PrintWriter out = resp . getWriter ( ) ; resp . setContentType ( JsonCharacterEncodingResponseFilter . APPLICATION_JSON_UTF8 ) ; ObjectMapper mapper = new ObjectMapper ( ) ; mapper . writeValue ( out , response ) ; out . close ( ) ; } | Get an upload URL | 254 | 4 |
11,001 | private static String getEncodeFileName ( String userAgent , String fileName ) { String encodedFileName = fileName ; try { if ( userAgent . contains ( "MSIE" ) || userAgent . contains ( "Opera" ) ) { encodedFileName = URLEncoder . encode ( fileName , "UTF-8" ) ; } else { encodedFileName = "=?UTF-8?B?" + new String ( BaseEncoding . base64 ( ) . encode ( fileName . getBytes ( "UTF-8" ) ) ) + "?=" ; } } catch ( Exception e ) { LOGGER . error ( e . getMessage ( ) ) ; } return encodedFileName ; } | Encode header value for Content - Disposition | 152 | 9 |
11,002 | Attribute . Compound enterAnnotation ( JCAnnotation a , Type expected , Env < AttrContext > env ) { return enterAnnotation ( a , expected , env , false ) ; } | Process a single compound annotation returning its Attribute . Used from MemberEnter for attaching the attributes to the annotated symbol . | 41 | 24 |
11,003 | private Type getContainingType ( Attribute . Compound currentAnno , DiagnosticPosition pos , boolean reportError ) { Type origAnnoType = currentAnno . type ; TypeSymbol origAnnoDecl = origAnnoType . tsym ; // Fetch the Repeatable annotation from the current // annotation's declaration, or null if it has none Attribute . Compound ca = origAnnoDecl . attribute ( syms . repeatableType . tsym ) ; if ( ca == null ) { // has no Repeatable annotation if ( reportError ) log . error ( pos , "duplicate.annotation.missing.container" , origAnnoType , syms . repeatableType ) ; return null ; } return filterSame ( extractContainingType ( ca , pos , origAnnoDecl ) , origAnnoType ) ; } | Fetches the actual Type that should be the containing annotation . | 180 | 13 |
11,004 | @ Override public String [ ] getSheetNames ( ) { String [ ] ret = null ; if ( sheets != null ) { ret = new String [ sheets . size ( ) ] ; for ( int i = 0 ; i < sheets . size ( ) ; i ++ ) { Sheet sheet = ( Sheet ) sheets . get ( i ) ; ret [ i ] = sheet . getName ( ) ; } } return ret ; } | Returns the list of worksheet names from the given Excel XLSX file . | 90 | 16 |
11,005 | public String getSharedString ( int i ) { String ret = null ; CTRst string = strings . getSi ( ) . get ( i ) ; if ( string != null && string . getT ( ) != null ) ret = string . getT ( ) . getValue ( ) ; if ( ret == null ) // cell has multiple formats or fonts { List < CTRElt > list = string . getR ( ) ; if ( list . size ( ) > 0 ) { for ( CTRElt lt : list ) { String str = lt . getT ( ) . getValue ( ) ; if ( str != null ) { if ( ret == null ) ret = "" ; ret += str ; } } } } return ret ; } | Returns the string at the given index in SharedStrings . xml . | 157 | 14 |
11,006 | public String getFormatCode ( long id ) { if ( numFmts == null ) cacheFormatCodes ( ) ; return ( String ) numFmts . get ( new Long ( id ) ) ; } | Returns the number format code for given id in styles . xml . | 45 | 13 |
11,007 | private void addFormatCode ( CTNumFmt fmt ) { if ( numFmts == null ) numFmts = new HashMap ( ) ; numFmts . put ( fmt . getNumFmtId ( ) , fmt . getFormatCode ( ) ) ; } | Adds the given number format to the cache . | 60 | 9 |
11,008 | private long getFormatId ( String formatCode ) { long ret = 0L ; if ( formatCode != null && formatCode . length ( ) > 0 ) { if ( numFmts != null ) { Iterator it = numFmts . entrySet ( ) . iterator ( ) ; while ( it . hasNext ( ) && ret == 0L ) { java . util . Map . Entry entry = ( java . util . Map . Entry ) it . next ( ) ; Long id = ( Long ) entry . getKey ( ) ; String code = ( String ) entry . getValue ( ) ; if ( code != null && code . equals ( formatCode ) ) ret = id . longValue ( ) ; } } // If not found, also search // the built-in formats if ( ret == 0L ) { Long l = ( Long ) builtinNumFmts . get ( formatCode ) ; if ( l != null ) ret = l . longValue ( ) ; } // If still not found, // create a new format if ( ret == 0L ) { CTNumFmts numFmts = stylesheet . getNumFmts ( ) ; if ( numFmts == null ) { numFmts = new CTNumFmts ( ) ; stylesheet . setNumFmts ( numFmts ) ; } List list = numFmts . getNumFmt ( ) ; CTNumFmt numFmt = new CTNumFmt ( ) ; numFmt . setNumFmtId ( getMaxNumFmtId ( ) + 1 ) ; numFmt . setFormatCode ( formatCode ) ; list . add ( numFmt ) ; numFmts . setCount ( ( long ) list . size ( ) ) ; addFormatCode ( numFmt ) ; ret = numFmt . getNumFmtId ( ) ; } } return ret ; } | Returns the id for the given number format from the cache . | 409 | 12 |
11,009 | private long getMaxNumFmtId ( ) { long ret = 163 ; List list = stylesheet . getNumFmts ( ) . getNumFmt ( ) ; for ( int i = 0 ; i < list . size ( ) ; i ++ ) { CTNumFmt numFmt = ( CTNumFmt ) list . get ( i ) ; if ( numFmt . getNumFmtId ( ) > ret ) ret = numFmt . getNumFmtId ( ) ; } return ret ; } | Returns the maximum numFmtId in styles . xml . | 112 | 12 |
11,010 | void setSize ( int x , int y , int z ) { this . sizeX = x ; this . sizeY = y ; this . sizeZ = z ; } | Set the size of this plan | 36 | 6 |
11,011 | public static Object invoke ( Object source , String methodName , Class < ? > [ ] parameterTypes , Object [ ] parameterValues ) throws MethodException { Class < ? extends Object > clazz = source . getClass ( ) ; Method method ; if ( ArrayUtils . isEmpty ( parameterTypes ) ) { method = findMethod ( clazz , methodName , EMPTY_PARAMETER_CLASSTYPES ) ; return invoke ( source , method , EMPTY_PARAMETER_VALUES ) ; } method = findMethod ( clazz , methodName , parameterTypes ) ; return invoke ( source , method , parameterValues ) ; } | Invokes method which name equals given method name and parameter types equals given parameter types on the given source with the given parameters . | 137 | 25 |
11,012 | public static Object invoke ( Object source , Method method , Object [ ] parameterValues ) throws MethodException { try { return method . invoke ( source , parameterValues ) ; } catch ( Exception e ) { throw new MethodException ( INVOKE_METHOD_FAILED , e ) ; } } | Invokes given method on the given source object with the specified parameters . | 61 | 14 |
11,013 | public void add ( Collection < ApplicationHost > applicationHosts ) { for ( ApplicationHost applicationHost : applicationHosts ) this . applicationHosts . put ( applicationHost . getId ( ) , applicationHost ) ; } | Adds the application host list to the application hosts for the account . | 46 | 13 |
11,014 | public ApplicationInstanceCache applicationInstances ( long applicationHostId ) { ApplicationInstanceCache cache = applicationInstances . get ( applicationHostId ) ; if ( cache == null ) applicationInstances . put ( applicationHostId , cache = new ApplicationInstanceCache ( applicationHostId ) ) ; return cache ; } | Returns the cache of application instances for the given application host creating one if it doesn t exist . | 63 | 19 |
11,015 | public void addApplicationInstances ( Collection < ApplicationInstance > applicationInstances ) { for ( ApplicationInstance applicationInstance : applicationInstances ) { // Add the instance to any application hosts it is associated with long applicationHostId = applicationInstance . getLinks ( ) . getApplicationHost ( ) ; ApplicationHost applicationHost = applicationHosts . get ( applicationHostId ) ; if ( applicationHost != null ) applicationInstances ( applicationHostId ) . add ( applicationInstance ) ; else logger . severe ( String . format ( "Unable to find application host for application instance '%s': %d" , applicationInstance . getName ( ) , applicationHostId ) ) ; } } | Adds the application instances to the applications for the account . | 141 | 11 |
11,016 | public static ClassReader instance ( Context context ) { ClassReader instance = context . get ( classReaderKey ) ; if ( instance == null ) instance = new ClassReader ( context , true ) ; return instance ; } | Get the ClassReader instance for this invocation . | 44 | 9 |
11,017 | private void init ( Symtab syms , boolean definitive ) { if ( classes != null ) return ; if ( definitive ) { Assert . check ( packages == null || packages == syms . packages ) ; packages = syms . packages ; Assert . check ( classes == null || classes == syms . classes ) ; classes = syms . classes ; } else { packages = new HashMap < Name , PackageSymbol > ( ) ; classes = new HashMap < Name , ClassSymbol > ( ) ; } packages . put ( names . empty , syms . rootPackage ) ; syms . rootPackage . completer = thisCompleter ; syms . unnamedPackage . completer = thisCompleter ; } | Initialize classes and packages optionally treating this as the definitive classreader . | 152 | 14 |
11,018 | private void readClassFile ( ClassSymbol c ) throws IOException { int magic = nextInt ( ) ; if ( magic != JAVA_MAGIC ) throw badClassFile ( "illegal.start.of.class.file" ) ; minorVersion = nextChar ( ) ; majorVersion = nextChar ( ) ; int maxMajor = Target . MAX ( ) . majorVersion ; int maxMinor = Target . MAX ( ) . minorVersion ; if ( majorVersion > maxMajor || majorVersion * 1000 + minorVersion < Target . MIN ( ) . majorVersion * 1000 + Target . MIN ( ) . minorVersion ) { if ( majorVersion == ( maxMajor + 1 ) ) log . warning ( "big.major.version" , currentClassFile , majorVersion , maxMajor ) ; else throw badClassFile ( "wrong.version" , Integer . toString ( majorVersion ) , Integer . toString ( minorVersion ) , Integer . toString ( maxMajor ) , Integer . toString ( maxMinor ) ) ; } else if ( checkClassFile && majorVersion == maxMajor && minorVersion > maxMinor ) { printCCF ( "found.later.version" , Integer . toString ( minorVersion ) ) ; } indexPool ( ) ; if ( signatureBuffer . length < bp ) { int ns = Integer . highestOneBit ( bp ) << 1 ; signatureBuffer = new byte [ ns ] ; } readClass ( c ) ; } | Read a class file . | 307 | 5 |
11,019 | public PackageSymbol enterPackage ( Name name , PackageSymbol owner ) { return enterPackage ( TypeSymbol . formFullName ( name , owner ) ) ; } | Make a package given its unqualified name and enclosing package . | 35 | 13 |
11,020 | public void shutdown ( ) { interrupt ( ) ; try { join ( ) ; } catch ( Exception x ) { _logger . log ( Level . WARNING , "Failed to see DaySchedule thread joining" , x ) ; } } | Shuts down the DaySchedule thread . | 50 | 9 |
11,021 | @ Override public void contextInitialized ( ServletContextEvent sce ) { Gig . bootstrap ( sce . getServletContext ( ) ) ; Jaguar . assemble ( this ) ; } | Bootstraps Gig application in web environment . | 40 | 9 |
11,022 | protected DocumentType upsertType ( String reference , String name , ExecutionContext executionContext ) { DocumentType documentType = documentTypeRepository . findByReference ( reference ) ; if ( documentType != null ) { documentType . setName ( name ) ; } else { documentType = documentTypeRepository . create ( reference , name ) ; } return executionContext . addResult ( this , documentType ) ; } | convenience as templates and types often created together | 86 | 10 |
11,023 | public static Socket getCurrentSocket ( ) { ConnectionHandler handler = connectionMap . get ( Thread . currentThread ( ) ) ; return ( handler == null ? null : handler . getSocket ( ) ) ; } | Get the current Socket for this call . Only works in the main thread call . | 43 | 16 |
11,024 | public void prepareParameter ( Map < String , Object > extra ) { if ( from != null ) { from . prepareParameter ( extra ) ; } } | Prepares the parameter s datasource passing it the extra options and if necessary executing the appropriate code and caching the value . | 31 | 24 |
11,025 | public void process ( ) { try { Enumeration < URL > urls = Thread . currentThread ( ) . getContextClassLoader ( ) . getResources ( "META-INF/persistence.xml" ) ; XMLInputFactory factory = XMLInputFactory . newInstance ( ) ; List < String > persistenceUnits = new ArrayList < String > ( ) ; while ( urls . hasMoreElements ( ) ) { URL url = urls . nextElement ( ) ; XMLStreamReader reader = factory . createXMLStreamReader ( url . openStream ( ) ) ; while ( reader . hasNext ( ) ) { if ( reader . next ( ) == XMLStreamConstants . START_ELEMENT && reader . getName ( ) . getLocalPart ( ) . equals ( "persistence-unit" ) ) { for ( int i = 0 ; i < reader . getAttributeCount ( ) ; i ++ ) { if ( reader . getAttributeLocalName ( i ) . equals ( "name" ) ) { persistenceUnits . add ( reader . getAttributeValue ( i ) ) ; break ; } } } } } this . persistenceUnits = persistenceUnits ; } catch ( Exception e ) { logger . error ( "Failed to parse persistence.xml" , e ) ; } } | Parses persistence . xml files on the current ClassLoader s search path entries and detects persistence unit declarations from them . | 277 | 24 |
11,026 | public static InputStream getInputStreamFromHttp ( String httpFileURL ) throws IOException { URLConnection urlConnection = null ; urlConnection = new URL ( httpFileURL ) . openConnection ( ) ; urlConnection . connect ( ) ; return urlConnection . getInputStream ( ) ; } | Get destination web file input stream . | 60 | 7 |
11,027 | public static byte [ ] getBytesFromHttp ( String httpFileURL ) throws IOException { InputStream bufferedInputStream = null ; try { bufferedInputStream = getInputStreamFromHttp ( httpFileURL ) ; ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream ( ) ; byte [ ] buffer = new byte [ BUFFER_SIZE ] ; for ( int len = 0 ; ( len = bufferedInputStream . read ( buffer ) ) != - 1 ; ) { byteArrayOutputStream . write ( buffer , 0 , len ) ; } byte [ ] arrayOfByte1 = byteArrayOutputStream . toByteArray ( ) ; return arrayOfByte1 ; } finally { if ( bufferedInputStream != null ) bufferedInputStream . close ( ) ; } } | Get destination web file bytes . | 166 | 6 |
11,028 | public static < T > Link < T > make ( Link < T > root , T object ) { Link < T > link = new Link <> ( object ) ; if ( root == null ) { root = link ; } else if ( root . last == null ) { root . next = link ; } else { root . last . next = link ; } root . last = link ; return root ; } | Adds a new object at the end of the list identified by the root link . | 85 | 16 |
11,029 | boolean foundGroupFormat ( Map < String , ? > map , String pkgFormat ) { if ( map . containsKey ( pkgFormat ) ) { configuration . message . error ( "doclet.Same_package_name_used" , pkgFormat ) ; return true ; } return false ; } | Search if the given map has given the package format . | 65 | 11 |
11,030 | public Map < String , List < PackageDoc > > groupPackages ( PackageDoc [ ] packages ) { Map < String , List < PackageDoc > > groupPackageMap = new HashMap < String , List < PackageDoc > > ( ) ; String defaultGroupName = ( pkgNameGroupMap . isEmpty ( ) && regExpGroupMap . isEmpty ( ) ) ? configuration . message . getText ( "doclet.Packages" ) : configuration . message . getText ( "doclet.Other_Packages" ) ; // if the user has not used the default group name, add it if ( ! groupList . contains ( defaultGroupName ) ) { groupList . add ( defaultGroupName ) ; } for ( int i = 0 ; i < packages . length ; i ++ ) { PackageDoc pkg = packages [ i ] ; String pkgName = pkg . name ( ) ; String groupName = pkgNameGroupMap . get ( pkgName ) ; // if this package is not explicitly assigned to a group, // try matching it to group specified by regular expression if ( groupName == null ) { groupName = regExpGroupName ( pkgName ) ; } // if it is in neither group map, put it in the default // group if ( groupName == null ) { groupName = defaultGroupName ; } getPkgList ( groupPackageMap , groupName ) . add ( pkg ) ; } return groupPackageMap ; } | Group the packages according the grouping information provided on the command line . Given a list of packages search each package name in regular expression map as well as package name map to get the corresponding group name . Create another map with mapping of group name to the package list which will fall under the specified group . If any package doesen t belong to any specified group on the comamnd line then a new group named Other Packages will be created for it . If there are no groups found in other words if - group option is not at all used then all the packages will be grouped under group Packages . | 310 | 120 |
11,031 | String regExpGroupName ( String pkgName ) { for ( int j = 0 ; j < sortedRegExpList . size ( ) ; j ++ ) { String regexp = sortedRegExpList . get ( j ) ; if ( pkgName . startsWith ( regexp ) ) { return regExpGroupMap . get ( regexp ) ; } } return null ; } | Search for package name in the sorted regular expression list if found return the group name . If not return null . | 80 | 22 |
11,032 | @ SuppressWarnings ( "unchecked" ) public Map marshal ( Contract contract ) throws RpcException { Map map = new HashMap ( ) ; map . put ( "jsonrpc" , "2.0" ) ; if ( id != null ) map . put ( "id" , id ) ; map . put ( "method" , method . getMethod ( ) ) ; if ( params != null && params . length > 0 ) { Function f = contract . getFunction ( getIface ( ) , getFunc ( ) ) ; map . put ( "params" , f . marshalParams ( this ) ) ; } return map ; } | Marshals this request to a Map that can be serialized and sent over the wire . Uses the Contract to resolve the Function associated with the method . | 142 | 30 |
11,033 | public void init ( ) { int numProcessors = Runtime . getRuntime ( ) . availableProcessors ( ) ; cacheRedisClientPools = CacheBuilder . newBuilder ( ) . concurrencyLevel ( numProcessors ) . expireAfterAccess ( 3600 , TimeUnit . SECONDS ) . removalListener ( new RemovalListener < String , JedisClientPool > ( ) { @ Override public void onRemoval ( RemovalNotification < String , JedisClientPool > notification ) { JedisClientPool pool = notification . getValue ( ) ; pool . destroy ( ) ; } } ) . build ( ) ; } | Initializes the factory . | 131 | 5 |
11,034 | protected static String calcRedisPoolName ( String host , int port , String username , String password , PoolConfig poolConfig ) { StringBuilder sb = new StringBuilder ( ) ; sb . append ( host != null ? host : "NULL" ) ; sb . append ( "." ) ; sb . append ( port ) ; sb . append ( "." ) ; sb . append ( username != null ? username : "NULL" ) ; sb . append ( "." ) ; int passwordHashcode = password != null ? password . hashCode ( ) : "NULL" . hashCode ( ) ; int poolHashcode = poolConfig != null ? poolConfig . hashCode ( ) : "NULL" . hashCode ( ) ; return sb . append ( passwordHashcode ) . append ( "." ) . append ( poolHashcode ) . toString ( ) ; } | Builds a unique pool name from configurations . | 187 | 9 |
11,035 | private static Pattern importStringToPattern ( String s , Processor p , Log log ) { if ( isValidImportString ( s ) ) { return validImportStringToPattern ( s ) ; } else { log . warning ( "proc.malformed.supported.string" , s , p . getClass ( ) . getName ( ) ) ; return noMatches ; // won't match any valid identifier } } | Convert import - style string for supported annotations into a regex matching that string . If the string is a valid import - style string return a regex that won t match anything . | 86 | 35 |
11,036 | public AbstractBuilder getProfileSummaryBuilder ( Profile profile , Profile prevProfile , Profile nextProfile ) throws Exception { return ProfileSummaryBuilder . getInstance ( context , profile , writerFactory . getProfileSummaryWriter ( profile , prevProfile , nextProfile ) ) ; } | Return the builder that builds the profile summary . | 53 | 9 |
11,037 | public AbstractBuilder getProfilePackageSummaryBuilder ( PackageDoc pkg , PackageDoc prevPkg , PackageDoc nextPkg , Profile profile ) throws Exception { return ProfilePackageSummaryBuilder . getInstance ( context , pkg , writerFactory . getProfilePackageSummaryWriter ( pkg , prevPkg , nextPkg , profile ) , profile ) ; } | Return the builder that builds the profile package summary . | 73 | 10 |
11,038 | private Content getInheritedTagletOutput ( boolean isNonTypeParams , Doc holder , TagletWriter writer , Object [ ] formalParameters , Set < String > alreadyDocumented ) { Content result = writer . getOutputInstance ( ) ; if ( ( ! alreadyDocumented . contains ( null ) ) && holder instanceof MethodDoc ) { for ( int i = 0 ; i < formalParameters . length ; i ++ ) { if ( alreadyDocumented . contains ( String . valueOf ( i ) ) ) { continue ; } //This parameter does not have any @param documentation. //Try to inherit it. DocFinder . Output inheritedDoc = DocFinder . search ( new DocFinder . Input ( ( MethodDoc ) holder , this , String . valueOf ( i ) , ! isNonTypeParams ) ) ; if ( inheritedDoc . inlineTags != null && inheritedDoc . inlineTags . length > 0 ) { result . addContent ( processParamTag ( isNonTypeParams , writer , ( ParamTag ) inheritedDoc . holderTag , isNonTypeParams ? ( ( Parameter ) formalParameters [ i ] ) . name ( ) : ( ( TypeVariable ) formalParameters [ i ] ) . typeName ( ) , alreadyDocumented . size ( ) == 0 ) ) ; } alreadyDocumented . add ( String . valueOf ( i ) ) ; } } return result ; } | Loop through each indivitual parameter . It it does not have a corresponding param tag try to inherit it . | 295 | 22 |
11,039 | @ Override public void observe ( int age ) throws InterruptedException { if ( System . currentTimeMillis ( ) >= _limit ) { throw new InterruptedException ( "Time{" + System . currentTimeMillis ( ) + "}HasPassed{" + _limit + ' ' ) ; } } | Checks the current system time against the time limit throwing an InterruptedException if the time is up . | 65 | 21 |
11,040 | private < S extends Symbol > S nameToSymbol ( String nameStr , Class < S > clazz ) { Name name = names . fromString ( nameStr ) ; // First check cache. Symbol sym = ( clazz == ClassSymbol . class ) ? syms . classes . get ( name ) : syms . packages . get ( name ) ; try { if ( sym == null ) sym = javaCompiler . resolveIdent ( nameStr ) ; sym . complete ( ) ; return ( sym . kind != Kinds . ERR && sym . exists ( ) && clazz . isInstance ( sym ) && name . equals ( sym . getQualifiedName ( ) ) ) ? clazz . cast ( sym ) : null ; } catch ( CompletionFailure e ) { return null ; } } | Returns a symbol given the type s or packages s canonical name or null if the name isn t found . | 168 | 21 |
11,041 | public static String leftPad ( String text , String padding , int linesToIgnore ) { StringBuilder result = new StringBuilder ( ) ; Matcher matcher = LINE_START_PATTERN . matcher ( text ) ; while ( matcher . find ( ) ) { if ( linesToIgnore > 0 ) { linesToIgnore -- ; } else { result . append ( padding ) ; } result . append ( matcher . group ( ) ) . append ( "\n" ) ; } return result . toString ( ) ; } | Inserts the specified string at the beginning of each newline of the specified text . | 115 | 17 |
11,042 | public static Predicate < Class < ? > > classOrAncestorAnnotatedWith ( final Class < ? extends Annotation > annotationClass , boolean includeMetaAnnotations ) { return candidate -> candidate != null && Classes . from ( candidate ) . traversingSuperclasses ( ) . traversingInterfaces ( ) . classes ( ) . anyMatch ( elementAnnotatedWith ( annotationClass , includeMetaAnnotations ) ) ; } | Checks if the candidate or one of its superclasses or interfaces is annotated with the specified annotation . | 90 | 21 |
11,043 | public static Predicate < Annotation > annotationIsOfClass ( final Class < ? extends Annotation > annotationClass ) { return candidate -> candidate != null && candidate . annotationType ( ) . equals ( annotationClass ) ; } | Checks if the candidate annotation is of the specified annotation class . | 46 | 13 |
11,044 | public static Predicate < Class < ? > > atLeastOneFieldAnnotatedWith ( final Class < ? extends Annotation > annotationClass , boolean includeMetaAnnotations ) { return candidate -> candidate != null && Classes . from ( candidate ) . traversingSuperclasses ( ) . fields ( ) . anyMatch ( elementAnnotatedWith ( annotationClass , includeMetaAnnotations ) ) ; } | Checks if the candidate or one of its superclasses has at least one field annotated or meta - annotated by the given annotation . | 83 | 28 |
11,045 | public static Predicate < Class < ? > > atLeastOneMethodAnnotatedWith ( final Class < ? extends Annotation > annotationClass , boolean includeMetaAnnotations ) { return candidate -> Classes . from ( candidate ) . traversingInterfaces ( ) . traversingSuperclasses ( ) . methods ( ) . anyMatch ( elementAnnotatedWith ( annotationClass , includeMetaAnnotations ) ) ; } | Checks if the candidate or one of its superclasses or interfaces has at least one method annotated or meta - annotated by the given annotation . | 86 | 30 |
11,046 | public static boolean isValidVATIN ( @ Nonnull final String sVATIN , final boolean bIfNoValidator ) { ValueEnforcer . notNull ( sVATIN , "VATIN" ) ; if ( sVATIN . length ( ) > 2 ) { final String sCountryCode = sVATIN . substring ( 0 , 2 ) . toUpperCase ( Locale . US ) ; final IToBooleanFunction < String > aValidator = s_aMap . get ( sCountryCode ) ; if ( aValidator != null ) return aValidator . applyAsBoolean ( sVATIN . substring ( 2 ) ) ; } // No validator return bIfNoValidator ; } | Check if the provided VATIN is valid . This method handles VATINs for all countries . This check uses only the checksum algorithm and does not call any webservice etc . | 159 | 37 |
11,047 | public static boolean isValidatorPresent ( @ Nonnull final String sVATIN ) { ValueEnforcer . notNull ( sVATIN , "VATIN" ) ; if ( sVATIN . length ( ) <= 2 ) return false ; final String sCountryCode = sVATIN . substring ( 0 , 2 ) . toUpperCase ( Locale . US ) ; return s_aMap . containsKey ( sCountryCode ) ; } | Check if a validator is present for the provided VATIN . | 99 | 13 |
11,048 | public void printFramesetDocument ( String title , boolean noTimeStamp , Content frameset ) throws IOException { Content htmlDocType = DocType . FRAMESET ; Content htmlComment = new Comment ( configuration . getText ( "doclet.New_Page" ) ) ; Content head = new HtmlTree ( HtmlTag . HEAD ) ; head . addContent ( getGeneratedBy ( ! noTimeStamp ) ) ; if ( configuration . charset . length ( ) > 0 ) { Content meta = HtmlTree . META ( "Content-Type" , CONTENT_TYPE , configuration . charset ) ; head . addContent ( meta ) ; } Content windowTitle = HtmlTree . TITLE ( new StringContent ( title ) ) ; head . addContent ( windowTitle ) ; head . addContent ( getFramesetJavaScript ( ) ) ; Content htmlTree = HtmlTree . HTML ( configuration . getLocale ( ) . getLanguage ( ) , head , frameset ) ; Content htmlDocument = new HtmlDocument ( htmlDocType , htmlComment , htmlTree ) ; write ( htmlDocument ) ; } | Print the frameset version of the Html file header . Called only when generating an HTML frameset file . | 240 | 22 |
11,049 | private void skip ( boolean stopAtImport , boolean stopAtMemberDecl , boolean stopAtIdentifier , boolean stopAtStatement ) { while ( true ) { switch ( token . kind ) { case SEMI : nextToken ( ) ; return ; case PUBLIC : case FINAL : case ABSTRACT : case MONKEYS_AT : case EOF : case CLASS : case INTERFACE : case ENUM : return ; case IMPORT : if ( stopAtImport ) return ; break ; case LBRACE : case RBRACE : case PRIVATE : case PROTECTED : case STATIC : case TRANSIENT : case NATIVE : case VOLATILE : case SYNCHRONIZED : case STRICTFP : case LT : case BYTE : case SHORT : case CHAR : case INT : case LONG : case FLOAT : case DOUBLE : case BOOLEAN : case VOID : if ( stopAtMemberDecl ) return ; break ; case UNDERSCORE : case IDENTIFIER : if ( stopAtIdentifier ) return ; break ; case CASE : case DEFAULT : case IF : case FOR : case WHILE : case DO : case TRY : case SWITCH : case RETURN : case THROW : case BREAK : case CONTINUE : case ELSE : case FINALLY : case CATCH : if ( stopAtStatement ) return ; break ; } nextToken ( ) ; } } | Skip forward until a suitable stop token is found . | 299 | 10 |
11,050 | void checkNoMods ( long mods ) { if ( mods != 0 ) { long lowestMod = mods & - mods ; error ( token . pos , "mod.not.allowed.here" , Flags . asFlagSet ( lowestMod ) ) ; } } | Diagnose a modifier flag from the set if any . | 54 | 12 |
11,051 | void attach ( JCTree tree , Comment dc ) { if ( keepDocComments && dc != null ) { // System.out.println("doc comment = ");System.out.println(dc);//DEBUG docComments . putComment ( tree , dc ) ; } } | Make an entry into docComments hashtable provided flag keepDocComments is set and given doc comment is non - null . | 58 | 24 |
11,052 | List < JCStatement > forInit ( ) { ListBuffer < JCStatement > stats = new ListBuffer <> ( ) ; int pos = token . pos ; if ( token . kind == FINAL || token . kind == MONKEYS_AT ) { return variableDeclarators ( optFinal ( 0 ) , parseType ( ) , stats ) . toList ( ) ; } else { JCExpression t = term ( EXPR | TYPE ) ; if ( ( lastmode & TYPE ) != 0 && LAX_IDENTIFIER . accepts ( token . kind ) ) { return variableDeclarators ( mods ( pos , 0 , List . < JCAnnotation > nil ( ) ) , t , stats ) . toList ( ) ; } else if ( ( lastmode & TYPE ) != 0 && token . kind == COLON ) { error ( pos , "bad.initializer" , "for-loop" ) ; return List . of ( ( JCStatement ) F . at ( pos ) . VarDef ( null , null , t , null ) ) ; } else { return moreStatementExpressions ( pos , t , stats ) . toList ( ) ; } } } | ForInit = StatementExpression MoreStatementExpressions | { FINAL | | 245 | 14 |
11,053 | protected JCTree resource ( ) { JCModifiers optFinal = optFinal ( Flags . FINAL ) ; JCExpression type = parseType ( ) ; int pos = token . pos ; Name ident = ident ( ) ; return variableDeclaratorRest ( pos , optFinal , type , ident , true , null ) ; } | Resource = VariableModifiersOpt Type VariableDeclaratorId = Expression | 68 | 14 |
11,054 | public final void run ( ) { _interrupted = null ; _age = 0 ; while ( true ) { try { _strategy . observe ( _age ) ; if ( _preparation != null ) _preparation . run ( ) ; _result = execute ( ) ; if ( _age > 0 ) { _reporting . emit ( Level . INFO , "Failure recovered: " + toString ( ) , _age , _logger ) ; } break ; } catch ( InterruptedException x ) { _logger . log ( Level . WARNING , "Interrupted, age = " + _age , x ) ; _interrupted = x ; break ; } catch ( Exception x ) { _reporting . emit ( x , "Failure detected, age = " + _age , _age , _logger ) ; try { _strategy . backoff ( _age ) ; } catch ( InterruptedException i ) { _logger . log ( Level . WARNING , "Interrupted, age = " + _age , x ) ; _interrupted = i ; break ; } ++ _age ; } } } | Task entry point . | 232 | 4 |
11,055 | protected void loadReport ( ReportsConfig result , File report , String reportId ) throws IOException { if ( report . isDirectory ( ) ) { FilenameFilter configYamlFilter = new PatternFilenameFilter ( "^reportconf.(yaml|json)$" ) ; File [ ] selectYaml = report . listFiles ( configYamlFilter ) ; if ( selectYaml != null && selectYaml . length == 1 ) { File selectedYaml = selectYaml [ 0 ] ; loadReport ( result , FileUtils . openInputStream ( selectedYaml ) , reportId ) ; } } } | Custom separate dload report component so it can be called elsewhere or overwritten by child Providers . Checks the report to ensure it is a directory then looks for reportconf . yaml or reportconf . json inside the file . If it exists loads it . | 129 | 52 |
11,056 | @ SuppressWarnings ( "unchecked" ) public Map toMap ( ) { HashMap map = new HashMap ( ) ; map . put ( "code" , code ) ; map . put ( "message" , message ) ; if ( data != null ) map . put ( "data" , data ) ; return map ; } | Used to marshal this exception to a Map suiteable for serialization to JSON | 72 | 16 |
11,057 | public boolean lint ( String s ) { // return true if either the specific option is enabled, or // they are all enabled without the specific one being // disabled return isSet ( XLINT_CUSTOM , s ) || ( isSet ( XLINT ) || isSet ( XLINT_CUSTOM , "all" ) ) && isUnset ( XLINT_CUSTOM , "-" + s ) ; } | Check for a lint suboption . | 89 | 8 |
11,058 | @ POST @ Path ( "refresh" ) @ Consumes ( MediaType . APPLICATION_JSON ) public Response refreshAccessToken ( RefreshTokenRequest refreshToken ) { // Perform all validation here to control the exact error message returned to comply with the Oauth2 standard if ( null == refreshToken . getRefresh_token ( ) || null == refreshToken . getGrant_type ( ) ) { throw new BadRequestRestException ( ImmutableMap . of ( "error" , "invalid_request" ) ) ; } if ( ! REFRESH_TOKEN_GRANT_TYPE . equals ( refreshToken . getGrant_type ( ) ) ) { // Unsupported grant type throw new BadRequestRestException ( ImmutableMap . of ( "error" , "unsupported_grant_type" ) ) ; } DConnection connection = connectionDao . findByRefreshToken ( refreshToken . getRefresh_token ( ) ) ; if ( null == connection ) { throw new BadRequestRestException ( ImmutableMap . of ( "error" , "invalid_grant" ) ) ; } // Invalidate the old cache key connectionDao . invalidateCacheKey ( connection . getAccessToken ( ) ) ; connection . setAccessToken ( accessTokenGenerator . generate ( ) ) ; connection . setExpireTime ( calculateExpirationDate ( tokenExpiresIn ) ) ; connectionDao . putWithCacheKey ( connection . getAccessToken ( ) , connection ) ; return Response . ok ( ImmutableMap . builder ( ) . put ( "access_token" , connection . getAccessToken ( ) ) . put ( "refresh_token" , connection . getRefreshToken ( ) ) . put ( "expires_in" , tokenExpiresIn ) . build ( ) ) . cookie ( createCookie ( connection . getAccessToken ( ) , tokenExpiresIn ) ) . build ( ) ; } | Refresh an access_token using the refresh token | 410 | 10 |
11,059 | @ GET @ Path ( "tokeninfo" ) public Response validate ( @ QueryParam ( "access_token" ) String access_token ) { checkNotNull ( access_token ) ; DConnection connection = connectionDao . findByAccessToken ( access_token ) ; LOGGER . debug ( "Connection {}" , connection ) ; if ( null == connection || hasAccessTokenExpired ( connection ) ) { throw new BadRequestRestException ( "Invalid access_token" ) ; } return Response . ok ( ImmutableMap . builder ( ) . put ( "user_id" , connection . getUserId ( ) ) . put ( "expires_in" , Seconds . secondsBetween ( DateTime . now ( ) , new DateTime ( connection . getExpireTime ( ) ) ) . getSeconds ( ) ) . build ( ) ) . build ( ) ; } | Validate an access_token . The Oauth2 specification does not specify how this should be done . Do similar to what Google does | 185 | 27 |
11,060 | @ GET @ Path ( "logout" ) public Response logout ( ) throws URISyntaxException { return Response . temporaryRedirect ( new URI ( "/" ) ) . cookie ( createCookie ( null , 0 ) ) . build ( ) ; } | Remove cookie from the user agent . | 55 | 7 |
11,061 | public static Output search ( Input input ) { Output output = new Output ( ) ; if ( input . isInheritDocTag ) { //Do nothing because "element" does not have any documentation. //All it has it {@inheritDoc}. } else if ( input . taglet == null ) { //We want overall documentation. output . inlineTags = input . isFirstSentence ? input . element . firstSentenceTags ( ) : input . element . inlineTags ( ) ; output . holder = input . element ; } else { input . taglet . inherit ( input , output ) ; } if ( output . inlineTags != null && output . inlineTags . length > 0 ) { return output ; } output . isValidInheritDocTag = false ; Input inheritedSearchInput = input . copy ( ) ; inheritedSearchInput . isInheritDocTag = false ; if ( input . element instanceof MethodDoc ) { MethodDoc overriddenMethod = ( ( MethodDoc ) input . element ) . overriddenMethod ( ) ; if ( overriddenMethod != null ) { inheritedSearchInput . element = overriddenMethod ; output = search ( inheritedSearchInput ) ; output . isValidInheritDocTag = true ; if ( output . inlineTags . length > 0 ) { return output ; } } //NOTE: When we fix the bug where ClassDoc.interfaceTypes() does // not pass all implemented interfaces, we will use the // appropriate element here. MethodDoc [ ] implementedMethods = ( new ImplementedMethods ( ( MethodDoc ) input . element , null ) ) . build ( false ) ; for ( int i = 0 ; i < implementedMethods . length ; i ++ ) { inheritedSearchInput . element = implementedMethods [ i ] ; output = search ( inheritedSearchInput ) ; output . isValidInheritDocTag = true ; if ( output . inlineTags . length > 0 ) { return output ; } } } else if ( input . element instanceof ClassDoc ) { ProgramElementDoc superclass = ( ( ClassDoc ) input . element ) . superclass ( ) ; if ( superclass != null ) { inheritedSearchInput . element = superclass ; output = search ( inheritedSearchInput ) ; output . isValidInheritDocTag = true ; if ( output . inlineTags . length > 0 ) { return output ; } } } return output ; } | Search for the requested comments in the given element . If it does not have comments return documentation from the overriden element if possible . If the overriden element does not exist or does not have documentation to inherit search for documentation to inherit from implemented methods . | 502 | 52 |
11,062 | public void init ( ServletConfig config ) throws ServletException { try { String idlPath = config . getInitParameter ( "idl" ) ; if ( idlPath == null ) { throw new ServletException ( "idl init param is required. Set to path to .json file, or classpath:/mycontract.json" ) ; } if ( idlPath . startsWith ( "classpath:" ) ) { idlPath = idlPath . substring ( 10 ) ; contract = Contract . load ( getClass ( ) . getResourceAsStream ( idlPath ) ) ; } else { contract = Contract . load ( new File ( idlPath ) ) ; } server = new Server ( contract ) ; int handlerCount = 0 ; Enumeration params = config . getInitParameterNames ( ) ; while ( params . hasMoreElements ( ) ) { String key = params . nextElement ( ) . toString ( ) ; if ( key . indexOf ( "handler." ) == 0 ) { String val = config . getInitParameter ( key ) ; int pos = val . indexOf ( "=" ) ; if ( pos == - 1 ) { throw new ServletException ( "Invalid init param: key=" + key + " value=" + val + " -- should be: interfaceClass=implClass" ) ; } String ifaceCname = val . substring ( 0 , pos ) ; String implCname = val . substring ( pos + 1 ) ; Class ifaceClazz = Class . forName ( ifaceCname ) ; Class implClazz = Class . forName ( implCname ) ; server . addHandler ( ifaceClazz , implClazz . newInstance ( ) ) ; handlerCount ++ ; } } if ( handlerCount == 0 ) { throw new ServletException ( "At least one handler.x init property is required" ) ; } } catch ( ServletException e ) { throw e ; } catch ( Exception e ) { throw new ServletException ( e ) ; } } | Initializes the servlet based on the init parameters in web . xml | 433 | 14 |
11,063 | public Content getTargetProfilePackageLink ( PackageDoc pd , String target , Content label , String profileName ) { return getHyperLink ( pathString ( pd , DocPaths . profilePackageSummary ( profileName ) ) , label , "" , target ) ; } | Get Profile Package link with target frame . | 56 | 8 |
11,064 | public Content getTargetProfileLink ( String target , Content label , String profileName ) { return getHyperLink ( pathToRoot . resolve ( DocPaths . profileSummary ( profileName ) ) , label , "" , target ) ; } | Get Profile link with target frame . | 49 | 7 |
11,065 | public String getTypeNameForProfile ( ClassDoc cd ) { StringBuilder typeName = new StringBuilder ( ( cd . containingPackage ( ) ) . name ( ) . replace ( "." , "/" ) ) ; typeName . append ( "/" ) . append ( cd . name ( ) . replace ( "." , "$" ) ) ; return typeName . toString ( ) ; } | Get the type name for profile search . | 82 | 8 |
11,066 | public boolean isTypeInProfile ( ClassDoc cd , int profileValue ) { return ( configuration . profiles . getProfile ( getTypeNameForProfile ( cd ) ) <= profileValue ) ; } | Check if a type belongs to a profile . | 40 | 9 |
11,067 | public void addBottom ( Content body ) { Content bottom = new RawHtml ( replaceDocRootDir ( configuration . bottom ) ) ; Content small = HtmlTree . SMALL ( bottom ) ; Content p = HtmlTree . P ( HtmlStyle . legalCopy , small ) ; body . addContent ( p ) ; } | Adds the user specified bottom . | 69 | 6 |
11,068 | protected void addPackageDeprecatedAPI ( List < Doc > deprPkgs , String headingKey , String tableSummary , String [ ] tableHeader , Content contentTree ) { if ( deprPkgs . size ( ) > 0 ) { Content table = HtmlTree . TABLE ( HtmlStyle . deprecatedSummary , 0 , 3 , 0 , tableSummary , getTableCaption ( configuration . getResource ( headingKey ) ) ) ; table . addContent ( getSummaryTableHeader ( tableHeader , "col" ) ) ; Content tbody = new HtmlTree ( HtmlTag . TBODY ) ; for ( int i = 0 ; i < deprPkgs . size ( ) ; i ++ ) { PackageDoc pkg = ( PackageDoc ) deprPkgs . get ( i ) ; HtmlTree td = HtmlTree . TD ( HtmlStyle . colOne , getPackageLink ( pkg , getPackageName ( pkg ) ) ) ; if ( pkg . tags ( "deprecated" ) . length > 0 ) { addInlineDeprecatedComment ( pkg , pkg . tags ( "deprecated" ) [ 0 ] , td ) ; } HtmlTree tr = HtmlTree . TR ( td ) ; if ( i % 2 == 0 ) { tr . addStyle ( HtmlStyle . altColor ) ; } else { tr . addStyle ( HtmlStyle . rowColor ) ; } tbody . addContent ( tr ) ; } table . addContent ( tbody ) ; Content li = HtmlTree . LI ( HtmlStyle . blockList , table ) ; Content ul = HtmlTree . UL ( HtmlStyle . blockList , li ) ; contentTree . addContent ( ul ) ; } } | Add package deprecation information to the documentation tree | 374 | 10 |
11,069 | public HtmlTree getScriptProperties ( ) { HtmlTree script = HtmlTree . SCRIPT ( "text/javascript" , pathToRoot . resolve ( DocPaths . JAVASCRIPT ) . getPath ( ) ) ; return script ; } | Returns a link to the JavaScript file . | 56 | 8 |
11,070 | private boolean addAnnotationInfo ( int indent , Doc doc , AnnotationDesc [ ] descList , boolean lineBreak , Content htmltree ) { List < Content > annotations = getAnnotations ( indent , descList , lineBreak ) ; String sep = "" ; if ( annotations . isEmpty ( ) ) { return false ; } for ( Content annotation : annotations ) { htmltree . addContent ( sep ) ; htmltree . addContent ( annotation ) ; sep = " " ; } return true ; } | Adds the annotation types for the given doc . | 110 | 9 |
11,071 | public static ApruveResponse < Payment > get ( String paymentRequestId , String paymentId ) { return ApruveClient . getInstance ( ) . get ( getPaymentsPath ( paymentRequestId ) + paymentId , Payment . class ) ; } | Fetches the Payment with the given ID from Apruve . | 53 | 14 |
11,072 | public static ApruveResponse < List < Payment > > getAll ( String paymentRequestId ) { return ApruveClient . getInstance ( ) . index ( getPaymentsPath ( paymentRequestId ) , new GenericType < List < Payment > > ( ) { } ) ; } | Fetches all Payments belonging to the PaymentRequest with the specified ID . | 60 | 15 |
11,073 | public void init ( ) { Dictionary < String , String > properties = getConfigurationProperties ( this . getProperties ( ) , false ) ; this . setProperties ( properties ) ; this . setProperty ( BundleConstants . SERVICE_PID , getServicePid ( ) ) ; this . setProperty ( BundleConstants . SERVICE_CLASS , getServiceClassName ( ) ) ; } | Setup the application properties . Override this to set the properties . | 83 | 13 |
11,074 | public void start ( BundleContext context ) throws Exception { ClassServiceUtility . log ( context , LogService . LOG_INFO , "Starting " + this . getClass ( ) . getName ( ) + " Bundle" ) ; this . context = context ; this . init ( ) ; // Setup the properties String interfaceClassName = getInterfaceClassName ( ) ; this . setProperty ( BundleConstants . ACTIVATOR , this . getClass ( ) . getName ( ) ) ; // In case I have to find this service by activator class try { context . addServiceListener ( this , ClassServiceUtility . addToFilter ( ( String ) null , Constants . OBJECTCLASS , interfaceClassName ) ) ; } catch ( InvalidSyntaxException e ) { e . printStackTrace ( ) ; } if ( service == null ) { boolean allStarted = this . checkDependentServices ( context ) ; if ( allStarted ) { service = this . startupService ( context ) ; this . registerService ( service ) ; } } } | Bundle starting up . Don t override this override startupService . | 225 | 13 |
11,075 | public void stop ( BundleContext context ) throws Exception { ClassServiceUtility . log ( context , LogService . LOG_INFO , "Stopping " + this . getClass ( ) . getName ( ) + " Bundle" ) ; if ( this . shutdownService ( service , context ) ) service = null ; // Unregisters automatically this . context = null ; } | Bundle stopping . Don t override this override shutdownService . | 77 | 12 |
11,076 | public void registerService ( Object service ) { this . setService ( service ) ; String serviceClass = getInterfaceClassName ( ) ; if ( service != null ) serviceRegistration = context . registerService ( serviceClass , this . service , properties ) ; } | Get the service for this implementation class . | 53 | 8 |
11,077 | public Object getService ( String interfaceClassName , String serviceClassName , String versionRange , Dictionary < String , String > filter ) { return ClassServiceUtility . getClassService ( ) . getClassFinder ( context ) . getClassBundleService ( interfaceClassName , serviceClassName , versionRange , filter , - 1 ) ; } | Convenience method to get the service for this implementation class . | 72 | 13 |
11,078 | public String getServicePid ( ) { String servicePid = context . getProperty ( BundleConstants . SERVICE_PID ) ; if ( servicePid != null ) return servicePid ; servicePid = this . getServiceClassName ( ) ; if ( servicePid == null ) servicePid = this . getClass ( ) . getName ( ) ; return ClassFinderActivator . getPackageName ( servicePid , false ) ; } | The service key in the config admin system . | 98 | 9 |
11,079 | public static Dictionary < String , String > putAll ( Dictionary < String , String > sourceDictionary , Dictionary < String , String > destDictionary ) { if ( destDictionary == null ) destDictionary = new Hashtable < String , String > ( ) ; if ( sourceDictionary != null ) { Enumeration < String > keys = sourceDictionary . keys ( ) ; while ( keys . hasMoreElements ( ) ) { String key = keys . nextElement ( ) ; destDictionary . put ( key , sourceDictionary . get ( key ) ) ; } } return destDictionary ; } | Copy all the values from one dictionary to another . | 128 | 10 |
11,080 | public static < T > T getFirstNotNullValue ( final Collection < T > collection ) { if ( isNotEmpty ( collection ) ) { for ( T element : collection ) { if ( element != null ) { return element ; } } } return null ; } | Returns the first not null element if the collection is not null and have not null value else return null . | 55 | 21 |
11,081 | public static < T > List < T > toList ( final Collection < T > collection ) { if ( isEmpty ( collection ) ) { return new ArrayList < T > ( 0 ) ; } else { return new ArrayList < T > ( collection ) ; } } | Convert given collection to a list . | 56 | 8 |
11,082 | public static < T > Set < T > toSet ( final Collection < T > collection ) { if ( isEmpty ( collection ) ) { return new HashSet < T > ( 0 ) ; } else { return new HashSet < T > ( collection ) ; } } | Convert given collection to a set . | 56 | 8 |
11,083 | public static < T > T [ ] toArray ( final Collection < T > collection ) { T next = getFirstNotNullValue ( collection ) ; if ( next != null ) { Object [ ] objects = collection . toArray ( ) ; @ SuppressWarnings ( "unchecked" ) T [ ] convertedObjects = ( T [ ] ) Array . newInstance ( next . getClass ( ) , objects . length ) ; System . arraycopy ( objects , 0 , convertedObjects , 0 , objects . length ) ; return convertedObjects ; } else { return null ; } } | Convert given collection to an array . | 124 | 8 |
11,084 | public void setMappings ( List < String > mappings ) { if ( mappings . size ( ) > 0 ) { @ SuppressWarnings ( "unchecked" ) Pair < String , String > [ ] renames = ( Pair < String , String > [ ] ) Array . newInstance ( Pair . class , mappings . size ( ) ) ; for ( int i = 0 ; i < _renames . length ; ++ i ) { String [ ] names = mappings . get ( i ) . split ( "[ ,]+" ) ; renames [ i ] = new Pair < String , String > ( names [ 0 ] , names [ 1 ] ) ; } _renames = renames ; } } | Defines parameter mappings . One parameter can be mapped to multiple new names so a list is used instead of a map as the input to this method . | 151 | 31 |
11,085 | @ Nullable @ ReturnsMutableCopy public static ICommonsNavigableSet < EContinent > getContinentsOfCountry ( @ Nullable final Locale aLocale ) { final Locale aCountry = CountryCache . getInstance ( ) . getCountry ( aLocale ) ; if ( aCountry != null ) { final ICommonsNavigableSet < EContinent > ret = s_aMap . get ( aCountry ) ; if ( ret != null ) return ret . getClone ( ) ; } return null ; } | Get all continents for the specified country ID | 115 | 8 |
11,086 | public boolean isLoadable ( ) { if ( getPayload ( ) instanceof NullPayload ) { return false ; } try { InputStream is = getInputStream ( ) ; try { is . read ( ) ; return true ; } finally { is . close ( ) ; } } catch ( IOException ex ) { return false ; } } | Tests whether the Cargo s payload is loadable . | 72 | 11 |
11,087 | public String loadString ( String encoding ) throws IOException { byte [ ] bytes = loadByteArray ( ) ; ByteOrderMask bom = ByteOrderMask . valueOf ( bytes ) ; if ( bom != null ) { int offset = ( bom . getBytes ( ) ) . length ; return new String ( bytes , offset , bytes . length - offset , bom . getEncoding ( ) ) ; } return new String ( bytes , encoding ) ; } | Loads the string in the user specified character encoding . | 93 | 11 |
11,088 | public Result transfer ( long count ) { if ( count < 0L ) throw new IllegalArgumentException ( "negative count" ) ; return buffer == null ? transferNoBuffer ( count ) : transferBuffered ( count ) ; } | Transfers the specified number of bytes from the source to the target . Fewer bytes may be transferred if an end - of - stream condition occurs in either the source or the target . | 48 | 38 |
11,089 | public static TreePath getPath ( TreePath path , Tree target ) { path . getClass ( ) ; target . getClass ( ) ; class Result extends Error { static final long serialVersionUID = - 5942088234594905625L ; TreePath path ; Result ( TreePath path ) { this . path = path ; } } class PathFinder extends TreePathScanner < TreePath , Tree > { public TreePath scan ( Tree tree , Tree target ) { if ( tree == target ) { throw new Result ( new TreePath ( getCurrentPath ( ) , target ) ) ; } return super . scan ( tree , target ) ; } } if ( path . getLeaf ( ) == target ) { return path ; } try { new PathFinder ( ) . scan ( path , target ) ; } catch ( Result result ) { return result . path ; } return null ; } | Gets a tree path for a tree node within a subtree identified by a TreePath object . | 188 | 20 |
11,090 | public Reifier addTypeSet ( Class < ? > spec ) { for ( Field field : spec . getDeclaredFields ( ) ) { if ( Modifier . isPublic ( field . getModifiers ( ) ) ) { String name = field . getName ( ) ; try { _named . put ( name , new Validator ( name , field . getType ( ) , field ) ) ; } catch ( IllegalArgumentException x ) { Trace . g . std . note ( Reifier . class , "Ignored " + name + ": " + x . getMessage ( ) ) ; } } else { Trace . g . std . note ( Reifier . class , "Ignored non-public field: " + field . getName ( ) ) ; } } return this ; } | Adds a set of data type specifications . | 167 | 8 |
11,091 | public < T extends DataObject > T collect ( T data , Map < String , String > binder ) throws SecurityException , DataValidationException { return collect ( data , binder , null ) ; } | Populates a data object by collecting and validating the named values from a Map< ; String String> ; . | 43 | 25 |
11,092 | public static boolean localeSupportsCurrencyRetrieval ( @ Nullable final Locale aLocale ) { return aLocale != null && aLocale . getCountry ( ) != null && aLocale . getCountry ( ) . length ( ) == 2 ; } | Check if a currency could be available for the given locale . | 57 | 12 |
11,093 | @ Nullable public static BigDecimal parseCurrency ( @ Nullable final String sStr , @ Nonnull final DecimalFormat aFormat , @ Nullable final BigDecimal aDefault , @ Nonnull final RoundingMode eRoundingMode ) { // Shortcut if ( StringHelper . hasNoText ( sStr ) ) return aDefault ; // So that the call to "parse" returns a BigDecimal aFormat . setParseBigDecimal ( true ) ; aFormat . setRoundingMode ( eRoundingMode ) ; // Parse as double final BigDecimal aNum = LocaleParser . parseBigDecimal ( sStr , aFormat ) ; if ( aNum == null ) return aDefault ; // And finally do the correct scaling, depending of the decimal format // fraction return aNum . setScale ( aFormat . getMaximumFractionDigits ( ) , eRoundingMode ) ; } | Parse a currency value from string using a custom rounding mode . | 194 | 13 |
11,094 | @ Nullable private static String _getTextValueForDecimalSeparator ( @ Nullable final String sTextValue , @ Nonnull final EDecimalSeparator eDecimalSep , @ Nonnull final EGroupingSeparator eGroupingSep ) { ValueEnforcer . notNull ( eDecimalSep , "DecimalSeparator" ) ; ValueEnforcer . notNull ( eGroupingSep , "GroupingSeparator" ) ; final String ret = StringHelper . trim ( sTextValue ) ; // Replace only, if the desired decimal separator is not present if ( ret != null && ret . indexOf ( eDecimalSep . getChar ( ) ) < 0 ) switch ( eDecimalSep ) { case COMMA : { // Decimal separator is a "," if ( ret . indexOf ( ' ' ) > - 1 && eGroupingSep . getChar ( ) != ' ' ) { // Currency expects "," but user passed "." return StringHelper . replaceAll ( ret , ' ' , eDecimalSep . getChar ( ) ) ; } break ; } case POINT : { // Decimal separator is a "." if ( ret . indexOf ( ' ' ) > - 1 && eGroupingSep . getChar ( ) != ' ' ) { // Pattern contains no "," but value contains "," return StringHelper . replaceAll ( ret , ' ' , eDecimalSep . getChar ( ) ) ; } break ; } default : throw new IllegalStateException ( "Unexpected decimal separator [" + eDecimalSep + "]" ) ; } return ret ; } | Adopt the passed text value according to the requested decimal separator . | 347 | 14 |
11,095 | public static void setRoundingMode ( @ Nullable final ECurrency eCurrency , @ Nullable final RoundingMode eRoundingMode ) { getSettings ( eCurrency ) . setRoundingMode ( eRoundingMode ) ; } | Change the rounding mode of this currency . | 51 | 8 |
11,096 | public List < Symbol > functionalInterfaceBridges ( TypeSymbol origin ) { Assert . check ( isFunctionalInterface ( origin ) ) ; Symbol descSym = findDescriptorSymbol ( origin ) ; CompoundScope members = membersClosure ( origin . type , false ) ; ListBuffer < Symbol > overridden = new ListBuffer <> ( ) ; outer : for ( Symbol m2 : members . getElementsByName ( descSym . name , bridgeFilter ) ) { if ( m2 == descSym ) continue ; else if ( descSym . overrides ( m2 , origin , Types . this , false ) ) { for ( Symbol m3 : overridden ) { if ( isSameType ( m3 . erasure ( Types . this ) , m2 . erasure ( Types . this ) ) || ( m3 . overrides ( m2 , origin , Types . this , false ) && ( pendingBridges ( ( ClassSymbol ) origin , m3 . enclClass ( ) ) || ( ( ( MethodSymbol ) m2 ) . binaryImplementation ( ( ClassSymbol ) m3 . owner , Types . this ) != null ) ) ) ) { continue outer ; } } overridden . add ( m2 ) ; } } return overridden . toList ( ) ; } | Find the minimal set of methods that are overridden by the functional descriptor in origin . All returned methods are assumed to have different erased signatures . | 274 | 28 |
11,097 | public boolean isEqualityComparable ( Type s , Type t , Warner warn ) { if ( t . isNumeric ( ) && s . isNumeric ( ) ) return true ; boolean tPrimitive = t . isPrimitive ( ) ; boolean sPrimitive = s . isPrimitive ( ) ; if ( ! tPrimitive && ! sPrimitive ) { return isCastable ( s , t , warn ) || isCastable ( t , s , warn ) ; } else { return false ; } } | Can t and s be compared for equality? Any primitive == primitive or primitive == object comparisons here are an error . Unboxing and correct primitive == primitive comparisons are already dealt with in Attr . visitBinary . | 109 | 43 |
11,098 | public Type elemtype ( Type t ) { switch ( t . getTag ( ) ) { case WILDCARD : return elemtype ( wildUpperBound ( t ) ) ; case ARRAY : t = t . unannotatedType ( ) ; return ( ( ArrayType ) t ) . elemtype ; case FORALL : return elemtype ( ( ( ForAll ) t ) . qtype ) ; case ERROR : return t ; default : return null ; } } | The element type of an array . | 102 | 7 |
11,099 | public int rank ( Type t ) { t = t . unannotatedType ( ) ; switch ( t . getTag ( ) ) { case CLASS : { ClassType cls = ( ClassType ) t ; if ( cls . rank_field < 0 ) { Name fullname = cls . tsym . getQualifiedName ( ) ; if ( fullname == names . java_lang_Object ) cls . rank_field = 0 ; else { int r = rank ( supertype ( cls ) ) ; for ( List < Type > l = interfaces ( cls ) ; l . nonEmpty ( ) ; l = l . tail ) { if ( rank ( l . head ) > r ) r = rank ( l . head ) ; } cls . rank_field = r + 1 ; } } return cls . rank_field ; } case TYPEVAR : { TypeVar tvar = ( TypeVar ) t ; if ( tvar . rank_field < 0 ) { int r = rank ( supertype ( tvar ) ) ; for ( List < Type > l = interfaces ( tvar ) ; l . nonEmpty ( ) ; l = l . tail ) { if ( rank ( l . head ) > r ) r = rank ( l . head ) ; } tvar . rank_field = r + 1 ; } return tvar . rank_field ; } case ERROR : case NONE : return 0 ; default : throw new AssertionError ( ) ; } } | The rank of a class is the length of the longest path between the class and java . lang . Object in the class inheritance graph . Undefined for all but reference types . | 316 | 35 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.