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 . getLongitude ( ) , latLng . getLatitude ( ) ) ) ; } points . add ( innerList ) ; } geometry = Polygon . fromLngLats ( points ) ; return this ; }
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 ( layerIds . contains ( layer . getId ( ) ) ) { layer . setProperties ( visibility ( visible ? Property . VISIBLE : Property . NONE ) ) ; } } }
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 . ZOOM_LEVEL , Local . FILTER , Local . FUNCTION_LINE_COLOR_CASE , Local . FUNCTION_LINE_WIDTH_CASE , Local . FUNCTION_LINE_OFFSET , Local . FUNCTION_LINE_OPACITY_CASE ) ; addTrafficLayersToMap ( localCase , local , placeLayerBelow ( ) ) ; }
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 ( ) ; } } } return belowLayer ; }
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 . getLineLayer ( Secondary . CASE_LAYER_ID , Secondary . ZOOM_LEVEL , Secondary . FILTER , Secondary . FUNCTION_LINE_COLOR_CASE , Secondary . FUNCTION_LINE_WIDTH_CASE , Secondary . FUNCTION_LINE_OFFSET , Secondary . FUNCTION_LINE_OPACITY_CASE ) ; addTrafficLayersToMap ( secondaryCase , secondary , getLastAddedLayerId ( ) ) ; }
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_LAYER_ID , Primary . ZOOM_LEVEL , Primary . FILTER , Primary . FUNCTION_LINE_COLOR_CASE , Primary . FUNCTION_LINE_WIDTH_CASE , Primary . FUNCTION_LINE_OFFSET , Primary . FUNCTION_LINE_OPACITY_CASE ) ; addTrafficLayersToMap ( primaryCase , primary , getLastAddedLayerId ( ) ) ; }
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 . ZOOM_LEVEL , Trunk . FILTER , Trunk . FUNCTION_LINE_COLOR_CASE , Trunk . FUNCTION_LINE_WIDTH_CASE , Trunk . FUNCTION_LINE_OFFSET ) ; addTrafficLayersToMap ( trunkCase , trunk , getLastAddedLayerId ( ) ) ; }
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 ( MotorWay . CASE_LAYER_ID , MotorWay . ZOOM_LEVEL , MotorWay . FILTER , MotorWay . FUNCTION_LINE_COLOR_CASE , MotorWay . FUNCTION_LINE_WIDTH_CASE , MotorWay . FUNCTION_LINE_OFFSET ) ; addTrafficLayersToMap ( motorwayCase , motorWay , getLastAddedLayerId ( ) ) ; }
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 ( ) ) { offlineDownload = download ; } } } return offlineDownload ; }
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 ? VISIBLE : NONE ) , fillExtrusionColor ( color ) , fillExtrusionHeight ( interpolate ( exponential ( 1f ) , zoom ( ) , stop ( 15 , literal ( 0 ) ) , stop ( 16 , get ( "height" ) ) ) ) , fillExtrusionOpacity ( opacity ) ) ; addLayer ( fillExtrusionLayer , belowLayer ) ; }
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 ( offlineDownload . uuid ( ) . intValue ( ) ) ; }
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 false ; }
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 = rightParenthesis + 1 ; int lenOfPoint = idxOfPointSeparator - start ; Point point = textDecodePOINT ( start , lenOfPoint , buff ) ; points . add ( point ) ; start = idxOfPointSeparator + 1 ; } return points ; }
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 ) ; parseNetLocation ( matcher . group ( NET_LOCATION_GROUP ) , configuration ) ; parsePort ( matcher . group ( PORT_GROUP ) , configuration ) ; parseDatabaseName ( matcher . group ( DATABASE_GROUP ) , configuration ) ; parseParameters ( matcher . group ( PARAMETER_GROUP ) , configuration ) ; } else { throw new IllegalArgumentException ( "Wrong syntax of connection URI" ) ; } }
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 ( ) ) ; cache . invalidateAll ( keys ) ; }
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 ) { final String prefix = calculatePrefix ( v , invocable ) ; PREFIX_CACHE . put ( of , prefix ) ; return prefix + v . getMessage ( ) ; } return cachePrefix + v . getMessage ( ) ; }
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_VALUE ) ) { returnValueNames = 0 ; } else if ( returnValueNames >= 0 ) { result . append ( returnValueNames ++ == 0 ? " " : "." ) . append ( node ) ; } } return returnValueNames >= 0 ? Optional . of ( result . toString ( ) ) : Optional . empty ( ) ; }
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 . getRegistration ( ) ; checkDuplicateRegistration ( name , servlets , "servlet" ) ; return registration ; }
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 ( "path param " + ( ( PathParam ) a ) . value ( ) ) ; } else if ( a instanceof HeaderParam ) { return Optional . of ( "header " + ( ( HeaderParam ) a ) . value ( ) ) ; } else if ( a instanceof CookieParam ) { return Optional . of ( "cookie " + ( ( CookieParam ) a ) . value ( ) ) ; } else if ( a instanceof FormParam ) { return Optional . of ( "form field " + ( ( FormParam ) a ) . value ( ) ) ; } else if ( a instanceof Context ) { return Optional . of ( "context" ) ; } else if ( a instanceof MatrixParam ) { return Optional . of ( "matrix param " + ( ( MatrixParam ) a ) . value ( ) ) ; } } return Optional . empty ( ) ; }
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 ( space + 1 ) ; }
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 ) . getActualTypeArguments ( ) ) { if ( param instanceof Class < ? > ) { final Class < T > cls = determineClass ( bound , param ) ; if ( cls != null ) { return cls ; } } else if ( param instanceof TypeVariable ) { for ( Type paramBound : ( ( TypeVariable < ? > ) param ) . getBounds ( ) ) { if ( paramBound instanceof Class < ? > ) { final Class < T > cls = determineClass ( bound , paramBound ) ; if ( cls != null ) { return cls ; } } } } else if ( param instanceof ParameterizedType ) { final Type rawType = ( ( ParameterizedType ) param ) . getRawType ( ) ; if ( rawType instanceof Class < ? > ) { final Class < T > cls = determineClass ( bound , rawType ) ; if ( cls != null ) { return cls ; } } } } } throw new IllegalStateException ( "Cannot figure out type parameterization for " + klass . getName ( ) ) ; }
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 { CHANGE_LOGGER_CONTEXT_LOCK . unlock ( ) ; } StatusPrinter . setPrintStream ( System . out ) ; } }
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 , registry , null , null , resolver , ttl . getQuantity ( ) , ttl . getUnit ( ) , name ) ; return configureConnectionManager ( manager ) ; }
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 ( ) ) ; } else { return new UsernamePasswordCredentials ( auth . getUsername ( ) , auth . getPassword ( ) ) ; } }
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 = requireNonNull ( commands . get ( namespace . getString ( COMMAND_NAME_ATTR ) ) , "Command is not found" ) ; try { command . run ( bootstrap , namespace ) ; } catch ( Throwable e ) { command . onError ( this , namespace , e ) ; return false ; } } return true ; } catch ( HelpScreenException ignored ) { return true ; } catch ( ArgumentParserException e ) { stdErr . println ( e . getMessage ( ) ) ; e . getParser ( ) . printHelp ( stdErr ) ; return false ; } }
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 ( ) . register ( "jvm.classloader" , new ClassLoadingGaugeSet ( ) ) ; getMetricRegistry ( ) . register ( "jvm.filedescriptor" , new FileDescriptorRatioGauge ( ) ) ; getMetricRegistry ( ) . register ( "jvm.gc" , new GarbageCollectorMetricSet ( ) ) ; getMetricRegistry ( ) . register ( "jvm.memory" , new MemoryUsageGaugeSet ( ) ) ; getMetricRegistry ( ) . register ( "jvm.threads" , new ThreadStatesGaugeSet ( ) ) ; JmxReporter . forRegistry ( metricRegistry ) . build ( ) . start ( ) ; metricsAreRegistered = true ; }
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 decoded ; try { decoded = new String ( Base64 . getDecoder ( ) . decode ( header . substring ( space + 1 ) ) , StandardCharsets . UTF_8 ) ; } catch ( IllegalArgumentException e ) { logger . warn ( "Error decoding credentials" , e ) ; return null ; } final int i = decoded . indexOf ( ':' ) ; if ( i <= 0 ) { return null ; } final String username = decoded . substring ( 0 , i ) ; final String password = decoded . substring ( i + 1 ) ; return new BasicCredentials ( username , password ) ; }
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 ( mostSig , leastSig ) ; }
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 ( actualTypes [ i ] ) ) ) continue ; return false ; } return true ; } else { return false ; } }
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 ( Exception e ) { throw new ReflectException ( e ) ; } }
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 ( short . class == type ) { return Short . class ; } else if ( byte . class == type ) { return Byte . class ; } else if ( double . class == type ) { return Double . class ; } else if ( float . class == type ) { return Float . class ; } else if ( char . class == type ) { return Character . class ; } else if ( void . class == type ) { return Void . class ; } } return type ; }
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 { String name = method . getName ( ) ; try { return on ( type , object ) . call ( name , args ) . get ( ) ; } catch ( ReflectException e ) { if ( isMap ) { Map < String , Object > map = ( Map < String , Object > ) object ; int length = ( args == null ? 0 : args . length ) ; if ( length == 0 && name . startsWith ( "get" ) ) { return map . get ( property ( name . substring ( 3 ) ) ) ; } else if ( length == 0 && name . startsWith ( "is" ) ) { return map . get ( property ( name . substring ( 2 ) ) ) ; } else if ( length == 1 && name . startsWith ( "set" ) ) { map . put ( property ( name . substring ( 3 ) ) , args [ 0 ] ) ; return null ; } } throw e ; } } } ; return ( P ) Proxy . newProxyInstance ( proxyType . getClassLoader ( ) , new Class [ ] { proxyType } , handler ) ; }
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 result ; } final Builder builder = EmbeddedPostgres . builder ( ) ; customizers . forEach ( c -> c . accept ( builder ) ) ; final EmbeddedPostgres pg = builder . start ( ) ; preparer . prepare ( pg . getTemplateDatabase ( ) ) ; result = new PrepPipeline ( pg ) . start ( ) ; CLUSTERS . put ( key , result ) ; return result ; }
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 + ".ds.user" , db . user ) ; return result ; }
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 ( ) ) ; if ( prunedCFG == null ) { prunedCFG = ExceptionPrunedCFG . make ( cfg ) ; } if ( prunedCFG . getNumberOfNodes ( ) == 2 && prunedCFG . containsNode ( cfg . entry ( ) ) && prunedCFG . containsNode ( cfg . exit ( ) ) && GraphUtil . countEdges ( prunedCFG ) == 0 ) { return NullnessHint . UNKNOWN ; } for ( ISSABasicBlock bb : prunedCFG . getNormalPredecessors ( prunedCFG . exit ( ) ) ) { for ( int i = bb . getFirstInstructionIndex ( ) ; i <= bb . getLastInstructionIndex ( ) ; i ++ ) { SSAInstruction instr = ir . getInstructions ( ) [ i ] ; if ( instr instanceof SSAReturnInstruction ) { SSAReturnInstruction retInstr = ( SSAReturnInstruction ) instr ; if ( ir . getSymbolTable ( ) . isNullConstant ( retInstr . getResult ( ) ) ) { LOG ( DEBUG , "DEBUG" , "Nullable return in method: " + method . getSignature ( ) ) ; return NullnessHint . NULLABLE ; } } } } return NullnessHint . UNKNOWN ; }
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 ( NestingKind . LOCAL ) ; } return false ; }
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 . MethodSymbol ) types . findDescriptorSymbol ( funcInterfaceType . tsym ) ; }
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 ( outermostClassSymbol . owner ) ; if ( enclosingSymbol != null ) { outermostClassSymbol = enclosingSymbol ; } else { break ; } } return outermostClassSymbol ; }
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 . getParentPath ( ) ; if ( parent != null && parent . getLeaf ( ) instanceof ClassTree ) { if ( curPath . getLeaf ( ) instanceof BlockTree ) { return curPath ; } if ( curPath . getLeaf ( ) instanceof VariableTree && ( ( VariableTree ) curPath . getLeaf ( ) ) . getInitializer ( ) != null ) { return curPath ; } } curPath = parent ; } return null ; }
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 ( ) . stream ( ) . filter ( t -> t . position . type . equals ( TargetType . METHOD_FORMAL_PARAMETER ) && t . position . parameter_index == paramInd ) ) ; }
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/aar file" ) . build ( ) ) ; options . addOption ( Option . builder ( "p" ) . argName ( "pkg_name" ) . longOpt ( "package" ) . hasArg ( ) . desc ( "qualified package name" ) . build ( ) ) ; options . addOption ( Option . builder ( "o" ) . argName ( "out_path" ) . longOpt ( "output-file" ) . hasArg ( ) . required ( ) . desc ( "path to processed jar/aar file" ) . build ( ) ) ; options . addOption ( Option . builder ( "h" ) . argName ( "help" ) . longOpt ( "help" ) . desc ( "print usage information" ) . build ( ) ) ; options . addOption ( Option . builder ( "d" ) . argName ( "debug" ) . longOpt ( "debug" ) . desc ( "print debug information" ) . build ( ) ) ; options . addOption ( Option . builder ( "v" ) . argName ( "verbose" ) . longOpt ( "verbose" ) . desc ( "set verbosity" ) . build ( ) ) ; try { CommandLine line = new DefaultParser ( ) . parse ( options , args ) ; if ( line . hasOption ( 'h' ) ) { hf . printHelp ( appName , options , true ) ; return ; } String jarPath = line . getOptionValue ( 'i' ) ; String pkgName = line . getOptionValue ( 'p' , "" ) ; String outPath = line . getOptionValue ( 'o' ) ; boolean debug = line . hasOption ( 'd' ) ; boolean verbose = line . hasOption ( 'v' ) ; if ( ! pkgName . isEmpty ( ) ) { pkgName = "L" + pkgName . replaceAll ( "\\." , "/" ) ; } DefinitelyDerefedParamsDriver . run ( jarPath , pkgName , outPath , debug , verbose ) ; if ( ! new File ( outPath ) . exists ( ) ) { System . out . println ( "Could not write jar file: " + outPath ) ; } } catch ( ParseException pe ) { hf . printHelp ( appName , options , true ) ; } }
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 ( ) ) { handlerListBuilder . add ( new InferredJARModelsHandler ( config ) ) ; } if ( config . handleTestAssertionLibraries ( ) ) { handlerListBuilder . add ( new AssertionHandler ( ) ) ; } handlerListBuilder . add ( new LibraryModelsHandler ( ) ) ; handlerListBuilder . add ( new RxNullabilityPropagator ( ) ) ; handlerListBuilder . add ( new ContractHandler ( ) ) ; handlerListBuilder . add ( new ApacheThriftIsSetHandler ( ) ) ; if ( config . checkOptionalEmptiness ( ) ) { handlerListBuilder . add ( new OptionalEmptinessHandler ( config ) ) ; } return new CompositeHandler ( handlerListBuilder . build ( ) ) ; }
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 ) . equals ( "-processorpath" ) ) { foundProcessorPath = true ; String procPath = javacArgs . get ( i + 1 ) ; procPath = procPath + System . getProperties ( ) . getProperty ( "path.separator" ) + nullawayJar ; javacArgs . set ( i + 1 , procPath ) ; break ; } } if ( ! foundProcessorPath ) { javacArgs . add ( "-processorpath" ) ; javacArgs . add ( nullawayJar ) ; } System . out . println ( "Running" ) ; runCompile ( javacArgs , 3 , 8 ) ; }
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" , "-XepDisableAllChecks" , "-Xep:NullAway:WARN" , "-XepOpt:NullAway:AnnotatedPackages=" + annotPackages , "-processorpath" , nullawayJar ) ; List < String > fixedArgs = new ArrayList < > ( ) ; fixedArgs . addAll ( nullawayArgs ) ; fixedArgs . addAll ( Arrays . asList ( javacArgs ) ) ; System . out . println ( "With NullAway" ) ; runCompile ( fixedArgs , 7 , 10 ) ; fixedArgs = new ArrayList < > ( ) ; fixedArgs . add ( "-XepDisableAllChecks" ) ; fixedArgs . addAll ( Arrays . asList ( javacArgs ) ) ; System . out . println ( "No NullAway" ) ; runCompile ( fixedArgs , 7 , 10 ) ; }
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 no NullAway .
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 ( tree , state . getTypes ( ) ) ; handler . onMatchMethodReference ( this , tree , state , referencedMethod ) ; return checkOverriding ( funcInterfaceSymbol , referencedMethod , tree , state ) ; }
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 ( mayBeNullExpr ( state , tree ) ) { final ErrorMessage errorMessage = new ErrorMessage ( MessageTypes . UNBOX_NULLABLE , "unboxing of a @Nullable value" ) ; return errorBuilder . createErrorDescription ( errorMessage , state . getPath ( ) , buildDescription ( tree ) ) ; } } } return Description . NO_MATCH ; }
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 . onUnannotatedInvocationGetNonNullPositions ( this , state , methodSymbol , actualParams , ImmutableSet . of ( ) ) ; } List < VarSymbol > formalParams = methodSymbol . getParameters ( ) ; if ( nonNullPositions == null ) { ImmutableSet . Builder < Integer > builder = ImmutableSet . builder ( ) ; for ( int i = 0 ; i < formalParams . size ( ) ; i ++ ) { VarSymbol param = formalParams . get ( i ) ; if ( param . type . isPrimitive ( ) ) { Description unboxingCheck = doUnboxingCheck ( state , actualParams . get ( i ) ) ; if ( unboxingCheck != Description . NO_MATCH ) { return unboxingCheck ; } else { continue ; } } if ( ! Nullness . paramHasNullableAnnotation ( methodSymbol , i ) ) { builder . add ( i ) ; } } nonNullPositions = builder . build ( ) ; } for ( int argPos : nonNullPositions ) { ExpressionTree actual = null ; boolean mayActualBeNull = false ; if ( argPos == formalParams . size ( ) - 1 && methodSymbol . isVarArgs ( ) ) { if ( actualParams . size ( ) <= argPos ) { continue ; } for ( ExpressionTree arg : actualParams . subList ( argPos , actualParams . size ( ) ) ) { actual = arg ; mayActualBeNull = mayBeNullExpr ( state , actual ) ; if ( mayActualBeNull ) { break ; } } } else { actual = actualParams . get ( argPos ) ; mayActualBeNull = mayBeNullExpr ( state , actual ) ; } Preconditions . checkNotNull ( actual ) ; if ( mayActualBeNull ) { String message = "passing @Nullable parameter '" + state . getSourceForNode ( actual ) + "' where @NonNull is required" ; return errorBuilder . createErrorDescriptionForNullAssignment ( new ErrorMessage ( MessageTypes . PASS_NULLABLE , message ) , actual , state . getPath ( ) , buildDescription ( actual ) ) ; } } return checkCastToNonNullTakesNullable ( tree , state , methodSymbol , actualParams ) ; }
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 ( TYPE_CAST ) ) { expr = ( ( TypeCastTree ) expr ) . getExpression ( ) ; someChange = true ; } } return expr ; }
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 ( ) . getSymbolsByName ( method . name ) ) { if ( ! ( m instanceof Symbol . MethodSymbol ) ) { continue ; } Symbol . MethodSymbol msym = ( Symbol . MethodSymbol ) m ; if ( msym . isStatic ( ) ) { continue ; } if ( method . overrides ( msym , owner , types , false ) ) { return msym ; } } } return null ; }
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: " + libPath + "..." ) ; InputStream jarIS = null ; if ( libPath . endsWith ( ".jar" ) ) { jarIS = new FileInputStream ( libPath ) ; } else if ( libPath . endsWith ( ".aar" ) ) { ZipFile aar = new ZipFile ( libPath ) ; ZipEntry jarEntry = aar . getEntry ( "classes.jar" ) ; jarIS = ( jarEntry == null ? null : aar . getInputStream ( jarEntry ) ) ; } return jarIS ; }
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 entry = new ZipEntry ( DEFAULT_ASTUBX_LOCATION ) ; entry . setTime ( 0 ) ; entry . setCreationTime ( FileTime . fromMillis ( 0 ) ) ; zos . putNextEntry ( entry ) ; writeModel ( new DataOutputStream ( zos ) ) ; zos . closeEntry ( ) ; } zos . close ( ) ; LOG ( VERBOSE , "Info" , "wrote model to: " + outPath ) ; }
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" ) . put ( "Z" , "boolean" ) . build ( ) ; if ( typ . isArrayType ( ) ) return "Array" ; String typName = typ . getName ( ) . toString ( ) ; if ( typName . startsWith ( "L" ) ) { typName = typName . split ( "<" ) [ 0 ] . substring ( 1 ) ; typName = typName . substring ( typName . lastIndexOf ( '/' ) + 1 ) ; typName = typName . substring ( typName . lastIndexOf ( '$' ) + 1 ) ; } else { typName = mapFullTypeName . get ( typName ) ; } return typName ; }
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 ; i < h ; i ++ , k ++ ) { for ( int j = 0 ; j < w ; j ++ ) { int pix = b [ i * w + j ] ; int pb = ( pix >> 16 ) & 0xff ; int pr = ( pix << 16 ) & 0x00ff0000 ; int pix1 = ( pix & 0xff00ff00 ) | pr | pb ; bt [ ( h - k - 1 ) * w + j ] = pix1 ; } } Bitmap sb = Bitmap . createBitmap ( bt , w , h , Bitmap . Config . ARGB_8888 ) ; return sb ; }
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 ; MotionEvent event = MotionEvent . obtain ( downTime , eventTime , MotionEvent . ACTION_DOWN , fromX , fromY , 0 ) ; try { inst . sendPointerSync ( event ) ; } catch ( SecurityException ignored ) { } for ( int i = 0 ; i < stepCount ; ++ i ) { y += yStep ; x += xStep ; eventTime = SystemClock . uptimeMillis ( ) ; event = MotionEvent . obtain ( downTime , eventTime , MotionEvent . ACTION_MOVE , x , y , 0 ) ; try { inst . sendPointerSync ( event ) ; } catch ( SecurityException ignored ) { } } eventTime = SystemClock . uptimeMillis ( ) ; event = MotionEvent . obtain ( downTime , eventTime , MotionEvent . ACTION_UP , toX , toY , 0 ) ; try { inst . sendPointerSync ( event ) ; } catch ( SecurityException ignored ) { } }
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 int scrollAmount = scrollTo ; inst . runOnMainSync ( new Runnable ( ) { public void run ( ) { view . scrollBy ( 0 , scrollAmount ) ; } } ) ; if ( originalY == view . getScrollY ( ) ) { return false ; } else { return true ; } }
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 . class , GridView . class , WebView . class } , viewList ) ; List < View > scrollableSupportPackageViews = viewFetcher . getScrollableSupportPackageViews ( true ) ; for ( View viewToScroll : scrollableSupportPackageViews ) { filteredViews . add ( viewToScroll ) ; } View view = viewFetcher . getFreshestView ( filteredViews ) ; if ( view == null ) { return false ; } if ( view instanceof AbsListView ) { return scrollList ( ( AbsListView ) view , direction , allTheWay ) ; } if ( view instanceof WebView ) { return scrollWebView ( ( WebView ) view , direction , allTheWay ) ; } if ( allTheWay ) { scrollViewAllTheWay ( view , direction ) ; return false ; } else { return scrollView ( view , direction ) ; } }
Scrolls up and down .