idx int64 0 41.2k | question stringlengths 74 4.21k | target stringlengths 5 888 |
|---|---|---|
5,100 | private void fillAdapters ( ) { List < Fragment > fragments = new ArrayList < Fragment > ( ) ; List < String > listItems = new ArrayList < String > ( ) ; for ( int i = 0 ; i < 100 ; i ++ ) { String title = "Fragment #" + i ; fragments . add ( SampleFragment . newInstance ( title ) ) ; listItems . add ( title ) ; } mFragmentAdapter . addAll ( fragments ) ; mListAdapter . addAll ( listItems ) ; } | Creates a list of fragments and list items and loads up the adapters . |
5,101 | public String get ( String url , Map < String , String > headers ) throws IOException { return doHttpTransfer ( url , null , headers ) ; } | Sends a HTTP Get request . |
5,102 | public String post ( String url , String data , Map < String , String > headers ) throws IOException { return doHttpTransfer ( url , data , headers ) ; } | Sends a HTTP POST request . |
5,103 | final synchronized void prepareForDelivery ( int length , int index , long sequence , long timeUs ) { frameLength = length ; dataBuffer . setNewFrameSize ( length ) ; sequenceNumber = sequence ; captureTime = timeUs ; bufferIndex = index ; recycled = false ; } | This method marks this frame as ready to be delivered to the user as its buffer has just been filled with a new frame of the given length . |
5,104 | public DfsTraversalNode getNextNode ( BEvent e , ExecutorService exSvc ) throws BPjsRuntimeException { try { return new DfsTraversalNode ( bp , BProgramSyncSnapshotCloner . clone ( systemState ) . triggerEvent ( e , exSvc , Collections . emptySet ( ) ) , e ) ; } catch ( InterruptedException ie ) { throw new BPjsRuntimeException ( "Thread interrupted during event invocaiton" , ie ) ; } } | Get a Node object for each possible state of the system after triggering the given event . |
5,105 | public static int jsHash ( Object jsObj ) { if ( jsObj == null ) { return 1 ; } if ( jsObj instanceof ConsString ) { return jsObj . toString ( ) . hashCode ( ) ; } return ( jsObj instanceof ScriptableObject ) ? jsScriptableObjectHashCode ( ( ScriptableObject ) jsObj ) : jsObj . hashCode ( ) ; } | Deep - hash of an object . |
5,106 | public List < String > eventNames ( ) { return events . stream ( ) . map ( BEvent :: getName ) . collect ( toList ( ) ) ; } | Convenience method for getting only the names of the events . |
5,107 | private Object collectJsValue ( Object jsValue ) { if ( jsValue == null ) { return null ; } else if ( jsValue instanceof NativeFunction ) { return ( ( NativeFunction ) jsValue ) . getEncodedSource ( ) ; } else if ( jsValue instanceof NativeArray ) { NativeArray jsArr = ( NativeArray ) jsValue ; List < Object > retVal = new ArrayList < > ( ( int ) jsArr . getLength ( ) ) ; for ( int idx = 0 ; idx < jsArr . getLength ( ) ; idx ++ ) { retVal . add ( collectJsValue ( jsArr . get ( idx ) ) ) ; } return retVal ; } else if ( jsValue instanceof ScriptableObject ) { ScriptableObject jsObj = ( ScriptableObject ) jsValue ; Map < Object , Object > retVal = new HashMap < > ( ) ; for ( Object key : jsObj . getIds ( ) ) { retVal . put ( key , collectJsValue ( jsObj . get ( key ) ) ) ; } return retVal ; } else if ( jsValue instanceof ConsString ) { return ( ( ConsString ) jsValue ) . toString ( ) ; } else if ( jsValue instanceof NativeJavaObject ) { NativeJavaObject jsJavaObj = ( NativeJavaObject ) jsValue ; Object obj = jsJavaObj . unwrap ( ) ; return obj ; } else { String cn = jsValue . getClass ( ) . getCanonicalName ( ) ; if ( ! cn . startsWith ( "java." ) && ( ! cn . startsWith ( "il.ac.bgu" ) ) ) { System . out . println ( "collectJsValue: blind translation to java: " + jsValue + " (" + jsValue . getClass ( ) + ")" ) ; } return jsValue ; } } | Take a Javascript value from Rhino build a Java value for it . |
5,108 | protected Object evaluate ( InputStream inStrm , String scriptName ) { InputStreamReader streamReader = new InputStreamReader ( inStrm , StandardCharsets . UTF_8 ) ; BufferedReader br = new BufferedReader ( streamReader ) ; StringBuilder sb = new StringBuilder ( ) ; String line ; try { while ( ( line = br . readLine ( ) ) != null ) { sb . append ( line ) . append ( "\n" ) ; } } catch ( IOException e ) { throw new RuntimeException ( "error while reading javascript from stream" , e ) ; } String script = sb . toString ( ) ; return evaluate ( script , scriptName ) ; } | Reads and evaluates the code at the passed input stream . The stream is read to its end but is not closed . |
5,109 | protected Object evaluate ( String script , String scriptName ) { try { Context curCtx = Context . getCurrentContext ( ) ; curCtx . setLanguageVersion ( Context . VERSION_1_8 ) ; return curCtx . evaluateString ( programScope , script , scriptName , 1 , null ) ; } catch ( EcmaError rerr ) { throw new BPjsCodeEvaluationException ( rerr ) ; } catch ( WrappedException wrapped ) { try { throw wrapped . getCause ( ) ; } catch ( BPjsException be ) { throw be ; } catch ( IllegalStateException ise ) { String msg = ise . getMessage ( ) ; if ( msg . contains ( "Cannot capture continuation" ) && msg . contains ( "executeScriptWithContinuations or callFunctionWithContinuations" ) ) { throw new BPjsCodeEvaluationException ( "bp.sync called outside of a b-thread" ) ; } else { throw ise ; } } catch ( Throwable generalException ) { throw new BPjsRuntimeException ( "(Wrapped) Exception evaluating BProgram code: " + generalException . getMessage ( ) , generalException ) ; } } catch ( EvaluatorException evalExp ) { throw new BPjsCodeEvaluationException ( evalExp ) ; } catch ( Exception exp ) { throw new BPjsRuntimeException ( "Error evaluating BProgram code: " + exp . getMessage ( ) , exp ) ; } } | Runs the passed code in the passed scope . |
5,110 | public void registerBThread ( BThreadSyncSnapshot bt ) { recentlyRegisteredBthreads . add ( bt ) ; addBThreadCallback . ifPresent ( cb -> cb . bthreadAdded ( this , bt ) ) ; } | Registers a BThread into the program . If the program started the BThread will take part in the current bstep . |
5,111 | public BProgramSyncSnapshot setup ( ) { if ( started ) { throw new IllegalStateException ( "Program already set up." ) ; } Set < BThreadSyncSnapshot > bthreads = drainRecentlyRegisteredBthreads ( ) ; if ( eventSelectionStrategy == null ) { eventSelectionStrategy = new SimpleEventSelectionStrategy ( ) ; } FailedAssertion failedAssertion = null ; try { Context cx = ContextFactory . getGlobal ( ) . enterContext ( ) ; cx . setOptimizationLevel ( - 1 ) ; initProgramScope ( cx ) ; if ( prependedCode != null ) { prependedCode . forEach ( s -> evaluate ( s , "prependedCode" ) ) ; prependedCode = null ; } setupProgramScope ( programScope ) ; if ( appendedCode != null ) { appendedCode . forEach ( s -> evaluate ( s , "appendedCode" ) ) ; appendedCode = null ; } } catch ( FailedAssertionException fae ) { failedAssertion = new FailedAssertion ( fae . getMessage ( ) , "---init_code" ) ; } finally { Context . exit ( ) ; } started = true ; return new BProgramSyncSnapshot ( this , bthreads , Collections . emptyList ( ) , failedAssertion ) ; } | Sets up the program scope and evaluates the program source . |
5,112 | public void setWaitForExternalEvents ( boolean shouldWait ) { if ( waitForExternalEvents && ! shouldWait ) { waitForExternalEvents = false ; recentlyEnqueuedExternalEvents . add ( NO_MORE_WAIT_EXTERNAL ) ; } else { waitForExternalEvents = shouldWait ; } } | Sets whether this program waits for external events or not . |
5,113 | public < T > Optional < T > getFromGlobalScope ( String name , Class < T > clazz ) { if ( getGlobalScope ( ) . has ( name , programScope ) ) { return Optional . of ( ( T ) Context . jsToJava ( getGlobalScope ( ) . get ( name , getGlobalScope ( ) ) , clazz ) ) ; } else { return Optional . empty ( ) ; } } | Gets the object pointer by the passed name in the global scope . |
5,114 | public void registerBThread ( String name , Function func ) { program . registerBThread ( new BThreadSyncSnapshot ( name , func ) ) ; } | Called from JS to add BThreads running func as their runnable code . |
5,115 | public BProgramSyncSnapshot triggerEvent ( BEvent anEvent , ExecutorService exSvc , Iterable < BProgramRunnerListener > listeners ) throws InterruptedException , BPjsRuntimeException { if ( anEvent == null ) throw new IllegalArgumentException ( "Cannot trigger a null event." ) ; if ( triggered ) { throw new IllegalStateException ( "A BProgramSyncSnapshot is not allowed to be triggered twice." ) ; } triggered = true ; Set < BThreadSyncSnapshot > resumingThisRound = new HashSet < > ( threadSnapshots . size ( ) ) ; Set < BThreadSyncSnapshot > sleepingThisRound = new HashSet < > ( threadSnapshots . size ( ) ) ; Set < BThreadSyncSnapshot > nextRound = new HashSet < > ( threadSnapshots . size ( ) ) ; List < BEvent > nextExternalEvents = new ArrayList < > ( getExternalEvents ( ) ) ; try { Context ctxt = Context . enter ( ) ; handleInterrupts ( anEvent , listeners , bprog , ctxt ) ; nextExternalEvents . addAll ( bprog . drainEnqueuedExternalEvents ( ) ) ; threadSnapshots . forEach ( snapshot -> { ( snapshot . getSyncStatement ( ) . shouldWakeFor ( anEvent ) ? resumingThisRound : sleepingThisRound ) . add ( snapshot ) ; } ) ; } finally { Context . exit ( ) ; } BPEngineTask . Listener halter = new ViolationRecorder ( bprog , violationRecord ) ; try { nextRound . addAll ( exSvc . invokeAll ( resumingThisRound . stream ( ) . map ( bt -> new ResumeBThread ( bt , anEvent , halter ) ) . collect ( toList ( ) ) ) . stream ( ) . map ( f -> safeGet ( f ) ) . filter ( Objects :: nonNull ) . collect ( toList ( ) ) ) ; Set < String > nextRoundIds = nextRound . stream ( ) . map ( t -> t . getName ( ) ) . collect ( toSet ( ) ) ; resumingThisRound . stream ( ) . filter ( t -> ! nextRoundIds . contains ( t . getName ( ) ) ) . forEach ( t -> listeners . forEach ( l -> l . bthreadDone ( bprog , t ) ) ) ; executeAllAddedBThreads ( nextRound , exSvc , halter ) ; } catch ( RuntimeException re ) { Throwable cause = re ; while ( cause . getCause ( ) != null ) { cause = cause . getCause ( ) ; } if ( cause instanceof BPjsRuntimeException ) { throw ( BPjsRuntimeException ) cause ; } else if ( cause instanceof EcmaError ) { throw new BPjsRuntimeException ( "JavaScript Error: " + cause . getMessage ( ) , cause ) ; } else throw re ; } nextExternalEvents . addAll ( bprog . drainEnqueuedExternalEvents ( ) ) ; nextRound . addAll ( sleepingThisRound ) ; return new BProgramSyncSnapshot ( bprog , nextRound , nextExternalEvents , violationRecord . get ( ) ) ; } | Runs the program from the snapshot triggering the passed event . |
5,116 | private void executeAllAddedBThreads ( Set < BThreadSyncSnapshot > nextRound , ExecutorService exSvc , BPEngineTask . Listener listener ) throws InterruptedException { Set < BThreadSyncSnapshot > addedBThreads = bprog . drainRecentlyRegisteredBthreads ( ) ; Set < ForkStatement > addedForks = bprog . drainRecentlyAddedForks ( ) ; while ( ( ( ! addedBThreads . isEmpty ( ) ) || ( ! addedForks . isEmpty ( ) ) ) && ! exSvc . isShutdown ( ) ) { Stream < BPEngineTask > threadStream = addedBThreads . stream ( ) . map ( bt -> new StartBThread ( bt , listener ) ) ; Stream < BPEngineTask > forkStream = addedForks . stream ( ) . flatMap ( f -> convertToTasks ( f , listener ) ) ; nextRound . addAll ( exSvc . invokeAll ( Stream . concat ( forkStream , threadStream ) . collect ( toList ( ) ) ) . stream ( ) . map ( f -> safeGet ( f ) ) . filter ( Objects :: nonNull ) . collect ( toList ( ) ) ) ; addedBThreads = bprog . drainRecentlyRegisteredBthreads ( ) ; addedForks = bprog . drainRecentlyAddedForks ( ) ; } } | Executes and adds all newly registered b - threads until no more new b - threads are registered . |
5,117 | public < R extends BProgramRunnerListener > R addListener ( R aListener ) { listeners . add ( aListener ) ; return aListener ; } | Adds a listener to the BProgram . |
5,118 | private static boolean hasRequestedEvents ( BProgramSyncSnapshot bpss ) { return bpss . getBThreadSnapshots ( ) . stream ( ) . anyMatch ( btss -> ( ! btss . getSyncStatement ( ) . getRequest ( ) . isEmpty ( ) ) ) ; } | Utility methods . |
5,119 | public BThreadSyncSnapshot copyWith ( Object aContinuation , SyncStatement aStatement ) { BThreadSyncSnapshot retVal = new BThreadSyncSnapshot ( name , entryPoint ) ; retVal . continuation = aContinuation ; retVal . setInterruptHandler ( interruptHandler ) ; retVal . syncStatement = aStatement ; aStatement . setBthread ( retVal ) ; return retVal ; } | Creates the next snapshot of the BThread in a given run . |
5,120 | private BThreadSyncSnapshot handleContinuationPending ( ContinuationPending cbs , Context jsContext ) throws IllegalStateException { final Object capturedStatement = cbs . getApplicationState ( ) ; if ( capturedStatement instanceof SyncStatement ) { final SyncStatement syncStatement = ( SyncStatement ) cbs . getApplicationState ( ) ; return bss . copyWith ( cbs . getContinuation ( ) , syncStatement ) ; } else if ( capturedStatement instanceof ForkStatement ) { ForkStatement forkStmt = ( ForkStatement ) capturedStatement ; forkStmt . setForkingBThread ( bss ) ; final ScriptableObject globalScope = jsContext . initStandardObjects ( ) ; try ( ByteArrayOutputStream baos = new ByteArrayOutputStream ( ) ; BThreadSyncSnapshotOutputStream btos = new BThreadSyncSnapshotOutputStream ( baos , globalScope ) ) { btos . writeObject ( cbs . getContinuation ( ) ) ; btos . flush ( ) ; baos . flush ( ) ; forkStmt . setSerializedContinuation ( baos . toByteArray ( ) ) ; } catch ( IOException ex ) { Logger . getLogger ( BPEngineTask . class . getName ( ) ) . log ( Level . SEVERE , "Error while serializing continuation during fork:" + ex . getMessage ( ) , ex ) ; throw new RuntimeException ( "Error while serializing continuation during fork:" + ex . getMessage ( ) , ex ) ; } listener . addFork ( forkStmt ) ; return continueParentOfFork ( cbs , jsContext ) ; } else { throw new IllegalStateException ( "Captured a statement of an unknown type: " + capturedStatement ) ; } } | Handle a captures continuation . This can be because of a sync statement or because of a fork . |
5,121 | private String dataToString ( Object data ) { if ( data == null ) return "<null>" ; return ( data instanceof Scriptable ) ? ScriptableUtils . toString ( ( Scriptable ) data ) : Objects . toString ( data ) ; } | Take the data field and give it some sensible string representation . |
5,122 | public void call ( Subscriber < ? super Job < K , V > > subscriber ) { log . debug ( "onSubscribe()" ) ; if ( subscriber . isUnsubscribed ( ) ) { return ; } String subscriberId = getClass ( ) . getSimpleName ( ) + "-" + id + "-" + subscriberIds . incrementAndGet ( ) ; subscriber . onStart ( ) ; try { Scheduler . Worker worker = scheduler . createWorker ( ) ; GetJobsAction < K , V > getJobsAction = new GetJobsAction < K , V > ( disqueConnectionSupplier , subscriberId , subscriber , jobLocalityTracking , getJobsArgs ) ; actions . add ( getJobsAction ) ; Subscription subscription = worker . schedulePeriodically ( getJobsAction , 0 , 10 , TimeUnit . MILLISECONDS ) ; getJobsAction . setSelfSubscription ( subscription ) ; if ( improveLocalityTimeUnit != null && improveLocalityInterval > 0 && reconnectTrigger == null ) { reconnectTrigger = worker . schedulePeriodically ( new Action0 ( ) { public void call ( ) { switchNodes ( ) ; } } , improveLocalityInterval , improveLocalityInterval , improveLocalityTimeUnit ) ; } } catch ( Exception e ) { if ( log . isDebugEnabled ( ) ) { log . debug ( "QueueListener.call caught an exception: {}" , e . getMessage ( ) , e ) ; } subscriber . onError ( e ) ; } } | Setup subscriptions when the Observable subscription is set up . |
5,123 | public void close ( long timeout , TimeUnit timeUnit ) { disable ( ) ; for ( GetJobsAction < K , V > getJobsAction : actions ) { getJobsAction . close ( timeout , timeUnit ) ; } if ( reconnectTrigger != null ) { reconnectTrigger . unsubscribe ( ) ; reconnectTrigger = null ; } } | Unsubscribe and close the resources . |
5,124 | static SharedPreferences getSharedPreferences ( ) { if ( null == getApplicationContext ( ) ) return null ; SharedPreferences rtn = getApplicationContext ( ) . getSharedPreferences ( PREF_FILE , Context . MODE_PRIVATE ) ; if ( null == rtn ) { Log . e ( WonderPush . TAG , "Could not get shared preferences" , new NullPointerException ( "Stack" ) ) ; } return rtn ; } | Gets the WonderPush shared preferences for that application . |
5,125 | static String getAccessTokenForUserId ( String userId ) { if ( userId == null && getUserId ( ) == null || userId != null && userId . equals ( getUserId ( ) ) ) { return getAccessToken ( ) ; } else { JSONObject usersArchive = getJSONObject ( PER_USER_ARCHIVE_PREF_NAME ) ; if ( usersArchive == null ) usersArchive = new JSONObject ( ) ; JSONObject userArchive = usersArchive . optJSONObject ( userId == null ? "" : userId ) ; if ( userArchive == null ) userArchive = new JSONObject ( ) ; return JSONUtil . optString ( userArchive , ACCESS_TOKEN_PREF_NAME ) ; } } | Get the access token associated to a given user s shared preferences . |
5,126 | static void setOverrideSetLogging ( Boolean value ) { if ( value == null ) { remove ( OVERRIDE_SET_LOGGING_PREF_NAME ) ; } else { putBoolean ( OVERRIDE_SET_LOGGING_PREF_NAME , value ) ; } } | Sets whether to override logging . |
5,127 | static void setOverrideNotificationReceipt ( Boolean value ) { if ( value == null ) { remove ( OVERRIDE_NOTIFICATION_RECEIPT_PREF_NAME ) ; } else { putBoolean ( OVERRIDE_NOTIFICATION_RECEIPT_PREF_NAME , value ) ; } } | Sets whether to override notification receipts . |
5,128 | protected void put ( WonderPushRestClient . Request request , long delayMs ) { long notBeforeRealTimeElapsed = delayMs <= 0 ? delayMs : SystemClock . elapsedRealtime ( ) + delayMs ; long prevNotBeforeRealtimeElapsed = mJobQueue . peekNextJobNotBeforeRealtimeElapsed ( ) ; mJobQueue . postJobWithDescription ( request . toJSON ( ) , notBeforeRealTimeElapsed ) ; if ( notBeforeRealTimeElapsed < prevNotBeforeRealtimeElapsed ) { WonderPush . logDebug ( "RequestVault: Interrupting sleep" ) ; mThread . interrupt ( ) ; } } | Save a request in the vault for future retry |
5,129 | protected static long getTime ( ) { if ( deviceDateToServerDateUncertainty == Long . MAX_VALUE ) { deviceDateToServerDateUncertainty = WonderPushConfiguration . getDeviceDateSyncUncertainty ( ) ; deviceDateToServerDateOffset = WonderPushConfiguration . getDeviceDateSyncOffset ( ) ; } long currentTimeMillis = System . currentTimeMillis ( ) ; long elapsedRealtime = SystemClock . elapsedRealtime ( ) ; long startupToDeviceOffset = currentTimeMillis - elapsedRealtime ; if ( startupDateToDeviceDateOffset == Long . MAX_VALUE ) { startupDateToDeviceDateOffset = startupToDeviceOffset ; } if ( Math . abs ( startupToDeviceOffset - startupDateToDeviceDateOffset ) > 1000 ) { deviceDateToServerDateOffset -= startupToDeviceOffset - startupDateToDeviceDateOffset ; WonderPushConfiguration . setDeviceDateSyncOffset ( deviceDateToServerDateOffset ) ; startupDateToDeviceDateOffset = startupToDeviceOffset ; } if ( startupDateToServerDateUncertainty <= deviceDateToServerDateUncertainty && startupDateToServerDateUncertainty != Long . MAX_VALUE ) { return elapsedRealtime + startupDateToServerDateOffset ; } else { return currentTimeMillis + deviceDateToServerDateOffset ; } } | Get the current timestamp in milliseconds UTC . |
5,130 | protected static void syncTimeWithServer ( long elapsedRealtimeSend , long elapsedRealtimeReceive , long serverDate , long serverTook ) { if ( serverDate == 0 ) { return ; } if ( deviceDateToServerDateUncertainty == Long . MAX_VALUE ) { deviceDateToServerDateUncertainty = WonderPushConfiguration . getDeviceDateSyncUncertainty ( ) ; deviceDateToServerDateOffset = WonderPushConfiguration . getDeviceDateSyncOffset ( ) ; } long startupToDeviceOffset = System . currentTimeMillis ( ) - SystemClock . elapsedRealtime ( ) ; if ( startupDateToDeviceDateOffset == Long . MAX_VALUE ) { startupDateToDeviceDateOffset = startupToDeviceOffset ; } long uncertainty = ( elapsedRealtimeReceive - elapsedRealtimeSend - serverTook ) / 2 ; long offset = serverDate + serverTook / 2 - ( elapsedRealtimeSend + elapsedRealtimeReceive ) / 2 ; if ( uncertainty < startupDateToServerDateUncertainty || Math . abs ( offset - startupDateToServerDateOffset ) > uncertainty + startupDateToServerDateUncertainty ) { startupDateToServerDateOffset = offset ; startupDateToServerDateUncertainty = uncertainty ; } if ( startupDateToServerDateUncertainty < deviceDateToServerDateUncertainty || Math . abs ( startupToDeviceOffset - startupDateToDeviceDateOffset ) > startupDateToServerDateUncertainty || Math . abs ( deviceDateToServerDateOffset - ( startupDateToServerDateOffset - startupDateToDeviceDateOffset ) ) > deviceDateToServerDateUncertainty + startupDateToServerDateUncertainty ) { deviceDateToServerDateOffset = startupDateToServerDateOffset - startupDateToDeviceDateOffset ; deviceDateToServerDateUncertainty = startupDateToServerDateUncertainty ; WonderPushConfiguration . setDeviceDateSyncOffset ( deviceDateToServerDateOffset ) ; WonderPushConfiguration . setDeviceDateSyncUncertainty ( deviceDateToServerDateUncertainty ) ; } } | Synchronize time with the WonderPush servers . |
5,131 | static boolean downloadAllData ( ) { String data ; try { data = export ( ) . get ( ) ; } catch ( InterruptedException ex ) { Log . e ( WonderPush . TAG , "Unexpected error while exporting data" , ex ) ; return false ; } catch ( ExecutionException ex ) { Log . e ( WonderPush . TAG , "Unexpected error while exporting data" , ex ) ; return false ; } try { SimpleDateFormat sdf = new SimpleDateFormat ( "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'" , Locale . US ) ; sdf . setTimeZone ( TimeZone . getTimeZone ( "UTC" ) ) ; File folder = new File ( WonderPush . getApplicationContext ( ) . getFilesDir ( ) , "exports" ) ; folder . mkdirs ( ) ; String fn = "wonderpush-android-dataexport-" + sdf . format ( new Date ( ) ) + ".json" ; File f = new File ( folder , fn ) ; OutputStream os = new FileOutputStream ( f ) ; os . write ( data . getBytes ( ) ) ; os . close ( ) ; File fz = new File ( folder , fn + ".zip" ) ; ZipOutputStream osz = new ZipOutputStream ( new FileOutputStream ( fz ) ) ; osz . putNextEntry ( new ZipEntry ( fn ) ) ; osz . write ( data . getBytes ( ) ) ; osz . closeEntry ( ) ; osz . finish ( ) ; osz . close ( ) ; Uri uri = FileProvider . getUriForFile ( WonderPush . getApplicationContext ( ) , WonderPush . getApplicationContext ( ) . getPackageName ( ) + ".wonderpush.fileprovider" , fz ) ; Intent sendIntent = new Intent ( ) ; sendIntent . setAction ( Intent . ACTION_SEND ) ; sendIntent . putExtra ( Intent . EXTRA_STREAM , uri ) ; sendIntent . setType ( "application/zip" ) ; sendIntent . addFlags ( Intent . FLAG_GRANT_READ_URI_PERMISSION ) ; WonderPush . getApplicationContext ( ) . startActivity ( Intent . createChooser ( sendIntent , WonderPush . getApplicationContext ( ) . getResources ( ) . getText ( R . string . wonderpush_export_data_chooser ) ) ) ; return true ; } catch ( Exception ex ) { Log . e ( WonderPush . TAG , "Unexpected error while exporting data" , ex ) ; return false ; } } | Blocks until interrupted or completed . |
5,132 | protected static void get ( String resource , RequestParams params , ResponseHandler responseHandler ) { requestAuthenticated ( new Request ( WonderPushConfiguration . getUserId ( ) , HttpMethod . GET , resource , params , responseHandler ) ) ; } | A GET request |
5,133 | protected static void post ( String resource , RequestParams params , ResponseHandler responseHandler ) { requestAuthenticated ( new Request ( WonderPushConfiguration . getUserId ( ) , HttpMethod . POST , resource , params , responseHandler ) ) ; } | A POST request |
5,134 | protected static void postEventually ( String resource , RequestParams params ) { final Request request = new Request ( WonderPushConfiguration . getUserId ( ) , HttpMethod . POST , resource , params , null ) ; WonderPushRequestVault . getDefaultVault ( ) . put ( request , 0 ) ; } | A POST request that is guaranteed to be executed when a network connection is present surviving application reboot . The responseHandler will be called only if the network is present when the request is first run . |
5,135 | protected static void put ( String resource , RequestParams params , ResponseHandler responseHandler ) { requestAuthenticated ( new Request ( WonderPushConfiguration . getUserId ( ) , HttpMethod . PUT , resource , params , responseHandler ) ) ; } | A PUT request |
5,136 | protected static void delete ( String resource , ResponseHandler responseHandler ) { requestAuthenticated ( new Request ( WonderPushConfiguration . getUserId ( ) , HttpMethod . DELETE , resource , null , responseHandler ) ) ; } | A DELETE request |
5,137 | protected static boolean fetchAnonymousAccessTokenIfNeeded ( final String userId , final ResponseHandler onFetchedHandler ) { if ( ! WonderPush . isInitialized ( ) ) { WonderPush . safeDeferWithConsent ( new Runnable ( ) { public void run ( ) { if ( ! fetchAnonymousAccessTokenIfNeeded ( userId , onFetchedHandler ) ) { onFetchedHandler . onSuccess ( null ) ; } } } , null ) ; return true ; } if ( null == WonderPushConfiguration . getAccessToken ( ) ) { fetchAnonymousAccessToken ( userId , onFetchedHandler ) ; return true ; } return false ; } | If no access token is found in the user s preferences fetch an anonymous access token . |
5,138 | protected static void fetchAnonymousAccessTokenAndRunRequest ( final Request request ) { fetchAnonymousAccessToken ( request . getUserId ( ) , new ResponseHandler ( ) { public void onSuccess ( Response response ) { requestAuthenticated ( request ) ; } public void onFailure ( Throwable e , Response errorResponse ) { } } ) ; } | Fetches an anonymous access token and run the given request with that token . Retries when access token cannot be fetched . |
5,139 | public static synchronized void setDefaultChannelId ( String id ) { try { if ( _setDefaultChannelId ( id ) ) { save ( ) ; } } catch ( Exception ex ) { Log . e ( WonderPush . TAG , "Unexpected error while setting default channel id to " + id , ex ) ; } } | Set the default channel id . |
5,140 | public static synchronized WonderPushChannelGroup getChannelGroup ( String groupId ) { try { WonderPushChannelGroup rtn = sChannelGroups . get ( groupId ) ; if ( rtn != null ) { try { rtn = ( WonderPushChannelGroup ) rtn . clone ( ) ; } catch ( CloneNotSupportedException ex ) { Log . e ( WonderPush . TAG , "Unexpected error while cloning gotten channel group " + rtn , ex ) ; return null ; } } return rtn ; } catch ( Exception ex ) { Log . e ( WonderPush . TAG , "Unexpected error while getting channel group " + groupId , ex ) ; return null ; } } | Get a channel group . |
5,141 | public static synchronized void removeChannelGroup ( String groupId ) { try { if ( _removeChannelGroup ( groupId ) ) { save ( ) ; } } catch ( Exception ex ) { Log . e ( WonderPush . TAG , "Unexpected error while removing channel group " + groupId , ex ) ; } } | Remove a channel group . |
5,142 | public static synchronized void putChannelGroup ( WonderPushChannelGroup channelGroup ) { try { if ( _putChannelGroup ( channelGroup ) ) { save ( ) ; } } catch ( Exception ex ) { Log . e ( WonderPush . TAG , "Unexpected error while putting channel group " + channelGroup , ex ) ; } } | Create or update a channel group . |
5,143 | public static synchronized void setChannelGroups ( Collection < WonderPushChannelGroup > channelGroups ) { if ( channelGroups == null ) return ; boolean save = false ; try { Set < String > groupIdsToRemove = new HashSet < > ( sChannelGroups . keySet ( ) ) ; for ( WonderPushChannelGroup channelGroup : channelGroups ) { if ( channelGroup == null ) continue ; groupIdsToRemove . remove ( channelGroup . getId ( ) ) ; if ( _putChannelGroup ( channelGroup ) ) save = true ; } for ( String groupId : groupIdsToRemove ) { if ( _removeChannelGroup ( groupId ) ) save = true ; } } catch ( Exception ex ) { Log . e ( WonderPush . TAG , "Unexpected error while setting channel groups " + channelGroups , ex ) ; } finally { try { if ( save ) { save ( ) ; } } catch ( Exception ex ) { Log . e ( WonderPush . TAG , "Unexpected error while setting channel groups " + channelGroups , ex ) ; } } } | Create update and remove channel existing groups to match the given channel groups . |
5,144 | public static synchronized WonderPushChannel getChannel ( String channelId ) { try { WonderPushChannel rtn = sChannels . get ( channelId ) ; if ( rtn != null ) { try { rtn = ( WonderPushChannel ) rtn . clone ( ) ; } catch ( CloneNotSupportedException ex ) { Log . e ( WonderPush . TAG , "Unexpected error while cloning gotten channel " + rtn , ex ) ; return null ; } } return rtn ; } catch ( Exception ex ) { Log . e ( WonderPush . TAG , "Unexpected error while getting channel " + channelId , ex ) ; return null ; } } | Get a channel . |
5,145 | public static synchronized void removeChannel ( String channelId ) { try { if ( _removeChannel ( channelId ) ) { save ( ) ; } } catch ( Exception ex ) { Log . e ( WonderPush . TAG , "Unexpected error while removing channel " + channelId , ex ) ; } } | Remove a channel . |
5,146 | public static synchronized void putChannel ( WonderPushChannel channel ) { try { if ( _putChannel ( channel ) ) { save ( ) ; } } catch ( Exception ex ) { Log . e ( WonderPush . TAG , "Unexpected error while putting channel " + channel , ex ) ; } } | Create or update a channel . |
5,147 | public static synchronized void setChannels ( Collection < WonderPushChannel > channels ) { if ( channels == null ) return ; boolean save = false ; try { Set < String > channelIdsToRemove = new HashSet < > ( sChannels . keySet ( ) ) ; for ( WonderPushChannel channel : channels ) { if ( channel == null ) continue ; channelIdsToRemove . remove ( channel . getId ( ) ) ; if ( _putChannel ( channel ) ) save = true ; } for ( String channelId : channelIdsToRemove ) { if ( _removeChannel ( channelId ) ) save = true ; } } catch ( Exception ex ) { Log . e ( WonderPush . TAG , "Unexpected error while setting channels " + channels , ex ) ; } finally { try { if ( save ) { save ( ) ; } } catch ( Exception ex ) { Log . e ( WonderPush . TAG , "Unexpected error while setting channels " + channels , ex ) ; } } } | Create update and remove channels to match the given channels . |
5,148 | public void setPreferredNodeIdPrefix ( String preferredNodeIdPrefix ) { LettuceAssert . notNull ( preferredNodeIdPrefix , "preferredNodeIdPrefix must not be null" ) ; boolean resetRoundRobin = false ; if ( this . preferredNodeIdPrefix == null || ! preferredNodeIdPrefix . equals ( this . preferredNodeIdPrefix ) ) { resetRoundRobin = true ; } this . preferredNodeIdPrefix = preferredNodeIdPrefix ; if ( resetRoundRobin ) { resetRoundRobin ( preferredNodeIdPrefix ) ; } } | Set the id prefix of the preferred node . |
5,149 | public void setResource ( String resource , RequestParams params ) { if ( null == resource ) { WonderPush . logError ( "null resource provided to WonderPushView" ) ; return ; } mInitialResource = resource ; mInitialRequestParams = params ; mIsPreloading = false ; if ( null == params ) params = new RequestParams ( ) ; WonderPushRequestParamsDecorator . decorate ( resource , params ) ; String url = String . format ( Locale . getDefault ( ) , "%s?%s" , WonderPushUriHelper . getNonSecureAbsoluteUrl ( resource ) , params . getURLEncodedString ( ) ) ; mWebView . loadUrl ( url ) ; } | Sets the resource for the web content displayed in this WonderPushView s WebView . |
5,150 | public void setFullUrl ( String fullUrl ) { if ( fullUrl == null ) { return ; } Uri parsedUri = Uri . parse ( fullUrl ) ; if ( ! WonderPushUriHelper . isAPIUri ( parsedUri ) ) { mWebView . loadUrl ( fullUrl ) ; } else { setResource ( WonderPushUriHelper . getResource ( parsedUri ) , WonderPushUriHelper . getParams ( parsedUri ) ) ; } } | Sets the full URL for the web content displayed in this WonderPushView s WebView . |
5,151 | public Observable < Job < K , V > > getjobs ( long timeout , TimeUnit timeUnit , long count ) { return new GetJobsBuilder ( ) . getjobs ( timeout , timeUnit , count ) ; } | Get jobs from the specified queues . |
5,152 | protected Job postJobWithDescription ( JSONObject jobDescription , long notBeforeRealtimeElapsed ) { String jobId = UUID . randomUUID ( ) . toString ( ) ; InternalJob job = new InternalJob ( jobId , jobDescription , notBeforeRealtimeElapsed ) ; return post ( job ) ; } | Creates and stores a job in the queue based on the provided description |
5,153 | protected Job post ( Job job ) { if ( mQueue . offer ( job ) ) { save ( ) ; return job ; } else { return null ; } } | Stores an existing job in the queue . |
5,154 | protected synchronized void save ( ) { try { JSONArray jsonArray = new JSONArray ( ) ; for ( Job job : mQueue ) { if ( ! ( job instanceof InternalJob ) ) continue ; InternalJob internalJob = ( InternalJob ) job ; jsonArray . put ( internalJob . toJSON ( ) ) ; } SharedPreferences prefs = WonderPushConfiguration . getSharedPreferences ( ) ; SharedPreferences . Editor editor = prefs . edit ( ) ; editor . putString ( getPrefName ( ) , jsonArray . toString ( ) ) ; editor . apply ( ) ; } catch ( JSONException e ) { Log . e ( TAG , "Could not save job queue" , e ) ; } catch ( Exception e ) { Log . e ( TAG , "Could not save job queue" , e ) ; } } | Saves the job queue on disk . |
5,155 | protected synchronized void restore ( ) { try { SharedPreferences prefs = WonderPushConfiguration . getSharedPreferences ( ) ; String jsonString = prefs . getString ( getPrefName ( ) , "[]" ) ; JSONArray jsonArray = new JSONArray ( jsonString ) ; mQueue . clear ( ) ; for ( int i = 0 ; i < jsonArray . length ( ) ; i ++ ) { try { mQueue . add ( new InternalJob ( jsonArray . getJSONObject ( i ) ) ) ; } catch ( JSONException ex ) { Log . e ( TAG , "Failed to restore malformed job" , ex ) ; } catch ( Exception ex ) { Log . e ( TAG , "Unexpected error while restoring a job" , ex ) ; } } } catch ( JSONException e ) { Log . e ( TAG , "Could not restore job queue" , e ) ; } catch ( Exception e ) { Log . e ( TAG , "Could not restore job queue" , e ) ; } } | Restores the job queue from its on - disk version . |
5,156 | public Builder copyBuilder ( ) { return GetJobArgs . builder ( ) . noHang ( noHang ) . timeout ( timeout ) . withCounters ( withCounters ) ; } | Create a new builder populated with the current settings . |
5,157 | protected static void get ( String resource , RequestParams params , ResponseHandler responseHandler ) { WonderPushRestClient . get ( resource , params , responseHandler ) ; } | A GET request . |
5,158 | protected static void post ( String resource , RequestParams params , ResponseHandler responseHandler ) { WonderPushRestClient . post ( resource , params , responseHandler ) ; } | A POST request . |
5,159 | protected static void put ( String resource , RequestParams params , ResponseHandler responseHandler ) { WonderPushRestClient . put ( resource , params , responseHandler ) ; } | A PUT request . |
5,160 | protected static String getLang ( ) { Locale locale = Locale . getDefault ( ) ; if ( null == locale ) return DEFAULT_LANGUAGE_CODE ; String language = locale . getLanguage ( ) ; String country = locale . getCountry ( ) ; String localeString = String . format ( "%s_%s" , language != null ? language . toLowerCase ( Locale . ENGLISH ) : "" , country != null ? country . toUpperCase ( Locale . ENGLISH ) : "" ) ; if ( null == language ) return DEFAULT_LANGUAGE_CODE ; String matchedLanguageCode = null ; for ( String languageCode : VALID_LANGUAGE_CODES ) { if ( languageCode . equals ( localeString ) ) { return localeString ; } if ( languageCode . equals ( language ) ) { matchedLanguageCode = language ; } } if ( null != matchedLanguageCode ) return matchedLanguageCode ; return DEFAULT_LANGUAGE_CODE ; } | Gets the current language guessed from the system . |
5,161 | @ SuppressWarnings ( "unused" ) public static void initialize ( final Context context ) { try { ensureInitialized ( context ) ; } catch ( Exception e ) { Log . e ( TAG , "Unexpected error while initializing the SDK" , e ) ; } } | Initialize WonderPush . |
5,162 | public static void setRequiresUserConsent ( boolean value ) { if ( ! sIsInitialized ) { sRequiresUserConsent = value ; } else { boolean hadUserConsent = hasUserConsent ( ) ; sRequiresUserConsent = value ; Log . w ( TAG , "WonderPush.setRequiresUserConsent(" + value + ") called after WonderPush.initialize(). Although supported, a proper implementation typically only calls it before." ) ; boolean nowHasUserConsent = hasUserConsent ( ) ; if ( hadUserConsent != nowHasUserConsent ) { hasUserConsentChanged ( nowHasUserConsent ) ; } } } | Sets whether user consent is required before the SDK is allowed to work . |
5,163 | public static void setUserConsent ( boolean value ) { boolean hadUserConsent = hasUserConsent ( ) ; WonderPushConfiguration . setUserConsent ( value ) ; boolean nowHasUserConsent = hasUserConsent ( ) ; if ( sIsInitialized && hadUserConsent != nowHasUserConsent ) { hasUserConsentChanged ( nowHasUserConsent ) ; } } | Provides or withdraws user consent . |
5,164 | @ SuppressWarnings ( "unused" ) public static void setUserId ( String userId ) { try { if ( "" . equals ( userId ) ) userId = null ; logDebug ( "setUserId(" + userId + ")" ) ; if ( ! isInitialized ( ) ) { logDebug ( "setting user id for next initialization" ) ; sBeforeInitializationUserIdSet = true ; sBeforeInitializationUserId = userId ; return ; } sBeforeInitializationUserIdSet = false ; sBeforeInitializationUserId = null ; String oldUserId = WonderPushConfiguration . getUserId ( ) ; if ( userId == null && oldUserId == null || userId != null && userId . equals ( oldUserId ) ) { } else { initForNewUser ( userId ) ; } } catch ( Exception e ) { Log . e ( TAG , "Unexpected error while setting userId to \"" + userId + "\"" , e ) ; } } | Sets the user id used to identify a single identity across multiple devices and to correctly identify multiple users on a single device . |
5,165 | @ SuppressWarnings ( "unused" ) public static String getUserId ( ) { String userId = null ; try { userId = WonderPushConfiguration . getUserId ( ) ; } catch ( Exception e ) { Log . e ( TAG , "Unexpected error while getting userId" , e ) ; } return userId ; } | Gets the user id used to identify a single identity across multiple devices and to correctly identify multiple users on a single device . |
5,166 | protected static String getResource ( Uri uri ) { if ( ! isAPIUri ( uri ) ) { return null ; } String scheme = uri . getScheme ( ) ; String apiScheme = getBaseUri ( ) . getScheme ( ) ; String remainder = uri . toString ( ) . substring ( scheme . length ( ) ) ; String apiRemainder = getBaseUri ( ) . toString ( ) . substring ( apiScheme . length ( ) ) ; if ( ! remainder . startsWith ( apiRemainder ) ) { return null ; } return uri . getPath ( ) . substring ( getBaseUri ( ) . getPath ( ) . length ( ) ) ; } | Extracts the resource path from a Uri . |
5,167 | protected static boolean isAPIUri ( Uri uri ) { if ( uri == null ) { return false ; } return getBaseUri ( ) . getHost ( ) . equals ( uri . getHost ( ) ) ; } | Checks that the provided URI points to the WonderPush REST server |
5,168 | protected static String getAbsoluteUrl ( String resource ) { if ( resource . startsWith ( "/" + WonderPush . API_VERSION ) ) { resource = resource . substring ( 1 + WonderPush . API_VERSION . length ( ) ) ; } return WonderPush . getBaseURL ( ) + resource ; } | Returns the absolute URL for the given resource |
5,169 | protected static String getNonSecureAbsoluteUrl ( String resource ) { if ( resource . startsWith ( "/" + WonderPush . API_VERSION ) ) { resource = resource . substring ( 1 + WonderPush . API_VERSION . length ( ) ) ; } return WonderPush . getNonSecureBaseURL ( ) + resource ; } | Returns the non secure absolute url for the given resource |
5,170 | protected static String getDeviceName ( ) { try { if ( WonderPush . getApplicationContext ( ) . getPackageManager ( ) . checkPermission ( android . Manifest . permission . BLUETOOTH , WonderPush . getApplicationContext ( ) . getPackageName ( ) ) == PackageManager . PERMISSION_GRANTED ) { BluetoothAdapter btDevice = BluetoothAdapter . getDefaultAdapter ( ) ; return btDevice . getName ( ) ; } } catch ( Exception ex ) { } return null ; } | Returns the Bluetooth device name if permissions are granted and provided the device actually has Bluetooth . |
5,171 | public boolean next ( ) { int len = queryString . length ( ) ; while ( true ) { if ( paramEnd == len ) { return false ; } paramBegin = paramEnd == - 1 ? 0 : paramEnd + 1 ; int idx = queryString . indexOf ( '&' , paramBegin ) ; paramEnd = idx == - 1 ? len : idx ; if ( paramEnd > paramBegin ) { idx = queryString . indexOf ( '=' , paramBegin ) ; paramNameEnd = idx == - 1 || idx > paramEnd ? paramEnd : idx ; paramName = null ; paramValue = null ; return true ; } } } | Move to the next parameter in the query string . |
5,172 | public boolean search ( Collection < String > names ) { while ( next ( ) ) { if ( names . contains ( getName ( ) ) ) { return true ; } } return false ; } | Search for a parameter with a name in a given collection . This method iterates over the parameters until a parameter with a matching name has been found . Note that the current parameter is not considered . |
5,173 | public static RequestParams getRequestParams ( String queryString ) { if ( null == queryString ) return null ; QueryStringParser parser = new QueryStringParser ( queryString ) ; RequestParams result = new RequestParams ( ) ; while ( parser . next ( ) ) { result . put ( parser . getName ( ) , parser . getValue ( ) ) ; } return result ; } | Create a WonderPush . RequestParams from this query string |
5,174 | public < Intermediate > TransformationConcatenator < Intermediate , Target > first ( Transformation < Source , Intermediate > firstTransformation ) { transformationChain = new TransformationChain < Source , Target > ( ) ; transformationChain . chain . add ( firstTransformation ) ; return new TransformationConcatenator < Intermediate , Target > ( ) ; } | Adds the first sub - transformation to the chain . Subsequent transformations can be added by invoking methods on the TransformationConcatenator returned by this method . |
5,175 | private static List < Method > getPropertyMethods ( Class entityClass ) { List < Method > result = new ArrayList < Method > ( ) ; for ( Method m : entityClass . getMethods ( ) ) { if ( m . getParameterTypes ( ) . length == 0 && m . getName ( ) . startsWith ( "get" ) && m . getReturnType ( ) != void . class ) { if ( m . getName ( ) . equals ( "getClass" ) ) continue ; result . add ( m ) ; } } return result ; } | Returns the property - accessors for the specified class ; |
5,176 | public String getGeometryName ( ) { String result = null ; if ( geometryAccessor != null ) { result = geometryAccessor . getPropertyName ( ) ; } return result ; } | Returns the name of the geometryfield of the given entity . If no geometry field exists null is returned . |
5,177 | public String getIdName ( ) { String result = null ; if ( idAccessor != null ) { result = idAccessor . getPropertyName ( ) ; } return result ; } | Returns the name of the idfield of the given entity . If no id field exists null is returned . |
5,178 | public Object getId ( Object objectToGet ) throws InvalidObjectReaderException { if ( objectToGet == null ) { throw new IllegalArgumentException ( "Given object may not be null" ) ; } if ( objectToGet . getClass ( ) != entityClass ) { throw new InvalidObjectReaderException ( "Class of target object does not correspond with entityclass of this reader." ) ; } if ( idAccessor == null ) { return null ; } else { return idAccessor . getValueFrom ( objectToGet ) ; } } | Returns the value of the id of the given object if it is present . If no id property could be found null is returned . |
5,179 | public Geometry getGeometry ( Object objectToGet ) throws InvalidObjectReaderException { if ( objectToGet == null ) { throw new IllegalArgumentException ( "The given object may not be null" ) ; } if ( objectToGet . getClass ( ) != entityClass ) { throw new InvalidObjectReaderException ( "Class of target object does not correspond with entityclass of this reader." ) ; } if ( geometryAccessor == null ) { return null ; } else { return ( Geometry ) geometryAccessor . getValueFrom ( objectToGet ) ; } } | Will retrieve the value of the geometryfield in the given object . If no geometryfield exists null is returned . If more than one exist a random one is returned . |
5,180 | public Object getPropertyValue ( Object objectToGet , String propertyPath ) throws InvalidObjectReaderException { if ( objectToGet == null || propertyPath == null ) { throw new IllegalArgumentException ( "Given object/propertyname may not be null" ) ; } if ( objectToGet . getClass ( ) != entityClass ) { throw new InvalidObjectReaderException ( "Class of target object does not correspond with entityclass of this reader." ) ; } StringTokenizer tokenizer = new StringTokenizer ( propertyPath , "." , false ) ; return getPropertyValue ( objectToGet , tokenizer ) ; } | Returns the value of the property with a given name from the given object |
5,181 | private Object getPropertyValue ( Object objectToGet , StringTokenizer propertyPathParts ) { String propertyName = propertyPathParts . nextToken ( ) ; Object propertyValue = null ; if ( accessorMap . containsKey ( propertyName ) ) { propertyValue = accessorMap . get ( propertyName ) . getValueFrom ( objectToGet ) ; } if ( ! propertyPathParts . hasMoreTokens ( ) || propertyValue == null ) return propertyValue ; else { EntityClassReader currentPathReader = EntityClassReader . getClassReaderFor ( propertyValue . getClass ( ) ) ; return currentPathReader . getPropertyValue ( propertyValue , propertyPathParts ) ; } } | Recursive method to get the value of a property path . |
5,182 | public Class getPropertyType ( String propertyPath ) { if ( propertyPath == null ) { throw new IllegalArgumentException ( "Propertyname may not be null" ) ; } StringTokenizer tokenizer = new StringTokenizer ( propertyPath , "." , false ) ; return getPropertyType ( tokenizer ) ; } | Retrieves the type of the given property path . |
5,183 | private Class getPropertyType ( StringTokenizer propertyPathParts ) { String propertyName = propertyPathParts . nextToken ( ) ; Class propertyType = null ; if ( accessorMap . containsKey ( propertyName ) ) { propertyType = accessorMap . get ( propertyName ) . getReturnType ( ) ; } else if ( propertyName . equals ( getIdName ( ) ) ) { propertyType = idAccessor . getReturnType ( ) ; } else if ( propertyName . equals ( getGeometryName ( ) ) ) { propertyType = geometryAccessor . getReturnType ( ) ; } if ( ! propertyPathParts . hasMoreTokens ( ) || propertyType == null ) return propertyType ; else { EntityClassReader currentPathReader = EntityClassReader . getClassReaderFor ( propertyType ) ; return currentPathReader . getPropertyType ( propertyPathParts ) ; } } | Recursive method to retrieve the type of the given property path . |
5,184 | public Feature transform ( Source input ) throws TransformationException { if ( input == null ) { return null ; } else { EntityClassReader reader = EntityClassReader . getClassReaderFor ( input . getClass ( ) ) ; try { return reader . asFeature ( input ) ; } catch ( InvalidObjectReaderException e ) { throw new TransformationException ( "Transformation failed" , e ) ; } } } | Transforms any object into a feature . If the given object is null null is returned . |
5,185 | protected void writeCrs ( JsonGenerator jgen , Geometry shape ) throws IOException { if ( shape . getSRID ( ) > 0 ) { jgen . writeFieldName ( "crs" ) ; jgen . writeStartObject ( ) ; jgen . writeStringField ( "type" , "name" ) ; jgen . writeFieldName ( "properties" ) ; jgen . writeStartObject ( ) ; jgen . writeStringField ( "name" , "EPSG:" + shape . getSRID ( ) ) ; jgen . writeEndObject ( ) ; jgen . writeEndObject ( ) ; } } | Writes out the crs information in the GeoJSON string |
5,186 | public GeoJsonTo toTransferObject ( Geometry geometry ) { if ( geometry instanceof Point ) { return toTransferObject ( ( Point ) geometry ) ; } else if ( geometry instanceof LineString ) { return toTransferObject ( ( LineString ) geometry ) ; } else if ( geometry instanceof MultiPoint ) { return toTransferObject ( ( MultiPoint ) geometry ) ; } else if ( geometry instanceof MultiLineString ) { return toTransferObject ( ( MultiLineString ) geometry ) ; } else if ( geometry instanceof Polygon ) { return toTransferObject ( ( Polygon ) geometry ) ; } else if ( geometry instanceof MultiPolygon ) { return toTransferObject ( ( MultiPolygon ) geometry ) ; } else if ( geometry instanceof GeometryCollection ) { return toTransferObject ( ( GeometryCollection ) geometry ) ; } return null ; } | Creates the correct TO starting from any geolatte geometry . |
5,187 | public PolygonTo toTransferObject ( Polygon input ) { PolygonTo result = new PolygonTo ( ) ; result . setCrs ( GeoJsonTo . createCrsTo ( "EPSG:" + input . getSRID ( ) ) ) ; double [ ] [ ] [ ] rings = new double [ input . getNumInteriorRing ( ) + 1 ] [ ] [ ] ; rings [ 0 ] = getPoints ( input . getExteriorRing ( ) ) ; for ( int i = 0 ; i < input . getNumInteriorRing ( ) ; i ++ ) { rings [ i + 1 ] = getPoints ( input . getInteriorRingN ( i ) ) ; } result . setCoordinates ( rings ) ; return result ; } | Converts a polygon to its corresponding Transfer Object |
5,188 | public MultiLineStringTo toTransferObject ( MultiLineString input ) { MultiLineStringTo result = new MultiLineStringTo ( ) ; double [ ] [ ] [ ] resultCoordinates = new double [ input . getNumGeometries ( ) ] [ ] [ ] ; for ( int i = 0 ; i < input . getNumGeometries ( ) ; i ++ ) { resultCoordinates [ i ] = getPoints ( input . getGeometryN ( i ) ) ; } result . setCoordinates ( resultCoordinates ) ; result . setCrs ( GeoJsonTo . createCrsTo ( "EPSG:" + input . getSRID ( ) ) ) ; return result ; } | Converts a multilinestring to its corresponding Transfer Object |
5,189 | public MultiPointTo toTransferObject ( MultiPoint input ) { MultiPointTo result = new MultiPointTo ( ) ; result . setCrs ( GeoJsonTo . createCrsTo ( "EPSG:" + input . getSRID ( ) ) ) ; result . setCoordinates ( getPoints ( input ) ) ; return result ; } | Converts a multipoint to its corresponding Transfer Object |
5,190 | public PointTo toTransferObject ( Point input ) { PointTo result = new PointTo ( ) ; result . setCrs ( GeoJsonTo . createCrsTo ( "EPSG:" + input . getSRID ( ) ) ) ; result . setCoordinates ( getPoints ( input ) [ 0 ] ) ; return result ; } | Converts a point to its corresponding Transfer Object |
5,191 | public LineStringTo toTransferObject ( LineString input ) { LineStringTo result = new LineStringTo ( ) ; result . setCrs ( GeoJsonTo . createCrsTo ( "EPSG:" + input . getSRID ( ) ) ) ; result . setCoordinates ( getPoints ( input ) ) ; return result ; } | Converts a linestring to its corresponding Transfer Object |
5,192 | public Geometry fromTransferObject ( GeoJsonTo input , CrsId crsId ) throws IllegalArgumentException { if ( input instanceof PointTo ) { return fromTransferObject ( ( PointTo ) input , crsId ) ; } else if ( input instanceof MultiPointTo ) { return fromTransferObject ( ( MultiPointTo ) input , crsId ) ; } else if ( input instanceof LineStringTo ) { return fromTransferObject ( ( LineStringTo ) input , crsId ) ; } else if ( input instanceof MultiLineStringTo ) { return fromTransferObject ( ( MultiLineStringTo ) input , crsId ) ; } else if ( input instanceof PolygonTo ) { return fromTransferObject ( ( PolygonTo ) input , crsId ) ; } else if ( input instanceof MultiPolygonTo ) { return fromTransferObject ( ( MultiPolygonTo ) input , crsId ) ; } else if ( input instanceof GeometryCollectionTo ) { return fromTransferObject ( ( GeometryCollectionTo ) input , crsId ) ; } return null ; } | Creates a geolatte geometry object starting from a GeoJsonTo . |
5,193 | public Polygon fromTransferObject ( PolygonTo input , CrsId crsId ) { if ( input == null ) { return null ; } crsId = getCrsId ( input , crsId ) ; isValid ( input ) ; return createPolygon ( input . getCoordinates ( ) , crsId ) ; } | Creates a polygon object starting from a transfer object . |
5,194 | public GeometryCollection fromTransferObject ( GeometryCollectionTo input , CrsId crsId ) { if ( input == null ) { return null ; } crsId = getCrsId ( input , crsId ) ; isValid ( input ) ; Geometry [ ] geoms = new Geometry [ input . getGeometries ( ) . length ] ; for ( int i = 0 ; i < geoms . length ; i ++ ) { geoms [ i ] = fromTransferObject ( input . getGeometries ( ) [ i ] , crsId ) ; } return new GeometryCollection ( geoms ) ; } | Creates a geometrycollection object starting from a transfer object . |
5,195 | public MultiPolygon fromTransferObject ( MultiPolygonTo input , CrsId crsId ) { if ( input == null ) { return null ; } crsId = getCrsId ( input , crsId ) ; isValid ( input ) ; Polygon [ ] polygons = new Polygon [ input . getCoordinates ( ) . length ] ; for ( int i = 0 ; i < polygons . length ; i ++ ) { polygons [ i ] = createPolygon ( input . getCoordinates ( ) [ i ] , crsId ) ; } return new MultiPolygon ( polygons ) ; } | Creates a multipolygon object starting from a transfer object . |
5,196 | public MultiLineString fromTransferObject ( MultiLineStringTo input , CrsId crsId ) { if ( input == null ) { return null ; } crsId = getCrsId ( input , crsId ) ; isValid ( input ) ; LineString [ ] lineStrings = new LineString [ input . getCoordinates ( ) . length ] ; for ( int i = 0 ; i < lineStrings . length ; i ++ ) { lineStrings [ i ] = new LineString ( createPointSequence ( input . getCoordinates ( ) [ i ] , crsId ) ) ; } return new MultiLineString ( lineStrings ) ; } | Creates a multilinestring object starting from a transfer object . |
5,197 | public LineString fromTransferObject ( LineStringTo input , CrsId crsId ) { if ( input == null ) { return null ; } crsId = getCrsId ( input , crsId ) ; isValid ( input ) ; return new LineString ( createPointSequence ( input . getCoordinates ( ) , crsId ) ) ; } | Creates a linestring object starting from a transfer object . |
5,198 | public MultiPoint fromTransferObject ( MultiPointTo input , CrsId crsId ) { if ( input == null ) { return null ; } crsId = getCrsId ( input , crsId ) ; isValid ( input ) ; Point [ ] points = new Point [ input . getCoordinates ( ) . length ] ; for ( int i = 0 ; i < points . length ; i ++ ) { points [ i ] = createPoint ( input . getCoordinates ( ) [ i ] , crsId ) ; } return new MultiPoint ( points ) ; } | Creates a multipoint object starting from a transfer object . |
5,199 | public Point fromTransferObject ( PointTo input , CrsId crsId ) { if ( input == null ) { return null ; } crsId = getCrsId ( input , crsId ) ; isValid ( input ) ; return createPoint ( input . getCoordinates ( ) , crsId ) ; } | Creates a point object starting from a transfer object . |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.