idx int64 0 41.2k | question stringlengths 73 5.81k | target stringlengths 5 918 |
|---|---|---|
30,000 | @ OnClick ( R . id . iv_photo ) void onPhotoClicked ( ) { Toast . makeText ( getActivity ( ) , placeViewModel . getName ( ) , Toast . LENGTH_LONG ) . show ( ) ; } | Method triggered when the iv_photo widget is clicked . This method shows a toast with the place information . |
30,001 | @ OnClick ( R . id . iv_thumbnail ) void onThubmnailClicked ( ) { Toast . makeText ( getActivity ( ) , posterTitle , Toast . LENGTH_SHORT ) . show ( ) ; } | Method triggered when the iv_thumbnail widget is clicked . This method shows a toast with the poster information . |
30,002 | protected void updateRendererExtraValues ( EpisodeViewModel content , Renderer < EpisodeViewModel > renderer , int position ) { super . updateRendererExtraValues ( content , renderer , position ) ; EpisodeRenderer episodeRenderer = ( EpisodeRenderer ) renderer ; episodeRenderer . setPosition ( position ) ; } | Override method used to update the EpisodeRenderer position . |
30,003 | protected View inflate ( LayoutInflater layoutInflater , ViewGroup viewGroup ) { return layoutInflater . inflate ( R . layout . episode_row , viewGroup , false ) ; } | Inflate the layout associated to this renderer |
30,004 | protected void render ( ) { EpisodeViewModel episode = getContent ( ) ; episodeNumberTextView . setText ( String . format ( "%02d" , position + 1 ) ) ; episodeTitleTextView . setText ( episode . getTitle ( ) ) ; episodeDateTextView . setText ( episode . getPublishDate ( ) ) ; } | Render the EpisodeViewModel information . |
30,005 | protected void onSaveInstanceState ( Bundle outState ) { super . onSaveInstanceState ( outState ) ; saveDraggableState ( outState ) ; saveLastPlaceLoadedPosition ( outState ) ; } | Save the DraggablePanel state to restore it once the activity lifecycle be rebooted . |
30,006 | protected void onRestoreInstanceState ( Bundle savedInstanceState ) { super . onRestoreInstanceState ( savedInstanceState ) ; recoverDraggablePanelState ( savedInstanceState ) ; loadLastPlaceClicked ( savedInstanceState ) ; } | Restore the DraggablePanel state . |
30,007 | private void recoverDraggablePanelState ( Bundle savedInstanceState ) { final DraggableState draggableState = ( DraggableState ) savedInstanceState . getSerializable ( DRAGGABLE_PANEL_STATE ) ; if ( draggableState == null ) { draggablePanel . setVisibility ( View . GONE ) ; return ; } updateDraggablePanelStateDelayed ( draggableState ) ; } | Get the DraggablePanelState from the saved bundle modify the DraggablePanel visibility to GONE and apply the DraggablePanelState to recover the last graphic state . |
30,008 | private void saveDraggableState ( Bundle outState ) { DraggableState draggableState = null ; if ( draggablePanel . isMaximized ( ) ) { draggableState = DraggableState . MAXIMIZED ; } else if ( draggablePanel . isMinimized ( ) ) { draggableState = DraggableState . MINIMIZED ; } else if ( draggablePanel . isClosedAtLeft ( ) ) { draggableState = DraggableState . CLOSED_AT_LEFT ; } else if ( draggablePanel . isClosedAtRight ( ) ) { draggableState = DraggableState . CLOSED_AT_RIGHT ; } outState . putSerializable ( DRAGGABLE_PANEL_STATE , draggableState ) ; } | Keep a reference of the last DraggablePanelState . |
30,009 | private void initializeFragments ( ) { placeFragment = new PlaceFragment ( ) ; mapFragment = SupportMapFragment . newInstance ( new GoogleMapOptions ( ) . mapType ( GoogleMap . MAP_TYPE_SATELLITE ) ) ; Picasso . with ( this ) . load ( "http://www.hdiphonewallpapers.us/phone-wallpapers/iphone-4-wallpapers/" + "hd-iphone-3gs-wallpapers-496ios.jpg" ) . into ( drawerImageView ) ; } | Initialize PlaceFragment and SupportMapFragment . |
30,010 | private void initializeListView ( ) { placesListView . setAdapter ( placesAdapter ) ; placesListView . setOnItemClickListener ( new AdapterView . OnItemClickListener ( ) { public void onItemClick ( AdapterView < ? > adapterView , View view , int position , long id ) { lastLoadedPlacePosition = position ; showPlace ( position ) ; } } ) ; } | Initialize places ListView using placesAdapter and configure OnItemClickListener . |
30,011 | private void showPlace ( int position ) { draggablePanel . setVisibility ( View . VISIBLE ) ; draggablePanel . maximize ( ) ; PlaceViewModel placeViewModel = placesAdapter . getItem ( position ) ; placeFragment . showPlace ( placeViewModel ) ; mapFragment . getMap ( ) . clear ( ) ; LatLng latitudeLongitude = new LatLng ( placeViewModel . getLatitude ( ) , placeViewModel . getLongitude ( ) ) ; MarkerOptions marker = new MarkerOptions ( ) . position ( latitudeLongitude ) ; marker . title ( placeViewModel . getName ( ) ) ; marker . snippet ( placeViewModel . getLatitude ( ) + " , " + placeViewModel . getLongitude ( ) ) ; mapFragment . getMap ( ) . addMarker ( marker ) ; mapFragment . getMap ( ) . moveCamera ( CameraUpdateFactory . newLatLngZoom ( latitudeLongitude , ZOOM ) ) ; } | Show a place in PlaceFragment and SupportMapFragment and apply the maximize effect over the DraggablePanel . |
30,012 | private void initializeDraggablePanel ( ) { draggablePanel . setFragmentManager ( getSupportFragmentManager ( ) ) ; draggablePanel . setTopFragment ( placeFragment ) ; draggablePanel . setBottomFragment ( mapFragment ) ; TypedValue typedValue = new TypedValue ( ) ; getResources ( ) . getValue ( R . dimen . x_scale_factor , typedValue , true ) ; float xScaleFactor = typedValue . getFloat ( ) ; typedValue = new TypedValue ( ) ; getResources ( ) . getValue ( R . dimen . y_scale_factor , typedValue , true ) ; float yScaleFactor = typedValue . getFloat ( ) ; draggablePanel . setXScaleFactor ( xScaleFactor ) ; draggablePanel . setYScaleFactor ( yScaleFactor ) ; draggablePanel . setTopViewHeight ( getResources ( ) . getDimensionPixelSize ( R . dimen . top_fragment_height ) ) ; draggablePanel . setTopFragmentMarginRight ( getResources ( ) . getDimensionPixelSize ( R . dimen . top_fragment_margin ) ) ; draggablePanel . setTopFragmentMarginBottom ( getResources ( ) . getDimensionPixelSize ( R . dimen . top_fragment_margin ) ) ; draggablePanel . initializeView ( ) ; draggablePanel . setVisibility ( View . GONE ) ; } | Initialize the DraggablePanel with top and bottom Fragments and apply all the configuration . |
30,013 | public void setViewHeight ( int newHeight ) { if ( newHeight > 0 ) { originalHeight = newHeight ; RelativeLayout . LayoutParams layoutParams = ( RelativeLayout . LayoutParams ) view . getLayoutParams ( ) ; layoutParams . height = newHeight ; view . setLayoutParams ( layoutParams ) ; } } | Change view height using the LayoutParams of the view . |
30,014 | public void onCreate ( ) { super . onCreate ( ) ; MainModule mainModule = new MainModule ( this ) ; objectGraph = ObjectGraph . create ( mainModule ) ; objectGraph . inject ( this ) ; objectGraph . injectStatics ( ) ; } | Override method used to initialize the dependency container graph with the MainModule . |
30,015 | public static ExtensionClassLoader getInstance ( final File extension , final ClassLoader parent ) throws GuacamoleException { try { return AccessController . doPrivileged ( new PrivilegedExceptionAction < ExtensionClassLoader > ( ) { public ExtensionClassLoader run ( ) throws GuacamoleException { return new ExtensionClassLoader ( extension , parent ) ; } } ) ; } catch ( PrivilegedActionException e ) { throw ( GuacamoleException ) e . getException ( ) ; } } | Returns an instance of ExtensionClassLoader configured to load classes from the given extension . jar . If a necessary class cannot be found within the . jar the given parent ClassLoader is used . Calling this function multiple times will not affect previously - returned instances of ExtensionClassLoader . |
30,016 | private static URL getExtensionURL ( File extension ) throws GuacamoleException { if ( ! extension . isFile ( ) ) throw new GuacamoleException ( extension + " is not a file." ) ; try { return extension . toURI ( ) . toURL ( ) ; } catch ( MalformedURLException e ) { throw new GuacamoleServerException ( e ) ; } } | Returns a URL which points to the given extension . jar file . |
30,017 | @ Path ( "data/{dataSource}" ) public UserContextResource getUserContextResource ( @ PathParam ( "dataSource" ) String authProviderIdentifier ) throws GuacamoleException { UserContext userContext = session . getUserContext ( authProviderIdentifier ) ; return userContextResourceFactory . create ( userContext ) ; } | Retrieves a resource representing the UserContext associated with the AuthenticationProvider having the given identifier . |
30,018 | @ Path ( "ext/{dataSource}" ) public Object getExtensionResource ( @ PathParam ( "dataSource" ) String authProviderIdentifier ) throws GuacamoleException { UserContext userContext = session . getUserContext ( authProviderIdentifier ) ; Object resource = userContext . getResource ( ) ; if ( resource != null ) return resource ; throw new GuacamoleResourceNotFoundException ( "No such resource." ) ; } | Returns the arbitrary REST resource exposed by the UserContext associated with the AuthenticationProvider having the given identifier . |
30,019 | private String readResourceAsString ( Resource resource ) throws IOException { StringBuilder contents = new StringBuilder ( ) ; Reader reader = new InputStreamReader ( resource . asStream ( ) , "UTF-8" ) ; try { char buffer [ ] = new char [ 8192 ] ; int length ; while ( ( length = reader . read ( buffer ) ) != - 1 ) { contents . append ( buffer , 0 , length ) ; } } finally { reader . close ( ) ; } return contents . toString ( ) ; } | Reads the entire contents of the given resource as a String . The resource is assumed to be encoded in UTF - 8 . |
30,020 | public List < String > getPatches ( ) throws GuacamoleException { try { List < Resource > resources = patchResourceService . getPatchResources ( ) ; List < String > patches = new ArrayList < String > ( resources . size ( ) ) ; for ( Resource resource : resources ) { patches . add ( readResourceAsString ( resource ) ) ; } return patches ; } catch ( IOException e ) { throw new GuacamoleServerException ( "Unable to read HTML patches." , e ) ; } } | Returns a list of all available HTML patches in the order they should be applied . Each patch is raw HTML containing additional meta tags describing how and where the patch should be applied . |
30,021 | public String getParentIdentifier ( ) { String parentIdentifier = getModel ( ) . getParentIdentifier ( ) ; if ( parentIdentifier == null ) return RootConnectionGroup . IDENTIFIER ; return parentIdentifier ; } | Returns the identifier of the parent connection group which cannot be null . If the parent is the root connection group this will be RootConnectionGroup . IDENTIFIER . |
30,022 | public void setParentIdentifier ( String parentIdentifier ) { if ( parentIdentifier != null && parentIdentifier . equals ( RootConnectionGroup . IDENTIFIER ) ) parentIdentifier = null ; getModel ( ) . setParentIdentifier ( parentIdentifier ) ; } | Sets the identifier of the associated parent connection group . If the parent is the root connection group this should be RootConnectionGroup . IDENTIFIER . |
30,023 | private void updateRelatedObjectSet ( APIPatch . Operation operation , RelatedObjectSetPatch relatedObjectSetPatch , String identifier ) throws GuacamoleException { switch ( operation ) { case add : relatedObjectSetPatch . addObject ( identifier ) ; break ; case remove : relatedObjectSetPatch . removeObject ( identifier ) ; break ; default : throw new GuacamoleClientException ( "Unsupported patch operation: \"" + operation + "\"" ) ; } } | Updates the given RelatedObjectSetPatch by queuing an add or remove operation for the object having the given identifier based on the given patch operation . |
30,024 | public Map < String , ExternalType > getObjects ( @ QueryParam ( "permission" ) List < ObjectPermission . Type > permissions ) throws GuacamoleException { Permissions effective = userContext . self ( ) . getEffectivePermissions ( ) ; SystemPermissionSet systemPermissions = effective . getSystemPermissions ( ) ; boolean isAdmin = systemPermissions . hasPermission ( SystemPermission . Type . ADMINISTER ) ; Collection < String > identifiers = directory . getIdentifiers ( ) ; if ( ! isAdmin && permissions != null && ! permissions . isEmpty ( ) ) { ObjectPermissionSet objectPermissions = getObjectPermissions ( effective ) ; identifiers = objectPermissions . getAccessibleObjects ( permissions , identifiers ) ; } Map < String , ExternalType > apiObjects = new HashMap < String , ExternalType > ( ) ; for ( InternalType object : directory . getAll ( identifiers ) ) apiObjects . put ( object . getIdentifier ( ) , translator . toExternalObject ( object ) ) ; return apiObjects ; } | Returns a map of all objects available within this DirectoryResource filtering the returned map by the given permission if specified . |
30,025 | public ExternalType createObject ( ExternalType object ) throws GuacamoleException { if ( object == null ) throw new GuacamoleClientException ( "Data must be submitted when creating objects." ) ; translator . filterExternalObject ( userContext , object ) ; directory . add ( translator . toInternalObject ( object ) ) ; return object ; } | Creates a new object within the underlying Directory returning the object that was created . The identifier of the created object will be populated if applicable . |
30,026 | @ Path ( "{identifier}" ) public DirectoryObjectResource < InternalType , ExternalType > getObjectResource ( @ PathParam ( "identifier" ) String identifier ) throws GuacamoleException { InternalType object = directory . get ( identifier ) ; if ( object == null ) throw new GuacamoleResourceNotFoundException ( "Not found: \"" + identifier + "\"" ) ; return resourceFactory . create ( userContext , directory , object ) ; } | Retrieves an individual object returning a DirectoryObjectResource implementation which exposes operations available on that object . |
30,027 | public void put ( String identifier , ActiveConnectionRecord record ) { synchronized ( records ) { Set < ActiveConnectionRecord > connections = records . get ( identifier ) ; if ( connections == null ) { connections = Collections . synchronizedSet ( Collections . newSetFromMap ( new LinkedHashMap < ActiveConnectionRecord , Boolean > ( ) ) ) ; records . put ( identifier , connections ) ; } connections . add ( record ) ; } } | Stores the given connection record in the list of active connections associated with the object having the given identifier . |
30,028 | public void remove ( String identifier , ActiveConnectionRecord record ) { synchronized ( records ) { Set < ActiveConnectionRecord > connections = records . get ( identifier ) ; assert ( connections != null ) ; connections . remove ( record ) ; if ( connections . isEmpty ( ) ) records . remove ( identifier ) ; } } | Removes the given connection record from the list of active connections associated with the object having the given identifier . |
30,029 | public Collection < ActiveConnectionRecord > get ( String identifier ) { synchronized ( records ) { Collection < ActiveConnectionRecord > connections = records . get ( identifier ) ; if ( connections != null ) return Collections . unmodifiableCollection ( connections ) ; return Collections . < ActiveConnectionRecord > emptyList ( ) ; } } | Returns a collection of active connection records associated with the object having the given identifier . The collection will be sorted in insertion order . If there are no such connections an empty collection is returned . |
30,030 | public void init ( ModeledAuthenticatedUser currentUser , ActiveConnectionRecord activeConnectionRecord , boolean includeSensitiveInformation ) { super . init ( currentUser ) ; this . connectionRecord = activeConnectionRecord ; this . connection = activeConnectionRecord . getConnection ( ) ; this . sharingProfileIdentifier = activeConnectionRecord . getSharingProfileIdentifier ( ) ; this . identifier = activeConnectionRecord . getUUID ( ) . toString ( ) ; this . startDate = activeConnectionRecord . getStartDate ( ) ; if ( includeSensitiveInformation ) { this . remoteHost = activeConnectionRecord . getRemoteHost ( ) ; this . tunnel = activeConnectionRecord . getTunnel ( ) ; this . username = activeConnectionRecord . getUsername ( ) ; } } | Initializes this TrackedActiveConnection copying the data associated with the given active connection record . At a minimum the identifier of this active connection will be set the start date and the identifier of the associated connection will be copied . If requested sensitive information like the associated username will be copied as well . |
30,031 | public Map < String , UserGroup > getUserGroups ( LDAPConnection ldapConnection ) throws GuacamoleException { String groupBaseDN = confService . getGroupBaseDN ( ) ; if ( groupBaseDN == null ) return Collections . emptyMap ( ) ; Collection < String > attributes = confService . getGroupNameAttributes ( ) ; List < LDAPEntry > results = queryService . search ( ldapConnection , groupBaseDN , getGroupSearchFilter ( ) , attributes , null ) ; return queryService . asMap ( results , entry -> { String name = queryService . getIdentifier ( entry , attributes ) ; if ( name != null ) return new SimpleUserGroup ( name ) ; logger . debug ( "User group \"{}\" is missing a name attribute " + "and will be ignored." , entry . getDN ( ) ) ; return null ; } ) ; } | Returns all Guacamole user groups accessible to the user currently bound under the given LDAP connection . |
30,032 | public List < LDAPEntry > getParentUserGroupEntries ( LDAPConnection ldapConnection , String userDN ) throws GuacamoleException { String groupBaseDN = confService . getGroupBaseDN ( ) ; if ( groupBaseDN == null ) return Collections . emptyList ( ) ; return queryService . search ( ldapConnection , groupBaseDN , getGroupSearchFilter ( ) , Collections . singleton ( confService . getMemberAttribute ( ) ) , userDN ) ; } | Returns the LDAP entries representing all user groups that the given user is a member of . Only user groups which are readable by the current user will be retrieved . |
30,033 | public Set < String > getParentUserGroupIdentifiers ( LDAPConnection ldapConnection , String userDN ) throws GuacamoleException { Collection < String > attributes = confService . getGroupNameAttributes ( ) ; List < LDAPEntry > userGroups = getParentUserGroupEntries ( ldapConnection , userDN ) ; Set < String > identifiers = new HashSet < > ( userGroups . size ( ) ) ; userGroups . forEach ( entry -> { String name = queryService . getIdentifier ( entry , attributes ) ; if ( name != null ) identifiers . add ( name ) ; else logger . debug ( "User group \"{}\" is missing a name attribute " + "and will be ignored." , entry . getDN ( ) ) ; } ) ; return identifiers ; } | Returns the identifiers of all user groups that the given user is a member of . Only identifiers of user groups which are readable by the current user will be retrieved . |
30,034 | private AuthenticationProvider getAuthenticationProvider ( String identifier ) { for ( AuthenticationProvider authProvider : authProviders ) { if ( authProvider . getIdentifier ( ) . equals ( identifier ) ) return authProvider ; } return null ; } | Returns the AuthenticationProvider having the given identifier . If no such AuthenticationProvider has been loaded null is returned . |
30,035 | @ Path ( "{identifier}" ) public Object getExtensionResource ( @ PathParam ( "identifier" ) String identifier ) throws GuacamoleException { AuthenticationProvider authProvider = getAuthenticationProvider ( identifier ) ; if ( authProvider != null ) { Object resource = authProvider . getResource ( ) ; if ( resource != null ) return resource ; } throw new GuacamoleResourceNotFoundException ( "No such resource." ) ; } | Returns the arbitrary REST resource exposed by the AuthenticationProvider having the given identifier . |
30,036 | public void init ( AuthenticationProvider authProvider , RemoteAuthenticatedUser user ) { this . authProvider = authProvider ; this . connectionDirectory . init ( user ) ; this . rootGroup = new SharedRootConnectionGroup ( this ) ; this . self = new SharedUser ( user , this ) ; } | Creates a new SharedUserContext which provides access ONLY to the given user the SharedConnections associated with the share keys used by that user and an internal root connection group containing only those SharedConnections . |
30,037 | public String processUsername ( String token ) throws GuacamoleException { HttpsJwks jwks = new HttpsJwks ( confService . getJWKSEndpoint ( ) . toString ( ) ) ; HttpsJwksVerificationKeyResolver resolver = new HttpsJwksVerificationKeyResolver ( jwks ) ; JwtConsumer jwtConsumer = new JwtConsumerBuilder ( ) . setRequireExpirationTime ( ) . setMaxFutureValidityInMinutes ( confService . getMaxTokenValidity ( ) ) . setAllowedClockSkewInSeconds ( confService . getAllowedClockSkew ( ) ) . setRequireSubject ( ) . setExpectedIssuer ( confService . getIssuer ( ) ) . setExpectedAudience ( confService . getClientID ( ) ) . setVerificationKeyResolver ( resolver ) . build ( ) ; try { String usernameClaim = confService . getUsernameClaimType ( ) ; JwtClaims claims = jwtConsumer . processToClaims ( token ) ; String nonce = claims . getStringClaimValue ( "nonce" ) ; if ( nonce == null ) { logger . info ( "Rejected OpenID token without nonce." ) ; return null ; } if ( ! nonceService . isValid ( nonce ) ) { logger . debug ( "Rejected OpenID token with invalid/old nonce." ) ; return null ; } String username = claims . getStringClaimValue ( usernameClaim ) ; if ( username != null ) return username ; logger . warn ( "Username claim \"{}\" missing from token. Perhaps the " + "OpenID scope and/or username claim type are " + "misconfigured?" , usernameClaim ) ; } catch ( InvalidJwtException e ) { logger . info ( "Rejected invalid OpenID token: {}" , e . getMessage ( ) ) ; logger . debug ( "Invalid JWT received." , e ) ; } catch ( MalformedClaimException e ) { logger . info ( "Rejected OpenID token with malformed claim: {}" , e . getMessage ( ) ) ; logger . debug ( "Malformed claim within received JWT." , e ) ; } return null ; } | Validates and parses the given ID token returning the username contained therein as defined by the username claim type given in guacamole . properties . If the username claim type is missing or the ID token is invalid null is returned . |
30,038 | public Map < String , User > getUsers ( LDAPConnection ldapConnection ) throws GuacamoleException { Collection < String > attributes = confService . getUsernameAttributes ( ) ; List < LDAPEntry > results = queryService . search ( ldapConnection , confService . getUserBaseDN ( ) , confService . getUserSearchFilter ( ) , attributes , null ) ; return queryService . asMap ( results , entry -> { String username = queryService . getIdentifier ( entry , attributes ) ; if ( username == null ) { logger . warn ( "User \"{}\" is missing a username attribute " + "and will be ignored." , entry . getDN ( ) ) ; return null ; } return new SimpleUser ( username ) ; } ) ; } | Returns all Guacamole users accessible to the user currently bound under the given LDAP connection . |
30,039 | public List < String > getUserDNs ( LDAPConnection ldapConnection , String username ) throws GuacamoleException { List < LDAPEntry > results = queryService . search ( ldapConnection , confService . getUserBaseDN ( ) , confService . getUserSearchFilter ( ) , confService . getUsernameAttributes ( ) , username ) ; List < String > userDNs = new ArrayList < > ( results . size ( ) ) ; results . forEach ( entry -> userDNs . add ( entry . getDN ( ) ) ) ; return userDNs ; } | Returns a list of all DNs corresponding to the users having the given username . If multiple username attributes are defined or if uniqueness is not enforced across the username attribute it is possible that this will return multiple DNs . |
30,040 | private static void closeConnection ( Connection connection , int guacamoleStatusCode , int webSocketCode ) { connection . close ( webSocketCode , Integer . toString ( guacamoleStatusCode ) ) ; } | Sends the given numeric Guacamole and WebSocket status on the given WebSocket connection and closes the connection . |
30,041 | public int append ( char chunk [ ] , int offset , int length ) throws GuacamoleException { int charsParsed = 0 ; if ( elementCount == INSTRUCTION_MAX_ELEMENTS && state != State . COMPLETE ) { state = State . ERROR ; throw new GuacamoleServerException ( "Instruction contains too many elements." ) ; } if ( state == State . PARSING_LENGTH ) { int parsedLength = elementLength ; while ( charsParsed < length ) { char c = chunk [ offset + charsParsed ++ ] ; if ( c >= '0' && c <= '9' ) parsedLength = parsedLength * 10 + c - '0' ; else if ( c == '.' ) { state = State . PARSING_CONTENT ; break ; } else { state = State . ERROR ; throw new GuacamoleServerException ( "Non-numeric character in element length." ) ; } } if ( parsedLength > INSTRUCTION_MAX_LENGTH ) { state = State . ERROR ; throw new GuacamoleServerException ( "Instruction exceeds maximum length." ) ; } elementLength = parsedLength ; } if ( state == State . PARSING_CONTENT && charsParsed + elementLength + 1 <= length ) { String element = new String ( chunk , offset + charsParsed , elementLength ) ; charsParsed += elementLength ; elementLength = 0 ; char terminator = chunk [ offset + charsParsed ++ ] ; elements [ elementCount ++ ] = element ; if ( terminator == ';' ) { state = State . COMPLETE ; parsedInstruction = new GuacamoleInstruction ( elements [ 0 ] , Arrays . asList ( elements ) . subList ( 1 , elementCount ) ) ; } else if ( terminator == ',' ) state = State . PARSING_LENGTH ; else { state = State . ERROR ; throw new GuacamoleServerException ( "Element terminator of instruction was not ';' nor ','" ) ; } } return charsParsed ; } | Appends data from the given buffer to the current instruction . |
30,042 | private static Mac getMacInstance ( Mode mode , Key key ) throws InvalidKeyException { try { Mac hmac = Mac . getInstance ( mode . getAlgorithmName ( ) ) ; hmac . init ( key ) ; return hmac ; } catch ( NoSuchAlgorithmException e ) { throw new UnsupportedOperationException ( "Support for the HMAC " + "algorithm required for TOTP in " + mode + " mode is " + "missing." , e ) ; } } | Returns a new Mac instance which produces message authentication codes using the given secret key and the algorithm required by the given TOTP mode . |
30,043 | private byte [ ] getHMAC ( byte [ ] message ) { try { return getMacInstance ( mode , key ) . doFinal ( message ) ; } catch ( InvalidKeyException e ) { throw new IllegalStateException ( "Provided key became invalid after " + "passing validation." , e ) ; } } | Calculates the HMAC for the given message using the key and algorithm provided when this TOTPGenerator was created . |
30,044 | public static String parse ( String timeZone ) { if ( timeZone == null || timeZone . isEmpty ( ) ) return null ; return timeZone ; } | Parses the given string into a time zone ID string . As these strings are equivalent the only transformation currently performed by this function is to ensure that a blank time zone string is parsed into null . |
30,045 | @ Path ( "parameters" ) public Map < String , String > getParameters ( ) throws GuacamoleException { Permissions effective = userContext . self ( ) . getEffectivePermissions ( ) ; SystemPermissionSet systemPermissions = effective . getSystemPermissions ( ) ; ObjectPermissionSet sharingProfilePermissions = effective . getSharingProfilePermissions ( ) ; String identifier = sharingProfile . getIdentifier ( ) ; if ( ! systemPermissions . hasPermission ( SystemPermission . Type . ADMINISTER ) && ! sharingProfilePermissions . hasPermission ( ObjectPermission . Type . UPDATE , identifier ) ) throw new GuacamoleSecurityException ( "Permission to read sharing profile parameters denied." ) ; return sharingProfile . getParameters ( ) ; } | Retrieves the connection parameters associated with the SharingProfile exposed by this SharingProfile resource . |
30,046 | public boolean useCode ( String username , String code ) throws GuacamoleException { UsedCode usedCode = new UsedCode ( username , code ) ; for ( ; ; ) { long current = System . currentTimeMillis ( ) ; long invalidUntil = current + confService . getPeriod ( ) * 1000 * INVALID_INTERVAL ; Long expires = invalidCodes . putIfAbsent ( usedCode , invalidUntil ) ; if ( expires == null ) return true ; if ( expires > current ) return false ; invalidCodes . remove ( usedCode , expires ) ; } } | Attempts to mark the given code as used . The code MUST have already been validated against the user s secret key as this function only verifies whether the code has been previously used not whether it is actually valid . If the code has not previously been used the code is stored as having been used by the given user at the current time . |
30,047 | private static void handleUpstreamErrors ( GuacamoleInstruction instruction ) throws GuacamoleUpstreamException { List < String > args = instruction . getArgs ( ) ; if ( args . size ( ) < 2 ) { logger . debug ( "Received \"error\" instruction without status code." ) ; return ; } int statusCode ; try { statusCode = Integer . parseInt ( args . get ( 1 ) ) ; } catch ( NumberFormatException e ) { logger . debug ( "Received \"error\" instruction with non-numeric status code." , e ) ; return ; } GuacamoleStatus status = GuacamoleStatus . fromGuacamoleStatusCode ( statusCode ) ; if ( status == null ) { logger . debug ( "Received \"error\" instruction with unknown/invalid status code: {}" , statusCode ) ; return ; } switch ( status ) { case UPSTREAM_ERROR : throw new GuacamoleUpstreamException ( args . get ( 0 ) ) ; case UPSTREAM_NOT_FOUND : throw new GuacamoleUpstreamNotFoundException ( args . get ( 0 ) ) ; case UPSTREAM_TIMEOUT : throw new GuacamoleUpstreamTimeoutException ( args . get ( 0 ) ) ; case UPSTREAM_UNAVAILABLE : throw new GuacamoleUpstreamUnavailableException ( args . get ( 0 ) ) ; } } | Parses the given error instruction throwing an exception if the instruction represents an error from the upstream remote desktop . |
30,048 | private void init ( RemoteAuthenticatedUser user , ModeledConnectionGroup balancingGroup , ModeledConnection connection , ModeledSharingProfile sharingProfile ) { this . user = user ; this . balancingGroup = balancingGroup ; this . connection = connection ; this . sharingProfile = sharingProfile ; } | Initializes this connection record associating it with the given user connection balancing connection group and sharing profile . The given balancing connection group MUST be the connection group from which the given connection was chosen and the given sharing profile MUST be the sharing profile that was used to share access to the given connection . The start date of this connection record will be the time of its creation . |
30,049 | public void init ( RemoteAuthenticatedUser user , ModeledConnectionGroup balancingGroup , ModeledConnection connection ) { init ( user , balancingGroup , connection , null ) ; } | Initializes this connection record associating it with the given user connection and balancing connection group . The given balancing connection group MUST be the connection group from which the given connection was chosen . The start date of this connection record will be the time of its creation . |
30,050 | public void init ( RemoteAuthenticatedUser user , ActiveConnectionRecord activeConnection , ModeledSharingProfile sharingProfile ) { init ( user , null , activeConnection . getConnection ( ) , sharingProfile ) ; this . connectionID = activeConnection . getConnectionID ( ) ; } | Initializes this connection record associating it with the given user active connection and sharing profile . The given sharing profile MUST be the sharing profile that was used to share access to the given connection . The start date of this connection record will be the time of its creation . |
30,051 | public GuacamoleTunnel assignGuacamoleTunnel ( final GuacamoleSocket socket , String connectionID ) { this . tunnel = new AbstractGuacamoleTunnel ( ) { public GuacamoleSocket getSocket ( ) { return socket ; } public UUID getUUID ( ) { return uuid ; } } ; if ( isPrimaryConnection ( ) ) this . connectionID = connectionID ; return this . tunnel ; } | Associates a new GuacamoleTunnel with this connection record using the given socket . |
30,052 | public static String format ( Date time ) { DateFormat timeFormat = new SimpleDateFormat ( TimeField . FORMAT ) ; return time == null ? null : timeFormat . format ( time ) ; } | Converts the given time into a string which follows the format used by time fields . |
30,053 | public void init ( ModeledAuthenticatedUser currentUser , UserGroupModel model , boolean exposeRestrictedAttributes ) { super . init ( currentUser , model ) ; this . exposeRestrictedAttributes = exposeRestrictedAttributes ; } | Initializes this ModeledUserGroup associating it with the current authenticated user and populating it with data from the given user group model . |
30,054 | public String createSignedRequest ( AuthenticatedUser authenticatedUser ) throws GuacamoleException { DuoCookie cookie = new DuoCookie ( authenticatedUser . getIdentifier ( ) , confService . getIntegrationKey ( ) , DuoCookie . currentTimestamp ( ) + COOKIE_EXPIRATION_TIME ) ; SignedDuoCookie duoCookie = new SignedDuoCookie ( cookie , SignedDuoCookie . Type . DUO_REQUEST , confService . getSecretKey ( ) ) ; SignedDuoCookie appCookie = new SignedDuoCookie ( cookie , SignedDuoCookie . Type . APPLICATION , confService . getApplicationKey ( ) ) ; return duoCookie + ":" + appCookie ; } | Creates and signs a new request to verify the identity of the given user . This request may ultimately be sent to Duo resulting in a signed response from Duo if that verification succeeds . |
30,055 | private String getAuthenticationToken ( ) { String token = request . getParameter ( "token" ) ; if ( token != null && ! token . isEmpty ( ) ) return token ; return null ; } | Returns the authentication token that is in use in the current session if present or null if otherwise . |
30,056 | public void init ( ModeledAuthenticatedUser currentUser , ModeledPermissions < ? extends EntityModel > entity , Set < String > effectiveGroups ) { super . init ( currentUser ) ; this . entity = entity ; this . effectiveGroups = effectiveGroups ; } | Initializes this permission set with the current user and the entity to whom the permissions in this set are granted . |
30,057 | private GuacamoleConfiguration getGuacamoleConfiguration ( RemoteAuthenticatedUser user , ModeledConnection connection ) { GuacamoleConfiguration config = new GuacamoleConfiguration ( ) ; ConnectionModel model = connection . getModel ( ) ; config . setProtocol ( model . getProtocol ( ) ) ; Collection < ConnectionParameterModel > parameters = connectionParameterMapper . select ( connection . getIdentifier ( ) ) ; for ( ConnectionParameterModel parameter : parameters ) config . setParameter ( parameter . getName ( ) , parameter . getValue ( ) ) ; return config ; } | Returns a guacamole configuration containing the protocol and parameters from the given connection . If tokens are used in the connection parameter values credentials from the given user will be substituted appropriately . |
30,058 | private GuacamoleConfiguration getGuacamoleConfiguration ( RemoteAuthenticatedUser user , ModeledSharingProfile sharingProfile , String connectionID ) { GuacamoleConfiguration config = new GuacamoleConfiguration ( ) ; config . setConnectionID ( connectionID ) ; Collection < SharingProfileParameterModel > parameters = sharingProfileParameterMapper . select ( sharingProfile . getIdentifier ( ) ) ; for ( SharingProfileParameterModel parameter : parameters ) config . setParameter ( parameter . getName ( ) , parameter . getValue ( ) ) ; return config ; } | Returns a guacamole configuration which joins the active connection having the given ID using the provided sharing profile to restrict the access provided to the user accessing the shared connection . If tokens are used in the connection parameter values of the sharing profile credentials from the given user will be substituted appropriately . |
30,059 | private void saveConnectionRecord ( ActiveConnectionRecord record ) { ConnectionRecordModel recordModel = new ConnectionRecordModel ( ) ; recordModel . setUsername ( record . getUsername ( ) ) ; recordModel . setConnectionIdentifier ( record . getConnectionIdentifier ( ) ) ; recordModel . setConnectionName ( record . getConnectionName ( ) ) ; recordModel . setRemoteHost ( record . getRemoteHost ( ) ) ; recordModel . setSharingProfileIdentifier ( record . getSharingProfileIdentifier ( ) ) ; recordModel . setSharingProfileName ( record . getSharingProfileName ( ) ) ; recordModel . setStartDate ( record . getStartDate ( ) ) ; recordModel . setEndDate ( new Date ( ) ) ; connectionRecordMapper . insert ( recordModel ) ; } | Saves the given ActiveConnectionRecord to the database . The end date of the saved record will be populated with the current time . |
30,060 | private GuacamoleSocket getUnconfiguredGuacamoleSocket ( GuacamoleProxyConfiguration proxyConfig , Runnable socketClosedCallback ) throws GuacamoleException { switch ( proxyConfig . getEncryptionMethod ( ) ) { case SSL : return new ManagedSSLGuacamoleSocket ( proxyConfig . getHostname ( ) , proxyConfig . getPort ( ) , socketClosedCallback ) ; case NONE : return new ManagedInetGuacamoleSocket ( proxyConfig . getHostname ( ) , proxyConfig . getPort ( ) , socketClosedCallback ) ; } throw new GuacamoleServerException ( "Unimplemented encryption method." ) ; } | Returns an unconfigured GuacamoleSocket that is already connected to guacd as specified in guacamole . properties using SSL if necessary . |
30,061 | private Collection < String > getPreferredConnections ( ModeledAuthenticatedUser user , Collection < String > identifiers ) { for ( String identifier : identifiers ) { if ( user . isPreferredConnection ( identifier ) ) return Collections . singletonList ( identifier ) ; } return identifiers ; } | Filters the given collection of connection identifiers returning a new collection which contains only those identifiers which are preferred . If no connection identifiers within the given collection are preferred the collection is left untouched . |
30,062 | private List < ModeledConnection > getBalancedConnections ( ModeledAuthenticatedUser user , ModeledConnectionGroup connectionGroup ) { if ( connectionGroup . getType ( ) != ConnectionGroup . Type . BALANCING ) return Collections . < ModeledConnection > emptyList ( ) ; Collection < String > identifiers = connectionMapper . selectIdentifiersWithin ( connectionGroup . getIdentifier ( ) ) ; if ( identifiers . isEmpty ( ) ) return Collections . < ModeledConnection > emptyList ( ) ; if ( connectionGroup . isSessionAffinityEnabled ( ) ) identifiers = getPreferredConnections ( user , identifiers ) ; Collection < ConnectionModel > models = connectionMapper . select ( identifiers ) ; List < ModeledConnection > connections = new ArrayList < ModeledConnection > ( models . size ( ) ) ; for ( ConnectionModel model : models ) { ModeledConnection connection = connectionProvider . get ( ) ; connection . init ( user , model ) ; connections . add ( connection ) ; } return connections ; } | Returns a list of all balanced connections within a given connection group . If the connection group is not balancing or it contains no connections an empty list is returned . |
30,063 | public void init ( Credentials credentials , Map < String , String > tokens , Set < String > effectiveGroups ) { this . credentials = credentials ; this . tokens = Collections . unmodifiableMap ( tokens ) ; this . effectiveGroups = effectiveGroups ; setIdentifier ( credentials . getUsername ( ) ) ; } | Initializes this AuthenticatedUser with the given credentials connection parameter tokens . and set of effective user groups . |
30,064 | public static String fromAttribute ( String name ) { Matcher groupMatcher = LDAP_ATTRIBUTE_NAME_GROUPING . matcher ( name ) ; if ( ! groupMatcher . find ( ) ) return LDAP_ATTRIBUTE_TOKEN_PREFIX + name . toUpperCase ( ) ; StringBuilder builder = new StringBuilder ( LDAP_ATTRIBUTE_TOKEN_PREFIX ) ; builder . append ( groupMatcher . group ( 0 ) . toUpperCase ( ) ) ; while ( groupMatcher . find ( ) ) { builder . append ( "_" ) ; builder . append ( groupMatcher . group ( 0 ) . toUpperCase ( ) ) ; } return builder . toString ( ) ; } | Generates the name of the parameter token that should be populated with the value of the given LDAP attribute . The name of the LDAP attribute will automatically be transformed from CamelCase headlessCamelCase lowercase_with_underscores and mixes_ofBoth_Styles to consistent UPPERCASE_WITH_UNDERSCORES . Each returned attribute will be prefixed with LDAP_ . |
30,065 | public static GuacamoleConfiguration getConfiguration ( String uri ) throws GuacamoleException { URI qcUri ; try { qcUri = new URI ( uri ) ; if ( ! qcUri . isAbsolute ( ) ) throw new QuickConnectException ( "URI must be absolute." , "QUICKCONNECT.ERROR_NOT_ABSOLUTE_URI" ) ; } catch ( URISyntaxException e ) { throw new QuickConnectException ( "Invalid URI Syntax" , "QUICKCONNECT.ERROR_INVALID_URI" ) ; } String protocol = qcUri . getScheme ( ) ; String host = qcUri . getHost ( ) ; int port = qcUri . getPort ( ) ; String userInfo = qcUri . getUserInfo ( ) ; String query = qcUri . getQuery ( ) ; GuacamoleConfiguration qcConfig = new GuacamoleConfiguration ( ) ; if ( protocol != null && ! protocol . isEmpty ( ) ) qcConfig . setProtocol ( protocol ) ; else throw new QuickConnectException ( "No protocol specified." , "QUICKCONNECT.ERROR_NO_PROTOCOL" ) ; if ( port > 0 ) qcConfig . setParameter ( "port" , Integer . toString ( port ) ) ; if ( host != null && ! host . isEmpty ( ) ) qcConfig . setParameter ( "hostname" , host ) ; else throw new QuickConnectException ( "No host specified." , "QUICKCONNECT.ERROR_NO_HOST" ) ; if ( query != null && ! query . isEmpty ( ) ) { try { Map < String , String > queryParams = parseQueryString ( query ) ; if ( queryParams != null ) for ( Map . Entry < String , String > entry : queryParams . entrySet ( ) ) qcConfig . setParameter ( entry . getKey ( ) , entry . getValue ( ) ) ; } catch ( UnsupportedEncodingException e ) { throw new GuacamoleServerException ( "Unexpected lack of UTF-8 encoding support." , e ) ; } } if ( userInfo != null && ! userInfo . isEmpty ( ) ) { try { parseUserInfo ( userInfo , qcConfig ) ; } catch ( UnsupportedEncodingException e ) { throw new GuacamoleServerException ( "Unexpected lack of UTF-8 encoding support." , e ) ; } } return qcConfig ; } | Parse out a URI string and get a GuacamoleConfiguration from that string or an exception if the parsing fails . |
30,066 | public static void parseUserInfo ( String userInfo , GuacamoleConfiguration config ) throws UnsupportedEncodingException { Matcher userinfoMatcher = userinfoPattern . matcher ( userInfo ) ; if ( userinfoMatcher . matches ( ) ) { String username = userinfoMatcher . group ( USERNAME_GROUP ) ; String password = userinfoMatcher . group ( PASSWORD_GROUP ) ; if ( username != null && ! username . isEmpty ( ) ) config . setParameter ( "username" , URLDecoder . decode ( username , "UTF-8" ) ) ; if ( password != null && ! password . isEmpty ( ) ) config . setParameter ( "password" , URLDecoder . decode ( password , "UTF-8" ) ) ; } } | Parse the given string for username and password values and if values are present decode them and set them in the provided GuacamoleConfiguration object . |
30,067 | public static String getName ( GuacamoleConfiguration config ) throws GuacamoleException { if ( config == null ) return null ; String protocol = config . getProtocol ( ) ; String host = config . getParameter ( "hostname" ) ; String port = config . getParameter ( "port" ) ; String user = config . getParameter ( "username" ) ; StringBuilder name = new StringBuilder ( ) ; if ( protocol != null && ! protocol . isEmpty ( ) ) name . append ( protocol ) . append ( "://" ) ; if ( user != null && ! user . isEmpty ( ) ) name . append ( user ) . append ( "@" ) ; if ( host != null && ! host . isEmpty ( ) ) name . append ( host ) ; if ( port != null && ! port . isEmpty ( ) ) name . append ( ":" ) . append ( port ) ; name . append ( "/" ) ; return name . toString ( ) ; } | Given a GuacamoleConfiguration object generate a name for the configuration based on the protocol host user and port in the configuration and return the string value . |
30,068 | public void verifyAuthenticatedUser ( AuthenticatedUser authenticatedUser ) throws GuacamoleException { Credentials credentials = authenticatedUser . getCredentials ( ) ; HttpServletRequest request = credentials . getRequest ( ) ; if ( authenticatedUser . getIdentifier ( ) . equals ( AuthenticatedUser . ANONYMOUS_IDENTIFIER ) ) return ; String signedResponse = request . getParameter ( DuoSignedResponseField . PARAMETER_NAME ) ; if ( signedResponse == null ) { Field signedResponseField = new DuoSignedResponseField ( confService . getAPIHostname ( ) , duoService . createSignedRequest ( authenticatedUser ) ) ; CredentialsInfo expectedCredentials = new CredentialsInfo ( Collections . singletonList ( signedResponseField ) ) ; throw new GuacamoleInsufficientCredentialsException ( "LOGIN.INFO_DUO_AUTH_REQUIRED" , expectedCredentials ) ; } if ( ! duoService . isValidSignedResponse ( authenticatedUser , signedResponse ) ) throw new GuacamoleClientException ( "LOGIN.INFO_DUO_VALIDATION_CODE_INCORRECT" ) ; } | Verifies the identity of the given user via the Duo multi - factor authentication service . If a signed response from Duo has not already been provided a signed response from Duo is requested in the form of additional expected credentials . Any provided signed response is cryptographically verified . If no signed response is present or the signed response is invalid an exception is thrown . |
30,069 | private static String getHexString ( byte [ ] bytes ) { if ( bytes == null ) return null ; StringBuilder hex = new StringBuilder ( 2 * bytes . length ) ; for ( byte b : bytes ) { hex . append ( HEX_CHARS [ ( b & 0xF0 ) >> 4 ] ) . append ( HEX_CHARS [ b & 0x0F ] ) ; } return hex . toString ( ) ; } | Produces a String containing the bytes provided in hexadecimal notation . |
30,070 | protected boolean canUpdateModifiedParents ( ModeledAuthenticatedUser user , String identifier , ModelType model ) throws GuacamoleException { if ( user . getUser ( ) . isAdministrator ( ) ) return true ; Collection < String > modifiedParents = getModifiedParents ( user , identifier , model ) ; if ( ! modifiedParents . isEmpty ( ) ) { ObjectPermissionSet permissionSet = getParentEffectivePermissionSet ( user ) ; Collection < String > updateableParents = permissionSet . getAccessibleObjects ( Collections . singleton ( ObjectPermission . Type . UPDATE ) , modifiedParents ) ; return updateableParents . size ( ) == modifiedParents . size ( ) ; } return true ; } | Returns whether the given user has permission to modify the parents affected by the modifications made to the given model object . |
30,071 | private Map < String , Resource > getClassPathResources ( String mimetype , Collection < String > paths ) { if ( paths == null ) return Collections . < String , Resource > emptyMap ( ) ; Map < String , Resource > resources = new HashMap < String , Resource > ( paths . size ( ) ) ; for ( String path : paths ) resources . put ( path , new ClassPathResource ( classLoader , mimetype , path ) ) ; return Collections . unmodifiableMap ( resources ) ; } | Returns a new map of all resources corresponding to the collection of paths provided . Each resource will be associated with the given mimetype and stored in the map using its path as the key . |
30,072 | private Map < String , Resource > getClassPathResources ( Map < String , String > resourceTypes ) { if ( resourceTypes == null ) return Collections . < String , Resource > emptyMap ( ) ; Map < String , Resource > resources = new HashMap < String , Resource > ( resourceTypes . size ( ) ) ; for ( Map . Entry < String , String > resource : resourceTypes . entrySet ( ) ) { String path = resource . getKey ( ) ; String mimetype = resource . getValue ( ) ; resources . put ( path , new ClassPathResource ( classLoader , mimetype , path ) ) ; } return Collections . unmodifiableMap ( resources ) ; } | Returns a new map of all resources corresponding to the map of resource paths provided . Each resource will be associated with the mimetype stored in the given map using its path as the key . |
30,073 | @ SuppressWarnings ( "unchecked" ) private Class < AuthenticationProvider > getAuthenticationProviderClass ( String name ) throws GuacamoleException { try { Class < ? > authenticationProviderClass = classLoader . loadClass ( name ) ; if ( ! AuthenticationProvider . class . isAssignableFrom ( authenticationProviderClass ) ) throw new GuacamoleServerException ( "Authentication providers MUST extend the AuthenticationProvider class." ) ; return ( Class < AuthenticationProvider > ) authenticationProviderClass ; } catch ( ClassNotFoundException e ) { throw new GuacamoleException ( "Authentication provider class not found." , e ) ; } catch ( LinkageError e ) { throw new GuacamoleException ( "Authentication provider class cannot be loaded (wrong version of API?)." , e ) ; } } | Retrieve the AuthenticationProvider subclass having the given name . If the class having the given name does not exist or isn t actually a subclass of AuthenticationProvider an exception will be thrown . |
30,074 | private Collection < Class < AuthenticationProvider > > getAuthenticationProviderClasses ( Collection < String > names ) throws GuacamoleException { if ( names == null ) return Collections . < Class < AuthenticationProvider > > emptyList ( ) ; Collection < Class < AuthenticationProvider > > classes = new ArrayList < Class < AuthenticationProvider > > ( names . size ( ) ) ; for ( String name : names ) classes . add ( getAuthenticationProviderClass ( name ) ) ; return Collections . unmodifiableCollection ( classes ) ; } | Returns a new collection of all AuthenticationProvider subclasses having the given names . If any class does not exist or isn t actually a subclass of AuthenticationProvider an exception will be thrown and no further AuthenticationProvider classes will be loaded . |
30,075 | @ SuppressWarnings ( "unchecked" ) private Class < Listener > getListenerClass ( String name ) throws GuacamoleException { try { Class < ? > listenerClass = classLoader . loadClass ( name ) ; if ( ! Listener . class . isAssignableFrom ( listenerClass ) ) throw new GuacamoleServerException ( "Listeners MUST implement a Listener subclass." ) ; return ( Class < Listener > ) listenerClass ; } catch ( ClassNotFoundException e ) { throw new GuacamoleException ( "Listener class not found." , e ) ; } catch ( LinkageError e ) { throw new GuacamoleException ( "Listener class cannot be loaded (wrong version of API?)." , e ) ; } } | Retrieve the Listener subclass having the given name . If the class having the given name does not exist or isn t actually a subclass of Listener an exception will be thrown . |
30,076 | private Collection < Class < ? > > getListenerClasses ( Collection < String > names ) throws GuacamoleException { if ( names == null ) return Collections . < Class < ? > > emptyList ( ) ; Collection < Class < ? > > classes = new ArrayList < Class < ? > > ( names . size ( ) ) ; for ( String name : names ) classes . add ( getListenerClass ( name ) ) ; return Collections . unmodifiableCollection ( classes ) ; } | Returns a new collection of all Listener subclasses having the given names . If any class does not exist or isn t actually subclass of Listener an exception will be thrown an no further Listener classes will be loaded . |
30,077 | @ Path ( "connection" ) public DirectoryObjectResource < Connection , APIConnection > getConnection ( ) throws GuacamoleException { return connectionDirectoryResourceFactory . create ( userContext , userContext . getConnectionDirectory ( ) ) . getObjectResource ( activeConnection . getConnectionIdentifier ( ) ) ; } | Retrieves a resource representing the Connection object that is being actively used . |
30,078 | private void closeConnection ( Session session , int guacamoleStatusCode , int webSocketCode ) { try { String message = Integer . toString ( guacamoleStatusCode ) ; session . close ( new CloseStatus ( webSocketCode , message ) ) ; } catch ( IOException e ) { logger . debug ( "Unable to close WebSocket connection." , e ) ; } } | Sends the given numeric Guacamole and WebSocket status codes on the given WebSocket connection and closes the connection . |
30,079 | private UserTOTPKey getKey ( UserContext context , String username ) throws GuacamoleException { User self = context . self ( ) ; Map < String , String > attributes = context . self ( ) . getAttributes ( ) ; String secret = attributes . get ( TOTPUser . TOTP_KEY_SECRET_ATTRIBUTE_NAME ) ; if ( secret == null ) { TOTPGenerator . Mode mode = confService . getMode ( ) ; UserTOTPKey generated = new UserTOTPKey ( username , mode . getRecommendedKeyLength ( ) ) ; if ( setKey ( context , generated ) ) return generated ; return null ; } byte [ ] key ; try { key = BASE32 . decode ( secret ) ; } catch ( IllegalArgumentException e ) { logger . warn ( "TOTP key of user \"{}\" is not valid base32." , self . getIdentifier ( ) ) ; logger . debug ( "TOTP key is not valid base32." , e ) ; return null ; } boolean confirmed = "true" . equals ( attributes . get ( TOTPUser . TOTP_KEY_CONFIRMED_ATTRIBUTE_NAME ) ) ; return new UserTOTPKey ( username , key , confirmed ) ; } | Retrieves and decodes the base32 - encoded TOTP key associated with user having the given UserContext . If no TOTP key is associated with the user a random key is generated and associated with the user . If the extension storing the user does not support storage of the TOTP key null is returned . |
30,080 | private boolean setKey ( UserContext context , UserTOTPKey key ) throws GuacamoleException { User self = context . self ( ) ; Map < String , String > attributes = new HashMap < String , String > ( ) ; attributes . put ( TOTPUser . TOTP_KEY_SECRET_ATTRIBUTE_NAME , BASE32 . encode ( key . getSecret ( ) ) ) ; attributes . put ( TOTPUser . TOTP_KEY_CONFIRMED_ATTRIBUTE_NAME , key . isConfirmed ( ) ? "true" : "false" ) ; self . setAttributes ( attributes ) ; Map < String , String > setAttributes = self . getAttributes ( ) ; if ( ! setAttributes . containsKey ( TOTPUser . TOTP_KEY_SECRET_ATTRIBUTE_NAME ) || ! setAttributes . containsKey ( TOTPUser . TOTP_KEY_CONFIRMED_ATTRIBUTE_NAME ) ) return false ; try { context . getUserDirectory ( ) . update ( self ) ; } catch ( GuacamoleSecurityException e ) { logger . info ( "User \"{}\" cannot store their TOTP key as they " + "lack permission to update their own account. TOTP " + "will be disabled for this user." , self . getIdentifier ( ) ) ; logger . debug ( "Permission denied to set TOTP key of user " + "account." , e ) ; return false ; } catch ( GuacamoleUnsupportedException e ) { logger . debug ( "Extension storage for user is explicitly read-only. " + "Cannot update attributes to store TOTP key." , e ) ; return false ; } return true ; } | Attempts to store the given TOTP key within the user account of the user having the given UserContext . As not all extensions will support storage of arbitrary attributes this operation may fail . |
30,081 | public void verifyIdentity ( UserContext context , AuthenticatedUser authenticatedUser ) throws GuacamoleException { String username = authenticatedUser . getIdentifier ( ) ; if ( username . equals ( AuthenticatedUser . ANONYMOUS_IDENTIFIER ) ) return ; UserTOTPKey key = getKey ( context , username ) ; if ( key == null ) return ; Credentials credentials = authenticatedUser . getCredentials ( ) ; HttpServletRequest request = credentials . getRequest ( ) ; String code = request . getParameter ( AuthenticationCodeField . PARAMETER_NAME ) ; if ( code == null ) { AuthenticationCodeField field = codeFieldProvider . get ( ) ; if ( ! key . isConfirmed ( ) ) { field . exposeKey ( key ) ; throw new GuacamoleInsufficientCredentialsException ( "TOTP.INFO_ENROLL_REQUIRED" , new CredentialsInfo ( Collections . < Field > singletonList ( field ) ) ) ; } throw new GuacamoleInsufficientCredentialsException ( "TOTP.INFO_CODE_REQUIRED" , new CredentialsInfo ( Collections . < Field > singletonList ( field ) ) ) ; } try { TOTPGenerator totp = new TOTPGenerator ( key . getSecret ( ) , confService . getMode ( ) , confService . getDigits ( ) ) ; if ( ( code . equals ( totp . generate ( ) ) || code . equals ( totp . previous ( ) ) ) && codeService . useCode ( username , code ) ) { if ( ! key . isConfirmed ( ) ) { key . setConfirmed ( true ) ; setKey ( context , key ) ; } return ; } } catch ( InvalidKeyException e ) { logger . warn ( "User \"{}\" is associated with an invalid TOTP key." , username ) ; logger . debug ( "TOTP key is not valid." , e ) ; } throw new GuacamoleClientException ( "TOTP.INFO_VERIFICATION_FAILED" ) ; } | Verifies the identity of the given user using TOTP . If a authentication code from the user s TOTP device has not already been provided a code is requested in the form of additional expected credentials . Any provided code is cryptographically verified . If no code is present or the received code is invalid an exception is thrown . |
30,082 | private GuacamoleInstruction handleBlob ( GuacamoleInstruction instruction ) { List < String > args = instruction . getArgs ( ) ; if ( args . size ( ) < 2 ) return instruction ; String index = args . get ( 0 ) ; InterceptedStream < OutputStream > stream = getInterceptedStream ( index ) ; if ( stream == null ) return instruction ; byte [ ] blob ; try { String data = args . get ( 1 ) ; blob = BaseEncoding . base64 ( ) . decode ( data ) ; } catch ( IllegalArgumentException e ) { logger . warn ( "Received base64 data for intercepted stream was invalid." ) ; logger . debug ( "Decoding base64 data for intercepted stream failed." , e ) ; return null ; } try { stream . getStream ( ) . write ( blob ) ; if ( ! acknowledgeBlobs ) { acknowledgeBlobs = true ; return new GuacamoleInstruction ( "blob" , index , "" ) ; } sendAck ( index , "OK" , GuacamoleStatus . SUCCESS ) ; } catch ( IOException e ) { sendAck ( index , "FAIL" , GuacamoleStatus . SERVER_ERROR ) ; logger . debug ( "Write failed for intercepted stream." , e ) ; } return null ; } | Handles a single blob instruction decoding its base64 data sending that data to the associated OutputStream and ultimately dropping the blob instruction such that the client never receives it . If no OutputStream is associated with the stream index within the blob instruction the instruction is passed through untouched . |
30,083 | private void handleEnd ( GuacamoleInstruction instruction ) { List < String > args = instruction . getArgs ( ) ; if ( args . size ( ) < 1 ) return ; closeInterceptedStream ( args . get ( 0 ) ) ; } | Handles a single end instruction closing the associated OutputStream . If no OutputStream is associated with the stream index within the end instruction this function has no effect . |
30,084 | private static Set < ObjectPermission > createPermissions ( Collection < String > identifiers , Collection < ObjectPermission . Type > types ) { Set < ObjectPermission > permissions = new HashSet < > ( identifiers . size ( ) ) ; types . forEach ( type -> { identifiers . forEach ( identifier -> permissions . add ( new ObjectPermission ( type , identifier ) ) ) ; } ) ; return permissions ; } | Creates a new set of ObjectPermissions for each possible combination of the given identifiers and permission types . |
30,085 | private void addSystemPermissions ( Set < SystemPermission . Type > permissions , SystemPermissionSet permSet ) throws GuacamoleException { for ( SystemPermission permission : permSet . getPermissions ( ) ) permissions . add ( permission . getType ( ) ) ; } | Adds the system permissions from the given SystemPermissionSet to the Set of system permissions provided . |
30,086 | private void addObjectPermissions ( Map < String , Set < ObjectPermission . Type > > permissions , ObjectPermissionSet permSet ) throws GuacamoleException { for ( ObjectPermission permission : permSet . getPermissions ( ) ) { String identifier = permission . getObjectIdentifier ( ) ; Set < ObjectPermission . Type > objectPermissions = permissions . get ( identifier ) ; if ( objectPermissions == null ) permissions . put ( identifier , EnumSet . of ( permission . getType ( ) ) ) ; else objectPermissions . add ( permission . getType ( ) ) ; } } | Adds the object permissions from the given ObjectPermissionSet to the Map of object permissions provided . |
30,087 | @ SuppressWarnings ( "deprecation" ) private static List < Listener > createListenerAdapters ( Object provider ) { final List < Listener > listeners = new ArrayList < Listener > ( ) ; if ( provider instanceof AuthenticationSuccessListener ) { listeners . add ( new AuthenticationSuccessListenerAdapter ( ( AuthenticationSuccessListener ) provider ) ) ; } if ( provider instanceof AuthenticationFailureListener ) { listeners . add ( new AuthenticationFailureListenerAdapter ( ( AuthenticationFailureListener ) provider ) ) ; } if ( provider instanceof TunnelConnectListener ) { listeners . add ( new TunnelConnectListenerAdapter ( ( TunnelConnectListener ) provider ) ) ; } if ( provider instanceof TunnelCloseListener ) { listeners . add ( new TunnelCloseListenerAdapter ( ( TunnelCloseListener ) provider ) ) ; } return listeners ; } | Creates a list of adapters for the given object based on the legacy listener interfaces it implements . |
30,088 | public UserCredentials generateTemporaryCredentials ( ModeledAuthenticatedUser user , ActiveConnectionRecord activeConnection , String sharingProfileIdentifier ) throws GuacamoleException { ModeledSharingProfile sharingProfile = sharingProfileService . retrieveObject ( user , sharingProfileIdentifier ) ; String connectionIdentifier = activeConnection . getConnectionIdentifier ( ) ; if ( sharingProfile == null || ! sharingProfile . getPrimaryConnectionIdentifier ( ) . equals ( connectionIdentifier ) ) throw new GuacamoleSecurityException ( "Permission denied." ) ; String key = keyGenerator . getShareKey ( ) ; connectionMap . add ( new SharedConnectionDefinition ( activeConnection , sharingProfile , key ) ) ; activeConnection . registerShareKey ( key ) ; return new UserCredentials ( SHARE_KEY , Collections . singletonMap ( SHARE_KEY_NAME , key ) ) ; } | Generates a set of temporary credentials which can be used to connect to the given connection using the given sharing profile . If the user does not have permission to share the connection via the given sharing profile permission will be denied . |
30,089 | public String getShareKey ( Credentials credentials ) { HttpServletRequest request = credentials . getRequest ( ) ; if ( request == null ) return null ; return request . getParameter ( SHARE_KEY_NAME ) ; } | Returns the share key contained within the given credentials . If there is no such share key null is returned . |
30,090 | public SharedAuthenticatedUser retrieveSharedConnectionUser ( AuthenticationProvider authProvider , Credentials credentials ) { String shareKey = getShareKey ( credentials ) ; if ( shareKey == null || connectionMap . get ( shareKey ) == null ) return null ; return new SharedAuthenticatedUser ( authProvider , credentials , shareKey ) ; } | Returns a SharedAuthenticatedUser if the given credentials contain a valid share key . The returned user will be associated with the single shared connection to which they have been granted temporary access . If the share key is invalid or no share key is contained within the given credentials null is returned . |
30,091 | public void setTokens ( Map < String , String > tokens ) { tokenValues . clear ( ) ; tokenValues . putAll ( tokens ) ; } | Replaces all current token values with the contents of the given map where each map key represents a token name and each map value represents a token value . |
30,092 | public String filter ( String input ) { StringBuilder output = new StringBuilder ( ) ; Matcher tokenMatcher = tokenPattern . matcher ( input ) ; int endOfLastMatch = 0 ; while ( tokenMatcher . find ( ) ) { String literal = tokenMatcher . group ( LEADING_TEXT_GROUP ) ; String escape = tokenMatcher . group ( ESCAPE_CHAR_GROUP ) ; output . append ( literal ) ; if ( "$" . equals ( escape ) ) { String notToken = tokenMatcher . group ( TOKEN_GROUP ) ; output . append ( notToken ) ; } else { output . append ( escape ) ; String tokenName = tokenMatcher . group ( TOKEN_NAME_GROUP ) ; String tokenValue = getToken ( tokenName ) ; if ( tokenValue == null ) { String notToken = tokenMatcher . group ( TOKEN_GROUP ) ; output . append ( notToken ) ; } else output . append ( tokenValue ) ; } endOfLastMatch = tokenMatcher . end ( ) ; } output . append ( input . substring ( endOfLastMatch ) ) ; return output . toString ( ) ; } | Filters the given string replacing any tokens with their corresponding values . |
30,093 | public void filterValues ( Map < ? , String > map ) { for ( Map . Entry < ? , String > entry : map . entrySet ( ) ) { String value = entry . getValue ( ) ; if ( value != null ) entry . setValue ( filter ( value ) ) ; } } | Given an arbitrary map containing String values replace each non - null value with the corresponding filtered value . |
30,094 | public String getLanguageKey ( String path ) { Matcher languageKeyMatcher = LANGUAGE_KEY_PATTERN . matcher ( path ) ; if ( ! languageKeyMatcher . matches ( ) ) return null ; return languageKeyMatcher . group ( 1 ) ; } | Derives a language key from the filename within the given path if possible . If the filename is not a valid language key null is returned . |
30,095 | private JsonNode mergeTranslations ( JsonNode original , JsonNode overlay ) { if ( ! overlay . isObject ( ) || original == null ) return overlay ; ObjectNode newNode = JsonNodeFactory . instance . objectNode ( ) ; Iterator < String > fieldNames = original . getFieldNames ( ) ; while ( fieldNames . hasNext ( ) ) { String fieldName = fieldNames . next ( ) ; newNode . put ( fieldName , original . get ( fieldName ) ) ; } fieldNames = overlay . getFieldNames ( ) ; while ( fieldNames . hasNext ( ) ) { String fieldName = fieldNames . next ( ) ; newNode . put ( fieldName , mergeTranslations ( original . get ( fieldName ) , overlay . get ( fieldName ) ) ) ; } return newNode ; } | Merges the given JSON objects . Any leaf node in overlay will overwrite the corresponding path in original . |
30,096 | private JsonNode parseLanguageResource ( Resource resource ) throws IOException { InputStream stream = resource . asStream ( ) ; if ( stream == null ) return null ; try { JsonNode tree = mapper . readTree ( stream ) ; return tree ; } finally { stream . close ( ) ; } } | Parses the given language resource returning the resulting JsonNode . If the resource cannot be read because it does not exist null is returned . |
30,097 | public void addLanguageResource ( String key , Resource resource ) { if ( ! isLanguageAllowed ( key ) ) { logger . debug ( "OMITTING language: \"{}\"" , key ) ; return ; } Resource existing = resources . get ( key ) ; if ( existing != null ) { try { JsonNode existingTree = parseLanguageResource ( existing ) ; if ( existingTree == null ) { logger . warn ( "Base language resource \"{}\" does not exist." , key ) ; return ; } JsonNode resourceTree = parseLanguageResource ( resource ) ; if ( resourceTree == null ) { logger . warn ( "Overlay language resource \"{}\" does not exist." , key ) ; return ; } JsonNode mergedTree = mergeTranslations ( existingTree , resourceTree ) ; resources . put ( key , new ByteArrayResource ( "application/json" , mapper . writeValueAsBytes ( mergedTree ) ) ) ; logger . debug ( "Merged strings with existing language: \"{}\"" , key ) ; } catch ( IOException e ) { logger . error ( "Unable to merge language resource \"{}\": {}" , key , e . getMessage ( ) ) ; logger . debug ( "Error merging language resource." , e ) ; } } else { resources . put ( key , resource ) ; logger . debug ( "Added language: \"{}\"" , key ) ; } } | Adds or overlays the given language resource which need not exist in the ServletContext . If a language resource is already defined for the given language key the strings from the given resource will be overlaid on top of the existing strings augmenting or overriding the available strings for that language . |
30,098 | private < T > boolean tryAdd ( ConcurrentHashMultiset < T > multiset , T value , int max ) { while ( true ) { int count = multiset . count ( value ) ; if ( count >= max && max != 0 ) return false ; if ( multiset . setCount ( value , count , count + 1 ) ) return true ; } } | Attempts to add a single instance of the given value to the given multiset without exceeding the specified maximum number of values . If the value cannot be added without exceeding the maximum false is returned . |
30,099 | private boolean tryIncrement ( AtomicInteger counter , int max ) { while ( true ) { int count = counter . get ( ) ; if ( count >= max && max != 0 ) return false ; if ( counter . compareAndSet ( count , count + 1 ) ) return true ; } } | Attempts to increment the given AtomicInteger without exceeding the specified maximum value . If the AtomicInteger cannot be incremented without exceeding the maximum false is returned . |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.