idx
int64
0
165k
question
stringlengths
73
5.81k
target
stringlengths
5
918
11,000
public static List < Player > loadPlayers ( List < String > playersFiles ) throws PlayerException { log . info ( "[loadPlayers] Loading all players" ) ; List < Player > players = new ArrayList < > ( ) ; if ( playersFiles . size ( ) < 1 ) { log . warn ( "[loadPlayers] No players to load" ) ; } for ( String singlePath : playersFiles ) { Player single = new Player ( new File ( singlePath ) ) ; players . add ( single ) ; } return players ; }
Creates a list of players using the paths provided
11,001
public void add ( Collection < Dashboard > dashboards ) { for ( Dashboard dashboard : dashboards ) this . dashboards . put ( dashboard . getId ( ) , dashboard ) ; }
Adds the dashboard list to the dashboards for the account .
11,002
public synchronized void write ( final Event event ) throws IOException { if ( ! acceptsEvents ) { log . warn ( "Writer not ready, discarding event: {}" , event ) ; return ; } delegate . write ( event ) ; uncommittedWriteCount ++ ; commitIfNeeded ( ) ; }
Write an Event via the delegate writer
11,003
@ Managed ( description = "Commit locally spooled events for flushing" ) public synchronized void forceCommit ( ) throws IOException { log . debug ( "Performing commit on delegate EventWriter [{}]" , delegate . getClass ( ) ) ; delegate . commit ( ) ; uncommittedWriteCount = 0 ; lastCommitNanos = getNow ( ) ; }
Perform a commit via the delegate writer
11,004
public OptionalFunction < T , R > orElse ( Supplier < R > supplier ) { return new OptionalFunction < > ( function , supplier ) ; }
Creates a new OptionalFunction that will use the given function for null values .
11,005
public OptionalFunction < T , R > orElseThrow ( Supplier < ? extends RuntimeException > exceptionSupplier ) { return new OptionalFunction < > ( this . function , ( ) -> { throw exceptionSupplier . get ( ) ; } ) ; }
Creates a new OptionalFunction that will throw the exception supplied by the given supplier for null values .
11,006
public static TimeZone getTimeZone ( String name ) { TimeZone ret = null ; if ( timezones != null ) { for ( int i = 0 ; i < timezones . length && ret == null ; i ++ ) { if ( timezones [ i ] . getName ( ) . equals ( name ) ) ret = timezones [ i ] . getTimeZone ( ) ; } } return ret ; }
Returns the cached timezone with the given name .
11,007
public static TimeZone getTimeZoneById ( String id ) { TimeZone ret = null ; if ( timezones != null ) { for ( int i = 0 ; i < timezones . length && ret == null ; i ++ ) { if ( timezones [ i ] . getId ( ) . equals ( id ) ) ret = timezones [ i ] . getTimeZone ( ) ; } } return ret ; }
Returns the cached timezone with the given ID .
11,008
public static TimeZone getTimeZoneByIdIgnoreCase ( String id ) { TimeZone ret = null ; if ( timezones != null ) { id = id . toLowerCase ( ) ; for ( int i = 0 ; i < timezones . length && ret == null ; i ++ ) { if ( timezones [ i ] . getId ( ) . toLowerCase ( ) . equals ( id ) ) ret = timezones [ i ] . getTimeZone ( ) ; } } return ret ; }
Returns the cached timezone with the given ID ignoring case .
11,009
private String getDisplayName ( ) { long hours = TimeUnit . MILLISECONDS . toHours ( tz . getRawOffset ( ) ) ; long minutes = Math . abs ( TimeUnit . MILLISECONDS . toMinutes ( tz . getRawOffset ( ) ) - TimeUnit . HOURS . toMinutes ( hours ) ) ; return String . format ( "(GMT%+d:%02d) %s" , hours , minutes , tz . getID ( ) ) ; }
Returns the display name of the timezone .
11,010
public void report ( DiagnosticPosition pos , String msg , Object ... args ) { JavaFileObject currentSource = log . currentSourceFile ( ) ; if ( verbose ) { if ( sourcesWithReportedWarnings == null ) sourcesWithReportedWarnings = new HashSet < JavaFileObject > ( ) ; if ( log . nwarnings < log . MaxWarnings ) { logMandatoryWarning ( pos , msg , args ) ; sourcesWithReportedWarnings . add ( currentSource ) ; } else if ( deferredDiagnosticKind == null ) { if ( sourcesWithReportedWarnings . contains ( currentSource ) ) { deferredDiagnosticKind = DeferredDiagnosticKind . ADDITIONAL_IN_FILE ; } else { deferredDiagnosticKind = DeferredDiagnosticKind . IN_FILE ; } deferredDiagnosticSource = currentSource ; deferredDiagnosticArg = currentSource ; } else if ( ( deferredDiagnosticKind == DeferredDiagnosticKind . IN_FILE || deferredDiagnosticKind == DeferredDiagnosticKind . ADDITIONAL_IN_FILE ) && ! equal ( deferredDiagnosticSource , currentSource ) ) { deferredDiagnosticKind = DeferredDiagnosticKind . ADDITIONAL_IN_FILES ; deferredDiagnosticArg = null ; } } else { if ( deferredDiagnosticKind == null ) { deferredDiagnosticKind = DeferredDiagnosticKind . IN_FILE ; deferredDiagnosticSource = currentSource ; deferredDiagnosticArg = currentSource ; } else if ( deferredDiagnosticKind == DeferredDiagnosticKind . IN_FILE && ! equal ( deferredDiagnosticSource , currentSource ) ) { deferredDiagnosticKind = DeferredDiagnosticKind . IN_FILES ; deferredDiagnosticArg = null ; } } }
Report a mandatory warning .
11,011
public static long combineInts ( String high , String low ) throws NumberFormatException { int highInt = Integer . parseInt ( high ) ; int lowInt = Integer . parseInt ( low ) ; return ( ( long ) highInt << 32 ) + ( lowInt & 0x00000000FFFFFFFFL ) ; }
Combine two numbers that represent the high and low bits of a 64 - bit number .
11,012
public static Pair < String , String > splitLong ( long value ) { return Pair . of ( String . valueOf ( ( int ) ( value >> 32 ) ) , String . valueOf ( ( int ) value ) ) ; }
Split a single 64 bit number into integers representing the high and low 32 bits .
11,013
public static void sendExpectOk ( SocketManager socketManager , String message ) throws IOException { expectOk ( socketManager . sendAndWait ( message ) ) ; }
Send a message via the given socket manager which should always receive a case insensitive OK as the reply .
11,014
public static void expectOk ( String response ) throws ProtocolException { if ( ! "OK" . equalsIgnoreCase ( response ) ) { throw new ProtocolException ( response , Direction . RECEIVE ) ; } }
Check the response for an OK message . Throw an exception if response is not expected .
11,015
public void printError ( SourcePosition pos , String msg ) { if ( diagListener != null ) { report ( DiagnosticType . ERROR , pos , msg ) ; return ; } if ( nerrors < MaxErrors ) { String prefix = ( pos == null ) ? programName : pos . toString ( ) ; errWriter . println ( prefix + ": " + getText ( "javadoc.error" ) + " - " + msg ) ; errWriter . flush ( ) ; prompt ( ) ; nerrors ++ ; } }
Print error message increment error count . Part of DocErrorReporter .
11,016
public Object unmarshal ( Object map ) throws RpcException { return unmarshal ( getTypeClass ( ) , map , this . s , this . isOptional ) ; }
Converts o from a Map back to the Java Class associated with this Struct . Recursively unmarshals all the members of the map .
11,017
@ SuppressWarnings ( "unchecked" ) public Object marshal ( Object o ) throws RpcException { if ( o == null ) { return returnNullIfOptional ( ) ; } else if ( o instanceof BStruct ) { return validateMap ( structToMap ( o , this . s ) , this . s ) ; } else if ( o instanceof Map ) { return validateMap ( ( Map ) o , this . s ) ; } else { String msg = "Unable to convert class: " + o . getClass ( ) . getName ( ) ; throw RpcException . Error . INVALID_RESP . exc ( msg ) ; } }
Marshals native Java type o to a Map that can be serialized . Recursively marshals all of the Struct fields from o onto the map .
11,018
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 ) ; 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
11,019
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
11,020
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 .
11,021
private Type getContainingType ( Attribute . Compound currentAnno , DiagnosticPosition pos , boolean reportError ) { Type origAnnoType = currentAnno . type ; TypeSymbol origAnnoDecl = origAnnoType . tsym ; Attribute . Compound ca = origAnnoDecl . attribute ( syms . repeatableType . tsym ) ; if ( ca == null ) { 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 .
11,022
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 .
11,023
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 ) { 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 .
11,024
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 .
11,025
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 .
11,026
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 ( ret == 0L ) { Long l = ( Long ) builtinNumFmts . get ( formatCode ) ; if ( l != null ) ret = l . longValue ( ) ; } 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 .
11,027
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 .
11,028
void setSize ( int x , int y , int z ) { this . sizeX = x ; this . sizeY = y ; this . sizeZ = z ; }
Set the size of this plan
11,029
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 .
11,030
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 .
11,031
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 .
11,032
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 .
11,033
public void addApplicationInstances ( Collection < ApplicationInstance > applicationInstances ) { for ( ApplicationInstance applicationInstance : applicationInstances ) { 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 .
11,034
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 .
11,035
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 .
11,036
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 .
11,037
public PackageSymbol enterPackage ( Name name , PackageSymbol owner ) { return enterPackage ( TypeSymbol . formFullName ( name , owner ) ) ; }
Make a package given its unqualified name and enclosing package .
11,038
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 .
11,039
public void contextInitialized ( ServletContextEvent sce ) { Gig . bootstrap ( sce . getServletContext ( ) ) ; Jaguar . assemble ( this ) ; }
Bootstraps Gig application in web environment .
11,040
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
11,041
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 .
11,042
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 .
11,043
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 .
11,044
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 .
11,045
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 .
11,046
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 .
11,047
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 .
11,048
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 ( ! 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 ( groupName == null ) { groupName = regExpGroupName ( pkgName ) ; } 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 .
11,049
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 .
11,050
@ 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 .
11,051
public void init ( ) { int numProcessors = Runtime . getRuntime ( ) . availableProcessors ( ) ; cacheRedisClientPools = CacheBuilder . newBuilder ( ) . concurrencyLevel ( numProcessors ) . expireAfterAccess ( 3600 , TimeUnit . SECONDS ) . removalListener ( new RemovalListener < String , JedisClientPool > ( ) { public void onRemoval ( RemovalNotification < String , JedisClientPool > notification ) { JedisClientPool pool = notification . getValue ( ) ; pool . destroy ( ) ; } } ) . build ( ) ; }
Initializes the factory .
11,052
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 .
11,053
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 ; } }
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 .
11,054
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 .
11,055
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 .
11,056
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 ; } 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 .
11,057
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 .
11,058
private < S extends Symbol > S nameToSymbol ( String nameStr , Class < S > clazz ) { Name name = names . fromString ( nameStr ) ; 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 .
11,059
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 .
11,060
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 .
11,061
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 .
11,062
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 .
11,063
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 .
11,064
public static boolean isValidVATIN ( 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 ) ) ; } 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 .
11,065
public static boolean isValidatorPresent ( 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 .
11,066
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 .
11,067
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 .
11,068
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 .
11,069
void attach ( JCTree tree , Comment dc ) { if ( keepDocComments && dc != null ) { docComments . putComment ( tree , dc ) ; } }
Make an entry into docComments hashtable provided flag keepDocComments is set and given doc comment is non - null .
11,070
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 |
11,071
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
11,072
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 .
11,073
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 .
11,074
@ 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
11,075
public boolean lint ( String s ) { return isSet ( XLINT_CUSTOM , s ) || ( isSet ( XLINT ) || isSet ( XLINT_CUSTOM , "all" ) ) && isUnset ( XLINT_CUSTOM , "-" + s ) ; }
Check for a lint suboption .
11,076
@ Path ( "refresh" ) @ Consumes ( MediaType . APPLICATION_JSON ) public Response refreshAccessToken ( RefreshTokenRequest refreshToken ) { 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 ( ) ) ) { 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" ) ) ; } 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
11,077
@ 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
11,078
@ Path ( "logout" ) public Response logout ( ) throws URISyntaxException { return Response . temporaryRedirect ( new URI ( "/" ) ) . cookie ( createCookie ( null , 0 ) ) . build ( ) ; }
Remove cookie from the user agent .
11,079
public static Output search ( Input input ) { Output output = new Output ( ) ; if ( input . isInheritDocTag ) { } else if ( input . taglet == null ) { 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 ; } } 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 .
11,080
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
11,081
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 .
11,082
public Content getTargetProfileLink ( String target , Content label , String profileName ) { return getHyperLink ( pathToRoot . resolve ( DocPaths . profileSummary ( profileName ) ) , label , "" , target ) ; }
Get Profile link with target frame .
11,083
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 .
11,084
public boolean isTypeInProfile ( ClassDoc cd , int profileValue ) { return ( configuration . profiles . getProfile ( getTypeNameForProfile ( cd ) ) <= profileValue ) ; }
Check if a type belongs to a profile .
11,085
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 .
11,086
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
11,087
public HtmlTree getScriptProperties ( ) { HtmlTree script = HtmlTree . SCRIPT ( "text/javascript" , pathToRoot . resolve ( DocPaths . JAVASCRIPT ) . getPath ( ) ) ; return script ; }
Returns a link to the JavaScript file .
11,088
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 .
11,089
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 .
11,090
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 .
11,091
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 .
11,092
public void start ( BundleContext context ) throws Exception { ClassServiceUtility . log ( context , LogService . LOG_INFO , "Starting " + this . getClass ( ) . getName ( ) + " Bundle" ) ; this . context = context ; this . init ( ) ; String interfaceClassName = getInterfaceClassName ( ) ; this . setProperty ( BundleConstants . ACTIVATOR , this . getClass ( ) . getName ( ) ) ; 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 .
11,093
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 ; this . context = null ; }
Bundle stopping . Don t override this override shutdownService .
11,094
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 .
11,095
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 .
11,096
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 .
11,097
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 .
11,098
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 .
11,099
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 .