idx
int64
0
41.2k
question
stringlengths
74
4.21k
target
stringlengths
5
888
22,500
public FillOptions withLatLngs ( List < List < LatLng > > latLngs ) { List < List < Point > > points = new ArrayList < > ( ) ; for ( List < LatLng > innerLatLngs : latLngs ) { List < Point > innerList = new ArrayList < > ( ) ; for ( LatLng latLng : innerLatLngs ) { innerList . add ( Point . fromLngLat ( latLng . getLon...
Set a list of lists of LatLng for the fill which represents the locations of the fill on the map
22,501
public void setVisibility ( boolean visible ) { this . visible = visible ; if ( ! style . isFullyLoaded ( ) ) { return ; } Source source = style . getSource ( TrafficData . SOURCE_ID ) ; if ( source == null ) { initialise ( ) ; } List < Layer > layers = style . getLayers ( ) ; for ( Layer layer : layers ) { if ( layerI...
Toggles the visibility of the traffic layers .
22,502
private void initialise ( ) { try { addTrafficSource ( ) ; addTrafficLayers ( ) ; } catch ( Exception exception ) { Timber . e ( exception , "Unable to attach Traffic to current style: " ) ; } catch ( UnsatisfiedLinkError error ) { Timber . e ( error , "Unable to load native libraries: " ) ; } }
Initialise the traffic source and layers .
22,503
private void addTrafficSource ( ) { VectorSource trafficSource = new VectorSource ( TrafficData . SOURCE_ID , TrafficData . SOURCE_URL ) ; style . addSource ( trafficSource ) ; }
Adds traffic source to the map .
22,504
private void addLocalLayer ( ) { LineLayer local = TrafficLayer . getLineLayer ( Local . BASE_LAYER_ID , Local . ZOOM_LEVEL , Local . FILTER , Local . FUNCTION_LINE_COLOR , Local . FUNCTION_LINE_WIDTH , Local . FUNCTION_LINE_OFFSET ) ; LineLayer localCase = TrafficLayer . getLineLayer ( Local . CASE_LAYER_ID , Local . ...
Add local layer to the map .
22,505
private String placeLayerBelow ( ) { if ( belowLayer == null || belowLayer . isEmpty ( ) ) { List < Layer > styleLayers = style . getLayers ( ) ; Layer layer ; for ( int i = styleLayers . size ( ) - 1 ; i >= 0 ; i -- ) { layer = styleLayers . get ( i ) ; if ( ! ( layer instanceof SymbolLayer ) ) { return layer . getId ...
Attempts to find the layer which the traffic should be placed below . Depending on the style this might not always be accurate .
22,506
private void addSecondaryLayer ( ) { LineLayer secondary = TrafficLayer . getLineLayer ( Secondary . BASE_LAYER_ID , Secondary . ZOOM_LEVEL , Secondary . FILTER , Secondary . FUNCTION_LINE_COLOR , Secondary . FUNCTION_LINE_WIDTH , Secondary . FUNCTION_LINE_OFFSET ) ; LineLayer secondaryCase = TrafficLayer . getLineLaye...
Add secondary layer to the map .
22,507
private void addPrimaryLayer ( ) { LineLayer primary = TrafficLayer . getLineLayer ( Primary . BASE_LAYER_ID , Primary . ZOOM_LEVEL , Primary . FILTER , Primary . FUNCTION_LINE_COLOR , Primary . FUNCTION_LINE_WIDTH , Primary . FUNCTION_LINE_OFFSET ) ; LineLayer primaryCase = TrafficLayer . getLineLayer ( Primary . CASE...
Add primary layer to the map .
22,508
private void addTrunkLayer ( ) { LineLayer trunk = TrafficLayer . getLineLayer ( Trunk . BASE_LAYER_ID , Trunk . ZOOM_LEVEL , Trunk . FILTER , Trunk . FUNCTION_LINE_COLOR , Trunk . FUNCTION_LINE_WIDTH , Trunk . FUNCTION_LINE_OFFSET ) ; LineLayer trunkCase = TrafficLayer . getLineLayer ( Trunk . CASE_LAYER_ID , Trunk . ...
Add trunk layer to the map .
22,509
private void addMotorwayLayer ( ) { LineLayer motorWay = TrafficLayer . getLineLayer ( MotorWay . BASE_LAYER_ID , MotorWay . ZOOM_LEVEL , MotorWay . FILTER , MotorWay . FUNCTION_LINE_COLOR , MotorWay . FUNCTION_LINE_WIDTH , MotorWay . FUNCTION_LINE_OFFSET ) ; LineLayer motorwayCase = TrafficLayer . getLineLayer ( Motor...
Add motorway layer to the map .
22,510
private void addTrafficLayersToMap ( Layer layerCase , Layer layer , String idAboveLayer ) { style . addLayerBelow ( layerCase , idAboveLayer ) ; style . addLayerAbove ( layer , layerCase . getId ( ) ) ; layerIds . add ( layerCase . getId ( ) ) ; layerIds . add ( layer . getId ( ) ) ; }
Add Layer to the map and track the id .
22,511
public void cancelDownload ( OfflineDownloadOptions offlineDownload ) { Intent intent = new Intent ( context , OfflineDownloadService . class ) ; intent . setAction ( OfflineConstants . ACTION_CANCEL_DOWNLOAD ) ; intent . putExtra ( KEY_BUNDLE , offlineDownload ) ; context . startService ( intent ) ; }
Cancel an ongoing download .
22,512
public OfflineDownloadOptions getActiveDownloadForOfflineRegion ( OfflineRegion offlineRegion ) { OfflineDownloadOptions offlineDownload = null ; if ( ! offlineDownloads . isEmpty ( ) ) { for ( OfflineDownloadOptions download : offlineDownloads ) { if ( download . uuid ( ) == offlineRegion . getID ( ) ) { offlineDownlo...
Get the OfflineDownloadOptions for an offline region returns null if no download is active for region .
22,513
void removeDownload ( OfflineDownloadOptions offlineDownload , boolean canceled ) { if ( canceled ) { stateChangeDispatcher . onCancel ( offlineDownload ) ; } else { stateChangeDispatcher . onSuccess ( offlineDownload ) ; } offlineDownloads . remove ( offlineDownload ) ; }
Called when the OfflineDownloadService has finished downloading .
22,514
void errorDownload ( OfflineDownloadOptions offlineDownload , String error , String errorMessage ) { stateChangeDispatcher . onError ( offlineDownload , error , errorMessage ) ; offlineDownloads . remove ( offlineDownload ) ; }
Called when the OfflineDownloadService produced an error while downloading
22,515
private void initLayer ( String belowLayer ) { light = style . getLight ( ) ; fillExtrusionLayer = new FillExtrusionLayer ( LAYER_ID , "composite" ) ; fillExtrusionLayer . setSourceLayer ( "building" ) ; fillExtrusionLayer . setMinZoom ( minZoomLevel ) ; fillExtrusionLayer . setProperties ( visibility ( visible ? VISIB...
Initialises and adds the fill extrusion layer used by this plugin .
22,516
public void setVisibility ( boolean visible ) { this . visible = visible ; if ( ! style . isFullyLoaded ( ) ) { return ; } fillExtrusionLayer . setProperties ( visibility ( visible ? VISIBLE : NONE ) ) ; }
Toggles the visibility of the building layer .
22,517
public void setOpacity ( @ FloatRange ( from = 0.0f , to = 1.0f ) float opacity ) { this . opacity = opacity ; if ( ! style . isFullyLoaded ( ) ) { return ; } fillExtrusionLayer . setProperties ( fillExtrusionOpacity ( opacity ) ) ; }
Change the building opacity . Calls into changing the fill extrusion fill opacity .
22,518
public void setMinZoomLevel ( @ FloatRange ( from = MINIMUM_ZOOM , to = MAXIMUM_ZOOM ) float minZoomLevel ) { this . minZoomLevel = minZoomLevel ; if ( ! style . isFullyLoaded ( ) ) { return ; } fillExtrusionLayer . setMinZoom ( minZoomLevel ) ; }
Change the building min zoom level . This is the minimum zoom level where buildings will start to show . useful to limit showing buildings at higher zoom levels .
22,519
void finishDownload ( OfflineDownloadOptions offlineDownload , OfflineRegion offlineRegion ) { OfflineDownloadStateReceiver . dispatchSuccessBroadcast ( this , offlineDownload ) ; offlineRegion . setDownloadState ( OfflineRegion . STATE_INACTIVE ) ; offlineRegion . setObserver ( null ) ; removeOfflineRegion ( offlineDo...
When a particular download has been completed this method s called which handles removing the notification and setting the download state .
22,520
private boolean sourceIsFromMapbox ( Source singleSource ) { if ( singleSource instanceof VectorSource ) { String url = ( ( VectorSource ) singleSource ) . getUrl ( ) ; if ( url != null ) { for ( String supportedSource : SUPPORTED_SOURCES ) { if ( url . contains ( supportedSource ) ) { return true ; } } } } return fals...
Checks whether the map s source is a source provided by Mapbox rather than a custom source .
22,521
private void close ( Handler < AsyncResult < Void > > completionHandler ) { client . close ( ) ; completionHandler . handle ( Future . succeededFuture ( ) ) ; }
Called by hook
22,522
private void init ( ) { host = DEFAULT_HOST ; port = DEFAULT_PORT ; database = DEFAULT_DATABASE ; user = DEFAULT_USER ; password = DEFAULT_PASSWORD ; cachePreparedStatements = DEFAULT_CACHE_PREPARED_STATEMENTS ; pipeliningLimit = DEFAULT_PIPELINING_LIMIT ; sslMode = DEFAULT_SSLMODE ; }
Initialize with the default options .
22,523
private static List < Point > textDecodeMultiplePoints ( int index , int len , ByteBuf buff ) { List < Point > points = new ArrayList < > ( ) ; int start = index ; int end = index + len - 1 ; while ( start < end ) { int rightParenthesis = buff . indexOf ( start , end + 1 , ( byte ) ')' ) ; int idxOfPointSeparator = rig...
this might be useful for decoding Lseg Box Path Polygon Data Type .
22,524
private static void doParse ( String connectionUri , JsonObject configuration ) { Pattern pattern = Pattern . compile ( FULL_URI_REGEX ) ; Matcher matcher = pattern . matcher ( connectionUri ) ; if ( matcher . matches ( ) ) { parseUserandPassword ( matcher . group ( USER_INFO_GROUP ) , configuration ) ; parseNetLocatio...
execute the parsing process and store options in the configuration
22,525
public MapBuilder addNumber ( String fieldName , boolean include , Supplier < Number > supplier ) { if ( include ) { Number value = supplier . get ( ) ; if ( value != null ) { map . put ( getFieldName ( fieldName ) , value ) ; } } return this ; }
Adds the number value to the provided map under the provided field name if it should be included . The supplier is only invoked if the field is to be included .
22,526
public MapBuilder addMap ( String fieldName , boolean include , Supplier < Map < String , ? > > supplier ) { if ( include ) { Map < String , ? > value = supplier . get ( ) ; if ( value != null && ! value . isEmpty ( ) ) { map . put ( getFieldName ( fieldName ) , value ) ; } } return this ; }
Adds the map value to the provided map under the provided field name if it should be included . The supplier is only invoked if the field is to be included .
22,527
public MapBuilder addTimestamp ( String fieldName , boolean include , long timestamp ) { if ( include && timestamp > 0 ) { map . put ( getFieldName ( fieldName ) , timestampFormatter . format ( timestamp ) ) ; } return this ; }
Adds and optionally formats the timestamp to the provided map under the provided field name if it s should be included .
22,528
public void onError ( Cli cli , Namespace namespace , Throwable e ) { e . printStackTrace ( cli . getStdErr ( ) ) ; }
Method is called if there is an issue parsing configuration setting up the environment or running the command itself . The default is printing the stacktrace to facilitate debugging but can be customized per command .
22,529
public void invalidate ( P principal , String role ) { cache . invalidate ( ImmutablePair . of ( principal , role ) ) ; }
Discards any cached role associations for the given principal and role .
22,530
public void invalidate ( P principal ) { final Set < ImmutablePair < P , String > > keys = cache . asMap ( ) . keySet ( ) . stream ( ) . filter ( cacheKey -> cacheKey . getLeft ( ) . equals ( principal ) ) . collect ( Collectors . toSet ( ) ) ; cache . invalidateAll ( keys ) ; }
Discards any cached role associations for the given principal .
22,531
public void invalidateAll ( Iterable < P > principals ) { final Set < P > principalSet = Sets . of ( principals ) ; final Set < ImmutablePair < P , String > > keys = cache . asMap ( ) . keySet ( ) . stream ( ) . filter ( cacheKey -> principalSet . contains ( cacheKey . getLeft ( ) ) ) . collect ( Collectors . toSet ( )...
Discards any cached role associations for the given collection of principals .
22,532
public void invalidateAll ( Predicate < ? super P > predicate ) { final Set < ImmutablePair < P , String > > keys = cache . asMap ( ) . keySet ( ) . stream ( ) . filter ( cacheKey -> predicate . test ( cacheKey . getLeft ( ) ) ) . collect ( Collectors . toSet ( ) ) ; cache . invalidateAll ( keys ) ; }
Discards any cached role associations for principals satisfying the given predicate .
22,533
protected AbstractLifeCycle . AbstractLifeCycleListener logSslInfoOnStart ( final SslContextFactory sslContextFactory ) { return new AbstractLifeCycle . AbstractLifeCycleListener ( ) { public void lifeCycleStarted ( LifeCycle event ) { logSupportedParameters ( sslContextFactory ) ; } } ; }
Register a listener that waits until the ssl context factory has started . Once it has started we can grab the fully initialized context so we can log the parameters .
22,534
public static String getMessage ( ConstraintViolation < ? > v , Invocable invocable ) { final Pair < Path , ? extends ConstraintDescriptor < ? > > of = Pair . of ( v . getPropertyPath ( ) , v . getConstraintDescriptor ( ) ) ; final String cachePrefix = PREFIX_CACHE . getIfPresent ( of ) ; if ( cachePrefix == null ) { f...
Gets the human friendly location of where the violation was raised .
22,535
private static Optional < String > getMethodReturnValueName ( ConstraintViolation < ? > violation ) { int returnValueNames = - 1 ; final StringBuilder result = new StringBuilder ( "server response" ) ; for ( Path . Node node : violation . getPropertyPath ( ) ) { if ( node . getKind ( ) . equals ( ElementKind . RETURN_V...
Gets the method return value name if the violation is raised in it
22,536
public ServletRegistration . Dynamic addServlet ( String name , Servlet servlet ) { final ServletHolder holder = new NonblockingServletHolder ( requireNonNull ( servlet ) ) ; holder . setName ( name ) ; handler . getServletHandler ( ) . addServlet ( holder ) ; final ServletRegistration . Dynamic registration = holder ....
Add a servlet instance .
22,537
public FilterRegistration . Dynamic addFilter ( String name , Filter filter ) { return addFilter ( name , new FilterHolder ( requireNonNull ( filter ) ) ) ; }
Add a filter instance .
22,538
public FilterRegistration . Dynamic addFilter ( String name , Class < ? extends Filter > klass ) { return addFilter ( name , new FilterHolder ( requireNonNull ( klass ) ) ) ; }
Add a filter class .
22,539
public void setProtectedTargets ( String ... targets ) { handler . setProtectedTargets ( Arrays . copyOf ( targets , targets . length ) ) ; }
Set protected targets .
22,540
public void setSessionHandler ( SessionHandler sessionHandler ) { handler . setSessionsEnabled ( sessionHandler != null ) ; handler . setSessionHandler ( sessionHandler ) ; }
Set the session handler .
22,541
public void setSecurityHandler ( SecurityHandler securityHandler ) { handler . setSecurityEnabled ( securityHandler != null ) ; handler . setSecurityHandler ( securityHandler ) ; }
Set the security handler .
22,542
public void addMimeMapping ( String extension , String type ) { handler . getMimeTypes ( ) . addMimeMapping ( extension , type ) ; }
Set a mime mapping .
22,543
public static Optional < String > getParameterNameFromAnnotations ( Annotation [ ] memberAnnotations ) { for ( Annotation a : memberAnnotations ) { if ( a instanceof QueryParam ) { return Optional . of ( "query param " + ( ( QueryParam ) a ) . value ( ) ) ; } else if ( a instanceof PathParam ) { return Optional . of ( ...
Derives member s name and type from it s annotations
22,544
private String getCredentials ( String header ) { if ( header == null ) { return null ; } final int space = header . indexOf ( ' ' ) ; if ( space <= 0 ) { return null ; } final String method = header . substring ( 0 , space ) ; if ( ! prefix . equalsIgnoreCase ( method ) ) { return null ; } return header . substring ( ...
Parses a value of the Authorization header in the form of Bearer a892bf3e284da9bb40648ab10 .
22,545
public static < T > Class < T > getTypeParameter ( Class < ? > klass , Class < ? super T > bound ) { Type t = requireNonNull ( klass ) ; while ( t instanceof Class < ? > ) { t = ( ( Class < ? > ) t ) . getGenericSuperclass ( ) ; } if ( t instanceof ParameterizedType ) { for ( Type param : ( ( ParameterizedType ) t ) . ...
Finds the type parameter for the given class which is assignable to the bound class .
22,546
void clear ( ) { final String name = loggerName ; if ( name != null ) { CHANGE_LOGGER_CONTEXT_LOCK . lock ( ) ; try { loggerContext . stop ( ) ; final Logger logger = loggerContext . getLogger ( org . slf4j . Logger . ROOT_LOGGER_NAME ) ; logger . detachAndStopAllAppenders ( ) ; configureLoggers ( name ) ; } finally { ...
This method is designed to be used by unit tests only .
22,547
private Timer getTimer ( ) { return timerReference . updateAndGet ( timer -> timer == null ? new Timer ( LogConfigurationTask . class . getSimpleName ( ) , true ) : timer ) ; }
Lazy create the timer to avoid unnecessary thread creation unless an expirable log configuration task is submitted
22,548
protected String createUserAgent ( String name ) { final String defaultUserAgent = environmentName == null ? name : String . format ( "%s (%s)" , environmentName , name ) ; return configuration . getUserAgent ( ) . orElse ( defaultUserAgent ) ; }
Create a user agent string using the configured user agent if defined otherwise using a combination of the environment name and this client name
22,549
protected InstrumentedHttpClientConnectionManager createConnectionManager ( Registry < ConnectionSocketFactory > registry , String name ) { final Duration ttl = configuration . getTimeToLive ( ) ; final InstrumentedHttpClientConnectionManager manager = new InstrumentedHttpClientConnectionManager ( metricRegistry , regi...
Create a InstrumentedHttpClientConnectionManager based on the HttpClientConfiguration . It sets the maximum connections per route and the maximum total connections that the connection manager can create
22,550
protected Credentials configureCredentials ( AuthConfiguration auth ) { if ( null != auth . getCredentialType ( ) && auth . getCredentialType ( ) . equalsIgnoreCase ( AuthConfiguration . NT_CREDS ) ) { return new NTCredentials ( auth . getUsername ( ) , auth . getPassword ( ) , auth . getHostname ( ) , auth . getDomain...
determine the Credentials implementation to use
22,551
protected E uniqueResult ( CriteriaQuery < E > criteriaQuery ) throws HibernateException { return AbstractProducedQuery . uniqueElement ( currentSession ( ) . createQuery ( requireNonNull ( criteriaQuery ) ) . getResultList ( ) ) ; }
Convenience method to return a single instance that matches the criteria query or null if the criteria returns no results .
22,552
@ SuppressWarnings ( "unchecked" ) protected E uniqueResult ( Criteria criteria ) throws HibernateException { return ( E ) requireNonNull ( criteria ) . uniqueResult ( ) ; }
Convenience method to return a single instance that matches the criteria or null if the criteria returns no results .
22,553
protected List < E > list ( Query < E > query ) throws HibernateException { return requireNonNull ( query ) . list ( ) ; }
Get the results of a query .
22,554
@ SuppressWarnings ( { "unchecked" , "TypeParameterUnusedInFormals" } ) public < T > T getProperty ( String name ) { return ( T ) config . getProperties ( ) . get ( name ) ; }
Gets the given Jersey property .
22,555
public static String getFullUrl ( HttpServletRequest request ) { if ( request . getQueryString ( ) == null ) { return request . getRequestURI ( ) ; } return request . getRequestURI ( ) + "?" + request . getQueryString ( ) ; }
Returns the full URL of the given request .
22,556
public boolean run ( String ... arguments ) throws Exception { try { if ( isFlag ( HELP , arguments ) ) { parser . printHelp ( stdOut ) ; } else if ( isFlag ( VERSION , arguments ) ) { parser . printVersion ( stdOut ) ; } else { final Namespace namespace = parser . parseArgs ( arguments ) ; final Command command = requ...
Runs the command line interface given some arguments .
22,557
public void registerMetrics ( ) { if ( metricsAreRegistered ) { return ; } getMetricRegistry ( ) . register ( "jvm.attribute" , new JvmAttributeGaugeSet ( ) ) ; getMetricRegistry ( ) . register ( "jvm.buffers" , new BufferPoolMetricSet ( ManagementFactory . getPlatformMBeanServer ( ) ) ) ; getMetricRegistry ( ) . regis...
Registers the JVM metrics to the metric registry and start to report the registry metrics via JMX .
22,558
public void run ( T configuration , Environment environment ) throws Exception { for ( ConfiguredBundle < ? super T > bundle : configuredBundles ) { bundle . run ( configuration , environment ) ; } }
Runs the bootstrap s bundles with the given configuration and environment .
22,559
private BasicCredentials getCredentials ( String header ) { if ( header == null ) { return null ; } final int space = header . indexOf ( ' ' ) ; if ( space <= 0 ) { return null ; } final String method = header . substring ( 0 , space ) ; if ( ! prefix . equalsIgnoreCase ( method ) ) { return null ; } final String decod...
Parses a Base64 - encoded value of the Authorization header in the form of Basic dXNlcm5hbWU6cGFzc3dvcmQ = .
22,560
public static byte [ ] toByteArray ( URL url ) throws IOException { try ( InputStream inputStream = url . openStream ( ) ) { return ByteStreams . toByteArray ( inputStream ) ; } }
Reads all bytes from a URL into a byte array .
22,561
public static void copy ( URL from , OutputStream to ) throws IOException { try ( InputStream inputStream = from . openStream ( ) ) { ByteStreams . copy ( inputStream , to ) ; } }
Copies all bytes from a URL to an output stream .
22,562
private static UUID generateRandomUuid ( ) { final Random rnd = ThreadLocalRandom . current ( ) ; long mostSig = rnd . nextLong ( ) ; long leastSig = rnd . nextLong ( ) ; mostSig &= 0xffffffffffff0fffL ; mostSig |= 0x0000000000004000L ; leastSig &= 0x3fffffffffffffffL ; leastSig |= 0x8000000000000000L ; return new UUID...
Generate a random UUID v4 that will perform reasonably when used by multiple threads under load .
22,563
private boolean isSimilarSignature ( Method possiblyMatchingMethod , String desiredMethodName , Class < ? > [ ] desiredParamTypes ) { return possiblyMatchingMethod . getName ( ) . equals ( desiredMethodName ) && match ( possiblyMatchingMethod . getParameterTypes ( ) , desiredParamTypes ) ; }
Determines if a method has a similar signature especially if wrapping primitive argument types would result in an exactly matching signature .
22,564
private boolean match ( Class < ? > [ ] declaredTypes , Class < ? > [ ] actualTypes ) { if ( declaredTypes . length == actualTypes . length ) { for ( int i = 0 ; i < actualTypes . length ; i ++ ) { if ( actualTypes [ i ] == NULL . class ) continue ; if ( wrapper ( declaredTypes [ i ] ) . isAssignableFrom ( wrapper ( ac...
Check whether two arrays of types match converting primitive types to their corresponding wrappers .
22,565
private static Reflect on ( Constructor < ? > constructor , Object ... args ) throws ReflectException { try { return on ( constructor . getDeclaringClass ( ) , accessible ( constructor ) . newInstance ( args ) ) ; } catch ( Exception e ) { throw new ReflectException ( e ) ; } }
Wrap an object created from a constructor
22,566
private static Reflect on ( Method method , Object object , Object ... args ) throws ReflectException { try { accessible ( method ) ; if ( method . getReturnType ( ) == void . class ) { method . invoke ( object , args ) ; return on ( object ) ; } else { return on ( method . invoke ( object , args ) ) ; } } catch ( Exce...
Wrap an object returned from a method
22,567
private static Object unwrap ( Object object ) { if ( object instanceof Reflect ) { return ( ( Reflect ) object ) . get ( ) ; } return object ; }
Unwrap an object
22,568
public static Class < ? > wrapper ( Class < ? > type ) { if ( type == null ) { return null ; } else if ( type . isPrimitive ( ) ) { if ( boolean . class == type ) { return Boolean . class ; } else if ( int . class == type ) { return Integer . class ; } else if ( long . class == type ) { return Long . class ; } else if ...
Get a wrapper type for a primitive type or the argument type itself if it is not a primitive type .
22,569
@ SuppressWarnings ( "unchecked" ) public < P > P as ( final Class < P > proxyType ) { final boolean isMap = ( object instanceof Map ) ; final InvocationHandler handler = new InvocationHandler ( ) { @ SuppressWarnings ( "null" ) public Object invoke ( Object proxy , Method method , Object [ ] args ) throws Throwable { ...
Create a proxy for the wrapped object allowing to typesafely invoke methods on it using a custom interface
22,570
private static synchronized PrepPipeline createOrFindPreparer ( DatabasePreparer preparer , Iterable < Consumer < Builder > > customizers ) throws IOException , SQLException { final ClusterKey key = new ClusterKey ( preparer , customizers ) ; PrepPipeline result = CLUSTERS . get ( key ) ; if ( result != null ) { return...
Each schema set has its own database cluster . The template1 database has the schema preloaded so that each test case need only create a new database and not re - invoke your preparer .
22,571
public Map < String , String > getConfigurationTweak ( String dbModuleName ) throws SQLException { final DbInfo db = dbPreparer . getNextDb ( ) ; final Map < String , String > result = new HashMap < > ( ) ; result . put ( "ot.db." + dbModuleName + ".uri" , getJdbcUri ( db ) ) ; result . put ( "ot.db." + dbModuleName + ...
Return configuration tweaks in a format appropriate for otj - jdbc DatabaseModule .
22,572
private static String getOS ( ) { if ( SystemUtils . IS_OS_WINDOWS ) { return "Windows" ; } if ( SystemUtils . IS_OS_MAC_OSX ) { return "Darwin" ; } if ( SystemUtils . IS_OS_LINUX ) { return "Linux" ; } throw new UnsupportedOperationException ( "Unknown OS " + SystemUtils . OS_NAME ) ; }
Get current operating system string . The string is used in the appropriate postgres binary name .
22,573
public NullnessHint analyzeReturnType ( ) { if ( method . getReturnType ( ) . isPrimitiveType ( ) ) { LOG ( DEBUG , "DEBUG" , "Skipping method with primitive return type: " + method . getSignature ( ) ) ; return NullnessHint . UNKNOWN ; } LOG ( DEBUG , "DEBUG" , "@ Return type analysis for: " + method . getSignature ( ...
This is the nullability analysis for the method return value .
22,574
private boolean isValidTreeType ( Tree t ) { if ( t instanceof LambdaExpressionTree ) { return true ; } if ( t instanceof ClassTree ) { NestingKind nestingKind = ASTHelpers . getSymbol ( ( ClassTree ) t ) . getNestingKind ( ) ; return nestingKind . equals ( NestingKind . ANONYMOUS ) || nestingKind . equals ( NestingKin...
Is t an anonymous inner class or a lambda?
22,575
public static Symbol . MethodSymbol getFunctionalInterfaceMethod ( ExpressionTree tree , Types types ) { Preconditions . checkArgument ( ( tree instanceof LambdaExpressionTree ) || ( tree instanceof MemberReferenceTree ) ) ; Type funcInterfaceType = ( ( JCTree . JCFunctionalExpression ) tree ) . type ; return ( Symbol ...
finds the corresponding functional interface method for a lambda expression or method reference
22,576
public static boolean lambdaParamIsImplicitlyTyped ( VariableTree lambdaParameter ) { JCDiagnostic . DiagnosticPosition diagnosticPosition = ( JCDiagnostic . DiagnosticPosition ) lambdaParameter ; return diagnosticPosition . getStartPosition ( ) == diagnosticPosition . getPreferredPosition ( ) ; }
determines whether a lambda parameter is missing an explicit type declaration
22,577
public static Symbol . ClassSymbol getOutermostClassSymbol ( Symbol symbol ) { Symbol . ClassSymbol outermostClassSymbol = ASTHelpers . enclosingClass ( symbol ) ; while ( outermostClassSymbol . getNestingKind ( ) . isNested ( ) ) { Symbol . ClassSymbol enclosingSymbol = ASTHelpers . enclosingClass ( outermostClassSymb...
finds the symbol for the top - level class containing the given symbol
22,578
public static TreePath findEnclosingMethodOrLambdaOrInitializer ( TreePath path ) { TreePath curPath = path . getParentPath ( ) ; while ( curPath != null ) { if ( curPath . getLeaf ( ) instanceof MethodTree || curPath . getLeaf ( ) instanceof LambdaExpressionTree ) { return curPath ; } TreePath parent = curPath . getPa...
find the enclosing method lambda expression or initializer block for the leaf of some tree path
22,579
public static Stream < ? extends AnnotationMirror > getAllAnnotationsForParameter ( Symbol . MethodSymbol symbol , int paramInd ) { Symbol . VarSymbol varSymbol = symbol . getParameters ( ) . get ( paramInd ) ; return Stream . concat ( varSymbol . getAnnotationMirrors ( ) . stream ( ) , symbol . getRawTypeAttributes ( ...
Works for method parameters defined either in source or in class files
22,580
public static void main ( String [ ] args ) throws Exception { Options options = new Options ( ) ; HelpFormatter hf = new HelpFormatter ( ) ; hf . setWidth ( 100 ) ; options . addOption ( Option . builder ( "i" ) . argName ( "in_path" ) . longOpt ( "input-file" ) . hasArg ( ) . required ( ) . desc ( "path to target jar...
This is the main method of the cli tool . It parses the arguments invokes the analysis driver and checks that the output file is written .
22,581
private void setNonnullIfAnalyzeable ( Updates updates , Node node ) { AccessPath ap = AccessPath . getAccessPathForNodeWithMapGet ( node , types ) ; if ( ap != null ) { updates . set ( ap , NONNULL ) ; } }
If node represents a local field access or method call we can track set it to be non - null in the updates
22,582
public static Handler buildDefault ( Config config ) { ImmutableList . Builder < Handler > handlerListBuilder = ImmutableList . builder ( ) ; if ( config . acknowledgeRestrictiveAnnotations ( ) ) { handlerListBuilder . add ( new RestrictiveAnnotationHandler ( config ) ) ; } if ( config . isJarInferEnabled ( ) ) { handl...
Builds the default handler for the checker .
22,583
private static void justRun ( String [ ] args ) { List < String > javacArgs = new ArrayList < > ( Arrays . asList ( args ) ) ; String nullawayJar = getJarFileForClass ( NullAway . class ) . getFile ( ) ; boolean foundProcessorPath = false ; for ( int i = 0 ; i < javacArgs . size ( ) ; i ++ ) { if ( javacArgs . get ( i ...
Some recommendations for this mode .
22,584
private static void addNullAwayArgsAndRun ( String [ ] args ) { String nullawayJar = getJarFileForClass ( NullAway . class ) . getFile ( ) ; String annotPackages = args [ 0 ] ; String [ ] javacArgs = Arrays . copyOfRange ( args , 1 , args . length ) ; List < String > nullawayArgs = Arrays . asList ( "-Xmaxwarns" , "1" ...
Here we assume that the javac command has no existing processorpath and no other error prone flags are being passed . In this case we assume the annotated packages are passed as the first argument and the remaining javac args as the rest . We run two configs one with NullAway added in a warning - only mode and one with...
22,585
public Description matchMemberReference ( MemberReferenceTree tree , VisitorState state ) { if ( ! matchWithinClass ) { return Description . NO_MATCH ; } Symbol . MethodSymbol referencedMethod = ASTHelpers . getSymbol ( tree ) ; Symbol . MethodSymbol funcInterfaceSymbol = NullabilityUtil . getFunctionalInterfaceMethod ...
for method references we check that the referenced method correctly overrides the corresponding functional interface method
22,586
private Description doUnboxingCheck ( VisitorState state , ExpressionTree ... expressions ) { for ( ExpressionTree tree : expressions ) { Type type = ASTHelpers . getType ( tree ) ; if ( type == null ) { throw new RuntimeException ( "was not expecting null type" ) ; } if ( ! type . isPrimitive ( ) ) { if ( mayBeNullExp...
if any expression has non - primitive type we should check that it can t be null as it is getting unboxed
22,587
private Description handleInvocation ( Tree tree , VisitorState state , Symbol . MethodSymbol methodSymbol , List < ? extends ExpressionTree > actualParams ) { ImmutableSet < Integer > nonNullPositions = null ; if ( NullabilityUtil . isUnannotated ( methodSymbol , config ) ) { nonNullPositions = handler . onUnannotated...
handle either a method invocation or a new invocation
22,588
private static ExpressionTree stripParensAndCasts ( ExpressionTree expr ) { boolean someChange = true ; while ( someChange ) { someChange = false ; if ( expr . getKind ( ) . equals ( PARENTHESIZED ) ) { expr = ( ( ParenthesizedTree ) expr ) . getExpression ( ) ; someChange = true ; } if ( expr . getKind ( ) . equals ( ...
strip out enclosing parentheses and type casts .
22,589
private Symbol . MethodSymbol getClosestOverriddenMethod ( Symbol . MethodSymbol method , Types types ) { Symbol . ClassSymbol owner = method . enclClass ( ) ; for ( Type s : types . closure ( owner . type ) ) { if ( types . isSameType ( s , owner . type ) ) { continue ; } for ( Symbol m : s . tsym . members ( ) . getS...
find the closest ancestor method in a superclass or superinterface that method overrides
22,590
public Nullness getComputedNullness ( ExpressionTree e ) { if ( computedNullnessMap . containsKey ( e ) ) { return computedNullnessMap . get ( e ) ; } else { return Nullness . NULLABLE ; } }
Returns the computed nullness information from an expression . If none is available it returns Nullable .
22,591
private static void accountCodeBytes ( IMethod mtd ) { if ( mtd instanceof ShrikeCTMethod ) { analyzedBytes += ( ( ShrikeCTMethod ) mtd ) . getBytecodes ( ) . length ; } }
Accounts the bytecode size of analyzed method for statistics .
22,592
private static boolean isAllPrimitiveTypes ( IMethod mtd ) { if ( ! mtd . getReturnType ( ) . isPrimitiveType ( ) ) return false ; for ( int i = ( mtd . isStatic ( ) ? 0 : 1 ) ; i < mtd . getNumberOfParameters ( ) ; i ++ ) { if ( ! mtd . getParameterType ( i ) . isPrimitiveType ( ) ) return false ; } return true ; }
Checks if all parameters and return value of a method have primitive types .
22,593
private static InputStream getInputStream ( String libPath ) throws IOException { Preconditions . checkArgument ( ( libPath . endsWith ( ".jar" ) || libPath . endsWith ( ".aar" ) ) && Files . exists ( Paths . get ( libPath ) ) , "invalid library path! " + libPath ) ; LOG ( VERBOSE , "Info" , "opening library: " + libPa...
Get InputStream of the jar of class files to be analyzed .
22,594
private static void writeModelJAR ( String outPath ) throws IOException { Preconditions . checkArgument ( outPath . endsWith ( MODEL_JAR_SUFFIX ) , "invalid model file path! " + outPath ) ; ZipOutputStream zos = new ZipOutputStream ( new FileOutputStream ( outPath ) ) ; if ( ! map_result . isEmpty ( ) ) { ZipEntry entr...
Write model jar file with nullability model at DEFAULT_ASTUBX_LOCATION
22,595
private static String getSimpleTypeName ( TypeReference typ ) { final Map < String , String > mapFullTypeName = ImmutableMap . < String , String > builder ( ) . put ( "B" , "byte" ) . put ( "C" , "char" ) . put ( "D" , "double" ) . put ( "F" , "float" ) . put ( "I" , "int" ) . put ( "J" , "long" ) . put ( "S" , "short"...
Get simple unqualified type name .
22,596
private Bitmap savePixels ( int x , int y , int w , int h ) { int b [ ] = new int [ w * ( y + h ) ] ; int bt [ ] = new int [ w * h ] ; IntBuffer ib = IntBuffer . wrap ( b ) ; ib . position ( 0 ) ; GLES20 . glReadPixels ( x , 0 , w , y + h , GLES20 . GL_RGBA , GLES20 . GL_UNSIGNED_BYTE , ib ) ; for ( int i = 0 , k = 0 ;...
Extract the bitmap from OpenGL
22,597
public void drag ( float fromX , float toX , float fromY , float toY , int stepCount ) { long downTime = SystemClock . uptimeMillis ( ) ; long eventTime = SystemClock . uptimeMillis ( ) ; float y = fromY ; float x = fromX ; float yStep = ( toY - fromY ) / stepCount ; float xStep = ( toX - fromX ) / stepCount ; MotionEv...
Simulate touching a specific location and dragging to a new location .
22,598
public boolean scrollView ( final View view , int direction ) { if ( view == null ) { return false ; } int height = view . getHeight ( ) ; height -- ; int scrollTo = - 1 ; if ( direction == DOWN ) { scrollTo = height ; } else if ( direction == UP ) { scrollTo = - height ; } int originalY = view . getScrollY ( ) ; final...
Scrolls a ScrollView .
22,599
@ SuppressWarnings ( "unchecked" ) public boolean scroll ( int direction , boolean allTheWay ) { ArrayList < View > viewList = RobotiumUtils . removeInvisibleViews ( viewFetcher . getAllViews ( true ) ) ; ArrayList < View > filteredViews = RobotiumUtils . filterViewsToSet ( new Class [ ] { ListView . class , ScrollView...
Scrolls up and down .