_id
stringlengths
2
7
title
stringlengths
3
140
partition
stringclasses
3 values
text
stringlengths
73
34.1k
language
stringclasses
1 value
meta_information
dict
q164600
CrudDSL.table
train
public Crud<T, K> table(String table) { return new LazyCrud<T, K>(this, table); }
java
{ "resource": "" }
q164601
CrudDSL.table
train
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); }
java
{ "resource": "" }
q164602
CrudDSL.table
train
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(); } }
java
{ "resource": "" }
q164603
CrudDSL.to
train
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(); } }
java
{ "resource": "" }
q164604
CrudDSL.to
train
public Crud<T, K> to(Connection connection) throws SQLException { return table(connection, getTable(connection, target)); }
java
{ "resource": "" }
q164605
RayAabIntersection.precomputeSlope
train
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; // <- original paper had a bug here. It switched originZ/originX c_zx = originX - s_zx * originZ; // <- original paper had a bug here. It switched originZ/originX int sgnX = signum(dirX); int sgnY = signum(dirY); int sgnZ = signum(dirZ); classification = (byte) ((sgnZ+1) << 4 | (sgnY+1) << 2 | (sgnX+1)); }
java
{ "resource": "" }
q164606
Quaterniond.rotationX
train
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; }
java
{ "resource": "" }
q164607
Vector3f.div
train
public Vector3f div(Vector3fc v) { return div(v.x(), v.y(), v.z(), thisOrNew()); }
java
{ "resource": "" }
q164608
Quaternionf.normalize
train
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; }
java
{ "resource": "" }
q164609
Matrix3d.set
train
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(); }
java
{ "resource": "" }
q164610
AABBd.correctBounds
train
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; }
java
{ "resource": "" }
q164611
Vector3i.add
train
public Vector3i add(Vector3ic v) { return add(v.x(), v.y(), v.z(), thisOrNew()); }
java
{ "resource": "" }
q164612
Vector3i.mul
train
public Vector3i mul(int x, int y, int z) { return mul(x, y, z, thisOrNew()); }
java
{ "resource": "" }
q164613
Vector3d.lengthSquared
train
public static double lengthSquared(double x, double y, double z) { return x * x + y * y + z * z; }
java
{ "resource": "" }
q164614
Vector4i.length
train
public static double length(int x, int y, int z, int w) { return Math.sqrt(lengthSquared(x, y, z, w)); }
java
{ "resource": "" }
q164615
LocalizationActivityDelegate.onResume
train
public void onResume(final Context context) { new Handler().post(new Runnable() { @Override public void run() { checkLocaleChange(context); checkAfterLocaleChanging(); } }); }
java
{ "resource": "" }
q164616
LocalizationActivityDelegate.setLanguage
train
public final void setLanguage(Context context, String language) { Locale locale = new Locale(language); setLanguage(context, locale); }
java
{ "resource": "" }
q164617
LocalizationActivityDelegate.checkBeforeLocaleChanging
train
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); } }
java
{ "resource": "" }
q164618
LocalizationActivityDelegate.setupLanguage
train
private void setupLanguage() { Locale locale = LanguageSetting.getLanguage(activity); setupLocale(locale); currentLanguage = locale; LanguageSetting.setLanguage(activity, locale); }
java
{ "resource": "" }
q164619
LocalizationActivityDelegate.isCurrentLanguageSetting
train
private boolean isCurrentLanguageSetting(Context context, Locale locale) { return locale.toString().equals(LanguageSetting.getLanguage(context).toString()); }
java
{ "resource": "" }
q164620
LocalizationActivityDelegate.notifyLanguageChanged
train
private void notifyLanguageChanged() { sendOnBeforeLocaleChangedEvent(); activity.getIntent().putExtra(KEY_ACTIVITY_LOCALE_CHANGED, true); callDummyActivity(); activity.recreate(); }
java
{ "resource": "" }
q164621
LocalizationActivityDelegate.checkLocaleChange
train
private void checkLocaleChange(Context context) { if (!isCurrentLanguageSetting(context, currentLanguage)) { sendOnBeforeLocaleChangedEvent(); isLocalizationChanged = true; callDummyActivity(); activity.recreate(); } }
java
{ "resource": "" }
q164622
AsciidoctorFileScanner.scan
train
public List<File> scan(List<Resource> resources) { List<File> files = new ArrayList<File>(); for (Resource resource: resources) { files.addAll(scan(resource)); } return files; }
java
{ "resource": "" }
q164623
MemoryLogHandler.filter
train
public List<LogRecord> filter(Severity severity) { // FIXME: find better name or replace with stream final List<LogRecord> records = new ArrayList<>(); for (LogRecord record : this.records) { if (record.getSeverity().ordinal() >= severity.ordinal()) records.add(record); } return records; }
java
{ "resource": "" }
q164624
MemoryLogHandler.filter
train
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; }
java
{ "resource": "" }
q164625
MemoryLogHandler.filter
train
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; }
java
{ "resource": "" }
q164626
SwipeBack.attach
train
public static SwipeBack attach(Activity activity, Type type, Position position, int dragMode) { return attach(activity, type, position, dragMode, new DefaultSwipeBackTransformer()); }
java
{ "resource": "" }
q164627
SwipeBack.createSwipeBack
train
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; }
java
{ "resource": "" }
q164628
SwipeBack.isActivitiyDestroyed
train
@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(); } }
java
{ "resource": "" }
q164629
SwipeBack.attachToContent
train
private static void attachToContent(Activity activity, SwipeBack swipeBack) { /** * Do not call mActivity#setContentView. * E.g. if using with a ListActivity, Activity#setContentView is overridden and dispatched to * SwipeBack#setContentView, which then again would call Activity#setContentView. */ ViewGroup content = (ViewGroup) activity .findViewById(android.R.id.content); content.removeAllViews(); content.addView(swipeBack, LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT); }
java
{ "resource": "" }
q164630
SwipeBack.attachToDecor
train
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()); }
java
{ "resource": "" }
q164631
SwipeBack.updateTouchAreaSize
train
protected void updateTouchAreaSize() { if (mTouchMode == TOUCH_MODE_BEZEL) { mTouchSize = mTouchBezelSize; } else if (mTouchMode == TOUCH_MODE_FULLSCREEN) { mTouchSize = getMeasuredWidth(); } else { mTouchSize = 0; } }
java
{ "resource": "" }
q164632
SwipeBack.setDividerAsShadowColor
train
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; }
java
{ "resource": "" }
q164633
SwipeBack.setSwipeBackView
train
public SwipeBack setSwipeBackView(int layoutResId) { mSwipeBackContainer.removeAllViews(); mSwipeBackView = LayoutInflater.from(getContext()).inflate(layoutResId, mSwipeBackContainer, false); mSwipeBackContainer.addView(mSwipeBackView); notifySwipeBackViewCreated(mSwipeBackView); return this; }
java
{ "resource": "" }
q164634
DraggableSwipeBack.completeAnimation
train
private void completeAnimation() { mScroller.abortAnimation(); final int finalX = mScroller.getFinalX(); setOffsetPixels(finalX); setDrawerState(finalX == 0 ? STATE_CLOSED : STATE_OPEN); stopLayerTranslation(); }
java
{ "resource": "" }
q164635
DraggableSwipeBack.postAnimationInvalidate
train
@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(); }
java
{ "resource": "" }
q164636
DraggableSwipeBack.peekDrawerInvalidate
train
@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() { @Override public void run() { startPeek(); } }; postDelayed(mPeekStartRunnable, mPeekDelay); } } completePeek(); }
java
{ "resource": "" }
q164637
Scroller.computeScrollOffset
train
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)); // Pin to mMinX <= mCurrX <= mMaxX mCurrX = Math.min(mCurrX, mMaxX); mCurrX = Math.max(mCurrX, mMinX); mCurrY = mStartY + Math.round(distanceCoef * (mFinalY - mStartY)); // Pin to mMinY <= mCurrY <= mMaxY 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; }
java
{ "resource": "" }
q164638
Scroller.startScroll
train
public void startScroll(int startX, int startY, int dx, int dy) { startScroll(startX, startY, dx, dy, DEFAULT_DURATION); }
java
{ "resource": "" }
q164639
BsonQueryFactory.marshallParameterAsPrimitive
train
private Object marshallParameterAsPrimitive(Object parameter) { Map<String, Object> primitiveWrapper = Collections.singletonMap("wrapped", parameter); BsonDocument document = marshaller.marshall(primitiveWrapper); return document.toDBObject().get("wrapped"); }
java
{ "resource": "" }
q164640
AWSDynamoUtils.getClient
train
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; }
java
{ "resource": "" }
q164641
AWSDynamoUtils.existsTable
train
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; } }
java
{ "resource": "" }
q164642
AWSDynamoUtils.createTable
train
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; }
java
{ "resource": "" }
q164643
AWSDynamoUtils.deleteTable
train
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; }
java
{ "resource": "" }
q164644
AWSDynamoUtils.createSharedTable
train
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; }
java
{ "resource": "" }
q164645
AWSDynamoUtils.listAllTables
train
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; }
java
{ "resource": "" }
q164646
AWSDynamoUtils.getTableNameForAppid
train
public static String getTableNameForAppid(String appIdentifier) { if (StringUtils.isBlank(appIdentifier)) { return null; } else { if (isSharedAppid(appIdentifier)) { // app is sharing a table with other apps appIdentifier = SHARED_TABLE; } return (App.isRoot(appIdentifier) || appIdentifier.startsWith(Config.PARA.concat("-"))) ? appIdentifier : Config.PARA + "-" + appIdentifier; } }
java
{ "resource": "" }
q164647
AWSDynamoUtils.batchGet
train
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); } }
java
{ "resource": "" }
q164648
AWSDynamoUtils.batchWrite
train
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); } }
java
{ "resource": "" }
q164649
AWSDynamoUtils.readPageFromTable
train
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()) { // set last key to be equal to the last result - end reached. pager.setLastKey(results.peekLast().getId()); } return results; }
java
{ "resource": "" }
q164650
AWSDynamoUtils.readPageFromSharedTable
train
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; }
java
{ "resource": "" }
q164651
AWSDynamoUtils.deleteAllFromSharedTable
train
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 { // read all phase 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); // only delete rows which belong to the given appid 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(); } // delete all phase 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()); }
java
{ "resource": "" }
q164652
AWSDynamoUtils.getSharedIndex
train
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; }
java
{ "resource": "" }
q164653
User.setCurrency
train
public void setCurrency(String currency) { currency = StringUtils.upperCase(currency); if (!CurrencyUtils.getInstance().isValidCurrency(currency)) { currency = "EUR"; } this.currency = currency; }
java
{ "resource": "" }
q164654
User.detachIdentifier
train
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); } } }
java
{ "resource": "" }
q164655
User.isModerator
train
@JsonIgnore public boolean isModerator() { return isAdmin() ? true : StringUtils.equalsIgnoreCase(this.groups, Groups.MODS.toString()); }
java
{ "resource": "" }
q164656
User.getIdentityProvider
train
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"; } }
java
{ "resource": "" }
q164657
User.readUserForIdentifier
train
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(); // Try to read the identifier object first, then read the user object linked to it. 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); } // Try to find the user by email if already created, but with a different identifier. // This prevents users with identical emails to have separate accounts by signing in through // different identity providers. 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); // the main identifier was changed - update 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; }
java
{ "resource": "" }
q164658
User.passwordMatches
train
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; }
java
{ "resource": "" }
q164659
User.generatePasswordResetToken
train
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 ""; }
java
{ "resource": "" }
q164660
User.resetPassword
train
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; }
java
{ "resource": "" }
q164661
User.deleteIdentifier
train
private void deleteIdentifier(String ident) { if (!StringUtils.isBlank(ident)) { CoreUtils.getInstance().getDao().delete(getAppid(), new Sysprop(ident)); } }
java
{ "resource": "" }
q164662
User.generateEmailConfirmationToken
train
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 ""; }
java
{ "resource": "" }
q164663
User.activateWithEmailToken
train
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; }
java
{ "resource": "" }
q164664
User.isValidPasswordResetToken
train
public final boolean isValidPasswordResetToken(String token) { Sysprop s = CoreUtils.getInstance().getDao().read(getAppid(), identifier); return isValidToken(s, Config._RESET_TOKEN, token); }
java
{ "resource": "" }
q164665
User.isValidEmailConfirmationToken
train
public final boolean isValidEmailConfirmationToken(String token) { Sysprop s = CoreUtils.getInstance().getDao().read(getAppid(), identifier); return isValidToken(s, Config._EMAIL_TOKEN, token); }
java
{ "resource": "" }
q164666
User.setGravatarPicture
train
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"); } } }
java
{ "resource": "" }
q164667
RestUtils.extractAccessKey
train
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)) { // try to get access key from parameter accessKey = request.getParameter("accessKey"); } return accessKey; }
java
{ "resource": "" }
q164668
RestUtils.isAnonymousRequest
train
public static boolean isAnonymousRequest(HttpServletRequest request) { return request != null && (StringUtils.startsWith(request.getHeader(HttpHeaders.AUTHORIZATION), "Anonymous") || StringUtils.isBlank(request.getHeader(HttpHeaders.AUTHORIZATION))); }
java
{ "resource": "" }
q164669
RestUtils.extractDate
train
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; } }
java
{ "resource": "" }
q164670
RestUtils.getEntity
train
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(); }
java
{ "resource": "" }
q164671
RestUtils.readEntityBytes
train
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; }
java
{ "resource": "" }
q164672
RestUtils.getVotingResponse
train
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(); }
java
{ "resource": "" }
q164673
RestUtils.getReadResponse
train
public static Response getReadResponse(App app, ParaObject content) { try (final Metrics.Context context = Metrics.time(app == null ? null : app.getAppid(), RestUtils.class, "crud", "read")) { // app can't modify other apps except itself if (app != null && content != null && checkImplicitAppPermissions(app, content) && checkIfUserCanModifyObject(app, content)) { return Response.ok(content).build(); } return getStatusResponse(Response.Status.NOT_FOUND); } }
java
{ "resource": "" }
q164674
RestUtils.getCreateResponse
train
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); // The reason why we do two validation passes is because we want to return // the errors through the API and notify the end user. // This is the primary validation pass (validates not only core POJOS but also user defined objects). String[] errors = validateObject(app, content); if (errors.length == 0) { // Secondary validation pass called here. Object is validated again before being created // See: IndexAndCacheAspect.java String id = content.create(); if (id != null) { // new type added so update app object 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; } }
java
{ "resource": "" }
q164675
RestUtils.getOverwriteResponse
train
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); // The reason why we do two validation passes is because we want to return // the errors through the API and notify the end user. // This is the primary validation pass (validates not only core POJOS but also user defined objects). String[] errors = validateObject(app, content); if (errors.length == 0 && checkIfUserCanModifyObject(app, content)) { // Secondary validation pass called here. Object is validated again before being created // See: IndexAndCacheAspect.java CoreUtils.getInstance().overwrite(app.getAppIdentifier(), content); // new type added so update app object 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; } }
java
{ "resource": "" }
q164676
RestUtils.getUpdateResponse
train
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); // app can't modify other apps except itself if (checkImplicitAppPermissions(app, object)) { // This is the primary validation pass (validates not only core POJOS but also user defined objects). errors = validateObject(app, object); if (errors.length == 0 && checkIfUserCanModifyObject(app, object)) { // Secondary validation pass: object is validated again before being updated object.update(); // check if update failed due to optimistic locking 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); } }
java
{ "resource": "" }
q164677
RestUtils.getDeleteResponse
train
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); } }
java
{ "resource": "" }
q164678
RestUtils.getBatchReadResponse
train
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."); } } }
java
{ "resource": "" }
q164679
RestUtils.getBatchCreateResponse
train
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) { // can't create multiple apps in batch 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); } } }
java
{ "resource": "" }
q164680
RestUtils.getBatchUpdateResponse
train
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)); // updating apps in batch is not allowed 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); // check if any or all updates failed due to optimistic locking return handleFailedUpdates(hasPositiveVersions, updatedObjects); } else { return getStatusResponse(Response.Status.BAD_REQUEST); } } }
java
{ "resource": "" }
q164681
RestUtils.getBatchDeleteResponse
train
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) { // deleting apps in batch is not allowed 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(); } }
java
{ "resource": "" }
q164682
RestUtils.readLinksHandler
train
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."); } } }
java
{ "resource": "" }
q164683
RestUtils.deleteLinksHandler
train
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(); } }
java
{ "resource": "" }
q164684
RestUtils.createLinksHandler
train
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."); } } }
java
{ "resource": "" }
q164685
RestUtils.getStatusResponse
train
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(); } }
java
{ "resource": "" }
q164686
RestUtils.returnStatusResponse
train
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(); } } }
java
{ "resource": "" }
q164687
RestUtils.pathParam
train
public static String pathParam(String param, ContainerRequestContext ctx) { return ctx.getUriInfo().getPathParameters().getFirst(param); }
java
{ "resource": "" }
q164688
RestUtils.pathParams
train
public static List<String> pathParams(String param, ContainerRequestContext ctx) { return ctx.getUriInfo().getPathParameters().get(param); }
java
{ "resource": "" }
q164689
RestUtils.queryParam
train
public static String queryParam(String param, ContainerRequestContext ctx) { return ctx.getUriInfo().getQueryParameters().getFirst(param); }
java
{ "resource": "" }
q164690
RestUtils.queryParams
train
public static List<String> queryParams(String param, ContainerRequestContext ctx) { return ctx.getUriInfo().getQueryParameters().get(param); }
java
{ "resource": "" }
q164691
RestUtils.hasQueryParam
train
public static boolean hasQueryParam(String param, ContainerRequestContext ctx) { return ctx.getUriInfo().getQueryParameters().containsKey(param); }
java
{ "resource": "" }
q164692
AWSQueue.getUrl
train
public String getUrl() { if (StringUtils.isBlank(url) && !StringUtils.isBlank(name)) { this.url = AWSQueueUtils.createQueue(name); } return url; }
java
{ "resource": "" }
q164693
GZipServletFilter.isIncluded
train
private boolean isIncluded(final HttpServletRequest request) { final String uri = (String) request.getAttribute("javax.servlet.include.request_uri"); final boolean includeRequest = !(uri == null); if (includeRequest && log.isDebugEnabled()) { log.debug("{} resulted in an include request. This is unusable, because" + "the response will be assembled into the overrall response. Not gzipping.", request.getRequestURL()); } return includeRequest; }
java
{ "resource": "" }
q164694
Signer.parseAWSDate
train
public static Date parseAWSDate(String date) { if (date == null) { return null; } return TIME_FORMATTER.parseDateTime(date).toDate(); }
java
{ "resource": "" }
q164695
Signer.signRequest
train
public Map<String, String> signRequest(String accessKey, String secretKey, String httpMethod, String endpointURL, String reqPath, Map<String, String> headers, MultivaluedMap<String, String> params, byte[] jsonEntity) { if (StringUtils.isBlank(accessKey)) { logger.error("Blank access key: {} {}", httpMethod, reqPath); return headers; } if (StringUtils.isBlank(secretKey)) { logger.debug("Anonymous request: {} {}", httpMethod, reqPath); if (headers == null) { headers = new HashMap<>(); } headers.put(HttpHeaders.AUTHORIZATION, "Anonymous " + accessKey); return headers; } if (httpMethod == null) { httpMethod = HttpMethod.GET; } InputStream in = null; Map<String, String> sigParams = new HashMap<>(); if (params != null) { for (Map.Entry<String, List<String>> param : params.entrySet()) { String key = param.getKey(); List<String> value = param.getValue(); if (value != null && !value.isEmpty() && value.get(0) != null) { sigParams.put(key, value.get(0)); } } } if (jsonEntity != null && jsonEntity.length > 0) { in = new ByteArrayInputStream(jsonEntity); } return sign(httpMethod, endpointURL, reqPath, headers, sigParams, in, accessKey, secretKey); }
java
{ "resource": "" }
q164696
ValidationUtils.validateObject
train
public static String[] validateObject(ParaObject content) { if (content == null) { return new String[]{"Object cannot be null."}; } LinkedList<String> list = new LinkedList<>(); try { for (ConstraintViolation<ParaObject> constraintViolation : getValidator().validate(content)) { String prop = "'".concat(constraintViolation.getPropertyPath().toString()).concat("'"); list.add(prop.concat(" ").concat(constraintViolation.getMessage())); } } catch (Exception e) { logger.error(null, e); } return list.toArray(new String[]{}); }
java
{ "resource": "" }
q164697
ValidationUtils.validateObject
train
public static String[] validateObject(App app, ParaObject content) { if (content == null || app == null) { return new String[]{"Object cannot be null."}; } try { String type = content.getType(); boolean isCustomType = (content instanceof Sysprop) && !type.equals(Utils.type(Sysprop.class)); // Validate custom types and user-defined properties if (!app.getValidationConstraints().isEmpty() && isCustomType) { Map<String, Map<String, Map<String, ?>>> fieldsMap = app.getValidationConstraints().get(type); if (fieldsMap != null && !fieldsMap.isEmpty()) { LinkedList<String> errors = new LinkedList<>(); for (Map.Entry<String, Map<String, Map<String, ?>>> e : fieldsMap.entrySet()) { String field = e.getKey(); Object actualValue = ((Sysprop) content).getProperty(field); // overriding core property validation rules is allowed if (actualValue == null && PropertyUtils.isReadable(content, field)) { actualValue = PropertyUtils.getProperty(content, field); } Map<String, Map<String, ?>> consMap = e.getValue(); for (Map.Entry<String, Map<String, ?>> constraint : consMap.entrySet()) { buildAndValidateConstraint(constraint, field, actualValue, errors); } } if (!errors.isEmpty()) { return errors.toArray(new String[0]); } } } } catch (Exception ex) { logger.error(null, ex); } return validateObject(content); }
java
{ "resource": "" }
q164698
ValidationUtils.getCoreValidationConstraints
train
public static Map<String, Map<String, Map<String, Map<String, ?>>>> getCoreValidationConstraints() { if (CORE_CONSTRAINTS.isEmpty()) { for (Map.Entry<String, Class<? extends ParaObject>> e : ParaObjectUtils.getCoreClassesMap().entrySet()) { String type = e.getKey(); List<Field> fieldlist = Utils.getAllDeclaredFields(e.getValue()); for (Field field : fieldlist) { Annotation[] annos = field.getAnnotations(); if (annos.length > 1) { Map<String, Map<String, ?>> constrMap = new HashMap<>(); for (Annotation anno : annos) { if (isValidConstraintType(anno.annotationType())) { Constraint c = fromAnnotation(anno); if (c != null) { constrMap.put(c.getName(), c.getPayload()); } } } if (!constrMap.isEmpty()) { if (!CORE_CONSTRAINTS.containsKey(type)) { CORE_CONSTRAINTS.put(type, new HashMap<>()); } CORE_CONSTRAINTS.get(type).put(field.getName(), constrMap); } } } } } return Collections.unmodifiableMap(CORE_CONSTRAINTS); }
java
{ "resource": "" }
q164699
IndexAndCacheAspect.invoke
train
public Object invoke(MethodInvocation mi) throws Throwable { if (!Modifier.isPublic(mi.getMethod().getModifiers())) { return mi.proceed(); } Method daoMethod = mi.getMethod(); Object[] args = mi.getArguments(); String appid = AOPUtils.getFirstArgOfString(args); Method superMethod = null; Indexed indexedAnno = null; Cached cachedAnno = null; try { superMethod = DAO.class.getMethod(daoMethod.getName(), daoMethod.getParameterTypes()); indexedAnno = Config.isSearchEnabled() ? superMethod.getAnnotation(Indexed.class) : null; cachedAnno = Config.isCacheEnabled() ? superMethod.getAnnotation(Cached.class) : null; detectNestedInvocations(daoMethod); } catch (Exception e) { logger.error("Error in AOP layer!", e); } Set<IOListener> ioListeners = Para.getIOListeners(); for (IOListener ioListener : ioListeners) { ioListener.onPreInvoke(superMethod, args); logger.debug("Executed {}.onPreInvoke().", ioListener.getClass().getName()); } Object result = handleIndexing(indexedAnno, appid, daoMethod, args, mi); Object cachingResult = handleCaching(cachedAnno, appid, daoMethod, args, mi); // we have a read operation without any result but we get back objects from cache if (result == null && cachingResult != null) { result = cachingResult; } // both searching and caching are disabled - pass it through if (indexedAnno == null && cachedAnno == null) { result = invokeDAO(appid, daoMethod, mi); } for (IOListener ioListener : ioListeners) { ioListener.onPostInvoke(superMethod, result); logger.debug("Executed {}.onPostInvoke().", ioListener.getClass().getName()); } return result; }
java
{ "resource": "" }