idx int64 0 41.2k | question stringlengths 74 4.21k | target stringlengths 5 888 |
|---|---|---|
39,100 | public VehicleMessage get ( MessageKey key ) throws NoValueException { if ( mRemoteService == null ) { Log . w ( TAG , "Not connected to the VehicleService -- " + "throwing a NoValueException" ) ; throw new NoValueException ( ) ; } try { VehicleMessage message = mRemoteService . get ( key ) ; if ( message == null ) { throw new NoValueException ( ) ; } return message ; } catch ( RemoteException | ClassCastException e ) { Log . w ( TAG , "Unable to get value from remote vehicle service" , e ) ; throw new NoValueException ( ) ; } } | Retrieve the most current value of a keyed message . |
39,101 | public void request ( KeyedMessage message , VehicleMessage . Listener listener ) { mNotifier . register ( ExactKeyMatcher . buildExactMatcher ( message . getKey ( ) ) , listener , false ) ; send ( message ) ; } | Send a message to the VehicleInterface and register the given listener to receive the first response matching the message s key . |
39,102 | public VehicleMessage request ( KeyedMessage message ) { BlockingMessageListener callback = new BlockingMessageListener ( ) ; request ( message , callback ) ; return callback . waitForResponse ( ) ; } | Send a message to the VehicleInterface and wait up to 2 seconds to receive a response . |
39,103 | public void addListener ( Class < ? extends Measurement > measurementType , Measurement . Listener listener ) { Log . i ( TAG , "Adding listener " + listener + " for " + measurementType ) ; mNotifier . register ( measurementType , listener ) ; } | Register to receive asynchronous updates for a specific Measurement type . |
39,104 | public void addListener ( Class < ? extends VehicleMessage > messageType , VehicleMessage . Listener listener ) { Log . i ( TAG , "Adding listener " + listener + " for " + messageType ) ; mNotifier . register ( messageType , listener ) ; } | Register to receive asynchronous updates for a specific VehicleMessage type . |
39,105 | public void addListener ( KeyedMessage keyedMessage , VehicleMessage . Listener listener ) { addListener ( keyedMessage . getKey ( ) , listener ) ; } | Register to receive a callback when a message with same key as the given KeyedMessage is received . |
39,106 | public void addListener ( MessageKey key , VehicleMessage . Listener listener ) { addListener ( ExactKeyMatcher . buildExactMatcher ( key ) , listener ) ; } | Register to receive a callback when a message with the given key is received . |
39,107 | public void addListener ( KeyMatcher matcher , VehicleMessage . Listener listener ) { Log . i ( TAG , "Adding listener " + listener + " to " + matcher ) ; mNotifier . register ( matcher , listener ) ; } | Register to receive a callback when a message with key matching the given KeyMatcher is received . |
39,108 | public void removeListener ( Class < ? extends Measurement > measurementType , Measurement . Listener listener ) { Log . i ( TAG , "Removing listener " + listener + " for " + measurementType ) ; mNotifier . unregister ( measurementType , listener ) ; } | Unregister a previously registered Measurement . Listener instance . |
39,109 | public void removeListener ( Class < ? extends VehicleMessage > messageType , VehicleMessage . Listener listener ) { mNotifier . unregister ( messageType , listener ) ; } | Unregister a previously registered message type listener . |
39,110 | public void removeListener ( KeyedMessage message , VehicleMessage . Listener listener ) { removeListener ( message . getKey ( ) , listener ) ; } | Unregister a previously registered keyed message listener . |
39,111 | public void removeListener ( KeyMatcher matcher , VehicleMessage . Listener listener ) { mNotifier . unregister ( matcher , listener ) ; } | Unregister a previously registered key matcher listener . |
39,112 | public void removeListener ( MessageKey key , VehicleMessage . Listener listener ) { removeListener ( ExactKeyMatcher . buildExactMatcher ( key ) , listener ) ; } | Unregister a previously registered key listener . |
39,113 | public void addSource ( VehicleDataSource source ) { Log . i ( TAG , "Adding data source " + source ) ; mUserOriginPipeline . addSource ( source ) ; } | Add a new data source to the vehicle service . |
39,114 | public void removeSource ( VehicleDataSource source ) { if ( source != null ) { Log . i ( TAG , "Removing data source " + source ) ; mUserOriginPipeline . removeSource ( source ) ; } } | Remove a previously registered source from the data pipeline . |
39,115 | public void addSink ( VehicleDataSink sink ) { Log . i ( TAG , "Adding data sink " + sink ) ; mRemoteOriginPipeline . addSink ( sink ) ; } | Add a new data sink to the vehicle service . |
39,116 | public void removeSink ( VehicleDataSink sink ) { if ( sink != null ) { mRemoteOriginPipeline . removeSink ( sink ) ; sink . stop ( ) ; } } | Remove a previously registered sink from the data pipeline . |
39,117 | public String requestCommandMessage ( CommandType type ) { VehicleMessage message = request ( new Command ( type ) ) ; String value = null ; if ( message != null ) { try { CommandResponse response = message . asCommandResponse ( ) ; if ( response . getStatus ( ) ) { value = response . getMessage ( ) ; } } catch ( ClassCastException e ) { Log . w ( TAG , "Expected a command response but got " + message + " -- ignoring, assuming no response" ) ; } } return value ; } | Send a command request to the vehicle that does not require any metadata . |
39,118 | public void addOnVehicleInterfaceConnectedListener ( ViConnectionListener listener ) throws VehicleServiceException { if ( mRemoteService != null ) { try { mRemoteService . addViConnectionListener ( listener ) ; } catch ( RemoteException e ) { throw new VehicleServiceException ( "Unable to add connection status listener" , e ) ; } } } | Register a listener to receive a callback when the selected VI is connected . |
39,119 | public void setVehicleInterface ( Class < ? extends VehicleInterface > vehicleInterfaceType , String resource ) throws VehicleServiceException { Log . i ( TAG , "Setting VI to: " + vehicleInterfaceType ) ; String interfaceName = null ; if ( vehicleInterfaceType != null ) { interfaceName = vehicleInterfaceType . getName ( ) ; } if ( mRemoteService != null ) { try { mRemoteService . setVehicleInterface ( interfaceName , resource ) ; } catch ( RemoteException e ) { throw new VehicleServiceException ( "Unable to set vehicle interface" , e ) ; } } else { Log . w ( TAG , "Can't set vehicle interface, not connected to the " + "VehicleService" ) ; } } | Change the active vehicle interface to a new type using the given resource . |
39,120 | public void setNativeGpsStatus ( boolean enabled ) { Log . i ( TAG , ( enabled ? "Enabling" : "Disabling" ) + " native GPS" ) ; if ( mRemoteService != null ) { try { mRemoteService . setNativeGpsStatus ( enabled ) ; } catch ( RemoteException e ) { Log . w ( TAG , "Unable to change native GPS status" , e ) ; } } else { Log . w ( TAG , "Not connected to the VehicleService" ) ; } } | Control whether the device s built - in GPS is used to provide location . |
39,121 | public VehicleInterfaceDescriptor getActiveVehicleInterface ( ) { VehicleInterfaceDescriptor descriptor = null ; if ( mRemoteService != null ) { try { descriptor = mRemoteService . getVehicleInterfaceDescriptor ( ) ; } catch ( RemoteException e ) { Log . w ( TAG , "Unable to retrieve VI descriptor" , e ) ; } } return descriptor ; } | Returns a descriptor of the active vehicle interface . |
39,122 | public int getMessageCount ( ) throws VehicleServiceException { if ( mRemoteService != null ) { try { return mRemoteService . getMessageCount ( ) ; } catch ( RemoteException e ) { throw new VehicleServiceException ( "Unable to retrieve message count" , e ) ; } } else { throw new VehicleServiceException ( "Unable to retrieve message count" ) ; } } | Read the number of messages received by the vehicle service . |
39,123 | public boolean isViConnected ( ) { if ( mRemoteService != null ) { try { return mUserOriginPipeline . isActive ( ) || mRemoteService . isViConnected ( ) ; } catch ( RemoteException e ) { Log . d ( TAG , "Unable to send message to remote service" , e ) ; } } return false ; } | Return the connection status of the selected VI . |
39,124 | public int compareTo ( VehicleMessage other ) { CanMessage otherMessage = ( CanMessage ) other ; if ( getBusId ( ) < otherMessage . getBusId ( ) ) { return - 1 ; } else if ( getBusId ( ) > otherMessage . getBusId ( ) ) { return 1 ; } else { if ( getId ( ) < otherMessage . getId ( ) ) { return - 1 ; } else if ( getId ( ) > otherMessage . getId ( ) ) { return 1 ; } } return 0 ; } | Sort by bus then by message ID . |
39,125 | public IBinder onBind ( Intent intent ) { Log . i ( TAG , "Service binding in response to " + intent ) ; initializeDefaultSources ( ) ; initializeDefaultSinks ( mPipeline ) ; return mBinder ; } | Initialize the service and data source when a client binds to us . |
39,126 | @ TargetApi ( Build . VERSION_CODES . HONEYCOMB ) public static Set < String > getStringSet ( SharedPreferences preferences , String key , Set < String > defaultValue ) { Set < String > result = defaultValue ; if ( supportsStringSet ( ) ) { result = preferences . getStringSet ( key , defaultValue ) ; } else { String serializedSet = preferences . getString ( key , "" ) ; if ( serializedSet . length ( ) > 0 ) { result = new HashSet < > ( Arrays . asList ( serializedSet . split ( "," ) ) ) ; } } return result ; } | Retrieve a set of strings from SharedPreferences using the built - in getStringSet method if available and falling back to a comma separated String if not . |
39,127 | public static int vendorFromUri ( URI uri ) throws DataSourceResourceException { try { return Integer . parseInt ( uri . getAuthority ( ) , 16 ) ; } catch ( NumberFormatException e ) { throw new DataSourceResourceException ( "USB device must be of the format " + DEFAULT_USB_DEVICE_URI + " -- the given " + uri + " has a bad vendor ID" ) ; } } | Return an integer vendor ID from a URI specifying a USB device . |
39,128 | public static int productFromUri ( URI uri ) throws DataSourceResourceException { try { return Integer . parseInt ( uri . getPath ( ) . substring ( 1 ) , 16 ) ; } catch ( NumberFormatException e ) { throw new DataSourceResourceException ( "USB device must be of the format " + DEFAULT_USB_DEVICE_URI + " -- the given " + uri + " has a bad product ID" ) ; } catch ( StringIndexOutOfBoundsException e ) { throw new DataSourceResourceException ( "USB device must be of the format " + DEFAULT_USB_DEVICE_URI + " -- the given " + uri + " has a bad product ID" ) ; } } | Return an integer product ID from a URI specifying a USB device . |
39,129 | public void setCallback ( SourceCallback callback ) { try { mCallbackLock . lock ( ) ; mCallback = callback ; mCallbackChanged . signal ( ) ; } finally { mCallbackLock . unlock ( ) ; } } | Set the current source callback to the given value . |
39,130 | protected void handleMessage ( VehicleMessage message ) { if ( message != null ) { message . timestamp ( ) ; if ( mCallback != null ) { mCallback . receive ( message ) ; } } } | Pass a new message to the callback if set . |
39,131 | public static boolean validateResource ( String uriString ) { try { URI uri = UriBasedVehicleInterfaceMixin . createUri ( massageUri ( uriString ) ) ; return UriBasedVehicleInterfaceMixin . validateResource ( uri ) && uri . getPort ( ) < 65536 ; } catch ( DataSourceException e ) { return false ; } } | Return true if the address and port are valid . |
39,132 | protected synchronized boolean write ( byte [ ] bytes ) { mConnectionLock . readLock ( ) . lock ( ) ; boolean success = true ; try { if ( isConnected ( ) ) { Log . v ( TAG , "Writing " + bytes . length + " to socket" ) ; mOutStream . write ( bytes ) ; } else { Log . w ( TAG , "No connection established, could not send anything." ) ; success = false ; } } catch ( IOException e ) { Log . w ( TAG , "Unable to write CAN message to Network. Error: " + e . toString ( ) ) ; success = false ; } finally { mConnectionLock . readLock ( ) . unlock ( ) ; } return success ; } | Writes given data to the socket . |
39,133 | private static String massageUri ( String uriString ) { if ( ! uriString . startsWith ( SCHEMA_SPECIFIC_PREFIX ) ) { uriString = SCHEMA_SPECIFIC_PREFIX + uriString ; } return uriString ; } | Add the prefix required to parse with URI if it s not already there . |
39,134 | public static void logTransferStats ( final String tag , final long startTime , final double bytesReceived ) { double kilobytesTransferred = bytesReceived / 1024.0 ; long elapsedTime = TimeUnit . SECONDS . convert ( System . nanoTime ( ) - startTime , TimeUnit . NANOSECONDS ) ; Log . i ( tag , "Transferred " + kilobytesTransferred + " KB in the last " + elapsedTime + " seconds at an average of " + kilobytesTransferred / elapsedTime + " KB/s" ) ; } | Log data transfer statistics to the Android log . |
39,135 | public static VehicleMessage deserialize ( String data ) throws UnrecognizedMessageTypeException { JsonObject root ; try { JsonParser parser = new JsonParser ( ) ; root = parser . parse ( data ) . getAsJsonObject ( ) ; } catch ( JsonSyntaxException | IllegalStateException e ) { throw new UnrecognizedMessageTypeException ( "Unable to parse JSON from \"" + data + "\": " + e ) ; } Set < String > fields = new HashSet < > ( ) ; for ( Map . Entry < String , JsonElement > entry : root . entrySet ( ) ) { fields . add ( entry . getKey ( ) ) ; } VehicleMessage message ; try { if ( CanMessage . containsRequiredFields ( fields ) ) { message = sGson . fromJson ( root , CanMessage . class ) ; } else if ( DiagnosticResponse . containsRequiredFields ( fields ) ) { message = sGson . fromJson ( root , DiagnosticResponse . class ) ; } else if ( Command . containsRequiredFields ( fields ) ) { message = sGson . fromJson ( root , Command . class ) ; } else if ( CommandResponse . containsRequiredFields ( fields ) ) { message = sGson . fromJson ( root , CommandResponse . class ) ; if ( ( ( CommandResponse ) message ) . getCommand ( ) == null ) { message = sGson . fromJson ( root , CustomCommandResponse . class ) ; } } else if ( EventedSimpleVehicleMessage . containsRequiredFields ( fields ) ) { message = sGson . fromJson ( root , EventedSimpleVehicleMessage . class ) ; } else if ( SimpleVehicleMessage . containsRequiredFields ( fields ) ) { message = sGson . fromJson ( root , SimpleVehicleMessage . class ) ; } else if ( NamedVehicleMessage . containsRequiredFields ( fields ) ) { message = sGson . fromJson ( root , NamedVehicleMessage . class ) ; } else if ( fields . contains ( VehicleMessage . EXTRAS_KEY ) ) { message = sGson . fromJson ( root , VehicleMessage . class ) ; } else { throw new UnrecognizedMessageTypeException ( "Unrecognized combination of fields: " + fields ) ; } } catch ( NumberFormatException e ) { throw new UnrecognizedMessageTypeException ( "Unable to parse JSON from \"" + data + "\": " + e ) ; } return message ; } | Deserialize a single vehicle messages from the string . |
39,136 | private String readToDelimiter ( ) { String line = null ; while ( line == null || line . isEmpty ( ) ) { int delimiterIndex = mBuffer . indexOf ( DELIMITER ) ; if ( delimiterIndex != - 1 ) { line = mBuffer . substring ( 0 , delimiterIndex ) ; mBuffer . delete ( 0 , delimiterIndex + 1 ) ; } else { line = null ; break ; } } return line ; } | Parse the current byte buffer to find the next potential message . |
39,137 | public void run ( ) { while ( mRunning ) { waitForCallback ( ) ; Log . d ( TAG , "Starting trace playback from beginning of " + mFilename ) ; BufferedReader reader = null ; if ( checkPermission ( ) ) { try { reader = openFile ( mFilename ) ; } catch ( DataSourceException e ) { Log . w ( TAG , "Couldn't open the trace file " + mFilename , e ) ; break ; } String line ; long startingTime = System . currentTimeMillis ( ) ; try { while ( mRunning && ( line = reader . readLine ( ) ) != null ) { VehicleMessage measurement ; try { measurement = JsonFormatter . deserialize ( line ) ; } catch ( UnrecognizedMessageTypeException e ) { Log . w ( TAG , "A trace line was not in the expected " + "format: " + line ) ; continue ; } if ( measurement == null ) { continue ; } if ( measurement != null && ! measurement . isTimestamped ( ) ) { Log . w ( TAG , "A trace line was missing a timestamp: " + line ) ; continue ; } try { waitForNextRecord ( startingTime , measurement . getTimestamp ( ) ) ; } catch ( NumberFormatException e ) { Log . w ( TAG , "A trace line was not in the expected " + "format: " + line ) ; continue ; } measurement . untimestamp ( ) ; if ( ! mTraceValid ) { connected ( ) ; mTraceValid = true ; } handleMessage ( measurement ) ; } } catch ( IOException e ) { Log . w ( TAG , "An exception occurred when reading the trace " + reader , e ) ; break ; } finally { try { if ( reader != null ) { reader . close ( ) ; } } catch ( IOException e ) { Log . w ( TAG , "Couldn't even close the trace file" , e ) ; } } if ( ! mLoop ) { Log . d ( TAG , "Not looping trace." ) ; break ; } disconnected ( ) ; Log . d ( TAG , "Restarting playback of trace " + mFilename ) ; mTraceValid = false ; try { Thread . sleep ( 1000 ) ; } catch ( InterruptedException e ) { } } disconnected ( ) ; mRunning = false ; Log . d ( TAG , "Playback of trace " + mFilename + " is finished" ) ; } } | While running continuously read from the trace file and send messages to the callback . |
39,138 | private void waitForNextRecord ( long startingTime , long timestamp ) { if ( mFirstTimestamp == 0 ) { mFirstTimestamp = timestamp ; Log . d ( TAG , "Storing " + timestamp + " as the first " + "timestamp of the trace file" ) ; } long targetTime = startingTime + ( timestamp - mFirstTimestamp ) ; long sleepDuration = Math . max ( targetTime - System . currentTimeMillis ( ) , 0 ) ; try { Thread . sleep ( sleepDuration ) ; } catch ( InterruptedException e ) { } } | Using the startingTime as the relative starting point sleep this thread until the next timestamp would occur . |
39,139 | public void stop ( ) { super . stop ( ) ; try { getContext ( ) . unregisterReceiver ( mBroadcastReceiver ) ; } catch ( IllegalArgumentException e ) { Log . d ( TAG , "Unable to unregister receiver when stopping, probably not registered" ) ; } } | Unregister USB device intent broadcast receivers and stop waiting for a connection . |
39,140 | public void acquireWakeLock ( ) { if ( mWakeLock == null ) { PowerManager manager = ( PowerManager ) mContext . getSystemService ( Context . POWER_SERVICE ) ; mWakeLock = manager . newWakeLock ( PowerManager . PARTIAL_WAKE_LOCK , mTag ) ; mWakeLock . acquire ( ) ; Log . d ( mTag , "Wake lock acquired" ) ; } else { Log . d ( mTag , "Already have a wake lock -- keeping it" ) ; } } | Acquire a wake lock if we don t already have one . |
39,141 | public void releaseWakeLock ( ) { if ( mWakeLock != null && mWakeLock . isHeld ( ) ) { mWakeLock . release ( ) ; mWakeLock = null ; Log . d ( mTag , "Wake lock released" ) ; } } | If we have an active wake lock release it . |
39,142 | public void setOverwritingStatus ( boolean enabled ) { mOverwriteNativeStatus = enabled ; mNativeGpsOverridden = false ; if ( mLocationManager != null && ! enabled ) { try { mLocationManager . removeTestProvider ( LocationManager . GPS_PROVIDER ) ; Log . d ( TAG , "Disabled overwriting native GPS with OpenXC GPS" ) ; } catch ( IllegalArgumentException e ) { Log . d ( TAG , "Unable to remove GPS test provider - " + "probably wasn't added yet" ) ; } mVehicleManager . removeListener ( Latitude . class , this ) ; mVehicleManager . removeListener ( Longitude . class , this ) ; mVehicleManager . removeListener ( VehicleSpeed . class , this ) ; } else { Log . d ( TAG , "Enabled overwriting native GPS with OpenXC GPS" ) ; mVehicleManager . addListener ( Latitude . class , this ) ; mVehicleManager . addListener ( Longitude . class , this ) ; mVehicleManager . addListener ( VehicleSpeed . class , this ) ; } } | Enable or disable overwriting Android s native GPS values with those from the vehicle . |
39,143 | public static boolean sameResource ( URI uri , String otherResource ) { try { return createUri ( otherResource ) . equals ( uri ) ; } catch ( DataSourceException e ) { return false ; } } | Determine if two URIs refer to the same resource . |
39,144 | public static boolean validateResource ( String uriString ) { if ( uriString == null ) { return false ; } try { return validateResource ( createUri ( uriString ) ) ; } catch ( DataSourceException e ) { Log . d ( TAG , "URI is not valid" , e ) ; return false ; } } | Convert the parameter to a URI and validate the correctness of its host and port . |
39,145 | public static boolean validateResource ( URI uri ) { return uri != null && uri . getPort ( ) != - 1 && uri . getHost ( ) != null ; } | Validate the correctness of the host and port in a given URI . |
39,146 | public static URI createUri ( String uriString ) throws DataSourceException { if ( uriString == null ) { throw new DataSourceResourceException ( "URI string is null" ) ; } try { return new URI ( uriString ) ; } catch ( URISyntaxException e ) { throw new DataSourceResourceException ( "Not a valid URI: " + uriString , e ) ; } } | Attempt to construct an instance of URI from the given String . |
39,147 | @ TargetApi ( Build . VERSION_CODES . KITKAT ) @ SuppressLint ( "NewApi" ) public static String getPath ( final Context context , final Uri uri ) { final boolean isKitKat = Build . VERSION . SDK_INT >= Build . VERSION_CODES . KITKAT ; if ( isKitKat && DocumentsContract . isDocumentUri ( context , uri ) ) { if ( isExternalStorageDocument ( uri ) ) { final String docId = DocumentsContract . getDocumentId ( uri ) ; final String [ ] split = docId . split ( ":" ) ; final String type = split [ 0 ] ; if ( "primary" . equalsIgnoreCase ( type ) ) { return Environment . getExternalStorageDirectory ( ) + "/" + split [ 1 ] ; } } else if ( isDownloadsDocument ( uri ) ) { final String id = DocumentsContract . getDocumentId ( uri ) ; if ( ! TextUtils . isEmpty ( id ) ) { return id . replace ( "raw:" , "" ) ; } try { final Uri contentUri = ContentUris . withAppendedId ( Uri . parse ( "content://downloads/public_downloads" ) , Long . valueOf ( id ) ) ; return getDataColumn ( context , contentUri , null , null ) ; } catch ( NumberFormatException e ) { Log . i ( TAG , e . getMessage ( ) ) ; return null ; } } } else if ( "file" . equalsIgnoreCase ( uri . getScheme ( ) ) || "content" . equalsIgnoreCase ( uri . getScheme ( ) ) ) { return uri . getPath ( ) ; } return null ; } | Thanks to Paul Burke on Stack Overflow |
39,148 | public void receive ( VehicleMessage message ) { if ( message == null ) { return ; } if ( message instanceof KeyedMessage ) { KeyedMessage keyedMessage = message . asKeyedMessage ( ) ; mKeyedMessages . put ( keyedMessage . getKey ( ) , keyedMessage ) ; } List < VehicleDataSink > deadSinks = new ArrayList < > ( ) ; for ( VehicleDataSink sink : mSinks ) { try { sink . receive ( message ) ; } catch ( DataSinkException e ) { Log . w ( TAG , this . getClass ( ) . getName ( ) + ": The sink " + sink + " exploded when we sent a new message " + "-- removing it from the pipeline: " + e ) ; deadSinks . add ( sink ) ; } } mMessagesReceived ++ ; for ( VehicleDataSink sink : deadSinks ) { removeSink ( sink ) ; } } | Accept new values from data sources and send it out to all registered sinks . |
39,149 | public void removeSink ( VehicleDataSink sink ) { if ( sink != null ) { mSinks . remove ( sink ) ; sink . stop ( ) ; } } | Remove a previously added sink from the pipeline . |
39,150 | public VehicleDataSource addSource ( VehicleDataSource source ) { source . setCallback ( this ) ; mSources . add ( source ) ; if ( isActive ( ) ) { source . onPipelineActivated ( ) ; } else { source . onPipelineDeactivated ( ) ; } return source ; } | Add a new source to the pipeline . |
39,151 | public void removeSource ( VehicleDataSource source ) { if ( source != null ) { mSources . remove ( source ) ; source . stop ( ) ; } } | Remove a previously added source from the pipeline . |
39,152 | public boolean isActive ( VehicleDataSource skipSource ) { boolean connected = false ; for ( VehicleDataSource s : mSources ) { if ( s != skipSource ) { connected = connected || s . isConnected ( ) ; } } return connected ; } | Return true if at least one source is active . |
39,153 | public void sourceDisconnected ( VehicleDataSource source ) { if ( mOperator != null ) { if ( ! isActive ( source ) ) { mOperator . onPipelineDeactivated ( ) ; for ( VehicleDataSource s : mSources ) { s . onPipelineDeactivated ( ) ; } } } } | At least one source is not active - if all sources are inactive notify the operator . |
39,154 | public void sourceConnected ( VehicleDataSource source ) { if ( mOperator != null ) { mOperator . onPipelineActivated ( ) ; for ( VehicleDataSource s : mSources ) { s . onPipelineActivated ( ) ; } } } | At least one source is active - notify the operator . |
39,155 | public void setImageResource ( int imageResource , int imageWidth , int imageHeight ) { bitmap = extractBitmapFromDrawable ( getResources ( ) . getDrawable ( imageResource ) ) ; bitmapSrcRect = bitmapRect ( bitmap ) ; this . imageWidth = imageWidth ; this . imageHeight = imageHeight ; rebuildFitter ( ) ; } | Changes the background image and its layout dimensions . |
39,156 | public static boolean isConnectedToWiFiOrMobileNetwork ( Context context ) { final String service = Context . CONNECTIVITY_SERVICE ; final ConnectivityManager manager = ( ConnectivityManager ) context . getSystemService ( service ) ; final NetworkInfo networkInfo = manager . getActiveNetworkInfo ( ) ; if ( networkInfo == null ) { return false ; } final boolean isWifiNetwork = networkInfo . getType ( ) == ConnectivityManager . TYPE_WIFI ; final boolean isMobileNetwork = networkInfo . getType ( ) == ConnectivityManager . TYPE_MOBILE ; if ( isWifiNetwork || isMobileNetwork ) { return true ; } return false ; } | Helper method which checks if device is connected to WiFi or mobile network . |
39,157 | public NetworkEvents setPingParameters ( String host , int port , int timeoutInMs ) { onlineChecker . setPingParameters ( host , port , timeoutInMs ) ; return this ; } | Sets ping parameters of the host used to check Internet connection . If it s not set library will use default ping parameters . |
39,158 | public static < T extends Query < ? , R > , R extends Object > T createMock ( Class < T > type ) { return Mockito . mock ( type , createAnswer ( type ) ) ; } | Creates a new mock of given type with a fluent default answer already set up . |
39,159 | public static < T extends Query < ? , R > , R extends Object > FluentAnswer < T , R > createAnswer ( Class < T > type ) { return new FluentAnswer < T , R > ( type ) ; } | Creates a new instance for the given type . |
39,160 | public CallActivityMock onExecutionAddVariables ( final VariableMap variables ) { return this . onExecutionDo ( "addVariablesServiceMock_" + randomUUID ( ) , ( execution ) -> variables . forEach ( execution :: setVariable ) ) ; } | On execution the MockProcess will add the given VariableMap to the execution |
39,161 | public CallActivityMock onExecutionAddVariable ( final String key , final Object val ) { return this . onExecutionAddVariables ( createVariables ( ) . putValue ( key , val ) ) ; } | On execution the MockProcess will add the given process variable |
39,162 | public CallActivityMock onExecutionDo ( final String serviceId , final Consumer < DelegateExecution > consumer ) { flowNodeBuilder = flowNodeBuilder . serviceTask ( serviceId ) . camundaDelegateExpression ( "${id}" . replace ( "id" , serviceId ) ) ; registerInstance ( serviceId , ( JavaDelegate ) consumer :: accept ) ; return this ; } | On execution the MockProcess will execute the given consumer with a DelegateExecution . |
39,163 | public CallActivityMock onExecutionSendMessage ( final String message ) { return onExecutionDo ( execution -> execution . getProcessEngineServices ( ) . getRuntimeService ( ) . correlateMessage ( message ) ) ; } | On execution the MockProcess will send the given message to all |
39,164 | public Deployment deploy ( final RepositoryService repositoryService ) { return new DeployProcess ( repositoryService ) . apply ( processId , flowNodeBuilder . endEvent ( "end" ) . done ( ) ) ; } | This will deploy the mock process . |
39,165 | private RebelXmlBuilder buildWar ( ) throws MojoExecutionException { RebelXmlBuilder builder = createXmlBuilder ( ) ; buildWeb ( builder ) ; buildClasspath ( builder ) ; if ( war != null ) { war . setPath ( fixFilePath ( war . getPath ( ) ) ) ; builder . setWar ( war ) ; } return builder ; } | Build war configuration . |
39,166 | private RebelXmlBuilder buildJar ( ) throws MojoExecutionException { RebelXmlBuilder builder = createXmlBuilder ( ) ; buildClasspath ( builder ) ; if ( web != null && web . getResources ( ) != null && web . getResources ( ) . length != 0 ) { generateDefaultWeb = false ; buildWeb ( builder ) ; } return builder ; } | Build jar configuration . |
39,167 | private boolean handleResourceAsInclude ( RebelResource rebelResource , Resource resource ) { File dir = new File ( resource . getDirectory ( ) ) ; if ( ! dir . isAbsolute ( ) ) { dir = new File ( getProject ( ) . getBasedir ( ) , resource . getDirectory ( ) ) ; } if ( ! dir . exists ( ) || ! dir . isDirectory ( ) ) { return false ; } resource . setDirectory ( dir . getAbsolutePath ( ) ) ; String [ ] files = getFilesToCopy ( resource ) ; if ( files . length > 0 ) { List < String > includedFiles = new ArrayList < String > ( ) ; for ( String file : files ) { includedFiles . add ( StringUtils . replace ( file , '\\' , '/' ) ) ; } rebelResource . setIncludes ( includedFiles ) ; } else { return false ; } return true ; } | Set includes & excludes for filtered resources . |
39,168 | private String [ ] getFilesToCopy ( Resource resource ) { DirectoryScanner scanner = new DirectoryScanner ( ) ; scanner . setBasedir ( resource . getDirectory ( ) ) ; if ( resource . getIncludes ( ) != null && ! resource . getIncludes ( ) . isEmpty ( ) ) { scanner . setIncludes ( resource . getIncludes ( ) . toArray ( new String [ 0 ] ) ) ; } else { scanner . setIncludes ( DEFAULT_INCLUDES ) ; } if ( resource . getExcludes ( ) != null && ! resource . getExcludes ( ) . isEmpty ( ) ) { scanner . setExcludes ( resource . getExcludes ( ) . toArray ( new String [ 0 ] ) ) ; } scanner . addDefaultExcludes ( ) ; scanner . scan ( ) ; return scanner . getIncludedFiles ( ) ; } | Taken from war plugin . |
39,169 | private List < Resource > parseWarResources ( Xpp3Dom warResourcesNode ) { List < Resource > resources = new ArrayList < Resource > ( ) ; Xpp3Dom [ ] resourceNodes = warResourcesNode . getChildren ( "resource" ) ; for ( Xpp3Dom resourceNode : resourceNodes ) { if ( resourceNode == null || resourceNode . getChild ( "directory" ) == null ) { continue ; } resources . add ( parseResourceNode ( resourceNode ) ) ; } return resources ; } | Parse resources node content . |
39,170 | private Resource parseResourceNode ( Xpp3Dom rn ) { Resource r = new Resource ( ) ; if ( rn . getChild ( "directory" ) != null ) { r . setDirectory ( getValue ( getProject ( ) , rn . getChild ( "directory" ) ) ) ; } if ( rn . getChild ( "filtering" ) != null ) { r . setFiltering ( ( Boolean . valueOf ( getValue ( getProject ( ) , rn . getChild ( "filtering" ) ) ) ) ) ; } if ( rn . getChild ( "targetPath" ) != null ) { r . setTargetPath ( rn . getChild ( "targetPath" ) . getValue ( ) ) ; } if ( rn . getChild ( "excludes" ) != null ) { List < String > excludes = new ArrayList < String > ( ) ; Xpp3Dom [ ] excludeNodes = rn . getChild ( "excludes" ) . getChildren ( "exclude" ) ; for ( Xpp3Dom excludeNode : excludeNodes ) { if ( excludeNode != null && excludeNode . getValue ( ) != null ) { excludes . add ( getValue ( getProject ( ) , excludeNode ) ) ; } } r . setExcludes ( excludes ) ; } if ( rn . getChild ( "includes" ) != null ) { List < String > includes = new ArrayList < String > ( ) ; Xpp3Dom [ ] includeNodes = rn . getChild ( "includes" ) . getChildren ( "include" ) ; for ( Xpp3Dom includeNode : includeNodes ) { if ( includeNode != null && includeNode . getValue ( ) != null ) { includes . add ( getValue ( getProject ( ) , includeNode ) ) ; } } r . setIncludes ( includes ) ; } return r ; } | Parse resouce node content . |
39,171 | private static Xpp3Dom getPluginConfigurationDom ( MavenProject project , String pluginId ) { Plugin plugin = project . getBuild ( ) . getPluginsAsMap ( ) . get ( pluginId ) ; if ( plugin != null ) { return ( Xpp3Dom ) plugin . getConfiguration ( ) ; } return null ; } | Taken from eclipse plugin . Search for the configuration Xpp3 dom of an other plugin . |
39,172 | private String getPluginSetting ( MavenProject project , String pluginId , String optionName , String defaultValue ) { Xpp3Dom dom = getPluginConfigurationDom ( project , pluginId ) ; if ( dom != null && dom . getChild ( optionName ) != null ) { return getValue ( project , dom . getChild ( optionName ) ) ; } return defaultValue ; } | Search for a configuration setting of an other plugin . |
39,173 | protected String fixFilePath ( File file ) throws MojoExecutionException { File baseDir = getProject ( ) . getFile ( ) . getParentFile ( ) ; if ( file . isAbsolute ( ) && ! isRelativeToPath ( new File ( baseDir , getRelativePath ( ) ) , file ) ) { return StringUtils . replace ( getCanonicalPath ( file ) , '\\' , '/' ) ; } if ( ! file . isAbsolute ( ) ) { file = new File ( baseDir , file . getPath ( ) ) ; } String relative = getRelativePath ( new File ( baseDir , getRelativePath ( ) ) , file ) ; if ( ! ( new File ( relative ) ) . isAbsolute ( ) ) { return StringUtils . replace ( getRootPath ( ) , '\\' , '/' ) + "/" + relative ; } if ( ( new File ( getRootPath ( ) ) ) . isAbsolute ( ) ) { String s = getRelativePath ( new File ( getRootPath ( ) ) , file ) ; if ( ! ( new File ( s ) ) . isAbsolute ( ) ) { return StringUtils . replace ( getRootPath ( ) , '\\' , '/' ) + "/" + s ; } else { return s ; } } return StringUtils . replace ( file . getAbsolutePath ( ) , '\\' , '/' ) ; } | Returns path expressed through rootPath and relativePath . |
39,174 | public static String getMatchingRootFolder ( String targetedUrl ) { String [ ] targetedRootFolders = SiteProperties . getRootFolders ( ) ; if ( ArrayUtils . isNotEmpty ( targetedRootFolders ) ) { for ( String targetedRootFolder : targetedRootFolders ) { if ( targetedUrl . startsWith ( targetedRootFolder ) ) { return targetedRootFolder ; } } } return null ; } | Return the root folder of the specified targeted URL |
39,175 | public static boolean excludePath ( String path ) { String [ ] excludePatterns = SiteProperties . getExcludePatterns ( ) ; if ( ArrayUtils . isNotEmpty ( excludePatterns ) ) { return RegexUtils . matchesAny ( path , excludePatterns ) ; } else { return false ; } } | Returns true if the path should be excluded or ignored for targeting . |
39,176 | public static boolean isTargetingEnabled ( ) { Configuration config = ConfigUtils . getCurrentConfig ( ) ; if ( config != null ) { return config . getBoolean ( TARGETING_ENABLED_CONFIG_KEY , false ) ; } else { return false ; } } | Returns trues if targeting is enabled . |
39,177 | public static String [ ] getAvailableTargetIds ( ) { Configuration config = ConfigUtils . getCurrentConfig ( ) ; if ( config != null ) { return config . getStringArray ( AVAILABLE_TARGET_IDS_CONFIG_KEY ) ; } else { return null ; } } | Returns the list of available target IDs . |
39,178 | public static String getFallbackTargetId ( ) { Configuration config = ConfigUtils . getCurrentConfig ( ) ; if ( config != null ) { return config . getString ( FALLBACK_ID_CONFIG_KEY ) ; } else { return null ; } } | Returns the fallback target ID . The fallback target ID is used in case none of the resolved candidate targeted URLs map to existing content . |
39,179 | public static String [ ] getRootFolders ( ) { Configuration config = ConfigUtils . getCurrentConfig ( ) ; if ( config != null ) { return config . getStringArray ( ROOT_FOLDERS_CONFIG_KEY ) ; } else { return null ; } } | Returns the folders that will be handled for targeted content . |
39,180 | public static String [ ] getExcludePatterns ( ) { Configuration config = ConfigUtils . getCurrentConfig ( ) ; if ( config != null ) { return config . getStringArray ( EXCLUDE_PATTERNS_CONFIG_KEY ) ; } else { return null ; } } | Returns the patterns that a path might match if it should be excluded |
39,181 | public static boolean isRedirectToTargetedUrl ( ) { Configuration config = ConfigUtils . getCurrentConfig ( ) ; if ( config != null ) { return config . getBoolean ( REDIRECT_TO_TARGETED_URL_CONFIG_KEY , false ) ; } else { return false ; } } | Returns true if the request should be redirected when the targeted URL is different from the current URL . |
39,182 | public static boolean isDisableFullModelTypeConversion ( ) { Configuration config = ConfigUtils . getCurrentConfig ( ) ; if ( config != null ) { return config . getBoolean ( DISABLE_FULL_MODEL_TYPE_CONVERSION_CONFIG_KEY , false ) ; } else { return false ; } } | Returns true if full content model type conversion should be disabled . |
39,183 | public static String [ ] getNavigationAdditionalFields ( ) { Configuration config = ConfigUtils . getCurrentConfig ( ) ; if ( config != null && config . containsKey ( NAVIGATION_ADDITIONAL_FIELDS_CONFIG_KEY ) ) { return config . getStringArray ( NAVIGATION_ADDITIONAL_FIELDS_CONFIG_KEY ) ; } else { return new String [ ] { } ; } } | Returns the list of additional fields that navigation items should extract from the item descriptor . |
39,184 | public static BeanDefinition createBeanDefinitionFromOriginal ( ApplicationContext applicationContext , String beanName ) { ApplicationContext parentContext = applicationContext . getParent ( ) ; BeanDefinition parentDefinition = null ; if ( parentContext != null && parentContext . getAutowireCapableBeanFactory ( ) instanceof ConfigurableListableBeanFactory ) { ConfigurableListableBeanFactory parentBeanFactory = ( ConfigurableListableBeanFactory ) parentContext . getAutowireCapableBeanFactory ( ) ; try { parentDefinition = parentBeanFactory . getBeanDefinition ( beanName ) ; } catch ( NoSuchBeanDefinitionException e ) { } } if ( parentDefinition != null ) { return new GenericBeanDefinition ( parentDefinition ) ; } else { return new GenericBeanDefinition ( ) ; } } | Creates a bean definition for the specified bean name . If the parent context of the current context contains a bean definition with the same name the definition is created as a bean copy of the parent definition . This method is useful for config parsers that want to create a bean definition from configuration but also want to retain the default properties of the original bean . |
39,185 | public static void addPropertyIfNotNull ( BeanDefinition definition , String propertyName , Object propertyValue ) { if ( propertyValue != null ) { definition . getPropertyValues ( ) . add ( propertyName , propertyValue ) ; } } | Adds the property to the bean definition if the values it not empty |
39,186 | public static void setCurrent ( SiteContext current ) { threadLocal . set ( current ) ; MDC . put ( SITE_NAME_MDC_KEY , current . getSiteName ( ) ) ; } | Sets the context for the current thread . |
39,187 | protected boolean shouldNotFilter ( final HttpServletRequest request ) throws ServletException { SiteContext siteContext = SiteContext . getCurrent ( ) ; HierarchicalConfiguration config = siteContext . getConfig ( ) ; try { HierarchicalConfiguration corsConfig = config . configurationAt ( CONFIG_KEY ) ; if ( corsConfig != null ) { return ! corsConfig . getBoolean ( ENABLE_KEY , false ) ; } } catch ( Exception e ) { logger . debug ( "Site '{}' has no CORS configuration" , siteContext . getSiteName ( ) ) ; } return true ; } | Exclude requests for sites that have no configuration or it is marked as disabled . |
39,188 | protected void doFilterInternal ( final HttpServletRequest request , final HttpServletResponse response , final FilterChain filterChain ) throws ServletException , IOException { SiteContext siteContext = SiteContext . getCurrent ( ) ; HierarchicalConfiguration corsConfig = siteContext . getConfig ( ) . configurationAt ( CONFIG_KEY ) ; response . setHeader ( CORSFilter . ALLOW_ORIGIN , corsConfig . getString ( ALLOW_ORIGIN_KEY , ALLOW_ORIGIN_DEFAULT ) ) ; response . setHeader ( CORSFilter . ALLOW_CREDENTIALS , corsConfig . getString ( ALLOW_CREDENTIALS_KEY , ALLOW_CREDENTIALS_DEFAULT ) ) ; response . setHeader ( CORSFilter . ALLOW_METHODS , corsConfig . getString ( ALLOW_METHODS_KEY , ALLOW_METHODS_DEFAULT ) ) ; response . setHeader ( CORSFilter . ALLOW_HEADERS , corsConfig . getString ( ALLOW_HEADERS_KEY , ALLOW_HEADERS_DEFAULT ) ) ; response . setHeader ( CORSFilter . MAX_AGE , corsConfig . getString ( MAX_AGE_KEY , MAX_AGE_DEFAULT ) ) ; filterChain . doFilter ( request , response ) ; } | Copy the values from the site configuration to the response headers . |
39,189 | public static HierarchicalConfiguration getCurrentConfig ( ) { SiteContext siteContext = SiteContext . getCurrent ( ) ; if ( siteContext != null ) { return siteContext . getConfig ( ) ; } else { return null ; } } | Returns the configuration from the current site context . |
39,190 | public static SpannableString getFormattedText ( Span span ) { SpannableString ss = null ; if ( span != null ) { ss = setUpSpannableString ( span ) ; } return ss ; } | Set a single span |
39,191 | public static CharSequence getFormattedText ( List < Span > spans ) { CharSequence formattedText = null ; if ( spans != null ) { int size = spans . size ( ) ; List < SpannableString > spannableStrings = new ArrayList < > ( size ) ; for ( Span span : spans ) { SpannableString ss = setUpSpannableString ( span ) ; spannableStrings . add ( ss ) ; } formattedText = TextUtils . concat ( spannableStrings . toArray ( new SpannableString [ size ] ) ) ; } return formattedText ; } | Set multiple spans |
39,192 | private static Set < Parameter < ? > > getParametersFromPublicFields ( Class < ? > type ) { Set < Parameter < ? > > params = new HashSet < > ( ) ; try { Field [ ] fields = type . getFields ( ) ; for ( Field field : fields ) { if ( field . getType ( ) . isAssignableFrom ( Parameter . class ) ) { params . add ( ( Parameter < ? > ) field . get ( null ) ) ; } } } catch ( IllegalArgumentException | IllegalAccessException ex ) { throw new RuntimeException ( "Unable to access fields of " + type . getName ( ) , ex ) ; } return ImmutableSet . copyOf ( params ) ; } | Get all parameters defined as public static fields in the given type . |
39,193 | public static String [ ] splitPreserveAllTokens ( String value , char separatorChar ) { if ( value == null ) { return ArrayUtils . EMPTY_STRING_ARRAY ; } int len = value . length ( ) ; if ( len == 0 ) { return ArrayUtils . EMPTY_STRING_ARRAY ; } List < String > list = new ArrayList < > ( ) ; int i = 0 ; int start = 0 ; boolean match = false ; boolean lastMatch = false ; int escapeStart = - 2 ; while ( i < len ) { char c = value . charAt ( i ) ; if ( c == ESCAPE_CHAR ) { escapeStart = i ; } if ( c == separatorChar && escapeStart != i - 1 ) { lastMatch = true ; list . add ( value . substring ( start , i ) ) ; match = false ; start = ++ i ; continue ; } match = true ; i ++ ; } if ( match || lastMatch ) { list . add ( value . substring ( start , i ) ) ; } return list . toArray ( new String [ list . size ( ) ] ) ; } | String tokenizer that preservers all tokens and ignores escaped separator chars . |
39,194 | public static String traceOutput ( Map < String , Object > properties ) { SortedSet < String > propertyNames = new TreeSet < > ( properties . keySet ( ) ) ; StringBuilder sb = new StringBuilder ( ) ; sb . append ( "{" ) ; Iterator < String > propertyNameIterator = propertyNames . iterator ( ) ; while ( propertyNameIterator . hasNext ( ) ) { String propertyName = propertyNameIterator . next ( ) ; sb . append ( propertyName ) . append ( ": " ) ; appendValue ( sb , properties . get ( propertyName ) ) ; if ( propertyNameIterator . hasNext ( ) ) { sb . append ( ", " ) ; } } sb . append ( "}" ) ; return sb . toString ( ) ; } | Produce trace output for properties map . |
39,195 | @ SuppressWarnings ( "unchecked" ) private Iterator < String > findConfigRefs ( final Resource startResource , final Collection < String > bucketNames ) { final Iterator < ContextResource > contextResources = new FilterIterator ( contextPathStrategy . findContextResources ( startResource ) , new Predicate ( ) { public boolean evaluate ( Object object ) { ContextResource contextResource = ( ContextResource ) object ; return StringUtils . isNotBlank ( contextResource . getConfigRef ( ) ) ; } } ) ; final Iterator < String > configPaths = new TransformIterator ( contextResources , new Transformer ( ) { public Object transform ( Object input ) { final ContextResource contextResource = ( ContextResource ) input ; String val = checkPath ( contextResource , contextResource . getConfigRef ( ) , bucketNames ) ; if ( val != null ) { log . trace ( "+ Found reference for context path {}: {}" , contextResource . getResource ( ) . getPath ( ) , val ) ; } return val ; } } ) ; return new FilterIterator ( configPaths , PredicateUtils . notNullPredicate ( ) ) ; } | Searches the resource hierarchy upwards for all config references and returns them . |
39,196 | public static Resource ensurePageIfNotContainingPage ( ResourceResolver resolver , String pagePath , String resourceType , ConfigurationManagementSettings configurationManagementSettings ) { Matcher matcher = PAGE_PATH_PATTERN . matcher ( pagePath ) ; if ( matcher . matches ( ) ) { String detectedPagePath = matcher . group ( 1 ) ; ensurePage ( resolver , detectedPagePath , null , resourceType , null , configurationManagementSettings ) ; return getOrCreateResource ( resolver , pagePath , DEFAULT_FOLDER_NODE_TYPE_IN_PAGE , null , configurationManagementSettings ) ; } return ensurePage ( resolver , pagePath , null , resourceType , null , configurationManagementSettings ) ; } | Ensure that a page at the given path exists if the path is not already contained in a page . |
39,197 | public static void deleteChildrenNotInCollection ( Resource resource , ConfigurationCollectionPersistData data ) { Set < String > collectionItemNames = data . getItems ( ) . stream ( ) . map ( item -> item . getCollectionItemName ( ) ) . collect ( Collectors . toSet ( ) ) ; for ( Resource child : resource . getChildren ( ) ) { if ( ! collectionItemNames . contains ( child . getName ( ) ) && ! StringUtils . equals ( JCR_CONTENT , child . getName ( ) ) ) { deletePageOrResource ( child ) ; } } } | Delete children that are no longer contained in list of collection items . |
39,198 | public static void deletePageOrResource ( Resource resource ) { Page configPage = resource . adaptTo ( Page . class ) ; if ( configPage != null ) { try { log . trace ( "! Delete page {}" , configPage . getPath ( ) ) ; PageManager pageManager = configPage . getPageManager ( ) ; pageManager . delete ( configPage , false ) ; } catch ( WCMException ex ) { throw convertWCMException ( "Unable to delete configuration page at " + resource . getPath ( ) , ex ) ; } } else { try { log . trace ( "! Delete resource {}" , resource . getPath ( ) ) ; resource . getResourceResolver ( ) . delete ( resource ) ; } catch ( PersistenceException ex ) { throw convertPersistenceException ( "Unable to delete configuration resource at " + resource . getPath ( ) , ex ) ; } } } | If the given resource points to an AEM page delete the page using PageManager . Otherwise delete the resource using ResourceResolver . |
39,199 | @ SuppressWarnings ( "unchecked" ) public static < T > T stringToObject ( String value , Class < T > type ) { if ( value == null ) { return null ; } if ( type == String . class ) { return ( T ) value ; } else if ( type == String [ ] . class ) { return ( T ) decodeString ( splitPreserveAllTokens ( value , ARRAY_DELIMITER_CHAR ) ) ; } if ( type == Integer . class ) { return ( T ) ( Integer ) NumberUtils . toInt ( value , 0 ) ; } if ( type == Long . class ) { return ( T ) ( Long ) NumberUtils . toLong ( value , 0L ) ; } if ( type == Double . class ) { return ( T ) ( Double ) NumberUtils . toDouble ( value , 0d ) ; } if ( type == Boolean . class ) { return ( T ) ( Boolean ) BooleanUtils . toBoolean ( value ) ; } if ( type == Map . class ) { String [ ] rows = splitPreserveAllTokens ( value , ARRAY_DELIMITER_CHAR ) ; Map < String , String > map = new LinkedHashMap < > ( ) ; for ( int i = 0 ; i < rows . length ; i ++ ) { String [ ] keyValue = splitPreserveAllTokens ( rows [ i ] , KEY_VALUE_DELIMITER_CHAR ) ; if ( keyValue . length == 2 && StringUtils . isNotEmpty ( keyValue [ 0 ] ) ) { map . put ( decodeString ( keyValue [ 0 ] ) , StringUtils . isEmpty ( keyValue [ 1 ] ) ? null : decodeString ( keyValue [ 1 ] ) ) ; } } return ( T ) map ; } throw new IllegalArgumentException ( "Unsupported type: " + type . getName ( ) ) ; } | Converts a string value to an object with the given parameter type . |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.