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 ( curre... | 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 = fi... | 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 waySta... | 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 ( cr... | 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 ... | 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 . leng... | 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... | 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 * nodeEntryBy... | 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 Ed... | 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 , H... | 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 Weight... | 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 ( ... | 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... | 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 ( ) ; e... | 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... |
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 ... | 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 ... | 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 ; } ele... | 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 ;... | 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... | 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... | 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 ] ) ; glo... | 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 = get... | 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 ( pre... | 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 ... | 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 num... | 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 " + s... | 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 . fromLine... | 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 = blockAreaS... | 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 ... | 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... | 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 ( BotC... | 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 = Multip... | 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 ( ) . getFr... | 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 ) ) { re... | 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 ( ... | 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 ) upd... | 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 ) { th... | 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 = authoriti... | 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... | 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 ( ) ... | 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 ) && ... | 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 . getPr... | 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 ( ) ; CompositeTok... | 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 . setCon... | 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 ( grant... | 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 ... | 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 . addAdditionalInfor... | 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 ( messagePropertyNameTempl... | 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 +... | 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 ( entityBa... | 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 ... | 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" ) ; As... | 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 ... | 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 . getI... | 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 ( IncorrectResultSizeDataAccessExcept... | 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 ( ... | 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 ( "Reques... | 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 conta... | 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 ) ... | 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 != nul... | 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 ) ; mo... | 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 client... | 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... | 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.