idx
int64
0
41.2k
question
stringlengths
73
5.81k
target
stringlengths
5
918
36,200
public DiscriminatorJdbcSubBuilder when ( Predicate < String > predicate , Type type ) { final DiscriminatorJdbcSubBuilder subBuilder = new DiscriminatorJdbcSubBuilder ( predicate , type ) ; builders . add ( subBuilder ) ; return subBuilder ; }
Add a discriminator matching predicate with its associated type .
36,201
public DiscriminatorJdbcSubBuilder when ( String value , Class < ? extends T > type ) { return when ( value , ( Type ) type ) ; }
Add a discriminator value with its associated class .
36,202
public DiscriminatorJdbcSubBuilder when ( String value , TypeReference < ? extends T > type ) { return when ( value , type . getType ( ) ) ; }
Add a discriminator value with its associated type specified by the type reference .
36,203
public JdbcMapperBuilder < T > addMapping ( final String column , final int index , final int sqlType ) { addMapping ( column , index , sqlType , FieldMapperColumnDefinition . < JdbcColumnKey > identity ( ) ) ; return this ; }
add a new mapping to the specified property with the specified index and the specified type .
36,204
private int getNonEmptyParentIndex ( ) { return parent == null ? - 1 : parent . effectiveKeys ( ) . isEmpty ( ) ? parent . getNonEmptyParentIndex ( ) : parent . currentIndex ; }
ignore empty parent useful to skip root keys
36,205
public static int parseInt ( char [ ] s , int beginIndex , int endIndex ) throws NumberFormatException { s = Objects . requireNonNull ( s ) ; if ( beginIndex < 0 || beginIndex > endIndex || endIndex > s . length ) { throw new IndexOutOfBoundsException ( ) ; } if ( radix < Character . MIN_RADIX ) { throw new NumberFormatException ( "radix " + radix + " less than Character.MIN_RADIX" ) ; } if ( radix > Character . MAX_RADIX ) { throw new NumberFormatException ( "radix " + radix + " greater than Character.MAX_RADIX" ) ; } boolean negative = false ; int i = beginIndex ; int limit = - Integer . MAX_VALUE ; if ( i < endIndex ) { char firstChar = s [ i ] ; if ( firstChar < '0' ) { if ( firstChar == '-' ) { negative = true ; limit = Integer . MIN_VALUE ; } else if ( firstChar != '+' ) { throw numberFormatExceptionforCharSequence ( s , beginIndex , endIndex , i ) ; } i ++ ; if ( i == endIndex ) { throw numberFormatExceptionforCharSequence ( s , beginIndex , endIndex , i ) ; } } int multmin = limit / radix ; int result = 0 ; while ( i < endIndex ) { int digit = digit ( s [ i ] ) ; if ( digit < 0 || result < multmin ) { throw numberFormatExceptionforCharSequence ( s , beginIndex , endIndex , i ) ; } result *= radix ; if ( result < limit + digit ) { throw numberFormatExceptionforCharSequence ( s , beginIndex , endIndex , i ) ; } i ++ ; result -= digit ; } return negative ? result : - result ; } else { return 0 ; } }
copy of Integer . parseInt
36,206
public SheetMapperFactory getterFactory ( GetterFactory < Row , CsvColumnKey > getterFactory ) { return super . addGetterFactory ( new ContextualGetterFactoryAdapter < Row , CsvColumnKey > ( getterFactory ) ) ; }
set a new getterFactory .
36,207
public void update ( final Collection < T > values ) throws DataAccessException { jdbcTemplate . execute ( new ConnectionCallback < Object > ( ) { public Object doInConnection ( Connection connection ) throws SQLException , DataAccessException { crud . update ( connection , values ) ; return null ; } } ) ; }
update the objects .
36,208
public void delete ( final K key ) throws DataAccessException { jdbcTemplate . execute ( new ConnectionCallback < Object > ( ) { public Object doInConnection ( Connection connection ) throws SQLException , DataAccessException { crud . delete ( connection , key ) ; return null ; } } ) ; }
delete the object with the specified key .
36,209
private static boolean _areParameterNamePresent ( Type target ) { Class < ? > targetClass = TypeHelper . toClass ( target ) ; for ( Method m : targetClass . getDeclaredMethods ( ) ) { final java . lang . reflect . Parameter [ ] parameters = m . getParameters ( ) ; if ( parameters . length > 0 ) { return parameters [ 0 ] . isNamePresent ( ) ; } } for ( Constructor < ? > c : targetClass . getDeclaredConstructors ( ) ) { final java . lang . reflect . Parameter [ ] parameters = c . getParameters ( ) ; if ( parameters . length > 0 ) { return parameters [ 0 ] . isNamePresent ( ) ; } } return false ; }
assume parameter name are either present or not for the type
36,210
public < T > CsvMapperBuilder < T > newBuilder ( final Class < T > target ) { return newBuilder ( ( Type ) target ) ; }
Will create a newInstance of ResultSetMapperBuilder
36,211
private int _hashCode ( Object values ) { int valueHash = 0 ; if ( values instanceof Object [ ] ) valueHash = Arrays . deepHashCode ( ( Object [ ] ) values ) ; else if ( values instanceof byte [ ] ) valueHash = Arrays . hashCode ( ( byte [ ] ) values ) ; else if ( values instanceof short [ ] ) valueHash = Arrays . hashCode ( ( short [ ] ) values ) ; else if ( values instanceof int [ ] ) valueHash = Arrays . hashCode ( ( int [ ] ) values ) ; else if ( values instanceof long [ ] ) valueHash = Arrays . hashCode ( ( long [ ] ) values ) ; else if ( values instanceof char [ ] ) valueHash = Arrays . hashCode ( ( char [ ] ) values ) ; else if ( values instanceof float [ ] ) valueHash = Arrays . hashCode ( ( float [ ] ) values ) ; else if ( values instanceof double [ ] ) valueHash = Arrays . hashCode ( ( double [ ] ) values ) ; else if ( values instanceof boolean [ ] ) valueHash = Arrays . hashCode ( ( boolean [ ] ) values ) ; else if ( values != null ) valueHash = values . hashCode ( ) ; return valueHash ; }
copy from Array . deepHashCode0
36,212
public Crud < T , K > table ( String table ) { return new LazyCrud < T , K > ( this , table ) ; }
Create a crud against the specified table that will validate on the first interaction with a connection .
36,213
public Crud < T , K > table ( Connection connection , String table ) throws SQLException { CrudMeta crudMeta = CrudMeta . of ( connection , table , jdbcMapperFactory . columnDefinitions ( ) ) ; return CrudFactory . < T , K > newInstance ( target , keyTarget , crudMeta , jdbcMapperFactory ) ; }
Create a crud against the specified table validating it against the specified connection .
36,214
public ConnectedCrud < T , K > table ( DataSource dataSource , String table ) throws SQLException { Connection connection = dataSource . getConnection ( ) ; try { return new ConnectedCrud < T , K > ( new DataSourceTransactionTemplate ( dataSource ) , table ( connection , table ) ) ; } finally { connection . close ( ) ; } }
Create a connected crud against the specified table validating it against the specified datasource .
36,215
public ConnectedCrud < T , K > to ( DataSource dataSource ) throws SQLException { Connection connection = dataSource . getConnection ( ) ; try { return new ConnectedCrud < T , K > ( new DataSourceTransactionTemplate ( dataSource ) , to ( connection ) ) ; } finally { connection . close ( ) ; } }
Create a connected crud validating it against the specified datasource . The table name is derived from the jpa annotation or from the class name .
36,216
public Crud < T , K > to ( Connection connection ) throws SQLException { return table ( connection , getTable ( connection , target ) ) ; }
Create a connected crud validating it against the specified connection . The table name is derived from the jpa annotation or from the class name .
36,217
private void precomputeSlope ( ) { float invDirX = 1.0f / dirX ; float invDirY = 1.0f / dirY ; float invDirZ = 1.0f / dirZ ; s_yx = dirX * invDirY ; s_xy = dirY * invDirX ; s_zy = dirY * invDirZ ; s_yz = dirZ * invDirY ; s_xz = dirZ * invDirX ; s_zx = dirX * invDirZ ; c_xy = originY - s_xy * originX ; c_yx = originX - s_yx * originY ; c_zy = originY - s_zy * originZ ; c_yz = originZ - s_yz * originY ; c_xz = originZ - s_xz * originX ; c_zx = originX - s_zx * originZ ; int sgnX = signum ( dirX ) ; int sgnY = signum ( dirY ) ; int sgnZ = signum ( dirZ ) ; classification = ( byte ) ( ( sgnZ + 1 ) << 4 | ( sgnY + 1 ) << 2 | ( sgnX + 1 ) ) ; }
Precompute the values necessary for the ray slope algorithm .
36,218
public Quaterniond rotationX ( double angle ) { double sin = Math . sin ( angle * 0.5 ) ; double cos = Math . cosFromSin ( sin , angle * 0.5 ) ; w = cos ; x = sin ; y = 0.0 ; z = 0.0 ; return this ; }
Set this quaternion to represent a rotation of the given radians about the x axis .
36,219
public Vector3f div ( Vector3fc v ) { return div ( v . x ( ) , v . y ( ) , v . z ( ) , thisOrNew ( ) ) ; }
Divide this Vector3f component - wise by another Vector3fc .
36,220
public Quaternionf normalize ( ) { float invNorm = ( float ) ( 1.0 / Math . sqrt ( x * x + y * y + z * z + w * w ) ) ; x *= invNorm ; y *= invNorm ; z *= invNorm ; w *= invNorm ; return this ; }
Normalize this quaternion .
36,221
public Matrix3d set ( int column , int row , double value ) { switch ( column ) { case 0 : switch ( row ) { case 0 : this . m00 = value ; return this ; case 1 : this . m01 = value ; return this ; case 2 : this . m02 = value ; return this ; default : break ; } break ; case 1 : switch ( row ) { case 0 : this . m10 = value ; return this ; case 1 : this . m11 = value ; return this ; case 2 : this . m12 = value ; return this ; default : break ; } break ; case 2 : switch ( row ) { case 0 : this . m20 = value ; return this ; case 1 : this . m21 = value ; return this ; case 2 : this . m22 = value ; return this ; default : break ; } break ; default : break ; } throw new IllegalArgumentException ( ) ; }
Set the matrix element at the given column and row to the specified value .
36,222
public AABBd correctBounds ( ) { double tmp ; if ( this . minX > this . maxX ) { tmp = this . minX ; this . minX = this . maxX ; this . maxX = tmp ; } if ( this . minY > this . maxY ) { tmp = this . minY ; this . minY = this . maxY ; this . maxY = tmp ; } if ( this . minZ > this . maxZ ) { tmp = this . minZ ; this . minZ = this . maxZ ; this . maxZ = tmp ; } return this ; }
Ensure that the minimum coordinates are strictly less than or equal to the maximum coordinates by swapping them if necessary .
36,223
public Vector3i add ( Vector3ic v ) { return add ( v . x ( ) , v . y ( ) , v . z ( ) , thisOrNew ( ) ) ; }
Add the supplied vector to this one .
36,224
public Vector3i mul ( int x , int y , int z ) { return mul ( x , y , z , thisOrNew ( ) ) ; }
Multiply the components of this vector by the given values .
36,225
public static double lengthSquared ( double x , double y , double z ) { return x * x + y * y + z * z ; }
Get the length squared of a 3 - dimensional double - precision vector .
36,226
public static double length ( int x , int y , int z , int w ) { return Math . sqrt ( lengthSquared ( x , y , z , w ) ) ; }
Get the length of a 4 - dimensional single - precision vector .
36,227
public void onResume ( final Context context ) { new Handler ( ) . post ( new Runnable ( ) { public void run ( ) { checkLocaleChange ( context ) ; checkAfterLocaleChanging ( ) ; } } ) ; }
If activity is run to back stack . So we have to check if this activity is resume working .
36,228
public final void setLanguage ( Context context , String language ) { Locale locale = new Locale ( language ) ; setLanguage ( context , locale ) ; }
Provide method to set application language by country name .
36,229
private void checkBeforeLocaleChanging ( ) { boolean isLocalizationChanged = activity . getIntent ( ) . getBooleanExtra ( KEY_ACTIVITY_LOCALE_CHANGED , false ) ; if ( isLocalizationChanged ) { this . isLocalizationChanged = true ; activity . getIntent ( ) . removeExtra ( KEY_ACTIVITY_LOCALE_CHANGED ) ; } }
If yes bundle will obe remove and set boolean flag to true .
36,230
private void setupLanguage ( ) { Locale locale = LanguageSetting . getLanguage ( activity ) ; setupLocale ( locale ) ; currentLanguage = locale ; LanguageSetting . setLanguage ( activity , locale ) ; }
This method will called before onCreate .
36,231
private boolean isCurrentLanguageSetting ( Context context , Locale locale ) { return locale . toString ( ) . equals ( LanguageSetting . getLanguage ( context ) . toString ( ) ) ; }
Avoid duplicated setup
36,232
private void notifyLanguageChanged ( ) { sendOnBeforeLocaleChangedEvent ( ) ; activity . getIntent ( ) . putExtra ( KEY_ACTIVITY_LOCALE_CHANGED , true ) ; callDummyActivity ( ) ; activity . recreate ( ) ; }
Let s take it change! ( Using recreate method that available on API 11 or more .
36,233
private void checkLocaleChange ( Context context ) { if ( ! isCurrentLanguageSetting ( context , currentLanguage ) ) { sendOnBeforeLocaleChangedEvent ( ) ; isLocalizationChanged = true ; callDummyActivity ( ) ; activity . recreate ( ) ; } }
Check if locale has change while this activity was run to back stack .
36,234
public List < File > scan ( List < Resource > resources ) { List < File > files = new ArrayList < File > ( ) ; for ( Resource resource : resources ) { files . addAll ( scan ( resource ) ) ; } return files ; }
Scans a list of resources returning all AsciiDoc documents found .
36,235
public List < LogRecord > filter ( Severity severity ) { final List < LogRecord > records = new ArrayList < > ( ) ; for ( LogRecord record : this . records ) { if ( record . getSeverity ( ) . ordinal ( ) >= severity . ordinal ( ) ) records . add ( record ) ; } return records ; }
Returns LogRecords that are equal or above the severity level .
36,236
public List < LogRecord > filter ( String text ) { final List < LogRecord > records = new ArrayList < > ( ) ; for ( LogRecord record : this . records ) { if ( record . getMessage ( ) . contains ( text ) ) records . add ( record ) ; } return records ; }
Returns LogRecords whose message contains text .
36,237
public List < LogRecord > filter ( Severity severity , String text ) { final List < LogRecord > records = new ArrayList < > ( ) ; for ( LogRecord record : this . records ) { if ( record . getSeverity ( ) . ordinal ( ) >= severity . ordinal ( ) && record . getMessage ( ) . contains ( text ) ) records . add ( record ) ; } return records ; }
Returns LogRecords that are equal or above the severity level and whose message contains text .
36,238
public static SwipeBack attach ( Activity activity , Type type , Position position , int dragMode ) { return attach ( activity , type , position , dragMode , new DefaultSwipeBackTransformer ( ) ) ; }
Attaches the SwipeBack to the Activity
36,239
private static SwipeBack createSwipeBack ( Activity activity , int dragMode , Position position , Type type , SwipeBackTransformer transformer ) { SwipeBack drawerHelper ; if ( type == Type . OVERLAY ) { drawerHelper = new OverlaySwipeBack ( activity , dragMode ) ; } else { drawerHelper = new SlidingSwipeBack ( activity , dragMode ) ; } final SwipeBack drawer = drawerHelper ; drawer . mDragMode = dragMode ; drawer . setPosition ( position ) ; drawer . mSwipeBackTransformer = transformer ; drawer . initSwipeListener ( ) ; return drawer ; }
Constructs the appropriate SwipeBack based on the position .
36,240
@ SuppressLint ( "NewApi" ) protected boolean isActivitiyDestroyed ( ) { if ( Build . VERSION . SDK_INT >= Build . VERSION_CODES . JELLY_BEAN_MR1 ) { return mActivity . isFinishing ( ) || mActivity . isDestroyed ( ) ; } else { return mActivity . isFinishing ( ) ; } }
Determines if the activity has been destroyed or finished . This is useful to dertermine if a
36,241
private static void attachToContent ( Activity activity , SwipeBack swipeBack ) { ViewGroup content = ( ViewGroup ) activity . findViewById ( android . R . id . content ) ; content . removeAllViews ( ) ; content . addView ( swipeBack , LayoutParams . MATCH_PARENT , LayoutParams . MATCH_PARENT ) ; }
Attaches the swipe back to the content view .
36,242
private static void attachToDecor ( Activity activity , SwipeBack swipeBack ) { ViewGroup decorView = ( ViewGroup ) activity . getWindow ( ) . getDecorView ( ) ; ViewGroup decorChild = ( ViewGroup ) decorView . getChildAt ( 0 ) ; decorView . removeAllViews ( ) ; decorView . addView ( swipeBack , LayoutParams . MATCH_PARENT , LayoutParams . MATCH_PARENT ) ; swipeBack . mContentContainer . addView ( decorChild , decorChild . getLayoutParams ( ) ) ; }
Attaches the swipe back drawer to the window .
36,243
protected void updateTouchAreaSize ( ) { if ( mTouchMode == TOUCH_MODE_BEZEL ) { mTouchSize = mTouchBezelSize ; } else if ( mTouchMode == TOUCH_MODE_FULLSCREEN ) { mTouchSize = getMeasuredWidth ( ) ; } else { mTouchSize = 0 ; } }
Compute the touch area based on the touch mode .
36,244
public SwipeBack setDividerAsShadowColor ( int color ) { GradientDrawable . Orientation orientation = getDividerOrientation ( ) ; final int endColor = color & 0x00FFFFFF ; GradientDrawable gradient = new GradientDrawable ( orientation , new int [ ] { color , endColor , } ) ; setDivider ( gradient ) ; return this ; }
Sets the color of the divider if you have set the option to use a shadow gradient as divider
36,245
public SwipeBack setSwipeBackView ( int layoutResId ) { mSwipeBackContainer . removeAllViews ( ) ; mSwipeBackView = LayoutInflater . from ( getContext ( ) ) . inflate ( layoutResId , mSwipeBackContainer , false ) ; mSwipeBackContainer . addView ( mSwipeBackView ) ; notifySwipeBackViewCreated ( mSwipeBackView ) ; return this ; }
Set the swipe back view from a layout resource .
36,246
private void completeAnimation ( ) { mScroller . abortAnimation ( ) ; final int finalX = mScroller . getFinalX ( ) ; setOffsetPixels ( finalX ) ; setDrawerState ( finalX == 0 ? STATE_CLOSED : STATE_OPEN ) ; stopLayerTranslation ( ) ; }
Called when a drawer animation has successfully completed .
36,247
@ SuppressLint ( "NewApi" ) private void postAnimationInvalidate ( ) { if ( mScroller . computeScrollOffset ( ) ) { final int oldX = ( int ) mOffsetPixels ; final int x = mScroller . getCurrX ( ) ; if ( x != oldX ) { setOffsetPixels ( x ) ; } if ( x != mScroller . getFinalX ( ) ) { postOnAnimation ( mDragRunnable ) ; return ; } } completeAnimation ( ) ; }
Callback when each frame in the drawer animation should be drawn .
36,248
@ SuppressLint ( "NewApi" ) private void peekDrawerInvalidate ( ) { if ( mPeekScroller . computeScrollOffset ( ) ) { final int oldX = ( int ) mOffsetPixels ; final int x = mPeekScroller . getCurrX ( ) ; if ( x != oldX ) { setOffsetPixels ( x ) ; } if ( ! mPeekScroller . isFinished ( ) ) { postOnAnimation ( mPeekRunnable ) ; return ; } else if ( mPeekDelay > 0 ) { mPeekStartRunnable = new Runnable ( ) { public void run ( ) { startPeek ( ) ; } } ; postDelayed ( mPeekStartRunnable , mPeekDelay ) ; } } completePeek ( ) ; }
Callback when each frame in the peek drawer animation should be drawn .
36,249
public boolean computeScrollOffset ( ) { if ( mFinished ) { return false ; } int timePassed = ( int ) ( AnimationUtils . currentAnimationTimeMillis ( ) - mStartTime ) ; if ( timePassed < mDuration ) { switch ( mMode ) { case SCROLL_MODE : float x = timePassed * mDurationReciprocal ; if ( mInterpolator == null ) x = viscousFluid ( x ) ; else x = mInterpolator . getInterpolation ( x ) ; mCurrX = mStartX + Math . round ( x * mDeltaX ) ; mCurrY = mStartY + Math . round ( x * mDeltaY ) ; break ; case FLING_MODE : final float t = ( float ) timePassed / mDuration ; final int index = ( int ) ( NB_SAMPLES * t ) ; final float tInf = ( float ) index / NB_SAMPLES ; final float tSup = ( float ) ( index + 1 ) / NB_SAMPLES ; final float dInf = SPLINE [ index ] ; final float dSup = SPLINE [ index + 1 ] ; final float distanceCoef = dInf + ( t - tInf ) / ( tSup - tInf ) * ( dSup - dInf ) ; mCurrX = mStartX + Math . round ( distanceCoef * ( mFinalX - mStartX ) ) ; mCurrX = Math . min ( mCurrX , mMaxX ) ; mCurrX = Math . max ( mCurrX , mMinX ) ; mCurrY = mStartY + Math . round ( distanceCoef * ( mFinalY - mStartY ) ) ; mCurrY = Math . min ( mCurrY , mMaxY ) ; mCurrY = Math . max ( mCurrY , mMinY ) ; if ( mCurrX == mFinalX && mCurrY == mFinalY ) { mFinished = true ; } break ; } } else { mCurrX = mFinalX ; mCurrY = mFinalY ; mFinished = true ; } return true ; }
Call this when you want to know the new location . If it returns true the animation is not yet finished . loc will be altered to provide the new location .
36,250
public void startScroll ( int startX , int startY , int dx , int dy ) { startScroll ( startX , startY , dx , dy , DEFAULT_DURATION ) ; }
Start scrolling by providing a starting point and the distance to travel . The scroll will use the default value of 250 milliseconds for the duration .
36,251
private Object marshallParameterAsPrimitive ( Object parameter ) { Map < String , Object > primitiveWrapper = Collections . singletonMap ( "wrapped" , parameter ) ; BsonDocument document = marshaller . marshall ( primitiveWrapper ) ; return document . toDBObject ( ) . get ( "wrapped" ) ; }
The object may have been serialized to a primitive type with a custom serializer so try again after wrapping as an object property . We do this trick only as a falllback since it causes Jackson to consider the parameter as Object and thus ignore any annotations that may exist on its actual class .
36,252
public static AmazonDynamoDB getClient ( ) { if ( ddbClient != null ) { return ddbClient ; } if ( Config . IN_PRODUCTION ) { ddbClient = AmazonDynamoDBClientBuilder . standard ( ) . build ( ) ; } else { ddbClient = AmazonDynamoDBClientBuilder . standard ( ) . withCredentials ( new AWSStaticCredentialsProvider ( new BasicAWSCredentials ( "local" , "null" ) ) ) . withEndpointConfiguration ( new EndpointConfiguration ( LOCAL_ENDPOINT , "" ) ) . build ( ) ; } if ( ! existsTable ( Config . getRootAppIdentifier ( ) ) ) { createTable ( Config . getRootAppIdentifier ( ) ) ; } ddb = new DynamoDB ( ddbClient ) ; Para . addDestroyListener ( new DestroyListener ( ) { public void onDestroy ( ) { shutdownClient ( ) ; } } ) ; return ddbClient ; }
Returns a client instance for AWS DynamoDB .
36,253
public static boolean existsTable ( String appid ) { if ( StringUtils . isBlank ( appid ) ) { return false ; } try { DescribeTableResult res = getClient ( ) . describeTable ( getTableNameForAppid ( appid ) ) ; return res != null ; } catch ( Exception e ) { return false ; } }
Checks if the main table exists in the database .
36,254
public static boolean createTable ( String appid , long readCapacity , long writeCapacity ) { if ( StringUtils . isBlank ( appid ) ) { return false ; } else if ( StringUtils . containsWhitespace ( appid ) ) { logger . warn ( "DynamoDB table name contains whitespace. The name '{}' is invalid." , appid ) ; return false ; } else if ( existsTable ( appid ) ) { logger . warn ( "DynamoDB table '{}' already exists." , appid ) ; return false ; } try { String table = getTableNameForAppid ( appid ) ; getClient ( ) . createTable ( new CreateTableRequest ( ) . withTableName ( table ) . withKeySchema ( new KeySchemaElement ( Config . _KEY , KeyType . HASH ) ) . withSSESpecification ( new SSESpecification ( ) . withEnabled ( ENCRYPTION_AT_REST_ENABLED ) ) . withAttributeDefinitions ( new AttributeDefinition ( Config . _KEY , ScalarAttributeType . S ) ) . withProvisionedThroughput ( new ProvisionedThroughput ( readCapacity , writeCapacity ) ) ) ; logger . info ( "Created DynamoDB table '{}'." , table ) ; } catch ( Exception e ) { logger . error ( null , e ) ; return false ; } return true ; }
Creates a table in AWS DynamoDB .
36,255
public static boolean deleteTable ( String appid ) { if ( StringUtils . isBlank ( appid ) || ! existsTable ( appid ) ) { return false ; } try { String table = getTableNameForAppid ( appid ) ; getClient ( ) . deleteTable ( new DeleteTableRequest ( ) . withTableName ( table ) ) ; logger . info ( "Deleted DynamoDB table '{}'." , table ) ; } catch ( Exception e ) { logger . error ( null , e ) ; return false ; } return true ; }
Deletes the main table from AWS DynamoDB .
36,256
public static boolean createSharedTable ( long readCapacity , long writeCapacity ) { if ( StringUtils . isBlank ( SHARED_TABLE ) || StringUtils . containsWhitespace ( SHARED_TABLE ) || existsTable ( SHARED_TABLE ) ) { return false ; } try { GlobalSecondaryIndex secIndex = new GlobalSecondaryIndex ( ) . withIndexName ( getSharedIndexName ( ) ) . withProvisionedThroughput ( new ProvisionedThroughput ( ) . withReadCapacityUnits ( 1L ) . withWriteCapacityUnits ( 1L ) ) . withProjection ( new Projection ( ) . withProjectionType ( ProjectionType . ALL ) ) . withKeySchema ( new KeySchemaElement ( ) . withAttributeName ( Config . _APPID ) . withKeyType ( KeyType . HASH ) , new KeySchemaElement ( ) . withAttributeName ( Config . _ID ) . withKeyType ( KeyType . RANGE ) ) ; getClient ( ) . createTable ( new CreateTableRequest ( ) . withTableName ( getTableNameForAppid ( SHARED_TABLE ) ) . withKeySchema ( new KeySchemaElement ( Config . _KEY , KeyType . HASH ) ) . withSSESpecification ( new SSESpecification ( ) . withEnabled ( ENCRYPTION_AT_REST_ENABLED ) ) . withAttributeDefinitions ( new AttributeDefinition ( Config . _KEY , ScalarAttributeType . S ) , new AttributeDefinition ( Config . _APPID , ScalarAttributeType . S ) , new AttributeDefinition ( Config . _ID , ScalarAttributeType . S ) ) . withGlobalSecondaryIndexes ( secIndex ) . withProvisionedThroughput ( new ProvisionedThroughput ( readCapacity , writeCapacity ) ) ) ; } catch ( Exception e ) { logger . error ( null , e ) ; return false ; } return true ; }
Creates a table in AWS DynamoDB which will be shared between apps .
36,257
public static List < String > listAllTables ( ) { int items = 100 ; ListTablesResult ltr = getClient ( ) . listTables ( items ) ; List < String > tables = new LinkedList < > ( ) ; String lastKey ; do { tables . addAll ( ltr . getTableNames ( ) ) ; lastKey = ltr . getLastEvaluatedTableName ( ) ; logger . info ( "Found {} tables. Total found: {}." , ltr . getTableNames ( ) . size ( ) , tables . size ( ) ) ; if ( lastKey == null ) { break ; } ltr = getClient ( ) . listTables ( lastKey , items ) ; } while ( ! ltr . getTableNames ( ) . isEmpty ( ) ) ; return tables ; }
Lists all table names for this account .
36,258
public static String getTableNameForAppid ( String appIdentifier ) { if ( StringUtils . isBlank ( appIdentifier ) ) { return null ; } else { if ( isSharedAppid ( appIdentifier ) ) { appIdentifier = SHARED_TABLE ; } return ( App . isRoot ( appIdentifier ) || appIdentifier . startsWith ( Config . PARA . concat ( "-" ) ) ) ? appIdentifier : Config . PARA + "-" + appIdentifier ; } }
Returns the table name for a given app id . Table names are usually in the form prefix - appid .
36,259
protected static < P extends ParaObject > void batchGet ( Map < String , KeysAndAttributes > kna , Map < String , P > results ) { if ( kna == null || kna . isEmpty ( ) || results == null ) { return ; } try { BatchGetItemResult result = getClient ( ) . batchGetItem ( new BatchGetItemRequest ( ) . withReturnConsumedCapacity ( ReturnConsumedCapacity . TOTAL ) . withRequestItems ( kna ) ) ; if ( result == null ) { return ; } List < Map < String , AttributeValue > > res = result . getResponses ( ) . get ( kna . keySet ( ) . iterator ( ) . next ( ) ) ; for ( Map < String , AttributeValue > item : res ) { P obj = fromRow ( item ) ; if ( obj != null ) { results . put ( obj . getId ( ) , obj ) ; } } logger . debug ( "batchGet(): total {}, cc {}" , res . size ( ) , result . getConsumedCapacity ( ) ) ; if ( result . getUnprocessedKeys ( ) != null && ! result . getUnprocessedKeys ( ) . isEmpty ( ) ) { Thread . sleep ( 1000 ) ; logger . warn ( "{} UNPROCESSED read requests!" , result . getUnprocessedKeys ( ) . size ( ) ) ; batchGet ( result . getUnprocessedKeys ( ) , results ) ; } } catch ( Exception e ) { logger . error ( null , e ) ; } }
Reads multiple items from DynamoDB in batch .
36,260
protected static void batchWrite ( Map < String , List < WriteRequest > > items , int backoff ) { if ( items == null || items . isEmpty ( ) ) { return ; } try { BatchWriteItemResult result = getClient ( ) . batchWriteItem ( new BatchWriteItemRequest ( ) . withReturnConsumedCapacity ( ReturnConsumedCapacity . TOTAL ) . withRequestItems ( items ) ) ; if ( result == null ) { return ; } logger . debug ( "batchWrite(): total {}, cc {}" , items . size ( ) , result . getConsumedCapacity ( ) ) ; if ( result . getUnprocessedItems ( ) != null && ! result . getUnprocessedItems ( ) . isEmpty ( ) ) { Thread . sleep ( ( long ) backoff * 1000L ) ; logger . warn ( "{} UNPROCESSED write requests!" , result . getUnprocessedItems ( ) . size ( ) ) ; batchWrite ( result . getUnprocessedItems ( ) , backoff * 2 ) ; } } catch ( Exception e ) { logger . error ( null , e ) ; throwIfNecessary ( e ) ; } }
Writes multiple items in batch .
36,261
public static < P extends ParaObject > List < P > readPageFromTable ( String appid , Pager p ) { Pager pager = ( p != null ) ? p : new Pager ( ) ; ScanRequest scanRequest = new ScanRequest ( ) . withTableName ( getTableNameForAppid ( appid ) ) . withLimit ( pager . getLimit ( ) ) . withReturnConsumedCapacity ( ReturnConsumedCapacity . TOTAL ) ; if ( ! StringUtils . isBlank ( pager . getLastKey ( ) ) ) { scanRequest = scanRequest . withExclusiveStartKey ( Collections . singletonMap ( Config . _KEY , new AttributeValue ( pager . getLastKey ( ) ) ) ) ; } ScanResult result = getClient ( ) . scan ( scanRequest ) ; LinkedList < P > results = new LinkedList < > ( ) ; for ( Map < String , AttributeValue > item : result . getItems ( ) ) { P obj = fromRow ( item ) ; if ( obj != null ) { results . add ( obj ) ; } } if ( result . getLastEvaluatedKey ( ) != null ) { pager . setLastKey ( result . getLastEvaluatedKey ( ) . get ( Config . _KEY ) . getS ( ) ) ; } else if ( ! results . isEmpty ( ) ) { pager . setLastKey ( results . peekLast ( ) . getId ( ) ) ; } return results ; }
Reads a page from a standard DynamoDB table .
36,262
public static < P extends ParaObject > List < P > readPageFromSharedTable ( String appid , Pager pager ) { LinkedList < P > results = new LinkedList < > ( ) ; if ( StringUtils . isBlank ( appid ) ) { return results ; } PageIterable < Item , QueryOutcome > pages = queryGSI ( appid , pager ) ; if ( pages != null ) { for ( Page < Item , QueryOutcome > page : pages ) { for ( Item item : page ) { P obj = ParaObjectUtils . setAnnotatedFields ( item . asMap ( ) ) ; if ( obj != null ) { results . add ( obj ) ; } } } } if ( ! results . isEmpty ( ) && pager != null ) { pager . setLastKey ( results . peekLast ( ) . getId ( ) ) ; } return results ; }
Reads a page from a shared DynamoDB table . Shared tables are tables that have global secondary indexes and can contain the objects of multiple apps .
36,263
public static void deleteAllFromSharedTable ( String appid ) { if ( StringUtils . isBlank ( appid ) || ! isSharedAppid ( appid ) ) { return ; } Pager pager = new Pager ( 25 ) ; PageIterable < Item , QueryOutcome > pages ; Map < String , AttributeValue > lastKey = null ; do { pages = queryGSI ( appid , pager ) ; if ( pages == null ) { break ; } List < WriteRequest > deletePage = new LinkedList < > ( ) ; for ( Page < Item , QueryOutcome > page : pages ) { for ( Item item : page ) { String key = item . getString ( Config . _KEY ) ; if ( StringUtils . startsWith ( key , appid . trim ( ) ) ) { logger . debug ( "Preparing to delete '{}' from shared table, appid: '{}'." , key , appid ) ; pager . setLastKey ( item . getString ( Config . _ID ) ) ; deletePage . add ( new WriteRequest ( ) . withDeleteRequest ( new DeleteRequest ( ) . withKey ( Collections . singletonMap ( Config . _KEY , new AttributeValue ( key ) ) ) ) ) ; } } lastKey = page . getLowLevelResult ( ) . getQueryResult ( ) . getLastEvaluatedKey ( ) ; } logger . info ( "Deleting {} items belonging to app '{}', from shared table..." , deletePage . size ( ) , appid ) ; if ( ! deletePage . isEmpty ( ) ) { batchWrite ( Collections . singletonMap ( getTableNameForAppid ( appid ) , deletePage ) , 1 ) ; } } while ( lastKey != null && ! lastKey . isEmpty ( ) ) ; }
Deletes all objects in a shared table which belong to a given appid by scanning the GSI .
36,264
public static Index getSharedIndex ( ) { if ( ddb == null ) { getClient ( ) ; } try { Table t = ddb . getTable ( getTableNameForAppid ( SHARED_TABLE ) ) ; if ( t != null ) { return t . getIndex ( getSharedIndexName ( ) ) ; } } catch ( Exception e ) { logger . info ( "Could not get shared index: {}." , e . getMessage ( ) ) ; } return null ; }
Returns the Index object for the shared table .
36,265
public void setCurrency ( String currency ) { currency = StringUtils . upperCase ( currency ) ; if ( ! CurrencyUtils . getInstance ( ) . isValidCurrency ( currency ) ) { currency = "EUR" ; } this . currency = currency ; }
Sets a preferred currency . Default is EUR .
36,266
public void detachIdentifier ( String identifier ) { if ( ! StringUtils . equals ( identifier , getIdentifier ( ) ) ) { Sysprop s = CoreUtils . getInstance ( ) . getDao ( ) . read ( getAppid ( ) , identifier ) ; if ( s != null && StringUtils . equals ( getId ( ) , s . getCreatorid ( ) ) ) { deleteIdentifier ( identifier ) ; } } }
Detaches a secondary identifier which is not already used by this user .
36,267
public boolean isModerator ( ) { return isAdmin ( ) ? true : StringUtils . equalsIgnoreCase ( this . groups , Groups . MODS . toString ( ) ) ; }
Checks for moderator rights .
36,268
public String getIdentityProvider ( ) { if ( isFacebookUser ( ) ) { return "facebook" ; } else if ( isGooglePlusUser ( ) ) { return "google" ; } else if ( isGitHubUser ( ) ) { return "github" ; } else if ( isTwitterUser ( ) ) { return "twitter" ; } else if ( isLinkedInUser ( ) ) { return "linkedin" ; } else if ( isMicrosoftUser ( ) ) { return "microsoft" ; } else if ( isLDAPUser ( ) ) { return "ldap" ; } else if ( isSAMLUser ( ) ) { return "saml" ; } else { return "generic" ; } }
Returns the name of the identity provider .
36,269
public static final User readUserForIdentifier ( final User u ) { if ( u == null || StringUtils . isBlank ( u . getIdentifier ( ) ) ) { return null ; } User user = null ; String password = null ; String identifier = u . getIdentifier ( ) ; Sysprop s = CoreUtils . getInstance ( ) . getDao ( ) . read ( u . getAppid ( ) , identifier ) ; if ( s != null && s . getCreatorid ( ) != null ) { user = CoreUtils . getInstance ( ) . getDao ( ) . read ( u . getAppid ( ) , s . getCreatorid ( ) ) ; password = ( String ) s . getProperty ( Config . _PASSWORD ) ; } if ( user == null && ! StringUtils . isBlank ( u . getEmail ( ) ) ) { HashMap < String , Object > terms = new HashMap < > ( 2 ) ; terms . put ( Config . _EMAIL , u . getEmail ( ) ) ; terms . put ( Config . _APPID , u . getAppid ( ) ) ; List < User > users = CoreUtils . getInstance ( ) . getSearch ( ) . findTerms ( u . getAppid ( ) , u . getType ( ) , terms , true , new Pager ( 1 ) ) ; if ( ! users . isEmpty ( ) ) { user = users . get ( 0 ) ; password = Utils . generateSecurityToken ( ) ; user . createIdentifier ( u . getIdentifier ( ) , password ) ; } } if ( user != null ) { if ( password != null ) { user . setPassword ( password ) ; } if ( ! identifier . equals ( user . getIdentifier ( ) ) ) { logger . info ( "Identifier changed for user '{}', from {} to {}." , user . getId ( ) , user . getIdentifier ( ) , identifier ) ; user . setIdentifier ( identifier ) ; CoreUtils . getInstance ( ) . getDao ( ) . update ( user . getAppid ( ) , user ) ; } return user ; } logger . debug ( "User not found for identifier {}/{}, {}." , u . getAppid ( ) , identifier , u . getId ( ) ) ; return null ; }
Returns a user object for a given identifier .
36,270
public static final boolean passwordMatches ( User u ) { if ( u == null ) { return false ; } String password = u . getPassword ( ) ; String identifier = u . getIdentifier ( ) ; if ( StringUtils . isBlank ( password ) || StringUtils . isBlank ( identifier ) ) { return false ; } ParaObject s = CoreUtils . getInstance ( ) . getDao ( ) . read ( u . getAppid ( ) , identifier ) ; if ( s != null ) { if ( s instanceof Sysprop ) { String storedHash = ( String ) ( ( Sysprop ) s ) . getProperty ( Config . _PASSWORD ) ; return Utils . bcryptMatches ( password , storedHash ) ; } else { LoggerFactory . getLogger ( User . class ) . warn ( Utils . formatMessage ( "Failed to read auth object for user '{}' using identifier '{}'." , u . getId ( ) , identifier ) ) ; } } return false ; }
Checks if a user has entered the correct password . Compares password hashes .
36,271
public final String generatePasswordResetToken ( ) { if ( StringUtils . isBlank ( identifier ) ) { return "" ; } Sysprop s = CoreUtils . getInstance ( ) . getDao ( ) . read ( getAppid ( ) , identifier ) ; if ( s != null ) { String token = Utils . generateSecurityToken ( 42 , true ) ; s . addProperty ( Config . _RESET_TOKEN , token ) ; CoreUtils . getInstance ( ) . getDao ( ) . update ( getAppid ( ) , s ) ; return token ; } return "" ; }
Generates a new password reset token . Sent via email for pass reset .
36,272
public final boolean resetPassword ( String token , String newpass ) { if ( StringUtils . isBlank ( newpass ) || StringUtils . isBlank ( token ) || newpass . length ( ) < Config . MIN_PASS_LENGTH ) { return false ; } Sysprop s = CoreUtils . getInstance ( ) . getDao ( ) . read ( getAppid ( ) , identifier ) ; if ( isValidToken ( s , Config . _RESET_TOKEN , token ) ) { s . removeProperty ( Config . _RESET_TOKEN ) ; String hashed = Utils . bcrypt ( newpass ) ; s . addProperty ( Config . _PASSWORD , hashed ) ; setPassword ( hashed ) ; CoreUtils . getInstance ( ) . getDao ( ) . update ( getAppid ( ) , s ) ; return true ; } return false ; }
Changes the user password permanently .
36,273
private void deleteIdentifier ( String ident ) { if ( ! StringUtils . isBlank ( ident ) ) { CoreUtils . getInstance ( ) . getDao ( ) . delete ( getAppid ( ) , new Sysprop ( ident ) ) ; } }
Deletes the identifier and the user can no longer sign in with it .
36,274
public String generateEmailConfirmationToken ( ) { if ( StringUtils . isBlank ( identifier ) ) { return "" ; } Sysprop s = CoreUtils . getInstance ( ) . getDao ( ) . read ( getAppid ( ) , identifier ) ; if ( s != null ) { String token = Utils . base64encURL ( Utils . generateSecurityToken ( ) . getBytes ( ) ) ; s . addProperty ( Config . _EMAIL_TOKEN , token ) ; CoreUtils . getInstance ( ) . getDao ( ) . update ( getAppid ( ) , s ) ; return token ; } return "" ; }
Generates a new email confirmation token . Sent via email for user activation .
36,275
public final boolean activateWithEmailToken ( String token ) { Sysprop s = CoreUtils . getInstance ( ) . getDao ( ) . read ( getAppid ( ) , identifier ) ; if ( isValidToken ( s , Config . _EMAIL_TOKEN , token ) ) { s . removeProperty ( Config . _EMAIL_TOKEN ) ; CoreUtils . getInstance ( ) . getDao ( ) . update ( getAppid ( ) , s ) ; setActive ( true ) ; update ( ) ; return true ; } return false ; }
Activates a user if a given token matches the one stored .
36,276
public final boolean isValidPasswordResetToken ( String token ) { Sysprop s = CoreUtils . getInstance ( ) . getDao ( ) . read ( getAppid ( ) , identifier ) ; return isValidToken ( s , Config . _RESET_TOKEN , token ) ; }
Validates a token sent via email for password reset .
36,277
public final boolean isValidEmailConfirmationToken ( String token ) { Sysprop s = CoreUtils . getInstance ( ) . getDao ( ) . read ( getAppid ( ) , identifier ) ; return isValidToken ( s , Config . _EMAIL_TOKEN , token ) ; }
Validates a token sent for email confirmation .
36,278
private void setGravatarPicture ( ) { if ( StringUtils . isBlank ( picture ) ) { if ( email != null ) { String emailHash = Utils . md5 ( email . toLowerCase ( ) ) ; setPicture ( "https://www.gravatar.com/avatar/" + emailHash + "?size=400&d=mm&r=pg" ) ; } else { setPicture ( "https://www.gravatar.com/avatar?d=mm&size=400" ) ; } } }
Sets the profile picture using the Gravatar service .
36,279
public static String extractAccessKey ( HttpServletRequest request ) { if ( request == null ) { return "" ; } String accessKey = "" ; String auth = request . getHeader ( HttpHeaders . AUTHORIZATION ) ; boolean isAnonymousRequest = isAnonymousRequest ( request ) ; if ( StringUtils . isBlank ( auth ) ) { auth = request . getParameter ( "X-Amz-Credential" ) ; if ( ! StringUtils . isBlank ( auth ) ) { accessKey = StringUtils . substringBetween ( auth , "=" , "/" ) ; } } else { if ( isAnonymousRequest ) { accessKey = StringUtils . substringAfter ( auth , "Anonymous" ) . trim ( ) ; } else { accessKey = StringUtils . substringBetween ( auth , "=" , "/" ) ; } } if ( isAnonymousRequest && StringUtils . isBlank ( accessKey ) ) { accessKey = request . getParameter ( "accessKey" ) ; } return accessKey ; }
Extracts the access key from a request . It can be a header or a parameter .
36,280
public static boolean isAnonymousRequest ( HttpServletRequest request ) { return request != null && ( StringUtils . startsWith ( request . getHeader ( HttpHeaders . AUTHORIZATION ) , "Anonymous" ) || StringUtils . isBlank ( request . getHeader ( HttpHeaders . AUTHORIZATION ) ) ) ; }
Check if Authorization header starts with Anonymous . Used for guest access .
36,281
public static String extractDate ( HttpServletRequest request ) { if ( request == null ) { return "" ; } String date = request . getHeader ( "X-Amz-Date" ) ; if ( StringUtils . isBlank ( date ) ) { return request . getParameter ( "X-Amz-Date" ) ; } else { return date ; } }
Extracts the date field from a request . It can be a header or a parameter .
36,282
public static Response getEntity ( InputStream is , Class < ? > type ) { Object entity ; try { if ( is != null && is . available ( ) > 0 ) { if ( is . available ( ) > Config . MAX_ENTITY_SIZE_BYTES ) { return getStatusResponse ( Response . Status . BAD_REQUEST , "Request is too large - the maximum is " + ( Config . MAX_ENTITY_SIZE_BYTES / 1024 ) + " KB." ) ; } if ( type == null ) { entity = is ; } else { entity = ParaObjectUtils . getJsonReader ( type ) . readValue ( is ) ; } } else { return getStatusResponse ( Response . Status . BAD_REQUEST , "Missing request body." ) ; } } catch ( JsonMappingException e ) { return getStatusResponse ( Response . Status . BAD_REQUEST , e . getMessage ( ) ) ; } catch ( JsonParseException e ) { return getStatusResponse ( Response . Status . BAD_REQUEST , e . getMessage ( ) ) ; } catch ( IOException e ) { logger . error ( null , e ) ; return getStatusResponse ( Response . Status . INTERNAL_SERVER_ERROR , e . toString ( ) ) ; } return Response . ok ( entity ) . build ( ) ; }
Returns a Response with the entity object inside it and 200 status code . If there was and error the status code is different than 200 .
36,283
public static byte [ ] readEntityBytes ( InputStream in ) { byte [ ] jsonEntity = null ; try { if ( in != null && in . available ( ) > 0 ) { ByteArrayOutputStream baos = new ByteArrayOutputStream ( ) ; byte [ ] buf = new byte [ 1024 ] ; int length ; while ( ( length = in . read ( buf ) ) > 0 ) { baos . write ( buf , 0 , length ) ; } jsonEntity = baos . toByteArray ( ) ; } else { jsonEntity = new byte [ 0 ] ; } } catch ( IOException ex ) { logger . error ( null , ex ) ; } finally { try { if ( in != null ) { in . close ( ) ; } } catch ( IOException ex ) { logger . error ( null , ex ) ; } } return jsonEntity ; }
Reads the bytes from an InputStream .
36,284
public static Response getVotingResponse ( ParaObject object , Map < String , Object > entity ) { boolean voteSuccess = false ; if ( object != null && entity != null ) { String upvoterId = ( String ) entity . get ( "_voteup" ) ; String downvoterId = ( String ) entity . get ( "_votedown" ) ; if ( ! StringUtils . isBlank ( upvoterId ) ) { voteSuccess = object . voteUp ( upvoterId ) ; } else if ( ! StringUtils . isBlank ( downvoterId ) ) { voteSuccess = object . voteDown ( downvoterId ) ; } if ( voteSuccess ) { object . update ( ) ; } } return Response . ok ( voteSuccess ) . build ( ) ; }
Process voting request and create vote object .
36,285
public static Response getReadResponse ( App app , ParaObject content ) { try ( final Metrics . Context context = Metrics . time ( app == null ? null : app . getAppid ( ) , RestUtils . class , "crud" , "read" ) ) { if ( app != null && content != null && checkImplicitAppPermissions ( app , content ) && checkIfUserCanModifyObject ( app , content ) ) { return Response . ok ( content ) . build ( ) ; } return getStatusResponse ( Response . Status . NOT_FOUND ) ; } }
Read response as JSON .
36,286
public static Response getCreateResponse ( App app , String type , InputStream is ) { try ( final Metrics . Context context = Metrics . time ( app == null ? null : app . getAppid ( ) , RestUtils . class , "crud" , "create" ) ) { ParaObject content ; Response entityRes = getEntity ( is , Map . class ) ; if ( entityRes . getStatusInfo ( ) == Response . Status . OK ) { Map < String , Object > newContent = ( Map < String , Object > ) entityRes . getEntity ( ) ; String declaredType = ( String ) newContent . get ( Config . _TYPE ) ; if ( ! StringUtils . isBlank ( type ) && ( StringUtils . isBlank ( declaredType ) || ! type . startsWith ( declaredType ) ) ) { newContent . put ( Config . _TYPE , type ) ; } content = ParaObjectUtils . setAnnotatedFields ( newContent ) ; if ( app != null && content != null && isNotAnApp ( type ) ) { warnIfUserTypeDetected ( type ) ; content . setAppid ( app . getAppIdentifier ( ) ) ; setCreatorid ( app , content ) ; int typesCount = app . getDatatypes ( ) . size ( ) ; app . addDatatypes ( content ) ; String [ ] errors = validateObject ( app , content ) ; if ( errors . length == 0 ) { String id = content . create ( ) ; if ( id != null ) { if ( typesCount < app . getDatatypes ( ) . size ( ) ) { app . update ( ) ; } return Response . created ( URI . create ( Utils . urlEncode ( content . getObjectURI ( ) ) ) ) . entity ( content ) . build ( ) ; } } return getStatusResponse ( Response . Status . BAD_REQUEST , errors ) ; } return getStatusResponse ( Response . Status . BAD_REQUEST , "Failed to create object." ) ; } return entityRes ; } }
Create response as JSON .
36,287
public static Response getOverwriteResponse ( App app , String id , String type , InputStream is ) { try ( final Metrics . Context context = Metrics . time ( app == null ? null : app . getAppid ( ) , RestUtils . class , "crud" , "overwrite" ) ) { ParaObject content ; Response entityRes = getEntity ( is , Map . class ) ; if ( entityRes . getStatusInfo ( ) == Response . Status . OK ) { Map < String , Object > newContent = ( Map < String , Object > ) entityRes . getEntity ( ) ; if ( ! StringUtils . isBlank ( type ) ) { newContent . put ( Config . _TYPE , type ) ; } content = ParaObjectUtils . setAnnotatedFields ( newContent ) ; if ( app != null && content != null && ! StringUtils . isBlank ( id ) && isNotAnApp ( type ) ) { warnIfUserTypeDetected ( type ) ; content . setType ( type ) ; content . setAppid ( app . getAppIdentifier ( ) ) ; content . setId ( id ) ; setCreatorid ( app , content ) ; int typesCount = app . getDatatypes ( ) . size ( ) ; app . addDatatypes ( content ) ; String [ ] errors = validateObject ( app , content ) ; if ( errors . length == 0 && checkIfUserCanModifyObject ( app , content ) ) { CoreUtils . getInstance ( ) . overwrite ( app . getAppIdentifier ( ) , content ) ; if ( typesCount < app . getDatatypes ( ) . size ( ) ) { app . update ( ) ; } return Response . ok ( content ) . build ( ) ; } return getStatusResponse ( Response . Status . BAD_REQUEST , errors ) ; } return getStatusResponse ( Response . Status . BAD_REQUEST , "Failed to overwrite object." ) ; } return entityRes ; } }
Overwrite response as JSON .
36,288
public static Response getUpdateResponse ( App app , ParaObject object , InputStream is ) { try ( final Metrics . Context context = Metrics . time ( app == null ? null : app . getAppid ( ) , RestUtils . class , "crud" , "update" ) ) { if ( app != null && object != null ) { Map < String , Object > newContent ; Response entityRes = getEntity ( is , Map . class ) ; String [ ] errors = { } ; if ( entityRes . getStatusInfo ( ) == Response . Status . OK ) { newContent = ( Map < String , Object > ) entityRes . getEntity ( ) ; } else { return entityRes ; } object . setAppid ( isNotAnApp ( object . getType ( ) ) ? app . getAppIdentifier ( ) : app . getAppid ( ) ) ; if ( newContent . containsKey ( "_voteup" ) || newContent . containsKey ( "_votedown" ) ) { return getVotingResponse ( object , newContent ) ; } else { ParaObjectUtils . setAnnotatedFields ( object , newContent , Locked . class ) ; if ( checkImplicitAppPermissions ( app , object ) ) { errors = validateObject ( app , object ) ; if ( errors . length == 0 && checkIfUserCanModifyObject ( app , object ) ) { object . update ( ) ; if ( object . getVersion ( ) == - 1 ) { return getStatusResponse ( Response . Status . PRECONDITION_FAILED , "Update failed due to 'version' mismatch." ) ; } return Response . ok ( object ) . build ( ) ; } } } return getStatusResponse ( Response . Status . BAD_REQUEST , errors ) ; } return getStatusResponse ( Response . Status . NOT_FOUND ) ; } }
Update response as JSON .
36,289
public static Response getDeleteResponse ( App app , ParaObject content ) { try ( final Metrics . Context context = Metrics . time ( app == null ? null : app . getAppid ( ) , RestUtils . class , "crud" , "delete" ) ) { if ( app != null && content != null && content . getId ( ) != null && content . getAppid ( ) != null ) { if ( checkImplicitAppPermissions ( app , content ) && checkIfUserCanModifyObject ( app , content ) ) { content . setAppid ( isNotAnApp ( content . getType ( ) ) ? app . getAppIdentifier ( ) : app . getAppid ( ) ) ; content . delete ( ) ; return Response . ok ( ) . build ( ) ; } return getStatusResponse ( Response . Status . BAD_REQUEST ) ; } return getStatusResponse ( Response . Status . NOT_FOUND ) ; } }
Delete response as JSON .
36,290
public static Response getBatchReadResponse ( App app , List < String > ids ) { try ( final Metrics . Context context = Metrics . time ( app == null ? null : app . getAppid ( ) , RestUtils . class , "batch" , "read" ) ) { if ( app != null && ids != null && ! ids . isEmpty ( ) ) { ArrayList < ParaObject > results = new ArrayList < > ( ids . size ( ) ) ; for ( ParaObject result : Para . getDAO ( ) . readAll ( app . getAppIdentifier ( ) , ids , true ) . values ( ) ) { if ( checkImplicitAppPermissions ( app , result ) && checkIfUserCanModifyObject ( app , result ) ) { results . add ( result ) ; } } return Response . ok ( results ) . build ( ) ; } else { return getStatusResponse ( Response . Status . BAD_REQUEST , "Missing ids." ) ; } } }
Batch read response as JSON .
36,291
public static Response getBatchCreateResponse ( final App app , InputStream is ) { try ( final Metrics . Context context = Metrics . time ( app == null ? null : app . getAppid ( ) , RestUtils . class , "batch" , "create" ) ) { if ( app != null ) { final LinkedList < ParaObject > newObjects = new LinkedList < > ( ) ; Response entityRes = getEntity ( is , List . class ) ; if ( entityRes . getStatusInfo ( ) == Response . Status . OK ) { List < Map < String , Object > > items = ( List < Map < String , Object > > ) entityRes . getEntity ( ) ; for ( Map < String , Object > object : items ) { String type = ( String ) object . get ( Config . _TYPE ) ; if ( isNotAnApp ( type ) ) { warnIfUserTypeDetected ( type ) ; ParaObject pobj = ParaObjectUtils . setAnnotatedFields ( object ) ; if ( pobj != null && isValidObject ( app , pobj ) ) { pobj . setAppid ( app . getAppIdentifier ( ) ) ; setCreatorid ( app , pobj ) ; newObjects . add ( pobj ) ; } } } Para . getDAO ( ) . createAll ( app . getAppIdentifier ( ) , newObjects ) ; Para . asyncExecute ( new Runnable ( ) { public void run ( ) { int typesCount = app . getDatatypes ( ) . size ( ) ; app . addDatatypes ( newObjects . toArray ( new ParaObject [ 0 ] ) ) ; if ( typesCount < app . getDatatypes ( ) . size ( ) ) { app . update ( ) ; } } } ) ; } else { return entityRes ; } return Response . ok ( newObjects ) . build ( ) ; } else { return getStatusResponse ( Response . Status . BAD_REQUEST ) ; } } }
Batch create response as JSON .
36,292
public static Response getBatchUpdateResponse ( App app , Map < String , ParaObject > oldObjects , List < Map < String , Object > > newProperties ) { try ( final Metrics . Context context = Metrics . time ( app == null ? null : app . getAppid ( ) , RestUtils . class , "batch" , "update" ) ) { if ( app != null && oldObjects != null && newProperties != null ) { LinkedList < ParaObject > updatedObjects = new LinkedList < > ( ) ; boolean hasPositiveVersions = false ; for ( Map < String , Object > newProps : newProperties ) { if ( newProps != null && newProps . containsKey ( Config . _ID ) ) { ParaObject oldObject = oldObjects . get ( ( String ) newProps . get ( Config . _ID ) ) ; if ( oldObject != null && checkImplicitAppPermissions ( app , oldObject ) ) { ParaObject updatedObject = ParaObjectUtils . setAnnotatedFields ( oldObject , newProps , Locked . class ) ; if ( isValidObject ( app , updatedObject ) && checkIfUserCanModifyObject ( app , updatedObject ) ) { updatedObject . setAppid ( app . getAppIdentifier ( ) ) ; updatedObjects . add ( updatedObject ) ; if ( updatedObject . getVersion ( ) != null && updatedObject . getVersion ( ) > 0 ) { hasPositiveVersions = true ; } } } } } Para . getDAO ( ) . updateAll ( app . getAppIdentifier ( ) , updatedObjects ) ; return handleFailedUpdates ( hasPositiveVersions , updatedObjects ) ; } else { return getStatusResponse ( Response . Status . BAD_REQUEST ) ; } } }
Batch update response as JSON .
36,293
public static Response getBatchDeleteResponse ( App app , List < String > ids ) { try ( final Metrics . Context context = Metrics . time ( app == null ? null : app . getAppid ( ) , RestUtils . class , "batch" , "delete" ) ) { LinkedList < ParaObject > objects = new LinkedList < > ( ) ; if ( app != null && ids != null && ! ids . isEmpty ( ) ) { if ( ids . size ( ) <= Config . MAX_ITEMS_PER_PAGE ) { for ( ParaObject pobj : Para . getDAO ( ) . readAll ( app . getAppIdentifier ( ) , ids , true ) . values ( ) ) { if ( pobj != null && pobj . getId ( ) != null && pobj . getType ( ) != null ) { if ( isNotAnApp ( pobj . getType ( ) ) && checkIfUserCanModifyObject ( app , pobj ) ) { objects . add ( pobj ) ; } } } Para . getDAO ( ) . deleteAll ( app . getAppIdentifier ( ) , objects ) ; } else { return getStatusResponse ( Response . Status . BAD_REQUEST , "Limit reached. Maximum number of items to delete is " + Config . MAX_ITEMS_PER_PAGE ) ; } } else { return getStatusResponse ( Response . Status . BAD_REQUEST , "Missing ids." ) ; } return Response . ok ( ) . build ( ) ; } }
Batch delete response as JSON .
36,294
public static Response readLinksHandler ( ParaObject pobj , String id2 , String type2 , MultivaluedMap < String , String > params , Pager pager , boolean childrenOnly ) { try ( final Metrics . Context context = Metrics . time ( null , RestUtils . class , "links" , "read" ) ) { String query = params . getFirst ( "q" ) ; if ( type2 != null ) { if ( id2 != null ) { return Response . ok ( pobj . isLinked ( type2 , id2 ) , MediaType . TEXT_PLAIN_TYPE ) . build ( ) ; } else { List < ParaObject > items = new ArrayList < > ( ) ; if ( childrenOnly ) { if ( params . containsKey ( "count" ) ) { pager . setCount ( pobj . countChildren ( type2 ) ) ; } else { if ( params . containsKey ( "field" ) && params . containsKey ( "term" ) ) { items = pobj . getChildren ( type2 , params . getFirst ( "field" ) , params . getFirst ( "term" ) , pager ) ; } else { if ( StringUtils . isBlank ( query ) ) { items = pobj . getChildren ( type2 , pager ) ; } else { items = pobj . findChildren ( type2 , query , pager ) ; } } } } else { if ( params . containsKey ( "count" ) ) { pager . setCount ( pobj . countLinks ( type2 ) ) ; } else { if ( StringUtils . isBlank ( query ) ) { items = pobj . getLinkedObjects ( type2 , pager ) ; } else { items = pobj . findLinkedObjects ( type2 , params . getFirst ( "field" ) , query , pager ) ; } } } return Response . ok ( buildPageResponse ( items , pager ) ) . build ( ) ; } } else { return getStatusResponse ( Response . Status . BAD_REQUEST , "Parameter 'type' is missing." ) ; } } }
Handles requests to search for linked objects .
36,295
public static Response deleteLinksHandler ( ParaObject pobj , String id2 , String type2 , boolean childrenOnly ) { try ( final Metrics . Context context = Metrics . time ( null , RestUtils . class , "links" , "delete" ) ) { if ( type2 == null && id2 == null ) { pobj . unlinkAll ( ) ; } else if ( type2 != null ) { if ( id2 != null ) { pobj . unlink ( type2 , id2 ) ; } else if ( childrenOnly ) { pobj . deleteChildren ( type2 ) ; } } return Response . ok ( ) . build ( ) ; } }
Handles requests to delete linked objects .
36,296
public static Response createLinksHandler ( ParaObject pobj , String id2 ) { try ( final Metrics . Context context = Metrics . time ( null , RestUtils . class , "links" , "create" ) ) { if ( id2 != null && pobj != null ) { String linkid = pobj . link ( id2 ) ; if ( linkid == null ) { return getStatusResponse ( Response . Status . BAD_REQUEST , "Failed to create link." ) ; } else { return Response . ok ( linkid , MediaType . TEXT_PLAIN_TYPE ) . build ( ) ; } } else { return getStatusResponse ( Response . Status . BAD_REQUEST , "Parameters 'type' and 'id' are missing." ) ; } } }
Handles requests to link an object to other objects .
36,297
public static Response getStatusResponse ( Response . Status status , String ... messages ) { if ( status == null ) { return Response . status ( Response . Status . BAD_REQUEST ) . build ( ) ; } String msg = StringUtils . join ( messages , ". " ) ; if ( StringUtils . isBlank ( msg ) ) { msg = status . getReasonPhrase ( ) ; } try { return GenericExceptionMapper . getExceptionResponse ( status . getStatusCode ( ) , msg ) ; } catch ( Exception ex ) { logger . error ( null , ex ) ; return Response . status ( Response . Status . BAD_REQUEST ) . build ( ) ; } }
A generic JSON response handler .
36,298
public static void returnStatusResponse ( HttpServletResponse response , int status , String message ) { if ( response == null ) { return ; } PrintWriter out = null ; try { response . setStatus ( status ) ; response . setContentType ( MediaType . APPLICATION_JSON ) ; out = response . getWriter ( ) ; ParaObjectUtils . getJsonWriter ( ) . writeValue ( out , getStatusResponse ( Response . Status . fromStatusCode ( status ) , message ) . getEntity ( ) ) ; } catch ( Exception ex ) { logger . error ( null , ex ) ; } finally { if ( out != null ) { out . close ( ) ; } } }
A generic JSON response handler . Returns a message and response code .
36,299
public static String pathParam ( String param , ContainerRequestContext ctx ) { return ctx . getUriInfo ( ) . getPathParameters ( ) . getFirst ( param ) ; }
Returns the path parameter value .