idx
int64
0
41.2k
question
stringlengths
73
5.81k
target
stringlengths
5
918
36,300
public static List < String > pathParams ( String param , ContainerRequestContext ctx ) { return ctx . getUriInfo ( ) . getPathParameters ( ) . get ( param ) ; }
Returns the path parameters values .
36,301
public static String queryParam ( String param , ContainerRequestContext ctx ) { return ctx . getUriInfo ( ) . getQueryParameters ( ) . getFirst ( param ) ; }
Returns the query parameter value .
36,302
public static List < String > queryParams ( String param , ContainerRequestContext ctx ) { return ctx . getUriInfo ( ) . getQueryParameters ( ) . get ( param ) ; }
Returns the query parameter values .
36,303
public static boolean hasQueryParam ( String param , ContainerRequestContext ctx ) { return ctx . getUriInfo ( ) . getQueryParameters ( ) . containsKey ( param ) ; }
Returns true if parameter exists .
36,304
public String getUrl ( ) { if ( StringUtils . isBlank ( url ) && ! StringUtils . isBlank ( name ) ) { this . url = AWSQueueUtils . createQueue ( name ) ; } return url ; }
Returns the queue URL on SQS .
36,305
private boolean isIncluded ( final HttpServletRequest request ) { final String uri = ( String ) request . getAttribute ( "javax.servlet.include.request_uri" ) ; final boolean includeRequest = ! ( uri == null ) ; if ( includeRequest && log . isDebugEnabled ( ) ) { log . debug ( "{} resulted in an include request. This is unusable, because" + "the response will be assembled into the overrall response. Not gzipping." , request . getRequestURL ( ) ) ; } return includeRequest ; }
Checks if the request uri is an include . These cannot be gzipped .
36,306
public static Date parseAWSDate ( String date ) { if ( date == null ) { return null ; } return TIME_FORMATTER . parseDateTime ( date ) . toDate ( ) ; }
Returns a parsed Date .
36,307
public Map < String , String > signRequest ( String accessKey , String secretKey , String httpMethod , String endpointURL , String reqPath , Map < String , String > headers , MultivaluedMap < String , String > params , byte [ ] jsonEntity ) { if ( StringUtils . isBlank ( accessKey ) ) { logger . error ( "Blank access key: {} {}" , httpMethod , reqPath ) ; return headers ; } if ( StringUtils . isBlank ( secretKey ) ) { logger . debug ( "Anonymous request: {} {}" , httpMethod , reqPath ) ; if ( headers == null ) { headers = new HashMap < > ( ) ; } headers . put ( HttpHeaders . AUTHORIZATION , "Anonymous " + accessKey ) ; return headers ; } if ( httpMethod == null ) { httpMethod = HttpMethod . GET ; } InputStream in = null ; Map < String , String > sigParams = new HashMap < > ( ) ; if ( params != null ) { for ( Map . Entry < String , List < String > > param : params . entrySet ( ) ) { String key = param . getKey ( ) ; List < String > value = param . getValue ( ) ; if ( value != null && ! value . isEmpty ( ) && value . get ( 0 ) != null ) { sigParams . put ( key , value . get ( 0 ) ) ; } } } if ( jsonEntity != null && jsonEntity . length > 0 ) { in = new ByteArrayInputStream ( jsonEntity ) ; } return sign ( httpMethod , endpointURL , reqPath , headers , sigParams , in , accessKey , secretKey ) ; }
Builds and signs a request to an API endpoint using the provided credentials .
36,308
public static String [ ] validateObject ( ParaObject content ) { if ( content == null ) { return new String [ ] { "Object cannot be null." } ; } LinkedList < String > list = new LinkedList < > ( ) ; try { for ( ConstraintViolation < ParaObject > constraintViolation : getValidator ( ) . validate ( content ) ) { String prop = "'" . concat ( constraintViolation . getPropertyPath ( ) . toString ( ) ) . concat ( "'" ) ; list . add ( prop . concat ( " " ) . concat ( constraintViolation . getMessage ( ) ) ) ; } } catch ( Exception e ) { logger . error ( null , e ) ; } return list . toArray ( new String [ ] { } ) ; }
Validates objects using Hibernate Validator .
36,309
public static String [ ] validateObject ( App app , ParaObject content ) { if ( content == null || app == null ) { return new String [ ] { "Object cannot be null." } ; } try { String type = content . getType ( ) ; boolean isCustomType = ( content instanceof Sysprop ) && ! type . equals ( Utils . type ( Sysprop . class ) ) ; if ( ! app . getValidationConstraints ( ) . isEmpty ( ) && isCustomType ) { Map < String , Map < String , Map < String , ? > > > fieldsMap = app . getValidationConstraints ( ) . get ( type ) ; if ( fieldsMap != null && ! fieldsMap . isEmpty ( ) ) { LinkedList < String > errors = new LinkedList < > ( ) ; for ( Map . Entry < String , Map < String , Map < String , ? > > > e : fieldsMap . entrySet ( ) ) { String field = e . getKey ( ) ; Object actualValue = ( ( Sysprop ) content ) . getProperty ( field ) ; if ( actualValue == null && PropertyUtils . isReadable ( content , field ) ) { actualValue = PropertyUtils . getProperty ( content , field ) ; } Map < String , Map < String , ? > > consMap = e . getValue ( ) ; for ( Map . Entry < String , Map < String , ? > > constraint : consMap . entrySet ( ) ) { buildAndValidateConstraint ( constraint , field , actualValue , errors ) ; } } if ( ! errors . isEmpty ( ) ) { return errors . toArray ( new String [ 0 ] ) ; } } } } catch ( Exception ex ) { logger . error ( null , ex ) ; } return validateObject ( content ) ; }
Validates objects .
36,310
public static Map < String , Map < String , Map < String , Map < String , ? > > > > getCoreValidationConstraints ( ) { if ( CORE_CONSTRAINTS . isEmpty ( ) ) { for ( Map . Entry < String , Class < ? extends ParaObject > > e : ParaObjectUtils . getCoreClassesMap ( ) . entrySet ( ) ) { String type = e . getKey ( ) ; List < Field > fieldlist = Utils . getAllDeclaredFields ( e . getValue ( ) ) ; for ( Field field : fieldlist ) { Annotation [ ] annos = field . getAnnotations ( ) ; if ( annos . length > 1 ) { Map < String , Map < String , ? > > constrMap = new HashMap < > ( ) ; for ( Annotation anno : annos ) { if ( isValidConstraintType ( anno . annotationType ( ) ) ) { Constraint c = fromAnnotation ( anno ) ; if ( c != null ) { constrMap . put ( c . getName ( ) , c . getPayload ( ) ) ; } } } if ( ! constrMap . isEmpty ( ) ) { if ( ! CORE_CONSTRAINTS . containsKey ( type ) ) { CORE_CONSTRAINTS . put ( type , new HashMap < > ( ) ) ; } CORE_CONSTRAINTS . get ( type ) . put ( field . getName ( ) , constrMap ) ; } } } } } return Collections . unmodifiableMap ( CORE_CONSTRAINTS ) ; }
Returns all validation constraints that are defined by Java annotation in the core classes .
36,311
public Object invoke ( MethodInvocation mi ) throws Throwable { if ( ! Modifier . isPublic ( mi . getMethod ( ) . getModifiers ( ) ) ) { return mi . proceed ( ) ; } Method daoMethod = mi . getMethod ( ) ; Object [ ] args = mi . getArguments ( ) ; String appid = AOPUtils . getFirstArgOfString ( args ) ; Method superMethod = null ; Indexed indexedAnno = null ; Cached cachedAnno = null ; try { superMethod = DAO . class . getMethod ( daoMethod . getName ( ) , daoMethod . getParameterTypes ( ) ) ; indexedAnno = Config . isSearchEnabled ( ) ? superMethod . getAnnotation ( Indexed . class ) : null ; cachedAnno = Config . isCacheEnabled ( ) ? superMethod . getAnnotation ( Cached . class ) : null ; detectNestedInvocations ( daoMethod ) ; } catch ( Exception e ) { logger . error ( "Error in AOP layer!" , e ) ; } Set < IOListener > ioListeners = Para . getIOListeners ( ) ; for ( IOListener ioListener : ioListeners ) { ioListener . onPreInvoke ( superMethod , args ) ; logger . debug ( "Executed {}.onPreInvoke()." , ioListener . getClass ( ) . getName ( ) ) ; } Object result = handleIndexing ( indexedAnno , appid , daoMethod , args , mi ) ; Object cachingResult = handleCaching ( cachedAnno , appid , daoMethod , args , mi ) ; if ( result == null && cachingResult != null ) { result = cachingResult ; } if ( indexedAnno == null && cachedAnno == null ) { result = invokeDAO ( appid , daoMethod , mi ) ; } for ( IOListener ioListener : ioListeners ) { ioListener . onPostInvoke ( superMethod , result ) ; logger . debug ( "Executed {}.onPostInvoke()." , ioListener . getClass ( ) . getName ( ) ) ; } return result ; }
Executes code when a method is invoked . A big switch statement .
36,312
public static Context time ( String appid , Class < ? > clazz , String ... names ) { String className = getClassName ( clazz ) ; Timer systemTimer = getTimer ( SYSTEM_METRICS_NAME , className , names ) ; Timer appTimer = appid == null || appid . isEmpty ( ) ? null : getTimer ( appid , className , names ) ; return new Context ( systemTimer , appTimer ) ; }
Instantiate timing of a particular class and method for a specific application .
36,313
public static Counter counter ( String appid , Class < ? > clazz , String ... names ) { String className = getClassName ( clazz ) ; return getCounter ( App . isRoot ( appid ) ? SYSTEM_METRICS_NAME : appid , className , names ) ; }
Creates a new counter for a particular class and method for a specific application .
36,314
@ SuppressWarnings ( "unchecked" ) public UserAuthentication getOrCreateUser ( App app , String accessToken ) throws IOException { UserAuthentication userAuth = null ; User user = new User ( ) ; if ( accessToken != null ) { String ctype = null ; HttpEntity respEntity = null ; CloseableHttpResponse resp2 = null ; try { HttpGet profileGet = new HttpGet ( PROFILE_URL + accessToken ) ; resp2 = httpclient . execute ( profileGet ) ; respEntity = resp2 . getEntity ( ) ; ctype = resp2 . getFirstHeader ( HttpHeaders . CONTENT_TYPE ) . getValue ( ) ; } catch ( Exception e ) { logger . warn ( "Facebook auth request failed: GET " + PROFILE_URL + accessToken , e ) ; } if ( respEntity != null && Utils . isJsonType ( ctype ) ) { Map < String , Object > profile = jreader . readValue ( respEntity . getContent ( ) ) ; if ( profile != null && profile . containsKey ( "id" ) ) { String fbId = ( String ) profile . get ( "id" ) ; String email = ( String ) profile . get ( "email" ) ; String name = ( String ) profile . get ( "name" ) ; user . setAppid ( getAppid ( app ) ) ; user . setIdentifier ( Config . FB_PREFIX . concat ( fbId ) ) ; user . setEmail ( email ) ; user = User . readUserForIdentifier ( user ) ; if ( user == null ) { user = new User ( ) ; user . setActive ( true ) ; user . setAppid ( getAppid ( app ) ) ; user . setEmail ( StringUtils . isBlank ( email ) ? fbId + "@facebook.com" : email ) ; user . setName ( StringUtils . isBlank ( name ) ? "No Name" : name ) ; user . setPassword ( Utils . generateSecurityToken ( ) ) ; user . setPicture ( getPicture ( fbId ) ) ; user . setIdentifier ( Config . FB_PREFIX . concat ( fbId ) ) ; String id = user . create ( ) ; if ( id == null ) { throw new AuthenticationServiceException ( "Authentication failed: cannot create new user." ) ; } } else { String picture = getPicture ( fbId ) ; boolean update = false ; if ( ! StringUtils . equals ( user . getPicture ( ) , picture ) ) { user . setPicture ( picture ) ; update = true ; } if ( ! StringUtils . isBlank ( email ) && ! StringUtils . equals ( user . getEmail ( ) , email ) ) { user . setEmail ( email ) ; update = true ; } if ( update ) { user . update ( ) ; } } userAuth = new UserAuthentication ( new AuthenticatedUserDetails ( user ) ) ; } EntityUtils . consumeQuietly ( respEntity ) ; } } return SecurityUtils . checkIfActive ( userAuth , user , false ) ; }
Calls the Facebook API to get the user profile using a given access token .
36,315
public static User getAuthenticatedUser ( Authentication auth ) { User user = null ; if ( auth != null && auth . isAuthenticated ( ) && auth . getPrincipal ( ) instanceof AuthenticatedUserDetails ) { user = ( ( AuthenticatedUserDetails ) auth . getPrincipal ( ) ) . getUser ( ) ; } return user ; }
Extracts a User object from the security context .
36,316
public static App getAuthenticatedApp ( ) { App app = null ; if ( SecurityContextHolder . getContext ( ) . getAuthentication ( ) != null ) { Authentication auth = SecurityContextHolder . getContext ( ) . getAuthentication ( ) ; if ( auth . isAuthenticated ( ) && auth . getPrincipal ( ) instanceof App ) { app = ( App ) auth . getPrincipal ( ) ; } } return app ; }
Extracts a App object from the security context .
36,317
public static boolean checkImplicitAppPermissions ( App app , ParaObject object ) { if ( app != null && object != null ) { return isNotAnApp ( object . getType ( ) ) || app . getId ( ) . equals ( object . getId ( ) ) || app . isRootApp ( ) ; } return false ; }
An app can edit itself or delete itself . It can t read edit overwrite or delete other apps unless it is the root app .
36,318
public static boolean checkIfUserCanModifyObject ( App app , ParaObject object ) { User user = SecurityUtils . getAuthenticatedUser ( ) ; if ( user != null && app != null && object != null ) { if ( app . permissionsContainOwnKeyword ( user , object ) ) { return user . canModify ( object ) ; } } return true ; }
Check if a user can modify an object . If there s no user principal found this returns true .
36,319
public static void clearSession ( HttpServletRequest req ) { SecurityContextHolder . clearContext ( ) ; if ( req != null ) { HttpSession session = req . getSession ( false ) ; if ( session != null ) { session . invalidate ( ) ; } } }
Clears the session . Deletes cookies and clears the security context .
36,320
public static boolean isValidJWToken ( String secret , SignedJWT jwt ) { try { if ( secret != null && jwt != null ) { JWSVerifier verifier = new MACVerifier ( secret ) ; if ( jwt . verify ( verifier ) ) { Date referenceTime = new Date ( ) ; JWTClaimsSet claims = jwt . getJWTClaimsSet ( ) ; Date expirationTime = claims . getExpirationTime ( ) ; Date notBeforeTime = claims . getNotBeforeTime ( ) ; boolean expired = expirationTime == null || expirationTime . before ( referenceTime ) ; boolean notYetValid = notBeforeTime == null || notBeforeTime . after ( referenceTime ) ; return ! ( expired || notYetValid ) ; } } } catch ( JOSEException e ) { logger . warn ( null , e ) ; } catch ( ParseException ex ) { logger . warn ( null , ex ) ; } return false ; }
Validates a JWT token .
36,321
public static SignedJWT generateJWToken ( User user , App app ) { if ( app != null ) { try { Date now = new Date ( ) ; JWTClaimsSet . Builder claimsSet = new JWTClaimsSet . Builder ( ) ; String userSecret = "" ; claimsSet . issueTime ( now ) ; claimsSet . expirationTime ( new Date ( now . getTime ( ) + ( app . getTokenValiditySec ( ) * 1000 ) ) ) ; claimsSet . notBeforeTime ( now ) ; claimsSet . claim ( "refresh" , getNextRefresh ( app . getTokenValiditySec ( ) ) ) ; claimsSet . claim ( Config . _APPID , app . getId ( ) ) ; if ( user != null ) { claimsSet . subject ( user . getId ( ) ) ; userSecret = user . getTokenSecret ( ) ; } JWSSigner signer = new MACSigner ( app . getSecret ( ) + userSecret ) ; SignedJWT signedJWT = new SignedJWT ( new JWSHeader ( JWSAlgorithm . HS256 ) , claimsSet . build ( ) ) ; signedJWT . sign ( signer ) ; return signedJWT ; } catch ( JOSEException e ) { logger . warn ( "Unable to sign JWT: {}." , e . getMessage ( ) ) ; } } return null ; }
Generates a new JWT token .
36,322
private static long getNextRefresh ( long tokenValiditySec ) { long interval = Config . JWT_REFRESH_INTERVAL_SEC ; if ( tokenValiditySec < ( 2 * interval ) ) { interval = ( tokenValiditySec / 2 ) ; } return System . currentTimeMillis ( ) + ( interval * 1000 ) ; }
Decides when the next token refresh should be .
36,323
public static String [ ] getOAuthKeysForApp ( App app , String prefix ) { prefix = StringUtils . removeEnd ( prefix + "" , Config . SEPARATOR ) ; String appIdKey = prefix + "_app_id" ; String secretKey = prefix + "_secret" ; String [ ] keys = new String [ ] { "" , "" } ; if ( app != null ) { Map < String , Object > settings = app . getSettings ( ) ; if ( settings . containsKey ( appIdKey ) && settings . containsKey ( secretKey ) ) { keys [ 0 ] = settings . get ( appIdKey ) + "" ; keys [ 1 ] = settings . get ( secretKey ) + "" ; } else if ( app . isRootApp ( ) ) { keys [ 0 ] = Config . getConfigParam ( appIdKey , "" ) ; keys [ 1 ] = Config . getConfigParam ( secretKey , "" ) ; } } return keys ; }
Return the OAuth app ID and secret key for a given app by reading the app settings or the config file .
36,324
public static Map < String , String > getLdapSettingsForApp ( App app ) { Map < String , String > ldapSettings = new HashMap < > ( ) ; if ( app != null ) { ldapSettings . put ( "security.ldap.server_url" , "ldap://localhost:8389/" ) ; ldapSettings . put ( "security.ldap.active_directory_domain" , "" ) ; ldapSettings . put ( "security.ldap.base_dn" , "dc=springframework,dc=org" ) ; ldapSettings . put ( "security.ldap.bind_dn" , "" ) ; ldapSettings . put ( "security.ldap.bind_pass" , "" ) ; ldapSettings . put ( "security.ldap.user_search_base" , "" ) ; ldapSettings . put ( "security.ldap.user_search_filter" , "(cn={0})" ) ; ldapSettings . put ( "security.ldap.user_dn_pattern" , "uid={0},ou=people" ) ; ldapSettings . put ( "security.ldap.password_attribute" , "userPassword" ) ; Map < String , Object > settings = app . getSettings ( ) ; for ( Map . Entry < String , String > entry : ldapSettings . entrySet ( ) ) { if ( settings . containsKey ( entry . getKey ( ) ) ) { entry . setValue ( settings . get ( entry . getKey ( ) ) + "" ) ; } else if ( app . isRootApp ( ) ) { entry . setValue ( Config . getConfigParam ( entry . getKey ( ) , entry . getValue ( ) ) ) ; } } } return ldapSettings ; }
Returns a map of LDAP configuration properties for a given app read from app . settings or config file .
36,325
public static String getSettingForApp ( App app , String key , String defaultValue ) { if ( app != null ) { Map < String , Object > settings = app . getSettings ( ) ; if ( settings . containsKey ( key ) ) { return String . valueOf ( settings . getOrDefault ( key , defaultValue ) ) ; } else if ( app . isRootApp ( ) ) { return Config . getConfigParam ( key , defaultValue ) ; } } return defaultValue ; }
Returns the value of the app setting read from from app . settings or from the config file if app is root .
36,326
public static UserAuthentication checkIfActive ( UserAuthentication userAuth , User user , boolean throwException ) { if ( userAuth == null || user == null || user . getIdentifier ( ) == null ) { if ( throwException ) { throw new BadCredentialsException ( "Bad credentials." ) ; } else { logger . debug ( "Bad credentials. {}" , userAuth ) ; return null ; } } else if ( ! user . getActive ( ) ) { if ( throwException ) { throw new LockedException ( "Account " + user . getId ( ) + " (" + user . getAppid ( ) + "/" + user . getIdentifier ( ) + ") is locked." ) ; } else { logger . warn ( "Account {} ({}/{}) is locked." , user . getId ( ) , user . getAppid ( ) , user . getIdentifier ( ) ) ; return null ; } } return userAuth ; }
Checks if account is active .
36,327
public static boolean isValidSignature ( HttpServletRequest incoming , String secretKey ) { if ( incoming == null || StringUtils . isBlank ( secretKey ) ) { return false ; } String auth = incoming . getHeader ( HttpHeaders . AUTHORIZATION ) ; String givenSig = StringUtils . substringAfter ( auth , "Signature=" ) ; String sigHeaders = StringUtils . substringBetween ( auth , "SignedHeaders=" , "," ) ; String credential = StringUtils . substringBetween ( auth , "Credential=" , "," ) ; String accessKey = StringUtils . substringBefore ( credential , "/" ) ; if ( StringUtils . isBlank ( auth ) ) { givenSig = incoming . getParameter ( "X-Amz-Signature" ) ; sigHeaders = incoming . getParameter ( "X-Amz-SignedHeaders" ) ; credential = incoming . getParameter ( "X-Amz-Credential" ) ; accessKey = StringUtils . substringBefore ( credential , "/" ) ; } Set < String > headersUsed = new HashSet < > ( Arrays . asList ( sigHeaders . split ( ";" ) ) ) ; Map < String , String > headers = new HashMap < > ( ) ; for ( Enumeration < String > e = incoming . getHeaderNames ( ) ; e . hasMoreElements ( ) ; ) { String head = e . nextElement ( ) . toLowerCase ( ) ; if ( headersUsed . contains ( head ) ) { headers . put ( head , incoming . getHeader ( head ) ) ; } } Map < String , String > params = new HashMap < > ( ) ; for ( Map . Entry < String , String [ ] > param : incoming . getParameterMap ( ) . entrySet ( ) ) { params . put ( param . getKey ( ) , param . getValue ( ) [ 0 ] ) ; } String path = incoming . getRequestURI ( ) ; String endpoint = StringUtils . removeEndIgnoreCase ( incoming . getRequestURL ( ) . toString ( ) , path ) ; String httpMethod = incoming . getMethod ( ) ; InputStream entity ; try { entity = new BufferedRequestWrapper ( incoming ) . getInputStream ( ) ; if ( entity . available ( ) <= 0 ) { entity = null ; } } catch ( IOException ex ) { logger . error ( null , ex ) ; entity = null ; } Signer signer = new Signer ( ) ; Map < String , String > sig = signer . sign ( httpMethod , endpoint , path , headers , params , entity , accessKey , secretKey ) ; String auth2 = sig . get ( HttpHeaders . AUTHORIZATION ) ; String recreatedSig = StringUtils . substringAfter ( auth2 , "Signature=" ) ; return StringUtils . equals ( givenSig , recreatedSig ) ; }
Validates the signature of the request .
36,328
public static void initialize ( ) { if ( isInitialized ) { return ; } isInitialized = true ; printLogo ( ) ; try { logger . info ( "--- Para.initialize() [{}] ---" , Config . ENVIRONMENT ) ; for ( InitializeListener initListener : INIT_LISTENERS ) { if ( initListener != null ) { initListener . onInitialize ( ) ; logger . debug ( "Executed {}.onInitialize()." , initListener . getClass ( ) . getName ( ) ) ; } } logger . info ( "Instance #{} initialized." , Config . WORKER_ID ) ; } catch ( Exception e ) { logger . error ( "Failed to initialize Para." , e ) ; } }
Executes all initialize listeners and prints logo . Call this method first .
36,329
public static void destroy ( ) { try { logger . info ( "--- Para.destroy() ---" ) ; for ( DestroyListener destroyListener : DESTROY_LISTENERS ) { if ( destroyListener != null ) { destroyListener . onDestroy ( ) ; logger . debug ( "Executed {}.onDestroy()." , destroyListener . getClass ( ) . getName ( ) ) ; } } if ( ! EXECUTOR . isShutdown ( ) ) { EXECUTOR . shutdown ( ) ; EXECUTOR . awaitTermination ( 60 , TimeUnit . SECONDS ) ; } if ( ! SCHEDULER . isShutdown ( ) ) { SCHEDULER . shutdown ( ) ; SCHEDULER . awaitTermination ( 60 , TimeUnit . SECONDS ) ; } } catch ( Exception e ) { logger . error ( "Failed to destroy Para." , e ) ; } }
Calls all registered listeners on exit . Call this method last .
36,330
public static Map < String , String > setup ( ) { return newApp ( Config . getRootAppIdentifier ( ) , Config . APP_NAME , false , false ) ; }
Creates the root application and returns the credentials for it .
36,331
public static Map < String , String > newApp ( String appid , String name , boolean sharedTable , boolean sharedIndex ) { Map < String , String > creds = new TreeMap < > ( ) ; creds . put ( "message" , "All set!" ) ; if ( StringUtils . isBlank ( appid ) ) { return creds ; } App app = new App ( appid ) ; if ( ! app . exists ( ) ) { app . setName ( name ) ; app . setSharingTable ( sharedTable ) ; app . setSharingIndex ( sharedIndex ) ; app . setActive ( true ) ; String id = app . create ( ) ; if ( id != null ) { logger . info ( "Created {} app '{}', sharingTable = {}, sharingIndex = {}." , app . isRootApp ( ) ? "root" : "new" , app . getAppIdentifier ( ) , sharedTable , sharedIndex ) ; creds . putAll ( app . getCredentials ( ) ) ; creds . put ( "message" , "Save the secret key - it is shown only once!" ) ; } else { logger . error ( "Failed to create app '{}'!" , appid ) ; creds . put ( "message" , "Error - app was not created." ) ; } } return creds ; }
Creates a new application and returns the credentials for it .
36,332
public Map < String , String > readLanguage ( String appid , String langCode ) { if ( StringUtils . isBlank ( langCode ) || langCode . equals ( getDefaultLanguageCode ( ) ) ) { return getDefaultLanguage ( appid ) ; } else if ( langCode . length ( ) > 2 && ! ALL_LOCALES . containsKey ( langCode ) ) { return readLanguage ( appid , langCode . substring ( 0 , 2 ) ) ; } else if ( LANG_CACHE . containsKey ( langCode ) ) { return LANG_CACHE . get ( langCode ) ; } Map < String , String > lang = readLanguageFromFile ( appid , langCode ) ; if ( lang == null || lang . isEmpty ( ) ) { lang = new TreeMap < String , String > ( getDefaultLanguage ( appid ) ) ; Sysprop s = dao . read ( appid , keyPrefix . concat ( langCode ) ) ; if ( s != null && ! s . getProperties ( ) . isEmpty ( ) ) { Map < String , Object > loaded = s . getProperties ( ) ; for ( Map . Entry < String , String > entry : lang . entrySet ( ) ) { if ( loaded . containsKey ( entry . getKey ( ) ) ) { lang . put ( entry . getKey ( ) , String . valueOf ( loaded . get ( entry . getKey ( ) ) ) ) ; } else { lang . put ( entry . getKey ( ) , entry . getValue ( ) ) ; } } } LANG_CACHE . put ( langCode , lang ) ; } return Collections . unmodifiableMap ( lang ) ; }
Returns a map of all translations for a given language . Defaults to the default language which must be set .
36,333
public void writeLanguage ( String appid , String langCode , Map < String , String > lang , boolean writeToDatabase ) { if ( lang == null || lang . isEmpty ( ) || StringUtils . isBlank ( langCode ) || ! ALL_LOCALES . containsKey ( langCode ) ) { return ; } writeLanguageToFile ( appid , langCode , lang ) ; if ( writeToDatabase ) { Sysprop s = new Sysprop ( keyPrefix . concat ( langCode ) ) ; Map < String , String > dlang = getDefaultLanguage ( appid ) ; for ( Map . Entry < String , String > entry : dlang . entrySet ( ) ) { String key = entry . getKey ( ) ; if ( lang . containsKey ( key ) ) { s . addProperty ( key , lang . get ( key ) ) ; } else { s . addProperty ( key , entry . getValue ( ) ) ; } } dao . create ( appid , s ) ; } }
Persists the language map in the data store . Overwrites any existing maps .
36,334
public Locale getProperLocale ( String langCode ) { if ( StringUtils . startsWith ( langCode , "zh" ) ) { if ( "zh_tw" . equalsIgnoreCase ( langCode ) ) { return Locale . TRADITIONAL_CHINESE ; } else { return Locale . SIMPLIFIED_CHINESE ; } } String lang = StringUtils . substring ( langCode , 0 , 2 ) ; lang = ( StringUtils . isBlank ( lang ) || ! ALL_LOCALES . containsKey ( lang ) ) ? "en" : lang . trim ( ) . toLowerCase ( ) ; return ALL_LOCALES . get ( lang ) ; }
Returns a non - null locale for a given language code .
36,335
public Map < String , String > getDefaultLanguage ( String appid ) { if ( ! LANG_CACHE . containsKey ( getDefaultLanguageCode ( ) ) ) { logger . info ( "Default language map not set, loading English." ) ; Map < String , String > deflang = readLanguageFromFile ( appid , getDefaultLanguageCode ( ) ) ; if ( deflang != null && ! deflang . isEmpty ( ) ) { LANG_CACHE . put ( getDefaultLanguageCode ( ) , deflang ) ; return Collections . unmodifiableMap ( deflang ) ; } } return Collections . unmodifiableMap ( LANG_CACHE . get ( getDefaultLanguageCode ( ) ) ) ; }
Returns the default language map .
36,336
public void setDefaultLanguage ( Map < String , String > deflang ) { if ( deflang != null && ! deflang . isEmpty ( ) ) { LANG_CACHE . put ( getDefaultLanguageCode ( ) , deflang ) ; } }
Sets the default language map . It is the basis language template which is to be translated .
36,337
public List < Translation > readAllTranslationsForKey ( String appid , String locale , String key , Pager pager ) { Map < String , Object > terms = new HashMap < > ( 2 ) ; terms . put ( "thekey" , key ) ; terms . put ( "locale" , locale ) ; return search . findTerms ( appid , Utils . type ( Translation . class ) , terms , true , pager ) ; }
Returns a list of translations for a specific string .
36,338
public Set < String > getApprovedTransKeys ( String appid , String langCode ) { HashSet < String > approvedTransKeys = new HashSet < > ( ) ; if ( StringUtils . isBlank ( langCode ) ) { return approvedTransKeys ; } for ( Map . Entry < String , String > entry : readLanguage ( appid , langCode ) . entrySet ( ) ) { if ( ! getDefaultLanguage ( appid ) . get ( entry . getKey ( ) ) . equals ( entry . getValue ( ) ) ) { approvedTransKeys . add ( entry . getKey ( ) ) ; } } return approvedTransKeys ; }
Returns the set of all approved translations .
36,339
public Map < String , Integer > getTranslationProgressMap ( String appid ) { if ( dao == null ) { return Collections . emptyMap ( ) ; } Sysprop progress ; if ( langProgressCache . getProperties ( ) . isEmpty ( ) ) { progress = dao . read ( appid , progressKey ) ; if ( progress != null ) { langProgressCache = progress ; } } else { progress = langProgressCache ; } Map < String , Integer > progressMap = new HashMap < > ( ALL_LOCALES . size ( ) ) ; boolean isMissing = progress == null ; if ( isMissing ) { progress = new Sysprop ( progressKey ) ; progress . addProperty ( getDefaultLanguageCode ( ) , 100 ) ; } for ( String langCode : ALL_LOCALES . keySet ( ) ) { Object percent = progress . getProperties ( ) . get ( langCode ) ; if ( percent != null && percent instanceof Number ) { progressMap . put ( langCode , ( Integer ) percent ) ; } else { progressMap . put ( langCode , 0 ) ; } } if ( isMissing ) { dao . create ( appid , progress ) ; langProgressCache = progress ; } return progressMap ; }
Returns a map of language codes and the percentage of translated string for that language .
36,340
public boolean approveTranslation ( String appid , String langCode , String key , String value ) { if ( StringUtils . isBlank ( langCode ) || key == null || value == null || getDefaultLanguageCode ( ) . equals ( langCode ) ) { return false ; } Sysprop s = dao . read ( appid , keyPrefix . concat ( langCode ) ) ; boolean create = false ; if ( s == null ) { create = true ; s = new Sysprop ( keyPrefix . concat ( langCode ) ) ; s . setAppid ( appid ) ; } s . addProperty ( key , value ) ; if ( create ) { dao . create ( appid , s ) ; } else { dao . update ( appid , s ) ; } if ( LANG_CACHE . containsKey ( langCode ) ) { LANG_CACHE . get ( langCode ) . put ( key , value ) ; } updateTranslationProgressMap ( appid , langCode , PLUS ) ; return true ; }
Approves a translation for a given language .
36,341
public boolean disapproveTranslation ( String appid , String langCode , String key ) { if ( StringUtils . isBlank ( langCode ) || key == null || getDefaultLanguageCode ( ) . equals ( langCode ) ) { return false ; } Sysprop s = dao . read ( appid , keyPrefix . concat ( langCode ) ) ; if ( s != null ) { String value = getDefaultLanguage ( appid ) . get ( key ) ; s . addProperty ( key , value ) ; dao . update ( appid , s ) ; if ( LANG_CACHE . containsKey ( langCode ) ) { LANG_CACHE . get ( langCode ) . put ( key , value ) ; } updateTranslationProgressMap ( appid , langCode , MINUS ) ; return true ; } return false ; }
Disapproves a translation for a given language .
36,342
private void updateTranslationProgressMap ( String appid , String langCode , int value ) { if ( dao == null || getDefaultLanguageCode ( ) . equals ( langCode ) ) { return ; } double defsize = getDefaultLanguage ( appid ) . size ( ) ; double approved = value ; Map < String , Integer > progress = getTranslationProgressMap ( appid ) ; Integer percent = progress . get ( langCode ) ; if ( value == PLUS ) { approved = Math . round ( percent * ( defsize / 100 ) + 1 ) ; } else if ( value == MINUS ) { approved = Math . round ( percent * ( defsize / 100 ) - 1 ) ; } int allowedUntranslated = defsize > 10 ? 5 : 0 ; if ( approved >= defsize - allowedUntranslated ) { approved = defsize ; } if ( ( ( int ) defsize ) == 0 ) { progress . put ( langCode , 0 ) ; } else { progress . put ( langCode , ( int ) ( ( approved / defsize ) * 100 ) ) ; } Sysprop updatedProgress = new Sysprop ( progressKey ) ; for ( Map . Entry < String , Integer > entry : progress . entrySet ( ) ) { updatedProgress . addProperty ( entry . getKey ( ) , entry . getValue ( ) ) ; } langProgressCache = updatedProgress ; if ( percent < 100 && ! percent . equals ( progress . get ( langCode ) ) ) { dao . create ( appid , updatedProgress ) ; } }
Updates the progress for all languages .
36,343
public Collection < ? extends GrantedAuthority > getAuthorities ( ) { if ( principal == null ) { return Collections . emptyList ( ) ; } return Collections . unmodifiableCollection ( principal . getAuthorities ( ) ) ; }
A list of roles for the authenticated user .
36,344
protected boolean isRestRequest ( HttpServletRequest request ) { return RestRequestMatcher . INSTANCE . matches ( request ) || AjaxRequestMatcher . INSTANCE . matches ( request ) ; }
Checks if it is a rest request .
36,345
public UserDetails loadUserByUsername ( String ident ) { User user = new User ( ) ; if ( StringUtils . contains ( ident , "/" ) ) { String [ ] parts = ident . split ( "/" ) ; user . setAppid ( parts [ 0 ] ) ; ident = parts [ 1 ] ; } user . setIdentifier ( ident ) ; user = loadUser ( user ) ; if ( user == null ) { throw new UsernameNotFoundException ( ident ) ; } return new AuthenticatedUserDetails ( user ) ; }
Loads a user from the data store .
36,346
public UserDetails loadUserDetails ( OpenIDAuthenticationToken token ) { if ( token == null ) { return null ; } User user = new User ( ) ; user . setIdentifier ( token . getIdentityUrl ( ) ) ; user = loadUser ( user ) ; if ( user == null ) { String email = "email@domain.com" ; String firstName = null , lastName = null , fullName = null ; List < OpenIDAttribute > attributes = token . getAttributes ( ) ; for ( OpenIDAttribute attribute : attributes ) { if ( attribute . getName ( ) . equals ( "email" ) ) { email = attribute . getValues ( ) . get ( 0 ) ; } if ( attribute . getName ( ) . equals ( "firstname" ) ) { firstName = attribute . getValues ( ) . get ( 0 ) ; } if ( attribute . getName ( ) . equals ( "lastname" ) ) { lastName = attribute . getValues ( ) . get ( 0 ) ; } if ( attribute . getName ( ) . equals ( "fullname" ) ) { fullName = attribute . getValues ( ) . get ( 0 ) ; } } if ( fullName == null ) { if ( firstName == null ) { firstName = "No" ; } if ( lastName == null ) { lastName = "Name" ; } fullName = firstName . concat ( " " ) . concat ( lastName ) ; } user = new User ( ) ; user . setActive ( true ) ; user . setEmail ( email ) ; user . setName ( fullName ) ; user . setPassword ( Utils . generateSecurityToken ( ) ) ; user . setIdentifier ( token . getIdentityUrl ( ) ) ; String id = user . create ( ) ; if ( id == null ) { throw new BadCredentialsException ( "Authentication failed: cannot create new user." ) ; } } return new AuthenticatedUserDetails ( user ) ; }
Loads a user from the data store or creates a new user from an OpenID profile .
36,347
protected void configure ( AuthenticationManagerBuilder auth ) throws Exception { OpenIDAuthenticationProvider openidProvider = new OpenIDAuthenticationProvider ( ) ; openidProvider . setAuthenticationUserDetailsService ( new SimpleUserService ( ) ) ; auth . authenticationProvider ( openidProvider ) ; RememberMeAuthenticationProvider rmeProvider = new RememberMeAuthenticationProvider ( Config . APP_SECRET_KEY ) ; auth . authenticationProvider ( rmeProvider ) ; JWTAuthenticationProvider jwtProvider = new JWTAuthenticationProvider ( ) ; auth . authenticationProvider ( jwtProvider ) ; LDAPAuthenticationProvider ldapProvider = new LDAPAuthenticationProvider ( ) ; auth . authenticationProvider ( ldapProvider ) ; }
Configures the authentication providers .
36,348
public void configure ( WebSecurity web ) throws Exception { web . ignoring ( ) . requestMatchers ( IgnoredRequestMatcher . INSTANCE ) ; DefaultHttpFirewall firewall = new DefaultHttpFirewall ( ) ; firewall . setAllowUrlEncodedSlash ( true ) ; web . httpFirewall ( firewall ) ; }
Configures the unsecured public resources .
36,349
protected void configure ( HttpSecurity http ) throws Exception { ConfigObject protectedResources = Config . getConfig ( ) . getObject ( "security.protected" ) ; ConfigValue apiSec = Config . getConfig ( ) . getValue ( "security.api_security" ) ; boolean enableRestFilter = apiSec != null && Boolean . TRUE . equals ( apiSec . unwrapped ( ) ) ; String signinPath = Config . getConfigParam ( "security.signin" , "/signin" ) ; String signoutPath = Config . getConfigParam ( "security.signout" , "/signout" ) ; String accessDeniedPath = Config . getConfigParam ( "security.access_denied" , "/403" ) ; String signoutSuccessPath = Config . getConfigParam ( "security.signout_success" , signinPath ) ; if ( enableRestFilter ) { http . authorizeRequests ( ) . requestMatchers ( RestRequestMatcher . INSTANCE ) ; } parseProtectedResources ( http , protectedResources ) ; if ( Config . getConfigBoolean ( "security.csrf_protection" , true ) ) { http . csrf ( ) . requireCsrfProtectionMatcher ( CsrfProtectionRequestMatcher . INSTANCE ) . csrfTokenRepository ( csrfTokenRepository ) ; } else { http . csrf ( ) . disable ( ) ; } http . sessionManagement ( ) . enableSessionUrlRewriting ( false ) ; http . sessionManagement ( ) . sessionCreationPolicy ( SessionCreationPolicy . NEVER ) ; http . sessionManagement ( ) . sessionAuthenticationStrategy ( new NullAuthenticatedSessionStrategy ( ) ) ; http . exceptionHandling ( ) . authenticationEntryPoint ( new SimpleAuthenticationEntryPoint ( signinPath ) ) ; http . exceptionHandling ( ) . accessDeniedHandler ( new SimpleAccessDeniedHandler ( accessDeniedPath ) ) ; http . requestCache ( ) . requestCache ( new SimpleRequestCache ( ) ) ; http . logout ( ) . logoutUrl ( signoutPath ) . logoutSuccessUrl ( signoutSuccessPath ) ; http . rememberMe ( ) . rememberMeServices ( rememberMeServices ) ; registerAuthFilters ( http ) ; if ( enableRestFilter ) { if ( jwtFilter != null ) { jwtFilter . setAuthenticationManager ( authenticationManager ( ) ) ; http . addFilterBefore ( jwtFilter , RememberMeAuthenticationFilter . class ) ; } RestAuthFilter restFilter = new RestAuthFilter ( ) ; http . addFilterAfter ( restFilter , JWTRestfulAuthFilter . class ) ; } }
Configures the protected private resources .
36,350
public static boolean matches ( Class < ? extends Annotation > anno , String consName ) { return VALIDATORS . get ( anno ) . equals ( consName ) ; }
Verifies that the given annotation type corresponds to a known constraint .
36,351
public static Constraint fromAnnotation ( Annotation anno ) { if ( anno instanceof Min ) { return min ( ( ( Min ) anno ) . value ( ) ) ; } else if ( anno instanceof Max ) { return max ( ( ( Max ) anno ) . value ( ) ) ; } else if ( anno instanceof Size ) { return size ( ( ( Size ) anno ) . min ( ) , ( ( Size ) anno ) . max ( ) ) ; } else if ( anno instanceof Digits ) { return digits ( ( ( Digits ) anno ) . integer ( ) , ( ( Digits ) anno ) . fraction ( ) ) ; } else if ( anno instanceof Pattern ) { return pattern ( ( ( Pattern ) anno ) . regexp ( ) ) ; } else { return new Constraint ( VALIDATORS . get ( anno . annotationType ( ) ) , simplePayload ( VALIDATORS . get ( anno . annotationType ( ) ) ) ) { public boolean isValid ( Object actualValue ) { return true ; } } ; } }
Builds a new constraint from the annotation data .
36,352
static Map < String , Object > simplePayload ( final String name ) { if ( name == null ) { return null ; } Map < String , Object > payload = new LinkedHashMap < > ( ) ; payload . put ( "message" , MSG_PREFIX + name ) ; return payload ; }
Creates a new map representing a simple validation constraint .
36,353
public static Constraint required ( ) { return new Constraint ( "required" , simplePayload ( "required" ) ) { public boolean isValid ( Object actualValue ) { return ! ( actualValue == null || StringUtils . isBlank ( actualValue . toString ( ) ) ) ; } } ; }
The required constraint - marks a field as required .
36,354
public static Constraint min ( final Number min ) { return new Constraint ( "min" , minPayload ( min ) ) { public boolean isValid ( Object actualValue ) { return actualValue == null || ( actualValue instanceof Number && min != null && min . longValue ( ) <= ( ( Number ) actualValue ) . longValue ( ) ) ; } } ; }
The min constraint - field must contain a number larger than or equal to min .
36,355
public static Constraint max ( final Number max ) { return new Constraint ( "max" , maxPayload ( max ) ) { public boolean isValid ( Object actualValue ) { return actualValue == null || ( actualValue instanceof Number && max != null && max . longValue ( ) >= ( ( Number ) actualValue ) . longValue ( ) ) ; } } ; }
The max constraint - field must contain a number smaller than or equal to max .
36,356
public static Constraint pattern ( final Object regex ) { return new Constraint ( "pattern" , patternPayload ( regex ) ) { public boolean isValid ( Object actualValue ) { if ( actualValue != null ) { if ( regex != null && regex instanceof String ) { if ( ! ( actualValue instanceof String ) || ! ( ( String ) actualValue ) . matches ( ( String ) regex ) ) { return false ; } } } return true ; } } ; }
The pattern constraint - field must contain a value matching a regular expression .
36,357
public static Constraint email ( ) { return new Constraint ( "email" , simplePayload ( "email" ) ) { public boolean isValid ( Object actualValue ) { if ( actualValue != null ) { if ( ! ( actualValue instanceof String ) || ! Utils . isValidEmail ( ( String ) actualValue ) ) { return false ; } } return true ; } } ; }
The email constraint - field must contain a valid email .
36,358
public static Constraint truthy ( ) { return new Constraint ( "true" , simplePayload ( "true" ) ) { public boolean isValid ( Object actualValue ) { if ( actualValue != null ) { if ( ( actualValue instanceof Boolean && ! ( ( Boolean ) actualValue ) ) || ( actualValue instanceof String && ! Boolean . parseBoolean ( ( String ) actualValue ) ) ) { return false ; } } return true ; } } ; }
The truthy constraint - field value must be equal to true .
36,359
public static Constraint url ( ) { return new Constraint ( "url" , simplePayload ( "url" ) ) { public boolean isValid ( Object actualValue ) { if ( actualValue != null ) { if ( ! Utils . isValidURL ( actualValue . toString ( ) ) ) { return false ; } } return true ; } } ; }
The url constraint - field value must be a valid URL .
36,360
public static Constraint build ( String cname , Map < String , Object > payload ) { if ( cname != null && payload != null ) { if ( "min" . equals ( cname ) && payload . containsKey ( "value" ) ) { return min ( NumberUtils . toLong ( payload . get ( "value" ) + "" , 0 ) ) ; } else if ( "max" . equals ( cname ) && payload . containsKey ( "value" ) ) { return max ( NumberUtils . toLong ( payload . get ( "value" ) + "" , Config . DEFAULT_LIMIT ) ) ; } else if ( "size" . equals ( cname ) && payload . containsKey ( "min" ) && payload . containsKey ( "max" ) ) { return size ( NumberUtils . toLong ( payload . get ( "min" ) + "" , 0 ) , NumberUtils . toLong ( payload . get ( "max" ) + "" , Config . DEFAULT_LIMIT ) ) ; } else if ( "digits" . equals ( cname ) && payload . containsKey ( "integer" ) && payload . containsKey ( "fraction" ) ) { return digits ( NumberUtils . toLong ( payload . get ( "integer" ) + "" , 0 ) , NumberUtils . toLong ( payload . get ( "fraction" ) + "" , 0 ) ) ; } else if ( "pattern" . equals ( cname ) && payload . containsKey ( "value" ) ) { return pattern ( payload . get ( "value" ) ) ; } else { return SIMPLE_CONSTRAINTS . get ( cname ) ; } } return null ; }
Builds a new constraint from a given name and payload .
36,361
public Collection < ? extends GrantedAuthority > getAuthorities ( ) { if ( user . isAdmin ( ) ) { return Collections . singleton ( new SimpleGrantedAuthority ( Roles . ADMIN . toString ( ) ) ) ; } else if ( user . isModerator ( ) ) { return Collections . singleton ( new SimpleGrantedAuthority ( Roles . MOD . toString ( ) ) ) ; } else { return Collections . singleton ( new SimpleGrantedAuthority ( Roles . USER . toString ( ) ) ) ; } }
A list of roles for this user .
36,362
public static Map < String , String > getCoreTypes ( ) { if ( CORE_TYPES . isEmpty ( ) ) { try { for ( Class < ? extends ParaObject > clazz : getCoreClassesMap ( ) . values ( ) ) { ParaObject p = clazz . getConstructor ( ) . newInstance ( ) ; CORE_TYPES . put ( p . getPlural ( ) , p . getType ( ) ) ; } } catch ( Exception ex ) { logger . error ( null , ex ) ; } } return Collections . unmodifiableMap ( CORE_TYPES ) ; }
Returns a map of the core data types .
36,363
public static Map < String , String > getAllTypes ( App app ) { Map < String , String > map = new LinkedHashMap < > ( getCoreTypes ( ) ) ; if ( app != null ) { map . putAll ( app . getDatatypes ( ) ) ; } return map ; }
Returns a map of all registered types .
36,364
public static String getAppidFromAuthHeader ( String authorization ) { if ( StringUtils . isBlank ( authorization ) ) { return "" ; } String appid = "" ; if ( StringUtils . startsWith ( authorization , "Bearer" ) ) { try { String [ ] parts = StringUtils . split ( authorization , '.' ) ; if ( parts . length > 1 ) { Map < String , Object > jwt = getJsonReader ( Map . class ) . readValue ( Utils . base64dec ( parts [ 1 ] ) ) ; if ( jwt != null && jwt . containsKey ( Config . _APPID ) ) { appid = ( String ) jwt . get ( Config . _APPID ) ; } } } catch ( Exception e ) { } } else if ( StringUtils . startsWith ( authorization , "Anonymous" ) ) { appid = StringUtils . substringAfter ( authorization , "Anonymous" ) . trim ( ) ; } else { appid = StringUtils . substringBetween ( authorization , "=" , "/" ) ; } if ( StringUtils . isBlank ( appid ) ) { return "" ; } return App . id ( appid ) . substring ( 4 ) ; }
Returns the app identifier by parsing the Authorization .
36,365
public static boolean typesMatch ( ParaObject so ) { return ( so == null ) ? false : so . getClass ( ) . equals ( toClass ( so . getType ( ) ) ) ; }
Checks if the type of an object matches its real Class name .
36,366
public static < P extends ParaObject > P toObject ( String type ) { try { return ( P ) toClass ( type ) . getConstructor ( ) . newInstance ( ) ; } catch ( Exception ex ) { logger . error ( null , ex ) ; return null ; } }
Constructs a new instance of a core object .
36,367
public static < P extends ParaObject > String toJSON ( P obj ) { if ( obj == null ) { return "{}" ; } try { return getJsonWriter ( ) . writeValueAsString ( obj ) ; } catch ( Exception e ) { logger . error ( null , e ) ; } return "{}" ; }
Converts a domain object to JSON .
36,368
public void flushBuffer ( ) throws IOException { if ( this . printWriter != null ) { this . printWriter . flush ( ) ; } if ( this . gzipOutputStream != null ) { this . gzipOutputStream . flush ( ) ; } if ( ! disableFlushBuffer ) { super . flushBuffer ( ) ; } }
Flush OutputStream or PrintWriter .
36,369
public void flush ( ) throws IOException { if ( printWriter != null ) { printWriter . flush ( ) ; } if ( gzipOutputStream != null ) { gzipOutputStream . flush ( ) ; } }
Flushes all the streams for this response .
36,370
public static final String id ( String id ) { if ( StringUtils . startsWith ( id , PREFIX ) ) { return PREFIX . concat ( Utils . noSpaces ( Utils . stripAndTrim ( id . replaceAll ( PREFIX , "" ) , " " ) , "-" ) ) ; } else if ( id != null ) { return PREFIX . concat ( Utils . noSpaces ( Utils . stripAndTrim ( id , " " ) , "-" ) ) ; } else { return null ; } }
Returns the correct id of this app with prefix .
36,371
public App addSetting ( String name , Object value ) { if ( ! StringUtils . isBlank ( name ) && value != null ) { getSettings ( ) . put ( name , value ) ; for ( AppSettingAddedListener listener : ADD_SETTING_LISTENERS ) { listener . onSettingAdded ( this , name , value ) ; logger . debug ( "Executed {}.onSettingAdded()." , listener . getClass ( ) . getName ( ) ) ; } } return this ; }
Adds a new setting to the map .
36,372
public Object getSetting ( String name ) { if ( ! StringUtils . isBlank ( name ) ) { return getSettings ( ) . get ( name ) ; } return null ; }
Returns the value of a setting for a given key .
36,373
public App removeSetting ( String name ) { if ( ! StringUtils . isBlank ( name ) ) { Object result = getSettings ( ) . remove ( name ) ; if ( result != null ) { for ( AppSettingRemovedListener listener : REMOVE_SETTING_LISTENERS ) { listener . onSettingRemoved ( this , name ) ; logger . debug ( "Executed {}.onSettingRemoved()." , listener . getClass ( ) . getName ( ) ) ; } } } return this ; }
Removes a setting from the map .
36,374
public Map < String , Map < String , Map < String , Map < String , ? > > > > getValidationConstraints ( ) { if ( validationConstraints == null ) { validationConstraints = new LinkedHashMap < > ( ) ; } return validationConstraints ; }
Returns a map of user - defined data types and their validation annotations .
36,375
public void setValidationConstraints ( Map < String , Map < String , Map < String , Map < String , ? > > > > validationConstraints ) { this . validationConstraints = validationConstraints ; }
Sets the validation constraints map .
36,376
public Map < String , Map < String , List < String > > > getResourcePermissions ( ) { if ( resourcePermissions == null ) { resourcePermissions = new LinkedHashMap < > ( ) ; } return resourcePermissions ; }
Returns a map of resource permissions .
36,377
public void setResourcePermissions ( Map < String , Map < String , List < String > > > resourcePermissions ) { this . resourcePermissions = resourcePermissions ; }
Sets the permissions map .
36,378
@ SuppressWarnings ( "unchecked" ) public Map < String , String > getDatatypes ( ) { if ( datatypes == null ) { datatypes = new DualHashBidiMap ( ) ; } return datatypes ; }
Returns a set of custom data types for this app . An app can have many custom types which describe its domain .
36,379
public Map < String , Map < String , Map < String , Map < String , ? > > > > getAllValidationConstraints ( String ... types ) { Map < String , Map < String , Map < String , Map < String , ? > > > > allConstr = new LinkedHashMap < > ( ) ; if ( types == null || types . length == 0 ) { types = ParaObjectUtils . getAllTypes ( this ) . values ( ) . toArray ( new String [ 0 ] ) ; } try { for ( String aType : types ) { Map < String , Map < String , Map < String , ? > > > vc = new LinkedHashMap < > ( ) ; if ( ValidationUtils . getCoreValidationConstraints ( ) . containsKey ( aType ) ) { vc . putAll ( ValidationUtils . getCoreValidationConstraints ( ) . get ( aType ) ) ; } Map < String , Map < String , Map < String , ? > > > appConstraints = getValidationConstraints ( ) . get ( aType ) ; if ( appConstraints != null && ! appConstraints . isEmpty ( ) ) { vc . putAll ( appConstraints ) ; } if ( ! vc . isEmpty ( ) ) { allConstr . put ( aType , vc ) ; } } } catch ( Exception ex ) { logger . error ( null , ex ) ; } return allConstr ; }
Returns all validation constraints for a list of types .
36,380
public boolean addValidationConstraint ( String type , String field , Constraint c ) { if ( ! StringUtils . isBlank ( type ) && ! StringUtils . isBlank ( field ) && c != null && ! c . getPayload ( ) . isEmpty ( ) && Constraint . isValidConstraintName ( c . getName ( ) ) ) { Map < String , Map < String , Map < String , ? > > > fieldMap = getValidationConstraints ( ) . get ( type ) ; Map < String , Map < String , ? > > consMap ; if ( fieldMap != null ) { consMap = fieldMap . get ( field ) ; if ( consMap == null ) { consMap = new LinkedHashMap < > ( ) ; } } else { fieldMap = new LinkedHashMap < > ( ) ; consMap = new LinkedHashMap < > ( ) ; } consMap . put ( c . getName ( ) , c . getPayload ( ) ) ; fieldMap . put ( field , consMap ) ; getValidationConstraints ( ) . put ( type , fieldMap ) ; return true ; } return false ; }
Adds a new constraint to the list of constraints for a given field and type .
36,381
public boolean removeValidationConstraint ( String type , String field , String constraintName ) { if ( ! StringUtils . isBlank ( type ) && ! StringUtils . isBlank ( field ) && constraintName != null ) { Map < String , Map < String , Map < String , ? > > > fieldsMap = getValidationConstraints ( ) . get ( type ) ; if ( fieldsMap != null && fieldsMap . containsKey ( field ) ) { if ( fieldsMap . get ( field ) . containsKey ( constraintName ) ) { fieldsMap . get ( field ) . remove ( constraintName ) ; } if ( fieldsMap . get ( field ) . isEmpty ( ) ) { getValidationConstraints ( ) . get ( type ) . remove ( field ) ; } if ( getValidationConstraints ( ) . get ( type ) . isEmpty ( ) ) { getValidationConstraints ( ) . remove ( type ) ; } return true ; } } return false ; }
Removes a constraint from the map .
36,382
public Map < String , Map < String , List < String > > > getAllResourcePermissions ( String ... subjectids ) { Map < String , Map < String , List < String > > > allPermits = new LinkedHashMap < > ( ) ; if ( subjectids == null || subjectids . length == 0 ) { return getResourcePermissions ( ) ; } try { for ( String subjectid : subjectids ) { if ( subjectid != null ) { if ( getResourcePermissions ( ) . containsKey ( subjectid ) ) { allPermits . put ( subjectid , getResourcePermissions ( ) . get ( subjectid ) ) ; } else { allPermits . put ( subjectid , new LinkedHashMap < > ( 0 ) ) ; } if ( getResourcePermissions ( ) . containsKey ( ALLOW_ALL ) ) { allPermits . put ( ALLOW_ALL , getResourcePermissions ( ) . get ( ALLOW_ALL ) ) ; } } } } catch ( Exception ex ) { logger . error ( null , ex ) ; } return allPermits ; }
Returns all resource permission for a list of subjects ids .
36,383
public boolean revokeResourcePermission ( String subjectid , String resourcePath ) { if ( ! StringUtils . isBlank ( subjectid ) && getResourcePermissions ( ) . containsKey ( subjectid ) && ! StringUtils . isBlank ( resourcePath ) ) { resourcePath = Utils . urlDecode ( resourcePath ) ; getResourcePermissions ( ) . get ( subjectid ) . remove ( resourcePath ) ; if ( getResourcePermissions ( ) . get ( subjectid ) . isEmpty ( ) ) { getResourcePermissions ( ) . remove ( subjectid ) ; } return true ; } return false ; }
Revokes a permission for given subject .
36,384
public boolean revokeAllResourcePermissions ( String subjectid ) { if ( ! StringUtils . isBlank ( subjectid ) && getResourcePermissions ( ) . containsKey ( subjectid ) ) { getResourcePermissions ( ) . remove ( subjectid ) ; return true ; } return false ; }
Revokes all permissions for a subject id .
36,385
final boolean isDeniedExplicitly ( String subjectid , String resourcePath , String httpMethod ) { if ( StringUtils . isBlank ( subjectid ) || StringUtils . isBlank ( resourcePath ) || StringUtils . isBlank ( httpMethod ) || getResourcePermissions ( ) . isEmpty ( ) ) { return false ; } resourcePath = Utils . urlDecode ( resourcePath ) ; if ( getResourcePermissions ( ) . containsKey ( subjectid ) ) { if ( getResourcePermissions ( ) . get ( subjectid ) . containsKey ( resourcePath ) ) { return ! isAllowed ( subjectid , resourcePath , httpMethod ) ; } else if ( getResourcePermissions ( ) . get ( subjectid ) . containsKey ( ALLOW_ALL ) ) { return ! isAllowed ( subjectid , ALLOW_ALL , httpMethod ) ; } } return false ; }
Check if a subject is explicitly denied access to a resource .
36,386
public boolean permissionsContainOwnKeyword ( User user , ParaObject object ) { if ( user == null || object == null ) { return false ; } String resourcePath1 = object . getType ( ) ; String resourcePath2 = object . getObjectURI ( ) . substring ( 1 ) ; String resourcePath3 = object . getPlural ( ) ; return hasOwnKeyword ( App . ALLOW_ALL , resourcePath1 ) || hasOwnKeyword ( App . ALLOW_ALL , resourcePath2 ) || hasOwnKeyword ( App . ALLOW_ALL , resourcePath3 ) || hasOwnKeyword ( user . getId ( ) , resourcePath1 ) || hasOwnKeyword ( user . getId ( ) , resourcePath2 ) || hasOwnKeyword ( user . getId ( ) , resourcePath3 ) ; }
Check if the permissions map contains OWN keyword which restricts access to objects to their creators .
36,387
public void addDatatype ( String pluralDatatype , String datatype ) { pluralDatatype = Utils . noSpaces ( Utils . stripAndTrim ( pluralDatatype , " " ) , "-" ) ; datatype = Utils . noSpaces ( Utils . stripAndTrim ( datatype , " " ) , "-" ) ; if ( StringUtils . isBlank ( pluralDatatype ) || StringUtils . isBlank ( datatype ) ) { return ; } if ( getDatatypes ( ) . size ( ) >= Config . MAX_DATATYPES_PER_APP ) { LoggerFactory . getLogger ( App . class ) . warn ( "Maximum number of types per app reached - {}." , Config . MAX_DATATYPES_PER_APP ) ; return ; } if ( ! getDatatypes ( ) . containsKey ( pluralDatatype ) && ! getDatatypes ( ) . containsValue ( datatype ) && ! ParaObjectUtils . getCoreTypes ( ) . containsKey ( pluralDatatype ) ) { getDatatypes ( ) . put ( pluralDatatype , datatype ) ; } }
Adds a user - defined data type to the types map .
36,388
public Map < String , String > getCredentials ( ) { if ( getId ( ) == null ) { return Collections . emptyMap ( ) ; } else { Map < String , String > keys = new LinkedHashMap < String , String > ( 2 ) ; keys . put ( "accessKey" , getId ( ) ) ; keys . put ( "secretKey" , getSecret ( ) ) ; return keys ; } }
Returns the map containing the app s access key and secret key .
36,389
public static void init ( com . typesafe . config . Config conf ) { try { config = ConfigFactory . load ( ) . getConfig ( PARA ) ; if ( conf != null ) { config = conf . withFallback ( config ) ; } configMap = new HashMap < > ( ) ; for ( Map . Entry < String , ConfigValue > con : config . entrySet ( ) ) { if ( con . getValue ( ) . valueType ( ) != ConfigValueType . LIST ) { configMap . put ( con . getKey ( ) , config . getString ( con . getKey ( ) ) ) ; } } } catch ( Exception ex ) { logger . warn ( "Para configuration file 'application.(conf|json|properties)' is missing from classpath." ) ; config = com . typesafe . config . ConfigFactory . empty ( ) ; } }
Initializes the configuration class by loading the configuration file .
36,390
public static boolean getConfigBoolean ( String key , boolean defaultValue ) { return Boolean . parseBoolean ( getConfigParam ( key , Boolean . toString ( defaultValue ) ) ) ; }
Returns the boolean value of a configuration parameter .
36,391
public static int getConfigInt ( String key , int defaultValue ) { return NumberUtils . toInt ( getConfigParam ( key , Integer . toString ( defaultValue ) ) ) ; }
Returns the integer value of a configuration parameter .
36,392
public static double getConfigDouble ( String key , double defaultValue ) { return NumberUtils . toDouble ( getConfigParam ( key , Double . toString ( defaultValue ) ) ) ; }
Returns the double value of a configuration parameter .
36,393
public static com . typesafe . config . Config getConfig ( ) { if ( config == null ) { init ( null ) ; } return config ; }
Returns the Config object .
36,394
public void saveRequest ( HttpServletRequest request , HttpServletResponse response ) { if ( anyRequestMatcher . matches ( request ) && ! ajaxRequestMatcher . matches ( request ) ) { DefaultSavedRequest savedRequest = new DefaultSavedRequest ( request , portResolver ) ; HttpUtils . setStateParam ( Config . RETURNTO_COOKIE , Utils . base64enc ( savedRequest . getRedirectUrl ( ) . getBytes ( ) ) , request , response ) ; } }
Saves a request in cache .
36,395
public void removeRequest ( HttpServletRequest request , HttpServletResponse response ) { HttpUtils . removeStateParam ( Config . RETURNTO_COOKIE , request , response ) ; }
Removes a saved request from cache .
36,396
public Object invoke ( MethodInvocation mi ) throws Throwable { if ( ! Modifier . isPublic ( mi . getMethod ( ) . getModifiers ( ) ) ) { return mi . proceed ( ) ; } Method searchMethod = mi . getMethod ( ) ; Object [ ] args = mi . getArguments ( ) ; String appid = AOPUtils . getFirstArgOfString ( args ) ; Method superMethod = null ; Measured measuredAnno = null ; try { superMethod = Search . class . getMethod ( searchMethod . getName ( ) , searchMethod . getParameterTypes ( ) ) ; measuredAnno = superMethod . getAnnotation ( Measured . class ) ; } catch ( Exception e ) { logger . error ( "Error in search AOP layer!" , e ) ; } Set < IOListener > ioListeners = Para . getSearchQueryListeners ( ) ; for ( IOListener ioListener : ioListeners ) { ioListener . onPreInvoke ( superMethod , args ) ; logger . debug ( "Executed {}.onPreInvoke()." , ioListener . getClass ( ) . getName ( ) ) ; } Object result = null ; if ( measuredAnno != null ) { result = invokeTimedSearch ( appid , searchMethod , mi ) ; } else { result = mi . proceed ( ) ; } for ( IOListener ioListener : ioListeners ) { ioListener . onPostInvoke ( superMethod , result ) ; logger . debug ( "Executed {}.onPostInvoke()." , ioListener . getClass ( ) . getName ( ) ) ; } return result ; }
Executes code when a method is invoked .
36,397
public static void removeStateParam ( String name , HttpServletRequest req , HttpServletResponse res ) { setRawCookie ( name , "" , req , res , false , 0 ) ; }
Deletes a cookie .
36,398
public static String getCookieValue ( HttpServletRequest req , String name ) { if ( StringUtils . isBlank ( name ) || req == null ) { return null ; } Cookie [ ] cookies = req . getCookies ( ) ; if ( cookies == null ) { return null ; } for ( Cookie cookie : cookies ) { if ( cookie . getName ( ) . equals ( name ) ) { return cookie . getValue ( ) ; } } return null ; }
Reads a cookie .
36,399
public List < OpenIDAttribute > createAttributeList ( String identifier ) { List < OpenIDAttribute > list = new LinkedList < > ( ) ; if ( identifier != null && identifier . matches ( "https://www.google.com/.*" ) ) { OpenIDAttribute email = new OpenIDAttribute ( "email" , "http://axschema.org/contact/email" ) ; OpenIDAttribute first = new OpenIDAttribute ( "firstname" , "http://axschema.org/namePerson/first" ) ; OpenIDAttribute last = new OpenIDAttribute ( "lastname" , "http://axschema.org/namePerson/last" ) ; email . setCount ( 1 ) ; email . setRequired ( true ) ; first . setRequired ( true ) ; last . setRequired ( true ) ; list . add ( email ) ; list . add ( first ) ; list . add ( last ) ; } return list ; }
A list of OpenID attributes to send in a request .