idx int64 0 41.2k | question stringlengths 73 5.81k | target stringlengths 5 918 |
|---|---|---|
30,200 | @ Path ( "connections" ) public DirectoryResource < Connection , APIConnection > getConnectionDirectoryResource ( ) throws GuacamoleException { return connectionDirectoryResourceFactory . create ( userContext , userContext . getConnectionDirectory ( ) ) ; } | Returns a new resource which represents the Connection Directory contained within the UserContext exposed by this UserContextResource . |
30,201 | @ Path ( "connectionGroups" ) public DirectoryResource < ConnectionGroup , APIConnectionGroup > getConnectionGroupDirectoryResource ( ) throws GuacamoleException { return connectionGroupDirectoryResourceFactory . create ( userContext , userContext . getConnectionGroupDirectory ( ) ) ; } | Returns a new resource which represents the ConnectionGroup Directory contained within the UserContext exposed by this UserContextResource . |
30,202 | @ Path ( "sharingProfiles" ) public DirectoryResource < SharingProfile , APISharingProfile > getSharingProfileDirectoryResource ( ) throws GuacamoleException { return sharingProfileDirectoryResourceFactory . create ( userContext , userContext . getSharingProfileDirectory ( ) ) ; } | Returns a new resource which represents the SharingProfile Directory contained within the UserContext exposed by this UserContextResource . |
30,203 | @ Path ( "users" ) public DirectoryResource < User , APIUser > getUserDirectoryResource ( ) throws GuacamoleException { return userDirectoryResourceFactory . create ( userContext , userContext . getUserDirectory ( ) ) ; } | Returns a new resource which represents the User Directory contained within the UserContext exposed by this UserContextResource . |
30,204 | @ Path ( "userGroups" ) public DirectoryResource < UserGroup , APIUserGroup > getUserGroupDirectoryResource ( ) throws GuacamoleException { return userGroupDirectoryResourceFactory . create ( userContext , userContext . getUserGroupDirectory ( ) ) ; } | Returns a new resource which represents the UserGroup Directory contained within the UserContext exposed by this UserContextResource . |
30,205 | private void closeConnection ( WsOutbound outbound , int guacamoleStatusCode , int webSocketCode ) { try { byte [ ] message = Integer . toString ( guacamoleStatusCode ) . getBytes ( "UTF-8" ) ; outbound . close ( webSocketCode , ByteBuffer . wrap ( message ) ) ; } catch ( IOException e ) { logger . debug ( "Unable to close WebSocket tunnel." , e ) ; } } | Sends the given Guacamole and WebSocket numeric status on the given WebSocket connection and closes the connection . |
30,206 | public Map < String , Connection > getConnections ( AuthenticatedUser user , LDAPConnection ldapConnection ) throws GuacamoleException { String configurationBaseDN = confService . getConfigurationBaseDN ( ) ; if ( configurationBaseDN == null ) return Collections . < String , Connection > emptyMap ( ) ; try { String userDN = ldapConnection . getAuthenticationDN ( ) ; assert ( userDN != null ) ; String connectionSearchFilter = getConnectionSearchFilter ( userDN , ldapConnection ) ; List < LDAPEntry > results = queryService . search ( ldapConnection , configurationBaseDN , connectionSearchFilter ) ; return queryService . asMap ( results , ( entry ) -> { LDAPAttribute cn = entry . getAttribute ( "cn" ) ; if ( cn == null ) { logger . warn ( "guacConfigGroup is missing a cn." ) ; return null ; } LDAPAttribute protocol = entry . getAttribute ( "guacConfigProtocol" ) ; if ( protocol == null ) { logger . warn ( "guacConfigGroup \"{}\" is missing the " + "required \"guacConfigProtocol\" attribute." , cn . getStringValue ( ) ) ; return null ; } GuacamoleConfiguration config = new GuacamoleConfiguration ( ) ; config . setProtocol ( protocol . getStringValue ( ) ) ; LDAPAttribute parameterAttribute = entry . getAttribute ( "guacConfigParameter" ) ; if ( parameterAttribute != null ) { Enumeration < ? > parameters = parameterAttribute . getStringValues ( ) ; while ( parameters . hasMoreElements ( ) ) { String parameter = ( String ) parameters . nextElement ( ) ; int equals = parameter . indexOf ( '=' ) ; if ( equals != - 1 ) { String name = parameter . substring ( 0 , equals ) ; String value = parameter . substring ( equals + 1 ) ; config . setParameter ( name , value ) ; } } } String name = cn . getStringValue ( ) ; Connection connection = new SimpleConnection ( name , name , config ) ; connection . setParentIdentifier ( LDAPAuthenticationProvider . ROOT_CONNECTION_GROUP ) ; if ( user instanceof LDAPAuthenticatedUser ) connection = new TokenInjectingConnection ( connection , ( ( LDAPAuthenticatedUser ) user ) . getTokens ( ) ) ; return connection ; } ) ; } catch ( LDAPException e ) { throw new GuacamoleServerException ( "Error while querying for connections." , e ) ; } } | Returns all Guacamole connections accessible to the user currently bound under the given LDAP connection . |
30,207 | private LDAPConnection bindAs ( Credentials credentials ) throws GuacamoleException { String username = credentials . getUsername ( ) ; String password = credentials . getPassword ( ) ; if ( username == null || username . isEmpty ( ) ) { logger . debug ( "Anonymous bind is not currently allowed by the LDAP authentication provider." ) ; return null ; } if ( password == null || password . isEmpty ( ) ) { logger . debug ( "Anonymous bind is not currently allowed by the LDAP authentication provider." ) ; return null ; } String userDN = getUserBindDN ( username ) ; if ( userDN == null ) { logger . debug ( "Unable to determine DN for user \"{}\"." , username ) ; return null ; } return ldapService . bindAs ( userDN , password ) ; } | Binds to the LDAP server using the provided Guacamole credentials . The DN of the user is derived using the LDAP configuration properties provided in guacamole . properties as is the server hostname and port information . |
30,208 | public LDAPAuthenticatedUser authenticateUser ( Credentials credentials ) throws GuacamoleException { LDAPConnection ldapConnection ; try { ldapConnection = bindAs ( credentials ) ; } catch ( GuacamoleException e ) { logger . error ( "Cannot bind with LDAP server: {}" , e . getMessage ( ) ) ; logger . debug ( "Error binding with LDAP server." , e ) ; ldapConnection = null ; } if ( ldapConnection == null ) throw new GuacamoleInvalidCredentialsException ( "Permission denied." , CredentialsInfo . USERNAME_PASSWORD ) ; try { Set < String > effectiveGroups = userGroupService . getParentUserGroupIdentifiers ( ldapConnection , ldapConnection . getAuthenticationDN ( ) ) ; LDAPAuthenticatedUser authenticatedUser = authenticatedUserProvider . get ( ) ; authenticatedUser . init ( credentials , getAttributeTokens ( ldapConnection , credentials . getUsername ( ) ) , effectiveGroups ) ; return authenticatedUser ; } finally { ldapService . disconnect ( ldapConnection ) ; } } | Returns an AuthenticatedUser representing the user authenticated by the given credentials . Also adds custom LDAP attributes to the AuthenticatedUser . |
30,209 | private Map < String , String > getAttributeTokens ( LDAPConnection ldapConnection , String username ) throws GuacamoleException { List < String > attrList = confService . getAttributes ( ) ; if ( attrList . isEmpty ( ) ) return Collections . < String , String > emptyMap ( ) ; String [ ] attrArray = attrList . toArray ( new String [ attrList . size ( ) ] ) ; String userDN = getUserBindDN ( username ) ; Map < String , String > tokens = new HashMap < String , String > ( ) ; try { LDAPEntry userEntry = ldapConnection . read ( userDN , attrArray ) ; if ( userEntry == null ) return Collections . < String , String > emptyMap ( ) ; LDAPAttributeSet attrSet = userEntry . getAttributeSet ( ) ; if ( attrSet == null ) return Collections . < String , String > emptyMap ( ) ; for ( Object attrObj : attrSet ) { LDAPAttribute attr = ( LDAPAttribute ) attrObj ; tokens . put ( TokenName . fromAttribute ( attr . getName ( ) ) , attr . getStringValue ( ) ) ; } } catch ( LDAPException e ) { throw new GuacamoleServerException ( "Could not query LDAP user attributes." , e ) ; } return tokens ; } | Returns parameter tokens generated from LDAP attributes on the user currently bound under the given LDAP connection . The attributes to be converted into parameter tokens must be explicitly listed in guacamole . properties . If no attributes are specified or none are found on the LDAP user object an empty map is returned . |
30,210 | public LDAPUserContext getUserContext ( AuthenticatedUser authenticatedUser ) throws GuacamoleException { Credentials credentials = authenticatedUser . getCredentials ( ) ; LDAPConnection ldapConnection = bindAs ( credentials ) ; if ( ldapConnection == null ) return null ; try { LDAPUserContext userContext = userContextProvider . get ( ) ; userContext . init ( authenticatedUser , ldapConnection ) ; return userContext ; } finally { ldapService . disconnect ( ldapConnection ) ; } } | Returns a UserContext object initialized with data accessible to the given AuthenticatedUser . |
30,211 | public String getIdentifier ( LDAPEntry entry , Collection < String > attributes ) { for ( String identifierAttribute : attributes ) { LDAPAttribute identifier = entry . getAttribute ( identifierAttribute ) ; if ( identifier != null ) return identifier . getStringValue ( ) ; } return null ; } | Returns the identifier of the object represented by the given LDAP entry . Multiple attributes may be declared as containing the identifier of the object when present on an LDAP entry . If multiple such attributes are present on the same LDAP entry the value of the attribute with highest priority is used . If multiple copies of the same attribute are present on the same LDAPentry the first value of that attribute is used . |
30,212 | public String generateQuery ( String filter , Collection < String > attributes , String attributeValue ) { StringBuilder ldapQuery = new StringBuilder ( ) ; ldapQuery . append ( "(&" ) ; ldapQuery . append ( filter ) ; if ( attributes . size ( ) > 1 ) ldapQuery . append ( "(|" ) ; for ( String attribute : attributes ) { ldapQuery . append ( "(" ) ; ldapQuery . append ( escapingService . escapeLDAPSearchFilter ( attribute ) ) ; if ( attributeValue != null ) { ldapQuery . append ( "=" ) ; ldapQuery . append ( escapingService . escapeLDAPSearchFilter ( attributeValue ) ) ; ldapQuery . append ( ")" ) ; } else ldapQuery . append ( "=*)" ) ; } if ( attributes . size ( ) > 1 ) ldapQuery . append ( ")" ) ; ldapQuery . append ( ")" ) ; return ldapQuery . toString ( ) ; } | Generates a properly - escaped LDAP query which finds all objects which match the given LDAP filter and which have at least one of the given attributes set to the specified value . |
30,213 | public List < LDAPEntry > search ( LDAPConnection ldapConnection , String baseDN , String query ) throws GuacamoleException { logger . debug ( "Searching \"{}\" for objects matching \"{}\"." , baseDN , query ) ; try { LDAPSearchResults results = ldapConnection . search ( baseDN , LDAPConnection . SCOPE_SUB , query , null , false , confService . getLDAPSearchConstraints ( ) ) ; List < LDAPEntry > entries = new ArrayList < > ( results . getCount ( ) ) ; while ( results . hasMore ( ) ) { try { entries . add ( results . next ( ) ) ; } catch ( LDAPReferralException e ) { if ( confService . getFollowReferrals ( ) ) { logger . error ( "Could not follow referral: {}" , e . getFailedReferral ( ) ) ; logger . debug ( "Error encountered trying to follow referral." , e ) ; throw new GuacamoleServerException ( "Could not follow LDAP referral." , e ) ; } else { logger . warn ( "Given a referral, but referrals are disabled. Error was: {}" , e . getMessage ( ) ) ; logger . debug ( "Got a referral, but configured to not follow them." , e ) ; } } catch ( LDAPException e ) { logger . warn ( "Failed to process an LDAP search result. Error was: {}" , e . resultCodeToString ( ) ) ; logger . debug ( "Error processing LDAPEntry search result." , e ) ; } } return entries ; } catch ( LDAPException | GuacamoleException e ) { throw new GuacamoleServerException ( "Unable to query list of " + "objects from LDAP directory." , e ) ; } } | Executes an arbitrary LDAP query using the given connection returning a list of all results . Only objects beneath the given base DN are included in the search . |
30,214 | private String getLoggableAddress ( HttpServletRequest request ) { String header = request . getHeader ( "X-Forwarded-For" ) ; if ( header != null && X_FORWARDED_FOR . matcher ( header ) . matches ( ) ) return "[" + header + ", " + request . getRemoteAddr ( ) + "]" ; return request . getRemoteAddr ( ) ; } | Returns a formatted string containing an IP address or list of IP addresses which represent the HTTP client and any involved proxies . As the headers used to determine proxies can easily be forged this data is superficially validated to ensure that it at least looks like a list of IPs . |
30,215 | private AuthenticatedUser authenticateUser ( Credentials credentials ) throws GuacamoleException { GuacamoleCredentialsException authFailure = null ; for ( AuthenticationProvider authProvider : authProviders ) { try { AuthenticatedUser authenticatedUser = authProvider . authenticateUser ( credentials ) ; if ( authenticatedUser != null ) return authenticatedUser ; } catch ( GuacamoleCredentialsException e ) { if ( authFailure == null ) authFailure = e ; } } if ( authFailure != null ) throw authFailure ; throw new GuacamoleInvalidCredentialsException ( "Permission Denied." , CredentialsInfo . USERNAME_PASSWORD ) ; } | Attempts authentication against all AuthenticationProviders in order using the provided credentials . The first authentication failure takes priority but remaining AuthenticationProviders are attempted . If any AuthenticationProvider succeeds the resulting AuthenticatedUser is returned and no further AuthenticationProviders are tried . |
30,216 | private AuthenticatedUser updateAuthenticatedUser ( AuthenticatedUser authenticatedUser , Credentials credentials ) throws GuacamoleException { AuthenticationProvider authProvider = authenticatedUser . getAuthenticationProvider ( ) ; authenticatedUser = authProvider . updateAuthenticatedUser ( authenticatedUser , credentials ) ; if ( authenticatedUser == null ) throw new GuacamoleSecurityException ( "User re-authentication failed." ) ; return authenticatedUser ; } | Re - authenticates the given AuthenticatedUser against the AuthenticationProvider that originally created it using the given Credentials . |
30,217 | private AuthenticatedUser getAuthenticatedUser ( GuacamoleSession existingSession , Credentials credentials ) throws GuacamoleException { try { if ( existingSession != null ) { AuthenticatedUser updatedUser = updateAuthenticatedUser ( existingSession . getAuthenticatedUser ( ) , credentials ) ; fireAuthenticationSuccessEvent ( updatedUser ) ; return updatedUser ; } AuthenticatedUser authenticatedUser = AuthenticationService . this . authenticateUser ( credentials ) ; fireAuthenticationSuccessEvent ( authenticatedUser ) ; if ( logger . isInfoEnabled ( ) ) logger . info ( "User \"{}\" successfully authenticated from {}." , authenticatedUser . getIdentifier ( ) , getLoggableAddress ( credentials . getRequest ( ) ) ) ; return authenticatedUser ; } catch ( GuacamoleException e ) { fireAuthenticationFailedEvent ( credentials ) ; HttpServletRequest request = credentials . getRequest ( ) ; String username = credentials . getUsername ( ) ; if ( username != null ) { if ( logger . isWarnEnabled ( ) ) logger . warn ( "Authentication attempt from {} for user \"{}\" failed." , getLoggableAddress ( request ) , username ) ; } else if ( logger . isDebugEnabled ( ) ) logger . debug ( "Anonymous authentication attempt from {} failed." , getLoggableAddress ( request ) ) ; throw e ; } } | Returns the AuthenticatedUser associated with the given session and credentials performing a fresh authentication and creating a new AuthenticatedUser if necessary . |
30,218 | private List < DecoratedUserContext > getUserContexts ( GuacamoleSession existingSession , AuthenticatedUser authenticatedUser , Credentials credentials ) throws GuacamoleException { List < DecoratedUserContext > userContexts = new ArrayList < DecoratedUserContext > ( authProviders . size ( ) ) ; if ( existingSession != null ) { List < DecoratedUserContext > oldUserContexts = existingSession . getUserContexts ( ) ; for ( DecoratedUserContext userContext : oldUserContexts ) { UserContext oldUserContext = userContext . getUndecoratedUserContext ( ) ; AuthenticationProvider authProvider = oldUserContext . getAuthenticationProvider ( ) ; UserContext updatedUserContext = authProvider . updateUserContext ( oldUserContext , authenticatedUser , credentials ) ; if ( updatedUserContext != null ) userContexts . add ( decorationService . redecorate ( userContext , updatedUserContext , authenticatedUser , credentials ) ) ; else logger . debug ( "AuthenticationProvider \"{}\" retroactively destroyed its UserContext." , authProvider . getClass ( ) . getName ( ) ) ; } } else { for ( AuthenticationProvider authProvider : authProviders ) { UserContext userContext = authProvider . getUserContext ( authenticatedUser ) ; if ( userContext != null ) userContexts . add ( decorationService . decorate ( userContext , authenticatedUser , credentials ) ) ; } } return userContexts ; } | Returns all UserContexts associated with the given AuthenticatedUser updating existing UserContexts if any . If no UserContexts are yet associated with the given AuthenticatedUser new UserContexts are generated by polling each available AuthenticationProvider . |
30,219 | public String authenticate ( Credentials credentials , String token ) throws GuacamoleException { GuacamoleSession existingSession ; if ( token != null ) existingSession = tokenSessionMap . get ( token ) ; else existingSession = null ; AuthenticatedUser authenticatedUser = getAuthenticatedUser ( existingSession , credentials ) ; List < DecoratedUserContext > userContexts = getUserContexts ( existingSession , authenticatedUser , credentials ) ; String authToken ; if ( existingSession != null ) { authToken = token ; existingSession . setAuthenticatedUser ( authenticatedUser ) ; existingSession . setUserContexts ( userContexts ) ; } else { authToken = authTokenGenerator . getToken ( ) ; tokenSessionMap . put ( authToken , new GuacamoleSession ( environment , authenticatedUser , userContexts ) ) ; logger . debug ( "Login was successful for user \"{}\"." , authenticatedUser . getIdentifier ( ) ) ; } return authToken ; } | Authenticates a user using the given credentials and optional authentication token returning the authentication token associated with the user s Guacamole session which may be newly generated . If an existing token is provided the authentication procedure will attempt to update or reuse the provided token but it is possible that a new token will be returned . Note that this function CANNOT return null . |
30,220 | public GuacamoleSession getGuacamoleSession ( String authToken ) throws GuacamoleException { GuacamoleSession session = tokenSessionMap . get ( authToken ) ; if ( session == null ) throw new GuacamoleUnauthorizedException ( "Permission Denied." ) ; return session ; } | Finds the Guacamole session for a given auth token if the auth token represents a currently logged in user . Throws an unauthorized error otherwise . |
30,221 | public boolean destroyGuacamoleSession ( String authToken ) { GuacamoleSession session = tokenSessionMap . remove ( authToken ) ; if ( session == null ) return false ; session . invalidate ( ) ; return true ; } | Invalidates a specific authentication token and its corresponding Guacamole session effectively logging out the associated user . If the authentication token is not valid this function has no effect . |
30,222 | public ActiveConnection getActiveConnection ( ) throws GuacamoleException { UUID uuid = getUUID ( ) ; Directory < ActiveConnection > activeConnectionDirectory = userContext . getActiveConnectionDirectory ( ) ; Collection < String > activeConnectionIdentifiers = activeConnectionDirectory . getIdentifiers ( ) ; for ( ActiveConnection activeConnection : activeConnectionDirectory . getAll ( activeConnectionIdentifiers ) ) { GuacamoleTunnel tunnel = activeConnection . getTunnel ( ) ; if ( tunnel == null ) continue ; if ( uuid . equals ( tunnel . getUUID ( ) ) ) return activeConnection ; } return null ; } | Returns the ActiveConnection object associated with this tunnel within the AuthenticationProvider and UserContext which created the tunnel . If the AuthenticationProvider is not tracking active connections or this tunnel is no longer active this will be null . |
30,223 | private void bindAuthenticationProvider ( Class < ? extends AuthenticationProvider > authenticationProvider , Set < String > tolerateFailures ) { logger . debug ( "[{}] Binding AuthenticationProvider \"{}\"." , boundAuthenticationProviders . size ( ) , authenticationProvider . getName ( ) ) ; boundAuthenticationProviders . add ( new AuthenticationProviderFacade ( authenticationProvider , tolerateFailures ) ) ; } | Binds the given AuthenticationProvider class such that any service requiring access to the AuthenticationProvider can obtain it via injection along with any other bound AuthenticationProviders . |
30,224 | private void bindAuthenticationProviders ( Collection < Class < AuthenticationProvider > > authProviders , Set < String > tolerateFailures ) { for ( Class < AuthenticationProvider > authenticationProvider : authProviders ) bindAuthenticationProvider ( authenticationProvider , tolerateFailures ) ; } | Binds each of the the given AuthenticationProvider classes such that any service requiring access to the AuthenticationProvider can obtain it via injection . |
30,225 | private Set < String > getToleratedAuthenticationProviders ( ) { try { return environment . getProperty ( SKIP_IF_UNAVAILABLE , Collections . < String > emptySet ( ) ) ; } catch ( GuacamoleException e ) { logger . warn ( "The list of authentication providers specified via the \"{}\" property could not be parsed: {}" , SKIP_IF_UNAVAILABLE . getName ( ) , e . getMessage ( ) ) ; logger . debug ( "Unable to parse \"{}\" property." , SKIP_IF_UNAVAILABLE . getName ( ) , e ) ; return Collections . < String > emptySet ( ) ; } } | Returns the set of identifiers of all authentication providers whose internal failures should be tolerated during the authentication process . If the identifier of an authentication provider is within this set errors during authentication will result in the authentication provider being ignored for that authentication attempt with the authentication process proceeding as if that authentication provider were not present . By default errors during authentication halt the authentication process entirely . |
30,226 | private CredentialsInfo getRadiusChallenge ( RadiusPacket challengePacket ) { RadiusAttribute stateAttr = challengePacket . findAttribute ( Attr_State . TYPE ) ; if ( stateAttr == null ) { logger . error ( "Something went wrong, state attribute not present." ) ; logger . debug ( "State Attribute turned up null, which shouldn't happen in AccessChallenge." ) ; return null ; } RadiusAttribute replyAttr = challengePacket . findAttribute ( Attr_ReplyMessage . TYPE ) ; if ( replyAttr == null ) { logger . error ( "No reply message received from the server." ) ; logger . debug ( "Expecting a Attr_ReplyMessage attribute on this packet, and did not get one." ) ; return null ; } String replyMsg = replyAttr . toString ( ) ; String radiusState = BaseEncoding . base16 ( ) . encode ( stateAttr . getValue ( ) . getBytes ( ) ) ; Field radiusResponseField = new RadiusChallengeResponseField ( replyMsg ) ; Field radiusStateField = new RadiusStateField ( radiusState ) ; return new CredentialsInfo ( Arrays . asList ( radiusResponseField , radiusStateField ) ) ; } | Returns the expected credentials from a RADIUS challenge . |
30,227 | public void init ( String username , Credentials credentials ) { this . credentials = credentials ; setIdentifier ( username . toLowerCase ( ) ) ; } | Initializes this AuthenticatedUser using the given username and credentials . |
30,228 | public Injector get ( ) throws GuacamoleException { Injector value = injector . get ( ) ; if ( value != null ) return value ; injector . compareAndSet ( null , create ( ) ) ; return injector . get ( ) ; } | Returns a common singleton instance of a Guice Injector configured for the injections required by the JDBC authentication extension . The result of the first call to this function will be cached statically within this class and will be returned for all subsequent calls . |
30,229 | private < PermissionType extends Permission > void updatePermissionSet ( APIPatch . Operation operation , PermissionSetPatch < PermissionType > permissionSetPatch , PermissionType permission ) throws GuacamoleException { switch ( operation ) { case add : permissionSetPatch . addPermission ( permission ) ; break ; case remove : permissionSetPatch . removePermission ( permission ) ; break ; default : throw new GuacamoleClientException ( "Unsupported patch operation: \"" + operation + "\"" ) ; } } | Updates the given permission set patch by queuing an add or remove operation for the given permission based on the given patch operation . |
30,230 | public String validateTicket ( String ticket , Credentials credentials ) throws GuacamoleException { URI casServerUrl = confService . getAuthorizationEndpoint ( ) ; Cas20ProxyTicketValidator validator = new Cas20ProxyTicketValidator ( casServerUrl . toString ( ) ) ; validator . setAcceptAnyProxy ( true ) ; validator . setEncoding ( "UTF-8" ) ; try { URI confRedirectURI = confService . getRedirectURI ( ) ; Assertion a = validator . validate ( ticket , confRedirectURI . toString ( ) ) ; AttributePrincipal principal = a . getPrincipal ( ) ; String username = principal . getName ( ) ; if ( username != null ) credentials . setUsername ( username ) ; Object credObj = principal . getAttributes ( ) . get ( "credential" ) ; if ( credObj != null ) { String clearPass = decryptPassword ( credObj . toString ( ) ) ; if ( clearPass != null && ! clearPass . isEmpty ( ) ) credentials . setPassword ( clearPass ) ; } return username ; } catch ( TicketValidationException e ) { throw new GuacamoleException ( "Ticket validation failed." , e ) ; } catch ( Throwable t ) { logger . error ( "Error validating ticket with CAS server: {}" , t . getMessage ( ) ) ; throw new GuacamoleInvalidCredentialsException ( "CAS login failed." , CredentialsInfo . USERNAME_PASSWORD ) ; } } | Validates and parses the given ID ticket returning the username provided by the CAS server in the ticket . If the ticket is invalid an exception is thrown . |
30,231 | private final String decryptPassword ( String encryptedPassword ) throws GuacamoleException { if ( encryptedPassword == null || encryptedPassword . isEmpty ( ) ) { logger . warn ( "No or empty encrypted password, no password will be available." ) ; return null ; } final PrivateKey clearpassKey = confService . getClearpassKey ( ) ; if ( clearpassKey == null ) { logger . debug ( "No private key available to decrypt password." ) ; return null ; } try { final Cipher cipher = Cipher . getInstance ( clearpassKey . getAlgorithm ( ) ) ; if ( cipher == null ) throw new GuacamoleServerException ( "Failed to initialize cipher object with private key." ) ; cipher . init ( Cipher . DECRYPT_MODE , clearpassKey ) ; final byte [ ] pass64 = BaseEncoding . base64 ( ) . decode ( encryptedPassword ) ; final byte [ ] cipherData = cipher . doFinal ( pass64 ) ; return new String ( cipherData , Charset . forName ( "UTF-8" ) ) ; } catch ( BadPaddingException e ) { throw new GuacamoleServerException ( "Bad padding when decrypting cipher data." , e ) ; } catch ( IllegalBlockSizeException e ) { throw new GuacamoleServerException ( "Illegal block size while opening private key." , e ) ; } catch ( InvalidKeyException e ) { throw new GuacamoleServerException ( "Specified private key for ClearPass decryption is invalid." , e ) ; } catch ( NoSuchAlgorithmException e ) { throw new GuacamoleServerException ( "Unexpected algorithm for the private key." , e ) ; } catch ( NoSuchPaddingException e ) { throw new GuacamoleServerException ( "No such padding trying to initialize cipher with private key." , e ) ; } } | Takes an encrypted string representing a password provided by the CAS ClearPass service and decrypts it using the private key configured for this extension . Returns null if it is unable to decrypt the password . |
30,232 | protected Set < PermissionType > getPermissionInstances ( Collection < ModelType > models ) { Set < PermissionType > permissions = new HashSet < PermissionType > ( models . size ( ) ) ; for ( ModelType model : models ) permissions . add ( getPermissionInstance ( model ) ) ; return permissions ; } | Returns a collection of permissions which are based on the models in the given collection . |
30,233 | protected Collection < ModelType > getModelInstances ( ModeledPermissions < ? extends EntityModel > targetEntity , Collection < PermissionType > permissions ) { Collection < ModelType > models = new ArrayList < ModelType > ( permissions . size ( ) ) ; for ( PermissionType permission : permissions ) models . add ( getModelInstance ( targetEntity , permission ) ) ; return models ; } | Returns a collection of model objects which are based on the given permissions and target entity . |
30,234 | @ Path ( "/" ) public SessionResource getSessionResource ( @ QueryParam ( "token" ) String authToken ) throws GuacamoleException { GuacamoleSession session = authenticationService . getGuacamoleSession ( authToken ) ; return sessionResourceFactory . create ( session ) ; } | Retrieves a resource representing the GuacamoleSession associated with the given authentication token . |
30,235 | public void register ( T object ) { if ( invalidated . get ( ) ) { cleanup ( object ) ; return ; } objects . add ( object ) ; if ( invalidated . get ( ) ) cleanupAll ( ) ; } | Registers the given object with this SharedObjectManager such that it is cleaned up once the SharedObjectManager is invalidated . If the SharedObjectManager has already been invalidated the object will be cleaned up immediately . |
30,236 | protected ObjectPermissionSet getRelevantPermissionSet ( ModeledUser user , ModeledPermissions < ? extends EntityModel > targetEntity ) throws GuacamoleException { if ( targetEntity . isUser ( ) ) return user . getUserPermissions ( ) ; if ( targetEntity . isUserGroup ( ) ) return user . getUserGroupPermissions ( ) ; throw new UnsupportedOperationException ( "Unexpected entity type." ) ; } | Returns the ObjectPermissionSet related to the type of the given entity . If the given entity represents a user then the ObjectPermissionSet containing user permissions is returned . If the given entity represents a user group then the ObjectPermissionSet containing user group permissions is returned . |
30,237 | protected boolean canReadPermissions ( ModeledAuthenticatedUser user , ModeledPermissions < ? extends EntityModel > targetEntity ) throws GuacamoleException { if ( targetEntity . isUser ( user . getUser ( ) . getIdentifier ( ) ) ) return true ; if ( user . getUser ( ) . isAdministrator ( ) ) return true ; ObjectPermissionSet permissionSet = getRelevantPermissionSet ( user . getUser ( ) , targetEntity ) ; return permissionSet . hasPermission ( ObjectPermission . Type . READ , targetEntity . getIdentifier ( ) ) ; } | Determines whether the given user can read the permissions currently granted to the given target entity . If the reading user and the target entity are not the same then explicit READ or SYSTEM_ADMINISTER access is required . Permission inheritance via user groups is taken into account . |
30,238 | public ModeledAuthenticatedUser retrieveAuthenticatedUser ( AuthenticationProvider authenticationProvider , Credentials credentials ) throws GuacamoleException { String username = credentials . getUsername ( ) ; String password = credentials . getPassword ( ) ; UserModel userModel = userMapper . selectOne ( username ) ; if ( userModel == null ) return null ; byte [ ] hash = encryptionService . createPasswordHash ( password , userModel . getPasswordSalt ( ) ) ; if ( ! Arrays . equals ( hash , userModel . getPasswordHash ( ) ) ) return null ; ModeledUser user = getObjectInstance ( null , userModel ) ; user . setCurrentUser ( new ModeledAuthenticatedUser ( authenticationProvider , user , credentials ) ) ; return user . getCurrentUser ( ) ; } | Retrieves the user corresponding to the given credentials from the database . Note that this function will not enforce any additional account restrictions including explicitly disabled accounts scheduling and password expiration . It is the responsibility of the caller to enforce such restrictions if desired . |
30,239 | public ModeledUser retrieveUser ( AuthenticationProvider authenticationProvider , AuthenticatedUser authenticatedUser ) throws GuacamoleException { if ( authenticatedUser instanceof ModeledAuthenticatedUser ) return ( ( ModeledAuthenticatedUser ) authenticatedUser ) . getUser ( ) ; String username = authenticatedUser . getIdentifier ( ) ; UserModel userModel = userMapper . selectOne ( username ) ; if ( userModel == null ) return null ; ModeledUser user = getObjectInstance ( null , userModel ) ; user . setCurrentUser ( new ModeledAuthenticatedUser ( authenticatedUser , authenticationProvider , user ) ) ; return user ; } | Retrieves the user corresponding to the given AuthenticatedUser from the database . |
30,240 | public void resetExpiredPassword ( ModeledUser user , Credentials credentials ) throws GuacamoleException { UserModel userModel = user . getModel ( ) ; String username = user . getIdentifier ( ) ; HttpServletRequest request = credentials . getRequest ( ) ; String newPassword = request . getParameter ( NEW_PASSWORD_PARAMETER ) ; String confirmNewPassword = request . getParameter ( CONFIRM_NEW_PASSWORD_PARAMETER ) ; if ( newPassword == null || confirmNewPassword == null ) { logger . info ( "The password of user \"{}\" has expired and must be reset." , username ) ; throw new GuacamoleInsufficientCredentialsException ( "LOGIN.INFO_PASSWORD_EXPIRED" , EXPIRED_PASSWORD ) ; } if ( newPassword . equals ( credentials . getPassword ( ) ) ) throw new GuacamoleClientException ( "LOGIN.ERROR_PASSWORD_SAME" ) ; if ( newPassword . isEmpty ( ) ) throw new GuacamoleClientException ( "LOGIN.ERROR_PASSWORD_BLANK" ) ; if ( ! newPassword . equals ( confirmNewPassword ) ) throw new GuacamoleClientException ( "LOGIN.ERROR_PASSWORD_MISMATCH" ) ; passwordPolicyService . verifyPassword ( username , newPassword ) ; userModel . setExpired ( false ) ; user . setPassword ( newPassword ) ; userMapper . update ( userModel ) ; logger . info ( "Expired password of user \"{}\" has been reset." , username ) ; } | Resets the password of the given user to the new password specified via the new - password and confirm - new - password parameters from the provided credentials . If these parameters are missing or invalid additional credentials will be requested . |
30,241 | protected List < ActivityRecord > getObjectInstances ( List < ActivityRecordModel > models ) { List < ActivityRecord > objects = new ArrayList < ActivityRecord > ( models . size ( ) ) ; for ( ActivityRecordModel model : models ) objects . add ( getObjectInstance ( model ) ) ; return objects ; } | Returns a list of ActivityRecord objects which are backed by the models in the given list . |
30,242 | public List < ActivityRecord > retrieveHistory ( ModeledAuthenticatedUser authenticatedUser , ModeledUser user ) throws GuacamoleException { String username = user . getIdentifier ( ) ; if ( hasObjectPermission ( authenticatedUser , username , ObjectPermission . Type . READ ) ) return getObjectInstances ( userRecordMapper . select ( username ) ) ; throw new GuacamoleSecurityException ( "Permission denied." ) ; } | Retrieves the login history of the given user including any active sessions . |
30,243 | @ Path ( "protocols" ) public Map < String , ProtocolInfo > getProtocols ( ) throws GuacamoleException { Environment env = new LocalEnvironment ( ) ; return env . getProtocols ( ) ; } | Gets a map of protocols defined in the system - protocol name to protocol . |
30,244 | private void closeConnection ( Session session , int guacamoleStatusCode , int webSocketCode ) { try { CloseCode code = CloseReason . CloseCodes . getCloseCode ( webSocketCode ) ; String message = Integer . toString ( guacamoleStatusCode ) ; session . close ( new CloseReason ( code , message ) ) ; } catch ( IOException e ) { logger . debug ( "Unable to close WebSocket connection." , e ) ; } } | Sends the numeric Guacaomle Status Code and Web Socket code and closes the connection . |
30,245 | public static String format ( Date date ) { DateFormat dateFormat = new SimpleDateFormat ( DateField . FORMAT ) ; return date == null ? null : dateFormat . format ( date ) ; } | Converts the given date into a string which follows the format used by date fields . |
30,246 | @ Path ( "activeConnection" ) public DirectoryObjectResource < ActiveConnection , APIActiveConnection > getActiveConnection ( ) throws GuacamoleException { UserContext userContext = tunnel . getUserContext ( ) ; ActiveConnection activeConnection = tunnel . getActiveConnection ( ) ; if ( activeConnection == null ) throw new GuacamoleResourceNotFoundException ( "No readable active connection for tunnel." ) ; return activeConnectionResourceFactory . create ( userContext , userContext . getActiveConnectionDirectory ( ) , activeConnection ) ; } | Retrieves a resource representing the ActiveConnection object associated with this tunnel . |
30,247 | @ Path ( "streams/{index}/{filename}" ) public StreamResource getStream ( @ PathParam ( "index" ) final int streamIndex , @ QueryParam ( "type" ) @ DefaultValue ( DEFAULT_MEDIA_TYPE ) String mediaType , @ PathParam ( "filename" ) String filename ) throws GuacamoleException { return new StreamResource ( tunnel , streamIndex , mediaType ) ; } | Intercepts and returns the entire contents of a specific stream . |
30,248 | static < T > T newInstance ( String typeName , Class < ? extends T > providerClass ) { T instance = null ; try { instance = providerClass . getConstructor ( ) . newInstance ( ) ; } catch ( NoSuchMethodException e ) { logger . error ( "The {} extension in use is not properly defined. " + "Please contact the developers of the extension or, if you " + "are the developer, turn on debug-level logging." , typeName ) ; logger . debug ( "{} is missing a default constructor." , providerClass . getName ( ) , e ) ; } catch ( SecurityException e ) { logger . error ( "The Java security manager is preventing extensions " + "from being loaded. Please check the configuration of Java or your " + "servlet container." ) ; logger . debug ( "Creation of {} disallowed by security manager." , providerClass . getName ( ) , e ) ; } catch ( InstantiationException e ) { logger . error ( "The {} extension in use is not properly defined. " + "Please contact the developers of the extension or, if you " + "are the developer, turn on debug-level logging." , typeName ) ; logger . debug ( "{} cannot be instantiated." , providerClass . getName ( ) , e ) ; } catch ( IllegalAccessException e ) { logger . error ( "The {} extension in use is not properly defined. " + "Please contact the developers of the extension or, if you " + "are the developer, turn on debug-level logging." ) ; logger . debug ( "Default constructor of {} is not public." , typeName , e ) ; } catch ( IllegalArgumentException e ) { logger . error ( "The {} extension in use is not properly defined. " + "Please contact the developers of the extension or, if you " + "are the developer, turn on debug-level logging." , typeName ) ; logger . debug ( "Default constructor of {} cannot accept zero arguments." , providerClass . getName ( ) , e ) ; } catch ( InvocationTargetException e ) { Throwable cause = e . getCause ( ) ; if ( cause == null ) cause = new GuacamoleException ( "Error encountered during initialization." ) ; logger . error ( "{} extension failed to start: {}" , typeName , cause . getMessage ( ) ) ; logger . debug ( "{} instantiation failed." , providerClass . getName ( ) , e ) ; } return instance ; } | Creates an instance of the specified provider class using the no - arg constructor . |
30,249 | private boolean hasObjectPermissions ( ModeledAuthenticatedUser user , String identifier , ObjectPermission . Type type ) throws GuacamoleException { ObjectPermissionSet permissionSet = getPermissionSet ( user ) ; return user . getUser ( ) . isAdministrator ( ) || permissionSet . hasPermission ( type , identifier ) ; } | Return a boolean value representing whether or not a user has the given permission available to them on the active connection with the given identifier . |
30,250 | public void interceptStream ( int index , OutputStream stream ) throws GuacamoleException { logger . debug ( "Intercepting output stream #{} of tunnel \"{}\"." , index , getUUID ( ) ) ; try { outputStreamFilter . interceptStream ( index , new BufferedOutputStream ( stream ) ) ; } finally { logger . debug ( "Intercepted output stream #{} of tunnel \"{}\" ended." , index , getUUID ( ) ) ; } } | Intercept all data received along the stream having the given index writing that data to the given OutputStream . The OutputStream will automatically be closed when the stream ends . If there is no such stream then the OutputStream will be closed immediately . This function will block until all received data has been written to the OutputStream and the OutputStream has been closed . |
30,251 | public void interceptStream ( int index , InputStream stream ) throws GuacamoleException { logger . debug ( "Intercepting input stream #{} of tunnel \"{}\"." , index , getUUID ( ) ) ; try { inputStreamFilter . interceptStream ( index , new BufferedInputStream ( stream ) ) ; } finally { logger . debug ( "Intercepted input stream #{} of tunnel \"{}\" ended." , index , getUUID ( ) ) ; } } | Intercept the given stream continuously writing the contents of the given InputStream as blobs . The stream will automatically end when when the end of the InputStream is reached . If there is no such stream then the InputStream will be closed immediately . This function will block until all data from the InputStream has been written to the given stream . |
30,252 | public void apply ( PermissionSet < PermissionType > permissionSet ) throws GuacamoleException { if ( ! addedPermissions . isEmpty ( ) ) permissionSet . addPermissions ( addedPermissions ) ; if ( ! removedPermissions . isEmpty ( ) ) permissionSet . removePermissions ( removedPermissions ) ; } | Applies all queued changes to the given permission set . |
30,253 | public Response getStreamContents ( ) { StreamingOutput stream = new StreamingOutput ( ) { public void write ( OutputStream output ) throws IOException { try { tunnel . interceptStream ( streamIndex , output ) ; } catch ( GuacamoleException e ) { throw new IOException ( e ) ; } } } ; ResponseBuilder responseBuilder = Response . ok ( stream , mediaType ) ; if ( mediaType . equals ( MediaType . APPLICATION_OCTET_STREAM ) ) responseBuilder . header ( "Content-Disposition" , "attachment" ) ; return responseBuilder . build ( ) ; } | Intercepts and returns the entire contents the stream represented by this StreamResource . |
30,254 | @ Consumes ( MediaType . WILDCARD ) public void setStreamContents ( InputStream data ) throws GuacamoleException { tunnel . interceptStream ( streamIndex , data ) ; } | Intercepts the stream represented by this StreamResource sending the contents of the given InputStream over that stream as blob instructions . |
30,255 | private LDAPConnection createLDAPConnection ( ) throws GuacamoleException { EncryptionMethod encryptionMethod = confService . getEncryptionMethod ( ) ; switch ( encryptionMethod ) { case NONE : logger . debug ( "Connection to LDAP server without encryption." ) ; return new LDAPConnection ( ) ; case SSL : logger . debug ( "Connecting to LDAP server using SSL/TLS." ) ; return new LDAPConnection ( new LDAPJSSESecureSocketFactory ( ) ) ; case STARTTLS : logger . debug ( "Connecting to LDAP server using STARTTLS." ) ; return new LDAPConnection ( new LDAPJSSEStartTLSFactory ( ) ) ; default : throw new GuacamoleUnsupportedException ( "Unimplemented encryption method: " + encryptionMethod ) ; } } | Creates a new instance of LDAPConnection configured as required to use whichever encryption method is requested within guacamole . properties . |
30,256 | public LDAPConnection bindAs ( String userDN , String password ) throws GuacamoleException { LDAPConnection ldapConnection = createLDAPConnection ( ) ; LDAPConstraints ldapConstraints = ldapConnection . getConstraints ( ) ; if ( ldapConstraints == null ) ldapConstraints = new LDAPConstraints ( ) ; ldapConstraints . setReferralFollowing ( confService . getFollowReferrals ( ) ) ; if ( userDN != null && ! userDN . isEmpty ( ) ) ldapConstraints . setReferralHandler ( new ReferralAuthHandler ( userDN , password ) ) ; ldapConstraints . setHopLimit ( confService . getMaxReferralHops ( ) ) ; ldapConstraints . setTimeLimit ( confService . getOperationTimeout ( ) * 1000 ) ; ldapConnection . setConstraints ( ldapConstraints ) ; try { ldapConnection . connect ( confService . getServerHostname ( ) , confService . getServerPort ( ) ) ; if ( confService . getEncryptionMethod ( ) == EncryptionMethod . STARTTLS ) ldapConnection . startTLS ( ) ; } catch ( LDAPException e ) { logger . error ( "Unable to connect to LDAP server: {}" , e . getMessage ( ) ) ; logger . debug ( "Failed to connect to LDAP server." , e ) ; return null ; } try { byte [ ] passwordBytes ; try { if ( password != null ) passwordBytes = password . getBytes ( "UTF-8" ) ; else passwordBytes = null ; } catch ( UnsupportedEncodingException e ) { logger . error ( "Unexpected lack of support for UTF-8: {}" , e . getMessage ( ) ) ; logger . debug ( "Support for UTF-8 (as required by Java spec) not found." , e ) ; disconnect ( ldapConnection ) ; return null ; } ldapConnection . bind ( LDAPConnection . LDAP_V3 , userDN , passwordBytes ) ; } catch ( LDAPException e ) { logger . debug ( "LDAP bind failed." , e ) ; disconnect ( ldapConnection ) ; return null ; } return ldapConnection ; } | Binds to the LDAP server using the provided user DN and password . |
30,257 | public void disconnect ( LDAPConnection ldapConnection ) { try { ldapConnection . disconnect ( ) ; } catch ( LDAPException e ) { logger . warn ( "Unable to disconnect from LDAP server: {}" , e . getMessage ( ) ) ; logger . debug ( "LDAP disconnect failed." , e ) ; } } | Disconnects the given LDAP connection logging any failure to do so appropriately . |
30,258 | @ Path ( "tree" ) public APIConnectionGroup getConnectionGroupTree ( @ QueryParam ( "permission" ) List < ObjectPermission . Type > permissions ) throws GuacamoleException { ConnectionGroupTree tree = new ConnectionGroupTree ( userContext , connectionGroup , permissions ) ; return tree . getRootAPIConnectionGroup ( ) ; } | Returns the current connection group along with all descendants . |
30,259 | public int getDigits ( ) throws GuacamoleException { int digits = environment . getProperty ( TOTP_DIGITS , 6 ) ; if ( digits < 6 || digits > 8 ) throw new GuacamoleServerException ( "TOTP codes may have no fewer " + "than 6 digits and no more than 8 digits." ) ; return digits ; } | Returns the number of digits which should be included in each generated TOTP code . If not specified 6 will be used by default . |
30,260 | public TOTPGenerator . Mode getMode ( ) throws GuacamoleException { return environment . getProperty ( TOTP_MODE , TOTPGenerator . Mode . SHA1 ) ; } | Returns the hash algorithm that should be used to generate TOTP codes . If not specified SHA1 will be used by default . |
30,261 | public Set < String > retrieveEffectiveGroups ( ModeledPermissions < ? extends EntityModel > entity , Collection < String > effectiveGroups ) { boolean recursive = environment . isRecursiveQuerySupported ( sqlSession ) ; Set < String > identifiers = entityMapper . selectEffectiveGroupIdentifiers ( entity . getModel ( ) , effectiveGroups , recursive ) ; if ( ! recursive && ! identifiers . isEmpty ( ) ) { Set < String > previousIdentifiers ; do { previousIdentifiers = identifiers ; identifiers = entityMapper . selectEffectiveGroupIdentifiers ( entity . getModel ( ) , previousIdentifiers , false ) ; } while ( identifiers . size ( ) > previousIdentifiers . size ( ) ) ; } return identifiers ; } | Returns the set of all group identifiers of which the given entity is a member taking into account the given collection of known group memberships which are not necessarily defined within the database . |
30,262 | public boolean isAtLeast ( MySQLVersion version ) { if ( isMariaDB != version . isMariaDB ) return false ; return ComparisonChain . start ( ) . compare ( major , version . major ) . compare ( minor , version . minor ) . compare ( patch , version . patch ) . result ( ) >= 0 ; } | Returns whether this version is at least as recent as the given version . |
30,263 | private void addReadPermissions ( Set < ObjectPermission > permissions , Collection < String > identifiers ) { identifiers . forEach ( identifier -> permissions . add ( new ObjectPermission ( ObjectPermission . Type . READ , identifier ) ) ) ; } | Adds a new READ permission to the given set of permissions for each of the given identifiers . |
30,264 | private static boolean generateAsResource ( MetaDataObject metaDataObject ) { if ( metaDataObject instanceof MetaResource ) { return true ; } List < MetaDataObject > subTypes = metaDataObject . getSubTypes ( true , false ) ; if ( ! subTypes . isEmpty ( ) ) { for ( MetaDataObject subType : subTypes ) { if ( generateAsResource ( subType ) ) { return true ; } } return false ; } return false ; } | Generate resources and their base classes as resources . |
30,265 | public void addModule ( Module module ) { LOGGER . debug ( "adding module {}" , module ) ; module . setupModule ( new ModuleContextImpl ( module ) ) ; modules . add ( module ) ; } | Register an new module to this registry and setup the module . |
30,266 | public < T > void addParser ( Class < T > clazz , StringParser < T > parser ) { parsers . put ( clazz , parser ) ; } | Adds a custom parser for the given type . |
30,267 | public < T > void addMapper ( Class < T > clazz , StringMapper < T > mapper ) { addParser ( clazz , mapper ) ; mappers . put ( clazz , mapper ) ; } | Adds a custom mapper for the given type . |
30,268 | @ SuppressWarnings ( "unchecked" ) protected I getIdFromEntity ( EntityManager em , Object entity , ResourceField idField ) { Object pk = em . getEntityManagerFactory ( ) . getPersistenceUnitUtil ( ) . getIdentifier ( entity ) ; PreconditionUtil . verify ( pk != null , "pk not available for entity %s" , entity ) ; if ( pk != null && primaryKeyAttribute . getName ( ) . equals ( idField . getUnderlyingName ( ) ) && idField . getElementType ( ) . isAssignableFrom ( pk . getClass ( ) ) ) { return ( I ) pk ; } return null ; } | Extracts the resource ID from the entity . By default it uses the entity s primary key if the field name matches the DTO s ID field . Override in subclasses if a different entity field should be used . |
30,269 | public void boot ( ) { LOGGER . debug ( "performing setup" ) ; checkNotConfiguredYet ( ) ; configured = true ; moduleRegistry . setPropertiesProvider ( propertiesProvider ) ; setupServiceUrlProvider ( ) ; setupServiceDiscovery ( ) ; setupQuerySpecUrlMapper ( ) ; bootDiscovery ( ) ; LOGGER . debug ( "completed setup" ) ; } | Performs the setup . |
30,270 | @ SuppressWarnings ( "UnnecessaryLocalVariable" ) public static boolean isJsonApiRequest ( HttpRequestContext requestContext , boolean acceptPlainJson ) { String method = requestContext . getMethod ( ) . toUpperCase ( ) ; boolean isPatch = method . equals ( HttpMethod . PATCH . toString ( ) ) ; boolean isPost = method . equals ( HttpMethod . POST . toString ( ) ) ; if ( isPatch || isPost ) { String contentType = requestContext . getRequestHeader ( HttpHeaders . HTTP_CONTENT_TYPE ) ; if ( contentType == null || ! contentType . startsWith ( HttpHeaders . JSONAPI_CONTENT_TYPE ) ) { LOGGER . warn ( "not a JSON-API request due to content type {}" , contentType ) ; return false ; } } boolean acceptsJsonApi = requestContext . accepts ( HttpHeaders . JSONAPI_CONTENT_TYPE ) ; boolean acceptsAny = acceptsJsonApi || requestContext . acceptsAny ( ) ; boolean acceptsPlainJson = acceptsAny || ( acceptPlainJson && requestContext . accepts ( "application/json" ) ) ; LOGGER . debug ( "accepting request as JSON-API: {}" , acceptPlainJson ) ; return acceptsPlainJson ; } | Determines whether the supplied HTTP request is considered a JSON - API request . |
30,271 | private void handleIdOverride ( Class < ? > resourceClass , List < ResourceField > fields ) { List < ResourceField > idFields = fields . stream ( ) . filter ( field -> field . getResourceFieldType ( ) == ResourceFieldType . ID ) . collect ( Collectors . toList ( ) ) ; if ( idFields . size ( ) == 2 ) { ResourceField field0 = idFields . get ( 0 ) ; ResourceField field1 = idFields . get ( 1 ) ; BeanInformation beanInformation = BeanInformation . get ( resourceClass ) ; BeanAttributeInformation attr0 = beanInformation . getAttribute ( field0 . getUnderlyingName ( ) ) ; BeanAttributeInformation attr1 = beanInformation . getAttribute ( field1 . getUnderlyingName ( ) ) ; boolean jsonApiId0 = attr0 . getAnnotation ( JsonApiId . class ) . isPresent ( ) ; boolean jsonApiId1 = attr1 . getAnnotation ( JsonApiId . class ) . isPresent ( ) ; if ( jsonApiId0 && ! jsonApiId1 ) { ( ( ResourceFieldImpl ) field1 ) . setResourceFieldType ( ResourceFieldType . ATTRIBUTE ) ; ( ( ResourceFieldImpl ) field1 ) . setJsonName ( getJsonName ( attr1 , ResourceFieldType . ATTRIBUTE ) ) ; } else if ( ! jsonApiId0 && jsonApiId1 ) { ( ( ResourceFieldImpl ) field0 ) . setResourceFieldType ( ResourceFieldType . ATTRIBUTE ) ; ( ( ResourceFieldImpl ) field0 ) . setJsonName ( getJsonName ( attr0 , ResourceFieldType . ATTRIBUTE ) ) ; } } } | make sure that |
30,272 | private void registerActionRepositories ( FeatureContext context , CrnkBoot boot ) { ResourceRegistry resourceRegistry = boot . getResourceRegistry ( ) ; Collection < RegistryEntry > registryEntries = resourceRegistry . getEntries ( ) ; for ( RegistryEntry registryEntry : registryEntries ) { ResourceRepositoryInformation repositoryInformation = registryEntry . getRepositoryInformation ( ) ; if ( repositoryInformation != null && ! repositoryInformation . getActions ( ) . isEmpty ( ) ) { ResourceRepositoryAdapter repositoryAdapter = registryEntry . getResourceRepository ( ) ; Object resourceRepository = repositoryAdapter . getResourceRepository ( ) ; context . register ( resourceRepository ) ; } } } | All repositories with JAX - RS action need to be registered with JAX - RS as singletons . |
30,273 | @ SuppressWarnings ( "unchecked" ) public Result < Set < Resource > > lookupRelatedResource ( IncludeRequest request , Collection < Resource > sourceResources , ResourceField relationshipField ) { if ( sourceResources . isEmpty ( ) ) { return resultFactory . just ( Collections . emptySet ( ) ) ; } Collection < Resource > sourceResourcesWithData = new ArrayList < > ( ) ; Collection < Resource > sourceResourcesWithoutData = new ArrayList < > ( ) ; for ( Resource sourceResource : sourceResources ) { boolean present = sourceResource . getRelationships ( ) . get ( relationshipField . getJsonName ( ) ) . getData ( ) . isPresent ( ) ; if ( present ) { sourceResourcesWithData . add ( sourceResource ) ; } else { sourceResourcesWithoutData . add ( sourceResource ) ; } } Set < Resource > relatedResources = new HashSet < > ( ) ; Result < Set < Resource > > result = resultFactory . just ( relatedResources ) ; if ( ! sourceResourcesWithData . isEmpty ( ) ) { Result < Set < Resource > > lookupWithId = lookupRelatedResourcesWithId ( request , sourceResourcesWithData , relationshipField ) ; result = result . zipWith ( lookupWithId , this :: mergeList ) ; } if ( ! sourceResourcesWithoutData . isEmpty ( ) ) { Result < Set < Resource > > lookupWithoutData = lookupRelatedResourceWithRelationship ( request , sourceResourcesWithoutData , relationshipField ) ; result = result . zipWith ( lookupWithoutData , this :: mergeList ) ; } return result ; } | Loads all related resources for the given resources and relationship field . It updates the relationship data of the source resources accordingly and returns the loaded resources for potential inclusion in the result resource . |
30,274 | private ResourceRef resolvePath ( ConstraintViolation < ? > violation ) { Object resource = violation . getRootBean ( ) ; Object nodeObject = resource ; ResourceRef ref = new ResourceRef ( resource ) ; Iterator < Node > iterator = violation . getPropertyPath ( ) . iterator ( ) ; while ( iterator . hasNext ( ) ) { Node node = iterator . next ( ) ; if ( node . getKind ( ) == ElementKind . METHOD ) { continue ; } if ( node . getKind ( ) == ElementKind . PARAMETER ) { resource = getParameterValue ( node ) ; nodeObject = resource ; ref = new ResourceRef ( resource ) ; assertResource ( resource ) ; continue ; } nodeObject = ref . getNodeReference ( nodeObject , node ) ; ref . visitNode ( nodeObject ) ; nodeObject = ref . visitProperty ( nodeObject , node ) ; } return ref ; } | Translate validated bean and root path into validated resource and resource path . For example embeddables belonging to an entity document are mapped back to an entity violation and a proper path to the embeddable attribute . |
30,275 | public void filter ( ContainerRequestContext requestContext , ContainerResponseContext responseContext ) { Object response = responseContext . getEntity ( ) ; if ( response == null ) { if ( feature . getBoot ( ) . isNullDataResponseEnabled ( ) ) { Document document = new Document ( ) ; document . setData ( Nullable . nullValue ( ) ) ; responseContext . setEntity ( document ) ; responseContext . setStatus ( Response . Status . OK . getStatusCode ( ) ) ; responseContext . getHeaders ( ) . put ( "Content-Type" , Collections . singletonList ( JsonApiMediaType . APPLICATION_JSON_API ) ) ; } return ; } Optional < RegistryEntry > registryEntry = getRegistryEntry ( response ) ; if ( registryEntry . isPresent ( ) ) { CrnkBoot boot = feature . getBoot ( ) ; DocumentMapper documentMapper = boot . getDocumentMapper ( ) ; HttpRequestContextProvider httpRequestContextProvider = boot . getModuleRegistry ( ) . getHttpRequestContextProvider ( ) ; try { HttpRequestContext context = new HttpRequestContextBaseAdapter ( new JaxrsRequestContext ( requestContext , feature ) ) ; httpRequestContextProvider . onRequestStarted ( context ) ; JsonApiResponse jsonApiResponse = new JsonApiResponse ( ) ; jsonApiResponse . setEntity ( response ) ; DocumentMappingConfig mappingConfig = new DocumentMappingConfig ( ) ; ResourceInformation resourceInformation = registryEntry . get ( ) . getResourceInformation ( ) ; Map < String , Set < String > > jsonApiParameters = context . getRequestParameters ( ) . entrySet ( ) . stream ( ) . filter ( entry -> isJsonApiParameter ( entry . getKey ( ) ) ) . collect ( Collectors . toMap ( Map . Entry :: getKey , Map . Entry :: getValue ) ) ; QuerySpecUrlMapper urlMapper = feature . getBoot ( ) . getUrlMapper ( ) ; QuerySpec querySpec = urlMapper . deserialize ( resourceInformation , jsonApiParameters ) ; ResourceRegistry resourceRegistry = feature . getBoot ( ) . getResourceRegistry ( ) ; QueryAdapter queryAdapter = new QuerySpecAdapter ( querySpec , resourceRegistry , context . getQueryContext ( ) ) ; responseContext . setEntity ( documentMapper . toDocument ( jsonApiResponse , queryAdapter , mappingConfig ) . get ( ) ) ; responseContext . getHeaders ( ) . put ( "Content-Type" , Collections . singletonList ( JsonApiMediaType . APPLICATION_JSON_API ) ) ; } finally { httpRequestContextProvider . onRequestFinished ( ) ; } } else if ( isJsonApiResponse ( responseContext ) && ! doNotWrap ( response ) ) { Document document = new Document ( ) ; document . setData ( Nullable . of ( response ) ) ; responseContext . setEntity ( document ) ; } } | Creates JSON API responses for custom JAX - RS actions returning Crnk resources . |
30,276 | private Optional < RegistryEntry > getRegistryEntry ( Object response ) { if ( response != null ) { Class responseClass = response . getClass ( ) ; boolean resourceList = ResourceList . class . isAssignableFrom ( responseClass ) ; if ( resourceList ) { ResourceList responseList = ( ResourceList ) response ; if ( responseList . isEmpty ( ) ) { return Optional . empty ( ) ; } Class elementType = responseList . get ( 0 ) . getClass ( ) ; for ( int i = 0 ; i < responseList . size ( ) ; i ++ ) { Class otherType = responseList . get ( i ) . getClass ( ) ; while ( ! elementType . isAssignableFrom ( otherType ) ) { elementType = elementType . getSuperclass ( ) ; } } responseClass = elementType ; } ResourceRegistry resourceRegistry = feature . getBoot ( ) . getResourceRegistry ( ) ; if ( resourceRegistry . hasEntry ( responseClass ) ) { return Optional . of ( resourceRegistry . getEntry ( responseClass ) ) ; } } return Optional . empty ( ) ; } | Determines whether the given response entity is either a Crnk resource or a list of resource ; |
30,277 | protected int applyDistinct ( ) { int numAutoSelections = 0 ; boolean distinct ; if ( query . autoDistinct ) { distinct = query . autoDistinct && ! query . autoGroupBy && backend . hasManyRootsFetchesOrJoins ( ) ; if ( distinct ) { numAutoSelections = addOrderExpressionsToSelection ( ) ; } } else { distinct = query . distinct ; } if ( distinct ) { backend . distinct ( ) ; } return numAutoSelections ; } | Adds order expressions to selection if in auto distinct mode and the query performs a join or fetch on a relation . In this case attributes from referenced entities inlucded in the sort clause must be added to the select clause as well . |
30,278 | public static JpaModule newServerModule ( EntityManagerFactory emFactory , EntityManager em , TransactionRunner transactionRunner ) { JpaModuleConfig config = new JpaModuleConfig ( ) ; config . exposeAllEntities ( emFactory ) ; return new JpaModule ( config , emFactory , ( ) -> em , transactionRunner ) ; } | Creates a new JpaModule for a Crnk server . All entities managed by the provided EntityManagerFactory are registered to the module and exposed as JSON API resources if not later configured otherwise . |
30,279 | private boolean setupManyNesting ( ) { BeanAttributeInformation parentAttribute = null ; BeanAttributeInformation idAttribute = null ; BeanInformation beanInformation = BeanInformation . get ( idField . getType ( ) ) ; for ( String attributeName : beanInformation . getAttributeNames ( ) ) { BeanAttributeInformation attribute = beanInformation . getAttribute ( attributeName ) ; if ( attribute . getAnnotation ( JsonApiRelationId . class ) . isPresent ( ) ) { PreconditionUtil . verify ( parentAttribute == null , "nested identifiers can only have a single @JsonApiRelationId annotated field, got multiple for %s" , beanInformation . getImplementationClass ( ) ) ; parentAttribute = attribute ; } else if ( attribute . getAnnotation ( JsonApiId . class ) . isPresent ( ) ) { PreconditionUtil . verify ( idAttribute == null , "nested identifiers can only one attribute being annotated with @JsonApiId, got multiple for %s" , beanInformation . getImplementationClass ( ) ) ; idAttribute = attribute ; } } if ( parentAttribute != null || idAttribute != null ) { if ( ! shouldBeNested ( ) ) { LOGGER . warn ( "add @JsonApiResource(nested=true) to {} to mark it as being nested, in the future automatic discovery based on the id will be removed" , implementationClass ) ; } PreconditionUtil . verify ( idAttribute != null , "nested identifiers must have attribute annotated with @JsonApiId, got none for %s" , beanInformation . getImplementationClass ( ) ) ; PreconditionUtil . verify ( parentAttribute != null , "nested identifiers must have attribute annotated with @JsonApiRelationId, got none for %s" , beanInformation . getImplementationClass ( ) ) ; String relationshipName = parentAttribute . getName ( ) . substring ( 0 , parentAttribute . getName ( ) . length ( ) - 2 ) ; this . parentIdAccessor = new NestedIdAccessor ( parentAttribute ) ; this . childIdAccessor = new NestedIdAccessor ( idAttribute ) ; String parentName = parentAttribute . getName ( ) ; Optional < ResourceField > optParentField = relationshipFields . stream ( ) . filter ( it -> it . hasIdField ( ) && it . getIdName ( ) . equals ( parentName ) ) . findFirst ( ) ; if ( optParentField . isPresent ( ) ) { parentField = optParentField . get ( ) ; } else { PreconditionUtil . verify ( parentAttribute . getName ( ) . endsWith ( "Id" ) , "nested identifier must have @JsonApiRelationId field being named with a 'Id' suffix or match in name with a @JsonApiRelationId annotated field on the resource, got %s for %s" , parentAttribute . getName ( ) , beanInformation . getImplementationClass ( ) ) ; parentField = findRelationshipFieldByName ( relationshipName ) ; PreconditionUtil . verify ( parentField != null , "naming of relationship to parent resource and relationship identifier within resource identifier must " + "match, not found for %s of %s" , parentAttribute . getName ( ) , implementationClass ) ; ( ( ResourceFieldImpl ) parentField ) . setIdField ( parentAttribute . getName ( ) , parentAttribute . getImplementationClass ( ) , parentIdAccessor ) ; } return true ; } return false ; } | in the future |
30,280 | public String toIdString ( Object id ) { if ( id == null ) { return null ; } return idStringMapper . toString ( id ) ; } | Converts the given id to a string . |
30,281 | public final Response handle ( JsonPath jsonPath , QueryAdapter queryAdapter , Document requestDocument ) { Result < Response > response = handleAsync ( jsonPath , queryAdapter , requestDocument ) ; PreconditionUtil . verify ( response != null , "no response by controller provided" ) ; return response . get ( ) ; } | Passes the request to controller method . |
30,282 | public static List < Field > getClassFields ( Class < ? > beanClass ) { Map < String , Field > resultMap = new HashMap < > ( ) ; LinkedList < Field > results = new LinkedList < > ( ) ; Class < ? > currentClass = beanClass ; while ( currentClass != null && currentClass != Object . class ) { for ( Field field : currentClass . getDeclaredFields ( ) ) { if ( ! field . isSynthetic ( ) ) { Field v = resultMap . get ( field . getName ( ) ) ; if ( v == null ) { resultMap . put ( field . getName ( ) , field ) ; results . add ( field ) ; } } } currentClass = currentClass . getSuperclass ( ) ; } return results ; } | Returns a list of class fields . Supports inheritance and doesn t return synthetic fields . |
30,283 | public static < T extends Annotation > Optional < T > getAnnotation ( Class < ? > beanClass , Class < T > annotationClass ) { Class < ? > currentClass = beanClass ; while ( currentClass != null && currentClass != Object . class ) { if ( currentClass . isAnnotationPresent ( annotationClass ) ) { return Optional . of ( currentClass . getAnnotation ( annotationClass ) ) ; } currentClass = currentClass . getSuperclass ( ) ; } return Optional . empty ( ) ; } | Returns an instance of bean s annotation |
30,284 | public static Field findClassField ( Class < ? > beanClass , String fieldName ) { Class < ? > currentClass = beanClass ; while ( currentClass != null && currentClass != Object . class ) { for ( Field field : currentClass . getDeclaredFields ( ) ) { if ( field . isSynthetic ( ) ) { continue ; } if ( field . getName ( ) . equals ( fieldName ) ) { return field ; } } currentClass = currentClass . getSuperclass ( ) ; } return null ; } | Tries to find a class fields . Supports inheritance and doesn t return synthetic fields . |
30,285 | public static List < Method > getClassSetters ( Class < ? > beanClass ) { Map < String , Method > result = new HashMap < > ( ) ; Class < ? > currentClass = beanClass ; while ( currentClass != null && currentClass != Object . class ) { for ( Method method : currentClass . getDeclaredMethods ( ) ) { if ( ! method . isSynthetic ( ) && isSetter ( method ) ) { result . putIfAbsent ( method . getName ( ) , method ) ; } } currentClass = currentClass . getSuperclass ( ) ; } return new LinkedList < > ( result . values ( ) ) ; } | Return a list of class setters . Supports inheritance and overriding that is when a method is found on the lowest level of inheritance chain no other method can override it . Supports inheritance and doesn t return synthetic methods . |
30,286 | public static Class < ? > getRawType ( Type type ) { if ( type instanceof Class ) { return ( Class < ? > ) type ; } else if ( type instanceof ParameterizedType ) { return getRawType ( ( ( ParameterizedType ) type ) . getRawType ( ) ) ; } else if ( type instanceof TypeVariable < ? > ) { return getRawType ( ( ( TypeVariable < ? > ) type ) . getBounds ( ) [ 0 ] ) ; } throw new IllegalStateException ( "unknown type: " + type ) ; } | Given a type this method resolves the corresponding raw type . |
30,287 | public void reconfigure ( SecurityConfig config ) { this . config = config ; LOGGER . debug ( "reconfiguring with {} rules" , config . getRules ( ) . size ( ) ) ; Map < String , Map < String , ResourcePermission > > newPermissions = new HashMap < > ( ) ; for ( SecurityRule rule : config . getRules ( ) ) { String resourceType = rule . getResourceType ( ) ; if ( resourceType == null ) { Class < ? > resourceClass = rule . getResourceClass ( ) ; if ( resourceClass != null ) { resourceType = toType ( resourceClass ) ; } } if ( resourceType == null ) { Collection < RegistryEntry > entries = context . getResourceRegistry ( ) . getEntries ( ) ; for ( RegistryEntry entry : entries ) { String entryResourceType = entry . getResourceInformation ( ) . getResourceType ( ) ; configureRule ( newPermissions , entryResourceType , rule . getRole ( ) , rule . getPermission ( ) ) ; } } else { ResourceRegistry resourceRegistry = context . getResourceRegistry ( ) ; RegistryEntry entry = resourceRegistry . getEntry ( resourceType ) ; if ( entry == null ) { throw new RepositoryNotFoundException ( resourceType ) ; } configureRule ( newPermissions , resourceType , rule . getRole ( ) , rule . getPermission ( ) ) ; } } this . permissions = newPermissions ; } | Applies the new configuration to this module . |
30,288 | public boolean isUserInRole ( String role ) { if ( ! isEnabled ( ) ) { throw new IllegalStateException ( "security module is disabled" ) ; } checkInit ( ) ; SecurityProvider securityProvider = context . getSecurityProvider ( ) ; boolean contained = role == ALL_ROLE || securityProvider . isUserInRole ( role ) ; LOGGER . debug ( "isUserInRole returns {} for role {}" , contained , role ) ; return contained ; } | Checks whether the current user posses the provided role |
30,289 | public void findModules ( ) { ServiceLoader < ClientModuleFactory > loader = ServiceLoader . load ( ClientModuleFactory . class ) ; Iterator < ClientModuleFactory > iterator = loader . iterator ( ) ; while ( iterator . hasNext ( ) ) { ClientModuleFactory factory = iterator . next ( ) ; Module module = factory . create ( ) ; addModule ( module ) ; } objectMapper . findAndRegisterModules ( ) ; } | Finds and registers modules on the classpath trough the use of java . util . ServiceLoader . Each module can register itself for lookup by registering a ClientModuleFactory . |
30,290 | public static TSModule getNestedTypeContainer ( TSType type , boolean create ) { TSContainerElement parent = ( TSContainerElement ) type . getParent ( ) ; if ( parent == null ) { return null ; } int insertionIndex = parent . getElements ( ) . indexOf ( type ) ; return getModule ( parent , type . getName ( ) , insertionIndex , create ) ; } | Creates a module if the same name as the provided type used to hold nested types . |
30,291 | public static String toFileName ( String name ) { char [ ] charArray = name . toCharArray ( ) ; StringBuilder builder = new StringBuilder ( ) ; for ( int i = 0 ; i < charArray . length ; i ++ ) { if ( Character . isUpperCase ( charArray [ i ] ) && i > 0 && ! Character . isUpperCase ( charArray [ i - 1 ] ) ) { builder . append ( '.' ) ; } builder . append ( Character . toLowerCase ( charArray [ i ] ) ) ; } return builder . toString ( ) ; } | transforms helloWorld to hello . world to more closely resemble typical typescript naming . |
30,292 | public < L extends LinksInformation > L as ( Class < L > linksClass ) { try { ObjectReader reader = mapper . readerFor ( linksClass ) ; return reader . readValue ( data ) ; } catch ( IOException e ) { throw new IllegalStateException ( e ) ; } } | Converts this generic links information to the provided type . |
30,293 | public List < OperationResponse > apply ( List < Operation > operations , QueryContext queryContext ) { checkAccess ( operations , queryContext ) ; enrichTypeIdInformation ( operations ) ; List < OrderedOperation > orderedOperations = orderStrategy . order ( operations ) ; DefaultOperationFilterChain chain = new DefaultOperationFilterChain ( ) ; return chain . doFilter ( new DefaultOperationFilterContext ( orderedOperations ) ) ; } | Applies the given set of operations . |
30,294 | private void checkAccess ( List < Operation > operations , QueryContext queryContext ) { for ( Operation operation : operations ) { checkAccess ( operation , queryContext ) ; } } | This is not strictly necessary but allows to catch security issues early before accessing the individual repositories |
30,295 | private void compact ( Document doc , QueryAdapter queryAdapter ) { if ( queryAdapter != null && queryAdapter . getCompactMode ( ) ) { if ( doc . getIncluded ( ) != null ) { compact ( doc . getIncluded ( ) ) ; } if ( doc . getData ( ) . isPresent ( ) ) { if ( doc . isMultiple ( ) ) { compact ( doc . getCollectionData ( ) . get ( ) ) ; } else { compact ( doc . getSingleData ( ) . get ( ) ) ; } } } } | removes unncessary json elements |
30,296 | public < T > void addRepository ( JpaRepositoryConfig < T > config ) { Class < ? > resourceClass = config . getResourceClass ( ) ; if ( repositoryConfigurationMap . containsKey ( resourceClass ) ) { throw new IllegalStateException ( resourceClass . getName ( ) + " is already registered" ) ; } repositoryConfigurationMap . put ( resourceClass , config ) ; } | Adds the resource to this module . |
30,297 | public void exposeAllEntities ( EntityManagerFactory emf ) { Set < ManagedType < ? > > managedTypes = emf . getMetamodel ( ) . getManagedTypes ( ) ; for ( ManagedType < ? > managedType : managedTypes ) { Class < ? > managedJavaType = managedType . getJavaType ( ) ; if ( managedJavaType . getAnnotation ( Entity . class ) != null ) { addRepository ( JpaRepositoryConfig . builder ( managedJavaType ) . build ( ) ) ; } } } | Exposes all entities as repositories . |
30,298 | public static < E > JpaRepositoryConfig . Builder < E > builder ( Class < E > entityClass ) { JpaRepositoryConfig . Builder < E > builder = new JpaRepositoryConfig . Builder < > ( ) ; builder . entityClass = entityClass ; builder . resourceClass = entityClass ; return builder ; } | Prepares a builder to configure a jpa document for the given entity . |
30,299 | public static < E , D > JpaRepositoryConfig . Builder < D > builder ( Class < E > entityClass , Class < D > dtoClass , JpaMapper < E , D > mapper ) { JpaRepositoryConfig . Builder < D > builder = new JpaRepositoryConfig . Builder < > ( ) ; builder . entityClass = entityClass ; builder . resourceClass = dtoClass ; builder . mapper = mapper ; return builder ; } | Prepares a builder to configure a jpa document for the given entity class which is mapped to a DTO with the provided mapper . |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.