idx
int64
0
41.2k
question
stringlengths
73
5.81k
target
stringlengths
5
918
36,400
public Map < String , Object > getDeviceMetadata ( ) { if ( deviceMetadata == null ) { deviceMetadata = new LinkedHashMap < > ( 20 ) ; } return deviceMetadata ; }
Returns the device s metadata .
36,401
public boolean isExpired ( ) { if ( getTimestamp ( ) == null || getExpiresAfter ( ) == 0 ) { return false ; } long expires = ( getExpiresAfter ( ) * 1000 ) ; long now = Utils . timestamp ( ) ; return ( getTimestamp ( ) + expires ) <= now ; }
Checks if expired .
36,402
public boolean isAmendable ( ) { if ( getTimestamp ( ) == null ) { return false ; } long now = Utils . timestamp ( ) ; return ( getTimestamp ( ) + ( Config . VOTE_LOCKED_AFTER_SEC * 1000 ) ) > now ; }
Checks if vote can still be amended .
36,403
public static void addGzipHeader ( final HttpServletResponse response ) throws ServletException { response . setHeader ( "Content-Encoding" , "gzip" ) ; boolean containsEncoding = response . containsHeader ( "Content-Encoding" ) ; if ( ! containsEncoding ) { throw new ServletException ( "Failure when attempting to set Content-Encoding: gzip" ) ; } }
Adds the gzip HTTP header to the response . This is needed when a gzipped body is returned so that browsers can properly decompress it .
36,404
public static String sign ( String httpMethod , String url , Map < String , String [ ] > params , String apiKey , String apiSecret , String oauthToken , String tokenSecret ) { try { if ( httpMethod != null && url != null && ! url . trim ( ) . isEmpty ( ) && params != null && apiSecret != null ) { Map < String , String [ ] > paramMap = new TreeMap < > ( params ) ; String keyString = percentEncode ( apiSecret ) + "&" + percentEncode ( tokenSecret ) ; byte [ ] keyBytes = keyString . getBytes ( Config . DEFAULT_ENCODING ) ; SecretKey key = new SecretKeySpec ( keyBytes , "HmacSHA1" ) ; Mac mac = Mac . getInstance ( "HmacSHA1" ) ; mac . init ( key ) ; addRequiredParameters ( paramMap , apiKey , oauthToken ) ; String sbs = httpMethod . toUpperCase ( ) + "&" + percentEncode ( normalizeRequestUrl ( url ) ) + "&" + percentEncode ( normalizeRequestParameters ( paramMap ) ) ; logger . debug ( "Oatuh1 base string: {}" , sbs ) ; byte [ ] text = sbs . getBytes ( Config . DEFAULT_ENCODING ) ; String sig = Utils . base64enc ( mac . doFinal ( text ) ) . trim ( ) ; logger . debug ( "Oauth1 Signature: {}" , sig ) ; StringBuilder sb = new StringBuilder ( ) ; sb . append ( "OAuth " ) ; if ( paramMap . containsKey ( "realm" ) ) { String val = paramMap . get ( "realm" ) [ 0 ] ; sb . append ( "realm=\"" . concat ( val ) . concat ( "\"" ) ) ; sb . append ( ", " ) ; } Map < String , SortedSet < String > > oauthParams = getOAuthParameters ( paramMap ) ; TreeSet < String > set = new TreeSet < > ( ) ; set . add ( percentEncode ( sig ) ) ; oauthParams . put ( "oauth_signature" , set ) ; Iterator < String > iter = oauthParams . keySet ( ) . iterator ( ) ; while ( iter . hasNext ( ) ) { String param = iter . next ( ) ; SortedSet < String > valSet = oauthParams . get ( param ) ; String value = ( valSet == null || valSet . isEmpty ( ) ) ? null : valSet . first ( ) ; String headerElem = ( value == null ) ? null : param + "=\"" + value + "\"" ; sb . append ( headerElem ) ; if ( iter . hasNext ( ) ) { sb . append ( ", " ) ; } } String header = sb . toString ( ) ; logger . debug ( "OAuth1 signed header: {}" , header ) ; return header ; } } catch ( Exception e ) { logger . error ( null , e ) ; } return null ; }
Sign a request and return the Authorization header .
36,405
public static String md5 ( String s ) { if ( s == null ) { return "" ; } try { MessageDigest md = MessageDigest . getInstance ( "MD5" ) ; md . update ( s . getBytes ( ) ) ; byte [ ] byteData = md . digest ( ) ; StringBuilder sb = new StringBuilder ( ) ; for ( int i = 0 ; i < byteData . length ; i ++ ) { sb . append ( Integer . toString ( ( byteData [ i ] & 0xff ) + 0x100 , 16 ) . substring ( 1 ) ) ; } return sb . toString ( ) ; } catch ( NoSuchAlgorithmException ex ) { return "" ; } }
md5 hash function .
36,406
public static String bcrypt ( String s ) { return ( s == null ) ? s : BCrypt . hashpw ( s , BCrypt . gensalt ( 12 ) ) ; }
bcrypt hash function implemented by Spring Security .
36,407
public static boolean bcryptMatches ( String plain , String storedHash ) { if ( StringUtils . isBlank ( plain ) || StringUtils . isBlank ( storedHash ) ) { return false ; } try { return BCrypt . checkpw ( plain , storedHash ) ; } catch ( Exception e ) { return false ; } }
Checks if a hash matches a string .
36,408
public static String generateSecurityToken ( int length , boolean urlSafe ) { final byte [ ] bytes = new byte [ length ] ; SecureRandom rand ; try { rand = SecureRandom . getInstance ( "SHA1PRNG" ) ; } catch ( NoSuchAlgorithmException ex ) { logger . error ( null , ex ) ; rand = new SecureRandom ( ) ; } rand . nextBytes ( bytes ) ; return urlSafe ? base64encURL ( bytes ) : base64enc ( bytes ) ; }
Generates an authentication token - a random string encoded in Base64 .
36,409
public static String stripHtml ( String html ) { return ( html == null ) ? "" : Jsoup . parse ( html ) . text ( ) ; }
Strips all HTML tags from a string .
36,410
public static String abbreviate ( String str , int max ) { return StringUtils . isBlank ( str ) ? "" : StringUtils . abbreviate ( str , max ) ; }
Abbreviates a string .
36,411
public static String arrayJoin ( List < String > arr , String separator ) { return ( arr == null || separator == null ) ? "" : StringUtils . join ( arr , separator ) ; }
Joins a list of strings to String using a separator .
36,412
public static String base64dec ( String str ) { if ( str == null ) { return "" ; } try { return new String ( Base64 . decodeBase64 ( str ) , Config . DEFAULT_ENCODING ) ; } catch ( UnsupportedEncodingException ex ) { return "" ; } }
Decodes a string from Base64 .
36,413
public static String formatDate ( String format , Locale loc ) { return formatDate ( timestamp ( ) , format , loc ) ; }
Formats the date for today in a specific format .
36,414
public static String [ ] getMonths ( Locale locale ) { if ( locale == null ) { locale = Locale . US ; } DateFormatSymbols dfs = DateFormatSymbols . getInstance ( locale ) ; return dfs . getMonths ( ) ; }
Returns an array of the months in the Gregorian calendar .
36,415
public static double roundHalfUp ( double d , int scale ) { return BigDecimal . valueOf ( d ) . setScale ( scale , RoundingMode . HALF_UP ) . doubleValue ( ) ; }
Round up a double using the half up method .
36,416
public static String abbreviateInt ( Number number , int decPlaces ) { if ( number == null ) { return "" ; } String abbrevn = number . toString ( ) ; decPlaces = ( int ) Math . pow ( 10 , decPlaces ) ; String [ ] abbrev = { "K" , "M" , "B" , "T" } ; boolean done = false ; for ( int i = abbrev . length - 1 ; i >= 0 && ! done ; i -- ) { int size = ( int ) Math . pow ( 10 , ( double ) ( i + 1 ) * 3 ) ; if ( size <= number . intValue ( ) ) { number = Math . round ( number . intValue ( ) * decPlaces / ( float ) size ) / decPlaces ; abbrevn = number + abbrev [ i ] ; done = true ; } } return abbrevn ; }
Abbreviates an integer by adding a letter suffix at the end . E . g . M for millions K for thousands etc .
36,417
public static String urlDecode ( String s ) { if ( s == null ) { return "" ; } String decoded = s ; try { decoded = URLDecoder . decode ( s , Config . DEFAULT_ENCODING ) ; } catch ( UnsupportedEncodingException ex ) { logger . error ( null , ex ) ; } return decoded ; }
Decodes a URL - encoded string .
36,418
public static String getHostFromURL ( String url ) { URL u = toURL ( url ) ; String host = ( u == null ) ? "" : u . getHost ( ) ; return host ; }
Returns the host part of the URL .
36,419
public static String getObjectURI ( ParaObject obj , boolean includeName , boolean includeId ) { if ( obj == null ) { return "/" ; } if ( includeId && obj . getId ( ) != null ) { return ( includeName && ! StringUtils . isBlank ( obj . getName ( ) ) ) ? obj . getObjectURI ( ) . concat ( "-" ) . concat ( urlEncode ( noSpaces ( obj . getName ( ) , "-" ) ) ) : obj . getObjectURI ( ) ; } else { return obj . getObjectURI ( ) ; } }
Returns the default URL for a given domain object .
36,420
public static boolean isJsonType ( String contentType ) { return StringUtils . startsWith ( contentType , "application/json" ) || StringUtils . startsWith ( contentType , "application/javascript" ) || StringUtils . startsWith ( contentType , "text/javascript" ) ; }
Checks if a response is of type JSON .
36,421
public static String singularToPlural ( String singul ) { return ( StringUtils . isBlank ( singul ) || singul . endsWith ( "es" ) || singul . endsWith ( "ies" ) ) ? singul : ( singul . endsWith ( "s" ) ? singul + "es" : ( singul . endsWith ( "y" ) ? StringUtils . removeEndIgnoreCase ( singul , "y" ) + "ies" : singul + "s" ) ) ; }
Quick and dirty singular to plural conversion .
36,422
public static boolean isBasicType ( Class < ? > clazz ) { return ( clazz == null ) ? false : ( clazz . isPrimitive ( ) || clazz . equals ( String . class ) || clazz . equals ( Long . class ) || clazz . equals ( Integer . class ) || clazz . equals ( Boolean . class ) || clazz . equals ( Byte . class ) || clazz . equals ( Short . class ) || clazz . equals ( Float . class ) || clazz . equals ( Double . class ) || clazz . equals ( Character . class ) ) ; }
Checks if a class is primitive String or a primitive wrapper .
36,423
public static List < Field > getAllDeclaredFields ( Class < ? extends ParaObject > clazz ) { LinkedList < Field > fields = new LinkedList < > ( ) ; if ( clazz == null ) { return fields ; } Class < ? > parent = clazz ; do { for ( Field field : parent . getDeclaredFields ( ) ) { if ( ! Modifier . isTransient ( field . getModifiers ( ) ) && ! field . getName ( ) . equals ( "serialVersionUID" ) ) { fields . add ( field ) ; } } parent = parent . getSuperclass ( ) ; } while ( ! parent . equals ( Object . class ) ) ; return fields ; }
Returns a list of all declared fields in a class . Transient and serialVersionUID fields are skipped . This method scans parent classes as well .
36,424
public String getApiPath ( ) { if ( StringUtils . isBlank ( path ) ) { return DEFAULT_PATH ; } else { if ( ! path . endsWith ( "/" ) ) { path += "/" ; } return path ; } }
Returns the API request path .
36,425
@ SuppressWarnings ( "unchecked" ) public void setAccessToken ( String token ) { if ( ! StringUtils . isBlank ( token ) ) { try { String payload = Utils . base64dec ( StringUtils . substringBetween ( token , "." , "." ) ) ; Map < String , Object > decoded = ParaObjectUtils . getJsonMapper ( ) . readValue ( payload , Map . class ) ; if ( decoded != null && decoded . containsKey ( "exp" ) ) { this . tokenKeyExpires = ( Long ) decoded . get ( "exp" ) ; this . tokenKeyNextRefresh = ( Long ) decoded . get ( "refresh" ) ; } } catch ( Exception ex ) { this . tokenKeyExpires = null ; this . tokenKeyNextRefresh = null ; } } this . tokenKey = token ; }
Sets the JWT access token .
36,426
public Response invokeGet ( String resourcePath , MultivaluedMap < String , String > params ) { logger . debug ( "GET {}, params: {}" , getFullPath ( resourcePath ) , params ) ; return invokeSignedRequest ( getApiClient ( ) , accessKey , key ( ! JWT_PATH . equals ( resourcePath ) ) , GET , getEndpoint ( ) , getFullPath ( resourcePath ) , null , params , new byte [ 0 ] ) ; }
Invoke a GET request to the Para API .
36,427
public Response invokePost ( String resourcePath , Entity < ? > entity ) { logger . debug ( "POST {}, entity: {}" , getFullPath ( resourcePath ) , entity ) ; return invokeSignedRequest ( getApiClient ( ) , accessKey , key ( true ) , POST , getEndpoint ( ) , getFullPath ( resourcePath ) , null , null , entity ) ; }
Invoke a POST request to the Para API .
36,428
public Response invokeDelete ( String resourcePath , MultivaluedMap < String , String > params ) { logger . debug ( "DELETE {}, params: {}" , getFullPath ( resourcePath ) , params ) ; return invokeSignedRequest ( getApiClient ( ) , accessKey , key ( true ) , DELETE , getEndpoint ( ) , getFullPath ( resourcePath ) , null , params , new byte [ 0 ] ) ; }
Invoke a DELETE request to the Para API .
36,429
public < P extends ParaObject > List < P > getItems ( String at , Map < String , Object > result , Pager ... pager ) { if ( result != null && ! result . isEmpty ( ) && ! StringUtils . isBlank ( at ) && result . containsKey ( at ) ) { if ( pager != null && pager . length > 0 && pager [ 0 ] != null ) { if ( result . containsKey ( "totalHits" ) ) { pager [ 0 ] . setCount ( ( ( Integer ) result . get ( "totalHits" ) ) . longValue ( ) ) ; } if ( result . containsKey ( "lastKey" ) ) { pager [ 0 ] . setLastKey ( ( String ) result . get ( "lastKey" ) ) ; } } return getItemsFromList ( ( List < ? > ) result . get ( at ) ) ; } return Collections . emptyList ( ) ; }
Converts a list of Maps to a List of ParaObjects at a given path within the JSON tree structure .
36,430
public < P extends ParaObject > P update ( P obj ) { if ( obj == null ) { return null ; } return getEntity ( invokePatch ( obj . getType ( ) . concat ( "/" ) . concat ( obj . getId ( ) ) , Entity . json ( obj ) ) , obj . getClass ( ) ) ; }
Updates an object permanently . Supports partial updates .
36,431
public < P extends ParaObject > void delete ( P obj ) { if ( obj == null || obj . getId ( ) == null ) { return ; } invokeDelete ( obj . getType ( ) . concat ( "/" ) . concat ( obj . getId ( ) ) , null ) ; }
Deletes an object permanently .
36,432
public < P extends ParaObject > List < P > createAll ( List < P > objects ) { if ( objects == null || objects . isEmpty ( ) || objects . get ( 0 ) == null ) { return Collections . emptyList ( ) ; } final int size = this . chunkSize ; return IntStream . range ( 0 , getNumChunks ( objects , size ) ) . mapToObj ( i -> ( List < P > ) partitionList ( objects , i , size ) ) . map ( chunk -> invokePost ( "_batch" , Entity . json ( chunk ) ) ) . map ( response -> ( List < P > ) this . getEntity ( response , List . class ) ) . map ( entity -> ( List < P > ) getItemsFromList ( entity ) ) . flatMap ( List :: stream ) . collect ( Collectors . toList ( ) ) ; }
Saves multiple objects to the data store .
36,433
public < P extends ParaObject > List < P > readAll ( List < String > keys ) { if ( keys == null || keys . isEmpty ( ) ) { return Collections . emptyList ( ) ; } final int size = this . chunkSize ; return IntStream . range ( 0 , getNumChunks ( keys , size ) ) . mapToObj ( i -> ( List < String > ) partitionList ( keys , i , size ) ) . map ( chunk -> { MultivaluedMap < String , String > ids = new MultivaluedHashMap < > ( ) ; ids . put ( "ids" , chunk ) ; return invokeGet ( "_batch" , ids ) ; } ) . map ( response -> ( List < P > ) this . getEntity ( response , List . class ) ) . map ( entity -> ( List < P > ) getItemsFromList ( entity ) ) . flatMap ( List :: stream ) . collect ( Collectors . toList ( ) ) ; }
Retrieves multiple objects from the data store .
36,434
public void deleteAll ( List < String > keys ) { if ( keys == null || keys . isEmpty ( ) ) { return ; } final int size = this . chunkSize ; IntStream . range ( 0 , getNumChunks ( keys , size ) ) . mapToObj ( i -> ( List < String > ) partitionList ( keys , i , size ) ) . forEach ( chunk -> { MultivaluedMap < String , String > ids = new MultivaluedHashMap < > ( ) ; ids . put ( "ids" , chunk ) ; invokeDelete ( "_batch" , ids ) ; } ) ; }
Deletes multiple objects .
36,435
@ SuppressWarnings ( "unchecked" ) public < P extends ParaObject > List < P > list ( String type , Pager ... pager ) { if ( StringUtils . isBlank ( type ) ) { return Collections . emptyList ( ) ; } return getItems ( ( Map < String , Object > ) getEntity ( invokeGet ( type , pagerToParams ( pager ) ) , Map . class ) , pager ) ; }
Returns a list all objects found for the given type . The result is paginated so only one page of items is returned at a time .
36,436
public < P extends ParaObject > P findById ( String id ) { MultivaluedMap < String , String > params = new MultivaluedHashMap < > ( ) ; params . putSingle ( Config . _ID , id ) ; List < P > list = getItems ( find ( "id" , params ) ) ; return list . isEmpty ( ) ? null : list . get ( 0 ) ; }
Simple id search .
36,437
public < P extends ParaObject > List < P > findByIds ( List < String > ids ) { MultivaluedMap < String , String > params = new MultivaluedHashMap < > ( ) ; params . put ( "ids" , ids ) ; return getItems ( find ( "ids" , params ) ) ; }
Simple multi id search .
36,438
public < P extends ParaObject > List < P > findSimilar ( String type , String filterKey , String [ ] fields , String liketext , Pager ... pager ) { MultivaluedMap < String , String > params = new MultivaluedHashMap < > ( ) ; params . put ( "fields" , fields == null ? null : Arrays . asList ( fields ) ) ; params . putSingle ( "filterid" , filterKey ) ; params . putSingle ( "like" , liketext ) ; params . putSingle ( Config . _TYPE , type ) ; params . putAll ( pagerToParams ( pager ) ) ; return getItems ( find ( "similar" , params ) , pager ) ; }
Searches for objects that have similar property values to a given text . A find like this query .
36,439
public < P extends ParaObject > List < P > findTagged ( String type , String [ ] tags , Pager ... pager ) { MultivaluedMap < String , String > params = new MultivaluedHashMap < > ( ) ; params . put ( "tags" , tags == null ? null : Arrays . asList ( tags ) ) ; params . putSingle ( Config . _TYPE , type ) ; params . putAll ( pagerToParams ( pager ) ) ; return getItems ( find ( "tagged" , params ) , pager ) ; }
Searches for objects tagged with one or more tags .
36,440
public < P extends ParaObject > List < P > findTermInList ( String type , String field , List < String > terms , Pager ... pager ) { MultivaluedMap < String , String > params = new MultivaluedHashMap < > ( ) ; params . putSingle ( "field" , field ) ; params . put ( "terms" , terms ) ; params . putSingle ( Config . _TYPE , type ) ; params . putAll ( pagerToParams ( pager ) ) ; return getItems ( find ( "in" , params ) , pager ) ; }
Searches for objects having a property value that is in list of possible values .
36,441
public < P extends ParaObject > List < P > findTerms ( String type , Map < String , ? > terms , boolean matchAll , Pager ... pager ) { if ( terms == null ) { return Collections . emptyList ( ) ; } MultivaluedMap < String , String > params = new MultivaluedHashMap < > ( ) ; params . putSingle ( "matchall" , Boolean . toString ( matchAll ) ) ; LinkedList < String > list = new LinkedList < > ( ) ; for ( Map . Entry < String , ? extends Object > term : terms . entrySet ( ) ) { String key = term . getKey ( ) ; Object value = term . getValue ( ) ; if ( value != null ) { list . add ( key . concat ( Config . SEPARATOR ) . concat ( value . toString ( ) ) ) ; } } if ( ! terms . isEmpty ( ) ) { params . put ( "terms" , list ) ; } params . putSingle ( Config . _TYPE , type ) ; params . putAll ( pagerToParams ( pager ) ) ; return getItems ( find ( "terms" , params ) , pager ) ; }
Searches for objects that have properties matching some given values . A terms query .
36,442
public < P extends ParaObject > List < P > findWildcard ( String type , String field , String wildcard , Pager ... pager ) { MultivaluedMap < String , String > params = new MultivaluedHashMap < > ( ) ; params . putSingle ( "field" , field ) ; params . putSingle ( "q" , wildcard ) ; params . putSingle ( Config . _TYPE , type ) ; params . putAll ( pagerToParams ( pager ) ) ; return getItems ( find ( "wildcard" , params ) , pager ) ; }
Searches for objects that have a property with a value matching a wildcard query .
36,443
public Long getCount ( String type ) { MultivaluedMap < String , String > params = new MultivaluedHashMap < > ( ) ; params . putSingle ( Config . _TYPE , type ) ; Pager pager = new Pager ( ) ; getItems ( find ( "count" , params ) , pager ) ; return pager . getCount ( ) ; }
Counts indexed objects .
36,444
@ SuppressWarnings ( "unchecked" ) public Long countLinks ( ParaObject obj , String type2 ) { if ( obj == null || obj . getId ( ) == null || type2 == null ) { return 0L ; } MultivaluedMap < String , String > params = new MultivaluedHashMap < > ( ) ; params . putSingle ( "count" , "true" ) ; Pager pager = new Pager ( ) ; String url = Utils . formatMessage ( "{0}/links/{1}" , obj . getObjectURI ( ) , type2 ) ; getItems ( ( Map < String , Object > ) getEntity ( invokeGet ( url , params ) , Map . class ) , pager ) ; return pager . getCount ( ) ; }
Count the total number of links between this object and another type of object .
36,445
@ SuppressWarnings ( "unchecked" ) public < P extends ParaObject > List < P > getLinkedObjects ( ParaObject obj , String type2 , Pager ... pager ) { if ( obj == null || obj . getId ( ) == null || type2 == null ) { return Collections . emptyList ( ) ; } String url = Utils . formatMessage ( "{0}/links/{1}" , obj . getObjectURI ( ) , type2 ) ; return getItems ( ( Map < String , Object > ) getEntity ( invokeGet ( url , pagerToParams ( pager ) ) , Map . class ) , pager ) ; }
Returns all objects linked to the given one . Only applicable to many - to - many relationships .
36,446
public boolean isLinked ( ParaObject obj , String type2 , String id2 ) { if ( obj == null || obj . getId ( ) == null || type2 == null || id2 == null ) { return false ; } String url = Utils . formatMessage ( "{0}/links/{1}/{2}" , obj . getObjectURI ( ) , type2 , id2 ) ; Boolean result = getEntity ( invokeGet ( url , null ) , Boolean . class ) ; return result != null && result ; }
Checks if this object is linked to another .
36,447
public boolean isLinked ( ParaObject obj , ParaObject toObj ) { if ( obj == null || obj . getId ( ) == null || toObj == null || toObj . getId ( ) == null ) { return false ; } return isLinked ( obj , toObj . getType ( ) , toObj . getId ( ) ) ; }
Checks if a given object is linked to this one .
36,448
public String link ( ParaObject obj , String id2 ) { if ( obj == null || obj . getId ( ) == null || id2 == null ) { return null ; } String url = Utils . formatMessage ( "{0}/links/{1}" , obj . getObjectURI ( ) , id2 ) ; return getEntity ( invokePost ( url , null ) , String . class ) ; }
Links an object to this one in a many - to - many relationship . Only a link is created . Objects are left untouched . The type of the second object is automatically determined on read .
36,449
public void unlink ( ParaObject obj , String type2 , String id2 ) { if ( obj == null || obj . getId ( ) == null || type2 == null || id2 == null ) { return ; } String url = Utils . formatMessage ( "{0}/links/{1}/{2}" , obj . getObjectURI ( ) , type2 , id2 ) ; invokeDelete ( url , null ) ; }
Unlinks an object from this one . Only a link is deleted . Objects are left untouched .
36,450
public void unlinkAll ( ParaObject obj ) { if ( obj == null || obj . getId ( ) == null ) { return ; } String url = Utils . formatMessage ( "{0}/links" , obj . getObjectURI ( ) ) ; invokeDelete ( url , null ) ; }
Unlinks all objects that are linked to this one .
36,451
@ SuppressWarnings ( "unchecked" ) public < P extends ParaObject > List < P > getChildren ( ParaObject obj , String type2 , Pager ... pager ) { if ( obj == null || obj . getId ( ) == null || type2 == null ) { return Collections . emptyList ( ) ; } MultivaluedMap < String , String > params = new MultivaluedHashMap < > ( ) ; params . putSingle ( "childrenonly" , "true" ) ; params . putAll ( pagerToParams ( pager ) ) ; String url = Utils . formatMessage ( "{0}/links/{1}" , obj . getObjectURI ( ) , type2 ) ; return getItems ( ( Map < String , Object > ) getEntity ( invokeGet ( url , params ) , Map . class ) , pager ) ; }
Returns all child objects linked to this object .
36,452
public void deleteChildren ( ParaObject obj , String type2 ) { if ( obj == null || obj . getId ( ) == null || type2 == null ) { return ; } MultivaluedMap < String , String > params = new MultivaluedHashMap < > ( ) ; params . putSingle ( "childrenonly" , "true" ) ; String url = Utils . formatMessage ( "{0}/links/{1}" , obj . getObjectURI ( ) , type2 ) ; invokeDelete ( url , params ) ; }
Deletes all child objects permanently .
36,453
public String newId ( ) { String res = getEntity ( invokeGet ( "utils/newid" , null ) , String . class ) ; return res != null ? res : "" ; }
Generates a new unique id .
36,454
public long getTimestamp ( ) { Long res = getEntity ( invokeGet ( "utils/timestamp" , null ) , Long . class ) ; return res != null ? res : 0L ; }
Returns the current timestamp .
36,455
public < P extends ParaObject > P me ( String accessToken ) { if ( ! StringUtils . isBlank ( accessToken ) ) { String auth = accessToken . startsWith ( "Bearer" ) ? accessToken : "Bearer " + accessToken ; Response res = invokeSignedRequest ( getApiClient ( ) , accessKey , auth , GET , getEndpoint ( ) , getFullPath ( "_me" ) , null , null , new byte [ 0 ] ) ; Map < String , Object > data = getEntity ( res , Map . class ) ; return ParaObjectUtils . setAnnotatedFields ( data ) ; } return me ( ) ; }
Verifies a given JWT and returns the authenticated subject . This request will not remember the JWT in memory .
36,456
public boolean voteDown ( ParaObject obj , String voterid ) { if ( obj == null || StringUtils . isBlank ( voterid ) ) { return false ; } return getEntity ( invokePatch ( obj . getType ( ) . concat ( "/" ) . concat ( obj . getId ( ) ) , Entity . json ( Collections . singletonMap ( "_votedown" , voterid ) ) ) , Boolean . class ) ; }
Downvote an object and register the vote in DB .
36,457
public Map < String , Object > rebuildIndex ( String destinationIndex ) { MultivaluedMap < String , String > params = new MultivaluedHashMap < > ( ) ; params . putSingle ( "destinationIndex" , destinationIndex ) ; return getEntity ( invokeSignedRequest ( getApiClient ( ) , accessKey , key ( true ) , POST , getEndpoint ( ) , getFullPath ( "_reindex" ) , null , params , new byte [ 0 ] ) , Map . class ) ; }
Rebuilds the entire search index .
36,458
public Map < String , Map < String , Map < String , Map < String , ? > > > > addValidationConstraint ( String type , String field , Constraint c ) { if ( StringUtils . isBlank ( type ) || StringUtils . isBlank ( field ) || c == null ) { return Collections . emptyMap ( ) ; } return getEntity ( invokePut ( Utils . formatMessage ( "_constraints/{0}/{1}/{2}" , type , field , c . getName ( ) ) , Entity . json ( c . getPayload ( ) ) ) , Map . class ) ; }
Add a new constraint for a given field .
36,459
public Map < String , Map < String , Map < String , Map < String , ? > > > > removeValidationConstraint ( String type , String field , String constraintName ) { if ( StringUtils . isBlank ( type ) || StringUtils . isBlank ( field ) || StringUtils . isBlank ( constraintName ) ) { return Collections . emptyMap ( ) ; } return getEntity ( invokeDelete ( Utils . formatMessage ( "_constraints/{0}/{1}/{2}" , type , field , constraintName ) , null ) , Map . class ) ; }
Removes a validation constraint for a given field .
36,460
public Map < String , Map < String , List < String > > > resourcePermissions ( ) { return getEntity ( invokeGet ( "_permissions" , null ) , Map . class ) ; }
Returns the permissions for all subjects and resources for current app .
36,461
public Map < String , Map < String , List < String > > > revokeResourcePermission ( String subjectid , String resourcePath ) { if ( StringUtils . isBlank ( subjectid ) || StringUtils . isBlank ( resourcePath ) ) { return Collections . emptyMap ( ) ; } resourcePath = Utils . urlEncode ( resourcePath ) ; return getEntity ( invokeDelete ( Utils . formatMessage ( "_permissions/{0}/{1}" , subjectid , resourcePath ) , null ) , Map . class ) ; }
Revokes a permission for a subject meaning they no longer will be able to access the given resource .
36,462
public Map < String , Map < String , List < String > > > revokeAllResourcePermissions ( String subjectid ) { if ( StringUtils . isBlank ( subjectid ) ) { return Collections . emptyMap ( ) ; } return getEntity ( invokeDelete ( Utils . formatMessage ( "_permissions/{0}" , subjectid ) , null ) , Map . class ) ; }
Revokes all permission for a subject .
36,463
public void addAppSetting ( String key , Object value ) { if ( ! StringUtils . isBlank ( key ) && value != null ) { invokePut ( Utils . formatMessage ( "_settings/{0}" , key ) , Entity . json ( Collections . singletonMap ( "value" , value ) ) ) ; } }
Adds or overwrites an app - specific setting .
36,464
public void removeAppSetting ( String key ) { if ( ! StringUtils . isBlank ( key ) ) { invokeDelete ( Utils . formatMessage ( "_settings/{0}" , key ) , null ) ; } }
Removes an app - specific setting .
36,465
public static void putValue ( String registryName , String key , Object value ) { if ( StringUtils . isBlank ( registryName ) || StringUtils . isBlank ( key ) || value == null ) { return ; } Sysprop registryObject = readRegistryObject ( registryName ) ; if ( registryObject == null ) { registryObject = new Sysprop ( getRegistryID ( registryName ) ) ; registryObject . addProperty ( key , value ) ; CoreUtils . getInstance ( ) . getDao ( ) . create ( REGISTRY_APP_ID , registryObject ) ; } else { registryObject . addProperty ( key , value ) ; CoreUtils . getInstance ( ) . getDao ( ) . update ( REGISTRY_APP_ID , registryObject ) ; } }
Add a specific value to a registry . If the registry doesn t exist yet create it .
36,466
public static Object getValue ( String registryName , String key ) { Map < String , Object > registry = getRegistry ( registryName ) ; if ( registry == null || StringUtils . isBlank ( key ) ) { return null ; } return registry . get ( key ) ; }
Retrieve one specific value from a registry .
36,467
public static void removeValue ( String registryName , String key ) { Sysprop registryObject = readRegistryObject ( registryName ) ; if ( registryObject == null || StringUtils . isBlank ( key ) ) { return ; } if ( registryObject . hasProperty ( key ) ) { registryObject . removeProperty ( key ) ; CoreUtils . getInstance ( ) . getDao ( ) . update ( REGISTRY_APP_ID , registryObject ) ; } }
Remove a specific value from a registry .
36,468
public static Map < String , Object > getRegistry ( String registryName ) { if ( StringUtils . isBlank ( registryName ) ) { return null ; } Sysprop registryObject = readRegistryObject ( registryName ) ; return registryObject == null ? null : registryObject . getProperties ( ) ; }
Retrieve an entire registry .
36,469
public void doFilter ( ServletRequest req , ServletResponse res , FilterChain chain ) throws IOException , ServletException { BufferedRequestWrapper request = new BufferedRequestWrapper ( ( HttpServletRequest ) req ) ; HttpServletResponse response = ( HttpServletResponse ) res ; boolean proceed = true ; try { String appid = RestUtils . extractAccessKey ( request ) ; boolean isApp = ! StringUtils . isBlank ( appid ) ; boolean isGuest = RestUtils . isAnonymousRequest ( request ) ; if ( isGuest && RestRequestMatcher . INSTANCE . matches ( request ) ) { proceed = guestAuthRequestHandler ( appid , ( HttpServletRequest ) req , response ) ; } else if ( ! isApp && RestRequestMatcher . INSTANCE . matches ( request ) ) { proceed = userAuthRequestHandler ( ( HttpServletRequest ) req , response ) ; } else if ( isApp && RestRequestMatcher . INSTANCE_STRICT . matches ( request ) ) { proceed = appAuthRequestHandler ( appid , request , response ) ; } } catch ( Exception e ) { logger . error ( "Failed to authorize request." , e ) ; } if ( proceed ) { chain . doFilter ( request , res ) ; } }
Authenticates an application or user or guest .
36,470
public static AmazonSQS getClient ( ) { if ( sqsClient != null ) { return sqsClient ; } if ( Config . IN_PRODUCTION ) { sqsClient = AmazonSQSClientBuilder . standard ( ) . build ( ) ; } else { sqsClient = AmazonSQSClientBuilder . standard ( ) . withCredentials ( new AWSStaticCredentialsProvider ( new BasicAWSCredentials ( "x" , "x" ) ) ) . withEndpointConfiguration ( new EndpointConfiguration ( LOCAL_ENDPOINT , "" ) ) . build ( ) ; } Para . addDestroyListener ( new DestroyListener ( ) { public void onDestroy ( ) { sqsClient . shutdown ( ) ; } } ) ; return sqsClient ; }
Returns a client instance for AWS SQS .
36,471
public static String createQueue ( String name ) { if ( StringUtils . isBlank ( name ) ) { return null ; } String queueURL = getQueueURL ( name ) ; if ( queueURL == null ) { try { queueURL = getClient ( ) . createQueue ( new CreateQueueRequest ( name ) ) . getQueueUrl ( ) ; } catch ( AmazonServiceException ase ) { logException ( ase ) ; } catch ( AmazonClientException ace ) { logger . error ( "Could not reach SQS. {0}" , ace . toString ( ) ) ; } } return queueURL ; }
Creates a new SQS queue on AWS .
36,472
public static void deleteQueue ( String queueURL ) { if ( ! StringUtils . isBlank ( queueURL ) ) { try { getClient ( ) . deleteQueue ( new DeleteQueueRequest ( queueURL ) ) ; } catch ( AmazonServiceException ase ) { logException ( ase ) ; } catch ( AmazonClientException ace ) { logger . error ( "Could not reach SQS. {0}" , ace . toString ( ) ) ; } } }
Deletes an SQS queue on AWS .
36,473
public static String getQueueURL ( String name ) { try { return getClient ( ) . getQueueUrl ( name ) . getQueueUrl ( ) ; } catch ( Exception e ) { logger . info ( "Queue '{}' could not be found: {}" , name , e . getMessage ( ) ) ; return null ; } }
Returns the SQS queue URL .
36,474
public static List < String > listQueues ( ) { List < String > list = new ArrayList < > ( ) ; try { list = getClient ( ) . listQueues ( ) . getQueueUrls ( ) ; } catch ( AmazonServiceException ase ) { logException ( ase ) ; } catch ( AmazonClientException ace ) { logger . error ( "Could not reach SQS. {0}" , ace . toString ( ) ) ; } return list ; }
Returns a list of URLs for all available queues on SQS .
36,475
public static void pushMessages ( String queueURL , List < String > messages ) { if ( ! StringUtils . isBlank ( queueURL ) && messages != null ) { try { int j = 0 ; List < SendMessageBatchRequestEntry > msgs = new ArrayList < > ( MAX_MESSAGES ) ; for ( int i = 0 ; i < messages . size ( ) ; i ++ ) { String message = messages . get ( i ) ; if ( ! StringUtils . isBlank ( message ) ) { msgs . add ( new SendMessageBatchRequestEntry ( ) . withMessageBody ( message ) . withId ( Integer . toString ( i ) ) ) ; } if ( ++ j >= MAX_MESSAGES || i == messages . size ( ) - 1 ) { if ( ! msgs . isEmpty ( ) ) { getClient ( ) . sendMessageBatch ( queueURL , msgs ) ; msgs . clear ( ) ; } j = 0 ; } } } catch ( AmazonServiceException ase ) { logException ( ase ) ; } catch ( AmazonClientException ace ) { logger . error ( "Could not reach SQS. {}" , ace . toString ( ) ) ; } } }
Pushes a number of messages in batch to an SQS queue .
36,476
public static List < String > pullMessages ( String queueURL , int numberOfMessages ) { List < String > messages = new ArrayList < > ( ) ; if ( ! StringUtils . isBlank ( queueURL ) ) { try { int batchSteps = 1 ; int maxForBatch = numberOfMessages ; if ( ( numberOfMessages > MAX_MESSAGES ) ) { batchSteps = ( numberOfMessages / MAX_MESSAGES ) + ( ( numberOfMessages % MAX_MESSAGES > 0 ) ? 1 : 0 ) ; maxForBatch = MAX_MESSAGES ; } for ( int i = 0 ; i < batchSteps ; i ++ ) { List < Message > list = getClient ( ) . receiveMessage ( new ReceiveMessageRequest ( queueURL ) . withMaxNumberOfMessages ( maxForBatch ) . withWaitTimeSeconds ( POLLING_INTERVAL ) ) . getMessages ( ) ; if ( list != null && ! list . isEmpty ( ) ) { List < DeleteMessageBatchRequestEntry > del = new ArrayList < > ( ) ; for ( Message msg : list ) { messages . add ( msg . getBody ( ) ) ; del . add ( new DeleteMessageBatchRequestEntry ( msg . getMessageId ( ) , msg . getReceiptHandle ( ) ) ) ; } getClient ( ) . deleteMessageBatch ( queueURL , del ) ; } } } catch ( AmazonServiceException ase ) { logException ( ase ) ; } catch ( AmazonClientException ace ) { logger . error ( "Could not reach SQS. {}" , ace . toString ( ) ) ; } } return messages ; }
Pulls a number of messages from an SQS queue .
36,477
public static void startPollingForMessages ( final String queueURL ) { if ( ! StringUtils . isBlank ( queueURL ) && ! POLLING_THREADS . containsKey ( queueURL ) ) { logger . info ( "Starting SQS river using queue {} (polling interval: {}s)" , queueURL , POLLING_INTERVAL ) ; POLLING_THREADS . putIfAbsent ( queueURL , Para . getExecutorService ( ) . submit ( new SQSRiver ( queueURL ) ) ) ; Para . addDestroyListener ( new DestroyListener ( ) { public void onDestroy ( ) { stopPollingForMessages ( queueURL ) ; } } ) ; } }
Starts polling for messages from SQS in a separate thread .
36,478
public static void stopPollingForMessages ( String queueURL ) { if ( ! StringUtils . isBlank ( queueURL ) && POLLING_THREADS . containsKey ( queueURL ) ) { logger . info ( "Stopping SQS river on queue {} ..." , queueURL ) ; POLLING_THREADS . get ( queueURL ) . cancel ( true ) ; POLLING_THREADS . remove ( queueURL ) ; } }
Stops the thread that has been polling for messages .
36,479
public List < Map < String , Object > > getNstd ( ) { if ( nstd == null ) { nstd = new ArrayList < > ( ) ; } return nstd ; }
Get the nested objects that are linked by this link .
36,480
public void addNestedObject ( ParaObject obj ) { if ( obj != null ) { getNstd ( ) . add ( ParaObjectUtils . getAnnotatedFields ( obj , false ) ) ; } }
Add an object to nest inside the linker object . Used for joining queries when searching objects in a many - to - many relationship .
36,481
public void saveToken ( CsrfToken t , HttpServletRequest request , HttpServletResponse response ) { String ident = getIdentifierFromCookie ( request ) ; if ( ident != null ) { String key = ident . concat ( parameterName ) ; CsrfToken token = loadToken ( request ) ; if ( token == null ) { token = generateToken ( null ) ; if ( Config . isCacheEnabled ( ) ) { cache . put ( Config . getRootAppIdentifier ( ) , key , token , ( long ) Config . SESSION_TIMEOUT_SEC ) ; } else { localCache . put ( key , new Object [ ] { token , System . currentTimeMillis ( ) } ) ; } } storeTokenAsCookie ( token , request , response ) ; } }
Saves a CSRF token in cache .
36,482
public CsrfToken loadToken ( HttpServletRequest request ) { CsrfToken token = null ; String ident = getIdentifierFromCookie ( request ) ; if ( ident != null ) { String key = ident . concat ( parameterName ) ; if ( Config . isCacheEnabled ( ) ) { token = cache . get ( Config . getRootAppIdentifier ( ) , key ) ; } else { Object [ ] arr = localCache . get ( key ) ; if ( arr != null && arr . length == 2 ) { boolean expired = ( ( ( Long ) arr [ 1 ] ) + Config . SESSION_TIMEOUT_SEC * 1000 ) < System . currentTimeMillis ( ) ; if ( expired ) { localCache . remove ( key ) ; } else { token = ( CsrfToken ) arr [ 0 ] ; } } } } return token ; }
Loads a CSRF token from cache .
36,483
private static JsonPointer computeRelativePath ( JsonPointer path , int startIdx , int endIdx , List < Diff > diffs ) { List < Integer > counters = new ArrayList < Integer > ( path . size ( ) ) ; for ( int i = 0 ; i < path . size ( ) ; i ++ ) { counters . add ( 0 ) ; } for ( int i = startIdx ; i <= endIdx ; i ++ ) { Diff diff = diffs . get ( i ) ; if ( Operation . ADD == diff . getOperation ( ) || Operation . REMOVE == diff . getOperation ( ) ) { updatePath ( path , diff , counters ) ; } } return updatePathWithCounters ( counters , path ) ; }
Finds the longest common Ancestor ending at Array
36,484
public static JsonPointer parse ( String path ) throws IllegalArgumentException { StringBuilder reftoken = null ; List < RefToken > result = new ArrayList < RefToken > ( ) ; for ( int i = 0 ; i < path . length ( ) ; ++ i ) { char c = path . charAt ( i ) ; if ( i == 0 ) { if ( c != '/' ) throw new IllegalArgumentException ( "Missing leading slash" ) ; reftoken = new StringBuilder ( ) ; continue ; } switch ( c ) { case '~' : switch ( path . charAt ( ++ i ) ) { case '0' : reftoken . append ( '~' ) ; break ; case '1' : reftoken . append ( '/' ) ; break ; default : throw new IllegalArgumentException ( "Invalid escape sequence ~" + path . charAt ( i ) + " at index " + i ) ; } break ; case '/' : result . add ( new RefToken ( reftoken . toString ( ) ) ) ; reftoken . setLength ( 0 ) ; break ; default : reftoken . append ( c ) ; break ; } } if ( reftoken == null ) return ROOT ; result . add ( RefToken . parse ( reftoken . toString ( ) ) ) ; return new JsonPointer ( result ) ; }
Parses a valid string representation of a JSON Pointer .
36,485
JsonPointer append ( String field ) { RefToken [ ] newTokens = Arrays . copyOf ( tokens , tokens . length + 1 ) ; newTokens [ tokens . length ] = new RefToken ( field ) ; return new JsonPointer ( newTokens ) ; }
Creates a new JSON pointer to the specified field of the object referenced by this instance .
36,486
public RefToken get ( int index ) throws IndexOutOfBoundsException { if ( index < 0 || index >= tokens . length ) throw new IndexOutOfBoundsException ( "Illegal index: " + index ) ; return tokens [ index ] ; }
Retrieves the reference token at the specified index .
36,487
public JsonNode evaluate ( final JsonNode document ) throws JsonPointerEvaluationException { JsonNode current = document ; for ( int idx = 0 ; idx < tokens . length ; ++ idx ) { final RefToken token = tokens [ idx ] ; if ( current . isArray ( ) ) { if ( ! token . isArrayIndex ( ) ) error ( idx , "Can't reference field \"" + token . getField ( ) + "\" on array" , document ) ; if ( token . getIndex ( ) == LAST_INDEX || token . getIndex ( ) >= current . size ( ) ) error ( idx , "Array index " + token . toString ( ) + " is out of bounds" , document ) ; current = current . get ( token . getIndex ( ) ) ; } else if ( current . isObject ( ) ) { if ( ! current . has ( token . getField ( ) ) ) error ( idx , "Missing field \"" + token . getField ( ) + "\"" , document ) ; current = current . get ( token . getField ( ) ) ; } else error ( idx , "Can't reference past scalar value" , document ) ; } return current ; }
Takes a target document and resolves the node represented by this instance .
36,488
public FieldStatsOptions addField ( Field field ) { Assert . notNull ( field , "Field for statistics must not be 'null'." ) ; state . fields . add ( field ) ; return new FieldStatsOptions ( field , state ) ; }
Adds a field to the statistics to be requested .
36,489
public FieldStatsOptions addField ( String fieldName ) { Assert . hasText ( fieldName , "Fieldname for statistics must not be blank." ) ; return addField ( new SimpleField ( fieldName ) ) ; }
Adds a field via its name to the statistics to be requested .
36,490
public final < T extends Query > T addGroupByField ( String fieldname ) { return addGroupByField ( new SimpleField ( fieldname ) ) ; }
add grouping on field name
36,491
public SpellcheckOptions collateParam ( String param , Object value ) { return potentiallySetCollate ( ) . createNewAndAppend ( SpellingParams . SPELLCHECK_COLLATE_PARAM_OVERRIDE + param , value ) ; }
This parameter prefix can be used to specify any additional parameters that you wish to the Spellchecker to use when internally validating collation queries .
36,492
public HighlightOptions addField ( Field field ) { Assert . notNull ( field , "Field must not be null!" ) ; this . fields . add ( field ) ; return this ; }
Add field to highlight
36,493
public HighlightOptions addField ( String fieldname ) { Assert . hasText ( fieldname , "Fieldname must not be null nor empty!" ) ; return addField ( new SimpleField ( fieldname ) ) ; }
Add name of field to highlight on
36,494
public HighlightOptions addHighlightParameter ( String parameterName , Object value ) { return addHighlightParameter ( new HighlightParameter ( parameterName , value ) ) ; }
Add parameter by name
36,495
public Collection < FieldWithHighlightParameters > getFieldsWithHighlightParameters ( ) { List < FieldWithHighlightParameters > result = new ArrayList < > ( ) ; for ( Field candidate : fields ) { if ( candidate instanceof FieldWithHighlightParameters ) { result . add ( ( FieldWithHighlightParameters ) candidate ) ; } } return result ; }
Get Collection of fields that have field specific highlight options .
36,496
protected < T > T convert ( Object source , Class < T > targetType ) { return this . conversionService . convert ( source , targetType ) ; }
Convert given object into target type
36,497
public void add ( T queryParameter ) { Assert . notNull ( queryParameter , "QueryParameter must not be null!" ) ; this . parameters . put ( queryParameter . getName ( ) , queryParameter ) ; }
add a query parameter
36,498
public final FacetOptions addFacetOnField ( Field field ) { Assert . notNull ( field , "Cannot facet on null field." ) ; Assert . hasText ( field . getName ( ) , "Cannot facet on field with null/empty fieldname." ) ; this . facetOnFields . add ( field ) ; return this ; }
Append additional field for faceting
36,499
public final FacetOptions addFacetByRange ( FieldWithRangeParameters < ? , ? , ? > field ) { Assert . notNull ( field , "Cannot range facet on null field." ) ; Assert . hasText ( field . getName ( ) , "Cannot range facet on field with null/empty fieldname." ) ; this . facetRangeOnFields . add ( field ) ; return this ; }
Append additional field for range faceting