conflict_resolution
stringlengths 27
16k
|
---|
<<<<<<<
=======
import android.database.Cursor;
import android.os.Environment;
>>>>>>>
import android.os.Environment;
<<<<<<<
mExecutor = factory.createExecutor();
this.downloadsRepository = new DownloadsRepository(getContentResolver(), new DownloadsRepository.DownloadInfoCreator() {
@Override
public DownloadInfo create(DownloadInfo.Reader reader) {
return createNewDownloadInfo(reader);
}
});
}
/**
* Keeps a local copy of the info about a download, and initiates the
* download if appropriate.
*/
private DownloadInfo createNewDownloadInfo(DownloadInfo.Reader reader) {
DownloadInfo info = reader.newDownloadInfo(this, mSystemFacade, mStorageManager, mNotifier, downloadClientReadyChecker);
Log.v("processing inserted download " + info.mId);
return info;
=======
executor = factory.createExecutor();
>>>>>>>
executor = factory.createExecutor();
this.downloadsRepository = new DownloadsRepository(getContentResolver(), new DownloadsRepository.DownloadInfoCreator() {
@Override
public DownloadInfo create(DownloadInfo.Reader reader) {
return createNewDownloadInfo(reader);
}
});
}
/**
* Keeps a local copy of the info about a download, and initiates the
* download if appropriate.
*/
private DownloadInfo createNewDownloadInfo(DownloadInfo.Reader reader) {
DownloadInfo info = reader.newDownloadInfo(this, systemFacade, downloadClientReadyChecker);
Log.v("processing inserted download " + info.getId());
return info;
<<<<<<<
synchronized (DownloadService.this) {
=======
synchronized (downloads) {
>>>>>>>
synchronized (DownloadService.this) {
<<<<<<<
=======
Set<Long> staleDownloadIds = new HashSet<>(downloads.keySet());
>>>>>>>
<<<<<<<
private void updateTotalBytesFor(Collection<DownloadInfo> downloadInfos) {
ContentValues values = new ContentValues();
for (DownloadInfo downloadInfo : downloadInfos) {
if (downloadInfo.mTotalBytes == -1) {
downloadInfo.mTotalBytes = contentLengthFetcher.fetchContentLengthFor(downloadInfo);
values.put(Downloads.Impl.COLUMN_TOTAL_BYTES, downloadInfo.mTotalBytes);
getContentResolver().update(downloadInfo.getAllDownloadsUri(), values, null, null);
batchRepository.updateCurrentSize(downloadInfo.getBatchId());
batchRepository.updateTotalSize(downloadInfo.getBatchId());
}
=======
private void updateTotalBytesFor(DownloadInfo info) {
if (!info.hasTotalBytes()) {
ContentValues values = new ContentValues();
info.setTotalBytes(contentLengthFetcher.fetchContentLengthFor(info));
values.put(Downloads.Impl.COLUMN_TOTAL_BYTES, info.getTotalBytes());
getContentResolver().update(info.getAllDownloadsUri(), values, null, null);
>>>>>>>
private void updateTotalBytesFor(Collection<DownloadInfo> downloadInfos) {
ContentValues values = new ContentValues();
for (DownloadInfo downloadInfo : downloadInfos) {
if (downloadInfo.getTotalBytes() == -1) {
long totalBytes = contentLengthFetcher.fetchContentLengthFor(downloadInfo);
values.put(Downloads.Impl.COLUMN_TOTAL_BYTES, totalBytes);
getContentResolver().update(downloadInfo.getAllDownloadsUri(), values, null, null);
batchRepository.updateCurrentSize(downloadInfo.getBatchId());
batchRepository.updateTotalSize(downloadInfo.getBatchId());
}
<<<<<<<
=======
/**
* Keeps a local copy of the info about a download, and initiates the
* download if appropriate.
*/
private DownloadInfo createNewDownloadInfo(DownloadInfo.Reader reader) {
DownloadInfo info = reader.newDownloadInfo(this, systemFacade, downloadClientReadyChecker);
Log.v("processing inserted download " + info.getId());
return info;
}
/**
* Updates the local copy of the info about a download.
*/
private void updateDownloadFromDatabase(DownloadInfo.Reader reader, DownloadInfo info) {
reader.updateFromDatabase(info);
Log.v("processing updated download " + info.getId() + ", status: " + info.getStatus());
}
>>>>>>> |
<<<<<<<
locationTextView.setText(download.getDownloadStatusText() + " : " + download.getFileName());
deleteButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(@NonNull View v) {
listener.onDelete(download);
}
});
=======
String text = String.format("%1$s : %2$s\nBatch %3$d", download.getDownloadStatusText(), download.getFileName(), download.getBatchId());
locationTextView.setText(text);
>>>>>>>
String text = String.format("%1$s : %2$s\nBatch %3$d", download.getDownloadStatusText(), download.getFileName(), download.getBatchId());
locationTextView.setText(text);
deleteButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(@NonNull View v) {
listener.onDelete(download);
}
});
<<<<<<<
interface Listener {
void onDelete(Download download);
}
=======
public void updateDownloads(List<Download> downloads) {
this.downloads.clear();
this.downloads.addAll(downloads);
notifyDataSetChanged();
}
>>>>>>>
public void updateDownloads(List<Download> downloads) {
this.downloads.clear();
this.downloads.addAll(downloads);
notifyDataSetChanged();
}
interface Listener {
void onDelete(Download download);
} |
<<<<<<<
// TODO: move towards these in-memory objects being sources of truth, and
// periodically pushing to provider.
public static class Reader {
private ContentResolver mResolver;
private Cursor mCursor;
public Reader(ContentResolver resolver, Cursor cursor) {
mResolver = resolver;
mCursor = cursor;
}
public DownloadInfo newDownloadInfo(
Context context,
SystemFacade systemFacade,
StorageManager storageManager,
DownloadNotifier notifier,
DownloadClientReadyChecker downloadClientReadyChecker,
Downloads downloads) {
RandomNumberGenerator randomNumberGenerator = new RandomNumberGenerator();
ContentValues contentValues = new ContentValues();
DownloadInfo info = new DownloadInfo(
context,
systemFacade,
storageManager,
notifier,
randomNumberGenerator,
downloadClientReadyChecker,
contentValues,
downloads);
updateFromDatabase(info);
readRequestHeaders(info);
return info;
}
public void updateFromDatabase(DownloadInfo info) {
info.mId = getLong(Downloads.Impl._ID);
info.mUri = getString(Downloads.Impl.COLUMN_URI);
info.mScannable = getInt(Downloads.Impl.COLUMN_MEDIA_SCANNED) == 1;
info.mNoIntegrity = getInt(Downloads.Impl.COLUMN_NO_INTEGRITY) == 1;
info.mHint = getString(Downloads.Impl.COLUMN_FILE_NAME_HINT);
info.mFileName = getString(Downloads.Impl._DATA);
info.mMimeType = getString(Downloads.Impl.COLUMN_MIME_TYPE);
info.mDestination = getInt(Downloads.Impl.COLUMN_DESTINATION);
info.mStatus = getInt(Downloads.Impl.COLUMN_STATUS);
info.mNumFailed = getInt(Downloads.Impl.COLUMN_FAILED_CONNECTIONS);
int retryRedirect = getInt(Constants.RETRY_AFTER_X_REDIRECT_COUNT);
info.mRetryAfter = retryRedirect & 0xfffffff;
info.mLastMod = getLong(Downloads.Impl.COLUMN_LAST_MODIFICATION);
info.mClass = getString(Downloads.Impl.COLUMN_NOTIFICATION_CLASS);
info.mExtras = getString(Downloads.Impl.COLUMN_NOTIFICATION_EXTRAS);
info.mCookies = getString(Downloads.Impl.COLUMN_COOKIE_DATA);
info.mUserAgent = getString(Downloads.Impl.COLUMN_USER_AGENT);
info.mReferer = getString(Downloads.Impl.COLUMN_REFERER);
info.mTotalBytes = getLong(Downloads.Impl.COLUMN_TOTAL_BYTES);
info.mCurrentBytes = getLong(Downloads.Impl.COLUMN_CURRENT_BYTES);
info.mETag = getString(Constants.ETAG);
info.mUid = getInt(Constants.UID);
info.mMediaScanned = getInt(Constants.MEDIA_SCANNED);
info.mDeleted = getInt(Downloads.Impl.COLUMN_DELETED) == 1;
info.mMediaProviderUri = getString(Downloads.Impl.COLUMN_MEDIAPROVIDER_URI);
info.mAllowedNetworkTypes = getInt(Downloads.Impl.COLUMN_ALLOWED_NETWORK_TYPES);
info.mAllowRoaming = getInt(Downloads.Impl.COLUMN_ALLOW_ROAMING) != 0;
info.mAllowMetered = getInt(Downloads.Impl.COLUMN_ALLOW_METERED) != 0;
info.mBypassRecommendedSizeLimit = getInt(Downloads.Impl.COLUMN_BYPASS_RECOMMENDED_SIZE_LIMIT);
info.batchId = getLong(Downloads.Impl.COLUMN_BATCH_ID);
synchronized (this) {
info.mControl = getInt(Downloads.Impl.COLUMN_CONTROL);
}
}
private void readRequestHeaders(DownloadInfo info) {
info.mRequestHeaders.clear();
Uri headerUri = Uri.withAppendedPath(info.getAllDownloadsUri(), Downloads.Impl.RequestHeaders.URI_SEGMENT);
Cursor cursor = mResolver.query(headerUri, null, null, null, null);
try {
int headerIndex =
cursor.getColumnIndexOrThrow(Downloads.Impl.RequestHeaders.COLUMN_HEADER);
int valueIndex =
cursor.getColumnIndexOrThrow(Downloads.Impl.RequestHeaders.COLUMN_VALUE);
for (cursor.moveToFirst(); !cursor.isAfterLast(); cursor.moveToNext()) {
addHeader(info, cursor.getString(headerIndex), cursor.getString(valueIndex));
}
} finally {
cursor.close();
}
if (info.mCookies != null) {
addHeader(info, "Cookie", info.mCookies);
}
if (info.mReferer != null) {
addHeader(info, "Referer", info.mReferer);
}
}
private void addHeader(DownloadInfo info, String header, String value) {
info.mRequestHeaders.add(Pair.create(header, value));
}
private String getString(String column) {
int index = mCursor.getColumnIndexOrThrow(column);
String s = mCursor.getString(index);
return (TextUtils.isEmpty(s)) ? null : s;
}
private Integer getInt(String column) {
return mCursor.getInt(mCursor.getColumnIndexOrThrow(column));
}
private Long getLong(String column) {
return mCursor.getLong(mCursor.getColumnIndexOrThrow(column));
}
}
=======
// TODO: move towards these in-memory objects being sources of truth, and periodically pushing to provider.
>>>>>>>
// TODO: move towards these in-memory objects being sources of truth, and periodically pushing to provider.
<<<<<<<
ContentValues downloadStatusContentValues,
Downloads downloads) {
this.mContext = context;
this.mSystemFacade = systemFacade;
this.mStorageManager = storageManager;
this.mNotifier = notifier;
=======
ContentValues downloadStatusContentValues) {
this.context = context;
this.systemFacade = systemFacade;
>>>>>>>
ContentValues downloadStatusContentValues,
Downloads downloads) {
this.context = context;
this.systemFacade = systemFacade;
<<<<<<<
if (mSubmittedTask == null || mSubmittedTask.isDone()) {
BatchCompletionBroadcaster batchCompletionBroadcaster = BatchCompletionBroadcaster.newInstance(mContext);
ContentResolver contentResolver = mContext.getContentResolver();
BatchRepository batchRepository = new BatchRepository(contentResolver, new DownloadDeleter(contentResolver), downloads);
DownloadThread downloadThread = new DownloadThread(mContext, mSystemFacade, this, mStorageManager, mNotifier,
batchCompletionBroadcaster, batchRepository, downloads);
mSubmittedTask = executor.submit(downloadThread);
=======
if (submittedThread == null || submittedThread.isDone()) {
String applicationPackageName = context.getApplicationContext().getPackageName();
BatchCompletionBroadcaster batchCompletionBroadcaster = new BatchCompletionBroadcaster(context, applicationPackageName);
ContentResolver contentResolver = context.getContentResolver();
BatchRepository batchRepository = BatchRepository.newInstance(contentResolver, new DownloadDeleter(contentResolver));
DownloadThread downloadThread = new DownloadThread(context, systemFacade, this, storageManager, downloadNotifier,
batchCompletionBroadcaster, batchRepository);
submittedThread = executor.submit(downloadThread);
>>>>>>>
if (submittedThread == null || submittedThread.isDone()) {
String applicationPackageName = context.getApplicationContext().getPackageName();
BatchCompletionBroadcaster batchCompletionBroadcaster = new BatchCompletionBroadcaster(context, applicationPackageName);
ContentResolver contentResolver = context.getContentResolver();
BatchRepository batchRepository = new BatchRepository(contentResolver, new DownloadDeleter(contentResolver), downloads);
DownloadThread downloadThread = new DownloadThread(context, systemFacade, this, storageManager, downloadNotifier,
batchCompletionBroadcaster, batchRepository, downloads);
submittedThread = executor.submit(downloadThread);
<<<<<<<
public Uri getMyDownloadsUri() {
return ContentUris.withAppendedId(downloads.getContentUri(), mId);
=======
private Uri getMyDownloadsUri() {
return ContentUris.withAppendedId(Downloads.Impl.CONTENT_URI, id);
>>>>>>>
public Uri getMyDownloadsUri() {
return ContentUris.withAppendedId(downloads.getContentUri(), id);
<<<<<<<
return ContentUris.withAppendedId(downloads.getAllDownloadsContentUri(), mId);
=======
return ContentUris.withAppendedId(Downloads.Impl.ALL_DOWNLOADS_CONTENT_URI, id);
>>>>>>>
return ContentUris.withAppendedId(downloads.getAllDownloadsContentUri(), id); |
<<<<<<<
// @GuardedBy("activeNotifications")
private final HashMap<String, Long> activeNotifications = new HashMap<>();
=======
// @GuardedBy("mActiveNotifs")
private final SimpleArrayMap<String, Long> activeNotifs = new SimpleArrayMap<>();
>>>>>>>
// @GuardedBy("mActiveNotifs")
private final SimpleArrayMap<String, Long> activeNotifications = new SimpleArrayMap<>();
<<<<<<<
synchronized (activeNotifications) {
Map<String, Collection<DownloadBatch>> clusters = getClustersByNotificationTag(batches);
=======
synchronized (activeNotifs) {
SimpleArrayMap<String, Collection<DownloadBatch>> clusters = getClustersByNotificationTag(batches);
>>>>>>>
synchronized (activeNotifications) {
SimpleArrayMap<String, Collection<DownloadBatch>> clusters = getClustersByNotificationTag(batches);
<<<<<<<
if (activeNotifications.containsKey(tag)) {
firstShown = activeNotifications.get(tag);
=======
if (activeNotifs.containsKey(tag)) {
firstShown = activeNotifs.get(tag);
>>>>>>>
if (activeNotifications.containsKey(tag)) {
firstShown = activeNotifs.get(tag);
<<<<<<<
activeNotifications.put(tag, firstShown);
=======
activeNotifs.put(tag, firstShown);
>>>>>>>
activeNotifications.put(tag, firstShown);
<<<<<<<
private void removeStaleTagsThatWereNotRenewed(Map<String, Collection<DownloadBatch>> clustered) {
final Iterator<String> tags = activeNotifications.keySet().iterator();
while (tags.hasNext()) {
final String tag = tags.next();
=======
private void removeStaleTagsThatWereNotRenewed(SimpleArrayMap<String, Collection<DownloadBatch>> clustered) {
for (int i = 0, size = activeNotifs.size(); i < size; i++) {
String tag = activeNotifs.keyAt(i);
>>>>>>>
private void removeStaleTagsThatWereNotRenewed(SimpleArrayMap<String, Collection<DownloadBatch>> clustered) {
for (int i = 0, size = activeNotifications.size(); i < size; i++) {
String tag = activeNotifications.keyAt(i);
<<<<<<<
notificationManager.cancel(tag.hashCode());
tags.remove();
=======
mNotifManager.cancel(tag.hashCode());
activeNotifs.removeAt(i);
>>>>>>>
notificationManager.cancel(tag.hashCode());
activeNotifications.removeAt(i); |
<<<<<<<
/**
* columns to request from DownloadProvider.
*/
public static final String[] DOWNLOAD_BY_BATCH_VIEW_COLUMNS = new String[]{
DownloadContract.Downloads.DOWNLOADS_TABLE_NAME + "." + DownloadContract.Downloads._ID + " AS _id ",
DownloadContract.Downloads.COLUMN_DATA,
DownloadContract.Downloads.COLUMN_MEDIAPROVIDER_URI,
DownloadContract.Downloads.COLUMN_DESTINATION,
DownloadContract.Downloads.COLUMN_URI,
DownloadContract.Downloads.COLUMN_STATUS,
DownloadContract.Downloads.DOWNLOADS_TABLE_NAME + "." + DownloadContract.Downloads.COLUMN_DELETED,
DownloadContract.Downloads.COLUMN_FILE_NAME_HINT,
DownloadContract.Downloads.COLUMN_MIME_TYPE,
DownloadContract.Downloads.COLUMN_TOTAL_BYTES,
DownloadContract.Downloads.COLUMN_LAST_MODIFICATION,
DownloadContract.Downloads.COLUMN_CURRENT_BYTES,
DownloadContract.Downloads.COLUMN_NOTIFICATION_EXTRAS,
DownloadContract.Downloads.COLUMN_EXTRA_DATA,
DownloadContract.Downloads.COLUMN_BATCH_ID,
DownloadContract.Batches.COLUMN_TITLE,
DownloadContract.Batches.COLUMN_DESCRIPTION,
DownloadContract.Batches.COLUMN_BIG_PICTURE,
DownloadContract.Batches.COLUMN_VISIBILITY,
DownloadContract.Batches.COLUMN_STATUS,
DownloadContract.BatchesWithSizes.VIEW_NAME_BATCHES_WITH_SIZES + "." + DownloadContract.Batches.COLUMN_DELETED,
DownloadContract.BatchesWithSizes.COLUMN_TOTAL_BYTES,
DownloadContract.BatchesWithSizes.COLUMN_CURRENT_BYTES
};
=======
private void createDownloadsWithoutProgressView(SQLiteDatabase db) {
db.execSQL("DROP VIEW IF EXISTS " + DownloadContract.DownloadsWithoutProgress.VIEW_NAME_DOWNLOADS_WITHOUT_PROGRESS);
db.execSQL(
"CREATE VIEW " + DownloadContract.DownloadsWithoutProgress.VIEW_NAME_DOWNLOADS_WITHOUT_PROGRESS
+ " AS SELECT DISTINCT "
+ projectionFrom(DOWNLOADS_WITHOUT_PROGRESS_VIEW_COLUMNS)
+ " FROM " + DownloadContract.Downloads.DOWNLOADS_TABLE_NAME
+ " INNER JOIN " + DownloadContract.Batches.BATCHES_TABLE_NAME
+ " ON " + DownloadContract.Downloads.DOWNLOADS_TABLE_NAME + "." + DownloadContract.Downloads.COLUMN_BATCH_ID
+ " = " + DownloadContract.Batches.BATCHES_TABLE_NAME + "." + DownloadContract.Batches._ID + ";"
);
}
private void createBatchesWithoutProgressView(SQLiteDatabase db) {
db.execSQL("DROP VIEW IF EXISTS " + DownloadContract.BatchesWithoutProgress.VIEW_NAME_BATCHES_WITHOUT_PROGRESS);
db.execSQL(
"CREATE VIEW " + DownloadContract.BatchesWithoutProgress.VIEW_NAME_BATCHES_WITHOUT_PROGRESS
+ " AS SELECT DISTINCT "
+ projectionFrom(BATCHES_WITHOUT_PROGRESS_VIEW_COLUMNS)
+ " FROM " + DownloadContract.Batches.BATCHES_TABLE_NAME
+ ";"
);
}
>>>>>>>
private void createDownloadsWithoutProgressView(SQLiteDatabase db) {
db.execSQL("DROP VIEW IF EXISTS " + DownloadContract.DownloadsWithoutProgress.VIEW_NAME_DOWNLOADS_WITHOUT_PROGRESS);
db.execSQL(
"CREATE VIEW " + DownloadContract.DownloadsWithoutProgress.VIEW_NAME_DOWNLOADS_WITHOUT_PROGRESS
+ " AS SELECT DISTINCT "
+ projectionFrom(DOWNLOADS_WITHOUT_PROGRESS_VIEW_COLUMNS)
+ " FROM " + DownloadContract.Downloads.DOWNLOADS_TABLE_NAME
+ " INNER JOIN " + DownloadContract.Batches.BATCHES_TABLE_NAME
+ " ON " + DownloadContract.Downloads.DOWNLOADS_TABLE_NAME + "." + DownloadContract.Downloads.COLUMN_BATCH_ID
+ " = " + DownloadContract.Batches.BATCHES_TABLE_NAME + "." + DownloadContract.Batches._ID + ";"
);
}
private void createBatchesWithoutProgressView(SQLiteDatabase db) {
db.execSQL("DROP VIEW IF EXISTS " + DownloadContract.BatchesWithoutProgress.VIEW_NAME_BATCHES_WITHOUT_PROGRESS);
db.execSQL(
"CREATE VIEW " + DownloadContract.BatchesWithoutProgress.VIEW_NAME_BATCHES_WITHOUT_PROGRESS
+ " AS SELECT DISTINCT "
+ projectionFrom(BATCHES_WITHOUT_PROGRESS_VIEW_COLUMNS)
+ " FROM " + DownloadContract.Batches.BATCHES_TABLE_NAME
+ ";"
);
}
/**
* columns to request from DownloadProvider.
*/
public static final String[] DOWNLOAD_BY_BATCH_VIEW_COLUMNS = new String[]{
DownloadContract.Downloads.DOWNLOADS_TABLE_NAME + "." + DownloadContract.Downloads._ID + " AS _id ",
DownloadContract.Downloads.COLUMN_DATA,
DownloadContract.Downloads.COLUMN_MEDIAPROVIDER_URI,
DownloadContract.Downloads.COLUMN_DESTINATION,
DownloadContract.Downloads.COLUMN_URI,
DownloadContract.Downloads.COLUMN_STATUS,
DownloadContract.Downloads.DOWNLOADS_TABLE_NAME + "." + DownloadContract.Downloads.COLUMN_DELETED,
DownloadContract.Downloads.COLUMN_FILE_NAME_HINT,
DownloadContract.Downloads.COLUMN_MIME_TYPE,
DownloadContract.Downloads.COLUMN_TOTAL_BYTES,
DownloadContract.Downloads.COLUMN_LAST_MODIFICATION,
DownloadContract.Downloads.COLUMN_CURRENT_BYTES,
DownloadContract.Downloads.COLUMN_NOTIFICATION_EXTRAS,
DownloadContract.Downloads.COLUMN_EXTRA_DATA,
DownloadContract.Downloads.COLUMN_BATCH_ID,
DownloadContract.Batches.COLUMN_TITLE,
DownloadContract.Batches.COLUMN_DESCRIPTION,
DownloadContract.Batches.COLUMN_BIG_PICTURE,
DownloadContract.Batches.COLUMN_VISIBILITY,
DownloadContract.Batches.COLUMN_STATUS,
DownloadContract.BatchesWithSizes.VIEW_NAME_BATCHES_WITH_SIZES + "." + DownloadContract.Batches.COLUMN_DELETED,
DownloadContract.BatchesWithSizes.COLUMN_TOTAL_BYTES,
DownloadContract.BatchesWithSizes.COLUMN_CURRENT_BYTES
}; |
<<<<<<<
request.setBigPictureUrl(BBC_COMEDY_IMAGE);
request.setTitle("BBC Innuendo Bingo");
request.setDescription("Nothing to do with beards.");
request.setMimeType("audio/mp3");
request.setExtra("req_1");
=======
>>>>>>>
request.setExtra("req_1"); |
<<<<<<<
private final Context mContext;
private final Downloads downloads;
public StorageManager(Context context, Downloads downloads) {
mContext = context;
this.downloads = downloads;
mDownloadDataDir = getDownloadDataDirectory(context);
mExternalStorageDir = Environment.getExternalStorageDirectory();
mInternalStorageDir = Environment.getDataDirectory();
mSystemCacheDir = Environment.getDownloadCacheDirectory();
=======
private final ContentResolver contentResolver;
StorageManager(ContentResolver contentResolver, File externalStorageDir, File internalStorageDir, File systemCacheDir, File downloadDataDir) {
this.contentResolver = contentResolver;
this.externalStorageDir = externalStorageDir;
this.internalStorageDir = internalStorageDir;
this.systemCacheDir = systemCacheDir;
this.downloadDataDir = downloadDataDir;
>>>>>>>
private final ContentResolver contentResolver;
private final Downloads downloads;
StorageManager(
ContentResolver contentResolver,
File externalStorageDir,
File internalStorageDir,
File systemCacheDir,
File downloadDataDir,
Downloads downloads) {
this.contentResolver = contentResolver;
this.externalStorageDir = externalStorageDir;
this.internalStorageDir = internalStorageDir;
this.systemCacheDir = systemCacheDir;
this.downloadDataDir = downloadDataDir;
this.downloads = downloads;
<<<<<<<
Cursor cursor = mContext.getContentResolver().query(
downloads.getAllDownloadsContentUri(),
=======
Cursor cursor = contentResolver.query(
Downloads.Impl.ALL_DOWNLOADS_CONTENT_URI,
>>>>>>>
Cursor cursor = contentResolver.query(
downloads.getAllDownloadsContentUri(),
<<<<<<<
mContext.getContentResolver().delete(ContentUris.withAppendedId(downloads.getAllDownloadsContentUri(), id), null, null);
=======
contentResolver.delete(ContentUris.withAppendedId(Downloads.Impl.ALL_DOWNLOADS_CONTENT_URI, id), null, null);
>>>>>>>
contentResolver.delete(ContentUris.withAppendedId(downloads.getAllDownloadsContentUri(), id), null, null);
<<<<<<<
Cursor cursor = mContext.getContentResolver()
.query(downloads.getAllDownloadsContentUri(), new String[]{Downloads.Impl._DATA}, null, null, null);
=======
Cursor cursor = contentResolver
.query(Downloads.Impl.ALL_DOWNLOADS_CONTENT_URI, new String[]{Downloads.Impl._DATA}, null, null, null);
>>>>>>>
Cursor cursor = contentResolver
.query(downloads.getAllDownloadsContentUri(), new String[]{Downloads.Impl._DATA}, null, null, null);
<<<<<<<
cursor = mContext.getContentResolver().query(
downloads.getAllDownloadsContentUri(),
=======
cursor = contentResolver.query(Downloads.Impl.ALL_DOWNLOADS_CONTENT_URI,
>>>>>>>
cursor = contentResolver.query(downloads.getAllDownloadsContentUri(),
<<<<<<<
downloads.getAllDownloadsContentUri(), cursor.getLong(columnId));
mContext.getContentResolver().delete(downloadUri, null, null);
=======
Downloads.Impl.ALL_DOWNLOADS_CONTENT_URI, cursor.getLong(columnId));
contentResolver.delete(downloadUri, null, null);
>>>>>>>
downloads.getAllDownloadsContentUri(), cursor.getLong(columnId));
contentResolver.delete(downloadUri, null, null); |
<<<<<<<
private static final String EXTRA_EXTRA = "com.novoda.download.lib.KEY_INTENT_EXTRA";
=======
public static final String EXTRA_EXTRA = "com.novoda.download.lib.KEY_INTENT_EXTRA";
>>>>>>>
public static final String EXTRA_EXTRA = "com.novoda.download.lib.KEY_INTENT_EXTRA";
<<<<<<<
private long id;
private String uri;
private boolean scannable;
private boolean noIntegrity;
private String hint;
private String fileName;
private String mimeType;
private int destination;
private int control;
private int status;
private int numFailed;
private int retryAfter;
private long lastMod;
private String notificationClassName;
private String extras;
private String cookies;
private String userAgent;
private String referer;
private long totalBytes;
private long currentBytes;
private String eTag;
private int uid;
private int mediaScanned;
private boolean deleted;
private String mediaProviderUri;
private int allowedNetworkTypes;
private boolean allowRoaming;
private boolean allowMetered;
private int bypassRecommendedSizeLimit;
private long batchId;
=======
public long mId;
public String mUri;
/**
* Add to check if scannable i.e. we don't want internal files to be scanned
*/
public boolean mScannable;
public boolean mNoIntegrity;
public String mHint;
public String mFileName;
public String mMimeType;
public int mDestination;
public int mVisibility;
public int mControl;
public int mStatus;
public int mNumFailed;
public int mRetryAfter;
public long mLastMod;
public String mClass;
public String mExtras;
public String mCookies;
public String mUserAgent;
public String mReferer;
public long mTotalBytes;
public long mCurrentBytes;
public String mETag;
public int mUid;
public int mMediaScanned;
public boolean mDeleted;
public String mMediaProviderUri;
public int mAllowedNetworkTypes;
public boolean mAllowRoaming;
public boolean mAllowMetered;
public int mBypassRecommendedSizeLimit;
private long batchId;
private List<Pair<String, String>> mRequestHeaders = new ArrayList<Pair<String, String>>();
>>>>>>>
private long id;
private String uri;
private boolean scannable;
private boolean noIntegrity;
private String hint;
private String fileName;
private String mimeType;
private int destination;
private int control;
private int status;
private int numFailed;
private int retryAfter;
private long lastMod;
private String notificationClassName;
private String extras;
private String cookies;
private String userAgent;
private String referer;
private long totalBytes;
private long currentBytes;
private String eTag;
private int uid;
private int mediaScanned;
private boolean deleted;
private String mediaProviderUri;
private int allowedNetworkTypes;
private boolean allowRoaming;
private boolean allowMetered;
private int bypassRecommendedSizeLimit;
private long batchId;
<<<<<<<
public long getId() {
return id;
}
public String getUri() {
return uri;
}
public boolean isNoIntegrity() {
return noIntegrity;
}
public String getHint() {
return hint;
}
public String getFileName() {
return fileName;
}
public void setFileName(String fileName) {
this.fileName = fileName;
}
public String getMimeType() {
return mimeType;
}
public int getDestination() {
return destination;
}
public int getControl() {
return control;
}
public int getStatus() {
return status;
}
public void setStatus(int status) {
this.status = status;
}
public int getNumFailed() {
return numFailed;
}
public String getNotificationClassName() {
return notificationClassName;
}
public String getUserAgent() {
return userAgent;
}
public long getTotalBytes() {
return totalBytes;
}
public void setTotalBytes(long totalBytes) {
this.totalBytes = totalBytes;
}
public long getCurrentBytes() {
return currentBytes;
}
public String getETag() {
return eTag;
}
public boolean isDeleted() {
return deleted;
}
public String getMediaProviderUri() {
return mediaProviderUri;
}
public long getBatchId() {
return batchId;
}
=======
public long getBatchId() {
return batchId;
}
>>>>>>>
public long getId() {
return id;
}
public String getUri() {
return uri;
}
public boolean isNoIntegrity() {
return noIntegrity;
}
public String getHint() {
return hint;
}
public String getFileName() {
return fileName;
}
public void setFileName(String fileName) {
this.fileName = fileName;
}
public String getMimeType() {
return mimeType;
}
public int getDestination() {
return destination;
}
public int getControl() {
return control;
}
public int getStatus() {
return status;
}
public void setStatus(int status) {
this.status = status;
}
public int getNumFailed() {
return numFailed;
}
public String getNotificationClassName() {
return notificationClassName;
}
public String getUserAgent() {
return userAgent;
}
public long getTotalBytes() {
return totalBytes;
}
public void setTotalBytes(long totalBytes) {
this.totalBytes = totalBytes;
}
public long getCurrentBytes() {
return currentBytes;
}
public String getETag() {
return eTag;
}
public boolean isDeleted() {
return deleted;
}
public String getMediaProviderUri() {
return mediaProviderUri;
}
public long getBatchId() {
return batchId;
}
<<<<<<<
if (submittedThread == null || submittedThread.isDone()) {
String applicationPackageName = context.getApplicationContext().getPackageName();
BatchCompletionBroadcaster batchCompletionBroadcaster = new BatchCompletionBroadcaster(context, applicationPackageName);
ContentResolver contentResolver = context.getContentResolver();
BatchRepository batchRepository = new BatchRepository(contentResolver, new DownloadDeleter(contentResolver));
DownloadThread downloadThread = new DownloadThread(context, systemFacade, this, storageManager, downloadNotifier,
=======
if (mSubmittedTask == null || mSubmittedTask.isDone()) {
BatchCompletionBroadcaster batchCompletionBroadcaster = BatchCompletionBroadcaster.newInstance(mContext);
ContentResolver contentResolver = mContext.getContentResolver();
BatchRepository batchRepository = BatchRepository.newInstance(contentResolver, new DownloadDeleter(contentResolver));
DownloadThread downloadThread = new DownloadThread(mContext, mSystemFacade, this, mStorageManager, mNotifier,
>>>>>>>
if (submittedThread == null || submittedThread.isDone()) {
String applicationPackageName = context.getApplicationContext().getPackageName();
BatchCompletionBroadcaster batchCompletionBroadcaster = new BatchCompletionBroadcaster(context, applicationPackageName);
ContentResolver contentResolver = context.getContentResolver();
BatchRepository batchRepository = BatchRepository.newInstance(contentResolver, new DownloadDeleter(contentResolver));
DownloadThread downloadThread = new DownloadThread(context, systemFacade, this, storageManager, downloadNotifier, |
<<<<<<<
public void updateWith(List<DownloadBatch> batches) {
synchronized (activeNotifications) {
Map<String, List<DownloadBatch>> clusters = getClustersByNotificationTag(batches);
=======
public void updateWith(Collection<DownloadBatch> batches) {
synchronized (mActiveNotifs) {
Map<String, Collection<DownloadBatch>> clusters = getClustersByNotificationTag(batches);
>>>>>>>
public void updateWith(Collection<DownloadBatch> batches) {
synchronized (activeNotifications) {
Map<String, Collection<DownloadBatch>> clusters = getClustersByNotificationTag(batches);
<<<<<<<
Set<DownloadBatch> currentBatches = new HashSet<>(cluster.size());
=======
List<DownloadBatch> currentBatches = new ArrayList<>();
>>>>>>>
List<DownloadBatch> currentBatches = new ArrayList<>(cluster.size());
<<<<<<<
private void removeStaleTagsThatWereNotRenewed(Map<String, List<DownloadBatch>> clustered) {
final Iterator<String> tags = activeNotifications.keySet().iterator();
=======
private void removeStaleTagsThatWereNotRenewed(Map<String, Collection<DownloadBatch>> clustered) {
final Iterator<String> tags = mActiveNotifs.keySet().iterator();
>>>>>>>
private void removeStaleTagsThatWereNotRenewed(Map<String, Collection<DownloadBatch>> clustered) {
final Iterator<String> tags = activeNotifications.keySet().iterator();
<<<<<<<
private long[] getDownloadIds(List<DownloadBatch> batches) {
List<Long> ids = new ArrayList<>(batches.size() * 3);
=======
private long[] getDownloadIds(Collection<DownloadBatch> batches) {
List<Long> ids = new ArrayList<>();
>>>>>>>
private long[] getDownloadIds(Collection<DownloadBatch> batches) {
List<Long> ids = new ArrayList<>(batches.size()); |
<<<<<<<
import android.os.Handler;
=======
import android.os.IBinder;
>>>>>>>
<<<<<<<
=======
private final ServiceConnection migrationServiceConnection = new ServiceConnection() {
@Override
public void onServiceConnected(ComponentName componentName, IBinder iBinder) {
((LiteDownloadMigrationService.MigrationDownloadServiceBinder) iBinder)
.migrate();
}
@Override
public void onServiceDisconnected(ComponentName componentName) {
// TODO
}
};
private TextView databaseCloningUpdates;
>>>>>>>
private TextView databaseCloningUpdates; |
<<<<<<<
callbackHandler,
new HashMap<DownloadBatchId, DownloadBatch>(),
=======
new HashMap<>(),
>>>>>>>
callbackHandler,
new HashMap<>(), |
<<<<<<<
Logger.v("start download " + rawBatchId + ", status: " + downloadBatchStatus.status());
=======
Log.v("start sync download " + rawBatchId + ", " + STATUS + " " + downloadBatchStatus.status());
>>>>>>>
Logger.v("start sync download " + rawBatchId + ", " + STATUS + " " + downloadBatchStatus.status());
<<<<<<<
Logger.v("abort starting download " + rawBatchId);
=======
Log.v("abort starting download " + rawBatchId + ", " + STATUS + " " + downloadBatchStatus.status());
>>>>>>>
Logger.v("abort starting download " + rawBatchId + ", " + STATUS + " " + downloadBatchStatus.status());
<<<<<<<
Logger.v("abort after getting total batch size download " + rawBatchId);
=======
Log.v("abort after getting total batch size download " + rawBatchId + ", " + STATUS + " " + downloadBatchStatus.status());
>>>>>>>
Logger.v("abort after getting total batch size download " + rawBatchId + ", " + STATUS + " " + downloadBatchStatus.status());
<<<<<<<
Logger.v("end download " + rawBatchId);
=======
Log.v("end sync download " + rawBatchId);
>>>>>>>
Logger.v("end sync download " + rawBatchId);
<<<<<<<
Logger.v("batch id: " + downloadBatchStatus.getDownloadBatchId().rawId() + ", status: " + status + ", file: " + downloadFile.id().rawId());
=======
>>>>>>>
<<<<<<<
Logger.v("pause batch " + downloadBatchStatus.getDownloadBatchId().rawId() + ", status: " + downloadBatchStatus.status());
=======
Log.v("pause batch " + downloadBatchStatus.getDownloadBatchId().rawId() + ", " + STATUS + " " + downloadBatchStatus.status());
>>>>>>>
Logger.v("pause batch " + downloadBatchStatus.getDownloadBatchId().rawId() + ", " + STATUS + " " + downloadBatchStatus.status());
<<<<<<<
Logger.v("delete batch " + downloadBatchStatus.getDownloadBatchId().rawId() + ", mark as deleting from " + downloadBatchStatus.status());
=======
Log.v("delete request for batch " + downloadBatchStatus.getDownloadBatchId().rawId() + ", mark as deleting from " + downloadBatchStatus.status());
>>>>>>>
<<<<<<<
Logger.v("delete paused or downloaded batch " + downloadBatchStatus.getDownloadBatchId().rawId());
=======
Log.v("delete async paused or downloaded batch " + downloadBatchStatus.getDownloadBatchId().rawId());
>>>>>>>
Logger.v("delete async paused or downloaded batch " + downloadBatchStatus.getDownloadBatchId().rawId()); |
<<<<<<<
private final Context context;
private final DownloadInfo downloadInfo;
private final SystemFacade systemFacade;
private final StorageManager storageManager;
private final DownloadNotifier downloadNotifier;
=======
private final Context mContext;
private final DownloadInfo mInfo;
private final SystemFacade mSystemFacade;
private final StorageManager mStorageManager;
private final DownloadNotifier mNotifier;
private final BatchCompletionBroadcaster batchCompletionBroadcaster;
>>>>>>>
private final Context context;
private final DownloadInfo downloadInfo;
private final SystemFacade systemFacade;
private final StorageManager storageManager;
private final DownloadNotifier downloadNotifier;
private final BatchCompletionBroadcaster batchCompletionBroadcaster;
<<<<<<<
public DownloadThread(Context context, SystemFacade systemFacade, DownloadInfo downloadInfo,
StorageManager storageManager, DownloadNotifier downloadNotifier, BatchStatusRepository batchStatusRepository) {
this.context = context;
this.systemFacade = systemFacade;
this.downloadInfo = downloadInfo;
this.storageManager = storageManager;
this.downloadNotifier = downloadNotifier;
=======
public DownloadThread(Context context, SystemFacade systemFacade, DownloadInfo info,
StorageManager storageManager, DownloadNotifier notifier,
BatchCompletionBroadcaster batchCompletionBroadcaster, BatchStatusRepository batchStatusRepository) {
mContext = context;
mSystemFacade = systemFacade;
mInfo = info;
mStorageManager = storageManager;
mNotifier = notifier;
this.batchCompletionBroadcaster = batchCompletionBroadcaster;
>>>>>>>
public DownloadThread(Context context, SystemFacade systemFacade, DownloadInfo downloadInfo,
StorageManager storageManager, DownloadNotifier downloadNotifier,
BatchCompletionBroadcaster batchCompletionBroadcaster, BatchStatusRepository batchStatusRepository) {
this.context = context;
this.systemFacade = systemFacade;
this.downloadInfo = downloadInfo;
this.storageManager = storageManager;
this.downloadNotifier = downloadNotifier;
this.batchCompletionBroadcaster = batchCompletionBroadcaster; |
<<<<<<<
=======
/**
* The Service's view of the list of downloads, mapping download IDs to the corresponding info
* object. This is kept independently from the content provider, and the Service only initiates
* downloads based on this data, so that it can deal with situation where the data in the
* content provider changes or disappears.
*/
// @GuardedBy("downloads")
private final Map<Long, FileDownloadInfo> downloads = new HashMap<>();
>>>>>>>
<<<<<<<
Collection<DownloadInfo> allDownloads = downloadsRepository.getAllDownloads();
updateTotalBytesFor(allDownloads);
List<DownloadBatch> downloadBatches = batchRepository.retrieveBatchesFor(allDownloads);
for (DownloadBatch downloadBatch : downloadBatches) {
=======
Cursor downloadsCursor = getContentResolver().query(Downloads.Impl.ALL_DOWNLOADS_CONTENT_URI, null, null, null, null);
try {
FileDownloadInfo.Reader reader = new FileDownloadInfo.Reader(getContentResolver(), downloadsCursor);
int idColumn = downloadsCursor.getColumnIndexOrThrow(Downloads.Impl._ID);
while (downloadsCursor.moveToNext()) {
long id = downloadsCursor.getLong(idColumn);
staleDownloadIds.remove(id);
FileDownloadInfo info = downloads.get(id);
if (info == null) {
info = createNewDownloadInfo(reader);
downloads.put(info.getId(), info);
} else {
updateDownloadFromDatabase(reader, info);
}
>>>>>>>
Collection<FileDownloadInfo> allDownloads = downloadsRepository.getAllDownloads();
updateTotalBytesFor(allDownloads);
List<DownloadBatch> downloadBatches = batchRepository.retrieveBatchesFor(allDownloads);
for (DownloadBatch downloadBatch : downloadBatches) {
<<<<<<<
}
=======
Collection<FileDownloadInfo> allDownloads = downloads.values();
>>>>>>>
}
<<<<<<<
private void updateTotalBytesFor(Collection<DownloadInfo> downloadInfos) {
ContentValues values = new ContentValues();
for (DownloadInfo downloadInfo : downloadInfos) {
if (downloadInfo.getTotalBytes() == -1) {
long totalBytes = contentLengthFetcher.fetchContentLengthFor(downloadInfo);
values.put(Downloads.Impl.COLUMN_TOTAL_BYTES, totalBytes);
getContentResolver().update(downloadInfo.getAllDownloadsUri(), values, null, null);
batchRepository.updateCurrentSize(downloadInfo.getBatchId());
batchRepository.updateTotalSize(downloadInfo.getBatchId());
}
=======
private void updateTotalBytesFor(FileDownloadInfo info) {
if (!info.hasTotalBytes()) {
ContentValues values = new ContentValues();
info.setTotalBytes(contentLengthFetcher.fetchContentLengthFor(info));
values.put(Downloads.Impl.COLUMN_TOTAL_BYTES, info.getTotalBytes());
getContentResolver().update(info.getAllDownloadsUri(), values, null, null);
>>>>>>>
private void updateTotalBytesFor(Collection<FileDownloadInfo> downloadInfos) {
ContentValues values = new ContentValues();
for (FileDownloadInfo downloadInfo : downloadInfos) {
if (downloadInfo.getTotalBytes() == -1) {
long totalBytes = contentLengthFetcher.fetchContentLengthFor(downloadInfo);
values.put(Downloads.Impl.COLUMN_TOTAL_BYTES, totalBytes);
getContentResolver().update(downloadInfo.getAllDownloadsUri(), values, null, null);
batchRepository.updateCurrentSize(downloadInfo.getBatchId());
batchRepository.updateTotalSize(downloadInfo.getBatchId());
}
<<<<<<<
=======
/**
* Keeps a local copy of the info about a download, and initiates the
* download if appropriate.
*/
private FileDownloadInfo createNewDownloadInfo(FileDownloadInfo.Reader reader) {
FileDownloadInfo info = reader.newDownloadInfo(this, systemFacade, downloadClientReadyChecker);
Log.v("processing inserted download " + info.getId());
return info;
}
/**
* Updates the local copy of the info about a download.
*/
private void updateDownloadFromDatabase(FileDownloadInfo.Reader reader, FileDownloadInfo info) {
reader.updateFromDatabase(info);
Log.v("processing updated download " + info.getId() + ", status: " + info.getStatus());
}
>>>>>>> |
<<<<<<<
if (systemFacade == null) {
systemFacade = new RealSystemFacade(this);
=======
this.downloadDeleter = new DownloadDeleter(getContentResolver());
this.batchRepository = new BatchRepository(getContentResolver(), downloadDeleter);
if (mSystemFacade == null) {
mSystemFacade = new RealSystemFacade(this);
>>>>>>>
this.downloadDeleter = new DownloadDeleter(getContentResolver());
this.batchRepository = new BatchRepository(getContentResolver(), downloadDeleter);
if (systemFacade == null) {
systemFacade = new RealSystemFacade(this);
<<<<<<<
executor = factory.createExecutor();
resolver = getContentResolver();
=======
mExecutor = factory.createExecutor();
>>>>>>>
executor = factory.createExecutor();
<<<<<<<
if (info.isDeleted()) {
deleteFileAndDatabaseRow(info);
} else if (Downloads.Impl.isStatusCancelled(info.getStatus()) || Downloads.Impl.isStatusError(info.getStatus())) {
deleteFileAndMediaReference(info);
=======
if (info.mDeleted) {
downloadDeleter.deleteFileAndDatabaseRow(info);
} else if (Downloads.Impl.isStatusCancelled(info.mStatus) || Downloads.Impl.isStatusError(info.mStatus)) {
downloadDeleter.deleteFileAndMediaReference(info);
>>>>>>>
if (info.isDeleted()) {
downloadDeleter.deleteFileAndDatabaseRow(info);
} else if (Downloads.Impl.isStatusCancelled(info.getStatus()) || Downloads.Impl.isStatusError(info.getStatus())) {
downloadDeleter.deleteFileAndMediaReference(info);
<<<<<<<
private List<DownloadBatch> fetchBatches(Collection<DownloadInfo> downloads) {
Cursor batchesCursor = resolver.query(Downloads.Impl.BATCH_CONTENT_URI, null, null, null, null);
List<DownloadBatch> batches = new ArrayList<>(batchesCursor.getCount());
List<Long> forDeletion = new ArrayList<>();
try {
int idColumn = batchesCursor.getColumnIndexOrThrow(Downloads.Impl.Batches._ID);
int deleteIndex = batchesCursor.getColumnIndex(Downloads.Impl.Batches.COLUMN_DELETED);
int titleIndex = batchesCursor.getColumnIndexOrThrow(Downloads.Impl.Batches.COLUMN_TITLE);
int descriptionIndex = batchesCursor.getColumnIndexOrThrow(Downloads.Impl.Batches.COLUMN_DESCRIPTION);
int bigPictureUrlIndex = batchesCursor.getColumnIndexOrThrow(Downloads.Impl.Batches.COLUMN_BIG_PICTURE);
int statusIndex = batchesCursor.getColumnIndexOrThrow(Downloads.Impl.Batches.COLUMN_STATUS);
int visibilityColumn = batchesCursor.getColumnIndexOrThrow(Downloads.Impl.Batches.COLUMN_VISIBILITY);
while (batchesCursor.moveToNext()) {
long id = batchesCursor.getLong(idColumn);
if (batchesCursor.getInt(deleteIndex) == 1) {
forDeletion.add(id);
continue;
}
String title = batchesCursor.getString(titleIndex);
String description = batchesCursor.getString(descriptionIndex);
String bigPictureUrl = batchesCursor.getString(bigPictureUrlIndex);
int status = batchesCursor.getInt(statusIndex);
@NotificationVisibility.Value int visibility = batchesCursor.getInt(visibilityColumn);
BatchInfo batchInfo = new BatchInfo(title, description, bigPictureUrl, visibility);
List<DownloadInfo> batchDownloads = new ArrayList<>(1);
for (DownloadInfo downloadInfo : downloads) {
if (downloadInfo.getBatchId() == id) {
batchDownloads.add(downloadInfo);
}
}
batches.add(new DownloadBatch(id, batchInfo, batchDownloads, status));
}
} finally {
batchesCursor.close();
}
if (!forDeletion.isEmpty()) {
deleteBatchesForIds(forDeletion, downloads);
}
return batches;
}
private void deleteBatchesForIds(List<Long> ids, Collection<DownloadInfo> downloads) {
for (DownloadInfo download : downloads) {
if (ids.contains(download.getBatchId())) {
deleteFileAndDatabaseRow(download);
}
}
String selection = TextUtils.join(", ", ids);
String[] selectionArgs = {selection};
resolver.delete(Downloads.Impl.BATCH_CONTENT_URI, Downloads.Impl.Batches._ID + " IN (?)", selectionArgs);
}
=======
>>>>>>>
<<<<<<<
private void cleanUpStaleDownloadsThatDisappeared(Set<Long> staleIds, Map<Long, DownloadInfo> downloads) {
for (Long id : staleIds) {
deleteDownloadLocked(id, downloads);
}
}
private void updateUserVisibleNotification(List<DownloadBatch> batches) {
downloadNotifier.updateWith(batches);
=======
private void updateUserVisibleNotification(Collection<DownloadBatch> batches) {
mNotifier.updateWith(batches);
>>>>>>>
private void updateUserVisibleNotification(Collection<DownloadBatch> batches) {
downloadNotifier.updateWith(batches);
<<<<<<<
/**
* Removes the local copy of the info about a download.
*/
private void deleteDownloadLocked(long id, Map<Long, DownloadInfo> downloads) {
DownloadInfo info = downloads.get(id);
if (info.getStatus() == Downloads.Impl.STATUS_RUNNING) {
info.setStatus(Downloads.Impl.STATUS_CANCELED);
}
if (info.getDestination() != Downloads.Impl.DESTINATION_EXTERNAL && info.getFileName() != null) {
Log.d("deleteDownloadLocked() deleting " + info.getFileName());
deleteFileIfExists(info.getFileName());
}
downloads.remove(info.getId());
}
private void deleteFileIfExists(String path) {
if (!TextUtils.isEmpty(path)) {
Log.d("deleteFileIfExists() deleting " + path);
final File file = new File(path);
if (file.exists() && !file.delete()) {
Log.w("file: '" + path + "' couldn't be deleted");
}
}
}
=======
>>>>>>> |
<<<<<<<
String result = runS(cmdl);
=======
result = runS(cmdl, getFailOnErr());
// System.out.println( "lsCheckout: " + result );
>>>>>>>
String result = runS(cmdl, getFailOnErr()); |
<<<<<<<
import static com.novoda.downloadmanager.lib.DownloadsStatus.STATUS_HTTP_DATA_ERROR;
import static com.novoda.downloadmanager.lib.FileDownloadInfo.NetworkState;
=======
import static com.novoda.downloadmanager.lib.Downloads.Impl.*;
import static com.novoda.downloadmanager.lib.FileDownloadInfo.NetworkState;
>>>>>>>
import static com.novoda.downloadmanager.lib.DownloadsStatus.STATUS_HTTP_DATA_ERROR;
import static com.novoda.downloadmanager.lib.FileDownloadInfo.NetworkState;
<<<<<<<
private final DownloadsUriProvider downloadsUriProvider;
=======
private final DownloadsRepository downloadsRepository;
>>>>>>>
private final DownloadsUriProvider downloadsUriProvider;
private final DownloadsRepository downloadsRepository;
<<<<<<<
public DownloadThread(Context context,
SystemFacade systemFacade,
FileDownloadInfo fileDownloadInfo,
StorageManager storageManager,
DownloadNotifier downloadNotifier,
BatchCompletionBroadcaster batchCompletionBroadcaster,
BatchRepository batchRepository,
DownloadsUriProvider downloadsUriProvider) {
=======
public DownloadThread(Context context, SystemFacade systemFacade, FileDownloadInfo originalDownloadInfo,
StorageManager storageManager, DownloadNotifier downloadNotifier,
BatchCompletionBroadcaster batchCompletionBroadcaster, BatchRepository batchRepository,
DownloadsRepository downloadsRepository) {
>>>>>>>
public DownloadThread(Context context,
SystemFacade systemFacade,
FileDownloadInfo originalDownloadInfo,
StorageManager storageManager,
DownloadNotifier downloadNotifier,
BatchCompletionBroadcaster batchCompletionBroadcaster,
BatchRepository batchRepository,
DownloadsUriProvider downloadsUriProvider,
DownloadsRepository downloadsRepository) {
<<<<<<<
this.downloadsUriProvider = downloadsUriProvider;
=======
this.downloadsRepository = downloadsRepository;
>>>>>>>
this.downloadsUriProvider = downloadsUriProvider;
this.downloadsRepository = downloadsRepository;
<<<<<<<
if (downloadStatus != DownloadsStatus.STATUS_RUNNING) {
fileDownloadInfo.updateStatus(DownloadsStatus.STATUS_RUNNING);
updateBatchStatus(fileDownloadInfo.getBatchId(), fileDownloadInfo.getId());
=======
if (downloadStatus != Downloads.Impl.STATUS_RUNNING) {
originalDownloadInfo.updateStatus(Downloads.Impl.STATUS_RUNNING);
updateBatchStatus(originalDownloadInfo.getBatchId(), originalDownloadInfo.getId());
>>>>>>>
if (downloadStatus != DownloadsStatus.STATUS_RUNNING) {
originalDownloadInfo.updateStatus(DownloadsStatus.STATUS_RUNNING);
updateBatchStatus(originalDownloadInfo.getBatchId(), originalDownloadInfo.getId());
<<<<<<<
int finalStatus = DownloadsStatus.STATUS_UNKNOWN_ERROR;
int numFailed = fileDownloadInfo.getNumFailed();
=======
int finalStatus = STATUS_UNKNOWN_ERROR;
int numFailed = originalDownloadInfo.getNumFailed();
>>>>>>>
int finalStatus = DownloadsStatus.STATUS_UNKNOWN_ERROR;
int numFailed = originalDownloadInfo.getNumFailed();
<<<<<<<
status = DownloadsStatus.STATUS_QUEUED_FOR_WIFI;
fileDownloadInfo.notifyPauseDueToSize(true);
=======
status = Downloads.Impl.STATUS_QUEUED_FOR_WIFI;
originalDownloadInfo.notifyPauseDueToSize(true);
>>>>>>>
status = DownloadsStatus.STATUS_QUEUED_FOR_WIFI;
originalDownloadInfo.notifyPauseDueToSize(true);
<<<<<<<
status = DownloadsStatus.STATUS_QUEUED_FOR_WIFI;
fileDownloadInfo.notifyPauseDueToSize(false);
=======
status = Downloads.Impl.STATUS_QUEUED_FOR_WIFI;
originalDownloadInfo.notifyPauseDueToSize(false);
>>>>>>>
status = DownloadsStatus.STATUS_QUEUED_FOR_WIFI;
originalDownloadInfo.notifyPauseDueToSize(false);
<<<<<<<
synchronized (fileDownloadInfo) {
if (fileDownloadInfo.getControl() == DownloadsControl.CONTROL_PAUSED) {
throw new StopRequestException(DownloadsStatus.STATUS_PAUSED_BY_APP, "download paused by owner");
}
if (fileDownloadInfo.getStatus() == DownloadsStatus.STATUS_CANCELED) {
throw new StopRequestException(DownloadsStatus.STATUS_CANCELED, "download canceled");
}
=======
FileDownloadInfo currentDownloadInfo = downloadsRepository.getDownloadFor(originalDownloadInfo.getId());
if (currentDownloadInfo.getControl() == Downloads.Impl.CONTROL_PAUSED) {
throw new StopRequestException(Downloads.Impl.STATUS_PAUSED_BY_APP, "download paused by owner");
}
if (currentDownloadInfo.getStatus() == Downloads.Impl.STATUS_CANCELED) {
throw new StopRequestException(Downloads.Impl.STATUS_CANCELED, "download canceled");
>>>>>>>
FileDownloadInfo currentDownloadInfo = downloadsRepository.getDownloadFor(originalDownloadInfo.getId());
if (currentDownloadInfo.getControl() == DownloadsControl.CONTROL_PAUSED) {
throw new StopRequestException(DownloadsStatus.STATUS_PAUSED_BY_APP, "download paused by owner");
}
if (currentDownloadInfo.getStatus() == DownloadsStatus.STATUS_CANCELED) {
throw new StopRequestException(DownloadsStatus.STATUS_CANCELED, "download canceled");
<<<<<<<
values.put(DownloadsColumns.COLUMN_CURRENT_BYTES, state.currentBytes);
getContentResolver().update(fileDownloadInfo.getAllDownloadsUri(), values, null, null);
=======
values.put(Downloads.Impl.COLUMN_CURRENT_BYTES, state.currentBytes);
getContentResolver().update(originalDownloadInfo.getAllDownloadsUri(), values, null, null);
>>>>>>>
values.put(DownloadsColumns.COLUMN_CURRENT_BYTES, state.currentBytes);
getContentResolver().update(originalDownloadInfo.getAllDownloadsUri(), values, null, null);
<<<<<<<
values.put(DownloadsColumns.COLUMN_CURRENT_BYTES, state.currentBytes);
getContentResolver().update(fileDownloadInfo.getAllDownloadsUri(), values, null, null);
=======
values.put(Downloads.Impl.COLUMN_CURRENT_BYTES, state.currentBytes);
getContentResolver().update(originalDownloadInfo.getAllDownloadsUri(), values, null, null);
>>>>>>>
values.put(DownloadsColumns.COLUMN_CURRENT_BYTES, state.currentBytes);
getContentResolver().update(originalDownloadInfo.getAllDownloadsUri(), values, null, null);
<<<<<<<
values.put(DownloadsColumns.COLUMN_TOTAL_BYTES, fileDownloadInfo.getTotalBytes());
getContentResolver().update(fileDownloadInfo.getAllDownloadsUri(), values, null, null);
=======
values.put(Downloads.Impl.COLUMN_TOTAL_BYTES, originalDownloadInfo.getTotalBytes());
getContentResolver().update(originalDownloadInfo.getAllDownloadsUri(), values, null, null);
>>>>>>>
values.put(DownloadsColumns.COLUMN_TOTAL_BYTES, originalDownloadInfo.getTotalBytes());
getContentResolver().update(originalDownloadInfo.getAllDownloadsUri(), values, null, null);
<<<<<<<
if (!fileDownloadInfo.isNoIntegrity() && noSizeInfo) {
throw new StopRequestException(DownloadsStatus.STATUS_CANNOT_RESUME, "can't know size of download, giving up");
=======
if (!originalDownloadInfo.isNoIntegrity() && noSizeInfo) {
throw new StopRequestException(STATUS_CANNOT_RESUME, "can't know size of download, giving up");
>>>>>>>
if (!originalDownloadInfo.isNoIntegrity() && noSizeInfo) {
throw new StopRequestException(DownloadsStatus.STATUS_CANNOT_RESUME, "can't know size of download, giving up");
<<<<<<<
if (DownloadsStatus.isStatusCompleted(finalStatus)) {
fileDownloadInfo.broadcastIntentDownloadComplete(finalStatus);
} else if (DownloadsStatus.isStatusInsufficientSpace(finalStatus)) {
fileDownloadInfo.broadcastIntentDownloadFailedInsufficientSpace();
=======
if (Downloads.Impl.isStatusCompleted(finalStatus)) {
originalDownloadInfo.broadcastIntentDownloadComplete(finalStatus);
} else if (Downloads.Impl.isStatusInsufficientSpace(finalStatus)) {
originalDownloadInfo.broadcastIntentDownloadFailedInsufficientSpace();
>>>>>>>
if (DownloadsStatus.isStatusCompleted(finalStatus)) {
originalDownloadInfo.broadcastIntentDownloadComplete(finalStatus);
} else if (DownloadsStatus.isStatusInsufficientSpace(finalStatus)) {
originalDownloadInfo.broadcastIntentDownloadFailedInsufficientSpace();
<<<<<<<
if (!TextUtils.equals(fileDownloadInfo.getUri(), state.requestUri)) {
values.put(DownloadsColumns.COLUMN_URI, state.requestUri);
=======
if (!TextUtils.equals(originalDownloadInfo.getUri(), state.requestUri)) {
values.put(Downloads.Impl.COLUMN_URI, state.requestUri);
>>>>>>>
if (!TextUtils.equals(originalDownloadInfo.getUri(), state.requestUri)) {
values.put(DownloadsColumns.COLUMN_URI, state.requestUri); |
<<<<<<<
public DownloadThread(Context context, SystemFacade systemFacade, FileDownloadInfo originalDownloadInfo,
StorageManager storageManager, DownloadNotifier downloadNotifier,
BatchCompletionBroadcaster batchCompletionBroadcaster, BatchRepository batchRepository,
DownloadsRepository downloadsRepository, NetworkChecker networkChecker,
DownloadReadyChecker downloadReadyChecker) {
=======
public DownloadThread(Context context,
SystemFacade systemFacade,
FileDownloadInfo originalDownloadInfo,
StorageManager storageManager,
DownloadNotifier downloadNotifier,
BatchCompletionBroadcaster batchCompletionBroadcaster,
BatchRepository batchRepository,
DownloadsUriProvider downloadsUriProvider,
DownloadsRepository downloadsRepository) {
>>>>>>>
public DownloadThread(Context context,
SystemFacade systemFacade,
FileDownloadInfo originalDownloadInfo,
StorageManager storageManager,
DownloadNotifier downloadNotifier,
BatchCompletionBroadcaster batchCompletionBroadcaster,
BatchRepository batchRepository,
DownloadsUriProvider downloadsUriProvider,
DownloadsRepository downloadsRepository,
NetworkChecker networkChecker,
DownloadReadyChecker downloadReadyChecker) { |
<<<<<<<
/*
* Copyright (c) 2016 Network New Technologies Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.networknt.schema;
import com.fasterxml.jackson.databind.JsonNode;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.ArrayList;
import java.util.Collections;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Set;
public class ItemsValidator extends BaseJsonValidator implements JsonValidator {
private static final Logger logger = LoggerFactory.getLogger(ItemsValidator.class);
private static final String PROPERTY_ADDITIONAL_ITEMS = "additionalItems";
private JsonSchema schema;
private List<JsonSchema> tupleSchema;
private boolean additionalItems = true;
private JsonSchema additionalSchema;
public ItemsValidator(String schemaPath, JsonNode schemaNode, JsonSchema parentSchema, ValidationContext validationContext) {
super(schemaPath, schemaNode, parentSchema, ValidatorTypeCode.ITEMS, validationContext);
if (schemaNode.isObject()) {
schema = new JsonSchema(validationContext, getValidatorType().getValue(), parentSchema.getCurrentUrl(), schemaNode, parentSchema);
} else {
tupleSchema = new ArrayList<JsonSchema>();
for (JsonNode s : schemaNode) {
tupleSchema.add(new JsonSchema(validationContext, getValidatorType().getValue(), parentSchema.getCurrentUrl(), s, parentSchema));
}
JsonNode addItemNode = getParentSchema().getSchemaNode().get(PROPERTY_ADDITIONAL_ITEMS);
if (addItemNode != null) {
if (addItemNode.isBoolean()) {
additionalItems = addItemNode.asBoolean();
} else if (addItemNode.isObject()) {
additionalSchema = new JsonSchema(validationContext, parentSchema.getCurrentUrl(), addItemNode);
}
}
}
parseErrorCode(getValidatorType().getErrorCodeKey());
}
public Set<ValidationMessage> validate(JsonNode node, JsonNode rootNode, String at) {
debug(logger, node, rootNode, at);
Set<ValidationMessage> errors = new LinkedHashSet<ValidationMessage>();
if (!node.isArray()) {
// ignores non-arrays
return errors;
}
int i = 0;
for (JsonNode n : node) {
if (schema != null) {
// validate with item schema (the whole array has the same item
// schema)
errors.addAll(schema.validate(n, rootNode, at + "[" + i + "]"));
}
if (tupleSchema != null) {
if (i < tupleSchema.size()) {
// validate against tuple schema
errors.addAll(tupleSchema.get(i).validate(n, rootNode, at + "[" + i + "]"));
} else {
if (additionalSchema != null) {
// validate against additional item schema
errors.addAll(additionalSchema.validate(n, rootNode, at + "[" + i + "]"));
} else if (!additionalItems) {
// no additional item allowed, return error
errors.add(buildValidationMessage(at, "" + i));
}
}
}
i++;
}
return Collections.unmodifiableSet(errors);
}
}
=======
/*
* Copyright (c) 2016 Network New Technologies Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.networknt.schema;
import com.fasterxml.jackson.databind.JsonNode;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.ArrayList;
import java.util.Collections;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Set;
public class ItemsValidator extends BaseJsonValidator implements JsonValidator {
private static final Logger logger = LoggerFactory.getLogger(ItemsValidator.class);
private static final String PROPERTY_ADDITIONAL_ITEMS = "additionalItems";
private JsonSchema schema;
private List<JsonSchema> tupleSchema;
private boolean additionalItems = true;
private JsonSchema additionalSchema;
public ItemsValidator(String schemaPath, JsonNode schemaNode, JsonSchema parentSchema, ValidationContext validationContext) {
super(schemaPath, schemaNode, parentSchema, ValidatorTypeCode.ITEMS, validationContext);
if (schemaNode.isObject()) {
schema = new JsonSchema(validationContext, getValidatorType().getValue(), schemaNode, parentSchema);
} else {
tupleSchema = new ArrayList<JsonSchema>();
for (JsonNode s : schemaNode) {
tupleSchema.add(new JsonSchema(validationContext, getValidatorType().getValue(), s, parentSchema));
}
JsonNode addItemNode = getParentSchema().getSchemaNode().get(PROPERTY_ADDITIONAL_ITEMS);
if (addItemNode != null) {
if (addItemNode.isBoolean()) {
additionalItems = addItemNode.asBoolean();
} else if (addItemNode.isObject()) {
additionalSchema = new JsonSchema(validationContext, addItemNode);
}
}
}
parseErrorCode(getValidatorType().getErrorCodeKey());
}
public Set<ValidationMessage> validate(JsonNode node, JsonNode rootNode, String at) {
debug(logger, node, rootNode, at);
Set<ValidationMessage> errors = new LinkedHashSet<ValidationMessage>();
if (!node.isArray() && !config.isTypeLoose()) {
// ignores non-arrays
return errors;
}
if (node.isArray()) {
int i = 0;
for (JsonNode n : node) {
doValidate(errors, i, n, rootNode, at);
i++;
}
} else {
doValidate(errors, 0, node, rootNode, at);
}
return Collections.unmodifiableSet(errors);
}
private void doValidate(Set<ValidationMessage> errors, int i, JsonNode node, JsonNode rootNode, String at) {
if (schema != null) {
// validate with item schema (the whole array has the same item
// schema)
errors.addAll(schema.validate(node, rootNode, at + "[" + i + "]"));
}
if (tupleSchema != null) {
if (i < tupleSchema.size()) {
// validate against tuple schema
errors.addAll(tupleSchema.get(i).validate(node, rootNode, at + "[" + i + "]"));
} else {
if (additionalSchema != null) {
// validate against additional item schema
errors.addAll(additionalSchema.validate(node, rootNode, at + "[" + i + "]"));
} else if (!additionalItems) {
// no additional item allowed, return error
errors.add(buildValidationMessage(at, "" + i));
}
}
}
}
}
>>>>>>>
/*
* Copyright (c) 2016 Network New Technologies Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.networknt.schema;
import com.fasterxml.jackson.databind.JsonNode;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.ArrayList;
import java.util.Collections;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Set;
public class ItemsValidator extends BaseJsonValidator implements JsonValidator {
private static final Logger logger = LoggerFactory.getLogger(ItemsValidator.class);
private static final String PROPERTY_ADDITIONAL_ITEMS = "additionalItems";
private JsonSchema schema;
private List<JsonSchema> tupleSchema;
private boolean additionalItems = true;
private JsonSchema additionalSchema;
public ItemsValidator(String schemaPath, JsonNode schemaNode, JsonSchema parentSchema, ValidationContext validationContext) {
super(schemaPath, schemaNode, parentSchema, ValidatorTypeCode.ITEMS, validationContext);
if (schemaNode.isObject()) {
schema = new JsonSchema(validationContext, getValidatorType().getValue(), parentSchema.getCurrentUrl(), schemaNode, parentSchema);
} else {
tupleSchema = new ArrayList<JsonSchema>();
for (JsonNode s : schemaNode) {
tupleSchema.add(new JsonSchema(validationContext, getValidatorType().getValue(), parentSchema.getCurrentUrl(), s, parentSchema));
}
JsonNode addItemNode = getParentSchema().getSchemaNode().get(PROPERTY_ADDITIONAL_ITEMS);
if (addItemNode != null) {
if (addItemNode.isBoolean()) {
additionalItems = addItemNode.asBoolean();
} else if (addItemNode.isObject()) {
additionalSchema = new JsonSchema(validationContext, parentSchema.getCurrentUrl(), addItemNode);
}
}
}
parseErrorCode(getValidatorType().getErrorCodeKey());
}
public Set<ValidationMessage> validate(JsonNode node, JsonNode rootNode, String at) {
debug(logger, node, rootNode, at);
Set<ValidationMessage> errors = new LinkedHashSet<ValidationMessage>();
if (!node.isArray() && !config.isTypeLoose()) {
// ignores non-arrays
return errors;
}
if (node.isArray()) {
int i = 0;
for (JsonNode n : node) {
doValidate(errors, i, n, rootNode, at);
i++;
}
} else {
doValidate(errors, 0, node, rootNode, at);
}
return Collections.unmodifiableSet(errors);
}
private void doValidate(Set<ValidationMessage> errors, int i, JsonNode node, JsonNode rootNode, String at) {
if (schema != null) {
// validate with item schema (the whole array has the same item
// schema)
errors.addAll(schema.validate(node, rootNode, at + "[" + i + "]"));
}
if (tupleSchema != null) {
if (i < tupleSchema.size()) {
// validate against tuple schema
errors.addAll(tupleSchema.get(i).validate(node, rootNode, at + "[" + i + "]"));
} else {
if (additionalSchema != null) {
// validate against additional item schema
errors.addAll(additionalSchema.validate(node, rootNode, at + "[" + i + "]"));
} else if (!additionalItems) {
// no additional item allowed, return error
errors.add(buildValidationMessage(at, "" + i));
}
}
}
}
} |
<<<<<<<
import org.springframework.expression.Expression;
import org.springframework.expression.spel.standard.SpelExpressionParser;
=======
import org.springframework.util.ClassUtils;
>>>>>>>
import org.springframework.util.ClassUtils;
import org.springframework.expression.Expression;
import org.springframework.expression.spel.standard.SpelExpressionParser;
<<<<<<<
private final Expression getPrincipalExpression = new SpelExpressionParser()
.parseExpression("T(org.springframework.security.core.context.SecurityContextHolder).getContext().getAuthentication()?.getPrincipal()");
=======
/** Java 8's java.util.Optional.empty() */
private static Object javaUtilOptionalEmpty = null;
static {
try {
Class<?> clazz = ClassUtils.forName("java.util.Optional",
ParametersResolver.class.getClassLoader());
javaUtilOptionalEmpty = ClassUtils.getMethod(clazz, "empty").invoke(null);
}
catch (Exception ex) {
// Java 8 not available - conversion to Optional not supported then.
}
}
>>>>>>>
private final Expression getPrincipalExpression = new SpelExpressionParser()
.parseExpression("T(org.springframework.security.core.context.SecurityContextHolder).getContext().getAuthentication()?.getPrincipal()");
/** Java 8's java.util.Optional.empty() */
private static Object javaUtilOptionalEmpty = null;
static {
try {
Class<?> clazz = ClassUtils.forName("java.util.Optional",
ParametersResolver.class.getClassLoader());
javaUtilOptionalEmpty = ClassUtils.getMethod(clazz, "empty").invoke(null);
}
catch (Exception ex) {
// Java 8 not available - conversion to Optional not supported then.
}
} |
<<<<<<<
public boolean isClientParameter() {
return !isSupportedParameter() && !hasRequestHeaderAnnotation()
&& !hasCookieValueAnnotation() && !hasAuthenticationPrincipalAnnotation();
}
=======
public boolean isJavaUtilOptional() {
return javaUtilOptional;
}
>>>>>>>
public boolean isClientParameter() {
return !isSupportedParameter() && !hasRequestHeaderAnnotation()
&& !hasCookieValueAnnotation() && !hasAuthenticationPrincipalAnnotation();
}
public boolean isJavaUtilOptional() {
return javaUtilOptional;
} |
<<<<<<<
import java.lang.ref.WeakReference;
import java.util.ArrayList;
=======
import java.lang.reflect.Method;
>>>>>>>
import java.lang.ref.WeakReference;
import java.util.ArrayList;
<<<<<<<
import android.app.Activity;
import android.app.Application;
=======
>>>>>>>
import android.app.Activity;
import android.app.Application;
<<<<<<<
// event class to receiver objects map
private final HashMap<Class<?>, HashSet<Object>> mEventReceivers
= new HashMap<Class<?>, HashSet<Object>>();
=======
//-- fields
private final HashMap<Class<?>/*event class*/, HashSet<Object>/*multiple receiver objects*/>
mEventReceivers = new HashMap<Class<?>, HashSet<Object>>();
>>>>>>>
// event class to receiver objects map
private final HashMap<Class<?>, HashSet<Object>> mEventReceivers
= new HashMap<Class<?>, HashSet<Object>>();
<<<<<<<
=======
>>>>>>> |
<<<<<<<
import io.reactivex.Observable;
=======
>>>>>>>
import javafx.animation.Animation;
import javafx.animation.KeyFrame;
import javafx.animation.Timeline;
<<<<<<<
=======
import rx.Observable;
import rx.functions.Func1;
>>>>>>>
import rx.Observable;
import rx.functions.Func1;
import java.util.concurrent.atomic.AtomicLong;
<<<<<<<
import java.util.function.Function;
=======
import java.util.Objects;
>>>>>>>
<<<<<<<
public static <T,R> Observable<ListChange<T>> fromObservableListDistinctChanges(final ObservableList<T> source, Function<T,R> mapper) {
=======
public static <T,R> Observable<ListChange<T>> distinctChangesOf(final ObservableList<T> source, Func1<T,R> mapper) {
>>>>>>>
public static <T,R> Observable<ListChange<T>> fromObservableListDistinctChanges(final ObservableList<T> source, Func1<T,R> mapper) {
<<<<<<<
public static <T,R> Observable<ListChange<R>> fromObservableListDistinctMappings(final ObservableList<T> source, Function<T,R> mapper) {
=======
public static <T,R> Observable<ListChange<R>> distinctMappingsOf(final ObservableList<T> source, Func1<T,R> mapper) {
>>>>>>>
public static <T,R> Observable<ListChange<R>> fromObservableListDistinctMappings(final ObservableList<T> source, Func1<T,R> mapper) { |
<<<<<<<
fail();
} catch (MismatchedInputException e) {
verifyException(e, "expected JSON String");
=======
fail("Should not pass");
} catch (JsonMappingException e) {
verifyException(e, "Cannot deserialize value of type ");
verifyException(e, "from Object value");
>>>>>>>
fail("Should not pass");
} catch (MismatchedInputException e) {
verifyException(e, "Cannot deserialize value of type ");
verifyException(e, "from Object value"); |
<<<<<<<
public void testDateTimeKeyDeserialize() throws IOException {
final String json = "{" + quote("1970-01-01T00:00:00.000Z") + ":0}";
final Map<DateTime, Long> map = MAPPER.readValue(json, new TypeReference<Map<DateTime, String>>() { });
assertNotNull(map);
assertTrue(map.containsKey(DateTime.parse("1970-01-01T00:00:00.000Z")));
}
=======
public void testDeserMonthDay() throws Exception
{
String monthDayString = new MonthDay(7, 23).toString();
MonthDay monthDay = MAPPER.readValue(quote(monthDayString), MonthDay.class);
assertEquals(new MonthDay(7, 23), monthDay);
}
public void testDeserMonthDayFromEmptyString() throws Exception
{
MonthDay monthDay = MAPPER.readValue(quote(""), MonthDay.class);
assertNull(monthDay);
}
public void testDeserMonthDayFailsForUnexpectedType() throws IOException
{
try
{
MAPPER.readValue("{\"month\":8}", MonthDay.class);
fail();
} catch (JsonMappingException e)
{
assertTrue(e.getMessage().contains("expected JSON String"));
}
}
public void testDeserYearMonth() throws Exception
{
String yearMonthString = new YearMonth(2013, 8).toString();
YearMonth yearMonth = MAPPER.readValue(quote(yearMonthString), YearMonth.class);
assertEquals(new YearMonth(2013, 8), yearMonth);
}
public void testDeserYearMonthFromEmptyString() throws Exception
{
YearMonth yearMonth = MAPPER.readValue(quote(""), YearMonth.class);
assertNull(yearMonth);
}
public void testDeserYearMonthFailsForUnexpectedType() throws IOException
{
try
{
MAPPER.readValue("{\"year\":2013}", YearMonth.class);
fail();
} catch (JsonMappingException e)
{
assertTrue(e.getMessage().contains("expected JSON String"));
}
}
>>>>>>>
public void testDateTimeKeyDeserialize() throws IOException {
final String json = "{" + quote("1970-01-01T00:00:00.000Z") + ":0}";
final Map<DateTime, Long> map = MAPPER.readValue(json, new TypeReference<Map<DateTime, String>>() { });
assertNotNull(map);
assertTrue(map.containsKey(DateTime.parse("1970-01-01T00:00:00.000Z")));
}
public void testDeserMonthDay() throws Exception
{
String monthDayString = new MonthDay(7, 23).toString();
MonthDay monthDay = MAPPER.readValue(quote(monthDayString), MonthDay.class);
assertEquals(new MonthDay(7, 23), monthDay);
}
public void testDeserMonthDayFromEmptyString() throws Exception
{
MonthDay monthDay = MAPPER.readValue(quote(""), MonthDay.class);
assertNull(monthDay);
}
public void testDeserMonthDayFailsForUnexpectedType() throws IOException
{
try
{
MAPPER.readValue("{\"month\":8}", MonthDay.class);
fail();
} catch (JsonMappingException e)
{
assertTrue(e.getMessage().contains("expected JSON String"));
}
}
public void testDeserYearMonth() throws Exception
{
String yearMonthString = new YearMonth(2013, 8).toString();
YearMonth yearMonth = MAPPER.readValue(quote(yearMonthString), YearMonth.class);
assertEquals(new YearMonth(2013, 8), yearMonth);
}
public void testDeserYearMonthFromEmptyString() throws Exception
{
YearMonth yearMonth = MAPPER.readValue(quote(""), YearMonth.class);
assertNull(yearMonth);
}
public void testDeserYearMonthFailsForUnexpectedType() throws IOException
{
try
{
MAPPER.readValue("{\"year\":2013}", YearMonth.class);
fail();
} catch (JsonMappingException e)
{
assertTrue(e.getMessage().contains("expected JSON String"));
}
} |
<<<<<<<
private final ObjectMapper MAPPER = mapperWithModule();
=======
private final ObjectMapper MAPPER = jodaMapper();
private final ObjectReader READER = MAPPER.readerFor(DateTimeZone.class);
>>>>>>>
private final ObjectMapper MAPPER = mapperWithModule();
private final ObjectReader READER = MAPPER.readerFor(DateTimeZone.class); |
<<<<<<<
import com.fasterxml.jackson.databind.exc.MismatchedInputException;
=======
import com.fasterxml.jackson.databind.ObjectReader;
import com.fasterxml.jackson.databind.exc.InvalidFormatException;
>>>>>>>
import com.fasterxml.jackson.databind.ObjectReader;
import com.fasterxml.jackson.databind.exc.InvalidFormatException;
import com.fasterxml.jackson.databind.exc.MismatchedInputException;
<<<<<<<
final ObjectMapper MAPPER = mapperWithModule();
=======
private final ObjectMapper MAPPER = jodaMapper();
private final ObjectReader READER = MAPPER.readerFor(YearMonth.class);
>>>>>>>
private final ObjectMapper MAPPER = mapperWithModule();
private final ObjectReader READER = MAPPER.readerFor(YearMonth.class);
<<<<<<<
YearMonth yearMonth = mapper.readValue(quote(yearMonthString), YearMonth.class);
=======
YearMonth yearMonth = READER.readValue(quote(yearMonthString));
>>>>>>>
YearMonth yearMonth = mapper.readValue(quote(yearMonthString), YearMonth.class);
<<<<<<<
try {
MAPPER.readValue("{\"year\":2013}", YearMonth.class);
=======
try {
READER.readValue("{\"year\":2013}");
>>>>>>>
try {
READER.readValue("{\"year\":2013}"); |
<<<<<<<
ClassUtil.getTypeDescription(type), periodName);
rp = null; // never gets here
=======
handledType().getName(), periodName);
return null; // never gets here
>>>>>>>
ClassUtil.getTypeDescription(type), periodName);
return null; // never gets here |
<<<<<<<
import com.badlogic.gdx.utils.Scaling;
=======
>>>>>>>
import com.badlogic.gdx.utils.Scaling;
<<<<<<<
=======
stage.act(Math.min(Gdx.graphics.getDeltaTime(), 1 / 30f));
stage.draw();
Table.drawDebug(stage);
>>>>>>> |
<<<<<<<
=======
import co.paralleluniverse.fibers.Fiber;
import co.paralleluniverse.fibers.FiberControl;
import java.util.Iterator;
>>>>>>>
import co.paralleluniverse.fibers.Fiber;
import co.paralleluniverse.fibers.FiberControl;
<<<<<<<
for (Strand s : waiters) {
=======
for (final Strand s : waiters) {
>>>>>>>
for (Strand s : waiters) { |
<<<<<<<
import java.util.ArrayList;
import java.util.Date;
=======
import java.util.WeakHashMap;
>>>>>>>
import java.util.Date;
import java.util.WeakHashMap;
<<<<<<<
byte[] cb = toByteArray(is);
if (className != null) {
=======
MethodDatabase db = getMethodDatabase(loader);
if (className != null)
>>>>>>>
byte[] cb = toByteArray(is);
MethodDatabase db = getMethodDatabase(loader);
if (className != null) {
<<<<<<<
// DEBUG
if (EXAMINED_CLASS != null && className.startsWith(EXAMINED_CLASS)) {
writeToFile(className.replace('/', '.') + "-" + new Date().getTime() + "-quasar-1-preinstr.class", cb);
// cv1 = new TraceClassVisitor(cv, new PrintWriter(System.err));
}
} else {
=======
else
>>>>>>>
// DEBUG
if (EXAMINED_CLASS != null && className.startsWith(EXAMINED_CLASS)) {
writeToFile(className.replace('/', '.') + "-" + new Date().getTime() + "-quasar-1-preinstr.class", cb);
// cv1 = new TraceClassVisitor(cv, new PrintWriter(System.err));
}
} else {
<<<<<<<
@SuppressWarnings("WeakerAccess")
public MethodDatabase getMethodDatabase() {
return db;
=======
public synchronized MethodDatabase getMethodDatabase(ClassLoader loader) {
if (loader == null)
throw new IllegalArgumentException();
if (!dbForClassloader.containsKey(loader)) {
MethodDatabase newDb = new MethodDatabase(this, loader, new DefaultSuspendableClassifier(loader));
dbForClassloader.put(loader, newDb);
return newDb;
} else
return dbForClassloader.get(loader);
>>>>>>>
@SuppressWarnings("WeakerAccess")
public synchronized MethodDatabase getMethodDatabase(ClassLoader loader) {
if (loader == null)
throw new IllegalArgumentException();
if (!dbForClassloader.containsKey(loader)) {
MethodDatabase newDb = new MethodDatabase(this, loader, new DefaultSuspendableClassifier(loader));
dbForClassloader.put(loader, newDb);
return newDb;
} else
return dbForClassloader.get(loader);
<<<<<<<
@SuppressWarnings("WeakerAccess")
public QuasarInstrumentor setVerbose(boolean verbose) {
db.setVerbose(verbose);
=======
public synchronized QuasarInstrumentor setAllowBlocking(boolean allowBlocking) {
this.allowBlocking = allowBlocking;
>>>>>>>
@SuppressWarnings("WeakerAccess")
public synchronized QuasarInstrumentor setAllowBlocking(boolean allowBlocking) {
this.allowBlocking = allowBlocking; |
<<<<<<<
/**
* Resize an image to the given width and height. Leave one dimension 0 to
* perform an aspect-ratio scale on the provided dimension.
* @param bitmap
* @param width
* @param height
* @return a new, scaled Bitmap
*/
public static Bitmap resize(Bitmap bitmap, final int width, final int height) {
float aspect = bitmap.getWidth() / (float) bitmap.getHeight();
if (width > 0 && height > 0) {
return Bitmap.createScaledBitmap(bitmap, width, height, false);
} else if (width > 0) {
return Bitmap.createScaledBitmap(bitmap, width, (int) (width * 1 / aspect), false);
} else if (height > 0) {
return Bitmap.createScaledBitmap(bitmap, (int) (height * aspect), height, false);
}
=======
/**
* Resize an image to the given width and height.
* @param bitmap
* @param width
* @param height
* @return a new, scaled Bitmap
*/
public static Bitmap resize(Bitmap bitmap, final int width, final int height) {
return ImageUtils.resize(bitmap, width, height, false);
}
/**
* Resize an image to the given width and height considering the preserveAspectRatio flag.
* @param bitmap
* @param width
* @param height
* @param preserveAspectRatio
* @return a new, scaled Bitmap
*/
public static Bitmap resize(Bitmap bitmap, final int width, final int height, final boolean preserveAspectRatio) {
if (preserveAspectRatio) {
return ImageUtils.resizePreservingAspectRatio(bitmap, width, height);
}
return ImageUtils.resizeImageWithoutPreservingAspectRatio(bitmap, width, height);
}
/**
* Resize an image to the given width and height. Leave one dimension 0 to
* perform an aspect-ratio scale on the provided dimension.
* @param bitmap
* @param width
* @param height
* @return a new, scaled Bitmap
*/
private static Bitmap resizeImageWithoutPreservingAspectRatio(Bitmap bitmap, final int width, final int height) {
float aspect = bitmap.getWidth() / (float) bitmap.getHeight();
if (width > 0 && height > 0) {
return Bitmap.createScaledBitmap(bitmap, width, height, false);
} else if (width > 0) {
return Bitmap.createScaledBitmap(bitmap, width, (int) (width * 1/aspect), false);
} else if (height > 0) {
return Bitmap.createScaledBitmap(bitmap, (int) (height * aspect), height, false);
}
return bitmap;
}
/**
* Resize an image to the given max width and max height. Constraint can be put
* on one dimension, or both. Resize will always preserve aspect ratio.
* @param bitmap
* @param desiredMaxWidth
* @param desiredMaxHeight
* @return a new, scaled Bitmap
*/
private static Bitmap resizePreservingAspectRatio(Bitmap bitmap, final int desiredMaxWidth, final int desiredMaxHeight) {
int width = bitmap.getWidth();
int height = bitmap.getHeight();
// 0 is treated as 'no restriction'
int maxHeight = desiredMaxHeight == 0 ? height : desiredMaxHeight;
int maxWidth = desiredMaxWidth == 0 ? width : desiredMaxWidth;
// resize with preserved aspect ratio
float newWidth = Math.min(width, maxWidth);
float newHeight = (height * newWidth) / width;
if (newHeight > maxHeight) {
newWidth = (width * maxHeight) / height;
newHeight = maxHeight;
}
return Bitmap.createScaledBitmap(bitmap, Math.round(newWidth), Math.round(newHeight), false);
}
/**
* Transform an image with the given matrix
* @param bitmap
* @param matrix
* @return
*/
private static Bitmap transform(final Bitmap bitmap, final Matrix matrix) {
return Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(), bitmap.getHeight(), matrix, true);
}
/**
* Correct the orientation of an image by reading its exif information and rotating
* the appropriate amount for portrait mode
* @param bitmap
* @param imageUri
* @return
*/
public static Bitmap correctOrientation(final Context c, final Bitmap bitmap, final Uri imageUri) throws IOException {
if(Build.VERSION.SDK_INT < 24) {
return correctOrientationOlder(c, bitmap, imageUri);
} else {
final int orientation = getOrientation(c, imageUri);
if (orientation != 0) {
Matrix matrix = new Matrix();
matrix.postRotate(orientation);
>>>>>>>
/**
* Resize an image to the given width and height.
* @param bitmap
* @param width
* @param height
* @return a new, scaled Bitmap
*/
public static Bitmap resize(Bitmap bitmap, final int width, final int height) {
return ImageUtils.resize(bitmap, width, height, false);
}
/**
* Resize an image to the given width and height considering the preserveAspectRatio flag.
* @param bitmap
* @param width
* @param height
* @param preserveAspectRatio
* @return a new, scaled Bitmap
*/
public static Bitmap resize(Bitmap bitmap, final int width, final int height, final boolean preserveAspectRatio) {
if (preserveAspectRatio) {
return ImageUtils.resizePreservingAspectRatio(bitmap, width, height);
}
return ImageUtils.resizeImageWithoutPreservingAspectRatio(bitmap, width, height);
}
/**
* Resize an image to the given width and height. Leave one dimension 0 to
* perform an aspect-ratio scale on the provided dimension.
* @param bitmap
* @param width
* @param height
* @return a new, scaled Bitmap
*/
private static Bitmap resizeImageWithoutPreservingAspectRatio(Bitmap bitmap, final int width, final int height) {
float aspect = bitmap.getWidth() / (float) bitmap.getHeight();
if (width > 0 && height > 0) {
return Bitmap.createScaledBitmap(bitmap, width, height, false);
} else if (width > 0) {
return Bitmap.createScaledBitmap(bitmap, width, (int) (width * 1 / aspect), false);
} else if (height > 0) {
return Bitmap.createScaledBitmap(bitmap, (int) (height * aspect), height, false);
} |
<<<<<<<
=======
import java.text.SimpleDateFormat;
>>>>>>>
import java.text.SimpleDateFormat; |
<<<<<<<
private void showPrompt(final PluginCall call) {
// We have all necessary permissions, open the camera
String promptLabelPhoto = call.getString("promptLabelPhoto", "From Photos");
String promptLabelPicture = call.getString("promptLabelPicture", "Take Picture");
JSObject fromPhotos = new JSObject();
fromPhotos.put("title", promptLabelPhoto);
JSObject takePicture = new JSObject();
takePicture.put("title", promptLabelPicture);
Object[] options = new Object[] { fromPhotos, takePicture };
Dialogs.actions(
getActivity(),
options,
index -> {
if (index == 0) {
settings.setSource(CameraSource.PHOTOS);
openPhotos(call);
} else if (index == 1) {
settings.setSource(CameraSource.CAMERA);
openCamera(call);
}
},
() -> call.error("User cancelled photos app")
);
}
private void showCamera(final PluginCall call) {
if (!getActivity().getPackageManager().hasSystemFeature(PackageManager.FEATURE_CAMERA_ANY)) {
call.error(NO_CAMERA_ERROR);
return;
}
openCamera(call);
}
private void showPhotos(final PluginCall call) {
openPhotos(call);
}
private boolean checkCameraPermissions(PluginCall call) {
// If we want to save to the gallery, we need two permissions
if (
settings.isSaveToGallery() &&
!(hasPermission(Manifest.permission.CAMERA) && hasPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE))
) {
pluginRequestPermissions(
new String[] {
Manifest.permission.CAMERA,
Manifest.permission.WRITE_EXTERNAL_STORAGE,
Manifest.permission.READ_EXTERNAL_STORAGE
},
REQUEST_IMAGE_CAPTURE
);
return false;
}
// If we don't need to save to the gallery, we can just ask for camera permissions
else if (!hasPermission(Manifest.permission.CAMERA)) {
pluginRequestPermission(Manifest.permission.CAMERA, REQUEST_IMAGE_CAPTURE);
return false;
}
return true;
=======
private boolean checkPhotosPermissions(PluginCall call) {
if(!hasPermission(Manifest.permission.READ_EXTERNAL_STORAGE)) {
pluginRequestPermission(Manifest.permission.READ_EXTERNAL_STORAGE, REQUEST_IMAGE_CAPTURE);
return false;
}
return true;
}
private CameraSettings getSettings(PluginCall call) {
CameraSettings settings = new CameraSettings();
settings.setResultType(getResultType(call.getString("resultType")));
settings.setSaveToGallery(call.getBoolean("saveToGallery", CameraSettings.DEFAULT_SAVE_IMAGE_TO_GALLERY));
settings.setAllowEditing(call.getBoolean("allowEditing", false));
settings.setQuality(call.getInt("quality", CameraSettings.DEFAULT_QUALITY));
settings.setWidth(call.getInt("width", 0));
settings.setHeight(call.getInt("height", 0));
settings.setShouldResize(settings.getWidth() > 0 || settings.getHeight() > 0);
settings.setShouldCorrectOrientation(call.getBoolean("correctOrientation", CameraSettings.DEFAULT_CORRECT_ORIENTATION));
settings.setPreserveAspectRatio(call.getBoolean("preserveAspectRatio", false));
try {
settings.setSource(CameraSource.valueOf(call.getString("source", CameraSource.PROMPT.getSource())));
} catch (IllegalArgumentException ex) {
settings.setSource(CameraSource.PROMPT);
}
return settings;
}
private CameraResultType getResultType(String resultType) {
if (resultType == null) { return null; }
try {
return CameraResultType.valueOf(resultType.toUpperCase());
} catch (IllegalArgumentException ex) {
Logger.debug(getLogTag(), "Invalid result type \"" + resultType + "\", defaulting to base64");
return CameraResultType.BASE64;
>>>>>>>
private void showPrompt(final PluginCall call) {
// We have all necessary permissions, open the camera
String promptLabelPhoto = call.getString("promptLabelPhoto", "From Photos");
String promptLabelPicture = call.getString("promptLabelPicture", "Take Picture");
JSObject fromPhotos = new JSObject();
fromPhotos.put("title", promptLabelPhoto);
JSObject takePicture = new JSObject();
takePicture.put("title", promptLabelPicture);
Object[] options = new Object[] { fromPhotos, takePicture };
Dialogs.actions(
getActivity(),
options,
index -> {
if (index == 0) {
settings.setSource(CameraSource.PHOTOS);
openPhotos(call);
} else if (index == 1) {
settings.setSource(CameraSource.CAMERA);
openCamera(call);
}
},
() -> call.error("User cancelled photos app")
);
}
private void showCamera(final PluginCall call) {
if (!getActivity().getPackageManager().hasSystemFeature(PackageManager.FEATURE_CAMERA_ANY)) {
call.error(NO_CAMERA_ERROR);
return;
}
openCamera(call);
}
private void showPhotos(final PluginCall call) {
openPhotos(call);
}
private boolean checkCameraPermissions(PluginCall call) {
// If we want to save to the gallery, we need two permissions
if (
settings.isSaveToGallery() &&
!(hasPermission(Manifest.permission.CAMERA) && hasPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE))
) {
pluginRequestPermissions(
new String[] {
Manifest.permission.CAMERA,
Manifest.permission.WRITE_EXTERNAL_STORAGE,
Manifest.permission.READ_EXTERNAL_STORAGE
},
REQUEST_IMAGE_CAPTURE
);
return false;
}
// If we don't need to save to the gallery, we can just ask for camera permissions
else if (!hasPermission(Manifest.permission.CAMERA)) {
pluginRequestPermission(Manifest.permission.CAMERA, REQUEST_IMAGE_CAPTURE);
return false;
}
return true;
<<<<<<<
if (settings.isAllowEditing() && !isEdited) {
editImage(call, bitmap, u, bitmapOutputStream);
return;
}
=======
boolean saveToGallery = call.getBoolean("saveToGallery", CameraSettings.DEFAULT_SAVE_IMAGE_TO_GALLERY);
if (saveToGallery && (imageEditedFileSavePath != null || imageFileSavePath != null)) {
try {
String fileToSavePath = imageEditedFileSavePath != null ? imageEditedFileSavePath : imageFileSavePath;
File fileToSave = new File(fileToSavePath);
MediaStore.Images.Media.insertImage(getActivity().getContentResolver(), fileToSavePath, fileToSave.getName(), "");
} catch (FileNotFoundException e) {
Logger.error(getLogTag(), IMAGE_GALLERY_SAVE_ERROR, e);
}
}
>>>>>>>
if (settings.isAllowEditing() && !isEdited) {
editImage(call, bitmap, u, bitmapOutputStream);
return;
}
<<<<<<<
if (settings.isShouldResize()) {
final Bitmap newBitmap = ImageUtils.resize(bitmap, settings.getWidth(), settings.getHeight());
bitmap = replaceBitmap(bitmap, newBitmap);
}
return bitmap;
=======
if (settings.isShouldResize()) {
final Bitmap newBitmap = ImageUtils.resize(
bitmap,
settings.getWidth(),
settings.getHeight(),
settings.getPreserveAspectRatio()
);
bitmap = replaceBitmap(bitmap, newBitmap);
>>>>>>>
if (settings.isShouldResize()) {
final Bitmap newBitmap = ImageUtils.resize(
bitmap,
settings.getWidth(),
settings.getHeight(),
settings.getPreserveAspectRatio()
);
bitmap = replaceBitmap(bitmap, newBitmap);
}
return bitmap; |
<<<<<<<
//instantiate the sail
HBaseSail sail = new HBaseSail(HBaseConfiguration.create(), hconfig.getTablespace(), hconfig.isCreate(), hconfig.getSplitBits(), hconfig.isPush(), hconfig.getEvaluationTimeout(), null);
=======
HBaseSail sail = new HBaseSail(HBaseConfiguration.create(), hconfig.getTablespace(), hconfig.isCreate(), hconfig.getSplitBits(), hconfig.isPush(), hconfig.getEvaluationTimeout(), hconfig.getElasticIndexURL(), null);
>>>>>>>
//instantiate the sail
HBaseSail sail = new HBaseSail(HBaseConfiguration.create(), hconfig.getTablespace(), hconfig.isCreate(), hconfig.getSplitBits(), hconfig.isPush(), hconfig.getEvaluationTimeout(), hconfig.getElasticIndexURL(), null); |
<<<<<<<
protected double getCardinality(StatementPattern sp) { //get the cardinality of the Statement form VOID statistics
=======
protected double getCardinality(StatementPattern sp) {
Var objectVar = sp.getObjectVar();
//always return cardinality 1.0 for HALYARD.SEARCH_TYPE object literals to move such statements higher in the joins tree
if (objectVar.hasValue() && (objectVar.getValue() instanceof Literal) && HALYARD.SEARCH_TYPE.equals(((Literal)objectVar.getValue()).getDatatype())) {
return 1.0;
}
>>>>>>>
protected double getCardinality(StatementPattern sp) { //get the cardinality of the Statement form VOID statistics
Var objectVar = sp.getObjectVar();
//always return cardinality 1.0 for HALYARD.SEARCH_TYPE object literals to move such statements higher in the joins tree
if (objectVar.hasValue() && (objectVar.getValue() instanceof Literal) && HALYARD.SEARCH_TYPE.equals(((Literal)objectVar.getValue()).getDatatype())) {
return 1.0;
}
<<<<<<<
//Scans the Halyard table for statements that match the specified pattern
=======
Map <String, List<byte[]>> searchCache = Collections.synchronizedMap(new WeakHashMap<>());
private class LiteralSearchStatementScanner extends StatementScanner {
Iterator<byte[]> objectHashes = null;
private final String literalSearchQuery;
public LiteralSearchStatementScanner(long startTime, Resource subj, IRI pred, String literalSearchQuery, Resource... contexts) throws SailException {
super(startTime, subj, pred, null, contexts);
if (elasticIndexURL == null || elasticIndexURL.length() == 0) {
throw new SailException("ElasticSearch Index URL is not properly configured.");
}
this.literalSearchQuery = literalSearchQuery;
}
@Override
protected Result nextResult() throws IOException {
while (true) {
if (objHash == null) {
if (objectHashes == null) { //perform ES query and parse results
List<byte[]> objectHashesList = searchCache.get(literalSearchQuery);
if (objectHashesList == null) {
objectHashesList = new ArrayList<>();
HttpURLConnection http = (HttpURLConnection)(new URL(elasticIndexURL + "/_search").openConnection());
try {
http.setRequestMethod("POST");
http.setDoOutput(true);
http.setRequestProperty("Content-Type", "application/json; charset=UTF-8");
http.connect();
try (PrintStream out = new PrintStream(http.getOutputStream(), true, "UTF-8")) {
out.print("{\"query\":{\"query_string\":{\"query\":" + JSONObject.quote(literalSearchQuery) + "}},\"_source\":false,\"stored_fields\":\"_id\",\"size\":" + ELASTIC_RESULT_SIZE + "}");
}
int response = http.getResponseCode();
String msg = http.getResponseMessage();
if (response != 200) {
throw new IOException(msg);
}
try (InputStreamReader isr = new InputStreamReader(http.getInputStream(), "UTF-8")) {
JSONArray hits = new JSONObject(new JSONTokener(isr)).getJSONObject("hits").getJSONArray("hits");
for (int i=0; i<hits.length(); i++) {
objectHashesList.add(Hex.decodeHex(hits.getJSONObject(i).getString("_id").toCharArray()));
}
}
} catch (JSONException | DecoderException ex) {
throw new IOException(ex);
} finally {
http.disconnect();
}
searchCache.put(new String(literalSearchQuery), objectHashesList);
}
objectHashes = objectHashesList.iterator();
}
if (objectHashes.hasNext()) {
objHash = objectHashes.next();
} else {
return null;
}
contexts = contextsList.iterator(); //reset iterator over contexts
}
Result res = super.nextResult();
if (res == null) {
objHash = null;
} else {
return res;
}
}
}
}
>>>>>>>
Map <String, List<byte[]>> searchCache = Collections.synchronizedMap(new WeakHashMap<>());
//Scans the Halyard table for statements that match the specified pattern
private class LiteralSearchStatementScanner extends StatementScanner {
Iterator<byte[]> objectHashes = null;
private final String literalSearchQuery;
public LiteralSearchStatementScanner(long startTime, Resource subj, IRI pred, String literalSearchQuery, Resource... contexts) throws SailException {
super(startTime, subj, pred, null, contexts);
if (elasticIndexURL == null || elasticIndexURL.length() == 0) {
throw new SailException("ElasticSearch Index URL is not properly configured.");
}
this.literalSearchQuery = literalSearchQuery;
}
@Override
protected Result nextResult() throws IOException {
while (true) {
if (objHash == null) {
if (objectHashes == null) { //perform ES query and parse results
List<byte[]> objectHashesList = searchCache.get(literalSearchQuery);
if (objectHashesList == null) {
objectHashesList = new ArrayList<>();
HttpURLConnection http = (HttpURLConnection)(new URL(elasticIndexURL + "/_search").openConnection());
try {
http.setRequestMethod("POST");
http.setDoOutput(true);
http.setRequestProperty("Content-Type", "application/json; charset=UTF-8");
http.connect();
try (PrintStream out = new PrintStream(http.getOutputStream(), true, "UTF-8")) {
out.print("{\"query\":{\"query_string\":{\"query\":" + JSONObject.quote(literalSearchQuery) + "}},\"_source\":false,\"stored_fields\":\"_id\",\"size\":" + ELASTIC_RESULT_SIZE + "}");
}
int response = http.getResponseCode();
String msg = http.getResponseMessage();
if (response != 200) {
throw new IOException(msg);
}
try (InputStreamReader isr = new InputStreamReader(http.getInputStream(), "UTF-8")) {
JSONArray hits = new JSONObject(new JSONTokener(isr)).getJSONObject("hits").getJSONArray("hits");
for (int i=0; i<hits.length(); i++) {
objectHashesList.add(Hex.decodeHex(hits.getJSONObject(i).getString("_id").toCharArray()));
}
}
} catch (JSONException | DecoderException ex) {
throw new IOException(ex);
} finally {
http.disconnect();
}
searchCache.put(new String(literalSearchQuery), objectHashesList);
}
objectHashes = objectHashesList.iterator();
}
if (objectHashes.hasNext()) {
objHash = objectHashes.next();
} else {
return null;
}
contexts = contextsList.iterator(); //reset iterator over contexts
}
Result res = super.nextResult();
if (res == null) {
objHash = null;
} else {
return res;
}
}
}
}
<<<<<<<
private Result nextResult() throws IOException { //gets the next result to consider from the HBase Scan
=======
protected Result nextResult() throws IOException {
>>>>>>>
protected Result nextResult() throws IOException { //gets the next result to consider from the HBase Scan
<<<<<<<
//build a ResultScanner from an HBase Scan that finds potential matches
rs = table.getScanner(HalyardTableUtils.scan(subj, pred, obj, contexts.next()));
=======
rs = table.getScanner(HalyardTableUtils.scan(subjHash, predHash, objHash, HalyardTableUtils.hashKey(contexts.next())));
>>>>>>>
//build a ResultScanner from an HBase Scan that finds potential matches
rs = table.getScanner(HalyardTableUtils.scan(subjHash, predHash, objHash, HalyardTableUtils.hashKey(contexts.next()))); |
<<<<<<<
case DemoUtil.TYPE_DASH_VOD:
return new DashVodRendererBuilder(this, userAgent, contentUri.toString(), contentId);
case DemoUtil.TYPE_HLS:
return new HlsRendererBuilder(this, userAgent, contentUri.toString(), contentId);
=======
case DemoUtil.TYPE_DASH:
return new DashRendererBuilder(this, userAgent, contentUri.toString(), contentId);
>>>>>>>
case DemoUtil.TYPE_DASH:
return new DashRendererBuilder(this, userAgent, contentUri.toString(), contentId);
case DemoUtil.TYPE_HLS:
return new HlsRendererBuilder(this, userAgent, contentUri.toString(), contentId); |
<<<<<<<
float pixelWidthHeightRatio, byte[] projectionData, @C.StereoMode int stereoMode,
int channelCount, int sampleRate, @C.PcmEncoding int pcmEncoding, int encoderDelay,
int encoderPadding, @C.SelectionFlags int selectionFlags, String language,
long subsampleOffsetUs, List<byte[]> initializationData, DrmInitData drmInitData) {
=======
float pixelWidthHeightRatio, byte[] projectionData, int stereoMode, int channelCount,
int sampleRate, int pcmEncoding, int encoderDelay, int encoderPadding, int selectionFlags,
String language, long subsampleOffsetUs, List<byte[]> initializationData,
DrmInitData drmInitData, Metadata metadata) {
>>>>>>>
float pixelWidthHeightRatio, byte[] projectionData, @C.StereoMode int stereoMode,
int channelCount, int sampleRate, @C.PcmEncoding int pcmEncoding, int encoderDelay,
int encoderPadding, @C.SelectionFlags int selectionFlags, String language,
long subsampleOffsetUs, List<byte[]> initializationData, DrmInitData drmInitData,
Metadata metadata) { |
<<<<<<<
* @since Ant 1.10.6
=======
* @param other the argument to copy setting from
*
* @since Ant 1.9.14
>>>>>>>
* @param other the argument to copy setting from
*
* @since Ant 1.10.6 |
<<<<<<<
this(uri, 0, null, -1, C.TIME_UNSET, null, null, byterangeOffset, byterangeLength);
=======
this(uri, 0, -1, C.TIME_UNSET, null, null, byterangeOffset, byterangeLength, false);
>>>>>>>
this(uri, 0, null, -1, C.TIME_UNSET, null, null, byterangeOffset, byterangeLength, false);
<<<<<<<
public Segment(String url, long durationUs, String title, int relativeDiscontinuitySequence,
long relativeStartTimeUs, String fullSegmentEncryptionKeyUri,
String encryptionIV, long byterangeOffset, long byterangeLength) {
=======
public Segment(
String url,
long durationUs,
int relativeDiscontinuitySequence,
long relativeStartTimeUs,
String fullSegmentEncryptionKeyUri,
String encryptionIV,
long byterangeOffset,
long byterangeLength,
boolean hasGapTag) {
>>>>>>>
public Segment(String url, long durationUs, String title, int relativeDiscontinuitySequence,
long relativeStartTimeUs, String fullSegmentEncryptionKeyUri, String encryptionIV,
long byterangeOffset, long byterangeLength, boolean hasGapTag) { |
<<<<<<<
* See {@link TrackSelectionParameters#preferredRoleFlags}.
*
* @param preferredRoleFlags Preferred role flags.
* @return This builder.
*/
public Builder setPreferredRoleFlags(int preferredRoleFlags) {
this.preferredRoleFlags = preferredRoleFlags;
return this;
}
/**
* See {@link TrackSelectionParameters#selectUndeterminedTextLanguage}.
=======
* Sets whether a text track with undetermined language should be selected if no track with
* {@link #setPreferredTextLanguage(String)} is available, or if the preferred language is
* unset.
>>>>>>>
* See {@link TrackSelectionParameters#preferredRoleFlags}.
*
* @param preferredRoleFlags Preferred role flags.
* @return This builder.
*/
public Builder setPreferredRoleFlags(int preferredRoleFlags) {
this.preferredRoleFlags = preferredRoleFlags;
return this;
}
/**
* Sets whether a text track with undetermined language should be selected if no track with
* {@link #setPreferredTextLanguage(String)} is available, or if the preferred language is
* unset. |
<<<<<<<
/** Track selection flags. */
@C.SelectionFlags public final int selectionFlags;
=======
/** Track selection flags. **/
@C.SelectionFlags
public final int selectionFlags;
/** Track role flags. **/
@C.RoleFlags
public final int roleFlags;
>>>>>>>
/** Track selection flags. */
@C.SelectionFlags public final int selectionFlags;
/** Track role flags. */
@C.RoleFlags public final int roleFlags;
<<<<<<<
=======
selectionFlags,
roleFlags,
>>>>>>>
<<<<<<<
=======
/* selectionFlags= */ 0,
/* roleFlags= */ 0,
>>>>>>>
<<<<<<<
=======
selectionFlags,
roleFlags,
>>>>>>>
<<<<<<<
=======
selectionFlags,
/* roleFlags= */ 0,
>>>>>>>
<<<<<<<
=======
selectionFlags,
/* roleFlags= */ 0,
>>>>>>>
<<<<<<<
=======
selectionFlags,
/* roleFlags= */ 0,
>>>>>>>
<<<<<<<
=======
/* selectionFlags= */ 0,
/* roleFlags= */ 0,
>>>>>>>
<<<<<<<
=======
/* selectionFlags= */ 0,
/* roleFlags= */ 0,
>>>>>>>
<<<<<<<
// Audio and text specific.
=======
@C.SelectionFlags int selectionFlags,
@C.RoleFlags int roleFlags,
>>>>>>>
// Audio and text specific.
<<<<<<<
// Audio and text specific.
=======
this.selectionFlags = selectionFlags;
this.roleFlags = roleFlags;
>>>>>>>
// Audio and text specific.
<<<<<<<
// Audio and text specific.
=======
selectionFlags = in.readInt();
roleFlags = in.readInt();
>>>>>>>
// Audio and text specific.
<<<<<<<
&& accessibilityChannel == other.accessibilityChannel
&& Float.compare(frameRate, other.frameRate) == 0
&& Float.compare(pixelWidthHeightRatio, other.pixelWidthHeightRatio) == 0
=======
&& subsampleOffsetUs == other.subsampleOffsetUs
&& selectionFlags == other.selectionFlags
&& roleFlags == other.roleFlags
>>>>>>>
&& accessibilityChannel == other.accessibilityChannel
&& Float.compare(frameRate, other.frameRate) == 0
&& Float.compare(pixelWidthHeightRatio, other.pixelWidthHeightRatio) == 0
<<<<<<<
// Audio and text specific.
=======
dest.writeInt(selectionFlags);
dest.writeInt(roleFlags);
>>>>>>>
// Audio and text specific. |
<<<<<<<
private List<NameEntry> includeList = new ArrayList<>();
private List<NameEntry> excludeList = new ArrayList<>();
private List<NameEntry> includesFileList = new ArrayList<>();
private List<NameEntry> excludesFileList = new ArrayList<>();
=======
private List<NameEntry> includeList = new ArrayList<NameEntry>();
private List<NameEntry> excludeList = new ArrayList<NameEntry>();
private List<PatternFileNameEntry> includesFileList = new ArrayList<PatternFileNameEntry>();
private List<PatternFileNameEntry> excludesFileList = new ArrayList<PatternFileNameEntry>();
>>>>>>>
private List<NameEntry> includeList = new ArrayList<>();
private List<NameEntry> excludeList = new ArrayList<>();
private List<PatternFileNameEntry> includesFileList = new ArrayList<>();
private List<PatternFileNameEntry> excludesFileList = new ArrayList<>();
<<<<<<<
try (BufferedReader patternReader =
new BufferedReader(new FileReader(patternfile))) {
=======
BufferedReader patternReader = null;
try {
// Get a FileReader
if (encoding == null) {
patternReader = new BufferedReader(new FileReader(patternfile));
} else {
patternReader = new BufferedReader(new InputStreamReader(new FileInputStream(patternfile), encoding));
}
>>>>>>>
try (Reader r = encoding == null ? new FileReader(patternfile)
: new InputStreamReader(new FileInputStream(patternfile), encoding);
BufferedReader patternReader = new BufferedReader(r)) {
<<<<<<<
if (!includesFileList.isEmpty()) {
for (NameEntry ne : includesFileList) {
=======
if (includesFileList.size() > 0) {
for (PatternFileNameEntry ne : includesFileList) {
>>>>>>>
if (!includesFileList.isEmpty()) {
for (PatternFileNameEntry ne : includesFileList) {
<<<<<<<
if (!excludesFileList.isEmpty()) {
for (NameEntry ne : excludesFileList) {
=======
if (excludesFileList.size() > 0) {
for (PatternFileNameEntry ne : excludesFileList) {
>>>>>>>
if (!excludesFileList.isEmpty()) {
for (PatternFileNameEntry ne : excludesFileList) {
<<<<<<<
ps.includeList = new ArrayList<>(includeList);
ps.excludeList = new ArrayList<>(excludeList);
ps.includesFileList = new ArrayList<>(includesFileList);
ps.excludesFileList = new ArrayList<>(excludesFileList);
=======
ps.includeList = new ArrayList<NameEntry>(includeList);
ps.excludeList = new ArrayList<NameEntry>(excludeList);
ps.includesFileList = new ArrayList<PatternFileNameEntry>(includesFileList);
ps.excludesFileList = new ArrayList<PatternFileNameEntry>(excludesFileList);
>>>>>>>
ps.includeList = new ArrayList<>(includeList);
ps.excludeList = new ArrayList<>(excludeList);
ps.includesFileList = new ArrayList<>(includesFileList);
ps.excludesFileList = new ArrayList<>(excludesFileList); |
<<<<<<<
private static final String PLAYLIST_WITH_TTML_SUBTITLE =
" #EXTM3U\n"
+ "\n"
+ "#EXT-X-VERSION:6\n"
+ "\n"
+ "#EXT-X-INDEPENDENT-SEGMENTS\n"
+ "\n"
+ "#EXT-X-STREAM-INF:BANDWIDTH=1280000,CODECS=\"stpp.ttml.im1t,mp4a.40.2,avc1.66.30\",RESOLUTION=304x128,AUDIO=\"aud1\",SUBTITLES=\"sub1\"\n"
+ "http://example.com/low.m3u8\n"
+ "\n"
+ "#EXT-X-MEDIA:TYPE=AUDIO,GROUP-ID=\"aud1\",NAME=\"English\",URI=\"a1/index.m3u8\"\n"
+ "#EXT-X-MEDIA:TYPE=SUBTITLES,GROUP-ID=\"sub1\",NAME=\"English\",AUTOSELECT=YES,DEFAULT=YES,URI=\"s1/en/prog_index.m3u8\"\n";
=======
private static final String PLAYLIST_WITH_IFRAME_VARIANTS =
"#EXTM3U\n"
+ "#EXT-X-VERSION:5\n"
+ "#EXT-X-MEDIA:URI=\"AUDIO_English/index.m3u8\",TYPE=AUDIO,GROUP-ID=\"audio-aac\",LANGUAGE=\"en\",NAME=\"English\",AUTOSELECT=YES\n"
+ "#EXT-X-MEDIA:URI=\"AUDIO_Spanish/index.m3u8\",TYPE=AUDIO,GROUP-ID=\"audio-aac\",LANGUAGE=\"es\",NAME=\"Spanish\",AUTOSELECT=YES\n"
+ "#EXT-X-MEDIA:TYPE=CLOSED-CAPTIONS,GROUP-ID=\"cc1\",LANGUAGE=\"en\",NAME=\"English\",AUTOSELECT=YES,DEFAULT=YES,INSTREAM-ID=\"CC1\"\n"
+ "#EXT-X-STREAM-INF:PROGRAM-ID=1,BANDWIDTH=400000,RESOLUTION=480x320,CODECS=\"mp4a.40.2,avc1.640015\",AUDIO=\"audio-aac\",CLOSED-CAPTIONS=\"cc1\"\n"
+ "400000/index.m3u8\n"
+ "#EXT-X-STREAM-INF:PROGRAM-ID=1,BANDWIDTH=1000000,RESOLUTION=848x480,CODECS=\"mp4a.40.2,avc1.64001f\",AUDIO=\"audio-aac\",CLOSED-CAPTIONS=\"cc1\"\n"
+ "1000000/index.m3u8\n"
+ "#EXT-X-STREAM-INF:PROGRAM-ID=1,BANDWIDTH=3220000,RESOLUTION=1280x720,CODECS=\"mp4a.40.2,avc1.64001f\",AUDIO=\"audio-aac\",CLOSED-CAPTIONS=\"cc1\"\n"
+ "3220000/index.m3u8\n"
+ "#EXT-X-STREAM-INF:PROGRAM-ID=1,BANDWIDTH=8940000,RESOLUTION=1920x1080,CODECS=\"mp4a.40.2,avc1.640028\",AUDIO=\"audio-aac\",CLOSED-CAPTIONS=\"cc1\"\n"
+ "8940000/index.m3u8\n"
+ "#EXT-X-I-FRAME-STREAM-INF:BANDWIDTH=1313400,RESOLUTION=1920x1080,CODECS=\"avc1.640028\",URI=\"iframe_1313400/index.m3u8\"\n";
>>>>>>>
private static final String PLAYLIST_WITH_TTML_SUBTITLE =
" #EXTM3U\n"
+ "\n"
+ "#EXT-X-VERSION:6\n"
+ "\n"
+ "#EXT-X-INDEPENDENT-SEGMENTS\n"
+ "\n"
+ "#EXT-X-STREAM-INF:BANDWIDTH=1280000,CODECS=\"stpp.ttml.im1t,mp4a.40.2,avc1.66.30\",RESOLUTION=304x128,AUDIO=\"aud1\",SUBTITLES=\"sub1\"\n"
+ "http://example.com/low.m3u8\n"
+ "\n"
+ "#EXT-X-MEDIA:TYPE=AUDIO,GROUP-ID=\"aud1\",NAME=\"English\",URI=\"a1/index.m3u8\"\n"
+ "#EXT-X-MEDIA:TYPE=SUBTITLES,GROUP-ID=\"sub1\",NAME=\"English\",AUTOSELECT=YES,DEFAULT=YES,URI=\"s1/en/prog_index.m3u8\"\n";
private static final String PLAYLIST_WITH_IFRAME_VARIANTS =
"#EXTM3U\n"
+ "#EXT-X-VERSION:5\n"
+ "#EXT-X-MEDIA:URI=\"AUDIO_English/index.m3u8\",TYPE=AUDIO,GROUP-ID=\"audio-aac\",LANGUAGE=\"en\",NAME=\"English\",AUTOSELECT=YES\n"
+ "#EXT-X-MEDIA:URI=\"AUDIO_Spanish/index.m3u8\",TYPE=AUDIO,GROUP-ID=\"audio-aac\",LANGUAGE=\"es\",NAME=\"Spanish\",AUTOSELECT=YES\n"
+ "#EXT-X-MEDIA:TYPE=CLOSED-CAPTIONS,GROUP-ID=\"cc1\",LANGUAGE=\"en\",NAME=\"English\",AUTOSELECT=YES,DEFAULT=YES,INSTREAM-ID=\"CC1\"\n"
+ "#EXT-X-STREAM-INF:PROGRAM-ID=1,BANDWIDTH=400000,RESOLUTION=480x320,CODECS=\"mp4a.40.2,avc1.640015\",AUDIO=\"audio-aac\",CLOSED-CAPTIONS=\"cc1\"\n"
+ "400000/index.m3u8\n"
+ "#EXT-X-STREAM-INF:PROGRAM-ID=1,BANDWIDTH=1000000,RESOLUTION=848x480,CODECS=\"mp4a.40.2,avc1.64001f\",AUDIO=\"audio-aac\",CLOSED-CAPTIONS=\"cc1\"\n"
+ "1000000/index.m3u8\n"
+ "#EXT-X-STREAM-INF:PROGRAM-ID=1,BANDWIDTH=3220000,RESOLUTION=1280x720,CODECS=\"mp4a.40.2,avc1.64001f\",AUDIO=\"audio-aac\",CLOSED-CAPTIONS=\"cc1\"\n"
+ "3220000/index.m3u8\n"
+ "#EXT-X-STREAM-INF:PROGRAM-ID=1,BANDWIDTH=8940000,RESOLUTION=1920x1080,CODECS=\"mp4a.40.2,avc1.640028\",AUDIO=\"audio-aac\",CLOSED-CAPTIONS=\"cc1\"\n"
+ "8940000/index.m3u8\n"
+ "#EXT-X-I-FRAME-STREAM-INF:BANDWIDTH=1313400,RESOLUTION=1920x1080,CODECS=\"avc1.640028\",URI=\"iframe_1313400/index.m3u8\"\n"; |
<<<<<<<
private MediaCodecInfo codecInfo;
private float codecOperatingRate = 1;
=======
private @Nullable ArrayDeque<MediaCodecInfo> availableCodecInfos;
private @Nullable DecoderInitializationException preferredDecoderInitializationException;
private @Nullable MediaCodecInfo codecInfo;
>>>>>>>
private float codecOperatingRate = 1;
private @Nullable ArrayDeque<MediaCodecInfo> availableCodecInfos;
private @Nullable DecoderInitializationException preferredDecoderInitializationException;
private @Nullable MediaCodecInfo codecInfo; |
<<<<<<<
private boolean focusSkipButtonWhenAvailable;
=======
private int mediaBitrate;
>>>>>>>
private int mediaBitrate;
private boolean focusSkipButtonWhenAvailable;
<<<<<<<
focusSkipButtonWhenAvailable = true;
=======
mediaBitrate = BITRATE_UNSET;
>>>>>>>
mediaBitrate = BITRATE_UNSET;
focusSkipButtonWhenAvailable = true;
<<<<<<<
/**
* Sets whether to focus the skip button (when available) on Android TV devices. The default
* setting is {@code true}.
*
* @param focusSkipButtonWhenAvailable Whether to focus the skip button (when available) on
* Android TV devices.
* @return This builder, for convenience.
* @see AdsRenderingSettings#setFocusSkipButtonWhenAvailable(boolean)
*/
public Builder setFocusSkipButtonWhenAvailable(boolean focusSkipButtonWhenAvailable) {
this.focusSkipButtonWhenAvailable = focusSkipButtonWhenAvailable;
return this;
}
=======
/**
* Sets the ad media maximum recommended bitrate, in bps.
*
* @param bitrate The ad media maximum recommended bitrate, in bps.
* @return This builder, for convenience.
* @see AdsRenderingSettings#setBitrateKbps(int)
*/
public Builder setMaxMediaBitrate(int bitrate) {
Assertions.checkArgument(bitrate > 0);
this.mediaBitrate = bitrate;
return this;
}
>>>>>>>
/**
* Sets the media maximum recommended bitrate for ads, in bps.
*
* @param bitrate The media maximum recommended bitrate for ads, in bps.
* @return This builder, for convenience.
* @see AdsRenderingSettings#setBitrateKbps(int)
*/
public Builder setMaxMediaBitrate(int bitrate) {
Assertions.checkArgument(bitrate > 0);
this.mediaBitrate = bitrate;
return this;
}
/**
* Sets whether to focus the skip button (when available) on Android TV devices. The default
* setting is {@code true}.
*
* @param focusSkipButtonWhenAvailable Whether to focus the skip button (when available) on
* Android TV devices.
* @return This builder, for convenience.
* @see AdsRenderingSettings#setFocusSkipButtonWhenAvailable(boolean)
*/
public Builder setFocusSkipButtonWhenAvailable(boolean focusSkipButtonWhenAvailable) {
this.focusSkipButtonWhenAvailable = focusSkipButtonWhenAvailable;
return this;
}
<<<<<<<
focusSkipButtonWhenAvailable,
=======
mediaBitrate,
adUiElements,
>>>>>>>
mediaBitrate,
focusSkipButtonWhenAvailable,
adUiElements,
<<<<<<<
focusSkipButtonWhenAvailable,
=======
mediaBitrate,
adUiElements,
>>>>>>>
mediaBitrate,
focusSkipButtonWhenAvailable,
adUiElements,
<<<<<<<
private final boolean focusSkipButtonWhenAvailable;
=======
private final int mediaBitrate;
private final @Nullable Set<UiElement> adUiElements;
>>>>>>>
private final boolean focusSkipButtonWhenAvailable;
private final int mediaBitrate;
private final @Nullable Set<UiElement> adUiElements;
<<<<<<<
/* focusSkipButtonWhenAvailable= */ true,
=======
/* mediaBitrate= */ BITRATE_UNSET,
/* adUiElements= */ null,
>>>>>>>
/* mediaBitrate= */ BITRATE_UNSET,
/* focusSkipButtonWhenAvailable= */ true,
/* adUiElements= */ null,
<<<<<<<
/* focusSkipButtonWhenAvailable= */ true,
=======
/* mediaBitrate= */ BITRATE_UNSET,
/* adUiElements= */ null,
>>>>>>>
/* mediaBitrate= */ BITRATE_UNSET,
/* focusSkipButtonWhenAvailable= */ true,
/* adUiElements= */ null,
<<<<<<<
boolean focusSkipButtonWhenAvailable,
=======
int mediaBitrate,
@Nullable Set<UiElement> adUiElements,
>>>>>>>
int mediaBitrate,
boolean focusSkipButtonWhenAvailable,
@Nullable Set<UiElement> adUiElements,
<<<<<<<
this.focusSkipButtonWhenAvailable = focusSkipButtonWhenAvailable;
=======
this.mediaBitrate = mediaBitrate;
this.adUiElements = adUiElements;
>>>>>>>
this.mediaBitrate = mediaBitrate;
this.focusSkipButtonWhenAvailable = focusSkipButtonWhenAvailable;
this.adUiElements = adUiElements;
<<<<<<<
adsRenderingSettings.setFocusSkipButtonWhenAvailable(focusSkipButtonWhenAvailable);
=======
if (mediaBitrate != BITRATE_UNSET) {
adsRenderingSettings.setBitrateKbps(mediaBitrate / 1000);
}
if (adUiElements != null) {
adsRenderingSettings.setUiElements(adUiElements);
}
>>>>>>>
if (mediaBitrate != BITRATE_UNSET) {
adsRenderingSettings.setBitrateKbps(mediaBitrate / 1000);
}
adsRenderingSettings.setFocusSkipButtonWhenAvailable(focusSkipButtonWhenAvailable);
if (adUiElements != null) {
adsRenderingSettings.setUiElements(adUiElements);
} |
<<<<<<<
=======
@Test
public void testDecodeNoEndTimecodes() throws IOException {
SsaDecoder decoder = new SsaDecoder();
byte[] bytes =
TestUtil.getByteArray(ApplicationProvider.getApplicationContext(), NO_END_TIMECODES);
Subtitle subtitle = decoder.decode(bytes, bytes.length, false);
assertThat(subtitle.getEventTimeCount()).isEqualTo(3);
assertThat(subtitle.getEventTime(0)).isEqualTo(0);
assertThat(subtitle.getCues(subtitle.getEventTime(0)).get(0).text.toString())
.isEqualTo("This is the first subtitle.");
assertThat(subtitle.getEventTime(1)).isEqualTo(2340000);
assertThat(subtitle.getCues(subtitle.getEventTime(1)).get(0).text.toString())
.isEqualTo("This is the first subtitle.");
assertThat(subtitle.getCues(subtitle.getEventTime(1)).get(1).text.toString())
.isEqualTo("This is the second subtitle \nwith a newline \nand another.");
assertThat(subtitle.getEventTime(2)).isEqualTo(4560000);
assertThat(subtitle.getCues(subtitle.getEventTime(1)).get(0).text.toString())
.isEqualTo("This is the first subtitle.");
assertThat(subtitle.getCues(subtitle.getEventTime(1)).get(1).text.toString())
.isEqualTo("This is the second subtitle \nwith a newline \nand another.");
assertThat(subtitle.getCues(subtitle.getEventTime(2)).get(2).text.toString())
.isEqualTo("This is the third subtitle, with a comma.");
}
>>>>>>> |
<<<<<<<
=======
public int calculatePreferredAlignment() {
finalCueString = new SpannableStringBuilder();
// Add any rolled up captions, separated by new lines.
for (int i = 0; i < rolledUpCaptions.size(); i++) {
finalCueString.append(rolledUpCaptions.get(i));
finalCueString.append('\n');
}
// Add the current line.
finalCueString.append(buildSpannableString());
if (finalCueString.length() == 0) {
// The cue is empty, it does not influence alignment
return Cue.ANCHOR_TYPE_END;
}
// The number of empty columns before the start of the text, in the range [0-31].
startPadding = indent + tabOffset;
// The number of empty columns after the end of the text, in the same range.
endPadding = SCREEN_CHARWIDTH - startPadding - finalCueString.length();
int startEndPaddingDelta = startPadding - endPadding;
if (captionMode == CC_MODE_POP_ON && (Math.abs(startEndPaddingDelta) < 3 || endPadding < 0)) {
return Cue.ANCHOR_TYPE_MIDDLE;
} else if (captionMode == CC_MODE_POP_ON && startEndPaddingDelta > 0 && endPadding < 4) {
// endPadding check added to avoid RIGHT aligning short texts close to the middle of the
// screen
return Cue.ANCHOR_TYPE_END;
}
return Cue.ANCHOR_TYPE_START;
}
public Cue build(int positionAnchor) {
// Making sure, no-one calls build() without having the alignment function called first
if (finalCueString == null) {
calculatePreferredAlignment();
}
if (finalCueString.length() == 0) {
// The cue is empty.
return null;
}
float position;
if (positionAnchor == Cue.ANCHOR_TYPE_MIDDLE) {
// Treat approximately centered pop-on captions as middle aligned. We also treat captions
// that are wider than they should be in this way. See
// https://github.com/google/ExoPlayer/issues/3534.
position = 0.5f;
} else if (positionAnchor == Cue.ANCHOR_TYPE_END) {
// Treat pop-on captions with less padding at the end than the start as end aligned.
position = (float) (SCREEN_CHARWIDTH - endPadding) / SCREEN_CHARWIDTH;
// Adjust the position to fit within the safe area.
position = position * 0.8f + 0.1f;
} else {
// For all other cases assume start aligned.
position = (float) startPadding / SCREEN_CHARWIDTH;
// Adjust the position to fit within the safe area.
position = position * 0.8f + 0.1f;
}
int lineAnchor;
int line;
// Note: Row indices are in the range [1-15].
if (captionMode == CC_MODE_ROLL_UP || row > (BASE_ROW / 2)) {
lineAnchor = Cue.ANCHOR_TYPE_END;
line = row - BASE_ROW;
// Two line adjustments. The first is because line indices from the bottom of the window
// start from -1 rather than 0. The second is a blank row to act as the safe area.
line -= 2;
} else {
lineAnchor = Cue.ANCHOR_TYPE_START;
// Line indices from the top of the window start from 0, but we want a blank row to act as
// the safe area. As a result no adjustment is necessary.
line = row;
}
Cue result = new Cue(finalCueString, Alignment.ALIGN_NORMAL, line, Cue.LINE_TYPE_NUMBER,
lineAnchor, position, positionAnchor, Cue.DIMEN_UNSET);
finalCueString = null;
return result;
}
@Override
public String toString() {
return captionStringBuilder.toString();
}
>>>>>>> |
<<<<<<<
import com.google.android.exoplayer2.util.ColorParser;
=======
import com.google.android.exoplayer2.text.span.HorizontalTextInVerticalContextSpan;
import com.google.android.exoplayer2.text.span.RubySpan;
import com.google.android.exoplayer2.util.Assertions;
import com.google.android.exoplayer2.util.Log;
>>>>>>>
import com.google.android.exoplayer2.text.span.HorizontalTextInVerticalContextSpan;
import com.google.android.exoplayer2.text.span.RubySpan;
import com.google.android.exoplayer2.util.Assertions;
import com.google.android.exoplayer2.util.ColorParser;
import com.google.android.exoplayer2.util.Log; |
<<<<<<<
import com.google.android.exoplayer.demo.full.player.UnsupportedDrmException;
=======
import com.google.android.exoplayer.metadata.TxxxMetadata;
>>>>>>>
import com.google.android.exoplayer.demo.full.player.UnsupportedDrmException;
import com.google.android.exoplayer.metadata.TxxxMetadata;
<<<<<<<
DemoPlayer.Listener, DemoPlayer.TextListener, AudioCapabilitiesReceiver.Listener {
=======
DemoPlayer.Listener, DemoPlayer.TextListener, DemoPlayer.Id3MetadataListener {
private static final String TAG = "FullPlayerActivity";
>>>>>>>
DemoPlayer.Listener, DemoPlayer.TextListener, DemoPlayer.Id3MetadataListener,
AudioCapabilitiesReceiver.Listener {
private static final String TAG = "FullPlayerActivity";
<<<<<<<
new WidevineTestMediaDrmCallback(contentId), debugTextView, audioCapabilities);
=======
new WidevineTestMediaDrmCallback(contentId), debugTextView);
case DemoUtil.TYPE_HLS:
return new HlsRendererBuilder(userAgent, contentUri.toString(), contentId);
>>>>>>>
new WidevineTestMediaDrmCallback(contentId), debugTextView, audioCapabilities);
case DemoUtil.TYPE_HLS:
return new HlsRendererBuilder(userAgent, contentUri.toString(), contentId); |
<<<<<<<
AudioRendererEventListener, TextRenderer.Output, MetadataRenderer.Output<List<Id3Frame>>,
SurfaceHolder.Callback, TextureView.SurfaceTextureListener,
TrackSelector.EventListener<Object> {
=======
AudioRendererEventListener, TextRenderer.Output, MetadataRenderer.Output<Metadata>,
SurfaceHolder.Callback {
>>>>>>>
AudioRendererEventListener, TextRenderer.Output, MetadataRenderer.Output<Metadata>,
SurfaceHolder.Callback, TextureView.SurfaceTextureListener,
TrackSelector.EventListener<Object> { |
<<<<<<<
import androidx.annotation.Nullable;
=======
import android.os.Handler;
import android.support.annotation.Nullable;
>>>>>>>
import android.os.Handler;
import androidx.annotation.Nullable; |
<<<<<<<
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.domain.EntityScan;
import org.springframework.context.annotation.Bean;
=======
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.cloud.openfeign.EnableFeignClients;
import org.springframework.cloud.openfeign.FeignClient;
>>>>>>>
import org.springframework.boot.autoconfigure.domain.EntityScan;
import org.springframework.cloud.openfeign.EnableFeignClients;
import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.context.annotation.Bean;
<<<<<<<
@EnableJpaRepositories(
basePackages = "de.adorsys.opba.fintech.impl.database.repositories",
repositoryBaseClass = UserRepositoryImpl.class)
=======
@EnableFeignClients
>>>>>>>
@EnableFeignClients
@EnableJpaRepositories(
basePackages = "de.adorsys.opba.fintech.impl.database.repositories",
repositoryBaseClass = UserRepositoryImpl.class) |
<<<<<<<
switch (transactions.getStatusCode()) {
case OK:
return new ResponseEntity<>(ManualMapper.fromTppToFintech(transactions.getBody()), HttpStatus.OK);
case ACCEPTED:
log.info("create redirect entity for lot for redirectcode {}", fintechRedirectCode);
redirectHandlerService.registerRedirectStateForSession(fintechRedirectCode, fintechOkUrl, fintechNOkUrl);
return handleAccepted(fintechRedirectCode, sessionEntity, transactions.getHeaders());
case UNAUTHORIZED:
return new ResponseEntity<>(HttpStatus.UNAUTHORIZED);
default:
throw new RuntimeException("DID NOT EXPECT RETURNCODE:" + transactions.getStatusCode());
}
=======
>>>>>>>
switch (transactions.getStatusCode()) {
case OK:
return new ResponseEntity<>(ManualMapper.fromTppToFintech(transactions.getBody()), HttpStatus.OK);
case ACCEPTED:
log.info("create redirect entity for lot for redirectcode {}", fintechRedirectCode);
redirectHandlerService.registerRedirectStateForSession(fintechRedirectCode, fintechOkUrl, fintechNOkUrl);
return handleAccepted(fintechRedirectCode, sessionEntity, transactions.getHeaders());
case UNAUTHORIZED:
return new ResponseEntity<>(HttpStatus.UNAUTHORIZED);
default:
throw new RuntimeException("DID NOT EXPECT RETURNCODE:" + transactions.getStatusCode());
} |
<<<<<<<
public static final String SELECT_DATE = "SELECT DATE";
public static final String SI_ID = "standing_instruction_id";
=======
public static final String UNAUTHORIZED_ERROR = "401 Unauthorized";
>>>>>>>
public static final String SELECT_DATE = "SELECT DATE";
public static final String SI_ID = "standing_instruction_id";
public static final String UNAUTHORIZED_ERROR = "401 Unauthorized"; |
<<<<<<<
if (t.isSuccessToken()) {
synchronized ((Object) successSourceCount) {
successSourceCount++;
}
log.debug(String.format("Success count of %s: %d", node.toString(), successSourceCount));
} else {
return false;
=======
if (t.isSuccessToken()) {
successSourceCount++;
log.debug(String.format("Success count of %s: %d", node.toString(), successSourceCount));
} else {
return false;
>>>>>>>
if (t.isSuccessToken()) {
synchronized ((Object) successSourceCount) {
successSourceCount++;
}
log.trace(String.format("Success count of %s: %d", node.toString(), successSourceCount));
} else {
return false; |
<<<<<<<
import java.util.ArrayList;
import java.util.List;
=======
import com.google.common.base.Optional;
>>>>>>>
import java.util.ArrayList;
import java.util.List;
import com.google.common.base.Optional; |
<<<<<<<
@Override
public String getApproximateCountDistinct(String column) {
return String.format("ndv(%s)", column);
}
=======
@Override
public String getGenericStringDataTypeName() {
return "STRING";
}
>>>>>>>
@Override
public String getGenericStringDataTypeName() {
return "STRING";
}
@Override
public String getApproximateCountDistinct(String column) {
return String.format("ndv(%s)", column);
} |
<<<<<<<
import org.verdictdb.commons.DBTablePrinter;
=======
import org.verdictdb.commons.DataTypeConverter;
>>>>>>>
import org.verdictdb.commons.DBTablePrinter;
import org.verdictdb.commons.DataTypeConverter;
<<<<<<<
// Print in database form
public void print() {
VerdictResultSet vrs = new VerdictResultSet(this);
DBTablePrinter.printResultSet(vrs);
}
// // implemented in AttributeValueRetrievalHelper
// public abstract String getString(int index);
//
// public String getString(String label);
//
// public Boolean getBoolean(int index) throws SQLException;
//
// public Boolean getBoolean(String label) throws SQLException;
//
// public int getInt(int index);
//
// public int getInt(String label);
//
// public long getLong(int index);
//
// public long getLong(String label);
//
// public short getShort(int index);
//
// public short getShort(String label);
//
// public double getDouble(int index);
//
// public double getDouble(String label);
//
// public float getFloat(int index);
//
// public float getFloat(String label);
//
// public Date getDate(int index);
//
// public Date getDate(String label);
//
// public byte getByte(int index);
//
// public byte getByte(String label);
//
// public Timestamp getTimestamp(int index);
//
// public Timestamp getTimestamp(String label);
//
// public BigDecimal getBigDecimal(int index, int scale);
//
// public BigDecimal getBigDecimal(String label, int scale);
//
// public BigDecimal getBigDecimal(int index);
//
// public BigDecimal getBigDecimal(String label);
//
// public byte[] getBytes(int index);
//
// public byte[] getBytes(String label);
//
// public Time getTime(int index);
//
// public Time getTime(String label);
//
// public InputStream getAsciiStream(int index);
//
// public InputStream getAsciiStream(String label);
//
// public InputStream getUnicodeStream(int index);
//
// public InputStream getUnicodeStream(String label);
//
// public InputStream getBinaryStream(int index);
//
// public InputStream getBinaryStream(String label);
//
// public Ref getRef(int index);
//
// public Ref getRef(String label);
//
// public Blob getBlob(int index) throws SQLException;
//
// public Blob getBlob(String label) throws SQLException;
//
// public Clob getClob(int index);
//
// public Clob getClob(String label);
//
// public Array getArray(int index);
//
// public Array getArray(String label);
//
// public URL getURL(int index);
//
// public URL getURL(String label);
//
// public RowId getRowId(int index);
//
// public RowId getRowId(String label);
//
// public NClob getNClob(int index);
//
// public NClob getNClob(String label);
//
// public SQLXML getSQLXML(int index);
//
// public SQLXML getSQLXML(String label);
//
=======
>>>>>>>
// Print in database form
public void print() {
VerdictResultSet vrs = new VerdictResultSet(this);
DBTablePrinter.printResultSet(vrs);
}
// // implemented in AttributeValueRetrievalHelper
// public abstract String getString(int index);
//
// public String getString(String label);
//
// public Boolean getBoolean(int index) throws SQLException;
//
// public Boolean getBoolean(String label) throws SQLException;
//
// public int getInt(int index);
//
// public int getInt(String label);
//
// public long getLong(int index);
//
// public long getLong(String label);
//
// public short getShort(int index);
//
// public short getShort(String label);
//
// public double getDouble(int index);
//
// public double getDouble(String label);
//
// public float getFloat(int index);
//
// public float getFloat(String label);
//
// public Date getDate(int index);
//
// public Date getDate(String label);
//
// public byte getByte(int index);
//
// public byte getByte(String label);
//
// public Timestamp getTimestamp(int index);
//
// public Timestamp getTimestamp(String label);
//
// public BigDecimal getBigDecimal(int index, int scale);
//
// public BigDecimal getBigDecimal(String label, int scale);
//
// public BigDecimal getBigDecimal(int index);
//
// public BigDecimal getBigDecimal(String label);
//
// public byte[] getBytes(int index);
//
// public byte[] getBytes(String label);
//
// public Time getTime(int index);
//
// public Time getTime(String label);
//
// public InputStream getAsciiStream(int index);
//
// public InputStream getAsciiStream(String label);
//
// public InputStream getUnicodeStream(int index);
//
// public InputStream getUnicodeStream(String label);
//
// public InputStream getBinaryStream(int index);
//
// public InputStream getBinaryStream(String label);
//
// public Ref getRef(int index);
//
// public Ref getRef(String label);
//
// public Blob getBlob(int index) throws SQLException;
//
// public Blob getBlob(String label) throws SQLException;
//
// public Clob getClob(int index);
//
// public Clob getClob(String label);
//
// public Array getArray(int index);
//
// public Array getArray(String label);
//
// public URL getURL(int index);
//
// public URL getURL(String label);
//
// public RowId getRowId(int index);
//
// public RowId getRowId(String label);
//
// public NClob getNClob(int index);
//
// public NClob getNClob(String label);
//
// public SQLXML getSQLXML(int index);
//
// public SQLXML getSQLXML(String label);
// |
<<<<<<<
File cmdFile = createCommandFile(cmd, env);
Process p =
super.exec(project, new String[] {cmdFile.getPath()}, env);
=======
File cmdFile = createCommandFile(project, cmd, env);
Process p = super.exec(project, new String[] {cmdFile.getPath()}, env);
>>>>>>>
File cmdFile = createCommandFile(project, cmd, env);
Process p =
super.exec(project, new String[] {cmdFile.getPath()}, env);
<<<<<<<
File cmdFile = createCommandFile(cmd, env);
Process p = super.exec(project, new String[] {cmdFile.getPath()}, env,
workingDir);
=======
File cmdFile = createCommandFile(project, cmd, env);
Process p = super.exec(project, new String[] {cmdFile.getPath()}, env, workingDir);
>>>>>>>
File cmdFile = createCommandFile(project, cmd, env);
Process p = super.exec(project, new String[] {cmdFile.getPath()}, env,
workingDir);
<<<<<<<
File script = FILE_UTILS.createTempFile("ANT", ".COM", null, true, true);
try (BufferedWriter out = new BufferedWriter(new FileWriter(script))) {
=======
File script = FILE_UTILS.createTempFile(project, "ANT", ".COM", null, true, true);
BufferedWriter out = null;
try {
out = new BufferedWriter(new FileWriter(script));
>>>>>>>
File script = FILE_UTILS.createTempFile(project, "ANT", ".COM", null, true, true);
try (BufferedWriter out = new BufferedWriter(new FileWriter(script))) { |
<<<<<<<
SIGN, STRTOL, RAND, RANDOM , FNV_HASH, ABS, STDDEV, SQRT, MOD, PMOD,
=======
SIGN, RAND, RANDOM , FNV_HASH, ABS, STDDEV, SQRT, MOD, PMOD, YEAR,
>>>>>>>
SIGN, STRTOL, RAND, RANDOM , FNV_HASH, ABS, STDDEV, SQRT, MOD, PMOD, YEAR, |
<<<<<<<
import java.sql.Connection;
import java.sql.SQLException;
import java.util.Collection;
import java.util.LinkedList;
import java.util.List;
import java.util.Properties;
=======
>>>>>>>
import java.sql.Connection;
import java.sql.SQLException;
import java.util.Collection;
import java.util.LinkedList;
import java.util.List;
import java.util.Properties; |
<<<<<<<
=======
import org.apache.commons.lang3.tuple.Pair;
import org.verdictdb.sql.syntax.SyntaxAbstract;
>>>>>>> |
<<<<<<<
import com.google.common.base.Joiner;
=======
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ThreadLocalRandom;
>>>>>>>
import com.google.common.base.Joiner;
<<<<<<<
import org.verdictdb.core.sqlobject.*;
=======
import org.verdictdb.core.sqlobject.AsteriskColumn;
import org.verdictdb.core.sqlobject.BaseTable;
import org.verdictdb.core.sqlobject.CreateScrambledTableQuery;
import org.verdictdb.core.sqlobject.CreateTableAsSelectQuery;
import org.verdictdb.core.sqlobject.CreateTableDefinitionQuery;
import org.verdictdb.core.sqlobject.CreateTableQuery;
import org.verdictdb.core.sqlobject.DropTableQuery;
import org.verdictdb.core.sqlobject.SelectQuery;
>>>>>>>
import org.verdictdb.core.sqlobject.*;
<<<<<<<
sql =
(syntax instanceof PostgresqlSyntax)
? createPartitionTableToSql((CreateScrambledTableQuery) query)
: createAsSelectQueryToSql(
new CreateTableAsSelectQuery((CreateScrambledTableQuery) query));
=======
if (syntax instanceof PostgresqlSyntax) {
sql = createPostgresqlPartitionTableToSql((CreateScrambledTableQuery) query);
} else if (syntax instanceof ImpalaSyntax) {
sql = createImpalaPartitionTableToSql((CreateScrambledTableQuery) query);
} else {
sql = createAsSelectQueryToSql(new CreateTableAsSelectQuery((CreateScrambledTableQuery) query));
}
>>>>>>>
if (syntax instanceof PostgresqlSyntax) {
sql = createPostgresqlPartitionTableToSql((CreateScrambledTableQuery) query);
} else if (syntax instanceof ImpalaSyntax) {
sql = createImpalaPartitionTableToSql((CreateScrambledTableQuery) query);
} else {
sql =
createAsSelectQueryToSql(
new CreateTableAsSelectQuery((CreateScrambledTableQuery) query));
}
<<<<<<<
private String createPartitionTableToSql(CreateScrambledTableQuery query)
throws VerdictDBException {
=======
private String createImpalaPartitionTableToSql(CreateScrambledTableQuery query) throws VerdictDBException {
// 1. This method should only get called when the target DB is Impala.
// 2. Currently, Impala's create-table-as-select has a bug; dynamic partitioning is faulty
// when used in conjunction with rand();
if (!(syntax instanceof ImpalaSyntax)) {
throw new VerdictDBException("Target database must be Impala.");
}
StringBuilder sql = new StringBuilder();
String schemaName = query.getSchemaName();
String tableName = query.getTableName();
SelectQuery select = query.getSelect();
// this table will be created and dropped at the end
int randomNum = ThreadLocalRandom.current().nextInt(0, 10000);
String tempTableName = "verdictdb_scrambling_temp_" + randomNum;
// create a non-partitioned temp table as a select
CreateTableAsSelectQuery tempCreate = new CreateTableAsSelectQuery(schemaName, tempTableName, select);
sql.append(QueryToSql.convert(syntax, tempCreate));
sql.append(";");
// insert the temp table into a partitioned table.
String aliasName = "t";
SelectQuery selectAllFromTemp = SelectQuery.create(
new AsteriskColumn(),
new BaseTable(schemaName, tempTableName, aliasName));
CreateTableAsSelectQuery insert =
new CreateTableAsSelectQuery(schemaName, tableName, selectAllFromTemp);
for (String col : query.getPartitionColumns()) {
insert.addPartitionColumn(col);
}
sql.append(QueryToSql.convert(syntax, insert));
sql.append(";");
// drop the temp table
DropTableQuery drop = new DropTableQuery(schemaName, tempTableName);
sql.append(QueryToSql.convert(syntax, drop));
sql.append(";");
return sql.toString();
}
private String createPostgresqlPartitionTableToSql(CreateScrambledTableQuery query) throws VerdictDBException {
>>>>>>>
private String createImpalaPartitionTableToSql(CreateScrambledTableQuery query)
throws VerdictDBException {
// 1. This method should only get called when the target DB is Impala.
// 2. Currently, Impala's create-table-as-select has a bug; dynamic partitioning is faulty
// when used in conjunction with rand();
if (!(syntax instanceof ImpalaSyntax)) {
throw new VerdictDBException("Target database must be Impala.");
}
StringBuilder sql = new StringBuilder();
String schemaName = query.getSchemaName();
String tableName = query.getTableName();
SelectQuery select = query.getSelect();
// this table will be created and dropped at the end
int randomNum = ThreadLocalRandom.current().nextInt(0, 10000);
String tempTableName = "verdictdb_scrambling_temp_" + randomNum;
// create a non-partitioned temp table as a select
CreateTableAsSelectQuery tempCreate =
new CreateTableAsSelectQuery(schemaName, tempTableName, select);
sql.append(QueryToSql.convert(syntax, tempCreate));
sql.append(";");
// insert the temp table into a partitioned table.
String aliasName = "t";
SelectQuery selectAllFromTemp =
SelectQuery.create(
new AsteriskColumn(), new BaseTable(schemaName, tempTableName, aliasName));
CreateTableAsSelectQuery insert =
new CreateTableAsSelectQuery(schemaName, tableName, selectAllFromTemp);
for (String col : query.getPartitionColumns()) {
insert.addPartitionColumn(col);
}
sql.append(QueryToSql.convert(syntax, insert));
sql.append(";");
// drop the temp table
DropTableQuery drop = new DropTableQuery(schemaName, tempTableName);
sql.append(QueryToSql.convert(syntax, drop));
sql.append(";");
return sql.toString();
}
private String createPostgresqlPartitionTableToSql(CreateScrambledTableQuery query)
throws VerdictDBException {
<<<<<<<
if (syntax instanceof PostgresqlSyntax) {
sql.append("; ");
// create child partition tables for postgres
for (int blockNum = 0; blockNum < blockCount; ++blockNum) {
sql.append("create table ");
if (query.isIfNotExists()) {
sql.append("if not exists ");
}
sql.append(quoteName(schemaName));
sql.append(".");
sql.append(
quoteName(
String.format(
"%s" + PostgresqlSyntax.CHILD_PARTITION_TABLE_SUFFIX, tableName, blockNum)));
sql.append(
String.format(
" partition of %s.%s for values in (%d); ",
quoteName(schemaName), quoteName(tableName), blockNum));
=======
sql.append("; ")
;
// create child partition tables for postgres
for (int blockNum = 0; blockNum < blockCount; ++blockNum) {
sql.append("create table ");
if (query.isIfNotExists()) {
sql.append("if not exists ");
>>>>>>>
sql.append("; ");
// create child partition tables for postgres
for (int blockNum = 0; blockNum < blockCount; ++blockNum) {
sql.append("create table ");
if (query.isIfNotExists()) {
sql.append("if not exists "); |
<<<<<<<
=======
public static ColumnOp notgreaterthan(UnnamedColumn column1, UnnamedColumn column2) {
return new ColumnOp("notgreaterthan", Arrays.asList(column1, column2));
}
public static ColumnOp notlessthan(UnnamedColumn column1, UnnamedColumn column2) {
return new ColumnOp("notlessthan", Arrays.asList(column1, column2));
}
public static ColumnOp add(UnnamedColumn column1, UnnamedColumn column2) {
return new ColumnOp("add", Arrays.asList(column1, column2));
}
>>>>>>>
public static ColumnOp notgreaterthan(UnnamedColumn column1, UnnamedColumn column2) {
return new ColumnOp("notgreaterthan", Arrays.asList(column1, column2));
}
public static ColumnOp notlessthan(UnnamedColumn column1, UnnamedColumn column2) {
return new ColumnOp("notlessthan", Arrays.asList(column1, column2));
}
public static ColumnOp add(UnnamedColumn column1, UnnamedColumn column2) {
return new ColumnOp("add", Arrays.asList(column1, column2));
} |
<<<<<<<
ExecutionInfoToken result = super.executeNode(conn, downstreamResults);
// This node is one of the individual aggregate nodes inside an AsyncAggExecutionNode
if (parents.get(0) instanceof AsyncAggScaleExecutionNode) {
QueryExecutionNode asyncNode = parents.get(0);
int index = -1;
if (asyncNode.getParents().size()==2) {
index = 0;
asyncNode = asyncNode.getParents().get(1);
}
else {
AsyncAggExecutionNode asyncRoot = asyncNode.getParents().get(0).getParents().size()==2?
(AsyncAggExecutionNode) asyncNode.getParents().get(0).getParents().get(1):(AsyncAggExecutionNode) asyncNode.getParents().get(0).getParents().get(0);
index = asyncRoot.getDependents().indexOf(asyncNode.getParents().get(0));
asyncNode = asyncRoot;
}
// Assume only one scramble table in the query
BaseTable scrambleTable = ((AsyncAggExecutionNode)asyncNode).getScrambleTables().get(0);
Dimension dimension = new Dimension(scrambleTable.getSchemaName(), scrambleTable.getTableName(), index, index);
result.setKeyValue("hyperTableCube", Arrays.asList(new HyperTableCube(Arrays.asList(dimension))));
}
return result;
=======
ExecutionInfoToken result = super.executeNode(conn, downstreamResults);
// This node is one of the individual aggregate nodes inside an AsyncAggExecutionNode
// This part should not be execution part; it should be a construction part.
// Let's move this part to the AggExecutionNodeBlock around line 112.
// if (parents.size()==1 && (parents.get(0) instanceof AsyncAggExecutionNode || parents.get(0) instanceof AggCombinerExecutionNode)) {
// QueryExecutionNode asyncNode = parents.get(0);
// int index = 0;
// while (!(asyncNode instanceof AsyncAggExecutionNode)) {
// asyncNode = asyncNode.parents.get(0);
// index++;
// }
// // Assume only one scramble table in the query
// BaseTable scrambleTable = ((AsyncAggExecutionNode)asyncNode).getScrambleTables().get(0);
// Dimension dimension = new Dimension(scrambleTable.getSchemaName(), scrambleTable.getTableName(), index, index);
// result.setKeyValue("hyperTableCube", Arrays.asList(new HyperTableCube(Arrays.asList(dimension))));
// }
return result;
>>>>>>>
ExecutionInfoToken result = super.executeNode(conn, downstreamResults);
// This node is one of the individual aggregate nodes inside an AsyncAggExecutionNode
// This part should not be execution part; it should be a construction part.
// Let's move this part to the AggExecutionNodeBlock around line 112.
// if (parents.size()==1 && (parents.get(0) instanceof AsyncAggExecutionNode || parents.get(0) instanceof AggCombinerExecutionNode)) {
// QueryExecutionNode asyncNode = parents.get(0);
// int index = 0;
// while (!(asyncNode instanceof AsyncAggExecutionNode)) {
// asyncNode = asyncNode.parents.get(0);
// index++;
// }
// // Assume only one scramble table in the query
// BaseTable scrambleTable = ((AsyncAggExecutionNode)asyncNode).getScrambleTables().get(0);
// Dimension dimension = new Dimension(scrambleTable.getSchemaName(), scrambleTable.getTableName(), index, index);
// result.setKeyValue("hyperTableCube", Arrays.asList(new HyperTableCube(Arrays.asList(dimension))));
// }
if (parents.get(0) instanceof AsyncAggScaleExecutionNode) {
QueryExecutionNode asyncNode = parents.get(0);
int index = -1;
if (asyncNode.getParents().size()==2) {
index = 0;
asyncNode = asyncNode.getParents().get(1);
}
else {
AsyncAggExecutionNode asyncRoot = asyncNode.getParents().get(0).getParents().size()==2?
(AsyncAggExecutionNode) asyncNode.getParents().get(0).getParents().get(1):(AsyncAggExecutionNode) asyncNode.getParents().get(0).getParents().get(0);
index = asyncRoot.getDependents().indexOf(asyncNode.getParents().get(0));
asyncNode = asyncRoot;
}
// Assume only one scramble table in the query
BaseTable scrambleTable = ((AsyncAggExecutionNode)asyncNode).getScrambleTables().get(0);
Dimension dimension = new Dimension(scrambleTable.getSchemaName(), scrambleTable.getTableName(), index, index);
result.setKeyValue("hyperTableCube", Arrays.asList(new HyperTableCube(Arrays.asList(dimension))));
}
return result; |
<<<<<<<
import org.verdictdb.sqlsyntax.HiveSyntax;
import org.verdictdb.sqlsyntax.SparkSyntax;
=======
import org.verdictdb.exception.VerdictDBTypeException;
>>>>>>>
import org.verdictdb.exception.VerdictDBTypeException;
import org.verdictdb.sqlsyntax.HiveSyntax;
import org.verdictdb.sqlsyntax.SparkSyntax; |
<<<<<<<
import com.rits.cloning.Cloner;
=======
import com.google.common.base.Optional;
>>>>>>>
import com.google.common.base.Optional;
import com.rits.cloning.Cloner;
<<<<<<<
return new Cloner().deepClone(result);
// try {
// ByteArrayOutputStream bos = new ByteArrayOutputStream();
// ObjectOutputStream out = new ObjectOutputStream(bos);
// out.writeObject(result);
// out.flush();
// out.close();
//
// ObjectInputStream in = new ObjectInputStream(
// new ByteArrayInputStream(bos.toByteArray()));
// DbmsQueryResult copied = (DbmsQueryResult) in.readObject();
// return copied;
//
// } catch (ClassNotFoundException e) {
// e.printStackTrace();
// } catch (NotSerializableException e) {
// e.printStackTrace();
// } catch (IOException e) {
// e.printStackTrace();
// }
// return null;
=======
try {
ByteArrayOutputStream bos = new ByteArrayOutputStream();
ObjectOutputStream out = new ObjectOutputStream(bos);
out.writeObject(result);
out.flush();
out.close();
ObjectInputStream in = new ObjectInputStream(new ByteArrayInputStream(bos.toByteArray()));
DbmsQueryResult copied = (DbmsQueryResult) in.readObject();
return copied;
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (NotSerializableException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
>>>>>>>
DbmsQueryResult copied = new Cloner().deepClone(result);
return new Cloner().deepClone(result);
// try {
// ByteArrayOutputStream bos = new ByteArrayOutputStream();
// ObjectOutputStream out = new ObjectOutputStream(bos);
// out.writeObject(result);
// out.flush();
// out.close();
//
// ObjectInputStream in = new ObjectInputStream(new
// ByteArrayInputStream(bos.toByteArray()));
// DbmsQueryResult copied = (DbmsQueryResult) in.readObject();
// return copied;
//
// } catch (ClassNotFoundException e) {
// e.printStackTrace();
// } catch (NotSerializableException e) {
// e.printStackTrace();
// } catch (IOException e) {
// e.printStackTrace();
// }
// return null; |
<<<<<<<
@Override
public String getApproximateCountDistinct(String column) {
return String.format("approx_count_distinct(%s)", column);
}
=======
@Override
public String getGenericStringDataTypeName() {
return "STRING";
}
>>>>>>>
@Override
public String getGenericStringDataTypeName() {
return "STRING";
}
@Override
public String getApproximateCountDistinct(String column) {
return String.format("approx_count_distinct(%s)", column);
} |
<<<<<<<
=======
// private Map<String, Integer> aggColumnIdentifierMap = new HashMap<>();
>>>>>>>
<<<<<<<
* @param aggNodeBlock A set of the links to the nodes that will be processed in the asynchronous
* manner.
* @return Returns The root of the multiple aggregation nodes (each of which involves
* different combinations of partitions)
=======
* @param aggNodeBlock A set of the links to the nodes that will be processed in the asynchronous
* manner.
* @return Returns The root of the multiple aggregation nodes (each of which involves different
* combinations of partitions)
>>>>>>>
* @param aggNodeBlock A set of the links to the nodes that will be processed in the asynchronous
* manner.
* @return Returns The root of the multiple aggregation nodes (each of which involves different
* combinations of partitions)
<<<<<<<
// List<SelectItem> selectItemList = node.getSelectQuery().getSelectList();
=======
// List<SelectItem> selectItemList = node.getSelectQuery().getSelectList();
>>>>>>>
// List<SelectItem> selectItemList = node.getSelectQuery().getSelectList();
<<<<<<<
// node.getSelectQuery().addSelectItem();
// List<SelectItem> selectItemList = node.getSelectQuery().getSelectList();
// if (selectItemList.get(0) instanceof AsteriskColumn) {
// for (BaseTable t : MultiTiertables) {
// String tierColumnAlias = generateTierColumnAliasName();
//// VERDICTDB_TIER_COLUMN_NAME + verdictdbTierIndentiferNum++;
//
// // Record the tier column alias with its corresponding scramble table
// ScrambleMeta meta = scrambleMeta.getSingleMeta(t.getSchemaName(), t.getTableName());
// node.getAggMeta().getTierColumnForScramble().put(meta, tierColumnAlias);
// }
// } else {
// for (BaseTable t : MultiTiertables) {
// // Add tier column to the select list
// String tierColumnName = scrambleMeta.getTierColumn(t.getSchemaName(), t.getTableName());
// SelectItem tierColumn;
// String tierColumnAlias = generateTierColumnAliasName();
//// VERDICTDB_TIER_COLUMN_NAME + verdictdbTierIndentiferNum++;
// if (t.getAliasName().isPresent()) {
// tierColumn =
// new AliasedColumn(
// new BaseColumn(t.getAliasName().get(), tierColumnName), tierColumnAlias);
// } else {
// tierColumn =
// new AliasedColumn(new BaseColumn(t.getTableName(), tierColumnName), tierColumnAlias);
// }
// selectItemList.add(tierColumn);
//
// // Record the tier column alias with its corresponding scramble table
// ScrambleMeta meta = scrambleMeta.getSingleMeta(t.getSchemaName(), t.getTableName());
// node.getAggMeta().getTierColumnForScramble().put(meta, tierColumnAlias);
// }
// }
// verdictdbTierIndentiferNum = 0;
=======
// node.getSelectQuery().addSelectItem();
// List<SelectItem> selectItemList = node.getSelectQuery().getSelectList();
// if (selectItemList.get(0) instanceof AsteriskColumn) {
// for (BaseTable t : MultiTiertables) {
// String tierColumnAlias = generateTierColumnAliasName();
//// VERDICTDB_TIER_COLUMN_NAME + verdictdbTierIndentiferNum++;
//
// // Record the tier column alias with its corresponding scramble table
// ScrambleMeta meta = scrambleMeta.getSingleMeta(t.getSchemaName(), t.getTableName());
// node.getAggMeta().getTierColumnForScramble().put(meta, tierColumnAlias);
// }
// } else {
// for (BaseTable t : MultiTiertables) {
// // Add tier column to the select list
// String tierColumnName = scrambleMeta.getTierColumn(t.getSchemaName(),
// t.getTableName());
// SelectItem tierColumn;
// String tierColumnAlias = generateTierColumnAliasName();
//// VERDICTDB_TIER_COLUMN_NAME + verdictdbTierIndentiferNum++;
// if (t.getAliasName().isPresent()) {
// tierColumn =
// new AliasedColumn(
// new BaseColumn(t.getAliasName().get(), tierColumnName), tierColumnAlias);
// } else {
// tierColumn =
// new AliasedColumn(new BaseColumn(t.getTableName(), tierColumnName),
// tierColumnAlias);
// }
// selectItemList.add(tierColumn);
//
// // Record the tier column alias with its corresponding scramble table
// ScrambleMeta meta = scrambleMeta.getSingleMeta(t.getSchemaName(), t.getTableName());
// node.getAggMeta().getTierColumnForScramble().put(meta, tierColumnAlias);
// }
// }
// verdictdbTierIndentiferNum = 0;
>>>>>>>
// node.getSelectQuery().addSelectItem();
// List<SelectItem> selectItemList = node.getSelectQuery().getSelectList();
// if (selectItemList.get(0) instanceof AsteriskColumn) {
// for (BaseTable t : MultiTiertables) {
// String tierColumnAlias = generateTierColumnAliasName();
//// VERDICTDB_TIER_COLUMN_NAME + verdictdbTierIndentiferNum++;
//
// // Record the tier column alias with its corresponding scramble table
// ScrambleMeta meta = scrambleMeta.getSingleMeta(t.getSchemaName(), t.getTableName());
// node.getAggMeta().getTierColumnForScramble().put(meta, tierColumnAlias);
// }
// } else {
// for (BaseTable t : MultiTiertables) {
// // Add tier column to the select list
// String tierColumnName = scrambleMeta.getTierColumn(t.getSchemaName(), t.getTableName());
// SelectItem tierColumn;
// String tierColumnAlias = generateTierColumnAliasName();
//// VERDICTDB_TIER_COLUMN_NAME + verdictdbTierIndentiferNum++;
// if (t.getAliasName().isPresent()) {
// tierColumn =
// new AliasedColumn(
// new BaseColumn(t.getAliasName().get(), tierColumnName), tierColumnAlias);
// } else {
// tierColumn =
// new AliasedColumn(new BaseColumn(t.getTableName(), tierColumnName), tierColumnAlias);
// }
// selectItemList.add(tierColumn);
//
// // Record the tier column alias with its corresponding scramble table
// ScrambleMeta meta = scrambleMeta.getSingleMeta(t.getSchemaName(), t.getTableName());
// node.getAggMeta().getTierColumnForScramble().put(meta, tierColumnAlias);
// }
// }
// verdictdbTierIndentiferNum = 0;
<<<<<<<
/**
=======
/*-
>>>>>>>
/*-
<<<<<<<
meta.getAggColumn().put(selectItem.deepcopy(), columnOps);
=======
meta.getAggColumn().put(selectItem, columnOps);
int cnt = 0;
>>>>>>>
meta.getAggColumn().put(selectItem, columnOps);
int cnt = 0;
<<<<<<<
.containsKey(
new ImmutablePair<>("count", (UnnamedColumn) new AsteriskColumn()))) {
=======
.containsKey(
new ImmutablePair<>("count", (UnnamedColumn) new AsteriskColumn()))) {
if (prefix.equals("agg")) {
newAlias = prefix + aggColumnIdentiferNum;
} else {
newAlias += "_cnt";
}
++aggColumnIdentiferNum;
>>>>>>>
.containsKey(
new ImmutablePair<>("count", (UnnamedColumn) new AsteriskColumn()))) {
if (prefix.equals("agg")) {
newAlias = prefix + aggColumnIdentiferNum;
} else {
newAlias += "_cnt";
}
++aggColumnIdentiferNum;
<<<<<<<
if (col.getOpType().equals("count")
&& !meta.getAggColumnAggAliasPair()
.containsKey(
new ImmutablePair<>("count", (UnnamedColumn) (new AsteriskColumn())))) {
ColumnOp col1 = new ColumnOp(col.getOpType());
newSelectlist.add(new AliasedColumn(col1, "agg" + aggColumnIdentiferNum));
meta.getAggColumnAggAliasPair()
.put(
new ImmutablePair<>(col.getOpType(), (UnnamedColumn) new AsteriskColumn()),
"agg" + aggColumnIdentiferNum);
aggColumnAlias.add("agg" + aggColumnIdentiferNum++);
} else if (col.getOpType().equals("sum")
&& !meta.getAggColumnAggAliasPair()
.containsKey(new ImmutablePair<>(col.getOpType(), col.getOperand(0)))) {
ColumnOp col1 = new ColumnOp(col.getOpType(), col.getOperand(0));
newSelectlist.add(new AliasedColumn(col1, "agg" + aggColumnIdentiferNum));
meta.getAggColumnAggAliasPair()
.put(
new ImmutablePair<>(col.getOpType(), col1.getOperand(0)),
"agg" + aggColumnIdentiferNum);
aggColumnAlias.add("agg" + aggColumnIdentiferNum++);
=======
if (col.getOpType().equals("count")) {
if (!meta.getAggColumnAggAliasPair()
.containsKey(
new ImmutablePair<>("count", (UnnamedColumn) (new AsteriskColumn())))) {
ColumnOp col1 = new ColumnOp(col.getOpType());
newSelectlist.add(new AliasedColumn(col1, newAlias));
meta.getAggColumnAggAliasPair()
.put(
new ImmutablePair<>(
col.getOpType(), (UnnamedColumn) new AsteriskColumn()),
newAlias);
aggColumnAlias.add(newAlias);
++aggColumnIdentiferNum;
} else if (!newAlias.startsWith("agg")) {
ColumnOp col1 = new ColumnOp("count", col.getOperand(0));
newSelectlist.add(new AliasedColumn(col1, newAlias));
aggColumnAlias.add(newAlias);
}
} else if (col.getOpType().equals("sum")) {
if (!meta.getAggColumnAggAliasPair()
.containsKey(new ImmutablePair<>(col.getOpType(), col.getOperand(0)))) {
ColumnOp col1 = new ColumnOp(col.getOpType(), col.getOperand(0));
newSelectlist.add(new AliasedColumn(col1, newAlias));
meta.getAggColumnAggAliasPair()
.put(new ImmutablePair<>(col.getOpType(), col1.getOperand(0)), newAlias);
aggColumnAlias.add(newAlias);
++aggColumnIdentiferNum;
} else if (!newAlias.startsWith("agg")) {
ColumnOp col1 = new ColumnOp("sum", col.getOperand(0));
newSelectlist.add(new AliasedColumn(col1, newAlias));
aggColumnAlias.add(newAlias);
}
>>>>>>>
if (col.getOpType().equals("count")) {
if (!meta.getAggColumnAggAliasPair()
.containsKey(
new ImmutablePair<>("count", (UnnamedColumn) (new AsteriskColumn())))) {
ColumnOp col1 = new ColumnOp(col.getOpType());
newSelectlist.add(new AliasedColumn(col1, newAlias));
meta.getAggColumnAggAliasPair()
.put(
new ImmutablePair<>(
col.getOpType(), (UnnamedColumn) new AsteriskColumn()),
newAlias);
aggColumnAlias.add(newAlias);
++aggColumnIdentiferNum;
} else if (!newAlias.startsWith("agg")) {
ColumnOp col1 = new ColumnOp("count", col.getOperand(0));
newSelectlist.add(new AliasedColumn(col1, newAlias));
aggColumnAlias.add(newAlias);
}
} else if (col.getOpType().equals("sum")) {
if (!meta.getAggColumnAggAliasPair()
.containsKey(new ImmutablePair<>(col.getOpType(), col.getOperand(0)))) {
ColumnOp col1 = new ColumnOp(col.getOpType(), col.getOperand(0));
newSelectlist.add(new AliasedColumn(col1, newAlias));
meta.getAggColumnAggAliasPair()
.put(new ImmutablePair<>(col.getOpType(), col1.getOperand(0)), newAlias);
aggColumnAlias.add(newAlias);
++aggColumnIdentiferNum;
} else if (!newAlias.startsWith("agg")) {
ColumnOp col1 = new ColumnOp("sum", col.getOperand(0));
newSelectlist.add(new AliasedColumn(col1, newAlias));
aggColumnAlias.add(newAlias);
}
<<<<<<<
// verdictdbTierIndentiferNum = 0;
=======
// verdictdbTierIndentiferNum = 0;
>>>>>>>
// verdictdbTierIndentiferNum = 0;
<<<<<<<
private void rewriteProjectionNodeToAddTierColumn(AggExecutionNodeBlock block, ProjectionNode node) {
=======
private void rewriteProjectionNodeToAddTierColumn(
AggExecutionNodeBlock block, ProjectionNode node) {
>>>>>>>
private void rewriteProjectionNodeToAddTierColumn(
AggExecutionNodeBlock block, ProjectionNode node) {
<<<<<<<
}
=======
}
>>>>>>>
} |
<<<<<<<
public FieldTermsResponse fieldTerms(String field) throws IOException, APIException {
return ApiClient.get(FieldTermsResponse.class)
.path("/search/universal/{0}/terms", timeRange.getType().toString().toLowerCase())
.queryParam("field", field)
.queryParam("query", query)
.queryParams(timeRange.getQueryParams())
.execute();
}
=======
public interface Factory {
UniversalSearch queryWithRange(String query, TimeRange timeRange);
}
>>>>>>>
public FieldTermsResponse fieldTerms(String field) throws IOException, APIException {
return ApiClient.get(FieldTermsResponse.class)
.path("/search/universal/{0}/terms", timeRange.getType().toString().toLowerCase())
.queryParam("field", field)
.queryParam("query", query)
.queryParams(timeRange.getQueryParams())
.execute();
}
public interface Factory {
UniversalSearch queryWithRange(String query, TimeRange timeRange);
} |
<<<<<<<
TripsConfig tripsConfig = new TripsConfig(500, 300000, 180000, 900000);
=======
TripsConfig tripsConfig = new TripsConfig(500, 300000, 180000, false, 900000, false);
>>>>>>>
TripsConfig tripsConfig = new TripsConfig(500, 300000, 180000, 900000, false);
<<<<<<<
TripsConfig tripsConfig = new TripsConfig(500, 300000, 200000, 900000);
=======
TripsConfig tripsConfig = new TripsConfig(500, 300000, 200000, false, 900000, false);
>>>>>>>
TripsConfig tripsConfig = new TripsConfig(500, 300000, 200000, 900000, false);
<<<<<<<
TripsConfig tripsConfig = new TripsConfig(500, 300000, 200000, 900000);
=======
TripsConfig tripsConfig = new TripsConfig(500, 300000, 200000, false, 900000, false);
>>>>>>>
TripsConfig tripsConfig = new TripsConfig(500, 300000, 200000, 900000, false);
<<<<<<<
TripsConfig tripsConfig = new TripsConfig(500, 300000, 200000, 900000);
=======
TripsConfig tripsConfig = new TripsConfig(500, 300000, 200000, false, 900000, false);
>>>>>>>
TripsConfig tripsConfig = new TripsConfig(500, 300000, 200000, 900000, false);
<<<<<<<
TripsConfig tripsConfig = new TripsConfig(500, 300000, 200000, 900000);
=======
TripsConfig tripsConfig = new TripsConfig(500, 300000, 200000, false, 900000, false);
>>>>>>>
TripsConfig tripsConfig = new TripsConfig(500, 300000, 200000, 900000, false);
<<<<<<<
TripsConfig tripsConfig = new TripsConfig(500, 200000, 200000, 900000);
=======
TripsConfig tripsConfig = new TripsConfig(500, 200000, 200000, false, 900000, false);
>>>>>>>
TripsConfig tripsConfig = new TripsConfig(500, 200000, 200000, 900000, false); |
<<<<<<<
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import java.io.BufferedReader;
import java.io.BufferedWriter;
=======
import org.apache.tools.ant.DummyMailServer;
import org.junit.AssumptionViolatedException;
import org.junit.Before;
import org.junit.Test;
>>>>>>>
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import org.apache.tools.ant.DummyMailServer;
import org.junit.AssumptionViolatedException;
import org.junit.Before;
import org.junit.Test;
<<<<<<<
import java.net.ServerSocket;
import java.net.Socket;
=======
import java.util.Enumeration;
>>>>>>> |
<<<<<<<
import org.dynmap.web.Json;
=======
import org.dynmap.web.handlers.SendMessageHandler;
import org.dynmap.web.handlers.SendMessageHandler.Message;
>>>>>>>
import org.dynmap.web.handlers.SendMessageHandler;
import org.dynmap.web.handlers.SendMessageHandler.Message;
import org.dynmap.web.Json;
<<<<<<<
private Timer timer;
private BukkitPlayerDebugger debugger = new BukkitPlayerDebugger(this);
=======
public static File tilesDirectory;
>>>>>>>
public static File tilesDirectory;
private Timer timer;
<<<<<<<
if(!configuration.getBoolean("disable-webserver", true)) {
InetAddress bindAddress;
{
String address = configuration.getString("webserver-bindaddress", "0.0.0.0");
try {
bindAddress = address.equals("0.0.0.0")
? null
: InetAddress.getByName(address);
} catch (UnknownHostException e) {
bindAddress = null;
}
}
int port = configuration.getInt("webserver-port", 8123);
webServer = new HttpServer(bindAddress, port);
webServer.handlers.put("/", new FilesystemHandler(mapManager.webDirectory));
webServer.handlers.put("/tiles/", new FilesystemHandler(mapManager.tileDirectory));
webServer.handlers.put("/up/", new ClientUpdateHandler(mapManager, playerList, getWorld()));
webServer.handlers.put("/up/configuration", new ClientConfigurationHandler((Map<?, ?>) configuration.getProperty("web")));
try {
webServer.startServer();
} catch (IOException e) {
log.severe("Failed to start WebServer on " + bindAddress + ":" + port + "!");
}
}
if(configuration.getBoolean("jsonfile", false)) {
jsonConfig();
int jsonInterval = configuration.getInt("jsonfile", 1) * 1000;
timer = new Timer();
timer.scheduleAtFixedRate(new JsonTimerTask(this, configuration), jsonInterval, jsonInterval);
}
=======
InetAddress bindAddress;
{
String address = configuration.getString("webserver-bindaddress", "0.0.0.0");
try {
bindAddress = address.equals("0.0.0.0")
? null
: InetAddress.getByName(address);
} catch (UnknownHostException e) {
bindAddress = null;
}
}
int port = configuration.getInt("webserver-port", 8123);
webServer = new HttpServer(bindAddress, port);
webServer.handlers.put("/", new FilesystemHandler(getFile(configuration.getString("webpath", "web"))));
webServer.handlers.put("/tiles/", new FilesystemHandler(tilesDirectory));
webServer.handlers.put("/up/", new ClientUpdateHandler(mapManager, playerList, getServer()));
webServer.handlers.put("/up/configuration", new ClientConfigurationHandler((Map<?, ?>) configuration.getProperty("web")));
SendMessageHandler messageHandler = new SendMessageHandler();
messageHandler.onMessageReceived.addListener(new Listener<SendMessageHandler.Message>() {
@Override
public void triggered(Message t) {
log.info("[WEB] " + t.name + ": " + t.message);
getServer().broadcastMessage("[WEB] " + t.name + ": " + t.message);
}
});
webServer.handlers.put("/up/sendmessage", messageHandler);
try {
webServer.startServer();
} catch (IOException e) {
log.severe("Failed to start WebServer on " + bindAddress + ":" + port + "!");
}
>>>>>>>
if(!configuration.getBoolean("disable-webserver", true)) {
InetAddress bindAddress;
{
String address = configuration.getString("webserver-bindaddress", "0.0.0.0");
try {
bindAddress = address.equals("0.0.0.0")
? null
: InetAddress.getByName(address);
} catch (UnknownHostException e) {
bindAddress = null;
}
}
int port = configuration.getInt("webserver-port", 8123);
webServer = new HttpServer(bindAddress, port);
webServer.handlers.put("/", new FilesystemHandler(getFile(configuration.getString("webpath", "web"))));
webServer.handlers.put("/tiles/", new FilesystemHandler(tilesDirectory));
webServer.handlers.put("/up/", new ClientUpdateHandler(mapManager, playerList, getServer()));
webServer.handlers.put("/up/configuration", new ClientConfigurationHandler((Map<?, ?>) configuration.getProperty("web")));
SendMessageHandler messageHandler = new SendMessageHandler();
messageHandler.onMessageReceived.addListener(new Listener<SendMessageHandler.Message>() {
@Override
public void triggered(Message t) {
log.info("[WEB] " + t.name + ": " + t.message);
getServer().broadcastMessage("[WEB] " + t.name + ": " + t.message);
}
});
webServer.handlers.put("/up/sendmessage", messageHandler);
try {
webServer.startServer();
} catch (IOException e) {
log.severe("Failed to start WebServer on " + bindAddress + ":" + port + "!");
}
}
if(configuration.getBoolean("jsonfile", false)) {
jsonConfig();
int jsonInterval = configuration.getInt("jsonfile", 1) * 1000;
timer = new Timer();
timer.scheduleAtFixedRate(new JsonTimerTask(this, configuration), jsonInterval, jsonInterval);
}
<<<<<<<
private void jsonConfig()
{
File outputFile;
Map<?, ?> clientConfig = (Map<?, ?>) configuration.getProperty("web");
File webpath = new File(configuration.getString("webpath", "web"), "dynmap_config.json");
if(webpath.isAbsolute())
outputFile = webpath;
else
outputFile = new File(DynmapPlugin.dataRoot, webpath.toString());
try
{
FileOutputStream fos = new FileOutputStream(outputFile);
fos.write(Json.stringifyJson(clientConfig).getBytes());
fos.close();
}
catch(FileNotFoundException ex)
{
System.out.println("FileNotFoundException : " + ex);
}
catch(IOException ioe)
{
System.out.println("IOException : " + ioe);
}
}
=======
private static File combinePaths(File parent, String path) {
return combinePaths(parent, new File(path));
}
private static File combinePaths(File parent, File path) {
if (path.isAbsolute())
return path;
return new File(parent, path.getPath());
}
public File getFile(String path) {
return combinePaths(DynmapPlugin.dataRoot, path);
}
>>>>>>>
private static File combinePaths(File parent, String path) {
return combinePaths(parent, new File(path));
}
private static File combinePaths(File parent, File path) {
if (path.isAbsolute())
return path;
return new File(parent, path.getPath());
}
public File getFile(String path) {
return combinePaths(DynmapPlugin.dataRoot, path);
}
private void jsonConfig()
{
File outputFile;
Map<?, ?> clientConfig = (Map<?, ?>) configuration.getProperty("web");
File webpath = new File(configuration.getString("webpath", "web"), "dynmap_config.json");
if(webpath.isAbsolute())
outputFile = webpath;
else
outputFile = new File(DynmapPlugin.dataRoot, webpath.toString());
try
{
FileOutputStream fos = new FileOutputStream(outputFile);
fos.write(Json.stringifyJson(clientConfig).getBytes());
fos.close();
}
catch(FileNotFoundException ex)
{
System.out.println("FileNotFoundException : " + ex);
}
catch(IOException ioe)
{
System.out.println("IOException : " + ioe);
}
} |
<<<<<<<
double getPriceForDisk(List<InstanceOffer> offers, int instanceDisk, String instanceType, T region);
List<InstanceType> getAllInstanceTypes(Long regionId, boolean spot);
@Getter
@AllArgsConstructor
enum TermType {
ON_DEMAND("OnDemand"),
SPOT("Spot"),
LOW_PRIORITY("LowPriority"),
PREEMPTIBLE("Preemptible");
String name;
}
=======
double getPriceForDisk(List<InstanceOffer> offers, int instanceDisk, String instanceType, boolean spot, T region);
>>>>>>>
double getPriceForDisk(List<InstanceOffer> offers, int instanceDisk, String instanceType, boolean spot, T region);
List<InstanceType> getAllInstanceTypes(Long regionId, boolean spot);
@Getter
@AllArgsConstructor
enum TermType {
ON_DEMAND("OnDemand"),
SPOT("Spot"),
LOW_PRIORITY("LowPriority"),
PREEMPTIBLE("Preemptible");
String name;
} |
<<<<<<<
final String command = instanceService.buildTerminateNodeCommand(internalIp, nodeName,
CloudProvider.AWS.name(), nodeTerminateScript);
=======
final String command = instanceService.buildTerminateNodeCommand(internalIp, nodeName);
>>>>>>>
final String command = instanceService.buildTerminateNodeCommand(internalIp, nodeName,
CloudProvider.AWS.name());
<<<<<<<
oldId, newId, CloudProvider.AWS.name(), cmdExecutor, nodeReassignScript, Collections.emptyMap());
=======
oldId, newId, cmdExecutor, Collections.emptyMap());
>>>>>>>
oldId, newId, CloudProvider.AWS.name(), cmdExecutor, Collections.emptyMap());
<<<<<<<
private String buildNodeDownCommand(final Long runId) {
return RunIdArgCommand.builder()
.executable(AbstractClusterCommand.EXECUTABLE)
.script(nodeDownScript)
.runId(String.valueOf(runId))
.cloud(CloudProvider.AWS.name())
.build()
.getCommand();
}
=======
>>>>>>>
<<<<<<<
NodeUpCommand.NodeUpCommandBuilder commandBuilder = NodeUpCommand.builder()
.executable(AbstractClusterCommand.EXECUTABLE)
.script(nodeUpScript)
.runId(String.valueOf(runId))
.sshKey(region.getSshKeyName())
.instanceImage(instance.getNodeImage())
.instanceType(instance.getNodeType())
.instanceDisk(String.valueOf(instance.getEffectiveNodeDisk()))
.kubeIP(kubeMasterIP)
.kubeToken(kubeToken)
.cloud(CloudProvider.AWS.name())
.region(region.getRegionCode());
=======
NodeUpCommand.NodeUpCommandBuilder commandBuilder =
instanceService.buildNodeUpCommonCommand(region, runId, instance)
.sshKey(region.getSshKeyName());
>>>>>>>
NodeUpCommand.NodeUpCommandBuilder commandBuilder =
instanceService.buildNodeUpCommonCommand(region, runId, instance, CloudProvider.AWS.name())
.sshKey(region.getSshKeyName()); |
<<<<<<<
GS("GS"),
=======
AZ("AZ"),
>>>>>>>
AZ("AZ"),
GS("GS"), |
<<<<<<<
final String command = buildNodeReassignCommand(reassignScript, oldId, newId, cloud);
=======
final String command = buildNodeReassignCommand(oldId, newId);
>>>>>>>
final String command = buildNodeReassignCommand(oldId, newId, cloud);
<<<<<<<
public String buildTerminateNodeCommand(final String internalIp, final String nodeName, final String cloud,
final String nodeTerminateScript) {
=======
public String buildTerminateNodeCommand(final String internalIp, final String nodeName) {
>>>>>>>
public String buildTerminateNodeCommand(final String internalIp, final String nodeName, final String cloud) {
<<<<<<<
private String buildNodeReassignCommand(final String reassignScript,
final Long oldId,
final Long newId,
final String cloud) {
=======
private String buildNodeReassignCommand(final Long oldId,
final Long newId) {
>>>>>>>
private String buildNodeReassignCommand(final Long oldId,
final Long newId,
final String cloud) { |
<<<<<<<
import com.google.common.base.Preconditions;
import com.google.common.base.Strings;
import io.divolte.server.ServerTestUtils.EventPayload;
=======
import static io.divolte.server.IncomingRequestProcessor.*;
import static io.divolte.server.SeleniumTestBase.TEST_PAGES.*;
import static org.hamcrest.Matchers.*;
import static org.junit.Assert.*;
import java.util.Optional;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import javax.annotation.ParametersAreNonnullByDefault;
import io.divolte.server.config.BrowserSourceConfiguration;
>>>>>>>
import com.google.common.base.Preconditions;
import com.google.common.base.Strings;
import io.divolte.server.ServerTestUtils.EventPayload;
import io.divolte.server.config.BrowserSourceConfiguration; |
<<<<<<<
import javax.annotation.ParametersAreNonnullByDefault;
import javax.annotation.concurrent.NotThreadSafe;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import io.divolte.server.AvroRecordBuffer;
import io.divolte.server.config.ValidatedConfiguration;
import io.divolte.server.processing.Item;
import io.divolte.server.processing.ItemProcessor;
import kafka.common.FailedToSendMessageException;
import kafka.javaapi.producer.Producer;
import kafka.producer.KeyedMessage;
import kafka.producer.ProducerConfig;
=======
import static io.divolte.server.processing.ItemProcessor.ProcessingDirective.CONTINUE;
import static io.divolte.server.processing.ItemProcessor.ProcessingDirective.PAUSE;
>>>>>>>
import javax.annotation.ParametersAreNonnullByDefault;
import javax.annotation.concurrent.NotThreadSafe;
import org.apache.kafka.clients.producer.Producer;
import org.apache.kafka.clients.producer.ProducerRecord;
import org.apache.kafka.clients.producer.RecordMetadata;
import org.apache.kafka.common.errors.RetriableException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.google.common.collect.ImmutableList;
import io.divolte.server.AvroRecordBuffer;
import io.divolte.server.DivolteIdentifier;
import io.divolte.server.processing.Item;
import io.divolte.server.processing.ItemProcessor;
<<<<<<<
public ProcessingDirective process(final Item<AvroRecordBuffer> item) {
final AvroRecordBuffer record = item.payload;
logger.debug("Processing individual record.", record);
return send(() -> {
producer.send(buildMessage(record));
logger.debug("Sent individual record to Kafka.", record);
});
=======
public ProcessingDirective process(final AvroRecordBuffer record) {
logger.debug("Processing individual record: {}", record);
return flush(ImmutableList.of(buildRecord(record)));
>>>>>>>
public ProcessingDirective process(final Item<AvroRecordBuffer> item) {
final AvroRecordBuffer record = item.payload;
logger.debug("Processing individual record: {}", record);
return flush(ImmutableList.of(buildRecord(record)));
<<<<<<<
.map(i -> i.payload)
.map(this::buildMessage)
.collect(Collectors.toCollection(() -> new ArrayList<>(batchSize)));
=======
.map(this::buildRecord)
.collect(Collectors.toList());
>>>>>>>
.map(i -> i.payload)
.map(this::buildRecord)
.collect(Collectors.toList()); |
<<<<<<<
import org.openqa.selenium.support.ui.ExpectedCondition;
import org.openqa.selenium.support.ui.WebDriverWait;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
=======
import org.openqa.selenium.safari.SafariDriver;
>>>>>>>
import org.openqa.selenium.safari.SafariDriver;
import org.openqa.selenium.support.ui.ExpectedCondition;
import org.openqa.selenium.support.ui.WebDriverWait;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory; |
<<<<<<<
import io.divolte.server.IncomingRequestProcessingPool.HttpServerExchangeWithPartyId;
import io.divolte.server.geo2ip.ExternalDatabaseLookupService;
import io.divolte.server.geo2ip.LookupService;
=======
import io.divolte.server.CookieValues.CookieValue;
>>>>>>>
import io.divolte.server.CookieValues.CookieValue;
import io.divolte.server.geo2ip.ExternalDatabaseLookupService;
import io.divolte.server.geo2ip.LookupService;
<<<<<<<
private static LookupService lookupServiceFromConfig(final Config config) {
final LookupService service;
if (config.hasPath("divolte.geodb")) {
final String externalLocation = config.getString("divolte.geodb");
try {
service = new ExternalDatabaseLookupService(Paths.get(externalLocation));
} catch (final IOException e) {
logger.error("Failed to configure GeoIP database: " + externalLocation, e);
throw new RuntimeException("Failed to configure GeoIP lookup service.", e);
}
} else {
service = null;
}
return service;
}
public void enqueueIncomingExchangeForProcessing(final String partyId, final HttpServerExchange exchange) {
enqueue(partyId, new IncomingRequestProcessingPool.HttpServerExchangeWithPartyId(partyId, exchange));
=======
public void enqueueIncomingExchangeForProcessing(final CookieValue partyId, final HttpServerExchange exchange) {
enqueue(partyId.value, exchange);
>>>>>>>
private static LookupService lookupServiceFromConfig(final Config config) {
final LookupService service;
if (config.hasPath("divolte.geodb")) {
final String externalLocation = config.getString("divolte.geodb");
try {
service = new ExternalDatabaseLookupService(Paths.get(externalLocation));
} catch (final IOException e) {
logger.error("Failed to configure GeoIP database: " + externalLocation, e);
throw new RuntimeException("Failed to configure GeoIP lookup service.", e);
}
} else {
service = null;
}
return service;
}
public void enqueueIncomingExchangeForProcessing(final CookieValue partyId, final HttpServerExchange exchange) {
enqueue(partyId.value, exchange); |
<<<<<<<
}
try {
// How to handle non-file-Resources? I copy temporarily the
// resource to a file and use the file-implementation.
FileUtils fu = FileUtils.getFileUtils();
File tmpFile = fu.createTempFile("modified-", ".tmp", null, true, false);
Resource tmpResource = new FileResource(tmpFile);
ResourceUtils.copyResource(resource, tmpResource);
boolean isSelected = isSelected(tmpFile.getParentFile(),
tmpFile.getName(),
resource.toLongString());
tmpFile.delete();
return isSelected;
} catch (UnsupportedOperationException uoe) {
log("The resource '"
+ resource.getName()
+ "' does not provide an InputStream, so it is not checked. "
+ "According to 'selres' attribute value it is "
+ ((selectResourcesWithoutInputStream) ? "" : " not")
+ "selected.", Project.MSG_INFO);
return selectResourcesWithoutInputStream;
} catch (Exception e) {
throw new BuildException(e);
=======
} else {
try {
// How to handle non-file-Resources? I copy temporarily the
// resource to a file and use the file-implementation.
FileUtils fu = FileUtils.getFileUtils();
File tmpFile = fu.createTempFile(getProject(), "modified-", ".tmp", null, true, false);
Resource tmpResource = new FileResource(tmpFile);
ResourceUtils.copyResource(resource, tmpResource);
boolean isSelected = isSelected(tmpFile.getParentFile(),
tmpFile.getName(),
resource.toLongString());
tmpFile.delete();
return isSelected;
} catch (UnsupportedOperationException uoe) {
log("The resource '"
+ resource.getName()
+ "' does not provide an InputStream, so it is not checked. "
+ "According to 'selres' attribute value it is "
+ ((selectResourcesWithoutInputStream) ? "" : " not")
+ "selected.", Project.MSG_INFO);
return selectResourcesWithoutInputStream;
} catch (Exception e) {
throw new BuildException(e);
}
>>>>>>>
}
try {
// How to handle non-file-Resources? I copy temporarily the
// resource to a file and use the file-implementation.
FileUtils fu = FileUtils.getFileUtils();
File tmpFile = fu.createTempFile(getProject(), "modified-", ".tmp", null, true, false);
Resource tmpResource = new FileResource(tmpFile);
ResourceUtils.copyResource(resource, tmpResource);
boolean isSelected = isSelected(tmpFile.getParentFile(),
tmpFile.getName(),
resource.toLongString());
tmpFile.delete();
return isSelected;
} catch (UnsupportedOperationException uoe) {
log("The resource '"
+ resource.getName()
+ "' does not provide an InputStream, so it is not checked. "
+ "According to 'selres' attribute value it is "
+ ((selectResourcesWithoutInputStream) ? "" : " not")
+ "selected.", Project.MSG_INFO);
return selectResourcesWithoutInputStream;
} catch (Exception e) {
throw new BuildException(e); |
<<<<<<<
import com.epam.healenium.treecomparing.Scored;
=======
import com.epam.healenium.utils.ProxyFactory;
>>>>>>>
import com.epam.healenium.treecomparing.Scored;
import com.epam.healenium.utils.ProxyFactory; |
<<<<<<<
import clojuredev.lexers.ClojureLexer;
=======
import clojuredev.util.DisplayUtil;
>>>>>>>
import clojuredev.lexers.ClojureLexer;
import clojuredev.util.DisplayUtil;
<<<<<<<
colorRegistry = new ColorRegistry(getWorkbench().getDisplay());
=======
DisplayUtil.syncExec(new Runnable() {
public void run() {
colorRegistry = new ColorRegistry(getWorkbench().getDisplay());
AntlrBasedClojureEditor.registerEditorColors(colorRegistry);
}});
>>>>>>>
DisplayUtil.syncExec(new Runnable() {
public void run() {
colorRegistry = new ColorRegistry(getWorkbench().getDisplay());
}}); |
<<<<<<<
import cemerick.nrepl.Connection;
import clojure.lang.Compiler;
import clojure.lang.Symbol;
import clojure.lang.Var;
=======
import clojure.osgi.ClojureOSGi;
>>>>>>>
import cemerick.nrepl.Connection;
import clojure.osgi.ClojureOSGi; |
<<<<<<<
}
if (JavaEnvUtils.isJavaVersion(JavaEnvUtils.JAVA_9)) {
=======
} else if (JavaEnvUtils.isAtLeastJavaVersion("10")) {
return JAVAC10_PLUS;
} else if (JavaEnvUtils.isJavaVersion(JavaEnvUtils.JAVA_9)) {
>>>>>>>
}
if (JavaEnvUtils.isAtLeastJavaVersion("10")) {
return JAVAC10_PLUS;
}
if (JavaEnvUtils.isJavaVersion(JavaEnvUtils.JAVA_9)) { |
<<<<<<<
.optionalHeader("X-Vault-Token", config.getToken())
.body(requestJson.getBytes(StandardCharsets.UTF_8))
=======
.header("X-Vault-Token", config.getToken())
.body(requestJson.getBytes("UTF-8"))
>>>>>>>
.header("X-Vault-Token", config.getToken())
.body(requestJson.getBytes(StandardCharsets.UTF_8))
<<<<<<<
.optionalHeader("X-Vault-Token", config.getToken())
.body(requestJson.getBytes(StandardCharsets.UTF_8))
=======
.header("X-Vault-Token", config.getToken())
.body(requestJson.getBytes("UTF-8"))
>>>>>>>
.header("X-Vault-Token", config.getToken())
.body(requestJson.getBytes(StandardCharsets.UTF_8)) |
<<<<<<<
public static final String SCHEMAREGISTRY_RESOURCE_EXTENSION_CONFIG =
"schema.registry.resource.extension.class";
=======
protected static final String SCHEMAREGISTRY_CONNECTION_URL_DOC =
"Zookeeper URL used by the schema registry instances to coordinate. If not specified, it "
+ "will default to using the kafkastore.connection.url, i.e. the same Zookeeper cluster as "
+ "your Kafka cluster uses."
+ "\n"
+ "This setting is useful if you need to use a different Zookeeper cluster than your Kafka "
+ "cluster uses, for example if you use a cloud hosted Kafka cluster that does not expose "
+ "its underlying Zookeeper cluster.";
>>>>>>>
protected static final String SCHEMAREGISTRY_CONNECTION_URL_DOC =
"Zookeeper URL used by the schema registry instances to coordinate. If not specified, it "
+ "will default to using the kafkastore.connection.url, i.e. the same Zookeeper cluster as "
+ "your Kafka cluster uses."
+ "\n"
+ "This setting is useful if you need to use a different Zookeeper cluster than your Kafka "
+ "cluster uses, for example if you use a cloud hosted Kafka cluster that does not expose "
+ "its underlying Zookeeper cluster.";
public static final String SCHEMAREGISTRY_RESOURCE_EXTENSION_CONFIG =
"schema.registry.resource.extension.class";
<<<<<<<
SCHEMA_REGISTRY_MOST_SPECIFIC_DEFAULT,
ConfigDef.Importance.HIGH,
RESPONSE_MEDIATYPE_DEFAULT_CONFIG_DOC
)
.define(KAFKASTORE_CONNECTION_URL_CONFIG, ConfigDef.Type.STRING, ConfigDef.Importance.HIGH,
KAFKASTORE_CONNECTION_URL_DOC
)
=======
SCHEMA_REGISTRY_MOST_SPECIFIC_DEFAULT,
ConfigDef.Importance.HIGH,
RESPONSE_MEDIATYPE_DEFAULT_CONFIG_DOC)
.define(KAFKASTORE_CONNECTION_URL_CONFIG, ConfigDef.Type.STRING, "",
ConfigDef.Importance.HIGH, KAFKASTORE_CONNECTION_URL_DOC)
>>>>>>>
SCHEMA_REGISTRY_MOST_SPECIFIC_DEFAULT,
ConfigDef.Importance.HIGH,
RESPONSE_MEDIATYPE_DEFAULT_CONFIG_DOC)
.define(KAFKASTORE_CONNECTION_URL_CONFIG, ConfigDef.Type.STRING, "",
ConfigDef.Importance.HIGH, KAFKASTORE_CONNECTION_URL_DOC)
<<<<<<<
ConfigDef.Importance.MEDIUM,
KAFKASTORE_BOOTSTRAP_SERVERS_DOC
)
=======
ConfigDef.Importance.MEDIUM,
KAFKASTORE_BOOTSTRAP_SERVERS_DOC)
.define(SCHEMAREGISTRY_CONNECTION_URL_CONFIG, ConfigDef.Type.STRING, "",
ConfigDef.Importance.MEDIUM, SCHEMAREGISTRY_CONNECTION_URL_DOC)
>>>>>>>
ConfigDef.Importance.MEDIUM,
KAFKASTORE_BOOTSTRAP_SERVERS_DOC)
.define(SCHEMAREGISTRY_CONNECTION_URL_CONFIG, ConfigDef.Type.STRING, "",
ConfigDef.Importance.MEDIUM, SCHEMAREGISTRY_CONNECTION_URL_DOC)
<<<<<<<
public Properties getOriginalProperties() {
return originalProperties;
}
=======
public AvroCompatibilityLevel compatibilityType() {
return compatibilityType;
}
public String schemaRegistryZkUrl() {
String result = getString(SCHEMAREGISTRY_CONNECTION_URL_CONFIG);
if (result.isEmpty()) {
result = getString(KAFKASTORE_CONNECTION_URL_CONFIG);
}
if (result.isEmpty()) {
throw new ConfigException("Must specify at least one of "
+ KAFKASTORE_CONNECTION_URL_CONFIG + " or "
+ SCHEMAREGISTRY_CONNECTION_URL_CONFIG);
}
return result;
}
>>>>>>>
public Properties getOriginalProperties() {
return originalProperties;
}
public AvroCompatibilityLevel compatibilityType() {
return compatibilityType;
}
public String schemaRegistryZkUrl() {
String result = getString(SCHEMAREGISTRY_CONNECTION_URL_CONFIG);
if (result.isEmpty()) {
result = getString(KAFKASTORE_CONNECTION_URL_CONFIG);
}
if (result.isEmpty()) {
throw new ConfigException("Must specify at least one of "
+ KAFKASTORE_CONNECTION_URL_CONFIG + " or "
+ SCHEMAREGISTRY_CONNECTION_URL_CONFIG);
}
return result;
} |
<<<<<<<
ClientDnsLookup.DEFAULT.name());
this.metadata.bootstrap(addresses, time.milliseconds());
=======
clientConfig.getString(CommonClientConfigs.CLIENT_DNS_LOOKUP_CONFIG));
this.metadata.update(Cluster.bootstrap(addresses), Collections.<String>emptySet(), 0);
>>>>>>>
clientConfig.getString(CommonClientConfigs.CLIENT_DNS_LOOKUP_CONFIG));
this.metadata.bootstrap(addresses, time.milliseconds()); |
<<<<<<<
private final String kafkaClusterZkUrl;
private String schemaRegistryZkUrl;
private ZkClient zkClient;
private final int zkSessionTimeoutMs;
private final String clusterName;
=======
private final ZkClient zkClient;
private final Metrics metrics;
>>>>>>>
private final String kafkaClusterZkUrl;
private String schemaRegistryZkUrl;
private ZkClient zkClient;
private final int zkSessionTimeoutMs;
private final String clusterName;
<<<<<<<
private Integer nextSchemaIdCounterBatch() throws SchemaRegistryException {
int nextIdBatchLowerBound = 0;
=======
private Integer nextSchemaIdCounterBatch() throws SchemaRegistryStoreException {
>>>>>>>
private Integer nextSchemaIdCounterBatch() throws SchemaRegistryStoreException {
int nextIdBatchLowerBound = 0;
<<<<<<<
throw new SchemaRegistryException(
"Failed to initialize schema registry. Failed to read schema id counter " +
ZOOKEEPER_SCHEMA_ID_COUNTER + " from zookeeper");
=======
throw new SchemaRegistryStoreException(
"Failed to to read schema id counter " + ZOOKEEPER_SCHEMA_ID_COUNTER +
" from zookeeper");
>>>>>>>
throw new SchemaRegistryStoreException(
"Failed to initialize schema registry. Failed to read " +
"schema id counter " + ZOOKEEPER_SCHEMA_ID_COUNTER + " from zookeeper");
<<<<<<<
return nextIdBatchLowerBound;
=======
return schemaIdCounterThreshold;
>>>>>>>
return nextIdBatchLowerBound; |
<<<<<<<
import org.apache.kafka.common.cache.Cache;
import org.apache.kafka.common.cache.LRUCache;
=======
import org.apache.kafka.copycat.data.Date;
import org.apache.kafka.copycat.data.Decimal;
>>>>>>>
import org.apache.kafka.common.cache.Cache;
import org.apache.kafka.common.cache.LRUCache;
import org.apache.kafka.copycat.data.Date;
import org.apache.kafka.copycat.data.Decimal;
<<<<<<<
private Cache<Schema, org.apache.avro.Schema> fromCopycatSchemaCache;
private Cache<org.apache.avro.Schema, Schema> toCopycatSchemaCache;
public AvroData(int cacheSize) {
fromCopycatSchemaCache = new LRUCache<>(cacheSize);
toCopycatSchemaCache = new LRUCache<>(cacheSize);
}
=======
// Convert values in Copycat form into their logical types. These logical converters are discovered by logical type
// names specified in the field
private static final HashMap<String, LogicalTypeConverter> TO_COPYCAT_LOGICAL_CONVERTERS = new HashMap<>();
static {
TO_COPYCAT_LOGICAL_CONVERTERS.put(Decimal.LOGICAL_NAME, new LogicalTypeConverter() {
@Override
public Object convert(Schema schema, Object value) {
if (value instanceof byte[]) {
return Decimal.toLogical(schema, (byte[]) value);
} else if (value instanceof ByteBuffer) {
return Decimal.toLogical(schema, ((ByteBuffer) value).array());
}
throw new DataException("Invalid type for Decimal, underlying representation should be bytes but was " + value.getClass());
}
});
TO_COPYCAT_LOGICAL_CONVERTERS.put(Date.LOGICAL_NAME, new LogicalTypeConverter() {
@Override
public Object convert(Schema schema, Object value) {
if (!(value instanceof Integer))
throw new DataException("Invalid type for Date, underlying representation should be int32 but was " + value.getClass());
return Date.toLogical(schema, (int) value);
}
});
TO_COPYCAT_LOGICAL_CONVERTERS.put(Time.LOGICAL_NAME, new LogicalTypeConverter() {
@Override
public Object convert(Schema schema, Object value) {
if (!(value instanceof Integer))
throw new DataException("Invalid type for Time, underlying representation should be int32 but was " + value.getClass());
return Time.toLogical(schema, (int) value);
}
});
TO_COPYCAT_LOGICAL_CONVERTERS.put(Timestamp.LOGICAL_NAME, new LogicalTypeConverter() {
@Override
public Object convert(Schema schema, Object value) {
if (!(value instanceof Long))
throw new DataException("Invalid type for Timestamp, underlying representation should be int64 but was " + value.getClass());
return Timestamp.toLogical(schema, (long) value);
}
});
}
private static final HashMap<String, LogicalTypeConverter> TO_AVRO_LOGICAL_CONVERTERS
= new HashMap<>();
static {
TO_AVRO_LOGICAL_CONVERTERS.put(Decimal.LOGICAL_NAME, new LogicalTypeConverter() {
@Override
public Object convert(Schema schema, Object value) {
if (!(value instanceof BigDecimal))
throw new DataException(
"Invalid type for Decimal, expected BigDecimal but was " + value.getClass());
return Decimal.fromLogical(schema, (BigDecimal) value);
}
});
TO_AVRO_LOGICAL_CONVERTERS.put(Date.LOGICAL_NAME, new LogicalTypeConverter() {
@Override
public Object convert(Schema schema, Object value) {
if (!(value instanceof java.util.Date))
throw new DataException(
"Invalid type for Date, expected Date but was " + value.getClass());
return Date.fromLogical(schema, (java.util.Date) value);
}
});
TO_AVRO_LOGICAL_CONVERTERS.put(Time.LOGICAL_NAME, new LogicalTypeConverter() {
@Override
public Object convert(Schema schema, Object value) {
if (!(value instanceof java.util.Date))
throw new DataException(
"Invalid type for Time, expected Date but was " + value.getClass());
return Time.fromLogical(schema, (java.util.Date) value);
}
});
TO_AVRO_LOGICAL_CONVERTERS.put(Timestamp.LOGICAL_NAME, new LogicalTypeConverter() {
@Override
public Object convert(Schema schema, Object value) {
if (!(value instanceof java.util.Date))
throw new DataException(
"Invalid type for Timestamp, expected Date but was " + value.getClass());
return Timestamp.fromLogical(schema, (java.util.Date) value);
}
});
}
>>>>>>>
// Convert values in Copycat form into their logical types. These logical converters are discovered by logical type
// names specified in the field
private static final HashMap<String, LogicalTypeConverter> TO_COPYCAT_LOGICAL_CONVERTERS = new HashMap<>();
static {
TO_COPYCAT_LOGICAL_CONVERTERS.put(Decimal.LOGICAL_NAME, new LogicalTypeConverter() {
@Override
public Object convert(Schema schema, Object value) {
if (value instanceof byte[]) {
return Decimal.toLogical(schema, (byte[]) value);
} else if (value instanceof ByteBuffer) {
return Decimal.toLogical(schema, ((ByteBuffer) value).array());
}
throw new DataException("Invalid type for Decimal, underlying representation should be bytes but was " + value.getClass());
}
});
TO_COPYCAT_LOGICAL_CONVERTERS.put(Date.LOGICAL_NAME, new LogicalTypeConverter() {
@Override
public Object convert(Schema schema, Object value) {
if (!(value instanceof Integer))
throw new DataException("Invalid type for Date, underlying representation should be int32 but was " + value.getClass());
return Date.toLogical(schema, (int) value);
}
});
TO_COPYCAT_LOGICAL_CONVERTERS.put(Time.LOGICAL_NAME, new LogicalTypeConverter() {
@Override
public Object convert(Schema schema, Object value) {
if (!(value instanceof Integer))
throw new DataException("Invalid type for Time, underlying representation should be int32 but was " + value.getClass());
return Time.toLogical(schema, (int) value);
}
});
TO_COPYCAT_LOGICAL_CONVERTERS.put(Timestamp.LOGICAL_NAME, new LogicalTypeConverter() {
@Override
public Object convert(Schema schema, Object value) {
if (!(value instanceof Long))
throw new DataException("Invalid type for Timestamp, underlying representation should be int64 but was " + value.getClass());
return Timestamp.toLogical(schema, (long) value);
}
});
}
private static final HashMap<String, LogicalTypeConverter> TO_AVRO_LOGICAL_CONVERTERS
= new HashMap<>();
static {
TO_AVRO_LOGICAL_CONVERTERS.put(Decimal.LOGICAL_NAME, new LogicalTypeConverter() {
@Override
public Object convert(Schema schema, Object value) {
if (!(value instanceof BigDecimal))
throw new DataException(
"Invalid type for Decimal, expected BigDecimal but was " + value.getClass());
return Decimal.fromLogical(schema, (BigDecimal) value);
}
});
TO_AVRO_LOGICAL_CONVERTERS.put(Date.LOGICAL_NAME, new LogicalTypeConverter() {
@Override
public Object convert(Schema schema, Object value) {
if (!(value instanceof java.util.Date))
throw new DataException(
"Invalid type for Date, expected Date but was " + value.getClass());
return Date.fromLogical(schema, (java.util.Date) value);
}
});
TO_AVRO_LOGICAL_CONVERTERS.put(Time.LOGICAL_NAME, new LogicalTypeConverter() {
@Override
public Object convert(Schema schema, Object value) {
if (!(value instanceof java.util.Date))
throw new DataException(
"Invalid type for Time, expected Date but was " + value.getClass());
return Time.fromLogical(schema, (java.util.Date) value);
}
});
TO_AVRO_LOGICAL_CONVERTERS.put(Timestamp.LOGICAL_NAME, new LogicalTypeConverter() {
@Override
public Object convert(Schema schema, Object value) {
if (!(value instanceof java.util.Date))
throw new DataException(
"Invalid type for Timestamp, expected Date but was " + value.getClass());
return Timestamp.fromLogical(schema, (java.util.Date) value);
}
});
}
private Cache<Schema, org.apache.avro.Schema> fromCopycatSchemaCache;
private Cache<org.apache.avro.Schema, Schema> toCopycatSchemaCache;
public AvroData(int cacheSize) {
fromCopycatSchemaCache = new LRUCache<>(cacheSize);
toCopycatSchemaCache = new LRUCache<>(cacheSize);
} |
<<<<<<<
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
=======
import java.util.concurrent.atomic.AtomicInteger;
>>>>>>>
import java.util.concurrent.atomic.AtomicInteger;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
<<<<<<<
Logger log = LoggerFactory.getLogger(IncrementalIdGenerator.class);
private volatile int maxIdInKafkaStore = -1;
=======
private final AtomicInteger maxIdInKafkaStore = new AtomicInteger(0);
>>>>>>>
Logger log = LoggerFactory.getLogger(IncrementalIdGenerator.class);
private final AtomicInteger maxIdInKafkaStore = new AtomicInteger(0); |
<<<<<<<
private void handleSchemaUpdate(SchemaKey schemaKey,
SchemaValue schemaValue,
SchemaValue oldSchemaValue) {
if (schemaValue != null) {
=======
private void handleSchemaUpdate(SchemaKey schemaKey, SchemaValue schemaObj) {
if (schemaObj != null) {
// Update the maximum id seen so far
idGenerator.schemaRegistered(schemaKey, schemaObj);
>>>>>>>
private void handleSchemaUpdate(SchemaKey schemaKey,
SchemaValue schemaValue,
SchemaValue oldSchemaValue) {
if (schemaValue != null) {
// Update the maximum id seen so far
idGenerator.schemaRegistered(schemaKey, schemaValue);
<<<<<<<
// Update the maximum id seen so far
idGenerator.schemaRegistered(schemaKey, schemaValue);
lookupCache.schemaRegistered(schemaKey, schemaValue);
=======
lookupCache.schemaRegistered(schemaKey, schemaObj);
List<SchemaKey> schemaKeys = lookupCache.deletedSchemaKeys(schemaObj);
schemaKeys.stream().filter(v ->
v.getSubject().equals(schemaObj.getSubject())
&& v.getVersion() != schemaObj.getVersion())
.forEach(this::tombstoneSchemaKey);
>>>>>>>
lookupCache.schemaRegistered(schemaKey, schemaValue); |
<<<<<<<
import org.apache.avro.Schema;
import org.easymock.EasyMock;
import org.junit.Test;
import java.util.HashMap;
import java.util.Arrays;
import java.util.Map;
import io.confluent.kafka.schemaregistry.client.rest.RestService;
import io.confluent.kafka.schemaregistry.client.rest.entities.SchemaString;
import io.confluent.kafka.schemaregistry.client.rest.entities.requests.ModeGetResponse;
import io.confluent.kafka.schemaregistry.client.rest.entities.requests.ModeUpdateRequest;
import static io.confluent.kafka.schemaregistry.client.rest.RestService.DEFAULT_REQUEST_PROPERTIES;
=======
import static org.easymock.EasyMock.anyBoolean;
>>>>>>>
import org.apache.avro.Schema;
import org.easymock.EasyMock;
import org.junit.Test;
import java.util.HashMap;
import java.util.Arrays;
import java.util.Map;
import io.confluent.kafka.schemaregistry.client.rest.RestService;
import io.confluent.kafka.schemaregistry.client.rest.entities.SchemaString;
import io.confluent.kafka.schemaregistry.client.rest.entities.requests.ModeGetResponse;
import io.confluent.kafka.schemaregistry.client.rest.entities.requests.ModeUpdateRequest;
import static io.confluent.kafka.schemaregistry.client.rest.RestService.DEFAULT_REQUEST_PROPERTIES;
import static org.easymock.EasyMock.anyBoolean;
<<<<<<<
String subject = "foo";
int id = 25;
EasyMock.reset(restService);
// Expect one call to register schema
expect(restService.registerSchema(anyString(), eq(subject)))
.andReturn(id);
expect(restService.deleteSubject(DEFAULT_REQUEST_PROPERTIES, subject))
=======
expect(restService.deleteSubject(RestService.DEFAULT_REQUEST_PROPERTIES, SUBJECT_0))
>>>>>>>
expect(restService.deleteSubject(RestService.DEFAULT_REQUEST_PROPERTIES, SUBJECT_0))
<<<<<<<
expect(restService.deleteSchemaVersion(
DEFAULT_REQUEST_PROPERTIES,
subject,
=======
expect(restService.deleteSchemaVersion(RestService.DEFAULT_REQUEST_PROPERTIES,
SUBJECT_0,
>>>>>>>
expect(restService.deleteSchemaVersion(RestService.DEFAULT_REQUEST_PROPERTIES,
SUBJECT_0,
<<<<<<<
@Test
public void testSetMode() throws Exception {
RestService restService = createMock(RestService.class);
CachedSchemaRegistryClient client = new CachedSchemaRegistryClient(restService, 20, new
HashMap<String, Object>());
String mode = "READONLY";
EasyMock.reset(restService);
ModeUpdateRequest modeUpdateRequest = new ModeUpdateRequest();
modeUpdateRequest.setMode(mode);
expect(restService.setMode(eq(mode))).andReturn(modeUpdateRequest);
replay(restService);
assertEquals(mode, client.setMode(mode));
verify(restService);
}
@Test
public void testGetMode() throws Exception {
RestService restService = createMock(RestService.class);
CachedSchemaRegistryClient client = new CachedSchemaRegistryClient(restService, 20, new
HashMap<String, Object>());
String mode = "READONLY";
EasyMock.reset(restService);
ModeGetResponse modeGetResponse = new ModeGetResponse(mode);
expect(restService.getMode()).andReturn(modeGetResponse);
replay(restService);
assertEquals(mode, client.getMode());
verify(restService);
}
=======
@Test
public void testDeleteVersionNotInVersionCache() throws Exception {
expect(client.deleteSchemaVersion(Collections.emptyMap(), SUBJECT_0, "0"))
.andReturn(10);
replay(restService);
final Integer result = client.deleteSchemaVersion(Collections.emptyMap(), SUBJECT_0, "0");
assertEquals((Integer)10, result);
verify(restService);
}
@Test(expected = NullPointerException.class)
public void testDeleteNullSubjectThrows() throws Exception {
client.deleteSubject(null);
}
@Test
public void testThreadSafe() throws Exception {
expect(restService.registerSchema(anyString(), eq(SUBJECT_0)))
.andReturn(ID_25)
.anyTimes();
expect(restService.getId(ID_25))
.andReturn(new SchemaString(SCHEMA_STR_0))
.anyTimes();
expect(restService.lookUpSubjectVersion(eq(AVRO_SCHEMA_0.toString()), eq(SUBJECT_0), anyBoolean()))
.andReturn(SCHEMA_DETAILS)
.anyTimes();
replay(restService);
IntStream.range(0, 1_000)
.parallel()
.forEach(idx -> {
try {
final int id = client.register(SUBJECT_0, AVRO_SCHEMA_0);
final int version = client.getVersion(SUBJECT_0, AVRO_SCHEMA_0);
client.getId(SUBJECT_0, AVRO_SCHEMA_0);
client.getBySubjectAndId(SUBJECT_0, id);
client.deleteSchemaVersion(SUBJECT_0, String.valueOf(version));
client.deleteSubject(SUBJECT_0);
} catch (final IOException | RestClientException e) {
throw new RuntimeException(e);
}
});
}
private static Schema avroSchema(final int i) {
return new Schema.Parser().parse(avroSchemaString(i));
}
private static String avroSchemaString(final int i) {
return "{\"type\": \"record\", \"name\": \"Blah" + i + "\", "
+ "\"fields\": [{ \"name\": \"name\", \"type\": \"string\" }]}";
}
>>>>>>>
@Test
public void testSetMode() throws Exception {
CachedSchemaRegistryClient client = new CachedSchemaRegistryClient(restService, 20, new
HashMap<String, Object>());
String mode = "READONLY";
EasyMock.reset(restService);
ModeUpdateRequest modeUpdateRequest = new ModeUpdateRequest();
modeUpdateRequest.setMode(mode);
expect(restService.setMode(eq(mode))).andReturn(modeUpdateRequest);
replay(restService);
assertEquals(mode, client.setMode(mode));
verify(restService);
}
@Test
public void testGetMode() throws Exception {
CachedSchemaRegistryClient client = new CachedSchemaRegistryClient(restService, 20, new
HashMap<String, Object>());
String mode = "READONLY";
EasyMock.reset(restService);
ModeGetResponse modeGetResponse = new ModeGetResponse(mode);
expect(restService.getMode()).andReturn(modeGetResponse);
replay(restService);
assertEquals(mode, client.getMode());
verify(restService);
}
public void testDeleteVersionNotInVersionCache() throws Exception {
expect(client.deleteSchemaVersion(Collections.emptyMap(), SUBJECT_0, "0"))
.andReturn(10);
replay(restService);
final Integer result = client.deleteSchemaVersion(Collections.emptyMap(), SUBJECT_0, "0");
assertEquals((Integer)10, result);
verify(restService);
}
@Test(expected = NullPointerException.class)
public void testDeleteNullSubjectThrows() throws Exception {
client.deleteSubject(null);
}
@Test
public void testThreadSafe() throws Exception {
expect(restService.registerSchema(anyString(), eq(SUBJECT_0)))
.andReturn(ID_25)
.anyTimes();
expect(restService.getId(ID_25))
.andReturn(new SchemaString(SCHEMA_STR_0))
.anyTimes();
expect(restService.lookUpSubjectVersion(eq(AVRO_SCHEMA_0.toString()), eq(SUBJECT_0), anyBoolean()))
.andReturn(SCHEMA_DETAILS)
.anyTimes();
replay(restService);
IntStream.range(0, 1_000)
.parallel()
.forEach(idx -> {
try {
final int id = client.register(SUBJECT_0, AVRO_SCHEMA_0);
final int version = client.getVersion(SUBJECT_0, AVRO_SCHEMA_0);
client.getId(SUBJECT_0, AVRO_SCHEMA_0);
client.getBySubjectAndId(SUBJECT_0, id);
client.deleteSchemaVersion(SUBJECT_0, String.valueOf(version));
client.deleteSubject(SUBJECT_0);
} catch (final IOException | RestClientException e) {
throw new RuntimeException(e);
}
});
}
private static Schema avroSchema(final int i) {
return new Schema.Parser().parse(avroSchemaString(i));
}
private static String avroSchemaString(final int i) {
return "{\"type\": \"record\", \"name\": \"Blah" + i + "\", "
+ "\"fields\": [{ \"name\": \"name\", \"type\": \"string\" }]}";
} |
<<<<<<<
import org.apache.kafka.common.cache.Cache;
=======
import org.apache.kafka.copycat.data.Date;
import org.apache.kafka.copycat.data.Decimal;
>>>>>>>
import org.apache.kafka.common.cache.Cache;
import org.apache.kafka.copycat.data.Date;
import org.apache.kafka.copycat.data.Decimal; |
<<<<<<<
private int forwardRegisterRequestToLeader(String subject, Schema schema,
=======
public void checkIfSchemaWithIdExist(int id, Schema schema)
throws SchemaRegistryException, StoreException {
SchemaKey existingKey = this.lookupCache.schemaKeyById(id);
if (existingKey != null) {
SchemaRegistryValue existingValue = this.lookupCache.get(existingKey);
if (existingValue != null
&& existingValue instanceof SchemaValue
&& !((SchemaValue) existingValue).getSchema().equals(schema.getSchema())) {
throw new OperationNotPermittedException(
String.format("Overwrite new schema with id %s is not permitted.", id)
);
}
}
}
private int forwardRegisterRequestToMaster(String subject, Schema schema,
>>>>>>>
public void checkIfSchemaWithIdExist(int id, Schema schema)
throws SchemaRegistryException, StoreException {
SchemaKey existingKey = this.lookupCache.schemaKeyById(id);
if (existingKey != null) {
SchemaRegistryValue existingValue = this.lookupCache.get(existingKey);
if (existingValue != null
&& existingValue instanceof SchemaValue
&& !((SchemaValue) existingValue).getSchema().equals(schema.getSchema())) {
throw new OperationNotPermittedException(
String.format("Overwrite new schema with id %s is not permitted.", id)
);
}
}
}
private int forwardRegisterRequestToLeader(String subject, Schema schema, |
<<<<<<<
private final String TAG = "CameraPreview";
private final String setOnPictureTakenHandlerAction = "setOnPictureTakenHandler";
private final String setColorEffectAction = "setColorEffect";
private final String startCameraAction = "startCamera";
private final String stopCameraAction = "stopCamera";
private final String switchCameraAction = "switchCamera";
private final String takePictureAction = "takePicture";
private final String showCameraAction = "showCamera";
private final String hideCameraAction = "hideCamera";
private final String getSupportedPreviewSizesAction = "getSupportedPreviewSizes";
private final String getSupportedPictureSizesAction = "getSupportedPictureSizes";
private CameraActivity fragment;
private CallbackContext takePictureCallbackContext;
private int containerViewId = 1;
public CameraPreview(){
super();
Log.d(TAG, "Constructing");
}
=======
private final String TAG = "CameraPreview";
private final String setOnPictureTakenHandlerAction = "setOnPictureTakenHandler";
private final String setColorEffectAction = "setColorEffect";
private final String startCameraAction = "startCamera";
private final String stopCameraAction = "stopCamera";
private final String switchCameraAction = "switchCamera";
private final String takePictureAction = "takePicture";
private final String showCameraAction = "showCamera";
private final String hideCameraAction = "hideCamera";
private CameraActivity fragment;
private CallbackContext takePictureCallbackContext;
private CallbackContext wLogCallbackContext;
private int containerViewId = 1;
public CameraPreview() {
super();
Log.d(TAG, "Constructing");
}
>>>>>>>
private final String TAG = "CameraPreview";
private final String setOnPictureTakenHandlerAction = "setOnPictureTakenHandler";
private final String setColorEffectAction = "setColorEffect";
private final String startCameraAction = "startCamera";
private final String stopCameraAction = "stopCamera";
private final String switchCameraAction = "switchCamera";
private final String takePictureAction = "takePicture";
private final String showCameraAction = "showCamera";
private final String hideCameraAction = "hideCamera";
private final String getSupportedPreviewSizesAction = "getSupportedPreviewSizes";
private final String getSupportedPictureSizesAction = "getSupportedPictureSizes";
private CameraActivity fragment;
private CallbackContext takePictureCallbackContext;
private CallbackContext wLogCallbackContext;
private int containerViewId = 1;
public CameraPreview() {
super();
Log.d(TAG, "Constructing");
} |
<<<<<<<
import cn.vbill.middleware.porter.common.task.config.PublicSourceConfig;
=======
>>>>>>>
import cn.vbill.middleware.porter.common.task.config.PublicSourceConfig;
<<<<<<<
import cn.vbill.middleware.porter.common.plugin.config.PluginServiceConfig;
=======
import cn.vbill.middleware.porter.common.config.PublicSourceConfig;
>>>>>>> |
<<<<<<<
private int batchSize = 50;
private int totalRecordsWritten = 0;
private boolean veryLargeBulk = false; // by default this setting is set to false
=======
private long batchSize;
private boolean veryLargeBulk; // by default this setting is set to false
>>>>>>>
private long batchSize;
private boolean veryLargeBulk; // by default this setting is set to false
private int totalRecordsWritten = 0;
<<<<<<<
public void setBatchSize(int batchSize) {
this.batchSize = batchSize;
}
public void setVeryLargeBulk(boolean veryLargeBulk) {
this.veryLargeBulk = veryLargeBulk;
}
=======
private final List<String> affectedIndexes = new ArrayList<String>();
>>>>>>>
public void setBatchSize(int batchSize) {
this.batchSize = batchSize;
}
public void setVeryLargeBulk(boolean veryLargeBulk) {
this.veryLargeBulk = veryLargeBulk;
}
private final List<String> affectedIndexes = new ArrayList<String>();
<<<<<<<
public int getTotalOk() {
return totalOk;
}
=======
private ObjectMapper mapper;
>>>>>>>
public int getTotalOk() {
return totalOk;
}
private ObjectMapper mapper = new StreamsJacksonMapper();
<<<<<<<
public void add(String indexName, String type, String json) {
=======
private void flush(final BulkRequestBuilder bulkRequest, final Integer thisSent, final Long thisSizeInBytes)
{
bulkRequest.execute().addListener(new ActionListener<BulkResponse>()
{
@Override
public void onResponse(BulkResponse bulkItemResponses)
{
if (bulkItemResponses.hasFailures())
LOGGER.warn("Bulk Uploading had totalFailed: " + bulkItemResponses.buildFailureMessage());
long thisFailed = 0;
long thisOk = 0;
long thisMillis = bulkItemResponses.getTookInMillis();
// keep track of the number of totalFailed and items that we have totalOk.
for(BulkItemResponse resp : bulkItemResponses.getItems())
{
if(resp.isFailed())
thisFailed++;
else
thisOk++;
}
totalAttempted += thisSent;
totalOk += thisOk;
totalFailed += thisFailed;
totalSeconds += (thisMillis / 1000);
if(thisSent != (thisOk + thisFailed))
LOGGER.error("We sent more items than this");
LOGGER.debug("Batch[{}mb {} items with {} failures in {}ms] - Total[{}mb {} items with {} failures in {}seconds] {} outstanding]",
MEGABYTE_FORMAT.format((double) thisSizeInBytes / (double)(1024*1024)), NUMBER_FORMAT.format(thisOk), NUMBER_FORMAT.format(thisFailed), NUMBER_FORMAT.format(thisMillis),
MEGABYTE_FORMAT.format((double) totalSizeInBytes / (double)(1024*1024)), NUMBER_FORMAT.format(totalOk), NUMBER_FORMAT.format(totalFailed), NUMBER_FORMAT.format(totalSeconds), NUMBER_FORMAT.format(getTotalOutstanding()));
}
@Override
public void onFailure(Throwable e)
{
LOGGER.error("Error bulk loading: {}", e.getMessage());
e.printStackTrace();
}
});
this.notify();
}
public void add(String indexName, String type, String json)
{
>>>>>>>
public void add(String indexName, String type, String json) {
<<<<<<<
=======
private void trackItemAndBytesWritten(long sizeInBytes)
{
currentItems++;
batchItemsSent++;
batchSizeInBytes += sizeInBytes;
// If our queue is larger than our flush threashold, then we should flush the queue.
if( (batchSizeInBytes > flushThresholdSizeInBytes) ||
(currentItems >= batchSize) )
flushInternal();
}
private void checkAndCreateBulkRequest()
{
// Synchronize to ensure that we don't lose any records
synchronized (this)
{
if(bulkRequest == null)
bulkRequest = this.manager.getClient().prepareBulk();
}
}
private void checkIndexImplications(String indexName)
{
// check to see if we have seen this index before.
if(this.affectedIndexes.contains(indexName))
return;
// we haven't log this index.
this.affectedIndexes.add(indexName);
// Check to see if we are in 'veryLargeBulk' mode
// if we aren't, exit early
if(!this.veryLargeBulk)
return;
// They are in 'very large bulk' mode we want to turn off refreshing the index.
// Create a request then add the setting to tell it to stop refreshing the interval
UpdateSettingsRequest updateSettingsRequest = new UpdateSettingsRequest(indexName);
updateSettingsRequest.settings(ImmutableSettings.settingsBuilder().put("refresh_interval", -1));
// submit to ElasticSearch
this.manager.getClient()
.admin()
.indices()
.updateSettings(updateSettingsRequest)
.actionGet();
}
>>>>>>>
private void trackItemAndBytesWritten(long sizeInBytes)
{
currentItems++;
batchItemsSent++;
batchSizeInBytes += sizeInBytes;
// If our queue is larger than our flush threashold, then we should flush the queue.
if( (batchSizeInBytes > flushThresholdSizeInBytes) ||
(currentItems >= batchSize) )
flushInternal();
}
private void checkAndCreateBulkRequest()
{
// Synchronize to ensure that we don't lose any records
synchronized (this)
{
if(bulkRequest == null)
bulkRequest = this.manager.getClient().prepareBulk();
}
}
private void checkIndexImplications(String indexName)
{
// check to see if we have seen this index before.
if(this.affectedIndexes.contains(indexName))
return;
// we haven't log this index.
this.affectedIndexes.add(indexName);
// Check to see if we are in 'veryLargeBulk' mode
// if we aren't, exit early
if(!this.veryLargeBulk)
return;
// They are in 'very large bulk' mode we want to turn off refreshing the index.
// Create a request then add the setting to tell it to stop refreshing the interval
UpdateSettingsRequest updateSettingsRequest = new UpdateSettingsRequest(indexName);
updateSettingsRequest.settings(ImmutableSettings.settingsBuilder().put("refresh_interval", -1));
// submit to ElasticSearch
this.manager.getClient()
.admin()
.indices()
.updateSettings(updateSettingsRequest)
.actionGet();
}
<<<<<<<
private void flush(final BulkRequestBuilder bulkRequest, final Integer thisSent, final Long thisSizeInBytes) {
bulkRequest.execute().addListener(new ActionListener<BulkResponse>() {
@Override
public void onResponse(BulkResponse bulkItemResponses) {
if (bulkItemResponses.hasFailures())
LOGGER.warn("Bulk Uploading had totalFailed: " + bulkItemResponses.buildFailureMessage());
long thisFailed = 0;
long thisOk = 0;
long thisMillis = bulkItemResponses.getTookInMillis();
// keep track of the number of totalFailed and items that we have totalOk.
for (BulkItemResponse resp : bulkItemResponses.getItems()) {
if (resp.isFailed())
thisFailed++;
else
thisOk++;
}
totalAttempted += thisSent;
totalOk += thisOk;
totalFailed += thisFailed;
totalSeconds += (thisMillis / 1000);
if (thisSent != (thisOk + thisFailed))
LOGGER.error("We sent more items than this");
LOGGER.debug("Batch[{}mb {} items with {} failures in {}ms] - Total[{}mb {} items with {} failures in {}seconds] {} outstanding]",
MEGABYTE_FORMAT.format((double) thisSizeInBytes / (double) (1024 * 1024)), NUMBER_FORMAT.format(thisOk), NUMBER_FORMAT.format(thisFailed), NUMBER_FORMAT.format(thisMillis),
MEGABYTE_FORMAT.format((double) totalSizeInBytes / (double) (1024 * 1024)), NUMBER_FORMAT.format(totalOk), NUMBER_FORMAT.format(totalFailed), NUMBER_FORMAT.format(totalSeconds), NUMBER_FORMAT.format(getTotalOutstanding()));
}
@Override
public void onFailure(Throwable e) {
LOGGER.error("Error bulk loading: {}", e.getMessage());
e.printStackTrace();
}
});
this.notify();
=======
@Override
public void prepare(Object configurationObject) {
mapper = StreamsJacksonMapper.getInstance();
veryLargeBulk = this.config.getBulk();
batchSize = this.config.getBatchSize();
start();
>>>>>>>
@Override
public void prepare(Object configurationObject) {
mapper = StreamsJacksonMapper.getInstance();
veryLargeBulk = this.config.getBulk();
batchSize = this.config.getBatchSize();
start();
}
private void flush(final BulkRequestBuilder bulkRequest, final Integer thisSent, final Long thisSizeInBytes) {
bulkRequest.execute().addListener(new ActionListener<BulkResponse>() {
@Override
public void onResponse(BulkResponse bulkItemResponses) {
if (bulkItemResponses.hasFailures())
LOGGER.warn("Bulk Uploading had totalFailed: " + bulkItemResponses.buildFailureMessage());
long thisFailed = 0;
long thisOk = 0;
long thisMillis = bulkItemResponses.getTookInMillis();
// keep track of the number of totalFailed and items that we have totalOk.
for (BulkItemResponse resp : bulkItemResponses.getItems()) {
if (resp.isFailed())
thisFailed++;
else
thisOk++;
}
totalAttempted += thisSent;
totalOk += thisOk;
totalFailed += thisFailed;
totalSeconds += (thisMillis / 1000);
if (thisSent != (thisOk + thisFailed))
LOGGER.error("We sent more items than this");
LOGGER.debug("Batch[{}mb {} items with {} failures in {}ms] - Total[{}mb {} items with {} failures in {}seconds] {} outstanding]",
MEGABYTE_FORMAT.format((double) thisSizeInBytes / (double) (1024 * 1024)), NUMBER_FORMAT.format(thisOk), NUMBER_FORMAT.format(thisFailed), NUMBER_FORMAT.format(thisMillis),
MEGABYTE_FORMAT.format((double) totalSizeInBytes / (double) (1024 * 1024)), NUMBER_FORMAT.format(totalOk), NUMBER_FORMAT.format(totalFailed), NUMBER_FORMAT.format(totalSeconds), NUMBER_FORMAT.format(getTotalOutstanding()));
}
@Override
public void onFailure(Throwable e) {
LOGGER.error("Error bulk loading: {}", e.getMessage());
e.printStackTrace();
}
});
this.notify(); |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.