idx int64 0 41.2k | question stringlengths 74 4.21k | target stringlengths 5 888 |
|---|---|---|
31,500 | public void endInterval ( int lastIndex ) { if ( isOpen ) { currentDetail . setLast ( lastIndex ) ; pathDetails . add ( currentDetail ) ; } isOpen = false ; } | Ending intervals multiple times is safe we only write the interval if it was open and not empty . Writes the interval to the pathDetails |
31,501 | public void start ( EdgeExplorer explorer , int startNode ) { IntArrayDeque stack = new IntArrayDeque ( ) ; GHBitSet explored = createBitSet ( ) ; stack . addLast ( startNode ) ; int current ; while ( stack . size ( ) > 0 ) { current = stack . removeLast ( ) ; if ( ! explored . contains ( current ) && goFurther ( current ) ) { EdgeIterator iter = explorer . setBaseNode ( current ) ; while ( iter . next ( ) ) { int connectedId = iter . getAdjNode ( ) ; if ( checkAdjacent ( iter ) ) { stack . addLast ( connectedId ) ; } } explored . add ( current ) ; } } } | beginning with startNode add all following nodes to LIFO queue . If node has been already explored before skip reexploration . |
31,502 | void preProcess ( File osmFile ) { try ( OSMInput in = openOsmInputFile ( osmFile ) ) { long tmpWayCounter = 1 ; long tmpRelationCounter = 1 ; ReaderElement item ; while ( ( item = in . getNext ( ) ) != null ) { if ( item . isType ( ReaderElement . WAY ) ) { final ReaderWay way = ( ReaderWay ) item ; boolean valid = filterWay ( way ) ; if ( valid ) { LongIndexedContainer wayNodes = way . getNodes ( ) ; int s = wayNodes . size ( ) ; for ( int index = 0 ; index < s ; index ++ ) { prepareHighwayNode ( wayNodes . get ( index ) ) ; } if ( ++ tmpWayCounter % 10_000_000 == 0 ) { LOGGER . info ( nf ( tmpWayCounter ) + " (preprocess), osmIdMap:" + nf ( getNodeMap ( ) . getSize ( ) ) + " (" + getNodeMap ( ) . getMemoryUsage ( ) + "MB) " + Helper . getMemInfo ( ) ) ; } } } else if ( item . isType ( ReaderElement . RELATION ) ) { final ReaderRelation relation = ( ReaderRelation ) item ; if ( ! relation . isMetaRelation ( ) && relation . hasTag ( "type" , "route" ) ) prepareWaysWithRelationInfo ( relation ) ; if ( relation . hasTag ( "type" , "restriction" ) ) prepareRestrictionRelation ( relation ) ; if ( ++ tmpRelationCounter % 100_000 == 0 ) { LOGGER . info ( nf ( tmpRelationCounter ) + " (preprocess), osmWayMap:" + nf ( getRelFlagsMap ( ) . size ( ) ) + " " + Helper . getMemInfo ( ) ) ; } } else if ( item . isType ( ReaderElement . FILEHEADER ) ) { final OSMFileHeader fileHeader = ( OSMFileHeader ) item ; osmDataDate = Helper . createFormatter ( ) . parse ( fileHeader . getTag ( "timestamp" ) ) ; } } } catch ( Exception ex ) { throw new RuntimeException ( "Problem while parsing file" , ex ) ; } } | Preprocessing of OSM file to select nodes which are used for highways . This allows a more compact graph data structure . |
31,503 | boolean filterWay ( ReaderWay item ) { if ( item . getNodes ( ) . size ( ) < 2 ) return false ; if ( ! item . hasTags ( ) ) return false ; return encodingManager . acceptWay ( item , new EncodingManager . AcceptWay ( ) ) ; } | Filter ways but do not analyze properties wayNodes will be filled with participating node ids . |
31,504 | private void writeOsm2Graph ( File osmFile ) { int tmp = ( int ) Math . max ( getNodeMap ( ) . getSize ( ) / 50 , 100 ) ; LOGGER . info ( "creating graph. Found nodes (pillar+tower):" + nf ( getNodeMap ( ) . getSize ( ) ) + ", " + Helper . getMemInfo ( ) ) ; if ( createStorage ) ghStorage . create ( tmp ) ; long wayStart = - 1 ; long relationStart = - 1 ; long counter = 1 ; try ( OSMInput in = openOsmInputFile ( osmFile ) ) { LongIntMap nodeFilter = getNodeMap ( ) ; ReaderElement item ; while ( ( item = in . getNext ( ) ) != null ) { switch ( item . getType ( ) ) { case ReaderElement . NODE : if ( nodeFilter . get ( item . getId ( ) ) != EMPTY_NODE ) { processNode ( ( ReaderNode ) item ) ; } break ; case ReaderElement . WAY : if ( wayStart < 0 ) { LOGGER . info ( nf ( counter ) + ", now parsing ways" ) ; wayStart = counter ; } processWay ( ( ReaderWay ) item ) ; break ; case ReaderElement . RELATION : if ( relationStart < 0 ) { LOGGER . info ( nf ( counter ) + ", now parsing relations" ) ; relationStart = counter ; } processRelation ( ( ReaderRelation ) item ) ; break ; case ReaderElement . FILEHEADER : break ; default : throw new IllegalStateException ( "Unknown type " + item . getType ( ) ) ; } if ( ++ counter % 200_000_000 == 0 ) { LOGGER . info ( nf ( counter ) + ", locs:" + nf ( locations ) + " (" + skippedLocations + ") " + Helper . getMemInfo ( ) ) ; } } if ( in . getUnprocessedElements ( ) > 0 ) throw new IllegalStateException ( "Still unprocessed elements in reader queue " + in . getUnprocessedElements ( ) ) ; } catch ( Exception ex ) { throw new RuntimeException ( "Couldn't process file " + osmFile + ", error: " + ex . getMessage ( ) , ex ) ; } finishedReading ( ) ; if ( graph . getNodes ( ) == 0 ) throw new RuntimeException ( "Graph after reading OSM must not be empty. Read " + counter + " items and " + locations + " locations" ) ; } | Creates the graph with edges and nodes from the specified osm file . |
31,505 | private static boolean isOnePassable ( List < BooleanEncodedValue > checkEncoders , IntsRef edgeFlags ) { for ( BooleanEncodedValue accessEnc : checkEncoders ) { if ( accessEnc . getBool ( false , edgeFlags ) || accessEnc . getBool ( true , edgeFlags ) ) return true ; } return false ; } | The nodeFlags store the encoders to check for accessibility in edgeFlags . E . g . if nodeFlags == 3 then the accessibility of the first two encoders will be check in edgeFlags |
31,506 | protected void storeOsmWayID ( int edgeId , long osmWayId ) { if ( getOsmWayIdSet ( ) . contains ( osmWayId ) ) { getEdgeIdToOsmWayIdMap ( ) . put ( edgeId , osmWayId ) ; } } | Stores only osmWayIds which are required for relations |
31,507 | long addBarrierNode ( long nodeId ) { ReaderNode newNode ; int graphIndex = getNodeMap ( ) . get ( nodeId ) ; if ( graphIndex < TOWER_NODE ) { graphIndex = - graphIndex - 3 ; newNode = new ReaderNode ( createNewNodeId ( ) , nodeAccess , graphIndex ) ; } else { graphIndex = graphIndex - 3 ; newNode = new ReaderNode ( createNewNodeId ( ) , pillarInfo , graphIndex ) ; } final long id = newNode . getId ( ) ; prepareHighwayNode ( id ) ; addNode ( newNode ) ; return id ; } | Create a copy of the barrier node |
31,508 | Collection < EdgeIteratorState > addBarrierEdge ( long fromId , long toId , IntsRef inEdgeFlags , long nodeFlags , long wayOsmId ) { IntsRef edgeFlags = IntsRef . deepCopyOf ( inEdgeFlags ) ; for ( BooleanEncodedValue accessEnc : encodingManager . getAccessEncFromNodeFlags ( nodeFlags ) ) { accessEnc . setBool ( false , edgeFlags , false ) ; accessEnc . setBool ( true , edgeFlags , false ) ; } barrierNodeIds . clear ( ) ; barrierNodeIds . add ( fromId ) ; barrierNodeIds . add ( toId ) ; return addOSMWay ( barrierNodeIds , edgeFlags , wayOsmId ) ; } | Add a zero length edge with reduced routing options to the graph . |
31,509 | public void setSubnetwork ( int nodeId , int subnetwork ) { if ( subnetwork > 127 ) throw new IllegalArgumentException ( "Number of subnetworks is currently limited to 127 but requested " + subnetwork ) ; byte [ ] bytes = new byte [ 1 ] ; bytes [ 0 ] = ( byte ) subnetwork ; da . setBytes ( nodeId , bytes , bytes . length ) ; } | This method sets the subnetwork if of the specified nodeId . Default is 0 and means subnetwork was too small to be useful to be stored . |
31,510 | void initNodeRefs ( long oldCapacity , long newCapacity ) { for ( long pointer = oldCapacity + N_EDGE_REF ; pointer < newCapacity ; pointer += nodeEntryBytes ) { nodes . setInt ( pointer , EdgeIterator . NO_EDGE ) ; } if ( extStorage . isRequireNodeField ( ) ) { for ( long pointer = oldCapacity + N_ADDITIONAL ; pointer < newCapacity ; pointer += nodeEntryBytes ) { nodes . setInt ( pointer , extStorage . getDefaultNodeFieldValue ( ) ) ; } } } | Initializes the node area with the empty edge value and default additional value . |
31,511 | final void ensureNodeIndex ( int nodeIndex ) { if ( ! initialized ) throw new AssertionError ( "The graph has not yet been initialized." ) ; if ( nodeIndex < nodeCount ) return ; long oldNodes = nodeCount ; nodeCount = nodeIndex + 1 ; boolean capacityIncreased = nodes . ensureCapacity ( ( long ) nodeCount * nodeEntryBytes ) ; if ( capacityIncreased ) { long newBytesCapacity = nodes . getCapacity ( ) ; initNodeRefs ( oldNodes * nodeEntryBytes , newBytesCapacity ) ; } } | Check if byte capacity of DataAcess nodes object is sufficient to include node index else extend byte capacity |
31,512 | public EdgeIteratorState edge ( int nodeA , int nodeB ) { if ( isFrozen ( ) ) throw new IllegalStateException ( "Cannot create edge if graph is already frozen" ) ; ensureNodeIndex ( Math . max ( nodeA , nodeB ) ) ; int edgeId = edgeAccess . internalEdgeAdd ( nextEdgeId ( ) , nodeA , nodeB ) ; EdgeIterable iter = new EdgeIterable ( this , edgeAccess , EdgeFilter . ALL_EDGES ) ; boolean ret = iter . init ( edgeId , nodeB ) ; assert ret ; if ( extStorage . isRequireEdgeField ( ) ) iter . setAdditionalField ( extStorage . getDefaultEdgeFieldValue ( ) ) ; return iter ; } | Create edge between nodes a and b |
31,513 | protected int nextEdgeId ( ) { int nextEdge = edgeCount ; edgeCount ++ ; if ( edgeCount < 0 ) throw new IllegalStateException ( "too many edges. new edge id would be negative. " + toString ( ) ) ; edges . ensureCapacity ( ( ( long ) edgeCount + 1 ) * edgeEntryBytes ) ; return nextEdge ; } | Determine next free edgeId and ensure byte capacity to store edge |
31,514 | private SRTMProvider init ( ) { try { String strs [ ] = { "Africa" , "Australia" , "Eurasia" , "Islands" , "North_America" , "South_America" } ; for ( String str : strs ) { InputStream is = getClass ( ) . getResourceAsStream ( str + "_names.txt" ) ; for ( String line : Helper . readFile ( new InputStreamReader ( is , Helper . UTF_CS ) ) ) { int lat = Integer . parseInt ( line . substring ( 1 , 3 ) ) ; if ( line . substring ( 0 , 1 ) . charAt ( 0 ) == 'S' ) lat = - lat ; int lon = Integer . parseInt ( line . substring ( 4 , 7 ) ) ; if ( line . substring ( 3 , 4 ) . charAt ( 0 ) == 'W' ) lon = - lon ; int intKey = calcIntKey ( lat , lon ) ; String key = areas . put ( intKey , str ) ; if ( key != null ) throw new IllegalStateException ( "do not overwrite existing! key " + intKey + " " + key + " vs. " + str ) ; } } return this ; } catch ( Exception ex ) { throw new IllegalStateException ( "Cannot load area names from classpath" , ex ) ; } } | The URLs are a bit ugly and so we need to find out which area name a certain lat lon coordinate has . |
31,515 | public static OSMFileHeader create ( long id , XMLStreamReader parser ) throws XMLStreamException { OSMFileHeader header = new OSMFileHeader ( ) ; parser . nextTag ( ) ; return header ; } | Constructor for XML Parser |
31,516 | public String getHighwayAsString ( EdgeIteratorState edge ) { int val = getHighway ( edge ) ; for ( Entry < String , Integer > e : highwayMap . entrySet ( ) ) { if ( e . getValue ( ) == val ) return e . getKey ( ) ; } return null ; } | Do not use within weighting as this is suboptimal from performance point of view . |
31,517 | public WeightingConfig createWeightingConfig ( PMap pMap ) { HashMap < String , Double > map = new HashMap < > ( DEFAULT_SPEEDS . size ( ) ) ; for ( Entry < String , Double > e : DEFAULT_SPEEDS . entrySet ( ) ) { map . put ( e . getKey ( ) , pMap . getDouble ( e . getKey ( ) , e . getValue ( ) ) ) ; } return new WeightingConfig ( getHighwaySpeedMap ( map ) ) ; } | This method creates a Config map out of the PMap . Later on this conversion should not be necessary when we read JSON . |
31,518 | void handleBikeRelated ( IntsRef edgeFlags , ReaderWay way , boolean partOfCycleRelation ) { String surfaceTag = way . getTag ( "surface" ) ; String highway = way . getTag ( "highway" ) ; String trackType = way . getTag ( "tracktype" ) ; if ( "track" . equals ( highway ) && ( trackType == null || ! "grade1" . equals ( trackType ) ) || "path" . equals ( highway ) && surfaceTag == null || unpavedSurfaceTags . contains ( surfaceTag ) ) { unpavedEncoder . setBool ( false , edgeFlags , true ) ; } WayType wayType ; if ( roadValues . contains ( highway ) ) wayType = WayType . ROAD ; else wayType = WayType . OTHER_SMALL_WAY ; boolean isPushingSection = isPushingSection ( way ) ; if ( isPushingSection && ! partOfCycleRelation || "steps" . equals ( highway ) ) wayType = WayType . PUSHING_SECTION ; if ( way . hasTag ( "bicycle" , intendedValues ) ) { if ( isPushingSection && ! way . hasTag ( "bicycle" , "designated" ) ) wayType = WayType . OTHER_SMALL_WAY ; else if ( wayType == WayType . OTHER_SMALL_WAY || wayType == WayType . PUSHING_SECTION ) wayType = WayType . CYCLEWAY ; } else if ( "cycleway" . equals ( highway ) ) wayType = WayType . CYCLEWAY ; wayTypeEncoder . setInt ( false , edgeFlags , wayType . getValue ( ) ) ; } | Handle surface and wayType encoding |
31,519 | final long createReverseKey ( double lat , double lon ) { return BitUtil . BIG . reverse ( keyAlgo . encode ( lat , lon ) , keyAlgo . getBits ( ) ) ; } | this method returns the spatial key in reverse order for easier right - shifting |
31,520 | public static Polygon create ( org . locationtech . jts . geom . Polygon polygon ) { double [ ] lats = new double [ polygon . getNumPoints ( ) ] ; double [ ] lons = new double [ polygon . getNumPoints ( ) ] ; for ( int i = 0 ; i < polygon . getNumPoints ( ) ; i ++ ) { lats [ i ] = polygon . getCoordinates ( ) [ i ] . y ; lons [ i ] = polygon . getCoordinates ( ) [ i ] . x ; } return new Polygon ( lats , lons ) ; } | Lossy conversion to a GraphHopper Polygon . |
31,521 | public InputStream fetch ( HttpURLConnection connection , boolean readErrorStreamNoException ) throws IOException { connection . connect ( ) ; InputStream is ; if ( readErrorStreamNoException && connection . getResponseCode ( ) >= 400 && connection . getErrorStream ( ) != null ) is = connection . getErrorStream ( ) ; else is = connection . getInputStream ( ) ; if ( is == null ) throw new IOException ( "Stream is null. Message:" + connection . getResponseMessage ( ) ) ; try { String encoding = connection . getContentEncoding ( ) ; if ( encoding != null && encoding . equalsIgnoreCase ( "gzip" ) ) is = new GZIPInputStream ( is ) ; else if ( encoding != null && encoding . equalsIgnoreCase ( "deflate" ) ) is = new InflaterInputStream ( is , new Inflater ( true ) ) ; } catch ( IOException ex ) { } return is ; } | This method initiates a connect call of the provided connection and returns the response stream . It only returns the error stream if it is available and readErrorStreamNoException is true otherwise it throws an IOException if an error happens . Furthermore it wraps the stream to decompress it if the connection content encoding is specified . |
31,522 | public < T extends Graph > T getGraph ( Class < T > clazz , Weighting weighting ) { if ( clazz . equals ( Graph . class ) ) return ( T ) baseGraph ; Collection < CHGraphImpl > chGraphs = getAllCHGraphs ( ) ; if ( chGraphs . isEmpty ( ) ) throw new IllegalStateException ( "Cannot find graph implementation for " + clazz ) ; if ( weighting == null ) throw new IllegalStateException ( "Cannot find CHGraph with null weighting" ) ; List < Weighting > existing = new ArrayList < > ( ) ; for ( CHGraphImpl cg : chGraphs ) { if ( cg . getWeighting ( ) == weighting ) return ( T ) cg ; existing . add ( cg . getWeighting ( ) ) ; } throw new IllegalStateException ( "Cannot find CHGraph for specified weighting: " + weighting + ", existing:" + existing ) ; } | This method returns the routing graph for the specified weighting could be potentially filled with shortcuts . |
31,523 | public GraphHopperStorage create ( long byteCount ) { baseGraph . checkInit ( ) ; if ( encodingManager == null ) throw new IllegalStateException ( "EncodingManager can only be null if you call loadExisting" ) ; dir . create ( ) ; long initSize = Math . max ( byteCount , 100 ) ; properties . create ( 100 ) ; properties . put ( "graph.bytes_for_flags" , encodingManager . getBytesForFlags ( ) ) ; properties . put ( "graph.flag_encoders" , encodingManager . toDetailsString ( ) ) ; properties . put ( "graph.byte_order" , dir . getByteOrder ( ) ) ; properties . put ( "graph.dimension" , baseGraph . nodeAccess . getDimension ( ) ) ; properties . putCurrentVersions ( ) ; baseGraph . create ( initSize ) ; for ( CHGraphImpl cg : getAllCHGraphs ( ) ) { cg . create ( byteCount ) ; } properties . put ( "graph.ch.weightings" , getNodeBasedCHWeightings ( ) . toString ( ) ) ; properties . put ( "graph.ch.edge.weightings" , getEdgeBasedCHWeightings ( ) . toString ( ) ) ; return this ; } | After configuring this storage you need to create it explicitly . |
31,524 | final void percolateDownMinHeap ( final int index ) { final int element = elements [ index ] ; final float key = keys [ index ] ; int hole = index ; while ( hole * 2 <= size ) { int child = hole * 2 ; if ( child != size && keys [ child + 1 ] < keys [ child ] ) { child ++ ; } if ( keys [ child ] >= key ) { break ; } elements [ hole ] = elements [ child ] ; keys [ hole ] = keys [ child ] ; hole = child ; } elements [ hole ] = element ; keys [ hole ] = key ; } | Percolates element down heap from the array position given by the index . |
31,525 | public int compareTo ( GTFSError o ) { if ( this . file == null && o . file != null ) return - 1 ; else if ( this . file != null && o . file == null ) return 1 ; int file = this . file == null && o . file == null ? 0 : String . CASE_INSENSITIVE_ORDER . compare ( this . file , o . file ) ; if ( file != 0 ) return file ; int errorType = String . CASE_INSENSITIVE_ORDER . compare ( this . errorType , o . errorType ) ; if ( errorType != 0 ) return errorType ; int affectedEntityId = this . affectedEntityId == null && o . affectedEntityId == null ? 0 : String . CASE_INSENSITIVE_ORDER . compare ( this . affectedEntityId , o . affectedEntityId ) ; if ( affectedEntityId != 0 ) return affectedEntityId ; else return Long . compare ( this . line , o . line ) ; } | must be comparable to put into mapdb |
31,526 | List < Transfer > getTransfersToStop ( String toStopId , String toRouteId ) { final List < Transfer > allInboundTransfers = transfersToStop . getOrDefault ( toStopId , Collections . emptyList ( ) ) ; final Map < String , List < Transfer > > byFromStop = allInboundTransfers . stream ( ) . filter ( t -> t . transfer_type == 0 || t . transfer_type == 2 ) . filter ( t -> t . to_route_id == null || toRouteId . equals ( t . to_route_id ) ) . collect ( Collectors . groupingBy ( t -> t . from_stop_id ) ) ; final List < Transfer > result = new ArrayList < > ( ) ; byFromStop . forEach ( ( fromStop , transfers ) -> { routesByStop . getOrDefault ( fromStop , Collections . emptySet ( ) ) . forEach ( fromRoute -> { final Transfer mostSpecificRule = findMostSpecificRule ( transfers , fromRoute , toRouteId ) ; final Transfer myRule = new Transfer ( ) ; myRule . to_route_id = toRouteId ; myRule . from_route_id = fromRoute ; myRule . to_stop_id = mostSpecificRule . to_stop_id ; myRule . from_stop_id = mostSpecificRule . from_stop_id ; myRule . transfer_type = mostSpecificRule . transfer_type ; myRule . min_transfer_time = mostSpecificRule . min_transfer_time ; myRule . from_trip_id = mostSpecificRule . from_trip_id ; myRule . to_trip_id = mostSpecificRule . to_trip_id ; result . add ( myRule ) ; } ) ; } ) ; return result ; } | So far only the route is supported . |
31,527 | private void downloadFile ( File downloadFile , String url ) throws IOException { if ( ! downloadFile . exists ( ) ) { int max = 3 ; for ( int trial = 0 ; trial < max ; trial ++ ) { try { downloader . downloadFile ( url , downloadFile . getAbsolutePath ( ) ) ; return ; } catch ( SocketTimeoutException ex ) { if ( trial >= max - 1 ) throw new RuntimeException ( ex ) ; try { Thread . sleep ( sleep ) ; } catch ( InterruptedException ignored ) { } } } } } | Download a file at the provided url and save it as the given downloadFile if the downloadFile does not exist . |
31,528 | public List < IntArrayList > findComponents ( ) { int nodes = graph . getNodes ( ) ; for ( int start = 0 ; start < nodes ; start ++ ) { if ( nodeIndex [ start ] == 0 && ! ignoreSet . contains ( start ) && ! graph . isNodeRemoved ( start ) ) strongConnect ( start ) ; } return components ; } | Find and return list of all strongly connected components in g . |
31,529 | public ElevationProvider setBaseURL ( String baseURL ) { String [ ] urls = baseURL . split ( ";" ) ; if ( urls . length != 2 ) { throw new IllegalArgumentException ( "The base url must consist of two urls separated by a ';'. The first for cgiar, the second for gmted" ) ; } srtmProvider . setBaseURL ( urls [ 0 ] ) ; globalProvider . setBaseURL ( urls [ 1 ] ) ; return this ; } | For the MultiSourceElevationProvider you have to specify the base URL separated by a ; . The first for cgiar the second for gmted . |
31,530 | public double calcTurnWeight ( int edgeFrom , int nodeVia , int edgeTo ) { long turnFlags = turnCostExt . getTurnCostFlags ( edgeFrom , nodeVia , edgeTo ) ; if ( turnCostEncoder . isTurnRestricted ( turnFlags ) ) return Double . POSITIVE_INFINITY ; return turnCostEncoder . getTurnCost ( turnFlags ) ; } | This method calculates the turn weight separately . |
31,531 | public boolean outgoingEdgesAreSlowerByFactor ( double factor ) { double tmpSpeed = getSpeed ( currentEdge ) ; double pathSpeed = getSpeed ( prevEdge ) ; if ( pathSpeed != tmpSpeed || pathSpeed < 1 ) { return false ; } double maxSurroundingSpeed = - 1 ; for ( EdgeIteratorState edge : allOutgoingEdges ) { tmpSpeed = getSpeed ( edge ) ; if ( tmpSpeed < 1 ) { return false ; } if ( tmpSpeed > maxSurroundingSpeed ) { maxSurroundingSpeed = tmpSpeed ; } } return maxSurroundingSpeed * factor < pathSpeed ; } | Checks if the outgoing edges are slower by the provided factor . If they are this indicates that we are staying on the prominent street that one would follow anyway . |
31,532 | public EdgeIteratorState getOtherContinue ( double prevLat , double prevLon , double prevOrientation ) { int tmpSign ; for ( EdgeIteratorState edge : allowedOutgoingEdges ) { GHPoint point = InstructionsHelper . getPointForOrientationCalculation ( edge , nodeAccess ) ; tmpSign = InstructionsHelper . calculateSign ( prevLat , prevLon , point . getLat ( ) , point . getLon ( ) , prevOrientation ) ; if ( Math . abs ( tmpSign ) <= 1 ) { return edge ; } } return null ; } | Returns an edge that has more or less in the same orientation as the prevEdge but is not the currentEdge . If there is one this indicates that we might need an instruction to help finding the correct edge out of the different choices . If there is none return null . |
31,533 | public boolean isLeavingCurrentStreet ( String prevName , String name ) { if ( InstructionsHelper . isNameSimilar ( name , prevName ) ) { return false ; } boolean checkFlag = currentEdge . getFlags ( ) != prevEdge . getFlags ( ) ; for ( EdgeIteratorState edge : allowedOutgoingEdges ) { String edgeName = edge . getName ( ) ; IntsRef edgeFlag = edge . getFlags ( ) ; if ( isTheSameStreet ( prevName , prevEdge . getFlags ( ) , edgeName , edgeFlag , checkFlag ) || isTheSameStreet ( name , currentEdge . getFlags ( ) , edgeName , edgeFlag , checkFlag ) ) { return true ; } } return false ; } | If the name and prevName changes this method checks if either the current street is continued on a different edge or if the edge we are turning onto is continued on a different edge . If either of these properties is true we can be quite certain that a turn instruction should be provided . |
31,534 | public GHMRequest addPoint ( GHPoint point ) { fromPoints . add ( point ) ; toPoints . add ( point ) ; return this ; } | This methods adds the coordinate as from and to to the request . |
31,535 | public PrepareContractionHierarchies useFixedNodeOrdering ( NodeOrderingProvider nodeOrderingProvider ) { if ( nodeOrderingProvider . getNumNodes ( ) != prepareGraph . getNodes ( ) ) { throw new IllegalArgumentException ( "contraction order size (" + nodeOrderingProvider . getNumNodes ( ) + ")" + " must be equal to number of nodes in graph (" + prepareGraph . getNodes ( ) + ")." ) ; } this . nodeOrderingProvider = nodeOrderingProvider ; return this ; } | Instead of heuristically determining a node ordering for the graph contraction it is also possible to use a fixed ordering . For example this allows re - using a previously calculated node ordering . This will speed up CH preparation but might lead to slower queries . |
31,536 | public void findEdgesInShape ( final GHIntHashSet edgeIds , final Shape shape , EdgeFilter filter ) { GHPoint center = shape . getCenter ( ) ; QueryResult qr = locationIndex . findClosest ( center . getLat ( ) , center . getLon ( ) , filter ) ; if ( ! qr . isValid ( ) ) throw new IllegalArgumentException ( "Shape " + shape + " does not cover graph" ) ; if ( shape . contains ( qr . getSnappedPoint ( ) . lat , qr . getSnappedPoint ( ) . lon ) ) edgeIds . add ( qr . getClosestEdge ( ) . getEdge ( ) ) ; final boolean isPolygon = shape instanceof Polygon ; BreadthFirstSearch bfs = new BreadthFirstSearch ( ) { final NodeAccess na = graph . getNodeAccess ( ) ; final Shape localShape = shape ; protected boolean goFurther ( int nodeId ) { if ( isPolygon ) return isInsideBBox ( nodeId ) ; return localShape . contains ( na . getLatitude ( nodeId ) , na . getLongitude ( nodeId ) ) ; } protected boolean checkAdjacent ( EdgeIteratorState edge ) { int adjNodeId = edge . getAdjNode ( ) ; if ( localShape . contains ( na . getLatitude ( adjNodeId ) , na . getLongitude ( adjNodeId ) ) ) { edgeIds . add ( edge . getEdge ( ) ) ; return true ; } return isPolygon && isInsideBBox ( adjNodeId ) ; } private boolean isInsideBBox ( int nodeId ) { BBox bbox = localShape . getBounds ( ) ; double lat = na . getLatitude ( nodeId ) ; double lon = na . getLongitude ( nodeId ) ; return lat <= bbox . maxLat && lat >= bbox . minLat && lon <= bbox . maxLon && lon >= bbox . minLon ; } } ; bfs . start ( graph . createEdgeExplorer ( filter ) , qr . getClosestNode ( ) ) ; } | This method fills the edgeIds hash with edgeIds found inside the specified shape |
31,537 | public void fillEdgeIDs ( GHIntHashSet edgeIds , Geometry geometry , EdgeFilter filter ) { if ( geometry instanceof Point ) { GHPoint point = GHPoint . create ( ( Point ) geometry ) ; findClosestEdgeToPoint ( edgeIds , point , filter ) ; } else if ( geometry instanceof LineString ) { PointList pl = PointList . fromLineString ( ( LineString ) geometry ) ; int lastIdx = pl . size ( ) - 1 ; if ( pl . size ( ) >= 2 ) { double meanLat = ( pl . getLatitude ( 0 ) + pl . getLatitude ( lastIdx ) ) / 2 ; double meanLon = ( pl . getLongitude ( 0 ) + pl . getLongitude ( lastIdx ) ) / 2 ; findClosestEdge ( edgeIds , meanLat , meanLon , filter ) ; } } else if ( geometry instanceof MultiPoint ) { for ( Coordinate coordinate : geometry . getCoordinates ( ) ) { findClosestEdge ( edgeIds , coordinate . y , coordinate . x , filter ) ; } } } | This method fills the edgeIds hash with edgeIds found inside the specified geometry |
31,538 | public BlockArea parseBlockArea ( String blockAreaString , EdgeFilter filter , double useEdgeIdsUntilAreaSize ) { final String objectSeparator = ";" ; final String innerObjSep = "," ; BlockArea blockArea = new BlockArea ( graph ) ; if ( ! blockAreaString . isEmpty ( ) ) { String [ ] blockedCircularAreasArr = blockAreaString . split ( objectSeparator ) ; for ( int i = 0 ; i < blockedCircularAreasArr . length ; i ++ ) { String objectAsString = blockedCircularAreasArr [ i ] ; String [ ] splittedObject = objectAsString . split ( innerObjSep ) ; if ( splittedObject . length > 4 ) { final Polygon polygon = Polygon . parsePoints ( objectAsString , 0.003 ) ; findEdgesInShape ( blockArea . blockedEdges , polygon , filter ) ; } else if ( splittedObject . length == 4 ) { final BBox bbox = BBox . parseTwoPoints ( objectAsString ) ; if ( bbox . calculateArea ( ) > useEdgeIdsUntilAreaSize ) blockArea . add ( bbox ) ; else findEdgesInShape ( blockArea . blockedEdges , bbox , filter ) ; } else if ( splittedObject . length == 3 ) { double lat = Double . parseDouble ( splittedObject [ 0 ] ) ; double lon = Double . parseDouble ( splittedObject [ 1 ] ) ; int radius = Integer . parseInt ( splittedObject [ 2 ] ) ; Circle circle = new Circle ( lat , lon , radius ) ; if ( circle . calculateArea ( ) > useEdgeIdsUntilAreaSize ) { blockArea . add ( circle ) ; } else { findEdgesInShape ( blockArea . blockedEdges , circle , filter ) ; } } else if ( splittedObject . length == 2 ) { double lat = Double . parseDouble ( splittedObject [ 0 ] ) ; double lon = Double . parseDouble ( splittedObject [ 1 ] ) ; findClosestEdge ( blockArea . blockedEdges , lat , lon , filter ) ; } else { throw new IllegalArgumentException ( objectAsString + " at index " + i + " need to be defined as lat,lon " + "or as a circle lat,lon,radius or rectangular lat1,lon1,lat2,lon2" ) ; } } } return blockArea ; } | This method reads the blockAreaString and creates a Collection of Shapes or a set of found edges if area is small enough . |
31,539 | private boolean isBorderTile ( int xIndex , int yIndex , int ruleIndex ) { for ( int i = - 1 ; i < 2 ; i ++ ) { for ( int j = - 1 ; j < 2 ; j ++ ) { if ( i != xIndex && j != yIndex ) if ( ruleIndex != getRuleContainerIndex ( i , j ) ) return true ; } } return false ; } | Might fail for small holes that do not occur in the array |
31,540 | private int addRuleContainer ( SpatialRuleContainer container ) { int newIndex = this . ruleContainers . indexOf ( container ) ; if ( newIndex >= 0 ) return newIndex ; newIndex = ruleContainers . size ( ) ; if ( newIndex >= 255 ) throw new IllegalStateException ( "No more spatial rule container fit into this lookup as 255 combination of ruleContainers reached" ) ; this . ruleContainers . add ( container ) ; return newIndex ; } | This method adds the container if no such rule container exists in this lookup and returns the index otherwise . |
31,541 | public static DBContext onlineInstance ( String name ) { DB db = DBMaker . fileDB ( name ) . fileMmapEnableIfSupported ( ) . closeOnJvmShutdown ( ) . transactionEnable ( ) . make ( ) ; return new MapDBContext ( db ) ; } | This DB returned by this method does not trigger deletion on JVM shutdown . |
31,542 | public static DBContext offlineInstance ( String name ) { DB db = DBMaker . fileDB ( name ) . fileMmapEnableIfSupported ( ) . closeOnJvmShutdown ( ) . cleanerHackEnable ( ) . transactionEnable ( ) . fileDeleteAfterClose ( ) . make ( ) ; return new MapDBContext ( db ) ; } | This DB returned by this method gets deleted on JVM shutdown . |
31,543 | public BotSession registerBot ( LongPollingBot bot ) throws TelegramApiRequestException { bot . clearWebhook ( ) ; BotSession session = ApiContext . getInstance ( BotSession . class ) ; session . setToken ( bot . getBotToken ( ) ) ; session . setOptions ( bot . getOptions ( ) ) ; session . setCallback ( bot ) ; session . start ( ) ; return session ; } | Register a bot . The Bot Session is started immediately and may be disconnected by calling close . |
31,544 | public void registerBot ( WebhookBot bot ) throws TelegramApiRequestException { if ( useWebhook ) { webhook . registerWebhook ( bot ) ; bot . setWebhook ( externalUrl + bot . getBotPath ( ) , pathToCertificate ) ; } } | Register a bot in the api that will receive updates using webhook method |
31,545 | public final boolean executeCommand ( AbsSender absSender , Message message ) { if ( message . hasText ( ) ) { String text = message . getText ( ) ; if ( text . startsWith ( BotCommand . COMMAND_INIT_CHARACTER ) ) { String commandMessage = text . substring ( 1 ) ; String [ ] commandSplit = commandMessage . split ( BotCommand . COMMAND_PARAMETER_SEPARATOR_REGEXP ) ; String command = removeUsernameFromCommandIfNeeded ( commandSplit [ 0 ] ) ; if ( commandRegistryMap . containsKey ( command ) ) { String [ ] parameters = Arrays . copyOfRange ( commandSplit , 1 , commandSplit . length ) ; commandRegistryMap . get ( command ) . processMessage ( absSender , message , parameters ) ; return true ; } else if ( defaultConsumer != null ) { defaultConsumer . accept ( absSender , message ) ; return true ; } } } return false ; } | Executes a command action if the command is registered . |
31,546 | public void processMessage ( AbsSender absSender , Message message , String [ ] arguments ) { execute ( absSender , message . getFrom ( ) , message . getChat ( ) , message . getMessageId ( ) , arguments ) ; } | Process the message and execute the command |
31,547 | public final void execute ( AbsSender absSender , User user , Chat chat , String [ ] arguments ) { } | We ll override this method here for not repeating it in DefaultBotCommand s children |
31,548 | public final Message execute ( SendDocument sendDocument ) throws TelegramApiException { assertParamNotNull ( sendDocument , "sendDocument" ) ; sendDocument . validate ( ) ; try { String url = getBaseUrl ( ) + SendDocument . PATH ; HttpPost httppost = configuredHttpPost ( url ) ; MultipartEntityBuilder builder = MultipartEntityBuilder . create ( ) ; builder . setLaxMode ( ) ; builder . setCharset ( StandardCharsets . UTF_8 ) ; builder . addTextBody ( SendDocument . CHATID_FIELD , sendDocument . getChatId ( ) , TEXT_PLAIN_CONTENT_TYPE ) ; addInputFile ( builder , sendDocument . getDocument ( ) , SendDocument . DOCUMENT_FIELD , true ) ; if ( sendDocument . getReplyMarkup ( ) != null ) { builder . addTextBody ( SendDocument . REPLYMARKUP_FIELD , objectMapper . writeValueAsString ( sendDocument . getReplyMarkup ( ) ) , TEXT_PLAIN_CONTENT_TYPE ) ; } if ( sendDocument . getReplyToMessageId ( ) != null ) { builder . addTextBody ( SendDocument . REPLYTOMESSAGEID_FIELD , sendDocument . getReplyToMessageId ( ) . toString ( ) , TEXT_PLAIN_CONTENT_TYPE ) ; } if ( sendDocument . getCaption ( ) != null ) { builder . addTextBody ( SendDocument . CAPTION_FIELD , sendDocument . getCaption ( ) , TEXT_PLAIN_CONTENT_TYPE ) ; if ( sendDocument . getParseMode ( ) != null ) { builder . addTextBody ( SendDocument . PARSEMODE_FIELD , sendDocument . getParseMode ( ) , TEXT_PLAIN_CONTENT_TYPE ) ; } } if ( sendDocument . getDisableNotification ( ) != null ) { builder . addTextBody ( SendDocument . DISABLENOTIFICATION_FIELD , sendDocument . getDisableNotification ( ) . toString ( ) , TEXT_PLAIN_CONTENT_TYPE ) ; } if ( sendDocument . getThumb ( ) != null ) { addInputFile ( builder , sendDocument . getThumb ( ) , SendDocument . THUMB_FIELD , false ) ; builder . addTextBody ( SendDocument . THUMB_FIELD , sendDocument . getThumb ( ) . getAttachName ( ) , TEXT_PLAIN_CONTENT_TYPE ) ; } HttpEntity multipart = builder . build ( ) ; httppost . setEntity ( multipart ) ; return sendDocument . deserializeResponse ( sendHttpPostRequest ( httppost ) ) ; } catch ( IOException e ) { throw new TelegramApiException ( "Unable to send document" , e ) ; } } | Specific Send Requests |
31,549 | public static User getUser ( Update update ) { if ( MESSAGE . test ( update ) ) { return update . getMessage ( ) . getFrom ( ) ; } else if ( CALLBACK_QUERY . test ( update ) ) { return update . getCallbackQuery ( ) . getFrom ( ) ; } else if ( INLINE_QUERY . test ( update ) ) { return update . getInlineQuery ( ) . getFrom ( ) ; } else if ( CHANNEL_POST . test ( update ) ) { return update . getChannelPost ( ) . getFrom ( ) ; } else if ( EDITED_CHANNEL_POST . test ( update ) ) { return update . getEditedChannelPost ( ) . getFrom ( ) ; } else if ( EDITED_MESSAGE . test ( update ) ) { return update . getEditedMessage ( ) . getFrom ( ) ; } else if ( CHOSEN_INLINE_QUERY . test ( update ) ) { return update . getChosenInlineQuery ( ) . getFrom ( ) ; } else { throw new IllegalStateException ( "Could not retrieve originating user from update" ) ; } } | Fetches the user who caused the update . |
31,550 | public static boolean isGroupUpdate ( Update update ) { if ( MESSAGE . test ( update ) ) { return update . getMessage ( ) . isGroupMessage ( ) ; } else if ( CALLBACK_QUERY . test ( update ) ) { return update . getCallbackQuery ( ) . getMessage ( ) . isGroupMessage ( ) ; } else if ( CHANNEL_POST . test ( update ) ) { return update . getChannelPost ( ) . isGroupMessage ( ) ; } else if ( EDITED_CHANNEL_POST . test ( update ) ) { return update . getEditedChannelPost ( ) . isGroupMessage ( ) ; } else if ( EDITED_MESSAGE . test ( update ) ) { return update . getEditedMessage ( ) . isGroupMessage ( ) ; } else { return false ; } } | A best - effort boolean stating whether the update is a group message or not . |
31,551 | public static boolean isSuperGroupUpdate ( Update update ) { if ( MESSAGE . test ( update ) ) { return update . getMessage ( ) . isSuperGroupMessage ( ) ; } else if ( CALLBACK_QUERY . test ( update ) ) { return update . getCallbackQuery ( ) . getMessage ( ) . isSuperGroupMessage ( ) ; } else if ( CHANNEL_POST . test ( update ) ) { return update . getChannelPost ( ) . isSuperGroupMessage ( ) ; } else if ( EDITED_CHANNEL_POST . test ( update ) ) { return update . getEditedChannelPost ( ) . isSuperGroupMessage ( ) ; } else if ( EDITED_MESSAGE . test ( update ) ) { return update . getEditedMessage ( ) . isSuperGroupMessage ( ) ; } else { return false ; } } | A best - effort boolean stating whether the update is a super - group message or not . |
31,552 | public static Long getChatId ( Update update ) { if ( MESSAGE . test ( update ) ) { return update . getMessage ( ) . getChatId ( ) ; } else if ( CALLBACK_QUERY . test ( update ) ) { return update . getCallbackQuery ( ) . getMessage ( ) . getChatId ( ) ; } else if ( INLINE_QUERY . test ( update ) ) { return ( long ) update . getInlineQuery ( ) . getFrom ( ) . getId ( ) ; } else if ( CHANNEL_POST . test ( update ) ) { return update . getChannelPost ( ) . getChatId ( ) ; } else if ( EDITED_CHANNEL_POST . test ( update ) ) { return update . getEditedChannelPost ( ) . getChatId ( ) ; } else if ( EDITED_MESSAGE . test ( update ) ) { return update . getEditedMessage ( ) . getChatId ( ) ; } else if ( CHOSEN_INLINE_QUERY . test ( update ) ) { return ( long ) update . getChosenInlineQuery ( ) . getFrom ( ) . getId ( ) ; } else { throw new IllegalStateException ( "Could not retrieve originating chat ID from update" ) ; } } | Fetches the direct chat ID of the specified update . |
31,553 | public static String fullName ( User user ) { StringJoiner name = new StringJoiner ( " " ) ; if ( ! isEmpty ( user . getFirstName ( ) ) ) name . add ( user . getFirstName ( ) ) ; if ( ! isEmpty ( user . getLastName ( ) ) ) name . add ( user . getLastName ( ) ) ; return name . toString ( ) ; } | The full name is identified as the concatenation of the first and last name separated by a space . This method can return an empty name if both first and last name are empty . |
31,554 | public SendAudio setAudio ( File file ) { Objects . requireNonNull ( file , "file cannot be null!" ) ; this . audio = new InputFile ( file , file . getName ( ) ) ; return this ; } | Use this method to set the audio to a new file |
31,555 | protected User getUser ( String username ) { Integer id = userIds ( ) . get ( username . toLowerCase ( ) ) ; if ( id == null ) { throw new IllegalStateException ( format ( "Could not find ID corresponding to username [%s]" , username ) ) ; } return getUser ( id ) ; } | Gets the user with the specified username . |
31,556 | protected User getUser ( int id ) { User user = users ( ) . get ( id ) ; if ( user == null ) { throw new IllegalStateException ( format ( "Could not find user corresponding to id [%d]" , id ) ) ; } return user ; } | Gets the user with the specified ID . |
31,557 | protected int getUserIdSendError ( String username , MessageContext ctx ) { try { return getUser ( username ) . getId ( ) ; } catch ( IllegalStateException ex ) { silent . send ( getLocalizedMessage ( USER_NOT_FOUND , ctx . user ( ) . getLanguageCode ( ) , username ) , ctx . chatId ( ) ) ; throw propagate ( ex ) ; } } | Gets the user with the specified username . If user was not found the bot will send a message on Telegram . |
31,558 | public < T extends Serializable , Method extends BotApiMethod < T > , Callback extends SentCallback < T > > void executeAsync ( Method method , Callback callback ) throws TelegramApiException { if ( method == null ) { throw new TelegramApiException ( "Parameter method can not be null" ) ; } if ( callback == null ) { throw new TelegramApiException ( "Parameter callback can not be null" ) ; } sendApiMethodAsync ( method , callback ) ; } | General methods to execute BotApiMethods |
31,559 | public final void getMeAsync ( SentCallback < User > sentCallback ) throws TelegramApiException { if ( sentCallback == null ) { throw new TelegramApiException ( "Parameter sentCallback can not be null" ) ; } sendApiMethodAsync ( new GetMe ( ) , sentCallback ) ; } | Send Requests Async |
31,560 | public SendDocument setDocument ( File file ) { Objects . requireNonNull ( file , "documentName cannot be null!" ) ; this . document = new InputFile ( file , file . getName ( ) ) ; return this ; } | Use this method to set the document to a new file |
31,561 | public void setMethods ( Set < String > methods ) { this . methods = new HashSet < > ( ) ; for ( String method : methods ) { this . methods . add ( method . toUpperCase ( ) ) ; } } | The filter fails on requests that don t have one of these HTTP methods . |
31,562 | public Map < String , String > getAdditionalAuthorizationAttributes ( String authoritiesJson ) { if ( StringUtils . hasLength ( authoritiesJson ) ) { try { Map < String , Object > authorities = JsonUtils . readValue ( authoritiesJson , new TypeReference < Map < String , Object > > ( ) { } ) ; Object az_attr = authorities . get ( "az_attr" ) ; if ( az_attr == null ) return null ; Map < String , String > additionalAuthorizationAttributes = JsonUtils . readValue ( JsonUtils . writeValueAsBytes ( az_attr ) , new TypeReference < Map < String , String > > ( ) { } ) ; return additionalAuthorizationAttributes ; } catch ( Throwable t ) { logger . error ( "Unable to read additionalAuthorizationAttributes" , t ) ; } } return null ; } | This method searches the authorities in the request for additionalAuthorizationAttributes and returns a map of these attributes that will later be added to the token |
31,563 | protected void addUser ( UaaUser user ) { ScimUser scimUser = getScimUser ( user ) ; if ( scimUser == null ) { if ( isEmpty ( user . getPassword ( ) ) && user . getOrigin ( ) . equals ( OriginKeys . UAA ) ) { logger . debug ( "User's password cannot be empty" ) ; throw new InvalidPasswordException ( "Password cannot be empty" , BAD_REQUEST ) ; } createNewUser ( user ) ; } else { if ( override ) { updateUser ( scimUser , user ) ; } else { logger . debug ( "Override flag not set. Not registering existing user: " + user ) ; } } } | Add a user account from the properties provided . |
31,564 | private ScimUser convertToScimUser ( UaaUser user ) { ScimUser scim = new ScimUser ( user . getId ( ) , user . getUsername ( ) , user . getGivenName ( ) , user . getFamilyName ( ) ) ; scim . addPhoneNumber ( user . getPhoneNumber ( ) ) ; scim . addEmail ( user . getEmail ( ) ) ; scim . setOrigin ( user . getOrigin ( ) ) ; scim . setExternalId ( user . getExternalId ( ) ) ; scim . setVerified ( user . isVerified ( ) ) ; return scim ; } | Convert UaaUser to SCIM data . |
31,565 | private Collection < String > convertToGroups ( List < ? extends GrantedAuthority > authorities ) { List < String > groups = new ArrayList < String > ( ) ; for ( GrantedAuthority authority : authorities ) { groups . add ( authority . getAuthority ( ) ) ; } return groups ; } | Convert authorities to group names . |
31,566 | private int sequentialFailureCount ( List < AuditEvent > events ) { int failureCount = 0 ; for ( AuditEvent event : events ) { if ( event . getType ( ) == failureEventType ) { failureCount ++ ; } else if ( event . getType ( ) == successEventType ) { break ; } } return failureCount ; } | Counts the number of failures that occurred without an intervening successful login . |
31,567 | protected boolean isXhrRequest ( final HttpServletRequest request ) { if ( StringUtils . hasText ( request . getHeader ( X_REQUESTED_WITH ) ) ) { return true ; } String accessControlRequestHeaders = request . getHeader ( ACCESS_CONTROL_REQUEST_HEADERS ) ; return StringUtils . hasText ( accessControlRequestHeaders ) && containsHeader ( accessControlRequestHeaders , X_REQUESTED_WITH ) ; } | Returns true if we believe this is an XHR request We look for the presence of the X - Requested - With header or that the X - Requested - With header is listed as a value in the Access - Control - Request - Headers header . |
31,568 | protected final void addPropertyAlias ( String alias , Class < ? > type , String name ) { Map < String , Property > typeMap = properties . get ( type ) ; if ( typeMap == null ) { typeMap = new HashMap < String , Property > ( ) ; properties . put ( type , typeMap ) ; } try { typeMap . put ( alias , propertyUtils . getProperty ( type , name ) ) ; } catch ( IntrospectionException e ) { throw new RuntimeException ( e ) ; } } | Adds an alias for a Javabean property name on a particular type . The values of YAML keys with the alias name will be mapped to the Javabean property . |
31,569 | public OAuth2AccessToken readAccessToken ( String accessToken ) { TokenValidation tokenValidation = tokenValidationService . validateToken ( accessToken , true ) . checkJti ( ) ; Map < String , Object > claims = tokenValidation . getClaims ( ) ; accessToken = tokenValidation . getJwt ( ) . getEncoded ( ) ; CompositeToken token = new CompositeToken ( accessToken ) ; token . setTokenType ( OAuth2AccessToken . BEARER_TYPE ) ; token . setExpiration ( new Date ( Long . valueOf ( claims . get ( EXP ) . toString ( ) ) * 1000L ) ) ; @ SuppressWarnings ( "unchecked" ) ArrayList < String > scopes = ( ArrayList < String > ) claims . get ( SCOPE ) ; if ( null != scopes && scopes . size ( ) > 0 ) { token . setScope ( new HashSet < > ( scopes ) ) ; } String clientId = ( String ) claims . get ( CID ) ; String userId = ( String ) claims . get ( USER_ID ) ; BaseClientDetails client = ( BaseClientDetails ) clientDetailsService . loadClientByClientId ( clientId , IdentityZoneHolder . get ( ) . getId ( ) ) ; if ( null != userId ) { @ SuppressWarnings ( "unchecked" ) ArrayList < String > tokenScopes = ( ArrayList < String > ) claims . get ( SCOPE ) ; approvalService . ensureRequiredApprovals ( userId , tokenScopes , ( String ) claims . get ( GRANT_TYPE ) , client ) ; } return token ; } | This method is implemented to support older API calls that assume the presence of a token store |
31,570 | public void doFilter ( ServletRequest request , ServletResponse response , FilterChain chain ) throws IOException , ServletException { HttpServletRequest httpServletRequest = ( HttpServletRequest ) request ; for ( String path : mediaTypes . keySet ( ) ) { if ( matches ( httpServletRequest , path ) ) { response . setContentType ( mediaTypes . get ( path ) ) ; break ; } } chain . doFilter ( request , response ) ; } | Add a content type header to any request whose path matches one of the supplied paths . |
31,571 | protected boolean isRefreshTokenSupported ( String grantType , Set < String > scope ) { if ( ! isRestrictRefreshGrant ) { return GRANT_TYPE_AUTHORIZATION_CODE . equals ( grantType ) || GRANT_TYPE_PASSWORD . equals ( grantType ) || GRANT_TYPE_USER_TOKEN . equals ( grantType ) || GRANT_TYPE_REFRESH_TOKEN . equals ( grantType ) || GRANT_TYPE_SAML2_BEARER . equals ( grantType ) ; } else { return scope . contains ( UAA_REFRESH_TOKEN ) ; } } | Check the current authorization request to indicate whether a refresh token should be issued or not . |
31,572 | protected void processMetadataInitialization ( HttpServletRequest request ) throws ServletException { if ( manager . getHostedIdpName ( ) == null ) { synchronized ( IdpMetadataManager . class ) { if ( manager . getHostedIdpName ( ) == null ) { try { log . info ( "No default metadata configured, generating with default values, please pre-configure metadata for production use" ) ; String alias = generator . getEntityAlias ( ) ; String baseURL = getDefaultBaseURL ( request ) ; if ( generator . getEntityBaseURL ( ) == null ) { log . warn ( "Generated default entity base URL {} based on values in the first server request. Please set property entityBaseURL on MetadataGenerator bean to fixate the value." , baseURL ) ; generator . setEntityBaseURL ( baseURL ) ; } else { baseURL = generator . getEntityBaseURL ( ) ; } if ( generator . getEntityId ( ) == null ) { generator . setEntityId ( getDefaultEntityID ( baseURL , alias ) ) ; } Collection < String > supportedNameID = Arrays . asList ( NameIDType . EMAIL , NameIDType . PERSISTENT , NameIDType . UNSPECIFIED ) ; generator . setNameID ( supportedNameID ) ; EntityDescriptor descriptor = generator . generateMetadata ( ) ; ExtendedMetadata extendedMetadata = generator . generateExtendedMetadata ( ) ; log . info ( "Created default metadata for system with entityID: " + descriptor . getEntityID ( ) ) ; MetadataMemoryProvider memoryProvider = new MetadataMemoryProvider ( descriptor ) ; memoryProvider . initialize ( ) ; MetadataProvider metadataProvider = new ExtendedMetadataDelegate ( memoryProvider , extendedMetadata ) ; manager . addMetadataProvider ( metadataProvider ) ; manager . setHostedIdpName ( descriptor . getEntityID ( ) ) ; manager . refreshMetadata ( ) ; } catch ( MetadataProviderException e ) { log . error ( "Error generating system metadata" , e ) ; throw new ServletException ( "Error generating system metadata" , e ) ; } } } } } | Verifies whether generation is needed and if so the metadata document is created and stored in metadata manager . |
31,573 | public void afterPropertiesSet ( ) throws ServletException { super . afterPropertiesSet ( ) ; Assert . notNull ( generator , "Metadata generator" ) ; Assert . notNull ( manager , "MetadataManager must be set" ) ; } | Verifies that required entities were autowired or set . |
31,574 | private void updateAutoApproveClients ( ) { autoApproveClients . removeAll ( clientsToDelete ) ; for ( String clientId : autoApproveClients ) { try { BaseClientDetails base = ( BaseClientDetails ) clientRegistrationService . loadClientByClientId ( clientId , IdentityZone . getUaaZoneId ( ) ) ; base . addAdditionalInformation ( ClientConstants . AUTO_APPROVE , true ) ; logger . debug ( "Adding autoapprove flag to client: " + clientId ) ; clientRegistrationService . updateClientDetails ( base , IdentityZone . getUaaZoneId ( ) ) ; } catch ( NoSuchClientException n ) { logger . debug ( "Client not found, unable to set autoapprove: " + clientId ) ; } } } | Explicitly override autoapprove in all clients that were provided in the whitelist . |
31,575 | protected boolean isEndpointSupported ( SingleSignOnService endpoint ) throws MetadataProviderException { return SAML2_POST_BINDING_URI . equals ( endpoint . getBinding ( ) ) || SAML2_REDIRECT_BINDING_URI . equals ( endpoint . getBinding ( ) ) ; } | Determines whether given SingleSignOn service can be used together with this profile . Bindings POST Artifact and Redirect are supported for WebSSO . |
31,576 | public void setGroups ( Map < String , String > groups ) { if ( groups == null ) { groups = Collections . EMPTY_MAP ; } groups . entrySet ( ) . forEach ( e -> { if ( ! StringUtils . hasText ( e . getValue ( ) ) ) { e . setValue ( ( String ) getMessageSource ( ) . getProperty ( String . format ( messagePropertyNameTemplate , e . getKey ( ) ) ) ) ; } } ) ; this . configuredGroups = groups ; setCombinedGroups ( ) ; } | Specify the list of groups to create as a comma - separated list of group - names |
31,577 | protected Collection < String > mapAliases ( Collection < String > values ) { LinkedHashSet < String > result = new LinkedHashSet < String > ( ) ; for ( String value : values ) { String alias = aliases . get ( value ) ; if ( alias != null ) { result . add ( alias ) ; } else { log . warn ( "Unsupported value " + value + " found" ) ; } } return result ; } | Method iterates all values in the input for each tries to resolve correct alias . When alias value is found it is entered into the return collection otherwise warning is logged . Values are returned in order of input with all duplicities removed . |
31,578 | public void setBindingsSSO ( Collection < String > bindingsSSO ) { if ( bindingsSSO == null ) { this . bindingsSSO = Collections . emptyList ( ) ; } else { this . bindingsSSO = bindingsSSO ; } } | List of bindings to be included in the generated metadata for Web Single Sign - On . Ordering of bindings affects inclusion in the generated metadata . |
31,579 | public void setBindingsSLO ( Collection < String > bindingsSLO ) { if ( bindingsSLO == null ) { this . bindingsSLO = Collections . emptyList ( ) ; } else { this . bindingsSLO = bindingsSLO ; } } | List of bindings to be included in the generated metadata for Single Logout . Ordering of bindings affects inclusion in the generated metadata . |
31,580 | public void setBindingsHoKSSO ( Collection < String > bindingsHoKSSO ) { if ( bindingsHoKSSO == null ) { this . bindingsHoKSSO = Collections . emptyList ( ) ; } else { this . bindingsHoKSSO = bindingsHoKSSO ; } } | List of bindings to be included in the generated metadata for Web Single Sign - On Holder of Key . Ordering of bindings affects inclusion in the generated metadata . |
31,581 | protected String getDiscoveryURL ( String entityBaseURL , String entityAlias ) { if ( extendedMetadata != null && extendedMetadata . getIdpDiscoveryURL ( ) != null && extendedMetadata . getIdpDiscoveryURL ( ) . length ( ) > 0 ) { return extendedMetadata . getIdpDiscoveryURL ( ) ; } else { return getServerURL ( entityBaseURL , entityAlias , getSAMLDiscoveryPath ( ) ) ; } } | Provides set discovery request url or generates a default when none was provided . Primarily value set on extenedMetadata property idpDiscoveryURL is used when empty local property customDiscoveryURL is used when empty URL is automatically generated . |
31,582 | protected String getDiscoveryResponseURL ( String entityBaseURL , String entityAlias ) { if ( extendedMetadata != null && extendedMetadata . getIdpDiscoveryResponseURL ( ) != null && extendedMetadata . getIdpDiscoveryResponseURL ( ) . length ( ) > 0 ) { return extendedMetadata . getIdpDiscoveryResponseURL ( ) ; } else { Map < String , String > params = new HashMap < String , String > ( ) ; params . put ( SAMLEntryPoint . DISCOVERY_RESPONSE_PARAMETER , "true" ) ; return getServerURL ( entityBaseURL , entityAlias , getSAMLEntryPointPath ( ) , params ) ; } } | Provides set discovery response url or generates a default when none was provided . Primarily value set on extenedMetadata property idpDiscoveryResponseURL is used when empty local property customDiscoveryResponseURL is used when empty URL is automatically generated . |
31,583 | protected String getSigningKey ( ) { if ( extendedMetadata != null && extendedMetadata . getSigningKey ( ) != null ) { return extendedMetadata . getSigningKey ( ) ; } else { return keyManager . getDefaultCredentialName ( ) ; } } | Provides key used for signing from extended metadata . Uses default key when key is not specified . |
31,584 | protected String getEncryptionKey ( ) { if ( extendedMetadata != null && extendedMetadata . getEncryptionKey ( ) != null ) { return extendedMetadata . getEncryptionKey ( ) ; } else { return keyManager . getDefaultCredentialName ( ) ; } } | Provides key used for encryption from extended metadata . Uses default when key is not specified . |
31,585 | public static ExpiringCode getExpiringCode ( ExpiringCodeStore codeStore , String userId , String email , String clientId , String redirectUri , ExpiringCodeType intent , String currentZoneId ) { Assert . notNull ( codeStore , "codeStore must not be null" ) ; Assert . notNull ( userId , "userId must not be null" ) ; Assert . notNull ( email , "email must not be null" ) ; Assert . notNull ( intent , "intent must not be null" ) ; Map < String , String > codeData = new HashMap < > ( ) ; codeData . put ( "user_id" , userId ) ; codeData . put ( "email" , email ) ; codeData . put ( "client_id" , clientId ) ; if ( redirectUri != null ) { codeData . put ( "redirect_uri" , redirectUri ) ; } String codeDataString = JsonUtils . writeValueAsString ( codeData ) ; Timestamp expiresAt = new Timestamp ( System . currentTimeMillis ( ) + ( 60 * 60 * 1000 ) ) ; return codeStore . generateCode ( codeDataString , expiresAt , intent . name ( ) , currentZoneId ) ; } | Generates a 1 hour expiring code . |
31,586 | public static URL getVerificationURL ( ExpiringCode expiringCode , IdentityZone currentIdentityZone ) { String url = "" ; try { url = UaaUrlUtils . getUaaUrl ( "/verify_user" , true , currentIdentityZone ) ; if ( expiringCode != null ) { url += "?code=" + expiringCode . getCode ( ) ; } return new URL ( url ) ; } catch ( MalformedURLException mfue ) { logger . error ( String . format ( "Unexpected error creating user verification URL from %s" , url ) , mfue ) ; } throw new IllegalStateException ( ) ; } | Returns a verification URL that may be sent to a user . |
31,587 | public synchronized void validateSamlIdentityProviderDefinition ( SamlIdentityProviderDefinition providerDefinition ) throws MetadataProviderException { ExtendedMetadataDelegate added , deleted = null ; if ( providerDefinition == null ) { throw new NullPointerException ( ) ; } if ( ! hasText ( providerDefinition . getIdpEntityAlias ( ) ) ) { throw new NullPointerException ( "SAML IDP Alias must be set" ) ; } if ( ! hasText ( providerDefinition . getZoneId ( ) ) ) { throw new NullPointerException ( "IDP Zone Id must be set" ) ; } SamlIdentityProviderDefinition clone = providerDefinition . clone ( ) ; added = getExtendedMetadataDelegate ( clone ) ; String entityIDToBeAdded = ( ( ConfigMetadataProvider ) added . getDelegate ( ) ) . getEntityID ( ) ; if ( ! StringUtils . hasText ( entityIDToBeAdded ) ) { throw new MetadataProviderException ( "Emtpy entityID for SAML provider with zoneId:" + providerDefinition . getZoneId ( ) + " and origin:" + providerDefinition . getIdpEntityAlias ( ) ) ; } boolean entityIDexists = false ; for ( SamlIdentityProviderDefinition existing : getIdentityProviderDefinitions ( ) ) { ConfigMetadataProvider existingProvider = ( ConfigMetadataProvider ) getExtendedMetadataDelegate ( existing ) . getDelegate ( ) ; if ( entityIDToBeAdded . equals ( existingProvider . getEntityID ( ) ) && ! ( existing . getUniqueAlias ( ) . equals ( clone . getUniqueAlias ( ) ) ) ) { entityIDexists = true ; break ; } } if ( entityIDexists ) { throw new MetadataProviderException ( "Duplicate entity ID:" + entityIDToBeAdded ) ; } } | adds or replaces a SAML identity proviider |
31,588 | public boolean checkPasswordMatches ( String id , String password , String zoneId ) { String currentPassword ; try { currentPassword = jdbcTemplate . queryForObject ( READ_PASSWORD_SQL , new Object [ ] { id , zoneId } , new int [ ] { VARCHAR , VARCHAR } , String . class ) ; } catch ( IncorrectResultSizeDataAccessException e ) { throw new ScimResourceNotFoundException ( "User " + id + " does not exist" ) ; } return passwordEncoder . matches ( password , currentPassword ) ; } | Checks the existing password for a user |
31,589 | public void setUsernamePattern ( String usernamePattern ) { Assert . hasText ( usernamePattern , "Username pattern must not be empty" ) ; this . usernamePattern = Pattern . compile ( usernamePattern ) ; } | Sets the regular expression which will be used to validate the username . |
31,590 | public static < T > List < T > subList ( List < T > input , int startIndex , int count ) { int fromIndex = startIndex - 1 ; int toIndex = fromIndex + count ; if ( toIndex >= input . size ( ) ) { toIndex = input . size ( ) ; } if ( fromIndex >= toIndex ) { return Collections . emptyList ( ) ; } return input . subList ( fromIndex , toIndex ) ; } | Calculates the substring of a list based on a 1 based start index never exceeding the bounds of the list . |
31,591 | public void addAttributeMapping ( String key , Object value ) { attributeMappings . put ( key , value ) ; } | adds an attribute mapping where the key is known to the UAA and the value represents the attribute name on the IDP |
31,592 | protected InputStream getBase64DecodedMessage ( HTTPInTransport transport ) throws MessageDecodingException { log . debug ( "Getting Base64 encoded message from request" ) ; String encodedMessage = transport . getParameterValue ( "assertion" ) ; if ( DatatypeHelper . isEmpty ( encodedMessage ) ) { log . error ( "Request did not contain either a SAMLRequest or " + "SAMLResponse paramter. Invalid request for SAML 2 HTTP POST binding." ) ; throw new MessageDecodingException ( "No SAML message present in request" ) ; } log . trace ( "Base64 decoding SAML message:\n{}" , encodedMessage ) ; byte [ ] decodedBytes = org . apache . commons . codec . binary . Base64 . decodeBase64 ( encodedMessage . getBytes ( StandardCharsets . UTF_8 ) ) ; if ( decodedBytes == null ) { log . error ( "Unable to Base64 decode SAML message" ) ; throw new MessageDecodingException ( "Unable to Base64 decode SAML message" ) ; } log . trace ( "Decoded SAML message:\n{}" , new String ( decodedBytes ) ) ; return new ByteArrayInputStream ( decodedBytes ) ; } | Gets the Base64 encoded message from the request and decodes it . |
31,593 | public void addEmail ( String newEmail ) { Assert . hasText ( newEmail , "Attempted to add null or empty email string to user." ) ; if ( emails == null ) { emails = new ArrayList < > ( 1 ) ; } for ( Email email : emails ) { if ( email . value . equals ( newEmail ) ) { throw new IllegalArgumentException ( "Already contains email " + newEmail ) ; } } Email e = new Email ( ) ; e . setValue ( newEmail ) ; emails . add ( e ) ; } | Adds a new email address ignoring type and primary fields which we don t need yet |
31,594 | public void addPhoneNumber ( String newPhoneNumber ) { if ( newPhoneNumber == null || newPhoneNumber . trim ( ) . length ( ) == 0 ) { return ; } if ( phoneNumbers == null ) { phoneNumbers = new ArrayList < > ( 1 ) ; } for ( PhoneNumber phoneNumber : phoneNumbers ) { if ( phoneNumber . value . equals ( newPhoneNumber ) && phoneNumber . getType ( ) == null ) { throw new IllegalArgumentException ( "Already contains phoneNumber " + newPhoneNumber ) ; } } PhoneNumber number = new PhoneNumber ( ) ; number . setValue ( newPhoneNumber ) ; phoneNumbers . add ( number ) ; } | Adds a new phone number with null type . |
31,595 | List < String > wordList ( ) { List < String > words = new ArrayList < > ( ) ; if ( userName != null ) { words . add ( userName ) ; } if ( name != null ) { if ( name . givenName != null ) { words . add ( name . givenName ) ; } if ( name . familyName != null ) { words . add ( name . familyName ) ; } if ( nickName != null ) { words . add ( nickName ) ; } } if ( emails != null ) { for ( Email email : emails ) { words . add ( email . getValue ( ) ) ; } } return words ; } | Creates a word list from the user data for use in password checking implementations |
31,596 | private void addDescriptor ( List < String > result , EntityDescriptor descriptor ) throws MetadataProviderException { String entityID = descriptor . getEntityID ( ) ; log . debug ( "Found metadata EntityDescriptor with ID" , entityID ) ; result . add ( entityID ) ; } | Parses entityID from the descriptor and adds it to the result set . Signatures on all found entities are verified using the given policy and trust engine . |
31,597 | @ RequestMapping ( value = "/profile" , method = RequestMethod . GET ) public String get ( Authentication authentication , Model model ) { Map < String , List < DescribedApproval > > approvals = getCurrentApprovalsForUser ( getCurrentUserId ( ) ) ; Map < String , String > clientNames = getClientNames ( approvals ) ; model . addAttribute ( "clientnames" , clientNames ) ; model . addAttribute ( "approvals" , approvals ) ; model . addAttribute ( "isUaaManagedUser" , isUaaManagedUser ( authentication ) ) ; return "approvals" ; } | Display the current user s approvals |
31,598 | @ RequestMapping ( value = "/profile" , method = RequestMethod . POST ) public String post ( @ RequestParam ( required = false ) Collection < String > checkedScopes , @ RequestParam ( required = false ) String update , @ RequestParam ( required = false ) String delete , @ RequestParam ( required = false ) String clientId ) { String userId = getCurrentUserId ( ) ; if ( null != update ) { Map < String , List < DescribedApproval > > approvalsByClientId = getCurrentApprovalsForUser ( userId ) ; List < DescribedApproval > allApprovals = new ArrayList < > ( ) ; for ( List < DescribedApproval > clientApprovals : approvalsByClientId . values ( ) ) { allApprovals . addAll ( clientApprovals ) ; } if ( hasText ( clientId ) ) { allApprovals . removeIf ( da -> ! clientId . equals ( da . getClientId ( ) ) ) ; } for ( Approval approval : allApprovals ) { String namespacedScope = approval . getClientId ( ) + "-" + approval . getScope ( ) ; if ( checkedScopes != null && checkedScopes . contains ( namespacedScope ) ) { approval . setStatus ( Approval . ApprovalStatus . APPROVED ) ; } else { approval . setStatus ( Approval . ApprovalStatus . DENIED ) ; } } updateApprovals ( allApprovals ) ; } else if ( null != delete ) { deleteApprovalsForClient ( userId , clientId ) ; } return "redirect:profile" ; } | Handle form post for revoking chosen approvals |
31,599 | public void validateParameters ( Map < String , String > parameters , ClientDetails clientDetails ) { if ( parameters . containsKey ( "scope" ) ) { Set < String > validScope = clientDetails . getScope ( ) ; if ( GRANT_TYPE_CLIENT_CREDENTIALS . equals ( parameters . get ( "grant_type" ) ) ) { validScope = AuthorityUtils . authorityListToSet ( clientDetails . getAuthorities ( ) ) ; } Set < Pattern > validWildcards = constructWildcards ( validScope ) ; Set < String > scopes = OAuth2Utils . parseParameterList ( parameters . get ( "scope" ) ) ; for ( String scope : scopes ) { if ( ! matches ( validWildcards , scope ) ) { throw new InvalidScopeException ( scope + " is invalid. Please use a valid scope name in the request" ) ; } } } } | Apply UAA rules to validate the requested scopes scope . For client credentials grants the valid requested scopes are actually in the authorities of the client . |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.