repo_name stringlengths 7 104 | file_path stringlengths 13 198 | context stringlengths 67 7.15k | import_statement stringlengths 16 4.43k | code stringlengths 40 6.98k | prompt stringlengths 227 8.27k | next_line stringlengths 8 795 |
|---|---|---|---|---|---|---|
vikasdesale/News24x7-news-from-every-part-of-the-world | app/src/main/java/com/news/news24x7/database/NewsProvider.java | // Path: app/src/main/java/com/news/news24x7/interfaces/ColumnsNews.java
// public interface ColumnsNews {
// @DataType(DataType.Type.INTEGER)
// @PrimaryKey
// @AutoIncrement
// String _ID = "_id";
// @DataType(DataType.Type.TEXT)
// @NotNull
// String AUTHOR = "author";
// @DataType(DataType.Type.TEXT)
// @NotNull
// String TITLE = "title";
// @DataType(DataType.Type.TEXT)
// @NotNull
// String DESCRIPTION = "description";
// @DataType(DataType.Type.TEXT)
// @NotNull
// String URL = "url";
// @DataType(DataType.Type.TEXT)
// @NotNull
// String URL_TO_IMAGE = "urlToImage";
// @DataType(DataType.Type.TEXT)
// @NotNull
// String PUBLISHED_AT = "publishedAt";
//
//
// }
| import android.net.Uri;
import com.news.news24x7.interfaces.ColumnsNews;
import net.simonvt.schematic.annotation.ContentProvider;
import net.simonvt.schematic.annotation.ContentUri;
import net.simonvt.schematic.annotation.TableEndpoint; | package com.news.news24x7.database;
/**
* Created by Dell on 6/4/2017.
*/
@ContentProvider(authority = NewsProvider.AUTHORITY, database = NewsDatabase.class)
public class NewsProvider {
public static final String AUTHORITY = "com.news.news24x7";
public static final Uri BASE_CONTENT_URI = Uri.parse("content://" + AUTHORITY);
private static Uri buildUri(String... paths) {
Uri.Builder builder = BASE_CONTENT_URI.buildUpon();
for (String path : paths) {
builder.appendPath(path);
}
return builder.build();
}
interface Path {
String MY_NEWS = "myNews";
String FAVOURITE_NEWS = "myFavouriteNews";
}
@TableEndpoint(table = NewsDatabase.MY_NEWS)
public static class MyNews {
@ContentUri(
path = Path.MY_NEWS,
type = "vnd.android.cursor.dir/myNews", | // Path: app/src/main/java/com/news/news24x7/interfaces/ColumnsNews.java
// public interface ColumnsNews {
// @DataType(DataType.Type.INTEGER)
// @PrimaryKey
// @AutoIncrement
// String _ID = "_id";
// @DataType(DataType.Type.TEXT)
// @NotNull
// String AUTHOR = "author";
// @DataType(DataType.Type.TEXT)
// @NotNull
// String TITLE = "title";
// @DataType(DataType.Type.TEXT)
// @NotNull
// String DESCRIPTION = "description";
// @DataType(DataType.Type.TEXT)
// @NotNull
// String URL = "url";
// @DataType(DataType.Type.TEXT)
// @NotNull
// String URL_TO_IMAGE = "urlToImage";
// @DataType(DataType.Type.TEXT)
// @NotNull
// String PUBLISHED_AT = "publishedAt";
//
//
// }
// Path: app/src/main/java/com/news/news24x7/database/NewsProvider.java
import android.net.Uri;
import com.news.news24x7.interfaces.ColumnsNews;
import net.simonvt.schematic.annotation.ContentProvider;
import net.simonvt.schematic.annotation.ContentUri;
import net.simonvt.schematic.annotation.TableEndpoint;
package com.news.news24x7.database;
/**
* Created by Dell on 6/4/2017.
*/
@ContentProvider(authority = NewsProvider.AUTHORITY, database = NewsDatabase.class)
public class NewsProvider {
public static final String AUTHORITY = "com.news.news24x7";
public static final Uri BASE_CONTENT_URI = Uri.parse("content://" + AUTHORITY);
private static Uri buildUri(String... paths) {
Uri.Builder builder = BASE_CONTENT_URI.buildUpon();
for (String path : paths) {
builder.appendPath(path);
}
return builder.build();
}
interface Path {
String MY_NEWS = "myNews";
String FAVOURITE_NEWS = "myFavouriteNews";
}
@TableEndpoint(table = NewsDatabase.MY_NEWS)
public static class MyNews {
@ContentUri(
path = Path.MY_NEWS,
type = "vnd.android.cursor.dir/myNews", | defaultSort = ColumnsNews._ID + " ASC") |
vikasdesale/News24x7-news-from-every-part-of-the-world | app/src/main/java/com/news/news24x7/util/NewsUtil.java | // Path: app/src/main/java/com/news/news24x7/database/NewsProvider.java
// @ContentProvider(authority = NewsProvider.AUTHORITY, database = NewsDatabase.class)
// public class NewsProvider {
//
// public static final String AUTHORITY = "com.news.news24x7";
// public static final Uri BASE_CONTENT_URI = Uri.parse("content://" + AUTHORITY);
//
// private static Uri buildUri(String... paths) {
// Uri.Builder builder = BASE_CONTENT_URI.buildUpon();
// for (String path : paths) {
// builder.appendPath(path);
// }
// return builder.build();
// }
//
// interface Path {
// String MY_NEWS = "myNews";
// String FAVOURITE_NEWS = "myFavouriteNews";
// }
//
// @TableEndpoint(table = NewsDatabase.MY_NEWS)
// public static class MyNews {
// @ContentUri(
// path = Path.MY_NEWS,
// type = "vnd.android.cursor.dir/myNews",
// defaultSort = ColumnsNews._ID + " ASC")
// public static final Uri CONTENT_URI = buildUri(Path.MY_NEWS);
//
// }
//
// @TableEndpoint(table = NewsDatabase.FAVOURITE_NEWS)
// public static class NewsFavourite {
// @ContentUri(
// path = Path.FAVOURITE_NEWS,
// type = "vnd.android.cursor.dir/myFavouriteNews",
// defaultSort = ColumnsNews._ID + " ASC")
// public static final Uri CONTENT_URI_FAVOURITE = buildUri(Path.FAVOURITE_NEWS);
//
// }
// }
//
// Path: app/src/main/java/com/news/news24x7/interfaces/ColumnsNews.java
// public interface ColumnsNews {
// @DataType(DataType.Type.INTEGER)
// @PrimaryKey
// @AutoIncrement
// String _ID = "_id";
// @DataType(DataType.Type.TEXT)
// @NotNull
// String AUTHOR = "author";
// @DataType(DataType.Type.TEXT)
// @NotNull
// String TITLE = "title";
// @DataType(DataType.Type.TEXT)
// @NotNull
// String DESCRIPTION = "description";
// @DataType(DataType.Type.TEXT)
// @NotNull
// String URL = "url";
// @DataType(DataType.Type.TEXT)
// @NotNull
// String URL_TO_IMAGE = "urlToImage";
// @DataType(DataType.Type.TEXT)
// @NotNull
// String PUBLISHED_AT = "publishedAt";
//
//
// }
//
// Path: app/src/main/java/com/news/news24x7/parcelable/Article.java
// public class Article implements Serializable, Parcelable {
//
// private final static long serialVersionUID = 8755682695955568073L;
// public final Parcelable.Creator<Article> CREATOR = new Parcelable.Creator<Article>() {
// @Override
// public Article createFromParcel(Parcel parcel) {
// return new Article(parcel);
// }
//
// @Override
// public Article[] newArray(int i) {
// return new Article[i];
// }
//
// };
// @SerializedName("author")
// private String author;
// @SerializedName("title")
// private String title;
// @SerializedName("description")
// private String description;
// @SerializedName("url")
// private String url;
// @SerializedName("urlToImage")
// private String urlToImage;
// @SerializedName("publishedAt")
// private String publishedAt;
//
// public Article(String mTitle, String mAuthor, String mDescription, String mUrl, String mUrlToImage, String mPublishedAt) {
// this.title = mTitle;
// this.author = mAuthor;
// this.description = mDescription;
// this.url = mUrl;
// this.urlToImage = mUrlToImage;
// this.publishedAt = mPublishedAt;
// }
//
//
// private Article(Parcel in) {
// this.author = in.readString();
// this.title = in.readString();
// this.description = in.readString();
// this.url = in.readString();
// this.urlToImage = in.readString();
// this.publishedAt = in.readString();
// }
//
// public String getAuthor() {
// return author;
// }
//
// public void setAuthor(String author) {
// this.author = author;
// }
//
// public String getTitle() {
// return title;
// }
//
// public void setTitle(String title) {
// this.title = title;
// }
//
// public String getDescription() {
// return description;
// }
//
// public void setDescription(String description) {
// this.description = description;
// }
//
// public String getUrl() {
// return url;
// }
//
// public void setUrl(String url) {
// this.url = url;
// }
//
// public String getUrlToImage() {
// return urlToImage;
// }
//
// public void setUrlToImage(String urlToImage) {
// this.urlToImage = urlToImage;
// }
//
// public String getPublishedAt() {
// return publishedAt;
// }
//
// public void setPublishedAt(String publishedAt) {
// this.publishedAt = publishedAt;
// }
//
// public void writeToParcel(Parcel dest, int flags) {
// dest.writeValue(author);
// dest.writeValue(title);
// dest.writeValue(description);
// dest.writeValue(url);
// dest.writeValue(urlToImage);
// dest.writeValue(publishedAt);
// }
//
// public int describeContents() {
// return 0;
// }
//
// }
| import android.content.ContentProviderOperation;
import android.content.Context;
import android.database.Cursor;
import com.news.news24x7.database.NewsProvider;
import com.news.news24x7.interfaces.ColumnsNews;
import com.news.news24x7.parcelable.Article;
import java.util.ArrayList; | package com.news.news24x7.util;
/**
* Created by Dell on 6/4/2017.
*/
public class NewsUtil {
public static final String FAVORITE = "favorite";
Cursor c;
int count = 0;
public static void CacheDelete(Context context) {
try {
| // Path: app/src/main/java/com/news/news24x7/database/NewsProvider.java
// @ContentProvider(authority = NewsProvider.AUTHORITY, database = NewsDatabase.class)
// public class NewsProvider {
//
// public static final String AUTHORITY = "com.news.news24x7";
// public static final Uri BASE_CONTENT_URI = Uri.parse("content://" + AUTHORITY);
//
// private static Uri buildUri(String... paths) {
// Uri.Builder builder = BASE_CONTENT_URI.buildUpon();
// for (String path : paths) {
// builder.appendPath(path);
// }
// return builder.build();
// }
//
// interface Path {
// String MY_NEWS = "myNews";
// String FAVOURITE_NEWS = "myFavouriteNews";
// }
//
// @TableEndpoint(table = NewsDatabase.MY_NEWS)
// public static class MyNews {
// @ContentUri(
// path = Path.MY_NEWS,
// type = "vnd.android.cursor.dir/myNews",
// defaultSort = ColumnsNews._ID + " ASC")
// public static final Uri CONTENT_URI = buildUri(Path.MY_NEWS);
//
// }
//
// @TableEndpoint(table = NewsDatabase.FAVOURITE_NEWS)
// public static class NewsFavourite {
// @ContentUri(
// path = Path.FAVOURITE_NEWS,
// type = "vnd.android.cursor.dir/myFavouriteNews",
// defaultSort = ColumnsNews._ID + " ASC")
// public static final Uri CONTENT_URI_FAVOURITE = buildUri(Path.FAVOURITE_NEWS);
//
// }
// }
//
// Path: app/src/main/java/com/news/news24x7/interfaces/ColumnsNews.java
// public interface ColumnsNews {
// @DataType(DataType.Type.INTEGER)
// @PrimaryKey
// @AutoIncrement
// String _ID = "_id";
// @DataType(DataType.Type.TEXT)
// @NotNull
// String AUTHOR = "author";
// @DataType(DataType.Type.TEXT)
// @NotNull
// String TITLE = "title";
// @DataType(DataType.Type.TEXT)
// @NotNull
// String DESCRIPTION = "description";
// @DataType(DataType.Type.TEXT)
// @NotNull
// String URL = "url";
// @DataType(DataType.Type.TEXT)
// @NotNull
// String URL_TO_IMAGE = "urlToImage";
// @DataType(DataType.Type.TEXT)
// @NotNull
// String PUBLISHED_AT = "publishedAt";
//
//
// }
//
// Path: app/src/main/java/com/news/news24x7/parcelable/Article.java
// public class Article implements Serializable, Parcelable {
//
// private final static long serialVersionUID = 8755682695955568073L;
// public final Parcelable.Creator<Article> CREATOR = new Parcelable.Creator<Article>() {
// @Override
// public Article createFromParcel(Parcel parcel) {
// return new Article(parcel);
// }
//
// @Override
// public Article[] newArray(int i) {
// return new Article[i];
// }
//
// };
// @SerializedName("author")
// private String author;
// @SerializedName("title")
// private String title;
// @SerializedName("description")
// private String description;
// @SerializedName("url")
// private String url;
// @SerializedName("urlToImage")
// private String urlToImage;
// @SerializedName("publishedAt")
// private String publishedAt;
//
// public Article(String mTitle, String mAuthor, String mDescription, String mUrl, String mUrlToImage, String mPublishedAt) {
// this.title = mTitle;
// this.author = mAuthor;
// this.description = mDescription;
// this.url = mUrl;
// this.urlToImage = mUrlToImage;
// this.publishedAt = mPublishedAt;
// }
//
//
// private Article(Parcel in) {
// this.author = in.readString();
// this.title = in.readString();
// this.description = in.readString();
// this.url = in.readString();
// this.urlToImage = in.readString();
// this.publishedAt = in.readString();
// }
//
// public String getAuthor() {
// return author;
// }
//
// public void setAuthor(String author) {
// this.author = author;
// }
//
// public String getTitle() {
// return title;
// }
//
// public void setTitle(String title) {
// this.title = title;
// }
//
// public String getDescription() {
// return description;
// }
//
// public void setDescription(String description) {
// this.description = description;
// }
//
// public String getUrl() {
// return url;
// }
//
// public void setUrl(String url) {
// this.url = url;
// }
//
// public String getUrlToImage() {
// return urlToImage;
// }
//
// public void setUrlToImage(String urlToImage) {
// this.urlToImage = urlToImage;
// }
//
// public String getPublishedAt() {
// return publishedAt;
// }
//
// public void setPublishedAt(String publishedAt) {
// this.publishedAt = publishedAt;
// }
//
// public void writeToParcel(Parcel dest, int flags) {
// dest.writeValue(author);
// dest.writeValue(title);
// dest.writeValue(description);
// dest.writeValue(url);
// dest.writeValue(urlToImage);
// dest.writeValue(publishedAt);
// }
//
// public int describeContents() {
// return 0;
// }
//
// }
// Path: app/src/main/java/com/news/news24x7/util/NewsUtil.java
import android.content.ContentProviderOperation;
import android.content.Context;
import android.database.Cursor;
import com.news.news24x7.database.NewsProvider;
import com.news.news24x7.interfaces.ColumnsNews;
import com.news.news24x7.parcelable.Article;
import java.util.ArrayList;
package com.news.news24x7.util;
/**
* Created by Dell on 6/4/2017.
*/
public class NewsUtil {
public static final String FAVORITE = "favorite";
Cursor c;
int count = 0;
public static void CacheDelete(Context context) {
try {
| context.getContentResolver().delete(NewsProvider.MyNews.CONTENT_URI, |
vikasdesale/News24x7-news-from-every-part-of-the-world | app/src/main/java/com/news/news24x7/util/NewsSyncUtils.java | // Path: app/src/main/java/com/news/news24x7/sync/NewsFirebaseJobService.java
// public class NewsFirebaseJobService extends JobService {
//
// private AsyncTask<Void, Void, Void> mNewsFetchTask;
//
//
// @Override
// public boolean onStartJob(final JobParameters jobParameters) {
//
// mNewsFetchTask = new AsyncTask<Void, Void, Void>() {
// @Override
// protected Void doInBackground(Void... voids) {
// Context context = getApplicationContext();
// NewsSyncTask.syncNews(context);
// jobFinished(jobParameters, false);
// return null;
// }
//
// @Override
// protected void onPostExecute(Void aVoid) {
// jobFinished(jobParameters, false);
// }
// };
//
// mNewsFetchTask.execute();
// return true;
// }
//
//
// @Override
// public boolean onStopJob(JobParameters jobParameters) {
// if (mNewsFetchTask != null) {
// mNewsFetchTask.cancel(true);
// }
// return true;
// }
// }
//
// Path: app/src/main/java/com/news/news24x7/sync/NewsSyncIntentService.java
// public class NewsSyncIntentService extends IntentService {
//
// public NewsSyncIntentService() {
// super("NewsSyncIntentService");
// }
//
// @Override
// protected void onHandleIntent(Intent intent) {
// NewsSyncTask.syncNews(this);
// }
// }
| import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.support.annotation.NonNull;
import com.news.news24x7.sync.NewsFirebaseJobService;
import com.news.news24x7.sync.NewsSyncIntentService;
import com.firebase.jobdispatcher.Constraint;
import com.firebase.jobdispatcher.Driver;
import com.firebase.jobdispatcher.FirebaseJobDispatcher;
import com.firebase.jobdispatcher.GooglePlayDriver;
import com.firebase.jobdispatcher.Job;
import com.firebase.jobdispatcher.Lifetime;
import com.firebase.jobdispatcher.Trigger;
import java.util.concurrent.TimeUnit; | package com.news.news24x7.util;
/**
* Created by Dell on 6/6/2017.
*/
public class NewsSyncUtils {
private static final int REMINDER_INTERVAL_MINUTES = 180;
private static final int REMINDER_INTERVAL_SECONDS = (int) (TimeUnit.MINUTES.toSeconds(REMINDER_INTERVAL_MINUTES));
private static final int SYNC_FLEXTIME_SECONDS = REMINDER_INTERVAL_SECONDS;
private static final String NEWS_SYNC_TAG = "news-sync";
static NewsUtil mNewsUtil;
private static boolean sInitialized;
static void scheduleFirebaseJobDispatcherSync(@NonNull final Context context) {
Driver driver = new GooglePlayDriver(context);
FirebaseJobDispatcher dispatcher = new FirebaseJobDispatcher(driver);
/* Create the Job to periodically sync Sunshine */
Job syncSunshineJob = dispatcher.newJobBuilder() | // Path: app/src/main/java/com/news/news24x7/sync/NewsFirebaseJobService.java
// public class NewsFirebaseJobService extends JobService {
//
// private AsyncTask<Void, Void, Void> mNewsFetchTask;
//
//
// @Override
// public boolean onStartJob(final JobParameters jobParameters) {
//
// mNewsFetchTask = new AsyncTask<Void, Void, Void>() {
// @Override
// protected Void doInBackground(Void... voids) {
// Context context = getApplicationContext();
// NewsSyncTask.syncNews(context);
// jobFinished(jobParameters, false);
// return null;
// }
//
// @Override
// protected void onPostExecute(Void aVoid) {
// jobFinished(jobParameters, false);
// }
// };
//
// mNewsFetchTask.execute();
// return true;
// }
//
//
// @Override
// public boolean onStopJob(JobParameters jobParameters) {
// if (mNewsFetchTask != null) {
// mNewsFetchTask.cancel(true);
// }
// return true;
// }
// }
//
// Path: app/src/main/java/com/news/news24x7/sync/NewsSyncIntentService.java
// public class NewsSyncIntentService extends IntentService {
//
// public NewsSyncIntentService() {
// super("NewsSyncIntentService");
// }
//
// @Override
// protected void onHandleIntent(Intent intent) {
// NewsSyncTask.syncNews(this);
// }
// }
// Path: app/src/main/java/com/news/news24x7/util/NewsSyncUtils.java
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.support.annotation.NonNull;
import com.news.news24x7.sync.NewsFirebaseJobService;
import com.news.news24x7.sync.NewsSyncIntentService;
import com.firebase.jobdispatcher.Constraint;
import com.firebase.jobdispatcher.Driver;
import com.firebase.jobdispatcher.FirebaseJobDispatcher;
import com.firebase.jobdispatcher.GooglePlayDriver;
import com.firebase.jobdispatcher.Job;
import com.firebase.jobdispatcher.Lifetime;
import com.firebase.jobdispatcher.Trigger;
import java.util.concurrent.TimeUnit;
package com.news.news24x7.util;
/**
* Created by Dell on 6/6/2017.
*/
public class NewsSyncUtils {
private static final int REMINDER_INTERVAL_MINUTES = 180;
private static final int REMINDER_INTERVAL_SECONDS = (int) (TimeUnit.MINUTES.toSeconds(REMINDER_INTERVAL_MINUTES));
private static final int SYNC_FLEXTIME_SECONDS = REMINDER_INTERVAL_SECONDS;
private static final String NEWS_SYNC_TAG = "news-sync";
static NewsUtil mNewsUtil;
private static boolean sInitialized;
static void scheduleFirebaseJobDispatcherSync(@NonNull final Context context) {
Driver driver = new GooglePlayDriver(context);
FirebaseJobDispatcher dispatcher = new FirebaseJobDispatcher(driver);
/* Create the Job to periodically sync Sunshine */
Job syncSunshineJob = dispatcher.newJobBuilder() | .setService(NewsFirebaseJobService.class) |
vikasdesale/News24x7-news-from-every-part-of-the-world | app/src/main/java/com/news/news24x7/util/NewsSyncUtils.java | // Path: app/src/main/java/com/news/news24x7/sync/NewsFirebaseJobService.java
// public class NewsFirebaseJobService extends JobService {
//
// private AsyncTask<Void, Void, Void> mNewsFetchTask;
//
//
// @Override
// public boolean onStartJob(final JobParameters jobParameters) {
//
// mNewsFetchTask = new AsyncTask<Void, Void, Void>() {
// @Override
// protected Void doInBackground(Void... voids) {
// Context context = getApplicationContext();
// NewsSyncTask.syncNews(context);
// jobFinished(jobParameters, false);
// return null;
// }
//
// @Override
// protected void onPostExecute(Void aVoid) {
// jobFinished(jobParameters, false);
// }
// };
//
// mNewsFetchTask.execute();
// return true;
// }
//
//
// @Override
// public boolean onStopJob(JobParameters jobParameters) {
// if (mNewsFetchTask != null) {
// mNewsFetchTask.cancel(true);
// }
// return true;
// }
// }
//
// Path: app/src/main/java/com/news/news24x7/sync/NewsSyncIntentService.java
// public class NewsSyncIntentService extends IntentService {
//
// public NewsSyncIntentService() {
// super("NewsSyncIntentService");
// }
//
// @Override
// protected void onHandleIntent(Intent intent) {
// NewsSyncTask.syncNews(this);
// }
// }
| import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.support.annotation.NonNull;
import com.news.news24x7.sync.NewsFirebaseJobService;
import com.news.news24x7.sync.NewsSyncIntentService;
import com.firebase.jobdispatcher.Constraint;
import com.firebase.jobdispatcher.Driver;
import com.firebase.jobdispatcher.FirebaseJobDispatcher;
import com.firebase.jobdispatcher.GooglePlayDriver;
import com.firebase.jobdispatcher.Job;
import com.firebase.jobdispatcher.Lifetime;
import com.firebase.jobdispatcher.Trigger;
import java.util.concurrent.TimeUnit; | package com.news.news24x7.util;
/**
* Created by Dell on 6/6/2017.
*/
public class NewsSyncUtils {
private static final int REMINDER_INTERVAL_MINUTES = 180;
private static final int REMINDER_INTERVAL_SECONDS = (int) (TimeUnit.MINUTES.toSeconds(REMINDER_INTERVAL_MINUTES));
private static final int SYNC_FLEXTIME_SECONDS = REMINDER_INTERVAL_SECONDS;
private static final String NEWS_SYNC_TAG = "news-sync";
static NewsUtil mNewsUtil;
private static boolean sInitialized;
static void scheduleFirebaseJobDispatcherSync(@NonNull final Context context) {
Driver driver = new GooglePlayDriver(context);
FirebaseJobDispatcher dispatcher = new FirebaseJobDispatcher(driver);
/* Create the Job to periodically sync Sunshine */
Job syncSunshineJob = dispatcher.newJobBuilder()
.setService(NewsFirebaseJobService.class)
.setTag(NEWS_SYNC_TAG)
.setConstraints(Constraint.ON_ANY_NETWORK)
.setLifetime(Lifetime.FOREVER)
.setRecurring(true)
.setTrigger(Trigger.executionWindow(
REMINDER_INTERVAL_SECONDS,
REMINDER_INTERVAL_SECONDS + SYNC_FLEXTIME_SECONDS))
.setReplaceCurrent(true)
.build();
dispatcher.schedule(syncSunshineJob);
}
synchronized public static void initialize(@NonNull final Context context) {
if (sInitialized) return;
sInitialized = true;
scheduleFirebaseJobDispatcherSync(context);
Thread checkForEmpty = new Thread(new Runnable() {
@Override
public void run() {
Cursor cursor = null;
mNewsUtil = new NewsUtil();
cursor = mNewsUtil.allNewsCursor(context);
if (null == cursor || cursor.getCount() == 0) {
startImmediateSync(context);
}
}
});
checkForEmpty.start();
}
public static void startImmediateSync(@NonNull final Context context) { | // Path: app/src/main/java/com/news/news24x7/sync/NewsFirebaseJobService.java
// public class NewsFirebaseJobService extends JobService {
//
// private AsyncTask<Void, Void, Void> mNewsFetchTask;
//
//
// @Override
// public boolean onStartJob(final JobParameters jobParameters) {
//
// mNewsFetchTask = new AsyncTask<Void, Void, Void>() {
// @Override
// protected Void doInBackground(Void... voids) {
// Context context = getApplicationContext();
// NewsSyncTask.syncNews(context);
// jobFinished(jobParameters, false);
// return null;
// }
//
// @Override
// protected void onPostExecute(Void aVoid) {
// jobFinished(jobParameters, false);
// }
// };
//
// mNewsFetchTask.execute();
// return true;
// }
//
//
// @Override
// public boolean onStopJob(JobParameters jobParameters) {
// if (mNewsFetchTask != null) {
// mNewsFetchTask.cancel(true);
// }
// return true;
// }
// }
//
// Path: app/src/main/java/com/news/news24x7/sync/NewsSyncIntentService.java
// public class NewsSyncIntentService extends IntentService {
//
// public NewsSyncIntentService() {
// super("NewsSyncIntentService");
// }
//
// @Override
// protected void onHandleIntent(Intent intent) {
// NewsSyncTask.syncNews(this);
// }
// }
// Path: app/src/main/java/com/news/news24x7/util/NewsSyncUtils.java
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.support.annotation.NonNull;
import com.news.news24x7.sync.NewsFirebaseJobService;
import com.news.news24x7.sync.NewsSyncIntentService;
import com.firebase.jobdispatcher.Constraint;
import com.firebase.jobdispatcher.Driver;
import com.firebase.jobdispatcher.FirebaseJobDispatcher;
import com.firebase.jobdispatcher.GooglePlayDriver;
import com.firebase.jobdispatcher.Job;
import com.firebase.jobdispatcher.Lifetime;
import com.firebase.jobdispatcher.Trigger;
import java.util.concurrent.TimeUnit;
package com.news.news24x7.util;
/**
* Created by Dell on 6/6/2017.
*/
public class NewsSyncUtils {
private static final int REMINDER_INTERVAL_MINUTES = 180;
private static final int REMINDER_INTERVAL_SECONDS = (int) (TimeUnit.MINUTES.toSeconds(REMINDER_INTERVAL_MINUTES));
private static final int SYNC_FLEXTIME_SECONDS = REMINDER_INTERVAL_SECONDS;
private static final String NEWS_SYNC_TAG = "news-sync";
static NewsUtil mNewsUtil;
private static boolean sInitialized;
static void scheduleFirebaseJobDispatcherSync(@NonNull final Context context) {
Driver driver = new GooglePlayDriver(context);
FirebaseJobDispatcher dispatcher = new FirebaseJobDispatcher(driver);
/* Create the Job to periodically sync Sunshine */
Job syncSunshineJob = dispatcher.newJobBuilder()
.setService(NewsFirebaseJobService.class)
.setTag(NEWS_SYNC_TAG)
.setConstraints(Constraint.ON_ANY_NETWORK)
.setLifetime(Lifetime.FOREVER)
.setRecurring(true)
.setTrigger(Trigger.executionWindow(
REMINDER_INTERVAL_SECONDS,
REMINDER_INTERVAL_SECONDS + SYNC_FLEXTIME_SECONDS))
.setReplaceCurrent(true)
.build();
dispatcher.schedule(syncSunshineJob);
}
synchronized public static void initialize(@NonNull final Context context) {
if (sInitialized) return;
sInitialized = true;
scheduleFirebaseJobDispatcherSync(context);
Thread checkForEmpty = new Thread(new Runnable() {
@Override
public void run() {
Cursor cursor = null;
mNewsUtil = new NewsUtil();
cursor = mNewsUtil.allNewsCursor(context);
if (null == cursor || cursor.getCount() == 0) {
startImmediateSync(context);
}
}
});
checkForEmpty.start();
}
public static void startImmediateSync(@NonNull final Context context) { | Intent intentToSyncImmediately = new Intent(context, NewsSyncIntentService.class); |
chanjarster/artemis-disruptor-miaosha | jms-server/src/main/java/me/chanjar/jms/server/dataloader/ItemDataStartupLoader.java | // Path: jms-server/src/main/java/me/chanjar/jms/server/memdb/Item.java
// public class Item implements Serializable {
//
// private static final long serialVersionUID = -873268150277605569L;
// /**
// * ID
// */
// private final Long id;
//
// /**
// * 库存
// */
// private int amount;
//
// public Item(Long id, int amount) {
// this.id = id;
// this.amount = amount;
// }
//
// public Long getId() {
// return id;
// }
//
// public int getAmount() {
// return amount;
// }
//
// public void setAmount(int amount) {
// this.amount = amount;
// }
//
// /**
// * 减库存,如果库存不足,则扣减失败
// *
// * @return
// */
// public boolean decreaseAmount() {
//
// if (!hasRemaining()) {
// return false;
// }
// amount--;
// return true;
//
// }
//
// /**
// * 是否还有库存
// *
// * @return
// */
// public boolean hasRemaining() {
// return amount > 0;
// }
//
// @Override
// public String toString() {
// return new ToStringBuilder(this)
// .append("id", id)
// .append("amount", amount)
// .toString();
// }
//
// }
//
// Path: jms-server/src/main/java/me/chanjar/jms/server/memdb/ItemRepository.java
// public interface ItemRepository {
//
// void put(Item item);
//
// Item get(Long id);
//
// }
| import me.chanjar.jms.server.memdb.Item;
import me.chanjar.jms.server.memdb.ItemRepository;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.Ordered;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Component;
import java.util.List; | package me.chanjar.jms.server.dataloader;
/**
* 启动时,将数据库中的数据,加载到内存中
*/
@Component
public class ItemDataStartupLoader extends DataStartupLoader {
private static final Logger LOGGER = LoggerFactory.getLogger(ItemDataStartupLoader.class);
private JdbcTemplate jdbcTemplate;
| // Path: jms-server/src/main/java/me/chanjar/jms/server/memdb/Item.java
// public class Item implements Serializable {
//
// private static final long serialVersionUID = -873268150277605569L;
// /**
// * ID
// */
// private final Long id;
//
// /**
// * 库存
// */
// private int amount;
//
// public Item(Long id, int amount) {
// this.id = id;
// this.amount = amount;
// }
//
// public Long getId() {
// return id;
// }
//
// public int getAmount() {
// return amount;
// }
//
// public void setAmount(int amount) {
// this.amount = amount;
// }
//
// /**
// * 减库存,如果库存不足,则扣减失败
// *
// * @return
// */
// public boolean decreaseAmount() {
//
// if (!hasRemaining()) {
// return false;
// }
// amount--;
// return true;
//
// }
//
// /**
// * 是否还有库存
// *
// * @return
// */
// public boolean hasRemaining() {
// return amount > 0;
// }
//
// @Override
// public String toString() {
// return new ToStringBuilder(this)
// .append("id", id)
// .append("amount", amount)
// .toString();
// }
//
// }
//
// Path: jms-server/src/main/java/me/chanjar/jms/server/memdb/ItemRepository.java
// public interface ItemRepository {
//
// void put(Item item);
//
// Item get(Long id);
//
// }
// Path: jms-server/src/main/java/me/chanjar/jms/server/dataloader/ItemDataStartupLoader.java
import me.chanjar.jms.server.memdb.Item;
import me.chanjar.jms.server.memdb.ItemRepository;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.Ordered;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Component;
import java.util.List;
package me.chanjar.jms.server.dataloader;
/**
* 启动时,将数据库中的数据,加载到内存中
*/
@Component
public class ItemDataStartupLoader extends DataStartupLoader {
private static final Logger LOGGER = LoggerFactory.getLogger(ItemDataStartupLoader.class);
private JdbcTemplate jdbcTemplate;
| private ItemRepository itemRepository; |
chanjarster/artemis-disruptor-miaosha | jms-server/src/main/java/me/chanjar/jms/server/dataloader/ItemDataStartupLoader.java | // Path: jms-server/src/main/java/me/chanjar/jms/server/memdb/Item.java
// public class Item implements Serializable {
//
// private static final long serialVersionUID = -873268150277605569L;
// /**
// * ID
// */
// private final Long id;
//
// /**
// * 库存
// */
// private int amount;
//
// public Item(Long id, int amount) {
// this.id = id;
// this.amount = amount;
// }
//
// public Long getId() {
// return id;
// }
//
// public int getAmount() {
// return amount;
// }
//
// public void setAmount(int amount) {
// this.amount = amount;
// }
//
// /**
// * 减库存,如果库存不足,则扣减失败
// *
// * @return
// */
// public boolean decreaseAmount() {
//
// if (!hasRemaining()) {
// return false;
// }
// amount--;
// return true;
//
// }
//
// /**
// * 是否还有库存
// *
// * @return
// */
// public boolean hasRemaining() {
// return amount > 0;
// }
//
// @Override
// public String toString() {
// return new ToStringBuilder(this)
// .append("id", id)
// .append("amount", amount)
// .toString();
// }
//
// }
//
// Path: jms-server/src/main/java/me/chanjar/jms/server/memdb/ItemRepository.java
// public interface ItemRepository {
//
// void put(Item item);
//
// Item get(Long id);
//
// }
| import me.chanjar.jms.server.memdb.Item;
import me.chanjar.jms.server.memdb.ItemRepository;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.Ordered;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Component;
import java.util.List; | package me.chanjar.jms.server.dataloader;
/**
* 启动时,将数据库中的数据,加载到内存中
*/
@Component
public class ItemDataStartupLoader extends DataStartupLoader {
private static final Logger LOGGER = LoggerFactory.getLogger(ItemDataStartupLoader.class);
private JdbcTemplate jdbcTemplate;
private ItemRepository itemRepository;
@Override
protected void doLoad() { | // Path: jms-server/src/main/java/me/chanjar/jms/server/memdb/Item.java
// public class Item implements Serializable {
//
// private static final long serialVersionUID = -873268150277605569L;
// /**
// * ID
// */
// private final Long id;
//
// /**
// * 库存
// */
// private int amount;
//
// public Item(Long id, int amount) {
// this.id = id;
// this.amount = amount;
// }
//
// public Long getId() {
// return id;
// }
//
// public int getAmount() {
// return amount;
// }
//
// public void setAmount(int amount) {
// this.amount = amount;
// }
//
// /**
// * 减库存,如果库存不足,则扣减失败
// *
// * @return
// */
// public boolean decreaseAmount() {
//
// if (!hasRemaining()) {
// return false;
// }
// amount--;
// return true;
//
// }
//
// /**
// * 是否还有库存
// *
// * @return
// */
// public boolean hasRemaining() {
// return amount > 0;
// }
//
// @Override
// public String toString() {
// return new ToStringBuilder(this)
// .append("id", id)
// .append("amount", amount)
// .toString();
// }
//
// }
//
// Path: jms-server/src/main/java/me/chanjar/jms/server/memdb/ItemRepository.java
// public interface ItemRepository {
//
// void put(Item item);
//
// Item get(Long id);
//
// }
// Path: jms-server/src/main/java/me/chanjar/jms/server/dataloader/ItemDataStartupLoader.java
import me.chanjar.jms.server.memdb.Item;
import me.chanjar.jms.server.memdb.ItemRepository;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.Ordered;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Component;
import java.util.List;
package me.chanjar.jms.server.dataloader;
/**
* 启动时,将数据库中的数据,加载到内存中
*/
@Component
public class ItemDataStartupLoader extends DataStartupLoader {
private static final Logger LOGGER = LoggerFactory.getLogger(ItemDataStartupLoader.class);
private JdbcTemplate jdbcTemplate;
private ItemRepository itemRepository;
@Override
protected void doLoad() { | List<Item> items = jdbcTemplate.query("select id, amount from item", |
chanjarster/artemis-disruptor-miaosha | jms-server/src/main/java/me/chanjar/jms/server/RequestDtoListener.java | // Path: jms-base/src/main/java/me/chanjar/jms/base/utils/MessageConvertUtils.java
// public abstract class MessageConvertUtils {
//
// private MessageConvertUtils() {
// // singleton
// }
//
// /**
// * 把对象转换成{@link Message}
// *
// * @param jmsTemplate
// * @param session
// * @param payload
// * @return
// * @throws JMSException
// */
// public static Message toMessage(JmsTemplate jmsTemplate, Session session, Object payload) throws JMSException {
// return toMessage(jmsTemplate.getMessageConverter(), session, payload);
// }
//
// /**
// * 把对象转换成{@link Message}
// *
// * @param messageConverter
// * @param session
// * @param payload
// * @return
// * @throws JMSException
// */
// public static Message toMessage(MessageConverter messageConverter, Session session, Object payload)
// throws JMSException {
// return messageConverter.toMessage(payload, session);
// }
//
// /**
// * 把{@link Message}转换成对象
// *
// * @param jmsTemplate
// * @param message
// * @param <T>
// * @return
// * @throws JMSException
// */
// public static <T> T fromMessage(JmsTemplate jmsTemplate, Message message) throws JMSException {
// return fromMessage(jmsTemplate.getMessageConverter(), message);
// }
//
// /**
// * 把{@link Message}转换成对象
// *
// * @param messageConverter
// * @param message
// * @param <T>
// * @return
// * @throws JMSException
// */
// public static <T> T fromMessage(MessageConverter messageConverter, Message message) throws JMSException {
// return (T) messageConverter.fromMessage(message);
// }
//
// }
//
// Path: jms-msg/src/main/java/me/chanjar/jms/msg/RequestDto.java
// public class RequestDto extends MessageDto {
//
// private static final long serialVersionUID = 5515305970509119810L;
// /**
// * 商品ID
// */
// private final Long itemId;
//
// /**
// * 用户ID
// */
// private final String userId;
//
// public RequestDto(Long itemId, String userId) {
// super();
// this.itemId = itemId;
// this.userId = userId;
// }
//
// public Long getItemId() {
// return itemId;
// }
//
// public String getUserId() {
// return userId;
// }
//
// @Override
// public boolean equals(Object o) {
// if (this == o) return true;
// if (o == null || getClass() != o.getClass()) return false;
//
// RequestDto that = (RequestDto) o;
//
// if (itemId != null ? !itemId.equals(that.itemId) : that.itemId != null) return false;
// return userId != null ? userId.equals(that.userId) : that.userId == null;
// }
//
// @Override
// public int hashCode() {
// int result = itemId != null ? itemId.hashCode() : 0;
// result = 31 * result + (userId != null ? userId.hashCode() : 0);
// return result;
// }
//
// @Override
// public String toString() {
// return new ToStringBuilder(this)
// .append("id", id)
// .append("itemId", itemId)
// .append("userId", userId)
// .toString();
// }
// }
//
// Path: jms-server/src/main/java/me/chanjar/jms/server/request/RequestDtoEventProducer.java
// public class RequestDtoEventProducer {
//
// private static final EventTranslatorOneArg<RequestDtoEvent, RequestDto> TRANSLATOR =
// (event, sequence, requestDto) -> event.setRequestDto(requestDto);
//
// private final RingBuffer<RequestDtoEvent> ringBuffer;
//
// public RequestDtoEventProducer(RingBuffer<RequestDtoEvent> ringBuffer) {
// this.ringBuffer = ringBuffer;
// }
//
// public void onData(RequestDto requestDto) {
// ringBuffer.publishEvent(TRANSLATOR, requestDto);
// }
//
// }
| import me.chanjar.jms.base.utils.MessageConvertUtils;
import me.chanjar.jms.msg.RequestDto;
import me.chanjar.jms.server.request.RequestDtoEventProducer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.jms.support.converter.MessageConverter;
import org.springframework.jms.support.converter.SimpleMessageConverter;
import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.MessageListener;
import javax.jms.ObjectMessage; | package me.chanjar.jms.server;
public class RequestDtoListener implements MessageListener {
private static final Logger LOGGER = LoggerFactory.getLogger(RequestDtoListener.class);
| // Path: jms-base/src/main/java/me/chanjar/jms/base/utils/MessageConvertUtils.java
// public abstract class MessageConvertUtils {
//
// private MessageConvertUtils() {
// // singleton
// }
//
// /**
// * 把对象转换成{@link Message}
// *
// * @param jmsTemplate
// * @param session
// * @param payload
// * @return
// * @throws JMSException
// */
// public static Message toMessage(JmsTemplate jmsTemplate, Session session, Object payload) throws JMSException {
// return toMessage(jmsTemplate.getMessageConverter(), session, payload);
// }
//
// /**
// * 把对象转换成{@link Message}
// *
// * @param messageConverter
// * @param session
// * @param payload
// * @return
// * @throws JMSException
// */
// public static Message toMessage(MessageConverter messageConverter, Session session, Object payload)
// throws JMSException {
// return messageConverter.toMessage(payload, session);
// }
//
// /**
// * 把{@link Message}转换成对象
// *
// * @param jmsTemplate
// * @param message
// * @param <T>
// * @return
// * @throws JMSException
// */
// public static <T> T fromMessage(JmsTemplate jmsTemplate, Message message) throws JMSException {
// return fromMessage(jmsTemplate.getMessageConverter(), message);
// }
//
// /**
// * 把{@link Message}转换成对象
// *
// * @param messageConverter
// * @param message
// * @param <T>
// * @return
// * @throws JMSException
// */
// public static <T> T fromMessage(MessageConverter messageConverter, Message message) throws JMSException {
// return (T) messageConverter.fromMessage(message);
// }
//
// }
//
// Path: jms-msg/src/main/java/me/chanjar/jms/msg/RequestDto.java
// public class RequestDto extends MessageDto {
//
// private static final long serialVersionUID = 5515305970509119810L;
// /**
// * 商品ID
// */
// private final Long itemId;
//
// /**
// * 用户ID
// */
// private final String userId;
//
// public RequestDto(Long itemId, String userId) {
// super();
// this.itemId = itemId;
// this.userId = userId;
// }
//
// public Long getItemId() {
// return itemId;
// }
//
// public String getUserId() {
// return userId;
// }
//
// @Override
// public boolean equals(Object o) {
// if (this == o) return true;
// if (o == null || getClass() != o.getClass()) return false;
//
// RequestDto that = (RequestDto) o;
//
// if (itemId != null ? !itemId.equals(that.itemId) : that.itemId != null) return false;
// return userId != null ? userId.equals(that.userId) : that.userId == null;
// }
//
// @Override
// public int hashCode() {
// int result = itemId != null ? itemId.hashCode() : 0;
// result = 31 * result + (userId != null ? userId.hashCode() : 0);
// return result;
// }
//
// @Override
// public String toString() {
// return new ToStringBuilder(this)
// .append("id", id)
// .append("itemId", itemId)
// .append("userId", userId)
// .toString();
// }
// }
//
// Path: jms-server/src/main/java/me/chanjar/jms/server/request/RequestDtoEventProducer.java
// public class RequestDtoEventProducer {
//
// private static final EventTranslatorOneArg<RequestDtoEvent, RequestDto> TRANSLATOR =
// (event, sequence, requestDto) -> event.setRequestDto(requestDto);
//
// private final RingBuffer<RequestDtoEvent> ringBuffer;
//
// public RequestDtoEventProducer(RingBuffer<RequestDtoEvent> ringBuffer) {
// this.ringBuffer = ringBuffer;
// }
//
// public void onData(RequestDto requestDto) {
// ringBuffer.publishEvent(TRANSLATOR, requestDto);
// }
//
// }
// Path: jms-server/src/main/java/me/chanjar/jms/server/RequestDtoListener.java
import me.chanjar.jms.base.utils.MessageConvertUtils;
import me.chanjar.jms.msg.RequestDto;
import me.chanjar.jms.server.request.RequestDtoEventProducer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.jms.support.converter.MessageConverter;
import org.springframework.jms.support.converter.SimpleMessageConverter;
import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.MessageListener;
import javax.jms.ObjectMessage;
package me.chanjar.jms.server;
public class RequestDtoListener implements MessageListener {
private static final Logger LOGGER = LoggerFactory.getLogger(RequestDtoListener.class);
| private RequestDtoEventProducer requestDtoEventProducer; |
chanjarster/artemis-disruptor-miaosha | jms-server/src/main/java/me/chanjar/jms/server/RequestDtoListener.java | // Path: jms-base/src/main/java/me/chanjar/jms/base/utils/MessageConvertUtils.java
// public abstract class MessageConvertUtils {
//
// private MessageConvertUtils() {
// // singleton
// }
//
// /**
// * 把对象转换成{@link Message}
// *
// * @param jmsTemplate
// * @param session
// * @param payload
// * @return
// * @throws JMSException
// */
// public static Message toMessage(JmsTemplate jmsTemplate, Session session, Object payload) throws JMSException {
// return toMessage(jmsTemplate.getMessageConverter(), session, payload);
// }
//
// /**
// * 把对象转换成{@link Message}
// *
// * @param messageConverter
// * @param session
// * @param payload
// * @return
// * @throws JMSException
// */
// public static Message toMessage(MessageConverter messageConverter, Session session, Object payload)
// throws JMSException {
// return messageConverter.toMessage(payload, session);
// }
//
// /**
// * 把{@link Message}转换成对象
// *
// * @param jmsTemplate
// * @param message
// * @param <T>
// * @return
// * @throws JMSException
// */
// public static <T> T fromMessage(JmsTemplate jmsTemplate, Message message) throws JMSException {
// return fromMessage(jmsTemplate.getMessageConverter(), message);
// }
//
// /**
// * 把{@link Message}转换成对象
// *
// * @param messageConverter
// * @param message
// * @param <T>
// * @return
// * @throws JMSException
// */
// public static <T> T fromMessage(MessageConverter messageConverter, Message message) throws JMSException {
// return (T) messageConverter.fromMessage(message);
// }
//
// }
//
// Path: jms-msg/src/main/java/me/chanjar/jms/msg/RequestDto.java
// public class RequestDto extends MessageDto {
//
// private static final long serialVersionUID = 5515305970509119810L;
// /**
// * 商品ID
// */
// private final Long itemId;
//
// /**
// * 用户ID
// */
// private final String userId;
//
// public RequestDto(Long itemId, String userId) {
// super();
// this.itemId = itemId;
// this.userId = userId;
// }
//
// public Long getItemId() {
// return itemId;
// }
//
// public String getUserId() {
// return userId;
// }
//
// @Override
// public boolean equals(Object o) {
// if (this == o) return true;
// if (o == null || getClass() != o.getClass()) return false;
//
// RequestDto that = (RequestDto) o;
//
// if (itemId != null ? !itemId.equals(that.itemId) : that.itemId != null) return false;
// return userId != null ? userId.equals(that.userId) : that.userId == null;
// }
//
// @Override
// public int hashCode() {
// int result = itemId != null ? itemId.hashCode() : 0;
// result = 31 * result + (userId != null ? userId.hashCode() : 0);
// return result;
// }
//
// @Override
// public String toString() {
// return new ToStringBuilder(this)
// .append("id", id)
// .append("itemId", itemId)
// .append("userId", userId)
// .toString();
// }
// }
//
// Path: jms-server/src/main/java/me/chanjar/jms/server/request/RequestDtoEventProducer.java
// public class RequestDtoEventProducer {
//
// private static final EventTranslatorOneArg<RequestDtoEvent, RequestDto> TRANSLATOR =
// (event, sequence, requestDto) -> event.setRequestDto(requestDto);
//
// private final RingBuffer<RequestDtoEvent> ringBuffer;
//
// public RequestDtoEventProducer(RingBuffer<RequestDtoEvent> ringBuffer) {
// this.ringBuffer = ringBuffer;
// }
//
// public void onData(RequestDto requestDto) {
// ringBuffer.publishEvent(TRANSLATOR, requestDto);
// }
//
// }
| import me.chanjar.jms.base.utils.MessageConvertUtils;
import me.chanjar.jms.msg.RequestDto;
import me.chanjar.jms.server.request.RequestDtoEventProducer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.jms.support.converter.MessageConverter;
import org.springframework.jms.support.converter.SimpleMessageConverter;
import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.MessageListener;
import javax.jms.ObjectMessage; | package me.chanjar.jms.server;
public class RequestDtoListener implements MessageListener {
private static final Logger LOGGER = LoggerFactory.getLogger(RequestDtoListener.class);
private RequestDtoEventProducer requestDtoEventProducer;
private MessageConverter messageConverter = new SimpleMessageConverter();
@Override
public void onMessage(Message message) {
if (!(message instanceof ObjectMessage)) {
LOGGER.error("Not ObjectMessage but actually {}", message.getClass().getSimpleName());
return;
}
try { | // Path: jms-base/src/main/java/me/chanjar/jms/base/utils/MessageConvertUtils.java
// public abstract class MessageConvertUtils {
//
// private MessageConvertUtils() {
// // singleton
// }
//
// /**
// * 把对象转换成{@link Message}
// *
// * @param jmsTemplate
// * @param session
// * @param payload
// * @return
// * @throws JMSException
// */
// public static Message toMessage(JmsTemplate jmsTemplate, Session session, Object payload) throws JMSException {
// return toMessage(jmsTemplate.getMessageConverter(), session, payload);
// }
//
// /**
// * 把对象转换成{@link Message}
// *
// * @param messageConverter
// * @param session
// * @param payload
// * @return
// * @throws JMSException
// */
// public static Message toMessage(MessageConverter messageConverter, Session session, Object payload)
// throws JMSException {
// return messageConverter.toMessage(payload, session);
// }
//
// /**
// * 把{@link Message}转换成对象
// *
// * @param jmsTemplate
// * @param message
// * @param <T>
// * @return
// * @throws JMSException
// */
// public static <T> T fromMessage(JmsTemplate jmsTemplate, Message message) throws JMSException {
// return fromMessage(jmsTemplate.getMessageConverter(), message);
// }
//
// /**
// * 把{@link Message}转换成对象
// *
// * @param messageConverter
// * @param message
// * @param <T>
// * @return
// * @throws JMSException
// */
// public static <T> T fromMessage(MessageConverter messageConverter, Message message) throws JMSException {
// return (T) messageConverter.fromMessage(message);
// }
//
// }
//
// Path: jms-msg/src/main/java/me/chanjar/jms/msg/RequestDto.java
// public class RequestDto extends MessageDto {
//
// private static final long serialVersionUID = 5515305970509119810L;
// /**
// * 商品ID
// */
// private final Long itemId;
//
// /**
// * 用户ID
// */
// private final String userId;
//
// public RequestDto(Long itemId, String userId) {
// super();
// this.itemId = itemId;
// this.userId = userId;
// }
//
// public Long getItemId() {
// return itemId;
// }
//
// public String getUserId() {
// return userId;
// }
//
// @Override
// public boolean equals(Object o) {
// if (this == o) return true;
// if (o == null || getClass() != o.getClass()) return false;
//
// RequestDto that = (RequestDto) o;
//
// if (itemId != null ? !itemId.equals(that.itemId) : that.itemId != null) return false;
// return userId != null ? userId.equals(that.userId) : that.userId == null;
// }
//
// @Override
// public int hashCode() {
// int result = itemId != null ? itemId.hashCode() : 0;
// result = 31 * result + (userId != null ? userId.hashCode() : 0);
// return result;
// }
//
// @Override
// public String toString() {
// return new ToStringBuilder(this)
// .append("id", id)
// .append("itemId", itemId)
// .append("userId", userId)
// .toString();
// }
// }
//
// Path: jms-server/src/main/java/me/chanjar/jms/server/request/RequestDtoEventProducer.java
// public class RequestDtoEventProducer {
//
// private static final EventTranslatorOneArg<RequestDtoEvent, RequestDto> TRANSLATOR =
// (event, sequence, requestDto) -> event.setRequestDto(requestDto);
//
// private final RingBuffer<RequestDtoEvent> ringBuffer;
//
// public RequestDtoEventProducer(RingBuffer<RequestDtoEvent> ringBuffer) {
// this.ringBuffer = ringBuffer;
// }
//
// public void onData(RequestDto requestDto) {
// ringBuffer.publishEvent(TRANSLATOR, requestDto);
// }
//
// }
// Path: jms-server/src/main/java/me/chanjar/jms/server/RequestDtoListener.java
import me.chanjar.jms.base.utils.MessageConvertUtils;
import me.chanjar.jms.msg.RequestDto;
import me.chanjar.jms.server.request.RequestDtoEventProducer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.jms.support.converter.MessageConverter;
import org.springframework.jms.support.converter.SimpleMessageConverter;
import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.MessageListener;
import javax.jms.ObjectMessage;
package me.chanjar.jms.server;
public class RequestDtoListener implements MessageListener {
private static final Logger LOGGER = LoggerFactory.getLogger(RequestDtoListener.class);
private RequestDtoEventProducer requestDtoEventProducer;
private MessageConverter messageConverter = new SimpleMessageConverter();
@Override
public void onMessage(Message message) {
if (!(message instanceof ObjectMessage)) {
LOGGER.error("Not ObjectMessage but actually {}", message.getClass().getSimpleName());
return;
}
try { | RequestDto requestDto = MessageConvertUtils.fromMessage(messageConverter, message); |
chanjarster/artemis-disruptor-miaosha | jms-server/src/main/java/me/chanjar/jms/server/RequestDtoListener.java | // Path: jms-base/src/main/java/me/chanjar/jms/base/utils/MessageConvertUtils.java
// public abstract class MessageConvertUtils {
//
// private MessageConvertUtils() {
// // singleton
// }
//
// /**
// * 把对象转换成{@link Message}
// *
// * @param jmsTemplate
// * @param session
// * @param payload
// * @return
// * @throws JMSException
// */
// public static Message toMessage(JmsTemplate jmsTemplate, Session session, Object payload) throws JMSException {
// return toMessage(jmsTemplate.getMessageConverter(), session, payload);
// }
//
// /**
// * 把对象转换成{@link Message}
// *
// * @param messageConverter
// * @param session
// * @param payload
// * @return
// * @throws JMSException
// */
// public static Message toMessage(MessageConverter messageConverter, Session session, Object payload)
// throws JMSException {
// return messageConverter.toMessage(payload, session);
// }
//
// /**
// * 把{@link Message}转换成对象
// *
// * @param jmsTemplate
// * @param message
// * @param <T>
// * @return
// * @throws JMSException
// */
// public static <T> T fromMessage(JmsTemplate jmsTemplate, Message message) throws JMSException {
// return fromMessage(jmsTemplate.getMessageConverter(), message);
// }
//
// /**
// * 把{@link Message}转换成对象
// *
// * @param messageConverter
// * @param message
// * @param <T>
// * @return
// * @throws JMSException
// */
// public static <T> T fromMessage(MessageConverter messageConverter, Message message) throws JMSException {
// return (T) messageConverter.fromMessage(message);
// }
//
// }
//
// Path: jms-msg/src/main/java/me/chanjar/jms/msg/RequestDto.java
// public class RequestDto extends MessageDto {
//
// private static final long serialVersionUID = 5515305970509119810L;
// /**
// * 商品ID
// */
// private final Long itemId;
//
// /**
// * 用户ID
// */
// private final String userId;
//
// public RequestDto(Long itemId, String userId) {
// super();
// this.itemId = itemId;
// this.userId = userId;
// }
//
// public Long getItemId() {
// return itemId;
// }
//
// public String getUserId() {
// return userId;
// }
//
// @Override
// public boolean equals(Object o) {
// if (this == o) return true;
// if (o == null || getClass() != o.getClass()) return false;
//
// RequestDto that = (RequestDto) o;
//
// if (itemId != null ? !itemId.equals(that.itemId) : that.itemId != null) return false;
// return userId != null ? userId.equals(that.userId) : that.userId == null;
// }
//
// @Override
// public int hashCode() {
// int result = itemId != null ? itemId.hashCode() : 0;
// result = 31 * result + (userId != null ? userId.hashCode() : 0);
// return result;
// }
//
// @Override
// public String toString() {
// return new ToStringBuilder(this)
// .append("id", id)
// .append("itemId", itemId)
// .append("userId", userId)
// .toString();
// }
// }
//
// Path: jms-server/src/main/java/me/chanjar/jms/server/request/RequestDtoEventProducer.java
// public class RequestDtoEventProducer {
//
// private static final EventTranslatorOneArg<RequestDtoEvent, RequestDto> TRANSLATOR =
// (event, sequence, requestDto) -> event.setRequestDto(requestDto);
//
// private final RingBuffer<RequestDtoEvent> ringBuffer;
//
// public RequestDtoEventProducer(RingBuffer<RequestDtoEvent> ringBuffer) {
// this.ringBuffer = ringBuffer;
// }
//
// public void onData(RequestDto requestDto) {
// ringBuffer.publishEvent(TRANSLATOR, requestDto);
// }
//
// }
| import me.chanjar.jms.base.utils.MessageConvertUtils;
import me.chanjar.jms.msg.RequestDto;
import me.chanjar.jms.server.request.RequestDtoEventProducer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.jms.support.converter.MessageConverter;
import org.springframework.jms.support.converter.SimpleMessageConverter;
import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.MessageListener;
import javax.jms.ObjectMessage; | package me.chanjar.jms.server;
public class RequestDtoListener implements MessageListener {
private static final Logger LOGGER = LoggerFactory.getLogger(RequestDtoListener.class);
private RequestDtoEventProducer requestDtoEventProducer;
private MessageConverter messageConverter = new SimpleMessageConverter();
@Override
public void onMessage(Message message) {
if (!(message instanceof ObjectMessage)) {
LOGGER.error("Not ObjectMessage but actually {}", message.getClass().getSimpleName());
return;
}
try { | // Path: jms-base/src/main/java/me/chanjar/jms/base/utils/MessageConvertUtils.java
// public abstract class MessageConvertUtils {
//
// private MessageConvertUtils() {
// // singleton
// }
//
// /**
// * 把对象转换成{@link Message}
// *
// * @param jmsTemplate
// * @param session
// * @param payload
// * @return
// * @throws JMSException
// */
// public static Message toMessage(JmsTemplate jmsTemplate, Session session, Object payload) throws JMSException {
// return toMessage(jmsTemplate.getMessageConverter(), session, payload);
// }
//
// /**
// * 把对象转换成{@link Message}
// *
// * @param messageConverter
// * @param session
// * @param payload
// * @return
// * @throws JMSException
// */
// public static Message toMessage(MessageConverter messageConverter, Session session, Object payload)
// throws JMSException {
// return messageConverter.toMessage(payload, session);
// }
//
// /**
// * 把{@link Message}转换成对象
// *
// * @param jmsTemplate
// * @param message
// * @param <T>
// * @return
// * @throws JMSException
// */
// public static <T> T fromMessage(JmsTemplate jmsTemplate, Message message) throws JMSException {
// return fromMessage(jmsTemplate.getMessageConverter(), message);
// }
//
// /**
// * 把{@link Message}转换成对象
// *
// * @param messageConverter
// * @param message
// * @param <T>
// * @return
// * @throws JMSException
// */
// public static <T> T fromMessage(MessageConverter messageConverter, Message message) throws JMSException {
// return (T) messageConverter.fromMessage(message);
// }
//
// }
//
// Path: jms-msg/src/main/java/me/chanjar/jms/msg/RequestDto.java
// public class RequestDto extends MessageDto {
//
// private static final long serialVersionUID = 5515305970509119810L;
// /**
// * 商品ID
// */
// private final Long itemId;
//
// /**
// * 用户ID
// */
// private final String userId;
//
// public RequestDto(Long itemId, String userId) {
// super();
// this.itemId = itemId;
// this.userId = userId;
// }
//
// public Long getItemId() {
// return itemId;
// }
//
// public String getUserId() {
// return userId;
// }
//
// @Override
// public boolean equals(Object o) {
// if (this == o) return true;
// if (o == null || getClass() != o.getClass()) return false;
//
// RequestDto that = (RequestDto) o;
//
// if (itemId != null ? !itemId.equals(that.itemId) : that.itemId != null) return false;
// return userId != null ? userId.equals(that.userId) : that.userId == null;
// }
//
// @Override
// public int hashCode() {
// int result = itemId != null ? itemId.hashCode() : 0;
// result = 31 * result + (userId != null ? userId.hashCode() : 0);
// return result;
// }
//
// @Override
// public String toString() {
// return new ToStringBuilder(this)
// .append("id", id)
// .append("itemId", itemId)
// .append("userId", userId)
// .toString();
// }
// }
//
// Path: jms-server/src/main/java/me/chanjar/jms/server/request/RequestDtoEventProducer.java
// public class RequestDtoEventProducer {
//
// private static final EventTranslatorOneArg<RequestDtoEvent, RequestDto> TRANSLATOR =
// (event, sequence, requestDto) -> event.setRequestDto(requestDto);
//
// private final RingBuffer<RequestDtoEvent> ringBuffer;
//
// public RequestDtoEventProducer(RingBuffer<RequestDtoEvent> ringBuffer) {
// this.ringBuffer = ringBuffer;
// }
//
// public void onData(RequestDto requestDto) {
// ringBuffer.publishEvent(TRANSLATOR, requestDto);
// }
//
// }
// Path: jms-server/src/main/java/me/chanjar/jms/server/RequestDtoListener.java
import me.chanjar.jms.base.utils.MessageConvertUtils;
import me.chanjar.jms.msg.RequestDto;
import me.chanjar.jms.server.request.RequestDtoEventProducer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.jms.support.converter.MessageConverter;
import org.springframework.jms.support.converter.SimpleMessageConverter;
import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.MessageListener;
import javax.jms.ObjectMessage;
package me.chanjar.jms.server;
public class RequestDtoListener implements MessageListener {
private static final Logger LOGGER = LoggerFactory.getLogger(RequestDtoListener.class);
private RequestDtoEventProducer requestDtoEventProducer;
private MessageConverter messageConverter = new SimpleMessageConverter();
@Override
public void onMessage(Message message) {
if (!(message instanceof ObjectMessage)) {
LOGGER.error("Not ObjectMessage but actually {}", message.getClass().getSimpleName());
return;
}
try { | RequestDto requestDto = MessageConvertUtils.fromMessage(messageConverter, message); |
chanjarster/artemis-disruptor-miaosha | jms-server/src/main/java/me/chanjar/jms/server/request/RequestDtoEventJmsOutputer.java | // Path: jms-base/src/main/java/me/chanjar/jms/base/sender/JmsMessageSender.java
// public interface JmsMessageSender {
//
// /**
// * 发送Jms消息
// *
// * @param payload 消息主体
// * @throws JMSException
// */
// void sendMessage(MessageDto payload) throws JMSException;
//
// }
//
// Path: jms-msg/src/main/java/me/chanjar/jms/msg/ResponseDto.java
// public class ResponseDto extends MessageDto {
//
// private static final long serialVersionUID = -4690648814874030736L;
// /**
// * 关联的RequestDto的id
// */
// private final String requestId;
//
// /**
// * 错误消息
// */
// protected String errorMessage;
//
// /**
// * 是否成功处理请求
// */
// protected boolean success;
//
// public ResponseDto(String requestId) {
// super();
// this.requestId = requestId;
// }
//
// public String getRequestId() {
// return requestId;
// }
//
// public String getErrorMessage() {
// return errorMessage;
// }
//
// public void setErrorMessage(String errorMessage) {
// this.errorMessage = errorMessage;
// }
//
// public boolean isSuccess() {
// return success;
// }
//
// public void setSuccess(boolean success) {
// this.success = success;
// }
//
// @Override
// public boolean equals(Object o) {
// if (this == o) return true;
// if (o == null || getClass() != o.getClass()) return false;
//
// ResponseDto that = (ResponseDto) o;
//
// if (success != that.success) return false;
// if (requestId != null ? !requestId.equals(that.requestId) : that.requestId != null) return false;
// return errorMessage != null ? errorMessage.equals(that.errorMessage) : that.errorMessage == null;
// }
//
// @Override
// public int hashCode() {
// int result = requestId != null ? requestId.hashCode() : 0;
// result = 31 * result + (errorMessage != null ? errorMessage.hashCode() : 0);
// result = 31 * result + (success ? 1 : 0);
// return result;
// }
// }
| import com.lmax.disruptor.EventHandler;
import me.chanjar.jms.base.sender.JmsMessageSender;
import me.chanjar.jms.msg.ResponseDto;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory; | package me.chanjar.jms.server.request;
/**
* 将结果RequestDtoEvent的结果输出到jms的handler
*/
public class RequestDtoEventJmsOutputer implements EventHandler<RequestDtoEvent> {
private static final Logger LOGGER = LoggerFactory.getLogger(RequestDtoEventJmsOutputer.class);
| // Path: jms-base/src/main/java/me/chanjar/jms/base/sender/JmsMessageSender.java
// public interface JmsMessageSender {
//
// /**
// * 发送Jms消息
// *
// * @param payload 消息主体
// * @throws JMSException
// */
// void sendMessage(MessageDto payload) throws JMSException;
//
// }
//
// Path: jms-msg/src/main/java/me/chanjar/jms/msg/ResponseDto.java
// public class ResponseDto extends MessageDto {
//
// private static final long serialVersionUID = -4690648814874030736L;
// /**
// * 关联的RequestDto的id
// */
// private final String requestId;
//
// /**
// * 错误消息
// */
// protected String errorMessage;
//
// /**
// * 是否成功处理请求
// */
// protected boolean success;
//
// public ResponseDto(String requestId) {
// super();
// this.requestId = requestId;
// }
//
// public String getRequestId() {
// return requestId;
// }
//
// public String getErrorMessage() {
// return errorMessage;
// }
//
// public void setErrorMessage(String errorMessage) {
// this.errorMessage = errorMessage;
// }
//
// public boolean isSuccess() {
// return success;
// }
//
// public void setSuccess(boolean success) {
// this.success = success;
// }
//
// @Override
// public boolean equals(Object o) {
// if (this == o) return true;
// if (o == null || getClass() != o.getClass()) return false;
//
// ResponseDto that = (ResponseDto) o;
//
// if (success != that.success) return false;
// if (requestId != null ? !requestId.equals(that.requestId) : that.requestId != null) return false;
// return errorMessage != null ? errorMessage.equals(that.errorMessage) : that.errorMessage == null;
// }
//
// @Override
// public int hashCode() {
// int result = requestId != null ? requestId.hashCode() : 0;
// result = 31 * result + (errorMessage != null ? errorMessage.hashCode() : 0);
// result = 31 * result + (success ? 1 : 0);
// return result;
// }
// }
// Path: jms-server/src/main/java/me/chanjar/jms/server/request/RequestDtoEventJmsOutputer.java
import com.lmax.disruptor.EventHandler;
import me.chanjar.jms.base.sender.JmsMessageSender;
import me.chanjar.jms.msg.ResponseDto;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
package me.chanjar.jms.server.request;
/**
* 将结果RequestDtoEvent的结果输出到jms的handler
*/
public class RequestDtoEventJmsOutputer implements EventHandler<RequestDtoEvent> {
private static final Logger LOGGER = LoggerFactory.getLogger(RequestDtoEventJmsOutputer.class);
| private JmsMessageSender messageSender; |
chanjarster/artemis-disruptor-miaosha | jms-server/src/main/java/me/chanjar/jms/server/request/RequestDtoEventJmsOutputer.java | // Path: jms-base/src/main/java/me/chanjar/jms/base/sender/JmsMessageSender.java
// public interface JmsMessageSender {
//
// /**
// * 发送Jms消息
// *
// * @param payload 消息主体
// * @throws JMSException
// */
// void sendMessage(MessageDto payload) throws JMSException;
//
// }
//
// Path: jms-msg/src/main/java/me/chanjar/jms/msg/ResponseDto.java
// public class ResponseDto extends MessageDto {
//
// private static final long serialVersionUID = -4690648814874030736L;
// /**
// * 关联的RequestDto的id
// */
// private final String requestId;
//
// /**
// * 错误消息
// */
// protected String errorMessage;
//
// /**
// * 是否成功处理请求
// */
// protected boolean success;
//
// public ResponseDto(String requestId) {
// super();
// this.requestId = requestId;
// }
//
// public String getRequestId() {
// return requestId;
// }
//
// public String getErrorMessage() {
// return errorMessage;
// }
//
// public void setErrorMessage(String errorMessage) {
// this.errorMessage = errorMessage;
// }
//
// public boolean isSuccess() {
// return success;
// }
//
// public void setSuccess(boolean success) {
// this.success = success;
// }
//
// @Override
// public boolean equals(Object o) {
// if (this == o) return true;
// if (o == null || getClass() != o.getClass()) return false;
//
// ResponseDto that = (ResponseDto) o;
//
// if (success != that.success) return false;
// if (requestId != null ? !requestId.equals(that.requestId) : that.requestId != null) return false;
// return errorMessage != null ? errorMessage.equals(that.errorMessage) : that.errorMessage == null;
// }
//
// @Override
// public int hashCode() {
// int result = requestId != null ? requestId.hashCode() : 0;
// result = 31 * result + (errorMessage != null ? errorMessage.hashCode() : 0);
// result = 31 * result + (success ? 1 : 0);
// return result;
// }
// }
| import com.lmax.disruptor.EventHandler;
import me.chanjar.jms.base.sender.JmsMessageSender;
import me.chanjar.jms.msg.ResponseDto;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory; | package me.chanjar.jms.server.request;
/**
* 将结果RequestDtoEvent的结果输出到jms的handler
*/
public class RequestDtoEventJmsOutputer implements EventHandler<RequestDtoEvent> {
private static final Logger LOGGER = LoggerFactory.getLogger(RequestDtoEventJmsOutputer.class);
private JmsMessageSender messageSender;
@Override
public void onEvent(RequestDtoEvent event, long sequence, boolean endOfBatch) throws Exception {
| // Path: jms-base/src/main/java/me/chanjar/jms/base/sender/JmsMessageSender.java
// public interface JmsMessageSender {
//
// /**
// * 发送Jms消息
// *
// * @param payload 消息主体
// * @throws JMSException
// */
// void sendMessage(MessageDto payload) throws JMSException;
//
// }
//
// Path: jms-msg/src/main/java/me/chanjar/jms/msg/ResponseDto.java
// public class ResponseDto extends MessageDto {
//
// private static final long serialVersionUID = -4690648814874030736L;
// /**
// * 关联的RequestDto的id
// */
// private final String requestId;
//
// /**
// * 错误消息
// */
// protected String errorMessage;
//
// /**
// * 是否成功处理请求
// */
// protected boolean success;
//
// public ResponseDto(String requestId) {
// super();
// this.requestId = requestId;
// }
//
// public String getRequestId() {
// return requestId;
// }
//
// public String getErrorMessage() {
// return errorMessage;
// }
//
// public void setErrorMessage(String errorMessage) {
// this.errorMessage = errorMessage;
// }
//
// public boolean isSuccess() {
// return success;
// }
//
// public void setSuccess(boolean success) {
// this.success = success;
// }
//
// @Override
// public boolean equals(Object o) {
// if (this == o) return true;
// if (o == null || getClass() != o.getClass()) return false;
//
// ResponseDto that = (ResponseDto) o;
//
// if (success != that.success) return false;
// if (requestId != null ? !requestId.equals(that.requestId) : that.requestId != null) return false;
// return errorMessage != null ? errorMessage.equals(that.errorMessage) : that.errorMessage == null;
// }
//
// @Override
// public int hashCode() {
// int result = requestId != null ? requestId.hashCode() : 0;
// result = 31 * result + (errorMessage != null ? errorMessage.hashCode() : 0);
// result = 31 * result + (success ? 1 : 0);
// return result;
// }
// }
// Path: jms-server/src/main/java/me/chanjar/jms/server/request/RequestDtoEventJmsOutputer.java
import com.lmax.disruptor.EventHandler;
import me.chanjar.jms.base.sender.JmsMessageSender;
import me.chanjar.jms.msg.ResponseDto;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
package me.chanjar.jms.server.request;
/**
* 将结果RequestDtoEvent的结果输出到jms的handler
*/
public class RequestDtoEventJmsOutputer implements EventHandler<RequestDtoEvent> {
private static final Logger LOGGER = LoggerFactory.getLogger(RequestDtoEventJmsOutputer.class);
private JmsMessageSender messageSender;
@Override
public void onEvent(RequestDtoEvent event, long sequence, boolean endOfBatch) throws Exception {
| ResponseDto responseDto = event.getResponseDto(); |
chanjarster/artemis-disruptor-miaosha | jms-base/src/main/java/me/chanjar/jms/base/msg/MessageDto.java | // Path: jms-base/src/main/java/me/chanjar/jms/base/utils/StrongUuidGenerator.java
// public class StrongUuidGenerator {
//
// private StrongUuidGenerator() {
// // make singleton
// }
// // different ProcessEngines on the same classloader share one generator.
// private static TimeBasedGenerator timeBasedGenerator = Generators.timeBasedGenerator(EthernetAddress.fromInterface());
//
// public static String getNextId() {
// return timeBasedGenerator.generate().toString();
// }
//
// }
| import me.chanjar.jms.base.utils.StrongUuidGenerator;
import java.io.Serializable; | package me.chanjar.jms.base.msg;
public abstract class MessageDto implements Serializable {
private static final long serialVersionUID = 9003442515985424079L;
/**
* 应该保证全局唯一, 用uuid
*/
protected final String id;
public MessageDto() { | // Path: jms-base/src/main/java/me/chanjar/jms/base/utils/StrongUuidGenerator.java
// public class StrongUuidGenerator {
//
// private StrongUuidGenerator() {
// // make singleton
// }
// // different ProcessEngines on the same classloader share one generator.
// private static TimeBasedGenerator timeBasedGenerator = Generators.timeBasedGenerator(EthernetAddress.fromInterface());
//
// public static String getNextId() {
// return timeBasedGenerator.generate().toString();
// }
//
// }
// Path: jms-base/src/main/java/me/chanjar/jms/base/msg/MessageDto.java
import me.chanjar.jms.base.utils.StrongUuidGenerator;
import java.io.Serializable;
package me.chanjar.jms.base.msg;
public abstract class MessageDto implements Serializable {
private static final long serialVersionUID = 9003442515985424079L;
/**
* 应该保证全局唯一, 用uuid
*/
protected final String id;
public MessageDto() { | this.id = StrongUuidGenerator.getNextId(); |
chanjarster/artemis-disruptor-miaosha | jms-server/src/main/java/me/chanjar/jms/server/command/order/OrderInsertCommandBuffer.java | // Path: jms-server/src/main/java/me/chanjar/jms/server/command/infras/CommandBuffer.java
// public interface CommandBuffer<T extends Command> {
//
// /**
// * Buffer是否已经满了
// *
// * @return
// */
// boolean hasRemaining();
//
// /**
// * 放入Command
// *
// * @param command
// */
// void put(T command);
//
// /**
// * 清空缓存
// */
// void clear();
//
// /**
// * 获得{@link Command}
// *
// * @return
// */
// List<T> get();
//
// }
//
// Path: jms-server/src/main/java/me/chanjar/jms/server/command/infras/CommandBufferOverflowException.java
// public class CommandBufferOverflowException extends RuntimeException {
//
// private static final long serialVersionUID = -408555980971903979L;
//
// /**
// * Constructs an instance of this class.
// */
// public CommandBufferOverflowException() {
// // do nothing
// }
//
// }
| import me.chanjar.jms.server.command.infras.CommandBuffer;
import me.chanjar.jms.server.command.infras.CommandBufferOverflowException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.ArrayList;
import java.util.List; | package me.chanjar.jms.server.command.order;
public class OrderInsertCommandBuffer implements CommandBuffer<OrderInsertCommand> {
private static final Logger LOGGER = LoggerFactory.getLogger(OrderInsertCommandBuffer.class);
private final List<OrderInsertCommand> commandList;
private final int capacity;
public OrderInsertCommandBuffer(int capacity) {
this.capacity = capacity;
this.commandList = new ArrayList<>(capacity);
}
@Override
public boolean hasRemaining() {
return commandList.size() < this.capacity;
}
/**
* @param command
* @throws CommandBufferOverflowException
*/
@Override
public void put(OrderInsertCommand command) {
if (!hasRemaining()) { | // Path: jms-server/src/main/java/me/chanjar/jms/server/command/infras/CommandBuffer.java
// public interface CommandBuffer<T extends Command> {
//
// /**
// * Buffer是否已经满了
// *
// * @return
// */
// boolean hasRemaining();
//
// /**
// * 放入Command
// *
// * @param command
// */
// void put(T command);
//
// /**
// * 清空缓存
// */
// void clear();
//
// /**
// * 获得{@link Command}
// *
// * @return
// */
// List<T> get();
//
// }
//
// Path: jms-server/src/main/java/me/chanjar/jms/server/command/infras/CommandBufferOverflowException.java
// public class CommandBufferOverflowException extends RuntimeException {
//
// private static final long serialVersionUID = -408555980971903979L;
//
// /**
// * Constructs an instance of this class.
// */
// public CommandBufferOverflowException() {
// // do nothing
// }
//
// }
// Path: jms-server/src/main/java/me/chanjar/jms/server/command/order/OrderInsertCommandBuffer.java
import me.chanjar.jms.server.command.infras.CommandBuffer;
import me.chanjar.jms.server.command.infras.CommandBufferOverflowException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.ArrayList;
import java.util.List;
package me.chanjar.jms.server.command.order;
public class OrderInsertCommandBuffer implements CommandBuffer<OrderInsertCommand> {
private static final Logger LOGGER = LoggerFactory.getLogger(OrderInsertCommandBuffer.class);
private final List<OrderInsertCommand> commandList;
private final int capacity;
public OrderInsertCommandBuffer(int capacity) {
this.capacity = capacity;
this.commandList = new ArrayList<>(capacity);
}
@Override
public boolean hasRemaining() {
return commandList.size() < this.capacity;
}
/**
* @param command
* @throws CommandBufferOverflowException
*/
@Override
public void put(OrderInsertCommand command) {
if (!hasRemaining()) { | throw new CommandBufferOverflowException(); |
chanjarster/artemis-disruptor-miaosha | jms-server/src/main/java/me/chanjar/jms/server/command/infras/Command.java | // Path: jms-base/src/main/java/me/chanjar/jms/base/utils/StrongUuidGenerator.java
// public class StrongUuidGenerator {
//
// private StrongUuidGenerator() {
// // make singleton
// }
// // different ProcessEngines on the same classloader share one generator.
// private static TimeBasedGenerator timeBasedGenerator = Generators.timeBasedGenerator(EthernetAddress.fromInterface());
//
// public static String getNextId() {
// return timeBasedGenerator.generate().toString();
// }
//
// }
//
// Path: jms-msg/src/main/java/me/chanjar/jms/msg/RequestDto.java
// public class RequestDto extends MessageDto {
//
// private static final long serialVersionUID = 5515305970509119810L;
// /**
// * 商品ID
// */
// private final Long itemId;
//
// /**
// * 用户ID
// */
// private final String userId;
//
// public RequestDto(Long itemId, String userId) {
// super();
// this.itemId = itemId;
// this.userId = userId;
// }
//
// public Long getItemId() {
// return itemId;
// }
//
// public String getUserId() {
// return userId;
// }
//
// @Override
// public boolean equals(Object o) {
// if (this == o) return true;
// if (o == null || getClass() != o.getClass()) return false;
//
// RequestDto that = (RequestDto) o;
//
// if (itemId != null ? !itemId.equals(that.itemId) : that.itemId != null) return false;
// return userId != null ? userId.equals(that.userId) : that.userId == null;
// }
//
// @Override
// public int hashCode() {
// int result = itemId != null ? itemId.hashCode() : 0;
// result = 31 * result + (userId != null ? userId.hashCode() : 0);
// return result;
// }
//
// @Override
// public String toString() {
// return new ToStringBuilder(this)
// .append("id", id)
// .append("itemId", itemId)
// .append("userId", userId)
// .toString();
// }
// }
| import me.chanjar.jms.base.utils.StrongUuidGenerator;
import me.chanjar.jms.msg.RequestDto;
import java.io.Serializable; | package me.chanjar.jms.server.command.infras;
/**
* 数据库操作命令
*/
public abstract class Command implements Serializable {
private static final long serialVersionUID = -2463630580877588711L;
protected final String id;
protected final String requestId;
/**
* Command来源的requestId
*
* @param requestId
*/
public Command(String requestId) { | // Path: jms-base/src/main/java/me/chanjar/jms/base/utils/StrongUuidGenerator.java
// public class StrongUuidGenerator {
//
// private StrongUuidGenerator() {
// // make singleton
// }
// // different ProcessEngines on the same classloader share one generator.
// private static TimeBasedGenerator timeBasedGenerator = Generators.timeBasedGenerator(EthernetAddress.fromInterface());
//
// public static String getNextId() {
// return timeBasedGenerator.generate().toString();
// }
//
// }
//
// Path: jms-msg/src/main/java/me/chanjar/jms/msg/RequestDto.java
// public class RequestDto extends MessageDto {
//
// private static final long serialVersionUID = 5515305970509119810L;
// /**
// * 商品ID
// */
// private final Long itemId;
//
// /**
// * 用户ID
// */
// private final String userId;
//
// public RequestDto(Long itemId, String userId) {
// super();
// this.itemId = itemId;
// this.userId = userId;
// }
//
// public Long getItemId() {
// return itemId;
// }
//
// public String getUserId() {
// return userId;
// }
//
// @Override
// public boolean equals(Object o) {
// if (this == o) return true;
// if (o == null || getClass() != o.getClass()) return false;
//
// RequestDto that = (RequestDto) o;
//
// if (itemId != null ? !itemId.equals(that.itemId) : that.itemId != null) return false;
// return userId != null ? userId.equals(that.userId) : that.userId == null;
// }
//
// @Override
// public int hashCode() {
// int result = itemId != null ? itemId.hashCode() : 0;
// result = 31 * result + (userId != null ? userId.hashCode() : 0);
// return result;
// }
//
// @Override
// public String toString() {
// return new ToStringBuilder(this)
// .append("id", id)
// .append("itemId", itemId)
// .append("userId", userId)
// .toString();
// }
// }
// Path: jms-server/src/main/java/me/chanjar/jms/server/command/infras/Command.java
import me.chanjar.jms.base.utils.StrongUuidGenerator;
import me.chanjar.jms.msg.RequestDto;
import java.io.Serializable;
package me.chanjar.jms.server.command.infras;
/**
* 数据库操作命令
*/
public abstract class Command implements Serializable {
private static final long serialVersionUID = -2463630580877588711L;
protected final String id;
protected final String requestId;
/**
* Command来源的requestId
*
* @param requestId
*/
public Command(String requestId) { | this.id = StrongUuidGenerator.getNextId(); |
chanjarster/artemis-disruptor-miaosha | jms-client/src/main/java/me/chanjar/jms/client/command/ResponseJmsMessageListener.java | // Path: jms-base/src/main/java/me/chanjar/jms/base/utils/MessageConvertUtils.java
// public abstract class MessageConvertUtils {
//
// private MessageConvertUtils() {
// // singleton
// }
//
// /**
// * 把对象转换成{@link Message}
// *
// * @param jmsTemplate
// * @param session
// * @param payload
// * @return
// * @throws JMSException
// */
// public static Message toMessage(JmsTemplate jmsTemplate, Session session, Object payload) throws JMSException {
// return toMessage(jmsTemplate.getMessageConverter(), session, payload);
// }
//
// /**
// * 把对象转换成{@link Message}
// *
// * @param messageConverter
// * @param session
// * @param payload
// * @return
// * @throws JMSException
// */
// public static Message toMessage(MessageConverter messageConverter, Session session, Object payload)
// throws JMSException {
// return messageConverter.toMessage(payload, session);
// }
//
// /**
// * 把{@link Message}转换成对象
// *
// * @param jmsTemplate
// * @param message
// * @param <T>
// * @return
// * @throws JMSException
// */
// public static <T> T fromMessage(JmsTemplate jmsTemplate, Message message) throws JMSException {
// return fromMessage(jmsTemplate.getMessageConverter(), message);
// }
//
// /**
// * 把{@link Message}转换成对象
// *
// * @param messageConverter
// * @param message
// * @param <T>
// * @return
// * @throws JMSException
// */
// public static <T> T fromMessage(MessageConverter messageConverter, Message message) throws JMSException {
// return (T) messageConverter.fromMessage(message);
// }
//
// }
//
// Path: jms-msg/src/main/java/me/chanjar/jms/msg/ResponseDto.java
// public class ResponseDto extends MessageDto {
//
// private static final long serialVersionUID = -4690648814874030736L;
// /**
// * 关联的RequestDto的id
// */
// private final String requestId;
//
// /**
// * 错误消息
// */
// protected String errorMessage;
//
// /**
// * 是否成功处理请求
// */
// protected boolean success;
//
// public ResponseDto(String requestId) {
// super();
// this.requestId = requestId;
// }
//
// public String getRequestId() {
// return requestId;
// }
//
// public String getErrorMessage() {
// return errorMessage;
// }
//
// public void setErrorMessage(String errorMessage) {
// this.errorMessage = errorMessage;
// }
//
// public boolean isSuccess() {
// return success;
// }
//
// public void setSuccess(boolean success) {
// this.success = success;
// }
//
// @Override
// public boolean equals(Object o) {
// if (this == o) return true;
// if (o == null || getClass() != o.getClass()) return false;
//
// ResponseDto that = (ResponseDto) o;
//
// if (success != that.success) return false;
// if (requestId != null ? !requestId.equals(that.requestId) : that.requestId != null) return false;
// return errorMessage != null ? errorMessage.equals(that.errorMessage) : that.errorMessage == null;
// }
//
// @Override
// public int hashCode() {
// int result = requestId != null ? requestId.hashCode() : 0;
// result = 31 * result + (errorMessage != null ? errorMessage.hashCode() : 0);
// result = 31 * result + (success ? 1 : 0);
// return result;
// }
// }
| import me.chanjar.jms.base.utils.MessageConvertUtils;
import me.chanjar.jms.msg.ResponseDto;
import org.apache.commons.lang3.exception.ExceptionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.jms.support.converter.MessageConverter;
import org.springframework.jms.support.converter.SimpleMessageConverter;
import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.MessageListener; | package me.chanjar.jms.client.command;
public class ResponseJmsMessageListener implements MessageListener {
private static final Logger LOGGER = LoggerFactory.getLogger(ResponseJmsMessageListener.class);
private ResponseCache responseCache;
private MessageConverter messageConverter = new SimpleMessageConverter();
@Override
public void onMessage(Message message) {
try { | // Path: jms-base/src/main/java/me/chanjar/jms/base/utils/MessageConvertUtils.java
// public abstract class MessageConvertUtils {
//
// private MessageConvertUtils() {
// // singleton
// }
//
// /**
// * 把对象转换成{@link Message}
// *
// * @param jmsTemplate
// * @param session
// * @param payload
// * @return
// * @throws JMSException
// */
// public static Message toMessage(JmsTemplate jmsTemplate, Session session, Object payload) throws JMSException {
// return toMessage(jmsTemplate.getMessageConverter(), session, payload);
// }
//
// /**
// * 把对象转换成{@link Message}
// *
// * @param messageConverter
// * @param session
// * @param payload
// * @return
// * @throws JMSException
// */
// public static Message toMessage(MessageConverter messageConverter, Session session, Object payload)
// throws JMSException {
// return messageConverter.toMessage(payload, session);
// }
//
// /**
// * 把{@link Message}转换成对象
// *
// * @param jmsTemplate
// * @param message
// * @param <T>
// * @return
// * @throws JMSException
// */
// public static <T> T fromMessage(JmsTemplate jmsTemplate, Message message) throws JMSException {
// return fromMessage(jmsTemplate.getMessageConverter(), message);
// }
//
// /**
// * 把{@link Message}转换成对象
// *
// * @param messageConverter
// * @param message
// * @param <T>
// * @return
// * @throws JMSException
// */
// public static <T> T fromMessage(MessageConverter messageConverter, Message message) throws JMSException {
// return (T) messageConverter.fromMessage(message);
// }
//
// }
//
// Path: jms-msg/src/main/java/me/chanjar/jms/msg/ResponseDto.java
// public class ResponseDto extends MessageDto {
//
// private static final long serialVersionUID = -4690648814874030736L;
// /**
// * 关联的RequestDto的id
// */
// private final String requestId;
//
// /**
// * 错误消息
// */
// protected String errorMessage;
//
// /**
// * 是否成功处理请求
// */
// protected boolean success;
//
// public ResponseDto(String requestId) {
// super();
// this.requestId = requestId;
// }
//
// public String getRequestId() {
// return requestId;
// }
//
// public String getErrorMessage() {
// return errorMessage;
// }
//
// public void setErrorMessage(String errorMessage) {
// this.errorMessage = errorMessage;
// }
//
// public boolean isSuccess() {
// return success;
// }
//
// public void setSuccess(boolean success) {
// this.success = success;
// }
//
// @Override
// public boolean equals(Object o) {
// if (this == o) return true;
// if (o == null || getClass() != o.getClass()) return false;
//
// ResponseDto that = (ResponseDto) o;
//
// if (success != that.success) return false;
// if (requestId != null ? !requestId.equals(that.requestId) : that.requestId != null) return false;
// return errorMessage != null ? errorMessage.equals(that.errorMessage) : that.errorMessage == null;
// }
//
// @Override
// public int hashCode() {
// int result = requestId != null ? requestId.hashCode() : 0;
// result = 31 * result + (errorMessage != null ? errorMessage.hashCode() : 0);
// result = 31 * result + (success ? 1 : 0);
// return result;
// }
// }
// Path: jms-client/src/main/java/me/chanjar/jms/client/command/ResponseJmsMessageListener.java
import me.chanjar.jms.base.utils.MessageConvertUtils;
import me.chanjar.jms.msg.ResponseDto;
import org.apache.commons.lang3.exception.ExceptionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.jms.support.converter.MessageConverter;
import org.springframework.jms.support.converter.SimpleMessageConverter;
import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.MessageListener;
package me.chanjar.jms.client.command;
public class ResponseJmsMessageListener implements MessageListener {
private static final Logger LOGGER = LoggerFactory.getLogger(ResponseJmsMessageListener.class);
private ResponseCache responseCache;
private MessageConverter messageConverter = new SimpleMessageConverter();
@Override
public void onMessage(Message message) {
try { | ResponseDto responseDto = MessageConvertUtils.fromMessage(messageConverter, message); |
chanjarster/artemis-disruptor-miaosha | jms-client/src/main/java/me/chanjar/jms/client/command/ResponseJmsMessageListener.java | // Path: jms-base/src/main/java/me/chanjar/jms/base/utils/MessageConvertUtils.java
// public abstract class MessageConvertUtils {
//
// private MessageConvertUtils() {
// // singleton
// }
//
// /**
// * 把对象转换成{@link Message}
// *
// * @param jmsTemplate
// * @param session
// * @param payload
// * @return
// * @throws JMSException
// */
// public static Message toMessage(JmsTemplate jmsTemplate, Session session, Object payload) throws JMSException {
// return toMessage(jmsTemplate.getMessageConverter(), session, payload);
// }
//
// /**
// * 把对象转换成{@link Message}
// *
// * @param messageConverter
// * @param session
// * @param payload
// * @return
// * @throws JMSException
// */
// public static Message toMessage(MessageConverter messageConverter, Session session, Object payload)
// throws JMSException {
// return messageConverter.toMessage(payload, session);
// }
//
// /**
// * 把{@link Message}转换成对象
// *
// * @param jmsTemplate
// * @param message
// * @param <T>
// * @return
// * @throws JMSException
// */
// public static <T> T fromMessage(JmsTemplate jmsTemplate, Message message) throws JMSException {
// return fromMessage(jmsTemplate.getMessageConverter(), message);
// }
//
// /**
// * 把{@link Message}转换成对象
// *
// * @param messageConverter
// * @param message
// * @param <T>
// * @return
// * @throws JMSException
// */
// public static <T> T fromMessage(MessageConverter messageConverter, Message message) throws JMSException {
// return (T) messageConverter.fromMessage(message);
// }
//
// }
//
// Path: jms-msg/src/main/java/me/chanjar/jms/msg/ResponseDto.java
// public class ResponseDto extends MessageDto {
//
// private static final long serialVersionUID = -4690648814874030736L;
// /**
// * 关联的RequestDto的id
// */
// private final String requestId;
//
// /**
// * 错误消息
// */
// protected String errorMessage;
//
// /**
// * 是否成功处理请求
// */
// protected boolean success;
//
// public ResponseDto(String requestId) {
// super();
// this.requestId = requestId;
// }
//
// public String getRequestId() {
// return requestId;
// }
//
// public String getErrorMessage() {
// return errorMessage;
// }
//
// public void setErrorMessage(String errorMessage) {
// this.errorMessage = errorMessage;
// }
//
// public boolean isSuccess() {
// return success;
// }
//
// public void setSuccess(boolean success) {
// this.success = success;
// }
//
// @Override
// public boolean equals(Object o) {
// if (this == o) return true;
// if (o == null || getClass() != o.getClass()) return false;
//
// ResponseDto that = (ResponseDto) o;
//
// if (success != that.success) return false;
// if (requestId != null ? !requestId.equals(that.requestId) : that.requestId != null) return false;
// return errorMessage != null ? errorMessage.equals(that.errorMessage) : that.errorMessage == null;
// }
//
// @Override
// public int hashCode() {
// int result = requestId != null ? requestId.hashCode() : 0;
// result = 31 * result + (errorMessage != null ? errorMessage.hashCode() : 0);
// result = 31 * result + (success ? 1 : 0);
// return result;
// }
// }
| import me.chanjar.jms.base.utils.MessageConvertUtils;
import me.chanjar.jms.msg.ResponseDto;
import org.apache.commons.lang3.exception.ExceptionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.jms.support.converter.MessageConverter;
import org.springframework.jms.support.converter.SimpleMessageConverter;
import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.MessageListener; | package me.chanjar.jms.client.command;
public class ResponseJmsMessageListener implements MessageListener {
private static final Logger LOGGER = LoggerFactory.getLogger(ResponseJmsMessageListener.class);
private ResponseCache responseCache;
private MessageConverter messageConverter = new SimpleMessageConverter();
@Override
public void onMessage(Message message) {
try { | // Path: jms-base/src/main/java/me/chanjar/jms/base/utils/MessageConvertUtils.java
// public abstract class MessageConvertUtils {
//
// private MessageConvertUtils() {
// // singleton
// }
//
// /**
// * 把对象转换成{@link Message}
// *
// * @param jmsTemplate
// * @param session
// * @param payload
// * @return
// * @throws JMSException
// */
// public static Message toMessage(JmsTemplate jmsTemplate, Session session, Object payload) throws JMSException {
// return toMessage(jmsTemplate.getMessageConverter(), session, payload);
// }
//
// /**
// * 把对象转换成{@link Message}
// *
// * @param messageConverter
// * @param session
// * @param payload
// * @return
// * @throws JMSException
// */
// public static Message toMessage(MessageConverter messageConverter, Session session, Object payload)
// throws JMSException {
// return messageConverter.toMessage(payload, session);
// }
//
// /**
// * 把{@link Message}转换成对象
// *
// * @param jmsTemplate
// * @param message
// * @param <T>
// * @return
// * @throws JMSException
// */
// public static <T> T fromMessage(JmsTemplate jmsTemplate, Message message) throws JMSException {
// return fromMessage(jmsTemplate.getMessageConverter(), message);
// }
//
// /**
// * 把{@link Message}转换成对象
// *
// * @param messageConverter
// * @param message
// * @param <T>
// * @return
// * @throws JMSException
// */
// public static <T> T fromMessage(MessageConverter messageConverter, Message message) throws JMSException {
// return (T) messageConverter.fromMessage(message);
// }
//
// }
//
// Path: jms-msg/src/main/java/me/chanjar/jms/msg/ResponseDto.java
// public class ResponseDto extends MessageDto {
//
// private static final long serialVersionUID = -4690648814874030736L;
// /**
// * 关联的RequestDto的id
// */
// private final String requestId;
//
// /**
// * 错误消息
// */
// protected String errorMessage;
//
// /**
// * 是否成功处理请求
// */
// protected boolean success;
//
// public ResponseDto(String requestId) {
// super();
// this.requestId = requestId;
// }
//
// public String getRequestId() {
// return requestId;
// }
//
// public String getErrorMessage() {
// return errorMessage;
// }
//
// public void setErrorMessage(String errorMessage) {
// this.errorMessage = errorMessage;
// }
//
// public boolean isSuccess() {
// return success;
// }
//
// public void setSuccess(boolean success) {
// this.success = success;
// }
//
// @Override
// public boolean equals(Object o) {
// if (this == o) return true;
// if (o == null || getClass() != o.getClass()) return false;
//
// ResponseDto that = (ResponseDto) o;
//
// if (success != that.success) return false;
// if (requestId != null ? !requestId.equals(that.requestId) : that.requestId != null) return false;
// return errorMessage != null ? errorMessage.equals(that.errorMessage) : that.errorMessage == null;
// }
//
// @Override
// public int hashCode() {
// int result = requestId != null ? requestId.hashCode() : 0;
// result = 31 * result + (errorMessage != null ? errorMessage.hashCode() : 0);
// result = 31 * result + (success ? 1 : 0);
// return result;
// }
// }
// Path: jms-client/src/main/java/me/chanjar/jms/client/command/ResponseJmsMessageListener.java
import me.chanjar.jms.base.utils.MessageConvertUtils;
import me.chanjar.jms.msg.ResponseDto;
import org.apache.commons.lang3.exception.ExceptionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.jms.support.converter.MessageConverter;
import org.springframework.jms.support.converter.SimpleMessageConverter;
import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.MessageListener;
package me.chanjar.jms.client.command;
public class ResponseJmsMessageListener implements MessageListener {
private static final Logger LOGGER = LoggerFactory.getLogger(ResponseJmsMessageListener.class);
private ResponseCache responseCache;
private MessageConverter messageConverter = new SimpleMessageConverter();
@Override
public void onMessage(Message message) {
try { | ResponseDto responseDto = MessageConvertUtils.fromMessage(messageConverter, message); |
chanjarster/artemis-disruptor-miaosha | jms-base/src/main/java/me/chanjar/jms/base/sender/disruptor/DisruptorJmsMessageSenderFactory.java | // Path: jms-base/src/main/java/me/chanjar/jms/base/utils/DupMessageDetectStrategy.java
// public interface DupMessageDetectStrategy {
//
// void setId(Message message, Object payload) throws JMSException;
// }
| import com.lmax.disruptor.dsl.Disruptor;
import me.chanjar.jms.base.utils.DupMessageDetectStrategy;
import javax.jms.JMSException;
import javax.jms.MessageProducer;
import javax.jms.Session;
import java.util.concurrent.Executors; | package me.chanjar.jms.base.sender.disruptor;
public abstract class DisruptorJmsMessageSenderFactory {
private DisruptorJmsMessageSenderFactory() {
}
/**
* 得到返回的结果后, 必须执行 {@link DisruptorJmsMessageSender#getDisruptor()}.start() 才可以使用
*
* @param session
* @param messageProducer
* @param dupMessageDetectStrategy
* @param ringBufferSize 必须是2的次方
* @return
* @throws JMSException
*/
public static DisruptorJmsMessageSender create(
Session session,
MessageProducer messageProducer, | // Path: jms-base/src/main/java/me/chanjar/jms/base/utils/DupMessageDetectStrategy.java
// public interface DupMessageDetectStrategy {
//
// void setId(Message message, Object payload) throws JMSException;
// }
// Path: jms-base/src/main/java/me/chanjar/jms/base/sender/disruptor/DisruptorJmsMessageSenderFactory.java
import com.lmax.disruptor.dsl.Disruptor;
import me.chanjar.jms.base.utils.DupMessageDetectStrategy;
import javax.jms.JMSException;
import javax.jms.MessageProducer;
import javax.jms.Session;
import java.util.concurrent.Executors;
package me.chanjar.jms.base.sender.disruptor;
public abstract class DisruptorJmsMessageSenderFactory {
private DisruptorJmsMessageSenderFactory() {
}
/**
* 得到返回的结果后, 必须执行 {@link DisruptorJmsMessageSender#getDisruptor()}.start() 才可以使用
*
* @param session
* @param messageProducer
* @param dupMessageDetectStrategy
* @param ringBufferSize 必须是2的次方
* @return
* @throws JMSException
*/
public static DisruptorJmsMessageSender create(
Session session,
MessageProducer messageProducer, | DupMessageDetectStrategy dupMessageDetectStrategy, |
chanjarster/artemis-disruptor-miaosha | jms-base/src/main/java/me/chanjar/jms/base/sender/simple/SimpleJmsMessageSender.java | // Path: jms-base/src/main/java/me/chanjar/jms/base/sender/JmsMessageSender.java
// public interface JmsMessageSender {
//
// /**
// * 发送Jms消息
// *
// * @param payload 消息主体
// * @throws JMSException
// */
// void sendMessage(MessageDto payload) throws JMSException;
//
// }
//
// Path: jms-base/src/main/java/me/chanjar/jms/base/utils/ArtemisMessageDtoDupMessageDetectStrategy.java
// public class ArtemisMessageDtoDupMessageDetectStrategy implements DupMessageDetectStrategy {
//
// private static final String HDR_DUPLICATE_DETECTION_ID =
// org.apache.activemq.artemis.api.core.Message.HDR_DUPLICATE_DETECTION_ID.toString();
//
// @Override
// public void setId(Message message, Object payload) throws JMSException {
// message.setStringProperty(HDR_DUPLICATE_DETECTION_ID, ((MessageDto) payload).getId());
// }
//
// }
//
// Path: jms-base/src/main/java/me/chanjar/jms/base/msg/MessageDto.java
// public abstract class MessageDto implements Serializable {
//
// private static final long serialVersionUID = 9003442515985424079L;
// /**
// * 应该保证全局唯一, 用uuid
// */
// protected final String id;
//
// public MessageDto() {
// this.id = StrongUuidGenerator.getNextId();
// }
//
// public String getId() {
// return id;
// }
//
// }
//
// Path: jms-base/src/main/java/me/chanjar/jms/base/utils/DupMessageDetectStrategy.java
// public interface DupMessageDetectStrategy {
//
// void setId(Message message, Object payload) throws JMSException;
// }
//
// Path: jms-base/src/main/java/me/chanjar/jms/base/utils/MessageConvertUtils.java
// public abstract class MessageConvertUtils {
//
// private MessageConvertUtils() {
// // singleton
// }
//
// /**
// * 把对象转换成{@link Message}
// *
// * @param jmsTemplate
// * @param session
// * @param payload
// * @return
// * @throws JMSException
// */
// public static Message toMessage(JmsTemplate jmsTemplate, Session session, Object payload) throws JMSException {
// return toMessage(jmsTemplate.getMessageConverter(), session, payload);
// }
//
// /**
// * 把对象转换成{@link Message}
// *
// * @param messageConverter
// * @param session
// * @param payload
// * @return
// * @throws JMSException
// */
// public static Message toMessage(MessageConverter messageConverter, Session session, Object payload)
// throws JMSException {
// return messageConverter.toMessage(payload, session);
// }
//
// /**
// * 把{@link Message}转换成对象
// *
// * @param jmsTemplate
// * @param message
// * @param <T>
// * @return
// * @throws JMSException
// */
// public static <T> T fromMessage(JmsTemplate jmsTemplate, Message message) throws JMSException {
// return fromMessage(jmsTemplate.getMessageConverter(), message);
// }
//
// /**
// * 把{@link Message}转换成对象
// *
// * @param messageConverter
// * @param message
// * @param <T>
// * @return
// * @throws JMSException
// */
// public static <T> T fromMessage(MessageConverter messageConverter, Message message) throws JMSException {
// return (T) messageConverter.fromMessage(message);
// }
//
// }
| import me.chanjar.jms.base.sender.JmsMessageSender;
import me.chanjar.jms.base.utils.ArtemisMessageDtoDupMessageDetectStrategy;
import me.chanjar.jms.base.msg.MessageDto;
import me.chanjar.jms.base.utils.DupMessageDetectStrategy;
import me.chanjar.jms.base.utils.MessageConvertUtils;
import org.springframework.jms.support.converter.MessageConverter;
import org.springframework.jms.support.converter.SimpleMessageConverter;
import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.MessageProducer;
import javax.jms.Session; | package me.chanjar.jms.base.sender.simple;
public class SimpleJmsMessageSender implements JmsMessageSender {
private Session session;
private MessageProducer messageProducer;
private MessageConverter messageConverter = new SimpleMessageConverter();
| // Path: jms-base/src/main/java/me/chanjar/jms/base/sender/JmsMessageSender.java
// public interface JmsMessageSender {
//
// /**
// * 发送Jms消息
// *
// * @param payload 消息主体
// * @throws JMSException
// */
// void sendMessage(MessageDto payload) throws JMSException;
//
// }
//
// Path: jms-base/src/main/java/me/chanjar/jms/base/utils/ArtemisMessageDtoDupMessageDetectStrategy.java
// public class ArtemisMessageDtoDupMessageDetectStrategy implements DupMessageDetectStrategy {
//
// private static final String HDR_DUPLICATE_DETECTION_ID =
// org.apache.activemq.artemis.api.core.Message.HDR_DUPLICATE_DETECTION_ID.toString();
//
// @Override
// public void setId(Message message, Object payload) throws JMSException {
// message.setStringProperty(HDR_DUPLICATE_DETECTION_ID, ((MessageDto) payload).getId());
// }
//
// }
//
// Path: jms-base/src/main/java/me/chanjar/jms/base/msg/MessageDto.java
// public abstract class MessageDto implements Serializable {
//
// private static final long serialVersionUID = 9003442515985424079L;
// /**
// * 应该保证全局唯一, 用uuid
// */
// protected final String id;
//
// public MessageDto() {
// this.id = StrongUuidGenerator.getNextId();
// }
//
// public String getId() {
// return id;
// }
//
// }
//
// Path: jms-base/src/main/java/me/chanjar/jms/base/utils/DupMessageDetectStrategy.java
// public interface DupMessageDetectStrategy {
//
// void setId(Message message, Object payload) throws JMSException;
// }
//
// Path: jms-base/src/main/java/me/chanjar/jms/base/utils/MessageConvertUtils.java
// public abstract class MessageConvertUtils {
//
// private MessageConvertUtils() {
// // singleton
// }
//
// /**
// * 把对象转换成{@link Message}
// *
// * @param jmsTemplate
// * @param session
// * @param payload
// * @return
// * @throws JMSException
// */
// public static Message toMessage(JmsTemplate jmsTemplate, Session session, Object payload) throws JMSException {
// return toMessage(jmsTemplate.getMessageConverter(), session, payload);
// }
//
// /**
// * 把对象转换成{@link Message}
// *
// * @param messageConverter
// * @param session
// * @param payload
// * @return
// * @throws JMSException
// */
// public static Message toMessage(MessageConverter messageConverter, Session session, Object payload)
// throws JMSException {
// return messageConverter.toMessage(payload, session);
// }
//
// /**
// * 把{@link Message}转换成对象
// *
// * @param jmsTemplate
// * @param message
// * @param <T>
// * @return
// * @throws JMSException
// */
// public static <T> T fromMessage(JmsTemplate jmsTemplate, Message message) throws JMSException {
// return fromMessage(jmsTemplate.getMessageConverter(), message);
// }
//
// /**
// * 把{@link Message}转换成对象
// *
// * @param messageConverter
// * @param message
// * @param <T>
// * @return
// * @throws JMSException
// */
// public static <T> T fromMessage(MessageConverter messageConverter, Message message) throws JMSException {
// return (T) messageConverter.fromMessage(message);
// }
//
// }
// Path: jms-base/src/main/java/me/chanjar/jms/base/sender/simple/SimpleJmsMessageSender.java
import me.chanjar.jms.base.sender.JmsMessageSender;
import me.chanjar.jms.base.utils.ArtemisMessageDtoDupMessageDetectStrategy;
import me.chanjar.jms.base.msg.MessageDto;
import me.chanjar.jms.base.utils.DupMessageDetectStrategy;
import me.chanjar.jms.base.utils.MessageConvertUtils;
import org.springframework.jms.support.converter.MessageConverter;
import org.springframework.jms.support.converter.SimpleMessageConverter;
import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.MessageProducer;
import javax.jms.Session;
package me.chanjar.jms.base.sender.simple;
public class SimpleJmsMessageSender implements JmsMessageSender {
private Session session;
private MessageProducer messageProducer;
private MessageConverter messageConverter = new SimpleMessageConverter();
| private DupMessageDetectStrategy dupMessageDetectStrategy = new ArtemisMessageDtoDupMessageDetectStrategy(); |
chanjarster/artemis-disruptor-miaosha | jms-base/src/main/java/me/chanjar/jms/base/sender/simple/SimpleJmsMessageSender.java | // Path: jms-base/src/main/java/me/chanjar/jms/base/sender/JmsMessageSender.java
// public interface JmsMessageSender {
//
// /**
// * 发送Jms消息
// *
// * @param payload 消息主体
// * @throws JMSException
// */
// void sendMessage(MessageDto payload) throws JMSException;
//
// }
//
// Path: jms-base/src/main/java/me/chanjar/jms/base/utils/ArtemisMessageDtoDupMessageDetectStrategy.java
// public class ArtemisMessageDtoDupMessageDetectStrategy implements DupMessageDetectStrategy {
//
// private static final String HDR_DUPLICATE_DETECTION_ID =
// org.apache.activemq.artemis.api.core.Message.HDR_DUPLICATE_DETECTION_ID.toString();
//
// @Override
// public void setId(Message message, Object payload) throws JMSException {
// message.setStringProperty(HDR_DUPLICATE_DETECTION_ID, ((MessageDto) payload).getId());
// }
//
// }
//
// Path: jms-base/src/main/java/me/chanjar/jms/base/msg/MessageDto.java
// public abstract class MessageDto implements Serializable {
//
// private static final long serialVersionUID = 9003442515985424079L;
// /**
// * 应该保证全局唯一, 用uuid
// */
// protected final String id;
//
// public MessageDto() {
// this.id = StrongUuidGenerator.getNextId();
// }
//
// public String getId() {
// return id;
// }
//
// }
//
// Path: jms-base/src/main/java/me/chanjar/jms/base/utils/DupMessageDetectStrategy.java
// public interface DupMessageDetectStrategy {
//
// void setId(Message message, Object payload) throws JMSException;
// }
//
// Path: jms-base/src/main/java/me/chanjar/jms/base/utils/MessageConvertUtils.java
// public abstract class MessageConvertUtils {
//
// private MessageConvertUtils() {
// // singleton
// }
//
// /**
// * 把对象转换成{@link Message}
// *
// * @param jmsTemplate
// * @param session
// * @param payload
// * @return
// * @throws JMSException
// */
// public static Message toMessage(JmsTemplate jmsTemplate, Session session, Object payload) throws JMSException {
// return toMessage(jmsTemplate.getMessageConverter(), session, payload);
// }
//
// /**
// * 把对象转换成{@link Message}
// *
// * @param messageConverter
// * @param session
// * @param payload
// * @return
// * @throws JMSException
// */
// public static Message toMessage(MessageConverter messageConverter, Session session, Object payload)
// throws JMSException {
// return messageConverter.toMessage(payload, session);
// }
//
// /**
// * 把{@link Message}转换成对象
// *
// * @param jmsTemplate
// * @param message
// * @param <T>
// * @return
// * @throws JMSException
// */
// public static <T> T fromMessage(JmsTemplate jmsTemplate, Message message) throws JMSException {
// return fromMessage(jmsTemplate.getMessageConverter(), message);
// }
//
// /**
// * 把{@link Message}转换成对象
// *
// * @param messageConverter
// * @param message
// * @param <T>
// * @return
// * @throws JMSException
// */
// public static <T> T fromMessage(MessageConverter messageConverter, Message message) throws JMSException {
// return (T) messageConverter.fromMessage(message);
// }
//
// }
| import me.chanjar.jms.base.sender.JmsMessageSender;
import me.chanjar.jms.base.utils.ArtemisMessageDtoDupMessageDetectStrategy;
import me.chanjar.jms.base.msg.MessageDto;
import me.chanjar.jms.base.utils.DupMessageDetectStrategy;
import me.chanjar.jms.base.utils.MessageConvertUtils;
import org.springframework.jms.support.converter.MessageConverter;
import org.springframework.jms.support.converter.SimpleMessageConverter;
import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.MessageProducer;
import javax.jms.Session; | package me.chanjar.jms.base.sender.simple;
public class SimpleJmsMessageSender implements JmsMessageSender {
private Session session;
private MessageProducer messageProducer;
private MessageConverter messageConverter = new SimpleMessageConverter();
| // Path: jms-base/src/main/java/me/chanjar/jms/base/sender/JmsMessageSender.java
// public interface JmsMessageSender {
//
// /**
// * 发送Jms消息
// *
// * @param payload 消息主体
// * @throws JMSException
// */
// void sendMessage(MessageDto payload) throws JMSException;
//
// }
//
// Path: jms-base/src/main/java/me/chanjar/jms/base/utils/ArtemisMessageDtoDupMessageDetectStrategy.java
// public class ArtemisMessageDtoDupMessageDetectStrategy implements DupMessageDetectStrategy {
//
// private static final String HDR_DUPLICATE_DETECTION_ID =
// org.apache.activemq.artemis.api.core.Message.HDR_DUPLICATE_DETECTION_ID.toString();
//
// @Override
// public void setId(Message message, Object payload) throws JMSException {
// message.setStringProperty(HDR_DUPLICATE_DETECTION_ID, ((MessageDto) payload).getId());
// }
//
// }
//
// Path: jms-base/src/main/java/me/chanjar/jms/base/msg/MessageDto.java
// public abstract class MessageDto implements Serializable {
//
// private static final long serialVersionUID = 9003442515985424079L;
// /**
// * 应该保证全局唯一, 用uuid
// */
// protected final String id;
//
// public MessageDto() {
// this.id = StrongUuidGenerator.getNextId();
// }
//
// public String getId() {
// return id;
// }
//
// }
//
// Path: jms-base/src/main/java/me/chanjar/jms/base/utils/DupMessageDetectStrategy.java
// public interface DupMessageDetectStrategy {
//
// void setId(Message message, Object payload) throws JMSException;
// }
//
// Path: jms-base/src/main/java/me/chanjar/jms/base/utils/MessageConvertUtils.java
// public abstract class MessageConvertUtils {
//
// private MessageConvertUtils() {
// // singleton
// }
//
// /**
// * 把对象转换成{@link Message}
// *
// * @param jmsTemplate
// * @param session
// * @param payload
// * @return
// * @throws JMSException
// */
// public static Message toMessage(JmsTemplate jmsTemplate, Session session, Object payload) throws JMSException {
// return toMessage(jmsTemplate.getMessageConverter(), session, payload);
// }
//
// /**
// * 把对象转换成{@link Message}
// *
// * @param messageConverter
// * @param session
// * @param payload
// * @return
// * @throws JMSException
// */
// public static Message toMessage(MessageConverter messageConverter, Session session, Object payload)
// throws JMSException {
// return messageConverter.toMessage(payload, session);
// }
//
// /**
// * 把{@link Message}转换成对象
// *
// * @param jmsTemplate
// * @param message
// * @param <T>
// * @return
// * @throws JMSException
// */
// public static <T> T fromMessage(JmsTemplate jmsTemplate, Message message) throws JMSException {
// return fromMessage(jmsTemplate.getMessageConverter(), message);
// }
//
// /**
// * 把{@link Message}转换成对象
// *
// * @param messageConverter
// * @param message
// * @param <T>
// * @return
// * @throws JMSException
// */
// public static <T> T fromMessage(MessageConverter messageConverter, Message message) throws JMSException {
// return (T) messageConverter.fromMessage(message);
// }
//
// }
// Path: jms-base/src/main/java/me/chanjar/jms/base/sender/simple/SimpleJmsMessageSender.java
import me.chanjar.jms.base.sender.JmsMessageSender;
import me.chanjar.jms.base.utils.ArtemisMessageDtoDupMessageDetectStrategy;
import me.chanjar.jms.base.msg.MessageDto;
import me.chanjar.jms.base.utils.DupMessageDetectStrategy;
import me.chanjar.jms.base.utils.MessageConvertUtils;
import org.springframework.jms.support.converter.MessageConverter;
import org.springframework.jms.support.converter.SimpleMessageConverter;
import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.MessageProducer;
import javax.jms.Session;
package me.chanjar.jms.base.sender.simple;
public class SimpleJmsMessageSender implements JmsMessageSender {
private Session session;
private MessageProducer messageProducer;
private MessageConverter messageConverter = new SimpleMessageConverter();
| private DupMessageDetectStrategy dupMessageDetectStrategy = new ArtemisMessageDtoDupMessageDetectStrategy(); |
chanjarster/artemis-disruptor-miaosha | jms-base/src/main/java/me/chanjar/jms/base/sender/simple/SimpleJmsMessageSender.java | // Path: jms-base/src/main/java/me/chanjar/jms/base/sender/JmsMessageSender.java
// public interface JmsMessageSender {
//
// /**
// * 发送Jms消息
// *
// * @param payload 消息主体
// * @throws JMSException
// */
// void sendMessage(MessageDto payload) throws JMSException;
//
// }
//
// Path: jms-base/src/main/java/me/chanjar/jms/base/utils/ArtemisMessageDtoDupMessageDetectStrategy.java
// public class ArtemisMessageDtoDupMessageDetectStrategy implements DupMessageDetectStrategy {
//
// private static final String HDR_DUPLICATE_DETECTION_ID =
// org.apache.activemq.artemis.api.core.Message.HDR_DUPLICATE_DETECTION_ID.toString();
//
// @Override
// public void setId(Message message, Object payload) throws JMSException {
// message.setStringProperty(HDR_DUPLICATE_DETECTION_ID, ((MessageDto) payload).getId());
// }
//
// }
//
// Path: jms-base/src/main/java/me/chanjar/jms/base/msg/MessageDto.java
// public abstract class MessageDto implements Serializable {
//
// private static final long serialVersionUID = 9003442515985424079L;
// /**
// * 应该保证全局唯一, 用uuid
// */
// protected final String id;
//
// public MessageDto() {
// this.id = StrongUuidGenerator.getNextId();
// }
//
// public String getId() {
// return id;
// }
//
// }
//
// Path: jms-base/src/main/java/me/chanjar/jms/base/utils/DupMessageDetectStrategy.java
// public interface DupMessageDetectStrategy {
//
// void setId(Message message, Object payload) throws JMSException;
// }
//
// Path: jms-base/src/main/java/me/chanjar/jms/base/utils/MessageConvertUtils.java
// public abstract class MessageConvertUtils {
//
// private MessageConvertUtils() {
// // singleton
// }
//
// /**
// * 把对象转换成{@link Message}
// *
// * @param jmsTemplate
// * @param session
// * @param payload
// * @return
// * @throws JMSException
// */
// public static Message toMessage(JmsTemplate jmsTemplate, Session session, Object payload) throws JMSException {
// return toMessage(jmsTemplate.getMessageConverter(), session, payload);
// }
//
// /**
// * 把对象转换成{@link Message}
// *
// * @param messageConverter
// * @param session
// * @param payload
// * @return
// * @throws JMSException
// */
// public static Message toMessage(MessageConverter messageConverter, Session session, Object payload)
// throws JMSException {
// return messageConverter.toMessage(payload, session);
// }
//
// /**
// * 把{@link Message}转换成对象
// *
// * @param jmsTemplate
// * @param message
// * @param <T>
// * @return
// * @throws JMSException
// */
// public static <T> T fromMessage(JmsTemplate jmsTemplate, Message message) throws JMSException {
// return fromMessage(jmsTemplate.getMessageConverter(), message);
// }
//
// /**
// * 把{@link Message}转换成对象
// *
// * @param messageConverter
// * @param message
// * @param <T>
// * @return
// * @throws JMSException
// */
// public static <T> T fromMessage(MessageConverter messageConverter, Message message) throws JMSException {
// return (T) messageConverter.fromMessage(message);
// }
//
// }
| import me.chanjar.jms.base.sender.JmsMessageSender;
import me.chanjar.jms.base.utils.ArtemisMessageDtoDupMessageDetectStrategy;
import me.chanjar.jms.base.msg.MessageDto;
import me.chanjar.jms.base.utils.DupMessageDetectStrategy;
import me.chanjar.jms.base.utils.MessageConvertUtils;
import org.springframework.jms.support.converter.MessageConverter;
import org.springframework.jms.support.converter.SimpleMessageConverter;
import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.MessageProducer;
import javax.jms.Session; | package me.chanjar.jms.base.sender.simple;
public class SimpleJmsMessageSender implements JmsMessageSender {
private Session session;
private MessageProducer messageProducer;
private MessageConverter messageConverter = new SimpleMessageConverter();
private DupMessageDetectStrategy dupMessageDetectStrategy = new ArtemisMessageDtoDupMessageDetectStrategy();
@Override | // Path: jms-base/src/main/java/me/chanjar/jms/base/sender/JmsMessageSender.java
// public interface JmsMessageSender {
//
// /**
// * 发送Jms消息
// *
// * @param payload 消息主体
// * @throws JMSException
// */
// void sendMessage(MessageDto payload) throws JMSException;
//
// }
//
// Path: jms-base/src/main/java/me/chanjar/jms/base/utils/ArtemisMessageDtoDupMessageDetectStrategy.java
// public class ArtemisMessageDtoDupMessageDetectStrategy implements DupMessageDetectStrategy {
//
// private static final String HDR_DUPLICATE_DETECTION_ID =
// org.apache.activemq.artemis.api.core.Message.HDR_DUPLICATE_DETECTION_ID.toString();
//
// @Override
// public void setId(Message message, Object payload) throws JMSException {
// message.setStringProperty(HDR_DUPLICATE_DETECTION_ID, ((MessageDto) payload).getId());
// }
//
// }
//
// Path: jms-base/src/main/java/me/chanjar/jms/base/msg/MessageDto.java
// public abstract class MessageDto implements Serializable {
//
// private static final long serialVersionUID = 9003442515985424079L;
// /**
// * 应该保证全局唯一, 用uuid
// */
// protected final String id;
//
// public MessageDto() {
// this.id = StrongUuidGenerator.getNextId();
// }
//
// public String getId() {
// return id;
// }
//
// }
//
// Path: jms-base/src/main/java/me/chanjar/jms/base/utils/DupMessageDetectStrategy.java
// public interface DupMessageDetectStrategy {
//
// void setId(Message message, Object payload) throws JMSException;
// }
//
// Path: jms-base/src/main/java/me/chanjar/jms/base/utils/MessageConvertUtils.java
// public abstract class MessageConvertUtils {
//
// private MessageConvertUtils() {
// // singleton
// }
//
// /**
// * 把对象转换成{@link Message}
// *
// * @param jmsTemplate
// * @param session
// * @param payload
// * @return
// * @throws JMSException
// */
// public static Message toMessage(JmsTemplate jmsTemplate, Session session, Object payload) throws JMSException {
// return toMessage(jmsTemplate.getMessageConverter(), session, payload);
// }
//
// /**
// * 把对象转换成{@link Message}
// *
// * @param messageConverter
// * @param session
// * @param payload
// * @return
// * @throws JMSException
// */
// public static Message toMessage(MessageConverter messageConverter, Session session, Object payload)
// throws JMSException {
// return messageConverter.toMessage(payload, session);
// }
//
// /**
// * 把{@link Message}转换成对象
// *
// * @param jmsTemplate
// * @param message
// * @param <T>
// * @return
// * @throws JMSException
// */
// public static <T> T fromMessage(JmsTemplate jmsTemplate, Message message) throws JMSException {
// return fromMessage(jmsTemplate.getMessageConverter(), message);
// }
//
// /**
// * 把{@link Message}转换成对象
// *
// * @param messageConverter
// * @param message
// * @param <T>
// * @return
// * @throws JMSException
// */
// public static <T> T fromMessage(MessageConverter messageConverter, Message message) throws JMSException {
// return (T) messageConverter.fromMessage(message);
// }
//
// }
// Path: jms-base/src/main/java/me/chanjar/jms/base/sender/simple/SimpleJmsMessageSender.java
import me.chanjar.jms.base.sender.JmsMessageSender;
import me.chanjar.jms.base.utils.ArtemisMessageDtoDupMessageDetectStrategy;
import me.chanjar.jms.base.msg.MessageDto;
import me.chanjar.jms.base.utils.DupMessageDetectStrategy;
import me.chanjar.jms.base.utils.MessageConvertUtils;
import org.springframework.jms.support.converter.MessageConverter;
import org.springframework.jms.support.converter.SimpleMessageConverter;
import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.MessageProducer;
import javax.jms.Session;
package me.chanjar.jms.base.sender.simple;
public class SimpleJmsMessageSender implements JmsMessageSender {
private Session session;
private MessageProducer messageProducer;
private MessageConverter messageConverter = new SimpleMessageConverter();
private DupMessageDetectStrategy dupMessageDetectStrategy = new ArtemisMessageDtoDupMessageDetectStrategy();
@Override | public void sendMessage(MessageDto payload) throws JMSException { |
chanjarster/artemis-disruptor-miaosha | jms-base/src/main/java/me/chanjar/jms/base/sender/simple/SimpleJmsMessageSender.java | // Path: jms-base/src/main/java/me/chanjar/jms/base/sender/JmsMessageSender.java
// public interface JmsMessageSender {
//
// /**
// * 发送Jms消息
// *
// * @param payload 消息主体
// * @throws JMSException
// */
// void sendMessage(MessageDto payload) throws JMSException;
//
// }
//
// Path: jms-base/src/main/java/me/chanjar/jms/base/utils/ArtemisMessageDtoDupMessageDetectStrategy.java
// public class ArtemisMessageDtoDupMessageDetectStrategy implements DupMessageDetectStrategy {
//
// private static final String HDR_DUPLICATE_DETECTION_ID =
// org.apache.activemq.artemis.api.core.Message.HDR_DUPLICATE_DETECTION_ID.toString();
//
// @Override
// public void setId(Message message, Object payload) throws JMSException {
// message.setStringProperty(HDR_DUPLICATE_DETECTION_ID, ((MessageDto) payload).getId());
// }
//
// }
//
// Path: jms-base/src/main/java/me/chanjar/jms/base/msg/MessageDto.java
// public abstract class MessageDto implements Serializable {
//
// private static final long serialVersionUID = 9003442515985424079L;
// /**
// * 应该保证全局唯一, 用uuid
// */
// protected final String id;
//
// public MessageDto() {
// this.id = StrongUuidGenerator.getNextId();
// }
//
// public String getId() {
// return id;
// }
//
// }
//
// Path: jms-base/src/main/java/me/chanjar/jms/base/utils/DupMessageDetectStrategy.java
// public interface DupMessageDetectStrategy {
//
// void setId(Message message, Object payload) throws JMSException;
// }
//
// Path: jms-base/src/main/java/me/chanjar/jms/base/utils/MessageConvertUtils.java
// public abstract class MessageConvertUtils {
//
// private MessageConvertUtils() {
// // singleton
// }
//
// /**
// * 把对象转换成{@link Message}
// *
// * @param jmsTemplate
// * @param session
// * @param payload
// * @return
// * @throws JMSException
// */
// public static Message toMessage(JmsTemplate jmsTemplate, Session session, Object payload) throws JMSException {
// return toMessage(jmsTemplate.getMessageConverter(), session, payload);
// }
//
// /**
// * 把对象转换成{@link Message}
// *
// * @param messageConverter
// * @param session
// * @param payload
// * @return
// * @throws JMSException
// */
// public static Message toMessage(MessageConverter messageConverter, Session session, Object payload)
// throws JMSException {
// return messageConverter.toMessage(payload, session);
// }
//
// /**
// * 把{@link Message}转换成对象
// *
// * @param jmsTemplate
// * @param message
// * @param <T>
// * @return
// * @throws JMSException
// */
// public static <T> T fromMessage(JmsTemplate jmsTemplate, Message message) throws JMSException {
// return fromMessage(jmsTemplate.getMessageConverter(), message);
// }
//
// /**
// * 把{@link Message}转换成对象
// *
// * @param messageConverter
// * @param message
// * @param <T>
// * @return
// * @throws JMSException
// */
// public static <T> T fromMessage(MessageConverter messageConverter, Message message) throws JMSException {
// return (T) messageConverter.fromMessage(message);
// }
//
// }
| import me.chanjar.jms.base.sender.JmsMessageSender;
import me.chanjar.jms.base.utils.ArtemisMessageDtoDupMessageDetectStrategy;
import me.chanjar.jms.base.msg.MessageDto;
import me.chanjar.jms.base.utils.DupMessageDetectStrategy;
import me.chanjar.jms.base.utils.MessageConvertUtils;
import org.springframework.jms.support.converter.MessageConverter;
import org.springframework.jms.support.converter.SimpleMessageConverter;
import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.MessageProducer;
import javax.jms.Session; | package me.chanjar.jms.base.sender.simple;
public class SimpleJmsMessageSender implements JmsMessageSender {
private Session session;
private MessageProducer messageProducer;
private MessageConverter messageConverter = new SimpleMessageConverter();
private DupMessageDetectStrategy dupMessageDetectStrategy = new ArtemisMessageDtoDupMessageDetectStrategy();
@Override
public void sendMessage(MessageDto payload) throws JMSException {
| // Path: jms-base/src/main/java/me/chanjar/jms/base/sender/JmsMessageSender.java
// public interface JmsMessageSender {
//
// /**
// * 发送Jms消息
// *
// * @param payload 消息主体
// * @throws JMSException
// */
// void sendMessage(MessageDto payload) throws JMSException;
//
// }
//
// Path: jms-base/src/main/java/me/chanjar/jms/base/utils/ArtemisMessageDtoDupMessageDetectStrategy.java
// public class ArtemisMessageDtoDupMessageDetectStrategy implements DupMessageDetectStrategy {
//
// private static final String HDR_DUPLICATE_DETECTION_ID =
// org.apache.activemq.artemis.api.core.Message.HDR_DUPLICATE_DETECTION_ID.toString();
//
// @Override
// public void setId(Message message, Object payload) throws JMSException {
// message.setStringProperty(HDR_DUPLICATE_DETECTION_ID, ((MessageDto) payload).getId());
// }
//
// }
//
// Path: jms-base/src/main/java/me/chanjar/jms/base/msg/MessageDto.java
// public abstract class MessageDto implements Serializable {
//
// private static final long serialVersionUID = 9003442515985424079L;
// /**
// * 应该保证全局唯一, 用uuid
// */
// protected final String id;
//
// public MessageDto() {
// this.id = StrongUuidGenerator.getNextId();
// }
//
// public String getId() {
// return id;
// }
//
// }
//
// Path: jms-base/src/main/java/me/chanjar/jms/base/utils/DupMessageDetectStrategy.java
// public interface DupMessageDetectStrategy {
//
// void setId(Message message, Object payload) throws JMSException;
// }
//
// Path: jms-base/src/main/java/me/chanjar/jms/base/utils/MessageConvertUtils.java
// public abstract class MessageConvertUtils {
//
// private MessageConvertUtils() {
// // singleton
// }
//
// /**
// * 把对象转换成{@link Message}
// *
// * @param jmsTemplate
// * @param session
// * @param payload
// * @return
// * @throws JMSException
// */
// public static Message toMessage(JmsTemplate jmsTemplate, Session session, Object payload) throws JMSException {
// return toMessage(jmsTemplate.getMessageConverter(), session, payload);
// }
//
// /**
// * 把对象转换成{@link Message}
// *
// * @param messageConverter
// * @param session
// * @param payload
// * @return
// * @throws JMSException
// */
// public static Message toMessage(MessageConverter messageConverter, Session session, Object payload)
// throws JMSException {
// return messageConverter.toMessage(payload, session);
// }
//
// /**
// * 把{@link Message}转换成对象
// *
// * @param jmsTemplate
// * @param message
// * @param <T>
// * @return
// * @throws JMSException
// */
// public static <T> T fromMessage(JmsTemplate jmsTemplate, Message message) throws JMSException {
// return fromMessage(jmsTemplate.getMessageConverter(), message);
// }
//
// /**
// * 把{@link Message}转换成对象
// *
// * @param messageConverter
// * @param message
// * @param <T>
// * @return
// * @throws JMSException
// */
// public static <T> T fromMessage(MessageConverter messageConverter, Message message) throws JMSException {
// return (T) messageConverter.fromMessage(message);
// }
//
// }
// Path: jms-base/src/main/java/me/chanjar/jms/base/sender/simple/SimpleJmsMessageSender.java
import me.chanjar.jms.base.sender.JmsMessageSender;
import me.chanjar.jms.base.utils.ArtemisMessageDtoDupMessageDetectStrategy;
import me.chanjar.jms.base.msg.MessageDto;
import me.chanjar.jms.base.utils.DupMessageDetectStrategy;
import me.chanjar.jms.base.utils.MessageConvertUtils;
import org.springframework.jms.support.converter.MessageConverter;
import org.springframework.jms.support.converter.SimpleMessageConverter;
import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.MessageProducer;
import javax.jms.Session;
package me.chanjar.jms.base.sender.simple;
public class SimpleJmsMessageSender implements JmsMessageSender {
private Session session;
private MessageProducer messageProducer;
private MessageConverter messageConverter = new SimpleMessageConverter();
private DupMessageDetectStrategy dupMessageDetectStrategy = new ArtemisMessageDtoDupMessageDetectStrategy();
@Override
public void sendMessage(MessageDto payload) throws JMSException {
| Message message = MessageConvertUtils.toMessage(messageConverter, session, payload); |
chanjarster/artemis-disruptor-miaosha | jms-server/src/main/java/me/chanjar/jms/server/request/RequestDtoEventExceptionHandler.java | // Path: jms-msg/src/main/java/me/chanjar/jms/msg/ResponseDto.java
// public class ResponseDto extends MessageDto {
//
// private static final long serialVersionUID = -4690648814874030736L;
// /**
// * 关联的RequestDto的id
// */
// private final String requestId;
//
// /**
// * 错误消息
// */
// protected String errorMessage;
//
// /**
// * 是否成功处理请求
// */
// protected boolean success;
//
// public ResponseDto(String requestId) {
// super();
// this.requestId = requestId;
// }
//
// public String getRequestId() {
// return requestId;
// }
//
// public String getErrorMessage() {
// return errorMessage;
// }
//
// public void setErrorMessage(String errorMessage) {
// this.errorMessage = errorMessage;
// }
//
// public boolean isSuccess() {
// return success;
// }
//
// public void setSuccess(boolean success) {
// this.success = success;
// }
//
// @Override
// public boolean equals(Object o) {
// if (this == o) return true;
// if (o == null || getClass() != o.getClass()) return false;
//
// ResponseDto that = (ResponseDto) o;
//
// if (success != that.success) return false;
// if (requestId != null ? !requestId.equals(that.requestId) : that.requestId != null) return false;
// return errorMessage != null ? errorMessage.equals(that.errorMessage) : that.errorMessage == null;
// }
//
// @Override
// public int hashCode() {
// int result = requestId != null ? requestId.hashCode() : 0;
// result = 31 * result + (errorMessage != null ? errorMessage.hashCode() : 0);
// result = 31 * result + (success ? 1 : 0);
// return result;
// }
// }
| import com.lmax.disruptor.ExceptionHandler;
import me.chanjar.jms.msg.ResponseDto;
import org.apache.commons.lang3.exception.ExceptionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory; | package me.chanjar.jms.server.request;
public class RequestDtoEventExceptionHandler implements ExceptionHandler<RequestDtoEvent> {
private static final Logger LOGGER = LoggerFactory.getLogger(RequestDtoEventExceptionHandler.class);
@Override
public void handleEventException(Throwable ex, long sequence, RequestDtoEvent event) {
// 遇到异常要记录日志的
event.setResponseDto(
createExceptionResponseDto(event.getRequestDto().getId(), ExceptionUtils.getStackTrace(ex))
);
LOGGER.error("{} : {}. {} ", event.getRequestDto().getClass().getName(), event.getRequestDto().getId(), ExceptionUtils.getStackTrace(ex));
}
| // Path: jms-msg/src/main/java/me/chanjar/jms/msg/ResponseDto.java
// public class ResponseDto extends MessageDto {
//
// private static final long serialVersionUID = -4690648814874030736L;
// /**
// * 关联的RequestDto的id
// */
// private final String requestId;
//
// /**
// * 错误消息
// */
// protected String errorMessage;
//
// /**
// * 是否成功处理请求
// */
// protected boolean success;
//
// public ResponseDto(String requestId) {
// super();
// this.requestId = requestId;
// }
//
// public String getRequestId() {
// return requestId;
// }
//
// public String getErrorMessage() {
// return errorMessage;
// }
//
// public void setErrorMessage(String errorMessage) {
// this.errorMessage = errorMessage;
// }
//
// public boolean isSuccess() {
// return success;
// }
//
// public void setSuccess(boolean success) {
// this.success = success;
// }
//
// @Override
// public boolean equals(Object o) {
// if (this == o) return true;
// if (o == null || getClass() != o.getClass()) return false;
//
// ResponseDto that = (ResponseDto) o;
//
// if (success != that.success) return false;
// if (requestId != null ? !requestId.equals(that.requestId) : that.requestId != null) return false;
// return errorMessage != null ? errorMessage.equals(that.errorMessage) : that.errorMessage == null;
// }
//
// @Override
// public int hashCode() {
// int result = requestId != null ? requestId.hashCode() : 0;
// result = 31 * result + (errorMessage != null ? errorMessage.hashCode() : 0);
// result = 31 * result + (success ? 1 : 0);
// return result;
// }
// }
// Path: jms-server/src/main/java/me/chanjar/jms/server/request/RequestDtoEventExceptionHandler.java
import com.lmax.disruptor.ExceptionHandler;
import me.chanjar.jms.msg.ResponseDto;
import org.apache.commons.lang3.exception.ExceptionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
package me.chanjar.jms.server.request;
public class RequestDtoEventExceptionHandler implements ExceptionHandler<RequestDtoEvent> {
private static final Logger LOGGER = LoggerFactory.getLogger(RequestDtoEventExceptionHandler.class);
@Override
public void handleEventException(Throwable ex, long sequence, RequestDtoEvent event) {
// 遇到异常要记录日志的
event.setResponseDto(
createExceptionResponseDto(event.getRequestDto().getId(), ExceptionUtils.getStackTrace(ex))
);
LOGGER.error("{} : {}. {} ", event.getRequestDto().getClass().getName(), event.getRequestDto().getId(), ExceptionUtils.getStackTrace(ex));
}
| private ResponseDto createExceptionResponseDto(String requestId, String exception) { |
chanjarster/artemis-disruptor-miaosha | jms-base/src/main/java/me/chanjar/jms/base/sender/simple/SimpleJmsMessageSenderFactory.java | // Path: jms-base/src/main/java/me/chanjar/jms/base/utils/DupMessageDetectStrategy.java
// public interface DupMessageDetectStrategy {
//
// void setId(Message message, Object payload) throws JMSException;
// }
| import me.chanjar.jms.base.utils.DupMessageDetectStrategy;
import javax.jms.JMSException;
import javax.jms.MessageProducer;
import javax.jms.Session; | package me.chanjar.jms.base.sender.simple;
public abstract class SimpleJmsMessageSenderFactory {
private SimpleJmsMessageSenderFactory() {
}
/**
* @param session
* @param messageProducer
* @param dupMessageDetectStrategy
* @return
* @throws JMSException
*/
public static SimpleJmsMessageSender create(
Session session,
MessageProducer messageProducer, | // Path: jms-base/src/main/java/me/chanjar/jms/base/utils/DupMessageDetectStrategy.java
// public interface DupMessageDetectStrategy {
//
// void setId(Message message, Object payload) throws JMSException;
// }
// Path: jms-base/src/main/java/me/chanjar/jms/base/sender/simple/SimpleJmsMessageSenderFactory.java
import me.chanjar.jms.base.utils.DupMessageDetectStrategy;
import javax.jms.JMSException;
import javax.jms.MessageProducer;
import javax.jms.Session;
package me.chanjar.jms.base.sender.simple;
public abstract class SimpleJmsMessageSenderFactory {
private SimpleJmsMessageSenderFactory() {
}
/**
* @param session
* @param messageProducer
* @param dupMessageDetectStrategy
* @return
* @throws JMSException
*/
public static SimpleJmsMessageSender create(
Session session,
MessageProducer messageProducer, | DupMessageDetectStrategy dupMessageDetectStrategy |
chanjarster/artemis-disruptor-miaosha | jms-client/src/main/java/me/chanjar/jms/client/command/MiaoShaCommandService.java | // Path: jms-msg/src/main/java/me/chanjar/jms/msg/RequestDto.java
// public class RequestDto extends MessageDto {
//
// private static final long serialVersionUID = 5515305970509119810L;
// /**
// * 商品ID
// */
// private final Long itemId;
//
// /**
// * 用户ID
// */
// private final String userId;
//
// public RequestDto(Long itemId, String userId) {
// super();
// this.itemId = itemId;
// this.userId = userId;
// }
//
// public Long getItemId() {
// return itemId;
// }
//
// public String getUserId() {
// return userId;
// }
//
// @Override
// public boolean equals(Object o) {
// if (this == o) return true;
// if (o == null || getClass() != o.getClass()) return false;
//
// RequestDto that = (RequestDto) o;
//
// if (itemId != null ? !itemId.equals(that.itemId) : that.itemId != null) return false;
// return userId != null ? userId.equals(that.userId) : that.userId == null;
// }
//
// @Override
// public int hashCode() {
// int result = itemId != null ? itemId.hashCode() : 0;
// result = 31 * result + (userId != null ? userId.hashCode() : 0);
// return result;
// }
//
// @Override
// public String toString() {
// return new ToStringBuilder(this)
// .append("id", id)
// .append("itemId", itemId)
// .append("userId", userId)
// .toString();
// }
// }
//
// Path: jms-msg/src/main/java/me/chanjar/jms/msg/ResponseDto.java
// public class ResponseDto extends MessageDto {
//
// private static final long serialVersionUID = -4690648814874030736L;
// /**
// * 关联的RequestDto的id
// */
// private final String requestId;
//
// /**
// * 错误消息
// */
// protected String errorMessage;
//
// /**
// * 是否成功处理请求
// */
// protected boolean success;
//
// public ResponseDto(String requestId) {
// super();
// this.requestId = requestId;
// }
//
// public String getRequestId() {
// return requestId;
// }
//
// public String getErrorMessage() {
// return errorMessage;
// }
//
// public void setErrorMessage(String errorMessage) {
// this.errorMessage = errorMessage;
// }
//
// public boolean isSuccess() {
// return success;
// }
//
// public void setSuccess(boolean success) {
// this.success = success;
// }
//
// @Override
// public boolean equals(Object o) {
// if (this == o) return true;
// if (o == null || getClass() != o.getClass()) return false;
//
// ResponseDto that = (ResponseDto) o;
//
// if (success != that.success) return false;
// if (requestId != null ? !requestId.equals(that.requestId) : that.requestId != null) return false;
// return errorMessage != null ? errorMessage.equals(that.errorMessage) : that.errorMessage == null;
// }
//
// @Override
// public int hashCode() {
// int result = requestId != null ? requestId.hashCode() : 0;
// result = 31 * result + (errorMessage != null ? errorMessage.hashCode() : 0);
// result = 31 * result + (success ? 1 : 0);
// return result;
// }
// }
| import me.chanjar.jms.msg.RequestDto;
import me.chanjar.jms.msg.ResponseDto; | package me.chanjar.jms.client.command;
public interface MiaoShaCommandService {
String doRequest(RequestDto requestDto);
| // Path: jms-msg/src/main/java/me/chanjar/jms/msg/RequestDto.java
// public class RequestDto extends MessageDto {
//
// private static final long serialVersionUID = 5515305970509119810L;
// /**
// * 商品ID
// */
// private final Long itemId;
//
// /**
// * 用户ID
// */
// private final String userId;
//
// public RequestDto(Long itemId, String userId) {
// super();
// this.itemId = itemId;
// this.userId = userId;
// }
//
// public Long getItemId() {
// return itemId;
// }
//
// public String getUserId() {
// return userId;
// }
//
// @Override
// public boolean equals(Object o) {
// if (this == o) return true;
// if (o == null || getClass() != o.getClass()) return false;
//
// RequestDto that = (RequestDto) o;
//
// if (itemId != null ? !itemId.equals(that.itemId) : that.itemId != null) return false;
// return userId != null ? userId.equals(that.userId) : that.userId == null;
// }
//
// @Override
// public int hashCode() {
// int result = itemId != null ? itemId.hashCode() : 0;
// result = 31 * result + (userId != null ? userId.hashCode() : 0);
// return result;
// }
//
// @Override
// public String toString() {
// return new ToStringBuilder(this)
// .append("id", id)
// .append("itemId", itemId)
// .append("userId", userId)
// .toString();
// }
// }
//
// Path: jms-msg/src/main/java/me/chanjar/jms/msg/ResponseDto.java
// public class ResponseDto extends MessageDto {
//
// private static final long serialVersionUID = -4690648814874030736L;
// /**
// * 关联的RequestDto的id
// */
// private final String requestId;
//
// /**
// * 错误消息
// */
// protected String errorMessage;
//
// /**
// * 是否成功处理请求
// */
// protected boolean success;
//
// public ResponseDto(String requestId) {
// super();
// this.requestId = requestId;
// }
//
// public String getRequestId() {
// return requestId;
// }
//
// public String getErrorMessage() {
// return errorMessage;
// }
//
// public void setErrorMessage(String errorMessage) {
// this.errorMessage = errorMessage;
// }
//
// public boolean isSuccess() {
// return success;
// }
//
// public void setSuccess(boolean success) {
// this.success = success;
// }
//
// @Override
// public boolean equals(Object o) {
// if (this == o) return true;
// if (o == null || getClass() != o.getClass()) return false;
//
// ResponseDto that = (ResponseDto) o;
//
// if (success != that.success) return false;
// if (requestId != null ? !requestId.equals(that.requestId) : that.requestId != null) return false;
// return errorMessage != null ? errorMessage.equals(that.errorMessage) : that.errorMessage == null;
// }
//
// @Override
// public int hashCode() {
// int result = requestId != null ? requestId.hashCode() : 0;
// result = 31 * result + (errorMessage != null ? errorMessage.hashCode() : 0);
// result = 31 * result + (success ? 1 : 0);
// return result;
// }
// }
// Path: jms-client/src/main/java/me/chanjar/jms/client/command/MiaoShaCommandService.java
import me.chanjar.jms.msg.RequestDto;
import me.chanjar.jms.msg.ResponseDto;
package me.chanjar.jms.client.command;
public interface MiaoShaCommandService {
String doRequest(RequestDto requestDto);
| ResponseDto getResponse(String requestId); |
chanjarster/artemis-disruptor-miaosha | jms-server/src/main/java/me/chanjar/jms/server/request/RequestDtoEvent.java | // Path: jms-msg/src/main/java/me/chanjar/jms/msg/RequestDto.java
// public class RequestDto extends MessageDto {
//
// private static final long serialVersionUID = 5515305970509119810L;
// /**
// * 商品ID
// */
// private final Long itemId;
//
// /**
// * 用户ID
// */
// private final String userId;
//
// public RequestDto(Long itemId, String userId) {
// super();
// this.itemId = itemId;
// this.userId = userId;
// }
//
// public Long getItemId() {
// return itemId;
// }
//
// public String getUserId() {
// return userId;
// }
//
// @Override
// public boolean equals(Object o) {
// if (this == o) return true;
// if (o == null || getClass() != o.getClass()) return false;
//
// RequestDto that = (RequestDto) o;
//
// if (itemId != null ? !itemId.equals(that.itemId) : that.itemId != null) return false;
// return userId != null ? userId.equals(that.userId) : that.userId == null;
// }
//
// @Override
// public int hashCode() {
// int result = itemId != null ? itemId.hashCode() : 0;
// result = 31 * result + (userId != null ? userId.hashCode() : 0);
// return result;
// }
//
// @Override
// public String toString() {
// return new ToStringBuilder(this)
// .append("id", id)
// .append("itemId", itemId)
// .append("userId", userId)
// .toString();
// }
// }
//
// Path: jms-msg/src/main/java/me/chanjar/jms/msg/ResponseDto.java
// public class ResponseDto extends MessageDto {
//
// private static final long serialVersionUID = -4690648814874030736L;
// /**
// * 关联的RequestDto的id
// */
// private final String requestId;
//
// /**
// * 错误消息
// */
// protected String errorMessage;
//
// /**
// * 是否成功处理请求
// */
// protected boolean success;
//
// public ResponseDto(String requestId) {
// super();
// this.requestId = requestId;
// }
//
// public String getRequestId() {
// return requestId;
// }
//
// public String getErrorMessage() {
// return errorMessage;
// }
//
// public void setErrorMessage(String errorMessage) {
// this.errorMessage = errorMessage;
// }
//
// public boolean isSuccess() {
// return success;
// }
//
// public void setSuccess(boolean success) {
// this.success = success;
// }
//
// @Override
// public boolean equals(Object o) {
// if (this == o) return true;
// if (o == null || getClass() != o.getClass()) return false;
//
// ResponseDto that = (ResponseDto) o;
//
// if (success != that.success) return false;
// if (requestId != null ? !requestId.equals(that.requestId) : that.requestId != null) return false;
// return errorMessage != null ? errorMessage.equals(that.errorMessage) : that.errorMessage == null;
// }
//
// @Override
// public int hashCode() {
// int result = requestId != null ? requestId.hashCode() : 0;
// result = 31 * result + (errorMessage != null ? errorMessage.hashCode() : 0);
// result = 31 * result + (success ? 1 : 0);
// return result;
// }
// }
//
// Path: jms-server/src/main/java/me/chanjar/jms/server/command/infras/CommandCollector.java
// public class CommandCollector {
//
// private List<Command> commandList = new ArrayList<>(4);
//
// public List<Command> getCommandList() {
// return commandList;
// }
//
// public void addCommand(Command command) {
// commandList.add(command);
// }
//
// }
| import me.chanjar.jms.msg.RequestDto;
import me.chanjar.jms.msg.ResponseDto;
import me.chanjar.jms.server.command.infras.CommandCollector; | package me.chanjar.jms.server.request;
public class RequestDtoEvent {
private RequestDto requestDto;
/**
* 数据库操作Command收集器
*/ | // Path: jms-msg/src/main/java/me/chanjar/jms/msg/RequestDto.java
// public class RequestDto extends MessageDto {
//
// private static final long serialVersionUID = 5515305970509119810L;
// /**
// * 商品ID
// */
// private final Long itemId;
//
// /**
// * 用户ID
// */
// private final String userId;
//
// public RequestDto(Long itemId, String userId) {
// super();
// this.itemId = itemId;
// this.userId = userId;
// }
//
// public Long getItemId() {
// return itemId;
// }
//
// public String getUserId() {
// return userId;
// }
//
// @Override
// public boolean equals(Object o) {
// if (this == o) return true;
// if (o == null || getClass() != o.getClass()) return false;
//
// RequestDto that = (RequestDto) o;
//
// if (itemId != null ? !itemId.equals(that.itemId) : that.itemId != null) return false;
// return userId != null ? userId.equals(that.userId) : that.userId == null;
// }
//
// @Override
// public int hashCode() {
// int result = itemId != null ? itemId.hashCode() : 0;
// result = 31 * result + (userId != null ? userId.hashCode() : 0);
// return result;
// }
//
// @Override
// public String toString() {
// return new ToStringBuilder(this)
// .append("id", id)
// .append("itemId", itemId)
// .append("userId", userId)
// .toString();
// }
// }
//
// Path: jms-msg/src/main/java/me/chanjar/jms/msg/ResponseDto.java
// public class ResponseDto extends MessageDto {
//
// private static final long serialVersionUID = -4690648814874030736L;
// /**
// * 关联的RequestDto的id
// */
// private final String requestId;
//
// /**
// * 错误消息
// */
// protected String errorMessage;
//
// /**
// * 是否成功处理请求
// */
// protected boolean success;
//
// public ResponseDto(String requestId) {
// super();
// this.requestId = requestId;
// }
//
// public String getRequestId() {
// return requestId;
// }
//
// public String getErrorMessage() {
// return errorMessage;
// }
//
// public void setErrorMessage(String errorMessage) {
// this.errorMessage = errorMessage;
// }
//
// public boolean isSuccess() {
// return success;
// }
//
// public void setSuccess(boolean success) {
// this.success = success;
// }
//
// @Override
// public boolean equals(Object o) {
// if (this == o) return true;
// if (o == null || getClass() != o.getClass()) return false;
//
// ResponseDto that = (ResponseDto) o;
//
// if (success != that.success) return false;
// if (requestId != null ? !requestId.equals(that.requestId) : that.requestId != null) return false;
// return errorMessage != null ? errorMessage.equals(that.errorMessage) : that.errorMessage == null;
// }
//
// @Override
// public int hashCode() {
// int result = requestId != null ? requestId.hashCode() : 0;
// result = 31 * result + (errorMessage != null ? errorMessage.hashCode() : 0);
// result = 31 * result + (success ? 1 : 0);
// return result;
// }
// }
//
// Path: jms-server/src/main/java/me/chanjar/jms/server/command/infras/CommandCollector.java
// public class CommandCollector {
//
// private List<Command> commandList = new ArrayList<>(4);
//
// public List<Command> getCommandList() {
// return commandList;
// }
//
// public void addCommand(Command command) {
// commandList.add(command);
// }
//
// }
// Path: jms-server/src/main/java/me/chanjar/jms/server/request/RequestDtoEvent.java
import me.chanjar.jms.msg.RequestDto;
import me.chanjar.jms.msg.ResponseDto;
import me.chanjar.jms.server.command.infras.CommandCollector;
package me.chanjar.jms.server.request;
public class RequestDtoEvent {
private RequestDto requestDto;
/**
* 数据库操作Command收集器
*/ | private final CommandCollector commandCollector = new CommandCollector(); |
chanjarster/artemis-disruptor-miaosha | jms-server/src/main/java/me/chanjar/jms/server/request/RequestDtoEvent.java | // Path: jms-msg/src/main/java/me/chanjar/jms/msg/RequestDto.java
// public class RequestDto extends MessageDto {
//
// private static final long serialVersionUID = 5515305970509119810L;
// /**
// * 商品ID
// */
// private final Long itemId;
//
// /**
// * 用户ID
// */
// private final String userId;
//
// public RequestDto(Long itemId, String userId) {
// super();
// this.itemId = itemId;
// this.userId = userId;
// }
//
// public Long getItemId() {
// return itemId;
// }
//
// public String getUserId() {
// return userId;
// }
//
// @Override
// public boolean equals(Object o) {
// if (this == o) return true;
// if (o == null || getClass() != o.getClass()) return false;
//
// RequestDto that = (RequestDto) o;
//
// if (itemId != null ? !itemId.equals(that.itemId) : that.itemId != null) return false;
// return userId != null ? userId.equals(that.userId) : that.userId == null;
// }
//
// @Override
// public int hashCode() {
// int result = itemId != null ? itemId.hashCode() : 0;
// result = 31 * result + (userId != null ? userId.hashCode() : 0);
// return result;
// }
//
// @Override
// public String toString() {
// return new ToStringBuilder(this)
// .append("id", id)
// .append("itemId", itemId)
// .append("userId", userId)
// .toString();
// }
// }
//
// Path: jms-msg/src/main/java/me/chanjar/jms/msg/ResponseDto.java
// public class ResponseDto extends MessageDto {
//
// private static final long serialVersionUID = -4690648814874030736L;
// /**
// * 关联的RequestDto的id
// */
// private final String requestId;
//
// /**
// * 错误消息
// */
// protected String errorMessage;
//
// /**
// * 是否成功处理请求
// */
// protected boolean success;
//
// public ResponseDto(String requestId) {
// super();
// this.requestId = requestId;
// }
//
// public String getRequestId() {
// return requestId;
// }
//
// public String getErrorMessage() {
// return errorMessage;
// }
//
// public void setErrorMessage(String errorMessage) {
// this.errorMessage = errorMessage;
// }
//
// public boolean isSuccess() {
// return success;
// }
//
// public void setSuccess(boolean success) {
// this.success = success;
// }
//
// @Override
// public boolean equals(Object o) {
// if (this == o) return true;
// if (o == null || getClass() != o.getClass()) return false;
//
// ResponseDto that = (ResponseDto) o;
//
// if (success != that.success) return false;
// if (requestId != null ? !requestId.equals(that.requestId) : that.requestId != null) return false;
// return errorMessage != null ? errorMessage.equals(that.errorMessage) : that.errorMessage == null;
// }
//
// @Override
// public int hashCode() {
// int result = requestId != null ? requestId.hashCode() : 0;
// result = 31 * result + (errorMessage != null ? errorMessage.hashCode() : 0);
// result = 31 * result + (success ? 1 : 0);
// return result;
// }
// }
//
// Path: jms-server/src/main/java/me/chanjar/jms/server/command/infras/CommandCollector.java
// public class CommandCollector {
//
// private List<Command> commandList = new ArrayList<>(4);
//
// public List<Command> getCommandList() {
// return commandList;
// }
//
// public void addCommand(Command command) {
// commandList.add(command);
// }
//
// }
| import me.chanjar.jms.msg.RequestDto;
import me.chanjar.jms.msg.ResponseDto;
import me.chanjar.jms.server.command.infras.CommandCollector; | package me.chanjar.jms.server.request;
public class RequestDtoEvent {
private RequestDto requestDto;
/**
* 数据库操作Command收集器
*/
private final CommandCollector commandCollector = new CommandCollector();
/**
* 响应结果
*/ | // Path: jms-msg/src/main/java/me/chanjar/jms/msg/RequestDto.java
// public class RequestDto extends MessageDto {
//
// private static final long serialVersionUID = 5515305970509119810L;
// /**
// * 商品ID
// */
// private final Long itemId;
//
// /**
// * 用户ID
// */
// private final String userId;
//
// public RequestDto(Long itemId, String userId) {
// super();
// this.itemId = itemId;
// this.userId = userId;
// }
//
// public Long getItemId() {
// return itemId;
// }
//
// public String getUserId() {
// return userId;
// }
//
// @Override
// public boolean equals(Object o) {
// if (this == o) return true;
// if (o == null || getClass() != o.getClass()) return false;
//
// RequestDto that = (RequestDto) o;
//
// if (itemId != null ? !itemId.equals(that.itemId) : that.itemId != null) return false;
// return userId != null ? userId.equals(that.userId) : that.userId == null;
// }
//
// @Override
// public int hashCode() {
// int result = itemId != null ? itemId.hashCode() : 0;
// result = 31 * result + (userId != null ? userId.hashCode() : 0);
// return result;
// }
//
// @Override
// public String toString() {
// return new ToStringBuilder(this)
// .append("id", id)
// .append("itemId", itemId)
// .append("userId", userId)
// .toString();
// }
// }
//
// Path: jms-msg/src/main/java/me/chanjar/jms/msg/ResponseDto.java
// public class ResponseDto extends MessageDto {
//
// private static final long serialVersionUID = -4690648814874030736L;
// /**
// * 关联的RequestDto的id
// */
// private final String requestId;
//
// /**
// * 错误消息
// */
// protected String errorMessage;
//
// /**
// * 是否成功处理请求
// */
// protected boolean success;
//
// public ResponseDto(String requestId) {
// super();
// this.requestId = requestId;
// }
//
// public String getRequestId() {
// return requestId;
// }
//
// public String getErrorMessage() {
// return errorMessage;
// }
//
// public void setErrorMessage(String errorMessage) {
// this.errorMessage = errorMessage;
// }
//
// public boolean isSuccess() {
// return success;
// }
//
// public void setSuccess(boolean success) {
// this.success = success;
// }
//
// @Override
// public boolean equals(Object o) {
// if (this == o) return true;
// if (o == null || getClass() != o.getClass()) return false;
//
// ResponseDto that = (ResponseDto) o;
//
// if (success != that.success) return false;
// if (requestId != null ? !requestId.equals(that.requestId) : that.requestId != null) return false;
// return errorMessage != null ? errorMessage.equals(that.errorMessage) : that.errorMessage == null;
// }
//
// @Override
// public int hashCode() {
// int result = requestId != null ? requestId.hashCode() : 0;
// result = 31 * result + (errorMessage != null ? errorMessage.hashCode() : 0);
// result = 31 * result + (success ? 1 : 0);
// return result;
// }
// }
//
// Path: jms-server/src/main/java/me/chanjar/jms/server/command/infras/CommandCollector.java
// public class CommandCollector {
//
// private List<Command> commandList = new ArrayList<>(4);
//
// public List<Command> getCommandList() {
// return commandList;
// }
//
// public void addCommand(Command command) {
// commandList.add(command);
// }
//
// }
// Path: jms-server/src/main/java/me/chanjar/jms/server/request/RequestDtoEvent.java
import me.chanjar.jms.msg.RequestDto;
import me.chanjar.jms.msg.ResponseDto;
import me.chanjar.jms.server.command.infras.CommandCollector;
package me.chanjar.jms.server.request;
public class RequestDtoEvent {
private RequestDto requestDto;
/**
* 数据库操作Command收集器
*/
private final CommandCollector commandCollector = new CommandCollector();
/**
* 响应结果
*/ | private ResponseDto responseDto; |
chanjarster/artemis-disruptor-miaosha | jms-client/src/main/java/me/chanjar/jms/client/command/MiaoShaCommandServiceImpl.java | // Path: jms-base/src/main/java/me/chanjar/jms/base/sender/JmsMessageSender.java
// public interface JmsMessageSender {
//
// /**
// * 发送Jms消息
// *
// * @param payload 消息主体
// * @throws JMSException
// */
// void sendMessage(MessageDto payload) throws JMSException;
//
// }
//
// Path: jms-msg/src/main/java/me/chanjar/jms/msg/RequestDto.java
// public class RequestDto extends MessageDto {
//
// private static final long serialVersionUID = 5515305970509119810L;
// /**
// * 商品ID
// */
// private final Long itemId;
//
// /**
// * 用户ID
// */
// private final String userId;
//
// public RequestDto(Long itemId, String userId) {
// super();
// this.itemId = itemId;
// this.userId = userId;
// }
//
// public Long getItemId() {
// return itemId;
// }
//
// public String getUserId() {
// return userId;
// }
//
// @Override
// public boolean equals(Object o) {
// if (this == o) return true;
// if (o == null || getClass() != o.getClass()) return false;
//
// RequestDto that = (RequestDto) o;
//
// if (itemId != null ? !itemId.equals(that.itemId) : that.itemId != null) return false;
// return userId != null ? userId.equals(that.userId) : that.userId == null;
// }
//
// @Override
// public int hashCode() {
// int result = itemId != null ? itemId.hashCode() : 0;
// result = 31 * result + (userId != null ? userId.hashCode() : 0);
// return result;
// }
//
// @Override
// public String toString() {
// return new ToStringBuilder(this)
// .append("id", id)
// .append("itemId", itemId)
// .append("userId", userId)
// .toString();
// }
// }
//
// Path: jms-msg/src/main/java/me/chanjar/jms/msg/ResponseDto.java
// public class ResponseDto extends MessageDto {
//
// private static final long serialVersionUID = -4690648814874030736L;
// /**
// * 关联的RequestDto的id
// */
// private final String requestId;
//
// /**
// * 错误消息
// */
// protected String errorMessage;
//
// /**
// * 是否成功处理请求
// */
// protected boolean success;
//
// public ResponseDto(String requestId) {
// super();
// this.requestId = requestId;
// }
//
// public String getRequestId() {
// return requestId;
// }
//
// public String getErrorMessage() {
// return errorMessage;
// }
//
// public void setErrorMessage(String errorMessage) {
// this.errorMessage = errorMessage;
// }
//
// public boolean isSuccess() {
// return success;
// }
//
// public void setSuccess(boolean success) {
// this.success = success;
// }
//
// @Override
// public boolean equals(Object o) {
// if (this == o) return true;
// if (o == null || getClass() != o.getClass()) return false;
//
// ResponseDto that = (ResponseDto) o;
//
// if (success != that.success) return false;
// if (requestId != null ? !requestId.equals(that.requestId) : that.requestId != null) return false;
// return errorMessage != null ? errorMessage.equals(that.errorMessage) : that.errorMessage == null;
// }
//
// @Override
// public int hashCode() {
// int result = requestId != null ? requestId.hashCode() : 0;
// result = 31 * result + (errorMessage != null ? errorMessage.hashCode() : 0);
// result = 31 * result + (success ? 1 : 0);
// return result;
// }
// }
| import me.chanjar.jms.base.sender.JmsMessageSender;
import me.chanjar.jms.msg.RequestDto;
import me.chanjar.jms.msg.ResponseDto;
import org.apache.commons.lang3.exception.ExceptionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Component;
import javax.jms.JMSException; | package me.chanjar.jms.client.command;
@Component
public class MiaoShaCommandServiceImpl implements MiaoShaCommandService {
private static final Logger LOGGER = LoggerFactory.getLogger(MiaoShaCommandService.class);
private ResponseCache responseCache;
| // Path: jms-base/src/main/java/me/chanjar/jms/base/sender/JmsMessageSender.java
// public interface JmsMessageSender {
//
// /**
// * 发送Jms消息
// *
// * @param payload 消息主体
// * @throws JMSException
// */
// void sendMessage(MessageDto payload) throws JMSException;
//
// }
//
// Path: jms-msg/src/main/java/me/chanjar/jms/msg/RequestDto.java
// public class RequestDto extends MessageDto {
//
// private static final long serialVersionUID = 5515305970509119810L;
// /**
// * 商品ID
// */
// private final Long itemId;
//
// /**
// * 用户ID
// */
// private final String userId;
//
// public RequestDto(Long itemId, String userId) {
// super();
// this.itemId = itemId;
// this.userId = userId;
// }
//
// public Long getItemId() {
// return itemId;
// }
//
// public String getUserId() {
// return userId;
// }
//
// @Override
// public boolean equals(Object o) {
// if (this == o) return true;
// if (o == null || getClass() != o.getClass()) return false;
//
// RequestDto that = (RequestDto) o;
//
// if (itemId != null ? !itemId.equals(that.itemId) : that.itemId != null) return false;
// return userId != null ? userId.equals(that.userId) : that.userId == null;
// }
//
// @Override
// public int hashCode() {
// int result = itemId != null ? itemId.hashCode() : 0;
// result = 31 * result + (userId != null ? userId.hashCode() : 0);
// return result;
// }
//
// @Override
// public String toString() {
// return new ToStringBuilder(this)
// .append("id", id)
// .append("itemId", itemId)
// .append("userId", userId)
// .toString();
// }
// }
//
// Path: jms-msg/src/main/java/me/chanjar/jms/msg/ResponseDto.java
// public class ResponseDto extends MessageDto {
//
// private static final long serialVersionUID = -4690648814874030736L;
// /**
// * 关联的RequestDto的id
// */
// private final String requestId;
//
// /**
// * 错误消息
// */
// protected String errorMessage;
//
// /**
// * 是否成功处理请求
// */
// protected boolean success;
//
// public ResponseDto(String requestId) {
// super();
// this.requestId = requestId;
// }
//
// public String getRequestId() {
// return requestId;
// }
//
// public String getErrorMessage() {
// return errorMessage;
// }
//
// public void setErrorMessage(String errorMessage) {
// this.errorMessage = errorMessage;
// }
//
// public boolean isSuccess() {
// return success;
// }
//
// public void setSuccess(boolean success) {
// this.success = success;
// }
//
// @Override
// public boolean equals(Object o) {
// if (this == o) return true;
// if (o == null || getClass() != o.getClass()) return false;
//
// ResponseDto that = (ResponseDto) o;
//
// if (success != that.success) return false;
// if (requestId != null ? !requestId.equals(that.requestId) : that.requestId != null) return false;
// return errorMessage != null ? errorMessage.equals(that.errorMessage) : that.errorMessage == null;
// }
//
// @Override
// public int hashCode() {
// int result = requestId != null ? requestId.hashCode() : 0;
// result = 31 * result + (errorMessage != null ? errorMessage.hashCode() : 0);
// result = 31 * result + (success ? 1 : 0);
// return result;
// }
// }
// Path: jms-client/src/main/java/me/chanjar/jms/client/command/MiaoShaCommandServiceImpl.java
import me.chanjar.jms.base.sender.JmsMessageSender;
import me.chanjar.jms.msg.RequestDto;
import me.chanjar.jms.msg.ResponseDto;
import org.apache.commons.lang3.exception.ExceptionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Component;
import javax.jms.JMSException;
package me.chanjar.jms.client.command;
@Component
public class MiaoShaCommandServiceImpl implements MiaoShaCommandService {
private static final Logger LOGGER = LoggerFactory.getLogger(MiaoShaCommandService.class);
private ResponseCache responseCache;
| private JmsMessageSender jmsMessageSender; |
chanjarster/artemis-disruptor-miaosha | jms-client/src/main/java/me/chanjar/jms/client/command/MiaoShaCommandServiceImpl.java | // Path: jms-base/src/main/java/me/chanjar/jms/base/sender/JmsMessageSender.java
// public interface JmsMessageSender {
//
// /**
// * 发送Jms消息
// *
// * @param payload 消息主体
// * @throws JMSException
// */
// void sendMessage(MessageDto payload) throws JMSException;
//
// }
//
// Path: jms-msg/src/main/java/me/chanjar/jms/msg/RequestDto.java
// public class RequestDto extends MessageDto {
//
// private static final long serialVersionUID = 5515305970509119810L;
// /**
// * 商品ID
// */
// private final Long itemId;
//
// /**
// * 用户ID
// */
// private final String userId;
//
// public RequestDto(Long itemId, String userId) {
// super();
// this.itemId = itemId;
// this.userId = userId;
// }
//
// public Long getItemId() {
// return itemId;
// }
//
// public String getUserId() {
// return userId;
// }
//
// @Override
// public boolean equals(Object o) {
// if (this == o) return true;
// if (o == null || getClass() != o.getClass()) return false;
//
// RequestDto that = (RequestDto) o;
//
// if (itemId != null ? !itemId.equals(that.itemId) : that.itemId != null) return false;
// return userId != null ? userId.equals(that.userId) : that.userId == null;
// }
//
// @Override
// public int hashCode() {
// int result = itemId != null ? itemId.hashCode() : 0;
// result = 31 * result + (userId != null ? userId.hashCode() : 0);
// return result;
// }
//
// @Override
// public String toString() {
// return new ToStringBuilder(this)
// .append("id", id)
// .append("itemId", itemId)
// .append("userId", userId)
// .toString();
// }
// }
//
// Path: jms-msg/src/main/java/me/chanjar/jms/msg/ResponseDto.java
// public class ResponseDto extends MessageDto {
//
// private static final long serialVersionUID = -4690648814874030736L;
// /**
// * 关联的RequestDto的id
// */
// private final String requestId;
//
// /**
// * 错误消息
// */
// protected String errorMessage;
//
// /**
// * 是否成功处理请求
// */
// protected boolean success;
//
// public ResponseDto(String requestId) {
// super();
// this.requestId = requestId;
// }
//
// public String getRequestId() {
// return requestId;
// }
//
// public String getErrorMessage() {
// return errorMessage;
// }
//
// public void setErrorMessage(String errorMessage) {
// this.errorMessage = errorMessage;
// }
//
// public boolean isSuccess() {
// return success;
// }
//
// public void setSuccess(boolean success) {
// this.success = success;
// }
//
// @Override
// public boolean equals(Object o) {
// if (this == o) return true;
// if (o == null || getClass() != o.getClass()) return false;
//
// ResponseDto that = (ResponseDto) o;
//
// if (success != that.success) return false;
// if (requestId != null ? !requestId.equals(that.requestId) : that.requestId != null) return false;
// return errorMessage != null ? errorMessage.equals(that.errorMessage) : that.errorMessage == null;
// }
//
// @Override
// public int hashCode() {
// int result = requestId != null ? requestId.hashCode() : 0;
// result = 31 * result + (errorMessage != null ? errorMessage.hashCode() : 0);
// result = 31 * result + (success ? 1 : 0);
// return result;
// }
// }
| import me.chanjar.jms.base.sender.JmsMessageSender;
import me.chanjar.jms.msg.RequestDto;
import me.chanjar.jms.msg.ResponseDto;
import org.apache.commons.lang3.exception.ExceptionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Component;
import javax.jms.JMSException; | package me.chanjar.jms.client.command;
@Component
public class MiaoShaCommandServiceImpl implements MiaoShaCommandService {
private static final Logger LOGGER = LoggerFactory.getLogger(MiaoShaCommandService.class);
private ResponseCache responseCache;
private JmsMessageSender jmsMessageSender;
@Override | // Path: jms-base/src/main/java/me/chanjar/jms/base/sender/JmsMessageSender.java
// public interface JmsMessageSender {
//
// /**
// * 发送Jms消息
// *
// * @param payload 消息主体
// * @throws JMSException
// */
// void sendMessage(MessageDto payload) throws JMSException;
//
// }
//
// Path: jms-msg/src/main/java/me/chanjar/jms/msg/RequestDto.java
// public class RequestDto extends MessageDto {
//
// private static final long serialVersionUID = 5515305970509119810L;
// /**
// * 商品ID
// */
// private final Long itemId;
//
// /**
// * 用户ID
// */
// private final String userId;
//
// public RequestDto(Long itemId, String userId) {
// super();
// this.itemId = itemId;
// this.userId = userId;
// }
//
// public Long getItemId() {
// return itemId;
// }
//
// public String getUserId() {
// return userId;
// }
//
// @Override
// public boolean equals(Object o) {
// if (this == o) return true;
// if (o == null || getClass() != o.getClass()) return false;
//
// RequestDto that = (RequestDto) o;
//
// if (itemId != null ? !itemId.equals(that.itemId) : that.itemId != null) return false;
// return userId != null ? userId.equals(that.userId) : that.userId == null;
// }
//
// @Override
// public int hashCode() {
// int result = itemId != null ? itemId.hashCode() : 0;
// result = 31 * result + (userId != null ? userId.hashCode() : 0);
// return result;
// }
//
// @Override
// public String toString() {
// return new ToStringBuilder(this)
// .append("id", id)
// .append("itemId", itemId)
// .append("userId", userId)
// .toString();
// }
// }
//
// Path: jms-msg/src/main/java/me/chanjar/jms/msg/ResponseDto.java
// public class ResponseDto extends MessageDto {
//
// private static final long serialVersionUID = -4690648814874030736L;
// /**
// * 关联的RequestDto的id
// */
// private final String requestId;
//
// /**
// * 错误消息
// */
// protected String errorMessage;
//
// /**
// * 是否成功处理请求
// */
// protected boolean success;
//
// public ResponseDto(String requestId) {
// super();
// this.requestId = requestId;
// }
//
// public String getRequestId() {
// return requestId;
// }
//
// public String getErrorMessage() {
// return errorMessage;
// }
//
// public void setErrorMessage(String errorMessage) {
// this.errorMessage = errorMessage;
// }
//
// public boolean isSuccess() {
// return success;
// }
//
// public void setSuccess(boolean success) {
// this.success = success;
// }
//
// @Override
// public boolean equals(Object o) {
// if (this == o) return true;
// if (o == null || getClass() != o.getClass()) return false;
//
// ResponseDto that = (ResponseDto) o;
//
// if (success != that.success) return false;
// if (requestId != null ? !requestId.equals(that.requestId) : that.requestId != null) return false;
// return errorMessage != null ? errorMessage.equals(that.errorMessage) : that.errorMessage == null;
// }
//
// @Override
// public int hashCode() {
// int result = requestId != null ? requestId.hashCode() : 0;
// result = 31 * result + (errorMessage != null ? errorMessage.hashCode() : 0);
// result = 31 * result + (success ? 1 : 0);
// return result;
// }
// }
// Path: jms-client/src/main/java/me/chanjar/jms/client/command/MiaoShaCommandServiceImpl.java
import me.chanjar.jms.base.sender.JmsMessageSender;
import me.chanjar.jms.msg.RequestDto;
import me.chanjar.jms.msg.ResponseDto;
import org.apache.commons.lang3.exception.ExceptionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Component;
import javax.jms.JMSException;
package me.chanjar.jms.client.command;
@Component
public class MiaoShaCommandServiceImpl implements MiaoShaCommandService {
private static final Logger LOGGER = LoggerFactory.getLogger(MiaoShaCommandService.class);
private ResponseCache responseCache;
private JmsMessageSender jmsMessageSender;
@Override | public String doRequest(RequestDto requestDto) { |
chanjarster/artemis-disruptor-miaosha | jms-client/src/main/java/me/chanjar/jms/client/command/MiaoShaCommandServiceImpl.java | // Path: jms-base/src/main/java/me/chanjar/jms/base/sender/JmsMessageSender.java
// public interface JmsMessageSender {
//
// /**
// * 发送Jms消息
// *
// * @param payload 消息主体
// * @throws JMSException
// */
// void sendMessage(MessageDto payload) throws JMSException;
//
// }
//
// Path: jms-msg/src/main/java/me/chanjar/jms/msg/RequestDto.java
// public class RequestDto extends MessageDto {
//
// private static final long serialVersionUID = 5515305970509119810L;
// /**
// * 商品ID
// */
// private final Long itemId;
//
// /**
// * 用户ID
// */
// private final String userId;
//
// public RequestDto(Long itemId, String userId) {
// super();
// this.itemId = itemId;
// this.userId = userId;
// }
//
// public Long getItemId() {
// return itemId;
// }
//
// public String getUserId() {
// return userId;
// }
//
// @Override
// public boolean equals(Object o) {
// if (this == o) return true;
// if (o == null || getClass() != o.getClass()) return false;
//
// RequestDto that = (RequestDto) o;
//
// if (itemId != null ? !itemId.equals(that.itemId) : that.itemId != null) return false;
// return userId != null ? userId.equals(that.userId) : that.userId == null;
// }
//
// @Override
// public int hashCode() {
// int result = itemId != null ? itemId.hashCode() : 0;
// result = 31 * result + (userId != null ? userId.hashCode() : 0);
// return result;
// }
//
// @Override
// public String toString() {
// return new ToStringBuilder(this)
// .append("id", id)
// .append("itemId", itemId)
// .append("userId", userId)
// .toString();
// }
// }
//
// Path: jms-msg/src/main/java/me/chanjar/jms/msg/ResponseDto.java
// public class ResponseDto extends MessageDto {
//
// private static final long serialVersionUID = -4690648814874030736L;
// /**
// * 关联的RequestDto的id
// */
// private final String requestId;
//
// /**
// * 错误消息
// */
// protected String errorMessage;
//
// /**
// * 是否成功处理请求
// */
// protected boolean success;
//
// public ResponseDto(String requestId) {
// super();
// this.requestId = requestId;
// }
//
// public String getRequestId() {
// return requestId;
// }
//
// public String getErrorMessage() {
// return errorMessage;
// }
//
// public void setErrorMessage(String errorMessage) {
// this.errorMessage = errorMessage;
// }
//
// public boolean isSuccess() {
// return success;
// }
//
// public void setSuccess(boolean success) {
// this.success = success;
// }
//
// @Override
// public boolean equals(Object o) {
// if (this == o) return true;
// if (o == null || getClass() != o.getClass()) return false;
//
// ResponseDto that = (ResponseDto) o;
//
// if (success != that.success) return false;
// if (requestId != null ? !requestId.equals(that.requestId) : that.requestId != null) return false;
// return errorMessage != null ? errorMessage.equals(that.errorMessage) : that.errorMessage == null;
// }
//
// @Override
// public int hashCode() {
// int result = requestId != null ? requestId.hashCode() : 0;
// result = 31 * result + (errorMessage != null ? errorMessage.hashCode() : 0);
// result = 31 * result + (success ? 1 : 0);
// return result;
// }
// }
| import me.chanjar.jms.base.sender.JmsMessageSender;
import me.chanjar.jms.msg.RequestDto;
import me.chanjar.jms.msg.ResponseDto;
import org.apache.commons.lang3.exception.ExceptionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Component;
import javax.jms.JMSException; | package me.chanjar.jms.client.command;
@Component
public class MiaoShaCommandServiceImpl implements MiaoShaCommandService {
private static final Logger LOGGER = LoggerFactory.getLogger(MiaoShaCommandService.class);
private ResponseCache responseCache;
private JmsMessageSender jmsMessageSender;
@Override
public String doRequest(RequestDto requestDto) {
try {
jmsMessageSender.sendMessage(requestDto);
return requestDto.getId();
} catch (JMSException e) {
LOGGER.error(ExceptionUtils.getStackTrace(e));
throw new RuntimeException(e);
}
}
@Override | // Path: jms-base/src/main/java/me/chanjar/jms/base/sender/JmsMessageSender.java
// public interface JmsMessageSender {
//
// /**
// * 发送Jms消息
// *
// * @param payload 消息主体
// * @throws JMSException
// */
// void sendMessage(MessageDto payload) throws JMSException;
//
// }
//
// Path: jms-msg/src/main/java/me/chanjar/jms/msg/RequestDto.java
// public class RequestDto extends MessageDto {
//
// private static final long serialVersionUID = 5515305970509119810L;
// /**
// * 商品ID
// */
// private final Long itemId;
//
// /**
// * 用户ID
// */
// private final String userId;
//
// public RequestDto(Long itemId, String userId) {
// super();
// this.itemId = itemId;
// this.userId = userId;
// }
//
// public Long getItemId() {
// return itemId;
// }
//
// public String getUserId() {
// return userId;
// }
//
// @Override
// public boolean equals(Object o) {
// if (this == o) return true;
// if (o == null || getClass() != o.getClass()) return false;
//
// RequestDto that = (RequestDto) o;
//
// if (itemId != null ? !itemId.equals(that.itemId) : that.itemId != null) return false;
// return userId != null ? userId.equals(that.userId) : that.userId == null;
// }
//
// @Override
// public int hashCode() {
// int result = itemId != null ? itemId.hashCode() : 0;
// result = 31 * result + (userId != null ? userId.hashCode() : 0);
// return result;
// }
//
// @Override
// public String toString() {
// return new ToStringBuilder(this)
// .append("id", id)
// .append("itemId", itemId)
// .append("userId", userId)
// .toString();
// }
// }
//
// Path: jms-msg/src/main/java/me/chanjar/jms/msg/ResponseDto.java
// public class ResponseDto extends MessageDto {
//
// private static final long serialVersionUID = -4690648814874030736L;
// /**
// * 关联的RequestDto的id
// */
// private final String requestId;
//
// /**
// * 错误消息
// */
// protected String errorMessage;
//
// /**
// * 是否成功处理请求
// */
// protected boolean success;
//
// public ResponseDto(String requestId) {
// super();
// this.requestId = requestId;
// }
//
// public String getRequestId() {
// return requestId;
// }
//
// public String getErrorMessage() {
// return errorMessage;
// }
//
// public void setErrorMessage(String errorMessage) {
// this.errorMessage = errorMessage;
// }
//
// public boolean isSuccess() {
// return success;
// }
//
// public void setSuccess(boolean success) {
// this.success = success;
// }
//
// @Override
// public boolean equals(Object o) {
// if (this == o) return true;
// if (o == null || getClass() != o.getClass()) return false;
//
// ResponseDto that = (ResponseDto) o;
//
// if (success != that.success) return false;
// if (requestId != null ? !requestId.equals(that.requestId) : that.requestId != null) return false;
// return errorMessage != null ? errorMessage.equals(that.errorMessage) : that.errorMessage == null;
// }
//
// @Override
// public int hashCode() {
// int result = requestId != null ? requestId.hashCode() : 0;
// result = 31 * result + (errorMessage != null ? errorMessage.hashCode() : 0);
// result = 31 * result + (success ? 1 : 0);
// return result;
// }
// }
// Path: jms-client/src/main/java/me/chanjar/jms/client/command/MiaoShaCommandServiceImpl.java
import me.chanjar.jms.base.sender.JmsMessageSender;
import me.chanjar.jms.msg.RequestDto;
import me.chanjar.jms.msg.ResponseDto;
import org.apache.commons.lang3.exception.ExceptionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Component;
import javax.jms.JMSException;
package me.chanjar.jms.client.command;
@Component
public class MiaoShaCommandServiceImpl implements MiaoShaCommandService {
private static final Logger LOGGER = LoggerFactory.getLogger(MiaoShaCommandService.class);
private ResponseCache responseCache;
private JmsMessageSender jmsMessageSender;
@Override
public String doRequest(RequestDto requestDto) {
try {
jmsMessageSender.sendMessage(requestDto);
return requestDto.getId();
} catch (JMSException e) {
LOGGER.error(ExceptionUtils.getStackTrace(e));
throw new RuntimeException(e);
}
}
@Override | public ResponseDto getResponse(String requestId) { |
chanjarster/artemis-disruptor-miaosha | jms-server/src/main/java/me/chanjar/jms/server/command/item/ItemAmountUpdateCommandBuffer.java | // Path: jms-server/src/main/java/me/chanjar/jms/server/command/infras/CommandBuffer.java
// public interface CommandBuffer<T extends Command> {
//
// /**
// * Buffer是否已经满了
// *
// * @return
// */
// boolean hasRemaining();
//
// /**
// * 放入Command
// *
// * @param command
// */
// void put(T command);
//
// /**
// * 清空缓存
// */
// void clear();
//
// /**
// * 获得{@link Command}
// *
// * @return
// */
// List<T> get();
//
// }
//
// Path: jms-server/src/main/java/me/chanjar/jms/server/command/infras/CommandBufferOverflowException.java
// public class CommandBufferOverflowException extends RuntimeException {
//
// private static final long serialVersionUID = -408555980971903979L;
//
// /**
// * Constructs an instance of this class.
// */
// public CommandBufferOverflowException() {
// // do nothing
// }
//
// }
| import me.chanjar.jms.server.command.infras.CommandBuffer;
import me.chanjar.jms.server.command.infras.CommandBufferOverflowException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map; | package me.chanjar.jms.server.command.item;
/**
* {@link ItemAmountUpdateCommand}的Buffer <br>
* 内部存储是一个以{@link ItemAmountUpdateCommand#itemId}为Key的Map <br>
* 这样做的好处是, 如果有多个相同Key的{@link ItemAmountUpdateCommand}, 那么也就只会记录最后一个<br>
* 从而减少了Sql语句数量
*/
public class ItemAmountUpdateCommandBuffer implements CommandBuffer<ItemAmountUpdateCommand> {
private static final Logger LOGGER = LoggerFactory.getLogger(ItemAmountUpdateCommandBuffer.class);
private final Map<Long, ItemAmountUpdateCommand> commandMap = new HashMap<>();
private final int capacity;
public ItemAmountUpdateCommandBuffer(int capacity) {
this.capacity = capacity;
}
@Override
public boolean hasRemaining() {
return commandMap.size() < this.capacity;
}
/**
* @param command
* @throws CommandBufferOverflowException
*/
@Override
public void put(ItemAmountUpdateCommand command) {
Long key = command.getItemId();
if (!hasRemaining() && commandMap.get(key) == null) { | // Path: jms-server/src/main/java/me/chanjar/jms/server/command/infras/CommandBuffer.java
// public interface CommandBuffer<T extends Command> {
//
// /**
// * Buffer是否已经满了
// *
// * @return
// */
// boolean hasRemaining();
//
// /**
// * 放入Command
// *
// * @param command
// */
// void put(T command);
//
// /**
// * 清空缓存
// */
// void clear();
//
// /**
// * 获得{@link Command}
// *
// * @return
// */
// List<T> get();
//
// }
//
// Path: jms-server/src/main/java/me/chanjar/jms/server/command/infras/CommandBufferOverflowException.java
// public class CommandBufferOverflowException extends RuntimeException {
//
// private static final long serialVersionUID = -408555980971903979L;
//
// /**
// * Constructs an instance of this class.
// */
// public CommandBufferOverflowException() {
// // do nothing
// }
//
// }
// Path: jms-server/src/main/java/me/chanjar/jms/server/command/item/ItemAmountUpdateCommandBuffer.java
import me.chanjar.jms.server.command.infras.CommandBuffer;
import me.chanjar.jms.server.command.infras.CommandBufferOverflowException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
package me.chanjar.jms.server.command.item;
/**
* {@link ItemAmountUpdateCommand}的Buffer <br>
* 内部存储是一个以{@link ItemAmountUpdateCommand#itemId}为Key的Map <br>
* 这样做的好处是, 如果有多个相同Key的{@link ItemAmountUpdateCommand}, 那么也就只会记录最后一个<br>
* 从而减少了Sql语句数量
*/
public class ItemAmountUpdateCommandBuffer implements CommandBuffer<ItemAmountUpdateCommand> {
private static final Logger LOGGER = LoggerFactory.getLogger(ItemAmountUpdateCommandBuffer.class);
private final Map<Long, ItemAmountUpdateCommand> commandMap = new HashMap<>();
private final int capacity;
public ItemAmountUpdateCommandBuffer(int capacity) {
this.capacity = capacity;
}
@Override
public boolean hasRemaining() {
return commandMap.size() < this.capacity;
}
/**
* @param command
* @throws CommandBufferOverflowException
*/
@Override
public void put(ItemAmountUpdateCommand command) {
Long key = command.getItemId();
if (!hasRemaining() && commandMap.get(key) == null) { | throw new CommandBufferOverflowException(); |
chanjarster/artemis-disruptor-miaosha | jms-client/src/main/java/me/chanjar/jms/client/command/ResponseCacheImpl.java | // Path: jms-msg/src/main/java/me/chanjar/jms/msg/ResponseDto.java
// public class ResponseDto extends MessageDto {
//
// private static final long serialVersionUID = -4690648814874030736L;
// /**
// * 关联的RequestDto的id
// */
// private final String requestId;
//
// /**
// * 错误消息
// */
// protected String errorMessage;
//
// /**
// * 是否成功处理请求
// */
// protected boolean success;
//
// public ResponseDto(String requestId) {
// super();
// this.requestId = requestId;
// }
//
// public String getRequestId() {
// return requestId;
// }
//
// public String getErrorMessage() {
// return errorMessage;
// }
//
// public void setErrorMessage(String errorMessage) {
// this.errorMessage = errorMessage;
// }
//
// public boolean isSuccess() {
// return success;
// }
//
// public void setSuccess(boolean success) {
// this.success = success;
// }
//
// @Override
// public boolean equals(Object o) {
// if (this == o) return true;
// if (o == null || getClass() != o.getClass()) return false;
//
// ResponseDto that = (ResponseDto) o;
//
// if (success != that.success) return false;
// if (requestId != null ? !requestId.equals(that.requestId) : that.requestId != null) return false;
// return errorMessage != null ? errorMessage.equals(that.errorMessage) : that.errorMessage == null;
// }
//
// @Override
// public int hashCode() {
// int result = requestId != null ? requestId.hashCode() : 0;
// result = 31 * result + (errorMessage != null ? errorMessage.hashCode() : 0);
// result = 31 * result + (success ? 1 : 0);
// return result;
// }
// }
| import me.chanjar.jms.msg.ResponseDto;
import org.javatuples.Pair;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap; | package me.chanjar.jms.client.command;
@Component
public class ResponseCacheImpl implements ResponseCache {
// request_id -> response, expire time | // Path: jms-msg/src/main/java/me/chanjar/jms/msg/ResponseDto.java
// public class ResponseDto extends MessageDto {
//
// private static final long serialVersionUID = -4690648814874030736L;
// /**
// * 关联的RequestDto的id
// */
// private final String requestId;
//
// /**
// * 错误消息
// */
// protected String errorMessage;
//
// /**
// * 是否成功处理请求
// */
// protected boolean success;
//
// public ResponseDto(String requestId) {
// super();
// this.requestId = requestId;
// }
//
// public String getRequestId() {
// return requestId;
// }
//
// public String getErrorMessage() {
// return errorMessage;
// }
//
// public void setErrorMessage(String errorMessage) {
// this.errorMessage = errorMessage;
// }
//
// public boolean isSuccess() {
// return success;
// }
//
// public void setSuccess(boolean success) {
// this.success = success;
// }
//
// @Override
// public boolean equals(Object o) {
// if (this == o) return true;
// if (o == null || getClass() != o.getClass()) return false;
//
// ResponseDto that = (ResponseDto) o;
//
// if (success != that.success) return false;
// if (requestId != null ? !requestId.equals(that.requestId) : that.requestId != null) return false;
// return errorMessage != null ? errorMessage.equals(that.errorMessage) : that.errorMessage == null;
// }
//
// @Override
// public int hashCode() {
// int result = requestId != null ? requestId.hashCode() : 0;
// result = 31 * result + (errorMessage != null ? errorMessage.hashCode() : 0);
// result = 31 * result + (success ? 1 : 0);
// return result;
// }
// }
// Path: jms-client/src/main/java/me/chanjar/jms/client/command/ResponseCacheImpl.java
import me.chanjar.jms.msg.ResponseDto;
import org.javatuples.Pair;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
package me.chanjar.jms.client.command;
@Component
public class ResponseCacheImpl implements ResponseCache {
// request_id -> response, expire time | private static final ConcurrentMap<String, Pair<ResponseDto, Long>> RESPONSE_MAP = new ConcurrentHashMap<>(); |
chanjarster/artemis-disruptor-miaosha | jms-server/src/main/java/me/chanjar/jms/server/request/RequestDtoEventDbOutputer.java | // Path: jms-server/src/main/java/me/chanjar/jms/server/command/infras/Command.java
// public abstract class Command implements Serializable {
//
// private static final long serialVersionUID = -2463630580877588711L;
// protected final String id;
//
// protected final String requestId;
//
// /**
// * Command来源的requestId
// *
// * @param requestId
// */
// public Command(String requestId) {
// this.id = StrongUuidGenerator.getNextId();
// this.requestId = requestId;
// }
//
// /**
// * 全局唯一Id, uuid
// *
// * @return
// */
// public String getId() {
// return id;
// }
//
// /**
// * 对应的{@link RequestDto#id}
// *
// * @return
// */
// public String getRequestId() {
// return requestId;
// }
// }
//
// Path: jms-server/src/main/java/me/chanjar/jms/server/command/infras/CommandDispatcher.java
// public interface CommandDispatcher {
//
// void dispatch(Command command);
//
// void registerCommandProcessor(CommandProcessor commandProcessor);
//
// }
| import com.lmax.disruptor.EventHandler;
import me.chanjar.jms.server.command.infras.Command;
import me.chanjar.jms.server.command.infras.CommandDispatcher;
import org.apache.commons.collections.CollectionUtils;
import java.util.List; | package me.chanjar.jms.server.request;
/**
* 将结果RequestDtoEvent的结果输出到数据库
*/
public class RequestDtoEventDbOutputer implements EventHandler<RequestDtoEvent> {
private CommandDispatcher commandDispatcher;
@Override
public void onEvent(RequestDtoEvent event, long sequence, boolean endOfBatch) throws Exception {
if (event.hasErrorOrException()) {
return;
}
| // Path: jms-server/src/main/java/me/chanjar/jms/server/command/infras/Command.java
// public abstract class Command implements Serializable {
//
// private static final long serialVersionUID = -2463630580877588711L;
// protected final String id;
//
// protected final String requestId;
//
// /**
// * Command来源的requestId
// *
// * @param requestId
// */
// public Command(String requestId) {
// this.id = StrongUuidGenerator.getNextId();
// this.requestId = requestId;
// }
//
// /**
// * 全局唯一Id, uuid
// *
// * @return
// */
// public String getId() {
// return id;
// }
//
// /**
// * 对应的{@link RequestDto#id}
// *
// * @return
// */
// public String getRequestId() {
// return requestId;
// }
// }
//
// Path: jms-server/src/main/java/me/chanjar/jms/server/command/infras/CommandDispatcher.java
// public interface CommandDispatcher {
//
// void dispatch(Command command);
//
// void registerCommandProcessor(CommandProcessor commandProcessor);
//
// }
// Path: jms-server/src/main/java/me/chanjar/jms/server/request/RequestDtoEventDbOutputer.java
import com.lmax.disruptor.EventHandler;
import me.chanjar.jms.server.command.infras.Command;
import me.chanjar.jms.server.command.infras.CommandDispatcher;
import org.apache.commons.collections.CollectionUtils;
import java.util.List;
package me.chanjar.jms.server.request;
/**
* 将结果RequestDtoEvent的结果输出到数据库
*/
public class RequestDtoEventDbOutputer implements EventHandler<RequestDtoEvent> {
private CommandDispatcher commandDispatcher;
@Override
public void onEvent(RequestDtoEvent event, long sequence, boolean endOfBatch) throws Exception {
if (event.hasErrorOrException()) {
return;
}
| List<Command> commandList = event.getCommandCollector().getCommandList(); |
chanjarster/artemis-disruptor-miaosha | web/src/main/java/me/chanjar/MiaoshaRestController.java | // Path: jms-client/src/main/java/me/chanjar/jms/client/command/MiaoShaCommandService.java
// public interface MiaoShaCommandService {
//
// String doRequest(RequestDto requestDto);
//
// ResponseDto getResponse(String requestId);
//
// }
//
// Path: jms-msg/src/main/java/me/chanjar/jms/msg/RequestDto.java
// public class RequestDto extends MessageDto {
//
// private static final long serialVersionUID = 5515305970509119810L;
// /**
// * 商品ID
// */
// private final Long itemId;
//
// /**
// * 用户ID
// */
// private final String userId;
//
// public RequestDto(Long itemId, String userId) {
// super();
// this.itemId = itemId;
// this.userId = userId;
// }
//
// public Long getItemId() {
// return itemId;
// }
//
// public String getUserId() {
// return userId;
// }
//
// @Override
// public boolean equals(Object o) {
// if (this == o) return true;
// if (o == null || getClass() != o.getClass()) return false;
//
// RequestDto that = (RequestDto) o;
//
// if (itemId != null ? !itemId.equals(that.itemId) : that.itemId != null) return false;
// return userId != null ? userId.equals(that.userId) : that.userId == null;
// }
//
// @Override
// public int hashCode() {
// int result = itemId != null ? itemId.hashCode() : 0;
// result = 31 * result + (userId != null ? userId.hashCode() : 0);
// return result;
// }
//
// @Override
// public String toString() {
// return new ToStringBuilder(this)
// .append("id", id)
// .append("itemId", itemId)
// .append("userId", userId)
// .toString();
// }
// }
//
// Path: jms-msg/src/main/java/me/chanjar/jms/msg/ResponseDto.java
// public class ResponseDto extends MessageDto {
//
// private static final long serialVersionUID = -4690648814874030736L;
// /**
// * 关联的RequestDto的id
// */
// private final String requestId;
//
// /**
// * 错误消息
// */
// protected String errorMessage;
//
// /**
// * 是否成功处理请求
// */
// protected boolean success;
//
// public ResponseDto(String requestId) {
// super();
// this.requestId = requestId;
// }
//
// public String getRequestId() {
// return requestId;
// }
//
// public String getErrorMessage() {
// return errorMessage;
// }
//
// public void setErrorMessage(String errorMessage) {
// this.errorMessage = errorMessage;
// }
//
// public boolean isSuccess() {
// return success;
// }
//
// public void setSuccess(boolean success) {
// this.success = success;
// }
//
// @Override
// public boolean equals(Object o) {
// if (this == o) return true;
// if (o == null || getClass() != o.getClass()) return false;
//
// ResponseDto that = (ResponseDto) o;
//
// if (success != that.success) return false;
// if (requestId != null ? !requestId.equals(that.requestId) : that.requestId != null) return false;
// return errorMessage != null ? errorMessage.equals(that.errorMessage) : that.errorMessage == null;
// }
//
// @Override
// public int hashCode() {
// int result = requestId != null ? requestId.hashCode() : 0;
// result = 31 * result + (errorMessage != null ? errorMessage.hashCode() : 0);
// result = 31 * result + (success ? 1 : 0);
// return result;
// }
// }
| import me.chanjar.jms.client.command.MiaoShaCommandService;
import me.chanjar.jms.msg.RequestDto;
import me.chanjar.jms.msg.ResponseDto;
import org.apache.commons.lang3.RandomStringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController; | package me.chanjar;
/**
* 秒杀Rest Controller
*/
@RestController
public class MiaoshaRestController {
| // Path: jms-client/src/main/java/me/chanjar/jms/client/command/MiaoShaCommandService.java
// public interface MiaoShaCommandService {
//
// String doRequest(RequestDto requestDto);
//
// ResponseDto getResponse(String requestId);
//
// }
//
// Path: jms-msg/src/main/java/me/chanjar/jms/msg/RequestDto.java
// public class RequestDto extends MessageDto {
//
// private static final long serialVersionUID = 5515305970509119810L;
// /**
// * 商品ID
// */
// private final Long itemId;
//
// /**
// * 用户ID
// */
// private final String userId;
//
// public RequestDto(Long itemId, String userId) {
// super();
// this.itemId = itemId;
// this.userId = userId;
// }
//
// public Long getItemId() {
// return itemId;
// }
//
// public String getUserId() {
// return userId;
// }
//
// @Override
// public boolean equals(Object o) {
// if (this == o) return true;
// if (o == null || getClass() != o.getClass()) return false;
//
// RequestDto that = (RequestDto) o;
//
// if (itemId != null ? !itemId.equals(that.itemId) : that.itemId != null) return false;
// return userId != null ? userId.equals(that.userId) : that.userId == null;
// }
//
// @Override
// public int hashCode() {
// int result = itemId != null ? itemId.hashCode() : 0;
// result = 31 * result + (userId != null ? userId.hashCode() : 0);
// return result;
// }
//
// @Override
// public String toString() {
// return new ToStringBuilder(this)
// .append("id", id)
// .append("itemId", itemId)
// .append("userId", userId)
// .toString();
// }
// }
//
// Path: jms-msg/src/main/java/me/chanjar/jms/msg/ResponseDto.java
// public class ResponseDto extends MessageDto {
//
// private static final long serialVersionUID = -4690648814874030736L;
// /**
// * 关联的RequestDto的id
// */
// private final String requestId;
//
// /**
// * 错误消息
// */
// protected String errorMessage;
//
// /**
// * 是否成功处理请求
// */
// protected boolean success;
//
// public ResponseDto(String requestId) {
// super();
// this.requestId = requestId;
// }
//
// public String getRequestId() {
// return requestId;
// }
//
// public String getErrorMessage() {
// return errorMessage;
// }
//
// public void setErrorMessage(String errorMessage) {
// this.errorMessage = errorMessage;
// }
//
// public boolean isSuccess() {
// return success;
// }
//
// public void setSuccess(boolean success) {
// this.success = success;
// }
//
// @Override
// public boolean equals(Object o) {
// if (this == o) return true;
// if (o == null || getClass() != o.getClass()) return false;
//
// ResponseDto that = (ResponseDto) o;
//
// if (success != that.success) return false;
// if (requestId != null ? !requestId.equals(that.requestId) : that.requestId != null) return false;
// return errorMessage != null ? errorMessage.equals(that.errorMessage) : that.errorMessage == null;
// }
//
// @Override
// public int hashCode() {
// int result = requestId != null ? requestId.hashCode() : 0;
// result = 31 * result + (errorMessage != null ? errorMessage.hashCode() : 0);
// result = 31 * result + (success ? 1 : 0);
// return result;
// }
// }
// Path: web/src/main/java/me/chanjar/MiaoshaRestController.java
import me.chanjar.jms.client.command.MiaoShaCommandService;
import me.chanjar.jms.msg.RequestDto;
import me.chanjar.jms.msg.ResponseDto;
import org.apache.commons.lang3.RandomStringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
package me.chanjar;
/**
* 秒杀Rest Controller
*/
@RestController
public class MiaoshaRestController {
| private MiaoShaCommandService miaoshaCommandService; |
chanjarster/artemis-disruptor-miaosha | web/src/main/java/me/chanjar/MiaoshaRestController.java | // Path: jms-client/src/main/java/me/chanjar/jms/client/command/MiaoShaCommandService.java
// public interface MiaoShaCommandService {
//
// String doRequest(RequestDto requestDto);
//
// ResponseDto getResponse(String requestId);
//
// }
//
// Path: jms-msg/src/main/java/me/chanjar/jms/msg/RequestDto.java
// public class RequestDto extends MessageDto {
//
// private static final long serialVersionUID = 5515305970509119810L;
// /**
// * 商品ID
// */
// private final Long itemId;
//
// /**
// * 用户ID
// */
// private final String userId;
//
// public RequestDto(Long itemId, String userId) {
// super();
// this.itemId = itemId;
// this.userId = userId;
// }
//
// public Long getItemId() {
// return itemId;
// }
//
// public String getUserId() {
// return userId;
// }
//
// @Override
// public boolean equals(Object o) {
// if (this == o) return true;
// if (o == null || getClass() != o.getClass()) return false;
//
// RequestDto that = (RequestDto) o;
//
// if (itemId != null ? !itemId.equals(that.itemId) : that.itemId != null) return false;
// return userId != null ? userId.equals(that.userId) : that.userId == null;
// }
//
// @Override
// public int hashCode() {
// int result = itemId != null ? itemId.hashCode() : 0;
// result = 31 * result + (userId != null ? userId.hashCode() : 0);
// return result;
// }
//
// @Override
// public String toString() {
// return new ToStringBuilder(this)
// .append("id", id)
// .append("itemId", itemId)
// .append("userId", userId)
// .toString();
// }
// }
//
// Path: jms-msg/src/main/java/me/chanjar/jms/msg/ResponseDto.java
// public class ResponseDto extends MessageDto {
//
// private static final long serialVersionUID = -4690648814874030736L;
// /**
// * 关联的RequestDto的id
// */
// private final String requestId;
//
// /**
// * 错误消息
// */
// protected String errorMessage;
//
// /**
// * 是否成功处理请求
// */
// protected boolean success;
//
// public ResponseDto(String requestId) {
// super();
// this.requestId = requestId;
// }
//
// public String getRequestId() {
// return requestId;
// }
//
// public String getErrorMessage() {
// return errorMessage;
// }
//
// public void setErrorMessage(String errorMessage) {
// this.errorMessage = errorMessage;
// }
//
// public boolean isSuccess() {
// return success;
// }
//
// public void setSuccess(boolean success) {
// this.success = success;
// }
//
// @Override
// public boolean equals(Object o) {
// if (this == o) return true;
// if (o == null || getClass() != o.getClass()) return false;
//
// ResponseDto that = (ResponseDto) o;
//
// if (success != that.success) return false;
// if (requestId != null ? !requestId.equals(that.requestId) : that.requestId != null) return false;
// return errorMessage != null ? errorMessage.equals(that.errorMessage) : that.errorMessage == null;
// }
//
// @Override
// public int hashCode() {
// int result = requestId != null ? requestId.hashCode() : 0;
// result = 31 * result + (errorMessage != null ? errorMessage.hashCode() : 0);
// result = 31 * result + (success ? 1 : 0);
// return result;
// }
// }
| import me.chanjar.jms.client.command.MiaoShaCommandService;
import me.chanjar.jms.msg.RequestDto;
import me.chanjar.jms.msg.ResponseDto;
import org.apache.commons.lang3.RandomStringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController; | package me.chanjar;
/**
* 秒杀Rest Controller
*/
@RestController
public class MiaoshaRestController {
private MiaoShaCommandService miaoshaCommandService;
/**
* 下单
*
* @param itemId
* @return
*/
@RequestMapping(value = "/order", method = RequestMethod.POST) | // Path: jms-client/src/main/java/me/chanjar/jms/client/command/MiaoShaCommandService.java
// public interface MiaoShaCommandService {
//
// String doRequest(RequestDto requestDto);
//
// ResponseDto getResponse(String requestId);
//
// }
//
// Path: jms-msg/src/main/java/me/chanjar/jms/msg/RequestDto.java
// public class RequestDto extends MessageDto {
//
// private static final long serialVersionUID = 5515305970509119810L;
// /**
// * 商品ID
// */
// private final Long itemId;
//
// /**
// * 用户ID
// */
// private final String userId;
//
// public RequestDto(Long itemId, String userId) {
// super();
// this.itemId = itemId;
// this.userId = userId;
// }
//
// public Long getItemId() {
// return itemId;
// }
//
// public String getUserId() {
// return userId;
// }
//
// @Override
// public boolean equals(Object o) {
// if (this == o) return true;
// if (o == null || getClass() != o.getClass()) return false;
//
// RequestDto that = (RequestDto) o;
//
// if (itemId != null ? !itemId.equals(that.itemId) : that.itemId != null) return false;
// return userId != null ? userId.equals(that.userId) : that.userId == null;
// }
//
// @Override
// public int hashCode() {
// int result = itemId != null ? itemId.hashCode() : 0;
// result = 31 * result + (userId != null ? userId.hashCode() : 0);
// return result;
// }
//
// @Override
// public String toString() {
// return new ToStringBuilder(this)
// .append("id", id)
// .append("itemId", itemId)
// .append("userId", userId)
// .toString();
// }
// }
//
// Path: jms-msg/src/main/java/me/chanjar/jms/msg/ResponseDto.java
// public class ResponseDto extends MessageDto {
//
// private static final long serialVersionUID = -4690648814874030736L;
// /**
// * 关联的RequestDto的id
// */
// private final String requestId;
//
// /**
// * 错误消息
// */
// protected String errorMessage;
//
// /**
// * 是否成功处理请求
// */
// protected boolean success;
//
// public ResponseDto(String requestId) {
// super();
// this.requestId = requestId;
// }
//
// public String getRequestId() {
// return requestId;
// }
//
// public String getErrorMessage() {
// return errorMessage;
// }
//
// public void setErrorMessage(String errorMessage) {
// this.errorMessage = errorMessage;
// }
//
// public boolean isSuccess() {
// return success;
// }
//
// public void setSuccess(boolean success) {
// this.success = success;
// }
//
// @Override
// public boolean equals(Object o) {
// if (this == o) return true;
// if (o == null || getClass() != o.getClass()) return false;
//
// ResponseDto that = (ResponseDto) o;
//
// if (success != that.success) return false;
// if (requestId != null ? !requestId.equals(that.requestId) : that.requestId != null) return false;
// return errorMessage != null ? errorMessage.equals(that.errorMessage) : that.errorMessage == null;
// }
//
// @Override
// public int hashCode() {
// int result = requestId != null ? requestId.hashCode() : 0;
// result = 31 * result + (errorMessage != null ? errorMessage.hashCode() : 0);
// result = 31 * result + (success ? 1 : 0);
// return result;
// }
// }
// Path: web/src/main/java/me/chanjar/MiaoshaRestController.java
import me.chanjar.jms.client.command.MiaoShaCommandService;
import me.chanjar.jms.msg.RequestDto;
import me.chanjar.jms.msg.ResponseDto;
import org.apache.commons.lang3.RandomStringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
package me.chanjar;
/**
* 秒杀Rest Controller
*/
@RestController
public class MiaoshaRestController {
private MiaoShaCommandService miaoshaCommandService;
/**
* 下单
*
* @param itemId
* @return
*/
@RequestMapping(value = "/order", method = RequestMethod.POST) | public RequestDto order(@RequestParam("itemId") Long itemId) { |
chanjarster/artemis-disruptor-miaosha | web/src/main/java/me/chanjar/MiaoshaRestController.java | // Path: jms-client/src/main/java/me/chanjar/jms/client/command/MiaoShaCommandService.java
// public interface MiaoShaCommandService {
//
// String doRequest(RequestDto requestDto);
//
// ResponseDto getResponse(String requestId);
//
// }
//
// Path: jms-msg/src/main/java/me/chanjar/jms/msg/RequestDto.java
// public class RequestDto extends MessageDto {
//
// private static final long serialVersionUID = 5515305970509119810L;
// /**
// * 商品ID
// */
// private final Long itemId;
//
// /**
// * 用户ID
// */
// private final String userId;
//
// public RequestDto(Long itemId, String userId) {
// super();
// this.itemId = itemId;
// this.userId = userId;
// }
//
// public Long getItemId() {
// return itemId;
// }
//
// public String getUserId() {
// return userId;
// }
//
// @Override
// public boolean equals(Object o) {
// if (this == o) return true;
// if (o == null || getClass() != o.getClass()) return false;
//
// RequestDto that = (RequestDto) o;
//
// if (itemId != null ? !itemId.equals(that.itemId) : that.itemId != null) return false;
// return userId != null ? userId.equals(that.userId) : that.userId == null;
// }
//
// @Override
// public int hashCode() {
// int result = itemId != null ? itemId.hashCode() : 0;
// result = 31 * result + (userId != null ? userId.hashCode() : 0);
// return result;
// }
//
// @Override
// public String toString() {
// return new ToStringBuilder(this)
// .append("id", id)
// .append("itemId", itemId)
// .append("userId", userId)
// .toString();
// }
// }
//
// Path: jms-msg/src/main/java/me/chanjar/jms/msg/ResponseDto.java
// public class ResponseDto extends MessageDto {
//
// private static final long serialVersionUID = -4690648814874030736L;
// /**
// * 关联的RequestDto的id
// */
// private final String requestId;
//
// /**
// * 错误消息
// */
// protected String errorMessage;
//
// /**
// * 是否成功处理请求
// */
// protected boolean success;
//
// public ResponseDto(String requestId) {
// super();
// this.requestId = requestId;
// }
//
// public String getRequestId() {
// return requestId;
// }
//
// public String getErrorMessage() {
// return errorMessage;
// }
//
// public void setErrorMessage(String errorMessage) {
// this.errorMessage = errorMessage;
// }
//
// public boolean isSuccess() {
// return success;
// }
//
// public void setSuccess(boolean success) {
// this.success = success;
// }
//
// @Override
// public boolean equals(Object o) {
// if (this == o) return true;
// if (o == null || getClass() != o.getClass()) return false;
//
// ResponseDto that = (ResponseDto) o;
//
// if (success != that.success) return false;
// if (requestId != null ? !requestId.equals(that.requestId) : that.requestId != null) return false;
// return errorMessage != null ? errorMessage.equals(that.errorMessage) : that.errorMessage == null;
// }
//
// @Override
// public int hashCode() {
// int result = requestId != null ? requestId.hashCode() : 0;
// result = 31 * result + (errorMessage != null ? errorMessage.hashCode() : 0);
// result = 31 * result + (success ? 1 : 0);
// return result;
// }
// }
| import me.chanjar.jms.client.command.MiaoShaCommandService;
import me.chanjar.jms.msg.RequestDto;
import me.chanjar.jms.msg.ResponseDto;
import org.apache.commons.lang3.RandomStringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController; | package me.chanjar;
/**
* 秒杀Rest Controller
*/
@RestController
public class MiaoshaRestController {
private MiaoShaCommandService miaoshaCommandService;
/**
* 下单
*
* @param itemId
* @return
*/
@RequestMapping(value = "/order", method = RequestMethod.POST)
public RequestDto order(@RequestParam("itemId") Long itemId) {
RequestDto requestDto = new RequestDto(itemId, getUser());
miaoshaCommandService.doRequest(requestDto);
return requestDto;
}
/**
* 获得下单结果
*
* @param requestId
* @return
*/
@RequestMapping(value = "/order-result", method = RequestMethod.GET) | // Path: jms-client/src/main/java/me/chanjar/jms/client/command/MiaoShaCommandService.java
// public interface MiaoShaCommandService {
//
// String doRequest(RequestDto requestDto);
//
// ResponseDto getResponse(String requestId);
//
// }
//
// Path: jms-msg/src/main/java/me/chanjar/jms/msg/RequestDto.java
// public class RequestDto extends MessageDto {
//
// private static final long serialVersionUID = 5515305970509119810L;
// /**
// * 商品ID
// */
// private final Long itemId;
//
// /**
// * 用户ID
// */
// private final String userId;
//
// public RequestDto(Long itemId, String userId) {
// super();
// this.itemId = itemId;
// this.userId = userId;
// }
//
// public Long getItemId() {
// return itemId;
// }
//
// public String getUserId() {
// return userId;
// }
//
// @Override
// public boolean equals(Object o) {
// if (this == o) return true;
// if (o == null || getClass() != o.getClass()) return false;
//
// RequestDto that = (RequestDto) o;
//
// if (itemId != null ? !itemId.equals(that.itemId) : that.itemId != null) return false;
// return userId != null ? userId.equals(that.userId) : that.userId == null;
// }
//
// @Override
// public int hashCode() {
// int result = itemId != null ? itemId.hashCode() : 0;
// result = 31 * result + (userId != null ? userId.hashCode() : 0);
// return result;
// }
//
// @Override
// public String toString() {
// return new ToStringBuilder(this)
// .append("id", id)
// .append("itemId", itemId)
// .append("userId", userId)
// .toString();
// }
// }
//
// Path: jms-msg/src/main/java/me/chanjar/jms/msg/ResponseDto.java
// public class ResponseDto extends MessageDto {
//
// private static final long serialVersionUID = -4690648814874030736L;
// /**
// * 关联的RequestDto的id
// */
// private final String requestId;
//
// /**
// * 错误消息
// */
// protected String errorMessage;
//
// /**
// * 是否成功处理请求
// */
// protected boolean success;
//
// public ResponseDto(String requestId) {
// super();
// this.requestId = requestId;
// }
//
// public String getRequestId() {
// return requestId;
// }
//
// public String getErrorMessage() {
// return errorMessage;
// }
//
// public void setErrorMessage(String errorMessage) {
// this.errorMessage = errorMessage;
// }
//
// public boolean isSuccess() {
// return success;
// }
//
// public void setSuccess(boolean success) {
// this.success = success;
// }
//
// @Override
// public boolean equals(Object o) {
// if (this == o) return true;
// if (o == null || getClass() != o.getClass()) return false;
//
// ResponseDto that = (ResponseDto) o;
//
// if (success != that.success) return false;
// if (requestId != null ? !requestId.equals(that.requestId) : that.requestId != null) return false;
// return errorMessage != null ? errorMessage.equals(that.errorMessage) : that.errorMessage == null;
// }
//
// @Override
// public int hashCode() {
// int result = requestId != null ? requestId.hashCode() : 0;
// result = 31 * result + (errorMessage != null ? errorMessage.hashCode() : 0);
// result = 31 * result + (success ? 1 : 0);
// return result;
// }
// }
// Path: web/src/main/java/me/chanjar/MiaoshaRestController.java
import me.chanjar.jms.client.command.MiaoShaCommandService;
import me.chanjar.jms.msg.RequestDto;
import me.chanjar.jms.msg.ResponseDto;
import org.apache.commons.lang3.RandomStringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
package me.chanjar;
/**
* 秒杀Rest Controller
*/
@RestController
public class MiaoshaRestController {
private MiaoShaCommandService miaoshaCommandService;
/**
* 下单
*
* @param itemId
* @return
*/
@RequestMapping(value = "/order", method = RequestMethod.POST)
public RequestDto order(@RequestParam("itemId") Long itemId) {
RequestDto requestDto = new RequestDto(itemId, getUser());
miaoshaCommandService.doRequest(requestDto);
return requestDto;
}
/**
* 获得下单结果
*
* @param requestId
* @return
*/
@RequestMapping(value = "/order-result", method = RequestMethod.GET) | public ResponseDto getOrderResult(@RequestParam("requestId") String requestId) { |
chanjarster/artemis-disruptor-miaosha | jms-base/src/main/java/me/chanjar/jms/base/config/ArtemisJmsConfiguration.java | // Path: jms-base/src/main/java/me/chanjar/jms/base/lifecycle/ConnectionFactoryLifeCycleContainer.java
// public class ConnectionFactoryLifeCycleContainer implements SmartLifecycle {
//
// private static final Logger LOGGER = LoggerFactory.getLogger(ConnectionLifeCycleContainer.class);
//
// private volatile boolean running;
//
// private final Object monitor = new Object();
//
// private final ConnectionFactory connectionFactory;
//
// public ConnectionFactoryLifeCycleContainer(ConnectionFactory connectionFactory) {
// Assert.notNull(connectionFactory, "connectionFactory must not be null");
// this.connectionFactory = connectionFactory;
// }
//
// @Override
// public boolean isAutoStartup() {
// return true;
// }
//
// @Override
// public void stop(Runnable callback) {
// stop();
// callback.run();
// }
//
// @Override
// public void start() {
//
// LOGGER.info("Manage life cycle of " + this.connectionFactory.toString());
// this.running = true;
//
// }
//
// @Override
// public void stop() {
//
// synchronized (this.monitor) {
//
// if (this.running) {
//
// try {
//
// if (this.connectionFactory instanceof AutoCloseable) {
// ((AutoCloseable) this.connectionFactory).close();
// LOGGER.info("Close connection factory {}", this.connectionFactory.toString());
// } else {
// LOGGER.info("{} doesn't implements AutoCloseable, won't do close.", this.connectionFactory.toString());
// }
//
// } catch (Exception e) {
//
// LOGGER.error("Error happened when closing connection factory: {}", this.connectionFactory.toString());
// LOGGER.error(ExceptionUtils.getStackTrace(e));
//
// } finally {
//
// this.running = false;
//
// }
//
// }
//
// }
//
// }
//
// @Override
// public boolean isRunning() {
// return this.running;
// }
//
// @Override
// public int getPhase() {
// return JmsObjectLifecycleOrderConstants.CONNECTION_FACTORY;
// }
//
// }
//
// Path: jms-base/src/main/java/me/chanjar/jms/base/lifecycle/ConnectionLifeCycleContainer.java
// public class ConnectionLifeCycleContainer implements SmartLifecycle {
//
// private static final Logger LOGGER = LoggerFactory.getLogger(ConnectionLifeCycleContainer.class);
//
// private volatile boolean running;
//
// private final Object monitor = new Object();
//
// private final Connection connection;
//
// public ConnectionLifeCycleContainer(Connection connection) {
// Assert.notNull(connection, "Connection must not be null");
// this.connection = connection;
// }
//
// @Override
// public boolean isAutoStartup() {
// return true;
// }
//
// @Override
// public void stop(Runnable callback) {
// stop();
// callback.run();
// }
//
// @Override
// public void start() {
//
// synchronized (this.monitor) {
// if (!this.running) {
// try {
//
// this.connection.start();
// LOGGER.info("Start connection {}", this.connection.toString());
//
// } catch (Exception e) {
//
// LOGGER.error("Error happened when starting connection: {}", this.connection.toString());
// LOGGER.error(ExceptionUtils.getStackTrace(e));
//
// } finally {
//
// this.running = false;
//
// }
// }
// }
//
// }
//
// @Override
// public void stop() {
//
// synchronized (this.monitor) {
//
// if (this.running) {
//
// try {
//
// this.connection.stop();
// this.connection.close();
// this.running = false;
//
// LOGGER.info("Close connection {}", this.connection.toString());
//
// monitor.wait(1000L);
//
// } catch (JMSException e) {
//
// LOGGER.error("Error happened when closing connection: {}", this.connection.toString());
// throw new JmsConnectionCloseException(e);
//
// } catch (InterruptedException e) {
//
// LOGGER.error("Error happened when closing connection: {}", this.connection.toString());
// throw new JmsConnectionCloseException(e);
//
// }
//
// }
//
// }
//
// }
//
// @Override
// public boolean isRunning() {
// return this.running;
// }
//
// @Override
// public int getPhase() {
// return JmsObjectLifecycleOrderConstants.CONNECTION;
// }
//
// public static class JmsConnectionCloseException extends RuntimeException {
// private static final long serialVersionUID = -5707901053880272357L;
//
// public JmsConnectionCloseException(Throwable cause) {
// super(cause);
// }
// }
//
// }
| import me.chanjar.jms.base.lifecycle.ConnectionFactoryLifeCycleContainer;
import me.chanjar.jms.base.lifecycle.ConnectionLifeCycleContainer;
import org.apache.activemq.artemis.api.jms.ActiveMQJMSClient;
import org.apache.activemq.artemis.uri.ConnectionFactoryParser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import javax.jms.Connection;
import javax.jms.ConnectionFactory;
import javax.jms.Queue;
import javax.jms.Topic; | package me.chanjar.jms.base.config;
@Configuration
@EnableConfigurationProperties(ArtemisJmsConfiguration.ArtemisProperties.class)
public class ArtemisJmsConfiguration {
@Autowired
private ArtemisProperties artemisProperties;
@Bean
public ConnectionFactory defaultConnectionFactory() throws Exception {
ConnectionFactoryParser parser = new ConnectionFactoryParser();
return parser.newObject(parser.expandURI(artemisProperties.getUri()), "defaultConnectionFactory");
}
@Bean | // Path: jms-base/src/main/java/me/chanjar/jms/base/lifecycle/ConnectionFactoryLifeCycleContainer.java
// public class ConnectionFactoryLifeCycleContainer implements SmartLifecycle {
//
// private static final Logger LOGGER = LoggerFactory.getLogger(ConnectionLifeCycleContainer.class);
//
// private volatile boolean running;
//
// private final Object monitor = new Object();
//
// private final ConnectionFactory connectionFactory;
//
// public ConnectionFactoryLifeCycleContainer(ConnectionFactory connectionFactory) {
// Assert.notNull(connectionFactory, "connectionFactory must not be null");
// this.connectionFactory = connectionFactory;
// }
//
// @Override
// public boolean isAutoStartup() {
// return true;
// }
//
// @Override
// public void stop(Runnable callback) {
// stop();
// callback.run();
// }
//
// @Override
// public void start() {
//
// LOGGER.info("Manage life cycle of " + this.connectionFactory.toString());
// this.running = true;
//
// }
//
// @Override
// public void stop() {
//
// synchronized (this.monitor) {
//
// if (this.running) {
//
// try {
//
// if (this.connectionFactory instanceof AutoCloseable) {
// ((AutoCloseable) this.connectionFactory).close();
// LOGGER.info("Close connection factory {}", this.connectionFactory.toString());
// } else {
// LOGGER.info("{} doesn't implements AutoCloseable, won't do close.", this.connectionFactory.toString());
// }
//
// } catch (Exception e) {
//
// LOGGER.error("Error happened when closing connection factory: {}", this.connectionFactory.toString());
// LOGGER.error(ExceptionUtils.getStackTrace(e));
//
// } finally {
//
// this.running = false;
//
// }
//
// }
//
// }
//
// }
//
// @Override
// public boolean isRunning() {
// return this.running;
// }
//
// @Override
// public int getPhase() {
// return JmsObjectLifecycleOrderConstants.CONNECTION_FACTORY;
// }
//
// }
//
// Path: jms-base/src/main/java/me/chanjar/jms/base/lifecycle/ConnectionLifeCycleContainer.java
// public class ConnectionLifeCycleContainer implements SmartLifecycle {
//
// private static final Logger LOGGER = LoggerFactory.getLogger(ConnectionLifeCycleContainer.class);
//
// private volatile boolean running;
//
// private final Object monitor = new Object();
//
// private final Connection connection;
//
// public ConnectionLifeCycleContainer(Connection connection) {
// Assert.notNull(connection, "Connection must not be null");
// this.connection = connection;
// }
//
// @Override
// public boolean isAutoStartup() {
// return true;
// }
//
// @Override
// public void stop(Runnable callback) {
// stop();
// callback.run();
// }
//
// @Override
// public void start() {
//
// synchronized (this.monitor) {
// if (!this.running) {
// try {
//
// this.connection.start();
// LOGGER.info("Start connection {}", this.connection.toString());
//
// } catch (Exception e) {
//
// LOGGER.error("Error happened when starting connection: {}", this.connection.toString());
// LOGGER.error(ExceptionUtils.getStackTrace(e));
//
// } finally {
//
// this.running = false;
//
// }
// }
// }
//
// }
//
// @Override
// public void stop() {
//
// synchronized (this.monitor) {
//
// if (this.running) {
//
// try {
//
// this.connection.stop();
// this.connection.close();
// this.running = false;
//
// LOGGER.info("Close connection {}", this.connection.toString());
//
// monitor.wait(1000L);
//
// } catch (JMSException e) {
//
// LOGGER.error("Error happened when closing connection: {}", this.connection.toString());
// throw new JmsConnectionCloseException(e);
//
// } catch (InterruptedException e) {
//
// LOGGER.error("Error happened when closing connection: {}", this.connection.toString());
// throw new JmsConnectionCloseException(e);
//
// }
//
// }
//
// }
//
// }
//
// @Override
// public boolean isRunning() {
// return this.running;
// }
//
// @Override
// public int getPhase() {
// return JmsObjectLifecycleOrderConstants.CONNECTION;
// }
//
// public static class JmsConnectionCloseException extends RuntimeException {
// private static final long serialVersionUID = -5707901053880272357L;
//
// public JmsConnectionCloseException(Throwable cause) {
// super(cause);
// }
// }
//
// }
// Path: jms-base/src/main/java/me/chanjar/jms/base/config/ArtemisJmsConfiguration.java
import me.chanjar.jms.base.lifecycle.ConnectionFactoryLifeCycleContainer;
import me.chanjar.jms.base.lifecycle.ConnectionLifeCycleContainer;
import org.apache.activemq.artemis.api.jms.ActiveMQJMSClient;
import org.apache.activemq.artemis.uri.ConnectionFactoryParser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import javax.jms.Connection;
import javax.jms.ConnectionFactory;
import javax.jms.Queue;
import javax.jms.Topic;
package me.chanjar.jms.base.config;
@Configuration
@EnableConfigurationProperties(ArtemisJmsConfiguration.ArtemisProperties.class)
public class ArtemisJmsConfiguration {
@Autowired
private ArtemisProperties artemisProperties;
@Bean
public ConnectionFactory defaultConnectionFactory() throws Exception {
ConnectionFactoryParser parser = new ConnectionFactoryParser();
return parser.newObject(parser.expandURI(artemisProperties.getUri()), "defaultConnectionFactory");
}
@Bean | public ConnectionFactoryLifeCycleContainer defaultConnectionFactoryLifeCycleContainer() throws Exception { |
chanjarster/artemis-disruptor-miaosha | jms-base/src/main/java/me/chanjar/jms/base/config/ArtemisJmsConfiguration.java | // Path: jms-base/src/main/java/me/chanjar/jms/base/lifecycle/ConnectionFactoryLifeCycleContainer.java
// public class ConnectionFactoryLifeCycleContainer implements SmartLifecycle {
//
// private static final Logger LOGGER = LoggerFactory.getLogger(ConnectionLifeCycleContainer.class);
//
// private volatile boolean running;
//
// private final Object monitor = new Object();
//
// private final ConnectionFactory connectionFactory;
//
// public ConnectionFactoryLifeCycleContainer(ConnectionFactory connectionFactory) {
// Assert.notNull(connectionFactory, "connectionFactory must not be null");
// this.connectionFactory = connectionFactory;
// }
//
// @Override
// public boolean isAutoStartup() {
// return true;
// }
//
// @Override
// public void stop(Runnable callback) {
// stop();
// callback.run();
// }
//
// @Override
// public void start() {
//
// LOGGER.info("Manage life cycle of " + this.connectionFactory.toString());
// this.running = true;
//
// }
//
// @Override
// public void stop() {
//
// synchronized (this.monitor) {
//
// if (this.running) {
//
// try {
//
// if (this.connectionFactory instanceof AutoCloseable) {
// ((AutoCloseable) this.connectionFactory).close();
// LOGGER.info("Close connection factory {}", this.connectionFactory.toString());
// } else {
// LOGGER.info("{} doesn't implements AutoCloseable, won't do close.", this.connectionFactory.toString());
// }
//
// } catch (Exception e) {
//
// LOGGER.error("Error happened when closing connection factory: {}", this.connectionFactory.toString());
// LOGGER.error(ExceptionUtils.getStackTrace(e));
//
// } finally {
//
// this.running = false;
//
// }
//
// }
//
// }
//
// }
//
// @Override
// public boolean isRunning() {
// return this.running;
// }
//
// @Override
// public int getPhase() {
// return JmsObjectLifecycleOrderConstants.CONNECTION_FACTORY;
// }
//
// }
//
// Path: jms-base/src/main/java/me/chanjar/jms/base/lifecycle/ConnectionLifeCycleContainer.java
// public class ConnectionLifeCycleContainer implements SmartLifecycle {
//
// private static final Logger LOGGER = LoggerFactory.getLogger(ConnectionLifeCycleContainer.class);
//
// private volatile boolean running;
//
// private final Object monitor = new Object();
//
// private final Connection connection;
//
// public ConnectionLifeCycleContainer(Connection connection) {
// Assert.notNull(connection, "Connection must not be null");
// this.connection = connection;
// }
//
// @Override
// public boolean isAutoStartup() {
// return true;
// }
//
// @Override
// public void stop(Runnable callback) {
// stop();
// callback.run();
// }
//
// @Override
// public void start() {
//
// synchronized (this.monitor) {
// if (!this.running) {
// try {
//
// this.connection.start();
// LOGGER.info("Start connection {}", this.connection.toString());
//
// } catch (Exception e) {
//
// LOGGER.error("Error happened when starting connection: {}", this.connection.toString());
// LOGGER.error(ExceptionUtils.getStackTrace(e));
//
// } finally {
//
// this.running = false;
//
// }
// }
// }
//
// }
//
// @Override
// public void stop() {
//
// synchronized (this.monitor) {
//
// if (this.running) {
//
// try {
//
// this.connection.stop();
// this.connection.close();
// this.running = false;
//
// LOGGER.info("Close connection {}", this.connection.toString());
//
// monitor.wait(1000L);
//
// } catch (JMSException e) {
//
// LOGGER.error("Error happened when closing connection: {}", this.connection.toString());
// throw new JmsConnectionCloseException(e);
//
// } catch (InterruptedException e) {
//
// LOGGER.error("Error happened when closing connection: {}", this.connection.toString());
// throw new JmsConnectionCloseException(e);
//
// }
//
// }
//
// }
//
// }
//
// @Override
// public boolean isRunning() {
// return this.running;
// }
//
// @Override
// public int getPhase() {
// return JmsObjectLifecycleOrderConstants.CONNECTION;
// }
//
// public static class JmsConnectionCloseException extends RuntimeException {
// private static final long serialVersionUID = -5707901053880272357L;
//
// public JmsConnectionCloseException(Throwable cause) {
// super(cause);
// }
// }
//
// }
| import me.chanjar.jms.base.lifecycle.ConnectionFactoryLifeCycleContainer;
import me.chanjar.jms.base.lifecycle.ConnectionLifeCycleContainer;
import org.apache.activemq.artemis.api.jms.ActiveMQJMSClient;
import org.apache.activemq.artemis.uri.ConnectionFactoryParser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import javax.jms.Connection;
import javax.jms.ConnectionFactory;
import javax.jms.Queue;
import javax.jms.Topic; | package me.chanjar.jms.base.config;
@Configuration
@EnableConfigurationProperties(ArtemisJmsConfiguration.ArtemisProperties.class)
public class ArtemisJmsConfiguration {
@Autowired
private ArtemisProperties artemisProperties;
@Bean
public ConnectionFactory defaultConnectionFactory() throws Exception {
ConnectionFactoryParser parser = new ConnectionFactoryParser();
return parser.newObject(parser.expandURI(artemisProperties.getUri()), "defaultConnectionFactory");
}
@Bean
public ConnectionFactoryLifeCycleContainer defaultConnectionFactoryLifeCycleContainer() throws Exception {
return new ConnectionFactoryLifeCycleContainer(defaultConnectionFactory());
}
@Bean
public Connection defaultConnection() throws Exception {
return defaultConnectionFactory()
.createConnection(artemisProperties.getUsername(), artemisProperties.getPassword());
}
@Bean | // Path: jms-base/src/main/java/me/chanjar/jms/base/lifecycle/ConnectionFactoryLifeCycleContainer.java
// public class ConnectionFactoryLifeCycleContainer implements SmartLifecycle {
//
// private static final Logger LOGGER = LoggerFactory.getLogger(ConnectionLifeCycleContainer.class);
//
// private volatile boolean running;
//
// private final Object monitor = new Object();
//
// private final ConnectionFactory connectionFactory;
//
// public ConnectionFactoryLifeCycleContainer(ConnectionFactory connectionFactory) {
// Assert.notNull(connectionFactory, "connectionFactory must not be null");
// this.connectionFactory = connectionFactory;
// }
//
// @Override
// public boolean isAutoStartup() {
// return true;
// }
//
// @Override
// public void stop(Runnable callback) {
// stop();
// callback.run();
// }
//
// @Override
// public void start() {
//
// LOGGER.info("Manage life cycle of " + this.connectionFactory.toString());
// this.running = true;
//
// }
//
// @Override
// public void stop() {
//
// synchronized (this.monitor) {
//
// if (this.running) {
//
// try {
//
// if (this.connectionFactory instanceof AutoCloseable) {
// ((AutoCloseable) this.connectionFactory).close();
// LOGGER.info("Close connection factory {}", this.connectionFactory.toString());
// } else {
// LOGGER.info("{} doesn't implements AutoCloseable, won't do close.", this.connectionFactory.toString());
// }
//
// } catch (Exception e) {
//
// LOGGER.error("Error happened when closing connection factory: {}", this.connectionFactory.toString());
// LOGGER.error(ExceptionUtils.getStackTrace(e));
//
// } finally {
//
// this.running = false;
//
// }
//
// }
//
// }
//
// }
//
// @Override
// public boolean isRunning() {
// return this.running;
// }
//
// @Override
// public int getPhase() {
// return JmsObjectLifecycleOrderConstants.CONNECTION_FACTORY;
// }
//
// }
//
// Path: jms-base/src/main/java/me/chanjar/jms/base/lifecycle/ConnectionLifeCycleContainer.java
// public class ConnectionLifeCycleContainer implements SmartLifecycle {
//
// private static final Logger LOGGER = LoggerFactory.getLogger(ConnectionLifeCycleContainer.class);
//
// private volatile boolean running;
//
// private final Object monitor = new Object();
//
// private final Connection connection;
//
// public ConnectionLifeCycleContainer(Connection connection) {
// Assert.notNull(connection, "Connection must not be null");
// this.connection = connection;
// }
//
// @Override
// public boolean isAutoStartup() {
// return true;
// }
//
// @Override
// public void stop(Runnable callback) {
// stop();
// callback.run();
// }
//
// @Override
// public void start() {
//
// synchronized (this.monitor) {
// if (!this.running) {
// try {
//
// this.connection.start();
// LOGGER.info("Start connection {}", this.connection.toString());
//
// } catch (Exception e) {
//
// LOGGER.error("Error happened when starting connection: {}", this.connection.toString());
// LOGGER.error(ExceptionUtils.getStackTrace(e));
//
// } finally {
//
// this.running = false;
//
// }
// }
// }
//
// }
//
// @Override
// public void stop() {
//
// synchronized (this.monitor) {
//
// if (this.running) {
//
// try {
//
// this.connection.stop();
// this.connection.close();
// this.running = false;
//
// LOGGER.info("Close connection {}", this.connection.toString());
//
// monitor.wait(1000L);
//
// } catch (JMSException e) {
//
// LOGGER.error("Error happened when closing connection: {}", this.connection.toString());
// throw new JmsConnectionCloseException(e);
//
// } catch (InterruptedException e) {
//
// LOGGER.error("Error happened when closing connection: {}", this.connection.toString());
// throw new JmsConnectionCloseException(e);
//
// }
//
// }
//
// }
//
// }
//
// @Override
// public boolean isRunning() {
// return this.running;
// }
//
// @Override
// public int getPhase() {
// return JmsObjectLifecycleOrderConstants.CONNECTION;
// }
//
// public static class JmsConnectionCloseException extends RuntimeException {
// private static final long serialVersionUID = -5707901053880272357L;
//
// public JmsConnectionCloseException(Throwable cause) {
// super(cause);
// }
// }
//
// }
// Path: jms-base/src/main/java/me/chanjar/jms/base/config/ArtemisJmsConfiguration.java
import me.chanjar.jms.base.lifecycle.ConnectionFactoryLifeCycleContainer;
import me.chanjar.jms.base.lifecycle.ConnectionLifeCycleContainer;
import org.apache.activemq.artemis.api.jms.ActiveMQJMSClient;
import org.apache.activemq.artemis.uri.ConnectionFactoryParser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import javax.jms.Connection;
import javax.jms.ConnectionFactory;
import javax.jms.Queue;
import javax.jms.Topic;
package me.chanjar.jms.base.config;
@Configuration
@EnableConfigurationProperties(ArtemisJmsConfiguration.ArtemisProperties.class)
public class ArtemisJmsConfiguration {
@Autowired
private ArtemisProperties artemisProperties;
@Bean
public ConnectionFactory defaultConnectionFactory() throws Exception {
ConnectionFactoryParser parser = new ConnectionFactoryParser();
return parser.newObject(parser.expandURI(artemisProperties.getUri()), "defaultConnectionFactory");
}
@Bean
public ConnectionFactoryLifeCycleContainer defaultConnectionFactoryLifeCycleContainer() throws Exception {
return new ConnectionFactoryLifeCycleContainer(defaultConnectionFactory());
}
@Bean
public Connection defaultConnection() throws Exception {
return defaultConnectionFactory()
.createConnection(artemisProperties.getUsername(), artemisProperties.getPassword());
}
@Bean | public ConnectionLifeCycleContainer defaultConnectionLifeCycleContainer() throws Exception { |
chanjarster/artemis-disruptor-miaosha | jms-base/src/main/java/me/chanjar/jms/base/utils/ArtemisMessageDtoDupMessageDetectStrategy.java | // Path: jms-base/src/main/java/me/chanjar/jms/base/msg/MessageDto.java
// public abstract class MessageDto implements Serializable {
//
// private static final long serialVersionUID = 9003442515985424079L;
// /**
// * 应该保证全局唯一, 用uuid
// */
// protected final String id;
//
// public MessageDto() {
// this.id = StrongUuidGenerator.getNextId();
// }
//
// public String getId() {
// return id;
// }
//
// }
//
// Path: jms-base/src/main/java/me/chanjar/jms/base/utils/DupMessageDetectStrategy.java
// public interface DupMessageDetectStrategy {
//
// void setId(Message message, Object payload) throws JMSException;
// }
| import me.chanjar.jms.base.msg.MessageDto;
import me.chanjar.jms.base.utils.DupMessageDetectStrategy;
import javax.jms.JMSException;
import javax.jms.Message; | package me.chanjar.jms.base.utils;
/**
* 适用于Artemis, {@link MessageDto}的消息重复检测策略 <br>
* https://activemq.apache.org/artemis/docs/1.3.0/duplicate-detection.html#using-duplicate-detection-for-message-sending <br>
*/
public class ArtemisMessageDtoDupMessageDetectStrategy implements DupMessageDetectStrategy {
private static final String HDR_DUPLICATE_DETECTION_ID =
org.apache.activemq.artemis.api.core.Message.HDR_DUPLICATE_DETECTION_ID.toString();
@Override
public void setId(Message message, Object payload) throws JMSException { | // Path: jms-base/src/main/java/me/chanjar/jms/base/msg/MessageDto.java
// public abstract class MessageDto implements Serializable {
//
// private static final long serialVersionUID = 9003442515985424079L;
// /**
// * 应该保证全局唯一, 用uuid
// */
// protected final String id;
//
// public MessageDto() {
// this.id = StrongUuidGenerator.getNextId();
// }
//
// public String getId() {
// return id;
// }
//
// }
//
// Path: jms-base/src/main/java/me/chanjar/jms/base/utils/DupMessageDetectStrategy.java
// public interface DupMessageDetectStrategy {
//
// void setId(Message message, Object payload) throws JMSException;
// }
// Path: jms-base/src/main/java/me/chanjar/jms/base/utils/ArtemisMessageDtoDupMessageDetectStrategy.java
import me.chanjar.jms.base.msg.MessageDto;
import me.chanjar.jms.base.utils.DupMessageDetectStrategy;
import javax.jms.JMSException;
import javax.jms.Message;
package me.chanjar.jms.base.utils;
/**
* 适用于Artemis, {@link MessageDto}的消息重复检测策略 <br>
* https://activemq.apache.org/artemis/docs/1.3.0/duplicate-detection.html#using-duplicate-detection-for-message-sending <br>
*/
public class ArtemisMessageDtoDupMessageDetectStrategy implements DupMessageDetectStrategy {
private static final String HDR_DUPLICATE_DETECTION_ID =
org.apache.activemq.artemis.api.core.Message.HDR_DUPLICATE_DETECTION_ID.toString();
@Override
public void setId(Message message, Object payload) throws JMSException { | message.setStringProperty(HDR_DUPLICATE_DETECTION_ID, ((MessageDto) payload).getId()); |
chanjarster/artemis-disruptor-miaosha | jms-server/src/main/java/me/chanjar/jms/server/command/infras/disruptor/CommandEventDbHandler.java | // Path: jms-server/src/main/java/me/chanjar/jms/server/command/infras/Command.java
// public abstract class Command implements Serializable {
//
// private static final long serialVersionUID = -2463630580877588711L;
// protected final String id;
//
// protected final String requestId;
//
// /**
// * Command来源的requestId
// *
// * @param requestId
// */
// public Command(String requestId) {
// this.id = StrongUuidGenerator.getNextId();
// this.requestId = requestId;
// }
//
// /**
// * 全局唯一Id, uuid
// *
// * @return
// */
// public String getId() {
// return id;
// }
//
// /**
// * 对应的{@link RequestDto#id}
// *
// * @return
// */
// public String getRequestId() {
// return requestId;
// }
// }
//
// Path: jms-server/src/main/java/me/chanjar/jms/server/command/infras/CommandBuffer.java
// public interface CommandBuffer<T extends Command> {
//
// /**
// * Buffer是否已经满了
// *
// * @return
// */
// boolean hasRemaining();
//
// /**
// * 放入Command
// *
// * @param command
// */
// void put(T command);
//
// /**
// * 清空缓存
// */
// void clear();
//
// /**
// * 获得{@link Command}
// *
// * @return
// */
// List<T> get();
//
// }
//
// Path: jms-server/src/main/java/me/chanjar/jms/server/command/infras/CommandExecutor.java
// public interface CommandExecutor<T extends CommandBuffer> {
//
// void execute(T commandBuffer);
//
// }
| import com.lmax.disruptor.EventHandler;
import me.chanjar.jms.server.command.infras.Command;
import me.chanjar.jms.server.command.infras.CommandBuffer;
import me.chanjar.jms.server.command.infras.CommandExecutor; | package me.chanjar.jms.server.command.infras.disruptor;
public class CommandEventDbHandler<T extends Command> implements EventHandler<CommandEvent<T>> {
private final CommandBuffer<T> commandBuffer;
| // Path: jms-server/src/main/java/me/chanjar/jms/server/command/infras/Command.java
// public abstract class Command implements Serializable {
//
// private static final long serialVersionUID = -2463630580877588711L;
// protected final String id;
//
// protected final String requestId;
//
// /**
// * Command来源的requestId
// *
// * @param requestId
// */
// public Command(String requestId) {
// this.id = StrongUuidGenerator.getNextId();
// this.requestId = requestId;
// }
//
// /**
// * 全局唯一Id, uuid
// *
// * @return
// */
// public String getId() {
// return id;
// }
//
// /**
// * 对应的{@link RequestDto#id}
// *
// * @return
// */
// public String getRequestId() {
// return requestId;
// }
// }
//
// Path: jms-server/src/main/java/me/chanjar/jms/server/command/infras/CommandBuffer.java
// public interface CommandBuffer<T extends Command> {
//
// /**
// * Buffer是否已经满了
// *
// * @return
// */
// boolean hasRemaining();
//
// /**
// * 放入Command
// *
// * @param command
// */
// void put(T command);
//
// /**
// * 清空缓存
// */
// void clear();
//
// /**
// * 获得{@link Command}
// *
// * @return
// */
// List<T> get();
//
// }
//
// Path: jms-server/src/main/java/me/chanjar/jms/server/command/infras/CommandExecutor.java
// public interface CommandExecutor<T extends CommandBuffer> {
//
// void execute(T commandBuffer);
//
// }
// Path: jms-server/src/main/java/me/chanjar/jms/server/command/infras/disruptor/CommandEventDbHandler.java
import com.lmax.disruptor.EventHandler;
import me.chanjar.jms.server.command.infras.Command;
import me.chanjar.jms.server.command.infras.CommandBuffer;
import me.chanjar.jms.server.command.infras.CommandExecutor;
package me.chanjar.jms.server.command.infras.disruptor;
public class CommandEventDbHandler<T extends Command> implements EventHandler<CommandEvent<T>> {
private final CommandBuffer<T> commandBuffer;
| private final CommandExecutor commandExecutor; |
palaima/DebugDrawer | debugdrawer-no-op/src/main/java/io/palaima/debugdrawer/DebugDrawer.java | // Path: debugdrawer-base/src/main/java/io/palaima/debugdrawer/base/DebugModule.java
// public interface DebugModule {
//
// /**
// * Creates module view
// */
// @NonNull
// View onCreateView(@NonNull final LayoutInflater inflater, @NonNull final ViewGroup parent);
//
// /**
// * Override this method if you need to refresh
// * some information when drawer is opened
// */
// void onOpened();
//
// /**
// * Override this method if you need to stop
// * some actions when drawer is closed
// */
// void onClosed();
//
// /**
// * Override this method if you need to start
// * some processes
// */
// void onResume();
//
// /**
// * Override this method if you need to do
// * some clean up
// */
// void onPause();
//
// /**
// * Override this method if you need to start
// * some processes that would be killed when
// * onStop() is called
// * E.g. register receivers
// */
// void onStart();
//
// /**
// * Override this method if you need to do
// * some clean up when activity goes to foreground.
// * E.g. unregister receivers
// */
// void onStop();
// }
| import android.app.Activity;
import android.graphics.drawable.Drawable;
import android.support.annotation.DrawableRes;
import android.support.annotation.IntegerRes;
import android.support.annotation.StyleRes;
import android.support.v4.widget.DrawerLayout;
import android.view.ViewGroup;
import io.palaima.debugdrawer.base.DebugModule; |
/**
* Set the background drawable for the Slider.
* This is the view containing the list.
*/
public Builder backgroundDrawable(Drawable sliderBackgroundDrawable) {
return this;
}
/**
* Set the background drawable for the Slider from a Resource.
* This is the view containing the list.
*/
public Builder backgroundDrawableRes(@DrawableRes int sliderBackgroundDrawableRes) {
return this;
}
public Builder setDrawerListener(DrawerLayout.DrawerListener onDrawerListener) {
return this;
}
public Builder withTheme(@StyleRes int themeRes) {
return this;
}
/**
* Add a initial DrawerItem or a DrawerItem Array for the Drawer
*/ | // Path: debugdrawer-base/src/main/java/io/palaima/debugdrawer/base/DebugModule.java
// public interface DebugModule {
//
// /**
// * Creates module view
// */
// @NonNull
// View onCreateView(@NonNull final LayoutInflater inflater, @NonNull final ViewGroup parent);
//
// /**
// * Override this method if you need to refresh
// * some information when drawer is opened
// */
// void onOpened();
//
// /**
// * Override this method if you need to stop
// * some actions when drawer is closed
// */
// void onClosed();
//
// /**
// * Override this method if you need to start
// * some processes
// */
// void onResume();
//
// /**
// * Override this method if you need to do
// * some clean up
// */
// void onPause();
//
// /**
// * Override this method if you need to start
// * some processes that would be killed when
// * onStop() is called
// * E.g. register receivers
// */
// void onStart();
//
// /**
// * Override this method if you need to do
// * some clean up when activity goes to foreground.
// * E.g. unregister receivers
// */
// void onStop();
// }
// Path: debugdrawer-no-op/src/main/java/io/palaima/debugdrawer/DebugDrawer.java
import android.app.Activity;
import android.graphics.drawable.Drawable;
import android.support.annotation.DrawableRes;
import android.support.annotation.IntegerRes;
import android.support.annotation.StyleRes;
import android.support.v4.widget.DrawerLayout;
import android.view.ViewGroup;
import io.palaima.debugdrawer.base.DebugModule;
/**
* Set the background drawable for the Slider.
* This is the view containing the list.
*/
public Builder backgroundDrawable(Drawable sliderBackgroundDrawable) {
return this;
}
/**
* Set the background drawable for the Slider from a Resource.
* This is the view containing the list.
*/
public Builder backgroundDrawableRes(@DrawableRes int sliderBackgroundDrawableRes) {
return this;
}
public Builder setDrawerListener(DrawerLayout.DrawerListener onDrawerListener) {
return this;
}
public Builder withTheme(@StyleRes int themeRes) {
return this;
}
/**
* Add a initial DrawerItem or a DrawerItem Array for the Drawer
*/ | public Builder modules(DebugModule... drawerItems) { |
palaima/DebugDrawer | app/src/main/java/io/palaima/debugdrawer/app/DebugDrawerApplication.java | // Path: debugdrawer-timber/src/main/java/io/palaima/debugdrawer/timber/data/LumberYard.java
// public class LumberYard {
//
// private static final boolean HAS_TIMBER;
//
// static {
// boolean hasDependency;
//
// try {
// Class.forName("timber.log.Timber");
// hasDependency = true;
// } catch (ClassNotFoundException e) {
// hasDependency = false;
// }
//
// HAS_TIMBER = hasDependency;
// }
//
// private static final int BUFFER_SIZE = 200;
//
// private static final DateFormat FILENAME_DATE = new SimpleDateFormat("yyyy-MM-dd HHmm a", Locale.US);
// private static final DateFormat LOG_DATE_PATTERN = new SimpleDateFormat("MM-dd HH:mm:ss.S", Locale.US);
//
// private static final String LOG_FILE_END = ".log";
//
// private static LumberYard sInstance;
//
// private final Context context;
//
// private final Deque<LogEntry> entries = new ArrayDeque<>(BUFFER_SIZE + 1);
//
// private OnLogListener onLogListener;
//
// public LumberYard(@NonNull Context context) {
// if (!HAS_TIMBER) {
// throw new RuntimeException("Timber dependency is not found");
// }
// this.context = context.getApplicationContext();
// }
//
// public static LumberYard getInstance(Context context) {
// if (sInstance == null) {
// sInstance = new LumberYard(context);
// }
//
// return sInstance;
// }
//
// public Timber.Tree tree() {
// return new Timber.DebugTree() {
// @Override
// protected void log(int priority, String tag, String message, Throwable t) {
// addEntry(new LogEntry(priority, tag, message, LOG_DATE_PATTERN.format(Calendar.getInstance().getTime())));
// }
// };
// }
//
// public void setOnLogListener(OnLogListener onLogListener) {
// this.onLogListener = onLogListener;
// }
//
// private synchronized void addEntry(LogEntry entry) {
// entries.addLast(entry);
//
// if (entries.size() > BUFFER_SIZE) {
// entries.removeFirst();
// }
//
// onLog(entry);
// }
//
// public List<LogEntry> bufferedLogs() {
// return new ArrayList<>(entries);
// }
//
// /**
// * Save the current logs to disk.
// */
// public void save(OnSaveLogListener listener) {
// File dir = getLogDir();
//
// if (dir == null) {
// listener.onError("Can't save logs. External storage is not mounted. " +
// "Check android.permission.WRITE_EXTERNAL_STORAGE permission");
// return;
// }
//
// FileWriter fileWriter = null;
//
// try {
// File output = new File(dir, getLogFileName());
// fileWriter = new FileWriter(output, true);
//
// List<LogEntry> entries = bufferedLogs();
// for (LogEntry entry : entries) {
// fileWriter.write(entry.prettyPrint() + "\n");
// }
//
// listener.onSave(output);
//
// } catch (IOException e) {
// listener.onError(e.getMessage());
// e.printStackTrace();
//
// } finally {
// if (fileWriter != null) {
// try {
// fileWriter.close();
// } catch (IOException e) {
// listener.onError(e.getMessage());
// e.printStackTrace();
// }
// }
// }
// }
//
// public void cleanUp() {
// File dir = getLogDir();
// if (dir != null) {
// File[] files = dir.listFiles();
// if (files != null) {
// for (File file : files) {
// if (file.getName().endsWith(LOG_FILE_END)) {
// file.delete();
// }
// }
// }
// }
// }
//
// private File getLogDir() {
// return context.getExternalFilesDir(null);
// }
//
// private void onLog(LogEntry entry) {
// if (onLogListener != null) {
// onLogListener.onLog(entry);
// }
// }
//
// private String getLogFileName() {
// String pattern = "%s%s";
// String currentDate = FILENAME_DATE.format(Calendar.getInstance().getTime());
//
// return String.format(pattern, currentDate, LOG_FILE_END);
// }
//
// public interface OnSaveLogListener {
// void onSave(File file);
//
// void onError(String message);
// }
//
// public interface OnLogListener {
// void onLog(LogEntry logEntry);
// }
// }
| import android.app.Application;
import android.support.multidex.MultiDex;
import com.squareup.leakcanary.LeakCanary;
import io.palaima.debugdrawer.timber.data.LumberYard;
import timber.log.Timber; | package io.palaima.debugdrawer.app;
public class DebugDrawerApplication extends Application {
@Override
public void onCreate() {
super.onCreate();
MultiDex.install(this);
LeakCanary.install(this);
| // Path: debugdrawer-timber/src/main/java/io/palaima/debugdrawer/timber/data/LumberYard.java
// public class LumberYard {
//
// private static final boolean HAS_TIMBER;
//
// static {
// boolean hasDependency;
//
// try {
// Class.forName("timber.log.Timber");
// hasDependency = true;
// } catch (ClassNotFoundException e) {
// hasDependency = false;
// }
//
// HAS_TIMBER = hasDependency;
// }
//
// private static final int BUFFER_SIZE = 200;
//
// private static final DateFormat FILENAME_DATE = new SimpleDateFormat("yyyy-MM-dd HHmm a", Locale.US);
// private static final DateFormat LOG_DATE_PATTERN = new SimpleDateFormat("MM-dd HH:mm:ss.S", Locale.US);
//
// private static final String LOG_FILE_END = ".log";
//
// private static LumberYard sInstance;
//
// private final Context context;
//
// private final Deque<LogEntry> entries = new ArrayDeque<>(BUFFER_SIZE + 1);
//
// private OnLogListener onLogListener;
//
// public LumberYard(@NonNull Context context) {
// if (!HAS_TIMBER) {
// throw new RuntimeException("Timber dependency is not found");
// }
// this.context = context.getApplicationContext();
// }
//
// public static LumberYard getInstance(Context context) {
// if (sInstance == null) {
// sInstance = new LumberYard(context);
// }
//
// return sInstance;
// }
//
// public Timber.Tree tree() {
// return new Timber.DebugTree() {
// @Override
// protected void log(int priority, String tag, String message, Throwable t) {
// addEntry(new LogEntry(priority, tag, message, LOG_DATE_PATTERN.format(Calendar.getInstance().getTime())));
// }
// };
// }
//
// public void setOnLogListener(OnLogListener onLogListener) {
// this.onLogListener = onLogListener;
// }
//
// private synchronized void addEntry(LogEntry entry) {
// entries.addLast(entry);
//
// if (entries.size() > BUFFER_SIZE) {
// entries.removeFirst();
// }
//
// onLog(entry);
// }
//
// public List<LogEntry> bufferedLogs() {
// return new ArrayList<>(entries);
// }
//
// /**
// * Save the current logs to disk.
// */
// public void save(OnSaveLogListener listener) {
// File dir = getLogDir();
//
// if (dir == null) {
// listener.onError("Can't save logs. External storage is not mounted. " +
// "Check android.permission.WRITE_EXTERNAL_STORAGE permission");
// return;
// }
//
// FileWriter fileWriter = null;
//
// try {
// File output = new File(dir, getLogFileName());
// fileWriter = new FileWriter(output, true);
//
// List<LogEntry> entries = bufferedLogs();
// for (LogEntry entry : entries) {
// fileWriter.write(entry.prettyPrint() + "\n");
// }
//
// listener.onSave(output);
//
// } catch (IOException e) {
// listener.onError(e.getMessage());
// e.printStackTrace();
//
// } finally {
// if (fileWriter != null) {
// try {
// fileWriter.close();
// } catch (IOException e) {
// listener.onError(e.getMessage());
// e.printStackTrace();
// }
// }
// }
// }
//
// public void cleanUp() {
// File dir = getLogDir();
// if (dir != null) {
// File[] files = dir.listFiles();
// if (files != null) {
// for (File file : files) {
// if (file.getName().endsWith(LOG_FILE_END)) {
// file.delete();
// }
// }
// }
// }
// }
//
// private File getLogDir() {
// return context.getExternalFilesDir(null);
// }
//
// private void onLog(LogEntry entry) {
// if (onLogListener != null) {
// onLogListener.onLog(entry);
// }
// }
//
// private String getLogFileName() {
// String pattern = "%s%s";
// String currentDate = FILENAME_DATE.format(Calendar.getInstance().getTime());
//
// return String.format(pattern, currentDate, LOG_FILE_END);
// }
//
// public interface OnSaveLogListener {
// void onSave(File file);
//
// void onError(String message);
// }
//
// public interface OnLogListener {
// void onLog(LogEntry logEntry);
// }
// }
// Path: app/src/main/java/io/palaima/debugdrawer/app/DebugDrawerApplication.java
import android.app.Application;
import android.support.multidex.MultiDex;
import com.squareup.leakcanary.LeakCanary;
import io.palaima.debugdrawer.timber.data.LumberYard;
import timber.log.Timber;
package io.palaima.debugdrawer.app;
public class DebugDrawerApplication extends Application {
@Override
public void onCreate() {
super.onCreate();
MultiDex.install(this);
LeakCanary.install(this);
| LumberYard lumberYard = LumberYard.getInstance(this); |
palaima/DebugDrawer | debugdrawer-view-no-op/src/main/java/io/palaima/debugdrawer/view/DebugView.java | // Path: debugdrawer-base/src/main/java/io/palaima/debugdrawer/base/DebugModule.java
// public interface DebugModule {
//
// /**
// * Creates module view
// */
// @NonNull
// View onCreateView(@NonNull final LayoutInflater inflater, @NonNull final ViewGroup parent);
//
// /**
// * Override this method if you need to refresh
// * some information when drawer is opened
// */
// void onOpened();
//
// /**
// * Override this method if you need to stop
// * some actions when drawer is closed
// */
// void onClosed();
//
// /**
// * Override this method if you need to start
// * some processes
// */
// void onResume();
//
// /**
// * Override this method if you need to do
// * some clean up
// */
// void onPause();
//
// /**
// * Override this method if you need to start
// * some processes that would be killed when
// * onStop() is called
// * E.g. register receivers
// */
// void onStart();
//
// /**
// * Override this method if you need to do
// * some clean up when activity goes to foreground.
// * E.g. unregister receivers
// */
// void onStop();
// }
| import android.content.Context;
import android.util.AttributeSet;
import android.widget.LinearLayout;
import io.palaima.debugdrawer.base.DebugModule; | package io.palaima.debugdrawer.view;
public class DebugView extends LinearLayout {
public DebugView(Context context) {
super(context);
setOrientation(VERTICAL);
}
public DebugView(Context context, AttributeSet attrs) {
super(context, attrs);
setOrientation(VERTICAL);
}
public DebugView(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
setOrientation(VERTICAL);
}
/**
* Calls modules {@link DebugModule#onResume()} method
*/
public void onResume() {
}
/**
* Calls modules {@link DebugModule#onPause()} method
*/
public void onPause() {
}
/**
* Starts all modules and calls their {@link DebugModule#onStart()} method
*/
public void onStart() {
}
/**
* Removes all modules and calls their {@link DebugModule#onStop()} method
*/
public void onStop() {
}
| // Path: debugdrawer-base/src/main/java/io/palaima/debugdrawer/base/DebugModule.java
// public interface DebugModule {
//
// /**
// * Creates module view
// */
// @NonNull
// View onCreateView(@NonNull final LayoutInflater inflater, @NonNull final ViewGroup parent);
//
// /**
// * Override this method if you need to refresh
// * some information when drawer is opened
// */
// void onOpened();
//
// /**
// * Override this method if you need to stop
// * some actions when drawer is closed
// */
// void onClosed();
//
// /**
// * Override this method if you need to start
// * some processes
// */
// void onResume();
//
// /**
// * Override this method if you need to do
// * some clean up
// */
// void onPause();
//
// /**
// * Override this method if you need to start
// * some processes that would be killed when
// * onStop() is called
// * E.g. register receivers
// */
// void onStart();
//
// /**
// * Override this method if you need to do
// * some clean up when activity goes to foreground.
// * E.g. unregister receivers
// */
// void onStop();
// }
// Path: debugdrawer-view-no-op/src/main/java/io/palaima/debugdrawer/view/DebugView.java
import android.content.Context;
import android.util.AttributeSet;
import android.widget.LinearLayout;
import io.palaima.debugdrawer.base.DebugModule;
package io.palaima.debugdrawer.view;
public class DebugView extends LinearLayout {
public DebugView(Context context) {
super(context);
setOrientation(VERTICAL);
}
public DebugView(Context context, AttributeSet attrs) {
super(context, attrs);
setOrientation(VERTICAL);
}
public DebugView(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
setOrientation(VERTICAL);
}
/**
* Calls modules {@link DebugModule#onResume()} method
*/
public void onResume() {
}
/**
* Calls modules {@link DebugModule#onPause()} method
*/
public void onPause() {
}
/**
* Starts all modules and calls their {@link DebugModule#onStart()} method
*/
public void onStart() {
}
/**
* Removes all modules and calls their {@link DebugModule#onStop()} method
*/
public void onStop() {
}
| public void modules(DebugModule... drawerItems) { |
palaima/DebugDrawer | debugdrawer-timber/src/main/java/io/palaima/debugdrawer/timber/TimberModule.java | // Path: debugdrawer-base/src/main/java/io/palaima/debugdrawer/base/DebugModuleAdapter.java
// public abstract class DebugModuleAdapter implements DebugModule {
//
// @Override
// public void onOpened() {
// // do nothing
// }
//
// @Override
// public void onClosed() {
// // do nothing
// }
//
// @Override
// public void onResume() {
// // do nothing
// }
//
// @Override
// public void onPause() {
// // do nothing
// }
//
// @Override
// public void onStart() {
// // do nothing
// }
//
// @Override
// public void onStop() {
// // do nothing
// }
// }
//
// Path: debugdrawer-timber/src/main/java/io/palaima/debugdrawer/timber/ui/LogDialog.java
// public class LogDialog extends AlertDialog {
//
// private final LogAdapter adapter;
//
// private final Handler handler = new Handler(Looper.getMainLooper());
//
// public LogDialog(Context context) {
// super(context, R.style.Theme_AppCompat);
//
// adapter = new LogAdapter();
//
// ListView listView = new ListView(context);
// listView.setTranscriptMode(ListView.TRANSCRIPT_MODE_NORMAL);
// listView.setAdapter(adapter);
//
// setTitle("Logs");
// setView(listView);
// setButton(BUTTON_NEGATIVE, "Close", new DialogInterface.OnClickListener() {
// @Override
// public void onClick(DialogInterface dialog, int which) {
// /* no-op */
// }
// });
// setButton(BUTTON_POSITIVE, "Share", new DialogInterface.OnClickListener() {
// @Override
// public void onClick(DialogInterface dialog, int which) {
// share();
// }
// });
// }
//
// @Override
// protected void onStart() {
// super.onStart();
//
// LumberYard lumberYard = LumberYard.getInstance(getContext());
//
// adapter.setLogs(lumberYard.bufferedLogs());
//
// lumberYard.setOnLogListener(new LumberYard.OnLogListener() {
// @Override
// public void onLog(LogEntry logEntry) {
//
// addLogEntry(logEntry);
// }
// });
// }
//
// private void addLogEntry(final LogEntry logEntry) {
// handler.post(new Runnable() {
// @Override
// public void run() {
// adapter.addLog(logEntry);
// }
// });
// }
//
// @Override
// protected void onStop() {
// super.onStop();
// LumberYard.getInstance(getContext()).setOnLogListener(null);
// }
//
// private void share() {
// LumberYard.getInstance(getContext())
// .save(new LumberYard.OnSaveLogListener() {
// @Override
// public void onSave(File file) {
// Intent sendIntent = new Intent(Intent.ACTION_SEND);
// sendIntent.setType("text/plain");
// sendIntent.putExtra(Intent.EXTRA_STREAM, Uri.fromFile(file));
// Intents.maybeStartActivity(getContext(), sendIntent);
// }
//
// @Override
// public void onError(String message) {
// Toast.makeText(getContext(), message, Toast.LENGTH_LONG).show();
// }
// });
// }
// }
| import android.support.annotation.NonNull;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import io.palaima.debugdrawer.base.DebugModuleAdapter;
import io.palaima.debugdrawer.timber.ui.LogDialog; | package io.palaima.debugdrawer.timber;
public class TimberModule extends DebugModuleAdapter {
@NonNull
@Override
public View onCreateView(@NonNull LayoutInflater inflater, @NonNull final ViewGroup parent) {
final View view = inflater.inflate(R.layout.dd_debug_drawer_module_log, parent, false);
view.findViewById(R.id.dd_button_log).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) { | // Path: debugdrawer-base/src/main/java/io/palaima/debugdrawer/base/DebugModuleAdapter.java
// public abstract class DebugModuleAdapter implements DebugModule {
//
// @Override
// public void onOpened() {
// // do nothing
// }
//
// @Override
// public void onClosed() {
// // do nothing
// }
//
// @Override
// public void onResume() {
// // do nothing
// }
//
// @Override
// public void onPause() {
// // do nothing
// }
//
// @Override
// public void onStart() {
// // do nothing
// }
//
// @Override
// public void onStop() {
// // do nothing
// }
// }
//
// Path: debugdrawer-timber/src/main/java/io/palaima/debugdrawer/timber/ui/LogDialog.java
// public class LogDialog extends AlertDialog {
//
// private final LogAdapter adapter;
//
// private final Handler handler = new Handler(Looper.getMainLooper());
//
// public LogDialog(Context context) {
// super(context, R.style.Theme_AppCompat);
//
// adapter = new LogAdapter();
//
// ListView listView = new ListView(context);
// listView.setTranscriptMode(ListView.TRANSCRIPT_MODE_NORMAL);
// listView.setAdapter(adapter);
//
// setTitle("Logs");
// setView(listView);
// setButton(BUTTON_NEGATIVE, "Close", new DialogInterface.OnClickListener() {
// @Override
// public void onClick(DialogInterface dialog, int which) {
// /* no-op */
// }
// });
// setButton(BUTTON_POSITIVE, "Share", new DialogInterface.OnClickListener() {
// @Override
// public void onClick(DialogInterface dialog, int which) {
// share();
// }
// });
// }
//
// @Override
// protected void onStart() {
// super.onStart();
//
// LumberYard lumberYard = LumberYard.getInstance(getContext());
//
// adapter.setLogs(lumberYard.bufferedLogs());
//
// lumberYard.setOnLogListener(new LumberYard.OnLogListener() {
// @Override
// public void onLog(LogEntry logEntry) {
//
// addLogEntry(logEntry);
// }
// });
// }
//
// private void addLogEntry(final LogEntry logEntry) {
// handler.post(new Runnable() {
// @Override
// public void run() {
// adapter.addLog(logEntry);
// }
// });
// }
//
// @Override
// protected void onStop() {
// super.onStop();
// LumberYard.getInstance(getContext()).setOnLogListener(null);
// }
//
// private void share() {
// LumberYard.getInstance(getContext())
// .save(new LumberYard.OnSaveLogListener() {
// @Override
// public void onSave(File file) {
// Intent sendIntent = new Intent(Intent.ACTION_SEND);
// sendIntent.setType("text/plain");
// sendIntent.putExtra(Intent.EXTRA_STREAM, Uri.fromFile(file));
// Intents.maybeStartActivity(getContext(), sendIntent);
// }
//
// @Override
// public void onError(String message) {
// Toast.makeText(getContext(), message, Toast.LENGTH_LONG).show();
// }
// });
// }
// }
// Path: debugdrawer-timber/src/main/java/io/palaima/debugdrawer/timber/TimberModule.java
import android.support.annotation.NonNull;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import io.palaima.debugdrawer.base.DebugModuleAdapter;
import io.palaima.debugdrawer.timber.ui.LogDialog;
package io.palaima.debugdrawer.timber;
public class TimberModule extends DebugModuleAdapter {
@NonNull
@Override
public View onCreateView(@NonNull LayoutInflater inflater, @NonNull final ViewGroup parent) {
final View view = inflater.inflate(R.layout.dd_debug_drawer_module_log, parent, false);
view.findViewById(R.id.dd_button_log).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) { | new LogDialog(parent.getContext()).show(); |
passsy/CompositeAndroid | fragment/src/main/java/com/pascalwelsch/compositeandroid/fragment/CompositeFragment.java | // Path: core/src/main/java/com/pascalwelsch/compositeandroid/core/Removable.java
// public interface Removable {
//
// void remove();
// }
//
// Path: core/src/main/java/com/pascalwelsch/compositeandroid/core/SuppressedException.java
// public class SuppressedException extends RuntimeException {
//
// /**
// * Constructs a new {@code RuntimeException} with the current stack trace
// * and the specified cause.
// *
// * @param throwable the cause of this exception.
// */
// public SuppressedException(final Throwable throwable) {
// super(throwable);
// }
// }
| import android.animation.Animator;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.arch.lifecycle.LiveData;
import android.arch.lifecycle.ViewModelStore;
import android.content.Context;
import android.content.Intent;
import android.content.IntentSender;
import android.content.IntentSender.SendIntentException;
import android.content.res.Configuration;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.app.LoaderManager;
import android.support.v4.app.SharedElementCallback;
import android.util.AttributeSet;
import android.view.ContextMenu;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.Animation;
import com.pascalwelsch.compositeandroid.core.Removable;
import com.pascalwelsch.compositeandroid.core.SuppressedException;
import java.io.FileDescriptor;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List; | public void onStop() {
delegate.onStop();
}
@Override
public void onSaveInstanceState(@NonNull Bundle outState) {
delegate.onSaveInstanceState(outState);
}
@Override
public void onDestroyView() {
delegate.onDestroyView();
}
@Override
public void onDestroy() {
delegate.onDestroy();
}
@Override
public void onDetach() {
delegate.onDetach();
}
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions,
@NonNull int[] grantResults) {
delegate.onRequestPermissionsResult(requestCode, permissions, grantResults);
}
| // Path: core/src/main/java/com/pascalwelsch/compositeandroid/core/Removable.java
// public interface Removable {
//
// void remove();
// }
//
// Path: core/src/main/java/com/pascalwelsch/compositeandroid/core/SuppressedException.java
// public class SuppressedException extends RuntimeException {
//
// /**
// * Constructs a new {@code RuntimeException} with the current stack trace
// * and the specified cause.
// *
// * @param throwable the cause of this exception.
// */
// public SuppressedException(final Throwable throwable) {
// super(throwable);
// }
// }
// Path: fragment/src/main/java/com/pascalwelsch/compositeandroid/fragment/CompositeFragment.java
import android.animation.Animator;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.arch.lifecycle.LiveData;
import android.arch.lifecycle.ViewModelStore;
import android.content.Context;
import android.content.Intent;
import android.content.IntentSender;
import android.content.IntentSender.SendIntentException;
import android.content.res.Configuration;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.app.LoaderManager;
import android.support.v4.app.SharedElementCallback;
import android.util.AttributeSet;
import android.view.ContextMenu;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.Animation;
import com.pascalwelsch.compositeandroid.core.Removable;
import com.pascalwelsch.compositeandroid.core.SuppressedException;
import java.io.FileDescriptor;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;
public void onStop() {
delegate.onStop();
}
@Override
public void onSaveInstanceState(@NonNull Bundle outState) {
delegate.onSaveInstanceState(outState);
}
@Override
public void onDestroyView() {
delegate.onDestroyView();
}
@Override
public void onDestroy() {
delegate.onDestroy();
}
@Override
public void onDetach() {
delegate.onDetach();
}
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions,
@NonNull int[] grantResults) {
delegate.onRequestPermissionsResult(requestCode, permissions, grantResults);
}
| public List<Removable> addFragmentPlugins(@NonNull final FragmentPlugin... plugins) { |
passsy/CompositeAndroid | fragment/src/main/java/com/pascalwelsch/compositeandroid/fragment/CompositeFragment.java | // Path: core/src/main/java/com/pascalwelsch/compositeandroid/core/Removable.java
// public interface Removable {
//
// void remove();
// }
//
// Path: core/src/main/java/com/pascalwelsch/compositeandroid/core/SuppressedException.java
// public class SuppressedException extends RuntimeException {
//
// /**
// * Constructs a new {@code RuntimeException} with the current stack trace
// * and the specified cause.
// *
// * @param throwable the cause of this exception.
// */
// public SuppressedException(final Throwable throwable) {
// super(throwable);
// }
// }
| import android.animation.Animator;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.arch.lifecycle.LiveData;
import android.arch.lifecycle.ViewModelStore;
import android.content.Context;
import android.content.Intent;
import android.content.IntentSender;
import android.content.IntentSender.SendIntentException;
import android.content.res.Configuration;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.app.LoaderManager;
import android.support.v4.app.SharedElementCallback;
import android.util.AttributeSet;
import android.view.ContextMenu;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.Animation;
import com.pascalwelsch.compositeandroid.core.Removable;
import com.pascalwelsch.compositeandroid.core.SuppressedException;
import java.io.FileDescriptor;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List; | public boolean shouldShowRequestPermissionRationale(@NonNull String permission) {
return delegate.shouldShowRequestPermissionRationale(permission);
}
@Override
public void startActivity(Intent intent) {
delegate.startActivity(intent);
}
@Override
public void startActivity(Intent intent, @Nullable Bundle options) {
delegate.startActivity(intent, options);
}
@Override
public void startActivityForResult(Intent intent, int requestCode) {
delegate.startActivityForResult(intent, requestCode);
}
@Override
public void startActivityForResult(Intent intent, int requestCode, @Nullable Bundle options) {
delegate.startActivityForResult(intent, requestCode, options);
}
@Override
public void startIntentSenderForResult(IntentSender intent, int requestCode, @Nullable Intent fillInIntent,
int flagsMask, int flagsValues, int extraFlags, Bundle options) throws SendIntentException {
try {
delegate.startIntentSenderForResult(intent, requestCode, fillInIntent, flagsMask, flagsValues, extraFlags,
options); | // Path: core/src/main/java/com/pascalwelsch/compositeandroid/core/Removable.java
// public interface Removable {
//
// void remove();
// }
//
// Path: core/src/main/java/com/pascalwelsch/compositeandroid/core/SuppressedException.java
// public class SuppressedException extends RuntimeException {
//
// /**
// * Constructs a new {@code RuntimeException} with the current stack trace
// * and the specified cause.
// *
// * @param throwable the cause of this exception.
// */
// public SuppressedException(final Throwable throwable) {
// super(throwable);
// }
// }
// Path: fragment/src/main/java/com/pascalwelsch/compositeandroid/fragment/CompositeFragment.java
import android.animation.Animator;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.arch.lifecycle.LiveData;
import android.arch.lifecycle.ViewModelStore;
import android.content.Context;
import android.content.Intent;
import android.content.IntentSender;
import android.content.IntentSender.SendIntentException;
import android.content.res.Configuration;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.app.LoaderManager;
import android.support.v4.app.SharedElementCallback;
import android.util.AttributeSet;
import android.view.ContextMenu;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.Animation;
import com.pascalwelsch.compositeandroid.core.Removable;
import com.pascalwelsch.compositeandroid.core.SuppressedException;
import java.io.FileDescriptor;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;
public boolean shouldShowRequestPermissionRationale(@NonNull String permission) {
return delegate.shouldShowRequestPermissionRationale(permission);
}
@Override
public void startActivity(Intent intent) {
delegate.startActivity(intent);
}
@Override
public void startActivity(Intent intent, @Nullable Bundle options) {
delegate.startActivity(intent, options);
}
@Override
public void startActivityForResult(Intent intent, int requestCode) {
delegate.startActivityForResult(intent, requestCode);
}
@Override
public void startActivityForResult(Intent intent, int requestCode, @Nullable Bundle options) {
delegate.startActivityForResult(intent, requestCode, options);
}
@Override
public void startIntentSenderForResult(IntentSender intent, int requestCode, @Nullable Intent fillInIntent,
int flagsMask, int flagsValues, int extraFlags, Bundle options) throws SendIntentException {
try {
delegate.startIntentSenderForResult(intent, requestCode, fillInIntent, flagsMask, flagsValues, extraFlags,
options); | } catch (SuppressedException e) { |
passsy/CompositeAndroid | fragment/src/main/java/com/pascalwelsch/compositeandroid/fragment/DialogFragmentPlugin.java | // Path: core/src/main/java/com/pascalwelsch/compositeandroid/core/CallFun0.java
// public abstract class CallFun0<R> extends NamedSuperCall {
//
// public CallFun0(final String methodName) {
// super(methodName);
// }
//
// public abstract R call();
// }
//
// Path: core/src/main/java/com/pascalwelsch/compositeandroid/core/CallFun1.java
// public abstract class CallFun1<R, T1> extends NamedSuperCall {
//
// public CallFun1(final String methodName) {
// super(methodName);
// }
//
// public abstract R call(final T1 p1);
// }
//
// Path: core/src/main/java/com/pascalwelsch/compositeandroid/core/CallFun2.java
// public abstract class CallFun2<R, T1, T2> extends NamedSuperCall {
//
// public CallFun2(final String methodName) {
// super(methodName);
// }
//
// public abstract R call(final T1 p1, final T2 p2);
// }
//
// Path: core/src/main/java/com/pascalwelsch/compositeandroid/core/CallVoid0.java
// public abstract class CallVoid0 extends NamedSuperCall {
//
// public CallVoid0(final String methodName) {
// super(methodName);
// }
//
// public abstract void call();
// }
//
// Path: core/src/main/java/com/pascalwelsch/compositeandroid/core/CallVoid1.java
// public abstract class CallVoid1<T1> extends NamedSuperCall {
//
// public CallVoid1(final String methodName) {
// super(methodName);
// }
//
// public abstract void call(final T1 p1);
// }
//
// Path: core/src/main/java/com/pascalwelsch/compositeandroid/core/CallVoid2.java
// public abstract class CallVoid2<T1, T2> extends NamedSuperCall {
//
// public CallVoid2(final String methodName) {
// super(methodName);
// }
//
// public abstract void call(final T1 p1, final T2 p2);
// }
| import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.DialogFragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.view.LayoutInflater;
import com.pascalwelsch.compositeandroid.core.CallFun0;
import com.pascalwelsch.compositeandroid.core.CallFun1;
import com.pascalwelsch.compositeandroid.core.CallFun2;
import com.pascalwelsch.compositeandroid.core.CallVoid0;
import com.pascalwelsch.compositeandroid.core.CallVoid1;
import com.pascalwelsch.compositeandroid.core.CallVoid2; | package com.pascalwelsch.compositeandroid.fragment;
/**
* This code was auto-generated by the <a href="https://github.com/passsy/CompositeAndroid">CompositeAndroid</a>
* generator
*
* @author Pascal Welsch
*/
@SuppressWarnings("unused")
public class DialogFragmentPlugin extends FragmentPlugin {
public void onAttach(Context context) {
verifyMethodCalledFromDelegate("onAttach(Context)"); | // Path: core/src/main/java/com/pascalwelsch/compositeandroid/core/CallFun0.java
// public abstract class CallFun0<R> extends NamedSuperCall {
//
// public CallFun0(final String methodName) {
// super(methodName);
// }
//
// public abstract R call();
// }
//
// Path: core/src/main/java/com/pascalwelsch/compositeandroid/core/CallFun1.java
// public abstract class CallFun1<R, T1> extends NamedSuperCall {
//
// public CallFun1(final String methodName) {
// super(methodName);
// }
//
// public abstract R call(final T1 p1);
// }
//
// Path: core/src/main/java/com/pascalwelsch/compositeandroid/core/CallFun2.java
// public abstract class CallFun2<R, T1, T2> extends NamedSuperCall {
//
// public CallFun2(final String methodName) {
// super(methodName);
// }
//
// public abstract R call(final T1 p1, final T2 p2);
// }
//
// Path: core/src/main/java/com/pascalwelsch/compositeandroid/core/CallVoid0.java
// public abstract class CallVoid0 extends NamedSuperCall {
//
// public CallVoid0(final String methodName) {
// super(methodName);
// }
//
// public abstract void call();
// }
//
// Path: core/src/main/java/com/pascalwelsch/compositeandroid/core/CallVoid1.java
// public abstract class CallVoid1<T1> extends NamedSuperCall {
//
// public CallVoid1(final String methodName) {
// super(methodName);
// }
//
// public abstract void call(final T1 p1);
// }
//
// Path: core/src/main/java/com/pascalwelsch/compositeandroid/core/CallVoid2.java
// public abstract class CallVoid2<T1, T2> extends NamedSuperCall {
//
// public CallVoid2(final String methodName) {
// super(methodName);
// }
//
// public abstract void call(final T1 p1, final T2 p2);
// }
// Path: fragment/src/main/java/com/pascalwelsch/compositeandroid/fragment/DialogFragmentPlugin.java
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.DialogFragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.view.LayoutInflater;
import com.pascalwelsch.compositeandroid.core.CallFun0;
import com.pascalwelsch.compositeandroid.core.CallFun1;
import com.pascalwelsch.compositeandroid.core.CallFun2;
import com.pascalwelsch.compositeandroid.core.CallVoid0;
import com.pascalwelsch.compositeandroid.core.CallVoid1;
import com.pascalwelsch.compositeandroid.core.CallVoid2;
package com.pascalwelsch.compositeandroid.fragment;
/**
* This code was auto-generated by the <a href="https://github.com/passsy/CompositeAndroid">CompositeAndroid</a>
* generator
*
* @author Pascal Welsch
*/
@SuppressWarnings("unused")
public class DialogFragmentPlugin extends FragmentPlugin {
public void onAttach(Context context) {
verifyMethodCalledFromDelegate("onAttach(Context)"); | ((CallVoid1<Context>) mSuperListeners.pop()).call(context); |
passsy/CompositeAndroid | fragment/src/main/java/com/pascalwelsch/compositeandroid/fragment/DialogFragmentPlugin.java | // Path: core/src/main/java/com/pascalwelsch/compositeandroid/core/CallFun0.java
// public abstract class CallFun0<R> extends NamedSuperCall {
//
// public CallFun0(final String methodName) {
// super(methodName);
// }
//
// public abstract R call();
// }
//
// Path: core/src/main/java/com/pascalwelsch/compositeandroid/core/CallFun1.java
// public abstract class CallFun1<R, T1> extends NamedSuperCall {
//
// public CallFun1(final String methodName) {
// super(methodName);
// }
//
// public abstract R call(final T1 p1);
// }
//
// Path: core/src/main/java/com/pascalwelsch/compositeandroid/core/CallFun2.java
// public abstract class CallFun2<R, T1, T2> extends NamedSuperCall {
//
// public CallFun2(final String methodName) {
// super(methodName);
// }
//
// public abstract R call(final T1 p1, final T2 p2);
// }
//
// Path: core/src/main/java/com/pascalwelsch/compositeandroid/core/CallVoid0.java
// public abstract class CallVoid0 extends NamedSuperCall {
//
// public CallVoid0(final String methodName) {
// super(methodName);
// }
//
// public abstract void call();
// }
//
// Path: core/src/main/java/com/pascalwelsch/compositeandroid/core/CallVoid1.java
// public abstract class CallVoid1<T1> extends NamedSuperCall {
//
// public CallVoid1(final String methodName) {
// super(methodName);
// }
//
// public abstract void call(final T1 p1);
// }
//
// Path: core/src/main/java/com/pascalwelsch/compositeandroid/core/CallVoid2.java
// public abstract class CallVoid2<T1, T2> extends NamedSuperCall {
//
// public CallVoid2(final String methodName) {
// super(methodName);
// }
//
// public abstract void call(final T1 p1, final T2 p2);
// }
| import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.DialogFragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.view.LayoutInflater;
import com.pascalwelsch.compositeandroid.core.CallFun0;
import com.pascalwelsch.compositeandroid.core.CallFun1;
import com.pascalwelsch.compositeandroid.core.CallFun2;
import com.pascalwelsch.compositeandroid.core.CallVoid0;
import com.pascalwelsch.compositeandroid.core.CallVoid1;
import com.pascalwelsch.compositeandroid.core.CallVoid2; |
public void onCreate(@Nullable Bundle savedInstanceState) {
verifyMethodCalledFromDelegate("onCreate(Bundle)");
((CallVoid1<Bundle>) mSuperListeners.pop()).call(savedInstanceState);
}
void onCreate(final CallVoid1<Bundle> superCall, @Nullable Bundle savedInstanceState) {
synchronized (mSuperListeners) {
mSuperListeners.push(superCall);
onCreate(savedInstanceState);
}
}
public void onActivityCreated(@Nullable Bundle savedInstanceState) {
verifyMethodCalledFromDelegate("onActivityCreated(Bundle)");
((CallVoid1<Bundle>) mSuperListeners.pop()).call(savedInstanceState);
}
void onActivityCreated(final CallVoid1<Bundle> superCall, @Nullable Bundle savedInstanceState) {
synchronized (mSuperListeners) {
mSuperListeners.push(superCall);
onActivityCreated(savedInstanceState);
}
}
public void onStart() {
verifyMethodCalledFromDelegate("onStart()"); | // Path: core/src/main/java/com/pascalwelsch/compositeandroid/core/CallFun0.java
// public abstract class CallFun0<R> extends NamedSuperCall {
//
// public CallFun0(final String methodName) {
// super(methodName);
// }
//
// public abstract R call();
// }
//
// Path: core/src/main/java/com/pascalwelsch/compositeandroid/core/CallFun1.java
// public abstract class CallFun1<R, T1> extends NamedSuperCall {
//
// public CallFun1(final String methodName) {
// super(methodName);
// }
//
// public abstract R call(final T1 p1);
// }
//
// Path: core/src/main/java/com/pascalwelsch/compositeandroid/core/CallFun2.java
// public abstract class CallFun2<R, T1, T2> extends NamedSuperCall {
//
// public CallFun2(final String methodName) {
// super(methodName);
// }
//
// public abstract R call(final T1 p1, final T2 p2);
// }
//
// Path: core/src/main/java/com/pascalwelsch/compositeandroid/core/CallVoid0.java
// public abstract class CallVoid0 extends NamedSuperCall {
//
// public CallVoid0(final String methodName) {
// super(methodName);
// }
//
// public abstract void call();
// }
//
// Path: core/src/main/java/com/pascalwelsch/compositeandroid/core/CallVoid1.java
// public abstract class CallVoid1<T1> extends NamedSuperCall {
//
// public CallVoid1(final String methodName) {
// super(methodName);
// }
//
// public abstract void call(final T1 p1);
// }
//
// Path: core/src/main/java/com/pascalwelsch/compositeandroid/core/CallVoid2.java
// public abstract class CallVoid2<T1, T2> extends NamedSuperCall {
//
// public CallVoid2(final String methodName) {
// super(methodName);
// }
//
// public abstract void call(final T1 p1, final T2 p2);
// }
// Path: fragment/src/main/java/com/pascalwelsch/compositeandroid/fragment/DialogFragmentPlugin.java
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.DialogFragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.view.LayoutInflater;
import com.pascalwelsch.compositeandroid.core.CallFun0;
import com.pascalwelsch.compositeandroid.core.CallFun1;
import com.pascalwelsch.compositeandroid.core.CallFun2;
import com.pascalwelsch.compositeandroid.core.CallVoid0;
import com.pascalwelsch.compositeandroid.core.CallVoid1;
import com.pascalwelsch.compositeandroid.core.CallVoid2;
public void onCreate(@Nullable Bundle savedInstanceState) {
verifyMethodCalledFromDelegate("onCreate(Bundle)");
((CallVoid1<Bundle>) mSuperListeners.pop()).call(savedInstanceState);
}
void onCreate(final CallVoid1<Bundle> superCall, @Nullable Bundle savedInstanceState) {
synchronized (mSuperListeners) {
mSuperListeners.push(superCall);
onCreate(savedInstanceState);
}
}
public void onActivityCreated(@Nullable Bundle savedInstanceState) {
verifyMethodCalledFromDelegate("onActivityCreated(Bundle)");
((CallVoid1<Bundle>) mSuperListeners.pop()).call(savedInstanceState);
}
void onActivityCreated(final CallVoid1<Bundle> superCall, @Nullable Bundle savedInstanceState) {
synchronized (mSuperListeners) {
mSuperListeners.push(superCall);
onActivityCreated(savedInstanceState);
}
}
public void onStart() {
verifyMethodCalledFromDelegate("onStart()"); | ((CallVoid0) mSuperListeners.pop()).call(); |
passsy/CompositeAndroid | fragment/src/main/java/com/pascalwelsch/compositeandroid/fragment/DialogFragmentPlugin.java | // Path: core/src/main/java/com/pascalwelsch/compositeandroid/core/CallFun0.java
// public abstract class CallFun0<R> extends NamedSuperCall {
//
// public CallFun0(final String methodName) {
// super(methodName);
// }
//
// public abstract R call();
// }
//
// Path: core/src/main/java/com/pascalwelsch/compositeandroid/core/CallFun1.java
// public abstract class CallFun1<R, T1> extends NamedSuperCall {
//
// public CallFun1(final String methodName) {
// super(methodName);
// }
//
// public abstract R call(final T1 p1);
// }
//
// Path: core/src/main/java/com/pascalwelsch/compositeandroid/core/CallFun2.java
// public abstract class CallFun2<R, T1, T2> extends NamedSuperCall {
//
// public CallFun2(final String methodName) {
// super(methodName);
// }
//
// public abstract R call(final T1 p1, final T2 p2);
// }
//
// Path: core/src/main/java/com/pascalwelsch/compositeandroid/core/CallVoid0.java
// public abstract class CallVoid0 extends NamedSuperCall {
//
// public CallVoid0(final String methodName) {
// super(methodName);
// }
//
// public abstract void call();
// }
//
// Path: core/src/main/java/com/pascalwelsch/compositeandroid/core/CallVoid1.java
// public abstract class CallVoid1<T1> extends NamedSuperCall {
//
// public CallVoid1(final String methodName) {
// super(methodName);
// }
//
// public abstract void call(final T1 p1);
// }
//
// Path: core/src/main/java/com/pascalwelsch/compositeandroid/core/CallVoid2.java
// public abstract class CallVoid2<T1, T2> extends NamedSuperCall {
//
// public CallVoid2(final String methodName) {
// super(methodName);
// }
//
// public abstract void call(final T1 p1, final T2 p2);
// }
| import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.DialogFragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.view.LayoutInflater;
import com.pascalwelsch.compositeandroid.core.CallFun0;
import com.pascalwelsch.compositeandroid.core.CallFun1;
import com.pascalwelsch.compositeandroid.core.CallFun2;
import com.pascalwelsch.compositeandroid.core.CallVoid0;
import com.pascalwelsch.compositeandroid.core.CallVoid1;
import com.pascalwelsch.compositeandroid.core.CallVoid2; | onDestroyView();
}
}
public void onDetach() {
verifyMethodCalledFromDelegate("onDetach()");
((CallVoid0) mSuperListeners.pop()).call();
}
void onDetach(final CallVoid0 superCall) {
synchronized (mSuperListeners) {
mSuperListeners.push(superCall);
onDetach();
}
}
public void dismiss() {
verifyMethodCalledFromDelegate("dismiss()");
((CallVoid0) mSuperListeners.pop()).call();
}
public void dismissAllowingStateLoss() {
verifyMethodCalledFromDelegate("dismissAllowingStateLoss()");
((CallVoid0) mSuperListeners.pop()).call();
}
public Dialog getDialog() {
verifyMethodCalledFromDelegate("getDialog()"); | // Path: core/src/main/java/com/pascalwelsch/compositeandroid/core/CallFun0.java
// public abstract class CallFun0<R> extends NamedSuperCall {
//
// public CallFun0(final String methodName) {
// super(methodName);
// }
//
// public abstract R call();
// }
//
// Path: core/src/main/java/com/pascalwelsch/compositeandroid/core/CallFun1.java
// public abstract class CallFun1<R, T1> extends NamedSuperCall {
//
// public CallFun1(final String methodName) {
// super(methodName);
// }
//
// public abstract R call(final T1 p1);
// }
//
// Path: core/src/main/java/com/pascalwelsch/compositeandroid/core/CallFun2.java
// public abstract class CallFun2<R, T1, T2> extends NamedSuperCall {
//
// public CallFun2(final String methodName) {
// super(methodName);
// }
//
// public abstract R call(final T1 p1, final T2 p2);
// }
//
// Path: core/src/main/java/com/pascalwelsch/compositeandroid/core/CallVoid0.java
// public abstract class CallVoid0 extends NamedSuperCall {
//
// public CallVoid0(final String methodName) {
// super(methodName);
// }
//
// public abstract void call();
// }
//
// Path: core/src/main/java/com/pascalwelsch/compositeandroid/core/CallVoid1.java
// public abstract class CallVoid1<T1> extends NamedSuperCall {
//
// public CallVoid1(final String methodName) {
// super(methodName);
// }
//
// public abstract void call(final T1 p1);
// }
//
// Path: core/src/main/java/com/pascalwelsch/compositeandroid/core/CallVoid2.java
// public abstract class CallVoid2<T1, T2> extends NamedSuperCall {
//
// public CallVoid2(final String methodName) {
// super(methodName);
// }
//
// public abstract void call(final T1 p1, final T2 p2);
// }
// Path: fragment/src/main/java/com/pascalwelsch/compositeandroid/fragment/DialogFragmentPlugin.java
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.DialogFragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.view.LayoutInflater;
import com.pascalwelsch.compositeandroid.core.CallFun0;
import com.pascalwelsch.compositeandroid.core.CallFun1;
import com.pascalwelsch.compositeandroid.core.CallFun2;
import com.pascalwelsch.compositeandroid.core.CallVoid0;
import com.pascalwelsch.compositeandroid.core.CallVoid1;
import com.pascalwelsch.compositeandroid.core.CallVoid2;
onDestroyView();
}
}
public void onDetach() {
verifyMethodCalledFromDelegate("onDetach()");
((CallVoid0) mSuperListeners.pop()).call();
}
void onDetach(final CallVoid0 superCall) {
synchronized (mSuperListeners) {
mSuperListeners.push(superCall);
onDetach();
}
}
public void dismiss() {
verifyMethodCalledFromDelegate("dismiss()");
((CallVoid0) mSuperListeners.pop()).call();
}
public void dismissAllowingStateLoss() {
verifyMethodCalledFromDelegate("dismissAllowingStateLoss()");
((CallVoid0) mSuperListeners.pop()).call();
}
public Dialog getDialog() {
verifyMethodCalledFromDelegate("getDialog()"); | return ((CallFun0<Dialog>) mSuperListeners.pop()).call(); |
passsy/CompositeAndroid | fragment/src/main/java/com/pascalwelsch/compositeandroid/fragment/DialogFragmentPlugin.java | // Path: core/src/main/java/com/pascalwelsch/compositeandroid/core/CallFun0.java
// public abstract class CallFun0<R> extends NamedSuperCall {
//
// public CallFun0(final String methodName) {
// super(methodName);
// }
//
// public abstract R call();
// }
//
// Path: core/src/main/java/com/pascalwelsch/compositeandroid/core/CallFun1.java
// public abstract class CallFun1<R, T1> extends NamedSuperCall {
//
// public CallFun1(final String methodName) {
// super(methodName);
// }
//
// public abstract R call(final T1 p1);
// }
//
// Path: core/src/main/java/com/pascalwelsch/compositeandroid/core/CallFun2.java
// public abstract class CallFun2<R, T1, T2> extends NamedSuperCall {
//
// public CallFun2(final String methodName) {
// super(methodName);
// }
//
// public abstract R call(final T1 p1, final T2 p2);
// }
//
// Path: core/src/main/java/com/pascalwelsch/compositeandroid/core/CallVoid0.java
// public abstract class CallVoid0 extends NamedSuperCall {
//
// public CallVoid0(final String methodName) {
// super(methodName);
// }
//
// public abstract void call();
// }
//
// Path: core/src/main/java/com/pascalwelsch/compositeandroid/core/CallVoid1.java
// public abstract class CallVoid1<T1> extends NamedSuperCall {
//
// public CallVoid1(final String methodName) {
// super(methodName);
// }
//
// public abstract void call(final T1 p1);
// }
//
// Path: core/src/main/java/com/pascalwelsch/compositeandroid/core/CallVoid2.java
// public abstract class CallVoid2<T1, T2> extends NamedSuperCall {
//
// public CallVoid2(final String methodName) {
// super(methodName);
// }
//
// public abstract void call(final T1 p1, final T2 p2);
// }
| import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.DialogFragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.view.LayoutInflater;
import com.pascalwelsch.compositeandroid.core.CallFun0;
import com.pascalwelsch.compositeandroid.core.CallFun1;
import com.pascalwelsch.compositeandroid.core.CallFun2;
import com.pascalwelsch.compositeandroid.core.CallVoid0;
import com.pascalwelsch.compositeandroid.core.CallVoid1;
import com.pascalwelsch.compositeandroid.core.CallVoid2; | return ((CallFun0<Boolean>) mSuperListeners.pop()).call();
}
public void setShowsDialog(boolean showsDialog) {
verifyMethodCalledFromDelegate("setShowsDialog(Boolean)");
((CallVoid1<Boolean>) mSuperListeners.pop()).call(showsDialog);
}
public int getTheme() {
verifyMethodCalledFromDelegate("getTheme()");
return ((CallFun0<Integer>) mSuperListeners.pop()).call();
}
public boolean isCancelable() {
verifyMethodCalledFromDelegate("isCancelable()");
return ((CallFun0<Boolean>) mSuperListeners.pop()).call();
}
public void setCancelable(boolean cancelable) {
verifyMethodCalledFromDelegate("setCancelable(Boolean)");
((CallVoid1<Boolean>) mSuperListeners.pop()).call(cancelable);
}
public void onCancel(DialogInterface dialog) {
verifyMethodCalledFromDelegate("onCancel(DialogInterface)");
((CallVoid1<DialogInterface>) mSuperListeners.pop()).call(dialog);
}
public Dialog onCreateDialog(@Nullable Bundle savedInstanceState) {
verifyMethodCalledFromDelegate("onCreateDialog(Bundle)"); | // Path: core/src/main/java/com/pascalwelsch/compositeandroid/core/CallFun0.java
// public abstract class CallFun0<R> extends NamedSuperCall {
//
// public CallFun0(final String methodName) {
// super(methodName);
// }
//
// public abstract R call();
// }
//
// Path: core/src/main/java/com/pascalwelsch/compositeandroid/core/CallFun1.java
// public abstract class CallFun1<R, T1> extends NamedSuperCall {
//
// public CallFun1(final String methodName) {
// super(methodName);
// }
//
// public abstract R call(final T1 p1);
// }
//
// Path: core/src/main/java/com/pascalwelsch/compositeandroid/core/CallFun2.java
// public abstract class CallFun2<R, T1, T2> extends NamedSuperCall {
//
// public CallFun2(final String methodName) {
// super(methodName);
// }
//
// public abstract R call(final T1 p1, final T2 p2);
// }
//
// Path: core/src/main/java/com/pascalwelsch/compositeandroid/core/CallVoid0.java
// public abstract class CallVoid0 extends NamedSuperCall {
//
// public CallVoid0(final String methodName) {
// super(methodName);
// }
//
// public abstract void call();
// }
//
// Path: core/src/main/java/com/pascalwelsch/compositeandroid/core/CallVoid1.java
// public abstract class CallVoid1<T1> extends NamedSuperCall {
//
// public CallVoid1(final String methodName) {
// super(methodName);
// }
//
// public abstract void call(final T1 p1);
// }
//
// Path: core/src/main/java/com/pascalwelsch/compositeandroid/core/CallVoid2.java
// public abstract class CallVoid2<T1, T2> extends NamedSuperCall {
//
// public CallVoid2(final String methodName) {
// super(methodName);
// }
//
// public abstract void call(final T1 p1, final T2 p2);
// }
// Path: fragment/src/main/java/com/pascalwelsch/compositeandroid/fragment/DialogFragmentPlugin.java
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.DialogFragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.view.LayoutInflater;
import com.pascalwelsch.compositeandroid.core.CallFun0;
import com.pascalwelsch.compositeandroid.core.CallFun1;
import com.pascalwelsch.compositeandroid.core.CallFun2;
import com.pascalwelsch.compositeandroid.core.CallVoid0;
import com.pascalwelsch.compositeandroid.core.CallVoid1;
import com.pascalwelsch.compositeandroid.core.CallVoid2;
return ((CallFun0<Boolean>) mSuperListeners.pop()).call();
}
public void setShowsDialog(boolean showsDialog) {
verifyMethodCalledFromDelegate("setShowsDialog(Boolean)");
((CallVoid1<Boolean>) mSuperListeners.pop()).call(showsDialog);
}
public int getTheme() {
verifyMethodCalledFromDelegate("getTheme()");
return ((CallFun0<Integer>) mSuperListeners.pop()).call();
}
public boolean isCancelable() {
verifyMethodCalledFromDelegate("isCancelable()");
return ((CallFun0<Boolean>) mSuperListeners.pop()).call();
}
public void setCancelable(boolean cancelable) {
verifyMethodCalledFromDelegate("setCancelable(Boolean)");
((CallVoid1<Boolean>) mSuperListeners.pop()).call(cancelable);
}
public void onCancel(DialogInterface dialog) {
verifyMethodCalledFromDelegate("onCancel(DialogInterface)");
((CallVoid1<DialogInterface>) mSuperListeners.pop()).call(dialog);
}
public Dialog onCreateDialog(@Nullable Bundle savedInstanceState) {
verifyMethodCalledFromDelegate("onCreateDialog(Bundle)"); | return ((CallFun1<Dialog, Bundle>) mSuperListeners.pop()).call(savedInstanceState); |
passsy/CompositeAndroid | fragment/src/main/java/com/pascalwelsch/compositeandroid/fragment/DialogFragmentPlugin.java | // Path: core/src/main/java/com/pascalwelsch/compositeandroid/core/CallFun0.java
// public abstract class CallFun0<R> extends NamedSuperCall {
//
// public CallFun0(final String methodName) {
// super(methodName);
// }
//
// public abstract R call();
// }
//
// Path: core/src/main/java/com/pascalwelsch/compositeandroid/core/CallFun1.java
// public abstract class CallFun1<R, T1> extends NamedSuperCall {
//
// public CallFun1(final String methodName) {
// super(methodName);
// }
//
// public abstract R call(final T1 p1);
// }
//
// Path: core/src/main/java/com/pascalwelsch/compositeandroid/core/CallFun2.java
// public abstract class CallFun2<R, T1, T2> extends NamedSuperCall {
//
// public CallFun2(final String methodName) {
// super(methodName);
// }
//
// public abstract R call(final T1 p1, final T2 p2);
// }
//
// Path: core/src/main/java/com/pascalwelsch/compositeandroid/core/CallVoid0.java
// public abstract class CallVoid0 extends NamedSuperCall {
//
// public CallVoid0(final String methodName) {
// super(methodName);
// }
//
// public abstract void call();
// }
//
// Path: core/src/main/java/com/pascalwelsch/compositeandroid/core/CallVoid1.java
// public abstract class CallVoid1<T1> extends NamedSuperCall {
//
// public CallVoid1(final String methodName) {
// super(methodName);
// }
//
// public abstract void call(final T1 p1);
// }
//
// Path: core/src/main/java/com/pascalwelsch/compositeandroid/core/CallVoid2.java
// public abstract class CallVoid2<T1, T2> extends NamedSuperCall {
//
// public CallVoid2(final String methodName) {
// super(methodName);
// }
//
// public abstract void call(final T1 p1, final T2 p2);
// }
| import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.DialogFragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.view.LayoutInflater;
import com.pascalwelsch.compositeandroid.core.CallFun0;
import com.pascalwelsch.compositeandroid.core.CallFun1;
import com.pascalwelsch.compositeandroid.core.CallFun2;
import com.pascalwelsch.compositeandroid.core.CallVoid0;
import com.pascalwelsch.compositeandroid.core.CallVoid1;
import com.pascalwelsch.compositeandroid.core.CallVoid2; | return ((CallFun0<Boolean>) mSuperListeners.pop()).call();
}
public void setCancelable(boolean cancelable) {
verifyMethodCalledFromDelegate("setCancelable(Boolean)");
((CallVoid1<Boolean>) mSuperListeners.pop()).call(cancelable);
}
public void onCancel(DialogInterface dialog) {
verifyMethodCalledFromDelegate("onCancel(DialogInterface)");
((CallVoid1<DialogInterface>) mSuperListeners.pop()).call(dialog);
}
public Dialog onCreateDialog(@Nullable Bundle savedInstanceState) {
verifyMethodCalledFromDelegate("onCreateDialog(Bundle)");
return ((CallFun1<Dialog, Bundle>) mSuperListeners.pop()).call(savedInstanceState);
}
public void onDismiss(DialogInterface dialog) {
verifyMethodCalledFromDelegate("onDismiss(DialogInterface)");
((CallVoid1<DialogInterface>) mSuperListeners.pop()).call(dialog);
}
public LayoutInflater onGetLayoutInflater(@Nullable Bundle savedInstanceState) {
verifyMethodCalledFromDelegate("onGetLayoutInflater(Bundle)");
return ((CallFun1<LayoutInflater, Bundle>) mSuperListeners.pop()).call(savedInstanceState);
}
public void setStyle(int style, int theme) {
verifyMethodCalledFromDelegate("setStyle(Integer, Integer)"); | // Path: core/src/main/java/com/pascalwelsch/compositeandroid/core/CallFun0.java
// public abstract class CallFun0<R> extends NamedSuperCall {
//
// public CallFun0(final String methodName) {
// super(methodName);
// }
//
// public abstract R call();
// }
//
// Path: core/src/main/java/com/pascalwelsch/compositeandroid/core/CallFun1.java
// public abstract class CallFun1<R, T1> extends NamedSuperCall {
//
// public CallFun1(final String methodName) {
// super(methodName);
// }
//
// public abstract R call(final T1 p1);
// }
//
// Path: core/src/main/java/com/pascalwelsch/compositeandroid/core/CallFun2.java
// public abstract class CallFun2<R, T1, T2> extends NamedSuperCall {
//
// public CallFun2(final String methodName) {
// super(methodName);
// }
//
// public abstract R call(final T1 p1, final T2 p2);
// }
//
// Path: core/src/main/java/com/pascalwelsch/compositeandroid/core/CallVoid0.java
// public abstract class CallVoid0 extends NamedSuperCall {
//
// public CallVoid0(final String methodName) {
// super(methodName);
// }
//
// public abstract void call();
// }
//
// Path: core/src/main/java/com/pascalwelsch/compositeandroid/core/CallVoid1.java
// public abstract class CallVoid1<T1> extends NamedSuperCall {
//
// public CallVoid1(final String methodName) {
// super(methodName);
// }
//
// public abstract void call(final T1 p1);
// }
//
// Path: core/src/main/java/com/pascalwelsch/compositeandroid/core/CallVoid2.java
// public abstract class CallVoid2<T1, T2> extends NamedSuperCall {
//
// public CallVoid2(final String methodName) {
// super(methodName);
// }
//
// public abstract void call(final T1 p1, final T2 p2);
// }
// Path: fragment/src/main/java/com/pascalwelsch/compositeandroid/fragment/DialogFragmentPlugin.java
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.DialogFragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.view.LayoutInflater;
import com.pascalwelsch.compositeandroid.core.CallFun0;
import com.pascalwelsch.compositeandroid.core.CallFun1;
import com.pascalwelsch.compositeandroid.core.CallFun2;
import com.pascalwelsch.compositeandroid.core.CallVoid0;
import com.pascalwelsch.compositeandroid.core.CallVoid1;
import com.pascalwelsch.compositeandroid.core.CallVoid2;
return ((CallFun0<Boolean>) mSuperListeners.pop()).call();
}
public void setCancelable(boolean cancelable) {
verifyMethodCalledFromDelegate("setCancelable(Boolean)");
((CallVoid1<Boolean>) mSuperListeners.pop()).call(cancelable);
}
public void onCancel(DialogInterface dialog) {
verifyMethodCalledFromDelegate("onCancel(DialogInterface)");
((CallVoid1<DialogInterface>) mSuperListeners.pop()).call(dialog);
}
public Dialog onCreateDialog(@Nullable Bundle savedInstanceState) {
verifyMethodCalledFromDelegate("onCreateDialog(Bundle)");
return ((CallFun1<Dialog, Bundle>) mSuperListeners.pop()).call(savedInstanceState);
}
public void onDismiss(DialogInterface dialog) {
verifyMethodCalledFromDelegate("onDismiss(DialogInterface)");
((CallVoid1<DialogInterface>) mSuperListeners.pop()).call(dialog);
}
public LayoutInflater onGetLayoutInflater(@Nullable Bundle savedInstanceState) {
verifyMethodCalledFromDelegate("onGetLayoutInflater(Bundle)");
return ((CallFun1<LayoutInflater, Bundle>) mSuperListeners.pop()).call(savedInstanceState);
}
public void setStyle(int style, int theme) {
verifyMethodCalledFromDelegate("setStyle(Integer, Integer)"); | ((CallVoid2<Integer, Integer>) mSuperListeners.pop()).call(style, theme); |
passsy/CompositeAndroid | fragment/src/main/java/com/pascalwelsch/compositeandroid/fragment/DialogFragmentPlugin.java | // Path: core/src/main/java/com/pascalwelsch/compositeandroid/core/CallFun0.java
// public abstract class CallFun0<R> extends NamedSuperCall {
//
// public CallFun0(final String methodName) {
// super(methodName);
// }
//
// public abstract R call();
// }
//
// Path: core/src/main/java/com/pascalwelsch/compositeandroid/core/CallFun1.java
// public abstract class CallFun1<R, T1> extends NamedSuperCall {
//
// public CallFun1(final String methodName) {
// super(methodName);
// }
//
// public abstract R call(final T1 p1);
// }
//
// Path: core/src/main/java/com/pascalwelsch/compositeandroid/core/CallFun2.java
// public abstract class CallFun2<R, T1, T2> extends NamedSuperCall {
//
// public CallFun2(final String methodName) {
// super(methodName);
// }
//
// public abstract R call(final T1 p1, final T2 p2);
// }
//
// Path: core/src/main/java/com/pascalwelsch/compositeandroid/core/CallVoid0.java
// public abstract class CallVoid0 extends NamedSuperCall {
//
// public CallVoid0(final String methodName) {
// super(methodName);
// }
//
// public abstract void call();
// }
//
// Path: core/src/main/java/com/pascalwelsch/compositeandroid/core/CallVoid1.java
// public abstract class CallVoid1<T1> extends NamedSuperCall {
//
// public CallVoid1(final String methodName) {
// super(methodName);
// }
//
// public abstract void call(final T1 p1);
// }
//
// Path: core/src/main/java/com/pascalwelsch/compositeandroid/core/CallVoid2.java
// public abstract class CallVoid2<T1, T2> extends NamedSuperCall {
//
// public CallVoid2(final String methodName) {
// super(methodName);
// }
//
// public abstract void call(final T1 p1, final T2 p2);
// }
| import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.DialogFragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.view.LayoutInflater;
import com.pascalwelsch.compositeandroid.core.CallFun0;
import com.pascalwelsch.compositeandroid.core.CallFun1;
import com.pascalwelsch.compositeandroid.core.CallFun2;
import com.pascalwelsch.compositeandroid.core.CallVoid0;
import com.pascalwelsch.compositeandroid.core.CallVoid1;
import com.pascalwelsch.compositeandroid.core.CallVoid2; | return ((CallFun1<Dialog, Bundle>) mSuperListeners.pop()).call(savedInstanceState);
}
public void onDismiss(DialogInterface dialog) {
verifyMethodCalledFromDelegate("onDismiss(DialogInterface)");
((CallVoid1<DialogInterface>) mSuperListeners.pop()).call(dialog);
}
public LayoutInflater onGetLayoutInflater(@Nullable Bundle savedInstanceState) {
verifyMethodCalledFromDelegate("onGetLayoutInflater(Bundle)");
return ((CallFun1<LayoutInflater, Bundle>) mSuperListeners.pop()).call(savedInstanceState);
}
public void setStyle(int style, int theme) {
verifyMethodCalledFromDelegate("setStyle(Integer, Integer)");
((CallVoid2<Integer, Integer>) mSuperListeners.pop()).call(style, theme);
}
public void setupDialog(Dialog dialog, int style) {
verifyMethodCalledFromDelegate("setupDialog(Dialog, Integer)");
((CallVoid2<Dialog, Integer>) mSuperListeners.pop()).call(dialog, style);
}
public void show(FragmentManager manager, String tag) {
verifyMethodCalledFromDelegate("show(FragmentManager, String)");
((CallVoid2<FragmentManager, String>) mSuperListeners.pop()).call(manager, tag);
}
public int show(FragmentTransaction transaction, String tag) {
verifyMethodCalledFromDelegate("show(FragmentTransaction, String)"); | // Path: core/src/main/java/com/pascalwelsch/compositeandroid/core/CallFun0.java
// public abstract class CallFun0<R> extends NamedSuperCall {
//
// public CallFun0(final String methodName) {
// super(methodName);
// }
//
// public abstract R call();
// }
//
// Path: core/src/main/java/com/pascalwelsch/compositeandroid/core/CallFun1.java
// public abstract class CallFun1<R, T1> extends NamedSuperCall {
//
// public CallFun1(final String methodName) {
// super(methodName);
// }
//
// public abstract R call(final T1 p1);
// }
//
// Path: core/src/main/java/com/pascalwelsch/compositeandroid/core/CallFun2.java
// public abstract class CallFun2<R, T1, T2> extends NamedSuperCall {
//
// public CallFun2(final String methodName) {
// super(methodName);
// }
//
// public abstract R call(final T1 p1, final T2 p2);
// }
//
// Path: core/src/main/java/com/pascalwelsch/compositeandroid/core/CallVoid0.java
// public abstract class CallVoid0 extends NamedSuperCall {
//
// public CallVoid0(final String methodName) {
// super(methodName);
// }
//
// public abstract void call();
// }
//
// Path: core/src/main/java/com/pascalwelsch/compositeandroid/core/CallVoid1.java
// public abstract class CallVoid1<T1> extends NamedSuperCall {
//
// public CallVoid1(final String methodName) {
// super(methodName);
// }
//
// public abstract void call(final T1 p1);
// }
//
// Path: core/src/main/java/com/pascalwelsch/compositeandroid/core/CallVoid2.java
// public abstract class CallVoid2<T1, T2> extends NamedSuperCall {
//
// public CallVoid2(final String methodName) {
// super(methodName);
// }
//
// public abstract void call(final T1 p1, final T2 p2);
// }
// Path: fragment/src/main/java/com/pascalwelsch/compositeandroid/fragment/DialogFragmentPlugin.java
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.DialogFragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.view.LayoutInflater;
import com.pascalwelsch.compositeandroid.core.CallFun0;
import com.pascalwelsch.compositeandroid.core.CallFun1;
import com.pascalwelsch.compositeandroid.core.CallFun2;
import com.pascalwelsch.compositeandroid.core.CallVoid0;
import com.pascalwelsch.compositeandroid.core.CallVoid1;
import com.pascalwelsch.compositeandroid.core.CallVoid2;
return ((CallFun1<Dialog, Bundle>) mSuperListeners.pop()).call(savedInstanceState);
}
public void onDismiss(DialogInterface dialog) {
verifyMethodCalledFromDelegate("onDismiss(DialogInterface)");
((CallVoid1<DialogInterface>) mSuperListeners.pop()).call(dialog);
}
public LayoutInflater onGetLayoutInflater(@Nullable Bundle savedInstanceState) {
verifyMethodCalledFromDelegate("onGetLayoutInflater(Bundle)");
return ((CallFun1<LayoutInflater, Bundle>) mSuperListeners.pop()).call(savedInstanceState);
}
public void setStyle(int style, int theme) {
verifyMethodCalledFromDelegate("setStyle(Integer, Integer)");
((CallVoid2<Integer, Integer>) mSuperListeners.pop()).call(style, theme);
}
public void setupDialog(Dialog dialog, int style) {
verifyMethodCalledFromDelegate("setupDialog(Dialog, Integer)");
((CallVoid2<Dialog, Integer>) mSuperListeners.pop()).call(dialog, style);
}
public void show(FragmentManager manager, String tag) {
verifyMethodCalledFromDelegate("show(FragmentManager, String)");
((CallVoid2<FragmentManager, String>) mSuperListeners.pop()).call(manager, tag);
}
public int show(FragmentTransaction transaction, String tag) {
verifyMethodCalledFromDelegate("show(FragmentTransaction, String)"); | return ((CallFun2<Integer, FragmentTransaction, String>) mSuperListeners.pop()).call(transaction, tag); |
passsy/CompositeAndroid | fragment/src/main/java/com/pascalwelsch/compositeandroid/fragment/DialogFragmentDelegate.java | // Path: core/src/main/java/com/pascalwelsch/compositeandroid/core/AbstractDelegate.java
// public class AbstractDelegate<T, P extends AbstractPlugin> {
//
// protected final T mOriginal;
//
// protected List<P> mPlugins = new CopyOnWriteArrayList<>();
//
// public AbstractDelegate(final T original) {
// mOriginal = original;
// }
//
// @SuppressWarnings("unchecked")
// public Removable addPlugin(final P plugin) {
// plugin.addToDelegate(this, mOriginal);
// mPlugins.add(plugin);
//
// return new Removable() {
// @Override
// public void remove() {
// mPlugins.remove(plugin);
// plugin.removeFromDelegate();
// }
// };
// }
//
// public T getOriginal() {
// return mOriginal;
// }
//
// }
//
// Path: core/src/main/java/com/pascalwelsch/compositeandroid/core/CallFun0.java
// public abstract class CallFun0<R> extends NamedSuperCall {
//
// public CallFun0(final String methodName) {
// super(methodName);
// }
//
// public abstract R call();
// }
//
// Path: core/src/main/java/com/pascalwelsch/compositeandroid/core/CallFun1.java
// public abstract class CallFun1<R, T1> extends NamedSuperCall {
//
// public CallFun1(final String methodName) {
// super(methodName);
// }
//
// public abstract R call(final T1 p1);
// }
//
// Path: core/src/main/java/com/pascalwelsch/compositeandroid/core/CallFun2.java
// public abstract class CallFun2<R, T1, T2> extends NamedSuperCall {
//
// public CallFun2(final String methodName) {
// super(methodName);
// }
//
// public abstract R call(final T1 p1, final T2 p2);
// }
//
// Path: core/src/main/java/com/pascalwelsch/compositeandroid/core/CallVoid0.java
// public abstract class CallVoid0 extends NamedSuperCall {
//
// public CallVoid0(final String methodName) {
// super(methodName);
// }
//
// public abstract void call();
// }
//
// Path: core/src/main/java/com/pascalwelsch/compositeandroid/core/CallVoid1.java
// public abstract class CallVoid1<T1> extends NamedSuperCall {
//
// public CallVoid1(final String methodName) {
// super(methodName);
// }
//
// public abstract void call(final T1 p1);
// }
//
// Path: core/src/main/java/com/pascalwelsch/compositeandroid/core/CallVoid2.java
// public abstract class CallVoid2<T1, T2> extends NamedSuperCall {
//
// public CallVoid2(final String methodName) {
// super(methodName);
// }
//
// public abstract void call(final T1 p1, final T2 p2);
// }
//
// Path: core/src/main/java/com/pascalwelsch/compositeandroid/core/Removable.java
// public interface Removable {
//
// void remove();
// }
| import android.animation.Animator;
import android.app.Activity;
import android.app.Dialog;
import android.arch.lifecycle.LiveData;
import android.arch.lifecycle.ViewModelStore;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentSender;
import android.content.IntentSender.SendIntentException;
import android.content.res.Configuration;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.app.LoaderManager;
import android.support.v4.app.SharedElementCallback;
import android.util.AttributeSet;
import android.view.ContextMenu;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.Animation;
import com.pascalwelsch.compositeandroid.core.AbstractDelegate;
import com.pascalwelsch.compositeandroid.core.CallFun0;
import com.pascalwelsch.compositeandroid.core.CallFun1;
import com.pascalwelsch.compositeandroid.core.CallFun2;
import com.pascalwelsch.compositeandroid.core.CallVoid0;
import com.pascalwelsch.compositeandroid.core.CallVoid1;
import com.pascalwelsch.compositeandroid.core.CallVoid2;
import com.pascalwelsch.compositeandroid.core.Removable;
import java.io.FileDescriptor;
import java.io.PrintWriter;
import java.util.ListIterator; | package com.pascalwelsch.compositeandroid.fragment;
/**
* This code was auto-generated by the <a href="https://github.com/passsy/CompositeAndroid">CompositeAndroid</a>
* generator
*
* @author Pascal Welsch
*/
public class DialogFragmentDelegate extends AbstractDelegate<ICompositeDialogFragment, DialogFragmentPlugin> {
private final FragmentDelegate mFragmentDelegate;
public DialogFragmentDelegate(final ICompositeDialogFragment icompositedialogfragment) {
super(icompositedialogfragment);
mFragmentDelegate = new FragmentDelegate(icompositedialogfragment);
}
| // Path: core/src/main/java/com/pascalwelsch/compositeandroid/core/AbstractDelegate.java
// public class AbstractDelegate<T, P extends AbstractPlugin> {
//
// protected final T mOriginal;
//
// protected List<P> mPlugins = new CopyOnWriteArrayList<>();
//
// public AbstractDelegate(final T original) {
// mOriginal = original;
// }
//
// @SuppressWarnings("unchecked")
// public Removable addPlugin(final P plugin) {
// plugin.addToDelegate(this, mOriginal);
// mPlugins.add(plugin);
//
// return new Removable() {
// @Override
// public void remove() {
// mPlugins.remove(plugin);
// plugin.removeFromDelegate();
// }
// };
// }
//
// public T getOriginal() {
// return mOriginal;
// }
//
// }
//
// Path: core/src/main/java/com/pascalwelsch/compositeandroid/core/CallFun0.java
// public abstract class CallFun0<R> extends NamedSuperCall {
//
// public CallFun0(final String methodName) {
// super(methodName);
// }
//
// public abstract R call();
// }
//
// Path: core/src/main/java/com/pascalwelsch/compositeandroid/core/CallFun1.java
// public abstract class CallFun1<R, T1> extends NamedSuperCall {
//
// public CallFun1(final String methodName) {
// super(methodName);
// }
//
// public abstract R call(final T1 p1);
// }
//
// Path: core/src/main/java/com/pascalwelsch/compositeandroid/core/CallFun2.java
// public abstract class CallFun2<R, T1, T2> extends NamedSuperCall {
//
// public CallFun2(final String methodName) {
// super(methodName);
// }
//
// public abstract R call(final T1 p1, final T2 p2);
// }
//
// Path: core/src/main/java/com/pascalwelsch/compositeandroid/core/CallVoid0.java
// public abstract class CallVoid0 extends NamedSuperCall {
//
// public CallVoid0(final String methodName) {
// super(methodName);
// }
//
// public abstract void call();
// }
//
// Path: core/src/main/java/com/pascalwelsch/compositeandroid/core/CallVoid1.java
// public abstract class CallVoid1<T1> extends NamedSuperCall {
//
// public CallVoid1(final String methodName) {
// super(methodName);
// }
//
// public abstract void call(final T1 p1);
// }
//
// Path: core/src/main/java/com/pascalwelsch/compositeandroid/core/CallVoid2.java
// public abstract class CallVoid2<T1, T2> extends NamedSuperCall {
//
// public CallVoid2(final String methodName) {
// super(methodName);
// }
//
// public abstract void call(final T1 p1, final T2 p2);
// }
//
// Path: core/src/main/java/com/pascalwelsch/compositeandroid/core/Removable.java
// public interface Removable {
//
// void remove();
// }
// Path: fragment/src/main/java/com/pascalwelsch/compositeandroid/fragment/DialogFragmentDelegate.java
import android.animation.Animator;
import android.app.Activity;
import android.app.Dialog;
import android.arch.lifecycle.LiveData;
import android.arch.lifecycle.ViewModelStore;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentSender;
import android.content.IntentSender.SendIntentException;
import android.content.res.Configuration;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.app.LoaderManager;
import android.support.v4.app.SharedElementCallback;
import android.util.AttributeSet;
import android.view.ContextMenu;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.Animation;
import com.pascalwelsch.compositeandroid.core.AbstractDelegate;
import com.pascalwelsch.compositeandroid.core.CallFun0;
import com.pascalwelsch.compositeandroid.core.CallFun1;
import com.pascalwelsch.compositeandroid.core.CallFun2;
import com.pascalwelsch.compositeandroid.core.CallVoid0;
import com.pascalwelsch.compositeandroid.core.CallVoid1;
import com.pascalwelsch.compositeandroid.core.CallVoid2;
import com.pascalwelsch.compositeandroid.core.Removable;
import java.io.FileDescriptor;
import java.io.PrintWriter;
import java.util.ListIterator;
package com.pascalwelsch.compositeandroid.fragment;
/**
* This code was auto-generated by the <a href="https://github.com/passsy/CompositeAndroid">CompositeAndroid</a>
* generator
*
* @author Pascal Welsch
*/
public class DialogFragmentDelegate extends AbstractDelegate<ICompositeDialogFragment, DialogFragmentPlugin> {
private final FragmentDelegate mFragmentDelegate;
public DialogFragmentDelegate(final ICompositeDialogFragment icompositedialogfragment) {
super(icompositedialogfragment);
mFragmentDelegate = new FragmentDelegate(icompositedialogfragment);
}
| public Removable addPlugin(final FragmentPlugin plugin) { |
passsy/CompositeAndroid | fragment/src/main/java/com/pascalwelsch/compositeandroid/fragment/DialogFragmentDelegate.java | // Path: core/src/main/java/com/pascalwelsch/compositeandroid/core/AbstractDelegate.java
// public class AbstractDelegate<T, P extends AbstractPlugin> {
//
// protected final T mOriginal;
//
// protected List<P> mPlugins = new CopyOnWriteArrayList<>();
//
// public AbstractDelegate(final T original) {
// mOriginal = original;
// }
//
// @SuppressWarnings("unchecked")
// public Removable addPlugin(final P plugin) {
// plugin.addToDelegate(this, mOriginal);
// mPlugins.add(plugin);
//
// return new Removable() {
// @Override
// public void remove() {
// mPlugins.remove(plugin);
// plugin.removeFromDelegate();
// }
// };
// }
//
// public T getOriginal() {
// return mOriginal;
// }
//
// }
//
// Path: core/src/main/java/com/pascalwelsch/compositeandroid/core/CallFun0.java
// public abstract class CallFun0<R> extends NamedSuperCall {
//
// public CallFun0(final String methodName) {
// super(methodName);
// }
//
// public abstract R call();
// }
//
// Path: core/src/main/java/com/pascalwelsch/compositeandroid/core/CallFun1.java
// public abstract class CallFun1<R, T1> extends NamedSuperCall {
//
// public CallFun1(final String methodName) {
// super(methodName);
// }
//
// public abstract R call(final T1 p1);
// }
//
// Path: core/src/main/java/com/pascalwelsch/compositeandroid/core/CallFun2.java
// public abstract class CallFun2<R, T1, T2> extends NamedSuperCall {
//
// public CallFun2(final String methodName) {
// super(methodName);
// }
//
// public abstract R call(final T1 p1, final T2 p2);
// }
//
// Path: core/src/main/java/com/pascalwelsch/compositeandroid/core/CallVoid0.java
// public abstract class CallVoid0 extends NamedSuperCall {
//
// public CallVoid0(final String methodName) {
// super(methodName);
// }
//
// public abstract void call();
// }
//
// Path: core/src/main/java/com/pascalwelsch/compositeandroid/core/CallVoid1.java
// public abstract class CallVoid1<T1> extends NamedSuperCall {
//
// public CallVoid1(final String methodName) {
// super(methodName);
// }
//
// public abstract void call(final T1 p1);
// }
//
// Path: core/src/main/java/com/pascalwelsch/compositeandroid/core/CallVoid2.java
// public abstract class CallVoid2<T1, T2> extends NamedSuperCall {
//
// public CallVoid2(final String methodName) {
// super(methodName);
// }
//
// public abstract void call(final T1 p1, final T2 p2);
// }
//
// Path: core/src/main/java/com/pascalwelsch/compositeandroid/core/Removable.java
// public interface Removable {
//
// void remove();
// }
| import android.animation.Animator;
import android.app.Activity;
import android.app.Dialog;
import android.arch.lifecycle.LiveData;
import android.arch.lifecycle.ViewModelStore;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentSender;
import android.content.IntentSender.SendIntentException;
import android.content.res.Configuration;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.app.LoaderManager;
import android.support.v4.app.SharedElementCallback;
import android.util.AttributeSet;
import android.view.ContextMenu;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.Animation;
import com.pascalwelsch.compositeandroid.core.AbstractDelegate;
import com.pascalwelsch.compositeandroid.core.CallFun0;
import com.pascalwelsch.compositeandroid.core.CallFun1;
import com.pascalwelsch.compositeandroid.core.CallFun2;
import com.pascalwelsch.compositeandroid.core.CallVoid0;
import com.pascalwelsch.compositeandroid.core.CallVoid1;
import com.pascalwelsch.compositeandroid.core.CallVoid2;
import com.pascalwelsch.compositeandroid.core.Removable;
import java.io.FileDescriptor;
import java.io.PrintWriter;
import java.util.ListIterator; | package com.pascalwelsch.compositeandroid.fragment;
/**
* This code was auto-generated by the <a href="https://github.com/passsy/CompositeAndroid">CompositeAndroid</a>
* generator
*
* @author Pascal Welsch
*/
public class DialogFragmentDelegate extends AbstractDelegate<ICompositeDialogFragment, DialogFragmentPlugin> {
private final FragmentDelegate mFragmentDelegate;
public DialogFragmentDelegate(final ICompositeDialogFragment icompositedialogfragment) {
super(icompositedialogfragment);
mFragmentDelegate = new FragmentDelegate(icompositedialogfragment);
}
public Removable addPlugin(final FragmentPlugin plugin) {
return mFragmentDelegate.addPlugin(plugin);
}
@Override
public Removable addPlugin(final DialogFragmentPlugin plugin) {
final Removable removable = super.addPlugin(plugin);
final Removable superRemovable = mFragmentDelegate.addPlugin(plugin);
return new Removable() {
@Override
public void remove() {
removable.remove();
superRemovable.remove();
}
};
}
public void dismiss() {
if (mPlugins.isEmpty()) {
getOriginal().super_dismiss();
return;
}
final ListIterator<DialogFragmentPlugin> iterator = mPlugins.listIterator(mPlugins.size());
| // Path: core/src/main/java/com/pascalwelsch/compositeandroid/core/AbstractDelegate.java
// public class AbstractDelegate<T, P extends AbstractPlugin> {
//
// protected final T mOriginal;
//
// protected List<P> mPlugins = new CopyOnWriteArrayList<>();
//
// public AbstractDelegate(final T original) {
// mOriginal = original;
// }
//
// @SuppressWarnings("unchecked")
// public Removable addPlugin(final P plugin) {
// plugin.addToDelegate(this, mOriginal);
// mPlugins.add(plugin);
//
// return new Removable() {
// @Override
// public void remove() {
// mPlugins.remove(plugin);
// plugin.removeFromDelegate();
// }
// };
// }
//
// public T getOriginal() {
// return mOriginal;
// }
//
// }
//
// Path: core/src/main/java/com/pascalwelsch/compositeandroid/core/CallFun0.java
// public abstract class CallFun0<R> extends NamedSuperCall {
//
// public CallFun0(final String methodName) {
// super(methodName);
// }
//
// public abstract R call();
// }
//
// Path: core/src/main/java/com/pascalwelsch/compositeandroid/core/CallFun1.java
// public abstract class CallFun1<R, T1> extends NamedSuperCall {
//
// public CallFun1(final String methodName) {
// super(methodName);
// }
//
// public abstract R call(final T1 p1);
// }
//
// Path: core/src/main/java/com/pascalwelsch/compositeandroid/core/CallFun2.java
// public abstract class CallFun2<R, T1, T2> extends NamedSuperCall {
//
// public CallFun2(final String methodName) {
// super(methodName);
// }
//
// public abstract R call(final T1 p1, final T2 p2);
// }
//
// Path: core/src/main/java/com/pascalwelsch/compositeandroid/core/CallVoid0.java
// public abstract class CallVoid0 extends NamedSuperCall {
//
// public CallVoid0(final String methodName) {
// super(methodName);
// }
//
// public abstract void call();
// }
//
// Path: core/src/main/java/com/pascalwelsch/compositeandroid/core/CallVoid1.java
// public abstract class CallVoid1<T1> extends NamedSuperCall {
//
// public CallVoid1(final String methodName) {
// super(methodName);
// }
//
// public abstract void call(final T1 p1);
// }
//
// Path: core/src/main/java/com/pascalwelsch/compositeandroid/core/CallVoid2.java
// public abstract class CallVoid2<T1, T2> extends NamedSuperCall {
//
// public CallVoid2(final String methodName) {
// super(methodName);
// }
//
// public abstract void call(final T1 p1, final T2 p2);
// }
//
// Path: core/src/main/java/com/pascalwelsch/compositeandroid/core/Removable.java
// public interface Removable {
//
// void remove();
// }
// Path: fragment/src/main/java/com/pascalwelsch/compositeandroid/fragment/DialogFragmentDelegate.java
import android.animation.Animator;
import android.app.Activity;
import android.app.Dialog;
import android.arch.lifecycle.LiveData;
import android.arch.lifecycle.ViewModelStore;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentSender;
import android.content.IntentSender.SendIntentException;
import android.content.res.Configuration;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.app.LoaderManager;
import android.support.v4.app.SharedElementCallback;
import android.util.AttributeSet;
import android.view.ContextMenu;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.Animation;
import com.pascalwelsch.compositeandroid.core.AbstractDelegate;
import com.pascalwelsch.compositeandroid.core.CallFun0;
import com.pascalwelsch.compositeandroid.core.CallFun1;
import com.pascalwelsch.compositeandroid.core.CallFun2;
import com.pascalwelsch.compositeandroid.core.CallVoid0;
import com.pascalwelsch.compositeandroid.core.CallVoid1;
import com.pascalwelsch.compositeandroid.core.CallVoid2;
import com.pascalwelsch.compositeandroid.core.Removable;
import java.io.FileDescriptor;
import java.io.PrintWriter;
import java.util.ListIterator;
package com.pascalwelsch.compositeandroid.fragment;
/**
* This code was auto-generated by the <a href="https://github.com/passsy/CompositeAndroid">CompositeAndroid</a>
* generator
*
* @author Pascal Welsch
*/
public class DialogFragmentDelegate extends AbstractDelegate<ICompositeDialogFragment, DialogFragmentPlugin> {
private final FragmentDelegate mFragmentDelegate;
public DialogFragmentDelegate(final ICompositeDialogFragment icompositedialogfragment) {
super(icompositedialogfragment);
mFragmentDelegate = new FragmentDelegate(icompositedialogfragment);
}
public Removable addPlugin(final FragmentPlugin plugin) {
return mFragmentDelegate.addPlugin(plugin);
}
@Override
public Removable addPlugin(final DialogFragmentPlugin plugin) {
final Removable removable = super.addPlugin(plugin);
final Removable superRemovable = mFragmentDelegate.addPlugin(plugin);
return new Removable() {
@Override
public void remove() {
removable.remove();
superRemovable.remove();
}
};
}
public void dismiss() {
if (mPlugins.isEmpty()) {
getOriginal().super_dismiss();
return;
}
final ListIterator<DialogFragmentPlugin> iterator = mPlugins.listIterator(mPlugins.size());
| final CallVoid0 superCall = new CallVoid0("dismiss()") { |
passsy/CompositeAndroid | fragment/src/main/java/com/pascalwelsch/compositeandroid/fragment/DialogFragmentDelegate.java | // Path: core/src/main/java/com/pascalwelsch/compositeandroid/core/AbstractDelegate.java
// public class AbstractDelegate<T, P extends AbstractPlugin> {
//
// protected final T mOriginal;
//
// protected List<P> mPlugins = new CopyOnWriteArrayList<>();
//
// public AbstractDelegate(final T original) {
// mOriginal = original;
// }
//
// @SuppressWarnings("unchecked")
// public Removable addPlugin(final P plugin) {
// plugin.addToDelegate(this, mOriginal);
// mPlugins.add(plugin);
//
// return new Removable() {
// @Override
// public void remove() {
// mPlugins.remove(plugin);
// plugin.removeFromDelegate();
// }
// };
// }
//
// public T getOriginal() {
// return mOriginal;
// }
//
// }
//
// Path: core/src/main/java/com/pascalwelsch/compositeandroid/core/CallFun0.java
// public abstract class CallFun0<R> extends NamedSuperCall {
//
// public CallFun0(final String methodName) {
// super(methodName);
// }
//
// public abstract R call();
// }
//
// Path: core/src/main/java/com/pascalwelsch/compositeandroid/core/CallFun1.java
// public abstract class CallFun1<R, T1> extends NamedSuperCall {
//
// public CallFun1(final String methodName) {
// super(methodName);
// }
//
// public abstract R call(final T1 p1);
// }
//
// Path: core/src/main/java/com/pascalwelsch/compositeandroid/core/CallFun2.java
// public abstract class CallFun2<R, T1, T2> extends NamedSuperCall {
//
// public CallFun2(final String methodName) {
// super(methodName);
// }
//
// public abstract R call(final T1 p1, final T2 p2);
// }
//
// Path: core/src/main/java/com/pascalwelsch/compositeandroid/core/CallVoid0.java
// public abstract class CallVoid0 extends NamedSuperCall {
//
// public CallVoid0(final String methodName) {
// super(methodName);
// }
//
// public abstract void call();
// }
//
// Path: core/src/main/java/com/pascalwelsch/compositeandroid/core/CallVoid1.java
// public abstract class CallVoid1<T1> extends NamedSuperCall {
//
// public CallVoid1(final String methodName) {
// super(methodName);
// }
//
// public abstract void call(final T1 p1);
// }
//
// Path: core/src/main/java/com/pascalwelsch/compositeandroid/core/CallVoid2.java
// public abstract class CallVoid2<T1, T2> extends NamedSuperCall {
//
// public CallVoid2(final String methodName) {
// super(methodName);
// }
//
// public abstract void call(final T1 p1, final T2 p2);
// }
//
// Path: core/src/main/java/com/pascalwelsch/compositeandroid/core/Removable.java
// public interface Removable {
//
// void remove();
// }
| import android.animation.Animator;
import android.app.Activity;
import android.app.Dialog;
import android.arch.lifecycle.LiveData;
import android.arch.lifecycle.ViewModelStore;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentSender;
import android.content.IntentSender.SendIntentException;
import android.content.res.Configuration;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.app.LoaderManager;
import android.support.v4.app.SharedElementCallback;
import android.util.AttributeSet;
import android.view.ContextMenu;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.Animation;
import com.pascalwelsch.compositeandroid.core.AbstractDelegate;
import com.pascalwelsch.compositeandroid.core.CallFun0;
import com.pascalwelsch.compositeandroid.core.CallFun1;
import com.pascalwelsch.compositeandroid.core.CallFun2;
import com.pascalwelsch.compositeandroid.core.CallVoid0;
import com.pascalwelsch.compositeandroid.core.CallVoid1;
import com.pascalwelsch.compositeandroid.core.CallVoid2;
import com.pascalwelsch.compositeandroid.core.Removable;
import java.io.FileDescriptor;
import java.io.PrintWriter;
import java.util.ListIterator; | mFragmentDelegate.dump(prefix, fd, writer, args);
}
public boolean getAllowEnterTransitionOverlap() {
return mFragmentDelegate.getAllowEnterTransitionOverlap();
}
public void setAllowEnterTransitionOverlap(boolean allow) {
mFragmentDelegate.setAllowEnterTransitionOverlap(allow);
}
public boolean getAllowReturnTransitionOverlap() {
return mFragmentDelegate.getAllowReturnTransitionOverlap();
}
public void setAllowReturnTransitionOverlap(boolean allow) {
mFragmentDelegate.setAllowReturnTransitionOverlap(allow);
}
public Context getContext() {
return mFragmentDelegate.getContext();
}
public Dialog getDialog() {
if (mPlugins.isEmpty()) {
return getOriginal().super_getDialog();
}
final ListIterator<DialogFragmentPlugin> iterator = mPlugins.listIterator(mPlugins.size());
| // Path: core/src/main/java/com/pascalwelsch/compositeandroid/core/AbstractDelegate.java
// public class AbstractDelegate<T, P extends AbstractPlugin> {
//
// protected final T mOriginal;
//
// protected List<P> mPlugins = new CopyOnWriteArrayList<>();
//
// public AbstractDelegate(final T original) {
// mOriginal = original;
// }
//
// @SuppressWarnings("unchecked")
// public Removable addPlugin(final P plugin) {
// plugin.addToDelegate(this, mOriginal);
// mPlugins.add(plugin);
//
// return new Removable() {
// @Override
// public void remove() {
// mPlugins.remove(plugin);
// plugin.removeFromDelegate();
// }
// };
// }
//
// public T getOriginal() {
// return mOriginal;
// }
//
// }
//
// Path: core/src/main/java/com/pascalwelsch/compositeandroid/core/CallFun0.java
// public abstract class CallFun0<R> extends NamedSuperCall {
//
// public CallFun0(final String methodName) {
// super(methodName);
// }
//
// public abstract R call();
// }
//
// Path: core/src/main/java/com/pascalwelsch/compositeandroid/core/CallFun1.java
// public abstract class CallFun1<R, T1> extends NamedSuperCall {
//
// public CallFun1(final String methodName) {
// super(methodName);
// }
//
// public abstract R call(final T1 p1);
// }
//
// Path: core/src/main/java/com/pascalwelsch/compositeandroid/core/CallFun2.java
// public abstract class CallFun2<R, T1, T2> extends NamedSuperCall {
//
// public CallFun2(final String methodName) {
// super(methodName);
// }
//
// public abstract R call(final T1 p1, final T2 p2);
// }
//
// Path: core/src/main/java/com/pascalwelsch/compositeandroid/core/CallVoid0.java
// public abstract class CallVoid0 extends NamedSuperCall {
//
// public CallVoid0(final String methodName) {
// super(methodName);
// }
//
// public abstract void call();
// }
//
// Path: core/src/main/java/com/pascalwelsch/compositeandroid/core/CallVoid1.java
// public abstract class CallVoid1<T1> extends NamedSuperCall {
//
// public CallVoid1(final String methodName) {
// super(methodName);
// }
//
// public abstract void call(final T1 p1);
// }
//
// Path: core/src/main/java/com/pascalwelsch/compositeandroid/core/CallVoid2.java
// public abstract class CallVoid2<T1, T2> extends NamedSuperCall {
//
// public CallVoid2(final String methodName) {
// super(methodName);
// }
//
// public abstract void call(final T1 p1, final T2 p2);
// }
//
// Path: core/src/main/java/com/pascalwelsch/compositeandroid/core/Removable.java
// public interface Removable {
//
// void remove();
// }
// Path: fragment/src/main/java/com/pascalwelsch/compositeandroid/fragment/DialogFragmentDelegate.java
import android.animation.Animator;
import android.app.Activity;
import android.app.Dialog;
import android.arch.lifecycle.LiveData;
import android.arch.lifecycle.ViewModelStore;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentSender;
import android.content.IntentSender.SendIntentException;
import android.content.res.Configuration;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.app.LoaderManager;
import android.support.v4.app.SharedElementCallback;
import android.util.AttributeSet;
import android.view.ContextMenu;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.Animation;
import com.pascalwelsch.compositeandroid.core.AbstractDelegate;
import com.pascalwelsch.compositeandroid.core.CallFun0;
import com.pascalwelsch.compositeandroid.core.CallFun1;
import com.pascalwelsch.compositeandroid.core.CallFun2;
import com.pascalwelsch.compositeandroid.core.CallVoid0;
import com.pascalwelsch.compositeandroid.core.CallVoid1;
import com.pascalwelsch.compositeandroid.core.CallVoid2;
import com.pascalwelsch.compositeandroid.core.Removable;
import java.io.FileDescriptor;
import java.io.PrintWriter;
import java.util.ListIterator;
mFragmentDelegate.dump(prefix, fd, writer, args);
}
public boolean getAllowEnterTransitionOverlap() {
return mFragmentDelegate.getAllowEnterTransitionOverlap();
}
public void setAllowEnterTransitionOverlap(boolean allow) {
mFragmentDelegate.setAllowEnterTransitionOverlap(allow);
}
public boolean getAllowReturnTransitionOverlap() {
return mFragmentDelegate.getAllowReturnTransitionOverlap();
}
public void setAllowReturnTransitionOverlap(boolean allow) {
mFragmentDelegate.setAllowReturnTransitionOverlap(allow);
}
public Context getContext() {
return mFragmentDelegate.getContext();
}
public Dialog getDialog() {
if (mPlugins.isEmpty()) {
return getOriginal().super_getDialog();
}
final ListIterator<DialogFragmentPlugin> iterator = mPlugins.listIterator(mPlugins.size());
| final CallFun0<Dialog> superCall = new CallFun0<Dialog>("getDialog()") { |
passsy/CompositeAndroid | fragment/src/main/java/com/pascalwelsch/compositeandroid/fragment/DialogFragmentDelegate.java | // Path: core/src/main/java/com/pascalwelsch/compositeandroid/core/AbstractDelegate.java
// public class AbstractDelegate<T, P extends AbstractPlugin> {
//
// protected final T mOriginal;
//
// protected List<P> mPlugins = new CopyOnWriteArrayList<>();
//
// public AbstractDelegate(final T original) {
// mOriginal = original;
// }
//
// @SuppressWarnings("unchecked")
// public Removable addPlugin(final P plugin) {
// plugin.addToDelegate(this, mOriginal);
// mPlugins.add(plugin);
//
// return new Removable() {
// @Override
// public void remove() {
// mPlugins.remove(plugin);
// plugin.removeFromDelegate();
// }
// };
// }
//
// public T getOriginal() {
// return mOriginal;
// }
//
// }
//
// Path: core/src/main/java/com/pascalwelsch/compositeandroid/core/CallFun0.java
// public abstract class CallFun0<R> extends NamedSuperCall {
//
// public CallFun0(final String methodName) {
// super(methodName);
// }
//
// public abstract R call();
// }
//
// Path: core/src/main/java/com/pascalwelsch/compositeandroid/core/CallFun1.java
// public abstract class CallFun1<R, T1> extends NamedSuperCall {
//
// public CallFun1(final String methodName) {
// super(methodName);
// }
//
// public abstract R call(final T1 p1);
// }
//
// Path: core/src/main/java/com/pascalwelsch/compositeandroid/core/CallFun2.java
// public abstract class CallFun2<R, T1, T2> extends NamedSuperCall {
//
// public CallFun2(final String methodName) {
// super(methodName);
// }
//
// public abstract R call(final T1 p1, final T2 p2);
// }
//
// Path: core/src/main/java/com/pascalwelsch/compositeandroid/core/CallVoid0.java
// public abstract class CallVoid0 extends NamedSuperCall {
//
// public CallVoid0(final String methodName) {
// super(methodName);
// }
//
// public abstract void call();
// }
//
// Path: core/src/main/java/com/pascalwelsch/compositeandroid/core/CallVoid1.java
// public abstract class CallVoid1<T1> extends NamedSuperCall {
//
// public CallVoid1(final String methodName) {
// super(methodName);
// }
//
// public abstract void call(final T1 p1);
// }
//
// Path: core/src/main/java/com/pascalwelsch/compositeandroid/core/CallVoid2.java
// public abstract class CallVoid2<T1, T2> extends NamedSuperCall {
//
// public CallVoid2(final String methodName) {
// super(methodName);
// }
//
// public abstract void call(final T1 p1, final T2 p2);
// }
//
// Path: core/src/main/java/com/pascalwelsch/compositeandroid/core/Removable.java
// public interface Removable {
//
// void remove();
// }
| import android.animation.Animator;
import android.app.Activity;
import android.app.Dialog;
import android.arch.lifecycle.LiveData;
import android.arch.lifecycle.ViewModelStore;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentSender;
import android.content.IntentSender.SendIntentException;
import android.content.res.Configuration;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.app.LoaderManager;
import android.support.v4.app.SharedElementCallback;
import android.util.AttributeSet;
import android.view.ContextMenu;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.Animation;
import com.pascalwelsch.compositeandroid.core.AbstractDelegate;
import com.pascalwelsch.compositeandroid.core.CallFun0;
import com.pascalwelsch.compositeandroid.core.CallFun1;
import com.pascalwelsch.compositeandroid.core.CallFun2;
import com.pascalwelsch.compositeandroid.core.CallVoid0;
import com.pascalwelsch.compositeandroid.core.CallVoid1;
import com.pascalwelsch.compositeandroid.core.CallVoid2;
import com.pascalwelsch.compositeandroid.core.Removable;
import java.io.FileDescriptor;
import java.io.PrintWriter;
import java.util.ListIterator; |
public boolean getShowsDialog() {
if (mPlugins.isEmpty()) {
return getOriginal().super_getShowsDialog();
}
final ListIterator<DialogFragmentPlugin> iterator = mPlugins.listIterator(mPlugins.size());
final CallFun0<Boolean> superCall = new CallFun0<Boolean>("getShowsDialog()") {
@Override
public Boolean call() {
if (iterator.hasPrevious()) {
return iterator.previous().getShowsDialog(this);
} else {
return getOriginal().super_getShowsDialog();
}
}
};
return superCall.call();
}
public void setShowsDialog(boolean showsDialog) {
if (mPlugins.isEmpty()) {
getOriginal().super_setShowsDialog(showsDialog);
return;
}
final ListIterator<DialogFragmentPlugin> iterator = mPlugins.listIterator(mPlugins.size());
| // Path: core/src/main/java/com/pascalwelsch/compositeandroid/core/AbstractDelegate.java
// public class AbstractDelegate<T, P extends AbstractPlugin> {
//
// protected final T mOriginal;
//
// protected List<P> mPlugins = new CopyOnWriteArrayList<>();
//
// public AbstractDelegate(final T original) {
// mOriginal = original;
// }
//
// @SuppressWarnings("unchecked")
// public Removable addPlugin(final P plugin) {
// plugin.addToDelegate(this, mOriginal);
// mPlugins.add(plugin);
//
// return new Removable() {
// @Override
// public void remove() {
// mPlugins.remove(plugin);
// plugin.removeFromDelegate();
// }
// };
// }
//
// public T getOriginal() {
// return mOriginal;
// }
//
// }
//
// Path: core/src/main/java/com/pascalwelsch/compositeandroid/core/CallFun0.java
// public abstract class CallFun0<R> extends NamedSuperCall {
//
// public CallFun0(final String methodName) {
// super(methodName);
// }
//
// public abstract R call();
// }
//
// Path: core/src/main/java/com/pascalwelsch/compositeandroid/core/CallFun1.java
// public abstract class CallFun1<R, T1> extends NamedSuperCall {
//
// public CallFun1(final String methodName) {
// super(methodName);
// }
//
// public abstract R call(final T1 p1);
// }
//
// Path: core/src/main/java/com/pascalwelsch/compositeandroid/core/CallFun2.java
// public abstract class CallFun2<R, T1, T2> extends NamedSuperCall {
//
// public CallFun2(final String methodName) {
// super(methodName);
// }
//
// public abstract R call(final T1 p1, final T2 p2);
// }
//
// Path: core/src/main/java/com/pascalwelsch/compositeandroid/core/CallVoid0.java
// public abstract class CallVoid0 extends NamedSuperCall {
//
// public CallVoid0(final String methodName) {
// super(methodName);
// }
//
// public abstract void call();
// }
//
// Path: core/src/main/java/com/pascalwelsch/compositeandroid/core/CallVoid1.java
// public abstract class CallVoid1<T1> extends NamedSuperCall {
//
// public CallVoid1(final String methodName) {
// super(methodName);
// }
//
// public abstract void call(final T1 p1);
// }
//
// Path: core/src/main/java/com/pascalwelsch/compositeandroid/core/CallVoid2.java
// public abstract class CallVoid2<T1, T2> extends NamedSuperCall {
//
// public CallVoid2(final String methodName) {
// super(methodName);
// }
//
// public abstract void call(final T1 p1, final T2 p2);
// }
//
// Path: core/src/main/java/com/pascalwelsch/compositeandroid/core/Removable.java
// public interface Removable {
//
// void remove();
// }
// Path: fragment/src/main/java/com/pascalwelsch/compositeandroid/fragment/DialogFragmentDelegate.java
import android.animation.Animator;
import android.app.Activity;
import android.app.Dialog;
import android.arch.lifecycle.LiveData;
import android.arch.lifecycle.ViewModelStore;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentSender;
import android.content.IntentSender.SendIntentException;
import android.content.res.Configuration;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.app.LoaderManager;
import android.support.v4.app.SharedElementCallback;
import android.util.AttributeSet;
import android.view.ContextMenu;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.Animation;
import com.pascalwelsch.compositeandroid.core.AbstractDelegate;
import com.pascalwelsch.compositeandroid.core.CallFun0;
import com.pascalwelsch.compositeandroid.core.CallFun1;
import com.pascalwelsch.compositeandroid.core.CallFun2;
import com.pascalwelsch.compositeandroid.core.CallVoid0;
import com.pascalwelsch.compositeandroid.core.CallVoid1;
import com.pascalwelsch.compositeandroid.core.CallVoid2;
import com.pascalwelsch.compositeandroid.core.Removable;
import java.io.FileDescriptor;
import java.io.PrintWriter;
import java.util.ListIterator;
public boolean getShowsDialog() {
if (mPlugins.isEmpty()) {
return getOriginal().super_getShowsDialog();
}
final ListIterator<DialogFragmentPlugin> iterator = mPlugins.listIterator(mPlugins.size());
final CallFun0<Boolean> superCall = new CallFun0<Boolean>("getShowsDialog()") {
@Override
public Boolean call() {
if (iterator.hasPrevious()) {
return iterator.previous().getShowsDialog(this);
} else {
return getOriginal().super_getShowsDialog();
}
}
};
return superCall.call();
}
public void setShowsDialog(boolean showsDialog) {
if (mPlugins.isEmpty()) {
getOriginal().super_setShowsDialog(showsDialog);
return;
}
final ListIterator<DialogFragmentPlugin> iterator = mPlugins.listIterator(mPlugins.size());
| final CallVoid1<Boolean> superCall = new CallVoid1<Boolean>("setShowsDialog(Boolean)") { |
passsy/CompositeAndroid | fragment/src/main/java/com/pascalwelsch/compositeandroid/fragment/DialogFragmentDelegate.java | // Path: core/src/main/java/com/pascalwelsch/compositeandroid/core/AbstractDelegate.java
// public class AbstractDelegate<T, P extends AbstractPlugin> {
//
// protected final T mOriginal;
//
// protected List<P> mPlugins = new CopyOnWriteArrayList<>();
//
// public AbstractDelegate(final T original) {
// mOriginal = original;
// }
//
// @SuppressWarnings("unchecked")
// public Removable addPlugin(final P plugin) {
// plugin.addToDelegate(this, mOriginal);
// mPlugins.add(plugin);
//
// return new Removable() {
// @Override
// public void remove() {
// mPlugins.remove(plugin);
// plugin.removeFromDelegate();
// }
// };
// }
//
// public T getOriginal() {
// return mOriginal;
// }
//
// }
//
// Path: core/src/main/java/com/pascalwelsch/compositeandroid/core/CallFun0.java
// public abstract class CallFun0<R> extends NamedSuperCall {
//
// public CallFun0(final String methodName) {
// super(methodName);
// }
//
// public abstract R call();
// }
//
// Path: core/src/main/java/com/pascalwelsch/compositeandroid/core/CallFun1.java
// public abstract class CallFun1<R, T1> extends NamedSuperCall {
//
// public CallFun1(final String methodName) {
// super(methodName);
// }
//
// public abstract R call(final T1 p1);
// }
//
// Path: core/src/main/java/com/pascalwelsch/compositeandroid/core/CallFun2.java
// public abstract class CallFun2<R, T1, T2> extends NamedSuperCall {
//
// public CallFun2(final String methodName) {
// super(methodName);
// }
//
// public abstract R call(final T1 p1, final T2 p2);
// }
//
// Path: core/src/main/java/com/pascalwelsch/compositeandroid/core/CallVoid0.java
// public abstract class CallVoid0 extends NamedSuperCall {
//
// public CallVoid0(final String methodName) {
// super(methodName);
// }
//
// public abstract void call();
// }
//
// Path: core/src/main/java/com/pascalwelsch/compositeandroid/core/CallVoid1.java
// public abstract class CallVoid1<T1> extends NamedSuperCall {
//
// public CallVoid1(final String methodName) {
// super(methodName);
// }
//
// public abstract void call(final T1 p1);
// }
//
// Path: core/src/main/java/com/pascalwelsch/compositeandroid/core/CallVoid2.java
// public abstract class CallVoid2<T1, T2> extends NamedSuperCall {
//
// public CallVoid2(final String methodName) {
// super(methodName);
// }
//
// public abstract void call(final T1 p1, final T2 p2);
// }
//
// Path: core/src/main/java/com/pascalwelsch/compositeandroid/core/Removable.java
// public interface Removable {
//
// void remove();
// }
| import android.animation.Animator;
import android.app.Activity;
import android.app.Dialog;
import android.arch.lifecycle.LiveData;
import android.arch.lifecycle.ViewModelStore;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentSender;
import android.content.IntentSender.SendIntentException;
import android.content.res.Configuration;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.app.LoaderManager;
import android.support.v4.app.SharedElementCallback;
import android.util.AttributeSet;
import android.view.ContextMenu;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.Animation;
import com.pascalwelsch.compositeandroid.core.AbstractDelegate;
import com.pascalwelsch.compositeandroid.core.CallFun0;
import com.pascalwelsch.compositeandroid.core.CallFun1;
import com.pascalwelsch.compositeandroid.core.CallFun2;
import com.pascalwelsch.compositeandroid.core.CallVoid0;
import com.pascalwelsch.compositeandroid.core.CallVoid1;
import com.pascalwelsch.compositeandroid.core.CallVoid2;
import com.pascalwelsch.compositeandroid.core.Removable;
import java.io.FileDescriptor;
import java.io.PrintWriter;
import java.util.ListIterator; | mFragmentDelegate.onConfigurationChanged(newConfig);
}
public boolean onContextItemSelected(MenuItem item) {
return mFragmentDelegate.onContextItemSelected(item);
}
public void onCreate(@Nullable Bundle savedInstanceState) {
mFragmentDelegate.onCreate(savedInstanceState);
}
public Animation onCreateAnimation(int transit, boolean enter, int nextAnim) {
return mFragmentDelegate.onCreateAnimation(transit, enter, nextAnim);
}
public Animator onCreateAnimator(int transit, boolean enter, int nextAnim) {
return mFragmentDelegate.onCreateAnimator(transit, enter, nextAnim);
}
public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) {
mFragmentDelegate.onCreateContextMenu(menu, v, menuInfo);
}
public Dialog onCreateDialog(@Nullable Bundle savedInstanceState) {
if (mPlugins.isEmpty()) {
return getOriginal().super_onCreateDialog(savedInstanceState);
}
final ListIterator<DialogFragmentPlugin> iterator = mPlugins.listIterator(mPlugins.size());
| // Path: core/src/main/java/com/pascalwelsch/compositeandroid/core/AbstractDelegate.java
// public class AbstractDelegate<T, P extends AbstractPlugin> {
//
// protected final T mOriginal;
//
// protected List<P> mPlugins = new CopyOnWriteArrayList<>();
//
// public AbstractDelegate(final T original) {
// mOriginal = original;
// }
//
// @SuppressWarnings("unchecked")
// public Removable addPlugin(final P plugin) {
// plugin.addToDelegate(this, mOriginal);
// mPlugins.add(plugin);
//
// return new Removable() {
// @Override
// public void remove() {
// mPlugins.remove(plugin);
// plugin.removeFromDelegate();
// }
// };
// }
//
// public T getOriginal() {
// return mOriginal;
// }
//
// }
//
// Path: core/src/main/java/com/pascalwelsch/compositeandroid/core/CallFun0.java
// public abstract class CallFun0<R> extends NamedSuperCall {
//
// public CallFun0(final String methodName) {
// super(methodName);
// }
//
// public abstract R call();
// }
//
// Path: core/src/main/java/com/pascalwelsch/compositeandroid/core/CallFun1.java
// public abstract class CallFun1<R, T1> extends NamedSuperCall {
//
// public CallFun1(final String methodName) {
// super(methodName);
// }
//
// public abstract R call(final T1 p1);
// }
//
// Path: core/src/main/java/com/pascalwelsch/compositeandroid/core/CallFun2.java
// public abstract class CallFun2<R, T1, T2> extends NamedSuperCall {
//
// public CallFun2(final String methodName) {
// super(methodName);
// }
//
// public abstract R call(final T1 p1, final T2 p2);
// }
//
// Path: core/src/main/java/com/pascalwelsch/compositeandroid/core/CallVoid0.java
// public abstract class CallVoid0 extends NamedSuperCall {
//
// public CallVoid0(final String methodName) {
// super(methodName);
// }
//
// public abstract void call();
// }
//
// Path: core/src/main/java/com/pascalwelsch/compositeandroid/core/CallVoid1.java
// public abstract class CallVoid1<T1> extends NamedSuperCall {
//
// public CallVoid1(final String methodName) {
// super(methodName);
// }
//
// public abstract void call(final T1 p1);
// }
//
// Path: core/src/main/java/com/pascalwelsch/compositeandroid/core/CallVoid2.java
// public abstract class CallVoid2<T1, T2> extends NamedSuperCall {
//
// public CallVoid2(final String methodName) {
// super(methodName);
// }
//
// public abstract void call(final T1 p1, final T2 p2);
// }
//
// Path: core/src/main/java/com/pascalwelsch/compositeandroid/core/Removable.java
// public interface Removable {
//
// void remove();
// }
// Path: fragment/src/main/java/com/pascalwelsch/compositeandroid/fragment/DialogFragmentDelegate.java
import android.animation.Animator;
import android.app.Activity;
import android.app.Dialog;
import android.arch.lifecycle.LiveData;
import android.arch.lifecycle.ViewModelStore;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentSender;
import android.content.IntentSender.SendIntentException;
import android.content.res.Configuration;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.app.LoaderManager;
import android.support.v4.app.SharedElementCallback;
import android.util.AttributeSet;
import android.view.ContextMenu;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.Animation;
import com.pascalwelsch.compositeandroid.core.AbstractDelegate;
import com.pascalwelsch.compositeandroid.core.CallFun0;
import com.pascalwelsch.compositeandroid.core.CallFun1;
import com.pascalwelsch.compositeandroid.core.CallFun2;
import com.pascalwelsch.compositeandroid.core.CallVoid0;
import com.pascalwelsch.compositeandroid.core.CallVoid1;
import com.pascalwelsch.compositeandroid.core.CallVoid2;
import com.pascalwelsch.compositeandroid.core.Removable;
import java.io.FileDescriptor;
import java.io.PrintWriter;
import java.util.ListIterator;
mFragmentDelegate.onConfigurationChanged(newConfig);
}
public boolean onContextItemSelected(MenuItem item) {
return mFragmentDelegate.onContextItemSelected(item);
}
public void onCreate(@Nullable Bundle savedInstanceState) {
mFragmentDelegate.onCreate(savedInstanceState);
}
public Animation onCreateAnimation(int transit, boolean enter, int nextAnim) {
return mFragmentDelegate.onCreateAnimation(transit, enter, nextAnim);
}
public Animator onCreateAnimator(int transit, boolean enter, int nextAnim) {
return mFragmentDelegate.onCreateAnimator(transit, enter, nextAnim);
}
public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) {
mFragmentDelegate.onCreateContextMenu(menu, v, menuInfo);
}
public Dialog onCreateDialog(@Nullable Bundle savedInstanceState) {
if (mPlugins.isEmpty()) {
return getOriginal().super_onCreateDialog(savedInstanceState);
}
final ListIterator<DialogFragmentPlugin> iterator = mPlugins.listIterator(mPlugins.size());
| final CallFun1<Dialog, Bundle> superCall = new CallFun1<Dialog, Bundle>("onCreateDialog(Bundle)") { |
passsy/CompositeAndroid | fragment/src/main/java/com/pascalwelsch/compositeandroid/fragment/DialogFragmentDelegate.java | // Path: core/src/main/java/com/pascalwelsch/compositeandroid/core/AbstractDelegate.java
// public class AbstractDelegate<T, P extends AbstractPlugin> {
//
// protected final T mOriginal;
//
// protected List<P> mPlugins = new CopyOnWriteArrayList<>();
//
// public AbstractDelegate(final T original) {
// mOriginal = original;
// }
//
// @SuppressWarnings("unchecked")
// public Removable addPlugin(final P plugin) {
// plugin.addToDelegate(this, mOriginal);
// mPlugins.add(plugin);
//
// return new Removable() {
// @Override
// public void remove() {
// mPlugins.remove(plugin);
// plugin.removeFromDelegate();
// }
// };
// }
//
// public T getOriginal() {
// return mOriginal;
// }
//
// }
//
// Path: core/src/main/java/com/pascalwelsch/compositeandroid/core/CallFun0.java
// public abstract class CallFun0<R> extends NamedSuperCall {
//
// public CallFun0(final String methodName) {
// super(methodName);
// }
//
// public abstract R call();
// }
//
// Path: core/src/main/java/com/pascalwelsch/compositeandroid/core/CallFun1.java
// public abstract class CallFun1<R, T1> extends NamedSuperCall {
//
// public CallFun1(final String methodName) {
// super(methodName);
// }
//
// public abstract R call(final T1 p1);
// }
//
// Path: core/src/main/java/com/pascalwelsch/compositeandroid/core/CallFun2.java
// public abstract class CallFun2<R, T1, T2> extends NamedSuperCall {
//
// public CallFun2(final String methodName) {
// super(methodName);
// }
//
// public abstract R call(final T1 p1, final T2 p2);
// }
//
// Path: core/src/main/java/com/pascalwelsch/compositeandroid/core/CallVoid0.java
// public abstract class CallVoid0 extends NamedSuperCall {
//
// public CallVoid0(final String methodName) {
// super(methodName);
// }
//
// public abstract void call();
// }
//
// Path: core/src/main/java/com/pascalwelsch/compositeandroid/core/CallVoid1.java
// public abstract class CallVoid1<T1> extends NamedSuperCall {
//
// public CallVoid1(final String methodName) {
// super(methodName);
// }
//
// public abstract void call(final T1 p1);
// }
//
// Path: core/src/main/java/com/pascalwelsch/compositeandroid/core/CallVoid2.java
// public abstract class CallVoid2<T1, T2> extends NamedSuperCall {
//
// public CallVoid2(final String methodName) {
// super(methodName);
// }
//
// public abstract void call(final T1 p1, final T2 p2);
// }
//
// Path: core/src/main/java/com/pascalwelsch/compositeandroid/core/Removable.java
// public interface Removable {
//
// void remove();
// }
| import android.animation.Animator;
import android.app.Activity;
import android.app.Dialog;
import android.arch.lifecycle.LiveData;
import android.arch.lifecycle.ViewModelStore;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentSender;
import android.content.IntentSender.SendIntentException;
import android.content.res.Configuration;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.app.LoaderManager;
import android.support.v4.app.SharedElementCallback;
import android.util.AttributeSet;
import android.view.ContextMenu;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.Animation;
import com.pascalwelsch.compositeandroid.core.AbstractDelegate;
import com.pascalwelsch.compositeandroid.core.CallFun0;
import com.pascalwelsch.compositeandroid.core.CallFun1;
import com.pascalwelsch.compositeandroid.core.CallFun2;
import com.pascalwelsch.compositeandroid.core.CallVoid0;
import com.pascalwelsch.compositeandroid.core.CallVoid1;
import com.pascalwelsch.compositeandroid.core.CallVoid2;
import com.pascalwelsch.compositeandroid.core.Removable;
import java.io.FileDescriptor;
import java.io.PrintWriter;
import java.util.ListIterator; | }
public void setExitSharedElementCallback(SharedElementCallback callback) {
mFragmentDelegate.setExitSharedElementCallback(callback);
}
public void setHasOptionsMenu(boolean hasMenu) {
mFragmentDelegate.setHasOptionsMenu(hasMenu);
}
public void setInitialSavedState(@Nullable Fragment.SavedState state) {
mFragmentDelegate.setInitialSavedState(state);
}
public void setMenuVisibility(boolean menuVisible) {
mFragmentDelegate.setMenuVisibility(menuVisible);
}
public void setRetainInstance(boolean retain) {
mFragmentDelegate.setRetainInstance(retain);
}
public void setStyle(int style, int theme) {
if (mPlugins.isEmpty()) {
getOriginal().super_setStyle(style, theme);
return;
}
final ListIterator<DialogFragmentPlugin> iterator = mPlugins.listIterator(mPlugins.size());
| // Path: core/src/main/java/com/pascalwelsch/compositeandroid/core/AbstractDelegate.java
// public class AbstractDelegate<T, P extends AbstractPlugin> {
//
// protected final T mOriginal;
//
// protected List<P> mPlugins = new CopyOnWriteArrayList<>();
//
// public AbstractDelegate(final T original) {
// mOriginal = original;
// }
//
// @SuppressWarnings("unchecked")
// public Removable addPlugin(final P plugin) {
// plugin.addToDelegate(this, mOriginal);
// mPlugins.add(plugin);
//
// return new Removable() {
// @Override
// public void remove() {
// mPlugins.remove(plugin);
// plugin.removeFromDelegate();
// }
// };
// }
//
// public T getOriginal() {
// return mOriginal;
// }
//
// }
//
// Path: core/src/main/java/com/pascalwelsch/compositeandroid/core/CallFun0.java
// public abstract class CallFun0<R> extends NamedSuperCall {
//
// public CallFun0(final String methodName) {
// super(methodName);
// }
//
// public abstract R call();
// }
//
// Path: core/src/main/java/com/pascalwelsch/compositeandroid/core/CallFun1.java
// public abstract class CallFun1<R, T1> extends NamedSuperCall {
//
// public CallFun1(final String methodName) {
// super(methodName);
// }
//
// public abstract R call(final T1 p1);
// }
//
// Path: core/src/main/java/com/pascalwelsch/compositeandroid/core/CallFun2.java
// public abstract class CallFun2<R, T1, T2> extends NamedSuperCall {
//
// public CallFun2(final String methodName) {
// super(methodName);
// }
//
// public abstract R call(final T1 p1, final T2 p2);
// }
//
// Path: core/src/main/java/com/pascalwelsch/compositeandroid/core/CallVoid0.java
// public abstract class CallVoid0 extends NamedSuperCall {
//
// public CallVoid0(final String methodName) {
// super(methodName);
// }
//
// public abstract void call();
// }
//
// Path: core/src/main/java/com/pascalwelsch/compositeandroid/core/CallVoid1.java
// public abstract class CallVoid1<T1> extends NamedSuperCall {
//
// public CallVoid1(final String methodName) {
// super(methodName);
// }
//
// public abstract void call(final T1 p1);
// }
//
// Path: core/src/main/java/com/pascalwelsch/compositeandroid/core/CallVoid2.java
// public abstract class CallVoid2<T1, T2> extends NamedSuperCall {
//
// public CallVoid2(final String methodName) {
// super(methodName);
// }
//
// public abstract void call(final T1 p1, final T2 p2);
// }
//
// Path: core/src/main/java/com/pascalwelsch/compositeandroid/core/Removable.java
// public interface Removable {
//
// void remove();
// }
// Path: fragment/src/main/java/com/pascalwelsch/compositeandroid/fragment/DialogFragmentDelegate.java
import android.animation.Animator;
import android.app.Activity;
import android.app.Dialog;
import android.arch.lifecycle.LiveData;
import android.arch.lifecycle.ViewModelStore;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentSender;
import android.content.IntentSender.SendIntentException;
import android.content.res.Configuration;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.app.LoaderManager;
import android.support.v4.app.SharedElementCallback;
import android.util.AttributeSet;
import android.view.ContextMenu;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.Animation;
import com.pascalwelsch.compositeandroid.core.AbstractDelegate;
import com.pascalwelsch.compositeandroid.core.CallFun0;
import com.pascalwelsch.compositeandroid.core.CallFun1;
import com.pascalwelsch.compositeandroid.core.CallFun2;
import com.pascalwelsch.compositeandroid.core.CallVoid0;
import com.pascalwelsch.compositeandroid.core.CallVoid1;
import com.pascalwelsch.compositeandroid.core.CallVoid2;
import com.pascalwelsch.compositeandroid.core.Removable;
import java.io.FileDescriptor;
import java.io.PrintWriter;
import java.util.ListIterator;
}
public void setExitSharedElementCallback(SharedElementCallback callback) {
mFragmentDelegate.setExitSharedElementCallback(callback);
}
public void setHasOptionsMenu(boolean hasMenu) {
mFragmentDelegate.setHasOptionsMenu(hasMenu);
}
public void setInitialSavedState(@Nullable Fragment.SavedState state) {
mFragmentDelegate.setInitialSavedState(state);
}
public void setMenuVisibility(boolean menuVisible) {
mFragmentDelegate.setMenuVisibility(menuVisible);
}
public void setRetainInstance(boolean retain) {
mFragmentDelegate.setRetainInstance(retain);
}
public void setStyle(int style, int theme) {
if (mPlugins.isEmpty()) {
getOriginal().super_setStyle(style, theme);
return;
}
final ListIterator<DialogFragmentPlugin> iterator = mPlugins.listIterator(mPlugins.size());
| final CallVoid2<Integer, Integer> superCall = new CallVoid2<Integer, Integer>("setStyle(Integer, Integer)") { |
passsy/CompositeAndroid | fragment/src/main/java/com/pascalwelsch/compositeandroid/fragment/DialogFragmentDelegate.java | // Path: core/src/main/java/com/pascalwelsch/compositeandroid/core/AbstractDelegate.java
// public class AbstractDelegate<T, P extends AbstractPlugin> {
//
// protected final T mOriginal;
//
// protected List<P> mPlugins = new CopyOnWriteArrayList<>();
//
// public AbstractDelegate(final T original) {
// mOriginal = original;
// }
//
// @SuppressWarnings("unchecked")
// public Removable addPlugin(final P plugin) {
// plugin.addToDelegate(this, mOriginal);
// mPlugins.add(plugin);
//
// return new Removable() {
// @Override
// public void remove() {
// mPlugins.remove(plugin);
// plugin.removeFromDelegate();
// }
// };
// }
//
// public T getOriginal() {
// return mOriginal;
// }
//
// }
//
// Path: core/src/main/java/com/pascalwelsch/compositeandroid/core/CallFun0.java
// public abstract class CallFun0<R> extends NamedSuperCall {
//
// public CallFun0(final String methodName) {
// super(methodName);
// }
//
// public abstract R call();
// }
//
// Path: core/src/main/java/com/pascalwelsch/compositeandroid/core/CallFun1.java
// public abstract class CallFun1<R, T1> extends NamedSuperCall {
//
// public CallFun1(final String methodName) {
// super(methodName);
// }
//
// public abstract R call(final T1 p1);
// }
//
// Path: core/src/main/java/com/pascalwelsch/compositeandroid/core/CallFun2.java
// public abstract class CallFun2<R, T1, T2> extends NamedSuperCall {
//
// public CallFun2(final String methodName) {
// super(methodName);
// }
//
// public abstract R call(final T1 p1, final T2 p2);
// }
//
// Path: core/src/main/java/com/pascalwelsch/compositeandroid/core/CallVoid0.java
// public abstract class CallVoid0 extends NamedSuperCall {
//
// public CallVoid0(final String methodName) {
// super(methodName);
// }
//
// public abstract void call();
// }
//
// Path: core/src/main/java/com/pascalwelsch/compositeandroid/core/CallVoid1.java
// public abstract class CallVoid1<T1> extends NamedSuperCall {
//
// public CallVoid1(final String methodName) {
// super(methodName);
// }
//
// public abstract void call(final T1 p1);
// }
//
// Path: core/src/main/java/com/pascalwelsch/compositeandroid/core/CallVoid2.java
// public abstract class CallVoid2<T1, T2> extends NamedSuperCall {
//
// public CallVoid2(final String methodName) {
// super(methodName);
// }
//
// public abstract void call(final T1 p1, final T2 p2);
// }
//
// Path: core/src/main/java/com/pascalwelsch/compositeandroid/core/Removable.java
// public interface Removable {
//
// void remove();
// }
| import android.animation.Animator;
import android.app.Activity;
import android.app.Dialog;
import android.arch.lifecycle.LiveData;
import android.arch.lifecycle.ViewModelStore;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentSender;
import android.content.IntentSender.SendIntentException;
import android.content.res.Configuration;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.app.LoaderManager;
import android.support.v4.app.SharedElementCallback;
import android.util.AttributeSet;
import android.view.ContextMenu;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.Animation;
import com.pascalwelsch.compositeandroid.core.AbstractDelegate;
import com.pascalwelsch.compositeandroid.core.CallFun0;
import com.pascalwelsch.compositeandroid.core.CallFun1;
import com.pascalwelsch.compositeandroid.core.CallFun2;
import com.pascalwelsch.compositeandroid.core.CallVoid0;
import com.pascalwelsch.compositeandroid.core.CallVoid1;
import com.pascalwelsch.compositeandroid.core.CallVoid2;
import com.pascalwelsch.compositeandroid.core.Removable;
import java.io.FileDescriptor;
import java.io.PrintWriter;
import java.util.ListIterator; | public void show(FragmentManager manager, String tag) {
if (mPlugins.isEmpty()) {
getOriginal().super_show(manager, tag);
return;
}
final ListIterator<DialogFragmentPlugin> iterator = mPlugins.listIterator(mPlugins.size());
final CallVoid2<FragmentManager, String> superCall = new CallVoid2<FragmentManager, String>(
"show(FragmentManager, String)") {
@Override
public void call(final FragmentManager manager, final String tag) {
if (iterator.hasPrevious()) {
iterator.previous().show(this, manager, tag);
} else {
getOriginal().super_show(manager, tag);
}
}
};
superCall.call(manager, tag);
}
public int show(FragmentTransaction transaction, String tag) {
if (mPlugins.isEmpty()) {
return getOriginal().super_show(transaction, tag);
}
final ListIterator<DialogFragmentPlugin> iterator = mPlugins.listIterator(mPlugins.size());
| // Path: core/src/main/java/com/pascalwelsch/compositeandroid/core/AbstractDelegate.java
// public class AbstractDelegate<T, P extends AbstractPlugin> {
//
// protected final T mOriginal;
//
// protected List<P> mPlugins = new CopyOnWriteArrayList<>();
//
// public AbstractDelegate(final T original) {
// mOriginal = original;
// }
//
// @SuppressWarnings("unchecked")
// public Removable addPlugin(final P plugin) {
// plugin.addToDelegate(this, mOriginal);
// mPlugins.add(plugin);
//
// return new Removable() {
// @Override
// public void remove() {
// mPlugins.remove(plugin);
// plugin.removeFromDelegate();
// }
// };
// }
//
// public T getOriginal() {
// return mOriginal;
// }
//
// }
//
// Path: core/src/main/java/com/pascalwelsch/compositeandroid/core/CallFun0.java
// public abstract class CallFun0<R> extends NamedSuperCall {
//
// public CallFun0(final String methodName) {
// super(methodName);
// }
//
// public abstract R call();
// }
//
// Path: core/src/main/java/com/pascalwelsch/compositeandroid/core/CallFun1.java
// public abstract class CallFun1<R, T1> extends NamedSuperCall {
//
// public CallFun1(final String methodName) {
// super(methodName);
// }
//
// public abstract R call(final T1 p1);
// }
//
// Path: core/src/main/java/com/pascalwelsch/compositeandroid/core/CallFun2.java
// public abstract class CallFun2<R, T1, T2> extends NamedSuperCall {
//
// public CallFun2(final String methodName) {
// super(methodName);
// }
//
// public abstract R call(final T1 p1, final T2 p2);
// }
//
// Path: core/src/main/java/com/pascalwelsch/compositeandroid/core/CallVoid0.java
// public abstract class CallVoid0 extends NamedSuperCall {
//
// public CallVoid0(final String methodName) {
// super(methodName);
// }
//
// public abstract void call();
// }
//
// Path: core/src/main/java/com/pascalwelsch/compositeandroid/core/CallVoid1.java
// public abstract class CallVoid1<T1> extends NamedSuperCall {
//
// public CallVoid1(final String methodName) {
// super(methodName);
// }
//
// public abstract void call(final T1 p1);
// }
//
// Path: core/src/main/java/com/pascalwelsch/compositeandroid/core/CallVoid2.java
// public abstract class CallVoid2<T1, T2> extends NamedSuperCall {
//
// public CallVoid2(final String methodName) {
// super(methodName);
// }
//
// public abstract void call(final T1 p1, final T2 p2);
// }
//
// Path: core/src/main/java/com/pascalwelsch/compositeandroid/core/Removable.java
// public interface Removable {
//
// void remove();
// }
// Path: fragment/src/main/java/com/pascalwelsch/compositeandroid/fragment/DialogFragmentDelegate.java
import android.animation.Animator;
import android.app.Activity;
import android.app.Dialog;
import android.arch.lifecycle.LiveData;
import android.arch.lifecycle.ViewModelStore;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentSender;
import android.content.IntentSender.SendIntentException;
import android.content.res.Configuration;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.app.LoaderManager;
import android.support.v4.app.SharedElementCallback;
import android.util.AttributeSet;
import android.view.ContextMenu;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.Animation;
import com.pascalwelsch.compositeandroid.core.AbstractDelegate;
import com.pascalwelsch.compositeandroid.core.CallFun0;
import com.pascalwelsch.compositeandroid.core.CallFun1;
import com.pascalwelsch.compositeandroid.core.CallFun2;
import com.pascalwelsch.compositeandroid.core.CallVoid0;
import com.pascalwelsch.compositeandroid.core.CallVoid1;
import com.pascalwelsch.compositeandroid.core.CallVoid2;
import com.pascalwelsch.compositeandroid.core.Removable;
import java.io.FileDescriptor;
import java.io.PrintWriter;
import java.util.ListIterator;
public void show(FragmentManager manager, String tag) {
if (mPlugins.isEmpty()) {
getOriginal().super_show(manager, tag);
return;
}
final ListIterator<DialogFragmentPlugin> iterator = mPlugins.listIterator(mPlugins.size());
final CallVoid2<FragmentManager, String> superCall = new CallVoid2<FragmentManager, String>(
"show(FragmentManager, String)") {
@Override
public void call(final FragmentManager manager, final String tag) {
if (iterator.hasPrevious()) {
iterator.previous().show(this, manager, tag);
} else {
getOriginal().super_show(manager, tag);
}
}
};
superCall.call(manager, tag);
}
public int show(FragmentTransaction transaction, String tag) {
if (mPlugins.isEmpty()) {
return getOriginal().super_show(transaction, tag);
}
final ListIterator<DialogFragmentPlugin> iterator = mPlugins.listIterator(mPlugins.size());
| final CallFun2<Integer, FragmentTransaction, String> superCall |
passsy/CompositeAndroid | fragment/src/main/java/com/pascalwelsch/compositeandroid/fragment/CompositeDialogFragment.java | // Path: core/src/main/java/com/pascalwelsch/compositeandroid/core/Removable.java
// public interface Removable {
//
// void remove();
// }
//
// Path: core/src/main/java/com/pascalwelsch/compositeandroid/core/SuppressedException.java
// public class SuppressedException extends RuntimeException {
//
// /**
// * Constructs a new {@code RuntimeException} with the current stack trace
// * and the specified cause.
// *
// * @param throwable the cause of this exception.
// */
// public SuppressedException(final Throwable throwable) {
// super(throwable);
// }
// }
| import android.animation.Animator;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.Dialog;
import android.arch.lifecycle.LiveData;
import android.arch.lifecycle.ViewModelStore;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentSender;
import android.content.IntentSender.SendIntentException;
import android.content.res.Configuration;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.DialogFragment;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.app.LoaderManager;
import android.support.v4.app.SharedElementCallback;
import android.util.AttributeSet;
import android.view.ContextMenu;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.Animation;
import com.pascalwelsch.compositeandroid.core.Removable;
import com.pascalwelsch.compositeandroid.core.SuppressedException;
import java.io.FileDescriptor;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List; | public void onStop() {
delegate.onStop();
}
@Override
public void onSaveInstanceState(@NonNull Bundle outState) {
delegate.onSaveInstanceState(outState);
}
@Override
public void onDestroyView() {
delegate.onDestroyView();
}
@Override
public void onDestroy() {
delegate.onDestroy();
}
@Override
public void onDetach() {
delegate.onDetach();
}
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions,
@NonNull int[] grantResults) {
delegate.onRequestPermissionsResult(requestCode, permissions, grantResults);
}
| // Path: core/src/main/java/com/pascalwelsch/compositeandroid/core/Removable.java
// public interface Removable {
//
// void remove();
// }
//
// Path: core/src/main/java/com/pascalwelsch/compositeandroid/core/SuppressedException.java
// public class SuppressedException extends RuntimeException {
//
// /**
// * Constructs a new {@code RuntimeException} with the current stack trace
// * and the specified cause.
// *
// * @param throwable the cause of this exception.
// */
// public SuppressedException(final Throwable throwable) {
// super(throwable);
// }
// }
// Path: fragment/src/main/java/com/pascalwelsch/compositeandroid/fragment/CompositeDialogFragment.java
import android.animation.Animator;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.Dialog;
import android.arch.lifecycle.LiveData;
import android.arch.lifecycle.ViewModelStore;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentSender;
import android.content.IntentSender.SendIntentException;
import android.content.res.Configuration;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.DialogFragment;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.app.LoaderManager;
import android.support.v4.app.SharedElementCallback;
import android.util.AttributeSet;
import android.view.ContextMenu;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.Animation;
import com.pascalwelsch.compositeandroid.core.Removable;
import com.pascalwelsch.compositeandroid.core.SuppressedException;
import java.io.FileDescriptor;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;
public void onStop() {
delegate.onStop();
}
@Override
public void onSaveInstanceState(@NonNull Bundle outState) {
delegate.onSaveInstanceState(outState);
}
@Override
public void onDestroyView() {
delegate.onDestroyView();
}
@Override
public void onDestroy() {
delegate.onDestroy();
}
@Override
public void onDetach() {
delegate.onDetach();
}
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions,
@NonNull int[] grantResults) {
delegate.onRequestPermissionsResult(requestCode, permissions, grantResults);
}
| public List<Removable> addDialogFragmentPlugins(@NonNull final DialogFragmentPlugin... plugins) { |
passsy/CompositeAndroid | fragment/src/main/java/com/pascalwelsch/compositeandroid/fragment/CompositeDialogFragment.java | // Path: core/src/main/java/com/pascalwelsch/compositeandroid/core/Removable.java
// public interface Removable {
//
// void remove();
// }
//
// Path: core/src/main/java/com/pascalwelsch/compositeandroid/core/SuppressedException.java
// public class SuppressedException extends RuntimeException {
//
// /**
// * Constructs a new {@code RuntimeException} with the current stack trace
// * and the specified cause.
// *
// * @param throwable the cause of this exception.
// */
// public SuppressedException(final Throwable throwable) {
// super(throwable);
// }
// }
| import android.animation.Animator;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.Dialog;
import android.arch.lifecycle.LiveData;
import android.arch.lifecycle.ViewModelStore;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentSender;
import android.content.IntentSender.SendIntentException;
import android.content.res.Configuration;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.DialogFragment;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.app.LoaderManager;
import android.support.v4.app.SharedElementCallback;
import android.util.AttributeSet;
import android.view.ContextMenu;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.Animation;
import com.pascalwelsch.compositeandroid.core.Removable;
import com.pascalwelsch.compositeandroid.core.SuppressedException;
import java.io.FileDescriptor;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List; | public void showNow(FragmentManager manager, String tag) {
delegate.showNow(manager, tag);
}
@Override
public void startActivity(Intent intent) {
delegate.startActivity(intent);
}
@Override
public void startActivity(Intent intent, @Nullable Bundle options) {
delegate.startActivity(intent, options);
}
@Override
public void startActivityForResult(Intent intent, int requestCode) {
delegate.startActivityForResult(intent, requestCode);
}
@Override
public void startActivityForResult(Intent intent, int requestCode, @Nullable Bundle options) {
delegate.startActivityForResult(intent, requestCode, options);
}
@Override
public void startIntentSenderForResult(IntentSender intent, int requestCode, @Nullable Intent fillInIntent,
int flagsMask, int flagsValues, int extraFlags, Bundle options) throws SendIntentException {
try {
delegate.startIntentSenderForResult(intent, requestCode, fillInIntent, flagsMask, flagsValues, extraFlags,
options); | // Path: core/src/main/java/com/pascalwelsch/compositeandroid/core/Removable.java
// public interface Removable {
//
// void remove();
// }
//
// Path: core/src/main/java/com/pascalwelsch/compositeandroid/core/SuppressedException.java
// public class SuppressedException extends RuntimeException {
//
// /**
// * Constructs a new {@code RuntimeException} with the current stack trace
// * and the specified cause.
// *
// * @param throwable the cause of this exception.
// */
// public SuppressedException(final Throwable throwable) {
// super(throwable);
// }
// }
// Path: fragment/src/main/java/com/pascalwelsch/compositeandroid/fragment/CompositeDialogFragment.java
import android.animation.Animator;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.Dialog;
import android.arch.lifecycle.LiveData;
import android.arch.lifecycle.ViewModelStore;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentSender;
import android.content.IntentSender.SendIntentException;
import android.content.res.Configuration;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.DialogFragment;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.app.LoaderManager;
import android.support.v4.app.SharedElementCallback;
import android.util.AttributeSet;
import android.view.ContextMenu;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.Animation;
import com.pascalwelsch.compositeandroid.core.Removable;
import com.pascalwelsch.compositeandroid.core.SuppressedException;
import java.io.FileDescriptor;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;
public void showNow(FragmentManager manager, String tag) {
delegate.showNow(manager, tag);
}
@Override
public void startActivity(Intent intent) {
delegate.startActivity(intent);
}
@Override
public void startActivity(Intent intent, @Nullable Bundle options) {
delegate.startActivity(intent, options);
}
@Override
public void startActivityForResult(Intent intent, int requestCode) {
delegate.startActivityForResult(intent, requestCode);
}
@Override
public void startActivityForResult(Intent intent, int requestCode, @Nullable Bundle options) {
delegate.startActivityForResult(intent, requestCode, options);
}
@Override
public void startIntentSenderForResult(IntentSender intent, int requestCode, @Nullable Intent fillInIntent,
int flagsMask, int flagsValues, int extraFlags, Bundle options) throws SendIntentException {
try {
delegate.startIntentSenderForResult(intent, requestCode, fillInIntent, flagsMask, flagsValues, extraFlags,
options); | } catch (SuppressedException e) { |
passsy/CompositeAndroid | activity/src/main/java/com/pascalwelsch/compositeandroid/activity/CompositeActivity.java | // Path: core/src/main/java/com/pascalwelsch/compositeandroid/core/Removable.java
// public interface Removable {
//
// void remove();
// }
| import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.ActivityManager;
import android.app.ActivityManager.TaskDescription;
import android.app.ActivityOptions;
import android.app.Application;
import android.app.Dialog;
import android.app.KeyguardManager;
import android.app.PendingIntent;
import android.app.PictureInPictureParams;
import android.app.SearchManager;
import android.app.VoiceInteractor;
import android.app.assist.AssistContent;
import android.arch.lifecycle.Lifecycle;
import android.arch.lifecycle.ViewModelStore;
import android.content.ActivityNotFoundException;
import android.content.BroadcastReceiver;
import android.content.ComponentCallbacks;
import android.content.ComponentCallbacks2;
import android.content.ComponentName;
import android.content.ContentResolver;
import android.content.Context;
import android.content.CursorLoader;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.IntentSender;
import android.content.IntentSender.SendIntentException;
import android.content.ServiceConnection;
import android.content.SharedPreferences;
import android.content.pm.ActivityInfo;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.content.res.AssetManager;
import android.content.res.Configuration;
import android.content.res.Resources;
import android.content.res.Resources.Theme;
import android.database.Cursor;
import android.database.DatabaseErrorHandler;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteDatabase.CursorFactory;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.PersistableBundle;
import android.os.UserHandle;
import android.provider.Settings;
import android.service.voice.VoiceInteractionService;
import android.service.voice.VoiceInteractionSession;
import android.service.vr.VrListenerService;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.DialogFragment;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.LoaderManager;
import android.support.v4.app.SharedElementCallback;
import android.support.v4.app.SupportActivity;
import android.support.v4.app.TaskStackBuilder;
import android.support.v7.app.ActionBar;
import android.support.v7.app.ActionBarDrawerToggle.Delegate;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.app.AppCompatDelegate;
import android.support.v7.view.ActionMode;
import android.support.v7.view.ActionMode.Callback;
import android.support.v7.widget.Toolbar;
import android.transition.Scene;
import android.transition.TransitionManager;
import android.util.AttributeSet;
import android.util.Pair;
import android.view.ContextMenu;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.Display;
import android.view.DragAndDropPermissions;
import android.view.DragEvent;
import android.view.InputDevice;
import android.view.KeyEvent;
import android.view.KeyboardShortcutGroup;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.SearchEvent;
import android.view.View;
import android.view.ViewGroup.LayoutParams;
import android.view.Window;
import android.view.WindowManager;
import android.view.accessibility.AccessibilityEvent;
import com.pascalwelsch.compositeandroid.core.Removable;
import java.io.File;
import java.io.FileDescriptor;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Executor; | /**
* This is the same as {@link #onSaveInstanceState} but is called for activities
* created with the attribute {@link android.R.attr#persistableMode} set to
* <code>persistAcrossReboots</code>. The {@link PersistableBundle} passed
* in will be saved and presented in {@link #onCreate(Bundle, PersistableBundle)}
* the first time that this activity is restarted following the next device reboot.
*
* @param outState Bundle in which to place your saved state.
* @param outPersistentState State which will be saved across reboots.
* @see #onSaveInstanceState(Bundle)
* @see #onCreate
* @see #onRestoreInstanceState(Bundle, PersistableBundle)
* @see #onPause
*/
@Override
public void onSaveInstanceState(Bundle outState, PersistableBundle outPersistentState) {
delegate.onSaveInstanceState(outState, outPersistentState);
}
@Override
public void onDestroy() {
delegate.onDestroy();
}
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions,
@NonNull int[] grantResults) {
delegate.onRequestPermissionsResult(requestCode, permissions, grantResults);
}
| // Path: core/src/main/java/com/pascalwelsch/compositeandroid/core/Removable.java
// public interface Removable {
//
// void remove();
// }
// Path: activity/src/main/java/com/pascalwelsch/compositeandroid/activity/CompositeActivity.java
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.ActivityManager;
import android.app.ActivityManager.TaskDescription;
import android.app.ActivityOptions;
import android.app.Application;
import android.app.Dialog;
import android.app.KeyguardManager;
import android.app.PendingIntent;
import android.app.PictureInPictureParams;
import android.app.SearchManager;
import android.app.VoiceInteractor;
import android.app.assist.AssistContent;
import android.arch.lifecycle.Lifecycle;
import android.arch.lifecycle.ViewModelStore;
import android.content.ActivityNotFoundException;
import android.content.BroadcastReceiver;
import android.content.ComponentCallbacks;
import android.content.ComponentCallbacks2;
import android.content.ComponentName;
import android.content.ContentResolver;
import android.content.Context;
import android.content.CursorLoader;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.IntentSender;
import android.content.IntentSender.SendIntentException;
import android.content.ServiceConnection;
import android.content.SharedPreferences;
import android.content.pm.ActivityInfo;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.content.res.AssetManager;
import android.content.res.Configuration;
import android.content.res.Resources;
import android.content.res.Resources.Theme;
import android.database.Cursor;
import android.database.DatabaseErrorHandler;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteDatabase.CursorFactory;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.PersistableBundle;
import android.os.UserHandle;
import android.provider.Settings;
import android.service.voice.VoiceInteractionService;
import android.service.voice.VoiceInteractionSession;
import android.service.vr.VrListenerService;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.DialogFragment;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.LoaderManager;
import android.support.v4.app.SharedElementCallback;
import android.support.v4.app.SupportActivity;
import android.support.v4.app.TaskStackBuilder;
import android.support.v7.app.ActionBar;
import android.support.v7.app.ActionBarDrawerToggle.Delegate;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.app.AppCompatDelegate;
import android.support.v7.view.ActionMode;
import android.support.v7.view.ActionMode.Callback;
import android.support.v7.widget.Toolbar;
import android.transition.Scene;
import android.transition.TransitionManager;
import android.util.AttributeSet;
import android.util.Pair;
import android.view.ContextMenu;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.Display;
import android.view.DragAndDropPermissions;
import android.view.DragEvent;
import android.view.InputDevice;
import android.view.KeyEvent;
import android.view.KeyboardShortcutGroup;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.SearchEvent;
import android.view.View;
import android.view.ViewGroup.LayoutParams;
import android.view.Window;
import android.view.WindowManager;
import android.view.accessibility.AccessibilityEvent;
import com.pascalwelsch.compositeandroid.core.Removable;
import java.io.File;
import java.io.FileDescriptor;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Executor;
/**
* This is the same as {@link #onSaveInstanceState} but is called for activities
* created with the attribute {@link android.R.attr#persistableMode} set to
* <code>persistAcrossReboots</code>. The {@link PersistableBundle} passed
* in will be saved and presented in {@link #onCreate(Bundle, PersistableBundle)}
* the first time that this activity is restarted following the next device reboot.
*
* @param outState Bundle in which to place your saved state.
* @param outPersistentState State which will be saved across reboots.
* @see #onSaveInstanceState(Bundle)
* @see #onCreate
* @see #onRestoreInstanceState(Bundle, PersistableBundle)
* @see #onPause
*/
@Override
public void onSaveInstanceState(Bundle outState, PersistableBundle outPersistentState) {
delegate.onSaveInstanceState(outState, outPersistentState);
}
@Override
public void onDestroy() {
delegate.onDestroy();
}
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions,
@NonNull int[] grantResults) {
delegate.onRequestPermissionsResult(requestCode, permissions, grantResults);
}
| public List<Removable> addActivityPlugins(@NonNull final ActivityPlugin... plugins) { |
epickrram/perf-workshop | src/main/java/com/epickrram/workshop/perf/setup/InputGenerator.java | // Path: src/main/java/com/epickrram/workshop/perf/config/CommandLineArgs.java
// public final class CommandLineArgs
// {
// private final long executionTimestamp = System.currentTimeMillis();
//
// @Parameter(names = "-i", description = "number of iterations")
// private int numberOfIterations = 20;
// @Parameter(names = "-w", description = "number of warm-ups")
// private int numberOfWarmups = 10;
// @Parameter(names = "-n", description = "number of records per input file")
// private int numberOfRecords = 10000;
// @Parameter(names = "-l", description = "length of record (bytes)")
// private int recordLength = 64;
// @Parameter(names = "-f", description = "data file (default: /tmp/perf-workshop-input.bin)")
// private String inputFile = getTmpDirectory() + File.separator + "perf-workshop-input.bin";
// @Parameter(names = "-b", description = "buffer size (must be a power of two)")
// private int bufferSize = 524288;
// @Parameter(names = "-j", description = "journal file (default: /tmp/perf-workshop-output.jnl)")
// private String journalFile = getTmpDirectory() + File.separator + "perf-workshop-output.jnl";
// @Parameter(names = "-d", description = "output dir (default: /tmp)")
// private String outputDir = getTmpDirectory();
// @Parameter(names = "-o", description = "overrides file (default: /tmp/perf-workshop.properties)")
// private String overrideFile = getTmpDirectory() + File.separator + "perf-workshop.properties";
// @Parameter(names = "-r", description = "report format", variableArity = true)
// private List<String> reportFormats = asList(ReportFormat.LONG.name());
// @Parameter(names = "-s", description = "run busy spinning threads to perturb system")
// private boolean runSpinners = false;
// @Parameter(names = "-t", description = "test label")
// private String testLabel = Long.toString(executionTimestamp);
// @Parameter(names = "-h", description = "print help and exit", help = true)
// private boolean help;
//
// public int getBufferSize()
// {
// return bufferSize;
// }
//
// public String getInputFile()
// {
// return inputFile;
// }
//
// public int getNumberOfIterations()
// {
// return numberOfIterations;
// }
//
// public int getNumberOfWarmups()
// {
// return numberOfWarmups;
// }
//
// public int getNumberOfRecords()
// {
// return numberOfRecords;
// }
//
// public int getRecordLength()
// {
// return recordLength;
// }
//
// public String getJournalFile()
// {
// return journalFile;
// }
//
// public String getOutputDir()
// {
// return outputDir;
// }
//
// public boolean runSpinners()
// {
// return runSpinners;
// }
//
// private static String getTmpDirectory()
// {
// return getProperty("java.io.tmpdir");
// }
//
// public String getOverrideFile()
// {
// return overrideFile;
// }
//
// public String getTestLabel()
// {
// return testLabel;
// }
//
// public boolean isHelp()
// {
// return help;
// }
//
// public Set<ReportFormat> getReportFormats()
// {
// final EnumSet<ReportFormat> formats = EnumSet.noneOf(ReportFormat.class);
// for (final String reportFormat : reportFormats)
// {
// formats.add(parseReportFormat(reportFormat));
// }
// return formats;
// }
//
// private ReportFormat parseReportFormat(final String reportFormat)
// {
// try
// {
// return ReportFormat.valueOf(reportFormat);
// }
// catch(final RuntimeException e)
// {
// throw new IllegalArgumentException("Unable to parse report format, must be one of: " +
// Arrays.toString(ReportFormat.values()));
// }
// }
//
// public long getExecutionTimestamp()
// {
// return executionTimestamp;
// }
// }
| import com.beust.jcommander.JCommander;
import com.epickrram.workshop.perf.config.CommandLineArgs;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Random; | package com.epickrram.workshop.perf.setup;
//////////////////////////////////////////////////////////////////////////////////
// Copyright 2015 Mark Price mark at epickrram.com //
// //
// 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. //
//////////////////////////////////////////////////////////////////////////////////
public final class InputGenerator
{ | // Path: src/main/java/com/epickrram/workshop/perf/config/CommandLineArgs.java
// public final class CommandLineArgs
// {
// private final long executionTimestamp = System.currentTimeMillis();
//
// @Parameter(names = "-i", description = "number of iterations")
// private int numberOfIterations = 20;
// @Parameter(names = "-w", description = "number of warm-ups")
// private int numberOfWarmups = 10;
// @Parameter(names = "-n", description = "number of records per input file")
// private int numberOfRecords = 10000;
// @Parameter(names = "-l", description = "length of record (bytes)")
// private int recordLength = 64;
// @Parameter(names = "-f", description = "data file (default: /tmp/perf-workshop-input.bin)")
// private String inputFile = getTmpDirectory() + File.separator + "perf-workshop-input.bin";
// @Parameter(names = "-b", description = "buffer size (must be a power of two)")
// private int bufferSize = 524288;
// @Parameter(names = "-j", description = "journal file (default: /tmp/perf-workshop-output.jnl)")
// private String journalFile = getTmpDirectory() + File.separator + "perf-workshop-output.jnl";
// @Parameter(names = "-d", description = "output dir (default: /tmp)")
// private String outputDir = getTmpDirectory();
// @Parameter(names = "-o", description = "overrides file (default: /tmp/perf-workshop.properties)")
// private String overrideFile = getTmpDirectory() + File.separator + "perf-workshop.properties";
// @Parameter(names = "-r", description = "report format", variableArity = true)
// private List<String> reportFormats = asList(ReportFormat.LONG.name());
// @Parameter(names = "-s", description = "run busy spinning threads to perturb system")
// private boolean runSpinners = false;
// @Parameter(names = "-t", description = "test label")
// private String testLabel = Long.toString(executionTimestamp);
// @Parameter(names = "-h", description = "print help and exit", help = true)
// private boolean help;
//
// public int getBufferSize()
// {
// return bufferSize;
// }
//
// public String getInputFile()
// {
// return inputFile;
// }
//
// public int getNumberOfIterations()
// {
// return numberOfIterations;
// }
//
// public int getNumberOfWarmups()
// {
// return numberOfWarmups;
// }
//
// public int getNumberOfRecords()
// {
// return numberOfRecords;
// }
//
// public int getRecordLength()
// {
// return recordLength;
// }
//
// public String getJournalFile()
// {
// return journalFile;
// }
//
// public String getOutputDir()
// {
// return outputDir;
// }
//
// public boolean runSpinners()
// {
// return runSpinners;
// }
//
// private static String getTmpDirectory()
// {
// return getProperty("java.io.tmpdir");
// }
//
// public String getOverrideFile()
// {
// return overrideFile;
// }
//
// public String getTestLabel()
// {
// return testLabel;
// }
//
// public boolean isHelp()
// {
// return help;
// }
//
// public Set<ReportFormat> getReportFormats()
// {
// final EnumSet<ReportFormat> formats = EnumSet.noneOf(ReportFormat.class);
// for (final String reportFormat : reportFormats)
// {
// formats.add(parseReportFormat(reportFormat));
// }
// return formats;
// }
//
// private ReportFormat parseReportFormat(final String reportFormat)
// {
// try
// {
// return ReportFormat.valueOf(reportFormat);
// }
// catch(final RuntimeException e)
// {
// throw new IllegalArgumentException("Unable to parse report format, must be one of: " +
// Arrays.toString(ReportFormat.values()));
// }
// }
//
// public long getExecutionTimestamp()
// {
// return executionTimestamp;
// }
// }
// Path: src/main/java/com/epickrram/workshop/perf/setup/InputGenerator.java
import com.beust.jcommander.JCommander;
import com.epickrram.workshop.perf.config.CommandLineArgs;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Random;
package com.epickrram.workshop.perf.setup;
//////////////////////////////////////////////////////////////////////////////////
// Copyright 2015 Mark Price mark at epickrram.com //
// //
// 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. //
//////////////////////////////////////////////////////////////////////////////////
public final class InputGenerator
{ | private final CommandLineArgs commandLineArgs; |
epickrram/perf-workshop | src/main/java/com/epickrram/workshop/perf/app/jitter/Spinners.java | // Path: src/main/java/com/epickrram/workshop/perf/support/Threads.java
// public enum Threads
// {
// THREADS;
//
// public Runnable runOnCpu(final Runnable task, final int... cpus)
// {
// return () -> {
// setCurrentThreadAffinity(cpus);
// task.run();
// };
// }
//
// public void setCurrentThreadAffinity(final int... cpus)
// {
// if (cpus.length == 0)
// {
// return;
// }
// if (cpus.length != 1)
// {
// throw new UnsupportedOperationException();
// }
//
// ProcessBuilder builder = new ProcessBuilder("taskset", "-cp",
// Integer.toString(cpus[0]), Integer.toString(getCurrentThreadId()));
//
// try
// {
// builder.start().waitFor();
// System.out.println("Set affinity for thread " + Thread.currentThread().getName() + " to " + Arrays.toString(cpus));
// }
// catch (InterruptedException | IOException e)
// {
// e.printStackTrace();
// }
// }
//
// public int getCurrentThreadId()
// {
// try
// {
// final List<String> strings = Files.readAllLines(Paths.get("/proc/thread-self/status"));
// return Integer.parseInt(strings.stream().filter(s -> s.startsWith("Pid:")).map(s -> {
// return s.split("\\s+")[1];
// }).findAny().get());
//
// //
// // // TODO: if Java 9, then use ProcessHandle.
// // final String pidPorpertyValue = System.getProperty("sun.java.launcher.pid");
// //
// // if (null != pidPorpertyValue)
// // {
// // return Integer.parseInt(pidPorpertyValue);
// // }
// //
// // final String jvmName = ManagementFactory.getRuntimeMXBean().getName();
// //
// // return Integer.parseInt(jvmName.split("@")[0]);
// }
// catch (final Throwable ex)
// {
// return -1;
// }
// }
//
// public void sleep(final long duration, final TimeUnit unit)
// {
// try
// {
// Thread.sleep(unit.toMillis(duration));
// }
// catch (InterruptedException e)
// {
// throw new RuntimeException("Interrupted during sleep!");
// }
// }
//
// private BitSet cpuListToBitMask(final int[] cpus)
// {
// final BitSet bitSet = new BitSet();
//
// for(int cpu : cpus)
// {
// bitSet.set(cpu);
// }
//
// return bitSet;
// }
// }
| import com.epickrram.workshop.perf.support.Threads;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.TimeUnit;
import static com.epickrram.workshop.perf.support.DaemonThreadFactory.DAEMON_THREAD_FACTORY;
import static java.util.concurrent.Executors.newFixedThreadPool; | {
running = true;
final int processors = Runtime.getRuntime().availableProcessors();
final ExecutorService executorService = newFixedThreadPool(processors, DAEMON_THREAD_FACTORY);
for(int i = 0; i < processors; i++)
{
executorService.submit(new Spinner());
}
}
public void stop()
{
running = false;
}
private class Spinner implements Runnable
{
private long counter = 0;
@Override
public void run()
{
while(running)
{
final long stopSpinningAt = System.nanoTime() + BUSY_SPIN_PERIOD_NANOS;
while(System.nanoTime() < stopSpinningAt)
{
counter++;
}
| // Path: src/main/java/com/epickrram/workshop/perf/support/Threads.java
// public enum Threads
// {
// THREADS;
//
// public Runnable runOnCpu(final Runnable task, final int... cpus)
// {
// return () -> {
// setCurrentThreadAffinity(cpus);
// task.run();
// };
// }
//
// public void setCurrentThreadAffinity(final int... cpus)
// {
// if (cpus.length == 0)
// {
// return;
// }
// if (cpus.length != 1)
// {
// throw new UnsupportedOperationException();
// }
//
// ProcessBuilder builder = new ProcessBuilder("taskset", "-cp",
// Integer.toString(cpus[0]), Integer.toString(getCurrentThreadId()));
//
// try
// {
// builder.start().waitFor();
// System.out.println("Set affinity for thread " + Thread.currentThread().getName() + " to " + Arrays.toString(cpus));
// }
// catch (InterruptedException | IOException e)
// {
// e.printStackTrace();
// }
// }
//
// public int getCurrentThreadId()
// {
// try
// {
// final List<String> strings = Files.readAllLines(Paths.get("/proc/thread-self/status"));
// return Integer.parseInt(strings.stream().filter(s -> s.startsWith("Pid:")).map(s -> {
// return s.split("\\s+")[1];
// }).findAny().get());
//
// //
// // // TODO: if Java 9, then use ProcessHandle.
// // final String pidPorpertyValue = System.getProperty("sun.java.launcher.pid");
// //
// // if (null != pidPorpertyValue)
// // {
// // return Integer.parseInt(pidPorpertyValue);
// // }
// //
// // final String jvmName = ManagementFactory.getRuntimeMXBean().getName();
// //
// // return Integer.parseInt(jvmName.split("@")[0]);
// }
// catch (final Throwable ex)
// {
// return -1;
// }
// }
//
// public void sleep(final long duration, final TimeUnit unit)
// {
// try
// {
// Thread.sleep(unit.toMillis(duration));
// }
// catch (InterruptedException e)
// {
// throw new RuntimeException("Interrupted during sleep!");
// }
// }
//
// private BitSet cpuListToBitMask(final int[] cpus)
// {
// final BitSet bitSet = new BitSet();
//
// for(int cpu : cpus)
// {
// bitSet.set(cpu);
// }
//
// return bitSet;
// }
// }
// Path: src/main/java/com/epickrram/workshop/perf/app/jitter/Spinners.java
import com.epickrram.workshop.perf.support.Threads;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.TimeUnit;
import static com.epickrram.workshop.perf.support.DaemonThreadFactory.DAEMON_THREAD_FACTORY;
import static java.util.concurrent.Executors.newFixedThreadPool;
{
running = true;
final int processors = Runtime.getRuntime().availableProcessors();
final ExecutorService executorService = newFixedThreadPool(processors, DAEMON_THREAD_FACTORY);
for(int i = 0; i < processors; i++)
{
executorService.submit(new Spinner());
}
}
public void stop()
{
running = false;
}
private class Spinner implements Runnable
{
private long counter = 0;
@Override
public void run()
{
while(running)
{
final long stopSpinningAt = System.nanoTime() + BUSY_SPIN_PERIOD_NANOS;
while(System.nanoTime() < stopSpinningAt)
{
counter++;
}
| Threads.THREADS.sleep(SLEEP_PERIOD_NANOS, TimeUnit.NANOSECONDS); |
epickrram/perf-workshop | src/main/java/com/epickrram/workshop/perf/support/SpinLoopHintBusySpinWaitStrategy.java | // Path: src/main/java/org/performancehints/SpinHint.java
// public final class SpinHint
// {
// // sole ctor
// private SpinHint() {}
//
// /**
// * Provides a hint to the processor that the code sequence is a spin-wait loop.
// */
// public static void spinLoopHint()
// {
// // intentionally empty
// }
// }
| import com.lmax.disruptor.AlertException;
import com.lmax.disruptor.Sequence;
import com.lmax.disruptor.SequenceBarrier;
import com.lmax.disruptor.WaitStrategy;
import org.performancehints.SpinHint; | package com.epickrram.workshop.perf.support;
public final class SpinLoopHintBusySpinWaitStrategy implements WaitStrategy
{
@Override
public long waitFor(final long sequence, Sequence cursor, final Sequence dependentSequence, final SequenceBarrier barrier)
throws AlertException, InterruptedException
{
long availableSequence;
while ((availableSequence = dependentSequence.get()) < sequence)
{ | // Path: src/main/java/org/performancehints/SpinHint.java
// public final class SpinHint
// {
// // sole ctor
// private SpinHint() {}
//
// /**
// * Provides a hint to the processor that the code sequence is a spin-wait loop.
// */
// public static void spinLoopHint()
// {
// // intentionally empty
// }
// }
// Path: src/main/java/com/epickrram/workshop/perf/support/SpinLoopHintBusySpinWaitStrategy.java
import com.lmax.disruptor.AlertException;
import com.lmax.disruptor.Sequence;
import com.lmax.disruptor.SequenceBarrier;
import com.lmax.disruptor.WaitStrategy;
import org.performancehints.SpinHint;
package com.epickrram.workshop.perf.support;
public final class SpinLoopHintBusySpinWaitStrategy implements WaitStrategy
{
@Override
public long waitFor(final long sequence, Sequence cursor, final Sequence dependentSequence, final SequenceBarrier barrier)
throws AlertException, InterruptedException
{
long availableSequence;
while ((availableSequence = dependentSequence.get()) < sequence)
{ | SpinHint.spinLoopHint(); |
epickrram/perf-workshop | src/main/java/com/epickrram/workshop/perf/config/CommandLineArgs.java | // Path: src/main/java/com/epickrram/workshop/perf/reporting/ReportFormat.java
// public enum ReportFormat
// {
// LONG,
// SHORT,
// DETAILED
// }
| import com.beust.jcommander.Parameter;
import com.epickrram.workshop.perf.reporting.ReportFormat;
import java.io.File;
import java.util.Arrays;
import java.util.EnumSet;
import java.util.List;
import java.util.Set;
import static java.lang.System.getProperty;
import static java.util.Arrays.asList; | package com.epickrram.workshop.perf.config;
//////////////////////////////////////////////////////////////////////////////////
// Copyright 2015 Mark Price mark at epickrram.com //
// //
// 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. //
//////////////////////////////////////////////////////////////////////////////////
public final class CommandLineArgs
{
private final long executionTimestamp = System.currentTimeMillis();
@Parameter(names = "-i", description = "number of iterations")
private int numberOfIterations = 20;
@Parameter(names = "-w", description = "number of warm-ups")
private int numberOfWarmups = 10;
@Parameter(names = "-n", description = "number of records per input file")
private int numberOfRecords = 10000;
@Parameter(names = "-l", description = "length of record (bytes)")
private int recordLength = 64;
@Parameter(names = "-f", description = "data file (default: /tmp/perf-workshop-input.bin)")
private String inputFile = getTmpDirectory() + File.separator + "perf-workshop-input.bin";
@Parameter(names = "-b", description = "buffer size (must be a power of two)")
private int bufferSize = 524288;
@Parameter(names = "-j", description = "journal file (default: /tmp/perf-workshop-output.jnl)")
private String journalFile = getTmpDirectory() + File.separator + "perf-workshop-output.jnl";
@Parameter(names = "-d", description = "output dir (default: /tmp)")
private String outputDir = getTmpDirectory();
@Parameter(names = "-o", description = "overrides file (default: /tmp/perf-workshop.properties)")
private String overrideFile = getTmpDirectory() + File.separator + "perf-workshop.properties";
@Parameter(names = "-r", description = "report format", variableArity = true) | // Path: src/main/java/com/epickrram/workshop/perf/reporting/ReportFormat.java
// public enum ReportFormat
// {
// LONG,
// SHORT,
// DETAILED
// }
// Path: src/main/java/com/epickrram/workshop/perf/config/CommandLineArgs.java
import com.beust.jcommander.Parameter;
import com.epickrram.workshop.perf.reporting.ReportFormat;
import java.io.File;
import java.util.Arrays;
import java.util.EnumSet;
import java.util.List;
import java.util.Set;
import static java.lang.System.getProperty;
import static java.util.Arrays.asList;
package com.epickrram.workshop.perf.config;
//////////////////////////////////////////////////////////////////////////////////
// Copyright 2015 Mark Price mark at epickrram.com //
// //
// 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. //
//////////////////////////////////////////////////////////////////////////////////
public final class CommandLineArgs
{
private final long executionTimestamp = System.currentTimeMillis();
@Parameter(names = "-i", description = "number of iterations")
private int numberOfIterations = 20;
@Parameter(names = "-w", description = "number of warm-ups")
private int numberOfWarmups = 10;
@Parameter(names = "-n", description = "number of records per input file")
private int numberOfRecords = 10000;
@Parameter(names = "-l", description = "length of record (bytes)")
private int recordLength = 64;
@Parameter(names = "-f", description = "data file (default: /tmp/perf-workshop-input.bin)")
private String inputFile = getTmpDirectory() + File.separator + "perf-workshop-input.bin";
@Parameter(names = "-b", description = "buffer size (must be a power of two)")
private int bufferSize = 524288;
@Parameter(names = "-j", description = "journal file (default: /tmp/perf-workshop-output.jnl)")
private String journalFile = getTmpDirectory() + File.separator + "perf-workshop-output.jnl";
@Parameter(names = "-d", description = "output dir (default: /tmp)")
private String outputDir = getTmpDirectory();
@Parameter(names = "-o", description = "overrides file (default: /tmp/perf-workshop.properties)")
private String overrideFile = getTmpDirectory() + File.separator + "perf-workshop.properties";
@Parameter(names = "-r", description = "report format", variableArity = true) | private List<String> reportFormats = asList(ReportFormat.LONG.name()); |
epickrram/perf-workshop | src/main/java/com/epickrram/workshop/perf/support/EncodedHistogramReporter.java | // Path: src/main/java/com/epickrram/workshop/perf/reporting/HistogramReporter.java
// public final class HistogramReporter
// {
// private static final DateTimeFormatter FORMATTER = DateTimeFormatter.ofPattern("yyyyMMdd-HHmmss");
// private final long executionTimestamp;
// private final String outputDir;
// private final String testLabel;
//
// public HistogramReporter(final long executionTimestamp, final String outputDir, final String testLabel)
// {
// this.executionTimestamp = executionTimestamp;
// this.outputDir = outputDir;
// this.testLabel = testLabel;
// }
//
// public void writeReport(final Histogram histogram, final PrintStream out,
// final Set<ReportFormat> reportFormats,
// final String histogramTitle) throws IOException
// {
// if (histogram.getTotalCount() == 0L)
// {
// return;
// }
// for (final ReportFormat reportFormat : reportFormats)
// {
// switch (reportFormat)
// {
// case LONG:
// longReport(histogram, histogramTitle, out);
// break;
// case SHORT:
// shortReport(histogram, out);
// break;
// case DETAILED:
// encodedHistogram(histogram, histogramTitle, out, testLabel);
// break;
// default:
// throw new IllegalStateException("Unknown report format: " + reportFormat);
// }
// }
// }
//
// private void encodedHistogram(final Histogram histogram, final String histogramTitle, final PrintStream out, final String testLabel)
// {
// try
// {
// final File histogramOutputFile = getHistogramOutputFile(outputDir, histogramTitle, testLabel);
// out.println("Writing full encoded histogram to " + histogramOutputFile.getAbsolutePath() + "\n");
// try (final PrintStream printStream = new PrintStream(histogramOutputFile))
// {
// new HistogramLogWriter(printStream).outputIntervalHistogram(0, 1, histogram, 1d);
// }
// }
// catch (FileNotFoundException e)
// {
// throw new RuntimeException("Failed to write histogram", e);
// }
// }
//
// private File getHistogramOutputFile(final String rootDir, final String qualifier, final String testLabel)
// {
// final LocalDateTime timestamp = LocalDateTime.ofEpochSecond(executionTimestamp / 1000, 0, ZoneOffset.UTC);
// return new File(rootDir, "encoded-result-histogram-" + cleanse(qualifier) +
// "-" + FORMATTER.format(timestamp) + "-LABEL_" + testLabel + ".report.enc");
// }
//
// private String cleanse(final String qualifier)
// {
// return qualifier.replaceAll("[ =\\(\\)]", "_");
// }
//
// private void longReport(final Histogram histogram, final String histogramTitle,
// final PrintStream out) throws IOException
// {
// final PrintWriter printWriter = new PrintWriter(out);
// printWriter.append(format("== %s ==%n", histogramTitle));
// printWriter.append(format("%-8s%20d%n", "mean", (long) histogram.getMean()));
// printWriter.append(format("%-8s%20d%n", "min", histogram.getMinValue()));
// printWriter.append(format("%-8s%20d%n", "50.00%", histogram.getValueAtPercentile(50.0d)));
// printWriter.append(format("%-8s%20d%n", "90.00%", histogram.getValueAtPercentile(90.0d)));
// printWriter.append(format("%-8s%20d%n", "99.00%", histogram.getValueAtPercentile(99.0d)));
// printWriter.append(format("%-8s%20d%n", "99.90%", histogram.getValueAtPercentile(99.9d)));
// printWriter.append(format("%-8s%20d%n", "99.99%", histogram.getValueAtPercentile(99.99d)));
// printWriter.append(format("%-8s%20d%n", "99.999%", histogram.getValueAtPercentile(99.999d)));
// printWriter.append(format("%-8s%20d%n", "99.9999%", histogram.getValueAtPercentile(99.9999d)));
// printWriter.append(format("%-8s%20d%n", "max", histogram.getMaxValue()));
// printWriter.append(format("%-8s%20d%n", "count", histogram.getTotalCount()));
// printWriter.append("\n");
// printWriter.flush();
// }
//
// private void shortReport(final Histogram histogram, final PrintStream out) throws IOException
// {
// final PrintWriter printWriter = new PrintWriter(out);
// printWriter.append(format("%d,", histogram.getMinValue()));
// printWriter.append(format("%d,", (long) histogram.getMean()));
// printWriter.append(format("%d,", histogram.getValueAtPercentile(50.0d)));
// printWriter.append(format("%d,", histogram.getValueAtPercentile(90.0d)));
// printWriter.append(format("%d,", histogram.getValueAtPercentile(99.0d)));
// printWriter.append(format("%d,", histogram.getValueAtPercentile(99.9d)));
// printWriter.append(format("%d,", histogram.getValueAtPercentile(99.99d)));
// printWriter.append(format("%d,", histogram.getMaxValue()));
// printWriter.append(format("%d%n", histogram.getTotalCount()));
// printWriter.append("\n");
// printWriter.flush();
// }
// }
//
// Path: src/main/java/com/epickrram/workshop/perf/reporting/ReportFormat.java
// public enum ReportFormat
// {
// LONG,
// SHORT,
// DETAILED
// }
| import com.epickrram.workshop.perf.reporting.HistogramReporter;
import com.epickrram.workshop.perf.reporting.ReportFormat;
import org.HdrHistogram.Histogram;
import org.HdrHistogram.HistogramLogReader;
import java.io.IOException;
import java.util.EnumSet; | package com.epickrram.workshop.perf.support;
public final class EncodedHistogramReporter
{
public static void main(final String[] args) throws IOException
{
final Histogram histogram = (Histogram) new HistogramLogReader(args[0]).nextIntervalHistogram(); | // Path: src/main/java/com/epickrram/workshop/perf/reporting/HistogramReporter.java
// public final class HistogramReporter
// {
// private static final DateTimeFormatter FORMATTER = DateTimeFormatter.ofPattern("yyyyMMdd-HHmmss");
// private final long executionTimestamp;
// private final String outputDir;
// private final String testLabel;
//
// public HistogramReporter(final long executionTimestamp, final String outputDir, final String testLabel)
// {
// this.executionTimestamp = executionTimestamp;
// this.outputDir = outputDir;
// this.testLabel = testLabel;
// }
//
// public void writeReport(final Histogram histogram, final PrintStream out,
// final Set<ReportFormat> reportFormats,
// final String histogramTitle) throws IOException
// {
// if (histogram.getTotalCount() == 0L)
// {
// return;
// }
// for (final ReportFormat reportFormat : reportFormats)
// {
// switch (reportFormat)
// {
// case LONG:
// longReport(histogram, histogramTitle, out);
// break;
// case SHORT:
// shortReport(histogram, out);
// break;
// case DETAILED:
// encodedHistogram(histogram, histogramTitle, out, testLabel);
// break;
// default:
// throw new IllegalStateException("Unknown report format: " + reportFormat);
// }
// }
// }
//
// private void encodedHistogram(final Histogram histogram, final String histogramTitle, final PrintStream out, final String testLabel)
// {
// try
// {
// final File histogramOutputFile = getHistogramOutputFile(outputDir, histogramTitle, testLabel);
// out.println("Writing full encoded histogram to " + histogramOutputFile.getAbsolutePath() + "\n");
// try (final PrintStream printStream = new PrintStream(histogramOutputFile))
// {
// new HistogramLogWriter(printStream).outputIntervalHistogram(0, 1, histogram, 1d);
// }
// }
// catch (FileNotFoundException e)
// {
// throw new RuntimeException("Failed to write histogram", e);
// }
// }
//
// private File getHistogramOutputFile(final String rootDir, final String qualifier, final String testLabel)
// {
// final LocalDateTime timestamp = LocalDateTime.ofEpochSecond(executionTimestamp / 1000, 0, ZoneOffset.UTC);
// return new File(rootDir, "encoded-result-histogram-" + cleanse(qualifier) +
// "-" + FORMATTER.format(timestamp) + "-LABEL_" + testLabel + ".report.enc");
// }
//
// private String cleanse(final String qualifier)
// {
// return qualifier.replaceAll("[ =\\(\\)]", "_");
// }
//
// private void longReport(final Histogram histogram, final String histogramTitle,
// final PrintStream out) throws IOException
// {
// final PrintWriter printWriter = new PrintWriter(out);
// printWriter.append(format("== %s ==%n", histogramTitle));
// printWriter.append(format("%-8s%20d%n", "mean", (long) histogram.getMean()));
// printWriter.append(format("%-8s%20d%n", "min", histogram.getMinValue()));
// printWriter.append(format("%-8s%20d%n", "50.00%", histogram.getValueAtPercentile(50.0d)));
// printWriter.append(format("%-8s%20d%n", "90.00%", histogram.getValueAtPercentile(90.0d)));
// printWriter.append(format("%-8s%20d%n", "99.00%", histogram.getValueAtPercentile(99.0d)));
// printWriter.append(format("%-8s%20d%n", "99.90%", histogram.getValueAtPercentile(99.9d)));
// printWriter.append(format("%-8s%20d%n", "99.99%", histogram.getValueAtPercentile(99.99d)));
// printWriter.append(format("%-8s%20d%n", "99.999%", histogram.getValueAtPercentile(99.999d)));
// printWriter.append(format("%-8s%20d%n", "99.9999%", histogram.getValueAtPercentile(99.9999d)));
// printWriter.append(format("%-8s%20d%n", "max", histogram.getMaxValue()));
// printWriter.append(format("%-8s%20d%n", "count", histogram.getTotalCount()));
// printWriter.append("\n");
// printWriter.flush();
// }
//
// private void shortReport(final Histogram histogram, final PrintStream out) throws IOException
// {
// final PrintWriter printWriter = new PrintWriter(out);
// printWriter.append(format("%d,", histogram.getMinValue()));
// printWriter.append(format("%d,", (long) histogram.getMean()));
// printWriter.append(format("%d,", histogram.getValueAtPercentile(50.0d)));
// printWriter.append(format("%d,", histogram.getValueAtPercentile(90.0d)));
// printWriter.append(format("%d,", histogram.getValueAtPercentile(99.0d)));
// printWriter.append(format("%d,", histogram.getValueAtPercentile(99.9d)));
// printWriter.append(format("%d,", histogram.getValueAtPercentile(99.99d)));
// printWriter.append(format("%d,", histogram.getMaxValue()));
// printWriter.append(format("%d%n", histogram.getTotalCount()));
// printWriter.append("\n");
// printWriter.flush();
// }
// }
//
// Path: src/main/java/com/epickrram/workshop/perf/reporting/ReportFormat.java
// public enum ReportFormat
// {
// LONG,
// SHORT,
// DETAILED
// }
// Path: src/main/java/com/epickrram/workshop/perf/support/EncodedHistogramReporter.java
import com.epickrram.workshop.perf.reporting.HistogramReporter;
import com.epickrram.workshop.perf.reporting.ReportFormat;
import org.HdrHistogram.Histogram;
import org.HdrHistogram.HistogramLogReader;
import java.io.IOException;
import java.util.EnumSet;
package com.epickrram.workshop.perf.support;
public final class EncodedHistogramReporter
{
public static void main(final String[] args) throws IOException
{
final Histogram histogram = (Histogram) new HistogramLogReader(args[0]).nextIntervalHistogram(); | final HistogramReporter reporter = new HistogramReporter(0L, null, ""); |
epickrram/perf-workshop | src/main/java/com/epickrram/workshop/perf/support/EncodedHistogramReporter.java | // Path: src/main/java/com/epickrram/workshop/perf/reporting/HistogramReporter.java
// public final class HistogramReporter
// {
// private static final DateTimeFormatter FORMATTER = DateTimeFormatter.ofPattern("yyyyMMdd-HHmmss");
// private final long executionTimestamp;
// private final String outputDir;
// private final String testLabel;
//
// public HistogramReporter(final long executionTimestamp, final String outputDir, final String testLabel)
// {
// this.executionTimestamp = executionTimestamp;
// this.outputDir = outputDir;
// this.testLabel = testLabel;
// }
//
// public void writeReport(final Histogram histogram, final PrintStream out,
// final Set<ReportFormat> reportFormats,
// final String histogramTitle) throws IOException
// {
// if (histogram.getTotalCount() == 0L)
// {
// return;
// }
// for (final ReportFormat reportFormat : reportFormats)
// {
// switch (reportFormat)
// {
// case LONG:
// longReport(histogram, histogramTitle, out);
// break;
// case SHORT:
// shortReport(histogram, out);
// break;
// case DETAILED:
// encodedHistogram(histogram, histogramTitle, out, testLabel);
// break;
// default:
// throw new IllegalStateException("Unknown report format: " + reportFormat);
// }
// }
// }
//
// private void encodedHistogram(final Histogram histogram, final String histogramTitle, final PrintStream out, final String testLabel)
// {
// try
// {
// final File histogramOutputFile = getHistogramOutputFile(outputDir, histogramTitle, testLabel);
// out.println("Writing full encoded histogram to " + histogramOutputFile.getAbsolutePath() + "\n");
// try (final PrintStream printStream = new PrintStream(histogramOutputFile))
// {
// new HistogramLogWriter(printStream).outputIntervalHistogram(0, 1, histogram, 1d);
// }
// }
// catch (FileNotFoundException e)
// {
// throw new RuntimeException("Failed to write histogram", e);
// }
// }
//
// private File getHistogramOutputFile(final String rootDir, final String qualifier, final String testLabel)
// {
// final LocalDateTime timestamp = LocalDateTime.ofEpochSecond(executionTimestamp / 1000, 0, ZoneOffset.UTC);
// return new File(rootDir, "encoded-result-histogram-" + cleanse(qualifier) +
// "-" + FORMATTER.format(timestamp) + "-LABEL_" + testLabel + ".report.enc");
// }
//
// private String cleanse(final String qualifier)
// {
// return qualifier.replaceAll("[ =\\(\\)]", "_");
// }
//
// private void longReport(final Histogram histogram, final String histogramTitle,
// final PrintStream out) throws IOException
// {
// final PrintWriter printWriter = new PrintWriter(out);
// printWriter.append(format("== %s ==%n", histogramTitle));
// printWriter.append(format("%-8s%20d%n", "mean", (long) histogram.getMean()));
// printWriter.append(format("%-8s%20d%n", "min", histogram.getMinValue()));
// printWriter.append(format("%-8s%20d%n", "50.00%", histogram.getValueAtPercentile(50.0d)));
// printWriter.append(format("%-8s%20d%n", "90.00%", histogram.getValueAtPercentile(90.0d)));
// printWriter.append(format("%-8s%20d%n", "99.00%", histogram.getValueAtPercentile(99.0d)));
// printWriter.append(format("%-8s%20d%n", "99.90%", histogram.getValueAtPercentile(99.9d)));
// printWriter.append(format("%-8s%20d%n", "99.99%", histogram.getValueAtPercentile(99.99d)));
// printWriter.append(format("%-8s%20d%n", "99.999%", histogram.getValueAtPercentile(99.999d)));
// printWriter.append(format("%-8s%20d%n", "99.9999%", histogram.getValueAtPercentile(99.9999d)));
// printWriter.append(format("%-8s%20d%n", "max", histogram.getMaxValue()));
// printWriter.append(format("%-8s%20d%n", "count", histogram.getTotalCount()));
// printWriter.append("\n");
// printWriter.flush();
// }
//
// private void shortReport(final Histogram histogram, final PrintStream out) throws IOException
// {
// final PrintWriter printWriter = new PrintWriter(out);
// printWriter.append(format("%d,", histogram.getMinValue()));
// printWriter.append(format("%d,", (long) histogram.getMean()));
// printWriter.append(format("%d,", histogram.getValueAtPercentile(50.0d)));
// printWriter.append(format("%d,", histogram.getValueAtPercentile(90.0d)));
// printWriter.append(format("%d,", histogram.getValueAtPercentile(99.0d)));
// printWriter.append(format("%d,", histogram.getValueAtPercentile(99.9d)));
// printWriter.append(format("%d,", histogram.getValueAtPercentile(99.99d)));
// printWriter.append(format("%d,", histogram.getMaxValue()));
// printWriter.append(format("%d%n", histogram.getTotalCount()));
// printWriter.append("\n");
// printWriter.flush();
// }
// }
//
// Path: src/main/java/com/epickrram/workshop/perf/reporting/ReportFormat.java
// public enum ReportFormat
// {
// LONG,
// SHORT,
// DETAILED
// }
| import com.epickrram.workshop.perf.reporting.HistogramReporter;
import com.epickrram.workshop.perf.reporting.ReportFormat;
import org.HdrHistogram.Histogram;
import org.HdrHistogram.HistogramLogReader;
import java.io.IOException;
import java.util.EnumSet; | package com.epickrram.workshop.perf.support;
public final class EncodedHistogramReporter
{
public static void main(final String[] args) throws IOException
{
final Histogram histogram = (Histogram) new HistogramLogReader(args[0]).nextIntervalHistogram();
final HistogramReporter reporter = new HistogramReporter(0L, null, ""); | // Path: src/main/java/com/epickrram/workshop/perf/reporting/HistogramReporter.java
// public final class HistogramReporter
// {
// private static final DateTimeFormatter FORMATTER = DateTimeFormatter.ofPattern("yyyyMMdd-HHmmss");
// private final long executionTimestamp;
// private final String outputDir;
// private final String testLabel;
//
// public HistogramReporter(final long executionTimestamp, final String outputDir, final String testLabel)
// {
// this.executionTimestamp = executionTimestamp;
// this.outputDir = outputDir;
// this.testLabel = testLabel;
// }
//
// public void writeReport(final Histogram histogram, final PrintStream out,
// final Set<ReportFormat> reportFormats,
// final String histogramTitle) throws IOException
// {
// if (histogram.getTotalCount() == 0L)
// {
// return;
// }
// for (final ReportFormat reportFormat : reportFormats)
// {
// switch (reportFormat)
// {
// case LONG:
// longReport(histogram, histogramTitle, out);
// break;
// case SHORT:
// shortReport(histogram, out);
// break;
// case DETAILED:
// encodedHistogram(histogram, histogramTitle, out, testLabel);
// break;
// default:
// throw new IllegalStateException("Unknown report format: " + reportFormat);
// }
// }
// }
//
// private void encodedHistogram(final Histogram histogram, final String histogramTitle, final PrintStream out, final String testLabel)
// {
// try
// {
// final File histogramOutputFile = getHistogramOutputFile(outputDir, histogramTitle, testLabel);
// out.println("Writing full encoded histogram to " + histogramOutputFile.getAbsolutePath() + "\n");
// try (final PrintStream printStream = new PrintStream(histogramOutputFile))
// {
// new HistogramLogWriter(printStream).outputIntervalHistogram(0, 1, histogram, 1d);
// }
// }
// catch (FileNotFoundException e)
// {
// throw new RuntimeException("Failed to write histogram", e);
// }
// }
//
// private File getHistogramOutputFile(final String rootDir, final String qualifier, final String testLabel)
// {
// final LocalDateTime timestamp = LocalDateTime.ofEpochSecond(executionTimestamp / 1000, 0, ZoneOffset.UTC);
// return new File(rootDir, "encoded-result-histogram-" + cleanse(qualifier) +
// "-" + FORMATTER.format(timestamp) + "-LABEL_" + testLabel + ".report.enc");
// }
//
// private String cleanse(final String qualifier)
// {
// return qualifier.replaceAll("[ =\\(\\)]", "_");
// }
//
// private void longReport(final Histogram histogram, final String histogramTitle,
// final PrintStream out) throws IOException
// {
// final PrintWriter printWriter = new PrintWriter(out);
// printWriter.append(format("== %s ==%n", histogramTitle));
// printWriter.append(format("%-8s%20d%n", "mean", (long) histogram.getMean()));
// printWriter.append(format("%-8s%20d%n", "min", histogram.getMinValue()));
// printWriter.append(format("%-8s%20d%n", "50.00%", histogram.getValueAtPercentile(50.0d)));
// printWriter.append(format("%-8s%20d%n", "90.00%", histogram.getValueAtPercentile(90.0d)));
// printWriter.append(format("%-8s%20d%n", "99.00%", histogram.getValueAtPercentile(99.0d)));
// printWriter.append(format("%-8s%20d%n", "99.90%", histogram.getValueAtPercentile(99.9d)));
// printWriter.append(format("%-8s%20d%n", "99.99%", histogram.getValueAtPercentile(99.99d)));
// printWriter.append(format("%-8s%20d%n", "99.999%", histogram.getValueAtPercentile(99.999d)));
// printWriter.append(format("%-8s%20d%n", "99.9999%", histogram.getValueAtPercentile(99.9999d)));
// printWriter.append(format("%-8s%20d%n", "max", histogram.getMaxValue()));
// printWriter.append(format("%-8s%20d%n", "count", histogram.getTotalCount()));
// printWriter.append("\n");
// printWriter.flush();
// }
//
// private void shortReport(final Histogram histogram, final PrintStream out) throws IOException
// {
// final PrintWriter printWriter = new PrintWriter(out);
// printWriter.append(format("%d,", histogram.getMinValue()));
// printWriter.append(format("%d,", (long) histogram.getMean()));
// printWriter.append(format("%d,", histogram.getValueAtPercentile(50.0d)));
// printWriter.append(format("%d,", histogram.getValueAtPercentile(90.0d)));
// printWriter.append(format("%d,", histogram.getValueAtPercentile(99.0d)));
// printWriter.append(format("%d,", histogram.getValueAtPercentile(99.9d)));
// printWriter.append(format("%d,", histogram.getValueAtPercentile(99.99d)));
// printWriter.append(format("%d,", histogram.getMaxValue()));
// printWriter.append(format("%d%n", histogram.getTotalCount()));
// printWriter.append("\n");
// printWriter.flush();
// }
// }
//
// Path: src/main/java/com/epickrram/workshop/perf/reporting/ReportFormat.java
// public enum ReportFormat
// {
// LONG,
// SHORT,
// DETAILED
// }
// Path: src/main/java/com/epickrram/workshop/perf/support/EncodedHistogramReporter.java
import com.epickrram.workshop.perf.reporting.HistogramReporter;
import com.epickrram.workshop.perf.reporting.ReportFormat;
import org.HdrHistogram.Histogram;
import org.HdrHistogram.HistogramLogReader;
import java.io.IOException;
import java.util.EnumSet;
package com.epickrram.workshop.perf.support;
public final class EncodedHistogramReporter
{
public static void main(final String[] args) throws IOException
{
final Histogram histogram = (Histogram) new HistogramLogReader(args[0]).nextIntervalHistogram();
final HistogramReporter reporter = new HistogramReporter(0L, null, ""); | reporter.writeReport(histogram, System.out, EnumSet.of(ReportFormat.LONG), args[0]); |
Robyer/Gamework | Gamework/src/cz/robyer/gamework/scenario/variable/DecimalVariable.java | // Path: Gamework/src/cz/robyer/gamework/scenario/reaction/VariableReaction.java
// public static enum OperatorType {SET, INCREMENT, DECREMENT, MULTIPLY, DIVIDE, NEGATE};
//
// Path: Gamework/src/cz/robyer/gamework/utils/Log.java
// public class Log {
//
// private static final boolean debug = true;
//
// public static boolean loggingEnabled() {
// return debug;
// }
//
// public static void v(String tag, String msg) {
// if (loggingEnabled())
// android.util.Log.v(tag, msg);
// }
//
// public static void d(String tag, String msg) {
// if (loggingEnabled())
// android.util.Log.d(tag, msg);
// }
//
// public static void i(String tag, String msg) {
// if (loggingEnabled())
// android.util.Log.i(tag, msg);
// }
//
// public static void w(String tag, String msg) {
// android.util.Log.w(tag, msg);
// }
//
// public static void e(String tag, String msg) {
// android.util.Log.e(tag, msg);
// }
//
// public static void e(String tag, String msg, Exception e) {
// android.util.Log.e(tag, msg, e);
// }
//
// public static void println(int severity, String tag, String message) {
// if (loggingEnabled())
// android.util.Log.println(severity, tag, message);
// }
//
// }
| import java.security.InvalidParameterException;
import cz.robyer.gamework.scenario.reaction.VariableReaction.OperatorType;
import cz.robyer.gamework.utils.Log; | package cz.robyer.gamework.scenario.variable;
/**
* Represents numeric decimal variable.
* @author Robert Pösel
*/
public class DecimalVariable extends Variable {
protected int value;
protected int min = 0;
protected int max = 0;
/**
* Class constructor.
* @param id - identificator of variable
* @param value - actual (default) value
*/
public DecimalVariable(String id, int value) {
super(id);
this.value = value;
}
/**
* Class constructor.
* @param id - identificator of variable
* @param value - actual (default) value
* @param min - minimal value
* @param max - maximal value
*/
public DecimalVariable(String id, int value, int min, int max) {
this(id, value);
setLimit(min, max);
}
/**
* Factory for creating this variable from string value.
* @param id - identificator of variable
* @param value - actual (default) value a string
* @return DecimalVariable
*/
public static DecimalVariable fromString(String id, String value) {
return new DecimalVariable(id, Integer.parseInt(value));
}
/**
* Factory for creating this variable from string value.
* @param id - identificator of variable
* @param value - actual (default) value a string
* @param min - minimal value
* @param max - maximal value
* @return DecimalVariable
*/
public static DecimalVariable fromString(String id, String value, String min, String max) {
DecimalVariable variable = new DecimalVariable(id, Integer.parseInt(value));
variable.setLimit(Integer.parseInt(min), Integer.parseInt(max));
return variable;
}
/**
* Sets value of this variable.
* @param value to be set
*/
public void setValue(int value) {
this.value = value;
checkLimit();
}
/**
* Get value of this variable.
* @return actual value
*/
public int getValue() {
return value;
}
/**
* Sets limit of this variable, must be min < max.
* @param min - minimal value
* @param max - maximal value
*/
public void setLimit(int min, int max) {
if (min > max) { | // Path: Gamework/src/cz/robyer/gamework/scenario/reaction/VariableReaction.java
// public static enum OperatorType {SET, INCREMENT, DECREMENT, MULTIPLY, DIVIDE, NEGATE};
//
// Path: Gamework/src/cz/robyer/gamework/utils/Log.java
// public class Log {
//
// private static final boolean debug = true;
//
// public static boolean loggingEnabled() {
// return debug;
// }
//
// public static void v(String tag, String msg) {
// if (loggingEnabled())
// android.util.Log.v(tag, msg);
// }
//
// public static void d(String tag, String msg) {
// if (loggingEnabled())
// android.util.Log.d(tag, msg);
// }
//
// public static void i(String tag, String msg) {
// if (loggingEnabled())
// android.util.Log.i(tag, msg);
// }
//
// public static void w(String tag, String msg) {
// android.util.Log.w(tag, msg);
// }
//
// public static void e(String tag, String msg) {
// android.util.Log.e(tag, msg);
// }
//
// public static void e(String tag, String msg, Exception e) {
// android.util.Log.e(tag, msg, e);
// }
//
// public static void println(int severity, String tag, String message) {
// if (loggingEnabled())
// android.util.Log.println(severity, tag, message);
// }
//
// }
// Path: Gamework/src/cz/robyer/gamework/scenario/variable/DecimalVariable.java
import java.security.InvalidParameterException;
import cz.robyer.gamework.scenario.reaction.VariableReaction.OperatorType;
import cz.robyer.gamework.utils.Log;
package cz.robyer.gamework.scenario.variable;
/**
* Represents numeric decimal variable.
* @author Robert Pösel
*/
public class DecimalVariable extends Variable {
protected int value;
protected int min = 0;
protected int max = 0;
/**
* Class constructor.
* @param id - identificator of variable
* @param value - actual (default) value
*/
public DecimalVariable(String id, int value) {
super(id);
this.value = value;
}
/**
* Class constructor.
* @param id - identificator of variable
* @param value - actual (default) value
* @param min - minimal value
* @param max - maximal value
*/
public DecimalVariable(String id, int value, int min, int max) {
this(id, value);
setLimit(min, max);
}
/**
* Factory for creating this variable from string value.
* @param id - identificator of variable
* @param value - actual (default) value a string
* @return DecimalVariable
*/
public static DecimalVariable fromString(String id, String value) {
return new DecimalVariable(id, Integer.parseInt(value));
}
/**
* Factory for creating this variable from string value.
* @param id - identificator of variable
* @param value - actual (default) value a string
* @param min - minimal value
* @param max - maximal value
* @return DecimalVariable
*/
public static DecimalVariable fromString(String id, String value, String min, String max) {
DecimalVariable variable = new DecimalVariable(id, Integer.parseInt(value));
variable.setLimit(Integer.parseInt(min), Integer.parseInt(max));
return variable;
}
/**
* Sets value of this variable.
* @param value to be set
*/
public void setValue(int value) {
this.value = value;
checkLimit();
}
/**
* Get value of this variable.
* @return actual value
*/
public int getValue() {
return value;
}
/**
* Sets limit of this variable, must be min < max.
* @param min - minimal value
* @param max - maximal value
*/
public void setLimit(int min, int max) {
if (min > max) { | Log.e(TAG, String.format("Minimum value (%d) must be lower than maximum value (%d)", min, max)); |
Robyer/Gamework | Gamework/src/cz/robyer/gamework/scenario/variable/DecimalVariable.java | // Path: Gamework/src/cz/robyer/gamework/scenario/reaction/VariableReaction.java
// public static enum OperatorType {SET, INCREMENT, DECREMENT, MULTIPLY, DIVIDE, NEGATE};
//
// Path: Gamework/src/cz/robyer/gamework/utils/Log.java
// public class Log {
//
// private static final boolean debug = true;
//
// public static boolean loggingEnabled() {
// return debug;
// }
//
// public static void v(String tag, String msg) {
// if (loggingEnabled())
// android.util.Log.v(tag, msg);
// }
//
// public static void d(String tag, String msg) {
// if (loggingEnabled())
// android.util.Log.d(tag, msg);
// }
//
// public static void i(String tag, String msg) {
// if (loggingEnabled())
// android.util.Log.i(tag, msg);
// }
//
// public static void w(String tag, String msg) {
// android.util.Log.w(tag, msg);
// }
//
// public static void e(String tag, String msg) {
// android.util.Log.e(tag, msg);
// }
//
// public static void e(String tag, String msg, Exception e) {
// android.util.Log.e(tag, msg, e);
// }
//
// public static void println(int severity, String tag, String message) {
// if (loggingEnabled())
// android.util.Log.println(severity, tag, message);
// }
//
// }
| import java.security.InvalidParameterException;
import cz.robyer.gamework.scenario.reaction.VariableReaction.OperatorType;
import cz.robyer.gamework.utils.Log; |
/**
* Sets limit of this variable, must be min < max.
* @param min - minimal value
* @param max - maximal value
*/
public void setLimit(int min, int max) {
if (min > max) {
Log.e(TAG, String.format("Minimum value (%d) must be lower than maximum value (%d)", min, max));
throw new InvalidParameterException("Minimum value must be lower than maximum value");
}
this.min = min;
this.max = max;
}
/**
* Applies min/max limit to actual value.
*/
private void checkLimit() {
// if there is any limit applied
if (min != max) {
value = Math.min(Math.max(value, min), max);
}
}
/* (non-Javadoc)
* @see cz.robyer.gamework.scenario.variable.Variable#modify(cz.robyer.gamework.scenario.reaction.VariableReaction.OperatorType, java.lang.Object)
*/
@Override | // Path: Gamework/src/cz/robyer/gamework/scenario/reaction/VariableReaction.java
// public static enum OperatorType {SET, INCREMENT, DECREMENT, MULTIPLY, DIVIDE, NEGATE};
//
// Path: Gamework/src/cz/robyer/gamework/utils/Log.java
// public class Log {
//
// private static final boolean debug = true;
//
// public static boolean loggingEnabled() {
// return debug;
// }
//
// public static void v(String tag, String msg) {
// if (loggingEnabled())
// android.util.Log.v(tag, msg);
// }
//
// public static void d(String tag, String msg) {
// if (loggingEnabled())
// android.util.Log.d(tag, msg);
// }
//
// public static void i(String tag, String msg) {
// if (loggingEnabled())
// android.util.Log.i(tag, msg);
// }
//
// public static void w(String tag, String msg) {
// android.util.Log.w(tag, msg);
// }
//
// public static void e(String tag, String msg) {
// android.util.Log.e(tag, msg);
// }
//
// public static void e(String tag, String msg, Exception e) {
// android.util.Log.e(tag, msg, e);
// }
//
// public static void println(int severity, String tag, String message) {
// if (loggingEnabled())
// android.util.Log.println(severity, tag, message);
// }
//
// }
// Path: Gamework/src/cz/robyer/gamework/scenario/variable/DecimalVariable.java
import java.security.InvalidParameterException;
import cz.robyer.gamework.scenario.reaction.VariableReaction.OperatorType;
import cz.robyer.gamework.utils.Log;
/**
* Sets limit of this variable, must be min < max.
* @param min - minimal value
* @param max - maximal value
*/
public void setLimit(int min, int max) {
if (min > max) {
Log.e(TAG, String.format("Minimum value (%d) must be lower than maximum value (%d)", min, max));
throw new InvalidParameterException("Minimum value must be lower than maximum value");
}
this.min = min;
this.max = max;
}
/**
* Applies min/max limit to actual value.
*/
private void checkLimit() {
// if there is any limit applied
if (min != max) {
value = Math.min(Math.max(value, min), max);
}
}
/* (non-Javadoc)
* @see cz.robyer.gamework.scenario.variable.Variable#modify(cz.robyer.gamework.scenario.reaction.VariableReaction.OperatorType, java.lang.Object)
*/
@Override | public void modify(OperatorType type, Object val) { |
Robyer/Gamework | Gamework/src/cz/robyer/gamework/scenario/reaction/MessageReaction.java | // Path: Gamework/src/cz/robyer/gamework/scenario/message/Message.java
// public class Message extends IdentificableObject {
// protected String tag;
// protected String title;
// protected String value;
// protected MessageStatus status;
// protected long received;
//
// public static enum MessageStatus {NONE, UNREAD, READ, DELETED}
//
// /**
// * Class constructor
// * @param id - identificator of message
// * @param title - title of message
// * @param value - text or path to file with content of message
// */
// public Message(String id, String tag, String title, String value, boolean def) {
// super(id);
// this.title = title;
// this.tag = (tag == null ? "" : tag);
// this.value = value;
// this.status = def ? MessageStatus.UNREAD : MessageStatus.NONE;
// }
//
// /**
// * Sets status of this message.
// * @param status to be set
// */
// public void setStatus(MessageStatus status) {
// this.status = status;
// }
//
// /**
// * Returns actual status of this message.
// * @return actual status
// */
// public MessageStatus getStatus() {
// return status;
// }
//
// /**
// * Returns tag of this message.
// * @return tag
// */
// public String getTag() {
// return tag;
// }
//
// /**
// * Returns title of this message
// * @return title
// */
// public String getTitle() {
// return title;
// }
//
// /**
// * Returns content of text file in assets, which path is represented by value.
// * @return text of message
// */
// public String getContent() {
// InputStream stream = null;
// String content = null;
// try {
// stream = getContext().getAssets().open(value);
// int size = stream.available();
// byte[] buffer = new byte[size];
// stream.read(buffer);
// content = new String(buffer);
// } catch (IOException e) {
// Log.e(TAG, String.format("Can't load file '%s'", value));
// } finally {
// try {
// if (stream != null)
// stream.close();
// } catch (IOException ioe) {
// Log.e(TAG, ioe.getMessage(), ioe);
// }
// }
// return content;
// }
//
// /**
// * Return time when this message was received.
// * @return long timestamp
// */
// public long getReceived() {
// return received;
// }
//
// /**
// * Returns value of this message.
// * @return value
// */
// public String getValue() {
// return value;
// }
//
// /**
// * Checks if this message is received and not deleted.
// * @return true if message is visible, false otherwise
// */
// public boolean isVisible() {
// return (status != MessageStatus.NONE) && (status != MessageStatus.DELETED);
// }
//
// /**
// * Receive this message - marks as unread if not visible yet.
// */
// public void activate() {
// if (status == MessageStatus.NONE) {
// GameHandler handler = getScenario().getHandler();
//
// status = MessageStatus.UNREAD;
// received = handler.getGameTime();
// handler.broadcastEvent(new GameEvent(EventType.UPDATED_MESSAGES, id));
// }
// }
//
// }
| import android.util.Log;
import cz.robyer.gamework.scenario.message.Message; | package cz.robyer.gamework.scenario.reaction;
/**
* Game reaction which "receive" (make available to user) game message.
* @author Robert Pösel
*/
public class MessageReaction extends Reaction {
protected String value; | // Path: Gamework/src/cz/robyer/gamework/scenario/message/Message.java
// public class Message extends IdentificableObject {
// protected String tag;
// protected String title;
// protected String value;
// protected MessageStatus status;
// protected long received;
//
// public static enum MessageStatus {NONE, UNREAD, READ, DELETED}
//
// /**
// * Class constructor
// * @param id - identificator of message
// * @param title - title of message
// * @param value - text or path to file with content of message
// */
// public Message(String id, String tag, String title, String value, boolean def) {
// super(id);
// this.title = title;
// this.tag = (tag == null ? "" : tag);
// this.value = value;
// this.status = def ? MessageStatus.UNREAD : MessageStatus.NONE;
// }
//
// /**
// * Sets status of this message.
// * @param status to be set
// */
// public void setStatus(MessageStatus status) {
// this.status = status;
// }
//
// /**
// * Returns actual status of this message.
// * @return actual status
// */
// public MessageStatus getStatus() {
// return status;
// }
//
// /**
// * Returns tag of this message.
// * @return tag
// */
// public String getTag() {
// return tag;
// }
//
// /**
// * Returns title of this message
// * @return title
// */
// public String getTitle() {
// return title;
// }
//
// /**
// * Returns content of text file in assets, which path is represented by value.
// * @return text of message
// */
// public String getContent() {
// InputStream stream = null;
// String content = null;
// try {
// stream = getContext().getAssets().open(value);
// int size = stream.available();
// byte[] buffer = new byte[size];
// stream.read(buffer);
// content = new String(buffer);
// } catch (IOException e) {
// Log.e(TAG, String.format("Can't load file '%s'", value));
// } finally {
// try {
// if (stream != null)
// stream.close();
// } catch (IOException ioe) {
// Log.e(TAG, ioe.getMessage(), ioe);
// }
// }
// return content;
// }
//
// /**
// * Return time when this message was received.
// * @return long timestamp
// */
// public long getReceived() {
// return received;
// }
//
// /**
// * Returns value of this message.
// * @return value
// */
// public String getValue() {
// return value;
// }
//
// /**
// * Checks if this message is received and not deleted.
// * @return true if message is visible, false otherwise
// */
// public boolean isVisible() {
// return (status != MessageStatus.NONE) && (status != MessageStatus.DELETED);
// }
//
// /**
// * Receive this message - marks as unread if not visible yet.
// */
// public void activate() {
// if (status == MessageStatus.NONE) {
// GameHandler handler = getScenario().getHandler();
//
// status = MessageStatus.UNREAD;
// received = handler.getGameTime();
// handler.broadcastEvent(new GameEvent(EventType.UPDATED_MESSAGES, id));
// }
// }
//
// }
// Path: Gamework/src/cz/robyer/gamework/scenario/reaction/MessageReaction.java
import android.util.Log;
import cz.robyer.gamework.scenario.message.Message;
package cz.robyer.gamework.scenario.reaction;
/**
* Game reaction which "receive" (make available to user) game message.
* @author Robert Pösel
*/
public class MessageReaction extends Reaction {
protected String value; | protected Message message; |
Robyer/Gamework | Gamework/src/cz/robyer/gamework/scenario/reaction/ActivityReaction.java | // Path: Gamework/src/cz/robyer/gamework/utils/Utils.java
// public class Utils {
//
// /**
// * Checks if there exists activity required for particular intent.
// * @param context
// * @param intent to be checked.
// * @return true if intent can be called, false otherwise.
// */
// public static boolean isIntentCallable(Context context, Intent intent) {
// return context.getPackageManager().resolveActivity(intent, PackageManager.MATCH_DEFAULT_ONLY) != null;
// }
//
// }
| import android.content.Intent;
import android.util.Log;
import cz.robyer.gamework.utils.Utils; | package cz.robyer.gamework.scenario.reaction;
/**
* Game reaction which starts activity.
* @author Robert Pösel
*/
public class ActivityReaction extends Reaction {
protected String value;
protected Intent intent;
/**
* Class constructor.
* @param id Identificator of this reaction.
* @param value Full name (with namespace) of activity class which should be started.
*/
public ActivityReaction(String id, String value) {
super(id);
this.value = value;
}
/**
* Prepares intent which will be used to run activity.
*/
/* (non-Javadoc)
* @see cz.robyer.gamework.scenario.BaseObject#onScenarioLoaded()
*/
@Override
public boolean onScenarioLoaded() {
intent = new Intent();
// fix for relative class name, make it absolute
if (value.charAt(0) == '.')
value = getContext().getPackageName() + value;
intent.setClassName(getContext(), value);
intent.putExtra("reaction", id); // distribute reaction id to the activity
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
| // Path: Gamework/src/cz/robyer/gamework/utils/Utils.java
// public class Utils {
//
// /**
// * Checks if there exists activity required for particular intent.
// * @param context
// * @param intent to be checked.
// * @return true if intent can be called, false otherwise.
// */
// public static boolean isIntentCallable(Context context, Intent intent) {
// return context.getPackageManager().resolveActivity(intent, PackageManager.MATCH_DEFAULT_ONLY) != null;
// }
//
// }
// Path: Gamework/src/cz/robyer/gamework/scenario/reaction/ActivityReaction.java
import android.content.Intent;
import android.util.Log;
import cz.robyer.gamework.utils.Utils;
package cz.robyer.gamework.scenario.reaction;
/**
* Game reaction which starts activity.
* @author Robert Pösel
*/
public class ActivityReaction extends Reaction {
protected String value;
protected Intent intent;
/**
* Class constructor.
* @param id Identificator of this reaction.
* @param value Full name (with namespace) of activity class which should be started.
*/
public ActivityReaction(String id, String value) {
super(id);
this.value = value;
}
/**
* Prepares intent which will be used to run activity.
*/
/* (non-Javadoc)
* @see cz.robyer.gamework.scenario.BaseObject#onScenarioLoaded()
*/
@Override
public boolean onScenarioLoaded() {
intent = new Intent();
// fix for relative class name, make it absolute
if (value.charAt(0) == '.')
value = getContext().getPackageName() + value;
intent.setClassName(getContext(), value);
intent.putExtra("reaction", id); // distribute reaction id to the activity
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
| if (!Utils.isIntentCallable(getContext(), intent)) { |
Robyer/Gamework | Gamework/src/cz/robyer/gamework/scenario/BaseObject.java | // Path: Gamework/src/cz/robyer/gamework/game/GameHandler.java
// public class GameHandler implements GameEventBroadcaster {
// private static final String TAG = GameHandler.class.getSimpleName();
//
// private final WeakHashMap<GameEventListener, Boolean> listeners = new WeakHashMap<GameEventListener, Boolean>();
// private final GameService parent;
//
// /**
// * Class constructor.
// * @param parent GameService which uses this handler.
// */
// public GameHandler(GameService parent) {
// this.parent = parent;
// }
//
// /**
// * Add listener.
// * @param listener
// * @return true if listener was added or false if it already existed
// */
// public synchronized boolean addListener(GameEventListener listener) {
// Log.d(TAG, "Adding GameEventListener " + listener.toString());
// return (listeners.put(listener, true) == null);
// }
//
// /**
// * Remove registered listener.
// * @param listener to remove
// * @return true when listener was removed or false if it did not existed
// */
// public synchronized boolean removeListener(GameEventListener listener) {
// Log.d(TAG, "Removing GameEventListener " + listener.toString());
// return (listeners.remove(listener) != null);
// }
//
// /**
// * Removes all registered listeners.
// */
// public synchronized void clearListeners() {
// Log.d(TAG, "Clearing GameEventListeners");
// listeners.clear();
// }
//
// /**
// * Broadcasts {@link GameEvent} to all registered listeners.
// */
// @Override
// public synchronized void broadcastEvent(GameEvent event) {
// int severity = android.util.Log.INFO;
// if (event.type == EventType.UPDATED_LOCATION ||
// event.type == EventType.UPDATED_TIME) {
// severity = android.util.Log.DEBUG;
// }
//
// if (Log.loggingEnabled()) {
// Log.println(severity, TAG, "Broadcasting event " + event.type.name() + " to " + listeners.size() + " listeners");
// }
//
// for (GameEventListener listener : listeners.keySet()) {
// if (listener != null) {
// listener.receiveEvent(event);
// }
// }
// }
//
// /**
// * Broadcasts {@link GameEvent} to all registered listeners.
// * @param type
// */
// public synchronized void broadcastEvent(EventType type) {
// broadcastEvent(new GameEvent(type));
// }
//
// /**
// * Returns actual game time in milliseconds.
// */
// public long getGameTime() {
// return parent.getTime();
// }
// }
//
// Path: Gamework/src/cz/robyer/gamework/utils/Log.java
// public class Log {
//
// private static final boolean debug = true;
//
// public static boolean loggingEnabled() {
// return debug;
// }
//
// public static void v(String tag, String msg) {
// if (loggingEnabled())
// android.util.Log.v(tag, msg);
// }
//
// public static void d(String tag, String msg) {
// if (loggingEnabled())
// android.util.Log.d(tag, msg);
// }
//
// public static void i(String tag, String msg) {
// if (loggingEnabled())
// android.util.Log.i(tag, msg);
// }
//
// public static void w(String tag, String msg) {
// android.util.Log.w(tag, msg);
// }
//
// public static void e(String tag, String msg) {
// android.util.Log.e(tag, msg);
// }
//
// public static void e(String tag, String msg, Exception e) {
// android.util.Log.e(tag, msg, e);
// }
//
// public static void println(int severity, String tag, String message) {
// if (loggingEnabled())
// android.util.Log.println(severity, tag, message);
// }
//
// }
| import android.content.Context;
import cz.robyer.gamework.game.GameHandler;
import cz.robyer.gamework.utils.Log; | package cz.robyer.gamework.scenario;
/**
* This is base object for scenario.
* @author Robert Pösel
*/
public abstract class BaseObject {
protected Scenario scenario;
protected Context context;
/**
* Attach scenario to this object.
* @param scenario
*/
public void setScenario(Scenario scenario) {
this.scenario = scenario;
this.context = scenario.getContext();
}
/**
* This is called when scenario loaded all objects.
* @return false if error occured
*/
public boolean onScenarioLoaded() {
return true;
}
/**
* Checks if this object is attached to scenario.
* @return true if is attached, false otherwise
*/
public boolean isAttached() {
return (scenario != null);
}
/**
* Return application context from scenario.
* @return Context or throws exception
*/
public Context getContext() {
if (context == null) { | // Path: Gamework/src/cz/robyer/gamework/game/GameHandler.java
// public class GameHandler implements GameEventBroadcaster {
// private static final String TAG = GameHandler.class.getSimpleName();
//
// private final WeakHashMap<GameEventListener, Boolean> listeners = new WeakHashMap<GameEventListener, Boolean>();
// private final GameService parent;
//
// /**
// * Class constructor.
// * @param parent GameService which uses this handler.
// */
// public GameHandler(GameService parent) {
// this.parent = parent;
// }
//
// /**
// * Add listener.
// * @param listener
// * @return true if listener was added or false if it already existed
// */
// public synchronized boolean addListener(GameEventListener listener) {
// Log.d(TAG, "Adding GameEventListener " + listener.toString());
// return (listeners.put(listener, true) == null);
// }
//
// /**
// * Remove registered listener.
// * @param listener to remove
// * @return true when listener was removed or false if it did not existed
// */
// public synchronized boolean removeListener(GameEventListener listener) {
// Log.d(TAG, "Removing GameEventListener " + listener.toString());
// return (listeners.remove(listener) != null);
// }
//
// /**
// * Removes all registered listeners.
// */
// public synchronized void clearListeners() {
// Log.d(TAG, "Clearing GameEventListeners");
// listeners.clear();
// }
//
// /**
// * Broadcasts {@link GameEvent} to all registered listeners.
// */
// @Override
// public synchronized void broadcastEvent(GameEvent event) {
// int severity = android.util.Log.INFO;
// if (event.type == EventType.UPDATED_LOCATION ||
// event.type == EventType.UPDATED_TIME) {
// severity = android.util.Log.DEBUG;
// }
//
// if (Log.loggingEnabled()) {
// Log.println(severity, TAG, "Broadcasting event " + event.type.name() + " to " + listeners.size() + " listeners");
// }
//
// for (GameEventListener listener : listeners.keySet()) {
// if (listener != null) {
// listener.receiveEvent(event);
// }
// }
// }
//
// /**
// * Broadcasts {@link GameEvent} to all registered listeners.
// * @param type
// */
// public synchronized void broadcastEvent(EventType type) {
// broadcastEvent(new GameEvent(type));
// }
//
// /**
// * Returns actual game time in milliseconds.
// */
// public long getGameTime() {
// return parent.getTime();
// }
// }
//
// Path: Gamework/src/cz/robyer/gamework/utils/Log.java
// public class Log {
//
// private static final boolean debug = true;
//
// public static boolean loggingEnabled() {
// return debug;
// }
//
// public static void v(String tag, String msg) {
// if (loggingEnabled())
// android.util.Log.v(tag, msg);
// }
//
// public static void d(String tag, String msg) {
// if (loggingEnabled())
// android.util.Log.d(tag, msg);
// }
//
// public static void i(String tag, String msg) {
// if (loggingEnabled())
// android.util.Log.i(tag, msg);
// }
//
// public static void w(String tag, String msg) {
// android.util.Log.w(tag, msg);
// }
//
// public static void e(String tag, String msg) {
// android.util.Log.e(tag, msg);
// }
//
// public static void e(String tag, String msg, Exception e) {
// android.util.Log.e(tag, msg, e);
// }
//
// public static void println(int severity, String tag, String message) {
// if (loggingEnabled())
// android.util.Log.println(severity, tag, message);
// }
//
// }
// Path: Gamework/src/cz/robyer/gamework/scenario/BaseObject.java
import android.content.Context;
import cz.robyer.gamework.game.GameHandler;
import cz.robyer.gamework.utils.Log;
package cz.robyer.gamework.scenario;
/**
* This is base object for scenario.
* @author Robert Pösel
*/
public abstract class BaseObject {
protected Scenario scenario;
protected Context context;
/**
* Attach scenario to this object.
* @param scenario
*/
public void setScenario(Scenario scenario) {
this.scenario = scenario;
this.context = scenario.getContext();
}
/**
* This is called when scenario loaded all objects.
* @return false if error occured
*/
public boolean onScenarioLoaded() {
return true;
}
/**
* Checks if this object is attached to scenario.
* @return true if is attached, false otherwise
*/
public boolean isAttached() {
return (scenario != null);
}
/**
* Return application context from scenario.
* @return Context or throws exception
*/
public Context getContext() {
if (context == null) { | Log.e("BaseObject", "BaseObject '" + this + "' is not attached to any Scenario"); |
Robyer/Gamework | Gamework/src/cz/robyer/gamework/scenario/BaseObject.java | // Path: Gamework/src/cz/robyer/gamework/game/GameHandler.java
// public class GameHandler implements GameEventBroadcaster {
// private static final String TAG = GameHandler.class.getSimpleName();
//
// private final WeakHashMap<GameEventListener, Boolean> listeners = new WeakHashMap<GameEventListener, Boolean>();
// private final GameService parent;
//
// /**
// * Class constructor.
// * @param parent GameService which uses this handler.
// */
// public GameHandler(GameService parent) {
// this.parent = parent;
// }
//
// /**
// * Add listener.
// * @param listener
// * @return true if listener was added or false if it already existed
// */
// public synchronized boolean addListener(GameEventListener listener) {
// Log.d(TAG, "Adding GameEventListener " + listener.toString());
// return (listeners.put(listener, true) == null);
// }
//
// /**
// * Remove registered listener.
// * @param listener to remove
// * @return true when listener was removed or false if it did not existed
// */
// public synchronized boolean removeListener(GameEventListener listener) {
// Log.d(TAG, "Removing GameEventListener " + listener.toString());
// return (listeners.remove(listener) != null);
// }
//
// /**
// * Removes all registered listeners.
// */
// public synchronized void clearListeners() {
// Log.d(TAG, "Clearing GameEventListeners");
// listeners.clear();
// }
//
// /**
// * Broadcasts {@link GameEvent} to all registered listeners.
// */
// @Override
// public synchronized void broadcastEvent(GameEvent event) {
// int severity = android.util.Log.INFO;
// if (event.type == EventType.UPDATED_LOCATION ||
// event.type == EventType.UPDATED_TIME) {
// severity = android.util.Log.DEBUG;
// }
//
// if (Log.loggingEnabled()) {
// Log.println(severity, TAG, "Broadcasting event " + event.type.name() + " to " + listeners.size() + " listeners");
// }
//
// for (GameEventListener listener : listeners.keySet()) {
// if (listener != null) {
// listener.receiveEvent(event);
// }
// }
// }
//
// /**
// * Broadcasts {@link GameEvent} to all registered listeners.
// * @param type
// */
// public synchronized void broadcastEvent(EventType type) {
// broadcastEvent(new GameEvent(type));
// }
//
// /**
// * Returns actual game time in milliseconds.
// */
// public long getGameTime() {
// return parent.getTime();
// }
// }
//
// Path: Gamework/src/cz/robyer/gamework/utils/Log.java
// public class Log {
//
// private static final boolean debug = true;
//
// public static boolean loggingEnabled() {
// return debug;
// }
//
// public static void v(String tag, String msg) {
// if (loggingEnabled())
// android.util.Log.v(tag, msg);
// }
//
// public static void d(String tag, String msg) {
// if (loggingEnabled())
// android.util.Log.d(tag, msg);
// }
//
// public static void i(String tag, String msg) {
// if (loggingEnabled())
// android.util.Log.i(tag, msg);
// }
//
// public static void w(String tag, String msg) {
// android.util.Log.w(tag, msg);
// }
//
// public static void e(String tag, String msg) {
// android.util.Log.e(tag, msg);
// }
//
// public static void e(String tag, String msg, Exception e) {
// android.util.Log.e(tag, msg, e);
// }
//
// public static void println(int severity, String tag, String message) {
// if (loggingEnabled())
// android.util.Log.println(severity, tag, message);
// }
//
// }
| import android.content.Context;
import cz.robyer.gamework.game.GameHandler;
import cz.robyer.gamework.utils.Log; | package cz.robyer.gamework.scenario;
/**
* This is base object for scenario.
* @author Robert Pösel
*/
public abstract class BaseObject {
protected Scenario scenario;
protected Context context;
/**
* Attach scenario to this object.
* @param scenario
*/
public void setScenario(Scenario scenario) {
this.scenario = scenario;
this.context = scenario.getContext();
}
/**
* This is called when scenario loaded all objects.
* @return false if error occured
*/
public boolean onScenarioLoaded() {
return true;
}
/**
* Checks if this object is attached to scenario.
* @return true if is attached, false otherwise
*/
public boolean isAttached() {
return (scenario != null);
}
/**
* Return application context from scenario.
* @return Context or throws exception
*/
public Context getContext() {
if (context == null) {
Log.e("BaseObject", "BaseObject '" + this + "' is not attached to any Scenario");
throw new RuntimeException();
}
return context;
}
/**
* Return game scenario object.
* @return Scenario or throws exception
*/
public Scenario getScenario() {
if (scenario == null) {
Log.e("BaseObject", "BaseObject '" + this + "' is not attached to any Scenario");
throw new RuntimeException();
}
return scenario;
}
/**
* Shortcut for getting game handler from scenario.
* @return GameHandler or throws exception
*/ | // Path: Gamework/src/cz/robyer/gamework/game/GameHandler.java
// public class GameHandler implements GameEventBroadcaster {
// private static final String TAG = GameHandler.class.getSimpleName();
//
// private final WeakHashMap<GameEventListener, Boolean> listeners = new WeakHashMap<GameEventListener, Boolean>();
// private final GameService parent;
//
// /**
// * Class constructor.
// * @param parent GameService which uses this handler.
// */
// public GameHandler(GameService parent) {
// this.parent = parent;
// }
//
// /**
// * Add listener.
// * @param listener
// * @return true if listener was added or false if it already existed
// */
// public synchronized boolean addListener(GameEventListener listener) {
// Log.d(TAG, "Adding GameEventListener " + listener.toString());
// return (listeners.put(listener, true) == null);
// }
//
// /**
// * Remove registered listener.
// * @param listener to remove
// * @return true when listener was removed or false if it did not existed
// */
// public synchronized boolean removeListener(GameEventListener listener) {
// Log.d(TAG, "Removing GameEventListener " + listener.toString());
// return (listeners.remove(listener) != null);
// }
//
// /**
// * Removes all registered listeners.
// */
// public synchronized void clearListeners() {
// Log.d(TAG, "Clearing GameEventListeners");
// listeners.clear();
// }
//
// /**
// * Broadcasts {@link GameEvent} to all registered listeners.
// */
// @Override
// public synchronized void broadcastEvent(GameEvent event) {
// int severity = android.util.Log.INFO;
// if (event.type == EventType.UPDATED_LOCATION ||
// event.type == EventType.UPDATED_TIME) {
// severity = android.util.Log.DEBUG;
// }
//
// if (Log.loggingEnabled()) {
// Log.println(severity, TAG, "Broadcasting event " + event.type.name() + " to " + listeners.size() + " listeners");
// }
//
// for (GameEventListener listener : listeners.keySet()) {
// if (listener != null) {
// listener.receiveEvent(event);
// }
// }
// }
//
// /**
// * Broadcasts {@link GameEvent} to all registered listeners.
// * @param type
// */
// public synchronized void broadcastEvent(EventType type) {
// broadcastEvent(new GameEvent(type));
// }
//
// /**
// * Returns actual game time in milliseconds.
// */
// public long getGameTime() {
// return parent.getTime();
// }
// }
//
// Path: Gamework/src/cz/robyer/gamework/utils/Log.java
// public class Log {
//
// private static final boolean debug = true;
//
// public static boolean loggingEnabled() {
// return debug;
// }
//
// public static void v(String tag, String msg) {
// if (loggingEnabled())
// android.util.Log.v(tag, msg);
// }
//
// public static void d(String tag, String msg) {
// if (loggingEnabled())
// android.util.Log.d(tag, msg);
// }
//
// public static void i(String tag, String msg) {
// if (loggingEnabled())
// android.util.Log.i(tag, msg);
// }
//
// public static void w(String tag, String msg) {
// android.util.Log.w(tag, msg);
// }
//
// public static void e(String tag, String msg) {
// android.util.Log.e(tag, msg);
// }
//
// public static void e(String tag, String msg, Exception e) {
// android.util.Log.e(tag, msg, e);
// }
//
// public static void println(int severity, String tag, String message) {
// if (loggingEnabled())
// android.util.Log.println(severity, tag, message);
// }
//
// }
// Path: Gamework/src/cz/robyer/gamework/scenario/BaseObject.java
import android.content.Context;
import cz.robyer.gamework.game.GameHandler;
import cz.robyer.gamework.utils.Log;
package cz.robyer.gamework.scenario;
/**
* This is base object for scenario.
* @author Robert Pösel
*/
public abstract class BaseObject {
protected Scenario scenario;
protected Context context;
/**
* Attach scenario to this object.
* @param scenario
*/
public void setScenario(Scenario scenario) {
this.scenario = scenario;
this.context = scenario.getContext();
}
/**
* This is called when scenario loaded all objects.
* @return false if error occured
*/
public boolean onScenarioLoaded() {
return true;
}
/**
* Checks if this object is attached to scenario.
* @return true if is attached, false otherwise
*/
public boolean isAttached() {
return (scenario != null);
}
/**
* Return application context from scenario.
* @return Context or throws exception
*/
public Context getContext() {
if (context == null) {
Log.e("BaseObject", "BaseObject '" + this + "' is not attached to any Scenario");
throw new RuntimeException();
}
return context;
}
/**
* Return game scenario object.
* @return Scenario or throws exception
*/
public Scenario getScenario() {
if (scenario == null) {
Log.e("BaseObject", "BaseObject '" + this + "' is not attached to any Scenario");
throw new RuntimeException();
}
return scenario;
}
/**
* Shortcut for getting game handler from scenario.
* @return GameHandler or throws exception
*/ | public GameHandler getHandler() { |
Robyer/Gamework | Gamework/src/cz/robyer/gamework/scenario/variable/BooleanVariable.java | // Path: Gamework/src/cz/robyer/gamework/scenario/reaction/VariableReaction.java
// public static enum OperatorType {SET, INCREMENT, DECREMENT, MULTIPLY, DIVIDE, NEGATE};
//
// Path: Gamework/src/cz/robyer/gamework/utils/Log.java
// public class Log {
//
// private static final boolean debug = true;
//
// public static boolean loggingEnabled() {
// return debug;
// }
//
// public static void v(String tag, String msg) {
// if (loggingEnabled())
// android.util.Log.v(tag, msg);
// }
//
// public static void d(String tag, String msg) {
// if (loggingEnabled())
// android.util.Log.d(tag, msg);
// }
//
// public static void i(String tag, String msg) {
// if (loggingEnabled())
// android.util.Log.i(tag, msg);
// }
//
// public static void w(String tag, String msg) {
// android.util.Log.w(tag, msg);
// }
//
// public static void e(String tag, String msg) {
// android.util.Log.e(tag, msg);
// }
//
// public static void e(String tag, String msg, Exception e) {
// android.util.Log.e(tag, msg, e);
// }
//
// public static void println(int severity, String tag, String message) {
// if (loggingEnabled())
// android.util.Log.println(severity, tag, message);
// }
//
// }
| import cz.robyer.gamework.scenario.reaction.VariableReaction.OperatorType;
import cz.robyer.gamework.utils.Log; | package cz.robyer.gamework.scenario.variable;
/**
* Represents variable with only 2 states - true and false.
* @author Robert Pösel
*/
public class BooleanVariable extends Variable {
protected boolean value;
/**
* Class constructor.
* @param id - identificator of variable
* @param value - actual (default) value
*/
public BooleanVariable(String id, boolean value) {
super(id);
this.value = value;
}
/**
* Factory for creating this variable from string value.
* @param id - identificator of variable
* @param value - actual (default) value a string
* @return BooleanVariable
*/
public static BooleanVariable fromString(String id, String value) {
return new BooleanVariable(id, Boolean.parseBoolean(value));
}
/**
* Sets value of this variable.
* @param value to be set
*/
public void setValue(boolean value) {
this.value = value;
}
/**
* Get value of this variable.
* @return actual value
*/
public boolean getValue() {
return value;
}
/* (non-Javadoc)
* @see cz.robyer.gamework.scenario.variable.Variable#modify(cz.robyer.gamework.scenario.reaction.VariableReaction.OperatorType, java.lang.Object)
*/
@Override | // Path: Gamework/src/cz/robyer/gamework/scenario/reaction/VariableReaction.java
// public static enum OperatorType {SET, INCREMENT, DECREMENT, MULTIPLY, DIVIDE, NEGATE};
//
// Path: Gamework/src/cz/robyer/gamework/utils/Log.java
// public class Log {
//
// private static final boolean debug = true;
//
// public static boolean loggingEnabled() {
// return debug;
// }
//
// public static void v(String tag, String msg) {
// if (loggingEnabled())
// android.util.Log.v(tag, msg);
// }
//
// public static void d(String tag, String msg) {
// if (loggingEnabled())
// android.util.Log.d(tag, msg);
// }
//
// public static void i(String tag, String msg) {
// if (loggingEnabled())
// android.util.Log.i(tag, msg);
// }
//
// public static void w(String tag, String msg) {
// android.util.Log.w(tag, msg);
// }
//
// public static void e(String tag, String msg) {
// android.util.Log.e(tag, msg);
// }
//
// public static void e(String tag, String msg, Exception e) {
// android.util.Log.e(tag, msg, e);
// }
//
// public static void println(int severity, String tag, String message) {
// if (loggingEnabled())
// android.util.Log.println(severity, tag, message);
// }
//
// }
// Path: Gamework/src/cz/robyer/gamework/scenario/variable/BooleanVariable.java
import cz.robyer.gamework.scenario.reaction.VariableReaction.OperatorType;
import cz.robyer.gamework.utils.Log;
package cz.robyer.gamework.scenario.variable;
/**
* Represents variable with only 2 states - true and false.
* @author Robert Pösel
*/
public class BooleanVariable extends Variable {
protected boolean value;
/**
* Class constructor.
* @param id - identificator of variable
* @param value - actual (default) value
*/
public BooleanVariable(String id, boolean value) {
super(id);
this.value = value;
}
/**
* Factory for creating this variable from string value.
* @param id - identificator of variable
* @param value - actual (default) value a string
* @return BooleanVariable
*/
public static BooleanVariable fromString(String id, String value) {
return new BooleanVariable(id, Boolean.parseBoolean(value));
}
/**
* Sets value of this variable.
* @param value to be set
*/
public void setValue(boolean value) {
this.value = value;
}
/**
* Get value of this variable.
* @return actual value
*/
public boolean getValue() {
return value;
}
/* (non-Javadoc)
* @see cz.robyer.gamework.scenario.variable.Variable#modify(cz.robyer.gamework.scenario.reaction.VariableReaction.OperatorType, java.lang.Object)
*/
@Override | public void modify(OperatorType type, Object val) { |
Robyer/Gamework | Gamework/src/cz/robyer/gamework/scenario/variable/BooleanVariable.java | // Path: Gamework/src/cz/robyer/gamework/scenario/reaction/VariableReaction.java
// public static enum OperatorType {SET, INCREMENT, DECREMENT, MULTIPLY, DIVIDE, NEGATE};
//
// Path: Gamework/src/cz/robyer/gamework/utils/Log.java
// public class Log {
//
// private static final boolean debug = true;
//
// public static boolean loggingEnabled() {
// return debug;
// }
//
// public static void v(String tag, String msg) {
// if (loggingEnabled())
// android.util.Log.v(tag, msg);
// }
//
// public static void d(String tag, String msg) {
// if (loggingEnabled())
// android.util.Log.d(tag, msg);
// }
//
// public static void i(String tag, String msg) {
// if (loggingEnabled())
// android.util.Log.i(tag, msg);
// }
//
// public static void w(String tag, String msg) {
// android.util.Log.w(tag, msg);
// }
//
// public static void e(String tag, String msg) {
// android.util.Log.e(tag, msg);
// }
//
// public static void e(String tag, String msg, Exception e) {
// android.util.Log.e(tag, msg, e);
// }
//
// public static void println(int severity, String tag, String message) {
// if (loggingEnabled())
// android.util.Log.println(severity, tag, message);
// }
//
// }
| import cz.robyer.gamework.scenario.reaction.VariableReaction.OperatorType;
import cz.robyer.gamework.utils.Log; | package cz.robyer.gamework.scenario.variable;
/**
* Represents variable with only 2 states - true and false.
* @author Robert Pösel
*/
public class BooleanVariable extends Variable {
protected boolean value;
/**
* Class constructor.
* @param id - identificator of variable
* @param value - actual (default) value
*/
public BooleanVariable(String id, boolean value) {
super(id);
this.value = value;
}
/**
* Factory for creating this variable from string value.
* @param id - identificator of variable
* @param value - actual (default) value a string
* @return BooleanVariable
*/
public static BooleanVariable fromString(String id, String value) {
return new BooleanVariable(id, Boolean.parseBoolean(value));
}
/**
* Sets value of this variable.
* @param value to be set
*/
public void setValue(boolean value) {
this.value = value;
}
/**
* Get value of this variable.
* @return actual value
*/
public boolean getValue() {
return value;
}
/* (non-Javadoc)
* @see cz.robyer.gamework.scenario.variable.Variable#modify(cz.robyer.gamework.scenario.reaction.VariableReaction.OperatorType, java.lang.Object)
*/
@Override
public void modify(OperatorType type, Object val) {
boolean value;
if (val instanceof Boolean)
value = (Boolean)val;
else if (val instanceof String)
value = Boolean.parseBoolean((String)val);
else { | // Path: Gamework/src/cz/robyer/gamework/scenario/reaction/VariableReaction.java
// public static enum OperatorType {SET, INCREMENT, DECREMENT, MULTIPLY, DIVIDE, NEGATE};
//
// Path: Gamework/src/cz/robyer/gamework/utils/Log.java
// public class Log {
//
// private static final boolean debug = true;
//
// public static boolean loggingEnabled() {
// return debug;
// }
//
// public static void v(String tag, String msg) {
// if (loggingEnabled())
// android.util.Log.v(tag, msg);
// }
//
// public static void d(String tag, String msg) {
// if (loggingEnabled())
// android.util.Log.d(tag, msg);
// }
//
// public static void i(String tag, String msg) {
// if (loggingEnabled())
// android.util.Log.i(tag, msg);
// }
//
// public static void w(String tag, String msg) {
// android.util.Log.w(tag, msg);
// }
//
// public static void e(String tag, String msg) {
// android.util.Log.e(tag, msg);
// }
//
// public static void e(String tag, String msg, Exception e) {
// android.util.Log.e(tag, msg, e);
// }
//
// public static void println(int severity, String tag, String message) {
// if (loggingEnabled())
// android.util.Log.println(severity, tag, message);
// }
//
// }
// Path: Gamework/src/cz/robyer/gamework/scenario/variable/BooleanVariable.java
import cz.robyer.gamework.scenario.reaction.VariableReaction.OperatorType;
import cz.robyer.gamework.utils.Log;
package cz.robyer.gamework.scenario.variable;
/**
* Represents variable with only 2 states - true and false.
* @author Robert Pösel
*/
public class BooleanVariable extends Variable {
protected boolean value;
/**
* Class constructor.
* @param id - identificator of variable
* @param value - actual (default) value
*/
public BooleanVariable(String id, boolean value) {
super(id);
this.value = value;
}
/**
* Factory for creating this variable from string value.
* @param id - identificator of variable
* @param value - actual (default) value a string
* @return BooleanVariable
*/
public static BooleanVariable fromString(String id, String value) {
return new BooleanVariable(id, Boolean.parseBoolean(value));
}
/**
* Sets value of this variable.
* @param value to be set
*/
public void setValue(boolean value) {
this.value = value;
}
/**
* Get value of this variable.
* @return actual value
*/
public boolean getValue() {
return value;
}
/* (non-Javadoc)
* @see cz.robyer.gamework.scenario.variable.Variable#modify(cz.robyer.gamework.scenario.reaction.VariableReaction.OperatorType, java.lang.Object)
*/
@Override
public void modify(OperatorType type, Object val) {
boolean value;
if (val instanceof Boolean)
value = (Boolean)val;
else if (val instanceof String)
value = Boolean.parseBoolean((String)val);
else { | Log.e(TAG, "Not supported VariableReaction value"); |
Robyer/Gamework | Gamework/src/cz/robyer/gamework/scenario/reaction/EventReaction.java | // Path: Gamework/src/cz/robyer/gamework/game/GameEvent.java
// public class GameEvent implements Serializable {
//
// private static final long serialVersionUID = -624979683919801177L;
//
// public enum EventType {
// GAME_START, /** Game start/continue. */
// GAME_PAUSE, /** Event for pausing game service. */
// GAME_WIN, /** Player won the game. */
// GAME_LOSE, /** Player lost the game. */
// GAME_QUIT, /** Event for stop game service. */
// UPDATED_LOCATION, /** Player's location was updated. */
// UPDATED_TIME, /** Game time was updated. */
// UPDATED_MESSAGES, /** Game message was received */
// SCANNED_CODE, /** User scanned some QR code */
// CUSTOM, /** Custom event whose value was defined in scenario */
// }
//
// public final EventType type;
// public final Object value;
//
// /**
// * Class constructor for basic events without value.
// * @param type
// */
// public GameEvent(EventType type) {
// this(type, null);
// }
//
// /**
// * Class constructor for events which contains additional value.
// * @param type
// * @param value
// */
// public GameEvent(EventType type, Object value) {
// this.type = type;
// this.value = value;
// }
// }
//
// Path: Gamework/src/cz/robyer/gamework/game/GameEvent.java
// public enum EventType {
// GAME_START, /** Game start/continue. */
// GAME_PAUSE, /** Event for pausing game service. */
// GAME_WIN, /** Player won the game. */
// GAME_LOSE, /** Player lost the game. */
// GAME_QUIT, /** Event for stop game service. */
// UPDATED_LOCATION, /** Player's location was updated. */
// UPDATED_TIME, /** Game time was updated. */
// UPDATED_MESSAGES, /** Game message was received */
// SCANNED_CODE, /** User scanned some QR code */
// CUSTOM, /** Custom event whose value was defined in scenario */
// }
| import android.util.Log;
import cz.robyer.gamework.game.GameEvent;
import cz.robyer.gamework.game.GameEvent.EventType; | package cz.robyer.gamework.scenario.reaction;
/**
* Game reaction which sends game event.
* @author Robert Pösel
*/
public class EventReaction extends Reaction {
protected GameEvent value;
/**
* Class constructor.
* @param id Identificator of this reaction.
* @param value GameEvent which should be sent.
*/
public EventReaction(String id, GameEvent value) {
super(id);
this.value = value;
}
/**
* Class constructor.
* @param id Identificator of this reaction.
* @param type EventType of event which should be set.
*/ | // Path: Gamework/src/cz/robyer/gamework/game/GameEvent.java
// public class GameEvent implements Serializable {
//
// private static final long serialVersionUID = -624979683919801177L;
//
// public enum EventType {
// GAME_START, /** Game start/continue. */
// GAME_PAUSE, /** Event for pausing game service. */
// GAME_WIN, /** Player won the game. */
// GAME_LOSE, /** Player lost the game. */
// GAME_QUIT, /** Event for stop game service. */
// UPDATED_LOCATION, /** Player's location was updated. */
// UPDATED_TIME, /** Game time was updated. */
// UPDATED_MESSAGES, /** Game message was received */
// SCANNED_CODE, /** User scanned some QR code */
// CUSTOM, /** Custom event whose value was defined in scenario */
// }
//
// public final EventType type;
// public final Object value;
//
// /**
// * Class constructor for basic events without value.
// * @param type
// */
// public GameEvent(EventType type) {
// this(type, null);
// }
//
// /**
// * Class constructor for events which contains additional value.
// * @param type
// * @param value
// */
// public GameEvent(EventType type, Object value) {
// this.type = type;
// this.value = value;
// }
// }
//
// Path: Gamework/src/cz/robyer/gamework/game/GameEvent.java
// public enum EventType {
// GAME_START, /** Game start/continue. */
// GAME_PAUSE, /** Event for pausing game service. */
// GAME_WIN, /** Player won the game. */
// GAME_LOSE, /** Player lost the game. */
// GAME_QUIT, /** Event for stop game service. */
// UPDATED_LOCATION, /** Player's location was updated. */
// UPDATED_TIME, /** Game time was updated. */
// UPDATED_MESSAGES, /** Game message was received */
// SCANNED_CODE, /** User scanned some QR code */
// CUSTOM, /** Custom event whose value was defined in scenario */
// }
// Path: Gamework/src/cz/robyer/gamework/scenario/reaction/EventReaction.java
import android.util.Log;
import cz.robyer.gamework.game.GameEvent;
import cz.robyer.gamework.game.GameEvent.EventType;
package cz.robyer.gamework.scenario.reaction;
/**
* Game reaction which sends game event.
* @author Robert Pösel
*/
public class EventReaction extends Reaction {
protected GameEvent value;
/**
* Class constructor.
* @param id Identificator of this reaction.
* @param value GameEvent which should be sent.
*/
public EventReaction(String id, GameEvent value) {
super(id);
this.value = value;
}
/**
* Class constructor.
* @param id Identificator of this reaction.
* @param type EventType of event which should be set.
*/ | public EventReaction(String id, EventType type) { |
Robyer/Gamework | Gamework/src/cz/robyer/gamework/scenario/variable/Variable.java | // Path: Gamework/src/cz/robyer/gamework/scenario/HookableObject.java
// public abstract class HookableObject extends IdentificableObject {
// protected List<Hook> hooks;
//
// /**
// * Class constructor.
// * @param id of object
// */
// public HookableObject(String id) {
// super(id);
// }
//
// /**
// * Add new hook to be attached.
// * @param hook
// */
// public void addHook(Hook hook) {
// if (hooks == null)
// hooks = new ArrayList<Hook>();
//
// hooks.add(hook);
// hook.setParent(this);
// }
//
// /**
// * Call all attached hooks.
// * @param variable which was changed
// */
// protected void callHooks(Variable variable) {
// Log.d(TAG, "Calling all hooks");
// if (hooks != null) {
// for (Hook h : hooks) {
// h.call(variable);
// }
// }
// }
//
// }
//
// Path: Gamework/src/cz/robyer/gamework/scenario/reaction/VariableReaction.java
// public static enum OperatorType {SET, INCREMENT, DECREMENT, MULTIPLY, DIVIDE, NEGATE};
| import cz.robyer.gamework.scenario.HookableObject;
import cz.robyer.gamework.scenario.reaction.VariableReaction.OperatorType; | package cz.robyer.gamework.scenario.variable;
/**
* Abstract variable object.
* @author Robert Pösel
*/
public abstract class Variable extends HookableObject {
/**
* Class constructor.
* @param id - identificator of variable
*/
public Variable(String id) {
super(id);
}
/**
* This method applies modification of variable and call hooks.
* @param type of operator to be applied
* @param value value to be used
*/ | // Path: Gamework/src/cz/robyer/gamework/scenario/HookableObject.java
// public abstract class HookableObject extends IdentificableObject {
// protected List<Hook> hooks;
//
// /**
// * Class constructor.
// * @param id of object
// */
// public HookableObject(String id) {
// super(id);
// }
//
// /**
// * Add new hook to be attached.
// * @param hook
// */
// public void addHook(Hook hook) {
// if (hooks == null)
// hooks = new ArrayList<Hook>();
//
// hooks.add(hook);
// hook.setParent(this);
// }
//
// /**
// * Call all attached hooks.
// * @param variable which was changed
// */
// protected void callHooks(Variable variable) {
// Log.d(TAG, "Calling all hooks");
// if (hooks != null) {
// for (Hook h : hooks) {
// h.call(variable);
// }
// }
// }
//
// }
//
// Path: Gamework/src/cz/robyer/gamework/scenario/reaction/VariableReaction.java
// public static enum OperatorType {SET, INCREMENT, DECREMENT, MULTIPLY, DIVIDE, NEGATE};
// Path: Gamework/src/cz/robyer/gamework/scenario/variable/Variable.java
import cz.robyer.gamework.scenario.HookableObject;
import cz.robyer.gamework.scenario.reaction.VariableReaction.OperatorType;
package cz.robyer.gamework.scenario.variable;
/**
* Abstract variable object.
* @author Robert Pösel
*/
public abstract class Variable extends HookableObject {
/**
* Class constructor.
* @param id - identificator of variable
*/
public Variable(String id) {
super(id);
}
/**
* This method applies modification of variable and call hooks.
* @param type of operator to be applied
* @param value value to be used
*/ | public abstract void modify(OperatorType type, Object value); |
Robyer/Gamework | Gamework/src/cz/robyer/gamework/game/GameHandler.java | // Path: Gamework/src/cz/robyer/gamework/game/GameEvent.java
// public enum EventType {
// GAME_START, /** Game start/continue. */
// GAME_PAUSE, /** Event for pausing game service. */
// GAME_WIN, /** Player won the game. */
// GAME_LOSE, /** Player lost the game. */
// GAME_QUIT, /** Event for stop game service. */
// UPDATED_LOCATION, /** Player's location was updated. */
// UPDATED_TIME, /** Game time was updated. */
// UPDATED_MESSAGES, /** Game message was received */
// SCANNED_CODE, /** User scanned some QR code */
// CUSTOM, /** Custom event whose value was defined in scenario */
// }
//
// Path: Gamework/src/cz/robyer/gamework/utils/Log.java
// public class Log {
//
// private static final boolean debug = true;
//
// public static boolean loggingEnabled() {
// return debug;
// }
//
// public static void v(String tag, String msg) {
// if (loggingEnabled())
// android.util.Log.v(tag, msg);
// }
//
// public static void d(String tag, String msg) {
// if (loggingEnabled())
// android.util.Log.d(tag, msg);
// }
//
// public static void i(String tag, String msg) {
// if (loggingEnabled())
// android.util.Log.i(tag, msg);
// }
//
// public static void w(String tag, String msg) {
// android.util.Log.w(tag, msg);
// }
//
// public static void e(String tag, String msg) {
// android.util.Log.e(tag, msg);
// }
//
// public static void e(String tag, String msg, Exception e) {
// android.util.Log.e(tag, msg, e);
// }
//
// public static void println(int severity, String tag, String message) {
// if (loggingEnabled())
// android.util.Log.println(severity, tag, message);
// }
//
// }
| import java.util.WeakHashMap;
import cz.robyer.gamework.game.GameEvent.EventType;
import cz.robyer.gamework.utils.Log; | package cz.robyer.gamework.game;
/**
* Handler for broadcasting {@link GameEvent}s.
* @author Robert Pösel
*/
public class GameHandler implements GameEventBroadcaster {
private static final String TAG = GameHandler.class.getSimpleName();
private final WeakHashMap<GameEventListener, Boolean> listeners = new WeakHashMap<GameEventListener, Boolean>();
private final GameService parent;
/**
* Class constructor.
* @param parent GameService which uses this handler.
*/
public GameHandler(GameService parent) {
this.parent = parent;
}
/**
* Add listener.
* @param listener
* @return true if listener was added or false if it already existed
*/
public synchronized boolean addListener(GameEventListener listener) { | // Path: Gamework/src/cz/robyer/gamework/game/GameEvent.java
// public enum EventType {
// GAME_START, /** Game start/continue. */
// GAME_PAUSE, /** Event for pausing game service. */
// GAME_WIN, /** Player won the game. */
// GAME_LOSE, /** Player lost the game. */
// GAME_QUIT, /** Event for stop game service. */
// UPDATED_LOCATION, /** Player's location was updated. */
// UPDATED_TIME, /** Game time was updated. */
// UPDATED_MESSAGES, /** Game message was received */
// SCANNED_CODE, /** User scanned some QR code */
// CUSTOM, /** Custom event whose value was defined in scenario */
// }
//
// Path: Gamework/src/cz/robyer/gamework/utils/Log.java
// public class Log {
//
// private static final boolean debug = true;
//
// public static boolean loggingEnabled() {
// return debug;
// }
//
// public static void v(String tag, String msg) {
// if (loggingEnabled())
// android.util.Log.v(tag, msg);
// }
//
// public static void d(String tag, String msg) {
// if (loggingEnabled())
// android.util.Log.d(tag, msg);
// }
//
// public static void i(String tag, String msg) {
// if (loggingEnabled())
// android.util.Log.i(tag, msg);
// }
//
// public static void w(String tag, String msg) {
// android.util.Log.w(tag, msg);
// }
//
// public static void e(String tag, String msg) {
// android.util.Log.e(tag, msg);
// }
//
// public static void e(String tag, String msg, Exception e) {
// android.util.Log.e(tag, msg, e);
// }
//
// public static void println(int severity, String tag, String message) {
// if (loggingEnabled())
// android.util.Log.println(severity, tag, message);
// }
//
// }
// Path: Gamework/src/cz/robyer/gamework/game/GameHandler.java
import java.util.WeakHashMap;
import cz.robyer.gamework.game.GameEvent.EventType;
import cz.robyer.gamework.utils.Log;
package cz.robyer.gamework.game;
/**
* Handler for broadcasting {@link GameEvent}s.
* @author Robert Pösel
*/
public class GameHandler implements GameEventBroadcaster {
private static final String TAG = GameHandler.class.getSimpleName();
private final WeakHashMap<GameEventListener, Boolean> listeners = new WeakHashMap<GameEventListener, Boolean>();
private final GameService parent;
/**
* Class constructor.
* @param parent GameService which uses this handler.
*/
public GameHandler(GameService parent) {
this.parent = parent;
}
/**
* Add listener.
* @param listener
* @return true if listener was added or false if it already existed
*/
public synchronized boolean addListener(GameEventListener listener) { | Log.d(TAG, "Adding GameEventListener " + listener.toString()); |
Robyer/Gamework | Gamework/src/cz/robyer/gamework/game/GameHandler.java | // Path: Gamework/src/cz/robyer/gamework/game/GameEvent.java
// public enum EventType {
// GAME_START, /** Game start/continue. */
// GAME_PAUSE, /** Event for pausing game service. */
// GAME_WIN, /** Player won the game. */
// GAME_LOSE, /** Player lost the game. */
// GAME_QUIT, /** Event for stop game service. */
// UPDATED_LOCATION, /** Player's location was updated. */
// UPDATED_TIME, /** Game time was updated. */
// UPDATED_MESSAGES, /** Game message was received */
// SCANNED_CODE, /** User scanned some QR code */
// CUSTOM, /** Custom event whose value was defined in scenario */
// }
//
// Path: Gamework/src/cz/robyer/gamework/utils/Log.java
// public class Log {
//
// private static final boolean debug = true;
//
// public static boolean loggingEnabled() {
// return debug;
// }
//
// public static void v(String tag, String msg) {
// if (loggingEnabled())
// android.util.Log.v(tag, msg);
// }
//
// public static void d(String tag, String msg) {
// if (loggingEnabled())
// android.util.Log.d(tag, msg);
// }
//
// public static void i(String tag, String msg) {
// if (loggingEnabled())
// android.util.Log.i(tag, msg);
// }
//
// public static void w(String tag, String msg) {
// android.util.Log.w(tag, msg);
// }
//
// public static void e(String tag, String msg) {
// android.util.Log.e(tag, msg);
// }
//
// public static void e(String tag, String msg, Exception e) {
// android.util.Log.e(tag, msg, e);
// }
//
// public static void println(int severity, String tag, String message) {
// if (loggingEnabled())
// android.util.Log.println(severity, tag, message);
// }
//
// }
| import java.util.WeakHashMap;
import cz.robyer.gamework.game.GameEvent.EventType;
import cz.robyer.gamework.utils.Log; | package cz.robyer.gamework.game;
/**
* Handler for broadcasting {@link GameEvent}s.
* @author Robert Pösel
*/
public class GameHandler implements GameEventBroadcaster {
private static final String TAG = GameHandler.class.getSimpleName();
private final WeakHashMap<GameEventListener, Boolean> listeners = new WeakHashMap<GameEventListener, Boolean>();
private final GameService parent;
/**
* Class constructor.
* @param parent GameService which uses this handler.
*/
public GameHandler(GameService parent) {
this.parent = parent;
}
/**
* Add listener.
* @param listener
* @return true if listener was added or false if it already existed
*/
public synchronized boolean addListener(GameEventListener listener) {
Log.d(TAG, "Adding GameEventListener " + listener.toString());
return (listeners.put(listener, true) == null);
}
/**
* Remove registered listener.
* @param listener to remove
* @return true when listener was removed or false if it did not existed
*/
public synchronized boolean removeListener(GameEventListener listener) {
Log.d(TAG, "Removing GameEventListener " + listener.toString());
return (listeners.remove(listener) != null);
}
/**
* Removes all registered listeners.
*/
public synchronized void clearListeners() {
Log.d(TAG, "Clearing GameEventListeners");
listeners.clear();
}
/**
* Broadcasts {@link GameEvent} to all registered listeners.
*/
@Override
public synchronized void broadcastEvent(GameEvent event) {
int severity = android.util.Log.INFO; | // Path: Gamework/src/cz/robyer/gamework/game/GameEvent.java
// public enum EventType {
// GAME_START, /** Game start/continue. */
// GAME_PAUSE, /** Event for pausing game service. */
// GAME_WIN, /** Player won the game. */
// GAME_LOSE, /** Player lost the game. */
// GAME_QUIT, /** Event for stop game service. */
// UPDATED_LOCATION, /** Player's location was updated. */
// UPDATED_TIME, /** Game time was updated. */
// UPDATED_MESSAGES, /** Game message was received */
// SCANNED_CODE, /** User scanned some QR code */
// CUSTOM, /** Custom event whose value was defined in scenario */
// }
//
// Path: Gamework/src/cz/robyer/gamework/utils/Log.java
// public class Log {
//
// private static final boolean debug = true;
//
// public static boolean loggingEnabled() {
// return debug;
// }
//
// public static void v(String tag, String msg) {
// if (loggingEnabled())
// android.util.Log.v(tag, msg);
// }
//
// public static void d(String tag, String msg) {
// if (loggingEnabled())
// android.util.Log.d(tag, msg);
// }
//
// public static void i(String tag, String msg) {
// if (loggingEnabled())
// android.util.Log.i(tag, msg);
// }
//
// public static void w(String tag, String msg) {
// android.util.Log.w(tag, msg);
// }
//
// public static void e(String tag, String msg) {
// android.util.Log.e(tag, msg);
// }
//
// public static void e(String tag, String msg, Exception e) {
// android.util.Log.e(tag, msg, e);
// }
//
// public static void println(int severity, String tag, String message) {
// if (loggingEnabled())
// android.util.Log.println(severity, tag, message);
// }
//
// }
// Path: Gamework/src/cz/robyer/gamework/game/GameHandler.java
import java.util.WeakHashMap;
import cz.robyer.gamework.game.GameEvent.EventType;
import cz.robyer.gamework.utils.Log;
package cz.robyer.gamework.game;
/**
* Handler for broadcasting {@link GameEvent}s.
* @author Robert Pösel
*/
public class GameHandler implements GameEventBroadcaster {
private static final String TAG = GameHandler.class.getSimpleName();
private final WeakHashMap<GameEventListener, Boolean> listeners = new WeakHashMap<GameEventListener, Boolean>();
private final GameService parent;
/**
* Class constructor.
* @param parent GameService which uses this handler.
*/
public GameHandler(GameService parent) {
this.parent = parent;
}
/**
* Add listener.
* @param listener
* @return true if listener was added or false if it already existed
*/
public synchronized boolean addListener(GameEventListener listener) {
Log.d(TAG, "Adding GameEventListener " + listener.toString());
return (listeners.put(listener, true) == null);
}
/**
* Remove registered listener.
* @param listener to remove
* @return true when listener was removed or false if it did not existed
*/
public synchronized boolean removeListener(GameEventListener listener) {
Log.d(TAG, "Removing GameEventListener " + listener.toString());
return (listeners.remove(listener) != null);
}
/**
* Removes all registered listeners.
*/
public synchronized void clearListeners() {
Log.d(TAG, "Clearing GameEventListeners");
listeners.clear();
}
/**
* Broadcasts {@link GameEvent} to all registered listeners.
*/
@Override
public synchronized void broadcastEvent(GameEvent event) {
int severity = android.util.Log.INFO; | if (event.type == EventType.UPDATED_LOCATION || |
Robyer/Gamework | Gamework/src/cz/robyer/gamework/scenario/area/PointArea.java | // Path: Gamework/src/cz/robyer/gamework/utils/GPoint.java
// public class GPoint {
//
// public final double latitude;
// public final double longitude;
//
// /**
// * @param latitude
// * @param longitude
// */
// public GPoint(double latitude, double longitude) {
// this.latitude = latitude;
// this.longitude = longitude;
// }
//
// /**
// * Slightly modified version of code from http://www.androidsnippets.com/distance-between-two-gps-coordinates-in-meter
// * @return Distance in meters between given coordinates
// */
// public static double distanceBetween(double latFrom, double lonFrom, double latTo, double lonTo) {
// double pk = 180 / Math.PI;
//
// double a1 = latFrom / pk;
// double a2 = lonFrom / pk;
// double b1 = latTo / pk;
// double b2 = lonTo / pk;
//
// double t1 = Math.cos(a1) * Math.cos(a2) * Math.cos(b1) * Math.cos(b2);
// double t2 = Math.cos(a1) * Math.sin(a2) * Math.cos(b1) * Math.sin(b2);
// double t3 = Math.sin(a1) * Math.sin(b1);
// double tt = Math.acos(t1 + t2 + t3);
//
// double ellipsoidRadius = 6378.137 * (1 - 0.0033493 * Math.pow(Math.sin(0.5 * (latFrom + latTo)), 2));
//
// return ellipsoidRadius * tt * 1000;
// }
//
// }
| import cz.robyer.gamework.utils.GPoint; | package cz.robyer.gamework.scenario.area;
/**
* This represents circle game area based on center point and radius.
* @author Robert Pösel
*/
public class PointArea extends Area {
protected static int LEAVE_RADIUS = 3;
| // Path: Gamework/src/cz/robyer/gamework/utils/GPoint.java
// public class GPoint {
//
// public final double latitude;
// public final double longitude;
//
// /**
// * @param latitude
// * @param longitude
// */
// public GPoint(double latitude, double longitude) {
// this.latitude = latitude;
// this.longitude = longitude;
// }
//
// /**
// * Slightly modified version of code from http://www.androidsnippets.com/distance-between-two-gps-coordinates-in-meter
// * @return Distance in meters between given coordinates
// */
// public static double distanceBetween(double latFrom, double lonFrom, double latTo, double lonTo) {
// double pk = 180 / Math.PI;
//
// double a1 = latFrom / pk;
// double a2 = lonFrom / pk;
// double b1 = latTo / pk;
// double b2 = lonTo / pk;
//
// double t1 = Math.cos(a1) * Math.cos(a2) * Math.cos(b1) * Math.cos(b2);
// double t2 = Math.cos(a1) * Math.sin(a2) * Math.cos(b1) * Math.sin(b2);
// double t3 = Math.sin(a1) * Math.sin(b1);
// double tt = Math.acos(t1 + t2 + t3);
//
// double ellipsoidRadius = 6378.137 * (1 - 0.0033493 * Math.pow(Math.sin(0.5 * (latFrom + latTo)), 2));
//
// return ellipsoidRadius * tt * 1000;
// }
//
// }
// Path: Gamework/src/cz/robyer/gamework/scenario/area/PointArea.java
import cz.robyer.gamework.utils.GPoint;
package cz.robyer.gamework.scenario.area;
/**
* This represents circle game area based on center point and radius.
* @author Robert Pösel
*/
public class PointArea extends Area {
protected static int LEAVE_RADIUS = 3;
| protected GPoint point; // center |
Robyer/Gamework | GameworkApp/src/cz/robyer/gamework/app/activity/HelpActivity.java | // Path: GameworkApp/src/cz/robyer/gamework/app/service/JavaScriptHandler.java
// public class JavaScriptHandler {
//
// Activity parent;
//
// public JavaScriptHandler(Activity activity) {
// parent = activity;
// }
//
// @JavascriptInterface
// public void showToast(String text) {
// Toast.makeText(parent, text, Toast.LENGTH_LONG).show();
// }
//
// }
| import android.annotation.SuppressLint;
import android.annotation.TargetApi;
import android.os.Build;
import android.os.Bundle;
import android.support.v4.app.NavUtils;
import android.view.MenuItem;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import cz.robyer.gamework.app.R;
import cz.robyer.gamework.app.service.JavaScriptHandler; | package cz.robyer.gamework.app.activity;
/**
* Represents help with informations of how to use this application.
* @author Robert Pösel
*/
@SuppressLint("SetJavaScriptEnabled")
public class HelpActivity extends BaseActivity {
//private static final String TAG = HelpActivity.class.getSimpleName();
WebView webview;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_help);
webview = (WebView)findViewById(R.id.webview);
webview.getSettings().setJavaScriptEnabled(true); | // Path: GameworkApp/src/cz/robyer/gamework/app/service/JavaScriptHandler.java
// public class JavaScriptHandler {
//
// Activity parent;
//
// public JavaScriptHandler(Activity activity) {
// parent = activity;
// }
//
// @JavascriptInterface
// public void showToast(String text) {
// Toast.makeText(parent, text, Toast.LENGTH_LONG).show();
// }
//
// }
// Path: GameworkApp/src/cz/robyer/gamework/app/activity/HelpActivity.java
import android.annotation.SuppressLint;
import android.annotation.TargetApi;
import android.os.Build;
import android.os.Bundle;
import android.support.v4.app.NavUtils;
import android.view.MenuItem;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import cz.robyer.gamework.app.R;
import cz.robyer.gamework.app.service.JavaScriptHandler;
package cz.robyer.gamework.app.activity;
/**
* Represents help with informations of how to use this application.
* @author Robert Pösel
*/
@SuppressLint("SetJavaScriptEnabled")
public class HelpActivity extends BaseActivity {
//private static final String TAG = HelpActivity.class.getSimpleName();
WebView webview;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_help);
webview = (WebView)findViewById(R.id.webview);
webview.getSettings().setJavaScriptEnabled(true); | webview.addJavascriptInterface(new JavaScriptHandler(this), "Gamework"); |
Robyer/Gamework | GameworkApp/src/cz/robyer/gamework/app/activity/MainActivity.java | // Path: GameworkApp/src/cz/robyer/gamework/app/game/GameService.java
// public class GameService extends cz.robyer.gamework.game.GameService {
//
// /* (non-Javadoc)
// * @see cz.robyer.gamework.game.GameService#getGameNotification()
// */
// @SuppressLint("DefaultLocale")
// @Override
// protected Notification getGameNotification() {
// Intent notificationIntent = new Intent(this, GameMapActivity.class)
// .setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
//
// // location
// Location loc = getLocation();
// String gps = "-";
// if (loc != null)
// gps = String.format("%s, %s", loc.getLatitude(), loc.getLongitude());
//
// // time
// int seconds = (int) (getTime() / 1000);
// int minutes = seconds / 60;
// seconds = seconds % 60;
// String time = String.format("%d:%02d", minutes, seconds);
//
// String summary = null;
// String text = null;
//
// switch (getStatus()) {
// case GAME_LOADING:
// summary = "Loading...";
// break;
// case GAME_LOST:
// summary = "You lost this game!";
// break;
// case GAME_NONE:
// summary = "No game loaded";
// break;
// case GAME_PAUSED:
// summary = "Game is paused";
// break;
// case GAME_RUNNING:
// summary = "Game is running";
// text = String.format("Game time: %s\nGame location: %s", time, gps);
// break;
// case GAME_WAITING:
// summary = "Waiting for start...";
// break;
// case GAME_WON:
// summary = "You won this game!";
// break;
// }
//
// NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(this)
// .setWhen(getStartTime())
// .setSmallIcon(R.drawable.ic_stat_game)
// .setContentIntent(PendingIntent.getActivity(this, 0, notificationIntent, 0))
// .setContentTitle(getScenario().getInfo().title)
// .setContentText(summary);
//
// if (text != null)
// mBuilder.setStyle(new NotificationCompat.BigTextStyle()
// .bigText(text)
// .setSummaryText(summary));
//
// return mBuilder.build();
// }
//
// /* (non-Javadoc)
// * @see cz.robyer.gamework.game.GameService#onGameStart(boolean, android.content.Intent)
// */
// @Override
// protected void onGameStart(boolean starting, Intent intent) {
// if (starting) {
// Intent gameIntent = new Intent(this, GameMapActivity.class);
// gameIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
// startActivity(gameIntent);
// } else {
// Toast.makeText(getApplicationContext(), "Game is already running.", Toast.LENGTH_LONG).show();
// }
// }
//
// /* (non-Javadoc)
// * @see cz.robyer.gamework.game.GameService#onEvent(cz.robyer.gamework.game.GameEvent)
// */
// @Override
// protected void onEvent(GameEvent event) {
//
// switch (event.type) {
// case UPDATED_LOCATION:
// if (getStatus() == GameStatus.GAME_WAITING) {
// gameHandler.broadcastEvent(EventType.GAME_START);
// }
//
// case GAME_QUIT:
// case GAME_START:
// case GAME_PAUSE:
// case GAME_WIN:
// case GAME_LOSE:
// case UPDATED_TIME:
// refreshNotification(false);
// break;
//
// default:
// break;
// }
//
// }
//
// }
| import android.widget.Button;
import cz.robyer.gamework.app.R;
import cz.robyer.gamework.app.game.GameService;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener; | /*package cz.robyer.gamework.app.activity;
import cz.robyer.gamework.app.R;
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}
*/
package cz.robyer.gamework.app.activity;
/**
* This is the main activity of application.
* @author Robert Pösel
*/
public class MainActivity extends BaseActivity {
//private static final String TAG = MainActivity.class.getSimpleName();
private ProgressDialog dialog;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initButtons();
}
@Override
protected void onPause() {
super.onPause();
if (dialog != null)
dialog.dismiss();
}
/**
* Init handlers for main buttons.
*/
private void initButtons() {
((Button)findViewById(R.id.btn_play)).setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
dialog = ProgressDialog.show(MainActivity.this, "", "Loading. Please wait...", true, true);
// Start game service with example.xml | // Path: GameworkApp/src/cz/robyer/gamework/app/game/GameService.java
// public class GameService extends cz.robyer.gamework.game.GameService {
//
// /* (non-Javadoc)
// * @see cz.robyer.gamework.game.GameService#getGameNotification()
// */
// @SuppressLint("DefaultLocale")
// @Override
// protected Notification getGameNotification() {
// Intent notificationIntent = new Intent(this, GameMapActivity.class)
// .setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
//
// // location
// Location loc = getLocation();
// String gps = "-";
// if (loc != null)
// gps = String.format("%s, %s", loc.getLatitude(), loc.getLongitude());
//
// // time
// int seconds = (int) (getTime() / 1000);
// int minutes = seconds / 60;
// seconds = seconds % 60;
// String time = String.format("%d:%02d", minutes, seconds);
//
// String summary = null;
// String text = null;
//
// switch (getStatus()) {
// case GAME_LOADING:
// summary = "Loading...";
// break;
// case GAME_LOST:
// summary = "You lost this game!";
// break;
// case GAME_NONE:
// summary = "No game loaded";
// break;
// case GAME_PAUSED:
// summary = "Game is paused";
// break;
// case GAME_RUNNING:
// summary = "Game is running";
// text = String.format("Game time: %s\nGame location: %s", time, gps);
// break;
// case GAME_WAITING:
// summary = "Waiting for start...";
// break;
// case GAME_WON:
// summary = "You won this game!";
// break;
// }
//
// NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(this)
// .setWhen(getStartTime())
// .setSmallIcon(R.drawable.ic_stat_game)
// .setContentIntent(PendingIntent.getActivity(this, 0, notificationIntent, 0))
// .setContentTitle(getScenario().getInfo().title)
// .setContentText(summary);
//
// if (text != null)
// mBuilder.setStyle(new NotificationCompat.BigTextStyle()
// .bigText(text)
// .setSummaryText(summary));
//
// return mBuilder.build();
// }
//
// /* (non-Javadoc)
// * @see cz.robyer.gamework.game.GameService#onGameStart(boolean, android.content.Intent)
// */
// @Override
// protected void onGameStart(boolean starting, Intent intent) {
// if (starting) {
// Intent gameIntent = new Intent(this, GameMapActivity.class);
// gameIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
// startActivity(gameIntent);
// } else {
// Toast.makeText(getApplicationContext(), "Game is already running.", Toast.LENGTH_LONG).show();
// }
// }
//
// /* (non-Javadoc)
// * @see cz.robyer.gamework.game.GameService#onEvent(cz.robyer.gamework.game.GameEvent)
// */
// @Override
// protected void onEvent(GameEvent event) {
//
// switch (event.type) {
// case UPDATED_LOCATION:
// if (getStatus() == GameStatus.GAME_WAITING) {
// gameHandler.broadcastEvent(EventType.GAME_START);
// }
//
// case GAME_QUIT:
// case GAME_START:
// case GAME_PAUSE:
// case GAME_WIN:
// case GAME_LOSE:
// case UPDATED_TIME:
// refreshNotification(false);
// break;
//
// default:
// break;
// }
//
// }
//
// }
// Path: GameworkApp/src/cz/robyer/gamework/app/activity/MainActivity.java
import android.widget.Button;
import cz.robyer.gamework.app.R;
import cz.robyer.gamework.app.game.GameService;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
/*package cz.robyer.gamework.app.activity;
import cz.robyer.gamework.app.R;
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}
*/
package cz.robyer.gamework.app.activity;
/**
* This is the main activity of application.
* @author Robert Pösel
*/
public class MainActivity extends BaseActivity {
//private static final String TAG = MainActivity.class.getSimpleName();
private ProgressDialog dialog;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initButtons();
}
@Override
protected void onPause() {
super.onPause();
if (dialog != null)
dialog.dismiss();
}
/**
* Init handlers for main buttons.
*/
private void initButtons() {
((Button)findViewById(R.id.btn_play)).setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
dialog = ProgressDialog.show(MainActivity.this, "", "Loading. Please wait...", true, true);
// Start game service with example.xml | Intent intent = new Intent(MainActivity.this, GameService.class); |
ltettoni/logic2j | src/test/java/org/logic2j/core/library/impl/AdHocLibraryForTesting.java | // Path: src/main/java/org/logic2j/core/impl/PrologImplementation.java
// public interface PrologImplementation extends Prolog {
//
// // ---------------------------------------------------------------------------
// // Accessors to the sub-features of the Prolog engine
// // ---------------------------------------------------------------------------
//
// /**
// * @return The implementation for managing libraries.
// */
// LibraryManager getLibraryManager();
//
// /**
// * @return The implementation of inference logic.
// */
// Solver getSolver();
//
// /**
// * @return The implementation for managing operators.
// */
// OperatorManager getOperatorManager();
//
// /**
// * @return Marshalling
// */
// TermMarshaller getTermMarshaller();
//
// TermUnmarshaller getTermUnmarshaller();
//
// void setTermAdapter(TermAdapter termAdapter);
//
// }
| import static org.logic2j.engine.solver.Continuation.CONTINUE;
import java.util.ArrayList;
import java.util.List;
import org.logic2j.core.api.library.annotation.Predicate;
import org.logic2j.core.impl.PrologImplementation;
import org.logic2j.engine.model.Var;
import org.logic2j.engine.solver.Continuation;
import org.logic2j.engine.unify.UnifyContext; | /*
* logic2j - "Bring Logic to your Java" - Copyright (c) 2017 Laurent.Tettoni@gmail.com
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Foobar is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser Public License for more details.
*
* You should have received a copy of the GNU Lesser Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.logic2j.core.library.impl;
/**
* A small ad-hoc implementation of a {@link org.logic2j.core.api.library.PLibrary} just for testing.
*/
public class AdHocLibraryForTesting extends LibraryBase {
static final org.slf4j.Logger logger = org.slf4j.LoggerFactory.getLogger(AdHocLibraryForTesting.class);
| // Path: src/main/java/org/logic2j/core/impl/PrologImplementation.java
// public interface PrologImplementation extends Prolog {
//
// // ---------------------------------------------------------------------------
// // Accessors to the sub-features of the Prolog engine
// // ---------------------------------------------------------------------------
//
// /**
// * @return The implementation for managing libraries.
// */
// LibraryManager getLibraryManager();
//
// /**
// * @return The implementation of inference logic.
// */
// Solver getSolver();
//
// /**
// * @return The implementation for managing operators.
// */
// OperatorManager getOperatorManager();
//
// /**
// * @return Marshalling
// */
// TermMarshaller getTermMarshaller();
//
// TermUnmarshaller getTermUnmarshaller();
//
// void setTermAdapter(TermAdapter termAdapter);
//
// }
// Path: src/test/java/org/logic2j/core/library/impl/AdHocLibraryForTesting.java
import static org.logic2j.engine.solver.Continuation.CONTINUE;
import java.util.ArrayList;
import java.util.List;
import org.logic2j.core.api.library.annotation.Predicate;
import org.logic2j.core.impl.PrologImplementation;
import org.logic2j.engine.model.Var;
import org.logic2j.engine.solver.Continuation;
import org.logic2j.engine.unify.UnifyContext;
/*
* logic2j - "Bring Logic to your Java" - Copyright (c) 2017 Laurent.Tettoni@gmail.com
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Foobar is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser Public License for more details.
*
* You should have received a copy of the GNU Lesser Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.logic2j.core.library.impl;
/**
* A small ad-hoc implementation of a {@link org.logic2j.core.api.library.PLibrary} just for testing.
*/
public class AdHocLibraryForTesting extends LibraryBase {
static final org.slf4j.Logger logger = org.slf4j.LoggerFactory.getLogger(AdHocLibraryForTesting.class);
| public AdHocLibraryForTesting(PrologImplementation theProlog) { |
ltettoni/logic2j | src/main/java/org/logic2j/core/api/Prolog.java | // Path: src/main/java/org/logic2j/core/impl/theory/TheoryManager.java
// public interface TheoryManager extends ClauseProvider {
//
// // ---------------------------------------------------------------------------
// // Load Theories from various sources into a TheoryContent representation
// // ---------------------------------------------------------------------------
//
// /**
// * Load the {@link TheoryContent} from a File defining a theory;
// * this only loads and return the content, use {@link #addTheory(TheoryContent)} to make it
// * available to the {@link org.logic2j.core.impl.PrologImplementation}.
// *
// * @param theFile
// * @return The content of the theory
// * @throws java.io.IOException
// */
// TheoryContent load(File theFile) throws IOException;
//
// /**
// * Load from a URL.
// *
// * @param theTheory
// * @return The content of the theory
// */
// TheoryContent load(URL theTheory);
//
// /**
// * Load from a classloadable resource.
// *
// * @param theClassloadableResourceOrUrl
// * @return The content of the theory
// */
// TheoryContent load(String theClassloadableResourceOrUrl);
//
// /**
// * @return All clause providers, in same order as when registered.
// * TODO The actual ordering of ClauseProviders may not always be required: it is only
// * important when the same predicate is available from several providers (rare). Could we in certain cases use
// * multi-threaded access to all clause providers?
// */
// Iterable<ClauseProvider> getClauseProviders();
//
// boolean hasDataFactProviders();
//
// Iterable<DataFactProvider> getDataFactProviders();
//
// /**
// * @param theNewProvider
// */
// void addClauseProvider(ClauseProvider theNewProvider);
//
// /**
// * @param theNewProvider
// */
// void addDataFactProvider(DataFactProvider theNewProvider);
//
// // ---------------------------------------------------------------------------
// // Alter the current Prolog instance with content from theories
// // ---------------------------------------------------------------------------
//
// /**
// * @param theContent To be merged into this and made available to the {@link org.logic2j.core.impl.PrologImplementation}.
// */
// void addTheory(TheoryContent theContent);
//
// }
| import org.logic2j.core.impl.theory.TheoryManager;
import org.logic2j.engine.model.Struct;
import org.logic2j.engine.model.Term;
import org.logic2j.engine.solver.holder.GoalHolder;
import org.logic2j.engine.solver.holder.SolutionHolder;
import org.logic2j.engine.solver.listener.SolutionListener; | /*
* logic2j - "Bring Logic to your Java" - Copyright (c) 2017 Laurent.Tettoni@gmail.com
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Foobar is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser Public License for more details.
*
* You should have received a copy of the GNU Lesser Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.logic2j.core.api;
/**
* Interface for using Prolog from an application's perspective.
*/
public interface Prolog {
// ---------------------------------------------------------------------------
// Shortcuts or "syntactic sugars" to ease programming.
// The following methods delegate calls to sub-features of the Prolog engine.
// ---------------------------------------------------------------------------
/**
* The top-level method for solving a goal (exposes the high-level {@link SolutionHolder} API,
* internally it uses the low-level {@link SolutionListener}).
* This does NOT YET start solving.
* If you already have a parsed term, use {@link #solve(Object)} instead.
*
* @param theGoal To solve, will be parsed into a Term.
* @return A {@link org.logic2j.engine.solver.holder.SolutionHolder} that will allow the caller code to dereference solution(s) and their bindings (values of variables).
*/
GoalHolder solve(CharSequence theGoal);
/**
* Solves a goal expressed as a {@link Term} (exposes the high-level {@link SolutionHolder} API, internally it uses the low-level
* {@link SolutionListener}).
*
* @param theGoal The {@link Term} to solve, usually a {@link Struct}
* @return A {@link SolutionHolder} that will allow the caller code to dereference solution(s) and their bindings (values of variables).
*/
GoalHolder solve(Object theGoal);
// ---------------------------------------------------------------------------
// Accessors to the sub-features of the Prolog engine
// ---------------------------------------------------------------------------
/**
* The current adapter to convert {@link Term}s to and from Java {@link Object}s.
*
* @return Our {@link TermAdapter}
*/
TermAdapter getTermAdapter();
/**
* The current theory manager, will allow calling code to add clauses, load theories, etc.
*
* @return Our {@link TheoryManager}
*/ | // Path: src/main/java/org/logic2j/core/impl/theory/TheoryManager.java
// public interface TheoryManager extends ClauseProvider {
//
// // ---------------------------------------------------------------------------
// // Load Theories from various sources into a TheoryContent representation
// // ---------------------------------------------------------------------------
//
// /**
// * Load the {@link TheoryContent} from a File defining a theory;
// * this only loads and return the content, use {@link #addTheory(TheoryContent)} to make it
// * available to the {@link org.logic2j.core.impl.PrologImplementation}.
// *
// * @param theFile
// * @return The content of the theory
// * @throws java.io.IOException
// */
// TheoryContent load(File theFile) throws IOException;
//
// /**
// * Load from a URL.
// *
// * @param theTheory
// * @return The content of the theory
// */
// TheoryContent load(URL theTheory);
//
// /**
// * Load from a classloadable resource.
// *
// * @param theClassloadableResourceOrUrl
// * @return The content of the theory
// */
// TheoryContent load(String theClassloadableResourceOrUrl);
//
// /**
// * @return All clause providers, in same order as when registered.
// * TODO The actual ordering of ClauseProviders may not always be required: it is only
// * important when the same predicate is available from several providers (rare). Could we in certain cases use
// * multi-threaded access to all clause providers?
// */
// Iterable<ClauseProvider> getClauseProviders();
//
// boolean hasDataFactProviders();
//
// Iterable<DataFactProvider> getDataFactProviders();
//
// /**
// * @param theNewProvider
// */
// void addClauseProvider(ClauseProvider theNewProvider);
//
// /**
// * @param theNewProvider
// */
// void addDataFactProvider(DataFactProvider theNewProvider);
//
// // ---------------------------------------------------------------------------
// // Alter the current Prolog instance with content from theories
// // ---------------------------------------------------------------------------
//
// /**
// * @param theContent To be merged into this and made available to the {@link org.logic2j.core.impl.PrologImplementation}.
// */
// void addTheory(TheoryContent theContent);
//
// }
// Path: src/main/java/org/logic2j/core/api/Prolog.java
import org.logic2j.core.impl.theory.TheoryManager;
import org.logic2j.engine.model.Struct;
import org.logic2j.engine.model.Term;
import org.logic2j.engine.solver.holder.GoalHolder;
import org.logic2j.engine.solver.holder.SolutionHolder;
import org.logic2j.engine.solver.listener.SolutionListener;
/*
* logic2j - "Bring Logic to your Java" - Copyright (c) 2017 Laurent.Tettoni@gmail.com
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Foobar is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser Public License for more details.
*
* You should have received a copy of the GNU Lesser Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.logic2j.core.api;
/**
* Interface for using Prolog from an application's perspective.
*/
public interface Prolog {
// ---------------------------------------------------------------------------
// Shortcuts or "syntactic sugars" to ease programming.
// The following methods delegate calls to sub-features of the Prolog engine.
// ---------------------------------------------------------------------------
/**
* The top-level method for solving a goal (exposes the high-level {@link SolutionHolder} API,
* internally it uses the low-level {@link SolutionListener}).
* This does NOT YET start solving.
* If you already have a parsed term, use {@link #solve(Object)} instead.
*
* @param theGoal To solve, will be parsed into a Term.
* @return A {@link org.logic2j.engine.solver.holder.SolutionHolder} that will allow the caller code to dereference solution(s) and their bindings (values of variables).
*/
GoalHolder solve(CharSequence theGoal);
/**
* Solves a goal expressed as a {@link Term} (exposes the high-level {@link SolutionHolder} API, internally it uses the low-level
* {@link SolutionListener}).
*
* @param theGoal The {@link Term} to solve, usually a {@link Struct}
* @return A {@link SolutionHolder} that will allow the caller code to dereference solution(s) and their bindings (values of variables).
*/
GoalHolder solve(Object theGoal);
// ---------------------------------------------------------------------------
// Accessors to the sub-features of the Prolog engine
// ---------------------------------------------------------------------------
/**
* The current adapter to convert {@link Term}s to and from Java {@link Object}s.
*
* @return Our {@link TermAdapter}
*/
TermAdapter getTermAdapter();
/**
* The current theory manager, will allow calling code to add clauses, load theories, etc.
*
* @return Our {@link TheoryManager}
*/ | TheoryManager getTheoryManager(); |
ltettoni/logic2j | src/main/java/org/logic2j/contrib/excel/TabularData.java | // Path: src/main/java/org/logic2j/core/api/TermAdapter.java
// public interface TermAdapter {
//
// enum FactoryMode {
// /**
// * Result will always be an atom (a {@link Struct} of 0-arity), will never be a {@link Var}iable.
// * In the case of null, will create an empty-string atom.
// */
// ATOM,
//
// /**
// * Result will be either an atom (a {@link Struct} of 0-arity), an object, but not a {@link Var}iable neither a
// * compound {@link Struct}.
// */
// LITERAL,
//
// /**
// * Result will be any {@link Term} (atom, number, {@link Var}iable), but not a compound {@link Struct}.
// */
// ANY_TERM,
//
// /**
// * Result can be any term plus compound structures.
// */
// COMPOUND
// }
//
//
// /**
// * Describe the form that data structures should take when represented as Prolog compounds (Struct<?>).
// * See TabularData and related classes.
// */
// enum AssertionMode {
// /**
// * Data is asserted as "named triples". For a dataset called myData, assertions will be such as:
// * myData(entityIdentifier, propertyName, propertyValue).
// */
// EAV_NAMED,
// /**
// * Data is asserted as "quads". The predicate is always "eavt(entity, attribute, value, transaction)".
// * The "transaction" identifier is the dataset name. For example:
// * eavt(entityIdentifier, propertyName, propertyValue, myData).
// */
// EAVT,
// /**
// * Data is asserted as full records with one argument per column, such as
// * "myData(valueOfColumn1, valueOfColumn2, valueOfColumn3, ..., valueOfColumnN)."
// * The order of columns obviously matters.
// * If your data is already triples, use this mode.
// * This is the least flexible form since changes to the tabularData (adding or removing or reordering columns) will change the assertions.
// */
// RECORD
// }
//
// /**
// * Convert: From regular Java Object to Prolog internal Term.
// * Convert from virtually any possible instance of singular {@link Object} into to a Prolog term
// * (usually a Struct but any object is valid in logic2j).
// * This is the highest-level factory for terms.
// *
// * @param theObject
// * @param theMode
// * @return A factorized and normalized {@link Term}.
// */
// Object toTerm(Object theObject, FactoryMode theMode);
//
// /**
// * Instantiate a Struct with arguments from virtually any class of {@link Object}
// * This is the highest-level factory for Struct.
// *
// * @param thePredicateName The predicate (functor)
// * @param theMode
// * @param theArguments
// * @return A factorized and normalized {@link Term}.
// */
// Struct<?> toStruct(String thePredicateName, FactoryMode theMode, Object... theArguments);
//
// /**
// * Instantiate a list of Terms from one (possibly large) {@link Object}.
// *
// * @param theObject
// * @return A List of terms.
// */
// List<Object> toTerms(Object theObject, AssertionMode theAssertionMode);
//
// /**
// * Convert: From Prolog internal Term to regular Java Object.
// *
// * @param theTargetClass Either very specific or quite general like Enum, or even Object
// * @return The converted instance
// */
// <T> T fromTerm(Object theTerm, Class<T> theTargetClass);
//
//
// Object getVariable(String theExpression);
//
// TermAdapter setVariable(String theExpression, Object theValue);
// }
//
// Path: src/main/java/org/logic2j/core/impl/PrologImplementation.java
// public interface PrologImplementation extends Prolog {
//
// // ---------------------------------------------------------------------------
// // Accessors to the sub-features of the Prolog engine
// // ---------------------------------------------------------------------------
//
// /**
// * @return The implementation for managing libraries.
// */
// LibraryManager getLibraryManager();
//
// /**
// * @return The implementation of inference logic.
// */
// Solver getSolver();
//
// /**
// * @return The implementation for managing operators.
// */
// OperatorManager getOperatorManager();
//
// /**
// * @return Marshalling
// */
// TermMarshaller getTermMarshaller();
//
// TermUnmarshaller getTermUnmarshaller();
//
// void setTermAdapter(TermAdapter termAdapter);
//
// }
//
// Path: src/main/java/org/logic2j/engine/exception/PrologNonSpecificException.java
// @Deprecated
// public class PrologNonSpecificException extends Logic2jException {
//
// private static final long serialVersionUID = 1;
//
// public PrologNonSpecificException(String theString) {
// super(theString);
// }
//
// public PrologNonSpecificException(String theString, Throwable theRootCause) {
// super(theString, theRootCause);
// }
//
// }
| import java.io.Serializable;
import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
import org.logic2j.core.api.TermAdapter;
import org.logic2j.core.impl.PrologImplementation;
import org.logic2j.engine.exception.PrologNonSpecificException; | private void checkAll() {
checkColumnNames();
squarify();
checkPrimaryKeyColumn();
}
/**
* Make the data square, ie extend or reduce every data row to match the {@link #columnNames} size.
*/
private void squarify() {
final int nbColumns = this.columnNames.length;
for (int i = 0; i < this.data.length; i++) {
final Serializable[] row = this.data[i];
if (nbColumns != row.length) {
this.data[i] = Arrays.copyOf(this.data[i], nbColumns);
}
}
}
private void checkColumnNames() {
final HashSet<Serializable> duplicateKeys = new HashSet<>();
final HashSet<Serializable> existingKeys = new HashSet<>();
for (final String name : this.columnNames) {
if (existingKeys.contains(name)) {
duplicateKeys.add(name);
} else {
existingKeys.add(name);
}
}
if (!duplicateKeys.isEmpty()) { | // Path: src/main/java/org/logic2j/core/api/TermAdapter.java
// public interface TermAdapter {
//
// enum FactoryMode {
// /**
// * Result will always be an atom (a {@link Struct} of 0-arity), will never be a {@link Var}iable.
// * In the case of null, will create an empty-string atom.
// */
// ATOM,
//
// /**
// * Result will be either an atom (a {@link Struct} of 0-arity), an object, but not a {@link Var}iable neither a
// * compound {@link Struct}.
// */
// LITERAL,
//
// /**
// * Result will be any {@link Term} (atom, number, {@link Var}iable), but not a compound {@link Struct}.
// */
// ANY_TERM,
//
// /**
// * Result can be any term plus compound structures.
// */
// COMPOUND
// }
//
//
// /**
// * Describe the form that data structures should take when represented as Prolog compounds (Struct<?>).
// * See TabularData and related classes.
// */
// enum AssertionMode {
// /**
// * Data is asserted as "named triples". For a dataset called myData, assertions will be such as:
// * myData(entityIdentifier, propertyName, propertyValue).
// */
// EAV_NAMED,
// /**
// * Data is asserted as "quads". The predicate is always "eavt(entity, attribute, value, transaction)".
// * The "transaction" identifier is the dataset name. For example:
// * eavt(entityIdentifier, propertyName, propertyValue, myData).
// */
// EAVT,
// /**
// * Data is asserted as full records with one argument per column, such as
// * "myData(valueOfColumn1, valueOfColumn2, valueOfColumn3, ..., valueOfColumnN)."
// * The order of columns obviously matters.
// * If your data is already triples, use this mode.
// * This is the least flexible form since changes to the tabularData (adding or removing or reordering columns) will change the assertions.
// */
// RECORD
// }
//
// /**
// * Convert: From regular Java Object to Prolog internal Term.
// * Convert from virtually any possible instance of singular {@link Object} into to a Prolog term
// * (usually a Struct but any object is valid in logic2j).
// * This is the highest-level factory for terms.
// *
// * @param theObject
// * @param theMode
// * @return A factorized and normalized {@link Term}.
// */
// Object toTerm(Object theObject, FactoryMode theMode);
//
// /**
// * Instantiate a Struct with arguments from virtually any class of {@link Object}
// * This is the highest-level factory for Struct.
// *
// * @param thePredicateName The predicate (functor)
// * @param theMode
// * @param theArguments
// * @return A factorized and normalized {@link Term}.
// */
// Struct<?> toStruct(String thePredicateName, FactoryMode theMode, Object... theArguments);
//
// /**
// * Instantiate a list of Terms from one (possibly large) {@link Object}.
// *
// * @param theObject
// * @return A List of terms.
// */
// List<Object> toTerms(Object theObject, AssertionMode theAssertionMode);
//
// /**
// * Convert: From Prolog internal Term to regular Java Object.
// *
// * @param theTargetClass Either very specific or quite general like Enum, or even Object
// * @return The converted instance
// */
// <T> T fromTerm(Object theTerm, Class<T> theTargetClass);
//
//
// Object getVariable(String theExpression);
//
// TermAdapter setVariable(String theExpression, Object theValue);
// }
//
// Path: src/main/java/org/logic2j/core/impl/PrologImplementation.java
// public interface PrologImplementation extends Prolog {
//
// // ---------------------------------------------------------------------------
// // Accessors to the sub-features of the Prolog engine
// // ---------------------------------------------------------------------------
//
// /**
// * @return The implementation for managing libraries.
// */
// LibraryManager getLibraryManager();
//
// /**
// * @return The implementation of inference logic.
// */
// Solver getSolver();
//
// /**
// * @return The implementation for managing operators.
// */
// OperatorManager getOperatorManager();
//
// /**
// * @return Marshalling
// */
// TermMarshaller getTermMarshaller();
//
// TermUnmarshaller getTermUnmarshaller();
//
// void setTermAdapter(TermAdapter termAdapter);
//
// }
//
// Path: src/main/java/org/logic2j/engine/exception/PrologNonSpecificException.java
// @Deprecated
// public class PrologNonSpecificException extends Logic2jException {
//
// private static final long serialVersionUID = 1;
//
// public PrologNonSpecificException(String theString) {
// super(theString);
// }
//
// public PrologNonSpecificException(String theString, Throwable theRootCause) {
// super(theString, theRootCause);
// }
//
// }
// Path: src/main/java/org/logic2j/contrib/excel/TabularData.java
import java.io.Serializable;
import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
import org.logic2j.core.api.TermAdapter;
import org.logic2j.core.impl.PrologImplementation;
import org.logic2j.engine.exception.PrologNonSpecificException;
private void checkAll() {
checkColumnNames();
squarify();
checkPrimaryKeyColumn();
}
/**
* Make the data square, ie extend or reduce every data row to match the {@link #columnNames} size.
*/
private void squarify() {
final int nbColumns = this.columnNames.length;
for (int i = 0; i < this.data.length; i++) {
final Serializable[] row = this.data[i];
if (nbColumns != row.length) {
this.data[i] = Arrays.copyOf(this.data[i], nbColumns);
}
}
}
private void checkColumnNames() {
final HashSet<Serializable> duplicateKeys = new HashSet<>();
final HashSet<Serializable> existingKeys = new HashSet<>();
for (final String name : this.columnNames) {
if (existingKeys.contains(name)) {
duplicateKeys.add(name);
} else {
existingKeys.add(name);
}
}
if (!duplicateKeys.isEmpty()) { | throw new PrologNonSpecificException("Tabular data " + this.dataSetName + " contains duplicate column names: " + duplicateKeys); |
ltettoni/logic2j | src/main/java/org/logic2j/contrib/excel/TabularData.java | // Path: src/main/java/org/logic2j/core/api/TermAdapter.java
// public interface TermAdapter {
//
// enum FactoryMode {
// /**
// * Result will always be an atom (a {@link Struct} of 0-arity), will never be a {@link Var}iable.
// * In the case of null, will create an empty-string atom.
// */
// ATOM,
//
// /**
// * Result will be either an atom (a {@link Struct} of 0-arity), an object, but not a {@link Var}iable neither a
// * compound {@link Struct}.
// */
// LITERAL,
//
// /**
// * Result will be any {@link Term} (atom, number, {@link Var}iable), but not a compound {@link Struct}.
// */
// ANY_TERM,
//
// /**
// * Result can be any term plus compound structures.
// */
// COMPOUND
// }
//
//
// /**
// * Describe the form that data structures should take when represented as Prolog compounds (Struct<?>).
// * See TabularData and related classes.
// */
// enum AssertionMode {
// /**
// * Data is asserted as "named triples". For a dataset called myData, assertions will be such as:
// * myData(entityIdentifier, propertyName, propertyValue).
// */
// EAV_NAMED,
// /**
// * Data is asserted as "quads". The predicate is always "eavt(entity, attribute, value, transaction)".
// * The "transaction" identifier is the dataset name. For example:
// * eavt(entityIdentifier, propertyName, propertyValue, myData).
// */
// EAVT,
// /**
// * Data is asserted as full records with one argument per column, such as
// * "myData(valueOfColumn1, valueOfColumn2, valueOfColumn3, ..., valueOfColumnN)."
// * The order of columns obviously matters.
// * If your data is already triples, use this mode.
// * This is the least flexible form since changes to the tabularData (adding or removing or reordering columns) will change the assertions.
// */
// RECORD
// }
//
// /**
// * Convert: From regular Java Object to Prolog internal Term.
// * Convert from virtually any possible instance of singular {@link Object} into to a Prolog term
// * (usually a Struct but any object is valid in logic2j).
// * This is the highest-level factory for terms.
// *
// * @param theObject
// * @param theMode
// * @return A factorized and normalized {@link Term}.
// */
// Object toTerm(Object theObject, FactoryMode theMode);
//
// /**
// * Instantiate a Struct with arguments from virtually any class of {@link Object}
// * This is the highest-level factory for Struct.
// *
// * @param thePredicateName The predicate (functor)
// * @param theMode
// * @param theArguments
// * @return A factorized and normalized {@link Term}.
// */
// Struct<?> toStruct(String thePredicateName, FactoryMode theMode, Object... theArguments);
//
// /**
// * Instantiate a list of Terms from one (possibly large) {@link Object}.
// *
// * @param theObject
// * @return A List of terms.
// */
// List<Object> toTerms(Object theObject, AssertionMode theAssertionMode);
//
// /**
// * Convert: From Prolog internal Term to regular Java Object.
// *
// * @param theTargetClass Either very specific or quite general like Enum, or even Object
// * @return The converted instance
// */
// <T> T fromTerm(Object theTerm, Class<T> theTargetClass);
//
//
// Object getVariable(String theExpression);
//
// TermAdapter setVariable(String theExpression, Object theValue);
// }
//
// Path: src/main/java/org/logic2j/core/impl/PrologImplementation.java
// public interface PrologImplementation extends Prolog {
//
// // ---------------------------------------------------------------------------
// // Accessors to the sub-features of the Prolog engine
// // ---------------------------------------------------------------------------
//
// /**
// * @return The implementation for managing libraries.
// */
// LibraryManager getLibraryManager();
//
// /**
// * @return The implementation of inference logic.
// */
// Solver getSolver();
//
// /**
// * @return The implementation for managing operators.
// */
// OperatorManager getOperatorManager();
//
// /**
// * @return Marshalling
// */
// TermMarshaller getTermMarshaller();
//
// TermUnmarshaller getTermUnmarshaller();
//
// void setTermAdapter(TermAdapter termAdapter);
//
// }
//
// Path: src/main/java/org/logic2j/engine/exception/PrologNonSpecificException.java
// @Deprecated
// public class PrologNonSpecificException extends Logic2jException {
//
// private static final long serialVersionUID = 1;
//
// public PrologNonSpecificException(String theString) {
// super(theString);
// }
//
// public PrologNonSpecificException(String theString, Throwable theRootCause) {
// super(theString, theRootCause);
// }
//
// }
| import java.io.Serializable;
import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
import org.logic2j.core.api.TermAdapter;
import org.logic2j.core.impl.PrologImplementation;
import org.logic2j.engine.exception.PrologNonSpecificException; | throw new PrologNonSpecificException(
"Tabular data " + this.dataSetName + " contains duplicate keys in column " + this.primaryKeyColumn + ": " + duplicateKeys);
}
}
// ---------------------------------------------------------------------------
// Methods
// ---------------------------------------------------------------------------
/**
* @return Number of rows (entities) in the data.
*/
public int getNbRows() {
return this.data.length;
}
/**
* @return Number of columns (properties) in the data.
*/
public int getNbColumns() {
return this.columnNames.length;
}
/**
* Helper method to instantiate a {@link TabularDataClauseProvider} from this {@link TabularData} and
* add it to a Prolog implementation.
*
* @param mode
* @param prolog
*/ | // Path: src/main/java/org/logic2j/core/api/TermAdapter.java
// public interface TermAdapter {
//
// enum FactoryMode {
// /**
// * Result will always be an atom (a {@link Struct} of 0-arity), will never be a {@link Var}iable.
// * In the case of null, will create an empty-string atom.
// */
// ATOM,
//
// /**
// * Result will be either an atom (a {@link Struct} of 0-arity), an object, but not a {@link Var}iable neither a
// * compound {@link Struct}.
// */
// LITERAL,
//
// /**
// * Result will be any {@link Term} (atom, number, {@link Var}iable), but not a compound {@link Struct}.
// */
// ANY_TERM,
//
// /**
// * Result can be any term plus compound structures.
// */
// COMPOUND
// }
//
//
// /**
// * Describe the form that data structures should take when represented as Prolog compounds (Struct<?>).
// * See TabularData and related classes.
// */
// enum AssertionMode {
// /**
// * Data is asserted as "named triples". For a dataset called myData, assertions will be such as:
// * myData(entityIdentifier, propertyName, propertyValue).
// */
// EAV_NAMED,
// /**
// * Data is asserted as "quads". The predicate is always "eavt(entity, attribute, value, transaction)".
// * The "transaction" identifier is the dataset name. For example:
// * eavt(entityIdentifier, propertyName, propertyValue, myData).
// */
// EAVT,
// /**
// * Data is asserted as full records with one argument per column, such as
// * "myData(valueOfColumn1, valueOfColumn2, valueOfColumn3, ..., valueOfColumnN)."
// * The order of columns obviously matters.
// * If your data is already triples, use this mode.
// * This is the least flexible form since changes to the tabularData (adding or removing or reordering columns) will change the assertions.
// */
// RECORD
// }
//
// /**
// * Convert: From regular Java Object to Prolog internal Term.
// * Convert from virtually any possible instance of singular {@link Object} into to a Prolog term
// * (usually a Struct but any object is valid in logic2j).
// * This is the highest-level factory for terms.
// *
// * @param theObject
// * @param theMode
// * @return A factorized and normalized {@link Term}.
// */
// Object toTerm(Object theObject, FactoryMode theMode);
//
// /**
// * Instantiate a Struct with arguments from virtually any class of {@link Object}
// * This is the highest-level factory for Struct.
// *
// * @param thePredicateName The predicate (functor)
// * @param theMode
// * @param theArguments
// * @return A factorized and normalized {@link Term}.
// */
// Struct<?> toStruct(String thePredicateName, FactoryMode theMode, Object... theArguments);
//
// /**
// * Instantiate a list of Terms from one (possibly large) {@link Object}.
// *
// * @param theObject
// * @return A List of terms.
// */
// List<Object> toTerms(Object theObject, AssertionMode theAssertionMode);
//
// /**
// * Convert: From Prolog internal Term to regular Java Object.
// *
// * @param theTargetClass Either very specific or quite general like Enum, or even Object
// * @return The converted instance
// */
// <T> T fromTerm(Object theTerm, Class<T> theTargetClass);
//
//
// Object getVariable(String theExpression);
//
// TermAdapter setVariable(String theExpression, Object theValue);
// }
//
// Path: src/main/java/org/logic2j/core/impl/PrologImplementation.java
// public interface PrologImplementation extends Prolog {
//
// // ---------------------------------------------------------------------------
// // Accessors to the sub-features of the Prolog engine
// // ---------------------------------------------------------------------------
//
// /**
// * @return The implementation for managing libraries.
// */
// LibraryManager getLibraryManager();
//
// /**
// * @return The implementation of inference logic.
// */
// Solver getSolver();
//
// /**
// * @return The implementation for managing operators.
// */
// OperatorManager getOperatorManager();
//
// /**
// * @return Marshalling
// */
// TermMarshaller getTermMarshaller();
//
// TermUnmarshaller getTermUnmarshaller();
//
// void setTermAdapter(TermAdapter termAdapter);
//
// }
//
// Path: src/main/java/org/logic2j/engine/exception/PrologNonSpecificException.java
// @Deprecated
// public class PrologNonSpecificException extends Logic2jException {
//
// private static final long serialVersionUID = 1;
//
// public PrologNonSpecificException(String theString) {
// super(theString);
// }
//
// public PrologNonSpecificException(String theString, Throwable theRootCause) {
// super(theString, theRootCause);
// }
//
// }
// Path: src/main/java/org/logic2j/contrib/excel/TabularData.java
import java.io.Serializable;
import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
import org.logic2j.core.api.TermAdapter;
import org.logic2j.core.impl.PrologImplementation;
import org.logic2j.engine.exception.PrologNonSpecificException;
throw new PrologNonSpecificException(
"Tabular data " + this.dataSetName + " contains duplicate keys in column " + this.primaryKeyColumn + ": " + duplicateKeys);
}
}
// ---------------------------------------------------------------------------
// Methods
// ---------------------------------------------------------------------------
/**
* @return Number of rows (entities) in the data.
*/
public int getNbRows() {
return this.data.length;
}
/**
* @return Number of columns (properties) in the data.
*/
public int getNbColumns() {
return this.columnNames.length;
}
/**
* Helper method to instantiate a {@link TabularDataClauseProvider} from this {@link TabularData} and
* add it to a Prolog implementation.
*
* @param mode
* @param prolog
*/ | public void addClauseProviderTo(PrologImplementation prolog, TermAdapter.AssertionMode mode) { |
ltettoni/logic2j | src/main/java/org/logic2j/contrib/excel/TabularData.java | // Path: src/main/java/org/logic2j/core/api/TermAdapter.java
// public interface TermAdapter {
//
// enum FactoryMode {
// /**
// * Result will always be an atom (a {@link Struct} of 0-arity), will never be a {@link Var}iable.
// * In the case of null, will create an empty-string atom.
// */
// ATOM,
//
// /**
// * Result will be either an atom (a {@link Struct} of 0-arity), an object, but not a {@link Var}iable neither a
// * compound {@link Struct}.
// */
// LITERAL,
//
// /**
// * Result will be any {@link Term} (atom, number, {@link Var}iable), but not a compound {@link Struct}.
// */
// ANY_TERM,
//
// /**
// * Result can be any term plus compound structures.
// */
// COMPOUND
// }
//
//
// /**
// * Describe the form that data structures should take when represented as Prolog compounds (Struct<?>).
// * See TabularData and related classes.
// */
// enum AssertionMode {
// /**
// * Data is asserted as "named triples". For a dataset called myData, assertions will be such as:
// * myData(entityIdentifier, propertyName, propertyValue).
// */
// EAV_NAMED,
// /**
// * Data is asserted as "quads". The predicate is always "eavt(entity, attribute, value, transaction)".
// * The "transaction" identifier is the dataset name. For example:
// * eavt(entityIdentifier, propertyName, propertyValue, myData).
// */
// EAVT,
// /**
// * Data is asserted as full records with one argument per column, such as
// * "myData(valueOfColumn1, valueOfColumn2, valueOfColumn3, ..., valueOfColumnN)."
// * The order of columns obviously matters.
// * If your data is already triples, use this mode.
// * This is the least flexible form since changes to the tabularData (adding or removing or reordering columns) will change the assertions.
// */
// RECORD
// }
//
// /**
// * Convert: From regular Java Object to Prolog internal Term.
// * Convert from virtually any possible instance of singular {@link Object} into to a Prolog term
// * (usually a Struct but any object is valid in logic2j).
// * This is the highest-level factory for terms.
// *
// * @param theObject
// * @param theMode
// * @return A factorized and normalized {@link Term}.
// */
// Object toTerm(Object theObject, FactoryMode theMode);
//
// /**
// * Instantiate a Struct with arguments from virtually any class of {@link Object}
// * This is the highest-level factory for Struct.
// *
// * @param thePredicateName The predicate (functor)
// * @param theMode
// * @param theArguments
// * @return A factorized and normalized {@link Term}.
// */
// Struct<?> toStruct(String thePredicateName, FactoryMode theMode, Object... theArguments);
//
// /**
// * Instantiate a list of Terms from one (possibly large) {@link Object}.
// *
// * @param theObject
// * @return A List of terms.
// */
// List<Object> toTerms(Object theObject, AssertionMode theAssertionMode);
//
// /**
// * Convert: From Prolog internal Term to regular Java Object.
// *
// * @param theTargetClass Either very specific or quite general like Enum, or even Object
// * @return The converted instance
// */
// <T> T fromTerm(Object theTerm, Class<T> theTargetClass);
//
//
// Object getVariable(String theExpression);
//
// TermAdapter setVariable(String theExpression, Object theValue);
// }
//
// Path: src/main/java/org/logic2j/core/impl/PrologImplementation.java
// public interface PrologImplementation extends Prolog {
//
// // ---------------------------------------------------------------------------
// // Accessors to the sub-features of the Prolog engine
// // ---------------------------------------------------------------------------
//
// /**
// * @return The implementation for managing libraries.
// */
// LibraryManager getLibraryManager();
//
// /**
// * @return The implementation of inference logic.
// */
// Solver getSolver();
//
// /**
// * @return The implementation for managing operators.
// */
// OperatorManager getOperatorManager();
//
// /**
// * @return Marshalling
// */
// TermMarshaller getTermMarshaller();
//
// TermUnmarshaller getTermUnmarshaller();
//
// void setTermAdapter(TermAdapter termAdapter);
//
// }
//
// Path: src/main/java/org/logic2j/engine/exception/PrologNonSpecificException.java
// @Deprecated
// public class PrologNonSpecificException extends Logic2jException {
//
// private static final long serialVersionUID = 1;
//
// public PrologNonSpecificException(String theString) {
// super(theString);
// }
//
// public PrologNonSpecificException(String theString, Throwable theRootCause) {
// super(theString, theRootCause);
// }
//
// }
| import java.io.Serializable;
import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
import org.logic2j.core.api.TermAdapter;
import org.logic2j.core.impl.PrologImplementation;
import org.logic2j.engine.exception.PrologNonSpecificException; | throw new PrologNonSpecificException(
"Tabular data " + this.dataSetName + " contains duplicate keys in column " + this.primaryKeyColumn + ": " + duplicateKeys);
}
}
// ---------------------------------------------------------------------------
// Methods
// ---------------------------------------------------------------------------
/**
* @return Number of rows (entities) in the data.
*/
public int getNbRows() {
return this.data.length;
}
/**
* @return Number of columns (properties) in the data.
*/
public int getNbColumns() {
return this.columnNames.length;
}
/**
* Helper method to instantiate a {@link TabularDataClauseProvider} from this {@link TabularData} and
* add it to a Prolog implementation.
*
* @param mode
* @param prolog
*/ | // Path: src/main/java/org/logic2j/core/api/TermAdapter.java
// public interface TermAdapter {
//
// enum FactoryMode {
// /**
// * Result will always be an atom (a {@link Struct} of 0-arity), will never be a {@link Var}iable.
// * In the case of null, will create an empty-string atom.
// */
// ATOM,
//
// /**
// * Result will be either an atom (a {@link Struct} of 0-arity), an object, but not a {@link Var}iable neither a
// * compound {@link Struct}.
// */
// LITERAL,
//
// /**
// * Result will be any {@link Term} (atom, number, {@link Var}iable), but not a compound {@link Struct}.
// */
// ANY_TERM,
//
// /**
// * Result can be any term plus compound structures.
// */
// COMPOUND
// }
//
//
// /**
// * Describe the form that data structures should take when represented as Prolog compounds (Struct<?>).
// * See TabularData and related classes.
// */
// enum AssertionMode {
// /**
// * Data is asserted as "named triples". For a dataset called myData, assertions will be such as:
// * myData(entityIdentifier, propertyName, propertyValue).
// */
// EAV_NAMED,
// /**
// * Data is asserted as "quads". The predicate is always "eavt(entity, attribute, value, transaction)".
// * The "transaction" identifier is the dataset name. For example:
// * eavt(entityIdentifier, propertyName, propertyValue, myData).
// */
// EAVT,
// /**
// * Data is asserted as full records with one argument per column, such as
// * "myData(valueOfColumn1, valueOfColumn2, valueOfColumn3, ..., valueOfColumnN)."
// * The order of columns obviously matters.
// * If your data is already triples, use this mode.
// * This is the least flexible form since changes to the tabularData (adding or removing or reordering columns) will change the assertions.
// */
// RECORD
// }
//
// /**
// * Convert: From regular Java Object to Prolog internal Term.
// * Convert from virtually any possible instance of singular {@link Object} into to a Prolog term
// * (usually a Struct but any object is valid in logic2j).
// * This is the highest-level factory for terms.
// *
// * @param theObject
// * @param theMode
// * @return A factorized and normalized {@link Term}.
// */
// Object toTerm(Object theObject, FactoryMode theMode);
//
// /**
// * Instantiate a Struct with arguments from virtually any class of {@link Object}
// * This is the highest-level factory for Struct.
// *
// * @param thePredicateName The predicate (functor)
// * @param theMode
// * @param theArguments
// * @return A factorized and normalized {@link Term}.
// */
// Struct<?> toStruct(String thePredicateName, FactoryMode theMode, Object... theArguments);
//
// /**
// * Instantiate a list of Terms from one (possibly large) {@link Object}.
// *
// * @param theObject
// * @return A List of terms.
// */
// List<Object> toTerms(Object theObject, AssertionMode theAssertionMode);
//
// /**
// * Convert: From Prolog internal Term to regular Java Object.
// *
// * @param theTargetClass Either very specific or quite general like Enum, or even Object
// * @return The converted instance
// */
// <T> T fromTerm(Object theTerm, Class<T> theTargetClass);
//
//
// Object getVariable(String theExpression);
//
// TermAdapter setVariable(String theExpression, Object theValue);
// }
//
// Path: src/main/java/org/logic2j/core/impl/PrologImplementation.java
// public interface PrologImplementation extends Prolog {
//
// // ---------------------------------------------------------------------------
// // Accessors to the sub-features of the Prolog engine
// // ---------------------------------------------------------------------------
//
// /**
// * @return The implementation for managing libraries.
// */
// LibraryManager getLibraryManager();
//
// /**
// * @return The implementation of inference logic.
// */
// Solver getSolver();
//
// /**
// * @return The implementation for managing operators.
// */
// OperatorManager getOperatorManager();
//
// /**
// * @return Marshalling
// */
// TermMarshaller getTermMarshaller();
//
// TermUnmarshaller getTermUnmarshaller();
//
// void setTermAdapter(TermAdapter termAdapter);
//
// }
//
// Path: src/main/java/org/logic2j/engine/exception/PrologNonSpecificException.java
// @Deprecated
// public class PrologNonSpecificException extends Logic2jException {
//
// private static final long serialVersionUID = 1;
//
// public PrologNonSpecificException(String theString) {
// super(theString);
// }
//
// public PrologNonSpecificException(String theString, Throwable theRootCause) {
// super(theString, theRootCause);
// }
//
// }
// Path: src/main/java/org/logic2j/contrib/excel/TabularData.java
import java.io.Serializable;
import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
import org.logic2j.core.api.TermAdapter;
import org.logic2j.core.impl.PrologImplementation;
import org.logic2j.engine.exception.PrologNonSpecificException;
throw new PrologNonSpecificException(
"Tabular data " + this.dataSetName + " contains duplicate keys in column " + this.primaryKeyColumn + ": " + duplicateKeys);
}
}
// ---------------------------------------------------------------------------
// Methods
// ---------------------------------------------------------------------------
/**
* @return Number of rows (entities) in the data.
*/
public int getNbRows() {
return this.data.length;
}
/**
* @return Number of columns (properties) in the data.
*/
public int getNbColumns() {
return this.columnNames.length;
}
/**
* Helper method to instantiate a {@link TabularDataClauseProvider} from this {@link TabularData} and
* add it to a Prolog implementation.
*
* @param mode
* @param prolog
*/ | public void addClauseProviderTo(PrologImplementation prolog, TermAdapter.AssertionMode mode) { |
ltettoni/logic2j | src/main/java/org/logic2j/core/api/library/LibraryContent.java | // Path: src/main/java/org/logic2j/engine/exception/PrologNonSpecificException.java
// @Deprecated
// public class PrologNonSpecificException extends Logic2jException {
//
// private static final long serialVersionUID = 1;
//
// public PrologNonSpecificException(String theString) {
// super(theString);
// }
//
// public PrologNonSpecificException(String theString, Throwable theRootCause) {
// super(theString, theRootCause);
// }
//
// }
| import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
import org.logic2j.engine.exception.PrologNonSpecificException;
import org.logic2j.engine.model.Struct; | /*
* logic2j - "Bring Logic to your Java" - Copyright (c) 2017 Laurent.Tettoni@gmail.com
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Foobar is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser Public License for more details.
*
* You should have received a copy of the GNU Lesser Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.logic2j.core.api.library;
/**
* Describe the content of a {@link PLibrary}: its primitives, directives, functors and predicates.
*/
public class LibraryContent {
private final Map<String, PrimitiveInfo> directiveMap = new HashMap<>();
private final Map<String, PrimitiveInfo> predicateMap = new HashMap<>();
private final Map<String, PrimitiveInfo> functorMap = new HashMap<>();
private final Map<String, PrimitiveInfo> primitiveMap = new HashMap<>();
private List<Function<Struct<?>, Struct<?>>> foPredicateFactories = new ArrayList<>();
public void putDirective(String theKey, PrimitiveInfo theDesc) {
if (this.directiveMap.containsKey(theKey)) { | // Path: src/main/java/org/logic2j/engine/exception/PrologNonSpecificException.java
// @Deprecated
// public class PrologNonSpecificException extends Logic2jException {
//
// private static final long serialVersionUID = 1;
//
// public PrologNonSpecificException(String theString) {
// super(theString);
// }
//
// public PrologNonSpecificException(String theString, Throwable theRootCause) {
// super(theString, theRootCause);
// }
//
// }
// Path: src/main/java/org/logic2j/core/api/library/LibraryContent.java
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
import org.logic2j.engine.exception.PrologNonSpecificException;
import org.logic2j.engine.model.Struct;
/*
* logic2j - "Bring Logic to your Java" - Copyright (c) 2017 Laurent.Tettoni@gmail.com
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Foobar is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser Public License for more details.
*
* You should have received a copy of the GNU Lesser Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.logic2j.core.api.library;
/**
* Describe the content of a {@link PLibrary}: its primitives, directives, functors and predicates.
*/
public class LibraryContent {
private final Map<String, PrimitiveInfo> directiveMap = new HashMap<>();
private final Map<String, PrimitiveInfo> predicateMap = new HashMap<>();
private final Map<String, PrimitiveInfo> functorMap = new HashMap<>();
private final Map<String, PrimitiveInfo> primitiveMap = new HashMap<>();
private List<Function<Struct<?>, Struct<?>>> foPredicateFactories = new ArrayList<>();
public void putDirective(String theKey, PrimitiveInfo theDesc) {
if (this.directiveMap.containsKey(theKey)) { | throw new PrologNonSpecificException("A directive is already defined for key " + theKey + ", cannot override with " + theDesc); |
ltettoni/logic2j | src/main/java/org/logic2j/contrib/excel/ExcelReader.java | // Path: src/main/java/org/logic2j/engine/util/TypeUtils.java
// public abstract class TypeUtils {
//
// /**
// * Dynamic runtime checking of an instance against a class or interface; tolerates null values.
// *
// * @param context Contextual information to be reported, in case of an exception being thrown, to the beginning of the exception's
// * message. Typical use case would be safeCastOrNull("Downloading " + this, eventDate, Date.class).
// * @param instance The instance to check, can be null.
// * @param desiredClassOrInterface The class or interface that we want to make sure the instance is "instanceof".
// * @return The instance checked, or null.
// * @throws ClassCastException If the instance was not of the desiredClassOrInterface, i.e. if desiredClassOrInterface is not assignable
// * to instance.
// */
// @SuppressWarnings("unchecked")
// public static <T> T safeCastOrNull(String context, Object instance, Class<? extends T> desiredClassOrInterface) throws ClassCastException {
// if (instance == null) {
// return null;
// }
// if (!(desiredClassOrInterface.isAssignableFrom(instance.getClass()))) {
// final String message =
// "Could not cast an instance of " + instance.getClass() + " to expected " + desiredClassOrInterface + " [formatted object was " + instance
// + "]";
// throw new PrologNonSpecificException(message);
// }
// return (T) instance;
// }
//
// /**
// * Dynamic runtime checking of an instance against a class or interface; does now allow null values.
// *
// * @param context Contextual information to be reported, in case of an exception being thrown, to the beginning of the exception's
// * message. Typical use case would be safeCastNotNull("Obtaining PMDB API", api, PMDB.class).
// * @param instance The instance to check, must not be null
// * @param desiredClassOrInterface The class or interface that we want to make sure the instance is "instanceof".
// * @return The instance checked, never null.
// * @throws ClassCastException If the instance was not of the desiredClassOrInterface, i.e. if desiredClassOrInterface is not assignable
// * to instance.
// */
// public static <T> T safeCastNotNull(String context, Object instance, Class<? extends T> desiredClassOrInterface) throws ClassCastException {
// if (instance == null) {
// throw new PrologNonSpecificException("null value not allowed, expected an instance of " + desiredClassOrInterface + ", while " + context);
// }
// final String effectiveContext = (context != null) ? context : "casting undescribed object";
// return safeCastOrNull(effectiveContext, instance, desiredClassOrInterface);
// }
//
// }
| import org.logic2j.engine.util.TypeUtils;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Sheet;
import org.logic2j.engine.exception.InvalidTermException; | return null;
}
final int nbCols = row.getPhysicalNumberOfCells();
final ArrayList<T> values = new ArrayList<>();
boolean hasSomeData = false;
for (int c = 0; c < nbCols; c++) {
final HSSFCell cell = row.getCell(c);
Object value = null;
if (cell != null) {
switch (cell.getCellTypeEnum()) {
case FORMULA:
value = cell.getCellFormula();
break;
case NUMERIC:
value = cell.getNumericCellValue();
break;
case STRING:
value = cell.getStringCellValue();
break;
case BLANK:
break;
default:
throw new InvalidTermException(
"Excel cell at row=" + rowNumber + ", column=" + c + " of type " + cell.getCellTypeEnum() + " " + "not handled");
}
}
value = mapCellValue(value);
if (value != null) {
hasSomeData = true;
} | // Path: src/main/java/org/logic2j/engine/util/TypeUtils.java
// public abstract class TypeUtils {
//
// /**
// * Dynamic runtime checking of an instance against a class or interface; tolerates null values.
// *
// * @param context Contextual information to be reported, in case of an exception being thrown, to the beginning of the exception's
// * message. Typical use case would be safeCastOrNull("Downloading " + this, eventDate, Date.class).
// * @param instance The instance to check, can be null.
// * @param desiredClassOrInterface The class or interface that we want to make sure the instance is "instanceof".
// * @return The instance checked, or null.
// * @throws ClassCastException If the instance was not of the desiredClassOrInterface, i.e. if desiredClassOrInterface is not assignable
// * to instance.
// */
// @SuppressWarnings("unchecked")
// public static <T> T safeCastOrNull(String context, Object instance, Class<? extends T> desiredClassOrInterface) throws ClassCastException {
// if (instance == null) {
// return null;
// }
// if (!(desiredClassOrInterface.isAssignableFrom(instance.getClass()))) {
// final String message =
// "Could not cast an instance of " + instance.getClass() + " to expected " + desiredClassOrInterface + " [formatted object was " + instance
// + "]";
// throw new PrologNonSpecificException(message);
// }
// return (T) instance;
// }
//
// /**
// * Dynamic runtime checking of an instance against a class or interface; does now allow null values.
// *
// * @param context Contextual information to be reported, in case of an exception being thrown, to the beginning of the exception's
// * message. Typical use case would be safeCastNotNull("Obtaining PMDB API", api, PMDB.class).
// * @param instance The instance to check, must not be null
// * @param desiredClassOrInterface The class or interface that we want to make sure the instance is "instanceof".
// * @return The instance checked, never null.
// * @throws ClassCastException If the instance was not of the desiredClassOrInterface, i.e. if desiredClassOrInterface is not assignable
// * to instance.
// */
// public static <T> T safeCastNotNull(String context, Object instance, Class<? extends T> desiredClassOrInterface) throws ClassCastException {
// if (instance == null) {
// throw new PrologNonSpecificException("null value not allowed, expected an instance of " + desiredClassOrInterface + ", while " + context);
// }
// final String effectiveContext = (context != null) ? context : "casting undescribed object";
// return safeCastOrNull(effectiveContext, instance, desiredClassOrInterface);
// }
//
// }
// Path: src/main/java/org/logic2j/contrib/excel/ExcelReader.java
import org.logic2j.engine.util.TypeUtils;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Sheet;
import org.logic2j.engine.exception.InvalidTermException;
return null;
}
final int nbCols = row.getPhysicalNumberOfCells();
final ArrayList<T> values = new ArrayList<>();
boolean hasSomeData = false;
for (int c = 0; c < nbCols; c++) {
final HSSFCell cell = row.getCell(c);
Object value = null;
if (cell != null) {
switch (cell.getCellTypeEnum()) {
case FORMULA:
value = cell.getCellFormula();
break;
case NUMERIC:
value = cell.getNumericCellValue();
break;
case STRING:
value = cell.getStringCellValue();
break;
case BLANK:
break;
default:
throw new InvalidTermException(
"Excel cell at row=" + rowNumber + ", column=" + c + " of type " + cell.getCellTypeEnum() + " " + "not handled");
}
}
value = mapCellValue(value);
if (value != null) {
hasSomeData = true;
} | final T cast = TypeUtils.safeCastOrNull("casting Excel cell", value, theTargetClass); |
ltettoni/logic2j | src/test/java/org/logic2j/core/ExtractingSolutionListener.java | // Path: src/main/java/org/logic2j/engine/model/TermApiLocator.java
// public static TermApi termApi() {
// return termApi;
// }
| import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import static org.logic2j.engine.model.TermApiLocator.termApi;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.TreeSet;
import org.logic2j.engine.model.Var;
import org.logic2j.engine.solver.listener.CountingSolutionListener;
import org.logic2j.engine.unify.UnifyContext; | /*
* logic2j - "Bring Logic to your Java" - Copyright (c) 2017 Laurent.Tettoni@gmail.com
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Foobar is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser Public License for more details.
*
* You should have received a copy of the GNU Lesser Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.logic2j.core;
/**
* Used in test cases to extract number of solutions and solutions to a goal.
*/
public class ExtractingSolutionListener extends CountingSolutionListener {
private static final Logger logger = LoggerFactory.getLogger(ExtractingSolutionListener.class);
private final Object goal;
private final Var<?>[] vars;
private final Set<String> varNames;
private final List<Map<String, Object>> solutions;
public ExtractingSolutionListener(Object theGoal) {
this.goal = theGoal; | // Path: src/main/java/org/logic2j/engine/model/TermApiLocator.java
// public static TermApi termApi() {
// return termApi;
// }
// Path: src/test/java/org/logic2j/core/ExtractingSolutionListener.java
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import static org.logic2j.engine.model.TermApiLocator.termApi;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.TreeSet;
import org.logic2j.engine.model.Var;
import org.logic2j.engine.solver.listener.CountingSolutionListener;
import org.logic2j.engine.unify.UnifyContext;
/*
* logic2j - "Bring Logic to your Java" - Copyright (c) 2017 Laurent.Tettoni@gmail.com
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Foobar is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser Public License for more details.
*
* You should have received a copy of the GNU Lesser Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.logic2j.core;
/**
* Used in test cases to extract number of solutions and solutions to a goal.
*/
public class ExtractingSolutionListener extends CountingSolutionListener {
private static final Logger logger = LoggerFactory.getLogger(ExtractingSolutionListener.class);
private final Object goal;
private final Var<?>[] vars;
private final Set<String> varNames;
private final List<Map<String, Object>> solutions;
public ExtractingSolutionListener(Object theGoal) {
this.goal = theGoal; | this.vars = termApi().distinctVars(this.goal); |
ltettoni/logic2j | src/main/java/org/logic2j/core/library/impl/IOLibrary.java | // Path: src/main/java/org/logic2j/core/impl/PrologImplementation.java
// public interface PrologImplementation extends Prolog {
//
// // ---------------------------------------------------------------------------
// // Accessors to the sub-features of the Prolog engine
// // ---------------------------------------------------------------------------
//
// /**
// * @return The implementation for managing libraries.
// */
// LibraryManager getLibraryManager();
//
// /**
// * @return The implementation of inference logic.
// */
// Solver getSolver();
//
// /**
// * @return The implementation for managing operators.
// */
// OperatorManager getOperatorManager();
//
// /**
// * @return Marshalling
// */
// TermMarshaller getTermMarshaller();
//
// TermUnmarshaller getTermUnmarshaller();
//
// void setTermAdapter(TermAdapter termAdapter);
//
// }
| import java.io.PrintStream;
import org.logic2j.core.api.library.annotation.Predicate;
import org.logic2j.core.impl.PrologImplementation;
import org.logic2j.engine.model.Struct;
import org.logic2j.engine.solver.Continuation;
import org.logic2j.engine.unify.UnifyContext; | /*
* logic2j - "Bring Logic to your Java" - Copyright (c) 2017 Laurent.Tettoni@gmail.com
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Foobar is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser Public License for more details.
*
* You should have received a copy of the GNU Lesser Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.logic2j.core.library.impl;
public class IOLibrary extends LibraryBase {
/**
* Name of the logger to which all logging events go.
*/
private static final String LOGIC2J_PROLOG_LOGGER = "org.logic2j.logger";
private static final org.slf4j.Logger logger = org.slf4j.LoggerFactory.getLogger(LOGIC2J_PROLOG_LOGGER);
private static final String QUOTE = "'";
final PrintStream writer = System.out;
| // Path: src/main/java/org/logic2j/core/impl/PrologImplementation.java
// public interface PrologImplementation extends Prolog {
//
// // ---------------------------------------------------------------------------
// // Accessors to the sub-features of the Prolog engine
// // ---------------------------------------------------------------------------
//
// /**
// * @return The implementation for managing libraries.
// */
// LibraryManager getLibraryManager();
//
// /**
// * @return The implementation of inference logic.
// */
// Solver getSolver();
//
// /**
// * @return The implementation for managing operators.
// */
// OperatorManager getOperatorManager();
//
// /**
// * @return Marshalling
// */
// TermMarshaller getTermMarshaller();
//
// TermUnmarshaller getTermUnmarshaller();
//
// void setTermAdapter(TermAdapter termAdapter);
//
// }
// Path: src/main/java/org/logic2j/core/library/impl/IOLibrary.java
import java.io.PrintStream;
import org.logic2j.core.api.library.annotation.Predicate;
import org.logic2j.core.impl.PrologImplementation;
import org.logic2j.engine.model.Struct;
import org.logic2j.engine.solver.Continuation;
import org.logic2j.engine.unify.UnifyContext;
/*
* logic2j - "Bring Logic to your Java" - Copyright (c) 2017 Laurent.Tettoni@gmail.com
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Foobar is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser Public License for more details.
*
* You should have received a copy of the GNU Lesser Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.logic2j.core.library.impl;
public class IOLibrary extends LibraryBase {
/**
* Name of the logger to which all logging events go.
*/
private static final String LOGIC2J_PROLOG_LOGGER = "org.logic2j.logger";
private static final org.slf4j.Logger logger = org.slf4j.LoggerFactory.getLogger(LOGIC2J_PROLOG_LOGGER);
private static final String QUOTE = "'";
final PrintStream writer = System.out;
| public IOLibrary(PrologImplementation theProlog) { |
ltettoni/logic2j | src/test/java/org/logic2j/core/library/impl/UseCaseTest.java | // Path: src/main/java/org/logic2j/contrib/helper/FluentPrologBuilder.java
// public class FluentPrologBuilder implements PrologBuilder {
//
// private boolean noLibraries = false;
//
// private boolean coreLibraries = false;
//
// private Collection<File> theoryFiles = new ArrayList<>();
// private Collection<String> theoryResources = new ArrayList<>();
//
// @Override
// public PrologImplementation build() {
// final PrologReferenceImplementation.InitLevel initLevel;
// if (isNoLibraries()) {
// initLevel = PrologReferenceImplementation.InitLevel.L0_BARE;
// } else if (isCoreLibraries()) {
// initLevel = PrologReferenceImplementation.InitLevel.L1_CORE_LIBRARY;
// } else {
// initLevel = PrologReferenceImplementation.InitLevel.L2_BASE_LIBRARIES;
// }
// final PrologReferenceImplementation prolog = new PrologReferenceImplementation(initLevel);
//
// // Theories from files
// final TheoryManager theoryManager = prolog.getTheoryManager();
// try {
// for (File theory : theoryFiles) {
// final TheoryContent content = theoryManager.load(theory);
// theoryManager.addTheory(content);
// }
// } catch (IOException e) {
// throw new PrologNonSpecificException("Builder could not load theory: " + e);
// }
// // Theories from resources
// for (String resource : theoryResources) {
// final TheoryContent content = theoryManager.load(resource);
// theoryManager.addTheory(content);
// }
//
// return prolog;
// }
//
//
// // ---------------------------------------------------------------------------
// // Fluent API
// // ---------------------------------------------------------------------------
//
// public FluentPrologBuilder withoutLibraries(boolean noLibraries) {
// this.noLibraries = noLibraries;
// return this;
// }
//
// public FluentPrologBuilder withCoreLibraries(boolean coreLibraries) {
// this.coreLibraries = coreLibraries;
// return this;
// }
//
//
// public FluentPrologBuilder withTheory(File... files) {
// for (File file : files) {
// theoryFiles.add(file);
// }
// return this;
// }
//
// public FluentPrologBuilder withTheory(String... resources) {
// for (String resource : resources) {
// theoryResources.add(resource);
// }
// return this;
// }
// // ---------------------------------------------------------------------------
// // Accessors
// // ---------------------------------------------------------------------------
//
// public boolean isNoLibraries() {
// return noLibraries;
// }
//
// public void setNoLibraries(boolean noLibraries) {
// this.noLibraries = noLibraries;
// }
//
// public boolean isCoreLibraries() {
// return coreLibraries;
// }
//
// public void setCoreLibraries(boolean coreLibraries) {
// this.coreLibraries = coreLibraries;
// }
//
// public Collection<File> getTheoryFiles() {
// return theoryFiles;
// }
//
// public void setTheoryFiles(Collection<File> theoryFiles) {
// this.theoryFiles = theoryFiles;
// }
//
// public Collection<String> getTheoryResources() {
// return theoryResources;
// }
//
// public void setTheoryResources(Collection<String> theoryResources) {
// this.theoryResources = theoryResources;
// }
// }
//
// Path: src/main/java/org/logic2j/core/api/Prolog.java
// public interface Prolog {
//
// // ---------------------------------------------------------------------------
// // Shortcuts or "syntactic sugars" to ease programming.
// // The following methods delegate calls to sub-features of the Prolog engine.
// // ---------------------------------------------------------------------------
//
// /**
// * The top-level method for solving a goal (exposes the high-level {@link SolutionHolder} API,
// * internally it uses the low-level {@link SolutionListener}).
// * This does NOT YET start solving.
// * If you already have a parsed term, use {@link #solve(Object)} instead.
// *
// * @param theGoal To solve, will be parsed into a Term.
// * @return A {@link org.logic2j.engine.solver.holder.SolutionHolder} that will allow the caller code to dereference solution(s) and their bindings (values of variables).
// */
// GoalHolder solve(CharSequence theGoal);
//
// /**
// * Solves a goal expressed as a {@link Term} (exposes the high-level {@link SolutionHolder} API, internally it uses the low-level
// * {@link SolutionListener}).
// *
// * @param theGoal The {@link Term} to solve, usually a {@link Struct}
// * @return A {@link SolutionHolder} that will allow the caller code to dereference solution(s) and their bindings (values of variables).
// */
// GoalHolder solve(Object theGoal);
//
// // ---------------------------------------------------------------------------
// // Accessors to the sub-features of the Prolog engine
// // ---------------------------------------------------------------------------
//
// /**
// * The current adapter to convert {@link Term}s to and from Java {@link Object}s.
// *
// * @return Our {@link TermAdapter}
// */
// TermAdapter getTermAdapter();
//
// /**
// * The current theory manager, will allow calling code to add clauses, load theories, etc.
// *
// * @return Our {@link TheoryManager}
// */
// TheoryManager getTheoryManager();
//
//
// }
| import static org.assertj.core.api.Assertions.assertThat;
import java.io.File;
import java.util.List;
import org.junit.Test;
import org.logic2j.contrib.helper.FluentPrologBuilder;
import org.logic2j.core.api.Prolog; | /*
* logic2j - "Bring Logic to your Java" - Copyright (c) 2017 Laurent.Tettoni@gmail.com
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Foobar is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser Public License for more details.
*
* You should have received a copy of the GNU Lesser Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.logic2j.core.library.impl;
/**
* Demonstrate simple use cases for Logic2j.
*/
public class UseCaseTest {
@Test
public void instantiateViaFactory() { | // Path: src/main/java/org/logic2j/contrib/helper/FluentPrologBuilder.java
// public class FluentPrologBuilder implements PrologBuilder {
//
// private boolean noLibraries = false;
//
// private boolean coreLibraries = false;
//
// private Collection<File> theoryFiles = new ArrayList<>();
// private Collection<String> theoryResources = new ArrayList<>();
//
// @Override
// public PrologImplementation build() {
// final PrologReferenceImplementation.InitLevel initLevel;
// if (isNoLibraries()) {
// initLevel = PrologReferenceImplementation.InitLevel.L0_BARE;
// } else if (isCoreLibraries()) {
// initLevel = PrologReferenceImplementation.InitLevel.L1_CORE_LIBRARY;
// } else {
// initLevel = PrologReferenceImplementation.InitLevel.L2_BASE_LIBRARIES;
// }
// final PrologReferenceImplementation prolog = new PrologReferenceImplementation(initLevel);
//
// // Theories from files
// final TheoryManager theoryManager = prolog.getTheoryManager();
// try {
// for (File theory : theoryFiles) {
// final TheoryContent content = theoryManager.load(theory);
// theoryManager.addTheory(content);
// }
// } catch (IOException e) {
// throw new PrologNonSpecificException("Builder could not load theory: " + e);
// }
// // Theories from resources
// for (String resource : theoryResources) {
// final TheoryContent content = theoryManager.load(resource);
// theoryManager.addTheory(content);
// }
//
// return prolog;
// }
//
//
// // ---------------------------------------------------------------------------
// // Fluent API
// // ---------------------------------------------------------------------------
//
// public FluentPrologBuilder withoutLibraries(boolean noLibraries) {
// this.noLibraries = noLibraries;
// return this;
// }
//
// public FluentPrologBuilder withCoreLibraries(boolean coreLibraries) {
// this.coreLibraries = coreLibraries;
// return this;
// }
//
//
// public FluentPrologBuilder withTheory(File... files) {
// for (File file : files) {
// theoryFiles.add(file);
// }
// return this;
// }
//
// public FluentPrologBuilder withTheory(String... resources) {
// for (String resource : resources) {
// theoryResources.add(resource);
// }
// return this;
// }
// // ---------------------------------------------------------------------------
// // Accessors
// // ---------------------------------------------------------------------------
//
// public boolean isNoLibraries() {
// return noLibraries;
// }
//
// public void setNoLibraries(boolean noLibraries) {
// this.noLibraries = noLibraries;
// }
//
// public boolean isCoreLibraries() {
// return coreLibraries;
// }
//
// public void setCoreLibraries(boolean coreLibraries) {
// this.coreLibraries = coreLibraries;
// }
//
// public Collection<File> getTheoryFiles() {
// return theoryFiles;
// }
//
// public void setTheoryFiles(Collection<File> theoryFiles) {
// this.theoryFiles = theoryFiles;
// }
//
// public Collection<String> getTheoryResources() {
// return theoryResources;
// }
//
// public void setTheoryResources(Collection<String> theoryResources) {
// this.theoryResources = theoryResources;
// }
// }
//
// Path: src/main/java/org/logic2j/core/api/Prolog.java
// public interface Prolog {
//
// // ---------------------------------------------------------------------------
// // Shortcuts or "syntactic sugars" to ease programming.
// // The following methods delegate calls to sub-features of the Prolog engine.
// // ---------------------------------------------------------------------------
//
// /**
// * The top-level method for solving a goal (exposes the high-level {@link SolutionHolder} API,
// * internally it uses the low-level {@link SolutionListener}).
// * This does NOT YET start solving.
// * If you already have a parsed term, use {@link #solve(Object)} instead.
// *
// * @param theGoal To solve, will be parsed into a Term.
// * @return A {@link org.logic2j.engine.solver.holder.SolutionHolder} that will allow the caller code to dereference solution(s) and their bindings (values of variables).
// */
// GoalHolder solve(CharSequence theGoal);
//
// /**
// * Solves a goal expressed as a {@link Term} (exposes the high-level {@link SolutionHolder} API, internally it uses the low-level
// * {@link SolutionListener}).
// *
// * @param theGoal The {@link Term} to solve, usually a {@link Struct}
// * @return A {@link SolutionHolder} that will allow the caller code to dereference solution(s) and their bindings (values of variables).
// */
// GoalHolder solve(Object theGoal);
//
// // ---------------------------------------------------------------------------
// // Accessors to the sub-features of the Prolog engine
// // ---------------------------------------------------------------------------
//
// /**
// * The current adapter to convert {@link Term}s to and from Java {@link Object}s.
// *
// * @return Our {@link TermAdapter}
// */
// TermAdapter getTermAdapter();
//
// /**
// * The current theory manager, will allow calling code to add clauses, load theories, etc.
// *
// * @return Our {@link TheoryManager}
// */
// TheoryManager getTheoryManager();
//
//
// }
// Path: src/test/java/org/logic2j/core/library/impl/UseCaseTest.java
import static org.assertj.core.api.Assertions.assertThat;
import java.io.File;
import java.util.List;
import org.junit.Test;
import org.logic2j.contrib.helper.FluentPrologBuilder;
import org.logic2j.core.api.Prolog;
/*
* logic2j - "Bring Logic to your Java" - Copyright (c) 2017 Laurent.Tettoni@gmail.com
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Foobar is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser Public License for more details.
*
* You should have received a copy of the GNU Lesser Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.logic2j.core.library.impl;
/**
* Demonstrate simple use cases for Logic2j.
*/
public class UseCaseTest {
@Test
public void instantiateViaFactory() { | final Prolog prolog = new FluentPrologBuilder().build(); |
ltettoni/logic2j | src/test/java/org/logic2j/core/library/impl/UseCaseTest.java | // Path: src/main/java/org/logic2j/contrib/helper/FluentPrologBuilder.java
// public class FluentPrologBuilder implements PrologBuilder {
//
// private boolean noLibraries = false;
//
// private boolean coreLibraries = false;
//
// private Collection<File> theoryFiles = new ArrayList<>();
// private Collection<String> theoryResources = new ArrayList<>();
//
// @Override
// public PrologImplementation build() {
// final PrologReferenceImplementation.InitLevel initLevel;
// if (isNoLibraries()) {
// initLevel = PrologReferenceImplementation.InitLevel.L0_BARE;
// } else if (isCoreLibraries()) {
// initLevel = PrologReferenceImplementation.InitLevel.L1_CORE_LIBRARY;
// } else {
// initLevel = PrologReferenceImplementation.InitLevel.L2_BASE_LIBRARIES;
// }
// final PrologReferenceImplementation prolog = new PrologReferenceImplementation(initLevel);
//
// // Theories from files
// final TheoryManager theoryManager = prolog.getTheoryManager();
// try {
// for (File theory : theoryFiles) {
// final TheoryContent content = theoryManager.load(theory);
// theoryManager.addTheory(content);
// }
// } catch (IOException e) {
// throw new PrologNonSpecificException("Builder could not load theory: " + e);
// }
// // Theories from resources
// for (String resource : theoryResources) {
// final TheoryContent content = theoryManager.load(resource);
// theoryManager.addTheory(content);
// }
//
// return prolog;
// }
//
//
// // ---------------------------------------------------------------------------
// // Fluent API
// // ---------------------------------------------------------------------------
//
// public FluentPrologBuilder withoutLibraries(boolean noLibraries) {
// this.noLibraries = noLibraries;
// return this;
// }
//
// public FluentPrologBuilder withCoreLibraries(boolean coreLibraries) {
// this.coreLibraries = coreLibraries;
// return this;
// }
//
//
// public FluentPrologBuilder withTheory(File... files) {
// for (File file : files) {
// theoryFiles.add(file);
// }
// return this;
// }
//
// public FluentPrologBuilder withTheory(String... resources) {
// for (String resource : resources) {
// theoryResources.add(resource);
// }
// return this;
// }
// // ---------------------------------------------------------------------------
// // Accessors
// // ---------------------------------------------------------------------------
//
// public boolean isNoLibraries() {
// return noLibraries;
// }
//
// public void setNoLibraries(boolean noLibraries) {
// this.noLibraries = noLibraries;
// }
//
// public boolean isCoreLibraries() {
// return coreLibraries;
// }
//
// public void setCoreLibraries(boolean coreLibraries) {
// this.coreLibraries = coreLibraries;
// }
//
// public Collection<File> getTheoryFiles() {
// return theoryFiles;
// }
//
// public void setTheoryFiles(Collection<File> theoryFiles) {
// this.theoryFiles = theoryFiles;
// }
//
// public Collection<String> getTheoryResources() {
// return theoryResources;
// }
//
// public void setTheoryResources(Collection<String> theoryResources) {
// this.theoryResources = theoryResources;
// }
// }
//
// Path: src/main/java/org/logic2j/core/api/Prolog.java
// public interface Prolog {
//
// // ---------------------------------------------------------------------------
// // Shortcuts or "syntactic sugars" to ease programming.
// // The following methods delegate calls to sub-features of the Prolog engine.
// // ---------------------------------------------------------------------------
//
// /**
// * The top-level method for solving a goal (exposes the high-level {@link SolutionHolder} API,
// * internally it uses the low-level {@link SolutionListener}).
// * This does NOT YET start solving.
// * If you already have a parsed term, use {@link #solve(Object)} instead.
// *
// * @param theGoal To solve, will be parsed into a Term.
// * @return A {@link org.logic2j.engine.solver.holder.SolutionHolder} that will allow the caller code to dereference solution(s) and their bindings (values of variables).
// */
// GoalHolder solve(CharSequence theGoal);
//
// /**
// * Solves a goal expressed as a {@link Term} (exposes the high-level {@link SolutionHolder} API, internally it uses the low-level
// * {@link SolutionListener}).
// *
// * @param theGoal The {@link Term} to solve, usually a {@link Struct}
// * @return A {@link SolutionHolder} that will allow the caller code to dereference solution(s) and their bindings (values of variables).
// */
// GoalHolder solve(Object theGoal);
//
// // ---------------------------------------------------------------------------
// // Accessors to the sub-features of the Prolog engine
// // ---------------------------------------------------------------------------
//
// /**
// * The current adapter to convert {@link Term}s to and from Java {@link Object}s.
// *
// * @return Our {@link TermAdapter}
// */
// TermAdapter getTermAdapter();
//
// /**
// * The current theory manager, will allow calling code to add clauses, load theories, etc.
// *
// * @return Our {@link TheoryManager}
// */
// TheoryManager getTheoryManager();
//
//
// }
| import static org.assertj.core.api.Assertions.assertThat;
import java.io.File;
import java.util.List;
import org.junit.Test;
import org.logic2j.contrib.helper.FluentPrologBuilder;
import org.logic2j.core.api.Prolog; | /*
* logic2j - "Bring Logic to your Java" - Copyright (c) 2017 Laurent.Tettoni@gmail.com
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Foobar is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser Public License for more details.
*
* You should have received a copy of the GNU Lesser Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.logic2j.core.library.impl;
/**
* Demonstrate simple use cases for Logic2j.
*/
public class UseCaseTest {
@Test
public void instantiateViaFactory() { | // Path: src/main/java/org/logic2j/contrib/helper/FluentPrologBuilder.java
// public class FluentPrologBuilder implements PrologBuilder {
//
// private boolean noLibraries = false;
//
// private boolean coreLibraries = false;
//
// private Collection<File> theoryFiles = new ArrayList<>();
// private Collection<String> theoryResources = new ArrayList<>();
//
// @Override
// public PrologImplementation build() {
// final PrologReferenceImplementation.InitLevel initLevel;
// if (isNoLibraries()) {
// initLevel = PrologReferenceImplementation.InitLevel.L0_BARE;
// } else if (isCoreLibraries()) {
// initLevel = PrologReferenceImplementation.InitLevel.L1_CORE_LIBRARY;
// } else {
// initLevel = PrologReferenceImplementation.InitLevel.L2_BASE_LIBRARIES;
// }
// final PrologReferenceImplementation prolog = new PrologReferenceImplementation(initLevel);
//
// // Theories from files
// final TheoryManager theoryManager = prolog.getTheoryManager();
// try {
// for (File theory : theoryFiles) {
// final TheoryContent content = theoryManager.load(theory);
// theoryManager.addTheory(content);
// }
// } catch (IOException e) {
// throw new PrologNonSpecificException("Builder could not load theory: " + e);
// }
// // Theories from resources
// for (String resource : theoryResources) {
// final TheoryContent content = theoryManager.load(resource);
// theoryManager.addTheory(content);
// }
//
// return prolog;
// }
//
//
// // ---------------------------------------------------------------------------
// // Fluent API
// // ---------------------------------------------------------------------------
//
// public FluentPrologBuilder withoutLibraries(boolean noLibraries) {
// this.noLibraries = noLibraries;
// return this;
// }
//
// public FluentPrologBuilder withCoreLibraries(boolean coreLibraries) {
// this.coreLibraries = coreLibraries;
// return this;
// }
//
//
// public FluentPrologBuilder withTheory(File... files) {
// for (File file : files) {
// theoryFiles.add(file);
// }
// return this;
// }
//
// public FluentPrologBuilder withTheory(String... resources) {
// for (String resource : resources) {
// theoryResources.add(resource);
// }
// return this;
// }
// // ---------------------------------------------------------------------------
// // Accessors
// // ---------------------------------------------------------------------------
//
// public boolean isNoLibraries() {
// return noLibraries;
// }
//
// public void setNoLibraries(boolean noLibraries) {
// this.noLibraries = noLibraries;
// }
//
// public boolean isCoreLibraries() {
// return coreLibraries;
// }
//
// public void setCoreLibraries(boolean coreLibraries) {
// this.coreLibraries = coreLibraries;
// }
//
// public Collection<File> getTheoryFiles() {
// return theoryFiles;
// }
//
// public void setTheoryFiles(Collection<File> theoryFiles) {
// this.theoryFiles = theoryFiles;
// }
//
// public Collection<String> getTheoryResources() {
// return theoryResources;
// }
//
// public void setTheoryResources(Collection<String> theoryResources) {
// this.theoryResources = theoryResources;
// }
// }
//
// Path: src/main/java/org/logic2j/core/api/Prolog.java
// public interface Prolog {
//
// // ---------------------------------------------------------------------------
// // Shortcuts or "syntactic sugars" to ease programming.
// // The following methods delegate calls to sub-features of the Prolog engine.
// // ---------------------------------------------------------------------------
//
// /**
// * The top-level method for solving a goal (exposes the high-level {@link SolutionHolder} API,
// * internally it uses the low-level {@link SolutionListener}).
// * This does NOT YET start solving.
// * If you already have a parsed term, use {@link #solve(Object)} instead.
// *
// * @param theGoal To solve, will be parsed into a Term.
// * @return A {@link org.logic2j.engine.solver.holder.SolutionHolder} that will allow the caller code to dereference solution(s) and their bindings (values of variables).
// */
// GoalHolder solve(CharSequence theGoal);
//
// /**
// * Solves a goal expressed as a {@link Term} (exposes the high-level {@link SolutionHolder} API, internally it uses the low-level
// * {@link SolutionListener}).
// *
// * @param theGoal The {@link Term} to solve, usually a {@link Struct}
// * @return A {@link SolutionHolder} that will allow the caller code to dereference solution(s) and their bindings (values of variables).
// */
// GoalHolder solve(Object theGoal);
//
// // ---------------------------------------------------------------------------
// // Accessors to the sub-features of the Prolog engine
// // ---------------------------------------------------------------------------
//
// /**
// * The current adapter to convert {@link Term}s to and from Java {@link Object}s.
// *
// * @return Our {@link TermAdapter}
// */
// TermAdapter getTermAdapter();
//
// /**
// * The current theory manager, will allow calling code to add clauses, load theories, etc.
// *
// * @return Our {@link TheoryManager}
// */
// TheoryManager getTheoryManager();
//
//
// }
// Path: src/test/java/org/logic2j/core/library/impl/UseCaseTest.java
import static org.assertj.core.api.Assertions.assertThat;
import java.io.File;
import java.util.List;
import org.junit.Test;
import org.logic2j.contrib.helper.FluentPrologBuilder;
import org.logic2j.core.api.Prolog;
/*
* logic2j - "Bring Logic to your Java" - Copyright (c) 2017 Laurent.Tettoni@gmail.com
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Foobar is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser Public License for more details.
*
* You should have received a copy of the GNU Lesser Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.logic2j.core.library.impl;
/**
* Demonstrate simple use cases for Logic2j.
*/
public class UseCaseTest {
@Test
public void instantiateViaFactory() { | final Prolog prolog = new FluentPrologBuilder().build(); |
ltettoni/logic2j | src/test/java/org/logic2j/core/ParsingAndFormattingTest.java | // Path: src/main/java/org/logic2j/core/api/model/Operator.java
// public final class Operator implements Serializable {
// private static final long serialVersionUID = 1L;
//
// // TODO Probably this should become an enum
// public static final String FX = "fx"; // prefix non-associative - (i.e. --5 not possible)
// public static final String FY = "fy"; // prefix associative
// public static final String XF = "xf"; // postfix non-associative
// public static final String XFX = "xfx"; // infix non-associative =, is, < (i.e. no nesting)
// public static final String XFY = "xfy"; // infix right-associative , (for subgoals)
// public static final String YF = "yf"; // postfix associative
// public static final String YFX = "yfx"; // infix left-associative +, -, *
// public static final String YFY = "yfy"; // makes no sense, structuring would be impossible
//
// /**
// * highest operator precedence
// */
// public static final int OP_HIGHEST = 1200;
// /**
// * lowest operator precedence
// */
// public static final int OP_LOWEST = 1;
//
// /**
// * operator text representation
// */
// private final String text;
//
// /**
// * precedence
// */
// private final int precedence;
//
// /**
// * xf, yf, fx, fy, xfx, xfy, yfx, (yfy)
// */
// private final String associativity;
//
// public Operator(String theText, String theAssociativity, int thePrecedence) {
// this.text = theText;
// this.associativity = theAssociativity;
// this.precedence = thePrecedence;
// }
//
// // ---------------------------------------------------------------------------
// // Getters
// // ---------------------------------------------------------------------------
//
//
// public String getText() {
// return text;
// }
//
// public int getPrecedence() {
// return precedence;
// }
//
// public String getAssociativity() {
// return associativity;
// }
// }
//
// Path: src/main/java/org/logic2j/core/impl/PrologReferenceImplementation.java
// public enum InitLevel {
// /**
// * A completely bare prolog engine, not functional for running programs (misses core predicates such as true/1, fail/1, !/1 (cut),
// * =/2, call/1, not/1, etc. Yet unification and inference of user predicates will work. No libraries loaded at all.
// */
// L0_BARE,
// /**
// * This is the default initialization level, it loads the {@link org.logic2j.core.library.impl.CoreLibrary},
// * containing (among others), core predicates such as
// * true/1, fail/1, !/1 (cut), =/2, call/1, not/1, findall/3, etc.
// */
// L1_CORE_LIBRARY,
// /**
// * Higher level libraries loaded, such as {@link org.logic2j.core.library.impl.IOLibrary}.
// */
// L2_BASE_LIBRARIES,
// }
| import static org.assertj.core.api.Assertions.assertThat;
import org.junit.Test;
import org.logic2j.core.api.model.Operator;
import org.logic2j.core.impl.PrologReferenceImplementation.InitLevel; | /*
* logic2j - "Bring Logic to your Java" - Copyright (c) 2017 Laurent.Tettoni@gmail.com
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Foobar is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser Public License for more details.
*
* You should have received a copy of the GNU Lesser Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.logic2j.core;
/**
* Test parsing and formatting.
*/
public class ParsingAndFormattingTest extends PrologTestBase {
private static final org.slf4j.Logger logger = org.slf4j.LoggerFactory.getLogger(ParsingAndFormattingTest.class);
/**
* No need for special init for only testing parsing and formatting.
*/
@Override | // Path: src/main/java/org/logic2j/core/api/model/Operator.java
// public final class Operator implements Serializable {
// private static final long serialVersionUID = 1L;
//
// // TODO Probably this should become an enum
// public static final String FX = "fx"; // prefix non-associative - (i.e. --5 not possible)
// public static final String FY = "fy"; // prefix associative
// public static final String XF = "xf"; // postfix non-associative
// public static final String XFX = "xfx"; // infix non-associative =, is, < (i.e. no nesting)
// public static final String XFY = "xfy"; // infix right-associative , (for subgoals)
// public static final String YF = "yf"; // postfix associative
// public static final String YFX = "yfx"; // infix left-associative +, -, *
// public static final String YFY = "yfy"; // makes no sense, structuring would be impossible
//
// /**
// * highest operator precedence
// */
// public static final int OP_HIGHEST = 1200;
// /**
// * lowest operator precedence
// */
// public static final int OP_LOWEST = 1;
//
// /**
// * operator text representation
// */
// private final String text;
//
// /**
// * precedence
// */
// private final int precedence;
//
// /**
// * xf, yf, fx, fy, xfx, xfy, yfx, (yfy)
// */
// private final String associativity;
//
// public Operator(String theText, String theAssociativity, int thePrecedence) {
// this.text = theText;
// this.associativity = theAssociativity;
// this.precedence = thePrecedence;
// }
//
// // ---------------------------------------------------------------------------
// // Getters
// // ---------------------------------------------------------------------------
//
//
// public String getText() {
// return text;
// }
//
// public int getPrecedence() {
// return precedence;
// }
//
// public String getAssociativity() {
// return associativity;
// }
// }
//
// Path: src/main/java/org/logic2j/core/impl/PrologReferenceImplementation.java
// public enum InitLevel {
// /**
// * A completely bare prolog engine, not functional for running programs (misses core predicates such as true/1, fail/1, !/1 (cut),
// * =/2, call/1, not/1, etc. Yet unification and inference of user predicates will work. No libraries loaded at all.
// */
// L0_BARE,
// /**
// * This is the default initialization level, it loads the {@link org.logic2j.core.library.impl.CoreLibrary},
// * containing (among others), core predicates such as
// * true/1, fail/1, !/1 (cut), =/2, call/1, not/1, findall/3, etc.
// */
// L1_CORE_LIBRARY,
// /**
// * Higher level libraries loaded, such as {@link org.logic2j.core.library.impl.IOLibrary}.
// */
// L2_BASE_LIBRARIES,
// }
// Path: src/test/java/org/logic2j/core/ParsingAndFormattingTest.java
import static org.assertj.core.api.Assertions.assertThat;
import org.junit.Test;
import org.logic2j.core.api.model.Operator;
import org.logic2j.core.impl.PrologReferenceImplementation.InitLevel;
/*
* logic2j - "Bring Logic to your Java" - Copyright (c) 2017 Laurent.Tettoni@gmail.com
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Foobar is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser Public License for more details.
*
* You should have received a copy of the GNU Lesser Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.logic2j.core;
/**
* Test parsing and formatting.
*/
public class ParsingAndFormattingTest extends PrologTestBase {
private static final org.slf4j.Logger logger = org.slf4j.LoggerFactory.getLogger(ParsingAndFormattingTest.class);
/**
* No need for special init for only testing parsing and formatting.
*/
@Override | protected InitLevel initLevel() { |
ltettoni/logic2j | src/test/java/org/logic2j/core/ParsingAndFormattingTest.java | // Path: src/main/java/org/logic2j/core/api/model/Operator.java
// public final class Operator implements Serializable {
// private static final long serialVersionUID = 1L;
//
// // TODO Probably this should become an enum
// public static final String FX = "fx"; // prefix non-associative - (i.e. --5 not possible)
// public static final String FY = "fy"; // prefix associative
// public static final String XF = "xf"; // postfix non-associative
// public static final String XFX = "xfx"; // infix non-associative =, is, < (i.e. no nesting)
// public static final String XFY = "xfy"; // infix right-associative , (for subgoals)
// public static final String YF = "yf"; // postfix associative
// public static final String YFX = "yfx"; // infix left-associative +, -, *
// public static final String YFY = "yfy"; // makes no sense, structuring would be impossible
//
// /**
// * highest operator precedence
// */
// public static final int OP_HIGHEST = 1200;
// /**
// * lowest operator precedence
// */
// public static final int OP_LOWEST = 1;
//
// /**
// * operator text representation
// */
// private final String text;
//
// /**
// * precedence
// */
// private final int precedence;
//
// /**
// * xf, yf, fx, fy, xfx, xfy, yfx, (yfy)
// */
// private final String associativity;
//
// public Operator(String theText, String theAssociativity, int thePrecedence) {
// this.text = theText;
// this.associativity = theAssociativity;
// this.precedence = thePrecedence;
// }
//
// // ---------------------------------------------------------------------------
// // Getters
// // ---------------------------------------------------------------------------
//
//
// public String getText() {
// return text;
// }
//
// public int getPrecedence() {
// return precedence;
// }
//
// public String getAssociativity() {
// return associativity;
// }
// }
//
// Path: src/main/java/org/logic2j/core/impl/PrologReferenceImplementation.java
// public enum InitLevel {
// /**
// * A completely bare prolog engine, not functional for running programs (misses core predicates such as true/1, fail/1, !/1 (cut),
// * =/2, call/1, not/1, etc. Yet unification and inference of user predicates will work. No libraries loaded at all.
// */
// L0_BARE,
// /**
// * This is the default initialization level, it loads the {@link org.logic2j.core.library.impl.CoreLibrary},
// * containing (among others), core predicates such as
// * true/1, fail/1, !/1 (cut), =/2, call/1, not/1, findall/3, etc.
// */
// L1_CORE_LIBRARY,
// /**
// * Higher level libraries loaded, such as {@link org.logic2j.core.library.impl.IOLibrary}.
// */
// L2_BASE_LIBRARIES,
// }
| import static org.assertj.core.api.Assertions.assertThat;
import org.junit.Test;
import org.logic2j.core.api.model.Operator;
import org.logic2j.core.impl.PrologReferenceImplementation.InitLevel; | /*
* logic2j - "Bring Logic to your Java" - Copyright (c) 2017 Laurent.Tettoni@gmail.com
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Foobar is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser Public License for more details.
*
* You should have received a copy of the GNU Lesser Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.logic2j.core;
/**
* Test parsing and formatting.
*/
public class ParsingAndFormattingTest extends PrologTestBase {
private static final org.slf4j.Logger logger = org.slf4j.LoggerFactory.getLogger(ParsingAndFormattingTest.class);
/**
* No need for special init for only testing parsing and formatting.
*/
@Override
protected InitLevel initLevel() {
return InitLevel.L0_BARE;
}
@Test
public void parsing() {
assertThat(marshall(unmarshall("p(X,Y) :- a;b,c,d"))).isEqualTo("p(X, Y) :- a ; b , c , d");
assertThat(marshall(unmarshall("[1,2,3]"))).isEqualTo("[1, 2, 3]");
}
@Test
public void parseNarityOperator() { | // Path: src/main/java/org/logic2j/core/api/model/Operator.java
// public final class Operator implements Serializable {
// private static final long serialVersionUID = 1L;
//
// // TODO Probably this should become an enum
// public static final String FX = "fx"; // prefix non-associative - (i.e. --5 not possible)
// public static final String FY = "fy"; // prefix associative
// public static final String XF = "xf"; // postfix non-associative
// public static final String XFX = "xfx"; // infix non-associative =, is, < (i.e. no nesting)
// public static final String XFY = "xfy"; // infix right-associative , (for subgoals)
// public static final String YF = "yf"; // postfix associative
// public static final String YFX = "yfx"; // infix left-associative +, -, *
// public static final String YFY = "yfy"; // makes no sense, structuring would be impossible
//
// /**
// * highest operator precedence
// */
// public static final int OP_HIGHEST = 1200;
// /**
// * lowest operator precedence
// */
// public static final int OP_LOWEST = 1;
//
// /**
// * operator text representation
// */
// private final String text;
//
// /**
// * precedence
// */
// private final int precedence;
//
// /**
// * xf, yf, fx, fy, xfx, xfy, yfx, (yfy)
// */
// private final String associativity;
//
// public Operator(String theText, String theAssociativity, int thePrecedence) {
// this.text = theText;
// this.associativity = theAssociativity;
// this.precedence = thePrecedence;
// }
//
// // ---------------------------------------------------------------------------
// // Getters
// // ---------------------------------------------------------------------------
//
//
// public String getText() {
// return text;
// }
//
// public int getPrecedence() {
// return precedence;
// }
//
// public String getAssociativity() {
// return associativity;
// }
// }
//
// Path: src/main/java/org/logic2j/core/impl/PrologReferenceImplementation.java
// public enum InitLevel {
// /**
// * A completely bare prolog engine, not functional for running programs (misses core predicates such as true/1, fail/1, !/1 (cut),
// * =/2, call/1, not/1, etc. Yet unification and inference of user predicates will work. No libraries loaded at all.
// */
// L0_BARE,
// /**
// * This is the default initialization level, it loads the {@link org.logic2j.core.library.impl.CoreLibrary},
// * containing (among others), core predicates such as
// * true/1, fail/1, !/1 (cut), =/2, call/1, not/1, findall/3, etc.
// */
// L1_CORE_LIBRARY,
// /**
// * Higher level libraries loaded, such as {@link org.logic2j.core.library.impl.IOLibrary}.
// */
// L2_BASE_LIBRARIES,
// }
// Path: src/test/java/org/logic2j/core/ParsingAndFormattingTest.java
import static org.assertj.core.api.Assertions.assertThat;
import org.junit.Test;
import org.logic2j.core.api.model.Operator;
import org.logic2j.core.impl.PrologReferenceImplementation.InitLevel;
/*
* logic2j - "Bring Logic to your Java" - Copyright (c) 2017 Laurent.Tettoni@gmail.com
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Foobar is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser Public License for more details.
*
* You should have received a copy of the GNU Lesser Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.logic2j.core;
/**
* Test parsing and formatting.
*/
public class ParsingAndFormattingTest extends PrologTestBase {
private static final org.slf4j.Logger logger = org.slf4j.LoggerFactory.getLogger(ParsingAndFormattingTest.class);
/**
* No need for special init for only testing parsing and formatting.
*/
@Override
protected InitLevel initLevel() {
return InitLevel.L0_BARE;
}
@Test
public void parsing() {
assertThat(marshall(unmarshall("p(X,Y) :- a;b,c,d"))).isEqualTo("p(X, Y) :- a ; b , c , d");
assertThat(marshall(unmarshall("[1,2,3]"))).isEqualTo("[1, 2, 3]");
}
@Test
public void parseNarityOperator() { | this.prolog.getOperatorManager().addOperator("oo", Operator.YFY, 1020); |
ltettoni/logic2j | src/test/java/org/logic2j/core/impl/DefaultTermUnmarshallerTest.java | // Path: src/test/java/org/logic2j/core/impl/DefaultTermMarshallerTest.java
// static final DefaultTermMarshaller MARSHALLER = new DefaultTermMarshaller();
| import static org.assertj.core.api.Assertions.assertThat;
import static org.logic2j.core.impl.DefaultTermMarshallerTest.MARSHALLER;
import org.junit.Test;
import org.logic2j.engine.exception.InvalidTermException;
import org.logic2j.engine.model.Struct;
import org.logic2j.engine.model.Var;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory; | /*
* logic2j - "Bring Logic to your Java" - Copyright (c) 2017 Laurent.Tettoni@gmail.com
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Foobar is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser Public License for more details.
*
* You should have received a copy of the GNU Lesser Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.logic2j.core.impl;
/**
* Test both the DefaultTermUnmarshaller and DefaultTermMarshaller
*/
public class DefaultTermUnmarshallerTest {
private static final Logger logger = LoggerFactory.getLogger(DefaultTermUnmarshallerTest.class);
static final DefaultTermUnmarshaller UNMARSHALLER = new DefaultTermUnmarshaller();
@Test
public void numbers() {
assertThat(UNMARSHALLER.unmarshall("2323")).isEqualTo(2323);
assertThat(UNMARSHALLER.unmarshall("3.14")).isEqualTo(3.14);
assertThat(UNMARSHALLER.unmarshall("2323L")).isEqualTo(2323L);
assertThat(UNMARSHALLER.unmarshall("3.14f")).isEqualTo(3.14f);
}
@Test
public void basicTerms() {
assertThat(UNMARSHALLER.unmarshall("a")).isEqualTo("a");
assertThat(UNMARSHALLER.unmarshall("X") instanceof Var<?>).isTrue();
assertThat(UNMARSHALLER.unmarshall("_")).isEqualTo(Var.anon());
}
@Test
public void struct() { | // Path: src/test/java/org/logic2j/core/impl/DefaultTermMarshallerTest.java
// static final DefaultTermMarshaller MARSHALLER = new DefaultTermMarshaller();
// Path: src/test/java/org/logic2j/core/impl/DefaultTermUnmarshallerTest.java
import static org.assertj.core.api.Assertions.assertThat;
import static org.logic2j.core.impl.DefaultTermMarshallerTest.MARSHALLER;
import org.junit.Test;
import org.logic2j.engine.exception.InvalidTermException;
import org.logic2j.engine.model.Struct;
import org.logic2j.engine.model.Var;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/*
* logic2j - "Bring Logic to your Java" - Copyright (c) 2017 Laurent.Tettoni@gmail.com
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Foobar is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser Public License for more details.
*
* You should have received a copy of the GNU Lesser Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.logic2j.core.impl;
/**
* Test both the DefaultTermUnmarshaller and DefaultTermMarshaller
*/
public class DefaultTermUnmarshallerTest {
private static final Logger logger = LoggerFactory.getLogger(DefaultTermUnmarshallerTest.class);
static final DefaultTermUnmarshaller UNMARSHALLER = new DefaultTermUnmarshaller();
@Test
public void numbers() {
assertThat(UNMARSHALLER.unmarshall("2323")).isEqualTo(2323);
assertThat(UNMARSHALLER.unmarshall("3.14")).isEqualTo(3.14);
assertThat(UNMARSHALLER.unmarshall("2323L")).isEqualTo(2323L);
assertThat(UNMARSHALLER.unmarshall("3.14f")).isEqualTo(3.14f);
}
@Test
public void basicTerms() {
assertThat(UNMARSHALLER.unmarshall("a")).isEqualTo("a");
assertThat(UNMARSHALLER.unmarshall("X") instanceof Var<?>).isTrue();
assertThat(UNMARSHALLER.unmarshall("_")).isEqualTo(Var.anon());
}
@Test
public void struct() { | assertThat(MARSHALLER.marshall(UNMARSHALLER.unmarshall("f(a)"))).isEqualTo("f(a)"); |
ltettoni/logic2j | src/main/java/org/logic2j/engine/model/PrologLists.java | // Path: src/main/java/org/logic2j/engine/model/TermApiLocator.java
// public static TermApi termApi() {
// return termApi;
// }
//
// Path: src/main/java/org/logic2j/engine/util/TypeUtils.java
// public abstract class TypeUtils {
//
// /**
// * Dynamic runtime checking of an instance against a class or interface; tolerates null values.
// *
// * @param context Contextual information to be reported, in case of an exception being thrown, to the beginning of the exception's
// * message. Typical use case would be safeCastOrNull("Downloading " + this, eventDate, Date.class).
// * @param instance The instance to check, can be null.
// * @param desiredClassOrInterface The class or interface that we want to make sure the instance is "instanceof".
// * @return The instance checked, or null.
// * @throws ClassCastException If the instance was not of the desiredClassOrInterface, i.e. if desiredClassOrInterface is not assignable
// * to instance.
// */
// @SuppressWarnings("unchecked")
// public static <T> T safeCastOrNull(String context, Object instance, Class<? extends T> desiredClassOrInterface) throws ClassCastException {
// if (instance == null) {
// return null;
// }
// if (!(desiredClassOrInterface.isAssignableFrom(instance.getClass()))) {
// final String message =
// "Could not cast an instance of " + instance.getClass() + " to expected " + desiredClassOrInterface + " [formatted object was " + instance
// + "]";
// throw new PrologNonSpecificException(message);
// }
// return (T) instance;
// }
//
// /**
// * Dynamic runtime checking of an instance against a class or interface; does now allow null values.
// *
// * @param context Contextual information to be reported, in case of an exception being thrown, to the beginning of the exception's
// * message. Typical use case would be safeCastNotNull("Obtaining PMDB API", api, PMDB.class).
// * @param instance The instance to check, must not be null
// * @param desiredClassOrInterface The class or interface that we want to make sure the instance is "instanceof".
// * @return The instance checked, never null.
// * @throws ClassCastException If the instance was not of the desiredClassOrInterface, i.e. if desiredClassOrInterface is not assignable
// * to instance.
// */
// public static <T> T safeCastNotNull(String context, Object instance, Class<? extends T> desiredClassOrInterface) throws ClassCastException {
// if (instance == null) {
// throw new PrologNonSpecificException("null value not allowed, expected an instance of " + desiredClassOrInterface + ", while " + context);
// }
// final String effectiveContext = (context != null) ? context : "casting undescribed object";
// return safeCastOrNull(effectiveContext, instance, desiredClassOrInterface);
// }
//
// }
| import static org.logic2j.engine.model.TermApiLocator.termApi;
import java.util.ArrayList;
import java.util.Collection;
import org.logic2j.engine.exception.InvalidTermException;
import org.logic2j.engine.util.TypeUtils; | }
/**
* Gets the number of elements of this structure, which is supposed to be a list.
*
* @param prologList
* @throws InvalidTermException if this is not a prolog list.
*/
public static int listSize(Struct<?> prologList) {
requireList(prologList);
Struct<?> running = prologList;
int count = 0;
while (!isEmptyList(running)) {
count++;
running = (Struct<?>) running.getRHS();
}
return count;
}
/**
* From a Prolog List, obtain a Struct with the first list element as functor, and all other elements as arguments. This returns
* a(b,c,d) form [a,b,c,d]. This is the =.. predicate.
*
* @param prologList
* @throws InvalidTermException if this is not a prolog list.
*/
// TODO (issue) Only used from Library. Clarify how it works, see https://github.com/ltettoni/logic2j/issues/14
public static Struct<?> predicateFromPList(Struct<?> prologList) {
requireList(prologList);
final Object functor = prologList.getLHS(); | // Path: src/main/java/org/logic2j/engine/model/TermApiLocator.java
// public static TermApi termApi() {
// return termApi;
// }
//
// Path: src/main/java/org/logic2j/engine/util/TypeUtils.java
// public abstract class TypeUtils {
//
// /**
// * Dynamic runtime checking of an instance against a class or interface; tolerates null values.
// *
// * @param context Contextual information to be reported, in case of an exception being thrown, to the beginning of the exception's
// * message. Typical use case would be safeCastOrNull("Downloading " + this, eventDate, Date.class).
// * @param instance The instance to check, can be null.
// * @param desiredClassOrInterface The class or interface that we want to make sure the instance is "instanceof".
// * @return The instance checked, or null.
// * @throws ClassCastException If the instance was not of the desiredClassOrInterface, i.e. if desiredClassOrInterface is not assignable
// * to instance.
// */
// @SuppressWarnings("unchecked")
// public static <T> T safeCastOrNull(String context, Object instance, Class<? extends T> desiredClassOrInterface) throws ClassCastException {
// if (instance == null) {
// return null;
// }
// if (!(desiredClassOrInterface.isAssignableFrom(instance.getClass()))) {
// final String message =
// "Could not cast an instance of " + instance.getClass() + " to expected " + desiredClassOrInterface + " [formatted object was " + instance
// + "]";
// throw new PrologNonSpecificException(message);
// }
// return (T) instance;
// }
//
// /**
// * Dynamic runtime checking of an instance against a class or interface; does now allow null values.
// *
// * @param context Contextual information to be reported, in case of an exception being thrown, to the beginning of the exception's
// * message. Typical use case would be safeCastNotNull("Obtaining PMDB API", api, PMDB.class).
// * @param instance The instance to check, must not be null
// * @param desiredClassOrInterface The class or interface that we want to make sure the instance is "instanceof".
// * @return The instance checked, never null.
// * @throws ClassCastException If the instance was not of the desiredClassOrInterface, i.e. if desiredClassOrInterface is not assignable
// * to instance.
// */
// public static <T> T safeCastNotNull(String context, Object instance, Class<? extends T> desiredClassOrInterface) throws ClassCastException {
// if (instance == null) {
// throw new PrologNonSpecificException("null value not allowed, expected an instance of " + desiredClassOrInterface + ", while " + context);
// }
// final String effectiveContext = (context != null) ? context : "casting undescribed object";
// return safeCastOrNull(effectiveContext, instance, desiredClassOrInterface);
// }
//
// }
// Path: src/main/java/org/logic2j/engine/model/PrologLists.java
import static org.logic2j.engine.model.TermApiLocator.termApi;
import java.util.ArrayList;
import java.util.Collection;
import org.logic2j.engine.exception.InvalidTermException;
import org.logic2j.engine.util.TypeUtils;
}
/**
* Gets the number of elements of this structure, which is supposed to be a list.
*
* @param prologList
* @throws InvalidTermException if this is not a prolog list.
*/
public static int listSize(Struct<?> prologList) {
requireList(prologList);
Struct<?> running = prologList;
int count = 0;
while (!isEmptyList(running)) {
count++;
running = (Struct<?>) running.getRHS();
}
return count;
}
/**
* From a Prolog List, obtain a Struct with the first list element as functor, and all other elements as arguments. This returns
* a(b,c,d) form [a,b,c,d]. This is the =.. predicate.
*
* @param prologList
* @throws InvalidTermException if this is not a prolog list.
*/
// TODO (issue) Only used from Library. Clarify how it works, see https://github.com/ltettoni/logic2j/issues/14
public static Struct<?> predicateFromPList(Struct<?> prologList) {
requireList(prologList);
final Object functor = prologList.getLHS(); | if (!termApi().isAtom(functor)) { |
ltettoni/logic2j | src/main/java/org/logic2j/engine/model/PrologLists.java | // Path: src/main/java/org/logic2j/engine/model/TermApiLocator.java
// public static TermApi termApi() {
// return termApi;
// }
//
// Path: src/main/java/org/logic2j/engine/util/TypeUtils.java
// public abstract class TypeUtils {
//
// /**
// * Dynamic runtime checking of an instance against a class or interface; tolerates null values.
// *
// * @param context Contextual information to be reported, in case of an exception being thrown, to the beginning of the exception's
// * message. Typical use case would be safeCastOrNull("Downloading " + this, eventDate, Date.class).
// * @param instance The instance to check, can be null.
// * @param desiredClassOrInterface The class or interface that we want to make sure the instance is "instanceof".
// * @return The instance checked, or null.
// * @throws ClassCastException If the instance was not of the desiredClassOrInterface, i.e. if desiredClassOrInterface is not assignable
// * to instance.
// */
// @SuppressWarnings("unchecked")
// public static <T> T safeCastOrNull(String context, Object instance, Class<? extends T> desiredClassOrInterface) throws ClassCastException {
// if (instance == null) {
// return null;
// }
// if (!(desiredClassOrInterface.isAssignableFrom(instance.getClass()))) {
// final String message =
// "Could not cast an instance of " + instance.getClass() + " to expected " + desiredClassOrInterface + " [formatted object was " + instance
// + "]";
// throw new PrologNonSpecificException(message);
// }
// return (T) instance;
// }
//
// /**
// * Dynamic runtime checking of an instance against a class or interface; does now allow null values.
// *
// * @param context Contextual information to be reported, in case of an exception being thrown, to the beginning of the exception's
// * message. Typical use case would be safeCastNotNull("Obtaining PMDB API", api, PMDB.class).
// * @param instance The instance to check, must not be null
// * @param desiredClassOrInterface The class or interface that we want to make sure the instance is "instanceof".
// * @return The instance checked, never null.
// * @throws ClassCastException If the instance was not of the desiredClassOrInterface, i.e. if desiredClassOrInterface is not assignable
// * to instance.
// */
// public static <T> T safeCastNotNull(String context, Object instance, Class<? extends T> desiredClassOrInterface) throws ClassCastException {
// if (instance == null) {
// throw new PrologNonSpecificException("null value not allowed, expected an instance of " + desiredClassOrInterface + ", while " + context);
// }
// final String effectiveContext = (context != null) ? context : "casting undescribed object";
// return safeCastOrNull(effectiveContext, instance, desiredClassOrInterface);
// }
//
// }
| import static org.logic2j.engine.model.TermApiLocator.termApi;
import java.util.ArrayList;
import java.util.Collection;
import org.logic2j.engine.exception.InvalidTermException;
import org.logic2j.engine.util.TypeUtils; | * @throws InvalidTermException if this is not a prolog list.
*/
@SuppressWarnings("unchecked")
public static <Q, T extends Collection<Q>> T javaListFromPList(Struct<?> prologList, T theCollectionToFillOrNull, Class<Q> theElementRequiredClass) {
return javaListFromPList(prologList, theCollectionToFillOrNull, theElementRequiredClass, false);
}
/**
* Traverse Prolog List adding all elements (in right order) into a target collection, possibly recursing if elements are
* Prolog lists too.
*
* @param prologList
* @param theCollectionToFillOrNull
* @param theElementRequiredClass
* @param <Q>
* @param <T>
* @return
* @throws InvalidTermException if this is not a prolog list.
*/
@SuppressWarnings("unchecked")
public static <Q, T extends Collection<Q>> T javaListFromPList(Struct<?> prologList, T theCollectionToFillOrNull, Class<Q> theElementRequiredClass,
boolean recursive) {
final T result;
if (theCollectionToFillOrNull == null) {
result = (T) new ArrayList<Q>();
} else {
result = theCollectionToFillOrNull;
}
// In case not a list, we just add a single element to the collection to fill
if (!isList(prologList)) { | // Path: src/main/java/org/logic2j/engine/model/TermApiLocator.java
// public static TermApi termApi() {
// return termApi;
// }
//
// Path: src/main/java/org/logic2j/engine/util/TypeUtils.java
// public abstract class TypeUtils {
//
// /**
// * Dynamic runtime checking of an instance against a class or interface; tolerates null values.
// *
// * @param context Contextual information to be reported, in case of an exception being thrown, to the beginning of the exception's
// * message. Typical use case would be safeCastOrNull("Downloading " + this, eventDate, Date.class).
// * @param instance The instance to check, can be null.
// * @param desiredClassOrInterface The class or interface that we want to make sure the instance is "instanceof".
// * @return The instance checked, or null.
// * @throws ClassCastException If the instance was not of the desiredClassOrInterface, i.e. if desiredClassOrInterface is not assignable
// * to instance.
// */
// @SuppressWarnings("unchecked")
// public static <T> T safeCastOrNull(String context, Object instance, Class<? extends T> desiredClassOrInterface) throws ClassCastException {
// if (instance == null) {
// return null;
// }
// if (!(desiredClassOrInterface.isAssignableFrom(instance.getClass()))) {
// final String message =
// "Could not cast an instance of " + instance.getClass() + " to expected " + desiredClassOrInterface + " [formatted object was " + instance
// + "]";
// throw new PrologNonSpecificException(message);
// }
// return (T) instance;
// }
//
// /**
// * Dynamic runtime checking of an instance against a class or interface; does now allow null values.
// *
// * @param context Contextual information to be reported, in case of an exception being thrown, to the beginning of the exception's
// * message. Typical use case would be safeCastNotNull("Obtaining PMDB API", api, PMDB.class).
// * @param instance The instance to check, must not be null
// * @param desiredClassOrInterface The class or interface that we want to make sure the instance is "instanceof".
// * @return The instance checked, never null.
// * @throws ClassCastException If the instance was not of the desiredClassOrInterface, i.e. if desiredClassOrInterface is not assignable
// * to instance.
// */
// public static <T> T safeCastNotNull(String context, Object instance, Class<? extends T> desiredClassOrInterface) throws ClassCastException {
// if (instance == null) {
// throw new PrologNonSpecificException("null value not allowed, expected an instance of " + desiredClassOrInterface + ", while " + context);
// }
// final String effectiveContext = (context != null) ? context : "casting undescribed object";
// return safeCastOrNull(effectiveContext, instance, desiredClassOrInterface);
// }
//
// }
// Path: src/main/java/org/logic2j/engine/model/PrologLists.java
import static org.logic2j.engine.model.TermApiLocator.termApi;
import java.util.ArrayList;
import java.util.Collection;
import org.logic2j.engine.exception.InvalidTermException;
import org.logic2j.engine.util.TypeUtils;
* @throws InvalidTermException if this is not a prolog list.
*/
@SuppressWarnings("unchecked")
public static <Q, T extends Collection<Q>> T javaListFromPList(Struct<?> prologList, T theCollectionToFillOrNull, Class<Q> theElementRequiredClass) {
return javaListFromPList(prologList, theCollectionToFillOrNull, theElementRequiredClass, false);
}
/**
* Traverse Prolog List adding all elements (in right order) into a target collection, possibly recursing if elements are
* Prolog lists too.
*
* @param prologList
* @param theCollectionToFillOrNull
* @param theElementRequiredClass
* @param <Q>
* @param <T>
* @return
* @throws InvalidTermException if this is not a prolog list.
*/
@SuppressWarnings("unchecked")
public static <Q, T extends Collection<Q>> T javaListFromPList(Struct<?> prologList, T theCollectionToFillOrNull, Class<Q> theElementRequiredClass,
boolean recursive) {
final T result;
if (theCollectionToFillOrNull == null) {
result = (T) new ArrayList<Q>();
} else {
result = theCollectionToFillOrNull;
}
// In case not a list, we just add a single element to the collection to fill
if (!isList(prologList)) { | result.add(TypeUtils.safeCastNotNull("casting single value", prologList, theElementRequiredClass)); |
ltettoni/logic2j | src/main/java/org/logic2j/core/impl/DefaultOperatorManager.java | // Path: src/main/java/org/logic2j/core/api/model/Operator.java
// public final class Operator implements Serializable {
// private static final long serialVersionUID = 1L;
//
// // TODO Probably this should become an enum
// public static final String FX = "fx"; // prefix non-associative - (i.e. --5 not possible)
// public static final String FY = "fy"; // prefix associative
// public static final String XF = "xf"; // postfix non-associative
// public static final String XFX = "xfx"; // infix non-associative =, is, < (i.e. no nesting)
// public static final String XFY = "xfy"; // infix right-associative , (for subgoals)
// public static final String YF = "yf"; // postfix associative
// public static final String YFX = "yfx"; // infix left-associative +, -, *
// public static final String YFY = "yfy"; // makes no sense, structuring would be impossible
//
// /**
// * highest operator precedence
// */
// public static final int OP_HIGHEST = 1200;
// /**
// * lowest operator precedence
// */
// public static final int OP_LOWEST = 1;
//
// /**
// * operator text representation
// */
// private final String text;
//
// /**
// * precedence
// */
// private final int precedence;
//
// /**
// * xf, yf, fx, fy, xfx, xfy, yfx, (yfy)
// */
// private final String associativity;
//
// public Operator(String theText, String theAssociativity, int thePrecedence) {
// this.text = theText;
// this.associativity = theAssociativity;
// this.precedence = thePrecedence;
// }
//
// // ---------------------------------------------------------------------------
// // Getters
// // ---------------------------------------------------------------------------
//
//
// public String getText() {
// return text;
// }
//
// public int getPrecedence() {
// return precedence;
// }
//
// public String getAssociativity() {
// return associativity;
// }
// }
| import org.logic2j.core.api.model.Operator;
import org.logic2j.engine.model.Struct; | /*
* tuProlog - Copyright (C) 2001-2002 aliCE team at deis.unibo.it
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
package org.logic2j.core.impl;
/**
* This class defines an OperatorManager with many standard Prolog operators defined.
*/
public class DefaultOperatorManager extends OperatorManagerBase {
private static final long serialVersionUID = 1L;
public DefaultOperatorManager() { | // Path: src/main/java/org/logic2j/core/api/model/Operator.java
// public final class Operator implements Serializable {
// private static final long serialVersionUID = 1L;
//
// // TODO Probably this should become an enum
// public static final String FX = "fx"; // prefix non-associative - (i.e. --5 not possible)
// public static final String FY = "fy"; // prefix associative
// public static final String XF = "xf"; // postfix non-associative
// public static final String XFX = "xfx"; // infix non-associative =, is, < (i.e. no nesting)
// public static final String XFY = "xfy"; // infix right-associative , (for subgoals)
// public static final String YF = "yf"; // postfix associative
// public static final String YFX = "yfx"; // infix left-associative +, -, *
// public static final String YFY = "yfy"; // makes no sense, structuring would be impossible
//
// /**
// * highest operator precedence
// */
// public static final int OP_HIGHEST = 1200;
// /**
// * lowest operator precedence
// */
// public static final int OP_LOWEST = 1;
//
// /**
// * operator text representation
// */
// private final String text;
//
// /**
// * precedence
// */
// private final int precedence;
//
// /**
// * xf, yf, fx, fy, xfx, xfy, yfx, (yfy)
// */
// private final String associativity;
//
// public Operator(String theText, String theAssociativity, int thePrecedence) {
// this.text = theText;
// this.associativity = theAssociativity;
// this.precedence = thePrecedence;
// }
//
// // ---------------------------------------------------------------------------
// // Getters
// // ---------------------------------------------------------------------------
//
//
// public String getText() {
// return text;
// }
//
// public int getPrecedence() {
// return precedence;
// }
//
// public String getAssociativity() {
// return associativity;
// }
// }
// Path: src/main/java/org/logic2j/core/impl/DefaultOperatorManager.java
import org.logic2j.core.api.model.Operator;
import org.logic2j.engine.model.Struct;
/*
* tuProlog - Copyright (C) 2001-2002 aliCE team at deis.unibo.it
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
package org.logic2j.core.impl;
/**
* This class defines an OperatorManager with many standard Prolog operators defined.
*/
public class DefaultOperatorManager extends OperatorManagerBase {
private static final long serialVersionUID = 1L;
public DefaultOperatorManager() { | addOperator(Struct.FUNCTOR_CLAUSE, Operator.XFX, 1200); |
ltettoni/logic2j | src/main/java/org/logic2j/core/api/library/PrimitiveInfo.java | // Path: src/main/java/org/logic2j/engine/exception/RecursionException.java
// public class RecursionException extends Logic2jException {
//
// private static final long serialVersionUID = -4416801118548866803L;
//
// public RecursionException(String theString) {
// super(theString);
// }
//
// public RecursionException(String theString, Throwable theRootCause) {
// super(theString, theRootCause);
// }
//
// }
| import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.HashSet;
import org.logic2j.engine.exception.InvalidTermException;
import org.logic2j.engine.exception.RecursionException;
import org.logic2j.engine.model.Struct;
import org.logic2j.engine.solver.listener.SolutionListener;
import org.logic2j.engine.unify.UnifyContext; | this.library = theLibrary;
this.name = theName;
this.method = theMethod;
this.methodName = theMethod.getName().intern();
this.isVarargs = theVarargs;
}
public Object invoke(Struct<?> theGoalStruct, UnifyContext currentVars) {
final Object result = this.library.dispatch(this.methodName, theGoalStruct, currentVars);
if (result != PLibrary.NO_DIRECT_INVOCATION_USE_REFLECTION) {
return result;
}
// We did not do a direct invocation - we will have to rely on reflection
if (!methodNeedingReflectiveInvocation.contains(this.methodName)) {
logger.warn("Invocation of library primitive \"{}\" for goal \"{}\" uses reflection - consider implementing {}.dispatch()", this.methodName,
theGoalStruct, this.library);
// Avoid multiple logging
methodNeedingReflectiveInvocation.add(this.methodName);
}
try {
if (isDebug) {
logger.debug("PRIMITIVE > invocation of {}", this);
}
return invokeReflective(theGoalStruct, currentVars);
} catch (final IllegalArgumentException e) {
throw e;
} catch (final IllegalAccessException e) {
throw new InvalidTermException("Could not access method " + this.method, e);
} catch (final InvocationTargetException e) {
final Throwable targetException = e.getTargetException(); | // Path: src/main/java/org/logic2j/engine/exception/RecursionException.java
// public class RecursionException extends Logic2jException {
//
// private static final long serialVersionUID = -4416801118548866803L;
//
// public RecursionException(String theString) {
// super(theString);
// }
//
// public RecursionException(String theString, Throwable theRootCause) {
// super(theString, theRootCause);
// }
//
// }
// Path: src/main/java/org/logic2j/core/api/library/PrimitiveInfo.java
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.HashSet;
import org.logic2j.engine.exception.InvalidTermException;
import org.logic2j.engine.exception.RecursionException;
import org.logic2j.engine.model.Struct;
import org.logic2j.engine.solver.listener.SolutionListener;
import org.logic2j.engine.unify.UnifyContext;
this.library = theLibrary;
this.name = theName;
this.method = theMethod;
this.methodName = theMethod.getName().intern();
this.isVarargs = theVarargs;
}
public Object invoke(Struct<?> theGoalStruct, UnifyContext currentVars) {
final Object result = this.library.dispatch(this.methodName, theGoalStruct, currentVars);
if (result != PLibrary.NO_DIRECT_INVOCATION_USE_REFLECTION) {
return result;
}
// We did not do a direct invocation - we will have to rely on reflection
if (!methodNeedingReflectiveInvocation.contains(this.methodName)) {
logger.warn("Invocation of library primitive \"{}\" for goal \"{}\" uses reflection - consider implementing {}.dispatch()", this.methodName,
theGoalStruct, this.library);
// Avoid multiple logging
methodNeedingReflectiveInvocation.add(this.methodName);
}
try {
if (isDebug) {
logger.debug("PRIMITIVE > invocation of {}", this);
}
return invokeReflective(theGoalStruct, currentVars);
} catch (final IllegalArgumentException e) {
throw e;
} catch (final IllegalAccessException e) {
throw new InvalidTermException("Could not access method " + this.method, e);
} catch (final InvocationTargetException e) {
final Throwable targetException = e.getTargetException(); | if (targetException instanceof RecursionException) { |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.