idx
int64
0
41.2k
question
stringlengths
83
4.15k
target
stringlengths
5
715
10,200
public Cursor getItem ( int position ) { if ( mDataValid && mCursor != null ) { mCursor . moveToPosition ( position ) ; return mCursor ; } else { return null ; } }
Returns a cursor pointed to the given position .
10,201
public void execute ( ) throws MojoExecutionException { if ( skipProject ( ) ) { getLog ( ) . info ( "POM project detected; skipping" ) ; } else { URLClassLoader classLoader = new URLClassLoader ( generateClassPathUrls ( ) ) ; List < Class < ? > > interfaceClasses = loadServiceClasses ( classLoader ) ; Map < String , List < String > > serviceImplementations = findImplementations ( classLoader , interfaceClasses ) ; writeServiceFiles ( serviceImplementations ) ; } }
The main entry point for this Mojo .
10,202
private void writeServiceFiles ( Map < String , List < String > > serviceImplementations ) throws MojoExecutionException { File parentFolder = new File ( getClassFolder ( ) , "META-INF" + File . separator + "services" ) ; if ( ! parentFolder . exists ( ) ) { parentFolder . mkdirs ( ) ; } for ( Entry < String , List < String > > interfaceClassName : serviceImplementations . entrySet ( ) ) { File serviceFile = new File ( parentFolder , interfaceClassName . getKey ( ) ) ; getLog ( ) . info ( "Generating service file " + serviceFile . getAbsolutePath ( ) ) ; FileWriter writer = null ; try { writer = new FileWriter ( serviceFile ) ; for ( String implementationClassName : interfaceClassName . getValue ( ) ) { getLog ( ) . info ( " + " + implementationClassName ) ; writer . write ( implementationClassName ) ; writer . write ( '\n' ) ; } buildContext . refresh ( serviceFile ) ; } catch ( IOException e ) { throw new MojoExecutionException ( "Error creating file " + serviceFile , e ) ; } finally { if ( writer != null ) { try { writer . close ( ) ; } catch ( IOException e ) { getLog ( ) . error ( e ) ; } } } } }
Writes the output for the service files to disk
10,203
private List < Class < ? > > loadServiceClasses ( ClassLoader loader ) throws MojoExecutionException { List < Class < ? > > serviceClasses = new ArrayList < Class < ? > > ( ) ; for ( String serviceClassName : getServices ( ) ) { try { Class < ? > serviceClass = loader . loadClass ( serviceClassName ) ; serviceClasses . add ( serviceClass ) ; } catch ( ClassNotFoundException ex ) { throw new MojoExecutionException ( "Could not load class: " + serviceClassName , ex ) ; } } return serviceClasses ; }
Loads all interfaces using the provided ClassLoader
10,204
private Map < String , List < String > > findImplementations ( ClassLoader loader , List < Class < ? > > interfaceClasses ) throws MojoExecutionException { Map < String , List < String > > serviceImplementations = new HashMap < String , List < String > > ( ) ; for ( String interfaceClassName : getServices ( ) ) { serviceImplementations . put ( interfaceClassName , new ArrayList < String > ( ) ) ; } getLog ( ) . info ( "Scanning generated classes for implementations..." ) ; File classFolder = getClassFolder ( ) ; List < String > classNames = listCompiledClasses ( classFolder ) ; for ( String className : classNames ) { try { if ( getLog ( ) . isDebugEnabled ( ) ) { getLog ( ) . debug ( "checking class: " + className ) ; } Class < ? > cls = loader . loadClass ( className ) ; int mods = cls . getModifiers ( ) ; if ( ! cls . isAnonymousClass ( ) && ! cls . isInterface ( ) && ! cls . isEnum ( ) && ! Modifier . isAbstract ( mods ) && Modifier . isPublic ( mods ) ) { for ( Class < ? > interfaceCls : interfaceClasses ) { if ( ! interfaceCls . equals ( cls ) && interfaceCls . isAssignableFrom ( cls ) ) { if ( includes == null || includes . length == 0 ) { serviceImplementations . get ( interfaceCls . getName ( ) ) . add ( className ) ; } else { for ( String include : includes ) { if ( SelectorUtils . match ( include , className ) ) { serviceImplementations . get ( interfaceCls . getName ( ) ) . add ( className ) ; } } } } } } } catch ( ClassNotFoundException e1 ) { getLog ( ) . warn ( e1 ) ; } catch ( NoClassDefFoundError e2 ) { getLog ( ) . warn ( e2 ) ; } } if ( excludes != null && excludes . length != 0 ) { Set < Entry < String , List < String > > > entrySet = serviceImplementations . entrySet ( ) ; for ( Entry < String , List < String > > entry : entrySet ) { classNames = entry . getValue ( ) ; ListIterator < String > classNamesIter = classNames . listIterator ( ) ; while ( classNamesIter . hasNext ( ) ) { String className = classNamesIter . next ( ) ; for ( String exclude : excludes ) { if ( SelectorUtils . match ( exclude , className ) ) { classNamesIter . remove ( ) ; break ; } } } } } return serviceImplementations ; }
Finds all implementations of interfaces in a folder
10,205
List < String > listCompiledClasses ( final File classFolder ) { List < String > classNames = new ArrayList < String > ( ) ; if ( ! classFolder . exists ( ) ) { getLog ( ) . info ( "Class folder does not exist; skipping scan" ) ; return classNames ; } final String extension = ".class" ; final DirectoryScanner directoryScanner = new DirectoryScanner ( ) ; directoryScanner . setBasedir ( classFolder ) ; directoryScanner . setIncludes ( new String [ ] { "**" + File . separator + "*" + extension } ) ; directoryScanner . scan ( ) ; String [ ] files = directoryScanner . getIncludedFiles ( ) ; String className ; for ( String file : files ) { className = file . substring ( 0 , file . length ( ) - extension . length ( ) ) . replace ( File . separator , "." ) ; classNames . add ( className ) ; } return classNames ; }
Walks the classFolder and finds all classes
10,206
private List < String > listCompiledClassesRegex ( File classFolder ) { List < String > classNames = new ArrayList < String > ( ) ; Stack < File > todo = new Stack < File > ( ) ; todo . push ( classFolder ) ; String classFolderPath = classFolder . getAbsolutePath ( ) ; getLog ( ) . info ( "ClassFolderPath=" + classFolderPath ) ; Pattern pat = Pattern . compile ( classFolderPath + File . separator + "(.*).class" ) ; File workDir ; String name ; while ( ! todo . isEmpty ( ) ) { workDir = todo . pop ( ) ; for ( File file : workDir . listFiles ( ) ) { if ( file . isDirectory ( ) ) { todo . push ( file ) ; } else { if ( file . getName ( ) . endsWith ( ".class" ) ) { name = file . getAbsolutePath ( ) ; name = pat . matcher ( name ) . group ( 1 ) ; name = name . replace ( File . separator , "." ) ; getLog ( ) . debug ( "Found class: " + name ) ; classNames . add ( name ) ; } } } } return classNames ; }
Walks the classFolder and finds all . class files
10,207
public void auth ( ) throws DockerException { try { client . resource ( restEndpointUrl + "/auth" ) . header ( "Content-Type" , MediaType . APPLICATION_JSON ) . accept ( MediaType . APPLICATION_JSON ) . post ( authConfig ( ) ) ; } catch ( UniformInterfaceException e ) { throw new DockerException ( e ) ; } }
Authenticate with the server useful for checking authentication .
10,208
public ClientResponse push ( final String name ) throws DockerException { if ( name == null ) { throw new IllegalArgumentException ( "name is null" ) ; } try { final String registryAuth = registryAuth ( ) ; return client . resource ( restEndpointUrl + "/images/" + name ( name ) + "/push" ) . header ( "X-Registry-Auth" , registryAuth ) . accept ( MediaType . APPLICATION_JSON ) . post ( ClientResponse . class ) ; } catch ( UniformInterfaceException e ) { throw new DockerException ( e ) ; } }
Push the latest image to the repository .
10,209
public int tag ( String image , String repository , String tag , boolean force ) throws DockerException { Preconditions . checkNotNull ( image , "image was not specified" ) ; Preconditions . checkNotNull ( repository , "repository was not specified" ) ; Preconditions . checkNotNull ( tag , " tag was not provided" ) ; MultivaluedMap < String , String > params = new MultivaluedMapImpl ( ) ; params . add ( "repo" , repository ) ; params . add ( "tag" , tag ) ; params . add ( "force" , String . valueOf ( force ) ) ; WebResource webResource = client . resource ( restEndpointUrl + "/images/" + image + "/tag" ) . queryParams ( params ) ; try { LOGGER . trace ( "POST: {}" , webResource ) ; ClientResponse resp = webResource . post ( ClientResponse . class ) ; return resp . getStatus ( ) ; } catch ( UniformInterfaceException exception ) { throw new DockerException ( exception ) ; } }
Tag an image into a repository
10,210
public ImageCreateResponse importImage ( String repository , String tag , InputStream imageStream ) throws DockerException { Preconditions . checkNotNull ( repository , "Repository was not specified" ) ; Preconditions . checkNotNull ( imageStream , "imageStream was not provided" ) ; MultivaluedMap < String , String > params = new MultivaluedMapImpl ( ) ; params . add ( "repo" , repository ) ; params . add ( "tag" , tag ) ; params . add ( "fromSrc" , "-" ) ; WebResource webResource = client . resource ( restEndpointUrl + "/images/create" ) . queryParams ( params ) ; try { LOGGER . trace ( "POST: {}" , webResource ) ; return webResource . accept ( MediaType . APPLICATION_OCTET_STREAM_TYPE ) . post ( ImageCreateResponse . class , imageStream ) ; } catch ( UniformInterfaceException exception ) { if ( exception . getResponse ( ) . getStatus ( ) == 500 ) { throw new DockerException ( "Server error." , exception ) ; } else { throw new DockerException ( exception ) ; } } }
Create an image by importing the given stream of a tar file .
10,211
public void removeImage ( String imageId ) throws DockerException { Preconditions . checkState ( ! StringUtils . isEmpty ( imageId ) , "Image ID can't be empty" ) ; try { WebResource webResource = client . resource ( restEndpointUrl + "/images/" + imageId ) . queryParam ( "force" , "true" ) ; LOGGER . trace ( "DELETE: {}" , webResource ) ; webResource . delete ( ) ; } catch ( UniformInterfaceException exception ) { if ( exception . getResponse ( ) . getStatus ( ) == 204 ) { LOGGER . trace ( "Successfully removed image " + imageId ) ; } else if ( exception . getResponse ( ) . getStatus ( ) == 404 ) { LOGGER . warn ( "{} no such image" , imageId ) ; } else if ( exception . getResponse ( ) . getStatus ( ) == 409 ) { throw new DockerException ( "Conflict" ) ; } else if ( exception . getResponse ( ) . getStatus ( ) == 500 ) { throw new DockerException ( "Server error." , exception ) ; } else { throw new DockerException ( exception ) ; } } }
Remove an image deleting any tags it might have .
10,212
protected boolean fillBuffer ( ) { if ( ! _inProgress . isEmpty ( ) || ! _queue . isEmpty ( ) ) { throw new IllegalStateException ( "cannot fill buffer when buffer or pending messages are non-empty" ) ; } if ( _iterator == null ) { final Map < String , List < KafkaStream < byte [ ] , byte [ ] > > > streams = _consumer . createMessageStreams ( Collections . singletonMap ( _topic , 1 ) ) ; _iterator = streams . get ( _topic ) . get ( 0 ) . iterator ( ) ; } try { int size = 0 ; while ( size < _bufSize && _iterator . hasNext ( ) ) { final MessageAndMetadata < byte [ ] , byte [ ] > message = _iterator . next ( ) ; final KafkaMessageId id = new KafkaMessageId ( message . partition ( ) , message . offset ( ) ) ; _inProgress . put ( id , message . message ( ) ) ; size ++ ; } } catch ( final InvalidMessageException e ) { LOG . warn ( e . getMessage ( ) , e ) ; } catch ( final ConsumerTimeoutException e ) { } if ( _inProgress . size ( ) > 0 ) { _queue . addAll ( _inProgress . keySet ( ) ) ; LOG . debug ( "buffer now has {} messages to be emitted" , _queue . size ( ) ) ; return true ; } else { return false ; } }
Refills the buffer with messages from the configured kafka topic if available .
10,213
public static void checkConfigSanity ( final Properties config ) { final Object autoCommit = config . getProperty ( "auto.commit.enable" ) ; if ( autoCommit == null || Boolean . parseBoolean ( String . valueOf ( autoCommit ) ) ) { throw new IllegalArgumentException ( "kafka configuration 'auto.commit.enable' should be set to false for operation in storm" ) ; } final Object consumerTimeout = config . getProperty ( "consumer.timeout.ms" ) ; if ( consumerTimeout == null || Integer . parseInt ( String . valueOf ( consumerTimeout ) ) < 0 ) { throw new IllegalArgumentException ( "kafka configuration value for 'consumer.timeout.ms' is not suitable for operation in storm" ) ; } }
Checks the sanity of a kafka consumer configuration for use in storm .
10,214
protected URL resolveURL ( ) { if ( this . clazz != null ) { return this . clazz . getResource ( this . path ) ; } else if ( this . classLoader != null ) { return this . classLoader . getResource ( this . path ) ; } else { return ClassLoader . getSystemResource ( this . path ) ; } }
Resolves a URL for the underlying class path resource .
10,215
public URL getURL ( ) throws IOException { URL url = resolveURL ( ) ; if ( url == null ) { throw new FileNotFoundException ( getDescription ( ) + " cannot be resolved to URL because it does not exist" ) ; } return url ; }
This implementation returns a URL for the underlying class path resource if available .
10,216
static Object adaptValue ( Object value , boolean classValuesAsString , boolean nestedAnnotationsAsMap ) { if ( classValuesAsString ) { if ( value instanceof Class ) { value = ( ( Class < ? > ) value ) . getName ( ) ; } else if ( value instanceof Class [ ] ) { Class < ? > [ ] clazzArray = ( Class [ ] ) value ; String [ ] newValue = new String [ clazzArray . length ] ; for ( int i = 0 ; i < clazzArray . length ; i ++ ) { newValue [ i ] = clazzArray [ i ] . getName ( ) ; } value = newValue ; } } if ( nestedAnnotationsAsMap && value instanceof Annotation ) { return getAnnotationAttributes ( ( Annotation ) value , classValuesAsString , true ) ; } else if ( nestedAnnotationsAsMap && value instanceof Annotation [ ] ) { Annotation [ ] realAnnotations = ( Annotation [ ] ) value ; AnnotationAttributes [ ] mappedAnnotations = new AnnotationAttributes [ realAnnotations . length ] ; for ( int i = 0 ; i < realAnnotations . length ; i ++ ) { mappedAnnotations [ i ] = getAnnotationAttributes ( realAnnotations [ i ] , classValuesAsString , true ) ; } return mappedAnnotations ; } else { return value ; } }
Adapt the given value according to the given class and nested annotation settings .
10,217
private void extendCG ( Configuration config , List < Context > contexts ) { PluginConfiguration pluginConfiguration = new PluginConfiguration ( ) ; pluginConfiguration . setConfigurationType ( CommentsWavePlugin . class . getTypeName ( ) ) ; addToContext ( contexts , pluginConfiguration ) ; if ( verbose ) getLog ( ) . info ( "enable comment wave service" ) ; for ( Context context : config . getContexts ( ) ) { context . getCommentGeneratorConfiguration ( ) . setConfigurationType ( CommentGenerator . class . getTypeName ( ) ) ; if ( i18nPath != null && i18nPath . exists ( ) ) { context . getCommentGeneratorConfiguration ( ) . addProperty ( CommentGenerator . XMBG_CG_I18N_PATH_KEY , i18nPath . getAbsolutePath ( ) ) ; } if ( StringUtils . isEmpty ( projectStartYear ) ) { projectStartYear = CommentGenerator . XMBG_CG_PROJECT_START_DEFAULT_YEAR ; } context . getCommentGeneratorConfiguration ( ) . addProperty ( CommentGenerator . XMBG_CG_PROJECT_START_YEAR , projectStartYear ) ; context . getCommentGeneratorConfiguration ( ) . addProperty ( CommentGenerator . XMBG_CG_I18N_LOCALE_KEY , locale ) ; } if ( verbose ) getLog ( ) . info ( "replace the origin comment generator" ) ; }
extend origin mbg the ability for generating comments
10,218
public static < T extends Node > AbstractMerger < T > getMerger ( Class < T > clazz ) { AbstractMerger < T > merger = null ; Class < ? > type = clazz ; while ( merger == null && type != null ) { merger = map . get ( type ) ; type = type . getSuperclass ( ) ; } return merger ; }
first check if mapper of the type T exist if existed return it else check if mapper of the supper type exist then return it
10,219
public boolean doIsEquals ( NormalAnnotationExpr first , NormalAnnotationExpr second ) { boolean equals = true ; if ( ! first . getName ( ) . equals ( second . getName ( ) ) ) equals = false ; if ( equals == true ) { if ( first . getPairs ( ) == null ) return second . getPairs ( ) == null ; if ( ! isSmallerHasEqualsInBigger ( first . getPairs ( ) , second . getPairs ( ) , true ) ) return false ; } return equals ; }
1 . check the name 2 . check the member including key and value if their size is not the same and the less one is all matched in the more one return true
10,220
public static String merge ( String first , String second ) throws ParseException { JavaParser . setDoNotAssignCommentsPreceedingEmptyLines ( false ) ; CompilationUnit cu1 = JavaParser . parse ( new StringReader ( first ) , true ) ; CompilationUnit cu2 = JavaParser . parse ( new StringReader ( second ) , true ) ; AbstractMerger < CompilationUnit > merger = AbstractMerger . getMerger ( CompilationUnit . class ) ; CompilationUnit result = merger . merge ( cu1 , cu2 ) ; return result . toString ( ) ; }
Util method to make source merge more convenient
10,221
public static Fixture parseFrom ( String fileName , Parser parser ) { if ( fileName == null ) { throw new NullPointerException ( "File name should not be null" ) ; } String path = "fixtures/" + fileName + ".yaml" ; InputStream inputStream = openPathAsStream ( path ) ; Fixture result = parser . parse ( inputStream ) ; if ( result . body != null && ! result . body . startsWith ( "{" ) ) { String bodyPath = "fixtures/" + result . body ; try { result . body = readPathIntoString ( bodyPath ) ; } catch ( IOException e ) { throw new IllegalStateException ( "Error reading body: " + bodyPath , e ) ; } } return result ; }
Parse the given filename and returns the Fixture object .
10,222
public Comparator < Object > withSourceProvider ( final OrderSourceProvider sourceProvider ) { return new Comparator < Object > ( ) { public int compare ( Object o1 , Object o2 ) { return doCompare ( o1 , o2 , sourceProvider ) ; } } ; }
Build an adapted order comparator with the given soruce provider .
10,223
public static String collapse ( String name ) { if ( name == null ) { return null ; } int breakPoint = name . lastIndexOf ( '.' ) ; if ( breakPoint < 0 ) { return name ; } return collapseQualifier ( name . substring ( 0 , breakPoint ) , true ) + name . substring ( breakPoint ) ; }
Collapses a name . Mainly intended for use with classnames where an example might serve best to explain . Imagine you have a class named org . hibernate . internal . util . StringHelper ; calling collapse on that classname will result in o . h . u . StringHelper .
10,224
public static String collapseQualifier ( String qualifier , boolean includeDots ) { StringTokenizer tokenizer = new StringTokenizer ( qualifier , "." ) ; String collapsed = Character . toString ( tokenizer . nextToken ( ) . charAt ( 0 ) ) ; while ( tokenizer . hasMoreTokens ( ) ) { if ( includeDots ) { collapsed += '.' ; } collapsed += tokenizer . nextToken ( ) . charAt ( 0 ) ; } return collapsed ; }
Given a qualifier collapse it .
10,225
public static String partiallyUnqualify ( String name , String qualifierBase ) { if ( name == null || ! name . startsWith ( qualifierBase ) ) { return name ; } return name . substring ( qualifierBase . length ( ) + 1 ) ; }
Partially unqualifies a qualified name . For example with a base of org . hibernate the name org . hibernate . internal . util . StringHelper would become util . StringHelper .
10,226
private static String cleanAlias ( String alias ) { char [ ] chars = alias . toCharArray ( ) ; if ( ! Character . isLetter ( chars [ 0 ] ) ) { for ( int i = 1 ; i < chars . length ; i ++ ) { if ( Character . isLetter ( chars [ i ] ) ) { return alias . substring ( i ) ; } } } return alias ; }
Clean the generated alias by removing any non - alpha characters from the beginning .
10,227
public String path ( M method , T target , Object ... params ) { MethodlessRouter < T > router = ( method == null ) ? anyMethodRouter : routers . get ( method ) ; if ( router == null ) router = anyMethodRouter ; String ret = router . path ( target , params ) ; if ( ret != null ) return ret ; return ( router == anyMethodRouter ) ? null : anyMethodRouter . path ( target , params ) ; }
Reverse routing .
10,228
public static < T , P extends Convertable < T > > T convert ( P value ) throws ParseException { return value == null ? null : value . convert ( ) ; }
Converting single item if it is not null .
10,229
public static < IN , OUT > OUT create ( IN obj , Creator < IN , OUT > creator ) { return obj == null ? null : creator . create ( obj ) ; }
Creates output object using provided creator . Returns null if obj null .
10,230
public static Object instanceFromTarget ( Object target ) throws InstantiationException , IllegalAccessException { if ( target == null ) return null ; if ( target instanceof Class ) { Class < ? > klass = ( Class < ? > ) target ; return klass . newInstance ( ) ; } else { return target ; } }
When target is a class this method calls newInstance on the class . Otherwise it returns the target as is .
10,231
private void getDescriptor ( final StringBuilder sb ) { if ( this . buf == null ) { sb . append ( ( char ) ( ( off & 0xFF000000 ) >>> 24 ) ) ; } else if ( sort == OBJECT ) { sb . append ( 'L' ) ; sb . append ( this . buf , off , len ) ; sb . append ( ';' ) ; } else { sb . append ( this . buf , off , len ) ; } }
Appends the descriptor corresponding to this Java type to the given string builder .
10,232
public static void showSoftKeyboard ( Context context , View view ) { if ( view == null ) { return ; } final InputMethodManager manager = ( InputMethodManager ) context . getSystemService ( Context . INPUT_METHOD_SERVICE ) ; view . requestFocus ( ) ; manager . showSoftInput ( view , 0 ) ; }
Shows soft keyboard and requests focus for given view .
10,233
public List < MockResponse > enqueue ( String ... paths ) { if ( paths == null ) { return null ; } List < MockResponse > mockResponseList = new ArrayList < > ( ) ; for ( String path : paths ) { Fixture fixture = Fixture . parseFrom ( path , parser ) ; MockResponse mockResponse = fixture . toMockResponse ( ) ; mockWebServer . enqueue ( mockResponse ) ; mockResponseList . add ( mockResponse ) ; } return mockResponseList ; }
Given paths will be parsed to fixtures and added to the queue . Can be multiple
10,234
public MockResponse enqueue ( SocketPolicy socketPolicy ) { MockResponse mockResponse = new MockResponse ( ) . setSocketPolicy ( socketPolicy ) ; mockWebServer . enqueue ( mockResponse ) ; return mockResponse ; }
Given policy will be enqueued as MockResponse
10,235
public static Class < ? > getMapValueReturnType ( Method method , int nestingLevel ) { return ResolvableType . forMethodReturnType ( method ) . getNested ( nestingLevel ) . asMap ( ) . resolveGeneric ( 1 ) ; }
Determine the generic value type of the given Map return type .
10,236
protected void addSingleUpsertToSqlMap ( Document document , IntrospectedTable introspectedTable ) { XmlElement update = new XmlElement ( "update" ) ; update . addAttribute ( new Attribute ( "id" , UPSERT ) ) ; update . addAttribute ( new Attribute ( "parameterType" , "map" ) ) ; generateSqlMapContent ( introspectedTable , update ) ; document . getRootElement ( ) . addElement ( update ) ; }
add update xml element to mapper . xml for upsert
10,237
public void start ( Intent intent ) { intent = setupIntent ( intent ) ; if ( application != null ) { intent . addFlags ( Intent . FLAG_ACTIVITY_NEW_TASK ) ; application . startActivity ( intent ) ; return ; } if ( activity != null ) { if ( requestCode == NO_RESULT_CODE ) { activity . startActivity ( intent ) ; } else { activity . startActivityForResult ( intent , requestCode ) ; } } else if ( fragment != null ) { if ( requestCode == NO_RESULT_CODE ) { fragment . startActivity ( intent ) ; } else { fragment . startActivityForResult ( intent , requestCode ) ; } } else if ( fragmentSupport != null ) { if ( requestCode == NO_RESULT_CODE ) { fragmentSupport . startActivity ( intent ) ; } else { fragmentSupport . startActivityForResult ( intent , requestCode ) ; } } setTransition ( false ) ; }
Starts activity by intent .
10,238
public void finish ( int resultCode , Intent data ) { Activity activity = getActivity ( ) ; activity . setResult ( resultCode , data ) ; activity . finish ( ) ; setTransition ( true ) ; }
Finishes current activity with provided result code and data .
10,239
public void navigateUp ( Intent intent ) { intent . setFlags ( Intent . FLAG_ACTIVITY_CLEAR_TOP | Intent . FLAG_ACTIVITY_SINGLE_TOP ) ; start ( intent ) ; finish ( ) ; }
Navigates up to specified activity in the back stack skipping intermediate activities
10,240
public static Config load ( final String ... resources ) { final ScriptEngine engine = new ScriptEngineManager ( ) . getEngineByName ( "nashorn" ) ; try ( final InputStream resourceAsStream = findResource ( "jjs-config-utils.js" ) ) { engine . eval ( new InputStreamReader ( resourceAsStream ) ) ; loadResources ( engine , resources ) ; } catch ( final ScriptException se ) { throw new IllegalArgumentException ( "unable to execute main javascript." , se ) ; } catch ( final Exception ex ) { if ( ex instanceof IllegalArgumentException ) { throw ( IllegalArgumentException ) ex ; } throw new IllegalArgumentException ( "unable to load main resource " , ex ) ; } return loadFromObject ( engine . get ( "config" ) ) ; }
Loads a config file .
10,241
private Duration parseDurationUsingTypeSafeSpec ( final String path , final String durationString ) { final Optional < Map . Entry < TimeUnit , List < String > > > entry = timeUnitMap . entrySet ( ) . stream ( ) . filter ( timeUnitListEntry -> timeUnitListEntry . getValue ( ) . stream ( ) . anyMatch ( durationString :: endsWith ) ) . findFirst ( ) ; if ( ! entry . isPresent ( ) ) { throw new IllegalArgumentException ( "Path " + path + " does not resolve to a duration " + durationString ) ; } Optional < Duration > optional = entry . map ( timeUnitListEntry -> { final Optional < String > postFix = timeUnitListEntry . getValue ( ) . stream ( ) . filter ( durationString :: endsWith ) . findFirst ( ) ; if ( postFix . isPresent ( ) ) { final String unitString = durationString . replace ( postFix . get ( ) , "" ) . trim ( ) ; try { long unit = Long . parseLong ( unitString ) ; return Duration . ofNanos ( timeUnitListEntry . getKey ( ) . toNanos ( unit ) ) ; } catch ( NumberFormatException nfe ) { throw new IllegalArgumentException ( "Path does not resolve to a duration " + durationString ) ; } } else { throw new IllegalArgumentException ( "Path does not resolve to a duration " + durationString ) ; } } ) ; if ( optional . isPresent ( ) ) { return optional . get ( ) ; } else { throw new IllegalArgumentException ( "Path does not resolve to a duration " + durationString ) ; } }
Parses a string into duration type safe spec format if possible .
10,242
public static Set < String > lowercaseLines ( final Class < ? > origin , final String resource ) throws IOException { return ImmutableSet . copyOf ( new HashSet < String > ( ) { { readResource ( origin , resource , new NullReturnLineProcessor ( ) { public boolean processLine ( final String line ) { final String l = simplify ( line ) ; if ( ! l . startsWith ( "#" ) && ! l . isEmpty ( ) ) add ( toEngLowerCase ( l ) ) ; return true ; } } ) ; } } ) ; }
Return a Set containing trimmed lowercaseLines read from a file skipping comments .
10,243
public static ImmutableSet < String > lowercaseWordSet ( final Class < ? > origin , final String resource , final boolean eliminatePrepAndConj ) throws IOException { return ImmutableSet . copyOf ( new HashSet < String > ( ) { { readResource ( origin , resource , new NullReturnLineProcessor ( ) { public boolean processLine ( final String line ) { final String l = simplify ( line ) ; if ( ! l . isEmpty ( ) && ! l . startsWith ( "#" ) ) { for ( final String part : SPACES . split ( l ) ) { if ( eliminatePrepAndConj ) { final String wordType = Dictionary . checkup ( part ) ; if ( wordType != null && ( wordType . startsWith ( "IN" ) || wordType . startsWith ( "CC" ) ) ) { continue ; } } add ( toEngLowerCase ( clean ( part ) ) ) ; } } return true ; } } ) ; } } ) ; }
Returns a Set containing only single words .
10,244
public static ImmutableSet < String > wordSet ( final Class < ? > origin , final String resource ) throws IOException { return ImmutableSet . copyOf ( new HashSet < String > ( ) { { readResource ( origin , resource , new NullReturnLineProcessor ( ) { public boolean processLine ( final String line ) { final String l = simplify ( line ) ; if ( ! l . isEmpty ( ) && ! l . startsWith ( "#" ) ) { for ( final String part : SPACES . split ( l ) ) { add ( clean ( part ) ) ; } } return true ; } } ) ; } } ) ; }
Return a set containing all non - comment non - empty words .
10,245
public void process ( final NerResultSet resultSet ) { final FeatureMap featureMap = conf . getFeatureMap ( ) ; if ( conf . tracing ) trace = new ArrayList < > ( ) ; final Map < Phrase , Set < Phrase > > phraseInMemory = new HashMap < > ( ) ; for ( final List < Phrase > phrasesInSentence : resultSet . phrases ) { for ( final Phrase phrase : phrasesInSentence ) { if ( phrase . isDate ) continue ; phrase . score = featureMap . score ( phrase ) ; if ( conf . tracing ) { trace . addAll ( featureMap . trace ) ; } boolean isSubPhrase = false ; for ( final Map . Entry < Phrase , Set < Phrase > > inMemoryEntry : phraseInMemory . entrySet ( ) ) { if ( phrase . isSubPhraseOf ( inMemoryEntry . getKey ( ) ) ) { inMemoryEntry . getValue ( ) . add ( phrase ) ; isSubPhrase = true ; break ; } } if ( ! isSubPhrase || phrase . phrase . size ( ) > 1 ) { final Set < Phrase > newSet = new HashSet < > ( ) ; newSet . add ( phrase ) ; phraseInMemory . put ( phrase , newSet ) ; } } } for ( final Map . Entry < Phrase , Set < Phrase > > inMemoryPhrase : phraseInMemory . entrySet ( ) ) { final Set < Phrase > aSet = inMemoryPhrase . getValue ( ) ; final Map < EntityClass , Double > score = inMemoryPhrase . getKey ( ) . score ; for ( final Phrase phrase : aSet ) { phrase . classify ( ) ; if ( EntityClass . UNKNOWN . equals ( phrase . phraseType ) ) { phrase . score = score ; phrase . classify ( ) ; } } } }
This method process the whole input result set and gives all _phrases in the set a name type - modifies the data of the passed in NerResultSet!
10,246
public List < List < Token > > process ( final String text ) { final List < List < Token > > paragraph = new ArrayList < > ( ) ; currentSentence = new ArrayList < > ( ) ; final Tokens tokens = splitText ( text ) ; while ( tokens . hasNext ( ) ) { final Token t = tokens . next ( ) ; final String trimmedWord = t . text . trim ( ) ; if ( trimmedWord . isEmpty ( ) ) continue ; if ( ( ( mode == WITH_PUNCTUATION ) || ( mode == WITHOUT_PUNCTUATION && isLetterOrDigit ( initChar ( t . text ) ) ) ) ) { boolean canBreakSentence = true ; if ( t . text . contains ( "'" ) ) { wordContainsApostrophe ( t ) ; } else if ( "." . equals ( trimmedWord ) ) { canBreakSentence = wordIsFullStop ( t ) ; } else if ( ":" . equals ( trimmedWord ) ) { wordIsColon ( tokens , t ) ; } else currentSentence . add ( t ) ; if ( canBreakSentence && equalss ( trimmedWord , "." , ";" , "?" , "!" ) ) { paragraph . add ( currentSentence ) ; currentSentence = new ArrayList < > ( ) ; } } } if ( ! currentSentence . isEmpty ( ) ) paragraph . add ( currentSentence ) ; return paragraph ; }
Tokenize some text - not thread safe .
10,247
private static boolean detectNameWordInSentenceByPosition ( final List < Token > _text , final int _pos ) { boolean isFirstWord = false ; boolean nextWordIsName = false ; if ( _pos == 0 || ! isLetterOrDigit ( ( _text . get ( _pos - 1 ) . text . charAt ( 0 ) ) ) ) { isFirstWord = true ; if ( _text . size ( ) > _pos + 1 ) { final String plus1 = _text . get ( _pos + 1 ) . text ; nextWordIsName = ( "of" . equalsIgnoreCase ( plus1 ) || "'s" . equalsIgnoreCase ( plus1 ) ) ? ( ( _text . size ( ) > ( _pos + 2 ) ) && isName ( _text . get ( _pos + 2 ) . text , false , false ) ) : isName ( plus1 , false , false ) ; } else nextWordIsName = false ; } final boolean isName = isName ( _text . get ( _pos ) . text , isFirstWord , nextWordIsName ) ; return isName ; }
Detects if a particular word in a sentence is a name .
10,248
private static boolean isName ( final String _text , final boolean isFirstWord , final boolean nextWordIsName ) { if ( hasManyCaps ( _text ) ) return true ; else if ( startsWithCap ( _text ) ) { if ( isFirstWord ) { if ( _text . endsWith ( "ly" ) ) return false ; final String type_original = Dictionary . checkup ( _text ) ; final String type_lowercase = Dictionary . checkup ( toEngLowerCase ( _text ) ) ; if ( type_original == null ) { if ( type_lowercase == null ) return true ; } else if ( "NNP" . equals ( type_original ) ) return true ; if ( startsWith ( type_lowercase , "IN" , "CC" , "RB" , "WRB" , "." ) ) return false ; else return nextWordIsName ; } else return true ; } else return false ; }
This method detects a word if it is a potential name word .
10,249
private static void getAttachedPrep ( final List < Token > sentenceToken , final List < Phrase > sentencePhrase , final int index ) { final String prep ; boolean nameSequenceMeetEnd = true ; final Collection < Phrase > phraseSequence = new HashSet < > ( ) ; int phrasePtr = index ; Phrase currentNamePhrase = sentencePhrase . get ( phrasePtr ) ; int phrasePtrInSentence ; if ( currentNamePhrase . attachedWordMap . get ( "prep" ) != null ) return ; while ( true ) { currentNamePhrase = sentencePhrase . get ( phrasePtr ) ; phrasePtrInSentence = currentNamePhrase . phrasePosition ; if ( phrasePtrInSentence == 0 ) return ; final String attachedWord = sentenceToken . get ( phrasePtrInSentence - 1 ) . text ; if ( "," . equalsIgnoreCase ( attachedWord ) ) { nameSequenceMeetEnd = false ; phraseSequence . add ( currentNamePhrase ) ; } else if ( "and" . equalsIgnoreCase ( attachedWord ) || "or" . equalsIgnoreCase ( attachedWord ) ) { phraseSequence . add ( currentNamePhrase ) ; nameSequenceMeetEnd = true ; } else if ( Dictionary . checkup ( toEngLowerCase ( attachedWord ) ) != null && Dictionary . checkup ( toEngLowerCase ( attachedWord ) ) . startsWith ( "IN" ) ) { prep = attachedWord ; phraseSequence . add ( currentNamePhrase ) ; break ; } else { return ; } phrasePtr -- ; if ( phrasePtr < 0 ) return ; if ( sentencePhrase . get ( phrasePtr ) . isDate ) return ; if ( sentencePhrase . get ( phrasePtr ) . phrasePosition + sentencePhrase . get ( phrasePtr ) . phraseLength + 1 != phrasePtrInSentence ) return ; } phrasePtr = index + 1 ; while ( ! nameSequenceMeetEnd ) { if ( phrasePtr == sentencePhrase . size ( ) ) return ; currentNamePhrase = sentencePhrase . get ( phrasePtr ) ; if ( currentNamePhrase . isDate ) return ; phrasePtrInSentence = currentNamePhrase . phrasePosition ; if ( sentencePhrase . get ( phrasePtr - 1 ) . phrasePosition + sentencePhrase . get ( phrasePtr - 1 ) . phraseLength + 1 != currentNamePhrase . phrasePosition ) return ; final String attachedWord = sentenceToken . get ( phrasePtrInSentence - 1 ) . text ; if ( "," . equalsIgnoreCase ( attachedWord ) ) { phraseSequence . add ( currentNamePhrase ) ; } else if ( "and" . equalsIgnoreCase ( attachedWord ) || "or" . equalsIgnoreCase ( attachedWord ) ) { phraseSequence . add ( currentNamePhrase ) ; break ; } else { return ; } phrasePtr ++ ; } for ( final Phrase name : phraseSequence ) { name . attachedWordMap . put ( "prep" , prep ) ; } }
This method will find all the attached preps of a phrase .
10,250
private static boolean startsWithCap ( final String word ) { return ! "i" . equalsIgnoreCase ( word ) && isAllowedChar ( word . charAt ( 0 ) ) && isUpperCase ( word . charAt ( 0 ) ) ; }
This method detects if the word s first character is in capital size .
10,251
private static boolean hasManyCaps ( final String word ) { if ( "i" . equalsIgnoreCase ( word ) ) return false ; int capCharCount = 0 ; for ( int i = 0 ; i < word . length ( ) ; i ++ ) { if ( isUpperCase ( word . charAt ( i ) ) ) capCharCount ++ ; if ( capCharCount == 2 ) return true ; } return false ; }
This method detects if the word has more than one character which is capital sized .
10,252
public static boolean isPlural ( final String _word ) { final String word = toEngLowerCase ( _word ) ; if ( word . endsWith ( "s" ) ) { final String wordStub = word . substring ( 0 , word . length ( ) - 1 ) ; if ( checkup ( wordStub ) != null ) return true ; } if ( word . endsWith ( "ed" ) ) { final String wordStub = word . substring ( 0 , word . length ( ) - 2 ) ; if ( checkup ( wordStub ) != null ) return true ; } if ( word . endsWith ( "ied" ) ) { final String wordStub = word . substring ( 0 , word . length ( ) - 3 ) + "y" ; if ( checkup ( wordStub ) != null ) return true ; } return false ; }
This method checks if the word is a plural form .
10,253
private void addHeadersToContext ( final HttpHeaders headers ) { for ( HttpHeader header : headers . all ( ) ) { final String rawKey = header . key ( ) ; final String transformedKey = rawKey . replaceAll ( "-" , "" ) ; context . put ( "requestHeader" . concat ( transformedKey ) , header . values ( ) . toString ( ) ) ; } }
Adds the request header information to the Velocity context .
10,254
private void addBodyToContext ( final String body ) { if ( ! body . isEmpty ( ) ) { final JSONParser parser = new JSONParser ( ) ; try { final JSONObject json = ( JSONObject ) parser . parse ( body ) ; context . put ( "requestBody" , json ) ; } catch ( final ParseException e ) { e . printStackTrace ( ) ; } } }
Adds the request body to the context if one exists .
10,255
private String getRenderedBody ( final ResponseDefinition response ) { final String templatePath = fileSource . getPath ( ) . concat ( "/" + response . getBodyFileName ( ) ) ; final Template template = Velocity . getTemplate ( templatePath ) ; StringWriter writer = new StringWriter ( ) ; template . merge ( context , writer ) ; final String rendered = String . valueOf ( writer . getBuffer ( ) ) ; return rendered ; }
Renders the velocity template .
10,256
public static Map < Integer , NerClassification > positionClassificationMap ( final NerResultSet nerResultSet ) { final Map < Integer , NerClassification > m = new HashMap < > ( ) ; for ( final List < Phrase > sentence : nerResultSet . phrases ) { for ( final Phrase p : sentence ) { final int phraseStartIndex = p . phrase . get ( 0 ) . startIndex ; for ( final Token t : p . phrase ) { final NerClassification clas = new NerClassification ( t . text , p . phraseType , phraseStartIndex , p . score ) ; final NerClassification replaced = m . put ( t . startIndex , clas ) ; if ( replaced != null ) { System . err . println ( "########### Error start" ) ; System . err . print ( nerResultSet ) ; throw new IllegalStateException ( "Tried to add a Token to the position classification map " + "with startIndex " + t . startIndex + " that is already there!" ) ; } } } } return m ; }
Return a Map of Token startIndex to classification of the Phrase that Token is a part of .
10,257
public static Feature generateFeatureByName ( final String featureType , final int weight , final List < String > resourceNames ) throws IllegalArgumentException , IOException { switch ( featureType ) { case "RuledWordFeature" : return new RuledWordFeature ( resourceNames , weight ) ; case "PrepositionContextFeature" : return new PrepositionContextFeature ( resourceNames , weight ) ; case "ExistingPhraseFeature" : return new ExistingPhraseFeature ( resourceNames , weight ) ; case "ExistingCleanPhraseFeature" : return new ExistingCleanPhraseFeature ( resourceNames , weight ) ; case "CaseSensitiveWordLookup" : return new CaseSensitiveWordLookup ( resourceNames , weight ) ; case "CaseInsensitiveWordLookup" : return new CaseInsensitiveWordLookup ( resourceNames , weight ) ; default : throw new IllegalArgumentException ( "Unknown feature: '" + featureType + "'" ) ; } }
Factory method create features by name .
10,258
public float getVoltage ( ) { float inMin = 0 ; float inMax = 100 ; float outMin = ( float ) 2.0 ; float outMax = ( float ) 3.7 ; float x = this . percentage ; return ( x - inMin ) * ( outMax - outMin ) / ( inMax - inMin ) + outMin ; }
Get the battery level in volts .
10,259
private void reset ( ) { setState ( OADState . INACTIVE ) ; currentImage = null ; firmwareBundle = null ; nextBlock = 0 ; oadListener = null ; watchdog . stop ( ) ; oadApproval . reset ( ) ; }
Set the state to INACTIVE and clear state variables
10,260
private void reconnect ( ) { if ( uploadInProgress ( ) ) { setState ( OADState . RECONNECTING ) ; BeanManager . getInstance ( ) . startDiscovery ( ) ; Log . i ( TAG , "Waiting for device to reconnect..." ) ; } }
Attempt to reconnect to a Bean that is in the middle of OAD process
10,261
private void offerNextImage ( ) { if ( oadState == OADState . OFFERING_IMAGES ) { try { currentImage = firmwareBundle . getNextImage ( ) ; if ( currentImage != null ) { Log . i ( TAG , "Offering image: " + currentImage . name ( ) ) ; writeToCharacteristic ( oadIdentify , currentImage . metadata ( ) ) ; } } catch ( OADException e ) { Log . e ( TAG , e . getMessage ( ) ) ; fail ( BeanError . BEAN_REJECTED_FW ) ; } } else { Log . e ( TAG , "Got notification on OAD Identify while in unexpected state: " + oadState ) ; } }
Offer the next image available in the Firmware Bundle
10,262
private void onNotificationBlock ( BluetoothGattCharacteristic characteristic ) { int requestedBlock = Convert . twoBytesToInt ( characteristic . getValue ( ) , Constants . CC2540_BYTE_ORDER ) ; if ( requestedBlock == 0 ) { Log . i ( TAG , String . format ( "Image accepted (Name: %s) (Size: %s bytes)" , currentImage . name ( ) , currentImage . sizeBytes ( ) ) ) ; blockTransferStarted = System . currentTimeMillis ( ) / 1000L ; setState ( OADState . BLOCK_XFER ) ; nextBlock = 0 ; } while ( oadState == OADState . BLOCK_XFER && nextBlock <= currentImage . blockCount ( ) - 1 && nextBlock < ( requestedBlock + MAX_IN_AIR_BLOCKS ) ) { writeToCharacteristic ( oadBlock , currentImage . block ( nextBlock ) ) ; oadListener . progress ( UploadProgress . create ( nextBlock + 1 , currentImage . blockCount ( ) ) ) ; nextBlock ++ ; watchdog . poke ( ) ; } if ( requestedBlock == currentImage . blockCount ( ) - 1 ) { long secondsElapsed = System . currentTimeMillis ( ) / 1000L - blockTransferStarted ; double KBs = 0 ; if ( secondsElapsed > 0 ) { KBs = ( double ) ( currentImage . sizeBytes ( ) / secondsElapsed ) / 1000 ; } Log . i ( TAG , String . format ( "Final OAD Block Requested: %s/%s" , nextBlock , currentImage . blockCount ( ) ) ) ; Log . i ( TAG , String . format ( "Sent %d blocks in %d seconds (%.2f KB/s)" , currentImage . blockCount ( ) , secondsElapsed , KBs ) ) ; } }
Received a notification on Block characteristic
10,263
private void setupOAD ( ) { BluetoothGattService oadService = mGattClient . getService ( Constants . UUID_OAD_SERVICE ) ; if ( oadService == null ) { fail ( BeanError . MISSING_OAD_SERVICE ) ; return ; } oadIdentify = oadService . getCharacteristic ( Constants . UUID_OAD_CHAR_IDENTIFY ) ; if ( oadIdentify == null ) { fail ( BeanError . MISSING_OAD_IDENTIFY ) ; return ; } oadBlock = oadService . getCharacteristic ( Constants . UUID_OAD_CHAR_BLOCK ) ; if ( oadBlock == null ) { fail ( BeanError . MISSING_OAD_BLOCK ) ; return ; } }
Setup BLOCK and IDENTIFY characteristics
10,264
private void setupNotifications ( ) { Log . i ( TAG , "Enabling OAD notifications" ) ; boolean oadIdentifyNotifying = enableNotifyForChar ( oadIdentify ) ; boolean oadBlockNotifying = enableNotifyForChar ( oadBlock ) ; if ( oadIdentifyNotifying && oadBlockNotifying ) { Log . i ( TAG , "Enable notifications successful" ) ; } else { Log . e ( TAG , "Error while enabling notifications" ) ; fail ( BeanError . ENABLE_OAD_NOTIFY_FAILED ) ; } }
Enables notifications for all OAD characteristics .
10,265
private boolean enableNotifyForChar ( BluetoothGattCharacteristic characteristic ) { boolean success = true ; boolean successEnable = mGattClient . setCharacteristicNotification ( characteristic , true ) ; if ( successEnable ) { Log . i ( TAG , "Enabled notify for characteristic: " + characteristic . getUuid ( ) ) ; } else { success = false ; Log . e ( TAG , "Enable notify failed for characteristic: " + characteristic . getUuid ( ) ) ; } BluetoothGattDescriptor descriptor = characteristic . getDescriptor ( Constants . UUID_CLIENT_CHAR_CONFIG ) ; descriptor . setValue ( BluetoothGattDescriptor . ENABLE_NOTIFICATION_VALUE ) ; boolean successDescriptor = mGattClient . writeDescriptor ( descriptor ) ; if ( successDescriptor ) { Log . i ( TAG , "Successfully wrote notification descriptor: " + descriptor . getUuid ( ) ) ; } else { success = false ; Log . e ( TAG , "Failed to write notification descriptor: " + descriptor . getUuid ( ) ) ; } return success ; }
Enable notifications for a given characteristic .
10,266
private boolean writeToCharacteristic ( BluetoothGattCharacteristic charc , byte [ ] data ) { charc . setValue ( data ) ; boolean result = mGattClient . writeCharacteristic ( charc ) ; if ( result ) { Log . d ( TAG , "Wrote to characteristic: " + charc . getUuid ( ) + ", data: " + Arrays . toString ( data ) ) ; } else { Log . e ( TAG , "Write failed to characteristic: " + charc . getUuid ( ) + ", data: " + Arrays . toString ( data ) ) ; } return result ; }
Write to a OAD characteristic
10,267
private boolean needsUpdate ( Long bundleVersion , String beanVersion ) { if ( beanVersion . contains ( "OAD" ) ) { Log . i ( TAG , "Bundle version: " + bundleVersion ) ; Log . i ( TAG , "Bean version: " + beanVersion ) ; return true ; } else { try { long parsedVersion = Long . parseLong ( beanVersion . split ( " " ) [ 0 ] ) ; Log . i ( TAG , "Bundle version: " + bundleVersion ) ; Log . i ( TAG , "Bean version: " + parsedVersion ) ; if ( bundleVersion > parsedVersion ) { return true ; } else { Log . i ( TAG , "No update required!" ) ; } } catch ( NumberFormatException e ) { Log . e ( TAG , "Couldn't parse Bean Version: " + beanVersion ) ; fail ( BeanError . UNPARSABLE_FW_VERSION ) ; } } return false ; }
Helper function to determine whether a Bean needs a FW update given a specific Bundle version
10,268
private void checkFirmwareVersion ( ) { Log . i ( TAG , "Checking Firmware version..." ) ; setState ( OADState . CHECKING_FW_VERSION ) ; mGattClient . getDeviceProfile ( ) . getFirmwareVersion ( new DeviceProfile . VersionCallback ( ) { public void onComplete ( String version ) { boolean updateNeeded = needsUpdate ( firmwareBundle . version ( ) , version ) ; if ( updateNeeded && oadApproval . isApproved ( ) ) { startOfferingImages ( ) ; } else if ( updateNeeded && ! oadApproval . isApproved ( ) ) { watchdog . pause ( ) ; oadListener . updateRequired ( true ) ; } else if ( ! updateNeeded && ! oadApproval . isApproved ( ) ) { finishNoUpdateOccurred ( ) ; oadListener . updateRequired ( false ) ; } else if ( ! updateNeeded && oadApproval . isApproved ( ) ) { finishUpdateOccurred ( ) ; } else { Log . w ( TAG , "Unexpected OAD Condition!" ) ; } } } ) ; }
Check the Beans FW version to determine if an update is required
10,269
private void fail ( BeanError error ) { Log . e ( TAG , "OAD Error: " + error . toString ( ) ) ; if ( uploadInProgress ( ) ) { oadListener . error ( error ) ; reset ( ) ; } }
Stop the firmware upload and alert the OADListener
10,270
public OADApproval programWithFirmware ( final FirmwareBundle bundle , OADListener listener ) { if ( ! mGattClient . isConnected ( ) ) { listener . error ( BeanError . NOT_CONNECTED ) ; } Log . i ( TAG , "Starting firmware update procedure" ) ; this . oadListener = listener ; this . firmwareBundle = bundle ; watchdog . start ( OAD_TIMEOUT_SECONDS , watchdogListener ) ; checkFirmwareVersion ( ) ; return this . oadApproval ; }
Program the Bean s CC2540 with new firmware .
10,271
public ObservableMap < String , Property < ? > > getBindings ( ) { if ( bindings == null ) { bindings = FXCollections . observableHashMap ( ) ; } return bindings ; }
session scope bindings
10,272
public static < T > Observable . Transformer < T , ImmutableList < T > > toImmutableList ( ) { return new Observable . Transformer < T , ImmutableList < T > > ( ) { public Observable < ImmutableList < T > > call ( Observable < T > source ) { return source . collect ( new Func0 < ImmutableList . Builder < T > > ( ) { public ImmutableList . Builder < T > call ( ) { return ImmutableList . builder ( ) ; } } , new Action2 < ImmutableList . Builder < T > , T > ( ) { public void call ( ImmutableList . Builder < T > builder , T t ) { builder . add ( t ) ; } } ) . map ( new Func1 < ImmutableList . Builder < T > , ImmutableList < T > > ( ) { public ImmutableList < T > call ( ImmutableList . Builder < T > builder ) { return builder . build ( ) ; } } ) ; } } ; }
Returns a Transformer&lt ; T ImmutableList&lt ; T&gt ; &gt that maps an Observable&lt ; T&gt ; to an Observable&lt ; ImmutableList&lt ; T&gt ; &gt ;
10,273
public static < T > Observable . Transformer < T , ImmutableSet < T > > toImmutableSet ( ) { return new Observable . Transformer < T , ImmutableSet < T > > ( ) { public Observable < ImmutableSet < T > > call ( Observable < T > source ) { return source . collect ( new Func0 < ImmutableSet . Builder < T > > ( ) { public ImmutableSet . Builder < T > call ( ) { return ImmutableSet . builder ( ) ; } } , new Action2 < ImmutableSet . Builder < T > , T > ( ) { public void call ( ImmutableSet . Builder < T > builder , T t ) { builder . add ( t ) ; } } ) . map ( new Func1 < ImmutableSet . Builder < T > , ImmutableSet < T > > ( ) { public ImmutableSet < T > call ( ImmutableSet . Builder < T > builder ) { return builder . build ( ) ; } } ) ; } } ; }
Returns a Transformer&lt ; T ImmutableSet&lt ; T&gt ; &gt that maps an Observable&lt ; T&gt ; to an Observable&lt ; ImmutableSet&lt ; T&gt ; &gt ;
10,274
public boolean update ( Object key , Object value , Object currentVersion , Object previousVersion ) throws CacheException { log . debug ( "region access strategy nonstrict-read-write entity update() {} {}" , getInternalRegion ( ) . getCacheNamespace ( ) , key ) ; return false ; }
not necessary in nostrict - read - write
10,275
public boolean afterUpdate ( Object key , Object value , Object currentVersion , Object previousVersion , SoftLock lock ) throws CacheException { log . debug ( "region access strategy nonstrict-read-write entity afterUpdate() {} {}" , getInternalRegion ( ) . getCacheNamespace ( ) , key ) ; getInternalRegion ( ) . evict ( key ) ; return false ; }
need evict the key after update .
10,276
private void handleMessage ( byte [ ] data ) { Buffer buffer = new Buffer ( ) ; buffer . write ( data ) ; int type = ( buffer . readShort ( ) & 0xffff ) & ~ ( APP_MSG_RESPONSE_BIT ) ; if ( type == BeanMessageID . SERIAL_DATA . getRawValue ( ) ) { beanListener . onSerialMessageReceived ( buffer . readByteArray ( ) ) ; } else if ( type == BeanMessageID . BT_GET_CONFIG . getRawValue ( ) ) { returnConfig ( buffer ) ; } else if ( type == BeanMessageID . CC_TEMP_READ . getRawValue ( ) ) { returnTemperature ( buffer ) ; } else if ( type == BeanMessageID . BL_GET_META . getRawValue ( ) ) { returnMetadata ( buffer ) ; } else if ( type == BeanMessageID . BT_GET_SCRATCH . getRawValue ( ) ) { returnScratchData ( buffer ) ; } else if ( type == BeanMessageID . CC_LED_READ_ALL . getRawValue ( ) ) { returnLed ( buffer ) ; } else if ( type == BeanMessageID . CC_ACCEL_READ . getRawValue ( ) ) { returnAcceleration ( buffer ) ; } else if ( type == BeanMessageID . CC_ACCEL_GET_RANGE . getRawValue ( ) ) { returnAccelerometerRange ( buffer ) ; } else if ( type == BeanMessageID . CC_GET_AR_POWER . getRawValue ( ) ) { returnArduinoPowerState ( buffer ) ; } else if ( type == BeanMessageID . BL_STATUS . getRawValue ( ) ) { try { Status status = Status . fromPayload ( buffer ) ; handleStatus ( status ) ; } catch ( NoEnumFoundException e ) { Log . e ( TAG , "Unable to parse status from buffer: " + buffer . toString ( ) ) ; e . printStackTrace ( ) ; } } else { String fourDigitHex = Integer . toHexString ( type ) ; while ( fourDigitHex . length ( ) < 4 ) { fourDigitHex = "0" + fourDigitHex ; } Log . e ( TAG , "Received message of unknown type 0x" + fourDigitHex ) ; returnError ( BeanError . UNKNOWN_MESSAGE_ID ) ; } }
Handles incoming messages from the Bean and dispatches them to the proper handlers .
10,277
private void handleStatus ( Status status ) { Log . d ( TAG , "Handling Bean status: " + status ) ; BeanState beanState = status . beanState ( ) ; if ( beanState == BeanState . READY ) { resetSketchStateTimeout ( ) ; if ( sketchUploadState == SketchUploadState . SENDING_START_COMMAND ) { sketchUploadState = SketchUploadState . SENDING_BLOCKS ; stopSketchStateTimeout ( ) ; sendNextSketchBlock ( ) ; } } else if ( beanState == BeanState . PROGRAMMING ) { resetSketchStateTimeout ( ) ; } else if ( beanState == BeanState . COMPLETE ) { if ( onSketchUploadComplete != null ) onSketchUploadComplete . run ( ) ; resetSketchUploadState ( ) ; } else if ( beanState == BeanState . ERROR ) { returnUploadError ( BeanError . UNKNOWN ) ; resetSketchUploadState ( ) ; } }
Fired when the Bean sends a Status message . Updates the client s internal state machine used for uploading sketches and firmware to the Bean .
10,278
private void resetSketchStateTimeout ( ) { TimerTask onTimeout = new TimerTask ( ) { public void run ( ) { returnUploadError ( BeanError . STATE_TIMEOUT ) ; } } ; stopSketchStateTimeout ( ) ; sketchStateTimeout = new Timer ( ) ; sketchStateTimeout . schedule ( onTimeout , SKETCH_UPLOAD_STATE_TIMEOUT ) ; }
Reset the state timeout timer . If this timer fires the client has waited too long for a state update from the Bean and an error will be fired .
10,279
private void resetSketchBlockSendTimeout ( ) { TimerTask onTimeout = new TimerTask ( ) { public void run ( ) { sendNextSketchBlock ( ) ; } } ; stopSketchBlockSendTimeout ( ) ; sketchBlockSendTimeout = new Timer ( ) ; sketchBlockSendTimeout . schedule ( onTimeout , SKETCH_BLOCK_SEND_INTERVAL ) ; }
Reset the block send timer . When this timer fires another sketch block is sent .
10,280
private void sendNextSketchBlock ( ) { byte [ ] rawBlock = sketchBlocksToSend . get ( currSketchBlockNum ) ; Buffer block = new Buffer ( ) ; block . write ( rawBlock ) ; sendMessage ( BeanMessageID . BL_FW_BLOCK , block ) ; resetSketchBlockSendTimeout ( ) ; int blocksSent = currSketchBlockNum + 1 ; int totalBlocks = sketchBlocksToSend . size ( ) ; onSketchUploadProgress . onResult ( UploadProgress . create ( blocksSent , totalBlocks ) ) ; currSketchBlockNum ++ ; if ( currSketchBlockNum >= sketchBlocksToSend . size ( ) ) { resetSketchUploadState ( ) ; } }
Send one block of sketch data to the Bean and increment the block counter .
10,281
private void addCallback ( BeanMessageID type , Callback < ? > callback ) { List < Callback < ? > > callbacks = beanCallbacks . get ( type ) ; if ( callbacks == null ) { callbacks = new ArrayList < > ( 16 ) ; beanCallbacks . put ( type , callbacks ) ; } callbacks . add ( callback ) ; }
Add a callback for a Bean message type .
10,282
@ SuppressWarnings ( "unchecked" ) private < T > Callback < T > getFirstCallback ( BeanMessageID type ) { List < Callback < ? > > callbacks = beanCallbacks . get ( type ) ; if ( callbacks == null || callbacks . isEmpty ( ) ) { Log . w ( TAG , "Got response without callback!" ) ; return null ; } return ( Callback < T > ) callbacks . remove ( 0 ) ; }
Get the first callback for a Bean message type .
10,283
public void connect ( Context context , BeanListener listener ) { lastKnownContext = context ; beanListener = listener ; gattClient . connect ( context , device ) ; }
Attempt to connect to this Bean .
10,284
public void setLed ( LedColor color ) { Buffer buffer = new Buffer ( ) ; buffer . writeByte ( color . red ( ) ) ; buffer . writeByte ( color . green ( ) ) ; buffer . writeByte ( color . blue ( ) ) ; sendMessage ( BeanMessageID . CC_LED_WRITE_ALL , buffer ) ; }
Set the LED color .
10,285
public void readLed ( Callback < LedColor > callback ) { addCallback ( BeanMessageID . CC_LED_READ_ALL , callback ) ; sendMessageWithoutPayload ( BeanMessageID . CC_LED_READ_ALL ) ; }
Read the LED color .
10,286
public void setAdvertising ( boolean enable ) { Buffer buffer = new Buffer ( ) ; buffer . writeByte ( enable ? 1 : 0 ) ; sendMessage ( BeanMessageID . BT_ADV_ONOFF , buffer ) ; }
Set the advertising flag .
10,287
public void readTemperature ( Callback < Integer > callback ) { addCallback ( BeanMessageID . CC_TEMP_READ , callback ) ; sendMessageWithoutPayload ( BeanMessageID . CC_TEMP_READ ) ; }
Request a temperature reading .
10,288
public void readAcceleration ( Callback < Acceleration > callback ) { addCallback ( BeanMessageID . CC_ACCEL_READ , callback ) ; sendMessageWithoutPayload ( BeanMessageID . CC_ACCEL_READ ) ; }
Request an acceleration sensor reading .
10,289
public void readSketchMetadata ( Callback < SketchMetadata > callback ) { addCallback ( BeanMessageID . BL_GET_META , callback ) ; sendMessageWithoutPayload ( BeanMessageID . BL_GET_META ) ; }
Request the sketch metadata .
10,290
public void readScratchData ( ScratchBank bank , Callback < ScratchData > callback ) { addCallback ( BeanMessageID . BT_GET_SCRATCH , callback ) ; Buffer buffer = new Buffer ( ) ; buffer . writeByte ( intToByte ( bank . getRawValue ( ) ) ) ; sendMessage ( BeanMessageID . BT_GET_SCRATCH , buffer ) ; }
Request a scratch bank data value .
10,291
public void setAccelerometerRange ( AccelerometerRange range ) { Buffer buffer = new Buffer ( ) ; buffer . writeByte ( range . getRawValue ( ) ) ; sendMessage ( BeanMessageID . CC_ACCEL_SET_RANGE , buffer ) ; }
Set the accelerometer range .
10,292
public void readAccelerometerRange ( Callback < AccelerometerRange > callback ) { addCallback ( BeanMessageID . CC_ACCEL_GET_RANGE , callback ) ; sendMessageWithoutPayload ( BeanMessageID . CC_ACCEL_GET_RANGE ) ; }
Read the accelerometer range .
10,293
public void setScratchData ( ScratchBank bank , byte [ ] data ) { ScratchData sd = ScratchData . create ( bank , data ) ; sendMessage ( BeanMessageID . BT_SET_SCRATCH , sd ) ; }
Set a scratch bank data value with raw bytes .
10,294
public void setRadioConfig ( RadioConfig config , boolean save ) { sendMessage ( save ? BeanMessageID . BT_SET_CONFIG : BeanMessageID . BT_SET_CONFIG_NOSAVE , config ) ; }
Set the radio config .
10,295
public void sendSerialMessage ( byte [ ] value ) { Buffer buffer = new Buffer ( ) ; buffer . write ( value ) ; sendMessage ( BeanMessageID . SERIAL_DATA , buffer ) ; }
Send raw bytes to the Bean as a serial message .
10,296
public void setPin ( int pin , boolean active ) { Buffer buffer = new Buffer ( ) ; buffer . writeIntLe ( pin ) ; buffer . writeByte ( active ? 1 : 0 ) ; sendMessage ( BeanMessageID . BT_SET_PIN , buffer ) ; }
Set the Bean s security code .
10,297
public void sendSerialMessage ( String value ) { Buffer buffer = new Buffer ( ) ; try { buffer . write ( value . getBytes ( "UTF-8" ) ) ; sendMessage ( BeanMessageID . SERIAL_DATA , buffer ) ; } catch ( UnsupportedEncodingException e ) { throw new RuntimeException ( e ) ; } }
Send a UTF - 8 string to the Bean as a serial message .
10,298
public void readFirmwareVersion ( final Callback < String > callback ) { gattClient . getDeviceProfile ( ) . getFirmwareVersion ( new DeviceProfile . VersionCallback ( ) { public void onComplete ( String version ) { callback . onResult ( version ) ; } } ) ; }
Read the Bean hardware version
10,299
public void readHardwareVersion ( final Callback < String > callback ) { gattClient . getDeviceProfile ( ) . getHardwareVersion ( new DeviceProfile . VersionCallback ( ) { public void onComplete ( String version ) { callback . onResult ( version ) ; } } ) ; }
Read Bean firmware version