idx int64 0 41.2k | question stringlengths 74 4.21k | target stringlengths 5 888 |
|---|---|---|
20,800 | private boolean buildConfigured ( BuildImageConfiguration config , ValueProvider valueProvider , MavenProject project ) { if ( isStringValueNull ( valueProvider , config , FROM , ( ) -> config . getFrom ( ) ) ) { return true ; } if ( valueProvider . getMap ( FROM_EXT , config == null ? null : config . getFromExt ( ) ) != null ) { return true ; } if ( isStringValueNull ( valueProvider , config , DOCKER_FILE , ( ) -> config . getDockerFileRaw ( ) ) ) { return true ; } if ( isStringValueNull ( valueProvider , config , DOCKER_ARCHIVE , ( ) -> config . getDockerArchiveRaw ( ) ) ) { return true ; } if ( isStringValueNull ( valueProvider , config , CONTEXT_DIR , ( ) -> config . getContextDirRaw ( ) ) ) { return true ; } if ( isStringValueNull ( valueProvider , config , DOCKER_FILE_DIR , ( ) -> config . getDockerFileDirRaw ( ) ) ) { return true ; } return new File ( project . getBasedir ( ) , "Dockerfile" ) . exists ( ) ; } | Enable build config only when a . from . . dockerFile . or . dockerFileDir . is configured |
20,801 | private List < String > extractPortValues ( List < String > config , ValueProvider valueProvider ) { List < String > ret = new ArrayList < > ( ) ; List < String > ports = valueProvider . getList ( PORTS , config ) ; if ( ports == null ) { return null ; } List < String [ ] > parsedPorts = EnvUtil . splitOnLastColon ( ports ) ; for ( String [ ] port : parsedPorts ) { ret . add ( port [ 1 ] ) ; } return ret ; } | Extract only the values of the port mapping |
20,802 | private void processImageConfig ( ServiceHub hub , ImageConfiguration aImageConfig ) throws IOException , MojoExecutionException { BuildImageConfiguration buildConfig = aImageConfig . getBuildConfiguration ( ) ; if ( buildConfig != null ) { if ( buildConfig . skip ( ) ) { log . info ( "%s : Skipped building" , aImageConfig . getDescription ( ) ) ; } else { buildAndTag ( hub , aImageConfig ) ; } } } | Helper method to process an ImageConfiguration . |
20,803 | private Builder u ( String format , String ... args ) { return new Builder ( createUrl ( String . format ( format , ( Object [ ] ) encodeArgs ( args ) ) ) ) ; } | Entry point for builder |
20,804 | public String getSimpleName ( ) { String prefix = user + "/" ; return repository . startsWith ( prefix ) ? repository . substring ( prefix . length ( ) ) : repository ; } | Get the simple name of the image which is the repository sans the user parts . |
20,805 | private void doValidate ( ) { List < String > errors = new ArrayList < > ( ) ; String image = user != null ? repository . substring ( user . length ( ) + 1 ) : repository ; Object [ ] checks = new Object [ ] { "registry" , DOMAIN_REGEXP , registry , "image" , IMAGE_NAME_REGEXP , image , "user" , NAME_COMP_REGEXP , user , "tag" , TAG_REGEXP , tag , "digest" , DIGEST_REGEXP , digest } ; for ( int i = 0 ; i < checks . length ; i += 3 ) { String value = ( String ) checks [ i + 2 ] ; Pattern checkPattern = ( Pattern ) checks [ i + 1 ] ; if ( value != null && ! checkPattern . matcher ( value ) . matches ( ) ) { errors . add ( String . format ( "%s part '%s' doesn't match allowed pattern '%s'" , checks [ i ] , value , checkPattern . pattern ( ) ) ) ; } } if ( errors . size ( ) > 0 ) { StringBuilder buf = new StringBuilder ( ) ; buf . append ( String . format ( "Given Docker name '%s' is invalid:\n" , getFullName ( ) ) ) ; for ( String error : errors ) { buf . append ( String . format ( " * %s\n" , error ) ) ; } buf . append ( "See http://bit.ly/docker_image_fmt for more details" ) ; throw new IllegalArgumentException ( buf . toString ( ) ) ; } } | Validate parts and throw an IllegalArgumentException if a part is not valid |
20,806 | public static ImageArchiveManifestEntry findEntryByRepoTag ( String repoTag , ImageArchiveManifest manifest ) { if ( repoTag == null || manifest == null ) { return null ; } for ( ImageArchiveManifestEntry entry : manifest . getEntries ( ) ) { for ( String entryRepoTag : entry . getRepoTags ( ) ) { if ( repoTag . equals ( entryRepoTag ) ) { return entry ; } } } return null ; } | Search the manifest for an entry that has the repository and tag provided . |
20,807 | public static Map < String , ImageArchiveManifestEntry > mapEntriesById ( Iterable < ImageArchiveManifestEntry > entries ) { Map < String , ImageArchiveManifestEntry > mapped = new LinkedHashMap < > ( ) ; for ( ImageArchiveManifestEntry entry : entries ) { mapped . put ( entry . getId ( ) , entry ) ; } return mapped ; } | Build a map of entries by id from an iterable of entries . |
20,808 | private boolean hasBeenAllImagesStarted ( Queue < ImageConfiguration > imagesWaitingToStart , Queue < ImageConfiguration > imagesStarting ) { return imagesWaitingToStart . isEmpty ( ) && imagesStarting . isEmpty ( ) ; } | Check if we are done |
20,809 | private List < ImageConfiguration > getImagesWhoseDependenciesHasStarted ( Queue < ImageConfiguration > imagesRemaining , Set < String > containersStarted , Set < String > aliases ) { final List < ImageConfiguration > ret = new ArrayList < > ( ) ; for ( ImageConfiguration imageWaitingToStart : imagesRemaining ) { List < String > allDependencies = imageWaitingToStart . getDependencies ( ) ; List < String > aliasDependencies = filterOutNonAliases ( aliases , allDependencies ) ; if ( containersStarted . containsAll ( aliasDependencies ) ) { ret . add ( imageWaitingToStart ) ; } } return ret ; } | Pick out all images who can be started right now because all their dependencies has been started |
20,810 | private Queue < ImageConfiguration > prepareStart ( ServiceHub hub , QueryService queryService , RunService runService , Set < String > imageAliases ) throws DockerAccessException , MojoExecutionException { final Queue < ImageConfiguration > imagesWaitingToStart = new ArrayDeque < > ( ) ; for ( StartOrderResolver . Resolvable resolvable : runService . getImagesConfigsInOrder ( queryService , getResolvedImages ( ) ) ) { final ImageConfiguration imageConfig = ( ImageConfiguration ) resolvable ; RunImageConfiguration runConfig = imageConfig . getRunConfiguration ( ) ; RegistryService . RegistryConfig registryConfig = getRegistryConfig ( pullRegistry ) ; ImagePullManager pullManager = getImagePullManager ( determinePullPolicy ( runConfig ) , autoPull ) ; hub . getRegistryService ( ) . pullImageWithPolicy ( imageConfig . getName ( ) , pullManager , registryConfig , queryService . hasImage ( imageConfig . getName ( ) ) ) ; NetworkConfig config = runConfig . getNetworkingConfig ( ) ; List < String > bindMounts = extractBindMounts ( runConfig . getVolumeConfiguration ( ) ) ; List < VolumeConfiguration > volumes = getVolumes ( ) ; if ( ! bindMounts . isEmpty ( ) && volumes != null ) { runService . createVolumesAsPerVolumeBinds ( hub , bindMounts , volumes ) ; } if ( autoCreateCustomNetworks && config . isCustomNetwork ( ) ) { runService . createCustomNetworkIfNotExistant ( config . getCustomNetwork ( ) ) ; } imagesWaitingToStart . add ( imageConfig ) ; updateAliasesSet ( imageAliases , imageConfig . getAlias ( ) ) ; } return imagesWaitingToStart ; } | to start in the correct order |
20,811 | public static List < String [ ] > extractLines ( File dockerFile , String keyword , FixedStringSearchInterpolator interpolator ) throws IOException { List < String [ ] > ret = new ArrayList < > ( ) ; try ( BufferedReader reader = new BufferedReader ( new FileReader ( dockerFile ) ) ) { String line ; while ( ( line = reader . readLine ( ) ) != null ) { String lineInterpolated = interpolator . interpolate ( line ) ; String [ ] lineParts = lineInterpolated . split ( "\\s+" ) ; if ( lineParts . length > 0 && lineParts [ 0 ] . equalsIgnoreCase ( keyword ) ) { ret . add ( lineParts ) ; } } } return ret ; } | Extract all lines containing the given keyword |
20,812 | public static String interpolate ( File dockerFile , FixedStringSearchInterpolator interpolator ) throws IOException { StringBuilder ret = new StringBuilder ( ) ; try ( BufferedReader reader = new BufferedReader ( new FileReader ( dockerFile ) ) ) { String line ; while ( ( line = reader . readLine ( ) ) != null ) { ret . append ( interpolator . interpolate ( line ) ) . append ( System . lineSeparator ( ) ) ; } } return ret . toString ( ) ; } | Interpolate a docker file with the given properties and filter |
20,813 | public static FixedStringSearchInterpolator createInterpolator ( MojoParameters params , String filter ) { String [ ] delimiters = extractDelimiters ( filter ) ; if ( delimiters == null ) { return FixedStringSearchInterpolator . create ( ) ; } DockerAssemblyConfigurationSource configSource = new DockerAssemblyConfigurationSource ( params , null , null ) ; return AssemblyInterpolator . fullInterpolator ( params . getProject ( ) , DefaultAssemblyReader . createProjectInterpolator ( params . getProject ( ) ) . withExpressionMarkers ( delimiters [ 0 ] , delimiters [ 1 ] ) , configSource ) . withExpressionMarkers ( delimiters [ 0 ] , delimiters [ 1 ] ) ; } | Create an interpolator for the given maven parameters and filter configuration . |
20,814 | public FieldScopeLogicMap < V > with ( FieldScopeLogic fieldScopeLogic , V value ) { ImmutableList . Builder < Entry < V > > newEntries = ImmutableList . builder ( ) ; newEntries . add ( Entry . of ( fieldScopeLogic , value ) ) ; newEntries . addAll ( entries ) ; return new FieldScopeLogicMap < > ( newEntries . build ( ) ) ; } | Returns a new immutable map that adds the given fields - > value mapping . |
20,815 | public static < V > FieldScopeLogicMap < V > defaultValue ( V value ) { return new FieldScopeLogicMap < > ( ImmutableList . of ( Entry . of ( FieldScopeLogic . all ( ) , value ) ) ) ; } | Returns a map which maps all fields to the given value by default . |
20,816 | static Function < Optional < Descriptor > , String > fieldNumbersFunction ( final String fmt , final Iterable < Integer > fieldNumbers ) { return new Function < Optional < Descriptor > , String > ( ) { public String apply ( Optional < Descriptor > optDescriptor ) { return resolveFieldNumbers ( optDescriptor , fmt , fieldNumbers ) ; } } ; } | Returns a function which translates integer field numbers into field names using the Descriptor if available . |
20,817 | static Function < Optional < Descriptor > , String > fieldScopeFunction ( final String fmt , final FieldScope fieldScope ) { return new Function < Optional < Descriptor > , String > ( ) { public String apply ( Optional < Descriptor > optDescriptor ) { return String . format ( fmt , fieldScope . usingCorrespondenceString ( optDescriptor ) ) ; } } ; } | Returns a function which formats the given string by getting the usingCorrespondenceString from the given FieldScope with the argument descriptor . |
20,818 | static Function < Optional < Descriptor > , String > concat ( final Function < ? super Optional < Descriptor > , String > function1 , final Function < ? super Optional < Descriptor > , String > function2 ) { return new Function < Optional < Descriptor > , String > ( ) { public String apply ( Optional < Descriptor > optDescriptor ) { return function1 . apply ( optDescriptor ) + function2 . apply ( optDescriptor ) ; } } ; } | Returns a function which concatenates the outputs of the two input functions . |
20,819 | static Optional < Descriptor > getSingleDescriptor ( Iterable < ? extends Message > messages ) { Optional < Descriptor > optDescriptor = Optional . absent ( ) ; for ( Message message : messages ) { if ( message != null ) { Descriptor descriptor = message . getDescriptorForType ( ) ; if ( ! optDescriptor . isPresent ( ) ) { optDescriptor = Optional . of ( descriptor ) ; } else if ( descriptor != optDescriptor . get ( ) ) { return Optional . absent ( ) ; } } } return optDescriptor ; } | Returns the singular descriptor used by all non - null messages in the list . |
20,820 | public Ordered containsExactly ( ) { return check ( ) . about ( iterableEntries ( ) ) . that ( actual ( ) . entries ( ) ) . containsExactly ( ) ; } | Fails if the multimap is not empty . |
20,821 | private static boolean advanceToFind ( Iterator < ? > iterator , Object value ) { while ( iterator . hasNext ( ) ) { if ( Objects . equal ( iterator . next ( ) , value ) ) { return true ; } } return false ; } | Advances the iterator until it either returns value or has no more elements . |
20,822 | public IterableSubject factKeys ( ) { if ( ! ( actual ( ) instanceof ErrorWithFacts ) ) { failWithActual ( simpleFact ( "expected a failure thrown by Truth's new failure API" ) ) ; return ignoreCheck ( ) . that ( ImmutableList . of ( ) ) ; } ErrorWithFacts error = ( ErrorWithFacts ) actual ( ) ; return check ( "factKeys()" ) . that ( getFactKeys ( error ) ) ; } | Returns a subject for the list of fact keys . |
20,823 | public MapWithProtoValuesFluentAssertion < M > usingFloatToleranceForFieldDescriptorsForValues ( float tolerance , FieldDescriptor firstFieldDescriptor , FieldDescriptor ... rest ) { return usingConfig ( config . usingFloatToleranceForFieldDescriptors ( tolerance , asList ( firstFieldDescriptor , rest ) ) ) ; } | Compares float fields with these explicitly specified fields using the provided absolute tolerance . |
20,824 | FieldScopeLogic ignoringFields ( Iterable < Integer > fieldNumbers ) { if ( isEmpty ( fieldNumbers ) ) { return this ; } return and ( this , new NegationFieldScopeLogic ( new FieldNumbersLogic ( fieldNumbers , true ) ) ) ; } | something else that doesn t tightly couple FieldScopeLogic to the ignore concept . |
20,825 | @ SuppressWarnings ( "GoodTime" ) public void containsAnyOf ( int first , int second , int ... rest ) { check ( ) . that ( actualList ) . containsAnyOf ( first , second , box ( rest ) ) ; } | Fails if the subject does not contain at least one of the given elements . |
20,826 | public void hasLength ( int expectedLength ) { checkArgument ( expectedLength >= 0 , "expectedLength(%s) must be >= 0" , expectedLength ) ; check ( "length()" ) . that ( actual ( ) . length ( ) ) . isEqualTo ( expectedLength ) ; } | Fails if the string does not have the given length . |
20,827 | public void contains ( CharSequence string ) { checkNotNull ( string ) ; if ( actual ( ) == null ) { failWithActual ( "expected a string that contains" , string ) ; } else if ( ! actual ( ) . contains ( string ) ) { failWithActual ( "expected to contain" , string ) ; } } | Fails if the string does not contain the given sequence . |
20,828 | public void startsWith ( String string ) { checkNotNull ( string ) ; if ( actual ( ) == null ) { failWithActual ( "expected a string that starts with" , string ) ; } else if ( ! actual ( ) . startsWith ( string ) ) { failWithActual ( "expected to start with" , string ) ; } } | Fails if the string does not start with the given string . |
20,829 | public void endsWith ( String string ) { checkNotNull ( string ) ; if ( actual ( ) == null ) { failWithActual ( "expected a string that ends with" , string ) ; } else if ( ! actual ( ) . endsWith ( string ) ) { failWithActual ( "expected to end with" , string ) ; } } | Fails if the string does not end with the given string . |
20,830 | @ GwtIncompatible ( "java.util.regex.Pattern" ) public void matches ( Pattern regex ) { if ( ! regex . matcher ( actual ( ) ) . matches ( ) ) { failWithActual ( "expected to match" , regex ) ; } } | Fails if the string does not match the given regex . |
20,831 | @ GwtIncompatible ( "java.util.regex.Pattern" ) public void containsMatch ( Pattern regex ) { if ( ! regex . matcher ( actual ( ) ) . find ( ) ) { failWithActual ( "expected to contain a match for" , regex ) ; } } | Fails if the string does not contain a match on the given regex . |
20,832 | @ GwtIncompatible ( "java.util.regex.Pattern" ) public void doesNotContainMatch ( Pattern regex ) { Matcher matcher = regex . matcher ( actual ( ) ) ; if ( matcher . find ( ) ) { failWithoutActual ( fact ( "expected not to contain a match for" , regex ) , fact ( "but contained" , matcher . group ( ) ) , fact ( "full string" , actualCustomStringRepresentationForPackageMembersToCall ( ) ) ) ; } } | Fails if the string contains a match on the given regex . |
20,833 | static boolean containsMatch ( String actual , String regex ) { return Pattern . compile ( regex ) . matcher ( actual ) . find ( ) ; } | Determines if the given subject contains a match for the given regex . |
20,834 | public Correspondence < A , E > formattingDiffsUsing ( DiffFormatter < ? super A , ? super E > formatter ) { return new FormattingDiffs < > ( this , formatter ) ; } | Returns a new correspondence which is like this one except that the given formatter may be used to format the difference between a pair of elements that do not correspond . |
20,835 | static ImmutableList < Fact > formatExpectedAndActual ( String expected , String actual ) { ImmutableList < Fact > result ; result = Platform . makeDiff ( expected , actual ) ; if ( result != null ) { return result ; } result = removeCommonPrefixAndSuffix ( expected , actual ) ; if ( result != null ) { return result ; } return ImmutableList . of ( fact ( "expected" , expected ) , fact ( "but was" , actual ) ) ; } | Returns one or more facts describing the difference between the given expected and actual values . |
20,836 | private static boolean validSurrogatePairAt ( CharSequence string , int index ) { return index >= 0 && index <= ( string . length ( ) - 2 ) && isHighSurrogate ( string . charAt ( index ) ) && isLowSurrogate ( string . charAt ( index + 1 ) ) ; } | From c . g . c . base . Strings . |
20,837 | static boolean isInstanceOfType ( Object instance , Class < ? > clazz ) { if ( clazz . isInterface ( ) ) { throw new UnsupportedOperationException ( "Under GWT, we can't determine whether an object is an instance of an interface Class" ) ; } for ( Class < ? > current = instance . getClass ( ) ; current != null ; current = current . getSuperclass ( ) ) { if ( current . equals ( clazz ) ) { return true ; } } return false ; } | Returns true if the instance is assignable to the type Clazz . |
20,838 | DiffResult diffMessages ( Message actual , Message expected ) { checkNotNull ( actual ) ; checkNotNull ( expected ) ; checkArgument ( actual . getDescriptorForType ( ) == expected . getDescriptorForType ( ) , "The actual [%s] and expected [%s] message descriptors do not match." , actual . getDescriptorForType ( ) , expected . getDescriptorForType ( ) ) ; return diffMessages ( actual , expected , rootConfig ) ; } | Compare the two non - null messages and return a detailed comparison report . |
20,839 | private RepeatedField . PairResult findMatchingPairResult ( Deque < Integer > actualIndices , List < ? > actualValues , int expectedIndex , Object expectedValue , boolean excludeNonRecursive , FieldDescriptor fieldDescriptor , FluentEqualityConfig config ) { Iterator < Integer > actualIndexIter = actualIndices . iterator ( ) ; while ( actualIndexIter . hasNext ( ) ) { int actualIndex = actualIndexIter . next ( ) ; RepeatedField . PairResult pairResult = compareRepeatedFieldElementPair ( actualValues . get ( actualIndex ) , expectedValue , excludeNonRecursive , fieldDescriptor , actualIndex , expectedIndex , config ) ; if ( pairResult . isMatched ( ) ) { actualIndexIter . remove ( ) ; return pairResult ; } } return null ; } | If there is no match returns null . |
20,840 | static < T > Iterable < T > annotateEmptyStrings ( Iterable < T > items ) { if ( Iterables . contains ( items , "" ) ) { List < T > annotatedItems = Lists . newArrayList ( ) ; for ( T item : items ) { if ( Objects . equal ( item , "" ) ) { @ SuppressWarnings ( "unchecked" ) T newItem = ( T ) HUMAN_UNDERSTANDABLE_EMPTY_STRING ; annotatedItems . add ( newItem ) ; } else { annotatedItems . add ( item ) ; } } return annotatedItems ; } else { return items ; } } | Returns an iterable with all empty strings replaced by a non - empty human understandable indicator for an empty string . |
20,841 | private ImmutableList < Fact > description ( ) { String description = null ; boolean descriptionWasDerived = false ; for ( Step step : steps ) { if ( step . isCheckCall ( ) ) { checkState ( description != null ) ; if ( step . descriptionUpdate == null ) { description = null ; descriptionWasDerived = false ; } else { description = verifyNotNull ( step . descriptionUpdate . apply ( description ) ) ; descriptionWasDerived = true ; } continue ; } if ( description == null ) { description = firstNonNull ( step . subject . internalCustomName ( ) , step . subject . typeDescription ( ) ) ; } } return descriptionWasDerived ? ImmutableList . of ( fact ( "value of" , description ) ) : ImmutableList . < Fact > of ( ) ; } | Returns a description of how the final actual value was derived from earlier actual values in the chain if the chain ends with at least one derivation that we have a name for . |
20,842 | public Ordered containsExactlyEntriesIn ( Map < ? , ? > expectedMap ) { if ( expectedMap . isEmpty ( ) ) { if ( actual ( ) . isEmpty ( ) ) { return IN_ORDER ; } else { isEmpty ( ) ; return ALREADY_FAILED ; } } boolean containsAnyOrder = containsEntriesInAnyOrder ( expectedMap , "contains exactly" , false ) ; if ( containsAnyOrder ) { return new MapInOrder ( expectedMap , "contains exactly these entries in order" ) ; } else { return ALREADY_FAILED ; } } | Fails if the map does not contain exactly the given set of entries in the given map . |
20,843 | public Ordered containsAtLeastEntriesIn ( Map < ? , ? > expectedMap ) { if ( expectedMap . isEmpty ( ) ) { return IN_ORDER ; } boolean containsAnyOrder = containsEntriesInAnyOrder ( expectedMap , "contains at least" , true ) ; if ( containsAnyOrder ) { return new MapInOrder ( expectedMap , "contains at least these entries in order" ) ; } else { return ALREADY_FAILED ; } } | Fails if the map does not contain at least the given set of entries in the given map . |
20,844 | static String makeMessage ( ImmutableList < String > messages , ImmutableList < Fact > facts ) { int longestKeyLength = 0 ; boolean seenNewlineInValue = false ; for ( Fact fact : facts ) { if ( fact . value != null ) { longestKeyLength = max ( longestKeyLength , fact . key . length ( ) ) ; seenNewlineInValue |= fact . value . contains ( "\n" ) ; } } StringBuilder builder = new StringBuilder ( ) ; for ( String message : messages ) { builder . append ( message ) ; builder . append ( '\n' ) ; } for ( Fact fact : facts ) { if ( fact . value == null ) { builder . append ( fact . key ) ; } else if ( seenNewlineInValue ) { builder . append ( fact . key ) ; builder . append ( ":\n" ) ; builder . append ( indent ( fact . value ) ) ; } else { builder . append ( padEnd ( fact . key , longestKeyLength , ' ' ) ) ; builder . append ( ": " ) ; builder . append ( fact . value ) ; } builder . append ( '\n' ) ; } builder . setLength ( builder . length ( ) - 1 ) ; return builder . toString ( ) ; } | Formats the given messages and facts into a string for use as the message of a test failure . In particular this method horizontally aligns the beginning of fact values . |
20,845 | final String shortName ( ) { if ( fieldDescriptor ( ) . isPresent ( ) ) { return fieldDescriptor ( ) . get ( ) . isExtension ( ) ? "[" + fieldDescriptor ( ) . get ( ) + "]" : fieldDescriptor ( ) . get ( ) . getName ( ) ; } else { return String . valueOf ( unknownFieldDescriptor ( ) . get ( ) . fieldNumber ( ) ) ; } } | Returns a short human - readable version of this identifier . |
20,846 | public final void hasSize ( int expectedSize ) { checkArgument ( expectedSize >= 0 , "expectedSize(%s) must be >= 0" , expectedSize ) ; int actualSize = size ( actual ( ) ) ; check ( "size()" ) . that ( actualSize ) . isEqualTo ( expectedSize ) ; } | Fails if the subject does not have the given size . |
20,847 | public final void containsNoDuplicates ( ) { List < Entry < ? > > duplicates = newArrayList ( ) ; for ( Multiset . Entry < ? > entry : LinkedHashMultiset . create ( actual ( ) ) . entrySet ( ) ) { if ( entry . getCount ( ) > 1 ) { duplicates . add ( entry ) ; } } if ( ! duplicates . isEmpty ( ) ) { failWithoutActual ( simpleFact ( "expected not to contain duplicates" ) , fact ( "but contained" , duplicates ) , fullContents ( ) ) ; } } | Checks that the subject does not contain duplicate elements . |
20,848 | public final Ordered containsAtLeastElementsIn ( Iterable < ? > expectedIterable ) { List < ? > actual = Lists . newLinkedList ( actual ( ) ) ; final Collection < ? > expected = iterableToCollection ( expectedIterable ) ; List < Object > missing = newArrayList ( ) ; List < Object > actualNotInOrder = newArrayList ( ) ; boolean ordered = true ; for ( Object e : expected ) { int index = actual . indexOf ( e ) ; if ( index != - 1 ) { moveElements ( actual , actualNotInOrder , index ) ; actual . remove ( 0 ) ; } else { if ( actualNotInOrder . remove ( e ) ) { ordered = false ; } else { missing . add ( e ) ; } } } if ( ! missing . isEmpty ( ) ) { return failAtLeast ( expected , missing ) ; } return ordered ? IN_ORDER : new Ordered ( ) { public void inOrder ( ) { failWithActual ( simpleFact ( "required elements were all found, but order was wrong" ) , fact ( "expected order for required elements" , expected ) ) ; } } ; } | Checks that the actual iterable contains at least all of the expected elements or fails . If an element appears more than once in the expected elements then it must appear at least that number of times in the actual elements . |
20,849 | private static void moveElements ( List < ? > input , Collection < Object > output , int maxElements ) { for ( int i = 0 ; i < maxElements ; i ++ ) { output . add ( input . remove ( 0 ) ) ; } } | Removes at most the given number of available elements from the input list and adds them to the given output collection . |
20,850 | final boolean isAnyChildMatched ( ) { if ( isAnyChildMatched == null ) { isAnyChildMatched = false ; for ( RecursableDiffEntity entity : childEntities ( ) ) { if ( ( entity . isMatched ( ) && ! entity . isContentEmpty ( ) ) || entity . isAnyChildMatched ( ) ) { isAnyChildMatched = true ; break ; } } } return isAnyChildMatched ; } | Returns true if some child entity matched . |
20,851 | final boolean isAnyChildIgnored ( ) { if ( isAnyChildIgnored == null ) { isAnyChildIgnored = false ; for ( RecursableDiffEntity entity : childEntities ( ) ) { if ( ( entity . isIgnored ( ) && ! entity . isContentEmpty ( ) ) || entity . isAnyChildIgnored ( ) ) { isAnyChildIgnored = true ; break ; } } } return isAnyChildIgnored ; } | Returns true if some child entity was ignored . |
20,852 | private void addToStreak ( StackTraceElementWrapper stackTraceElementWrapper ) { if ( stackTraceElementWrapper . getStackFrameType ( ) != currentStreakType ) { endStreak ( ) ; currentStreakType = stackTraceElementWrapper . getStackFrameType ( ) ; currentStreakLength = 1 ; } else { currentStreakLength ++ ; } } | Either adds the given frame to the running streak or closes out the running streak and starts a new one . |
20,853 | private void endStreak ( ) { if ( currentStreakLength == 0 ) { return ; } if ( currentStreakLength == 1 ) { cleanedStackTrace . add ( lastStackFrameElementWrapper ) ; } else { cleanedStackTrace . add ( createStreakReplacementFrame ( currentStreakType , currentStreakLength ) ) ; } clearStreak ( ) ; } | Ends the current streak adding a summary frame to the result . Resets the streak counter . |
20,854 | public static void writeFile ( MapWriterConfiguration configuration , TileBasedDataProcessor dataProcessor ) throws IOException { EXECUTOR_SERVICE = Executors . newFixedThreadPool ( configuration . getThreads ( ) ) ; RandomAccessFile randomAccessFile = new RandomAccessFile ( configuration . getOutputFile ( ) , "rw" ) ; int amountOfZoomIntervals = dataProcessor . getZoomIntervalConfiguration ( ) . getNumberOfZoomIntervals ( ) ; ByteBuffer containerHeaderBuffer = ByteBuffer . allocate ( HEADER_BUFFER_SIZE ) ; int totalHeaderSize = writeHeaderBuffer ( configuration , dataProcessor , containerHeaderBuffer ) ; containerHeaderBuffer . reset ( ) ; final LoadingCache < TDWay , Geometry > jtsGeometryCache = CacheBuilder . newBuilder ( ) . maximumSize ( JTS_GEOMETRY_CACHE_SIZE ) . concurrencyLevel ( Runtime . getRuntime ( ) . availableProcessors ( ) * 2 ) . build ( new JTSGeometryCacheLoader ( dataProcessor ) ) ; long currentFileSize = totalHeaderSize ; for ( int i = 0 ; i < amountOfZoomIntervals ; i ++ ) { long subfileSize = writeSubfile ( currentFileSize , i , dataProcessor , jtsGeometryCache , randomAccessFile , configuration ) ; writeSubfileMetaDataToContainerHeader ( dataProcessor . getZoomIntervalConfiguration ( ) , i , currentFileSize , subfileSize , containerHeaderBuffer ) ; currentFileSize += subfileSize ; } randomAccessFile . seek ( 0 ) ; randomAccessFile . write ( containerHeaderBuffer . array ( ) , 0 , totalHeaderSize ) ; long fileSize = randomAccessFile . length ( ) ; randomAccessFile . seek ( OFFSET_FILE_SIZE ) ; randomAccessFile . writeLong ( fileSize ) ; randomAccessFile . close ( ) ; CacheStats stats = jtsGeometryCache . stats ( ) ; LOGGER . fine ( "Tag values stats:\n" + OSMUtils . logValueTypeCount ( ) ) ; LOGGER . info ( "JTS Geometry cache hit rate: " + stats . hitRate ( ) ) ; LOGGER . info ( "JTS Geometry total load time: " + stats . totalLoadTime ( ) / 1000 ) ; LOGGER . info ( "Finished writing file." ) ; } | Writes the map file according to the given configuration using the given data processor . |
20,855 | protected static Set < Tag > stringToTags ( String data ) { Set < Tag > tags = new HashSet < > ( ) ; String [ ] split = data . split ( "\r" ) ; for ( String s : split ) { if ( s . indexOf ( Tag . KEY_VALUE_SEPARATOR ) > - 1 ) { String [ ] keyValue = s . split ( String . valueOf ( Tag . KEY_VALUE_SEPARATOR ) ) ; if ( keyValue . length == 2 ) { tags . add ( new Tag ( keyValue [ 0 ] , keyValue [ 1 ] ) ) ; } } } return tags ; } | Convert tags string representation with \ r delimiter to collection . |
20,856 | protected static String tagsToString ( Set < Tag > tags ) { StringBuilder sb = new StringBuilder ( ) ; for ( Tag tag : tags ) { if ( sb . length ( ) > 0 ) { sb . append ( '\r' ) ; } sb . append ( tag . key ) . append ( Tag . KEY_VALUE_SEPARATOR ) . append ( tag . value ) ; } return sb . toString ( ) ; } | Convert tags collection to string representation with \ r delimiter . |
20,857 | private void storeData ( Job key , TileBitmap bitmap ) { OutputStream outputStream = null ; try { File file = getOutputFile ( key ) ; if ( file == null ) { return ; } outputStream = new FileOutputStream ( file ) ; bitmap . compress ( outputStream ) ; try { lock . writeLock ( ) . lock ( ) ; if ( this . lruCache . put ( key . getKey ( ) , file ) != null ) { LOGGER . warning ( "overwriting cached entry: " + key . getKey ( ) ) ; } } finally { lock . writeLock ( ) . unlock ( ) ; } } catch ( Exception e ) { LOGGER . log ( Level . SEVERE , "Disabling filesystem cache" , e ) ; this . destroy ( ) ; try { lock . writeLock ( ) . lock ( ) ; this . lruCache = new FileWorkingSetCache < String > ( 0 ) ; } finally { lock . writeLock ( ) . unlock ( ) ; } } finally { IOUtils . closeQuietly ( outputStream ) ; } } | stores the bitmap data on disk with filename key |
20,858 | public boolean onOptionsItemSelected ( MenuItem item ) { super . onOptionsItemSelected ( item ) ; switch ( item . getItemId ( ) ) { case 1234 : if ( clusterer != null ) { break ; } clusterer = new ClusterManager ( mapView , getMarkerBitmap ( ) , getZoomLevelMax ( ) , false ) ; Toast toast = Toast . makeText ( this , "" , Toast . LENGTH_LONG ) ; ClusterManager . setToast ( toast ) ; this . mapView . getModel ( ) . frameBufferModel . addObserver ( clusterer ) ; for ( int i = 0 ; i < geoItems . length ; i ++ ) { clusterer . addItem ( geoItems [ i ] ) ; } clusterer . redraw ( ) ; displayItems . setEnabled ( false ) ; displayMoreItems . setEnabled ( true ) ; hideItems . setEnabled ( true ) ; break ; case 5678 : setProgressBarIndeterminateVisibility ( true ) ; Handler myHandler = new Handler ( ) { public void handleMessage ( Message msg ) { switch ( msg . what ) { case 0 : addMarker ( ) ; break ; default : break ; } } } ; new ManyDummyContent ( myHandler ) ; item . setEnabled ( false ) ; break ; case 9012 : if ( clusterer != null ) { clusterer . destroyGeoClusterer ( ) ; this . mapView . getModel ( ) . frameBufferModel . removeObserver ( clusterer ) ; clusterer = null ; } displayItems . setEnabled ( true ) ; displayMoreItems . setEnabled ( false ) ; hideItems . setEnabled ( false ) ; break ; } return true ; } | onOptionsItemSelected handler since clustering need MapView to be created and visible this sample do clustering here . |
20,859 | private void updateTagData ( Map < Poi , Map < String , String > > pois , String key , String value ) { for ( Map . Entry < Poi , Map < String , String > > entry : pois . entrySet ( ) ) { Poi poi = entry . getKey ( ) ; String tmpValue = value ; Map < String , String > tagmap = entry . getValue ( ) ; if ( ! tagmap . keySet ( ) . contains ( "name" ) ) { continue ; } if ( tagmap . keySet ( ) . contains ( key ) ) { if ( ! key . equals ( "is_in" ) ) { continue ; } String prev = tagmap . get ( key ) ; if ( prev . contains ( "," ) || prev . contains ( ";" ) ) { continue ; } if ( tmpValue . contains ( "," ) || tmpValue . contains ( ";" ) ) { tmpValue = ( prev + "," + tmpValue ) ; } } tagmap . put ( key , tmpValue ) ; try { this . pStmtUpdateData . setLong ( 2 , poi . id ) ; this . pStmtUpdateData . setString ( 1 , writer . tagsToString ( tagmap ) ) ; this . pStmtUpdateData . addBatch ( ) ; batchCountRelation ++ ; if ( batchCountRelation % PoiWriter . BATCH_LIMIT == 0 ) { pStmtUpdateData . executeBatch ( ) ; pStmtUpdateData . clearBatch ( ) ; writer . conn . commit ( ) ; } } catch ( SQLException e ) { e . printStackTrace ( ) ; } } } | Updates the tags of a POI - List with key and value . |
20,860 | public static TDRelation fromRelation ( Relation relation , WayResolver resolver , List < String > preferredLanguages ) { if ( relation == null ) { return null ; } if ( relation . getMembers ( ) . isEmpty ( ) ) { return null ; } SpecialTagExtractionResult ster = OSMUtils . extractSpecialFields ( relation , preferredLanguages ) ; Map < Short , Object > knownWayTags = OSMUtils . extractKnownWayTags ( relation ) ; if ( ! knownRelationType ( ster . getType ( ) ) ) { return null ; } List < RelationMember > members = relation . getMembers ( ) ; List < TDWay > wayMembers = new ArrayList < > ( ) ; for ( RelationMember relationMember : members ) { if ( relationMember . getMemberType ( ) != EntityType . Way ) { continue ; } TDWay member = resolver . getWay ( relationMember . getMemberId ( ) ) ; if ( member == null ) { LOGGER . finest ( "relation is missing a member, rel-id: " + relation . getId ( ) + " member id: " + relationMember . getMemberId ( ) ) ; continue ; } wayMembers . add ( member ) ; } if ( wayMembers . isEmpty ( ) ) { LOGGER . finest ( "relation has no valid members: " + relation . getId ( ) ) ; return null ; } return new TDRelation ( relation . getId ( ) , ster . getLayer ( ) , ster . getName ( ) , ster . getHousenumber ( ) , ster . getRef ( ) , knownWayTags , wayMembers . toArray ( new TDWay [ wayMembers . size ( ) ] ) ) ; } | Creates a new TDRelation from an osmosis entity using the given WayResolver . |
20,861 | public boolean onTap ( LatLong tapLatLong , Point layerXY , Point tapXY ) { for ( int i = layers . size ( ) - 1 ; i >= 0 ; i -- ) { Layer layer = layers . get ( i ) ; if ( layer . onTap ( tapLatLong , layerXY , tapXY ) ) { return true ; } } return false ; } | GroupLayer does not have a position layerXY is null . |
20,862 | protected boolean isItemInViewport ( final GeoItem item ) { BoundingBox curBounds = getCurBounds ( ) ; return curBounds != null && curBounds . contains ( item . getLatLong ( ) ) ; } | check if the item is within current viewport . |
20,863 | protected synchronized BoundingBox getCurBounds ( ) { if ( currBoundingBox == null ) { if ( mapView == null ) { throw new NullPointerException ( "mapView == null" ) ; } if ( mapView . getWidth ( ) <= 0 || mapView . getHeight ( ) <= 0 ) { throw new IllegalArgumentException ( " mapView.getWidth() <= 0 " + "|| mapView.getHeight() <= 0 " + mapView . getWidth ( ) + " || " + mapView . getHeight ( ) ) ; } LatLong nw_ = mapView . getMapViewProjection ( ) . fromPixels ( 0 , 0 ) ; LatLong se_ = mapView . getMapViewProjection ( ) . fromPixels ( mapView . getWidth ( ) , mapView . getHeight ( ) ) ; if ( nw_ != null && se_ != null ) { if ( se_ . latitude > nw_ . latitude ) { currBoundingBox = new BoundingBox ( nw_ . latitude , se_ . longitude , se_ . latitude , nw_ . longitude ) ; } else { currBoundingBox = new BoundingBox ( se_ . latitude , nw_ . longitude , nw_ . latitude , se_ . longitude ) ; } } } return currBoundingBox ; } | get the current BoundingBox of the viewport |
20,864 | private void addLeftItems ( ) { if ( leftItems . size ( ) == 0 ) { return ; } ArrayList < T > currentLeftItems = new ArrayList < T > ( ) ; currentLeftItems . addAll ( leftItems ) ; synchronized ( leftItems ) { leftItems . clear ( ) ; } for ( T currentLeftItem : currentLeftItems ) { addItem ( currentLeftItem ) ; } } | add items that were not clustered in last isClustering . |
20,865 | private synchronized void resetViewport ( boolean isMoving ) { isClustering = true ; clusterTask = new ClusterTask ( ) ; clusterTask . execute ( new Boolean [ ] { isMoving } ) ; } | reset current viewport re - cluster the items when zoom has changed else add not clustered items . |
20,866 | private void commit ( ) throws SQLException { LOGGER . info ( "Committing..." ) ; this . progressManager . setMessage ( "Committing..." ) ; this . pStmtIndex . executeBatch ( ) ; this . pStmtData . executeBatch ( ) ; this . pStmtCatMap . executeBatch ( ) ; if ( this . configuration . isGeoTags ( ) ) { this . geoTagger . commit ( ) ; } this . conn . commit ( ) ; } | Commit changes . |
20,867 | public void complete ( ) { if ( this . configuration . isGeoTags ( ) ) { this . geoTagger . processBoundaries ( ) ; } NumberFormat nfMegabyte = NumberFormat . getInstance ( ) ; nfMegabyte . setMaximumFractionDigits ( 2 ) ; try { commit ( ) ; if ( this . configuration . isFilterCategories ( ) ) { filterCategories ( ) ; } writeMetadata ( ) ; this . conn . close ( ) ; postProcess ( ) ; } catch ( SQLException e ) { e . printStackTrace ( ) ; } LOGGER . info ( "Added " + nfCounts . format ( this . poiAdded ) + " POIs." ) ; this . progressManager . setMessage ( "Done." ) ; LOGGER . info ( "Estimated memory consumption: " + nfMegabyte . format ( + ( ( Runtime . getRuntime ( ) . totalMemory ( ) - Runtime . getRuntime ( ) . freeMemory ( ) ) / Math . pow ( 1024 , 2 ) ) ) + "MB" ) ; } | Complete task . |
20,868 | private void filterCategories ( ) throws SQLException { LOGGER . info ( "Filtering categories..." ) ; PreparedStatement pStmtChildren = this . conn . prepareStatement ( "SELECT COUNT(*) FROM poi_categories WHERE parent = ?;" ) ; PreparedStatement pStmtPoi = this . conn . prepareStatement ( "SELECT COUNT(*) FROM poi_category_map WHERE category = ?;" ) ; PreparedStatement pStmtDel = this . conn . prepareStatement ( "DELETE FROM poi_categories WHERE id = ?;" ) ; Statement stmt = this . conn . createStatement ( ) ; ResultSet rs = stmt . executeQuery ( "SELECT id FROM poi_categories ORDER BY id;" ) ; while ( rs . next ( ) ) { int id = rs . getInt ( 1 ) ; pStmtChildren . setInt ( 1 , id ) ; ResultSet rsChildren = pStmtChildren . executeQuery ( ) ; if ( rsChildren . next ( ) ) { long nChildren = rsChildren . getLong ( 1 ) ; if ( nChildren == 0 ) { pStmtPoi . setInt ( 1 , id ) ; ResultSet rsPoi = pStmtPoi . executeQuery ( ) ; if ( rsPoi . next ( ) ) { long nPoi = rsPoi . getLong ( 1 ) ; if ( nPoi == 0 ) { pStmtDel . setInt ( 1 , id ) ; pStmtDel . executeUpdate ( ) ; } } } } } } | Filter categories i . e . without POIs and children . |
20,869 | List < Long > findWayNodesByWayID ( long id ) { try { this . pStmtWayNodesR . setLong ( 1 , id ) ; ResultSet rs = this . pStmtWayNodesR . executeQuery ( ) ; Map < Integer , Long > nodeList = new TreeMap < > ( ) ; while ( rs . next ( ) ) { Long nodeID = rs . getLong ( 1 ) ; Integer pos = rs . getInt ( 2 ) ; nodeList . put ( pos , nodeID ) ; } rs . close ( ) ; return new ArrayList < > ( nodeList . values ( ) ) ; } catch ( SQLException e ) { e . printStackTrace ( ) ; } return null ; } | Find way nodes by its ID . |
20,870 | String getTagValue ( Collection < Tag > tags , String key ) { for ( Tag tag : tags ) { if ( tag . getKey ( ) . toLowerCase ( Locale . ENGLISH ) . equals ( key . toLowerCase ( Locale . ENGLISH ) ) ) { return tag . getValue ( ) ; } } return null ; } | Returns value of given tag in a set of tags . |
20,871 | private void postProcess ( ) throws SQLException { LOGGER . info ( "Post-processing..." ) ; this . conn = DriverManager . getConnection ( "jdbc:sqlite:" + this . configuration . getOutputFile ( ) . getAbsolutePath ( ) ) ; this . conn . createStatement ( ) . execute ( DbConstants . DROP_NODES_STATEMENT ) ; this . conn . createStatement ( ) . execute ( DbConstants . DROP_WAYNODES_STATEMENT ) ; this . conn . close ( ) ; this . conn = DriverManager . getConnection ( "jdbc:sqlite:" + this . configuration . getOutputFile ( ) . getAbsolutePath ( ) ) ; this . conn . createStatement ( ) . execute ( "VACUUM;" ) ; this . conn . close ( ) ; } | Post - process . |
20,872 | private void prepareDatabase ( ) throws ClassNotFoundException , SQLException , UnknownPoiCategoryException { Class . forName ( "org.sqlite.JDBC" ) ; this . conn = DriverManager . getConnection ( "jdbc:sqlite:" + this . configuration . getOutputFile ( ) . getAbsolutePath ( ) ) ; this . conn . setAutoCommit ( false ) ; Statement stmt = this . conn . createStatement ( ) ; stmt . execute ( DbConstants . DROP_WAYNODES_STATEMENT ) ; stmt . execute ( DbConstants . DROP_NODES_STATEMENT ) ; stmt . execute ( DbConstants . DROP_METADATA_STATEMENT ) ; stmt . execute ( DbConstants . DROP_INDEX_STATEMENT ) ; stmt . execute ( DbConstants . DROP_CATEGORY_MAP_STATEMENT ) ; stmt . execute ( DbConstants . DROP_DATA_STATEMENT ) ; stmt . execute ( DbConstants . DROP_CATEGORIES_STATEMENT ) ; stmt . execute ( DbConstants . CREATE_CATEGORIES_STATEMENT ) ; stmt . execute ( DbConstants . CREATE_DATA_STATEMENT ) ; stmt . execute ( DbConstants . CREATE_CATEGORY_MAP_STATEMENT ) ; stmt . execute ( DbConstants . CREATE_INDEX_STATEMENT ) ; stmt . execute ( DbConstants . CREATE_METADATA_STATEMENT ) ; stmt . execute ( DbConstants . CREATE_NODES_STATEMENT ) ; stmt . execute ( DbConstants . CREATE_WAYNODES_STATEMENT ) ; this . pStmtCatMap = this . conn . prepareStatement ( DbConstants . INSERT_CATEGORY_MAP_STATEMENT ) ; this . pStmtData = this . conn . prepareStatement ( DbConstants . INSERT_DATA_STATEMENT ) ; this . pStmtIndex = this . conn . prepareStatement ( DbConstants . INSERT_INDEX_STATEMENT ) ; this . pStmtNodesC = this . conn . prepareStatement ( DbConstants . INSERT_NODES_STATEMENT ) ; this . pStmtNodesR = this . conn . prepareStatement ( DbConstants . FIND_NODES_STATEMENT ) ; this . pStmtWayNodesR = this . conn . prepareStatement ( DbConstants . FIND_WAYNODES_BY_ID_STATEMENT ) ; PreparedStatement pStmt = this . conn . prepareStatement ( DbConstants . INSERT_CATEGORIES_STATEMENT ) ; PoiCategory root = this . categoryManager . getRootCategory ( ) ; pStmt . setLong ( 1 , root . getID ( ) ) ; pStmt . setString ( 2 , root . getTitle ( ) ) ; pStmt . setNull ( 3 , 0 ) ; pStmt . addBatch ( ) ; Stack < PoiCategory > children = new Stack < > ( ) ; children . push ( root ) ; while ( ! children . isEmpty ( ) ) { for ( PoiCategory c : children . pop ( ) . getChildren ( ) ) { pStmt . setLong ( 1 , c . getID ( ) ) ; pStmt . setString ( 2 , c . getTitle ( ) ) ; pStmt . setInt ( 3 , c . getParent ( ) . getID ( ) ) ; pStmt . addBatch ( ) ; children . push ( c ) ; } } pStmt . executeBatch ( ) ; this . conn . commit ( ) ; } | Prepare database . |
20,873 | public void process ( EntityContainer entityContainer ) { Entity entity = entityContainer . getEntity ( ) ; LOGGER . finest ( "Processing entity: " + entity . toString ( ) ) ; switch ( entity . getType ( ) ) { case Node : Node node = ( Node ) entity ; if ( this . nNodes == 0 ) { LOGGER . info ( "Processing nodes..." ) ; } if ( this . configuration . isProgressLogs ( ) ) { if ( nNodes % 100000 == 0 ) { System . out . print ( "Progress: Nodes " + nfCounts . format ( nNodes ) + " \r" ) ; } } ++ this . nNodes ; if ( this . configuration . isWays ( ) ) { writeNode ( node ) ; } processEntity ( node , node . getLatitude ( ) , node . getLongitude ( ) ) ; break ; case Way : if ( this . configuration . isWays ( ) ) { Way way = ( Way ) entity ; if ( this . nWays == 0 ) { LOGGER . info ( "Processing ways..." ) ; try { this . pStmtNodesC . executeBatch ( ) ; this . pStmtNodesC . clearBatch ( ) ; } catch ( SQLException e ) { e . printStackTrace ( ) ; } } if ( this . configuration . isProgressLogs ( ) ) { if ( nWays % 10000 == 0 ) { System . out . print ( "Progress: Ways " + nfCounts . format ( nWays ) + " \r" ) ; } } ++ this . nWays ; processWay ( way ) ; } break ; case Relation : if ( this . configuration . isGeoTags ( ) && this . configuration . isWays ( ) ) { Relation relation = ( Relation ) entity ; if ( this . nRelations == 0 ) { LOGGER . info ( "Processing relations..." ) ; this . geoTagger . commit ( ) ; } this . geoTagger . filterBoundaries ( relation ) ; if ( this . configuration . isProgressLogs ( ) ) { if ( nRelations % 10000 == 0 ) { System . out . print ( "Progress: Relations " + nfCounts . format ( nRelations ) + " \r" ) ; } } ++ this . nRelations ; } break ; default : break ; } entity = null ; } | Process task . |
20,874 | Map < String , String > stringToTags ( String tagsmapstring ) { String [ ] sb = tagsmapstring . split ( "\\r" ) ; Map < String , String > map = new HashMap < > ( ) ; for ( String key : sb ) { if ( key . contains ( "=" ) ) { String [ ] set = key . split ( "=" ) ; if ( set . length == 2 ) map . put ( set [ 0 ] , set [ 1 ] ) ; } } return map ; } | Convert string representation back to tags map . |
20,875 | String tagsToString ( Map < String , String > tagMap ) { StringBuilder sb = new StringBuilder ( ) ; for ( String key : tagMap . keySet ( ) ) { if ( key . equalsIgnoreCase ( "created_by" ) ) { continue ; } if ( sb . length ( ) > 0 ) { sb . append ( '\r' ) ; } sb . append ( key ) . append ( '=' ) . append ( tagMap . get ( key ) ) ; } return sb . toString ( ) ; } | Convert tags to a string representation using \ r delimiter . |
20,876 | private void writeMetadata ( ) throws SQLException { LOGGER . info ( "Writing metadata..." ) ; PreparedStatement pStmtMetadata = this . conn . prepareStatement ( DbConstants . INSERT_METADATA_STATEMENT ) ; pStmtMetadata . setString ( 1 , DbConstants . METADATA_BOUNDS ) ; BoundingBox bb = this . configuration . getBboxConfiguration ( ) ; if ( bb == null ) { Statement stmt = this . conn . createStatement ( ) ; ResultSet rs = stmt . executeQuery ( "SELECT MIN(minLat), MIN(minLon), MAX(maxLat), MAX(maxLon) FROM poi_index;" ) ; rs . next ( ) ; bb = new BoundingBox ( rs . getDouble ( 1 ) , rs . getDouble ( 2 ) , rs . getDouble ( 3 ) , rs . getDouble ( 4 ) ) ; } pStmtMetadata . setString ( 2 , bb . minLatitude + "," + bb . minLongitude + "," + bb . maxLatitude + "," + bb . maxLongitude ) ; pStmtMetadata . addBatch ( ) ; pStmtMetadata . setString ( 1 , DbConstants . METADATA_COMMENT ) ; if ( this . configuration . getComment ( ) != null ) { pStmtMetadata . setString ( 2 , this . configuration . getComment ( ) ) ; } else { pStmtMetadata . setNull ( 2 , Types . NULL ) ; } pStmtMetadata . addBatch ( ) ; pStmtMetadata . setString ( 1 , DbConstants . METADATA_DATE ) ; pStmtMetadata . setLong ( 2 , System . currentTimeMillis ( ) ) ; pStmtMetadata . addBatch ( ) ; pStmtMetadata . setString ( 1 , DbConstants . METADATA_LANGUAGE ) ; if ( ! this . configuration . isAllTags ( ) && this . configuration . getPreferredLanguage ( ) != null ) { pStmtMetadata . setString ( 2 , this . configuration . getPreferredLanguage ( ) ) ; } else { pStmtMetadata . setNull ( 2 , Types . NULL ) ; } pStmtMetadata . addBatch ( ) ; pStmtMetadata . setString ( 1 , DbConstants . METADATA_VERSION ) ; pStmtMetadata . setInt ( 2 , this . configuration . getFileSpecificationVersion ( ) ) ; pStmtMetadata . addBatch ( ) ; pStmtMetadata . setString ( 1 , DbConstants . METADATA_WAYS ) ; pStmtMetadata . setString ( 2 , Boolean . toString ( this . configuration . isWays ( ) ) ) ; pStmtMetadata . addBatch ( ) ; pStmtMetadata . setString ( 1 , DbConstants . METADATA_WRITER ) ; pStmtMetadata . setString ( 2 , this . configuration . getWriterVersion ( ) ) ; pStmtMetadata . addBatch ( ) ; pStmtMetadata . executeBatch ( ) ; this . conn . commit ( ) ; } | Write the metadata to the database . |
20,877 | private void writePOI ( long id , double latitude , double longitude , Map < String , String > poiData , Set < PoiCategory > categories ) { try { this . pStmtIndex . setLong ( 1 , id ) ; this . pStmtIndex . setDouble ( 2 , latitude ) ; this . pStmtIndex . setDouble ( 3 , latitude ) ; this . pStmtIndex . setDouble ( 4 , longitude ) ; this . pStmtIndex . setDouble ( 5 , longitude ) ; this . pStmtIndex . addBatch ( ) ; this . pStmtData . setLong ( 1 , id ) ; if ( this . configuration . isAllTags ( ) ) { this . pStmtData . setString ( 2 , tagsToString ( poiData ) ) ; } else { boolean foundPreferredLanguageName = false ; String name = null ; for ( String key : poiData . keySet ( ) ) { if ( "name" . equals ( key ) && ! foundPreferredLanguageName ) { name = poiData . get ( key ) ; } else if ( this . configuration . getPreferredLanguage ( ) != null && ! foundPreferredLanguageName ) { Matcher matcher = NAME_LANGUAGE_PATTERN . matcher ( key ) ; if ( matcher . matches ( ) ) { String language = matcher . group ( 3 ) ; if ( language . equalsIgnoreCase ( this . configuration . getPreferredLanguage ( ) ) ) { name = poiData . get ( key ) ; foundPreferredLanguageName = true ; } } } } if ( name != null ) { this . pStmtData . setString ( 2 , name ) ; } else { this . pStmtData . setNull ( 2 , Types . NULL ) ; } } this . pStmtData . addBatch ( ) ; this . pStmtCatMap . setLong ( 1 , id ) ; for ( PoiCategory category : categories ) { this . pStmtCatMap . setInt ( 2 , category . getID ( ) ) ; this . pStmtCatMap . addBatch ( ) ; } if ( this . poiAdded % BATCH_LIMIT == 0 ) { this . pStmtIndex . executeBatch ( ) ; this . pStmtData . executeBatch ( ) ; this . pStmtCatMap . executeBatch ( ) ; this . pStmtIndex . clearBatch ( ) ; this . pStmtData . clearBatch ( ) ; this . pStmtCatMap . clearBatch ( ) ; } } catch ( SQLException e ) { e . printStackTrace ( ) ; } } | Write a POI to the database . |
20,878 | public int compareTo ( Tag tag ) { int keyResult = this . key . compareTo ( tag . key ) ; if ( keyResult != 0 ) { return keyResult ; } return this . value . compareTo ( tag . value ) ; } | Compares this tag to the specified tag . The tag comparison is based on a comparison of key and value in that order . |
20,879 | public Rectangle enlarge ( double left , double top , double right , double bottom ) { return new Rectangle ( this . left - left , this . top - top , this . right + right , this . bottom + bottom ) ; } | Enlarges the Rectangle sides individually |
20,880 | protected void createLayers2 ( ) { this . mapView2 . getLayerManager ( ) . getLayers ( ) . add ( AndroidUtil . createTileRendererLayer ( this . tileCaches . get ( 1 ) , this . mapView2 . getModel ( ) . mapViewPosition , getMapFile2 ( ) , getRenderTheme2 ( ) , false , true , false ) ) ; } | creates the layers for the second map view . |
20,881 | private void startupDialog ( String prefs , int message , final Class clazz ) { final SharedPreferences preferences = getSharedPreferences ( prefs , Activity . MODE_PRIVATE ) ; final String accepted = "accepted" ; if ( ! preferences . getBoolean ( accepted , false ) ) { AlertDialog . Builder builder = new AlertDialog . Builder ( Samples . this ) ; builder . setTitle ( "Warning" ) ; builder . setMessage ( message ) ; builder . setPositiveButton ( R . string . startup_dontshowagain , new DialogInterface . OnClickListener ( ) { public void onClick ( DialogInterface dialog , int which ) { preferences . edit ( ) . putBoolean ( accepted , true ) . apply ( ) ; startActivity ( new Intent ( Samples . this , clazz ) ) ; } } ) ; builder . show ( ) ; } else { startActivity ( new Intent ( Samples . this , clazz ) ) ; } } | Warning startup dialog . |
20,882 | public int compareTo ( MapElementContainer other ) { if ( this . priority < other . priority ) { return - 1 ; } if ( this . priority > other . priority ) { return 1 ; } return 0 ; } | Compares elements according to their priority . |
20,883 | public boolean clashesWith ( MapElementContainer other ) { if ( Display . ALWAYS == this . display || Display . ALWAYS == other . display ) { return false ; } return this . getBoundaryAbsolute ( ) . intersects ( other . getBoundaryAbsolute ( ) ) ; } | Returns if MapElementContainers clash with each other |
20,884 | public static Map < Short , Object > extractKnownPOITags ( Entity entity ) { Map < Short , Object > tagMap = new HashMap < > ( ) ; OSMTagMapping mapping = OSMTagMapping . getInstance ( ) ; if ( entity . getTags ( ) != null ) { for ( Tag tag : entity . getTags ( ) ) { OSMTag poiTag = mapping . getPoiTag ( tag . getKey ( ) , tag . getValue ( ) ) ; if ( poiTag != null ) { String wildcard = poiTag . getValue ( ) ; tagMap . put ( poiTag . getId ( ) , getObjectFromWildcardAndValue ( wildcard , tag . getValue ( ) ) ) ; } } } return tagMap ; } | Extracts known POI tags and returns their ids . |
20,885 | public static Map < Short , Object > extractKnownWayTags ( Entity entity ) { Map < Short , Object > tagMap = new HashMap < > ( ) ; OSMTagMapping mapping = OSMTagMapping . getInstance ( ) ; if ( entity . getTags ( ) != null ) { for ( Tag tag : entity . getTags ( ) ) { OSMTag wayTag = mapping . getWayTag ( tag . getKey ( ) , tag . getValue ( ) ) ; if ( wayTag != null ) { String wildcard = wayTag . getValue ( ) ; tagMap . put ( wayTag . getId ( ) , getObjectFromWildcardAndValue ( wildcard , tag . getValue ( ) ) ) ; } } } return tagMap ; } | Extracts known way tags and returns their ids . |
20,886 | private TileBitmap createBackgroundBitmap ( RenderContext renderContext ) { TileBitmap bitmap = this . graphicFactory . createTileBitmap ( renderContext . rendererJob . tile . tileSize , renderContext . rendererJob . hasAlpha ) ; renderContext . canvasRasterer . setCanvasBitmap ( bitmap ) ; if ( ! renderContext . rendererJob . hasAlpha ) { renderContext . canvasRasterer . fill ( renderContext . renderTheme . getMapBackgroundOutside ( ) ) ; } return bitmap ; } | Draws a bitmap just with outside colour used for bitmaps outside of map area . |
20,887 | public static TileCache createExternalStorageTileCache ( Context c , String id , int firstLevelSize , int tileSize ) { return createExternalStorageTileCache ( c , id , firstLevelSize , tileSize , false ) ; } | Utility function to create a two - level tile cache along with its backends . This is the compatibility version that by default creates a non - persistent cache . |
20,888 | public static TileCache createTileCache ( Context c , String id , int tileSize , float screenRatio , double overdraw ) { return createTileCache ( c , id , tileSize , screenRatio , overdraw , false ) ; } | Utility function to create a two - level tile cache with the right size . When the cache is created we do not actually know the size of the mapview so the screenRatio is an approximation of the required size . This is the compatibility version that by default creates a non - persistent cache . |
20,889 | public static TileCache createTileCache ( Context c , String id , int tileSize , int width , int height , double overdraw ) { return createTileCache ( c , id , tileSize , width , height , overdraw , false ) ; } | Utility function to create a two - level tile cache with the right size using the size of the map view . This is the compatibility version that by default creates a non - persistent cache . |
20,890 | @ SuppressWarnings ( "deprecation" ) @ TargetApi ( Build . VERSION_CODES . JELLY_BEAN_MR2 ) public static long getAvailableCacheSlots ( String directory , int fileSize ) { StatFs statfs = new StatFs ( directory ) ; if ( Build . VERSION . SDK_INT >= Build . VERSION_CODES . JELLY_BEAN_MR2 ) { return statfs . getAvailableBytes ( ) / fileSize ; } int blocksPerFile = Math . max ( fileSize / statfs . getBlockSize ( ) , 1 ) ; return statfs . getAvailableBlocks ( ) / blocksPerFile ; } | Get the number of tiles that can be stored on the file system . |
20,891 | @ SuppressWarnings ( "deprecation" ) @ TargetApi ( Build . VERSION_CODES . HONEYCOMB_MR2 ) public static int getMinimumCacheSize ( Context c , int tileSize , double overdrawFactor , float screenRatio ) { WindowManager wm = ( WindowManager ) c . getSystemService ( Context . WINDOW_SERVICE ) ; Display display = wm . getDefaultDisplay ( ) ; int height ; int width ; if ( Build . VERSION . SDK_INT >= Build . VERSION_CODES . HONEYCOMB_MR2 ) { Point p = new Point ( ) ; display . getSize ( p ) ; height = p . y ; width = p . x ; } else { height = display . getHeight ( ) ; width = display . getWidth ( ) ; } Dimension dimension = FrameBufferController . calculateFrameBufferDimension ( new Dimension ( width , height ) , overdrawFactor ) ; return ( int ) Math . max ( 4 , screenRatio * ( 2 + ( dimension . height / tileSize ) ) * ( 2 + ( dimension . width / tileSize ) ) ) ; } | Compute the minimum cache size for a view . When the cache is created we do not actually know the size of the mapview so the screenRatio is an approximation of the required size . For the view size we use the frame buffer calculated dimension . |
20,892 | public static int getMinimumCacheSize ( int tileSize , double overdrawFactor , int width , int height ) { Dimension dimension = FrameBufferController . calculateFrameBufferDimension ( new Dimension ( width , height ) , overdrawFactor ) ; return Math . max ( 4 , ( 2 + ( dimension . height / tileSize ) ) * ( 2 + ( dimension . width / tileSize ) ) ) ; } | Compute the minimum cache size for a view using the size of the map view . For the view size we use the frame buffer calculated dimension . |
20,893 | public static void setMapScaleBar ( MapView mapView , DistanceUnitAdapter primaryDistanceUnitAdapter , DistanceUnitAdapter secondaryDistanceUnitAdapter ) { if ( null == primaryDistanceUnitAdapter && null == secondaryDistanceUnitAdapter ) { mapView . setMapScaleBar ( null ) ; } else { MapScaleBar scaleBar = mapView . getMapScaleBar ( ) ; if ( scaleBar == null ) { scaleBar = new DefaultMapScaleBar ( mapView . getModel ( ) . mapViewPosition , mapView . getModel ( ) . mapViewDimension , AndroidGraphicFactory . INSTANCE , mapView . getModel ( ) . displayModel ) ; mapView . setMapScaleBar ( scaleBar ) ; } if ( scaleBar instanceof DefaultMapScaleBar ) { if ( null != secondaryDistanceUnitAdapter ) { ( ( DefaultMapScaleBar ) scaleBar ) . setScaleBarMode ( DefaultMapScaleBar . ScaleBarMode . BOTH ) ; ( ( DefaultMapScaleBar ) scaleBar ) . setSecondaryDistanceUnitAdapter ( secondaryDistanceUnitAdapter ) ; } else { ( ( DefaultMapScaleBar ) scaleBar ) . setScaleBarMode ( DefaultMapScaleBar . ScaleBarMode . SINGLE ) ; } } scaleBar . setDistanceUnitAdapter ( primaryDistanceUnitAdapter ) ; } } | Sets the scale bar on a map view with implicit arguments . If no distance unit adapters are supplied there will be no scalebar with only a primary adapter supplied the mode will be single with two adapters supplied the mode will be dual . |
20,894 | private List < DummyItem > loadXmlFromNetwork ( String urlString ) throws IOException { String jString ; List < Entry > entries = null ; List < DummyItem > rtnArray = new ArrayList < DummyItem > ( ) ; BufferedReader streamReader = null ; try { streamReader = new BufferedReader ( downloadUrl ( urlString ) ) ; StringBuilder responseStrBuilder = new StringBuilder ( ) ; String inputStr ; while ( ( inputStr = streamReader . readLine ( ) ) != null ) responseStrBuilder . append ( inputStr ) ; jString = responseStrBuilder . toString ( ) ; if ( jString == null ) { Log . e ( SamplesApplication . TAG , "Nominatim Webpage: request failed for " + urlString ) ; return new ArrayList < DummyItem > ( 0 ) ; } JSONArray jPlaceIds = new JSONArray ( jString ) ; int n = jPlaceIds . length ( ) ; entries = new ArrayList < Entry > ( n ) ; for ( int i = 0 ; i < n ; i ++ ) { JSONObject jPlace = jPlaceIds . getJSONObject ( i ) ; Entry poi = new Entry ( jPlace . optLong ( "place_id" ) , jPlace . getString ( "osm_type" ) , jPlace . getString ( "osm_id" ) , jPlace . getString ( "boundingbox" ) , jPlace . getString ( "lat" ) , jPlace . getString ( "lon" ) , jPlace . getString ( "display_name" ) , jPlace . getString ( "class" ) , jPlace . getString ( "type" ) , jPlace . getString ( "importance" ) ) ; entries . add ( poi ) ; } } catch ( JSONException e ) { e . printStackTrace ( ) ; return null ; } finally { if ( streamReader != null ) { streamReader . close ( ) ; } } for ( Entry entry : entries ) { rtnArray . add ( new DummyItem ( entry . mOsm_id , entry . mDisplay_name . split ( "," ) [ 0 ] , new LatLong ( Double . parseDouble ( entry . mLat ) , Double . parseDouble ( entry . mLon ) ) , entry . mDisplay_name ) ) ; } return rtnArray ; } | Uploads XML from nominatim . openstreetmap . org parses it and create DummyItems from it |
20,895 | private InputStreamReader downloadUrl ( String urlString ) throws IOException { URL url = new URL ( urlString ) ; HttpURLConnection conn = ( HttpURLConnection ) url . openConnection ( ) ; conn . setReadTimeout ( 10000 ) ; conn . setConnectTimeout ( 15000 ) ; conn . setRequestMethod ( "GET" ) ; conn . setDoInput ( true ) ; conn . connect ( ) ; return new InputStreamReader ( conn . getInputStream ( ) , "UTF-8" ) ; } | an input stream . |
20,896 | public synchronized void setCapacity ( int capacity ) { BitmapLRUCache lruCacheNew = new BitmapLRUCache ( capacity ) ; lruCacheNew . putAll ( this . lruCache ) ; this . lruCache = lruCacheNew ; } | Sets the new size of this cache . If this cache already contains more items than the new capacity allows items are discarded based on the cache policy . |
20,897 | public static Tile getUpperLeft ( BoundingBox boundingBox , byte zoomLevel , int tileSize ) { int tileLeft = MercatorProjection . longitudeToTileX ( boundingBox . minLongitude , zoomLevel ) ; int tileTop = MercatorProjection . latitudeToTileY ( boundingBox . maxLatitude , zoomLevel ) ; return new Tile ( tileLeft , tileTop , zoomLevel , tileSize ) ; } | Upper left tile for an area . |
20,898 | public static Tile getLowerRight ( BoundingBox boundingBox , byte zoomLevel , int tileSize ) { int tileRight = MercatorProjection . longitudeToTileX ( boundingBox . maxLongitude , zoomLevel ) ; int tileBottom = MercatorProjection . latitudeToTileY ( boundingBox . minLatitude , zoomLevel ) ; return new Tile ( tileRight , tileBottom , zoomLevel , tileSize ) ; } | Lower right tile for an area . |
20,899 | public static List < MapElementContainer > collisionFreeOrdered ( List < MapElementContainer > input ) { Collections . sort ( input , Collections . reverseOrder ( ) ) ; List < MapElementContainer > output = new LinkedList < MapElementContainer > ( ) ; for ( MapElementContainer item : input ) { boolean hasSpace = true ; for ( MapElementContainer outputElement : output ) { if ( outputElement . clashesWith ( item ) ) { hasSpace = false ; break ; } } if ( hasSpace ) { output . add ( item ) ; } } return output ; } | Transforms a list of MapElements orders it and removes those elements that overlap . This operation is useful for an early elimination of elements in a list that will never be drawn because they overlap . |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.