idx
int64
0
41.2k
question
stringlengths
74
4.04k
target
stringlengths
7
750
28,600
public FilteredView createFilteredView ( StaticView view , String key , String description , FilterMode mode , String ... tags ) { assertThatTheViewIsNotNull ( view ) ; assertThatTheViewKeyIsSpecifiedAndUnique ( key ) ; FilteredView filteredView = new FilteredView ( view , key , description , mode , tags ) ; filteredViews . add ( filteredView ) ; return filteredView ; }
Creates a FilteredView on top of an existing static view .
28,601
View getViewWithKey ( String key ) { if ( key == null ) { throw new IllegalArgumentException ( "A key must be specified." ) ; } Set < View > views = new HashSet < > ( ) ; views . addAll ( systemLandscapeViews ) ; views . addAll ( systemContextViews ) ; views . addAll ( containerViews ) ; views . addAll ( componentViews ) ; views . addAll ( dynamicViews ) ; views . addAll ( deploymentViews ) ; return views . stream ( ) . filter ( v -> key . equals ( v . getKey ( ) ) ) . findFirst ( ) . orElse ( null ) ; }
Finds the view with the specified key or null if the view does not exist .
28,602
FilteredView getFilteredViewWithKey ( String key ) { if ( key == null ) { throw new IllegalArgumentException ( "A key must be specified." ) ; } return filteredViews . stream ( ) . filter ( v -> key . equals ( v . getKey ( ) ) ) . findFirst ( ) . orElse ( null ) ; }
Finds the filtered view with the specified key or null if the view does not exist .
28,603
public String getTags ( ) { Set < String > setOfTags = getTagsAsSet ( ) ; if ( setOfTags . isEmpty ( ) ) { return "" ; } StringBuilder buf = new StringBuilder ( ) ; for ( String tag : setOfTags ) { buf . append ( tag ) ; buf . append ( "," ) ; } String tagsAsString = buf . toString ( ) ; return tagsAsString . substring ( 0 , tagsAsString . length ( ) - 1 ) ; }
Gets the comma separated list of tags .
28,604
public void addProperty ( String name , String value ) { if ( name == null || name . trim ( ) . length ( ) == 0 ) { throw new IllegalArgumentException ( "A property name must be specified." ) ; } if ( value == null || value . trim ( ) . length ( ) == 0 ) { throw new IllegalArgumentException ( "A property value must be specified." ) ; } properties . put ( name , value ) ; }
Adds a name - value pair property to this element .
28,605
public Perspective addPerspective ( String name , String description ) { if ( StringUtils . isNullOrEmpty ( name ) ) { throw new IllegalArgumentException ( "A name must be specified." ) ; } if ( StringUtils . isNullOrEmpty ( description ) ) { throw new IllegalArgumentException ( "A description must be specified." ) ; } if ( perspectives . stream ( ) . filter ( p -> p . getName ( ) . equals ( name ) ) . count ( ) > 0 ) { throw new IllegalArgumentException ( "A perspective named \"" + name + "\" already exists." ) ; } Perspective perspective = new Perspective ( name , description ) ; perspectives . add ( perspective ) ; return perspective ; }
Adds a perspective to this model item .
28,606
public ContainerInstance add ( Container container , boolean replicateContainerRelationships ) { ContainerInstance containerInstance = getModel ( ) . addContainerInstance ( this , container , replicateContainerRelationships ) ; this . containerInstances . add ( containerInstance ) ; return containerInstance ; }
Adds a container instance to this deployment node optionally replicating all of the container - container relationships .
28,607
public DeploymentNode getDeploymentNodeWithName ( String name ) { if ( name == null || name . trim ( ) . length ( ) == 0 ) { throw new IllegalArgumentException ( "A name must be specified." ) ; } for ( DeploymentNode deploymentNode : getChildren ( ) ) { if ( deploymentNode . getName ( ) . equals ( name ) ) { return deploymentNode ; } } return null ; }
Gets the DeploymentNode with the specified name .
28,608
public void write ( Workspace workspace , Writer writer ) { if ( workspace != null && writer != null ) { for ( DynamicView view : workspace . getViews ( ) . getDynamicViews ( ) ) { write ( view , writer ) ; } } }
Writes the dynamic views in the given workspace as WebSequenceDiagrams definitions to the specified writer .
28,609
public void write ( Workspace workspace ) { StringWriter stringWriter = new StringWriter ( ) ; write ( workspace , stringWriter ) ; System . out . println ( stringWriter . toString ( ) ) ; }
Writes the dynamic views in the given workspace as WebSequenceDiagrams definitions to stdout .
28,610
public void setLogo ( String url ) { if ( url != null && url . trim ( ) . length ( ) > 0 ) { if ( Url . isUrl ( url ) || url . startsWith ( "data:image/" ) ) { this . logo = url . trim ( ) ; } else { throw new IllegalArgumentException ( url + " is not a valid URL." ) ; } } }
Sets the URL of an image representing a logo .
28,611
public HttpHealthCheck addHealthCheck ( String name , String url , int interval , long timeout ) { if ( name == null || name . trim ( ) . length ( ) == 0 ) { throw new IllegalArgumentException ( "The name must not be null or empty." ) ; } if ( url == null || url . trim ( ) . length ( ) == 0 ) { throw new IllegalArgumentException ( "The URL must not be null or empty." ) ; } if ( ! Url . isUrl ( url ) ) { throw new IllegalArgumentException ( url + " is not a valid URL." ) ; } if ( interval < 0 ) { throw new IllegalArgumentException ( "The polling interval must be zero or a positive integer." ) ; } if ( timeout < 0 ) { throw new IllegalArgumentException ( "The timeout must be zero or a positive integer." ) ; } HttpHealthCheck healthCheck = new HttpHealthCheck ( name , url , interval , timeout ) ; healthChecks . add ( healthCheck ) ; return healthCheck ; }
Adds a new health check .
28,612
public static Workspace loadWorkspaceFromJson ( File file ) throws Exception { if ( file == null ) { throw new IllegalArgumentException ( "The path to a JSON file must be specified." ) ; } else if ( ! file . exists ( ) ) { throw new IllegalArgumentException ( "The specified JSON file does not exist." ) ; } return new JsonReader ( ) . read ( new FileReader ( file ) ) ; }
Loads a workspace from a JSON definition saved as a file .
28,613
public static void saveWorkspaceToJson ( Workspace workspace , File file ) throws Exception { if ( workspace == null ) { throw new IllegalArgumentException ( "A workspace must be provided." ) ; } else if ( file == null ) { throw new IllegalArgumentException ( "The path to a JSON file must be specified." ) ; } OutputStreamWriter writer = new OutputStreamWriter ( new FileOutputStream ( file ) , StandardCharsets . UTF_8 ) ; new JsonWriter ( true ) . write ( workspace , writer ) ; writer . flush ( ) ; writer . close ( ) ; }
Saves a workspace to a JSON definition as a file .
28,614
public static void printWorkspaceAsJson ( Workspace workspace ) { if ( workspace == null ) { throw new IllegalArgumentException ( "A workspace must be provided." ) ; } try { System . out . println ( toJson ( workspace , true ) ) ; } catch ( Exception e ) { e . printStackTrace ( ) ; } }
Prints a workspace as JSON to stdout - useful for debugging purposes .
28,615
public static String toJson ( Workspace workspace , boolean indentOutput ) throws Exception { if ( workspace == null ) { throw new IllegalArgumentException ( "A workspace must be provided." ) ; } JsonWriter jsonWriter = new JsonWriter ( indentOutput ) ; StringWriter stringWriter = new StringWriter ( ) ; jsonWriter . write ( workspace , stringWriter ) ; stringWriter . flush ( ) ; stringWriter . close ( ) ; return stringWriter . toString ( ) ; }
Serializes the specified workspace to a JSON string .
28,616
public static Workspace fromJson ( String json ) throws Exception { if ( json == null || json . trim ( ) . length ( ) == 0 ) { throw new IllegalArgumentException ( "A JSON string must be provided." ) ; } StringReader stringReader = new StringReader ( json ) ; return new JsonReader ( ) . read ( stringReader ) ; }
Converts the specified JSON string to a Workspace instance .
28,617
public Set < Component > findComponents ( ) throws Exception { Set < Component > componentsFound = new HashSet < > ( ) ; for ( ComponentFinderStrategy componentFinderStrategy : componentFinderStrategies ) { componentFinderStrategy . beforeFindComponents ( ) ; } for ( ComponentFinderStrategy componentFinderStrategy : componentFinderStrategies ) { componentsFound . addAll ( componentFinderStrategy . findComponents ( ) ) ; } for ( ComponentFinderStrategy componentFinderStrategy : componentFinderStrategies ) { componentFinderStrategy . afterFindComponents ( ) ; } return componentsFound ; }
Find components using all of the configured component finder strategies in the order they were added .
28,618
public void exclude ( String ... regexes ) { if ( regexes != null ) { for ( String regex : regexes ) { this . exclusions . add ( Pattern . compile ( regex ) ) ; } } }
Adds one or more regexes to the set of regexes that define which types should be excluded during the component finding process .
28,619
public TypeRepository getTypeRepository ( ) { if ( typeRepository == null ) { typeRepository = new DefaultTypeRepository ( getPackageNames ( ) , getExclusions ( ) , getUrlClassLoader ( ) ) ; } return typeRepository ; }
Gets the type repository used to analyse java classes .
28,620
public void setAutomaticLayout ( boolean enable ) { if ( enable ) { this . setAutomaticLayout ( AutomaticLayout . RankDirection . TopBottom , 300 , 600 , 200 , false ) ; } else { this . automaticLayout = null ; } }
Enables the automatic layout for this view with some default settings .
28,621
public void setAutomaticLayout ( AutomaticLayout . RankDirection rankDirection , int rankSeparation , int nodeSeparation , int edgeSeparation , boolean vertices ) { this . automaticLayout = new AutomaticLayout ( rankDirection , rankSeparation , nodeSeparation , edgeSeparation , vertices ) ; }
Enables the automatic layout for this view with the specified settings .
28,622
public void remove ( Relationship relationship ) { if ( relationship != null ) { RelationshipView relationshipView = new RelationshipView ( relationship ) ; relationshipViews . remove ( relationshipView ) ; } }
Removes a relationship from this view .
28,623
public void removeRelationshipsNotConnectedToElement ( Element element ) { if ( element != null ) { getRelationships ( ) . stream ( ) . map ( RelationshipView :: getRelationship ) . filter ( r -> ! r . getSource ( ) . equals ( element ) && ! r . getDestination ( ) . equals ( element ) ) . forEach ( this :: remove ) ; } }
Removes relationships that are not connected to the specified element .
28,624
public void removeElementsWithNoRelationships ( ) { Set < RelationshipView > relationships = getRelationships ( ) ; Set < String > elementIds = new HashSet < > ( ) ; relationships . forEach ( rv -> elementIds . add ( rv . getRelationship ( ) . getSourceId ( ) ) ) ; relationships . forEach ( rv -> elementIds . add ( rv . getRelationship ( ) . getDestinationId ( ) ) ) ; for ( ElementView elementView : getElements ( ) ) { if ( ! elementIds . contains ( elementView . getId ( ) ) ) { removeElement ( elementView . getElement ( ) ) ; } } }
Removes all elements that have no relationships to other elements in this view .
28,625
public DeploymentNode getDeploymentNodeWithName ( String name , String environment ) { for ( DeploymentNode deploymentNode : getDeploymentNodes ( ) ) { if ( deploymentNode . getEnvironment ( ) . equals ( environment ) && deploymentNode . getName ( ) . equals ( name ) ) { return deploymentNode ; } } return null ; }
Gets the deployment node with the specified name and environment .
28,626
public Element getElementWithCanonicalName ( String canonicalName ) { if ( canonicalName == null || canonicalName . trim ( ) . length ( ) == 0 ) { throw new IllegalArgumentException ( "A canonical name must be specified." ) ; } if ( ! canonicalName . startsWith ( "/" ) ) { canonicalName = "/" + canonicalName ; } for ( Element element : getElements ( ) ) { if ( element . getCanonicalName ( ) . equals ( canonicalName ) ) { return element ; } } return null ; }
Gets the element with the specified canonical name .
28,627
public void modifyRelationship ( Relationship relationship , String description , String technology ) { if ( relationship == null ) { throw new IllegalArgumentException ( "A relationship must be specified." ) ; } Relationship newRelationship = new Relationship ( relationship . getSource ( ) , relationship . getDestination ( ) , description , technology , relationship . getInteractionStyle ( ) ) ; if ( ! relationship . getSource ( ) . has ( newRelationship ) ) { relationship . setDescription ( description ) ; relationship . setTechnology ( technology ) ; } else { throw new IllegalArgumentException ( "This relationship exists already: " + newRelationship ) ; } }
Provides a way for the description and technology to be modified on an existing relationship .
28,628
public void setUrl ( String url ) { if ( url != null && url . trim ( ) . length ( ) > 0 ) { if ( Url . isUrl ( url ) ) { this . url = url ; } else { throw new IllegalArgumentException ( url + " is not a valid URL." ) ; } } }
Sets the URL where more information about this element can be found .
28,629
public Section addSection ( String title , File ... files ) throws IOException { return add ( null , title , files ) ; }
Adds a custom section from one or more files that isn t related to any element in the model .
28,630
public Section addSection ( String title , Format format , String content ) { return add ( null , title , format , content ) ; }
Adds a custom section that isn t related to any element in the model .
28,631
public Image addImage ( File file ) throws IOException { String contentType = ImageUtils . getContentType ( file ) ; String base64Content = ImageUtils . getImageAsBase64 ( file ) ; Image image = new Image ( file . getName ( ) , contentType , base64Content ) ; documentation . addImage ( image ) ; return image ; }
Adds an image from the given file to the workspace .
28,632
public void addUser ( String username , Role role ) { if ( StringUtils . isNullOrEmpty ( username ) ) { throw new IllegalArgumentException ( "A username must be specified." ) ; } if ( role == null ) { throw new IllegalArgumentException ( "A role must be specified." ) ; } users . add ( new User ( username , role ) ) ; }
Adds a user with the specified username and role .
28,633
public void add ( Container container , boolean addRelationships ) { if ( container != null && ! container . equals ( getContainer ( ) ) ) { addElement ( container , addRelationships ) ; } }
Adds an individual container to this view .
28,634
public void add ( Component component , boolean addRelationships ) { if ( component != null ) { if ( ! component . getContainer ( ) . equals ( getContainer ( ) ) ) { throw new IllegalArgumentException ( "Only components belonging to " + container . getName ( ) + " can be added to this view." ) ; } addElement ( component , addRelationships ) ; } }
Adds an individual component to this view .
28,635
public void removeElementsThatAreUnreachableFrom ( Element element ) { if ( element != null ) { Set < Element > elementsToShow = new HashSet < > ( ) ; Set < Element > elementsVisited = new HashSet < > ( ) ; findElementsToShow ( element , element , elementsToShow , elementsVisited ) ; for ( ElementView elementView : getElements ( ) ) { if ( ! elementsToShow . contains ( elementView . getElement ( ) ) && canBeRemoved ( elementView . getElement ( ) ) ) { removeElement ( elementView . getElement ( ) ) ; } } } }
Removes all elements that cannot be reached by traversing the graph of relationships starting with the specified element .
28,636
public void addAnimation ( Element ... elements ) { if ( elements == null || elements . length == 0 ) { throw new IllegalArgumentException ( "One or more elements must be specified." ) ; } Set < String > elementIdsInPreviousAnimationSteps = new HashSet < > ( ) ; Set < Element > elementsInThisAnimationStep = new HashSet < > ( ) ; Set < Relationship > relationshipsInThisAnimationStep = new HashSet < > ( ) ; for ( Element element : elements ) { if ( isElementInView ( element ) ) { elementIdsInPreviousAnimationSteps . add ( element . getId ( ) ) ; elementsInThisAnimationStep . add ( element ) ; } } if ( elementsInThisAnimationStep . size ( ) == 0 ) { throw new IllegalArgumentException ( "None of the specified elements exist in this view." ) ; } for ( Animation animationStep : animations ) { elementIdsInPreviousAnimationSteps . addAll ( animationStep . getElements ( ) ) ; } for ( RelationshipView relationshipView : this . getRelationships ( ) ) { if ( ( elementsInThisAnimationStep . contains ( relationshipView . getRelationship ( ) . getSource ( ) ) && elementIdsInPreviousAnimationSteps . contains ( relationshipView . getRelationship ( ) . getDestination ( ) . getId ( ) ) ) || ( elementIdsInPreviousAnimationSteps . contains ( relationshipView . getRelationship ( ) . getSource ( ) . getId ( ) ) && elementsInThisAnimationStep . contains ( relationshipView . getRelationship ( ) . getDestination ( ) ) ) ) { relationshipsInThisAnimationStep . add ( relationshipView . getRelationship ( ) ) ; } } animations . add ( new Animation ( animations . size ( ) + 1 , elementsInThisAnimationStep , relationshipsInThisAnimationStep ) ) ; }
Adds an animation step with the specified elements .
28,637
public void write ( Workspace workspace , Writer writer ) throws WorkspaceWriterException { if ( workspace == null ) { throw new IllegalArgumentException ( "Workspace cannot be null." ) ; } if ( writer == null ) { throw new IllegalArgumentException ( "Writer cannot be null." ) ; } try { ObjectMapper objectMapper = new ObjectMapper ( ) ; if ( indentOutput ) { objectMapper . enable ( SerializationFeature . INDENT_OUTPUT ) ; } objectMapper . setSerializationInclusion ( JsonInclude . Include . NON_NULL ) ; objectMapper . setSerializationInclusion ( JsonInclude . Include . NON_EMPTY ) ; objectMapper . disable ( SerializationFeature . WRITE_DATES_AS_TIMESTAMPS ) ; objectMapper . setDateFormat ( new ISO8601DateFormat ( ) ) ; writer . write ( objectMapper . writeValueAsString ( workspace ) ) ; } catch ( IOException ioe ) { throw new WorkspaceWriterException ( "Could not write as JSON" , ioe ) ; } }
Writes a workspace definition as a JSON string to the specified Writer object .
28,638
public List < Section > addSections ( SoftwareSystem softwareSystem , File directory ) throws IOException { if ( softwareSystem == null ) { throw new IllegalArgumentException ( "A software system must be specified." ) ; } return add ( softwareSystem , directory ) ; }
Adds all files in the specified directory each in its own section related to a software system .
28,639
public static TypeVisibility getVisibility ( TypeRepository typeRepository , String typeName ) { try { Class < ? > type = typeRepository . loadClass ( typeName ) ; int modifiers = type . getModifiers ( ) ; if ( Modifier . isPrivate ( modifiers ) ) { return TypeVisibility . PRIVATE ; } else if ( Modifier . isPublic ( modifiers ) ) { return TypeVisibility . PUBLIC ; } else if ( Modifier . isProtected ( modifiers ) ) { return TypeVisibility . PROTECTED ; } else { return TypeVisibility . PACKAGE ; } } catch ( ClassNotFoundException e ) { log . warn ( "Visibility for type " + typeName + " could not be found." ) ; return null ; } }
Finds the visibility of a given type .
28,640
public static TypeCategory getCategory ( TypeRepository typeRepository , String typeName ) { try { Class < ? > type = typeRepository . loadClass ( typeName ) ; if ( type . isInterface ( ) ) { return TypeCategory . INTERFACE ; } else if ( type . isEnum ( ) ) { return TypeCategory . ENUM ; } else { if ( Modifier . isAbstract ( type . getModifiers ( ) ) ) { return TypeCategory . ABSTRACT_CLASS ; } else { return TypeCategory . CLASS ; } } } catch ( ClassNotFoundException e ) { log . warn ( "Category for type " + typeName + " could not be found." ) ; return null ; } }
Finds the category of a given type .
28,641
public static Set < Class < ? > > findTypesAnnotatedWith ( Class < ? extends Annotation > annotation , Set < Class < ? > > types ) { if ( annotation == null ) { throw new IllegalArgumentException ( "An annotation type must be specified." ) ; } return types . stream ( ) . filter ( c -> c . isAnnotationPresent ( annotation ) ) . collect ( Collectors . toSet ( ) ) ; }
Finds the set of types that are annotated with the specified annotation .
28,642
public static Class findFirstImplementationOfInterface ( Class interfaceType , Set < Class < ? > > types ) { if ( interfaceType == null ) { throw new IllegalArgumentException ( "An interface type must be provided." ) ; } else if ( ! interfaceType . isInterface ( ) ) { throw new IllegalArgumentException ( "The interface type must represent an interface." ) ; } if ( types == null ) { throw new IllegalArgumentException ( "The set of types to search through must be provided." ) ; } for ( Class < ? > type : types ) { boolean isInterface = type . isInterface ( ) ; boolean isAbstract = Modifier . isAbstract ( type . getModifiers ( ) ) ; boolean isAssignable = interfaceType . isAssignableFrom ( type ) ; if ( ! isInterface && ! isAbstract && isAssignable ) { return type ; } } return null ; }
Finds the first implementation of the given interface .
28,643
public void write ( Workspace workspace , Writer writer ) { workspace . getViews ( ) . getSystemContextViews ( ) . forEach ( v -> write ( v , null , writer ) ) ; workspace . getViews ( ) . getContainerViews ( ) . forEach ( v -> write ( v , v . getSoftwareSystem ( ) , writer ) ) ; workspace . getViews ( ) . getComponentViews ( ) . forEach ( v -> write ( v , v . getContainer ( ) , writer ) ) ; }
Writes the views in the given workspace as DOT notation to the specified Writer .
28,644
public void addHeader ( String name , String value ) { if ( name == null || name . trim ( ) . length ( ) == 0 ) { throw new IllegalArgumentException ( "The header name must not be null or empty." ) ; } if ( value == null ) { throw new IllegalArgumentException ( "The header value must not be null." ) ; } this . headers . put ( name , value ) ; }
Adds a HTTP header which will be sent with the HTTP request to the health check URL .
28,645
public static boolean isUrl ( String urlAsString ) { if ( urlAsString != null && urlAsString . trim ( ) . length ( ) > 0 ) { try { new URL ( urlAsString ) ; return true ; } catch ( MalformedURLException murle ) { return false ; } } return false ; }
Determines whether the supplied string is a valid URL .
28,646
public Set < Class < ? > > findReferencedTypes ( String typeName ) { Set < Class < ? > > referencedTypes = new HashSet < > ( ) ; if ( referencedTypesCache . containsKey ( typeName ) ) { return referencedTypesCache . get ( typeName ) ; } try { CtClass cc = classPool . get ( typeName ) ; for ( Object referencedType : cc . getRefClasses ( ) ) { String referencedTypeName = ( String ) referencedType ; if ( ! isExcluded ( referencedTypeName ) ) { try { referencedTypes . add ( loadClass ( referencedTypeName ) ) ; } catch ( Throwable t ) { log . debug ( "Could not find " + referencedTypeName + " ... ignoring." ) ; } } } referencedTypes . remove ( loadClass ( typeName ) ) ; } catch ( Exception e ) { log . debug ( "Error finding referenced types for " + typeName + " ... ignoring." ) ; referencedTypesCache . put ( typeName , new HashSet < > ( ) ) ; } referencedTypesCache . put ( typeName , referencedTypes ) ; return referencedTypes ; }
Finds the set of types referenced by the specified type .
28,647
public void write ( EncryptedWorkspace workspace , Writer writer ) throws WorkspaceWriterException { if ( workspace == null ) { throw new IllegalArgumentException ( "EncryptedWorkspace cannot be null." ) ; } if ( writer == null ) { throw new IllegalArgumentException ( "Writer cannot be null." ) ; } try { ObjectMapper objectMapper = new ObjectMapper ( ) ; if ( indentOutput ) { objectMapper . enable ( SerializationFeature . INDENT_OUTPUT ) ; } objectMapper . setSerializationInclusion ( JsonInclude . Include . NON_NULL ) ; objectMapper . setSerializationInclusion ( JsonInclude . Include . NON_EMPTY ) ; objectMapper . disable ( SerializationFeature . WRITE_DATES_AS_TIMESTAMPS ) ; objectMapper . setDateFormat ( new ISO8601DateFormat ( ) ) ; writer . write ( objectMapper . writeValueAsString ( workspace ) ) ; } catch ( Exception e ) { throw new WorkspaceWriterException ( "Could not write as JSON" , e ) ; } }
Writes an encrypted workspace definition as a JSON string to the specified Writer object .
28,648
private void checkElement ( Element elementToBeAdded ) { if ( ! ( elementToBeAdded instanceof Person ) && ! ( elementToBeAdded instanceof SoftwareSystem ) && ! ( elementToBeAdded instanceof Container ) && ! ( elementToBeAdded instanceof Component ) ) { throw new IllegalArgumentException ( "Only people, software systems, containers and components can be added to dynamic views." ) ; } if ( elementToBeAdded instanceof Person ) { return ; } if ( element instanceof SoftwareSystem ) { if ( elementToBeAdded . equals ( element ) ) { throw new IllegalArgumentException ( elementToBeAdded . getName ( ) + " is already the scope of this view and cannot be added to it." ) ; } if ( elementToBeAdded instanceof Container && ! elementToBeAdded . getParent ( ) . equals ( element ) ) { throw new IllegalArgumentException ( "Only containers that reside inside " + element . getName ( ) + " can be added to this view." ) ; } if ( elementToBeAdded instanceof Component ) { throw new IllegalArgumentException ( "Components can't be added to a dynamic view when the scope is a software system." ) ; } } if ( element instanceof Container ) { if ( elementToBeAdded . equals ( element ) || elementToBeAdded . equals ( element . getParent ( ) ) ) { throw new IllegalArgumentException ( elementToBeAdded . getName ( ) + " is already the scope of this view and cannot be added to it." ) ; } if ( elementToBeAdded instanceof Container && ! elementToBeAdded . getParent ( ) . equals ( element . getParent ( ) ) ) { throw new IllegalArgumentException ( "Only containers that reside inside " + element . getParent ( ) . getName ( ) + " can be added to this view." ) ; } if ( elementToBeAdded instanceof Component && ! elementToBeAdded . getParent ( ) . equals ( element ) ) { throw new IllegalArgumentException ( "Only components that reside inside " + element . getName ( ) + " can be added to this view." ) ; } } if ( element == null ) { if ( ! ( elementToBeAdded instanceof SoftwareSystem ) ) { throw new IllegalArgumentException ( "Only people and software systems can be added to this dynamic view." ) ; } } }
This checks that only appropriate elements can be added to the view .
28,649
public int compare ( String file0 , String file1 ) { Matcher m0 = pattern . matcher ( file0 ) ; Matcher m1 = pattern . matcher ( file1 ) ; if ( ! m0 . matches ( ) ) { Log . w ( TAG , "could not parse upgrade script file: " + file0 ) ; throw new SQLiteAssetException ( "Invalid upgrade script file" ) ; } if ( ! m1 . matches ( ) ) { Log . w ( TAG , "could not parse upgrade script file: " + file1 ) ; throw new SQLiteAssetException ( "Invalid upgrade script file" ) ; } int v0_from = Integer . valueOf ( m0 . group ( 1 ) ) ; int v1_from = Integer . valueOf ( m1 . group ( 1 ) ) ; int v0_to = Integer . valueOf ( m0 . group ( 2 ) ) ; int v1_to = Integer . valueOf ( m1 . group ( 2 ) ) ; if ( v0_from == v1_from ) { if ( v0_to == v1_to ) { return 0 ; } return v0_to < v1_to ? - 1 : 1 ; } return v0_from < v1_from ? - 1 : 1 ; }
Compares the two specified upgrade script strings to determine their relative ordering considering their two version numbers . Assumes all database names used are the same as this function only compares the two version numbers .
28,650
private void init ( final Context context , final AttributeSet attrs ) { if ( isInEditMode ( ) ) return ; final TypedArray typedArray = context . obtainStyledAttributes ( attrs , R . styleable . RippleView ) ; rippleColor = typedArray . getColor ( R . styleable . RippleView_rv_color , getResources ( ) . getColor ( R . color . rippelColor ) ) ; rippleType = typedArray . getInt ( R . styleable . RippleView_rv_type , 0 ) ; hasToZoom = typedArray . getBoolean ( R . styleable . RippleView_rv_zoom , false ) ; isCentered = typedArray . getBoolean ( R . styleable . RippleView_rv_centered , false ) ; rippleDuration = typedArray . getInteger ( R . styleable . RippleView_rv_rippleDuration , rippleDuration ) ; frameRate = typedArray . getInteger ( R . styleable . RippleView_rv_framerate , frameRate ) ; rippleAlpha = typedArray . getInteger ( R . styleable . RippleView_rv_alpha , rippleAlpha ) ; ripplePadding = typedArray . getDimensionPixelSize ( R . styleable . RippleView_rv_ripplePadding , 0 ) ; canvasHandler = new Handler ( ) ; zoomScale = typedArray . getFloat ( R . styleable . RippleView_rv_zoomScale , 1.03f ) ; zoomDuration = typedArray . getInt ( R . styleable . RippleView_rv_zoomDuration , 200 ) ; typedArray . recycle ( ) ; paint = new Paint ( ) ; paint . setAntiAlias ( true ) ; paint . setStyle ( Paint . Style . FILL ) ; paint . setColor ( rippleColor ) ; paint . setAlpha ( rippleAlpha ) ; this . setWillNotDraw ( false ) ; gestureDetector = new GestureDetector ( context , new GestureDetector . SimpleOnGestureListener ( ) { public void onLongPress ( MotionEvent event ) { super . onLongPress ( event ) ; animateRipple ( event ) ; sendClickEvent ( true ) ; } public boolean onSingleTapConfirmed ( MotionEvent e ) { return true ; } public boolean onSingleTapUp ( MotionEvent e ) { return true ; } } ) ; this . setDrawingCacheEnabled ( true ) ; this . setClickable ( true ) ; }
Method that initializes all fields and sets listeners
28,651
private void createAnimation ( final float x , final float y ) { if ( this . isEnabled ( ) && ! animationRunning ) { if ( hasToZoom ) this . startAnimation ( scaleAnimation ) ; radiusMax = Math . max ( WIDTH , HEIGHT ) ; if ( rippleType != 2 ) radiusMax /= 2 ; radiusMax -= ripplePadding ; if ( isCentered || rippleType == 1 ) { this . x = getMeasuredWidth ( ) / 2 ; this . y = getMeasuredHeight ( ) / 2 ; } else { this . x = x ; this . y = y ; } animationRunning = true ; if ( rippleType == 1 && originBitmap == null ) originBitmap = getDrawingCache ( true ) ; invalidate ( ) ; } }
Create Ripple animation centered at x y
28,652
private void sendClickEvent ( final Boolean isLongClick ) { if ( getParent ( ) instanceof AdapterView ) { final AdapterView adapterView = ( AdapterView ) getParent ( ) ; final int position = adapterView . getPositionForView ( this ) ; final long id = adapterView . getItemIdAtPosition ( position ) ; if ( isLongClick ) { if ( adapterView . getOnItemLongClickListener ( ) != null ) adapterView . getOnItemLongClickListener ( ) . onItemLongClick ( adapterView , this , position , id ) ; } else { if ( adapterView . getOnItemClickListener ( ) != null ) adapterView . getOnItemClickListener ( ) . onItemClick ( adapterView , this , position , id ) ; } } }
Send a click event if parent view is a Listview instance
28,653
public static TypeAdapterFactory create ( ) { if ( geometryTypeFactory == null ) { geometryTypeFactory = RuntimeTypeAdapterFactory . of ( Geometry . class , "type" , true ) . registerSubtype ( GeometryCollection . class , "GeometryCollection" ) . registerSubtype ( Point . class , "Point" ) . registerSubtype ( MultiPoint . class , "MultiPoint" ) . registerSubtype ( LineString . class , "LineString" ) . registerSubtype ( MultiLineString . class , "MultiLineString" ) . registerSubtype ( Polygon . class , "Polygon" ) . registerSubtype ( MultiPolygon . class , "MultiPolygon" ) ; } return geometryTypeFactory ; }
Create a new instance of Geometry type adapter factory this is passed into the Gson Builder .
28,654
public List < LineString > lineStrings ( ) { List < List < Point > > coordinates = coordinates ( ) ; List < LineString > lineStrings = new ArrayList < > ( coordinates . size ( ) ) ; for ( List < Point > points : coordinates ) { lineStrings . add ( LineString . fromLngLats ( points ) ) ; } return lineStrings ; }
Returns a list of LineStrings which are currently making up this MultiLineString .
28,655
public static String formatCoordinate ( double coordinate ) { DecimalFormat decimalFormat = new DecimalFormat ( "0.######" , new DecimalFormatSymbols ( Locale . US ) ) ; return String . format ( Locale . US , "%s" , decimalFormat . format ( coordinate ) ) ; }
Useful to remove any trailing zeros and prevent a coordinate being over 7 significant figures .
28,656
public static String formatCoordinate ( double coordinate , int precision ) { String pattern = "0." + new String ( new char [ precision ] ) . replace ( "\0" , "0" ) ; DecimalFormat df = ( DecimalFormat ) DecimalFormat . getInstance ( Locale . US ) ; df . applyPattern ( pattern ) ; df . setRoundingMode ( RoundingMode . FLOOR ) ; return df . format ( coordinate ) ; }
Allows the specific adjusting of a coordinates precision .
28,657
public static String formatRadiuses ( double [ ] radiuses ) { if ( radiuses == null || radiuses . length == 0 ) { return null ; } String [ ] radiusesFormatted = new String [ radiuses . length ] ; for ( int i = 0 ; i < radiuses . length ; i ++ ) { if ( radiuses [ i ] == Double . POSITIVE_INFINITY ) { radiusesFormatted [ i ] = "unlimited" ; } else { radiusesFormatted [ i ] = String . format ( Locale . US , "%s" , TextUtils . formatCoordinate ( radiuses [ i ] ) ) ; } } return join ( ";" , radiusesFormatted ) ; }
Used in various APIs to format the user provided radiuses to a String matching the APIs format .
28,658
public static String formatBearing ( List < Double [ ] > bearings ) { if ( bearings . isEmpty ( ) ) { return null ; } String [ ] bearingFormatted = new String [ bearings . size ( ) ] ; for ( int i = 0 ; i < bearings . size ( ) ; i ++ ) { if ( bearings . get ( i ) . length == 0 ) { bearingFormatted [ i ] = "" ; } else { bearingFormatted [ i ] = String . format ( Locale . US , "%s,%s" , TextUtils . formatCoordinate ( bearings . get ( i ) [ 0 ] ) , TextUtils . formatCoordinate ( bearings . get ( i ) [ 1 ] ) ) ; } } return TextUtils . join ( ";" , bearingFormatted ) ; }
Formats the bearing variables from the raw values to a string which can than be used for the request URL .
28,659
public static String formatDistributions ( List < Integer [ ] > distributions ) { if ( distributions . isEmpty ( ) ) { return null ; } String [ ] distributionsFormatted = new String [ distributions . size ( ) ] ; for ( int i = 0 ; i < distributions . size ( ) ; i ++ ) { if ( distributions . get ( i ) . length == 0 ) { distributionsFormatted [ i ] = "" ; } else { distributionsFormatted [ i ] = String . format ( Locale . US , "%s,%s" , TextUtils . formatCoordinate ( distributions . get ( i ) [ 0 ] ) , TextUtils . formatCoordinate ( distributions . get ( i ) [ 1 ] ) ) ; } } return TextUtils . join ( ";" , distributionsFormatted ) ; }
converts the list of integer arrays to a string ready for API consumption .
28,660
public static String formatApproaches ( String [ ] approaches ) { for ( int i = 0 ; i < approaches . length ; i ++ ) { if ( approaches [ i ] == null ) { approaches [ i ] = "" ; } else if ( ! approaches [ i ] . equals ( "unrestricted" ) && ! approaches [ i ] . equals ( "curb" ) && ! approaches [ i ] . isEmpty ( ) ) { return null ; } } return TextUtils . join ( ";" , approaches ) ; }
Converts String array with approaches values to a string ready for API consumption . An approach could be unrestricted curb or null .
28,661
public static String formatWaypointNames ( String [ ] waypointNames ) { for ( int i = 0 ; i < waypointNames . length ; i ++ ) { if ( waypointNames [ i ] == null ) { waypointNames [ i ] = "" ; } } return TextUtils . join ( ";" , waypointNames ) ; }
Converts String array with waypoint_names values to a string ready for API consumption .
28,662
public static Point fromLngLat ( @ FloatRange ( from = MIN_LONGITUDE , to = MAX_LONGITUDE ) double longitude , @ FloatRange ( from = MIN_LATITUDE , to = MAX_LATITUDE ) double latitude ) { List < Double > coordinates = CoordinateShifterManager . getCoordinateShifter ( ) . shiftLonLat ( longitude , latitude ) ; return new Point ( TYPE , null , coordinates ) ; }
Create a new instance of this class defining a longitude and latitude value in that respective order . Longitude values are limited to a - 180 to 180 range and latitude s limited to - 90 to 90 as the spec defines . While no limit is placed on decimal precision for performance reasons when serializing and deserializing it is suggested to limit decimal precision to within 6 decimal places .
28,663
private static boolean isLinearRing ( LineString lineString ) { if ( lineString . coordinates ( ) . size ( ) < 4 ) { throw new GeoJsonException ( "LinearRings need to be made up of 4 or more coordinates." ) ; } if ( ! ( lineString . coordinates ( ) . get ( 0 ) . equals ( lineString . coordinates ( ) . get ( lineString . coordinates ( ) . size ( ) - 1 ) ) ) ) { throw new GeoJsonException ( "LinearRings require first and last coordinate to be identical." ) ; } return true ; }
Checks to ensure that the LineStrings defining the polygon correctly and adhering to the linear ring rules .
28,664
protected S getService ( ) { if ( service != null ) { return service ; } Retrofit . Builder retrofitBuilder = new Retrofit . Builder ( ) . baseUrl ( baseUrl ( ) ) . addConverterFactory ( GsonConverterFactory . create ( getGsonBuilder ( ) . create ( ) ) ) ; if ( getCallFactory ( ) != null ) { retrofitBuilder . callFactory ( getCallFactory ( ) ) ; } else { retrofitBuilder . client ( getOkHttpClient ( ) ) ; } retrofit = retrofitBuilder . build ( ) ; service = ( S ) retrofit . create ( serviceType ) ; return service ; }
Creates the Retrofit object and the service if they are not already created . Subclasses can override getGsonBuilder to add anything to the GsonBuilder .
28,665
protected synchronized OkHttpClient getOkHttpClient ( ) { if ( okHttpClient == null ) { if ( isEnableDebug ( ) ) { HttpLoggingInterceptor logging = new HttpLoggingInterceptor ( ) ; logging . setLevel ( HttpLoggingInterceptor . Level . BASIC ) ; OkHttpClient . Builder httpClient = new OkHttpClient . Builder ( ) ; httpClient . addInterceptor ( logging ) ; okHttpClient = httpClient . build ( ) ; } else { okHttpClient = new OkHttpClient ( ) ; } } return okHttpClient ; }
Used Internally .
28,666
private static String formatWaypointTargets ( Point [ ] waypointTargets ) { String [ ] coordinatesFormatted = new String [ waypointTargets . length ] ; int index = 0 ; for ( Point target : waypointTargets ) { if ( target == null ) { coordinatesFormatted [ index ++ ] = "" ; } else { coordinatesFormatted [ index ++ ] = String . format ( Locale . US , "%s,%s" , TextUtils . formatCoordinate ( target . longitude ( ) ) , TextUtils . formatCoordinate ( target . latitude ( ) ) ) ; } } return TextUtils . join ( ";" , coordinatesFormatted ) ; }
Converts array of Points with waypoint_targets values to a string ready for API consumption .
28,667
public List < Polygon > polygons ( ) { List < List < List < Point > > > coordinates = coordinates ( ) ; List < Polygon > polygons = new ArrayList < > ( coordinates . size ( ) ) ; for ( List < List < Point > > points : coordinates ) { polygons . add ( Polygon . fromLngLats ( points ) ) ; } return polygons ; }
Returns a list of polygons which make up this MultiPolygon instance .
28,668
public String toJson ( ) { GsonBuilder gson = new GsonBuilder ( ) ; gson . registerTypeAdapterFactory ( DirectionsAdapterFactory . create ( ) ) ; gson . registerTypeAdapter ( Point . class , new PointAsCoordinatesTypeAdapter ( ) ) ; return gson . create ( ) . toJson ( this ) ; }
This takes the currently defined values found inside this instance and converts it to a json string .
28,669
public HttpUrl url ( ) { HttpUrl . Builder urlBuilder = HttpUrl . parse ( baseUrl ( ) ) . newBuilder ( ) . addPathSegment ( "styles" ) . addPathSegment ( "v1" ) . addPathSegment ( user ( ) ) . addPathSegment ( styleId ( ) ) . addPathSegment ( "static" ) . addQueryParameter ( "access_token" , accessToken ( ) ) ; List < String > annotations = new ArrayList < > ( ) ; if ( staticMarkerAnnotations ( ) != null ) { List < String > markerStrings = new ArrayList < > ( staticMarkerAnnotations ( ) . size ( ) ) ; for ( StaticMarkerAnnotation marker : staticMarkerAnnotations ( ) ) { markerStrings . add ( marker . url ( ) ) ; } annotations . addAll ( markerStrings ) ; } if ( staticPolylineAnnotations ( ) != null ) { String [ ] polylineStringArray = new String [ staticPolylineAnnotations ( ) . size ( ) ] ; for ( StaticPolylineAnnotation polyline : staticPolylineAnnotations ( ) ) { polylineStringArray [ staticPolylineAnnotations ( ) . indexOf ( polyline ) ] = polyline . url ( ) ; } annotations . addAll ( Arrays . asList ( polylineStringArray ) ) ; } if ( geoJson ( ) != null ) { annotations . add ( String . format ( Locale . US , "geojson(%s)" , geoJson ( ) . toJson ( ) ) ) ; } if ( ! annotations . isEmpty ( ) ) { urlBuilder . addPathSegment ( TextUtils . join ( "," , annotations . toArray ( ) ) ) ; } urlBuilder . addPathSegment ( cameraAuto ( ) ? CAMERA_AUTO : generateLocationPathSegment ( ) ) ; if ( beforeLayer ( ) != null ) { urlBuilder . addQueryParameter ( BEFORE_LAYER , beforeLayer ( ) ) ; } if ( ! attribution ( ) ) { urlBuilder . addQueryParameter ( "attribution" , "false" ) ; } if ( ! logo ( ) ) { urlBuilder . addQueryParameter ( "logo" , "false" ) ; } urlBuilder . addPathSegment ( generateSizePathSegment ( ) ) ; return urlBuilder . build ( ) ; }
Returns the formatted URL string meant to be passed to your Http client for retrieval of the actual Mapbox Static Image .
28,670
private static void simpleMapboxDirectionsRequest ( ) throws IOException { MapboxDirections . Builder builder = MapboxDirections . builder ( ) ; builder . accessToken ( BuildConfig . MAPBOX_ACCESS_TOKEN ) ; builder . origin ( Point . fromLngLat ( - 95.6332 , 29.7890 ) ) ; builder . destination ( Point . fromLngLat ( - 95.3591 , 29.7576 ) ) ; Response < DirectionsResponse > response = builder . build ( ) . executeCall ( ) ; System . out . printf ( "Check that the GET response is successful %b" , response . isSuccessful ( ) ) ; System . out . printf ( "%nGet the first routes distance from origin to destination: %f" , response . body ( ) . routes ( ) . get ( 0 ) . distance ( ) ) ; }
Demonstrates how to make the most basic GET directions request .
28,671
private static void asyncMapboxDirectionsRequest ( ) { MapboxDirections request = MapboxDirections . builder ( ) . accessToken ( BuildConfig . MAPBOX_ACCESS_TOKEN ) . origin ( Point . fromLngLat ( - 95.6332 , 29.7890 ) ) . destination ( Point . fromLngLat ( - 95.3591 , 29.7576 ) ) . profile ( DirectionsCriteria . PROFILE_CYCLING ) . steps ( true ) . build ( ) ; request . enqueueCall ( new Callback < DirectionsResponse > ( ) { public void onResponse ( Call < DirectionsResponse > call , Response < DirectionsResponse > response ) { if ( response . isSuccessful ( ) ) { System . out . printf ( "%nGet the street name of the first step along the route: %s" , response . body ( ) . routes ( ) . get ( 0 ) . legs ( ) . get ( 0 ) . steps ( ) . get ( 0 ) . name ( ) ) ; } } public void onFailure ( Call < DirectionsResponse > call , Throwable throwable ) { System . err . println ( throwable ) ; } } ) ; }
Demonstrates how to make an asynchronous directions request .
28,672
public String getStringProperty ( String key ) { JsonElement propertyKey = properties ( ) . get ( key ) ; return propertyKey == null ? null : propertyKey . getAsString ( ) ; }
Convenience method to get a String member .
28,673
public Number getNumberProperty ( String key ) { JsonElement propertyKey = properties ( ) . get ( key ) ; return propertyKey == null ? null : propertyKey . getAsNumber ( ) ; }
Convenience method to get a Number member .
28,674
public Boolean getBooleanProperty ( String key ) { JsonElement propertyKey = properties ( ) . get ( key ) ; return propertyKey == null ? null : propertyKey . getAsBoolean ( ) ; }
Convenience method to get a Boolean member .
28,675
public Character getCharacterProperty ( String key ) { JsonElement propertyKey = properties ( ) . get ( key ) ; return propertyKey == null ? null : propertyKey . getAsCharacter ( ) ; }
Convenience method to get a Character member .
28,676
public JsonElement serialize ( Point src , Type typeOfSrc , JsonSerializationContext context ) { JsonArray rawCoordinates = new JsonArray ( ) ; List < Double > unshiftedCoordinates = CoordinateShifterManager . getCoordinateShifter ( ) . unshiftPoint ( src ) ; rawCoordinates . add ( new JsonPrimitive ( GeoJsonUtils . trim ( unshiftedCoordinates . get ( 0 ) ) ) ) ; rawCoordinates . add ( new JsonPrimitive ( GeoJsonUtils . trim ( unshiftedCoordinates . get ( 1 ) ) ) ) ; if ( src . hasAltitude ( ) ) { rawCoordinates . add ( new JsonPrimitive ( unshiftedCoordinates . get ( 2 ) ) ) ; } return rawCoordinates ; }
Required to handle the special case where the altitude might be a Double . NaN which isn t a valid double value as per JSON specification .
28,677
public static boolean isAccessTokenValid ( String accessToken ) { return ! TextUtils . isEmpty ( accessToken ) && ! ( ! accessToken . startsWith ( "pk." ) && ! accessToken . startsWith ( "sk." ) && ! accessToken . startsWith ( "tk." ) ) ; }
Checks that the provided access token is not empty or null and that it starts with the right prefixes . Note that this method does not check Mapbox servers to verify that it actually belongs to an account .
28,678
public static void geojsonType ( GeoJson value , String type , String name ) { if ( type == null || type . length ( ) == 0 || name == null || name . length ( ) == 0 ) { throw new TurfException ( "Type and name required" ) ; } if ( value == null || ! value . type ( ) . equals ( type ) ) { throw new TurfException ( "Invalid input to " + name + ": must be a " + type + ", given " + ( value != null ? value . type ( ) : " null" ) ) ; } }
Enforce expectations about types of GeoJson objects for Turf .
28,679
public static BoundingBox fromCoordinates ( @ FloatRange ( from = MIN_LONGITUDE , to = GeoJsonConstants . MAX_LONGITUDE ) double west , @ FloatRange ( from = MIN_LATITUDE , to = GeoJsonConstants . MAX_LATITUDE ) double south , @ FloatRange ( from = MIN_LONGITUDE , to = GeoJsonConstants . MAX_LONGITUDE ) double east , @ FloatRange ( from = MIN_LATITUDE , to = GeoJsonConstants . MAX_LATITUDE ) double north ) { return fromLngLats ( west , south , east , north ) ; }
Define a new instance of this class by passing in four coordinates in the same order they would appear in the serialized GeoJson form . Limits are placed on the minimum and maximum coordinate values which can exist and comply with the GeoJson spec .
28,680
public static String encode ( final List < Point > path , int precision ) { long lastLat = 0 ; long lastLng = 0 ; final StringBuilder result = new StringBuilder ( ) ; double factor = Math . pow ( 10 , precision ) ; for ( final Point point : path ) { long lat = Math . round ( point . latitude ( ) * factor ) ; long lng = Math . round ( point . longitude ( ) * factor ) ; long varLat = lat - lastLat ; long varLng = lng - lastLng ; encode ( varLat , result ) ; encode ( varLng , result ) ; lastLat = lat ; lastLng = lng ; } return result . toString ( ) ; }
Encodes a sequence of Points into an encoded path string .
28,681
private static double getSqDist ( Point p1 , Point p2 ) { double dx = p1 . longitude ( ) - p2 . longitude ( ) ; double dy = p1 . latitude ( ) - p2 . latitude ( ) ; return dx * dx + dy * dy ; }
Square distance between 2 points .
28,682
private static double getSqSegDist ( Point point , Point p1 , Point p2 ) { double horizontal = p1 . longitude ( ) ; double vertical = p1 . latitude ( ) ; double diffHorizontal = p2 . longitude ( ) - horizontal ; double diffVertical = p2 . latitude ( ) - vertical ; if ( diffHorizontal != 0 || diffVertical != 0 ) { double total = ( ( point . longitude ( ) - horizontal ) * diffHorizontal + ( point . latitude ( ) - vertical ) * diffVertical ) / ( diffHorizontal * diffHorizontal + diffVertical * diffVertical ) ; if ( total > 1 ) { horizontal = p2 . longitude ( ) ; vertical = p2 . latitude ( ) ; } else if ( total > 0 ) { horizontal += diffHorizontal * total ; vertical += diffVertical * total ; } } diffHorizontal = point . longitude ( ) - horizontal ; diffVertical = point . latitude ( ) - vertical ; return diffHorizontal * diffHorizontal + diffVertical * diffVertical ; }
Square distance from a point to a segment .
28,683
private static List < Point > simplifyRadialDist ( List < Point > points , double sqTolerance ) { Point prevPoint = points . get ( 0 ) ; ArrayList < Point > newPoints = new ArrayList < > ( ) ; newPoints . add ( prevPoint ) ; Point point = null ; for ( int i = 1 , len = points . size ( ) ; i < len ; i ++ ) { point = points . get ( i ) ; if ( getSqDist ( point , prevPoint ) > sqTolerance ) { newPoints . add ( point ) ; prevPoint = point ; } } if ( ! prevPoint . equals ( point ) ) { newPoints . add ( point ) ; } return newPoints ; }
Basic distance - based simplification .
28,684
private static List < Point > simplifyDouglasPeucker ( List < Point > points , double sqTolerance ) { int last = points . size ( ) - 1 ; ArrayList < Point > simplified = new ArrayList < > ( ) ; simplified . add ( points . get ( 0 ) ) ; simplified . addAll ( simplifyDpStep ( points , 0 , last , sqTolerance , simplified ) ) ; simplified . add ( points . get ( last ) ) ; return simplified ; }
Simplification using Ramer - Douglas - Peucker algorithm .
28,685
public static double trim ( double value ) { if ( value > MAX_DOUBLE_TO_ROUND || value < - MAX_DOUBLE_TO_ROUND ) { return value ; } return Math . round ( value * ROUND_PRECISION ) / ROUND_PRECISION ; }
Trims a double value to have only 7 digits after period .
28,686
public void showHint ( ) { final int [ ] screenPos = new int [ 2 ] ; final Rect displayFrame = new Rect ( ) ; getLocationOnScreen ( screenPos ) ; getWindowVisibleDisplayFrame ( displayFrame ) ; final Context context = getContext ( ) ; final int width = getWidth ( ) ; final int height = getHeight ( ) ; final int midy = screenPos [ 1 ] + height / 2 ; int referenceX = screenPos [ 0 ] + width / 2 ; if ( ViewCompat . getLayoutDirection ( this ) == ViewCompat . LAYOUT_DIRECTION_LTR ) { final int screenWidth = context . getResources ( ) . getDisplayMetrics ( ) . widthPixels ; referenceX = screenWidth - referenceX ; } StringBuilder hint = new StringBuilder ( "#" ) ; if ( Color . alpha ( color ) != 255 ) { hint . append ( Integer . toHexString ( color ) . toUpperCase ( Locale . ENGLISH ) ) ; } else { hint . append ( String . format ( "%06X" , 0xFFFFFF & color ) . toUpperCase ( Locale . ENGLISH ) ) ; } Toast cheatSheet = Toast . makeText ( context , hint . toString ( ) , Toast . LENGTH_SHORT ) ; if ( midy < displayFrame . height ( ) ) { cheatSheet . setGravity ( Gravity . TOP | GravityCompat . END , referenceX , screenPos [ 1 ] + height - displayFrame . top ) ; } else { cheatSheet . setGravity ( Gravity . BOTTOM | Gravity . CENTER_HORIZONTAL , 0 , height ) ; } cheatSheet . show ( ) ; }
Show a toast message with the hex color code below the view .
28,687
View createPickerView ( ) { View contentView = View . inflate ( getActivity ( ) , R . layout . cpv_dialog_color_picker , null ) ; colorPicker = ( ColorPickerView ) contentView . findViewById ( R . id . cpv_color_picker_view ) ; ColorPanelView oldColorPanel = ( ColorPanelView ) contentView . findViewById ( R . id . cpv_color_panel_old ) ; newColorPanel = ( ColorPanelView ) contentView . findViewById ( R . id . cpv_color_panel_new ) ; ImageView arrowRight = ( ImageView ) contentView . findViewById ( R . id . cpv_arrow_right ) ; hexEditText = ( EditText ) contentView . findViewById ( R . id . cpv_hex ) ; try { final TypedValue value = new TypedValue ( ) ; TypedArray typedArray = getActivity ( ) . obtainStyledAttributes ( value . data , new int [ ] { android . R . attr . textColorPrimary } ) ; int arrowColor = typedArray . getColor ( 0 , Color . BLACK ) ; typedArray . recycle ( ) ; arrowRight . setColorFilter ( arrowColor ) ; } catch ( Exception ignored ) { } colorPicker . setAlphaSliderVisible ( showAlphaSlider ) ; oldColorPanel . setColor ( getArguments ( ) . getInt ( ARG_COLOR ) ) ; colorPicker . setColor ( color , true ) ; newColorPanel . setColor ( color ) ; setHex ( color ) ; if ( ! showAlphaSlider ) { hexEditText . setFilters ( new InputFilter [ ] { new InputFilter . LengthFilter ( 6 ) } ) ; } newColorPanel . setOnClickListener ( new View . OnClickListener ( ) { public void onClick ( View v ) { if ( newColorPanel . getColor ( ) == color ) { onColorSelected ( color ) ; dismiss ( ) ; } } } ) ; contentView . setOnTouchListener ( onPickerTouchListener ) ; colorPicker . setOnColorChangedListener ( this ) ; hexEditText . addTextChangedListener ( this ) ; hexEditText . setOnFocusChangeListener ( new View . OnFocusChangeListener ( ) { public void onFocusChange ( View v , boolean hasFocus ) { if ( hasFocus ) { InputMethodManager imm = ( InputMethodManager ) getActivity ( ) . getSystemService ( Context . INPUT_METHOD_SERVICE ) ; imm . showSoftInput ( hexEditText , InputMethodManager . SHOW_IMPLICIT ) ; } } } ) ; return contentView ; }
region Custom Picker
28,688
View createPresetsView ( ) { View contentView = View . inflate ( getActivity ( ) , R . layout . cpv_dialog_presets , null ) ; shadesLayout = ( LinearLayout ) contentView . findViewById ( R . id . shades_layout ) ; transparencySeekBar = ( SeekBar ) contentView . findViewById ( R . id . transparency_seekbar ) ; transparencyPercText = ( TextView ) contentView . findViewById ( R . id . transparency_text ) ; GridView gridView = ( GridView ) contentView . findViewById ( R . id . gridView ) ; loadPresets ( ) ; if ( showColorShades ) { createColorShades ( color ) ; } else { shadesLayout . setVisibility ( View . GONE ) ; contentView . findViewById ( R . id . shades_divider ) . setVisibility ( View . GONE ) ; } adapter = new ColorPaletteAdapter ( new ColorPaletteAdapter . OnColorSelectedListener ( ) { public void onColorSelected ( int newColor ) { if ( color == newColor ) { ColorPickerDialog . this . onColorSelected ( color ) ; dismiss ( ) ; return ; } color = newColor ; if ( showColorShades ) { createColorShades ( color ) ; } } } , presets , getSelectedItemPosition ( ) , colorShape ) ; gridView . setAdapter ( adapter ) ; if ( showAlphaSlider ) { setupTransparency ( ) ; } else { contentView . findViewById ( R . id . transparency_layout ) . setVisibility ( View . GONE ) ; contentView . findViewById ( R . id . transparency_title ) . setVisibility ( View . GONE ) ; } return contentView ; }
region Presets Picker
28,689
public void setColor ( int color , boolean callback ) { int alpha = Color . alpha ( color ) ; int red = Color . red ( color ) ; int blue = Color . blue ( color ) ; int green = Color . green ( color ) ; float [ ] hsv = new float [ 3 ] ; Color . RGBToHSV ( red , green , blue , hsv ) ; this . alpha = alpha ; hue = hsv [ 0 ] ; sat = hsv [ 1 ] ; val = hsv [ 2 ] ; if ( callback && onColorChangedListener != null ) { onColorChangedListener . onColorChanged ( Color . HSVToColor ( this . alpha , new float [ ] { hue , sat , val } ) ) ; } invalidate ( ) ; }
Set the color this view should show .
28,690
public void setAlphaSliderVisible ( boolean visible ) { if ( showAlphaPanel != visible ) { showAlphaPanel = visible ; valShader = null ; satShader = null ; alphaShader = null ; hueBackgroundCache = null ; satValBackgroundCache = null ; requestLayout ( ) ; } }
Set if the user is allowed to adjust the alpha panel . Default is false . If it is set to false no alpha will be set .
28,691
public static UserAgent valueOf ( int id ) { OperatingSystem operatingSystem = OperatingSystem . valueOf ( ( short ) ( id >> 16 ) ) ; Browser browser = Browser . valueOf ( ( short ) ( id & 0x0FFFF ) ) ; return new UserAgent ( operatingSystem , browser ) ; }
Returns UserAgent based on specified unique id
28,692
public static UserAgent valueOf ( String name ) { if ( name == null ) throw new NullPointerException ( "Name is null" ) ; String [ ] elements = name . split ( "-" ) ; if ( elements . length == 2 ) { OperatingSystem operatingSystem = OperatingSystem . valueOf ( elements [ 0 ] ) ; Browser browser = Browser . valueOf ( elements [ 1 ] ) ; return new UserAgent ( operatingSystem , browser ) ; } throw new IllegalArgumentException ( "Invalid string for userAgent " + name ) ; }
Returns UserAgent based on combined string representation
28,693
public ByteBuffer reset ( ByteBuffer input ) { ByteBuffer old = this . input ; this . input = checkNotNull ( input , "input ByteBuffer is null" ) . slice ( ) ; isRead = false ; return old ; }
Reset buffer .
28,694
public MessagePacker packString ( String s ) throws IOException { if ( s . length ( ) <= 0 ) { packRawStringHeader ( 0 ) ; return this ; } else if ( CORRUPTED_CHARSET_ENCODER || s . length ( ) < smallStringOptimizationThreshold ) { packStringWithGetBytes ( s ) ; return this ; } else if ( s . length ( ) < ( 1 << 8 ) ) { ensureCapacity ( 2 + s . length ( ) * UTF_8_MAX_CHAR_SIZE + 1 ) ; int written = encodeStringToBufferAt ( position + 2 , s ) ; if ( written >= 0 ) { if ( str8FormatSupport && written < ( 1 << 8 ) ) { buffer . putByte ( position ++ , STR8 ) ; buffer . putByte ( position ++ , ( byte ) written ) ; position += written ; } else { if ( written >= ( 1 << 16 ) ) { throw new IllegalArgumentException ( "Unexpected UTF-8 encoder state" ) ; } buffer . putMessageBuffer ( position + 3 , buffer , position + 2 , written ) ; buffer . putByte ( position ++ , STR16 ) ; buffer . putShort ( position , ( short ) written ) ; position += 2 ; position += written ; } return this ; } } else if ( s . length ( ) < ( 1 << 16 ) ) { ensureCapacity ( 3 + s . length ( ) * UTF_8_MAX_CHAR_SIZE + 2 ) ; int written = encodeStringToBufferAt ( position + 3 , s ) ; if ( written >= 0 ) { if ( written < ( 1 << 16 ) ) { buffer . putByte ( position ++ , STR16 ) ; buffer . putShort ( position , ( short ) written ) ; position += 2 ; position += written ; } else { if ( written >= ( 1L << 32 ) ) { throw new IllegalArgumentException ( "Unexpected UTF-8 encoder state" ) ; } buffer . putMessageBuffer ( position + 5 , buffer , position + 3 , written ) ; buffer . putByte ( position ++ , STR32 ) ; buffer . putInt ( position , written ) ; position += 4 ; position += written ; } return this ; } } packStringWithGetBytes ( s ) ; return this ; }
Writes a String vlaue in UTF - 8 encoding .
28,695
private static MessageBuffer newMessageBuffer ( byte [ ] arr , int off , int len ) { checkNotNull ( arr ) ; if ( mbArrConstructor != null ) { return newInstance ( mbArrConstructor , arr , off , len ) ; } return new MessageBuffer ( arr , off , len ) ; }
Creates a new MessageBuffer instance backed by a java heap array
28,696
private static MessageBuffer newMessageBuffer ( ByteBuffer bb ) { checkNotNull ( bb ) ; if ( mbBBConstructor != null ) { return newInstance ( mbBBConstructor , bb ) ; } return new MessageBuffer ( bb ) ; }
Creates a new MessageBuffer instance backed by ByteBuffer
28,697
private static MessageBuffer newInstance ( Constructor < ? > constructor , Object ... args ) { try { return ( MessageBuffer ) constructor . newInstance ( args ) ; } catch ( InstantiationException e ) { throw new IllegalStateException ( e ) ; } catch ( IllegalAccessException e ) { throw new IllegalStateException ( e ) ; } catch ( InvocationTargetException e ) { if ( e . getCause ( ) instanceof RuntimeException ) { throw ( RuntimeException ) e . getCause ( ) ; } else if ( e . getCause ( ) instanceof Error ) { throw ( Error ) e . getCause ( ) ; } throw new IllegalStateException ( e . getCause ( ) ) ; } }
Creates a new MessageBuffer instance
28,698
public int getInt ( int index ) { int i = unsafe . getInt ( base , address + index ) ; return Integer . reverseBytes ( i ) ; }
Read a big - endian int value at the specified index
28,699
public void putInt ( int index , int v ) { v = Integer . reverseBytes ( v ) ; unsafe . putInt ( base , address + index , v ) ; }
Write a big - endian integer value to the memory