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 |
|---|---|---|---|---|---|---|
bxbxbai/ZhuanLan | app/src/main/java/io/bxbxbai/zhuanlan/widget/OnMenuListClickListener.java | // Path: app/src/main/java/io/bxbxbai/zhuanlan/ui/AllPeopleActivity.java
// public class AllPeopleActivity extends ToolBarActivity {
//
// @Override
// protected void onCreate(Bundle savedInstanceState) {
// super.onCreate(savedInstanceState);
// setContentView(R.layout.activity_all_people);
// setTitle(R.string.all_people);
//
// getSupportFragmentManager().beginTransaction().add(R.id.container,
// PeopleListFragment.newInstance()).commit();
// }
//
// public static void start(Activity activity) {
// activity.startActivity(new Intent(activity, AllPeopleActivity.class));
// }
// }
//
// Path: app/src/main/java/io/bxbxbai/zhuanlan/ui/RecentPostListActivity.java
// public class RecentPostListActivity extends ListBaseActivity {
//
// private List<Post> postList;
// private PostListAdapter adapter;
//
// //按文章的发布时间排序
// final Comparator<Post> mPublishTimeComparator = new Comparator<Post>() {
// @Override
// public int compare(Post lhs, Post rhs) {
// return Utils.compareTime(lhs.getPublishedTime(), rhs.getPublishedTime());
// }
// };
//
// @Override
// protected void onCreate(Bundle savedInstanceState) {
// super.onCreate(savedInstanceState);
// setTitle(R.string.recent_news);
//
// adapter = new PostListAdapter(this);
// recyclerView.setAdapter(adapter);
// postList = new ArrayList<>();
//
// String[] ids = getResources().getStringArray(R.array.people_ids);
//
// for (int i = 0; ids != null && i < ids.length; i++) {
// sendRequest(ids[i], 0);
// }
// }
//
// public void sendRequest(String id, int page) {
// ZhuanLanApi.getZhuanlanApi()
// .getPosts(id, ZhuanLanApi.DEFAULT_COUNT, page * ZhuanLanApi.DEFAULT_COUNT)
// .enqueue(new SimpleCallback<List<Post>>() {
// @Override
// public void onResponse(List<Post> posts, int code, String msg) {
// onSuccess(posts);
// }
// });
// }
//
// private void onSuccess(List<Post> posts) {
// if (postList.size() > 0) {
// recyclerView.setVisibility(View.VISIBLE);
// mLoadingView.setVisibility(View.GONE);
// }
// postList.addAll(filterNews(posts));
// Collections.sort(postList, mPublishTimeComparator);
// adapter.setItemList(postList);
// }
//
// public List<Post> filterNews(List<Post> origin) {
// List<Post> list = new ArrayList<>();
//
// for (Post post : origin) {
// if (Utils.withinDays(post.getPublishedTime(), 7)) {
// list.add(post);
// }
// }
// return list;
// }
//
// public static boolean start(final Context context) {
// final Intent intent = new Intent();
// intent.setClass(context, RecentPostListActivity.class);
// CommonExecutor.MAIN_HANDLER.postDelayed(new Runnable() {
// @Override
// public void run() {
// context.startActivity(intent);
// }
// }, 300);
// return true;
// }
// }
| import android.app.Activity;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.view.View;
import android.widget.AdapterView;
import io.bxbxbai.common.Tips;
import io.bxbxbai.zhuanlan.R;
import io.bxbxbai.zhuanlan.ui.AllPeopleActivity;
import io.bxbxbai.zhuanlan.ui.RecentPostListActivity; | package io.bxbxbai.zhuanlan.widget;
/**
*
* 点击事件
* @author bxbxbai
*/
public class OnMenuListClickListener implements AdapterView.OnItemClickListener {
private Activity mActivity;
private DrawerLayout mDrawerLayout;
public OnMenuListClickListener(Activity activity, DrawerLayout drawerLayout) {
mActivity = activity;
mDrawerLayout = drawerLayout;
}
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
DrawerMenuContent.DrawerItem item = (DrawerMenuContent.DrawerItem) view.getTag(R.id.key_data);
if (mDrawerLayout != null && mDrawerLayout.isDrawerOpen(GravityCompat.START)) {
mDrawerLayout.closeDrawers();
}
switch (item.id) {
case R.id.menu_search :
Tips.showToast("Coming soon...");
break;
case R.id.menu_all_people: | // Path: app/src/main/java/io/bxbxbai/zhuanlan/ui/AllPeopleActivity.java
// public class AllPeopleActivity extends ToolBarActivity {
//
// @Override
// protected void onCreate(Bundle savedInstanceState) {
// super.onCreate(savedInstanceState);
// setContentView(R.layout.activity_all_people);
// setTitle(R.string.all_people);
//
// getSupportFragmentManager().beginTransaction().add(R.id.container,
// PeopleListFragment.newInstance()).commit();
// }
//
// public static void start(Activity activity) {
// activity.startActivity(new Intent(activity, AllPeopleActivity.class));
// }
// }
//
// Path: app/src/main/java/io/bxbxbai/zhuanlan/ui/RecentPostListActivity.java
// public class RecentPostListActivity extends ListBaseActivity {
//
// private List<Post> postList;
// private PostListAdapter adapter;
//
// //按文章的发布时间排序
// final Comparator<Post> mPublishTimeComparator = new Comparator<Post>() {
// @Override
// public int compare(Post lhs, Post rhs) {
// return Utils.compareTime(lhs.getPublishedTime(), rhs.getPublishedTime());
// }
// };
//
// @Override
// protected void onCreate(Bundle savedInstanceState) {
// super.onCreate(savedInstanceState);
// setTitle(R.string.recent_news);
//
// adapter = new PostListAdapter(this);
// recyclerView.setAdapter(adapter);
// postList = new ArrayList<>();
//
// String[] ids = getResources().getStringArray(R.array.people_ids);
//
// for (int i = 0; ids != null && i < ids.length; i++) {
// sendRequest(ids[i], 0);
// }
// }
//
// public void sendRequest(String id, int page) {
// ZhuanLanApi.getZhuanlanApi()
// .getPosts(id, ZhuanLanApi.DEFAULT_COUNT, page * ZhuanLanApi.DEFAULT_COUNT)
// .enqueue(new SimpleCallback<List<Post>>() {
// @Override
// public void onResponse(List<Post> posts, int code, String msg) {
// onSuccess(posts);
// }
// });
// }
//
// private void onSuccess(List<Post> posts) {
// if (postList.size() > 0) {
// recyclerView.setVisibility(View.VISIBLE);
// mLoadingView.setVisibility(View.GONE);
// }
// postList.addAll(filterNews(posts));
// Collections.sort(postList, mPublishTimeComparator);
// adapter.setItemList(postList);
// }
//
// public List<Post> filterNews(List<Post> origin) {
// List<Post> list = new ArrayList<>();
//
// for (Post post : origin) {
// if (Utils.withinDays(post.getPublishedTime(), 7)) {
// list.add(post);
// }
// }
// return list;
// }
//
// public static boolean start(final Context context) {
// final Intent intent = new Intent();
// intent.setClass(context, RecentPostListActivity.class);
// CommonExecutor.MAIN_HANDLER.postDelayed(new Runnable() {
// @Override
// public void run() {
// context.startActivity(intent);
// }
// }, 300);
// return true;
// }
// }
// Path: app/src/main/java/io/bxbxbai/zhuanlan/widget/OnMenuListClickListener.java
import android.app.Activity;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.view.View;
import android.widget.AdapterView;
import io.bxbxbai.common.Tips;
import io.bxbxbai.zhuanlan.R;
import io.bxbxbai.zhuanlan.ui.AllPeopleActivity;
import io.bxbxbai.zhuanlan.ui.RecentPostListActivity;
package io.bxbxbai.zhuanlan.widget;
/**
*
* 点击事件
* @author bxbxbai
*/
public class OnMenuListClickListener implements AdapterView.OnItemClickListener {
private Activity mActivity;
private DrawerLayout mDrawerLayout;
public OnMenuListClickListener(Activity activity, DrawerLayout drawerLayout) {
mActivity = activity;
mDrawerLayout = drawerLayout;
}
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
DrawerMenuContent.DrawerItem item = (DrawerMenuContent.DrawerItem) view.getTag(R.id.key_data);
if (mDrawerLayout != null && mDrawerLayout.isDrawerOpen(GravityCompat.START)) {
mDrawerLayout.closeDrawers();
}
switch (item.id) {
case R.id.menu_search :
Tips.showToast("Coming soon...");
break;
case R.id.menu_all_people: | AllPeopleActivity.start(mActivity); |
bxbxbai/ZhuanLan | app/src/main/java/io/bxbxbai/zhuanlan/widget/OnMenuListClickListener.java | // Path: app/src/main/java/io/bxbxbai/zhuanlan/ui/AllPeopleActivity.java
// public class AllPeopleActivity extends ToolBarActivity {
//
// @Override
// protected void onCreate(Bundle savedInstanceState) {
// super.onCreate(savedInstanceState);
// setContentView(R.layout.activity_all_people);
// setTitle(R.string.all_people);
//
// getSupportFragmentManager().beginTransaction().add(R.id.container,
// PeopleListFragment.newInstance()).commit();
// }
//
// public static void start(Activity activity) {
// activity.startActivity(new Intent(activity, AllPeopleActivity.class));
// }
// }
//
// Path: app/src/main/java/io/bxbxbai/zhuanlan/ui/RecentPostListActivity.java
// public class RecentPostListActivity extends ListBaseActivity {
//
// private List<Post> postList;
// private PostListAdapter adapter;
//
// //按文章的发布时间排序
// final Comparator<Post> mPublishTimeComparator = new Comparator<Post>() {
// @Override
// public int compare(Post lhs, Post rhs) {
// return Utils.compareTime(lhs.getPublishedTime(), rhs.getPublishedTime());
// }
// };
//
// @Override
// protected void onCreate(Bundle savedInstanceState) {
// super.onCreate(savedInstanceState);
// setTitle(R.string.recent_news);
//
// adapter = new PostListAdapter(this);
// recyclerView.setAdapter(adapter);
// postList = new ArrayList<>();
//
// String[] ids = getResources().getStringArray(R.array.people_ids);
//
// for (int i = 0; ids != null && i < ids.length; i++) {
// sendRequest(ids[i], 0);
// }
// }
//
// public void sendRequest(String id, int page) {
// ZhuanLanApi.getZhuanlanApi()
// .getPosts(id, ZhuanLanApi.DEFAULT_COUNT, page * ZhuanLanApi.DEFAULT_COUNT)
// .enqueue(new SimpleCallback<List<Post>>() {
// @Override
// public void onResponse(List<Post> posts, int code, String msg) {
// onSuccess(posts);
// }
// });
// }
//
// private void onSuccess(List<Post> posts) {
// if (postList.size() > 0) {
// recyclerView.setVisibility(View.VISIBLE);
// mLoadingView.setVisibility(View.GONE);
// }
// postList.addAll(filterNews(posts));
// Collections.sort(postList, mPublishTimeComparator);
// adapter.setItemList(postList);
// }
//
// public List<Post> filterNews(List<Post> origin) {
// List<Post> list = new ArrayList<>();
//
// for (Post post : origin) {
// if (Utils.withinDays(post.getPublishedTime(), 7)) {
// list.add(post);
// }
// }
// return list;
// }
//
// public static boolean start(final Context context) {
// final Intent intent = new Intent();
// intent.setClass(context, RecentPostListActivity.class);
// CommonExecutor.MAIN_HANDLER.postDelayed(new Runnable() {
// @Override
// public void run() {
// context.startActivity(intent);
// }
// }, 300);
// return true;
// }
// }
| import android.app.Activity;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.view.View;
import android.widget.AdapterView;
import io.bxbxbai.common.Tips;
import io.bxbxbai.zhuanlan.R;
import io.bxbxbai.zhuanlan.ui.AllPeopleActivity;
import io.bxbxbai.zhuanlan.ui.RecentPostListActivity; | package io.bxbxbai.zhuanlan.widget;
/**
*
* 点击事件
* @author bxbxbai
*/
public class OnMenuListClickListener implements AdapterView.OnItemClickListener {
private Activity mActivity;
private DrawerLayout mDrawerLayout;
public OnMenuListClickListener(Activity activity, DrawerLayout drawerLayout) {
mActivity = activity;
mDrawerLayout = drawerLayout;
}
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
DrawerMenuContent.DrawerItem item = (DrawerMenuContent.DrawerItem) view.getTag(R.id.key_data);
if (mDrawerLayout != null && mDrawerLayout.isDrawerOpen(GravityCompat.START)) {
mDrawerLayout.closeDrawers();
}
switch (item.id) {
case R.id.menu_search :
Tips.showToast("Coming soon...");
break;
case R.id.menu_all_people:
AllPeopleActivity.start(mActivity);
break;
case R.id.menu_recent_news : | // Path: app/src/main/java/io/bxbxbai/zhuanlan/ui/AllPeopleActivity.java
// public class AllPeopleActivity extends ToolBarActivity {
//
// @Override
// protected void onCreate(Bundle savedInstanceState) {
// super.onCreate(savedInstanceState);
// setContentView(R.layout.activity_all_people);
// setTitle(R.string.all_people);
//
// getSupportFragmentManager().beginTransaction().add(R.id.container,
// PeopleListFragment.newInstance()).commit();
// }
//
// public static void start(Activity activity) {
// activity.startActivity(new Intent(activity, AllPeopleActivity.class));
// }
// }
//
// Path: app/src/main/java/io/bxbxbai/zhuanlan/ui/RecentPostListActivity.java
// public class RecentPostListActivity extends ListBaseActivity {
//
// private List<Post> postList;
// private PostListAdapter adapter;
//
// //按文章的发布时间排序
// final Comparator<Post> mPublishTimeComparator = new Comparator<Post>() {
// @Override
// public int compare(Post lhs, Post rhs) {
// return Utils.compareTime(lhs.getPublishedTime(), rhs.getPublishedTime());
// }
// };
//
// @Override
// protected void onCreate(Bundle savedInstanceState) {
// super.onCreate(savedInstanceState);
// setTitle(R.string.recent_news);
//
// adapter = new PostListAdapter(this);
// recyclerView.setAdapter(adapter);
// postList = new ArrayList<>();
//
// String[] ids = getResources().getStringArray(R.array.people_ids);
//
// for (int i = 0; ids != null && i < ids.length; i++) {
// sendRequest(ids[i], 0);
// }
// }
//
// public void sendRequest(String id, int page) {
// ZhuanLanApi.getZhuanlanApi()
// .getPosts(id, ZhuanLanApi.DEFAULT_COUNT, page * ZhuanLanApi.DEFAULT_COUNT)
// .enqueue(new SimpleCallback<List<Post>>() {
// @Override
// public void onResponse(List<Post> posts, int code, String msg) {
// onSuccess(posts);
// }
// });
// }
//
// private void onSuccess(List<Post> posts) {
// if (postList.size() > 0) {
// recyclerView.setVisibility(View.VISIBLE);
// mLoadingView.setVisibility(View.GONE);
// }
// postList.addAll(filterNews(posts));
// Collections.sort(postList, mPublishTimeComparator);
// adapter.setItemList(postList);
// }
//
// public List<Post> filterNews(List<Post> origin) {
// List<Post> list = new ArrayList<>();
//
// for (Post post : origin) {
// if (Utils.withinDays(post.getPublishedTime(), 7)) {
// list.add(post);
// }
// }
// return list;
// }
//
// public static boolean start(final Context context) {
// final Intent intent = new Intent();
// intent.setClass(context, RecentPostListActivity.class);
// CommonExecutor.MAIN_HANDLER.postDelayed(new Runnable() {
// @Override
// public void run() {
// context.startActivity(intent);
// }
// }, 300);
// return true;
// }
// }
// Path: app/src/main/java/io/bxbxbai/zhuanlan/widget/OnMenuListClickListener.java
import android.app.Activity;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.view.View;
import android.widget.AdapterView;
import io.bxbxbai.common.Tips;
import io.bxbxbai.zhuanlan.R;
import io.bxbxbai.zhuanlan.ui.AllPeopleActivity;
import io.bxbxbai.zhuanlan.ui.RecentPostListActivity;
package io.bxbxbai.zhuanlan.widget;
/**
*
* 点击事件
* @author bxbxbai
*/
public class OnMenuListClickListener implements AdapterView.OnItemClickListener {
private Activity mActivity;
private DrawerLayout mDrawerLayout;
public OnMenuListClickListener(Activity activity, DrawerLayout drawerLayout) {
mActivity = activity;
mDrawerLayout = drawerLayout;
}
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
DrawerMenuContent.DrawerItem item = (DrawerMenuContent.DrawerItem) view.getTag(R.id.key_data);
if (mDrawerLayout != null && mDrawerLayout.isDrawerOpen(GravityCompat.START)) {
mDrawerLayout.closeDrawers();
}
switch (item.id) {
case R.id.menu_search :
Tips.showToast("Coming soon...");
break;
case R.id.menu_all_people:
AllPeopleActivity.start(mActivity);
break;
case R.id.menu_recent_news : | RecentPostListActivity.start(mActivity); |
bxbxbai/ZhuanLan | app/src/main/java/io/bxbxbai/zhuanlan/utils/Utils.java | // Path: app/src/main/java/io/bxbxbai/zhuanlan/core/ZhuanLanApi.java
// public final class ZhuanLanApi {
//
// public static final int DEFAULT_COUNT = 10;
//
// public static final String KEY_POSTS = "/posts";
// public static final String KEY_LIMIT = "limit";
// public static final String KEY_OFFSET = "offset";
// public static final String KEY_RATING = "rating";
//
// public static final String ZHUAN_LAN_URL = "https://zhuanlan.zhihu.com";
// public static final String API_BASE = ZHUAN_LAN_URL + "/api/columns/%s";
//
// /**
// * slug, post id
// */
// public static final String API_POST_DETAIL = ZHUAN_LAN_URL + "/api/columns/%s/posts/%s";
//
//
// public static final class Url {
// private Url() {}
//
// public static final String ZHIHU_DAILY_BEFORE = "http://news.at.zhihu.com/api/3/news/before/";
// public static final String ZHIHU_DAILY_OFFLINE_NEWS = "http://news-at.zhihu.com/api/3/news/";
// public static final String ZHIHU_DAILY_PURIFY_HEROKU_BEFORE = "http://zhihu-daily-purify.herokuapp.com/raw/";
// public static final String ZHIHU_DAILY_PURIFY_SAE_BEFORE = "http://zhihudailypurify.sinaapp.com/raw/";
// public static final String SEARCH = "http://zhihudailypurify.sinaapp.com/search/";
// }
//
// /**
// * 知乎日报启动画面api(手机分辨率的长和宽)
// */
// public static final String API_START_IMAGE = "http://news-at.zhihu.com/api/4/start-image/%d*%d";
// public static final String API_RATING = API_BASE + KEY_POSTS + "{post_id}" + KEY_RATING;
// public static final String API_POST_LIST = API_BASE + KEY_POSTS;
//
// public static final String PIC_SIZE_XL = "xl";
// public static final String PIC_SIZE_XS = "xs";
//
//
// public static final String TEMPLATE_ID = "{id}";
// public static final String TEMPLATE_SIZE = "{size}";
//
//
// private static ZhuanLanApi instance = new ZhuanLanApi();
//
// private Retrofit retrofit;
//
// private ZhuanLanApi() {
// retrofit = new Retrofit.Builder()
// .baseUrl(ZHUAN_LAN_URL)
// .addConverterFactory(GsonConverterFactory.create())
// // .client(createHttpClient())
// .build();
// }
//
// public static <T> T api(Class<T> clazz) {
// return instance.retrofit.create(clazz);
// }
//
// public static Api getZhuanlanApi() {
// return api(Api.class);
// }
//
// private static OkHttpClient createHttpClient(Context context) {
// OkHttpClient.Builder builder = new OkHttpClient.Builder();
// builder.cache(new Cache(context.getCacheDir(), 10 * 1024*1024));
// return builder.build();
// }
// }
| import android.text.TextUtils;
import io.bxbxbai.zhuanlan.core.ZhuanLanApi;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.concurrent.TimeUnit; | package io.bxbxbai.zhuanlan.utils;
/**
*
*
* @author bxbxbai
*/
public class Utils {
private Utils() {}
private static final int MINUTE = 60;
private static final int HOUR = MINUTE * 60;
private static final int DAY = HOUR * 24;
private static final int MONTH = DAY * 30;
private static final int YEAR = MONTH * 12;
private static final DateFormat FORMAT = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZ");
public static String getAuthorAvatarUrl(String origin, String userId, String size) { | // Path: app/src/main/java/io/bxbxbai/zhuanlan/core/ZhuanLanApi.java
// public final class ZhuanLanApi {
//
// public static final int DEFAULT_COUNT = 10;
//
// public static final String KEY_POSTS = "/posts";
// public static final String KEY_LIMIT = "limit";
// public static final String KEY_OFFSET = "offset";
// public static final String KEY_RATING = "rating";
//
// public static final String ZHUAN_LAN_URL = "https://zhuanlan.zhihu.com";
// public static final String API_BASE = ZHUAN_LAN_URL + "/api/columns/%s";
//
// /**
// * slug, post id
// */
// public static final String API_POST_DETAIL = ZHUAN_LAN_URL + "/api/columns/%s/posts/%s";
//
//
// public static final class Url {
// private Url() {}
//
// public static final String ZHIHU_DAILY_BEFORE = "http://news.at.zhihu.com/api/3/news/before/";
// public static final String ZHIHU_DAILY_OFFLINE_NEWS = "http://news-at.zhihu.com/api/3/news/";
// public static final String ZHIHU_DAILY_PURIFY_HEROKU_BEFORE = "http://zhihu-daily-purify.herokuapp.com/raw/";
// public static final String ZHIHU_DAILY_PURIFY_SAE_BEFORE = "http://zhihudailypurify.sinaapp.com/raw/";
// public static final String SEARCH = "http://zhihudailypurify.sinaapp.com/search/";
// }
//
// /**
// * 知乎日报启动画面api(手机分辨率的长和宽)
// */
// public static final String API_START_IMAGE = "http://news-at.zhihu.com/api/4/start-image/%d*%d";
// public static final String API_RATING = API_BASE + KEY_POSTS + "{post_id}" + KEY_RATING;
// public static final String API_POST_LIST = API_BASE + KEY_POSTS;
//
// public static final String PIC_SIZE_XL = "xl";
// public static final String PIC_SIZE_XS = "xs";
//
//
// public static final String TEMPLATE_ID = "{id}";
// public static final String TEMPLATE_SIZE = "{size}";
//
//
// private static ZhuanLanApi instance = new ZhuanLanApi();
//
// private Retrofit retrofit;
//
// private ZhuanLanApi() {
// retrofit = new Retrofit.Builder()
// .baseUrl(ZHUAN_LAN_URL)
// .addConverterFactory(GsonConverterFactory.create())
// // .client(createHttpClient())
// .build();
// }
//
// public static <T> T api(Class<T> clazz) {
// return instance.retrofit.create(clazz);
// }
//
// public static Api getZhuanlanApi() {
// return api(Api.class);
// }
//
// private static OkHttpClient createHttpClient(Context context) {
// OkHttpClient.Builder builder = new OkHttpClient.Builder();
// builder.cache(new Cache(context.getCacheDir(), 10 * 1024*1024));
// return builder.build();
// }
// }
// Path: app/src/main/java/io/bxbxbai/zhuanlan/utils/Utils.java
import android.text.TextUtils;
import io.bxbxbai.zhuanlan.core.ZhuanLanApi;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.concurrent.TimeUnit;
package io.bxbxbai.zhuanlan.utils;
/**
*
*
* @author bxbxbai
*/
public class Utils {
private Utils() {}
private static final int MINUTE = 60;
private static final int HOUR = MINUTE * 60;
private static final int DAY = HOUR * 24;
private static final int MONTH = DAY * 30;
private static final int YEAR = MONTH * 12;
private static final DateFormat FORMAT = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZ");
public static String getAuthorAvatarUrl(String origin, String userId, String size) { | origin = origin.replace(ZhuanLanApi.TEMPLATE_ID, userId); |
bxbxbai/ZhuanLan | app/src/main/java/io/bxbxbai/zhuanlan/core/ZhuanLanWebViewClient.java | // Path: app/src/main/java/io/bxbxbai/zhuanlan/ui/WebActivity.java
// public class WebActivity extends BaseActivity {
// private static final String TAG = "AboutActivity";
//
// private static final String KEY_URL = "key_url";
// private static final String KEY_TITLE = "key_title";
//
// public static final String URL_BXBXBAI = "http://bxbxbai.gitcafe.io/about/";
//
// private String url, title;
//
// private CommonWebView mWebView;
//
// @Override
// protected void onCreate(Bundle savedInstanceState) {
// super.onCreate(savedInstanceState);
// setContentView(R.layout.activity_web);
// parseIntent(getIntent());
//
// ProgressBar bar = ButterKnife.findById(this, R.id.progress_bar);
// bar.setVisibility(View.GONE);
// View v = ButterKnife.findById(this, R.id.v_loading);
//
// mWebView = ButterKnife.findById(this, R.id.web_view);
// initWebSetting();
//
// mWebView.setWebChromeClient(new ZhuanLanWebChromeClient(bar, v,
// TextUtils.isEmpty(title) ? getSupportActionBar() : null));
// mWebView.setWebViewClient(new ZhuanLanWebViewClient(this));
// mWebView.loadUrl(url);
// }
//
//
// @Override
// protected void onNewIntent(Intent intent) {
// super.onNewIntent(intent);
// parseIntent(intent);
// }
//
// private void parseIntent(Intent intent) {
// url = intent.getStringExtra(KEY_URL);
// title = intent.getStringExtra(KEY_TITLE);
//
// if (TextUtils.isEmpty(url)) {
// Tips.showToast("木有URL...");
// finish();
// }
// setTitle(TextUtils.isEmpty(title) ? getString(R.string.app_name) : title);
// }
//
// private void initWebSetting() {
// JsHandler jsHandler = new JsHandler(this, mWebView);
// mWebView.addJavascriptInterface(jsHandler, "JsHandler");
// }
//
// private void createView() {
// FloatView view = new FloatView(getApplicationContext());
//
// WindowManager wm = (WindowManager) getApplicationContext().getSystemService(Context.WINDOW_SERVICE);
//
// WindowManager.LayoutParams wmParams = new WindowManager.LayoutParams();
// wmParams.type = WindowManager.LayoutParams.TYPE_PHONE;
// wmParams.format = PixelFormat.RGBA_8888;
// wmParams.flags |= 8;
// wmParams.gravity = Gravity.RIGHT | Gravity.CENTER_VERTICAL;
// wmParams.x = 0;
// wmParams.y = 80;
// wmParams.width = ViewGroup.LayoutParams.WRAP_CONTENT;
// wmParams.height = ViewGroup.LayoutParams.WRAP_CONTENT;
//
// view.setOnClickListener(new View.OnClickListener() {
// @Override
// public void onClick(View v) {
// ZhuanlanApplication.getInstance().startActivity(new Intent("com.bxbxbai.zhuanlan.ui.activity.AboutActivity"));
// Log.i(TAG, "onclick");
// }
// });
//
// wm.addView(view, wmParams);
// }
//
// public static boolean start(Activity activity, String url, String title) {
// Intent intent = new Intent();
// intent.setClass(activity, WebActivity.class);
// intent.putExtra(KEY_URL, url);
// intent.putExtra(KEY_TITLE, title);
// activity.startActivity(intent);
//
// return true;
// }
//
// public static boolean start(Activity activity, String url) {
// return start(activity, url, null);
// }
// }
| import android.app.Activity;
import android.graphics.Bitmap;
import android.webkit.WebResourceRequest;
import android.webkit.WebResourceResponse;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import io.bxbxbai.common.StopWatch;
import io.bxbxbai.zhuanlan.ui.WebActivity; | package io.bxbxbai.zhuanlan.core;
/**
*
* @author bxbxbai
*/
public class ZhuanLanWebViewClient extends WebViewClient {
private Activity mActivity;
public ZhuanLanWebViewClient(Activity activity) {
mActivity = activity;
}
@Override
public void onLoadResource(WebView view, String url) {
super.onLoadResource(view, url);
}
@Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
StopWatch.log("url " + url);
if (url != null && url.startsWith("orpheus")) {
return true;
}
if (url != null && url.startsWith("http")) { | // Path: app/src/main/java/io/bxbxbai/zhuanlan/ui/WebActivity.java
// public class WebActivity extends BaseActivity {
// private static final String TAG = "AboutActivity";
//
// private static final String KEY_URL = "key_url";
// private static final String KEY_TITLE = "key_title";
//
// public static final String URL_BXBXBAI = "http://bxbxbai.gitcafe.io/about/";
//
// private String url, title;
//
// private CommonWebView mWebView;
//
// @Override
// protected void onCreate(Bundle savedInstanceState) {
// super.onCreate(savedInstanceState);
// setContentView(R.layout.activity_web);
// parseIntent(getIntent());
//
// ProgressBar bar = ButterKnife.findById(this, R.id.progress_bar);
// bar.setVisibility(View.GONE);
// View v = ButterKnife.findById(this, R.id.v_loading);
//
// mWebView = ButterKnife.findById(this, R.id.web_view);
// initWebSetting();
//
// mWebView.setWebChromeClient(new ZhuanLanWebChromeClient(bar, v,
// TextUtils.isEmpty(title) ? getSupportActionBar() : null));
// mWebView.setWebViewClient(new ZhuanLanWebViewClient(this));
// mWebView.loadUrl(url);
// }
//
//
// @Override
// protected void onNewIntent(Intent intent) {
// super.onNewIntent(intent);
// parseIntent(intent);
// }
//
// private void parseIntent(Intent intent) {
// url = intent.getStringExtra(KEY_URL);
// title = intent.getStringExtra(KEY_TITLE);
//
// if (TextUtils.isEmpty(url)) {
// Tips.showToast("木有URL...");
// finish();
// }
// setTitle(TextUtils.isEmpty(title) ? getString(R.string.app_name) : title);
// }
//
// private void initWebSetting() {
// JsHandler jsHandler = new JsHandler(this, mWebView);
// mWebView.addJavascriptInterface(jsHandler, "JsHandler");
// }
//
// private void createView() {
// FloatView view = new FloatView(getApplicationContext());
//
// WindowManager wm = (WindowManager) getApplicationContext().getSystemService(Context.WINDOW_SERVICE);
//
// WindowManager.LayoutParams wmParams = new WindowManager.LayoutParams();
// wmParams.type = WindowManager.LayoutParams.TYPE_PHONE;
// wmParams.format = PixelFormat.RGBA_8888;
// wmParams.flags |= 8;
// wmParams.gravity = Gravity.RIGHT | Gravity.CENTER_VERTICAL;
// wmParams.x = 0;
// wmParams.y = 80;
// wmParams.width = ViewGroup.LayoutParams.WRAP_CONTENT;
// wmParams.height = ViewGroup.LayoutParams.WRAP_CONTENT;
//
// view.setOnClickListener(new View.OnClickListener() {
// @Override
// public void onClick(View v) {
// ZhuanlanApplication.getInstance().startActivity(new Intent("com.bxbxbai.zhuanlan.ui.activity.AboutActivity"));
// Log.i(TAG, "onclick");
// }
// });
//
// wm.addView(view, wmParams);
// }
//
// public static boolean start(Activity activity, String url, String title) {
// Intent intent = new Intent();
// intent.setClass(activity, WebActivity.class);
// intent.putExtra(KEY_URL, url);
// intent.putExtra(KEY_TITLE, title);
// activity.startActivity(intent);
//
// return true;
// }
//
// public static boolean start(Activity activity, String url) {
// return start(activity, url, null);
// }
// }
// Path: app/src/main/java/io/bxbxbai/zhuanlan/core/ZhuanLanWebViewClient.java
import android.app.Activity;
import android.graphics.Bitmap;
import android.webkit.WebResourceRequest;
import android.webkit.WebResourceResponse;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import io.bxbxbai.common.StopWatch;
import io.bxbxbai.zhuanlan.ui.WebActivity;
package io.bxbxbai.zhuanlan.core;
/**
*
* @author bxbxbai
*/
public class ZhuanLanWebViewClient extends WebViewClient {
private Activity mActivity;
public ZhuanLanWebViewClient(Activity activity) {
mActivity = activity;
}
@Override
public void onLoadResource(WebView view, String url) {
super.onLoadResource(view, url);
}
@Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
StopWatch.log("url " + url);
if (url != null && url.startsWith("orpheus")) {
return true;
}
if (url != null && url.startsWith("http")) { | WebActivity.start(mActivity, url); |
bxbxbai/ZhuanLan | app/src/main/java/io/bxbxbai/zhuanlan/ZhuanlanApplication.java | // Path: app/src/main/java/io/bxbxbai/zhuanlan/core/DataCenter.java
// public final class DataCenter {
//
// private static DataCenter instance;
//
// private DataBase db;
//
// private DataCenter(Context context, String dbName) {
// db = LiteOrm.newSingleInstance(context, dbName);
// }
//
// public static void init(Context context, String dbName) {
// if (instance == null) {
// synchronized (DataCenter.class) {
// if (instance == null) {
// instance = new DataCenter(context.getApplicationContext(), dbName);
// }
// }
// }
// }
//
// public static DataCenter instance() {
// if (instance == null) {
// throw new IllegalStateException("you must call LiteManager.init(context, dbName) first");
// }
// return instance;
// }
//
// public <T> long queryCount(Class<T> clazz) {
// return db.queryCount(clazz);
// }
//
// public <T> int clear(Class<T> clazz) {
// return db.delete(clazz);
// }
//
// public void save(Object o) {
// db.save(o);
// }
//
// public <T> List<T> queryAll(Class<T> clazz) {
// List<T> list = db.query(clazz);
// return list == null ? new ArrayList<T>() : list;
// }
//
// private class CacheContainer<T> extends HashMap<Class<T>, Map<String, T>> {
//
//
// }
//
// }
| import android.app.Application;
import android.view.Choreographer;
import com.facebook.stetho.Stetho;
import io.bxbxbai.common.StopWatch;
import io.bxbxbai.common.Tips;
import io.bxbxbai.zhuanlan.core.DataCenter; | package io.bxbxbai.zhuanlan;
/**
*
* @author bxbxbai
*/
public class ZhuanlanApplication extends Application {
private static ZhuanlanApplication mContext;
private static final Choreographer.FrameCallback FRAME_CALLBACK = new Choreographer.FrameCallback() {
@Override
public void doFrame(long frameTimeNanos) {
StopWatch.log("doFrame: " + frameTimeNanos);
}
};
@Override
public void onCreate() {
super.onCreate();
mContext = this;
Tips.init(this); | // Path: app/src/main/java/io/bxbxbai/zhuanlan/core/DataCenter.java
// public final class DataCenter {
//
// private static DataCenter instance;
//
// private DataBase db;
//
// private DataCenter(Context context, String dbName) {
// db = LiteOrm.newSingleInstance(context, dbName);
// }
//
// public static void init(Context context, String dbName) {
// if (instance == null) {
// synchronized (DataCenter.class) {
// if (instance == null) {
// instance = new DataCenter(context.getApplicationContext(), dbName);
// }
// }
// }
// }
//
// public static DataCenter instance() {
// if (instance == null) {
// throw new IllegalStateException("you must call LiteManager.init(context, dbName) first");
// }
// return instance;
// }
//
// public <T> long queryCount(Class<T> clazz) {
// return db.queryCount(clazz);
// }
//
// public <T> int clear(Class<T> clazz) {
// return db.delete(clazz);
// }
//
// public void save(Object o) {
// db.save(o);
// }
//
// public <T> List<T> queryAll(Class<T> clazz) {
// List<T> list = db.query(clazz);
// return list == null ? new ArrayList<T>() : list;
// }
//
// private class CacheContainer<T> extends HashMap<Class<T>, Map<String, T>> {
//
//
// }
//
// }
// Path: app/src/main/java/io/bxbxbai/zhuanlan/ZhuanlanApplication.java
import android.app.Application;
import android.view.Choreographer;
import com.facebook.stetho.Stetho;
import io.bxbxbai.common.StopWatch;
import io.bxbxbai.common.Tips;
import io.bxbxbai.zhuanlan.core.DataCenter;
package io.bxbxbai.zhuanlan;
/**
*
* @author bxbxbai
*/
public class ZhuanlanApplication extends Application {
private static ZhuanlanApplication mContext;
private static final Choreographer.FrameCallback FRAME_CALLBACK = new Choreographer.FrameCallback() {
@Override
public void doFrame(long frameTimeNanos) {
StopWatch.log("doFrame: " + frameTimeNanos);
}
};
@Override
public void onCreate() {
super.onCreate();
mContext = this;
Tips.init(this); | DataCenter.init(this, "zhuanlan.db"); |
bxbxbai/ZhuanLan | app/src/main/java/io/bxbxbai/zhuanlan/ui/MainActivity.java | // Path: app/src/main/java/io/bxbxbai/zhuanlan/widget/DrawerMenuContent.java
// public class DrawerMenuContent {
//
// public static final int DRAWER_MENU_COUNT = 3;
//
// private static final String FIELD_TITLE = "title";
// private static final String FIELD_ICON = "icon";
//
// private List<DrawerItem> items;
// private Class[] activities;
//
// public DrawerMenuContent(Context context) {
// activities = new Class[DRAWER_MENU_COUNT];
// items = new ArrayList<>(DRAWER_MENU_COUNT);
//
// activities[0] = SearchActivity.class;
// items.add(new DrawerItem(R.id.menu_search, context.getString(R.string.searching),
// R.drawable.ic_search_black_18dp));
//
// activities[1] = AllPeopleActivity.class;
// items.add(new DrawerItem(R.id.menu_all_people, context.getString(R.string.all_people),
// R.drawable.ic_supervisor_account_black_18dp));
//
// activities[2] = PostListActivity.class;
// items.add(new DrawerItem(R.id.menu_recent_news, context.getString(R.string.recent_news),
// R.drawable.ic_view_list_black_18dp));
// }
//
// public List<DrawerItem> getItems() {
// return items;
// }
//
// public Class getActivity(int pos) {
// if (0 <= pos && pos < activities.length) {
// return activities[pos];
// }
// return null;
// }
//
//
// public int getPosition(Class clazz) {
// for (int i = 0; i < activities.length; i++) {
// if (activities[i].equals(clazz)) {
// return i;
// }
// }
// return -1;
// }
//
// public static class DrawerItem {
// public int id;
// public String title;
// public int icon;
//
// private DrawerItem(int id, String title, @DrawableRes int icon) {
// this.id = id;
// this.title = title;
// this.icon = icon;
// }
// }
// }
//
// Path: app/src/main/java/io/bxbxbai/zhuanlan/widget/OnMenuListClickListener.java
// public class OnMenuListClickListener implements AdapterView.OnItemClickListener {
//
// private Activity mActivity;
// private DrawerLayout mDrawerLayout;
//
// public OnMenuListClickListener(Activity activity, DrawerLayout drawerLayout) {
// mActivity = activity;
// mDrawerLayout = drawerLayout;
// }
//
// @Override
// public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
// DrawerMenuContent.DrawerItem item = (DrawerMenuContent.DrawerItem) view.getTag(R.id.key_data);
//
// if (mDrawerLayout != null && mDrawerLayout.isDrawerOpen(GravityCompat.START)) {
// mDrawerLayout.closeDrawers();
// }
//
// switch (item.id) {
// case R.id.menu_search :
// Tips.showToast("Coming soon...");
// break;
//
// case R.id.menu_all_people:
// AllPeopleActivity.start(mActivity);
// break;
//
// case R.id.menu_recent_news :
// RecentPostListActivity.start(mActivity);
// break;
//
// default:break;
// }
// }
// }
| import android.app.Activity;
import android.app.FragmentManager;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.ListView;
import butterknife.Bind;
import butterknife.ButterKnife;
import io.bxbxbai.common.Tips;
import io.bxbxbai.common.utils.CommonExecutor;
import io.bxbxbai.common.utils.PrefUtils;
import io.bxbxbai.zhuanlan.R;
import io.bxbxbai.zhuanlan.widget.DrawerMenuContent;
import io.bxbxbai.zhuanlan.widget.MenuAdapter;
import io.bxbxbai.zhuanlan.widget.OnMenuListClickListener; | package io.bxbxbai.zhuanlan.ui;
public class MainActivity extends BaseActivity {
@Bind(R.id.drawer_list)
protected ListView listView;
@Bind(R.id.toolbar)
protected Toolbar toolbar;
@Bind(R.id.drawerLayout)
protected DrawerLayout drawerLayout;
private ActionBarDrawerToggle actionBarDrawerToggle;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ButterKnife.bind(this);
// ChoreographerHelper.getInstance(this).start();
initToolbarAndDrawer();
| // Path: app/src/main/java/io/bxbxbai/zhuanlan/widget/DrawerMenuContent.java
// public class DrawerMenuContent {
//
// public static final int DRAWER_MENU_COUNT = 3;
//
// private static final String FIELD_TITLE = "title";
// private static final String FIELD_ICON = "icon";
//
// private List<DrawerItem> items;
// private Class[] activities;
//
// public DrawerMenuContent(Context context) {
// activities = new Class[DRAWER_MENU_COUNT];
// items = new ArrayList<>(DRAWER_MENU_COUNT);
//
// activities[0] = SearchActivity.class;
// items.add(new DrawerItem(R.id.menu_search, context.getString(R.string.searching),
// R.drawable.ic_search_black_18dp));
//
// activities[1] = AllPeopleActivity.class;
// items.add(new DrawerItem(R.id.menu_all_people, context.getString(R.string.all_people),
// R.drawable.ic_supervisor_account_black_18dp));
//
// activities[2] = PostListActivity.class;
// items.add(new DrawerItem(R.id.menu_recent_news, context.getString(R.string.recent_news),
// R.drawable.ic_view_list_black_18dp));
// }
//
// public List<DrawerItem> getItems() {
// return items;
// }
//
// public Class getActivity(int pos) {
// if (0 <= pos && pos < activities.length) {
// return activities[pos];
// }
// return null;
// }
//
//
// public int getPosition(Class clazz) {
// for (int i = 0; i < activities.length; i++) {
// if (activities[i].equals(clazz)) {
// return i;
// }
// }
// return -1;
// }
//
// public static class DrawerItem {
// public int id;
// public String title;
// public int icon;
//
// private DrawerItem(int id, String title, @DrawableRes int icon) {
// this.id = id;
// this.title = title;
// this.icon = icon;
// }
// }
// }
//
// Path: app/src/main/java/io/bxbxbai/zhuanlan/widget/OnMenuListClickListener.java
// public class OnMenuListClickListener implements AdapterView.OnItemClickListener {
//
// private Activity mActivity;
// private DrawerLayout mDrawerLayout;
//
// public OnMenuListClickListener(Activity activity, DrawerLayout drawerLayout) {
// mActivity = activity;
// mDrawerLayout = drawerLayout;
// }
//
// @Override
// public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
// DrawerMenuContent.DrawerItem item = (DrawerMenuContent.DrawerItem) view.getTag(R.id.key_data);
//
// if (mDrawerLayout != null && mDrawerLayout.isDrawerOpen(GravityCompat.START)) {
// mDrawerLayout.closeDrawers();
// }
//
// switch (item.id) {
// case R.id.menu_search :
// Tips.showToast("Coming soon...");
// break;
//
// case R.id.menu_all_people:
// AllPeopleActivity.start(mActivity);
// break;
//
// case R.id.menu_recent_news :
// RecentPostListActivity.start(mActivity);
// break;
//
// default:break;
// }
// }
// }
// Path: app/src/main/java/io/bxbxbai/zhuanlan/ui/MainActivity.java
import android.app.Activity;
import android.app.FragmentManager;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.ListView;
import butterknife.Bind;
import butterknife.ButterKnife;
import io.bxbxbai.common.Tips;
import io.bxbxbai.common.utils.CommonExecutor;
import io.bxbxbai.common.utils.PrefUtils;
import io.bxbxbai.zhuanlan.R;
import io.bxbxbai.zhuanlan.widget.DrawerMenuContent;
import io.bxbxbai.zhuanlan.widget.MenuAdapter;
import io.bxbxbai.zhuanlan.widget.OnMenuListClickListener;
package io.bxbxbai.zhuanlan.ui;
public class MainActivity extends BaseActivity {
@Bind(R.id.drawer_list)
protected ListView listView;
@Bind(R.id.toolbar)
protected Toolbar toolbar;
@Bind(R.id.drawerLayout)
protected DrawerLayout drawerLayout;
private ActionBarDrawerToggle actionBarDrawerToggle;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ButterKnife.bind(this);
// ChoreographerHelper.getInstance(this).start();
initToolbarAndDrawer();
| DrawerMenuContent content = new DrawerMenuContent(this); |
bxbxbai/ZhuanLan | app/src/main/java/io/bxbxbai/zhuanlan/ui/MainActivity.java | // Path: app/src/main/java/io/bxbxbai/zhuanlan/widget/DrawerMenuContent.java
// public class DrawerMenuContent {
//
// public static final int DRAWER_MENU_COUNT = 3;
//
// private static final String FIELD_TITLE = "title";
// private static final String FIELD_ICON = "icon";
//
// private List<DrawerItem> items;
// private Class[] activities;
//
// public DrawerMenuContent(Context context) {
// activities = new Class[DRAWER_MENU_COUNT];
// items = new ArrayList<>(DRAWER_MENU_COUNT);
//
// activities[0] = SearchActivity.class;
// items.add(new DrawerItem(R.id.menu_search, context.getString(R.string.searching),
// R.drawable.ic_search_black_18dp));
//
// activities[1] = AllPeopleActivity.class;
// items.add(new DrawerItem(R.id.menu_all_people, context.getString(R.string.all_people),
// R.drawable.ic_supervisor_account_black_18dp));
//
// activities[2] = PostListActivity.class;
// items.add(new DrawerItem(R.id.menu_recent_news, context.getString(R.string.recent_news),
// R.drawable.ic_view_list_black_18dp));
// }
//
// public List<DrawerItem> getItems() {
// return items;
// }
//
// public Class getActivity(int pos) {
// if (0 <= pos && pos < activities.length) {
// return activities[pos];
// }
// return null;
// }
//
//
// public int getPosition(Class clazz) {
// for (int i = 0; i < activities.length; i++) {
// if (activities[i].equals(clazz)) {
// return i;
// }
// }
// return -1;
// }
//
// public static class DrawerItem {
// public int id;
// public String title;
// public int icon;
//
// private DrawerItem(int id, String title, @DrawableRes int icon) {
// this.id = id;
// this.title = title;
// this.icon = icon;
// }
// }
// }
//
// Path: app/src/main/java/io/bxbxbai/zhuanlan/widget/OnMenuListClickListener.java
// public class OnMenuListClickListener implements AdapterView.OnItemClickListener {
//
// private Activity mActivity;
// private DrawerLayout mDrawerLayout;
//
// public OnMenuListClickListener(Activity activity, DrawerLayout drawerLayout) {
// mActivity = activity;
// mDrawerLayout = drawerLayout;
// }
//
// @Override
// public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
// DrawerMenuContent.DrawerItem item = (DrawerMenuContent.DrawerItem) view.getTag(R.id.key_data);
//
// if (mDrawerLayout != null && mDrawerLayout.isDrawerOpen(GravityCompat.START)) {
// mDrawerLayout.closeDrawers();
// }
//
// switch (item.id) {
// case R.id.menu_search :
// Tips.showToast("Coming soon...");
// break;
//
// case R.id.menu_all_people:
// AllPeopleActivity.start(mActivity);
// break;
//
// case R.id.menu_recent_news :
// RecentPostListActivity.start(mActivity);
// break;
//
// default:break;
// }
// }
// }
| import android.app.Activity;
import android.app.FragmentManager;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.ListView;
import butterknife.Bind;
import butterknife.ButterKnife;
import io.bxbxbai.common.Tips;
import io.bxbxbai.common.utils.CommonExecutor;
import io.bxbxbai.common.utils.PrefUtils;
import io.bxbxbai.zhuanlan.R;
import io.bxbxbai.zhuanlan.widget.DrawerMenuContent;
import io.bxbxbai.zhuanlan.widget.MenuAdapter;
import io.bxbxbai.zhuanlan.widget.OnMenuListClickListener; | package io.bxbxbai.zhuanlan.ui;
public class MainActivity extends BaseActivity {
@Bind(R.id.drawer_list)
protected ListView listView;
@Bind(R.id.toolbar)
protected Toolbar toolbar;
@Bind(R.id.drawerLayout)
protected DrawerLayout drawerLayout;
private ActionBarDrawerToggle actionBarDrawerToggle;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ButterKnife.bind(this);
// ChoreographerHelper.getInstance(this).start();
initToolbarAndDrawer();
DrawerMenuContent content = new DrawerMenuContent(this);
listView.setAdapter(new MenuAdapter(this, content.getItems())); | // Path: app/src/main/java/io/bxbxbai/zhuanlan/widget/DrawerMenuContent.java
// public class DrawerMenuContent {
//
// public static final int DRAWER_MENU_COUNT = 3;
//
// private static final String FIELD_TITLE = "title";
// private static final String FIELD_ICON = "icon";
//
// private List<DrawerItem> items;
// private Class[] activities;
//
// public DrawerMenuContent(Context context) {
// activities = new Class[DRAWER_MENU_COUNT];
// items = new ArrayList<>(DRAWER_MENU_COUNT);
//
// activities[0] = SearchActivity.class;
// items.add(new DrawerItem(R.id.menu_search, context.getString(R.string.searching),
// R.drawable.ic_search_black_18dp));
//
// activities[1] = AllPeopleActivity.class;
// items.add(new DrawerItem(R.id.menu_all_people, context.getString(R.string.all_people),
// R.drawable.ic_supervisor_account_black_18dp));
//
// activities[2] = PostListActivity.class;
// items.add(new DrawerItem(R.id.menu_recent_news, context.getString(R.string.recent_news),
// R.drawable.ic_view_list_black_18dp));
// }
//
// public List<DrawerItem> getItems() {
// return items;
// }
//
// public Class getActivity(int pos) {
// if (0 <= pos && pos < activities.length) {
// return activities[pos];
// }
// return null;
// }
//
//
// public int getPosition(Class clazz) {
// for (int i = 0; i < activities.length; i++) {
// if (activities[i].equals(clazz)) {
// return i;
// }
// }
// return -1;
// }
//
// public static class DrawerItem {
// public int id;
// public String title;
// public int icon;
//
// private DrawerItem(int id, String title, @DrawableRes int icon) {
// this.id = id;
// this.title = title;
// this.icon = icon;
// }
// }
// }
//
// Path: app/src/main/java/io/bxbxbai/zhuanlan/widget/OnMenuListClickListener.java
// public class OnMenuListClickListener implements AdapterView.OnItemClickListener {
//
// private Activity mActivity;
// private DrawerLayout mDrawerLayout;
//
// public OnMenuListClickListener(Activity activity, DrawerLayout drawerLayout) {
// mActivity = activity;
// mDrawerLayout = drawerLayout;
// }
//
// @Override
// public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
// DrawerMenuContent.DrawerItem item = (DrawerMenuContent.DrawerItem) view.getTag(R.id.key_data);
//
// if (mDrawerLayout != null && mDrawerLayout.isDrawerOpen(GravityCompat.START)) {
// mDrawerLayout.closeDrawers();
// }
//
// switch (item.id) {
// case R.id.menu_search :
// Tips.showToast("Coming soon...");
// break;
//
// case R.id.menu_all_people:
// AllPeopleActivity.start(mActivity);
// break;
//
// case R.id.menu_recent_news :
// RecentPostListActivity.start(mActivity);
// break;
//
// default:break;
// }
// }
// }
// Path: app/src/main/java/io/bxbxbai/zhuanlan/ui/MainActivity.java
import android.app.Activity;
import android.app.FragmentManager;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.ListView;
import butterknife.Bind;
import butterknife.ButterKnife;
import io.bxbxbai.common.Tips;
import io.bxbxbai.common.utils.CommonExecutor;
import io.bxbxbai.common.utils.PrefUtils;
import io.bxbxbai.zhuanlan.R;
import io.bxbxbai.zhuanlan.widget.DrawerMenuContent;
import io.bxbxbai.zhuanlan.widget.MenuAdapter;
import io.bxbxbai.zhuanlan.widget.OnMenuListClickListener;
package io.bxbxbai.zhuanlan.ui;
public class MainActivity extends BaseActivity {
@Bind(R.id.drawer_list)
protected ListView listView;
@Bind(R.id.toolbar)
protected Toolbar toolbar;
@Bind(R.id.drawerLayout)
protected DrawerLayout drawerLayout;
private ActionBarDrawerToggle actionBarDrawerToggle;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ButterKnife.bind(this);
// ChoreographerHelper.getInstance(this).start();
initToolbarAndDrawer();
DrawerMenuContent content = new DrawerMenuContent(this);
listView.setAdapter(new MenuAdapter(this, content.getItems())); | listView.setOnItemClickListener(new OnMenuListClickListener(this, drawerLayout)); |
bxbxbai/ZhuanLan | app/src/androidTest/java/io/bxbxbai/zhuanlan/io/bxbxbai/zhuanlan/test/DateConvertTest.java | // Path: app/src/main/java/io/bxbxbai/zhuanlan/utils/Utils.java
// public class Utils {
//
// private Utils() {}
//
// private static final int MINUTE = 60;
// private static final int HOUR = MINUTE * 60;
// private static final int DAY = HOUR * 24;
// private static final int MONTH = DAY * 30;
// private static final int YEAR = MONTH * 12;
//
// private static final DateFormat FORMAT = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZ");
//
//
// public static String getAuthorAvatarUrl(String origin, String userId, String size) {
// origin = origin.replace(ZhuanLanApi.TEMPLATE_ID, userId);
// return origin.replace(ZhuanLanApi.TEMPLATE_SIZE, size);
// }
//
// public static String convertPublishTime(String time) {
// try {
// long s = TimeUnit.MILLISECONDS.toSeconds(
// new Date().getTime() - FORMAT.parse(time).getTime());
//
// long count = s / YEAR;
// if (count != 0) {
// return count + "年前";
// }
//
// count = s / MONTH;
// if (count != 0) {
// return count + "月前";
// }
//
// count = s / DAY;
// if (count != 0) {
// return count + "天前";
// }
//
// return "今天";
// } catch (ParseException e) {
// e.printStackTrace();
// }
// return "未知时间";
// }
//
// public static boolean withinDays(String time, int days) {
// try {
// long s = TimeUnit.MILLISECONDS.toSeconds(
// new Date().getTime() - FORMAT.parse(time).getTime());
// long count = s / DAY;
// if (0 < count && count <= days) {
// return true;
// }
// } catch (ParseException e) {
// e.printStackTrace();
// }
// return false;
// }
//
// public static int compareTime(String a, String b) {
// try {
// long timeA = TimeUnit.MILLISECONDS.toSeconds(
// new Date().getTime() - FORMAT.parse(a).getTime());
// long timeB = TimeUnit.MILLISECONDS.toSeconds(
// new Date().getTime() - FORMAT.parse(b).getTime());
//
// return timeA >= timeB ? 1 : -1;
// } catch (ParseException e) {
// e.printStackTrace();
// }
// return 0;
// }
//
// public static String removeHtmlCode(String source) {
// if (TextUtils.isEmpty(source)) {
// return source;
// }
//
// StringBuilder dest = new StringBuilder();
// for (int i = 0, flag = 0; i < source.length(); i++) {
// char c = source.charAt(i);
//
// if (c == '<') {
// flag = 1;
// }
//
// if (c == '>') {
// flag = 0;
// continue;
// }
//
// if (flag == 1) {
// continue;
// }
// dest.append(c);
// }
//
// return dest.toString();
// }
// }
| import android.test.AndroidTestCase;
import io.bxbxbai.common.StopWatch;
import io.bxbxbai.zhuanlan.utils.Utils;
| package io.bxbxbai.zhuanlan.io.bxbxbai.zhuanlan.test;
/**
* @author bxbxbai
*/
public class DateConvertTest extends AndroidTestCase {
public void testDateConvert() {
// <td><code>"yyyy-MM-dd'T'HH:mm:ssXXX"</code>
// * <td><code>2001-07-04T12:08:56.235-07:00</code>
String str = "2015-03-18T14:43:50+08:00";
| // Path: app/src/main/java/io/bxbxbai/zhuanlan/utils/Utils.java
// public class Utils {
//
// private Utils() {}
//
// private static final int MINUTE = 60;
// private static final int HOUR = MINUTE * 60;
// private static final int DAY = HOUR * 24;
// private static final int MONTH = DAY * 30;
// private static final int YEAR = MONTH * 12;
//
// private static final DateFormat FORMAT = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZ");
//
//
// public static String getAuthorAvatarUrl(String origin, String userId, String size) {
// origin = origin.replace(ZhuanLanApi.TEMPLATE_ID, userId);
// return origin.replace(ZhuanLanApi.TEMPLATE_SIZE, size);
// }
//
// public static String convertPublishTime(String time) {
// try {
// long s = TimeUnit.MILLISECONDS.toSeconds(
// new Date().getTime() - FORMAT.parse(time).getTime());
//
// long count = s / YEAR;
// if (count != 0) {
// return count + "年前";
// }
//
// count = s / MONTH;
// if (count != 0) {
// return count + "月前";
// }
//
// count = s / DAY;
// if (count != 0) {
// return count + "天前";
// }
//
// return "今天";
// } catch (ParseException e) {
// e.printStackTrace();
// }
// return "未知时间";
// }
//
// public static boolean withinDays(String time, int days) {
// try {
// long s = TimeUnit.MILLISECONDS.toSeconds(
// new Date().getTime() - FORMAT.parse(time).getTime());
// long count = s / DAY;
// if (0 < count && count <= days) {
// return true;
// }
// } catch (ParseException e) {
// e.printStackTrace();
// }
// return false;
// }
//
// public static int compareTime(String a, String b) {
// try {
// long timeA = TimeUnit.MILLISECONDS.toSeconds(
// new Date().getTime() - FORMAT.parse(a).getTime());
// long timeB = TimeUnit.MILLISECONDS.toSeconds(
// new Date().getTime() - FORMAT.parse(b).getTime());
//
// return timeA >= timeB ? 1 : -1;
// } catch (ParseException e) {
// e.printStackTrace();
// }
// return 0;
// }
//
// public static String removeHtmlCode(String source) {
// if (TextUtils.isEmpty(source)) {
// return source;
// }
//
// StringBuilder dest = new StringBuilder();
// for (int i = 0, flag = 0; i < source.length(); i++) {
// char c = source.charAt(i);
//
// if (c == '<') {
// flag = 1;
// }
//
// if (c == '>') {
// flag = 0;
// continue;
// }
//
// if (flag == 1) {
// continue;
// }
// dest.append(c);
// }
//
// return dest.toString();
// }
// }
// Path: app/src/androidTest/java/io/bxbxbai/zhuanlan/io/bxbxbai/zhuanlan/test/DateConvertTest.java
import android.test.AndroidTestCase;
import io.bxbxbai.common.StopWatch;
import io.bxbxbai.zhuanlan.utils.Utils;
package io.bxbxbai.zhuanlan.io.bxbxbai.zhuanlan.test;
/**
* @author bxbxbai
*/
public class DateConvertTest extends AndroidTestCase {
public void testDateConvert() {
// <td><code>"yyyy-MM-dd'T'HH:mm:ssXXX"</code>
// * <td><code>2001-07-04T12:08:56.235-07:00</code>
String str = "2015-03-18T14:43:50+08:00";
| StopWatch.log(Utils.convertPublishTime(str));
|
longzheng/PTVGlass | Components/googleglass-1.6/lib/android/16/content/google-gdk/samples/ApiDemo/tests/src/com/google/android/glass/sample/apidemo/ApiDemoActivityTest.java | // Path: Components/googleglass-1.6/lib/android/16/content/google-gdk/samples/ApiDemo/src/com/google/android/glass/sample/apidemo/card/CardsActivity.java
// public final class CardsActivity extends Activity {
//
// private CardScrollView mCardScroller;
//
// @Override
// protected void onCreate(Bundle bundle) {
// super.onCreate(bundle);
//
// mCardScroller = new CardScrollView(this);
// mCardScroller.setAdapter(new CardAdapter(createCards(this)));
// setContentView(mCardScroller);
// }
//
// /**
// * Create list of cards that showcase different type of {@link Card} API.
// */
// private List<Card> createCards(Context context) {
// ArrayList<Card> cards = new ArrayList<Card>();
// cards.add(getImagesCard(context)
// .setImageLayout(ImageLayout.LEFT)
// .setText(R.string.text_left_images_layout_card));
// cards.add(getImagesCard(context)
// .setImageLayout(ImageLayout.FULL)
// .setText(R.string.text_full_images_layout_card));
// return cards;
// }
//
// private Card getImagesCard(Context context) {
// Card card = new Card(context);
// card.addImage(R.drawable.codemonkey1);
// card.addImage(R.drawable.codemonkey2);
// card.addImage(R.drawable.codemonkey3);
// card.addImage(R.drawable.codemonkey4);
// card.addImage(R.drawable.codemonkey5);
// return card;
// }
//
// @Override
// protected void onResume() {
// super.onResume();
// mCardScroller.activate();
// }
//
// @Override
// protected void onPause() {
// mCardScroller.deactivate();
// super.onPause();
// }
// }
//
// Path: Components/googleglass-1.6/lib/android/16/content/google-gdk/samples/ApiDemo/src/com/google/android/glass/sample/apidemo/theming/ThemingActivity.java
// public final class ThemingActivity extends Activity {
//
// private CardScrollView mCardScroller;
//
// @Override
// protected void onCreate(Bundle bundle) {
// super.onCreate(bundle);
// mCardScroller = new CardScrollView(this);
// mCardScroller.setAdapter(new LayoutAdapter(this));
// setContentView(mCardScroller);
// }
//
// @Override
// protected void onResume() {
// super.onResume();
// mCardScroller.activate();
// }
//
// @Override
// protected void onPause() {
// mCardScroller.deactivate();
// super.onPause();
// }
// }
| import com.google.android.glass.sample.apidemo.card.CardsActivity;
import com.google.android.glass.sample.apidemo.theming.ThemingActivity;
import com.google.android.glass.sample.apidemo.touchpad.SelectGestureDemoActivity;
import android.app.Activity;
import android.app.Instrumentation;
import android.test.ActivityInstrumentationTestCase2; | /*
* Copyright (C) 2014 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.android.glass.sample.apidemo;
/**
* Unit tests for {@link ApiDemoActivity}.
*/
public class ApiDemoActivityTest extends ActivityInstrumentationTestCase2<ApiDemoActivity> {
private static final int MONITOR_TIMEOUT = 5 * 1000;
private Instrumentation.ActivityMonitor mCardsActivityMonitor;
private Instrumentation.ActivityMonitor mDetectorActivityMonitor;
private Instrumentation.ActivityMonitor mThemingActivityMonitor;
public ApiDemoActivityTest() {
super(ApiDemoActivity.class);
}
@Override
protected void setUp() throws Exception {
super.setUp();
mCardsActivityMonitor = new Instrumentation.ActivityMonitor( | // Path: Components/googleglass-1.6/lib/android/16/content/google-gdk/samples/ApiDemo/src/com/google/android/glass/sample/apidemo/card/CardsActivity.java
// public final class CardsActivity extends Activity {
//
// private CardScrollView mCardScroller;
//
// @Override
// protected void onCreate(Bundle bundle) {
// super.onCreate(bundle);
//
// mCardScroller = new CardScrollView(this);
// mCardScroller.setAdapter(new CardAdapter(createCards(this)));
// setContentView(mCardScroller);
// }
//
// /**
// * Create list of cards that showcase different type of {@link Card} API.
// */
// private List<Card> createCards(Context context) {
// ArrayList<Card> cards = new ArrayList<Card>();
// cards.add(getImagesCard(context)
// .setImageLayout(ImageLayout.LEFT)
// .setText(R.string.text_left_images_layout_card));
// cards.add(getImagesCard(context)
// .setImageLayout(ImageLayout.FULL)
// .setText(R.string.text_full_images_layout_card));
// return cards;
// }
//
// private Card getImagesCard(Context context) {
// Card card = new Card(context);
// card.addImage(R.drawable.codemonkey1);
// card.addImage(R.drawable.codemonkey2);
// card.addImage(R.drawable.codemonkey3);
// card.addImage(R.drawable.codemonkey4);
// card.addImage(R.drawable.codemonkey5);
// return card;
// }
//
// @Override
// protected void onResume() {
// super.onResume();
// mCardScroller.activate();
// }
//
// @Override
// protected void onPause() {
// mCardScroller.deactivate();
// super.onPause();
// }
// }
//
// Path: Components/googleglass-1.6/lib/android/16/content/google-gdk/samples/ApiDemo/src/com/google/android/glass/sample/apidemo/theming/ThemingActivity.java
// public final class ThemingActivity extends Activity {
//
// private CardScrollView mCardScroller;
//
// @Override
// protected void onCreate(Bundle bundle) {
// super.onCreate(bundle);
// mCardScroller = new CardScrollView(this);
// mCardScroller.setAdapter(new LayoutAdapter(this));
// setContentView(mCardScroller);
// }
//
// @Override
// protected void onResume() {
// super.onResume();
// mCardScroller.activate();
// }
//
// @Override
// protected void onPause() {
// mCardScroller.deactivate();
// super.onPause();
// }
// }
// Path: Components/googleglass-1.6/lib/android/16/content/google-gdk/samples/ApiDemo/tests/src/com/google/android/glass/sample/apidemo/ApiDemoActivityTest.java
import com.google.android.glass.sample.apidemo.card.CardsActivity;
import com.google.android.glass.sample.apidemo.theming.ThemingActivity;
import com.google.android.glass.sample.apidemo.touchpad.SelectGestureDemoActivity;
import android.app.Activity;
import android.app.Instrumentation;
import android.test.ActivityInstrumentationTestCase2;
/*
* Copyright (C) 2014 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.android.glass.sample.apidemo;
/**
* Unit tests for {@link ApiDemoActivity}.
*/
public class ApiDemoActivityTest extends ActivityInstrumentationTestCase2<ApiDemoActivity> {
private static final int MONITOR_TIMEOUT = 5 * 1000;
private Instrumentation.ActivityMonitor mCardsActivityMonitor;
private Instrumentation.ActivityMonitor mDetectorActivityMonitor;
private Instrumentation.ActivityMonitor mThemingActivityMonitor;
public ApiDemoActivityTest() {
super(ApiDemoActivity.class);
}
@Override
protected void setUp() throws Exception {
super.setUp();
mCardsActivityMonitor = new Instrumentation.ActivityMonitor( | CardsActivity.class.getName(), null, false); |
longzheng/PTVGlass | Components/googleglass-1.6/lib/android/16/content/google-gdk/samples/ApiDemo/tests/src/com/google/android/glass/sample/apidemo/ApiDemoActivityTest.java | // Path: Components/googleglass-1.6/lib/android/16/content/google-gdk/samples/ApiDemo/src/com/google/android/glass/sample/apidemo/card/CardsActivity.java
// public final class CardsActivity extends Activity {
//
// private CardScrollView mCardScroller;
//
// @Override
// protected void onCreate(Bundle bundle) {
// super.onCreate(bundle);
//
// mCardScroller = new CardScrollView(this);
// mCardScroller.setAdapter(new CardAdapter(createCards(this)));
// setContentView(mCardScroller);
// }
//
// /**
// * Create list of cards that showcase different type of {@link Card} API.
// */
// private List<Card> createCards(Context context) {
// ArrayList<Card> cards = new ArrayList<Card>();
// cards.add(getImagesCard(context)
// .setImageLayout(ImageLayout.LEFT)
// .setText(R.string.text_left_images_layout_card));
// cards.add(getImagesCard(context)
// .setImageLayout(ImageLayout.FULL)
// .setText(R.string.text_full_images_layout_card));
// return cards;
// }
//
// private Card getImagesCard(Context context) {
// Card card = new Card(context);
// card.addImage(R.drawable.codemonkey1);
// card.addImage(R.drawable.codemonkey2);
// card.addImage(R.drawable.codemonkey3);
// card.addImage(R.drawable.codemonkey4);
// card.addImage(R.drawable.codemonkey5);
// return card;
// }
//
// @Override
// protected void onResume() {
// super.onResume();
// mCardScroller.activate();
// }
//
// @Override
// protected void onPause() {
// mCardScroller.deactivate();
// super.onPause();
// }
// }
//
// Path: Components/googleglass-1.6/lib/android/16/content/google-gdk/samples/ApiDemo/src/com/google/android/glass/sample/apidemo/theming/ThemingActivity.java
// public final class ThemingActivity extends Activity {
//
// private CardScrollView mCardScroller;
//
// @Override
// protected void onCreate(Bundle bundle) {
// super.onCreate(bundle);
// mCardScroller = new CardScrollView(this);
// mCardScroller.setAdapter(new LayoutAdapter(this));
// setContentView(mCardScroller);
// }
//
// @Override
// protected void onResume() {
// super.onResume();
// mCardScroller.activate();
// }
//
// @Override
// protected void onPause() {
// mCardScroller.deactivate();
// super.onPause();
// }
// }
| import com.google.android.glass.sample.apidemo.card.CardsActivity;
import com.google.android.glass.sample.apidemo.theming.ThemingActivity;
import com.google.android.glass.sample.apidemo.touchpad.SelectGestureDemoActivity;
import android.app.Activity;
import android.app.Instrumentation;
import android.test.ActivityInstrumentationTestCase2; | /*
* Copyright (C) 2014 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.android.glass.sample.apidemo;
/**
* Unit tests for {@link ApiDemoActivity}.
*/
public class ApiDemoActivityTest extends ActivityInstrumentationTestCase2<ApiDemoActivity> {
private static final int MONITOR_TIMEOUT = 5 * 1000;
private Instrumentation.ActivityMonitor mCardsActivityMonitor;
private Instrumentation.ActivityMonitor mDetectorActivityMonitor;
private Instrumentation.ActivityMonitor mThemingActivityMonitor;
public ApiDemoActivityTest() {
super(ApiDemoActivity.class);
}
@Override
protected void setUp() throws Exception {
super.setUp();
mCardsActivityMonitor = new Instrumentation.ActivityMonitor(
CardsActivity.class.getName(), null, false);
mDetectorActivityMonitor = new Instrumentation.ActivityMonitor(
SelectGestureDemoActivity.class.getName(), null, false);
mThemingActivityMonitor = new Instrumentation.ActivityMonitor( | // Path: Components/googleglass-1.6/lib/android/16/content/google-gdk/samples/ApiDemo/src/com/google/android/glass/sample/apidemo/card/CardsActivity.java
// public final class CardsActivity extends Activity {
//
// private CardScrollView mCardScroller;
//
// @Override
// protected void onCreate(Bundle bundle) {
// super.onCreate(bundle);
//
// mCardScroller = new CardScrollView(this);
// mCardScroller.setAdapter(new CardAdapter(createCards(this)));
// setContentView(mCardScroller);
// }
//
// /**
// * Create list of cards that showcase different type of {@link Card} API.
// */
// private List<Card> createCards(Context context) {
// ArrayList<Card> cards = new ArrayList<Card>();
// cards.add(getImagesCard(context)
// .setImageLayout(ImageLayout.LEFT)
// .setText(R.string.text_left_images_layout_card));
// cards.add(getImagesCard(context)
// .setImageLayout(ImageLayout.FULL)
// .setText(R.string.text_full_images_layout_card));
// return cards;
// }
//
// private Card getImagesCard(Context context) {
// Card card = new Card(context);
// card.addImage(R.drawable.codemonkey1);
// card.addImage(R.drawable.codemonkey2);
// card.addImage(R.drawable.codemonkey3);
// card.addImage(R.drawable.codemonkey4);
// card.addImage(R.drawable.codemonkey5);
// return card;
// }
//
// @Override
// protected void onResume() {
// super.onResume();
// mCardScroller.activate();
// }
//
// @Override
// protected void onPause() {
// mCardScroller.deactivate();
// super.onPause();
// }
// }
//
// Path: Components/googleglass-1.6/lib/android/16/content/google-gdk/samples/ApiDemo/src/com/google/android/glass/sample/apidemo/theming/ThemingActivity.java
// public final class ThemingActivity extends Activity {
//
// private CardScrollView mCardScroller;
//
// @Override
// protected void onCreate(Bundle bundle) {
// super.onCreate(bundle);
// mCardScroller = new CardScrollView(this);
// mCardScroller.setAdapter(new LayoutAdapter(this));
// setContentView(mCardScroller);
// }
//
// @Override
// protected void onResume() {
// super.onResume();
// mCardScroller.activate();
// }
//
// @Override
// protected void onPause() {
// mCardScroller.deactivate();
// super.onPause();
// }
// }
// Path: Components/googleglass-1.6/lib/android/16/content/google-gdk/samples/ApiDemo/tests/src/com/google/android/glass/sample/apidemo/ApiDemoActivityTest.java
import com.google.android.glass.sample.apidemo.card.CardsActivity;
import com.google.android.glass.sample.apidemo.theming.ThemingActivity;
import com.google.android.glass.sample.apidemo.touchpad.SelectGestureDemoActivity;
import android.app.Activity;
import android.app.Instrumentation;
import android.test.ActivityInstrumentationTestCase2;
/*
* Copyright (C) 2014 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.android.glass.sample.apidemo;
/**
* Unit tests for {@link ApiDemoActivity}.
*/
public class ApiDemoActivityTest extends ActivityInstrumentationTestCase2<ApiDemoActivity> {
private static final int MONITOR_TIMEOUT = 5 * 1000;
private Instrumentation.ActivityMonitor mCardsActivityMonitor;
private Instrumentation.ActivityMonitor mDetectorActivityMonitor;
private Instrumentation.ActivityMonitor mThemingActivityMonitor;
public ApiDemoActivityTest() {
super(ApiDemoActivity.class);
}
@Override
protected void setUp() throws Exception {
super.setUp();
mCardsActivityMonitor = new Instrumentation.ActivityMonitor(
CardsActivity.class.getName(), null, false);
mDetectorActivityMonitor = new Instrumentation.ActivityMonitor(
SelectGestureDemoActivity.class.getName(), null, false);
mThemingActivityMonitor = new Instrumentation.ActivityMonitor( | ThemingActivity.class.getName(), null, false); |
longzheng/PTVGlass | Components/googleglass-1.6/lib/android/16/content/google-gdk/samples/ApiDemo/src/com/google/android/glass/sample/apidemo/ApiDemoActivity.java | // Path: Components/googleglass-1.6/lib/android/16/content/google-gdk/samples/ApiDemo/src/com/google/android/glass/sample/apidemo/card/CardsActivity.java
// public final class CardsActivity extends Activity {
//
// private CardScrollView mCardScroller;
//
// @Override
// protected void onCreate(Bundle bundle) {
// super.onCreate(bundle);
//
// mCardScroller = new CardScrollView(this);
// mCardScroller.setAdapter(new CardAdapter(createCards(this)));
// setContentView(mCardScroller);
// }
//
// /**
// * Create list of cards that showcase different type of {@link Card} API.
// */
// private List<Card> createCards(Context context) {
// ArrayList<Card> cards = new ArrayList<Card>();
// cards.add(getImagesCard(context)
// .setImageLayout(ImageLayout.LEFT)
// .setText(R.string.text_left_images_layout_card));
// cards.add(getImagesCard(context)
// .setImageLayout(ImageLayout.FULL)
// .setText(R.string.text_full_images_layout_card));
// return cards;
// }
//
// private Card getImagesCard(Context context) {
// Card card = new Card(context);
// card.addImage(R.drawable.codemonkey1);
// card.addImage(R.drawable.codemonkey2);
// card.addImage(R.drawable.codemonkey3);
// card.addImage(R.drawable.codemonkey4);
// card.addImage(R.drawable.codemonkey5);
// return card;
// }
//
// @Override
// protected void onResume() {
// super.onResume();
// mCardScroller.activate();
// }
//
// @Override
// protected void onPause() {
// mCardScroller.deactivate();
// super.onPause();
// }
// }
//
// Path: Components/googleglass-1.6/lib/android/16/content/google-gdk/samples/ApiDemo/src/com/google/android/glass/sample/apidemo/theming/ThemingActivity.java
// public final class ThemingActivity extends Activity {
//
// private CardScrollView mCardScroller;
//
// @Override
// protected void onCreate(Bundle bundle) {
// super.onCreate(bundle);
// mCardScroller = new CardScrollView(this);
// mCardScroller.setAdapter(new LayoutAdapter(this));
// setContentView(mCardScroller);
// }
//
// @Override
// protected void onResume() {
// super.onResume();
// mCardScroller.activate();
// }
//
// @Override
// protected void onPause() {
// mCardScroller.deactivate();
// super.onPause();
// }
// }
| import com.google.android.glass.app.Card;
import com.google.android.glass.media.Sounds;
import com.google.android.glass.sample.apidemo.card.CardsActivity;
import com.google.android.glass.sample.apidemo.card.CardAdapter;
import com.google.android.glass.sample.apidemo.opengl.OpenGlService;
import com.google.android.glass.sample.apidemo.theming.ThemingActivity;
import com.google.android.glass.sample.apidemo.touchpad.SelectGestureDemoActivity;
import com.google.android.glass.widget.CardScrollAdapter;
import com.google.android.glass.widget.CardScrollView;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.media.AudioManager;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import java.util.ArrayList;
import java.util.List; | cards.add(GESTURE_DETECTOR, new Card(context).setText(R.string.text_gesture_detector));
cards.add(THEMING, new Card(context).setText(R.string.text_theming));
cards.add(OPENGL, new Card(context).setText(R.string.text_opengl));
return cards;
}
@Override
protected void onResume() {
super.onResume();
mCardScroller.activate();
}
@Override
protected void onPause() {
mCardScroller.deactivate();
super.onPause();
}
/**
* Different type of activities can be shown, when tapped on a card.
*/
private void setCardScrollerListener() {
mCardScroller.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Log.d(TAG, "Clicked view at position " + position + ", row-id " + id);
int soundEffect = Sounds.TAP;
switch (position) {
case CARDS: | // Path: Components/googleglass-1.6/lib/android/16/content/google-gdk/samples/ApiDemo/src/com/google/android/glass/sample/apidemo/card/CardsActivity.java
// public final class CardsActivity extends Activity {
//
// private CardScrollView mCardScroller;
//
// @Override
// protected void onCreate(Bundle bundle) {
// super.onCreate(bundle);
//
// mCardScroller = new CardScrollView(this);
// mCardScroller.setAdapter(new CardAdapter(createCards(this)));
// setContentView(mCardScroller);
// }
//
// /**
// * Create list of cards that showcase different type of {@link Card} API.
// */
// private List<Card> createCards(Context context) {
// ArrayList<Card> cards = new ArrayList<Card>();
// cards.add(getImagesCard(context)
// .setImageLayout(ImageLayout.LEFT)
// .setText(R.string.text_left_images_layout_card));
// cards.add(getImagesCard(context)
// .setImageLayout(ImageLayout.FULL)
// .setText(R.string.text_full_images_layout_card));
// return cards;
// }
//
// private Card getImagesCard(Context context) {
// Card card = new Card(context);
// card.addImage(R.drawable.codemonkey1);
// card.addImage(R.drawable.codemonkey2);
// card.addImage(R.drawable.codemonkey3);
// card.addImage(R.drawable.codemonkey4);
// card.addImage(R.drawable.codemonkey5);
// return card;
// }
//
// @Override
// protected void onResume() {
// super.onResume();
// mCardScroller.activate();
// }
//
// @Override
// protected void onPause() {
// mCardScroller.deactivate();
// super.onPause();
// }
// }
//
// Path: Components/googleglass-1.6/lib/android/16/content/google-gdk/samples/ApiDemo/src/com/google/android/glass/sample/apidemo/theming/ThemingActivity.java
// public final class ThemingActivity extends Activity {
//
// private CardScrollView mCardScroller;
//
// @Override
// protected void onCreate(Bundle bundle) {
// super.onCreate(bundle);
// mCardScroller = new CardScrollView(this);
// mCardScroller.setAdapter(new LayoutAdapter(this));
// setContentView(mCardScroller);
// }
//
// @Override
// protected void onResume() {
// super.onResume();
// mCardScroller.activate();
// }
//
// @Override
// protected void onPause() {
// mCardScroller.deactivate();
// super.onPause();
// }
// }
// Path: Components/googleglass-1.6/lib/android/16/content/google-gdk/samples/ApiDemo/src/com/google/android/glass/sample/apidemo/ApiDemoActivity.java
import com.google.android.glass.app.Card;
import com.google.android.glass.media.Sounds;
import com.google.android.glass.sample.apidemo.card.CardsActivity;
import com.google.android.glass.sample.apidemo.card.CardAdapter;
import com.google.android.glass.sample.apidemo.opengl.OpenGlService;
import com.google.android.glass.sample.apidemo.theming.ThemingActivity;
import com.google.android.glass.sample.apidemo.touchpad.SelectGestureDemoActivity;
import com.google.android.glass.widget.CardScrollAdapter;
import com.google.android.glass.widget.CardScrollView;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.media.AudioManager;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import java.util.ArrayList;
import java.util.List;
cards.add(GESTURE_DETECTOR, new Card(context).setText(R.string.text_gesture_detector));
cards.add(THEMING, new Card(context).setText(R.string.text_theming));
cards.add(OPENGL, new Card(context).setText(R.string.text_opengl));
return cards;
}
@Override
protected void onResume() {
super.onResume();
mCardScroller.activate();
}
@Override
protected void onPause() {
mCardScroller.deactivate();
super.onPause();
}
/**
* Different type of activities can be shown, when tapped on a card.
*/
private void setCardScrollerListener() {
mCardScroller.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Log.d(TAG, "Clicked view at position " + position + ", row-id " + id);
int soundEffect = Sounds.TAP;
switch (position) {
case CARDS: | startActivity(new Intent(ApiDemoActivity.this, CardsActivity.class)); |
longzheng/PTVGlass | Components/googleglass-1.6/lib/android/16/content/google-gdk/samples/ApiDemo/src/com/google/android/glass/sample/apidemo/ApiDemoActivity.java | // Path: Components/googleglass-1.6/lib/android/16/content/google-gdk/samples/ApiDemo/src/com/google/android/glass/sample/apidemo/card/CardsActivity.java
// public final class CardsActivity extends Activity {
//
// private CardScrollView mCardScroller;
//
// @Override
// protected void onCreate(Bundle bundle) {
// super.onCreate(bundle);
//
// mCardScroller = new CardScrollView(this);
// mCardScroller.setAdapter(new CardAdapter(createCards(this)));
// setContentView(mCardScroller);
// }
//
// /**
// * Create list of cards that showcase different type of {@link Card} API.
// */
// private List<Card> createCards(Context context) {
// ArrayList<Card> cards = new ArrayList<Card>();
// cards.add(getImagesCard(context)
// .setImageLayout(ImageLayout.LEFT)
// .setText(R.string.text_left_images_layout_card));
// cards.add(getImagesCard(context)
// .setImageLayout(ImageLayout.FULL)
// .setText(R.string.text_full_images_layout_card));
// return cards;
// }
//
// private Card getImagesCard(Context context) {
// Card card = new Card(context);
// card.addImage(R.drawable.codemonkey1);
// card.addImage(R.drawable.codemonkey2);
// card.addImage(R.drawable.codemonkey3);
// card.addImage(R.drawable.codemonkey4);
// card.addImage(R.drawable.codemonkey5);
// return card;
// }
//
// @Override
// protected void onResume() {
// super.onResume();
// mCardScroller.activate();
// }
//
// @Override
// protected void onPause() {
// mCardScroller.deactivate();
// super.onPause();
// }
// }
//
// Path: Components/googleglass-1.6/lib/android/16/content/google-gdk/samples/ApiDemo/src/com/google/android/glass/sample/apidemo/theming/ThemingActivity.java
// public final class ThemingActivity extends Activity {
//
// private CardScrollView mCardScroller;
//
// @Override
// protected void onCreate(Bundle bundle) {
// super.onCreate(bundle);
// mCardScroller = new CardScrollView(this);
// mCardScroller.setAdapter(new LayoutAdapter(this));
// setContentView(mCardScroller);
// }
//
// @Override
// protected void onResume() {
// super.onResume();
// mCardScroller.activate();
// }
//
// @Override
// protected void onPause() {
// mCardScroller.deactivate();
// super.onPause();
// }
// }
| import com.google.android.glass.app.Card;
import com.google.android.glass.media.Sounds;
import com.google.android.glass.sample.apidemo.card.CardsActivity;
import com.google.android.glass.sample.apidemo.card.CardAdapter;
import com.google.android.glass.sample.apidemo.opengl.OpenGlService;
import com.google.android.glass.sample.apidemo.theming.ThemingActivity;
import com.google.android.glass.sample.apidemo.touchpad.SelectGestureDemoActivity;
import com.google.android.glass.widget.CardScrollAdapter;
import com.google.android.glass.widget.CardScrollView;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.media.AudioManager;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import java.util.ArrayList;
import java.util.List; | mCardScroller.activate();
}
@Override
protected void onPause() {
mCardScroller.deactivate();
super.onPause();
}
/**
* Different type of activities can be shown, when tapped on a card.
*/
private void setCardScrollerListener() {
mCardScroller.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Log.d(TAG, "Clicked view at position " + position + ", row-id " + id);
int soundEffect = Sounds.TAP;
switch (position) {
case CARDS:
startActivity(new Intent(ApiDemoActivity.this, CardsActivity.class));
break;
case GESTURE_DETECTOR:
startActivity(new Intent(ApiDemoActivity.this,
SelectGestureDemoActivity.class));
break;
case THEMING: | // Path: Components/googleglass-1.6/lib/android/16/content/google-gdk/samples/ApiDemo/src/com/google/android/glass/sample/apidemo/card/CardsActivity.java
// public final class CardsActivity extends Activity {
//
// private CardScrollView mCardScroller;
//
// @Override
// protected void onCreate(Bundle bundle) {
// super.onCreate(bundle);
//
// mCardScroller = new CardScrollView(this);
// mCardScroller.setAdapter(new CardAdapter(createCards(this)));
// setContentView(mCardScroller);
// }
//
// /**
// * Create list of cards that showcase different type of {@link Card} API.
// */
// private List<Card> createCards(Context context) {
// ArrayList<Card> cards = new ArrayList<Card>();
// cards.add(getImagesCard(context)
// .setImageLayout(ImageLayout.LEFT)
// .setText(R.string.text_left_images_layout_card));
// cards.add(getImagesCard(context)
// .setImageLayout(ImageLayout.FULL)
// .setText(R.string.text_full_images_layout_card));
// return cards;
// }
//
// private Card getImagesCard(Context context) {
// Card card = new Card(context);
// card.addImage(R.drawable.codemonkey1);
// card.addImage(R.drawable.codemonkey2);
// card.addImage(R.drawable.codemonkey3);
// card.addImage(R.drawable.codemonkey4);
// card.addImage(R.drawable.codemonkey5);
// return card;
// }
//
// @Override
// protected void onResume() {
// super.onResume();
// mCardScroller.activate();
// }
//
// @Override
// protected void onPause() {
// mCardScroller.deactivate();
// super.onPause();
// }
// }
//
// Path: Components/googleglass-1.6/lib/android/16/content/google-gdk/samples/ApiDemo/src/com/google/android/glass/sample/apidemo/theming/ThemingActivity.java
// public final class ThemingActivity extends Activity {
//
// private CardScrollView mCardScroller;
//
// @Override
// protected void onCreate(Bundle bundle) {
// super.onCreate(bundle);
// mCardScroller = new CardScrollView(this);
// mCardScroller.setAdapter(new LayoutAdapter(this));
// setContentView(mCardScroller);
// }
//
// @Override
// protected void onResume() {
// super.onResume();
// mCardScroller.activate();
// }
//
// @Override
// protected void onPause() {
// mCardScroller.deactivate();
// super.onPause();
// }
// }
// Path: Components/googleglass-1.6/lib/android/16/content/google-gdk/samples/ApiDemo/src/com/google/android/glass/sample/apidemo/ApiDemoActivity.java
import com.google.android.glass.app.Card;
import com.google.android.glass.media.Sounds;
import com.google.android.glass.sample.apidemo.card.CardsActivity;
import com.google.android.glass.sample.apidemo.card.CardAdapter;
import com.google.android.glass.sample.apidemo.opengl.OpenGlService;
import com.google.android.glass.sample.apidemo.theming.ThemingActivity;
import com.google.android.glass.sample.apidemo.touchpad.SelectGestureDemoActivity;
import com.google.android.glass.widget.CardScrollAdapter;
import com.google.android.glass.widget.CardScrollView;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.media.AudioManager;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import java.util.ArrayList;
import java.util.List;
mCardScroller.activate();
}
@Override
protected void onPause() {
mCardScroller.deactivate();
super.onPause();
}
/**
* Different type of activities can be shown, when tapped on a card.
*/
private void setCardScrollerListener() {
mCardScroller.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Log.d(TAG, "Clicked view at position " + position + ", row-id " + id);
int soundEffect = Sounds.TAP;
switch (position) {
case CARDS:
startActivity(new Intent(ApiDemoActivity.this, CardsActivity.class));
break;
case GESTURE_DETECTOR:
startActivity(new Intent(ApiDemoActivity.this,
SelectGestureDemoActivity.class));
break;
case THEMING: | startActivity(new Intent(ApiDemoActivity.this, ThemingActivity.class)); |
paveyry/LyreLand | src/analysis/phrase/Cadence.java | // Path: src/analysis/harmonic/ChordDegree.java
// public class ChordDegree {
// private int degree_;
// private boolean seventhChord_;
// private int barFractionDen_;
//
// /**
// * Constructor for the ChordDegree class
// * @param degree Degree of the chord
// * @param seventhChord Specify whether it is a seventh chord or not
// */
// public ChordDegree(int degree, boolean seventhChord, int barFractionDen) {
// this.degree_ = degree;
// this.seventhChord_ = seventhChord;
// this.barFractionDen_ = barFractionDen;
// }
//
// /**
// * Getter for the degree attribute
// * @return Degree of the chord
// */
// public int getDegree() {
// return degree_;
// }
//
// /**
// * Getter for the seventhChord attribute
// * @return True if the chord is a seventh chord, False elsewhere
// */
// public boolean isSeventhChord() {
// return seventhChord_;
// }
//
// /**
// * Getter for the barFractionDen attribute
// * @return Denominator of the fraction of bar corresponding to this degree
// */
// public int getBarFractionDen() {
// return barFractionDen_;
// }
//
// /**
// * HashCode of the ChordDegree using all the class attributes.
// * @return the hashCode value.
// */
// @Override
// public int hashCode() {
// int result = degree_;
// result = 31 * result + (seventhChord_ ? 1 : 0);
// result = 31 * result + barFractionDen_;
// return result;
// }
//
// /**
// * Equality method
// * @param other other ChordDegree
// * @return True if the two ChordDegrees are equal, False elsewhere and if the param is not a ChordDegree
// */
// @Override
// public boolean equals(Object other) {
// if (other == null || !(other instanceof ChordDegree))
// return false;
// return degree_ == ((ChordDegree) other).degree_
// && seventhChord_== ((ChordDegree) other).seventhChord_
// && barFractionDen_ == ((ChordDegree) other).barFractionDen_;
// }
//
// /**
// * Conversion to String
// * @return Formatted String corresponding to the object
// */
// @Override
// public String toString() {
// StringBuilder sb = new StringBuilder("(");
// switch (degree_) {
// case 0:
// sb.append("Ø");
// break;
// case 1:
// sb.append('I');
// break;
// case 2:
// sb.append("II");
// break;
// case 3:
// sb.append("III");
// break;
// case 4:
// sb.append("IV");
// break;
// case 5:
// sb.append('V');
// break;
// case 6:
// sb.append("VI");
// break;
// case 7:
// sb.append("VII");
// break;
// }
// if (seventhChord_)
// sb.append("7");
//
// sb.append("-1/").append(barFractionDen_).append(")");
//
// return sb.toString();
// }
//
// }
| import analysis.harmonic.ChordDegree; | package analysis.phrase;
public class Cadence {
private int beginBar_;
private int endBar_;
| // Path: src/analysis/harmonic/ChordDegree.java
// public class ChordDegree {
// private int degree_;
// private boolean seventhChord_;
// private int barFractionDen_;
//
// /**
// * Constructor for the ChordDegree class
// * @param degree Degree of the chord
// * @param seventhChord Specify whether it is a seventh chord or not
// */
// public ChordDegree(int degree, boolean seventhChord, int barFractionDen) {
// this.degree_ = degree;
// this.seventhChord_ = seventhChord;
// this.barFractionDen_ = barFractionDen;
// }
//
// /**
// * Getter for the degree attribute
// * @return Degree of the chord
// */
// public int getDegree() {
// return degree_;
// }
//
// /**
// * Getter for the seventhChord attribute
// * @return True if the chord is a seventh chord, False elsewhere
// */
// public boolean isSeventhChord() {
// return seventhChord_;
// }
//
// /**
// * Getter for the barFractionDen attribute
// * @return Denominator of the fraction of bar corresponding to this degree
// */
// public int getBarFractionDen() {
// return barFractionDen_;
// }
//
// /**
// * HashCode of the ChordDegree using all the class attributes.
// * @return the hashCode value.
// */
// @Override
// public int hashCode() {
// int result = degree_;
// result = 31 * result + (seventhChord_ ? 1 : 0);
// result = 31 * result + barFractionDen_;
// return result;
// }
//
// /**
// * Equality method
// * @param other other ChordDegree
// * @return True if the two ChordDegrees are equal, False elsewhere and if the param is not a ChordDegree
// */
// @Override
// public boolean equals(Object other) {
// if (other == null || !(other instanceof ChordDegree))
// return false;
// return degree_ == ((ChordDegree) other).degree_
// && seventhChord_== ((ChordDegree) other).seventhChord_
// && barFractionDen_ == ((ChordDegree) other).barFractionDen_;
// }
//
// /**
// * Conversion to String
// * @return Formatted String corresponding to the object
// */
// @Override
// public String toString() {
// StringBuilder sb = new StringBuilder("(");
// switch (degree_) {
// case 0:
// sb.append("Ø");
// break;
// case 1:
// sb.append('I');
// break;
// case 2:
// sb.append("II");
// break;
// case 3:
// sb.append("III");
// break;
// case 4:
// sb.append("IV");
// break;
// case 5:
// sb.append('V');
// break;
// case 6:
// sb.append("VI");
// break;
// case 7:
// sb.append("VII");
// break;
// }
// if (seventhChord_)
// sb.append("7");
//
// sb.append("-1/").append(barFractionDen_).append(")");
//
// return sb.toString();
// }
//
// }
// Path: src/analysis/phrase/Cadence.java
import analysis.harmonic.ChordDegree;
package analysis.phrase;
public class Cadence {
private int beginBar_;
private int endBar_;
| private ChordDegree firstDegree_; |
paveyry/LyreLand | tests/analysis/harmonic/ChordDegreeComputerTest.java | // Path: src/analysis/harmonic/Tonality.java
// public enum Mode {
// MAJOR,
// MINOR,
// HARMONICMINOR,
// MELODICMINOR
// }
| import org.junit.*;
import analysis.harmonic.Tonality.Mode;
import static jm.constants.Pitches.*;
import java.util.ArrayList;
import java.util.Arrays; | package analysis.harmonic;
public class ChordDegreeComputerTest {
@Test
public void CMajorChordToDegree() {
// Testing with C Major | // Path: src/analysis/harmonic/Tonality.java
// public enum Mode {
// MAJOR,
// MINOR,
// HARMONICMINOR,
// MELODICMINOR
// }
// Path: tests/analysis/harmonic/ChordDegreeComputerTest.java
import org.junit.*;
import analysis.harmonic.Tonality.Mode;
import static jm.constants.Pitches.*;
import java.util.ArrayList;
import java.util.Arrays;
package analysis.harmonic;
public class ChordDegreeComputerTest {
@Test
public void CMajorChordToDegree() {
// Testing with C Major | ChordDegreeComputer cMajor = new ChordDegreeComputer(new Tonality(C4, Mode.MAJOR, 0, 0, 0)); |
paveyry/LyreLand | src/analysis/harmonic/ChordDegreeComputer.java | // Path: src/tools/containers/CircularArrayList.java
// public class CircularArrayList<E> extends ArrayList<E> {
//
// /**
// * Overriding of the get method
// * @param index Index for the access
// * @return Corresponding value
// */
// public E get(int index) {
// while (index < 0)
// index += size();
// index %= size();
// return super.get(index);
// }
// }
//
// Path: src/main/options/ExecutionParameters.java
// public class ExecutionParameters {
// /**
// * Specify if the verbose mode is activated
// */
// public static boolean verbose = false;
//
// /**
// * Specify if we train the program (if we fill and save the Markov chains)
// */
// public static boolean train = false;
//
// /**
// * Specify the seed for generation
// */
// public static int seed = 3657263;
//
// /**
// * Specify the path to the training set (for writing or reading)
// */
// public static Path LSTMTrainingSetPath = Paths.get("assets/abc");
//
// /**
// * Specify the path to the trained data (created after training and used for generation)
// */
// public static Path trainedLSTMPath = Paths.get("assets/training/trained-lstm");
// }
| import tools.containers.CircularArrayList;
import jm.constants.Pitches;
import main.options.ExecutionParameters;
import java.util.ArrayList; | package analysis.harmonic;
/**
* Class that finds Chord Degree on a specific bar of bar part.
*/
public class ChordDegreeComputer {
private Tonality tonality_; | // Path: src/tools/containers/CircularArrayList.java
// public class CircularArrayList<E> extends ArrayList<E> {
//
// /**
// * Overriding of the get method
// * @param index Index for the access
// * @return Corresponding value
// */
// public E get(int index) {
// while (index < 0)
// index += size();
// index %= size();
// return super.get(index);
// }
// }
//
// Path: src/main/options/ExecutionParameters.java
// public class ExecutionParameters {
// /**
// * Specify if the verbose mode is activated
// */
// public static boolean verbose = false;
//
// /**
// * Specify if we train the program (if we fill and save the Markov chains)
// */
// public static boolean train = false;
//
// /**
// * Specify the seed for generation
// */
// public static int seed = 3657263;
//
// /**
// * Specify the path to the training set (for writing or reading)
// */
// public static Path LSTMTrainingSetPath = Paths.get("assets/abc");
//
// /**
// * Specify the path to the trained data (created after training and used for generation)
// */
// public static Path trainedLSTMPath = Paths.get("assets/training/trained-lstm");
// }
// Path: src/analysis/harmonic/ChordDegreeComputer.java
import tools.containers.CircularArrayList;
import jm.constants.Pitches;
import main.options.ExecutionParameters;
import java.util.ArrayList;
package analysis.harmonic;
/**
* Class that finds Chord Degree on a specific bar of bar part.
*/
public class ChordDegreeComputer {
private Tonality tonality_; | private CircularArrayList<Integer> scale_; |
paveyry/LyreLand | src/analysis/harmonic/ChordDegreeComputer.java | // Path: src/tools/containers/CircularArrayList.java
// public class CircularArrayList<E> extends ArrayList<E> {
//
// /**
// * Overriding of the get method
// * @param index Index for the access
// * @return Corresponding value
// */
// public E get(int index) {
// while (index < 0)
// index += size();
// index %= size();
// return super.get(index);
// }
// }
//
// Path: src/main/options/ExecutionParameters.java
// public class ExecutionParameters {
// /**
// * Specify if the verbose mode is activated
// */
// public static boolean verbose = false;
//
// /**
// * Specify if we train the program (if we fill and save the Markov chains)
// */
// public static boolean train = false;
//
// /**
// * Specify the seed for generation
// */
// public static int seed = 3657263;
//
// /**
// * Specify the path to the training set (for writing or reading)
// */
// public static Path LSTMTrainingSetPath = Paths.get("assets/abc");
//
// /**
// * Specify the path to the trained data (created after training and used for generation)
// */
// public static Path trainedLSTMPath = Paths.get("assets/training/trained-lstm");
// }
| import tools.containers.CircularArrayList;
import jm.constants.Pitches;
import main.options.ExecutionParameters;
import java.util.ArrayList; |
double max = 0.0;
int degree = 0;
// Find the degree with the best matching percentage
for (int i = 0; i < percentage.length; ++i) {
if (percentage[i] > max) {
max = percentage[i];
degree = i + 1;
}
}
boolean seventhChord = false;
double seventhPercentage = 0.0;
// Determine if the chord degree is a seventh chord
for (int i = 0; i < chord.size(); ++i) {
if (degree > 0 && chord.get(i) % 12 == chords_.get(degree - 1)[3] % 12)
++seventhPercentage;
}
seventhPercentage /= chord.size();
if (seventhPercentage >= 0.05)
seventhChord = true;
// If the matching percentage is not sufficient, return a 0 degree to specify that no degree was found
if (max < 0.5)
return new ChordDegree(0, false, barFractionDen);
// Log the chord and the detected degree | // Path: src/tools/containers/CircularArrayList.java
// public class CircularArrayList<E> extends ArrayList<E> {
//
// /**
// * Overriding of the get method
// * @param index Index for the access
// * @return Corresponding value
// */
// public E get(int index) {
// while (index < 0)
// index += size();
// index %= size();
// return super.get(index);
// }
// }
//
// Path: src/main/options/ExecutionParameters.java
// public class ExecutionParameters {
// /**
// * Specify if the verbose mode is activated
// */
// public static boolean verbose = false;
//
// /**
// * Specify if we train the program (if we fill and save the Markov chains)
// */
// public static boolean train = false;
//
// /**
// * Specify the seed for generation
// */
// public static int seed = 3657263;
//
// /**
// * Specify the path to the training set (for writing or reading)
// */
// public static Path LSTMTrainingSetPath = Paths.get("assets/abc");
//
// /**
// * Specify the path to the trained data (created after training and used for generation)
// */
// public static Path trainedLSTMPath = Paths.get("assets/training/trained-lstm");
// }
// Path: src/analysis/harmonic/ChordDegreeComputer.java
import tools.containers.CircularArrayList;
import jm.constants.Pitches;
import main.options.ExecutionParameters;
import java.util.ArrayList;
double max = 0.0;
int degree = 0;
// Find the degree with the best matching percentage
for (int i = 0; i < percentage.length; ++i) {
if (percentage[i] > max) {
max = percentage[i];
degree = i + 1;
}
}
boolean seventhChord = false;
double seventhPercentage = 0.0;
// Determine if the chord degree is a seventh chord
for (int i = 0; i < chord.size(); ++i) {
if (degree > 0 && chord.get(i) % 12 == chords_.get(degree - 1)[3] % 12)
++seventhPercentage;
}
seventhPercentage /= chord.size();
if (seventhPercentage >= 0.05)
seventhChord = true;
// If the matching percentage is not sufficient, return a 0 degree to specify that no degree was found
if (max < 0.5)
return new ChordDegree(0, false, barFractionDen);
// Log the chord and the detected degree | if (ExecutionParameters.verbose) { |
paveyry/LyreLand | src/analysis/harmonic/Tonality.java | // Path: src/tools/containers/CircularArrayList.java
// public class CircularArrayList<E> extends ArrayList<E> {
//
// /**
// * Overriding of the get method
// * @param index Index for the access
// * @return Corresponding value
// */
// public E get(int index) {
// while (index < 0)
// index += size();
// index %= size();
// return super.get(index);
// }
// }
| import tools.containers.CircularArrayList;
import jm.constants.Pitches;
import java.util.Arrays;
import static jm.constants.Pitches.*; | public Tonality(int tonic, Mode mode, int alteration, int keySignature, int keyQuality) {
tonic_ = tonic;
mode_ = mode;
alteration_ = alteration;
keySignature_ = keySignature;
keyQuality_ = keyQuality;
}
/**
* Tonality constructor that processes tonality from key signature and quality
* @param keySignature Key Signature of the Score
* @param keyQuality Key Quality of the Score
*/
public Tonality(int keySignature, int keyQuality)
{
keySignature_ = keySignature;
keyQuality_ = keyQuality;
alteration_ = 0;
if (keySignature == 0) {
if (keyQuality == 0) {
tonic_ = C0;
mode_ = Mode.MAJOR;
}
else {
tonic_ = A0;
mode_ = Mode.MINOR;
}
return;
}
mode_ = (keyQuality == 0) ? Tonality.Mode.MAJOR : Tonality.Mode.MINOR; | // Path: src/tools/containers/CircularArrayList.java
// public class CircularArrayList<E> extends ArrayList<E> {
//
// /**
// * Overriding of the get method
// * @param index Index for the access
// * @return Corresponding value
// */
// public E get(int index) {
// while (index < 0)
// index += size();
// index %= size();
// return super.get(index);
// }
// }
// Path: src/analysis/harmonic/Tonality.java
import tools.containers.CircularArrayList;
import jm.constants.Pitches;
import java.util.Arrays;
import static jm.constants.Pitches.*;
public Tonality(int tonic, Mode mode, int alteration, int keySignature, int keyQuality) {
tonic_ = tonic;
mode_ = mode;
alteration_ = alteration;
keySignature_ = keySignature;
keyQuality_ = keyQuality;
}
/**
* Tonality constructor that processes tonality from key signature and quality
* @param keySignature Key Signature of the Score
* @param keyQuality Key Quality of the Score
*/
public Tonality(int keySignature, int keyQuality)
{
keySignature_ = keySignature;
keyQuality_ = keyQuality;
alteration_ = 0;
if (keySignature == 0) {
if (keyQuality == 0) {
tonic_ = C0;
mode_ = Mode.MAJOR;
}
else {
tonic_ = A0;
mode_ = Mode.MINOR;
}
return;
}
mode_ = (keyQuality == 0) ? Tonality.Mode.MAJOR : Tonality.Mode.MINOR; | CircularArrayList<Integer> order = new CircularArrayList<>(); // Sharp or flat order |
paveyry/LyreLand | src/website/java/app/util/ResourceManager.java | // Path: src/tools/Misc.java
// public class Misc {
// public static String getJarPath() {
// String path = Misc.class.getProtectionDomain().getCodeSource().getLocation().getPath();
// String decoded = null;
// String dir = null;
//
// try {
// decoded = URLDecoder.decode(path, "UTF-8");
// int lastSlash = decoded.lastIndexOf("/");
//
// if (decoded.substring(lastSlash - 7, lastSlash).compareTo("classes") == 0)
// dir = decoded.substring(0, lastSlash - 7);
// else
// dir = decoded.substring(0, lastSlash + 1);
// } catch (UnsupportedEncodingException e) {
// e.printStackTrace();
// }
//
// return System.getProperty("os.name").contains("indow") ? dir.substring(1) : dir;
// }
//
// public static String getProjectPath() {
// String path = getJarPath();
// return path.substring(0, path.lastIndexOf("target"));
// }
// }
| import tools.Misc; | package website.java.app.util;
public class ResourceManager {
public static String getResourceDir() { | // Path: src/tools/Misc.java
// public class Misc {
// public static String getJarPath() {
// String path = Misc.class.getProtectionDomain().getCodeSource().getLocation().getPath();
// String decoded = null;
// String dir = null;
//
// try {
// decoded = URLDecoder.decode(path, "UTF-8");
// int lastSlash = decoded.lastIndexOf("/");
//
// if (decoded.substring(lastSlash - 7, lastSlash).compareTo("classes") == 0)
// dir = decoded.substring(0, lastSlash - 7);
// else
// dir = decoded.substring(0, lastSlash + 1);
// } catch (UnsupportedEncodingException e) {
// e.printStackTrace();
// }
//
// return System.getProperty("os.name").contains("indow") ? dir.substring(1) : dir;
// }
//
// public static String getProjectPath() {
// String path = getJarPath();
// return path.substring(0, path.lastIndexOf("target"));
// }
// }
// Path: src/website/java/app/util/ResourceManager.java
import tools.Misc;
package website.java.app.util;
public class ResourceManager {
public static String getResourceDir() { | return Misc.getProjectPath() + "target/classes/website/resources/"; |
paveyry/LyreLand | src/lstm/LSTMTrainer.java | // Path: src/main/options/ExecutionParameters.java
// public class ExecutionParameters {
// /**
// * Specify if the verbose mode is activated
// */
// public static boolean verbose = false;
//
// /**
// * Specify if we train the program (if we fill and save the Markov chains)
// */
// public static boolean train = false;
//
// /**
// * Specify the seed for generation
// */
// public static int seed = 3657263;
//
// /**
// * Specify the path to the training set (for writing or reading)
// */
// public static Path LSTMTrainingSetPath = Paths.get("assets/abc");
//
// /**
// * Specify the path to the trained data (created after training and used for generation)
// */
// public static Path trainedLSTMPath = Paths.get("assets/training/trained-lstm");
// }
//
// Path: src/tools/Misc.java
// public class Misc {
// public static String getJarPath() {
// String path = Misc.class.getProtectionDomain().getCodeSource().getLocation().getPath();
// String decoded = null;
// String dir = null;
//
// try {
// decoded = URLDecoder.decode(path, "UTF-8");
// int lastSlash = decoded.lastIndexOf("/");
//
// if (decoded.substring(lastSlash - 7, lastSlash).compareTo("classes") == 0)
// dir = decoded.substring(0, lastSlash - 7);
// else
// dir = decoded.substring(0, lastSlash + 1);
// } catch (UnsupportedEncodingException e) {
// e.printStackTrace();
// }
//
// return System.getProperty("os.name").contains("indow") ? dir.substring(1) : dir;
// }
//
// public static String getProjectPath() {
// String path = getJarPath();
// return path.substring(0, path.lastIndexOf("target"));
// }
// }
| import com.sun.org.apache.xpath.internal.operations.Mod;
import com.thoughtworks.xstream.XStream;
import com.thoughtworks.xstream.io.xml.DomDriver;
import main.options.ExecutionParameters;
import org.deeplearning4j.api.storage.StatsStorage;
import org.deeplearning4j.nn.api.Layer;
import org.deeplearning4j.nn.api.OptimizationAlgorithm;
import org.deeplearning4j.nn.conf.BackpropType;
import org.deeplearning4j.nn.conf.MultiLayerConfiguration;
import org.deeplearning4j.nn.conf.NeuralNetConfiguration;
import org.deeplearning4j.nn.conf.Updater;
import org.deeplearning4j.nn.conf.layers.GravesLSTM;
import org.deeplearning4j.nn.conf.layers.RnnOutputLayer;
import org.deeplearning4j.nn.multilayer.MultiLayerNetwork;
import org.deeplearning4j.nn.weights.WeightInit;
import org.deeplearning4j.optimize.listeners.ScoreIterationListener;
import org.deeplearning4j.ui.api.UIServer;
import org.deeplearning4j.ui.stats.StatsListener;
import org.deeplearning4j.ui.storage.InMemoryStatsStorage;
import org.deeplearning4j.util.ModelSerializer;
import org.nd4j.linalg.dataset.api.DataSet;
import org.nd4j.linalg.lossfunctions.LossFunctions;
import org.nd4j.linalg.api.ndarray.INDArray;
import org.nd4j.linalg.factory.Nd4j;
import tools.Misc;
import java.nio.charset.Charset;
import java.util.HashMap;
import java.util.Random;
import java.io.*; | .rmsDecay(0.95) // 0.95 original
.seed(seed_)
.regularization(true) // true original
.l2(0.001)
.weightInit(WeightInit.XAVIER)
.updater(Updater.RMSPROP)
.list()
.layer(0, new GravesLSTM.Builder().nIn(trainingSetIterator_.inputColumns()).nOut(lstmLayerSize_)
.activation("tanh").build())
.layer(1, new GravesLSTM.Builder().nIn(lstmLayerSize_).nOut(lstmLayerSize_)
.activation("tanh").build())
.layer(2, new GravesLSTM.Builder().nIn(lstmLayerSize_).nOut(lstmLayerSize_)
.activation("tanh").build())
.layer(3, new RnnOutputLayer.Builder(LossFunctions.LossFunction.MCXENT).activation("softmax")
.nIn(lstmLayerSize_).nOut(nOut).build())
.backpropType(BackpropType.TruncatedBPTT)
.tBPTTForwardLength(truncatedBackPropThroughTimeLength_)
.tBPTTBackwardLength(truncatedBackPropThroughTimeLength_)
.pretrain(false).backprop(true)
.build();
lstmNet_ = new MultiLayerNetwork(conf);
lstmNet_.init();
//lstmNet_.setListeners(new ScoreIterationListener(1));
//lstmNet_.setListeners(new HistogramIterationListener(1));
UIServer uiServer = UIServer.getInstance();
StatsStorage statsStorage = new InMemoryStatsStorage();
uiServer.attach(statsStorage);
lstmNet_.setListeners(new StatsListener(statsStorage));
| // Path: src/main/options/ExecutionParameters.java
// public class ExecutionParameters {
// /**
// * Specify if the verbose mode is activated
// */
// public static boolean verbose = false;
//
// /**
// * Specify if we train the program (if we fill and save the Markov chains)
// */
// public static boolean train = false;
//
// /**
// * Specify the seed for generation
// */
// public static int seed = 3657263;
//
// /**
// * Specify the path to the training set (for writing or reading)
// */
// public static Path LSTMTrainingSetPath = Paths.get("assets/abc");
//
// /**
// * Specify the path to the trained data (created after training and used for generation)
// */
// public static Path trainedLSTMPath = Paths.get("assets/training/trained-lstm");
// }
//
// Path: src/tools/Misc.java
// public class Misc {
// public static String getJarPath() {
// String path = Misc.class.getProtectionDomain().getCodeSource().getLocation().getPath();
// String decoded = null;
// String dir = null;
//
// try {
// decoded = URLDecoder.decode(path, "UTF-8");
// int lastSlash = decoded.lastIndexOf("/");
//
// if (decoded.substring(lastSlash - 7, lastSlash).compareTo("classes") == 0)
// dir = decoded.substring(0, lastSlash - 7);
// else
// dir = decoded.substring(0, lastSlash + 1);
// } catch (UnsupportedEncodingException e) {
// e.printStackTrace();
// }
//
// return System.getProperty("os.name").contains("indow") ? dir.substring(1) : dir;
// }
//
// public static String getProjectPath() {
// String path = getJarPath();
// return path.substring(0, path.lastIndexOf("target"));
// }
// }
// Path: src/lstm/LSTMTrainer.java
import com.sun.org.apache.xpath.internal.operations.Mod;
import com.thoughtworks.xstream.XStream;
import com.thoughtworks.xstream.io.xml.DomDriver;
import main.options.ExecutionParameters;
import org.deeplearning4j.api.storage.StatsStorage;
import org.deeplearning4j.nn.api.Layer;
import org.deeplearning4j.nn.api.OptimizationAlgorithm;
import org.deeplearning4j.nn.conf.BackpropType;
import org.deeplearning4j.nn.conf.MultiLayerConfiguration;
import org.deeplearning4j.nn.conf.NeuralNetConfiguration;
import org.deeplearning4j.nn.conf.Updater;
import org.deeplearning4j.nn.conf.layers.GravesLSTM;
import org.deeplearning4j.nn.conf.layers.RnnOutputLayer;
import org.deeplearning4j.nn.multilayer.MultiLayerNetwork;
import org.deeplearning4j.nn.weights.WeightInit;
import org.deeplearning4j.optimize.listeners.ScoreIterationListener;
import org.deeplearning4j.ui.api.UIServer;
import org.deeplearning4j.ui.stats.StatsListener;
import org.deeplearning4j.ui.storage.InMemoryStatsStorage;
import org.deeplearning4j.util.ModelSerializer;
import org.nd4j.linalg.dataset.api.DataSet;
import org.nd4j.linalg.lossfunctions.LossFunctions;
import org.nd4j.linalg.api.ndarray.INDArray;
import org.nd4j.linalg.factory.Nd4j;
import tools.Misc;
import java.nio.charset.Charset;
import java.util.HashMap;
import java.util.Random;
import java.io.*;
.rmsDecay(0.95) // 0.95 original
.seed(seed_)
.regularization(true) // true original
.l2(0.001)
.weightInit(WeightInit.XAVIER)
.updater(Updater.RMSPROP)
.list()
.layer(0, new GravesLSTM.Builder().nIn(trainingSetIterator_.inputColumns()).nOut(lstmLayerSize_)
.activation("tanh").build())
.layer(1, new GravesLSTM.Builder().nIn(lstmLayerSize_).nOut(lstmLayerSize_)
.activation("tanh").build())
.layer(2, new GravesLSTM.Builder().nIn(lstmLayerSize_).nOut(lstmLayerSize_)
.activation("tanh").build())
.layer(3, new RnnOutputLayer.Builder(LossFunctions.LossFunction.MCXENT).activation("softmax")
.nIn(lstmLayerSize_).nOut(nOut).build())
.backpropType(BackpropType.TruncatedBPTT)
.tBPTTForwardLength(truncatedBackPropThroughTimeLength_)
.tBPTTBackwardLength(truncatedBackPropThroughTimeLength_)
.pretrain(false).backprop(true)
.build();
lstmNet_ = new MultiLayerNetwork(conf);
lstmNet_.init();
//lstmNet_.setListeners(new ScoreIterationListener(1));
//lstmNet_.setListeners(new HistogramIterationListener(1));
UIServer uiServer = UIServer.getInstance();
StatsStorage statsStorage = new InMemoryStatsStorage();
uiServer.attach(statsStorage);
lstmNet_.setListeners(new StatsListener(statsStorage));
| if (ExecutionParameters.verbose) { |
paveyry/LyreLand | src/lstm/LSTMTrainer.java | // Path: src/main/options/ExecutionParameters.java
// public class ExecutionParameters {
// /**
// * Specify if the verbose mode is activated
// */
// public static boolean verbose = false;
//
// /**
// * Specify if we train the program (if we fill and save the Markov chains)
// */
// public static boolean train = false;
//
// /**
// * Specify the seed for generation
// */
// public static int seed = 3657263;
//
// /**
// * Specify the path to the training set (for writing or reading)
// */
// public static Path LSTMTrainingSetPath = Paths.get("assets/abc");
//
// /**
// * Specify the path to the trained data (created after training and used for generation)
// */
// public static Path trainedLSTMPath = Paths.get("assets/training/trained-lstm");
// }
//
// Path: src/tools/Misc.java
// public class Misc {
// public static String getJarPath() {
// String path = Misc.class.getProtectionDomain().getCodeSource().getLocation().getPath();
// String decoded = null;
// String dir = null;
//
// try {
// decoded = URLDecoder.decode(path, "UTF-8");
// int lastSlash = decoded.lastIndexOf("/");
//
// if (decoded.substring(lastSlash - 7, lastSlash).compareTo("classes") == 0)
// dir = decoded.substring(0, lastSlash - 7);
// else
// dir = decoded.substring(0, lastSlash + 1);
// } catch (UnsupportedEncodingException e) {
// e.printStackTrace();
// }
//
// return System.getProperty("os.name").contains("indow") ? dir.substring(1) : dir;
// }
//
// public static String getProjectPath() {
// String path = getJarPath();
// return path.substring(0, path.lastIndexOf("target"));
// }
// }
| import com.sun.org.apache.xpath.internal.operations.Mod;
import com.thoughtworks.xstream.XStream;
import com.thoughtworks.xstream.io.xml.DomDriver;
import main.options.ExecutionParameters;
import org.deeplearning4j.api.storage.StatsStorage;
import org.deeplearning4j.nn.api.Layer;
import org.deeplearning4j.nn.api.OptimizationAlgorithm;
import org.deeplearning4j.nn.conf.BackpropType;
import org.deeplearning4j.nn.conf.MultiLayerConfiguration;
import org.deeplearning4j.nn.conf.NeuralNetConfiguration;
import org.deeplearning4j.nn.conf.Updater;
import org.deeplearning4j.nn.conf.layers.GravesLSTM;
import org.deeplearning4j.nn.conf.layers.RnnOutputLayer;
import org.deeplearning4j.nn.multilayer.MultiLayerNetwork;
import org.deeplearning4j.nn.weights.WeightInit;
import org.deeplearning4j.optimize.listeners.ScoreIterationListener;
import org.deeplearning4j.ui.api.UIServer;
import org.deeplearning4j.ui.stats.StatsListener;
import org.deeplearning4j.ui.storage.InMemoryStatsStorage;
import org.deeplearning4j.util.ModelSerializer;
import org.nd4j.linalg.dataset.api.DataSet;
import org.nd4j.linalg.lossfunctions.LossFunctions;
import org.nd4j.linalg.api.ndarray.INDArray;
import org.nd4j.linalg.factory.Nd4j;
import tools.Misc;
import java.nio.charset.Charset;
import java.util.HashMap;
import java.util.Random;
import java.io.*; | lstmNet_.setListeners(new StatsListener(statsStorage));
if (ExecutionParameters.verbose) {
Layer[] layers = lstmNet_.getLayers();
int totalNumParams = 0;
for (int i = 0; i < layers.length; i++) {
int nParams = layers[i].numParams();
System.out.println("Number of parameters in layer " + i + ": " + nParams);
totalNumParams += nParams;
}
System.out.println("Total number of network parameters: " + totalNumParams);
}
}
/**
* Method to run the LSTM training
*/
public void train() throws IOException {
int counter = 0;
int sampleIndex = 1;
for (int i = 0; i < nbEpochs_; ++i) {
while (trainingSetIterator_.hasNext()) {
DataSet ds = trainingSetIterator_.next();
lstmNet_.fit(ds);
//if (counter % generateSamplesEveryNMinibatches_ == 0) {
// generateSample(i, counter);
//}
++counter;
}
trainingSetIterator_.reset(); // Reset for next epoch | // Path: src/main/options/ExecutionParameters.java
// public class ExecutionParameters {
// /**
// * Specify if the verbose mode is activated
// */
// public static boolean verbose = false;
//
// /**
// * Specify if we train the program (if we fill and save the Markov chains)
// */
// public static boolean train = false;
//
// /**
// * Specify the seed for generation
// */
// public static int seed = 3657263;
//
// /**
// * Specify the path to the training set (for writing or reading)
// */
// public static Path LSTMTrainingSetPath = Paths.get("assets/abc");
//
// /**
// * Specify the path to the trained data (created after training and used for generation)
// */
// public static Path trainedLSTMPath = Paths.get("assets/training/trained-lstm");
// }
//
// Path: src/tools/Misc.java
// public class Misc {
// public static String getJarPath() {
// String path = Misc.class.getProtectionDomain().getCodeSource().getLocation().getPath();
// String decoded = null;
// String dir = null;
//
// try {
// decoded = URLDecoder.decode(path, "UTF-8");
// int lastSlash = decoded.lastIndexOf("/");
//
// if (decoded.substring(lastSlash - 7, lastSlash).compareTo("classes") == 0)
// dir = decoded.substring(0, lastSlash - 7);
// else
// dir = decoded.substring(0, lastSlash + 1);
// } catch (UnsupportedEncodingException e) {
// e.printStackTrace();
// }
//
// return System.getProperty("os.name").contains("indow") ? dir.substring(1) : dir;
// }
//
// public static String getProjectPath() {
// String path = getJarPath();
// return path.substring(0, path.lastIndexOf("target"));
// }
// }
// Path: src/lstm/LSTMTrainer.java
import com.sun.org.apache.xpath.internal.operations.Mod;
import com.thoughtworks.xstream.XStream;
import com.thoughtworks.xstream.io.xml.DomDriver;
import main.options.ExecutionParameters;
import org.deeplearning4j.api.storage.StatsStorage;
import org.deeplearning4j.nn.api.Layer;
import org.deeplearning4j.nn.api.OptimizationAlgorithm;
import org.deeplearning4j.nn.conf.BackpropType;
import org.deeplearning4j.nn.conf.MultiLayerConfiguration;
import org.deeplearning4j.nn.conf.NeuralNetConfiguration;
import org.deeplearning4j.nn.conf.Updater;
import org.deeplearning4j.nn.conf.layers.GravesLSTM;
import org.deeplearning4j.nn.conf.layers.RnnOutputLayer;
import org.deeplearning4j.nn.multilayer.MultiLayerNetwork;
import org.deeplearning4j.nn.weights.WeightInit;
import org.deeplearning4j.optimize.listeners.ScoreIterationListener;
import org.deeplearning4j.ui.api.UIServer;
import org.deeplearning4j.ui.stats.StatsListener;
import org.deeplearning4j.ui.storage.InMemoryStatsStorage;
import org.deeplearning4j.util.ModelSerializer;
import org.nd4j.linalg.dataset.api.DataSet;
import org.nd4j.linalg.lossfunctions.LossFunctions;
import org.nd4j.linalg.api.ndarray.INDArray;
import org.nd4j.linalg.factory.Nd4j;
import tools.Misc;
import java.nio.charset.Charset;
import java.util.HashMap;
import java.util.Random;
import java.io.*;
lstmNet_.setListeners(new StatsListener(statsStorage));
if (ExecutionParameters.verbose) {
Layer[] layers = lstmNet_.getLayers();
int totalNumParams = 0;
for (int i = 0; i < layers.length; i++) {
int nParams = layers[i].numParams();
System.out.println("Number of parameters in layer " + i + ": " + nParams);
totalNumParams += nParams;
}
System.out.println("Total number of network parameters: " + totalNumParams);
}
}
/**
* Method to run the LSTM training
*/
public void train() throws IOException {
int counter = 0;
int sampleIndex = 1;
for (int i = 0; i < nbEpochs_; ++i) {
while (trainingSetIterator_.hasNext()) {
DataSet ds = trainingSetIterator_.next();
lstmNet_.fit(ds);
//if (counter % generateSamplesEveryNMinibatches_ == 0) {
// generateSample(i, counter);
//}
++counter;
}
trainingSetIterator_.reset(); // Reset for next epoch | this.serialize(Misc.getProjectPath() + "lstm-epoch-" + i + "-lr" + learningRate_); |
wpilibsuite/ntcore | src/main/java/edu/wpi/first/wpilibj/tables/IRemoteConnectionListener.java | // Path: src/main/java/edu/wpi/first/networktables/ConnectionInfo.java
// public final class ConnectionInfo {
// /**
// * The remote identifier (as set on the remote node by
// * {@link NetworkTableInstance#setNetworkIdentity(String)}).
// */
// public final String remote_id;
//
// /**
// * The IP address of the remote node.
// */
// public final String remote_ip;
//
// /**
// * The port number of the remote node.
// */
// public final int remote_port;
//
// /**
// * The last time any update was received from the remote node (same scale as
// * returned by {@link NetworkTablesJNI#now()}).
// */
// public final long last_update;
//
// /**
// * The protocol version being used for this connection. This is in protocol
// * layer format, so 0x0200 = 2.0, 0x0300 = 3.0).
// */
// public final int protocol_version;
//
// /** Constructor.
// * This should generally only be used internally to NetworkTables.
// * @param remote_id Remote identifier
// * @param remote_ip Remote IP address
// * @param remote_port Remote port number
// * @param last_update Last time an update was received
// * @param protocol_version The protocol version used for the connection
// */
// public ConnectionInfo(String remote_id, String remote_ip, int remote_port, long last_update, int protocol_version) {
// this.remote_id = remote_id;
// this.remote_ip = remote_ip;
// this.remote_port = remote_port;
// this.last_update = last_update;
// this.protocol_version = protocol_version;
// }
// }
| import edu.wpi.first.networktables.ConnectionInfo; | /*----------------------------------------------------------------------------*/
/* Copyright (c) FIRST 2017-2018. All Rights Reserved. */
/* Open Source Software - may be modified and shared by FRC teams. The code */
/* must be accompanied by the FIRST BSD license file in the root directory of */
/* the project. */
/*----------------------------------------------------------------------------*/
package edu.wpi.first.wpilibj.tables;
/**
* A listener that listens for connection changes in a {@link IRemote} object
* @deprecated Use Consumer<{@link edu.wpi.first.networktables.ConnectionNotification}>.
*/
@Deprecated
public interface IRemoteConnectionListener {
/**
* Called when an IRemote is connected
* @param remote the object that connected
*/
public void connected(IRemote remote);
/**
* Called when an IRemote is disconnected
* @param remote the object that disconnected
*/
public void disconnected(IRemote remote);
/**
* Extended version of connected called when an IRemote is connected.
* Contains the connection info of the connected remote
* @param remote the object that connected
* @param info the connection info for the connected remote
*/ | // Path: src/main/java/edu/wpi/first/networktables/ConnectionInfo.java
// public final class ConnectionInfo {
// /**
// * The remote identifier (as set on the remote node by
// * {@link NetworkTableInstance#setNetworkIdentity(String)}).
// */
// public final String remote_id;
//
// /**
// * The IP address of the remote node.
// */
// public final String remote_ip;
//
// /**
// * The port number of the remote node.
// */
// public final int remote_port;
//
// /**
// * The last time any update was received from the remote node (same scale as
// * returned by {@link NetworkTablesJNI#now()}).
// */
// public final long last_update;
//
// /**
// * The protocol version being used for this connection. This is in protocol
// * layer format, so 0x0200 = 2.0, 0x0300 = 3.0).
// */
// public final int protocol_version;
//
// /** Constructor.
// * This should generally only be used internally to NetworkTables.
// * @param remote_id Remote identifier
// * @param remote_ip Remote IP address
// * @param remote_port Remote port number
// * @param last_update Last time an update was received
// * @param protocol_version The protocol version used for the connection
// */
// public ConnectionInfo(String remote_id, String remote_ip, int remote_port, long last_update, int protocol_version) {
// this.remote_id = remote_id;
// this.remote_ip = remote_ip;
// this.remote_port = remote_port;
// this.last_update = last_update;
// this.protocol_version = protocol_version;
// }
// }
// Path: src/main/java/edu/wpi/first/wpilibj/tables/IRemoteConnectionListener.java
import edu.wpi.first.networktables.ConnectionInfo;
/*----------------------------------------------------------------------------*/
/* Copyright (c) FIRST 2017-2018. All Rights Reserved. */
/* Open Source Software - may be modified and shared by FRC teams. The code */
/* must be accompanied by the FIRST BSD license file in the root directory of */
/* the project. */
/*----------------------------------------------------------------------------*/
package edu.wpi.first.wpilibj.tables;
/**
* A listener that listens for connection changes in a {@link IRemote} object
* @deprecated Use Consumer<{@link edu.wpi.first.networktables.ConnectionNotification}>.
*/
@Deprecated
public interface IRemoteConnectionListener {
/**
* Called when an IRemote is connected
* @param remote the object that connected
*/
public void connected(IRemote remote);
/**
* Called when an IRemote is disconnected
* @param remote the object that disconnected
*/
public void disconnected(IRemote remote);
/**
* Extended version of connected called when an IRemote is connected.
* Contains the connection info of the connected remote
* @param remote the object that connected
* @param info the connection info for the connected remote
*/ | default public void connectedEx(IRemote remote, ConnectionInfo info) { |
mhgrove/cp-openrdf-utils | core/test/src/com/complexible/common/openrdf/GraphBuilderTests.java | // Path: core/main/src/com/complexible/common/openrdf/util/ModelBuilder.java
// public class ModelBuilder {
// private final Model mGraph;
// private final ValueFactory mValueFactory;
//
// public ModelBuilder() {
// mGraph = Models2.newModel();
// mValueFactory = SimpleValueFactory.getInstance();
// }
//
// public ModelBuilder(final ValueFactory theValueFactory) {
// mGraph = Models2.newModel();
// mValueFactory = theValueFactory;
// }
//
// /**
// * Return the Graph created via this builder
// *
// * @return the graph
// */
// public Model model() {
// return Models2.newModel(mGraph);
// }
//
// /**
// * Clear the contents of the builder
// */
// public void reset() {
// mGraph.clear();
// }
//
// /**
// * Create a {@link ResourceBuilder builder} for the individual
// * @param theURI the individual
// * @return the {@link ResourceBuilder builder}
// */
// public ResourceBuilder iri(IRI theURI) {
// return new ResourceBuilder(mGraph, getValueFactory(), getValueFactory().createIRI(theURI.toString()));
// }
//
// /**
// * Create a {@link ResourceBuilder builder} for the individual
// * @param theURI the individual
// * @return the {@link ResourceBuilder builder}
// */
// public ResourceBuilder iri(String theURI) {
// return instance(null, theURI);
// }
//
// /**
// * Create a new anonymous instance of the given type
// *
// * @param theType the type
// *
// * @return a {@link ResourceBuilder builder} for the new individual
// */
// public ResourceBuilder instance(IRI theType) {
// return instance(theType, (String) null);
// }
//
// /**
// * Create an un-typed anonymous individual in the graph
// *
// * @return a ResourceBuilder wrapping the bnode
// */
// public ResourceBuilder instance() {
// return instance(null, (String) null);
// }
//
//
// /**
// * Create a {@link ResourceBuilder builder} for the given individual and add the type
// *
// * @param theType the type
// * @param theURI the individual
// *
// * @return a {@link ResourceBuilder builder} for the new individual
// */
// public ResourceBuilder instance(IRI theType, java.net.URI theURI) {
// return instance(theType, theURI.toString());
// }
//
// /**
// * Create a {@link ResourceBuilder builder} for the given individual and add the type
// *
// * @param theType the type
// * @param theRes the individual
// *
// * @return a {@link ResourceBuilder builder} for the new individual
// */
// public ResourceBuilder instance(IRI theType, Resource theRes) {
// if (theType != null) {
// mGraph.add(theRes, RDF.TYPE, theType);
// }
//
// return new ResourceBuilder(mGraph, getValueFactory(), theRes);
// }
// /**
// * Create a {@link ResourceBuilder builder} for the given individual and add the type
// *
// * @param theType the type
// * @param theURI the individual
// *
// * @return a {@link ResourceBuilder builder} for the new individual
// */
// public ResourceBuilder instance(IRI theType, String theURI) {
// Resource aRes = theURI == null
// ? getValueFactory().createBNode()
// : getValueFactory().createIRI(theURI);
//
// if (theType != null) {
// mGraph.add(aRes, RDF.TYPE, theType);
// }
//
// return new ResourceBuilder(mGraph, getValueFactory(), aRes);
// }
//
// public ValueFactory getValueFactory() {
// return mValueFactory;
// }
// }
| import static org.junit.Assert.assertEquals;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import javax.xml.datatype.DatatypeFactory;
import com.complexible.common.openrdf.util.ModelBuilder;
import org.junit.Test;
import org.openrdf.model.IRI;
import org.openrdf.model.Literal;
import org.openrdf.model.Model;
import org.openrdf.model.Statement;
import org.openrdf.model.impl.SimpleValueFactory;
import org.openrdf.model.impl.ValueFactoryImpl;
import org.openrdf.model.vocabulary.XMLSchema; | /*
* Copyright (c) 2009-2015 Clark & Parsia, LLC. <http://www.clarkparsia.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.
*/
package com.complexible.common.openrdf;
/**
* <p></p>
*
* @author Michael Grove
* @since 3.0
* @version 3.0
*/
public class GraphBuilderTests {
@Test
public void createDate() throws Exception {
final IRI aURI = SimpleValueFactory.getInstance().createIRI("urn:foo"); | // Path: core/main/src/com/complexible/common/openrdf/util/ModelBuilder.java
// public class ModelBuilder {
// private final Model mGraph;
// private final ValueFactory mValueFactory;
//
// public ModelBuilder() {
// mGraph = Models2.newModel();
// mValueFactory = SimpleValueFactory.getInstance();
// }
//
// public ModelBuilder(final ValueFactory theValueFactory) {
// mGraph = Models2.newModel();
// mValueFactory = theValueFactory;
// }
//
// /**
// * Return the Graph created via this builder
// *
// * @return the graph
// */
// public Model model() {
// return Models2.newModel(mGraph);
// }
//
// /**
// * Clear the contents of the builder
// */
// public void reset() {
// mGraph.clear();
// }
//
// /**
// * Create a {@link ResourceBuilder builder} for the individual
// * @param theURI the individual
// * @return the {@link ResourceBuilder builder}
// */
// public ResourceBuilder iri(IRI theURI) {
// return new ResourceBuilder(mGraph, getValueFactory(), getValueFactory().createIRI(theURI.toString()));
// }
//
// /**
// * Create a {@link ResourceBuilder builder} for the individual
// * @param theURI the individual
// * @return the {@link ResourceBuilder builder}
// */
// public ResourceBuilder iri(String theURI) {
// return instance(null, theURI);
// }
//
// /**
// * Create a new anonymous instance of the given type
// *
// * @param theType the type
// *
// * @return a {@link ResourceBuilder builder} for the new individual
// */
// public ResourceBuilder instance(IRI theType) {
// return instance(theType, (String) null);
// }
//
// /**
// * Create an un-typed anonymous individual in the graph
// *
// * @return a ResourceBuilder wrapping the bnode
// */
// public ResourceBuilder instance() {
// return instance(null, (String) null);
// }
//
//
// /**
// * Create a {@link ResourceBuilder builder} for the given individual and add the type
// *
// * @param theType the type
// * @param theURI the individual
// *
// * @return a {@link ResourceBuilder builder} for the new individual
// */
// public ResourceBuilder instance(IRI theType, java.net.URI theURI) {
// return instance(theType, theURI.toString());
// }
//
// /**
// * Create a {@link ResourceBuilder builder} for the given individual and add the type
// *
// * @param theType the type
// * @param theRes the individual
// *
// * @return a {@link ResourceBuilder builder} for the new individual
// */
// public ResourceBuilder instance(IRI theType, Resource theRes) {
// if (theType != null) {
// mGraph.add(theRes, RDF.TYPE, theType);
// }
//
// return new ResourceBuilder(mGraph, getValueFactory(), theRes);
// }
// /**
// * Create a {@link ResourceBuilder builder} for the given individual and add the type
// *
// * @param theType the type
// * @param theURI the individual
// *
// * @return a {@link ResourceBuilder builder} for the new individual
// */
// public ResourceBuilder instance(IRI theType, String theURI) {
// Resource aRes = theURI == null
// ? getValueFactory().createBNode()
// : getValueFactory().createIRI(theURI);
//
// if (theType != null) {
// mGraph.add(aRes, RDF.TYPE, theType);
// }
//
// return new ResourceBuilder(mGraph, getValueFactory(), aRes);
// }
//
// public ValueFactory getValueFactory() {
// return mValueFactory;
// }
// }
// Path: core/test/src/com/complexible/common/openrdf/GraphBuilderTests.java
import static org.junit.Assert.assertEquals;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import javax.xml.datatype.DatatypeFactory;
import com.complexible.common.openrdf.util.ModelBuilder;
import org.junit.Test;
import org.openrdf.model.IRI;
import org.openrdf.model.Literal;
import org.openrdf.model.Model;
import org.openrdf.model.Statement;
import org.openrdf.model.impl.SimpleValueFactory;
import org.openrdf.model.impl.ValueFactoryImpl;
import org.openrdf.model.vocabulary.XMLSchema;
/*
* Copyright (c) 2009-2015 Clark & Parsia, LLC. <http://www.clarkparsia.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.
*/
package com.complexible.common.openrdf;
/**
* <p></p>
*
* @author Michael Grove
* @since 3.0
* @version 3.0
*/
public class GraphBuilderTests {
@Test
public void createDate() throws Exception {
final IRI aURI = SimpleValueFactory.getInstance().createIRI("urn:foo"); | ModelBuilder aBuilder = new ModelBuilder(); |
mhgrove/cp-openrdf-utils | core/main/src/com/complexible/common/openrdf/sail/Sails.java | // Path: core/main/src/com/complexible/common/openrdf/util/AdunaIterations.java
// public final class AdunaIterations {
// /**
// * the logger
// */
// private static final Logger LOGGER = LoggerFactory.getLogger(AdunaIterations.class);
//
// /**
// * Private constructor, no instances
// */
// private AdunaIterations() {
// throw new AssertionError();
// }
//
// /**
// * Quietly close the iteration
// * @param theCloseableIteration the iteration to close
// */
// public static void closeQuietly(final CloseableIteration<?,?> theCloseableIteration) {
// try {
// if (theCloseableIteration != null) {
// Iterations.closeCloseable(theCloseableIteration);
// }
// }
// catch (Exception e) {
// LOGGER.warn("Ignoring error while closing iteration.", e);
// }
// }
//
// /**
// * Return the first result of the iteration. If the Iteration is empty or null, the Optional will be absent.
// *
// * The Iteration is closed whether or not there is a result.
// *
// * @param theIter the iteration
// * @return an Optional containing the first result of the iteration, if present.
// * @throws E
// */
// public static <T, E extends Exception> Optional<T> singleResult(final CloseableIteration<T, E> theIter) throws E {
// if (theIter == null) {
// return Optional.empty();
// }
//
// try {
// return theIter.hasNext() ? Optional.of(theIter.next()) : Optional.<T>empty();
// }
// finally {
// theIter.close();
// }
// }
//
// /**
// * Consume all of the results in the Iteration and then close it when iteration is complete.
// * @param theIter the Iteration to consume
// * @throws E if there is an error while consuming the results
// */
// public static <T, E extends Exception> void consume(final CloseableIteration<T, E> theIter) throws E {
// if (theIter == null) {
// return;
// }
//
// try {
// while (theIter.hasNext()) {
// theIter.next();
// }
// }
// finally {
// theIter.close();
// }
// }
//
// /**
// * Return the number of elements left in the Iteration. The iteration is closed when complete.
// * @param theIter the Iteration whose size should be computed
// * @return the number of elements left
// * @throws E if there is an error while iterating
// */
// public static <T, E extends Exception> long size(final CloseableIteration<T, E> theIter) throws E {
// if (theIter == null) {
// return 0;
// }
//
// try {
// long aCount = 0;
// while (theIter.hasNext()) {
// theIter.next();
// aCount++;
// }
//
// return aCount;
// }
// finally {
// theIter.close();
// }
// }
// }
| import com.complexible.common.openrdf.util.AdunaIterations;
import info.aduna.iteration.CloseableIteration;
import org.openrdf.model.Graph;
import org.openrdf.model.Statement;
import org.openrdf.sail.Sail;
import org.openrdf.sail.SailConnection;
import org.openrdf.sail.SailException; | finally {
aConn.close();
}
}
public static void remove(final Sail theSail, final Graph theGraph) throws SailException {
SailConnection aConn = theSail.getConnection();
try {
SailConnections.remove(aConn, theGraph);
}
finally {
aConn.close();
}
}
public static boolean contains(final Sail theSail, final Statement theStmt) throws SailException {
SailConnection aConn = theSail.getConnection();
CloseableIteration<?,?> aIter = null;
try {
aIter =
theStmt.getContext() != null
? aConn.getStatements(theStmt.getSubject(), theStmt.getPredicate(), theStmt.getObject(), true, theStmt.getContext())
: aConn.getStatements(theStmt.getSubject(), theStmt.getPredicate(), theStmt.getObject(), true);
return aIter.hasNext();
}
catch (Exception e) {
throw new SailException(e);
}
finally { | // Path: core/main/src/com/complexible/common/openrdf/util/AdunaIterations.java
// public final class AdunaIterations {
// /**
// * the logger
// */
// private static final Logger LOGGER = LoggerFactory.getLogger(AdunaIterations.class);
//
// /**
// * Private constructor, no instances
// */
// private AdunaIterations() {
// throw new AssertionError();
// }
//
// /**
// * Quietly close the iteration
// * @param theCloseableIteration the iteration to close
// */
// public static void closeQuietly(final CloseableIteration<?,?> theCloseableIteration) {
// try {
// if (theCloseableIteration != null) {
// Iterations.closeCloseable(theCloseableIteration);
// }
// }
// catch (Exception e) {
// LOGGER.warn("Ignoring error while closing iteration.", e);
// }
// }
//
// /**
// * Return the first result of the iteration. If the Iteration is empty or null, the Optional will be absent.
// *
// * The Iteration is closed whether or not there is a result.
// *
// * @param theIter the iteration
// * @return an Optional containing the first result of the iteration, if present.
// * @throws E
// */
// public static <T, E extends Exception> Optional<T> singleResult(final CloseableIteration<T, E> theIter) throws E {
// if (theIter == null) {
// return Optional.empty();
// }
//
// try {
// return theIter.hasNext() ? Optional.of(theIter.next()) : Optional.<T>empty();
// }
// finally {
// theIter.close();
// }
// }
//
// /**
// * Consume all of the results in the Iteration and then close it when iteration is complete.
// * @param theIter the Iteration to consume
// * @throws E if there is an error while consuming the results
// */
// public static <T, E extends Exception> void consume(final CloseableIteration<T, E> theIter) throws E {
// if (theIter == null) {
// return;
// }
//
// try {
// while (theIter.hasNext()) {
// theIter.next();
// }
// }
// finally {
// theIter.close();
// }
// }
//
// /**
// * Return the number of elements left in the Iteration. The iteration is closed when complete.
// * @param theIter the Iteration whose size should be computed
// * @return the number of elements left
// * @throws E if there is an error while iterating
// */
// public static <T, E extends Exception> long size(final CloseableIteration<T, E> theIter) throws E {
// if (theIter == null) {
// return 0;
// }
//
// try {
// long aCount = 0;
// while (theIter.hasNext()) {
// theIter.next();
// aCount++;
// }
//
// return aCount;
// }
// finally {
// theIter.close();
// }
// }
// }
// Path: core/main/src/com/complexible/common/openrdf/sail/Sails.java
import com.complexible.common.openrdf.util.AdunaIterations;
import info.aduna.iteration.CloseableIteration;
import org.openrdf.model.Graph;
import org.openrdf.model.Statement;
import org.openrdf.sail.Sail;
import org.openrdf.sail.SailConnection;
import org.openrdf.sail.SailException;
finally {
aConn.close();
}
}
public static void remove(final Sail theSail, final Graph theGraph) throws SailException {
SailConnection aConn = theSail.getConnection();
try {
SailConnections.remove(aConn, theGraph);
}
finally {
aConn.close();
}
}
public static boolean contains(final Sail theSail, final Statement theStmt) throws SailException {
SailConnection aConn = theSail.getConnection();
CloseableIteration<?,?> aIter = null;
try {
aIter =
theStmt.getContext() != null
? aConn.getStatements(theStmt.getSubject(), theStmt.getPredicate(), theStmt.getObject(), true, theStmt.getContext())
: aConn.getStatements(theStmt.getSubject(), theStmt.getPredicate(), theStmt.getObject(), true);
return aIter.hasNext();
}
catch (Exception e) {
throw new SailException(e);
}
finally { | AdunaIterations.closeQuietly(aIter); |
mhgrove/cp-openrdf-utils | core/main/src/com/complexible/common/openrdf/model/ModelIO.java | // Path: core/main/src/com/complexible/common/openrdf/util/ModelBuildingRDFHandler.java
// public final class ModelBuildingRDFHandler extends AbstractRDFHandler {
//
// /**
// * The graph to collect statements in
// */
// private final Model mGraph;
//
// /**
// * Create a new GraphBuildingRDFHandler
// */
// public ModelBuildingRDFHandler() {
// this(Models2.newModel());
// }
//
// /**
// * Create a new GraphBuildingRDFHandler that will insert statements into the supplied Graph
// * @param theGraph the graph to insert into
// */
// public ModelBuildingRDFHandler(final Model theGraph) {
// mGraph = theGraph;
// }
//
// /**
// * {@inheritDoc}
// */
// @Override
// public void handleStatement(final Statement theStatement) throws RDFHandlerException {
// mGraph.add(theStatement);
// }
//
// /**
// * Return the graph built from events fired to this handler
// * @return the graph
// */
// public Model getModel() {
// return mGraph;
// }
//
// /**
// * Clear the underlying graph of all collected statements
// */
// public void clear() {
// mGraph.clear();
// }
// }
//
// Path: core/main/src/com/complexible/common/openrdf/util/RDFByteSource.java
// public abstract class RDFByteSource extends ByteSource {
//
// /**
// * Return the RDF format used by the source
// * @return the format
// */
// public abstract RDFFormat getFormat();
//
// /**
// * Return the base uri that should be used when parsing this source
// * @return the base
// */
// public String getBaseURI() {
// return "http://openrdf.clarkparsia.com";
// }
//
// public static RDFByteSource create(final ByteSource theSource, final RDFFormat theFormat) {
// return new RDFByteSource() {
// @Override
// public RDFFormat getFormat() {
// return theFormat;
// }
//
// @Override
// public InputStream openStream() throws IOException {
// return theSource.openStream();
// }
// };
// }
// }
| import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.Reader;
import java.io.StringWriter;
import java.io.Writer;
import java.nio.charset.Charset;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.Optional;
import com.complexible.common.openrdf.util.ModelBuildingRDFHandler;
import com.complexible.common.openrdf.util.RDFByteSource;
import com.google.common.base.Charsets;
import org.openrdf.model.Model;
import org.openrdf.model.Statement;
import org.openrdf.rio.RDFFormat;
import org.openrdf.rio.RDFHandler;
import org.openrdf.rio.RDFHandlerException;
import org.openrdf.rio.RDFParseException;
import org.openrdf.rio.RDFParser;
import org.openrdf.rio.RDFWriter;
import org.openrdf.rio.Rio;
import org.openrdf.rio.helpers.BasicParserSettings; | /*
* Copyright (c) 2009-2015 Clark & Parsia, LLC. <http://www.clarkparsia.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.
*/
package com.complexible.common.openrdf.model;
/**
* <p>Support for IO for {@link Model models}/</p>
*
* @author Michael Grove
* @since 4.0
* @version 4.0
*/
public final class ModelIO {
public static final String DEFAULT_BASE_URI = "http://openrdf.clarkparsia.com/";
private ModelIO() {
throw new AssertionError();
}
/**
* Read an RDF graph from the specified file
* @param theFile the file to read from
* @return the RDF graph contained in the file
*
* @throws IOException if there was an error reading from the file
* @throws RDFParseException if the RDF could not be parsed
*/
public static Model read(final Path theFile) throws IOException, RDFParseException {
return read(theFile, Rio.getParserFormatForFileName(theFile.getFileName().toString()).orElse(RDFFormat.TURTLE));
}
public static Model read(final Path theFile, final RDFFormat theFormat) throws IOException, RDFParseException {
return read(new InputStreamReader(Files.newInputStream(theFile), getCharset(theFormat).orElse(Charsets.UTF_8)),
theFormat,
DEFAULT_BASE_URI);
}
private static Optional<Charset> getCharset(final RDFFormat theFormat) {
return theFormat.hasCharset() ? Optional.of(theFormat.getCharset()) : Optional.empty();
}
| // Path: core/main/src/com/complexible/common/openrdf/util/ModelBuildingRDFHandler.java
// public final class ModelBuildingRDFHandler extends AbstractRDFHandler {
//
// /**
// * The graph to collect statements in
// */
// private final Model mGraph;
//
// /**
// * Create a new GraphBuildingRDFHandler
// */
// public ModelBuildingRDFHandler() {
// this(Models2.newModel());
// }
//
// /**
// * Create a new GraphBuildingRDFHandler that will insert statements into the supplied Graph
// * @param theGraph the graph to insert into
// */
// public ModelBuildingRDFHandler(final Model theGraph) {
// mGraph = theGraph;
// }
//
// /**
// * {@inheritDoc}
// */
// @Override
// public void handleStatement(final Statement theStatement) throws RDFHandlerException {
// mGraph.add(theStatement);
// }
//
// /**
// * Return the graph built from events fired to this handler
// * @return the graph
// */
// public Model getModel() {
// return mGraph;
// }
//
// /**
// * Clear the underlying graph of all collected statements
// */
// public void clear() {
// mGraph.clear();
// }
// }
//
// Path: core/main/src/com/complexible/common/openrdf/util/RDFByteSource.java
// public abstract class RDFByteSource extends ByteSource {
//
// /**
// * Return the RDF format used by the source
// * @return the format
// */
// public abstract RDFFormat getFormat();
//
// /**
// * Return the base uri that should be used when parsing this source
// * @return the base
// */
// public String getBaseURI() {
// return "http://openrdf.clarkparsia.com";
// }
//
// public static RDFByteSource create(final ByteSource theSource, final RDFFormat theFormat) {
// return new RDFByteSource() {
// @Override
// public RDFFormat getFormat() {
// return theFormat;
// }
//
// @Override
// public InputStream openStream() throws IOException {
// return theSource.openStream();
// }
// };
// }
// }
// Path: core/main/src/com/complexible/common/openrdf/model/ModelIO.java
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.Reader;
import java.io.StringWriter;
import java.io.Writer;
import java.nio.charset.Charset;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.Optional;
import com.complexible.common.openrdf.util.ModelBuildingRDFHandler;
import com.complexible.common.openrdf.util.RDFByteSource;
import com.google.common.base.Charsets;
import org.openrdf.model.Model;
import org.openrdf.model.Statement;
import org.openrdf.rio.RDFFormat;
import org.openrdf.rio.RDFHandler;
import org.openrdf.rio.RDFHandlerException;
import org.openrdf.rio.RDFParseException;
import org.openrdf.rio.RDFParser;
import org.openrdf.rio.RDFWriter;
import org.openrdf.rio.Rio;
import org.openrdf.rio.helpers.BasicParserSettings;
/*
* Copyright (c) 2009-2015 Clark & Parsia, LLC. <http://www.clarkparsia.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.
*/
package com.complexible.common.openrdf.model;
/**
* <p>Support for IO for {@link Model models}/</p>
*
* @author Michael Grove
* @since 4.0
* @version 4.0
*/
public final class ModelIO {
public static final String DEFAULT_BASE_URI = "http://openrdf.clarkparsia.com/";
private ModelIO() {
throw new AssertionError();
}
/**
* Read an RDF graph from the specified file
* @param theFile the file to read from
* @return the RDF graph contained in the file
*
* @throws IOException if there was an error reading from the file
* @throws RDFParseException if the RDF could not be parsed
*/
public static Model read(final Path theFile) throws IOException, RDFParseException {
return read(theFile, Rio.getParserFormatForFileName(theFile.getFileName().toString()).orElse(RDFFormat.TURTLE));
}
public static Model read(final Path theFile, final RDFFormat theFormat) throws IOException, RDFParseException {
return read(new InputStreamReader(Files.newInputStream(theFile), getCharset(theFormat).orElse(Charsets.UTF_8)),
theFormat,
DEFAULT_BASE_URI);
}
private static Optional<Charset> getCharset(final RDFFormat theFormat) {
return theFormat.hasCharset() ? Optional.of(theFormat.getCharset()) : Optional.empty();
}
| public static Model read(final RDFByteSource theSource) throws IOException, RDFParseException { |
mhgrove/cp-openrdf-utils | core/main/src/com/complexible/common/openrdf/model/ModelIO.java | // Path: core/main/src/com/complexible/common/openrdf/util/ModelBuildingRDFHandler.java
// public final class ModelBuildingRDFHandler extends AbstractRDFHandler {
//
// /**
// * The graph to collect statements in
// */
// private final Model mGraph;
//
// /**
// * Create a new GraphBuildingRDFHandler
// */
// public ModelBuildingRDFHandler() {
// this(Models2.newModel());
// }
//
// /**
// * Create a new GraphBuildingRDFHandler that will insert statements into the supplied Graph
// * @param theGraph the graph to insert into
// */
// public ModelBuildingRDFHandler(final Model theGraph) {
// mGraph = theGraph;
// }
//
// /**
// * {@inheritDoc}
// */
// @Override
// public void handleStatement(final Statement theStatement) throws RDFHandlerException {
// mGraph.add(theStatement);
// }
//
// /**
// * Return the graph built from events fired to this handler
// * @return the graph
// */
// public Model getModel() {
// return mGraph;
// }
//
// /**
// * Clear the underlying graph of all collected statements
// */
// public void clear() {
// mGraph.clear();
// }
// }
//
// Path: core/main/src/com/complexible/common/openrdf/util/RDFByteSource.java
// public abstract class RDFByteSource extends ByteSource {
//
// /**
// * Return the RDF format used by the source
// * @return the format
// */
// public abstract RDFFormat getFormat();
//
// /**
// * Return the base uri that should be used when parsing this source
// * @return the base
// */
// public String getBaseURI() {
// return "http://openrdf.clarkparsia.com";
// }
//
// public static RDFByteSource create(final ByteSource theSource, final RDFFormat theFormat) {
// return new RDFByteSource() {
// @Override
// public RDFFormat getFormat() {
// return theFormat;
// }
//
// @Override
// public InputStream openStream() throws IOException {
// return theSource.openStream();
// }
// };
// }
// }
| import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.Reader;
import java.io.StringWriter;
import java.io.Writer;
import java.nio.charset.Charset;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.Optional;
import com.complexible.common.openrdf.util.ModelBuildingRDFHandler;
import com.complexible.common.openrdf.util.RDFByteSource;
import com.google.common.base.Charsets;
import org.openrdf.model.Model;
import org.openrdf.model.Statement;
import org.openrdf.rio.RDFFormat;
import org.openrdf.rio.RDFHandler;
import org.openrdf.rio.RDFHandlerException;
import org.openrdf.rio.RDFParseException;
import org.openrdf.rio.RDFParser;
import org.openrdf.rio.RDFWriter;
import org.openrdf.rio.Rio;
import org.openrdf.rio.helpers.BasicParserSettings; | * @param theFormat the format the data is in
* @param theBase the base url used for parsing
* @return the graph represented by the data from the stream
* @throws IOException if there is an error while reading
* @throws RDFParseException if there is an error while trying to parse the data as the specified format
*/
public static Model read(InputStream theInput, RDFFormat theFormat, final String theBase) throws IOException, RDFParseException {
return read(new InputStreamReader(theInput, getCharset(theFormat).orElse(Charsets.UTF_8)), theFormat, theBase);
}
/**
* Read an RDF graph from the Reader using the specified format. The reader is closed after parsing.
*
* @param theInput the reader to read from
* @param theFormat the format the data is in
* @param theBase the base url for parsing
*
* @return the graph represented by the data from the stream
*
* @throws IOException if there is an error while reading
* @throws RDFParseException if there is an error while trying to parse the data as the specified format
*/
public static Model read(final Reader theInput, final RDFFormat theFormat, final String theBase) throws IOException, RDFParseException {
RDFParser aParser = Rio.createParser(theFormat);
aParser.getParserConfig().set(BasicParserSettings.VERIFY_DATATYPE_VALUES, false);
aParser.getParserConfig().set(BasicParserSettings.FAIL_ON_UNKNOWN_DATATYPES, false);
aParser.getParserConfig().set(BasicParserSettings.NORMALIZE_DATATYPE_VALUES, false);
aParser.getParserConfig().set(BasicParserSettings.PRESERVE_BNODE_IDS, true);
| // Path: core/main/src/com/complexible/common/openrdf/util/ModelBuildingRDFHandler.java
// public final class ModelBuildingRDFHandler extends AbstractRDFHandler {
//
// /**
// * The graph to collect statements in
// */
// private final Model mGraph;
//
// /**
// * Create a new GraphBuildingRDFHandler
// */
// public ModelBuildingRDFHandler() {
// this(Models2.newModel());
// }
//
// /**
// * Create a new GraphBuildingRDFHandler that will insert statements into the supplied Graph
// * @param theGraph the graph to insert into
// */
// public ModelBuildingRDFHandler(final Model theGraph) {
// mGraph = theGraph;
// }
//
// /**
// * {@inheritDoc}
// */
// @Override
// public void handleStatement(final Statement theStatement) throws RDFHandlerException {
// mGraph.add(theStatement);
// }
//
// /**
// * Return the graph built from events fired to this handler
// * @return the graph
// */
// public Model getModel() {
// return mGraph;
// }
//
// /**
// * Clear the underlying graph of all collected statements
// */
// public void clear() {
// mGraph.clear();
// }
// }
//
// Path: core/main/src/com/complexible/common/openrdf/util/RDFByteSource.java
// public abstract class RDFByteSource extends ByteSource {
//
// /**
// * Return the RDF format used by the source
// * @return the format
// */
// public abstract RDFFormat getFormat();
//
// /**
// * Return the base uri that should be used when parsing this source
// * @return the base
// */
// public String getBaseURI() {
// return "http://openrdf.clarkparsia.com";
// }
//
// public static RDFByteSource create(final ByteSource theSource, final RDFFormat theFormat) {
// return new RDFByteSource() {
// @Override
// public RDFFormat getFormat() {
// return theFormat;
// }
//
// @Override
// public InputStream openStream() throws IOException {
// return theSource.openStream();
// }
// };
// }
// }
// Path: core/main/src/com/complexible/common/openrdf/model/ModelIO.java
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.Reader;
import java.io.StringWriter;
import java.io.Writer;
import java.nio.charset.Charset;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.Optional;
import com.complexible.common.openrdf.util.ModelBuildingRDFHandler;
import com.complexible.common.openrdf.util.RDFByteSource;
import com.google.common.base.Charsets;
import org.openrdf.model.Model;
import org.openrdf.model.Statement;
import org.openrdf.rio.RDFFormat;
import org.openrdf.rio.RDFHandler;
import org.openrdf.rio.RDFHandlerException;
import org.openrdf.rio.RDFParseException;
import org.openrdf.rio.RDFParser;
import org.openrdf.rio.RDFWriter;
import org.openrdf.rio.Rio;
import org.openrdf.rio.helpers.BasicParserSettings;
* @param theFormat the format the data is in
* @param theBase the base url used for parsing
* @return the graph represented by the data from the stream
* @throws IOException if there is an error while reading
* @throws RDFParseException if there is an error while trying to parse the data as the specified format
*/
public static Model read(InputStream theInput, RDFFormat theFormat, final String theBase) throws IOException, RDFParseException {
return read(new InputStreamReader(theInput, getCharset(theFormat).orElse(Charsets.UTF_8)), theFormat, theBase);
}
/**
* Read an RDF graph from the Reader using the specified format. The reader is closed after parsing.
*
* @param theInput the reader to read from
* @param theFormat the format the data is in
* @param theBase the base url for parsing
*
* @return the graph represented by the data from the stream
*
* @throws IOException if there is an error while reading
* @throws RDFParseException if there is an error while trying to parse the data as the specified format
*/
public static Model read(final Reader theInput, final RDFFormat theFormat, final String theBase) throws IOException, RDFParseException {
RDFParser aParser = Rio.createParser(theFormat);
aParser.getParserConfig().set(BasicParserSettings.VERIFY_DATATYPE_VALUES, false);
aParser.getParserConfig().set(BasicParserSettings.FAIL_ON_UNKNOWN_DATATYPES, false);
aParser.getParserConfig().set(BasicParserSettings.NORMALIZE_DATATYPE_VALUES, false);
aParser.getParserConfig().set(BasicParserSettings.PRESERVE_BNODE_IDS, true);
| ModelBuildingRDFHandler aHandler = new ModelBuildingRDFHandler(); |
mhgrove/cp-openrdf-utils | core/test/src/com/complexible/common/openrdf/ConstrainedModelTests.java | // Path: core/main/src/com/complexible/common/openrdf/model/ConstrainedModel.java
// public final class ConstrainedModel extends DelegatingModel {
// private final Predicate<Statement> mConstraint;
//
// ConstrainedModel(final Model theGraph, final Predicate<Statement> theConstraint) {
// super(theGraph);
// mConstraint = theConstraint;
// }
//
// /**
// * Create a new empty, ConstrainedGraph, which will have the specified constraint place on all additions
// *
// * @param theConstraint the constraint to enforce
// * @return the new ConstrainedGraph
// */
// public static ConstrainedModel of(final Predicate<Statement> theConstraint) {
// return of(Models2.newModel(), theConstraint);
// }
//
// /**
// * Create a new ConstrainedGraph which will have the specified constraint enforced on all additions. Does not
// * retroactively enforce the constraint, so the provided Graph can contain invalid elements.
// *
// * @param theGraph the graph to constrain
// * @param theConstraint the constraint to enforce
// * @return the new ConstrainedGraph
// */
// public static ConstrainedModel of(final Model theGraph, final Predicate<Statement> theConstraint) {
// return new ConstrainedModel(theGraph, theConstraint);
// }
//
// /**
// * Return a {@link Predicate} which will only allow {@link Statements#isLiteralValid(Literal) valid} literals into the graph.
// *
// * @return a Constraint to enforce valid literals
// */
// public static Predicate<Statement> onlyValidLiterals() {
// return theStatement -> {
// if (theStatement.getObject() instanceof Literal && !Statements.isLiteralValid((Literal) theStatement.getObject())) {
// throw new StatementViolatedConstraintException(theStatement.getObject() + " is not a well-formed literal value.");
// }
//
// return true;
// };
// }
//
// /**
// * {@inheritDoc}
// */
// @Override
// public boolean add(final Statement e) {
// mConstraint.test(e);
//
// return super.add(e);
// }
//
// /**
// * {@inheritDoc}
// */
// @Override
// @SuppressWarnings("unchecked")
// public boolean add(final Resource theResource, final IRI theURI, final Value theValue, final Resource... theContexts) {
//
// if (theContexts == null || theContexts.length == 0) {
// return add(getValueFactory().createStatement(theResource, theURI, theValue));
// }
// else {
// boolean aAdded = true;
// for (Resource aCxt : theContexts) {
// aAdded |= add(getValueFactory().createStatement(theResource, theURI, theValue, aCxt));
// }
//
// return aAdded;
// }
// }
//
// /**
// * {@inheritDoc}
// */
// @Override
// public boolean addAll(final Collection<? extends Statement> c) {
// all(c, mConstraint);
//
// return super.addAll(c);
// }
//
// private static <T> void all(final Iterable<? extends T> theObjects, final Predicate<T> theConstraint) {
// for (T aObj : theObjects) {
// theConstraint.test(aObj);
// }
// }
//
// /**
// * A runtime exception suitable for being thrown from a {@link Predicate} on a {@link Statement}
// */
// public static class StatementViolatedConstraintException extends RuntimeException {
//
// /**
// * Create a new StatementViolatedConstraintException
// * @param theMessage a note about why the constraint was violated
// */
// public StatementViolatedConstraintException(final String theMessage) {
// super(theMessage);
// }
// }
// }
| import java.util.function.Predicate;
import com.complexible.common.openrdf.model.ConstrainedModel;
import org.junit.Test;
import org.openrdf.model.BNode;
import org.openrdf.model.Model;
import org.openrdf.model.Statement;
import org.openrdf.model.impl.SimpleValueFactory;
import org.openrdf.model.vocabulary.RDF;
import static org.junit.Assert.fail; | /*
* Copyright (c) 2009-2012 Clark & Parsia, LLC. <http://www.clarkparsia.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.
*/
package com.complexible.common.openrdf;
/**
* <p></p>
*
* @author Michael Grove
* @version 0
* @since 0
*/
public class ConstrainedModelTests {
@Test
public void testCannotAddViolatingConstraint() {
Predicate<Statement> noBNodes = theStatement -> {
if (theStatement.getSubject() instanceof BNode ||
theStatement.getObject() instanceof BNode) { | // Path: core/main/src/com/complexible/common/openrdf/model/ConstrainedModel.java
// public final class ConstrainedModel extends DelegatingModel {
// private final Predicate<Statement> mConstraint;
//
// ConstrainedModel(final Model theGraph, final Predicate<Statement> theConstraint) {
// super(theGraph);
// mConstraint = theConstraint;
// }
//
// /**
// * Create a new empty, ConstrainedGraph, which will have the specified constraint place on all additions
// *
// * @param theConstraint the constraint to enforce
// * @return the new ConstrainedGraph
// */
// public static ConstrainedModel of(final Predicate<Statement> theConstraint) {
// return of(Models2.newModel(), theConstraint);
// }
//
// /**
// * Create a new ConstrainedGraph which will have the specified constraint enforced on all additions. Does not
// * retroactively enforce the constraint, so the provided Graph can contain invalid elements.
// *
// * @param theGraph the graph to constrain
// * @param theConstraint the constraint to enforce
// * @return the new ConstrainedGraph
// */
// public static ConstrainedModel of(final Model theGraph, final Predicate<Statement> theConstraint) {
// return new ConstrainedModel(theGraph, theConstraint);
// }
//
// /**
// * Return a {@link Predicate} which will only allow {@link Statements#isLiteralValid(Literal) valid} literals into the graph.
// *
// * @return a Constraint to enforce valid literals
// */
// public static Predicate<Statement> onlyValidLiterals() {
// return theStatement -> {
// if (theStatement.getObject() instanceof Literal && !Statements.isLiteralValid((Literal) theStatement.getObject())) {
// throw new StatementViolatedConstraintException(theStatement.getObject() + " is not a well-formed literal value.");
// }
//
// return true;
// };
// }
//
// /**
// * {@inheritDoc}
// */
// @Override
// public boolean add(final Statement e) {
// mConstraint.test(e);
//
// return super.add(e);
// }
//
// /**
// * {@inheritDoc}
// */
// @Override
// @SuppressWarnings("unchecked")
// public boolean add(final Resource theResource, final IRI theURI, final Value theValue, final Resource... theContexts) {
//
// if (theContexts == null || theContexts.length == 0) {
// return add(getValueFactory().createStatement(theResource, theURI, theValue));
// }
// else {
// boolean aAdded = true;
// for (Resource aCxt : theContexts) {
// aAdded |= add(getValueFactory().createStatement(theResource, theURI, theValue, aCxt));
// }
//
// return aAdded;
// }
// }
//
// /**
// * {@inheritDoc}
// */
// @Override
// public boolean addAll(final Collection<? extends Statement> c) {
// all(c, mConstraint);
//
// return super.addAll(c);
// }
//
// private static <T> void all(final Iterable<? extends T> theObjects, final Predicate<T> theConstraint) {
// for (T aObj : theObjects) {
// theConstraint.test(aObj);
// }
// }
//
// /**
// * A runtime exception suitable for being thrown from a {@link Predicate} on a {@link Statement}
// */
// public static class StatementViolatedConstraintException extends RuntimeException {
//
// /**
// * Create a new StatementViolatedConstraintException
// * @param theMessage a note about why the constraint was violated
// */
// public StatementViolatedConstraintException(final String theMessage) {
// super(theMessage);
// }
// }
// }
// Path: core/test/src/com/complexible/common/openrdf/ConstrainedModelTests.java
import java.util.function.Predicate;
import com.complexible.common.openrdf.model.ConstrainedModel;
import org.junit.Test;
import org.openrdf.model.BNode;
import org.openrdf.model.Model;
import org.openrdf.model.Statement;
import org.openrdf.model.impl.SimpleValueFactory;
import org.openrdf.model.vocabulary.RDF;
import static org.junit.Assert.fail;
/*
* Copyright (c) 2009-2012 Clark & Parsia, LLC. <http://www.clarkparsia.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.
*/
package com.complexible.common.openrdf;
/**
* <p></p>
*
* @author Michael Grove
* @version 0
* @since 0
*/
public class ConstrainedModelTests {
@Test
public void testCannotAddViolatingConstraint() {
Predicate<Statement> noBNodes = theStatement -> {
if (theStatement.getSubject() instanceof BNode ||
theStatement.getObject() instanceof BNode) { | throw new ConstrainedModel.StatementViolatedConstraintException("Cannot add statements with bnodes to this graph"); |
mhgrove/cp-openrdf-utils | core/main/src/com/complexible/common/openrdf/sail/SailConnections.java | // Path: core/main/src/com/complexible/common/openrdf/util/AdunaIterations.java
// public final class AdunaIterations {
// /**
// * the logger
// */
// private static final Logger LOGGER = LoggerFactory.getLogger(AdunaIterations.class);
//
// /**
// * Private constructor, no instances
// */
// private AdunaIterations() {
// throw new AssertionError();
// }
//
// /**
// * Quietly close the iteration
// * @param theCloseableIteration the iteration to close
// */
// public static void closeQuietly(final CloseableIteration<?,?> theCloseableIteration) {
// try {
// if (theCloseableIteration != null) {
// Iterations.closeCloseable(theCloseableIteration);
// }
// }
// catch (Exception e) {
// LOGGER.warn("Ignoring error while closing iteration.", e);
// }
// }
//
// /**
// * Return the first result of the iteration. If the Iteration is empty or null, the Optional will be absent.
// *
// * The Iteration is closed whether or not there is a result.
// *
// * @param theIter the iteration
// * @return an Optional containing the first result of the iteration, if present.
// * @throws E
// */
// public static <T, E extends Exception> Optional<T> singleResult(final CloseableIteration<T, E> theIter) throws E {
// if (theIter == null) {
// return Optional.empty();
// }
//
// try {
// return theIter.hasNext() ? Optional.of(theIter.next()) : Optional.<T>empty();
// }
// finally {
// theIter.close();
// }
// }
//
// /**
// * Consume all of the results in the Iteration and then close it when iteration is complete.
// * @param theIter the Iteration to consume
// * @throws E if there is an error while consuming the results
// */
// public static <T, E extends Exception> void consume(final CloseableIteration<T, E> theIter) throws E {
// if (theIter == null) {
// return;
// }
//
// try {
// while (theIter.hasNext()) {
// theIter.next();
// }
// }
// finally {
// theIter.close();
// }
// }
//
// /**
// * Return the number of elements left in the Iteration. The iteration is closed when complete.
// * @param theIter the Iteration whose size should be computed
// * @return the number of elements left
// * @throws E if there is an error while iterating
// */
// public static <T, E extends Exception> long size(final CloseableIteration<T, E> theIter) throws E {
// if (theIter == null) {
// return 0;
// }
//
// try {
// long aCount = 0;
// while (theIter.hasNext()) {
// theIter.next();
// aCount++;
// }
//
// return aCount;
// }
// finally {
// theIter.close();
// }
// }
// }
| import com.complexible.common.openrdf.util.AdunaIterations;
import info.aduna.iteration.CloseableIteration;
import org.openrdf.model.Graph;
import org.openrdf.model.Resource;
import org.openrdf.model.Statement;
import org.openrdf.sail.SailConnection;
import org.openrdf.sail.SailException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory; | }
public static void remove(final SailConnection theConnection, final Graph theGraph) throws SailException {
try {
theConnection.begin();
for (Statement aStmt : theGraph) {
if (aStmt.getContext() != null) {
theConnection.removeStatements(aStmt.getSubject(), aStmt.getPredicate(), aStmt.getObject(), aStmt.getContext());
}
else {
theConnection.removeStatements(aStmt.getSubject(), aStmt.getPredicate(), aStmt.getObject());
}
}
theConnection.commit();
}
catch (SailException e) {
theConnection.rollback();
throw e;
}
}
public static boolean contains(final SailConnection theConnection, final Statement theStmt) throws SailException {
CloseableIteration<?,SailException> aIter = theStmt.getContext() == null
? theConnection.getStatements(theStmt.getSubject(), theStmt.getPredicate(), theStmt.getObject(), true)
: theConnection.getStatements(theStmt.getSubject(), theStmt.getPredicate(), theStmt.getObject(), true, theStmt.getContext());
try {
return aIter.hasNext();
}
finally { | // Path: core/main/src/com/complexible/common/openrdf/util/AdunaIterations.java
// public final class AdunaIterations {
// /**
// * the logger
// */
// private static final Logger LOGGER = LoggerFactory.getLogger(AdunaIterations.class);
//
// /**
// * Private constructor, no instances
// */
// private AdunaIterations() {
// throw new AssertionError();
// }
//
// /**
// * Quietly close the iteration
// * @param theCloseableIteration the iteration to close
// */
// public static void closeQuietly(final CloseableIteration<?,?> theCloseableIteration) {
// try {
// if (theCloseableIteration != null) {
// Iterations.closeCloseable(theCloseableIteration);
// }
// }
// catch (Exception e) {
// LOGGER.warn("Ignoring error while closing iteration.", e);
// }
// }
//
// /**
// * Return the first result of the iteration. If the Iteration is empty or null, the Optional will be absent.
// *
// * The Iteration is closed whether or not there is a result.
// *
// * @param theIter the iteration
// * @return an Optional containing the first result of the iteration, if present.
// * @throws E
// */
// public static <T, E extends Exception> Optional<T> singleResult(final CloseableIteration<T, E> theIter) throws E {
// if (theIter == null) {
// return Optional.empty();
// }
//
// try {
// return theIter.hasNext() ? Optional.of(theIter.next()) : Optional.<T>empty();
// }
// finally {
// theIter.close();
// }
// }
//
// /**
// * Consume all of the results in the Iteration and then close it when iteration is complete.
// * @param theIter the Iteration to consume
// * @throws E if there is an error while consuming the results
// */
// public static <T, E extends Exception> void consume(final CloseableIteration<T, E> theIter) throws E {
// if (theIter == null) {
// return;
// }
//
// try {
// while (theIter.hasNext()) {
// theIter.next();
// }
// }
// finally {
// theIter.close();
// }
// }
//
// /**
// * Return the number of elements left in the Iteration. The iteration is closed when complete.
// * @param theIter the Iteration whose size should be computed
// * @return the number of elements left
// * @throws E if there is an error while iterating
// */
// public static <T, E extends Exception> long size(final CloseableIteration<T, E> theIter) throws E {
// if (theIter == null) {
// return 0;
// }
//
// try {
// long aCount = 0;
// while (theIter.hasNext()) {
// theIter.next();
// aCount++;
// }
//
// return aCount;
// }
// finally {
// theIter.close();
// }
// }
// }
// Path: core/main/src/com/complexible/common/openrdf/sail/SailConnections.java
import com.complexible.common.openrdf.util.AdunaIterations;
import info.aduna.iteration.CloseableIteration;
import org.openrdf.model.Graph;
import org.openrdf.model.Resource;
import org.openrdf.model.Statement;
import org.openrdf.sail.SailConnection;
import org.openrdf.sail.SailException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
}
public static void remove(final SailConnection theConnection, final Graph theGraph) throws SailException {
try {
theConnection.begin();
for (Statement aStmt : theGraph) {
if (aStmt.getContext() != null) {
theConnection.removeStatements(aStmt.getSubject(), aStmt.getPredicate(), aStmt.getObject(), aStmt.getContext());
}
else {
theConnection.removeStatements(aStmt.getSubject(), aStmt.getPredicate(), aStmt.getObject());
}
}
theConnection.commit();
}
catch (SailException e) {
theConnection.rollback();
throw e;
}
}
public static boolean contains(final SailConnection theConnection, final Statement theStmt) throws SailException {
CloseableIteration<?,SailException> aIter = theStmt.getContext() == null
? theConnection.getStatements(theStmt.getSubject(), theStmt.getPredicate(), theStmt.getObject(), true)
: theConnection.getStatements(theStmt.getSubject(), theStmt.getPredicate(), theStmt.getObject(), true, theStmt.getContext());
try {
return aIter.hasNext();
}
finally { | AdunaIterations.closeQuietly(aIter); |
sumeetchhetri/gatf | alldep-jar/src/main/java/com/gatf/executor/dataprovider/GatfTestDataConfig.java | // Path: alldep-jar/src/main/java/com/gatf/executor/core/MapKeyValueCustomXstreamConverter.java
// public class MapKeyValueCustomXstreamConverter implements Converter
// {
// @SuppressWarnings("rawtypes")
// public boolean canConvert(final Class clazz)
// {
// return AbstractMap.class.isAssignableFrom(clazz);
// }
//
// @SuppressWarnings("unchecked")
// public void marshal(final Object value, final HierarchicalStreamWriter writer, final MarshallingContext context)
// {
// final AbstractMap<String, String> map = (AbstractMap<String, String>) value;
// for (final Entry<String, String> entry : map.entrySet())
// {
// writer.startNode(entry.getKey().toString());
// writer.setValue(entry.getValue().toString());
// writer.endNode();
// }
// }
//
// public Object unmarshal(final HierarchicalStreamReader reader, final UnmarshallingContext context)
// {
// final AbstractMap<String, String> map = new HashMap<String, String>();
// while (reader.hasMoreChildren())
// {
// reader.moveDown();
// map.put(reader.getNodeName(), reader.getValue());
// reader.moveUp();
// }
// return map;
// }
// }
| import java.io.Serializable;
import java.util.List;
import java.util.Map;
import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.JsonAutoDetect.Visibility;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonInclude.Include;
import com.gatf.executor.core.MapKeyValueCustomXstreamConverter;
import com.thoughtworks.xstream.annotations.XStreamAlias;
import com.thoughtworks.xstream.annotations.XStreamConverter;
| /*
Copyright 2013-2019, Sumeet Chhetri
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package com.gatf.executor.dataprovider;
/**
* @author Sumeet Chhetri
* The Test data configuration properties
*/
@XStreamAlias("gatf-testdata-config")
@JsonAutoDetect(getterVisibility=Visibility.NONE, fieldVisibility=Visibility.ANY, isGetterVisibility=Visibility.NONE)
@JsonInclude(value = Include.NON_NULL)
public class GatfTestDataConfig implements Serializable {
private static final long serialVersionUID = 1L;
| // Path: alldep-jar/src/main/java/com/gatf/executor/core/MapKeyValueCustomXstreamConverter.java
// public class MapKeyValueCustomXstreamConverter implements Converter
// {
// @SuppressWarnings("rawtypes")
// public boolean canConvert(final Class clazz)
// {
// return AbstractMap.class.isAssignableFrom(clazz);
// }
//
// @SuppressWarnings("unchecked")
// public void marshal(final Object value, final HierarchicalStreamWriter writer, final MarshallingContext context)
// {
// final AbstractMap<String, String> map = (AbstractMap<String, String>) value;
// for (final Entry<String, String> entry : map.entrySet())
// {
// writer.startNode(entry.getKey().toString());
// writer.setValue(entry.getValue().toString());
// writer.endNode();
// }
// }
//
// public Object unmarshal(final HierarchicalStreamReader reader, final UnmarshallingContext context)
// {
// final AbstractMap<String, String> map = new HashMap<String, String>();
// while (reader.hasMoreChildren())
// {
// reader.moveDown();
// map.put(reader.getNodeName(), reader.getValue());
// reader.moveUp();
// }
// return map;
// }
// }
// Path: alldep-jar/src/main/java/com/gatf/executor/dataprovider/GatfTestDataConfig.java
import java.io.Serializable;
import java.util.List;
import java.util.Map;
import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.JsonAutoDetect.Visibility;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonInclude.Include;
import com.gatf.executor.core.MapKeyValueCustomXstreamConverter;
import com.thoughtworks.xstream.annotations.XStreamAlias;
import com.thoughtworks.xstream.annotations.XStreamConverter;
/*
Copyright 2013-2019, Sumeet Chhetri
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package com.gatf.executor.dataprovider;
/**
* @author Sumeet Chhetri
* The Test data configuration properties
*/
@XStreamAlias("gatf-testdata-config")
@JsonAutoDetect(getterVisibility=Visibility.NONE, fieldVisibility=Visibility.ANY, isGetterVisibility=Visibility.NONE)
@JsonInclude(value = Include.NON_NULL)
public class GatfTestDataConfig implements Serializable {
private static final long serialVersionUID = 1L;
| @XStreamConverter(value=MapKeyValueCustomXstreamConverter.class)
|
sumeetchhetri/gatf | alldep-jar/src/main/java/com/gatf/selenium/SeleniumTestSession.java | // Path: alldep-jar/src/main/java/com/gatf/selenium/SeleniumTest.java
// public static class SeleniumTestResult implements Serializable {
// private static final long serialVersionUID = 1L;
//
// private Map<String, SerializableLogEntries> logs = new HashMap<String, SerializableLogEntries>();;
//
// private boolean status;
//
// long executionTime;
//
// private Map<String, Object[]> internalTestRes = new HashMap<String, Object[]>();
//
// public Map<String,SerializableLogEntries> getLogs()
// {
// return logs;
// }
// public boolean isStatus()
// {
// return status;
// }
// public long getExecutionTime()
// {
// return executionTime;
// }
// public Map<String,Object[]> getInternalTestRes()
// {
// return internalTestRes;
// }
// public SeleniumTestResult(WebDriver d, SeleniumTest test, LoggingPreferences ___lp___)
// {
// this.status = true;
// this.internalTestRes = test.getSession().internalTestRs;
// /*Logs logs = d.manage().logs();
// for (String s : LOG_TYPES_SET) {
// if(!logs.getAvailableLogTypes().contains(s))continue;
// LogEntries logEntries = logs.get(s);
// if(logEntries!=null && !logEntries.getAll().isEmpty()) {
// this.logs.put(s, new SerializableLogEntries(logEntries.getAll()));
// }
// }*/
// }
// public SeleniumTestResult(WebDriver d, SeleniumTest test, Throwable cause, LoggingPreferences ___lp___) {
// this.status = false;
// this.internalTestRes = test.getSession().internalTestRs;
// /*Logs logs = d.manage().logs();
// for (String s : LOG_TYPES_SET) {
// if(!logs.getAvailableLogTypes().contains(s))continue;
// LogEntries logEntries = logs.get(s);
// if(logEntries!=null && !logEntries.getAll().isEmpty()) {
// this.logs.put(s, new SerializableLogEntries(logEntries.getAll()));
// }
// }*/
// List<LogEntry> entries = new ArrayList<LogEntry>();
// entries.add(new LogEntry(Level.ALL, new Date().getTime(), cause.getMessage()));
// entries.add(new LogEntry(Level.ALL, new Date().getTime(), ExceptionUtils.getStackTrace(cause)));
// this.logs.put("gatf", new SerializableLogEntries(entries));
// }
// public SeleniumTestResult(SeleniumTest test, Throwable cause) {
// this.status = false;
// this.internalTestRes = test.getSession().internalTestRs;
// List<LogEntry> entries = new ArrayList<LogEntry>();
// entries.add(new LogEntry(Level.ALL, new Date().getTime(), cause.getMessage()));
// entries.add(new LogEntry(Level.ALL, new Date().getTime(), ExceptionUtils.getStackTrace(cause)));
// this.logs.put("gatf", new SerializableLogEntries(entries));
// }
// }
| import java.io.Serializable;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import org.openqa.selenium.WebDriver;
import com.gatf.selenium.SeleniumTest.SeleniumTestResult; | package com.gatf.selenium;
/**
* @author Sumeet Chhetri<br/>
*
*/
public class SeleniumTestSession implements Serializable {
private static final long serialVersionUID = 1L;
protected transient List<WebDriver> ___d___ = new ArrayList<WebDriver>();
protected transient int __wpos__ = 0;
protected final Map<String, SeleniumResult> __result__ = new HashMap<String, SeleniumResult>();
protected transient String __subtestname__ = null;
protected transient long __subtestexecutiontime__ = 0L;
protected transient long __teststarttime__ = 0L;
protected transient final Map<String, Integer> __provdetails__ = new LinkedHashMap<String, Integer>();
protected transient final Map<String, Object> __vars__ = new LinkedHashMap<String, Object>();
protected final Map<String, Object[]> internalTestRs = new HashMap<String,Object[]>();
protected transient final Map<String, List<Map<String, String>>> providerTestDataMap = new HashMap<String, List<Map<String,String>>>();
protected String browserName;
protected String sessionName;
public String getSessionName() {
return sessionName;
}
public static class SeleniumResult implements Serializable {
private static final long serialVersionUID = 1L;
String browserName;
| // Path: alldep-jar/src/main/java/com/gatf/selenium/SeleniumTest.java
// public static class SeleniumTestResult implements Serializable {
// private static final long serialVersionUID = 1L;
//
// private Map<String, SerializableLogEntries> logs = new HashMap<String, SerializableLogEntries>();;
//
// private boolean status;
//
// long executionTime;
//
// private Map<String, Object[]> internalTestRes = new HashMap<String, Object[]>();
//
// public Map<String,SerializableLogEntries> getLogs()
// {
// return logs;
// }
// public boolean isStatus()
// {
// return status;
// }
// public long getExecutionTime()
// {
// return executionTime;
// }
// public Map<String,Object[]> getInternalTestRes()
// {
// return internalTestRes;
// }
// public SeleniumTestResult(WebDriver d, SeleniumTest test, LoggingPreferences ___lp___)
// {
// this.status = true;
// this.internalTestRes = test.getSession().internalTestRs;
// /*Logs logs = d.manage().logs();
// for (String s : LOG_TYPES_SET) {
// if(!logs.getAvailableLogTypes().contains(s))continue;
// LogEntries logEntries = logs.get(s);
// if(logEntries!=null && !logEntries.getAll().isEmpty()) {
// this.logs.put(s, new SerializableLogEntries(logEntries.getAll()));
// }
// }*/
// }
// public SeleniumTestResult(WebDriver d, SeleniumTest test, Throwable cause, LoggingPreferences ___lp___) {
// this.status = false;
// this.internalTestRes = test.getSession().internalTestRs;
// /*Logs logs = d.manage().logs();
// for (String s : LOG_TYPES_SET) {
// if(!logs.getAvailableLogTypes().contains(s))continue;
// LogEntries logEntries = logs.get(s);
// if(logEntries!=null && !logEntries.getAll().isEmpty()) {
// this.logs.put(s, new SerializableLogEntries(logEntries.getAll()));
// }
// }*/
// List<LogEntry> entries = new ArrayList<LogEntry>();
// entries.add(new LogEntry(Level.ALL, new Date().getTime(), cause.getMessage()));
// entries.add(new LogEntry(Level.ALL, new Date().getTime(), ExceptionUtils.getStackTrace(cause)));
// this.logs.put("gatf", new SerializableLogEntries(entries));
// }
// public SeleniumTestResult(SeleniumTest test, Throwable cause) {
// this.status = false;
// this.internalTestRes = test.getSession().internalTestRs;
// List<LogEntry> entries = new ArrayList<LogEntry>();
// entries.add(new LogEntry(Level.ALL, new Date().getTime(), cause.getMessage()));
// entries.add(new LogEntry(Level.ALL, new Date().getTime(), ExceptionUtils.getStackTrace(cause)));
// this.logs.put("gatf", new SerializableLogEntries(entries));
// }
// }
// Path: alldep-jar/src/main/java/com/gatf/selenium/SeleniumTestSession.java
import java.io.Serializable;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import org.openqa.selenium.WebDriver;
import com.gatf.selenium.SeleniumTest.SeleniumTestResult;
package com.gatf.selenium;
/**
* @author Sumeet Chhetri<br/>
*
*/
public class SeleniumTestSession implements Serializable {
private static final long serialVersionUID = 1L;
protected transient List<WebDriver> ___d___ = new ArrayList<WebDriver>();
protected transient int __wpos__ = 0;
protected final Map<String, SeleniumResult> __result__ = new HashMap<String, SeleniumResult>();
protected transient String __subtestname__ = null;
protected transient long __subtestexecutiontime__ = 0L;
protected transient long __teststarttime__ = 0L;
protected transient final Map<String, Integer> __provdetails__ = new LinkedHashMap<String, Integer>();
protected transient final Map<String, Object> __vars__ = new LinkedHashMap<String, Object>();
protected final Map<String, Object[]> internalTestRs = new HashMap<String,Object[]>();
protected transient final Map<String, List<Map<String, String>>> providerTestDataMap = new HashMap<String, List<Map<String,String>>>();
protected String browserName;
protected String sessionName;
public String getSessionName() {
return sessionName;
}
public static class SeleniumResult implements Serializable {
private static final long serialVersionUID = 1L;
String browserName;
| SeleniumTestResult result; |
sumeetchhetri/gatf | alldep-jar/src/main/java/com/gatf/generator/core/GatfConfiguration.java | // Path: alldep-jar/src/main/java/com/gatf/GatfPluginConfig.java
// public interface GatfPluginConfig {
//
// }
| import java.io.Serializable;
import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.JsonAutoDetect.Visibility;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonInclude.Include;
import com.gatf.GatfPluginConfig;
import com.thoughtworks.xstream.annotations.XStreamAlias;
| /*
Copyright 2013-2019, Sumeet Chhetri
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package com.gatf.generator.core;
/*
* <configuration>
<testPaths>
<testPath>com.sample.services.*</testPath>
</testPaths>
<useSoapClient>true</useSoapClient>
<soapWsdlKeyPairs>
<soapWsdlKeyPair>AuthService,http://localhost:8081/soap/auth?wsdl</soapWsdlKeyPair>
<soapWsdlKeyPair>ExampleService,http://localhost:8081/soap/example?wsdl</soapWsdlKeyPair>
<soapWsdlKeyPair>MessageService,http://localhost:8081/soap/messages?wsdl</soapWsdlKeyPair>
<soapWsdlKeyPair>UserService,http://localhost:8081/soap/user?wsdl</soapWsdlKeyPair>
</soapWsdlKeyPairs>
<urlPrefix>rest</urlPrefix>
<urlSuffix>_param=value</urlSuffix>
<requestDataType>json</requestDataType>
<responseDataType>json</responseDataType>
<overrideSecure>true</overrideSecure>
<resourcepath>src/test/resources/generated</resourcepath>
<postmanCollectionVersion>2</postmanCollectionVersion>
<testCaseFormat>xml</testCaseFormat>
<enabled>true</enabled>
</configuration>
* @author Sumeet Chhetri
* The test case generator configuration parameters
*/
@XStreamAlias("configuration")
@JsonAutoDetect(getterVisibility=Visibility.NONE, fieldVisibility=Visibility.ANY, isGetterVisibility=Visibility.NONE)
@JsonInclude(value = Include.NON_NULL)
| // Path: alldep-jar/src/main/java/com/gatf/GatfPluginConfig.java
// public interface GatfPluginConfig {
//
// }
// Path: alldep-jar/src/main/java/com/gatf/generator/core/GatfConfiguration.java
import java.io.Serializable;
import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.JsonAutoDetect.Visibility;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonInclude.Include;
import com.gatf.GatfPluginConfig;
import com.thoughtworks.xstream.annotations.XStreamAlias;
/*
Copyright 2013-2019, Sumeet Chhetri
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package com.gatf.generator.core;
/*
* <configuration>
<testPaths>
<testPath>com.sample.services.*</testPath>
</testPaths>
<useSoapClient>true</useSoapClient>
<soapWsdlKeyPairs>
<soapWsdlKeyPair>AuthService,http://localhost:8081/soap/auth?wsdl</soapWsdlKeyPair>
<soapWsdlKeyPair>ExampleService,http://localhost:8081/soap/example?wsdl</soapWsdlKeyPair>
<soapWsdlKeyPair>MessageService,http://localhost:8081/soap/messages?wsdl</soapWsdlKeyPair>
<soapWsdlKeyPair>UserService,http://localhost:8081/soap/user?wsdl</soapWsdlKeyPair>
</soapWsdlKeyPairs>
<urlPrefix>rest</urlPrefix>
<urlSuffix>_param=value</urlSuffix>
<requestDataType>json</requestDataType>
<responseDataType>json</responseDataType>
<overrideSecure>true</overrideSecure>
<resourcepath>src/test/resources/generated</resourcepath>
<postmanCollectionVersion>2</postmanCollectionVersion>
<testCaseFormat>xml</testCaseFormat>
<enabled>true</enabled>
</configuration>
* @author Sumeet Chhetri
* The test case generator configuration parameters
*/
@XStreamAlias("configuration")
@JsonAutoDetect(getterVisibility=Visibility.NONE, fieldVisibility=Visibility.ANY, isGetterVisibility=Visibility.NONE)
@JsonInclude(value = Include.NON_NULL)
| public class GatfConfiguration implements Serializable, GatfPluginConfig {
|
sumeetchhetri/gatf | alldep-jar/src/main/java/com/gatf/selenium/SeleniumDriverConfig.java | // Path: alldep-jar/src/main/java/com/gatf/executor/core/MapKeyValueAttributeXstreamConverter.java
// public class MapKeyValueAttributeXstreamConverter implements Converter
// {
// @SuppressWarnings("rawtypes")
// public boolean canConvert(final Class clazz)
// {
// return AbstractMap.class.isAssignableFrom(clazz);
// }
//
// @SuppressWarnings("unchecked")
// public void marshal(final Object value, final HierarchicalStreamWriter writer, final MarshallingContext context)
// {
// final AbstractMap<String, String> map = (AbstractMap<String, String>) value;
// for (final Entry<String, String> entry : map.entrySet())
// {
// writer.startNode("property");
// writer.addAttribute("key", entry.getKey());
// writer.setValue(entry.getValue().toString());
// writer.endNode();
// }
// }
//
// public Object unmarshal(final HierarchicalStreamReader reader, final UnmarshallingContext context)
// {
// final AbstractMap<String, String> map = new HashMap<String, String>();
// while (reader.hasMoreChildren())
// {
// reader.moveDown();
// if(reader.getNodeName().equals("property")) {
// map.put(reader.getAttribute("key"), reader.getValue());
// }
// reader.moveUp();
// }
// return map;
// }
// }
| import java.io.Serializable;
import java.util.HashMap;
import java.util.Map;
import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.JsonAutoDetect.Visibility;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonInclude.Include;
import com.gatf.executor.core.MapKeyValueAttributeXstreamConverter;
import com.thoughtworks.xstream.annotations.XStreamAlias;
import com.thoughtworks.xstream.annotations.XStreamConverter; | package com.gatf.selenium;
/**
* @author Sumeet Chhetri
* The Selenium Driver configuration properties
*/
@XStreamAlias("seleniumDriverConfig")
@JsonAutoDetect(getterVisibility=Visibility.NONE, fieldVisibility=Visibility.ANY, isGetterVisibility=Visibility.NONE)
@JsonInclude(value = Include.NON_NULL)
public class SeleniumDriverConfig implements Serializable {
private static final long serialVersionUID = 1L;
private String name;
private String version;
private String platform;
private String driverName;
private String path;
private String arguments;
private String url;
| // Path: alldep-jar/src/main/java/com/gatf/executor/core/MapKeyValueAttributeXstreamConverter.java
// public class MapKeyValueAttributeXstreamConverter implements Converter
// {
// @SuppressWarnings("rawtypes")
// public boolean canConvert(final Class clazz)
// {
// return AbstractMap.class.isAssignableFrom(clazz);
// }
//
// @SuppressWarnings("unchecked")
// public void marshal(final Object value, final HierarchicalStreamWriter writer, final MarshallingContext context)
// {
// final AbstractMap<String, String> map = (AbstractMap<String, String>) value;
// for (final Entry<String, String> entry : map.entrySet())
// {
// writer.startNode("property");
// writer.addAttribute("key", entry.getKey());
// writer.setValue(entry.getValue().toString());
// writer.endNode();
// }
// }
//
// public Object unmarshal(final HierarchicalStreamReader reader, final UnmarshallingContext context)
// {
// final AbstractMap<String, String> map = new HashMap<String, String>();
// while (reader.hasMoreChildren())
// {
// reader.moveDown();
// if(reader.getNodeName().equals("property")) {
// map.put(reader.getAttribute("key"), reader.getValue());
// }
// reader.moveUp();
// }
// return map;
// }
// }
// Path: alldep-jar/src/main/java/com/gatf/selenium/SeleniumDriverConfig.java
import java.io.Serializable;
import java.util.HashMap;
import java.util.Map;
import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.JsonAutoDetect.Visibility;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonInclude.Include;
import com.gatf.executor.core.MapKeyValueAttributeXstreamConverter;
import com.thoughtworks.xstream.annotations.XStreamAlias;
import com.thoughtworks.xstream.annotations.XStreamConverter;
package com.gatf.selenium;
/**
* @author Sumeet Chhetri
* The Selenium Driver configuration properties
*/
@XStreamAlias("seleniumDriverConfig")
@JsonAutoDetect(getterVisibility=Visibility.NONE, fieldVisibility=Visibility.ANY, isGetterVisibility=Visibility.NONE)
@JsonInclude(value = Include.NON_NULL)
public class SeleniumDriverConfig implements Serializable {
private static final long serialVersionUID = 1L;
private String name;
private String version;
private String platform;
private String driverName;
private String path;
private String arguments;
private String url;
| @XStreamConverter(value=MapKeyValueAttributeXstreamConverter.class) |
sumeetchhetri/gatf | alldep-jar/src/main/java/com/gatf/selenium/SeleniumException.java | // Path: alldep-jar/src/main/java/com/gatf/selenium/SeleniumTest.java
// public static class SeleniumTestResult implements Serializable {
// private static final long serialVersionUID = 1L;
//
// private Map<String, SerializableLogEntries> logs = new HashMap<String, SerializableLogEntries>();;
//
// private boolean status;
//
// long executionTime;
//
// private Map<String, Object[]> internalTestRes = new HashMap<String, Object[]>();
//
// public Map<String,SerializableLogEntries> getLogs()
// {
// return logs;
// }
// public boolean isStatus()
// {
// return status;
// }
// public long getExecutionTime()
// {
// return executionTime;
// }
// public Map<String,Object[]> getInternalTestRes()
// {
// return internalTestRes;
// }
// public SeleniumTestResult(WebDriver d, SeleniumTest test, LoggingPreferences ___lp___)
// {
// this.status = true;
// this.internalTestRes = test.getSession().internalTestRs;
// /*Logs logs = d.manage().logs();
// for (String s : LOG_TYPES_SET) {
// if(!logs.getAvailableLogTypes().contains(s))continue;
// LogEntries logEntries = logs.get(s);
// if(logEntries!=null && !logEntries.getAll().isEmpty()) {
// this.logs.put(s, new SerializableLogEntries(logEntries.getAll()));
// }
// }*/
// }
// public SeleniumTestResult(WebDriver d, SeleniumTest test, Throwable cause, LoggingPreferences ___lp___) {
// this.status = false;
// this.internalTestRes = test.getSession().internalTestRs;
// /*Logs logs = d.manage().logs();
// for (String s : LOG_TYPES_SET) {
// if(!logs.getAvailableLogTypes().contains(s))continue;
// LogEntries logEntries = logs.get(s);
// if(logEntries!=null && !logEntries.getAll().isEmpty()) {
// this.logs.put(s, new SerializableLogEntries(logEntries.getAll()));
// }
// }*/
// List<LogEntry> entries = new ArrayList<LogEntry>();
// entries.add(new LogEntry(Level.ALL, new Date().getTime(), cause.getMessage()));
// entries.add(new LogEntry(Level.ALL, new Date().getTime(), ExceptionUtils.getStackTrace(cause)));
// this.logs.put("gatf", new SerializableLogEntries(entries));
// }
// public SeleniumTestResult(SeleniumTest test, Throwable cause) {
// this.status = false;
// this.internalTestRes = test.getSession().internalTestRs;
// List<LogEntry> entries = new ArrayList<LogEntry>();
// entries.add(new LogEntry(Level.ALL, new Date().getTime(), cause.getMessage()));
// entries.add(new LogEntry(Level.ALL, new Date().getTime(), ExceptionUtils.getStackTrace(cause)));
// this.logs.put("gatf", new SerializableLogEntries(entries));
// }
// }
| import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.logging.Level;
import org.apache.commons.lang3.exception.ExceptionUtils;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.logging.LogEntries;
import org.openqa.selenium.logging.LogEntry;
import org.openqa.selenium.logging.Logs;
import com.gatf.selenium.SeleniumTest.SeleniumTestResult;
| /*
Copyright 2013-2019, Sumeet Chhetri
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package com.gatf.selenium;
public class SeleniumException extends RuntimeException {
private static final long serialVersionUID = 1L;
| // Path: alldep-jar/src/main/java/com/gatf/selenium/SeleniumTest.java
// public static class SeleniumTestResult implements Serializable {
// private static final long serialVersionUID = 1L;
//
// private Map<String, SerializableLogEntries> logs = new HashMap<String, SerializableLogEntries>();;
//
// private boolean status;
//
// long executionTime;
//
// private Map<String, Object[]> internalTestRes = new HashMap<String, Object[]>();
//
// public Map<String,SerializableLogEntries> getLogs()
// {
// return logs;
// }
// public boolean isStatus()
// {
// return status;
// }
// public long getExecutionTime()
// {
// return executionTime;
// }
// public Map<String,Object[]> getInternalTestRes()
// {
// return internalTestRes;
// }
// public SeleniumTestResult(WebDriver d, SeleniumTest test, LoggingPreferences ___lp___)
// {
// this.status = true;
// this.internalTestRes = test.getSession().internalTestRs;
// /*Logs logs = d.manage().logs();
// for (String s : LOG_TYPES_SET) {
// if(!logs.getAvailableLogTypes().contains(s))continue;
// LogEntries logEntries = logs.get(s);
// if(logEntries!=null && !logEntries.getAll().isEmpty()) {
// this.logs.put(s, new SerializableLogEntries(logEntries.getAll()));
// }
// }*/
// }
// public SeleniumTestResult(WebDriver d, SeleniumTest test, Throwable cause, LoggingPreferences ___lp___) {
// this.status = false;
// this.internalTestRes = test.getSession().internalTestRs;
// /*Logs logs = d.manage().logs();
// for (String s : LOG_TYPES_SET) {
// if(!logs.getAvailableLogTypes().contains(s))continue;
// LogEntries logEntries = logs.get(s);
// if(logEntries!=null && !logEntries.getAll().isEmpty()) {
// this.logs.put(s, new SerializableLogEntries(logEntries.getAll()));
// }
// }*/
// List<LogEntry> entries = new ArrayList<LogEntry>();
// entries.add(new LogEntry(Level.ALL, new Date().getTime(), cause.getMessage()));
// entries.add(new LogEntry(Level.ALL, new Date().getTime(), ExceptionUtils.getStackTrace(cause)));
// this.logs.put("gatf", new SerializableLogEntries(entries));
// }
// public SeleniumTestResult(SeleniumTest test, Throwable cause) {
// this.status = false;
// this.internalTestRes = test.getSession().internalTestRs;
// List<LogEntry> entries = new ArrayList<LogEntry>();
// entries.add(new LogEntry(Level.ALL, new Date().getTime(), cause.getMessage()));
// entries.add(new LogEntry(Level.ALL, new Date().getTime(), ExceptionUtils.getStackTrace(cause)));
// this.logs.put("gatf", new SerializableLogEntries(entries));
// }
// }
// Path: alldep-jar/src/main/java/com/gatf/selenium/SeleniumException.java
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.logging.Level;
import org.apache.commons.lang3.exception.ExceptionUtils;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.logging.LogEntries;
import org.openqa.selenium.logging.LogEntry;
import org.openqa.selenium.logging.Logs;
import com.gatf.selenium.SeleniumTest.SeleniumTestResult;
/*
Copyright 2013-2019, Sumeet Chhetri
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package com.gatf.selenium;
public class SeleniumException extends RuntimeException {
private static final long serialVersionUID = 1L;
| private SeleniumTestResult res;
|
games647/ScoreboardStats | defaults/src/main/java/com/github/games647/scoreboardstats/defaults/CraftconomyVariables.java | // Path: variables/src/main/java/com/github/games647/scoreboardstats/variables/DefaultReplacers.java
// public abstract class DefaultReplacers<T extends Plugin> {
//
// protected final ReplacerAPI replaceManager;
// protected final T plugin;
//
// public DefaultReplacers(ReplacerAPI replaceManager, T plugin) {
// this.replaceManager = replaceManager;
// this.plugin = plugin;
// }
//
// /**
// * Register all variables that this class can manage
// */
// public abstract void register();
//
// /**
// * Shortcut method to register the variables without the boilerplate of adding the plugin instance and registering
// * it to the manager.
// *
// * @param variable variable name like "online"
// * @return the replacer responsible for this single variable
// */
// protected Replacer register(String variable) {
// Replacer replacer = new Replacer(plugin, variable);
// replaceManager.register(replacer);
// return replacer;
// }
// }
//
// Path: variables/src/main/java/com/github/games647/scoreboardstats/variables/ReplacerAPI.java
// public abstract class ReplacerAPI {
//
// protected final Logger logger;
// protected final Map<String, Replacer> replacers = Maps.newHashMap();
//
// public ReplacerAPI(Logger logger) {
// this.logger = logger;
// }
//
// public void register(Replacer replacer) {
// replacers.put(replacer.getVariable(), replacer);
//
// for (EventReplacer<? extends Event> eventReplacer : replacer.getEventsReplacers().values()) {
// Class<? extends Event> eventClass = eventReplacer.getEventClass();
// Plugin plugin = replacer.getPlugin();
//
// EventExecutor executor = (listener, event) -> eventReplacer.execute(this, event);
//
// Listener listener = new Listener() {};
//
// PluginManager pluginManager = Bukkit.getPluginManager();
// pluginManager.registerEvent(eventClass, listener, HIGHEST, executor, plugin, true);
// }
// }
//
// public void unregister(String variable) {
// replacers.remove(variable);
// }
//
// public void unregisterAll(Plugin disablePlugin) {
// Iterator<Replacer> iterator = replacers.values().iterator();
// while (iterator.hasNext()) {
// Plugin plugin = iterator.next().getPlugin();
// if (plugin == disablePlugin) {
// iterator.remove();
// }
// }
// }
//
// public void forceUpdate(String variable, int score) {
// Bukkit.getOnlinePlayers().forEach(player -> forceUpdate(player, variable, score));
// }
//
// public void forceUpdate(String variable, String value) {
// Bukkit.getOnlinePlayers().forEach(player -> forceUpdate(player, variable, value));
// }
//
// public abstract void forceUpdate(Player player, String variable, int score);
//
// public abstract void forceUpdate(Player player, String variable, String value);
//
// public Optional<String> replace(Player player, String variable, boolean complete) throws ReplacerException {
// Replacer replacer = getReplacer(variable);
// if (!complete && replacer.isGlobal() || replacer.isEventVariable() || replacer.isConstant()) {
// return Optional.empty();
// }
//
// try {
// return Optional.of(replacer.replace(player));
// } catch (Exception ex) {
// throw new ReplacerException(ex);
// }
// }
//
// public OptionalInt scoreReplace(Player player, String variable, boolean complete) throws ReplacerException {
// Replacer replacer = getReplacer(variable);
// if (!complete && replacer.isGlobal() || replacer.isEventVariable() || replacer.isConstant()) {
// return OptionalInt.empty();
// }
//
// try {
// return OptionalInt.of(replacer.scoreReplace(player));
// } catch (Exception ex) {
// throw new ReplacerException(ex);
// }
// }
//
// private Replacer getReplacer(String variable) throws UnknownVariableException {
// Replacer replacer = this.replacers.get(variable);
// if (replacer == null) {
// throw new UnknownVariableException(variable);
// }
//
// return replacer;
// }
// }
| import com.github.games647.scoreboardstats.variables.DefaultReplacer;
import com.github.games647.scoreboardstats.variables.DefaultReplacers;
import com.github.games647.scoreboardstats.variables.ReplacerAPI;
import com.greatmancode.craftconomy3.Common;
import com.greatmancode.craftconomy3.account.AccountManager;
import com.greatmancode.craftconomy3.currency.Currency;
import com.greatmancode.craftconomy3.currency.CurrencyManager;
import org.bukkit.plugin.Plugin;
import org.bukkit.util.NumberConversions; | package com.github.games647.scoreboardstats.defaults;
@DefaultReplacer(plugin = "CraftConomy3")
public class CraftconomyVariables extends DefaultReplacers<Plugin> {
private final AccountManager accountManager = Common.getInstance().getAccountManager();
private final CurrencyManager currencyManager = Common.getInstance().getCurrencyManager();
| // Path: variables/src/main/java/com/github/games647/scoreboardstats/variables/DefaultReplacers.java
// public abstract class DefaultReplacers<T extends Plugin> {
//
// protected final ReplacerAPI replaceManager;
// protected final T plugin;
//
// public DefaultReplacers(ReplacerAPI replaceManager, T plugin) {
// this.replaceManager = replaceManager;
// this.plugin = plugin;
// }
//
// /**
// * Register all variables that this class can manage
// */
// public abstract void register();
//
// /**
// * Shortcut method to register the variables without the boilerplate of adding the plugin instance and registering
// * it to the manager.
// *
// * @param variable variable name like "online"
// * @return the replacer responsible for this single variable
// */
// protected Replacer register(String variable) {
// Replacer replacer = new Replacer(plugin, variable);
// replaceManager.register(replacer);
// return replacer;
// }
// }
//
// Path: variables/src/main/java/com/github/games647/scoreboardstats/variables/ReplacerAPI.java
// public abstract class ReplacerAPI {
//
// protected final Logger logger;
// protected final Map<String, Replacer> replacers = Maps.newHashMap();
//
// public ReplacerAPI(Logger logger) {
// this.logger = logger;
// }
//
// public void register(Replacer replacer) {
// replacers.put(replacer.getVariable(), replacer);
//
// for (EventReplacer<? extends Event> eventReplacer : replacer.getEventsReplacers().values()) {
// Class<? extends Event> eventClass = eventReplacer.getEventClass();
// Plugin plugin = replacer.getPlugin();
//
// EventExecutor executor = (listener, event) -> eventReplacer.execute(this, event);
//
// Listener listener = new Listener() {};
//
// PluginManager pluginManager = Bukkit.getPluginManager();
// pluginManager.registerEvent(eventClass, listener, HIGHEST, executor, plugin, true);
// }
// }
//
// public void unregister(String variable) {
// replacers.remove(variable);
// }
//
// public void unregisterAll(Plugin disablePlugin) {
// Iterator<Replacer> iterator = replacers.values().iterator();
// while (iterator.hasNext()) {
// Plugin plugin = iterator.next().getPlugin();
// if (plugin == disablePlugin) {
// iterator.remove();
// }
// }
// }
//
// public void forceUpdate(String variable, int score) {
// Bukkit.getOnlinePlayers().forEach(player -> forceUpdate(player, variable, score));
// }
//
// public void forceUpdate(String variable, String value) {
// Bukkit.getOnlinePlayers().forEach(player -> forceUpdate(player, variable, value));
// }
//
// public abstract void forceUpdate(Player player, String variable, int score);
//
// public abstract void forceUpdate(Player player, String variable, String value);
//
// public Optional<String> replace(Player player, String variable, boolean complete) throws ReplacerException {
// Replacer replacer = getReplacer(variable);
// if (!complete && replacer.isGlobal() || replacer.isEventVariable() || replacer.isConstant()) {
// return Optional.empty();
// }
//
// try {
// return Optional.of(replacer.replace(player));
// } catch (Exception ex) {
// throw new ReplacerException(ex);
// }
// }
//
// public OptionalInt scoreReplace(Player player, String variable, boolean complete) throws ReplacerException {
// Replacer replacer = getReplacer(variable);
// if (!complete && replacer.isGlobal() || replacer.isEventVariable() || replacer.isConstant()) {
// return OptionalInt.empty();
// }
//
// try {
// return OptionalInt.of(replacer.scoreReplace(player));
// } catch (Exception ex) {
// throw new ReplacerException(ex);
// }
// }
//
// private Replacer getReplacer(String variable) throws UnknownVariableException {
// Replacer replacer = this.replacers.get(variable);
// if (replacer == null) {
// throw new UnknownVariableException(variable);
// }
//
// return replacer;
// }
// }
// Path: defaults/src/main/java/com/github/games647/scoreboardstats/defaults/CraftconomyVariables.java
import com.github.games647.scoreboardstats.variables.DefaultReplacer;
import com.github.games647.scoreboardstats.variables.DefaultReplacers;
import com.github.games647.scoreboardstats.variables.ReplacerAPI;
import com.greatmancode.craftconomy3.Common;
import com.greatmancode.craftconomy3.account.AccountManager;
import com.greatmancode.craftconomy3.currency.Currency;
import com.greatmancode.craftconomy3.currency.CurrencyManager;
import org.bukkit.plugin.Plugin;
import org.bukkit.util.NumberConversions;
package com.github.games647.scoreboardstats.defaults;
@DefaultReplacer(plugin = "CraftConomy3")
public class CraftconomyVariables extends DefaultReplacers<Plugin> {
private final AccountManager accountManager = Common.getInstance().getAccountManager();
private final CurrencyManager currencyManager = Common.getInstance().getCurrencyManager();
| public CraftconomyVariables(ReplacerAPI replaceManager, Plugin plugin) { |
games647/ScoreboardStats | defaults/src/main/java/com/github/games647/scoreboardstats/defaults/SkyblockVariables.java | // Path: variables/src/main/java/com/github/games647/scoreboardstats/variables/DefaultReplacers.java
// public abstract class DefaultReplacers<T extends Plugin> {
//
// protected final ReplacerAPI replaceManager;
// protected final T plugin;
//
// public DefaultReplacers(ReplacerAPI replaceManager, T plugin) {
// this.replaceManager = replaceManager;
// this.plugin = plugin;
// }
//
// /**
// * Register all variables that this class can manage
// */
// public abstract void register();
//
// /**
// * Shortcut method to register the variables without the boilerplate of adding the plugin instance and registering
// * it to the manager.
// *
// * @param variable variable name like "online"
// * @return the replacer responsible for this single variable
// */
// protected Replacer register(String variable) {
// Replacer replacer = new Replacer(plugin, variable);
// replaceManager.register(replacer);
// return replacer;
// }
// }
//
// Path: variables/src/main/java/com/github/games647/scoreboardstats/variables/ReplacerAPI.java
// public abstract class ReplacerAPI {
//
// protected final Logger logger;
// protected final Map<String, Replacer> replacers = Maps.newHashMap();
//
// public ReplacerAPI(Logger logger) {
// this.logger = logger;
// }
//
// public void register(Replacer replacer) {
// replacers.put(replacer.getVariable(), replacer);
//
// for (EventReplacer<? extends Event> eventReplacer : replacer.getEventsReplacers().values()) {
// Class<? extends Event> eventClass = eventReplacer.getEventClass();
// Plugin plugin = replacer.getPlugin();
//
// EventExecutor executor = (listener, event) -> eventReplacer.execute(this, event);
//
// Listener listener = new Listener() {};
//
// PluginManager pluginManager = Bukkit.getPluginManager();
// pluginManager.registerEvent(eventClass, listener, HIGHEST, executor, plugin, true);
// }
// }
//
// public void unregister(String variable) {
// replacers.remove(variable);
// }
//
// public void unregisterAll(Plugin disablePlugin) {
// Iterator<Replacer> iterator = replacers.values().iterator();
// while (iterator.hasNext()) {
// Plugin plugin = iterator.next().getPlugin();
// if (plugin == disablePlugin) {
// iterator.remove();
// }
// }
// }
//
// public void forceUpdate(String variable, int score) {
// Bukkit.getOnlinePlayers().forEach(player -> forceUpdate(player, variable, score));
// }
//
// public void forceUpdate(String variable, String value) {
// Bukkit.getOnlinePlayers().forEach(player -> forceUpdate(player, variable, value));
// }
//
// public abstract void forceUpdate(Player player, String variable, int score);
//
// public abstract void forceUpdate(Player player, String variable, String value);
//
// public Optional<String> replace(Player player, String variable, boolean complete) throws ReplacerException {
// Replacer replacer = getReplacer(variable);
// if (!complete && replacer.isGlobal() || replacer.isEventVariable() || replacer.isConstant()) {
// return Optional.empty();
// }
//
// try {
// return Optional.of(replacer.replace(player));
// } catch (Exception ex) {
// throw new ReplacerException(ex);
// }
// }
//
// public OptionalInt scoreReplace(Player player, String variable, boolean complete) throws ReplacerException {
// Replacer replacer = getReplacer(variable);
// if (!complete && replacer.isGlobal() || replacer.isEventVariable() || replacer.isConstant()) {
// return OptionalInt.empty();
// }
//
// try {
// return OptionalInt.of(replacer.scoreReplace(player));
// } catch (Exception ex) {
// throw new ReplacerException(ex);
// }
// }
//
// private Replacer getReplacer(String variable) throws UnknownVariableException {
// Replacer replacer = this.replacers.get(variable);
// if (replacer == null) {
// throw new UnknownVariableException(variable);
// }
//
// return replacer;
// }
// }
//
// Path: variables/src/main/java/com/github/games647/scoreboardstats/variables/UnsupportedPluginException.java
// public class UnsupportedPluginException extends ReplacerException {
//
// public UnsupportedPluginException(String pluginName, String expectedVersion, String currentVersion) {
// super(String.format("The version %s of plugin %s version isn't supported. We require at least %s",
// currentVersion, pluginName, expectedVersion));
// }
//
// public UnsupportedPluginException(String message) {
// super(message);
// }
// }
| import com.github.games647.scoreboardstats.variables.DefaultReplacer;
import com.github.games647.scoreboardstats.variables.DefaultReplacers;
import com.github.games647.scoreboardstats.variables.ReplacerAPI;
import com.github.games647.scoreboardstats.variables.UnsupportedPluginException;
import org.bukkit.plugin.Plugin;
import org.bukkit.util.NumberConversions;
import us.talabrek.ultimateskyblock.api.event.uSkyBlockScoreChangedEvent;
import us.talabrek.ultimateskyblock.api.uSkyBlockAPI; | package com.github.games647.scoreboardstats.defaults;
/**
* Replace all variables that are associated with the uSkyBlock plugin
* <p>
* https://dev.bukkit.org/bukkit-plugins/uskyblock/
*/
@DefaultReplacer(plugin = "uSkyblock")
public class SkyblockVariables extends DefaultReplacers<uSkyBlockAPI> {
| // Path: variables/src/main/java/com/github/games647/scoreboardstats/variables/DefaultReplacers.java
// public abstract class DefaultReplacers<T extends Plugin> {
//
// protected final ReplacerAPI replaceManager;
// protected final T plugin;
//
// public DefaultReplacers(ReplacerAPI replaceManager, T plugin) {
// this.replaceManager = replaceManager;
// this.plugin = plugin;
// }
//
// /**
// * Register all variables that this class can manage
// */
// public abstract void register();
//
// /**
// * Shortcut method to register the variables without the boilerplate of adding the plugin instance and registering
// * it to the manager.
// *
// * @param variable variable name like "online"
// * @return the replacer responsible for this single variable
// */
// protected Replacer register(String variable) {
// Replacer replacer = new Replacer(plugin, variable);
// replaceManager.register(replacer);
// return replacer;
// }
// }
//
// Path: variables/src/main/java/com/github/games647/scoreboardstats/variables/ReplacerAPI.java
// public abstract class ReplacerAPI {
//
// protected final Logger logger;
// protected final Map<String, Replacer> replacers = Maps.newHashMap();
//
// public ReplacerAPI(Logger logger) {
// this.logger = logger;
// }
//
// public void register(Replacer replacer) {
// replacers.put(replacer.getVariable(), replacer);
//
// for (EventReplacer<? extends Event> eventReplacer : replacer.getEventsReplacers().values()) {
// Class<? extends Event> eventClass = eventReplacer.getEventClass();
// Plugin plugin = replacer.getPlugin();
//
// EventExecutor executor = (listener, event) -> eventReplacer.execute(this, event);
//
// Listener listener = new Listener() {};
//
// PluginManager pluginManager = Bukkit.getPluginManager();
// pluginManager.registerEvent(eventClass, listener, HIGHEST, executor, plugin, true);
// }
// }
//
// public void unregister(String variable) {
// replacers.remove(variable);
// }
//
// public void unregisterAll(Plugin disablePlugin) {
// Iterator<Replacer> iterator = replacers.values().iterator();
// while (iterator.hasNext()) {
// Plugin plugin = iterator.next().getPlugin();
// if (plugin == disablePlugin) {
// iterator.remove();
// }
// }
// }
//
// public void forceUpdate(String variable, int score) {
// Bukkit.getOnlinePlayers().forEach(player -> forceUpdate(player, variable, score));
// }
//
// public void forceUpdate(String variable, String value) {
// Bukkit.getOnlinePlayers().forEach(player -> forceUpdate(player, variable, value));
// }
//
// public abstract void forceUpdate(Player player, String variable, int score);
//
// public abstract void forceUpdate(Player player, String variable, String value);
//
// public Optional<String> replace(Player player, String variable, boolean complete) throws ReplacerException {
// Replacer replacer = getReplacer(variable);
// if (!complete && replacer.isGlobal() || replacer.isEventVariable() || replacer.isConstant()) {
// return Optional.empty();
// }
//
// try {
// return Optional.of(replacer.replace(player));
// } catch (Exception ex) {
// throw new ReplacerException(ex);
// }
// }
//
// public OptionalInt scoreReplace(Player player, String variable, boolean complete) throws ReplacerException {
// Replacer replacer = getReplacer(variable);
// if (!complete && replacer.isGlobal() || replacer.isEventVariable() || replacer.isConstant()) {
// return OptionalInt.empty();
// }
//
// try {
// return OptionalInt.of(replacer.scoreReplace(player));
// } catch (Exception ex) {
// throw new ReplacerException(ex);
// }
// }
//
// private Replacer getReplacer(String variable) throws UnknownVariableException {
// Replacer replacer = this.replacers.get(variable);
// if (replacer == null) {
// throw new UnknownVariableException(variable);
// }
//
// return replacer;
// }
// }
//
// Path: variables/src/main/java/com/github/games647/scoreboardstats/variables/UnsupportedPluginException.java
// public class UnsupportedPluginException extends ReplacerException {
//
// public UnsupportedPluginException(String pluginName, String expectedVersion, String currentVersion) {
// super(String.format("The version %s of plugin %s version isn't supported. We require at least %s",
// currentVersion, pluginName, expectedVersion));
// }
//
// public UnsupportedPluginException(String message) {
// super(message);
// }
// }
// Path: defaults/src/main/java/com/github/games647/scoreboardstats/defaults/SkyblockVariables.java
import com.github.games647.scoreboardstats.variables.DefaultReplacer;
import com.github.games647.scoreboardstats.variables.DefaultReplacers;
import com.github.games647.scoreboardstats.variables.ReplacerAPI;
import com.github.games647.scoreboardstats.variables.UnsupportedPluginException;
import org.bukkit.plugin.Plugin;
import org.bukkit.util.NumberConversions;
import us.talabrek.ultimateskyblock.api.event.uSkyBlockScoreChangedEvent;
import us.talabrek.ultimateskyblock.api.uSkyBlockAPI;
package com.github.games647.scoreboardstats.defaults;
/**
* Replace all variables that are associated with the uSkyBlock plugin
* <p>
* https://dev.bukkit.org/bukkit-plugins/uskyblock/
*/
@DefaultReplacer(plugin = "uSkyblock")
public class SkyblockVariables extends DefaultReplacers<uSkyBlockAPI> {
| public SkyblockVariables(ReplacerAPI replaceManager, uSkyBlockAPI plugin) { |
games647/ScoreboardStats | defaults/src/main/java/com/github/games647/scoreboardstats/defaults/SkyblockVariables.java | // Path: variables/src/main/java/com/github/games647/scoreboardstats/variables/DefaultReplacers.java
// public abstract class DefaultReplacers<T extends Plugin> {
//
// protected final ReplacerAPI replaceManager;
// protected final T plugin;
//
// public DefaultReplacers(ReplacerAPI replaceManager, T plugin) {
// this.replaceManager = replaceManager;
// this.plugin = plugin;
// }
//
// /**
// * Register all variables that this class can manage
// */
// public abstract void register();
//
// /**
// * Shortcut method to register the variables without the boilerplate of adding the plugin instance and registering
// * it to the manager.
// *
// * @param variable variable name like "online"
// * @return the replacer responsible for this single variable
// */
// protected Replacer register(String variable) {
// Replacer replacer = new Replacer(plugin, variable);
// replaceManager.register(replacer);
// return replacer;
// }
// }
//
// Path: variables/src/main/java/com/github/games647/scoreboardstats/variables/ReplacerAPI.java
// public abstract class ReplacerAPI {
//
// protected final Logger logger;
// protected final Map<String, Replacer> replacers = Maps.newHashMap();
//
// public ReplacerAPI(Logger logger) {
// this.logger = logger;
// }
//
// public void register(Replacer replacer) {
// replacers.put(replacer.getVariable(), replacer);
//
// for (EventReplacer<? extends Event> eventReplacer : replacer.getEventsReplacers().values()) {
// Class<? extends Event> eventClass = eventReplacer.getEventClass();
// Plugin plugin = replacer.getPlugin();
//
// EventExecutor executor = (listener, event) -> eventReplacer.execute(this, event);
//
// Listener listener = new Listener() {};
//
// PluginManager pluginManager = Bukkit.getPluginManager();
// pluginManager.registerEvent(eventClass, listener, HIGHEST, executor, plugin, true);
// }
// }
//
// public void unregister(String variable) {
// replacers.remove(variable);
// }
//
// public void unregisterAll(Plugin disablePlugin) {
// Iterator<Replacer> iterator = replacers.values().iterator();
// while (iterator.hasNext()) {
// Plugin plugin = iterator.next().getPlugin();
// if (plugin == disablePlugin) {
// iterator.remove();
// }
// }
// }
//
// public void forceUpdate(String variable, int score) {
// Bukkit.getOnlinePlayers().forEach(player -> forceUpdate(player, variable, score));
// }
//
// public void forceUpdate(String variable, String value) {
// Bukkit.getOnlinePlayers().forEach(player -> forceUpdate(player, variable, value));
// }
//
// public abstract void forceUpdate(Player player, String variable, int score);
//
// public abstract void forceUpdate(Player player, String variable, String value);
//
// public Optional<String> replace(Player player, String variable, boolean complete) throws ReplacerException {
// Replacer replacer = getReplacer(variable);
// if (!complete && replacer.isGlobal() || replacer.isEventVariable() || replacer.isConstant()) {
// return Optional.empty();
// }
//
// try {
// return Optional.of(replacer.replace(player));
// } catch (Exception ex) {
// throw new ReplacerException(ex);
// }
// }
//
// public OptionalInt scoreReplace(Player player, String variable, boolean complete) throws ReplacerException {
// Replacer replacer = getReplacer(variable);
// if (!complete && replacer.isGlobal() || replacer.isEventVariable() || replacer.isConstant()) {
// return OptionalInt.empty();
// }
//
// try {
// return OptionalInt.of(replacer.scoreReplace(player));
// } catch (Exception ex) {
// throw new ReplacerException(ex);
// }
// }
//
// private Replacer getReplacer(String variable) throws UnknownVariableException {
// Replacer replacer = this.replacers.get(variable);
// if (replacer == null) {
// throw new UnknownVariableException(variable);
// }
//
// return replacer;
// }
// }
//
// Path: variables/src/main/java/com/github/games647/scoreboardstats/variables/UnsupportedPluginException.java
// public class UnsupportedPluginException extends ReplacerException {
//
// public UnsupportedPluginException(String pluginName, String expectedVersion, String currentVersion) {
// super(String.format("The version %s of plugin %s version isn't supported. We require at least %s",
// currentVersion, pluginName, expectedVersion));
// }
//
// public UnsupportedPluginException(String message) {
// super(message);
// }
// }
| import com.github.games647.scoreboardstats.variables.DefaultReplacer;
import com.github.games647.scoreboardstats.variables.DefaultReplacers;
import com.github.games647.scoreboardstats.variables.ReplacerAPI;
import com.github.games647.scoreboardstats.variables.UnsupportedPluginException;
import org.bukkit.plugin.Plugin;
import org.bukkit.util.NumberConversions;
import us.talabrek.ultimateskyblock.api.event.uSkyBlockScoreChangedEvent;
import us.talabrek.ultimateskyblock.api.uSkyBlockAPI; | package com.github.games647.scoreboardstats.defaults;
/**
* Replace all variables that are associated with the uSkyBlock plugin
* <p>
* https://dev.bukkit.org/bukkit-plugins/uskyblock/
*/
@DefaultReplacer(plugin = "uSkyblock")
public class SkyblockVariables extends DefaultReplacers<uSkyBlockAPI> {
public SkyblockVariables(ReplacerAPI replaceManager, uSkyBlockAPI plugin) {
super(replaceManager, plugin);
}
| // Path: variables/src/main/java/com/github/games647/scoreboardstats/variables/DefaultReplacers.java
// public abstract class DefaultReplacers<T extends Plugin> {
//
// protected final ReplacerAPI replaceManager;
// protected final T plugin;
//
// public DefaultReplacers(ReplacerAPI replaceManager, T plugin) {
// this.replaceManager = replaceManager;
// this.plugin = plugin;
// }
//
// /**
// * Register all variables that this class can manage
// */
// public abstract void register();
//
// /**
// * Shortcut method to register the variables without the boilerplate of adding the plugin instance and registering
// * it to the manager.
// *
// * @param variable variable name like "online"
// * @return the replacer responsible for this single variable
// */
// protected Replacer register(String variable) {
// Replacer replacer = new Replacer(plugin, variable);
// replaceManager.register(replacer);
// return replacer;
// }
// }
//
// Path: variables/src/main/java/com/github/games647/scoreboardstats/variables/ReplacerAPI.java
// public abstract class ReplacerAPI {
//
// protected final Logger logger;
// protected final Map<String, Replacer> replacers = Maps.newHashMap();
//
// public ReplacerAPI(Logger logger) {
// this.logger = logger;
// }
//
// public void register(Replacer replacer) {
// replacers.put(replacer.getVariable(), replacer);
//
// for (EventReplacer<? extends Event> eventReplacer : replacer.getEventsReplacers().values()) {
// Class<? extends Event> eventClass = eventReplacer.getEventClass();
// Plugin plugin = replacer.getPlugin();
//
// EventExecutor executor = (listener, event) -> eventReplacer.execute(this, event);
//
// Listener listener = new Listener() {};
//
// PluginManager pluginManager = Bukkit.getPluginManager();
// pluginManager.registerEvent(eventClass, listener, HIGHEST, executor, plugin, true);
// }
// }
//
// public void unregister(String variable) {
// replacers.remove(variable);
// }
//
// public void unregisterAll(Plugin disablePlugin) {
// Iterator<Replacer> iterator = replacers.values().iterator();
// while (iterator.hasNext()) {
// Plugin plugin = iterator.next().getPlugin();
// if (plugin == disablePlugin) {
// iterator.remove();
// }
// }
// }
//
// public void forceUpdate(String variable, int score) {
// Bukkit.getOnlinePlayers().forEach(player -> forceUpdate(player, variable, score));
// }
//
// public void forceUpdate(String variable, String value) {
// Bukkit.getOnlinePlayers().forEach(player -> forceUpdate(player, variable, value));
// }
//
// public abstract void forceUpdate(Player player, String variable, int score);
//
// public abstract void forceUpdate(Player player, String variable, String value);
//
// public Optional<String> replace(Player player, String variable, boolean complete) throws ReplacerException {
// Replacer replacer = getReplacer(variable);
// if (!complete && replacer.isGlobal() || replacer.isEventVariable() || replacer.isConstant()) {
// return Optional.empty();
// }
//
// try {
// return Optional.of(replacer.replace(player));
// } catch (Exception ex) {
// throw new ReplacerException(ex);
// }
// }
//
// public OptionalInt scoreReplace(Player player, String variable, boolean complete) throws ReplacerException {
// Replacer replacer = getReplacer(variable);
// if (!complete && replacer.isGlobal() || replacer.isEventVariable() || replacer.isConstant()) {
// return OptionalInt.empty();
// }
//
// try {
// return OptionalInt.of(replacer.scoreReplace(player));
// } catch (Exception ex) {
// throw new ReplacerException(ex);
// }
// }
//
// private Replacer getReplacer(String variable) throws UnknownVariableException {
// Replacer replacer = this.replacers.get(variable);
// if (replacer == null) {
// throw new UnknownVariableException(variable);
// }
//
// return replacer;
// }
// }
//
// Path: variables/src/main/java/com/github/games647/scoreboardstats/variables/UnsupportedPluginException.java
// public class UnsupportedPluginException extends ReplacerException {
//
// public UnsupportedPluginException(String pluginName, String expectedVersion, String currentVersion) {
// super(String.format("The version %s of plugin %s version isn't supported. We require at least %s",
// currentVersion, pluginName, expectedVersion));
// }
//
// public UnsupportedPluginException(String message) {
// super(message);
// }
// }
// Path: defaults/src/main/java/com/github/games647/scoreboardstats/defaults/SkyblockVariables.java
import com.github.games647.scoreboardstats.variables.DefaultReplacer;
import com.github.games647.scoreboardstats.variables.DefaultReplacers;
import com.github.games647.scoreboardstats.variables.ReplacerAPI;
import com.github.games647.scoreboardstats.variables.UnsupportedPluginException;
import org.bukkit.plugin.Plugin;
import org.bukkit.util.NumberConversions;
import us.talabrek.ultimateskyblock.api.event.uSkyBlockScoreChangedEvent;
import us.talabrek.ultimateskyblock.api.uSkyBlockAPI;
package com.github.games647.scoreboardstats.defaults;
/**
* Replace all variables that are associated with the uSkyBlock plugin
* <p>
* https://dev.bukkit.org/bukkit-plugins/uskyblock/
*/
@DefaultReplacer(plugin = "uSkyblock")
public class SkyblockVariables extends DefaultReplacers<uSkyBlockAPI> {
public SkyblockVariables(ReplacerAPI replaceManager, uSkyBlockAPI plugin) {
super(replaceManager, plugin);
}
| private static uSkyBlockAPI getCheckVersion(Plugin plugin) throws UnsupportedPluginException { |
games647/ScoreboardStats | defaults/src/main/java/com/github/games647/scoreboardstats/defaults/VaultVariables.java | // Path: variables/src/main/java/com/github/games647/scoreboardstats/variables/DefaultReplacers.java
// public abstract class DefaultReplacers<T extends Plugin> {
//
// protected final ReplacerAPI replaceManager;
// protected final T plugin;
//
// public DefaultReplacers(ReplacerAPI replaceManager, T plugin) {
// this.replaceManager = replaceManager;
// this.plugin = plugin;
// }
//
// /**
// * Register all variables that this class can manage
// */
// public abstract void register();
//
// /**
// * Shortcut method to register the variables without the boilerplate of adding the plugin instance and registering
// * it to the manager.
// *
// * @param variable variable name like "online"
// * @return the replacer responsible for this single variable
// */
// protected Replacer register(String variable) {
// Replacer replacer = new Replacer(plugin, variable);
// replaceManager.register(replacer);
// return replacer;
// }
// }
//
// Path: variables/src/main/java/com/github/games647/scoreboardstats/variables/ReplacerAPI.java
// public abstract class ReplacerAPI {
//
// protected final Logger logger;
// protected final Map<String, Replacer> replacers = Maps.newHashMap();
//
// public ReplacerAPI(Logger logger) {
// this.logger = logger;
// }
//
// public void register(Replacer replacer) {
// replacers.put(replacer.getVariable(), replacer);
//
// for (EventReplacer<? extends Event> eventReplacer : replacer.getEventsReplacers().values()) {
// Class<? extends Event> eventClass = eventReplacer.getEventClass();
// Plugin plugin = replacer.getPlugin();
//
// EventExecutor executor = (listener, event) -> eventReplacer.execute(this, event);
//
// Listener listener = new Listener() {};
//
// PluginManager pluginManager = Bukkit.getPluginManager();
// pluginManager.registerEvent(eventClass, listener, HIGHEST, executor, plugin, true);
// }
// }
//
// public void unregister(String variable) {
// replacers.remove(variable);
// }
//
// public void unregisterAll(Plugin disablePlugin) {
// Iterator<Replacer> iterator = replacers.values().iterator();
// while (iterator.hasNext()) {
// Plugin plugin = iterator.next().getPlugin();
// if (plugin == disablePlugin) {
// iterator.remove();
// }
// }
// }
//
// public void forceUpdate(String variable, int score) {
// Bukkit.getOnlinePlayers().forEach(player -> forceUpdate(player, variable, score));
// }
//
// public void forceUpdate(String variable, String value) {
// Bukkit.getOnlinePlayers().forEach(player -> forceUpdate(player, variable, value));
// }
//
// public abstract void forceUpdate(Player player, String variable, int score);
//
// public abstract void forceUpdate(Player player, String variable, String value);
//
// public Optional<String> replace(Player player, String variable, boolean complete) throws ReplacerException {
// Replacer replacer = getReplacer(variable);
// if (!complete && replacer.isGlobal() || replacer.isEventVariable() || replacer.isConstant()) {
// return Optional.empty();
// }
//
// try {
// return Optional.of(replacer.replace(player));
// } catch (Exception ex) {
// throw new ReplacerException(ex);
// }
// }
//
// public OptionalInt scoreReplace(Player player, String variable, boolean complete) throws ReplacerException {
// Replacer replacer = getReplacer(variable);
// if (!complete && replacer.isGlobal() || replacer.isEventVariable() || replacer.isConstant()) {
// return OptionalInt.empty();
// }
//
// try {
// return OptionalInt.of(replacer.scoreReplace(player));
// } catch (Exception ex) {
// throw new ReplacerException(ex);
// }
// }
//
// private Replacer getReplacer(String variable) throws UnknownVariableException {
// Replacer replacer = this.replacers.get(variable);
// if (replacer == null) {
// throw new UnknownVariableException(variable);
// }
//
// return replacer;
// }
// }
//
// Path: variables/src/main/java/com/github/games647/scoreboardstats/variables/UnsupportedPluginException.java
// public class UnsupportedPluginException extends ReplacerException {
//
// public UnsupportedPluginException(String pluginName, String expectedVersion, String currentVersion) {
// super(String.format("The version %s of plugin %s version isn't supported. We require at least %s",
// currentVersion, pluginName, expectedVersion));
// }
//
// public UnsupportedPluginException(String message) {
// super(message);
// }
// }
| import com.github.games647.scoreboardstats.variables.DefaultReplacer;
import com.github.games647.scoreboardstats.variables.DefaultReplacers;
import com.github.games647.scoreboardstats.variables.ReplacerAPI;
import com.github.games647.scoreboardstats.variables.UnsupportedPluginException;
import net.milkbowl.vault.economy.Economy;
import org.bukkit.Bukkit;
import org.bukkit.entity.Player;
import org.bukkit.plugin.Plugin;
import org.bukkit.plugin.RegisteredServiceProvider;
import org.bukkit.util.NumberConversions; | package com.github.games647.scoreboardstats.defaults;
/**
* Replace the economy variable with Vault.
* <p>
* https://dev.bukkit.org/bukkit-plugins/vault/
*
* @see Economy
*/
@DefaultReplacer(plugin = "Vault")
public class VaultVariables extends DefaultReplacers<Plugin> {
private final Economy economy;
| // Path: variables/src/main/java/com/github/games647/scoreboardstats/variables/DefaultReplacers.java
// public abstract class DefaultReplacers<T extends Plugin> {
//
// protected final ReplacerAPI replaceManager;
// protected final T plugin;
//
// public DefaultReplacers(ReplacerAPI replaceManager, T plugin) {
// this.replaceManager = replaceManager;
// this.plugin = plugin;
// }
//
// /**
// * Register all variables that this class can manage
// */
// public abstract void register();
//
// /**
// * Shortcut method to register the variables without the boilerplate of adding the plugin instance and registering
// * it to the manager.
// *
// * @param variable variable name like "online"
// * @return the replacer responsible for this single variable
// */
// protected Replacer register(String variable) {
// Replacer replacer = new Replacer(plugin, variable);
// replaceManager.register(replacer);
// return replacer;
// }
// }
//
// Path: variables/src/main/java/com/github/games647/scoreboardstats/variables/ReplacerAPI.java
// public abstract class ReplacerAPI {
//
// protected final Logger logger;
// protected final Map<String, Replacer> replacers = Maps.newHashMap();
//
// public ReplacerAPI(Logger logger) {
// this.logger = logger;
// }
//
// public void register(Replacer replacer) {
// replacers.put(replacer.getVariable(), replacer);
//
// for (EventReplacer<? extends Event> eventReplacer : replacer.getEventsReplacers().values()) {
// Class<? extends Event> eventClass = eventReplacer.getEventClass();
// Plugin plugin = replacer.getPlugin();
//
// EventExecutor executor = (listener, event) -> eventReplacer.execute(this, event);
//
// Listener listener = new Listener() {};
//
// PluginManager pluginManager = Bukkit.getPluginManager();
// pluginManager.registerEvent(eventClass, listener, HIGHEST, executor, plugin, true);
// }
// }
//
// public void unregister(String variable) {
// replacers.remove(variable);
// }
//
// public void unregisterAll(Plugin disablePlugin) {
// Iterator<Replacer> iterator = replacers.values().iterator();
// while (iterator.hasNext()) {
// Plugin plugin = iterator.next().getPlugin();
// if (plugin == disablePlugin) {
// iterator.remove();
// }
// }
// }
//
// public void forceUpdate(String variable, int score) {
// Bukkit.getOnlinePlayers().forEach(player -> forceUpdate(player, variable, score));
// }
//
// public void forceUpdate(String variable, String value) {
// Bukkit.getOnlinePlayers().forEach(player -> forceUpdate(player, variable, value));
// }
//
// public abstract void forceUpdate(Player player, String variable, int score);
//
// public abstract void forceUpdate(Player player, String variable, String value);
//
// public Optional<String> replace(Player player, String variable, boolean complete) throws ReplacerException {
// Replacer replacer = getReplacer(variable);
// if (!complete && replacer.isGlobal() || replacer.isEventVariable() || replacer.isConstant()) {
// return Optional.empty();
// }
//
// try {
// return Optional.of(replacer.replace(player));
// } catch (Exception ex) {
// throw new ReplacerException(ex);
// }
// }
//
// public OptionalInt scoreReplace(Player player, String variable, boolean complete) throws ReplacerException {
// Replacer replacer = getReplacer(variable);
// if (!complete && replacer.isGlobal() || replacer.isEventVariable() || replacer.isConstant()) {
// return OptionalInt.empty();
// }
//
// try {
// return OptionalInt.of(replacer.scoreReplace(player));
// } catch (Exception ex) {
// throw new ReplacerException(ex);
// }
// }
//
// private Replacer getReplacer(String variable) throws UnknownVariableException {
// Replacer replacer = this.replacers.get(variable);
// if (replacer == null) {
// throw new UnknownVariableException(variable);
// }
//
// return replacer;
// }
// }
//
// Path: variables/src/main/java/com/github/games647/scoreboardstats/variables/UnsupportedPluginException.java
// public class UnsupportedPluginException extends ReplacerException {
//
// public UnsupportedPluginException(String pluginName, String expectedVersion, String currentVersion) {
// super(String.format("The version %s of plugin %s version isn't supported. We require at least %s",
// currentVersion, pluginName, expectedVersion));
// }
//
// public UnsupportedPluginException(String message) {
// super(message);
// }
// }
// Path: defaults/src/main/java/com/github/games647/scoreboardstats/defaults/VaultVariables.java
import com.github.games647.scoreboardstats.variables.DefaultReplacer;
import com.github.games647.scoreboardstats.variables.DefaultReplacers;
import com.github.games647.scoreboardstats.variables.ReplacerAPI;
import com.github.games647.scoreboardstats.variables.UnsupportedPluginException;
import net.milkbowl.vault.economy.Economy;
import org.bukkit.Bukkit;
import org.bukkit.entity.Player;
import org.bukkit.plugin.Plugin;
import org.bukkit.plugin.RegisteredServiceProvider;
import org.bukkit.util.NumberConversions;
package com.github.games647.scoreboardstats.defaults;
/**
* Replace the economy variable with Vault.
* <p>
* https://dev.bukkit.org/bukkit-plugins/vault/
*
* @see Economy
*/
@DefaultReplacer(plugin = "Vault")
public class VaultVariables extends DefaultReplacers<Plugin> {
private final Economy economy;
| public VaultVariables(ReplacerAPI replaceManager, Plugin plugin) throws UnsupportedPluginException { |
games647/ScoreboardStats | defaults/src/main/java/com/github/games647/scoreboardstats/defaults/VaultVariables.java | // Path: variables/src/main/java/com/github/games647/scoreboardstats/variables/DefaultReplacers.java
// public abstract class DefaultReplacers<T extends Plugin> {
//
// protected final ReplacerAPI replaceManager;
// protected final T plugin;
//
// public DefaultReplacers(ReplacerAPI replaceManager, T plugin) {
// this.replaceManager = replaceManager;
// this.plugin = plugin;
// }
//
// /**
// * Register all variables that this class can manage
// */
// public abstract void register();
//
// /**
// * Shortcut method to register the variables without the boilerplate of adding the plugin instance and registering
// * it to the manager.
// *
// * @param variable variable name like "online"
// * @return the replacer responsible for this single variable
// */
// protected Replacer register(String variable) {
// Replacer replacer = new Replacer(plugin, variable);
// replaceManager.register(replacer);
// return replacer;
// }
// }
//
// Path: variables/src/main/java/com/github/games647/scoreboardstats/variables/ReplacerAPI.java
// public abstract class ReplacerAPI {
//
// protected final Logger logger;
// protected final Map<String, Replacer> replacers = Maps.newHashMap();
//
// public ReplacerAPI(Logger logger) {
// this.logger = logger;
// }
//
// public void register(Replacer replacer) {
// replacers.put(replacer.getVariable(), replacer);
//
// for (EventReplacer<? extends Event> eventReplacer : replacer.getEventsReplacers().values()) {
// Class<? extends Event> eventClass = eventReplacer.getEventClass();
// Plugin plugin = replacer.getPlugin();
//
// EventExecutor executor = (listener, event) -> eventReplacer.execute(this, event);
//
// Listener listener = new Listener() {};
//
// PluginManager pluginManager = Bukkit.getPluginManager();
// pluginManager.registerEvent(eventClass, listener, HIGHEST, executor, plugin, true);
// }
// }
//
// public void unregister(String variable) {
// replacers.remove(variable);
// }
//
// public void unregisterAll(Plugin disablePlugin) {
// Iterator<Replacer> iterator = replacers.values().iterator();
// while (iterator.hasNext()) {
// Plugin plugin = iterator.next().getPlugin();
// if (plugin == disablePlugin) {
// iterator.remove();
// }
// }
// }
//
// public void forceUpdate(String variable, int score) {
// Bukkit.getOnlinePlayers().forEach(player -> forceUpdate(player, variable, score));
// }
//
// public void forceUpdate(String variable, String value) {
// Bukkit.getOnlinePlayers().forEach(player -> forceUpdate(player, variable, value));
// }
//
// public abstract void forceUpdate(Player player, String variable, int score);
//
// public abstract void forceUpdate(Player player, String variable, String value);
//
// public Optional<String> replace(Player player, String variable, boolean complete) throws ReplacerException {
// Replacer replacer = getReplacer(variable);
// if (!complete && replacer.isGlobal() || replacer.isEventVariable() || replacer.isConstant()) {
// return Optional.empty();
// }
//
// try {
// return Optional.of(replacer.replace(player));
// } catch (Exception ex) {
// throw new ReplacerException(ex);
// }
// }
//
// public OptionalInt scoreReplace(Player player, String variable, boolean complete) throws ReplacerException {
// Replacer replacer = getReplacer(variable);
// if (!complete && replacer.isGlobal() || replacer.isEventVariable() || replacer.isConstant()) {
// return OptionalInt.empty();
// }
//
// try {
// return OptionalInt.of(replacer.scoreReplace(player));
// } catch (Exception ex) {
// throw new ReplacerException(ex);
// }
// }
//
// private Replacer getReplacer(String variable) throws UnknownVariableException {
// Replacer replacer = this.replacers.get(variable);
// if (replacer == null) {
// throw new UnknownVariableException(variable);
// }
//
// return replacer;
// }
// }
//
// Path: variables/src/main/java/com/github/games647/scoreboardstats/variables/UnsupportedPluginException.java
// public class UnsupportedPluginException extends ReplacerException {
//
// public UnsupportedPluginException(String pluginName, String expectedVersion, String currentVersion) {
// super(String.format("The version %s of plugin %s version isn't supported. We require at least %s",
// currentVersion, pluginName, expectedVersion));
// }
//
// public UnsupportedPluginException(String message) {
// super(message);
// }
// }
| import com.github.games647.scoreboardstats.variables.DefaultReplacer;
import com.github.games647.scoreboardstats.variables.DefaultReplacers;
import com.github.games647.scoreboardstats.variables.ReplacerAPI;
import com.github.games647.scoreboardstats.variables.UnsupportedPluginException;
import net.milkbowl.vault.economy.Economy;
import org.bukkit.Bukkit;
import org.bukkit.entity.Player;
import org.bukkit.plugin.Plugin;
import org.bukkit.plugin.RegisteredServiceProvider;
import org.bukkit.util.NumberConversions; | package com.github.games647.scoreboardstats.defaults;
/**
* Replace the economy variable with Vault.
* <p>
* https://dev.bukkit.org/bukkit-plugins/vault/
*
* @see Economy
*/
@DefaultReplacer(plugin = "Vault")
public class VaultVariables extends DefaultReplacers<Plugin> {
private final Economy economy;
| // Path: variables/src/main/java/com/github/games647/scoreboardstats/variables/DefaultReplacers.java
// public abstract class DefaultReplacers<T extends Plugin> {
//
// protected final ReplacerAPI replaceManager;
// protected final T plugin;
//
// public DefaultReplacers(ReplacerAPI replaceManager, T plugin) {
// this.replaceManager = replaceManager;
// this.plugin = plugin;
// }
//
// /**
// * Register all variables that this class can manage
// */
// public abstract void register();
//
// /**
// * Shortcut method to register the variables without the boilerplate of adding the plugin instance and registering
// * it to the manager.
// *
// * @param variable variable name like "online"
// * @return the replacer responsible for this single variable
// */
// protected Replacer register(String variable) {
// Replacer replacer = new Replacer(plugin, variable);
// replaceManager.register(replacer);
// return replacer;
// }
// }
//
// Path: variables/src/main/java/com/github/games647/scoreboardstats/variables/ReplacerAPI.java
// public abstract class ReplacerAPI {
//
// protected final Logger logger;
// protected final Map<String, Replacer> replacers = Maps.newHashMap();
//
// public ReplacerAPI(Logger logger) {
// this.logger = logger;
// }
//
// public void register(Replacer replacer) {
// replacers.put(replacer.getVariable(), replacer);
//
// for (EventReplacer<? extends Event> eventReplacer : replacer.getEventsReplacers().values()) {
// Class<? extends Event> eventClass = eventReplacer.getEventClass();
// Plugin plugin = replacer.getPlugin();
//
// EventExecutor executor = (listener, event) -> eventReplacer.execute(this, event);
//
// Listener listener = new Listener() {};
//
// PluginManager pluginManager = Bukkit.getPluginManager();
// pluginManager.registerEvent(eventClass, listener, HIGHEST, executor, plugin, true);
// }
// }
//
// public void unregister(String variable) {
// replacers.remove(variable);
// }
//
// public void unregisterAll(Plugin disablePlugin) {
// Iterator<Replacer> iterator = replacers.values().iterator();
// while (iterator.hasNext()) {
// Plugin plugin = iterator.next().getPlugin();
// if (plugin == disablePlugin) {
// iterator.remove();
// }
// }
// }
//
// public void forceUpdate(String variable, int score) {
// Bukkit.getOnlinePlayers().forEach(player -> forceUpdate(player, variable, score));
// }
//
// public void forceUpdate(String variable, String value) {
// Bukkit.getOnlinePlayers().forEach(player -> forceUpdate(player, variable, value));
// }
//
// public abstract void forceUpdate(Player player, String variable, int score);
//
// public abstract void forceUpdate(Player player, String variable, String value);
//
// public Optional<String> replace(Player player, String variable, boolean complete) throws ReplacerException {
// Replacer replacer = getReplacer(variable);
// if (!complete && replacer.isGlobal() || replacer.isEventVariable() || replacer.isConstant()) {
// return Optional.empty();
// }
//
// try {
// return Optional.of(replacer.replace(player));
// } catch (Exception ex) {
// throw new ReplacerException(ex);
// }
// }
//
// public OptionalInt scoreReplace(Player player, String variable, boolean complete) throws ReplacerException {
// Replacer replacer = getReplacer(variable);
// if (!complete && replacer.isGlobal() || replacer.isEventVariable() || replacer.isConstant()) {
// return OptionalInt.empty();
// }
//
// try {
// return OptionalInt.of(replacer.scoreReplace(player));
// } catch (Exception ex) {
// throw new ReplacerException(ex);
// }
// }
//
// private Replacer getReplacer(String variable) throws UnknownVariableException {
// Replacer replacer = this.replacers.get(variable);
// if (replacer == null) {
// throw new UnknownVariableException(variable);
// }
//
// return replacer;
// }
// }
//
// Path: variables/src/main/java/com/github/games647/scoreboardstats/variables/UnsupportedPluginException.java
// public class UnsupportedPluginException extends ReplacerException {
//
// public UnsupportedPluginException(String pluginName, String expectedVersion, String currentVersion) {
// super(String.format("The version %s of plugin %s version isn't supported. We require at least %s",
// currentVersion, pluginName, expectedVersion));
// }
//
// public UnsupportedPluginException(String message) {
// super(message);
// }
// }
// Path: defaults/src/main/java/com/github/games647/scoreboardstats/defaults/VaultVariables.java
import com.github.games647.scoreboardstats.variables.DefaultReplacer;
import com.github.games647.scoreboardstats.variables.DefaultReplacers;
import com.github.games647.scoreboardstats.variables.ReplacerAPI;
import com.github.games647.scoreboardstats.variables.UnsupportedPluginException;
import net.milkbowl.vault.economy.Economy;
import org.bukkit.Bukkit;
import org.bukkit.entity.Player;
import org.bukkit.plugin.Plugin;
import org.bukkit.plugin.RegisteredServiceProvider;
import org.bukkit.util.NumberConversions;
package com.github.games647.scoreboardstats.defaults;
/**
* Replace the economy variable with Vault.
* <p>
* https://dev.bukkit.org/bukkit-plugins/vault/
*
* @see Economy
*/
@DefaultReplacer(plugin = "Vault")
public class VaultVariables extends DefaultReplacers<Plugin> {
private final Economy economy;
| public VaultVariables(ReplacerAPI replaceManager, Plugin plugin) throws UnsupportedPluginException { |
games647/ScoreboardStats | defaults/src/main/java/com/github/games647/scoreboardstats/defaults/ASkyBlockVariables.java | // Path: variables/src/main/java/com/github/games647/scoreboardstats/variables/DefaultReplacers.java
// public abstract class DefaultReplacers<T extends Plugin> {
//
// protected final ReplacerAPI replaceManager;
// protected final T plugin;
//
// public DefaultReplacers(ReplacerAPI replaceManager, T plugin) {
// this.replaceManager = replaceManager;
// this.plugin = plugin;
// }
//
// /**
// * Register all variables that this class can manage
// */
// public abstract void register();
//
// /**
// * Shortcut method to register the variables without the boilerplate of adding the plugin instance and registering
// * it to the manager.
// *
// * @param variable variable name like "online"
// * @return the replacer responsible for this single variable
// */
// protected Replacer register(String variable) {
// Replacer replacer = new Replacer(plugin, variable);
// replaceManager.register(replacer);
// return replacer;
// }
// }
//
// Path: variables/src/main/java/com/github/games647/scoreboardstats/variables/ReplacerAPI.java
// public abstract class ReplacerAPI {
//
// protected final Logger logger;
// protected final Map<String, Replacer> replacers = Maps.newHashMap();
//
// public ReplacerAPI(Logger logger) {
// this.logger = logger;
// }
//
// public void register(Replacer replacer) {
// replacers.put(replacer.getVariable(), replacer);
//
// for (EventReplacer<? extends Event> eventReplacer : replacer.getEventsReplacers().values()) {
// Class<? extends Event> eventClass = eventReplacer.getEventClass();
// Plugin plugin = replacer.getPlugin();
//
// EventExecutor executor = (listener, event) -> eventReplacer.execute(this, event);
//
// Listener listener = new Listener() {};
//
// PluginManager pluginManager = Bukkit.getPluginManager();
// pluginManager.registerEvent(eventClass, listener, HIGHEST, executor, plugin, true);
// }
// }
//
// public void unregister(String variable) {
// replacers.remove(variable);
// }
//
// public void unregisterAll(Plugin disablePlugin) {
// Iterator<Replacer> iterator = replacers.values().iterator();
// while (iterator.hasNext()) {
// Plugin plugin = iterator.next().getPlugin();
// if (plugin == disablePlugin) {
// iterator.remove();
// }
// }
// }
//
// public void forceUpdate(String variable, int score) {
// Bukkit.getOnlinePlayers().forEach(player -> forceUpdate(player, variable, score));
// }
//
// public void forceUpdate(String variable, String value) {
// Bukkit.getOnlinePlayers().forEach(player -> forceUpdate(player, variable, value));
// }
//
// public abstract void forceUpdate(Player player, String variable, int score);
//
// public abstract void forceUpdate(Player player, String variable, String value);
//
// public Optional<String> replace(Player player, String variable, boolean complete) throws ReplacerException {
// Replacer replacer = getReplacer(variable);
// if (!complete && replacer.isGlobal() || replacer.isEventVariable() || replacer.isConstant()) {
// return Optional.empty();
// }
//
// try {
// return Optional.of(replacer.replace(player));
// } catch (Exception ex) {
// throw new ReplacerException(ex);
// }
// }
//
// public OptionalInt scoreReplace(Player player, String variable, boolean complete) throws ReplacerException {
// Replacer replacer = getReplacer(variable);
// if (!complete && replacer.isGlobal() || replacer.isEventVariable() || replacer.isConstant()) {
// return OptionalInt.empty();
// }
//
// try {
// return OptionalInt.of(replacer.scoreReplace(player));
// } catch (Exception ex) {
// throw new ReplacerException(ex);
// }
// }
//
// private Replacer getReplacer(String variable) throws UnknownVariableException {
// Replacer replacer = this.replacers.get(variable);
// if (replacer == null) {
// throw new UnknownVariableException(variable);
// }
//
// return replacer;
// }
// }
| import com.github.games647.scoreboardstats.variables.DefaultReplacer;
import com.github.games647.scoreboardstats.variables.DefaultReplacers;
import com.github.games647.scoreboardstats.variables.ReplacerAPI;
import com.wasteofplastic.askyblock.ASkyBlockAPI;
import com.wasteofplastic.askyblock.events.ChallengeCompleteEvent;
import com.wasteofplastic.askyblock.events.IslandPostLevelEvent;
import java.util.function.ToIntFunction;
import java.util.stream.Stream;
import org.bukkit.entity.Player;
import org.bukkit.plugin.Plugin; | package com.github.games647.scoreboardstats.defaults;
@DefaultReplacer(plugin = "ASkyBlock")
public class ASkyBlockVariables extends DefaultReplacers<Plugin> {
private final ASkyBlockAPI skyBlockAPI = ASkyBlockAPI.getInstance();
| // Path: variables/src/main/java/com/github/games647/scoreboardstats/variables/DefaultReplacers.java
// public abstract class DefaultReplacers<T extends Plugin> {
//
// protected final ReplacerAPI replaceManager;
// protected final T plugin;
//
// public DefaultReplacers(ReplacerAPI replaceManager, T plugin) {
// this.replaceManager = replaceManager;
// this.plugin = plugin;
// }
//
// /**
// * Register all variables that this class can manage
// */
// public abstract void register();
//
// /**
// * Shortcut method to register the variables without the boilerplate of adding the plugin instance and registering
// * it to the manager.
// *
// * @param variable variable name like "online"
// * @return the replacer responsible for this single variable
// */
// protected Replacer register(String variable) {
// Replacer replacer = new Replacer(plugin, variable);
// replaceManager.register(replacer);
// return replacer;
// }
// }
//
// Path: variables/src/main/java/com/github/games647/scoreboardstats/variables/ReplacerAPI.java
// public abstract class ReplacerAPI {
//
// protected final Logger logger;
// protected final Map<String, Replacer> replacers = Maps.newHashMap();
//
// public ReplacerAPI(Logger logger) {
// this.logger = logger;
// }
//
// public void register(Replacer replacer) {
// replacers.put(replacer.getVariable(), replacer);
//
// for (EventReplacer<? extends Event> eventReplacer : replacer.getEventsReplacers().values()) {
// Class<? extends Event> eventClass = eventReplacer.getEventClass();
// Plugin plugin = replacer.getPlugin();
//
// EventExecutor executor = (listener, event) -> eventReplacer.execute(this, event);
//
// Listener listener = new Listener() {};
//
// PluginManager pluginManager = Bukkit.getPluginManager();
// pluginManager.registerEvent(eventClass, listener, HIGHEST, executor, plugin, true);
// }
// }
//
// public void unregister(String variable) {
// replacers.remove(variable);
// }
//
// public void unregisterAll(Plugin disablePlugin) {
// Iterator<Replacer> iterator = replacers.values().iterator();
// while (iterator.hasNext()) {
// Plugin plugin = iterator.next().getPlugin();
// if (plugin == disablePlugin) {
// iterator.remove();
// }
// }
// }
//
// public void forceUpdate(String variable, int score) {
// Bukkit.getOnlinePlayers().forEach(player -> forceUpdate(player, variable, score));
// }
//
// public void forceUpdate(String variable, String value) {
// Bukkit.getOnlinePlayers().forEach(player -> forceUpdate(player, variable, value));
// }
//
// public abstract void forceUpdate(Player player, String variable, int score);
//
// public abstract void forceUpdate(Player player, String variable, String value);
//
// public Optional<String> replace(Player player, String variable, boolean complete) throws ReplacerException {
// Replacer replacer = getReplacer(variable);
// if (!complete && replacer.isGlobal() || replacer.isEventVariable() || replacer.isConstant()) {
// return Optional.empty();
// }
//
// try {
// return Optional.of(replacer.replace(player));
// } catch (Exception ex) {
// throw new ReplacerException(ex);
// }
// }
//
// public OptionalInt scoreReplace(Player player, String variable, boolean complete) throws ReplacerException {
// Replacer replacer = getReplacer(variable);
// if (!complete && replacer.isGlobal() || replacer.isEventVariable() || replacer.isConstant()) {
// return OptionalInt.empty();
// }
//
// try {
// return OptionalInt.of(replacer.scoreReplace(player));
// } catch (Exception ex) {
// throw new ReplacerException(ex);
// }
// }
//
// private Replacer getReplacer(String variable) throws UnknownVariableException {
// Replacer replacer = this.replacers.get(variable);
// if (replacer == null) {
// throw new UnknownVariableException(variable);
// }
//
// return replacer;
// }
// }
// Path: defaults/src/main/java/com/github/games647/scoreboardstats/defaults/ASkyBlockVariables.java
import com.github.games647.scoreboardstats.variables.DefaultReplacer;
import com.github.games647.scoreboardstats.variables.DefaultReplacers;
import com.github.games647.scoreboardstats.variables.ReplacerAPI;
import com.wasteofplastic.askyblock.ASkyBlockAPI;
import com.wasteofplastic.askyblock.events.ChallengeCompleteEvent;
import com.wasteofplastic.askyblock.events.IslandPostLevelEvent;
import java.util.function.ToIntFunction;
import java.util.stream.Stream;
import org.bukkit.entity.Player;
import org.bukkit.plugin.Plugin;
package com.github.games647.scoreboardstats.defaults;
@DefaultReplacer(plugin = "ASkyBlock")
public class ASkyBlockVariables extends DefaultReplacers<Plugin> {
private final ASkyBlockAPI skyBlockAPI = ASkyBlockAPI.getInstance();
| public ASkyBlockVariables(ReplacerAPI replaceManager, Plugin plugin) { |
games647/ScoreboardStats | defaults/src/main/java/com/github/games647/scoreboardstats/defaults/McPrisonVariables.java | // Path: variables/src/main/java/com/github/games647/scoreboardstats/variables/DefaultReplacers.java
// public abstract class DefaultReplacers<T extends Plugin> {
//
// protected final ReplacerAPI replaceManager;
// protected final T plugin;
//
// public DefaultReplacers(ReplacerAPI replaceManager, T plugin) {
// this.replaceManager = replaceManager;
// this.plugin = plugin;
// }
//
// /**
// * Register all variables that this class can manage
// */
// public abstract void register();
//
// /**
// * Shortcut method to register the variables without the boilerplate of adding the plugin instance and registering
// * it to the manager.
// *
// * @param variable variable name like "online"
// * @return the replacer responsible for this single variable
// */
// protected Replacer register(String variable) {
// Replacer replacer = new Replacer(plugin, variable);
// replaceManager.register(replacer);
// return replacer;
// }
// }
//
// Path: variables/src/main/java/com/github/games647/scoreboardstats/variables/ReplacerAPI.java
// public abstract class ReplacerAPI {
//
// protected final Logger logger;
// protected final Map<String, Replacer> replacers = Maps.newHashMap();
//
// public ReplacerAPI(Logger logger) {
// this.logger = logger;
// }
//
// public void register(Replacer replacer) {
// replacers.put(replacer.getVariable(), replacer);
//
// for (EventReplacer<? extends Event> eventReplacer : replacer.getEventsReplacers().values()) {
// Class<? extends Event> eventClass = eventReplacer.getEventClass();
// Plugin plugin = replacer.getPlugin();
//
// EventExecutor executor = (listener, event) -> eventReplacer.execute(this, event);
//
// Listener listener = new Listener() {};
//
// PluginManager pluginManager = Bukkit.getPluginManager();
// pluginManager.registerEvent(eventClass, listener, HIGHEST, executor, plugin, true);
// }
// }
//
// public void unregister(String variable) {
// replacers.remove(variable);
// }
//
// public void unregisterAll(Plugin disablePlugin) {
// Iterator<Replacer> iterator = replacers.values().iterator();
// while (iterator.hasNext()) {
// Plugin plugin = iterator.next().getPlugin();
// if (plugin == disablePlugin) {
// iterator.remove();
// }
// }
// }
//
// public void forceUpdate(String variable, int score) {
// Bukkit.getOnlinePlayers().forEach(player -> forceUpdate(player, variable, score));
// }
//
// public void forceUpdate(String variable, String value) {
// Bukkit.getOnlinePlayers().forEach(player -> forceUpdate(player, variable, value));
// }
//
// public abstract void forceUpdate(Player player, String variable, int score);
//
// public abstract void forceUpdate(Player player, String variable, String value);
//
// public Optional<String> replace(Player player, String variable, boolean complete) throws ReplacerException {
// Replacer replacer = getReplacer(variable);
// if (!complete && replacer.isGlobal() || replacer.isEventVariable() || replacer.isConstant()) {
// return Optional.empty();
// }
//
// try {
// return Optional.of(replacer.replace(player));
// } catch (Exception ex) {
// throw new ReplacerException(ex);
// }
// }
//
// public OptionalInt scoreReplace(Player player, String variable, boolean complete) throws ReplacerException {
// Replacer replacer = getReplacer(variable);
// if (!complete && replacer.isGlobal() || replacer.isEventVariable() || replacer.isConstant()) {
// return OptionalInt.empty();
// }
//
// try {
// return OptionalInt.of(replacer.scoreReplace(player));
// } catch (Exception ex) {
// throw new ReplacerException(ex);
// }
// }
//
// private Replacer getReplacer(String variable) throws UnknownVariableException {
// Replacer replacer = this.replacers.get(variable);
// if (replacer == null) {
// throw new UnknownVariableException(variable);
// }
//
// return replacer;
// }
// }
//
// Path: variables/src/main/java/com/github/games647/scoreboardstats/variables/UnsupportedPluginException.java
// public class UnsupportedPluginException extends ReplacerException {
//
// public UnsupportedPluginException(String pluginName, String expectedVersion, String currentVersion) {
// super(String.format("The version %s of plugin %s version isn't supported. We require at least %s",
// currentVersion, pluginName, expectedVersion));
// }
//
// public UnsupportedPluginException(String message) {
// super(message);
// }
// }
| import com.github.games647.scoreboardstats.variables.DefaultReplacer;
import com.github.games647.scoreboardstats.variables.DefaultReplacers;
import com.github.games647.scoreboardstats.variables.ReplacerAPI;
import com.github.games647.scoreboardstats.variables.UnsupportedPluginException;
import me.sirfaizdat.prison.ranks.Ranks;
import me.sirfaizdat.prison.ranks.UserInfo;
import me.sirfaizdat.prison.ranks.events.BalanceChangeEvent;
import me.sirfaizdat.prison.ranks.events.DemoteEvent;
import me.sirfaizdat.prison.ranks.events.RankupEvent;
import net.milkbowl.vault.economy.Economy;
import org.bukkit.Bukkit;
import org.bukkit.entity.Player;
import org.bukkit.plugin.Plugin;
import org.bukkit.plugin.RegisteredServiceProvider; | package com.github.games647.scoreboardstats.defaults;
/**
* Replace all variables that are associated with the prison plugin
* <p>
* https://dev.bukkit.org/bukkit-plugins/mcprison/
*/
@DefaultReplacer(plugin = "Prison")
public class McPrisonVariables extends DefaultReplacers<Plugin> {
private final Economy eco;
| // Path: variables/src/main/java/com/github/games647/scoreboardstats/variables/DefaultReplacers.java
// public abstract class DefaultReplacers<T extends Plugin> {
//
// protected final ReplacerAPI replaceManager;
// protected final T plugin;
//
// public DefaultReplacers(ReplacerAPI replaceManager, T plugin) {
// this.replaceManager = replaceManager;
// this.plugin = plugin;
// }
//
// /**
// * Register all variables that this class can manage
// */
// public abstract void register();
//
// /**
// * Shortcut method to register the variables without the boilerplate of adding the plugin instance and registering
// * it to the manager.
// *
// * @param variable variable name like "online"
// * @return the replacer responsible for this single variable
// */
// protected Replacer register(String variable) {
// Replacer replacer = new Replacer(plugin, variable);
// replaceManager.register(replacer);
// return replacer;
// }
// }
//
// Path: variables/src/main/java/com/github/games647/scoreboardstats/variables/ReplacerAPI.java
// public abstract class ReplacerAPI {
//
// protected final Logger logger;
// protected final Map<String, Replacer> replacers = Maps.newHashMap();
//
// public ReplacerAPI(Logger logger) {
// this.logger = logger;
// }
//
// public void register(Replacer replacer) {
// replacers.put(replacer.getVariable(), replacer);
//
// for (EventReplacer<? extends Event> eventReplacer : replacer.getEventsReplacers().values()) {
// Class<? extends Event> eventClass = eventReplacer.getEventClass();
// Plugin plugin = replacer.getPlugin();
//
// EventExecutor executor = (listener, event) -> eventReplacer.execute(this, event);
//
// Listener listener = new Listener() {};
//
// PluginManager pluginManager = Bukkit.getPluginManager();
// pluginManager.registerEvent(eventClass, listener, HIGHEST, executor, plugin, true);
// }
// }
//
// public void unregister(String variable) {
// replacers.remove(variable);
// }
//
// public void unregisterAll(Plugin disablePlugin) {
// Iterator<Replacer> iterator = replacers.values().iterator();
// while (iterator.hasNext()) {
// Plugin plugin = iterator.next().getPlugin();
// if (plugin == disablePlugin) {
// iterator.remove();
// }
// }
// }
//
// public void forceUpdate(String variable, int score) {
// Bukkit.getOnlinePlayers().forEach(player -> forceUpdate(player, variable, score));
// }
//
// public void forceUpdate(String variable, String value) {
// Bukkit.getOnlinePlayers().forEach(player -> forceUpdate(player, variable, value));
// }
//
// public abstract void forceUpdate(Player player, String variable, int score);
//
// public abstract void forceUpdate(Player player, String variable, String value);
//
// public Optional<String> replace(Player player, String variable, boolean complete) throws ReplacerException {
// Replacer replacer = getReplacer(variable);
// if (!complete && replacer.isGlobal() || replacer.isEventVariable() || replacer.isConstant()) {
// return Optional.empty();
// }
//
// try {
// return Optional.of(replacer.replace(player));
// } catch (Exception ex) {
// throw new ReplacerException(ex);
// }
// }
//
// public OptionalInt scoreReplace(Player player, String variable, boolean complete) throws ReplacerException {
// Replacer replacer = getReplacer(variable);
// if (!complete && replacer.isGlobal() || replacer.isEventVariable() || replacer.isConstant()) {
// return OptionalInt.empty();
// }
//
// try {
// return OptionalInt.of(replacer.scoreReplace(player));
// } catch (Exception ex) {
// throw new ReplacerException(ex);
// }
// }
//
// private Replacer getReplacer(String variable) throws UnknownVariableException {
// Replacer replacer = this.replacers.get(variable);
// if (replacer == null) {
// throw new UnknownVariableException(variable);
// }
//
// return replacer;
// }
// }
//
// Path: variables/src/main/java/com/github/games647/scoreboardstats/variables/UnsupportedPluginException.java
// public class UnsupportedPluginException extends ReplacerException {
//
// public UnsupportedPluginException(String pluginName, String expectedVersion, String currentVersion) {
// super(String.format("The version %s of plugin %s version isn't supported. We require at least %s",
// currentVersion, pluginName, expectedVersion));
// }
//
// public UnsupportedPluginException(String message) {
// super(message);
// }
// }
// Path: defaults/src/main/java/com/github/games647/scoreboardstats/defaults/McPrisonVariables.java
import com.github.games647.scoreboardstats.variables.DefaultReplacer;
import com.github.games647.scoreboardstats.variables.DefaultReplacers;
import com.github.games647.scoreboardstats.variables.ReplacerAPI;
import com.github.games647.scoreboardstats.variables.UnsupportedPluginException;
import me.sirfaizdat.prison.ranks.Ranks;
import me.sirfaizdat.prison.ranks.UserInfo;
import me.sirfaizdat.prison.ranks.events.BalanceChangeEvent;
import me.sirfaizdat.prison.ranks.events.DemoteEvent;
import me.sirfaizdat.prison.ranks.events.RankupEvent;
import net.milkbowl.vault.economy.Economy;
import org.bukkit.Bukkit;
import org.bukkit.entity.Player;
import org.bukkit.plugin.Plugin;
import org.bukkit.plugin.RegisteredServiceProvider;
package com.github.games647.scoreboardstats.defaults;
/**
* Replace all variables that are associated with the prison plugin
* <p>
* https://dev.bukkit.org/bukkit-plugins/mcprison/
*/
@DefaultReplacer(plugin = "Prison")
public class McPrisonVariables extends DefaultReplacers<Plugin> {
private final Economy eco;
| public McPrisonVariables(ReplacerAPI replaceManager, Plugin plugin) throws UnsupportedPluginException { |
games647/ScoreboardStats | defaults/src/main/java/com/github/games647/scoreboardstats/defaults/McPrisonVariables.java | // Path: variables/src/main/java/com/github/games647/scoreboardstats/variables/DefaultReplacers.java
// public abstract class DefaultReplacers<T extends Plugin> {
//
// protected final ReplacerAPI replaceManager;
// protected final T plugin;
//
// public DefaultReplacers(ReplacerAPI replaceManager, T plugin) {
// this.replaceManager = replaceManager;
// this.plugin = plugin;
// }
//
// /**
// * Register all variables that this class can manage
// */
// public abstract void register();
//
// /**
// * Shortcut method to register the variables without the boilerplate of adding the plugin instance and registering
// * it to the manager.
// *
// * @param variable variable name like "online"
// * @return the replacer responsible for this single variable
// */
// protected Replacer register(String variable) {
// Replacer replacer = new Replacer(plugin, variable);
// replaceManager.register(replacer);
// return replacer;
// }
// }
//
// Path: variables/src/main/java/com/github/games647/scoreboardstats/variables/ReplacerAPI.java
// public abstract class ReplacerAPI {
//
// protected final Logger logger;
// protected final Map<String, Replacer> replacers = Maps.newHashMap();
//
// public ReplacerAPI(Logger logger) {
// this.logger = logger;
// }
//
// public void register(Replacer replacer) {
// replacers.put(replacer.getVariable(), replacer);
//
// for (EventReplacer<? extends Event> eventReplacer : replacer.getEventsReplacers().values()) {
// Class<? extends Event> eventClass = eventReplacer.getEventClass();
// Plugin plugin = replacer.getPlugin();
//
// EventExecutor executor = (listener, event) -> eventReplacer.execute(this, event);
//
// Listener listener = new Listener() {};
//
// PluginManager pluginManager = Bukkit.getPluginManager();
// pluginManager.registerEvent(eventClass, listener, HIGHEST, executor, plugin, true);
// }
// }
//
// public void unregister(String variable) {
// replacers.remove(variable);
// }
//
// public void unregisterAll(Plugin disablePlugin) {
// Iterator<Replacer> iterator = replacers.values().iterator();
// while (iterator.hasNext()) {
// Plugin plugin = iterator.next().getPlugin();
// if (plugin == disablePlugin) {
// iterator.remove();
// }
// }
// }
//
// public void forceUpdate(String variable, int score) {
// Bukkit.getOnlinePlayers().forEach(player -> forceUpdate(player, variable, score));
// }
//
// public void forceUpdate(String variable, String value) {
// Bukkit.getOnlinePlayers().forEach(player -> forceUpdate(player, variable, value));
// }
//
// public abstract void forceUpdate(Player player, String variable, int score);
//
// public abstract void forceUpdate(Player player, String variable, String value);
//
// public Optional<String> replace(Player player, String variable, boolean complete) throws ReplacerException {
// Replacer replacer = getReplacer(variable);
// if (!complete && replacer.isGlobal() || replacer.isEventVariable() || replacer.isConstant()) {
// return Optional.empty();
// }
//
// try {
// return Optional.of(replacer.replace(player));
// } catch (Exception ex) {
// throw new ReplacerException(ex);
// }
// }
//
// public OptionalInt scoreReplace(Player player, String variable, boolean complete) throws ReplacerException {
// Replacer replacer = getReplacer(variable);
// if (!complete && replacer.isGlobal() || replacer.isEventVariable() || replacer.isConstant()) {
// return OptionalInt.empty();
// }
//
// try {
// return OptionalInt.of(replacer.scoreReplace(player));
// } catch (Exception ex) {
// throw new ReplacerException(ex);
// }
// }
//
// private Replacer getReplacer(String variable) throws UnknownVariableException {
// Replacer replacer = this.replacers.get(variable);
// if (replacer == null) {
// throw new UnknownVariableException(variable);
// }
//
// return replacer;
// }
// }
//
// Path: variables/src/main/java/com/github/games647/scoreboardstats/variables/UnsupportedPluginException.java
// public class UnsupportedPluginException extends ReplacerException {
//
// public UnsupportedPluginException(String pluginName, String expectedVersion, String currentVersion) {
// super(String.format("The version %s of plugin %s version isn't supported. We require at least %s",
// currentVersion, pluginName, expectedVersion));
// }
//
// public UnsupportedPluginException(String message) {
// super(message);
// }
// }
| import com.github.games647.scoreboardstats.variables.DefaultReplacer;
import com.github.games647.scoreboardstats.variables.DefaultReplacers;
import com.github.games647.scoreboardstats.variables.ReplacerAPI;
import com.github.games647.scoreboardstats.variables.UnsupportedPluginException;
import me.sirfaizdat.prison.ranks.Ranks;
import me.sirfaizdat.prison.ranks.UserInfo;
import me.sirfaizdat.prison.ranks.events.BalanceChangeEvent;
import me.sirfaizdat.prison.ranks.events.DemoteEvent;
import me.sirfaizdat.prison.ranks.events.RankupEvent;
import net.milkbowl.vault.economy.Economy;
import org.bukkit.Bukkit;
import org.bukkit.entity.Player;
import org.bukkit.plugin.Plugin;
import org.bukkit.plugin.RegisteredServiceProvider; | package com.github.games647.scoreboardstats.defaults;
/**
* Replace all variables that are associated with the prison plugin
* <p>
* https://dev.bukkit.org/bukkit-plugins/mcprison/
*/
@DefaultReplacer(plugin = "Prison")
public class McPrisonVariables extends DefaultReplacers<Plugin> {
private final Economy eco;
| // Path: variables/src/main/java/com/github/games647/scoreboardstats/variables/DefaultReplacers.java
// public abstract class DefaultReplacers<T extends Plugin> {
//
// protected final ReplacerAPI replaceManager;
// protected final T plugin;
//
// public DefaultReplacers(ReplacerAPI replaceManager, T plugin) {
// this.replaceManager = replaceManager;
// this.plugin = plugin;
// }
//
// /**
// * Register all variables that this class can manage
// */
// public abstract void register();
//
// /**
// * Shortcut method to register the variables without the boilerplate of adding the plugin instance and registering
// * it to the manager.
// *
// * @param variable variable name like "online"
// * @return the replacer responsible for this single variable
// */
// protected Replacer register(String variable) {
// Replacer replacer = new Replacer(plugin, variable);
// replaceManager.register(replacer);
// return replacer;
// }
// }
//
// Path: variables/src/main/java/com/github/games647/scoreboardstats/variables/ReplacerAPI.java
// public abstract class ReplacerAPI {
//
// protected final Logger logger;
// protected final Map<String, Replacer> replacers = Maps.newHashMap();
//
// public ReplacerAPI(Logger logger) {
// this.logger = logger;
// }
//
// public void register(Replacer replacer) {
// replacers.put(replacer.getVariable(), replacer);
//
// for (EventReplacer<? extends Event> eventReplacer : replacer.getEventsReplacers().values()) {
// Class<? extends Event> eventClass = eventReplacer.getEventClass();
// Plugin plugin = replacer.getPlugin();
//
// EventExecutor executor = (listener, event) -> eventReplacer.execute(this, event);
//
// Listener listener = new Listener() {};
//
// PluginManager pluginManager = Bukkit.getPluginManager();
// pluginManager.registerEvent(eventClass, listener, HIGHEST, executor, plugin, true);
// }
// }
//
// public void unregister(String variable) {
// replacers.remove(variable);
// }
//
// public void unregisterAll(Plugin disablePlugin) {
// Iterator<Replacer> iterator = replacers.values().iterator();
// while (iterator.hasNext()) {
// Plugin plugin = iterator.next().getPlugin();
// if (plugin == disablePlugin) {
// iterator.remove();
// }
// }
// }
//
// public void forceUpdate(String variable, int score) {
// Bukkit.getOnlinePlayers().forEach(player -> forceUpdate(player, variable, score));
// }
//
// public void forceUpdate(String variable, String value) {
// Bukkit.getOnlinePlayers().forEach(player -> forceUpdate(player, variable, value));
// }
//
// public abstract void forceUpdate(Player player, String variable, int score);
//
// public abstract void forceUpdate(Player player, String variable, String value);
//
// public Optional<String> replace(Player player, String variable, boolean complete) throws ReplacerException {
// Replacer replacer = getReplacer(variable);
// if (!complete && replacer.isGlobal() || replacer.isEventVariable() || replacer.isConstant()) {
// return Optional.empty();
// }
//
// try {
// return Optional.of(replacer.replace(player));
// } catch (Exception ex) {
// throw new ReplacerException(ex);
// }
// }
//
// public OptionalInt scoreReplace(Player player, String variable, boolean complete) throws ReplacerException {
// Replacer replacer = getReplacer(variable);
// if (!complete && replacer.isGlobal() || replacer.isEventVariable() || replacer.isConstant()) {
// return OptionalInt.empty();
// }
//
// try {
// return OptionalInt.of(replacer.scoreReplace(player));
// } catch (Exception ex) {
// throw new ReplacerException(ex);
// }
// }
//
// private Replacer getReplacer(String variable) throws UnknownVariableException {
// Replacer replacer = this.replacers.get(variable);
// if (replacer == null) {
// throw new UnknownVariableException(variable);
// }
//
// return replacer;
// }
// }
//
// Path: variables/src/main/java/com/github/games647/scoreboardstats/variables/UnsupportedPluginException.java
// public class UnsupportedPluginException extends ReplacerException {
//
// public UnsupportedPluginException(String pluginName, String expectedVersion, String currentVersion) {
// super(String.format("The version %s of plugin %s version isn't supported. We require at least %s",
// currentVersion, pluginName, expectedVersion));
// }
//
// public UnsupportedPluginException(String message) {
// super(message);
// }
// }
// Path: defaults/src/main/java/com/github/games647/scoreboardstats/defaults/McPrisonVariables.java
import com.github.games647.scoreboardstats.variables.DefaultReplacer;
import com.github.games647.scoreboardstats.variables.DefaultReplacers;
import com.github.games647.scoreboardstats.variables.ReplacerAPI;
import com.github.games647.scoreboardstats.variables.UnsupportedPluginException;
import me.sirfaizdat.prison.ranks.Ranks;
import me.sirfaizdat.prison.ranks.UserInfo;
import me.sirfaizdat.prison.ranks.events.BalanceChangeEvent;
import me.sirfaizdat.prison.ranks.events.DemoteEvent;
import me.sirfaizdat.prison.ranks.events.RankupEvent;
import net.milkbowl.vault.economy.Economy;
import org.bukkit.Bukkit;
import org.bukkit.entity.Player;
import org.bukkit.plugin.Plugin;
import org.bukkit.plugin.RegisteredServiceProvider;
package com.github.games647.scoreboardstats.defaults;
/**
* Replace all variables that are associated with the prison plugin
* <p>
* https://dev.bukkit.org/bukkit-plugins/mcprison/
*/
@DefaultReplacer(plugin = "Prison")
public class McPrisonVariables extends DefaultReplacers<Plugin> {
private final Economy eco;
| public McPrisonVariables(ReplacerAPI replaceManager, Plugin plugin) throws UnsupportedPluginException { |
games647/ScoreboardStats | defaults/src/main/java/com/github/games647/scoreboardstats/defaults/HeroesVariables.java | // Path: variables/src/main/java/com/github/games647/scoreboardstats/variables/DefaultReplacers.java
// public abstract class DefaultReplacers<T extends Plugin> {
//
// protected final ReplacerAPI replaceManager;
// protected final T plugin;
//
// public DefaultReplacers(ReplacerAPI replaceManager, T plugin) {
// this.replaceManager = replaceManager;
// this.plugin = plugin;
// }
//
// /**
// * Register all variables that this class can manage
// */
// public abstract void register();
//
// /**
// * Shortcut method to register the variables without the boilerplate of adding the plugin instance and registering
// * it to the manager.
// *
// * @param variable variable name like "online"
// * @return the replacer responsible for this single variable
// */
// protected Replacer register(String variable) {
// Replacer replacer = new Replacer(plugin, variable);
// replaceManager.register(replacer);
// return replacer;
// }
// }
//
// Path: variables/src/main/java/com/github/games647/scoreboardstats/variables/ReplacerAPI.java
// public abstract class ReplacerAPI {
//
// protected final Logger logger;
// protected final Map<String, Replacer> replacers = Maps.newHashMap();
//
// public ReplacerAPI(Logger logger) {
// this.logger = logger;
// }
//
// public void register(Replacer replacer) {
// replacers.put(replacer.getVariable(), replacer);
//
// for (EventReplacer<? extends Event> eventReplacer : replacer.getEventsReplacers().values()) {
// Class<? extends Event> eventClass = eventReplacer.getEventClass();
// Plugin plugin = replacer.getPlugin();
//
// EventExecutor executor = (listener, event) -> eventReplacer.execute(this, event);
//
// Listener listener = new Listener() {};
//
// PluginManager pluginManager = Bukkit.getPluginManager();
// pluginManager.registerEvent(eventClass, listener, HIGHEST, executor, plugin, true);
// }
// }
//
// public void unregister(String variable) {
// replacers.remove(variable);
// }
//
// public void unregisterAll(Plugin disablePlugin) {
// Iterator<Replacer> iterator = replacers.values().iterator();
// while (iterator.hasNext()) {
// Plugin plugin = iterator.next().getPlugin();
// if (plugin == disablePlugin) {
// iterator.remove();
// }
// }
// }
//
// public void forceUpdate(String variable, int score) {
// Bukkit.getOnlinePlayers().forEach(player -> forceUpdate(player, variable, score));
// }
//
// public void forceUpdate(String variable, String value) {
// Bukkit.getOnlinePlayers().forEach(player -> forceUpdate(player, variable, value));
// }
//
// public abstract void forceUpdate(Player player, String variable, int score);
//
// public abstract void forceUpdate(Player player, String variable, String value);
//
// public Optional<String> replace(Player player, String variable, boolean complete) throws ReplacerException {
// Replacer replacer = getReplacer(variable);
// if (!complete && replacer.isGlobal() || replacer.isEventVariable() || replacer.isConstant()) {
// return Optional.empty();
// }
//
// try {
// return Optional.of(replacer.replace(player));
// } catch (Exception ex) {
// throw new ReplacerException(ex);
// }
// }
//
// public OptionalInt scoreReplace(Player player, String variable, boolean complete) throws ReplacerException {
// Replacer replacer = getReplacer(variable);
// if (!complete && replacer.isGlobal() || replacer.isEventVariable() || replacer.isConstant()) {
// return OptionalInt.empty();
// }
//
// try {
// return OptionalInt.of(replacer.scoreReplace(player));
// } catch (Exception ex) {
// throw new ReplacerException(ex);
// }
// }
//
// private Replacer getReplacer(String variable) throws UnknownVariableException {
// Replacer replacer = this.replacers.get(variable);
// if (replacer == null) {
// throw new UnknownVariableException(variable);
// }
//
// return replacer;
// }
// }
| import com.github.games647.scoreboardstats.variables.DefaultReplacer;
import com.github.games647.scoreboardstats.variables.DefaultReplacers;
import com.github.games647.scoreboardstats.variables.ReplacerAPI;
import com.herocraftonline.heroes.Heroes;
import com.herocraftonline.heroes.api.events.ClassChangeEvent;
import com.herocraftonline.heroes.api.events.HeroChangeLevelEvent;
import com.herocraftonline.heroes.api.events.HeroRegainManaEvent;
import com.herocraftonline.heroes.api.events.SkillUseEvent;
import com.herocraftonline.heroes.characters.CharacterManager;
import com.herocraftonline.heroes.characters.Hero;
import org.bukkit.entity.Player; | package com.github.games647.scoreboardstats.defaults;
/**
* Replace all variables that are associated with the heroes plugin
* <p>
* https://dev.bukkit.org/bukkit-plugins/heroes/
*/
@DefaultReplacer(plugin = "Heroes")
public class HeroesVariables extends DefaultReplacers<Heroes> {
private final CharacterManager characterManager;
| // Path: variables/src/main/java/com/github/games647/scoreboardstats/variables/DefaultReplacers.java
// public abstract class DefaultReplacers<T extends Plugin> {
//
// protected final ReplacerAPI replaceManager;
// protected final T plugin;
//
// public DefaultReplacers(ReplacerAPI replaceManager, T plugin) {
// this.replaceManager = replaceManager;
// this.plugin = plugin;
// }
//
// /**
// * Register all variables that this class can manage
// */
// public abstract void register();
//
// /**
// * Shortcut method to register the variables without the boilerplate of adding the plugin instance and registering
// * it to the manager.
// *
// * @param variable variable name like "online"
// * @return the replacer responsible for this single variable
// */
// protected Replacer register(String variable) {
// Replacer replacer = new Replacer(plugin, variable);
// replaceManager.register(replacer);
// return replacer;
// }
// }
//
// Path: variables/src/main/java/com/github/games647/scoreboardstats/variables/ReplacerAPI.java
// public abstract class ReplacerAPI {
//
// protected final Logger logger;
// protected final Map<String, Replacer> replacers = Maps.newHashMap();
//
// public ReplacerAPI(Logger logger) {
// this.logger = logger;
// }
//
// public void register(Replacer replacer) {
// replacers.put(replacer.getVariable(), replacer);
//
// for (EventReplacer<? extends Event> eventReplacer : replacer.getEventsReplacers().values()) {
// Class<? extends Event> eventClass = eventReplacer.getEventClass();
// Plugin plugin = replacer.getPlugin();
//
// EventExecutor executor = (listener, event) -> eventReplacer.execute(this, event);
//
// Listener listener = new Listener() {};
//
// PluginManager pluginManager = Bukkit.getPluginManager();
// pluginManager.registerEvent(eventClass, listener, HIGHEST, executor, plugin, true);
// }
// }
//
// public void unregister(String variable) {
// replacers.remove(variable);
// }
//
// public void unregisterAll(Plugin disablePlugin) {
// Iterator<Replacer> iterator = replacers.values().iterator();
// while (iterator.hasNext()) {
// Plugin plugin = iterator.next().getPlugin();
// if (plugin == disablePlugin) {
// iterator.remove();
// }
// }
// }
//
// public void forceUpdate(String variable, int score) {
// Bukkit.getOnlinePlayers().forEach(player -> forceUpdate(player, variable, score));
// }
//
// public void forceUpdate(String variable, String value) {
// Bukkit.getOnlinePlayers().forEach(player -> forceUpdate(player, variable, value));
// }
//
// public abstract void forceUpdate(Player player, String variable, int score);
//
// public abstract void forceUpdate(Player player, String variable, String value);
//
// public Optional<String> replace(Player player, String variable, boolean complete) throws ReplacerException {
// Replacer replacer = getReplacer(variable);
// if (!complete && replacer.isGlobal() || replacer.isEventVariable() || replacer.isConstant()) {
// return Optional.empty();
// }
//
// try {
// return Optional.of(replacer.replace(player));
// } catch (Exception ex) {
// throw new ReplacerException(ex);
// }
// }
//
// public OptionalInt scoreReplace(Player player, String variable, boolean complete) throws ReplacerException {
// Replacer replacer = getReplacer(variable);
// if (!complete && replacer.isGlobal() || replacer.isEventVariable() || replacer.isConstant()) {
// return OptionalInt.empty();
// }
//
// try {
// return OptionalInt.of(replacer.scoreReplace(player));
// } catch (Exception ex) {
// throw new ReplacerException(ex);
// }
// }
//
// private Replacer getReplacer(String variable) throws UnknownVariableException {
// Replacer replacer = this.replacers.get(variable);
// if (replacer == null) {
// throw new UnknownVariableException(variable);
// }
//
// return replacer;
// }
// }
// Path: defaults/src/main/java/com/github/games647/scoreboardstats/defaults/HeroesVariables.java
import com.github.games647.scoreboardstats.variables.DefaultReplacer;
import com.github.games647.scoreboardstats.variables.DefaultReplacers;
import com.github.games647.scoreboardstats.variables.ReplacerAPI;
import com.herocraftonline.heroes.Heroes;
import com.herocraftonline.heroes.api.events.ClassChangeEvent;
import com.herocraftonline.heroes.api.events.HeroChangeLevelEvent;
import com.herocraftonline.heroes.api.events.HeroRegainManaEvent;
import com.herocraftonline.heroes.api.events.SkillUseEvent;
import com.herocraftonline.heroes.characters.CharacterManager;
import com.herocraftonline.heroes.characters.Hero;
import org.bukkit.entity.Player;
package com.github.games647.scoreboardstats.defaults;
/**
* Replace all variables that are associated with the heroes plugin
* <p>
* https://dev.bukkit.org/bukkit-plugins/heroes/
*/
@DefaultReplacer(plugin = "Heroes")
public class HeroesVariables extends DefaultReplacers<Heroes> {
private final CharacterManager characterManager;
| public HeroesVariables(ReplacerAPI replaceManager, Heroes plugin) { |
games647/ScoreboardStats | defaults/src/main/java/com/github/games647/scoreboardstats/defaults/SimpleClansVariables.java | // Path: variables/src/main/java/com/github/games647/scoreboardstats/variables/DefaultReplacers.java
// public abstract class DefaultReplacers<T extends Plugin> {
//
// protected final ReplacerAPI replaceManager;
// protected final T plugin;
//
// public DefaultReplacers(ReplacerAPI replaceManager, T plugin) {
// this.replaceManager = replaceManager;
// this.plugin = plugin;
// }
//
// /**
// * Register all variables that this class can manage
// */
// public abstract void register();
//
// /**
// * Shortcut method to register the variables without the boilerplate of adding the plugin instance and registering
// * it to the manager.
// *
// * @param variable variable name like "online"
// * @return the replacer responsible for this single variable
// */
// protected Replacer register(String variable) {
// Replacer replacer = new Replacer(plugin, variable);
// replaceManager.register(replacer);
// return replacer;
// }
// }
//
// Path: variables/src/main/java/com/github/games647/scoreboardstats/variables/ReplacerAPI.java
// public abstract class ReplacerAPI {
//
// protected final Logger logger;
// protected final Map<String, Replacer> replacers = Maps.newHashMap();
//
// public ReplacerAPI(Logger logger) {
// this.logger = logger;
// }
//
// public void register(Replacer replacer) {
// replacers.put(replacer.getVariable(), replacer);
//
// for (EventReplacer<? extends Event> eventReplacer : replacer.getEventsReplacers().values()) {
// Class<? extends Event> eventClass = eventReplacer.getEventClass();
// Plugin plugin = replacer.getPlugin();
//
// EventExecutor executor = (listener, event) -> eventReplacer.execute(this, event);
//
// Listener listener = new Listener() {};
//
// PluginManager pluginManager = Bukkit.getPluginManager();
// pluginManager.registerEvent(eventClass, listener, HIGHEST, executor, plugin, true);
// }
// }
//
// public void unregister(String variable) {
// replacers.remove(variable);
// }
//
// public void unregisterAll(Plugin disablePlugin) {
// Iterator<Replacer> iterator = replacers.values().iterator();
// while (iterator.hasNext()) {
// Plugin plugin = iterator.next().getPlugin();
// if (plugin == disablePlugin) {
// iterator.remove();
// }
// }
// }
//
// public void forceUpdate(String variable, int score) {
// Bukkit.getOnlinePlayers().forEach(player -> forceUpdate(player, variable, score));
// }
//
// public void forceUpdate(String variable, String value) {
// Bukkit.getOnlinePlayers().forEach(player -> forceUpdate(player, variable, value));
// }
//
// public abstract void forceUpdate(Player player, String variable, int score);
//
// public abstract void forceUpdate(Player player, String variable, String value);
//
// public Optional<String> replace(Player player, String variable, boolean complete) throws ReplacerException {
// Replacer replacer = getReplacer(variable);
// if (!complete && replacer.isGlobal() || replacer.isEventVariable() || replacer.isConstant()) {
// return Optional.empty();
// }
//
// try {
// return Optional.of(replacer.replace(player));
// } catch (Exception ex) {
// throw new ReplacerException(ex);
// }
// }
//
// public OptionalInt scoreReplace(Player player, String variable, boolean complete) throws ReplacerException {
// Replacer replacer = getReplacer(variable);
// if (!complete && replacer.isGlobal() || replacer.isEventVariable() || replacer.isConstant()) {
// return OptionalInt.empty();
// }
//
// try {
// return OptionalInt.of(replacer.scoreReplace(player));
// } catch (Exception ex) {
// throw new ReplacerException(ex);
// }
// }
//
// private Replacer getReplacer(String variable) throws UnknownVariableException {
// Replacer replacer = this.replacers.get(variable);
// if (replacer == null) {
// throw new UnknownVariableException(variable);
// }
//
// return replacer;
// }
// }
| import com.github.games647.scoreboardstats.variables.DefaultReplacer;
import com.github.games647.scoreboardstats.variables.DefaultReplacers;
import com.github.games647.scoreboardstats.variables.ReplacerAPI;
import java.util.Collection;
import java.util.Optional;
import net.sacredlabyrinth.phaed.simpleclans.Clan;
import net.sacredlabyrinth.phaed.simpleclans.ClanPlayer;
import net.sacredlabyrinth.phaed.simpleclans.SimpleClans;
import net.sacredlabyrinth.phaed.simpleclans.managers.ClanManager;
import org.bukkit.entity.Player;
import org.bukkit.util.NumberConversions; | package com.github.games647.scoreboardstats.defaults;
/**
* Replace all variables that are associated with the SimpleClans plugin
* <p>
* https://dev.bukkit.org/bukkit-plugins/simpleclans/
*
* @see SimpleClans
* @see ClanPlayer
* @see Clan
* @see ClanManager
*/
@DefaultReplacer(plugin = "SimpleClans")
public class SimpleClansVariables extends DefaultReplacers<SimpleClans> {
private final ClanManager clanManager;
| // Path: variables/src/main/java/com/github/games647/scoreboardstats/variables/DefaultReplacers.java
// public abstract class DefaultReplacers<T extends Plugin> {
//
// protected final ReplacerAPI replaceManager;
// protected final T plugin;
//
// public DefaultReplacers(ReplacerAPI replaceManager, T plugin) {
// this.replaceManager = replaceManager;
// this.plugin = plugin;
// }
//
// /**
// * Register all variables that this class can manage
// */
// public abstract void register();
//
// /**
// * Shortcut method to register the variables without the boilerplate of adding the plugin instance and registering
// * it to the manager.
// *
// * @param variable variable name like "online"
// * @return the replacer responsible for this single variable
// */
// protected Replacer register(String variable) {
// Replacer replacer = new Replacer(plugin, variable);
// replaceManager.register(replacer);
// return replacer;
// }
// }
//
// Path: variables/src/main/java/com/github/games647/scoreboardstats/variables/ReplacerAPI.java
// public abstract class ReplacerAPI {
//
// protected final Logger logger;
// protected final Map<String, Replacer> replacers = Maps.newHashMap();
//
// public ReplacerAPI(Logger logger) {
// this.logger = logger;
// }
//
// public void register(Replacer replacer) {
// replacers.put(replacer.getVariable(), replacer);
//
// for (EventReplacer<? extends Event> eventReplacer : replacer.getEventsReplacers().values()) {
// Class<? extends Event> eventClass = eventReplacer.getEventClass();
// Plugin plugin = replacer.getPlugin();
//
// EventExecutor executor = (listener, event) -> eventReplacer.execute(this, event);
//
// Listener listener = new Listener() {};
//
// PluginManager pluginManager = Bukkit.getPluginManager();
// pluginManager.registerEvent(eventClass, listener, HIGHEST, executor, plugin, true);
// }
// }
//
// public void unregister(String variable) {
// replacers.remove(variable);
// }
//
// public void unregisterAll(Plugin disablePlugin) {
// Iterator<Replacer> iterator = replacers.values().iterator();
// while (iterator.hasNext()) {
// Plugin plugin = iterator.next().getPlugin();
// if (plugin == disablePlugin) {
// iterator.remove();
// }
// }
// }
//
// public void forceUpdate(String variable, int score) {
// Bukkit.getOnlinePlayers().forEach(player -> forceUpdate(player, variable, score));
// }
//
// public void forceUpdate(String variable, String value) {
// Bukkit.getOnlinePlayers().forEach(player -> forceUpdate(player, variable, value));
// }
//
// public abstract void forceUpdate(Player player, String variable, int score);
//
// public abstract void forceUpdate(Player player, String variable, String value);
//
// public Optional<String> replace(Player player, String variable, boolean complete) throws ReplacerException {
// Replacer replacer = getReplacer(variable);
// if (!complete && replacer.isGlobal() || replacer.isEventVariable() || replacer.isConstant()) {
// return Optional.empty();
// }
//
// try {
// return Optional.of(replacer.replace(player));
// } catch (Exception ex) {
// throw new ReplacerException(ex);
// }
// }
//
// public OptionalInt scoreReplace(Player player, String variable, boolean complete) throws ReplacerException {
// Replacer replacer = getReplacer(variable);
// if (!complete && replacer.isGlobal() || replacer.isEventVariable() || replacer.isConstant()) {
// return OptionalInt.empty();
// }
//
// try {
// return OptionalInt.of(replacer.scoreReplace(player));
// } catch (Exception ex) {
// throw new ReplacerException(ex);
// }
// }
//
// private Replacer getReplacer(String variable) throws UnknownVariableException {
// Replacer replacer = this.replacers.get(variable);
// if (replacer == null) {
// throw new UnknownVariableException(variable);
// }
//
// return replacer;
// }
// }
// Path: defaults/src/main/java/com/github/games647/scoreboardstats/defaults/SimpleClansVariables.java
import com.github.games647.scoreboardstats.variables.DefaultReplacer;
import com.github.games647.scoreboardstats.variables.DefaultReplacers;
import com.github.games647.scoreboardstats.variables.ReplacerAPI;
import java.util.Collection;
import java.util.Optional;
import net.sacredlabyrinth.phaed.simpleclans.Clan;
import net.sacredlabyrinth.phaed.simpleclans.ClanPlayer;
import net.sacredlabyrinth.phaed.simpleclans.SimpleClans;
import net.sacredlabyrinth.phaed.simpleclans.managers.ClanManager;
import org.bukkit.entity.Player;
import org.bukkit.util.NumberConversions;
package com.github.games647.scoreboardstats.defaults;
/**
* Replace all variables that are associated with the SimpleClans plugin
* <p>
* https://dev.bukkit.org/bukkit-plugins/simpleclans/
*
* @see SimpleClans
* @see ClanPlayer
* @see Clan
* @see ClanManager
*/
@DefaultReplacer(plugin = "SimpleClans")
public class SimpleClansVariables extends DefaultReplacers<SimpleClans> {
private final ClanManager clanManager;
| public SimpleClansVariables(ReplacerAPI replaceManager, SimpleClans plugin) { |
games647/ScoreboardStats | defaults/src/main/java/com/github/games647/scoreboardstats/defaults/MyPetVariables.java | // Path: variables/src/main/java/com/github/games647/scoreboardstats/variables/DefaultReplacers.java
// public abstract class DefaultReplacers<T extends Plugin> {
//
// protected final ReplacerAPI replaceManager;
// protected final T plugin;
//
// public DefaultReplacers(ReplacerAPI replaceManager, T plugin) {
// this.replaceManager = replaceManager;
// this.plugin = plugin;
// }
//
// /**
// * Register all variables that this class can manage
// */
// public abstract void register();
//
// /**
// * Shortcut method to register the variables without the boilerplate of adding the plugin instance and registering
// * it to the manager.
// *
// * @param variable variable name like "online"
// * @return the replacer responsible for this single variable
// */
// protected Replacer register(String variable) {
// Replacer replacer = new Replacer(plugin, variable);
// replaceManager.register(replacer);
// return replacer;
// }
// }
//
// Path: variables/src/main/java/com/github/games647/scoreboardstats/variables/ReplacerAPI.java
// public abstract class ReplacerAPI {
//
// protected final Logger logger;
// protected final Map<String, Replacer> replacers = Maps.newHashMap();
//
// public ReplacerAPI(Logger logger) {
// this.logger = logger;
// }
//
// public void register(Replacer replacer) {
// replacers.put(replacer.getVariable(), replacer);
//
// for (EventReplacer<? extends Event> eventReplacer : replacer.getEventsReplacers().values()) {
// Class<? extends Event> eventClass = eventReplacer.getEventClass();
// Plugin plugin = replacer.getPlugin();
//
// EventExecutor executor = (listener, event) -> eventReplacer.execute(this, event);
//
// Listener listener = new Listener() {};
//
// PluginManager pluginManager = Bukkit.getPluginManager();
// pluginManager.registerEvent(eventClass, listener, HIGHEST, executor, plugin, true);
// }
// }
//
// public void unregister(String variable) {
// replacers.remove(variable);
// }
//
// public void unregisterAll(Plugin disablePlugin) {
// Iterator<Replacer> iterator = replacers.values().iterator();
// while (iterator.hasNext()) {
// Plugin plugin = iterator.next().getPlugin();
// if (plugin == disablePlugin) {
// iterator.remove();
// }
// }
// }
//
// public void forceUpdate(String variable, int score) {
// Bukkit.getOnlinePlayers().forEach(player -> forceUpdate(player, variable, score));
// }
//
// public void forceUpdate(String variable, String value) {
// Bukkit.getOnlinePlayers().forEach(player -> forceUpdate(player, variable, value));
// }
//
// public abstract void forceUpdate(Player player, String variable, int score);
//
// public abstract void forceUpdate(Player player, String variable, String value);
//
// public Optional<String> replace(Player player, String variable, boolean complete) throws ReplacerException {
// Replacer replacer = getReplacer(variable);
// if (!complete && replacer.isGlobal() || replacer.isEventVariable() || replacer.isConstant()) {
// return Optional.empty();
// }
//
// try {
// return Optional.of(replacer.replace(player));
// } catch (Exception ex) {
// throw new ReplacerException(ex);
// }
// }
//
// public OptionalInt scoreReplace(Player player, String variable, boolean complete) throws ReplacerException {
// Replacer replacer = getReplacer(variable);
// if (!complete && replacer.isGlobal() || replacer.isEventVariable() || replacer.isConstant()) {
// return OptionalInt.empty();
// }
//
// try {
// return OptionalInt.of(replacer.scoreReplace(player));
// } catch (Exception ex) {
// throw new ReplacerException(ex);
// }
// }
//
// private Replacer getReplacer(String variable) throws UnknownVariableException {
// Replacer replacer = this.replacers.get(variable);
// if (replacer == null) {
// throw new UnknownVariableException(variable);
// }
//
// return replacer;
// }
// }
| import com.github.games647.scoreboardstats.variables.DefaultReplacer;
import com.github.games647.scoreboardstats.variables.DefaultReplacers;
import com.github.games647.scoreboardstats.variables.ReplacerAPI;
import de.Keyle.MyPet.MyPetApi;
import de.Keyle.MyPet.api.event.MyPetLevelUpEvent;
import de.Keyle.MyPet.api.player.MyPetPlayer;
import org.bukkit.plugin.Plugin; | package com.github.games647.scoreboardstats.defaults;
@DefaultReplacer(plugin = "MyPet")
public class MyPetVariables extends DefaultReplacers<Plugin> {
| // Path: variables/src/main/java/com/github/games647/scoreboardstats/variables/DefaultReplacers.java
// public abstract class DefaultReplacers<T extends Plugin> {
//
// protected final ReplacerAPI replaceManager;
// protected final T plugin;
//
// public DefaultReplacers(ReplacerAPI replaceManager, T plugin) {
// this.replaceManager = replaceManager;
// this.plugin = plugin;
// }
//
// /**
// * Register all variables that this class can manage
// */
// public abstract void register();
//
// /**
// * Shortcut method to register the variables without the boilerplate of adding the plugin instance and registering
// * it to the manager.
// *
// * @param variable variable name like "online"
// * @return the replacer responsible for this single variable
// */
// protected Replacer register(String variable) {
// Replacer replacer = new Replacer(plugin, variable);
// replaceManager.register(replacer);
// return replacer;
// }
// }
//
// Path: variables/src/main/java/com/github/games647/scoreboardstats/variables/ReplacerAPI.java
// public abstract class ReplacerAPI {
//
// protected final Logger logger;
// protected final Map<String, Replacer> replacers = Maps.newHashMap();
//
// public ReplacerAPI(Logger logger) {
// this.logger = logger;
// }
//
// public void register(Replacer replacer) {
// replacers.put(replacer.getVariable(), replacer);
//
// for (EventReplacer<? extends Event> eventReplacer : replacer.getEventsReplacers().values()) {
// Class<? extends Event> eventClass = eventReplacer.getEventClass();
// Plugin plugin = replacer.getPlugin();
//
// EventExecutor executor = (listener, event) -> eventReplacer.execute(this, event);
//
// Listener listener = new Listener() {};
//
// PluginManager pluginManager = Bukkit.getPluginManager();
// pluginManager.registerEvent(eventClass, listener, HIGHEST, executor, plugin, true);
// }
// }
//
// public void unregister(String variable) {
// replacers.remove(variable);
// }
//
// public void unregisterAll(Plugin disablePlugin) {
// Iterator<Replacer> iterator = replacers.values().iterator();
// while (iterator.hasNext()) {
// Plugin plugin = iterator.next().getPlugin();
// if (plugin == disablePlugin) {
// iterator.remove();
// }
// }
// }
//
// public void forceUpdate(String variable, int score) {
// Bukkit.getOnlinePlayers().forEach(player -> forceUpdate(player, variable, score));
// }
//
// public void forceUpdate(String variable, String value) {
// Bukkit.getOnlinePlayers().forEach(player -> forceUpdate(player, variable, value));
// }
//
// public abstract void forceUpdate(Player player, String variable, int score);
//
// public abstract void forceUpdate(Player player, String variable, String value);
//
// public Optional<String> replace(Player player, String variable, boolean complete) throws ReplacerException {
// Replacer replacer = getReplacer(variable);
// if (!complete && replacer.isGlobal() || replacer.isEventVariable() || replacer.isConstant()) {
// return Optional.empty();
// }
//
// try {
// return Optional.of(replacer.replace(player));
// } catch (Exception ex) {
// throw new ReplacerException(ex);
// }
// }
//
// public OptionalInt scoreReplace(Player player, String variable, boolean complete) throws ReplacerException {
// Replacer replacer = getReplacer(variable);
// if (!complete && replacer.isGlobal() || replacer.isEventVariable() || replacer.isConstant()) {
// return OptionalInt.empty();
// }
//
// try {
// return OptionalInt.of(replacer.scoreReplace(player));
// } catch (Exception ex) {
// throw new ReplacerException(ex);
// }
// }
//
// private Replacer getReplacer(String variable) throws UnknownVariableException {
// Replacer replacer = this.replacers.get(variable);
// if (replacer == null) {
// throw new UnknownVariableException(variable);
// }
//
// return replacer;
// }
// }
// Path: defaults/src/main/java/com/github/games647/scoreboardstats/defaults/MyPetVariables.java
import com.github.games647.scoreboardstats.variables.DefaultReplacer;
import com.github.games647.scoreboardstats.variables.DefaultReplacers;
import com.github.games647.scoreboardstats.variables.ReplacerAPI;
import de.Keyle.MyPet.MyPetApi;
import de.Keyle.MyPet.api.event.MyPetLevelUpEvent;
import de.Keyle.MyPet.api.player.MyPetPlayer;
import org.bukkit.plugin.Plugin;
package com.github.games647.scoreboardstats.defaults;
@DefaultReplacer(plugin = "MyPet")
public class MyPetVariables extends DefaultReplacers<Plugin> {
| public MyPetVariables(ReplacerAPI replaceManager, Plugin plugin) { |
games647/ScoreboardStats | defaults/src/main/java/com/github/games647/scoreboardstats/defaults/McmmoVariables.java | // Path: variables/src/main/java/com/github/games647/scoreboardstats/variables/DefaultReplacers.java
// public abstract class DefaultReplacers<T extends Plugin> {
//
// protected final ReplacerAPI replaceManager;
// protected final T plugin;
//
// public DefaultReplacers(ReplacerAPI replaceManager, T plugin) {
// this.replaceManager = replaceManager;
// this.plugin = plugin;
// }
//
// /**
// * Register all variables that this class can manage
// */
// public abstract void register();
//
// /**
// * Shortcut method to register the variables without the boilerplate of adding the plugin instance and registering
// * it to the manager.
// *
// * @param variable variable name like "online"
// * @return the replacer responsible for this single variable
// */
// protected Replacer register(String variable) {
// Replacer replacer = new Replacer(plugin, variable);
// replaceManager.register(replacer);
// return replacer;
// }
// }
//
// Path: variables/src/main/java/com/github/games647/scoreboardstats/variables/ReplacerAPI.java
// public abstract class ReplacerAPI {
//
// protected final Logger logger;
// protected final Map<String, Replacer> replacers = Maps.newHashMap();
//
// public ReplacerAPI(Logger logger) {
// this.logger = logger;
// }
//
// public void register(Replacer replacer) {
// replacers.put(replacer.getVariable(), replacer);
//
// for (EventReplacer<? extends Event> eventReplacer : replacer.getEventsReplacers().values()) {
// Class<? extends Event> eventClass = eventReplacer.getEventClass();
// Plugin plugin = replacer.getPlugin();
//
// EventExecutor executor = (listener, event) -> eventReplacer.execute(this, event);
//
// Listener listener = new Listener() {};
//
// PluginManager pluginManager = Bukkit.getPluginManager();
// pluginManager.registerEvent(eventClass, listener, HIGHEST, executor, plugin, true);
// }
// }
//
// public void unregister(String variable) {
// replacers.remove(variable);
// }
//
// public void unregisterAll(Plugin disablePlugin) {
// Iterator<Replacer> iterator = replacers.values().iterator();
// while (iterator.hasNext()) {
// Plugin plugin = iterator.next().getPlugin();
// if (plugin == disablePlugin) {
// iterator.remove();
// }
// }
// }
//
// public void forceUpdate(String variable, int score) {
// Bukkit.getOnlinePlayers().forEach(player -> forceUpdate(player, variable, score));
// }
//
// public void forceUpdate(String variable, String value) {
// Bukkit.getOnlinePlayers().forEach(player -> forceUpdate(player, variable, value));
// }
//
// public abstract void forceUpdate(Player player, String variable, int score);
//
// public abstract void forceUpdate(Player player, String variable, String value);
//
// public Optional<String> replace(Player player, String variable, boolean complete) throws ReplacerException {
// Replacer replacer = getReplacer(variable);
// if (!complete && replacer.isGlobal() || replacer.isEventVariable() || replacer.isConstant()) {
// return Optional.empty();
// }
//
// try {
// return Optional.of(replacer.replace(player));
// } catch (Exception ex) {
// throw new ReplacerException(ex);
// }
// }
//
// public OptionalInt scoreReplace(Player player, String variable, boolean complete) throws ReplacerException {
// Replacer replacer = getReplacer(variable);
// if (!complete && replacer.isGlobal() || replacer.isEventVariable() || replacer.isConstant()) {
// return OptionalInt.empty();
// }
//
// try {
// return OptionalInt.of(replacer.scoreReplace(player));
// } catch (Exception ex) {
// throw new ReplacerException(ex);
// }
// }
//
// private Replacer getReplacer(String variable) throws UnknownVariableException {
// Replacer replacer = this.replacers.get(variable);
// if (replacer == null) {
// throw new UnknownVariableException(variable);
// }
//
// return replacer;
// }
// }
| import com.github.games647.scoreboardstats.variables.DefaultReplacer;
import com.github.games647.scoreboardstats.variables.DefaultReplacers;
import com.github.games647.scoreboardstats.variables.ReplacerAPI;
import com.gmail.nossr50.api.ExperienceAPI;
import com.gmail.nossr50.datatypes.skills.SkillType;
import com.gmail.nossr50.events.experience.McMMOPlayerLevelChangeEvent;
import com.gmail.nossr50.events.experience.McMMOPlayerLevelDownEvent;
import com.gmail.nossr50.events.experience.McMMOPlayerLevelUpEvent;
import java.util.stream.Stream;
import org.bukkit.plugin.Plugin; | package com.github.games647.scoreboardstats.defaults;
/**
* Replace all variables that are associated with the mcMMO plugin
* <p>
* https://dev.bukkit.org/bukkit-plugins/mcmmo/
*/
@DefaultReplacer(plugin = "mcMMO")
public class McmmoVariables extends DefaultReplacers<Plugin> {
| // Path: variables/src/main/java/com/github/games647/scoreboardstats/variables/DefaultReplacers.java
// public abstract class DefaultReplacers<T extends Plugin> {
//
// protected final ReplacerAPI replaceManager;
// protected final T plugin;
//
// public DefaultReplacers(ReplacerAPI replaceManager, T plugin) {
// this.replaceManager = replaceManager;
// this.plugin = plugin;
// }
//
// /**
// * Register all variables that this class can manage
// */
// public abstract void register();
//
// /**
// * Shortcut method to register the variables without the boilerplate of adding the plugin instance and registering
// * it to the manager.
// *
// * @param variable variable name like "online"
// * @return the replacer responsible for this single variable
// */
// protected Replacer register(String variable) {
// Replacer replacer = new Replacer(plugin, variable);
// replaceManager.register(replacer);
// return replacer;
// }
// }
//
// Path: variables/src/main/java/com/github/games647/scoreboardstats/variables/ReplacerAPI.java
// public abstract class ReplacerAPI {
//
// protected final Logger logger;
// protected final Map<String, Replacer> replacers = Maps.newHashMap();
//
// public ReplacerAPI(Logger logger) {
// this.logger = logger;
// }
//
// public void register(Replacer replacer) {
// replacers.put(replacer.getVariable(), replacer);
//
// for (EventReplacer<? extends Event> eventReplacer : replacer.getEventsReplacers().values()) {
// Class<? extends Event> eventClass = eventReplacer.getEventClass();
// Plugin plugin = replacer.getPlugin();
//
// EventExecutor executor = (listener, event) -> eventReplacer.execute(this, event);
//
// Listener listener = new Listener() {};
//
// PluginManager pluginManager = Bukkit.getPluginManager();
// pluginManager.registerEvent(eventClass, listener, HIGHEST, executor, plugin, true);
// }
// }
//
// public void unregister(String variable) {
// replacers.remove(variable);
// }
//
// public void unregisterAll(Plugin disablePlugin) {
// Iterator<Replacer> iterator = replacers.values().iterator();
// while (iterator.hasNext()) {
// Plugin plugin = iterator.next().getPlugin();
// if (plugin == disablePlugin) {
// iterator.remove();
// }
// }
// }
//
// public void forceUpdate(String variable, int score) {
// Bukkit.getOnlinePlayers().forEach(player -> forceUpdate(player, variable, score));
// }
//
// public void forceUpdate(String variable, String value) {
// Bukkit.getOnlinePlayers().forEach(player -> forceUpdate(player, variable, value));
// }
//
// public abstract void forceUpdate(Player player, String variable, int score);
//
// public abstract void forceUpdate(Player player, String variable, String value);
//
// public Optional<String> replace(Player player, String variable, boolean complete) throws ReplacerException {
// Replacer replacer = getReplacer(variable);
// if (!complete && replacer.isGlobal() || replacer.isEventVariable() || replacer.isConstant()) {
// return Optional.empty();
// }
//
// try {
// return Optional.of(replacer.replace(player));
// } catch (Exception ex) {
// throw new ReplacerException(ex);
// }
// }
//
// public OptionalInt scoreReplace(Player player, String variable, boolean complete) throws ReplacerException {
// Replacer replacer = getReplacer(variable);
// if (!complete && replacer.isGlobal() || replacer.isEventVariable() || replacer.isConstant()) {
// return OptionalInt.empty();
// }
//
// try {
// return OptionalInt.of(replacer.scoreReplace(player));
// } catch (Exception ex) {
// throw new ReplacerException(ex);
// }
// }
//
// private Replacer getReplacer(String variable) throws UnknownVariableException {
// Replacer replacer = this.replacers.get(variable);
// if (replacer == null) {
// throw new UnknownVariableException(variable);
// }
//
// return replacer;
// }
// }
// Path: defaults/src/main/java/com/github/games647/scoreboardstats/defaults/McmmoVariables.java
import com.github.games647.scoreboardstats.variables.DefaultReplacer;
import com.github.games647.scoreboardstats.variables.DefaultReplacers;
import com.github.games647.scoreboardstats.variables.ReplacerAPI;
import com.gmail.nossr50.api.ExperienceAPI;
import com.gmail.nossr50.datatypes.skills.SkillType;
import com.gmail.nossr50.events.experience.McMMOPlayerLevelChangeEvent;
import com.gmail.nossr50.events.experience.McMMOPlayerLevelDownEvent;
import com.gmail.nossr50.events.experience.McMMOPlayerLevelUpEvent;
import java.util.stream.Stream;
import org.bukkit.plugin.Plugin;
package com.github.games647.scoreboardstats.defaults;
/**
* Replace all variables that are associated with the mcMMO plugin
* <p>
* https://dev.bukkit.org/bukkit-plugins/mcmmo/
*/
@DefaultReplacer(plugin = "mcMMO")
public class McmmoVariables extends DefaultReplacers<Plugin> {
| public McmmoVariables(ReplacerAPI replaceManager, Plugin plugin) { |
games647/ScoreboardStats | defaults/src/main/java/com/github/games647/scoreboardstats/defaults/GeneralVariables.java | // Path: variables/src/main/java/com/github/games647/scoreboardstats/variables/DefaultReplacers.java
// public abstract class DefaultReplacers<T extends Plugin> {
//
// protected final ReplacerAPI replaceManager;
// protected final T plugin;
//
// public DefaultReplacers(ReplacerAPI replaceManager, T plugin) {
// this.replaceManager = replaceManager;
// this.plugin = plugin;
// }
//
// /**
// * Register all variables that this class can manage
// */
// public abstract void register();
//
// /**
// * Shortcut method to register the variables without the boilerplate of adding the plugin instance and registering
// * it to the manager.
// *
// * @param variable variable name like "online"
// * @return the replacer responsible for this single variable
// */
// protected Replacer register(String variable) {
// Replacer replacer = new Replacer(plugin, variable);
// replaceManager.register(replacer);
// return replacer;
// }
// }
//
// Path: variables/src/main/java/com/github/games647/scoreboardstats/variables/ReplacerAPI.java
// public abstract class ReplacerAPI {
//
// protected final Logger logger;
// protected final Map<String, Replacer> replacers = Maps.newHashMap();
//
// public ReplacerAPI(Logger logger) {
// this.logger = logger;
// }
//
// public void register(Replacer replacer) {
// replacers.put(replacer.getVariable(), replacer);
//
// for (EventReplacer<? extends Event> eventReplacer : replacer.getEventsReplacers().values()) {
// Class<? extends Event> eventClass = eventReplacer.getEventClass();
// Plugin plugin = replacer.getPlugin();
//
// EventExecutor executor = (listener, event) -> eventReplacer.execute(this, event);
//
// Listener listener = new Listener() {};
//
// PluginManager pluginManager = Bukkit.getPluginManager();
// pluginManager.registerEvent(eventClass, listener, HIGHEST, executor, plugin, true);
// }
// }
//
// public void unregister(String variable) {
// replacers.remove(variable);
// }
//
// public void unregisterAll(Plugin disablePlugin) {
// Iterator<Replacer> iterator = replacers.values().iterator();
// while (iterator.hasNext()) {
// Plugin plugin = iterator.next().getPlugin();
// if (plugin == disablePlugin) {
// iterator.remove();
// }
// }
// }
//
// public void forceUpdate(String variable, int score) {
// Bukkit.getOnlinePlayers().forEach(player -> forceUpdate(player, variable, score));
// }
//
// public void forceUpdate(String variable, String value) {
// Bukkit.getOnlinePlayers().forEach(player -> forceUpdate(player, variable, value));
// }
//
// public abstract void forceUpdate(Player player, String variable, int score);
//
// public abstract void forceUpdate(Player player, String variable, String value);
//
// public Optional<String> replace(Player player, String variable, boolean complete) throws ReplacerException {
// Replacer replacer = getReplacer(variable);
// if (!complete && replacer.isGlobal() || replacer.isEventVariable() || replacer.isConstant()) {
// return Optional.empty();
// }
//
// try {
// return Optional.of(replacer.replace(player));
// } catch (Exception ex) {
// throw new ReplacerException(ex);
// }
// }
//
// public OptionalInt scoreReplace(Player player, String variable, boolean complete) throws ReplacerException {
// Replacer replacer = getReplacer(variable);
// if (!complete && replacer.isGlobal() || replacer.isEventVariable() || replacer.isConstant()) {
// return OptionalInt.empty();
// }
//
// try {
// return OptionalInt.of(replacer.scoreReplace(player));
// } catch (Exception ex) {
// throw new ReplacerException(ex);
// }
// }
//
// private Replacer getReplacer(String variable) throws UnknownVariableException {
// Replacer replacer = this.replacers.get(variable);
// if (replacer == null) {
// throw new UnknownVariableException(variable);
// }
//
// return replacer;
// }
// }
| import com.github.games647.scoreboardstats.variables.DefaultReplacer;
import com.github.games647.scoreboardstats.variables.DefaultReplacers;
import com.github.games647.scoreboardstats.variables.ReplacerAPI;
import java.util.Calendar;
import org.bukkit.plugin.Plugin; | package com.github.games647.scoreboardstats.defaults;
/**
* Represents a replacer for non Minecraft related variables
*/
@DefaultReplacer
public class GeneralVariables extends DefaultReplacers<Plugin> {
//From bytes to mega bytes
private static final int MB_CONVERSION = 1_024 * 1_024;
private final Runtime runtime = Runtime.getRuntime();
| // Path: variables/src/main/java/com/github/games647/scoreboardstats/variables/DefaultReplacers.java
// public abstract class DefaultReplacers<T extends Plugin> {
//
// protected final ReplacerAPI replaceManager;
// protected final T plugin;
//
// public DefaultReplacers(ReplacerAPI replaceManager, T plugin) {
// this.replaceManager = replaceManager;
// this.plugin = plugin;
// }
//
// /**
// * Register all variables that this class can manage
// */
// public abstract void register();
//
// /**
// * Shortcut method to register the variables without the boilerplate of adding the plugin instance and registering
// * it to the manager.
// *
// * @param variable variable name like "online"
// * @return the replacer responsible for this single variable
// */
// protected Replacer register(String variable) {
// Replacer replacer = new Replacer(plugin, variable);
// replaceManager.register(replacer);
// return replacer;
// }
// }
//
// Path: variables/src/main/java/com/github/games647/scoreboardstats/variables/ReplacerAPI.java
// public abstract class ReplacerAPI {
//
// protected final Logger logger;
// protected final Map<String, Replacer> replacers = Maps.newHashMap();
//
// public ReplacerAPI(Logger logger) {
// this.logger = logger;
// }
//
// public void register(Replacer replacer) {
// replacers.put(replacer.getVariable(), replacer);
//
// for (EventReplacer<? extends Event> eventReplacer : replacer.getEventsReplacers().values()) {
// Class<? extends Event> eventClass = eventReplacer.getEventClass();
// Plugin plugin = replacer.getPlugin();
//
// EventExecutor executor = (listener, event) -> eventReplacer.execute(this, event);
//
// Listener listener = new Listener() {};
//
// PluginManager pluginManager = Bukkit.getPluginManager();
// pluginManager.registerEvent(eventClass, listener, HIGHEST, executor, plugin, true);
// }
// }
//
// public void unregister(String variable) {
// replacers.remove(variable);
// }
//
// public void unregisterAll(Plugin disablePlugin) {
// Iterator<Replacer> iterator = replacers.values().iterator();
// while (iterator.hasNext()) {
// Plugin plugin = iterator.next().getPlugin();
// if (plugin == disablePlugin) {
// iterator.remove();
// }
// }
// }
//
// public void forceUpdate(String variable, int score) {
// Bukkit.getOnlinePlayers().forEach(player -> forceUpdate(player, variable, score));
// }
//
// public void forceUpdate(String variable, String value) {
// Bukkit.getOnlinePlayers().forEach(player -> forceUpdate(player, variable, value));
// }
//
// public abstract void forceUpdate(Player player, String variable, int score);
//
// public abstract void forceUpdate(Player player, String variable, String value);
//
// public Optional<String> replace(Player player, String variable, boolean complete) throws ReplacerException {
// Replacer replacer = getReplacer(variable);
// if (!complete && replacer.isGlobal() || replacer.isEventVariable() || replacer.isConstant()) {
// return Optional.empty();
// }
//
// try {
// return Optional.of(replacer.replace(player));
// } catch (Exception ex) {
// throw new ReplacerException(ex);
// }
// }
//
// public OptionalInt scoreReplace(Player player, String variable, boolean complete) throws ReplacerException {
// Replacer replacer = getReplacer(variable);
// if (!complete && replacer.isGlobal() || replacer.isEventVariable() || replacer.isConstant()) {
// return OptionalInt.empty();
// }
//
// try {
// return OptionalInt.of(replacer.scoreReplace(player));
// } catch (Exception ex) {
// throw new ReplacerException(ex);
// }
// }
//
// private Replacer getReplacer(String variable) throws UnknownVariableException {
// Replacer replacer = this.replacers.get(variable);
// if (replacer == null) {
// throw new UnknownVariableException(variable);
// }
//
// return replacer;
// }
// }
// Path: defaults/src/main/java/com/github/games647/scoreboardstats/defaults/GeneralVariables.java
import com.github.games647.scoreboardstats.variables.DefaultReplacer;
import com.github.games647.scoreboardstats.variables.DefaultReplacers;
import com.github.games647.scoreboardstats.variables.ReplacerAPI;
import java.util.Calendar;
import org.bukkit.plugin.Plugin;
package com.github.games647.scoreboardstats.defaults;
/**
* Represents a replacer for non Minecraft related variables
*/
@DefaultReplacer
public class GeneralVariables extends DefaultReplacers<Plugin> {
//From bytes to mega bytes
private static final int MB_CONVERSION = 1_024 * 1_024;
private final Runtime runtime = Runtime.getRuntime();
| public GeneralVariables(ReplacerAPI replaceManager, Plugin plugin) { |
games647/ScoreboardStats | defaults/src/main/java/com/github/games647/scoreboardstats/defaults/GriefPreventionVariables.java | // Path: variables/src/main/java/com/github/games647/scoreboardstats/variables/DefaultReplacers.java
// public abstract class DefaultReplacers<T extends Plugin> {
//
// protected final ReplacerAPI replaceManager;
// protected final T plugin;
//
// public DefaultReplacers(ReplacerAPI replaceManager, T plugin) {
// this.replaceManager = replaceManager;
// this.plugin = plugin;
// }
//
// /**
// * Register all variables that this class can manage
// */
// public abstract void register();
//
// /**
// * Shortcut method to register the variables without the boilerplate of adding the plugin instance and registering
// * it to the manager.
// *
// * @param variable variable name like "online"
// * @return the replacer responsible for this single variable
// */
// protected Replacer register(String variable) {
// Replacer replacer = new Replacer(plugin, variable);
// replaceManager.register(replacer);
// return replacer;
// }
// }
//
// Path: variables/src/main/java/com/github/games647/scoreboardstats/variables/ReplacerAPI.java
// public abstract class ReplacerAPI {
//
// protected final Logger logger;
// protected final Map<String, Replacer> replacers = Maps.newHashMap();
//
// public ReplacerAPI(Logger logger) {
// this.logger = logger;
// }
//
// public void register(Replacer replacer) {
// replacers.put(replacer.getVariable(), replacer);
//
// for (EventReplacer<? extends Event> eventReplacer : replacer.getEventsReplacers().values()) {
// Class<? extends Event> eventClass = eventReplacer.getEventClass();
// Plugin plugin = replacer.getPlugin();
//
// EventExecutor executor = (listener, event) -> eventReplacer.execute(this, event);
//
// Listener listener = new Listener() {};
//
// PluginManager pluginManager = Bukkit.getPluginManager();
// pluginManager.registerEvent(eventClass, listener, HIGHEST, executor, plugin, true);
// }
// }
//
// public void unregister(String variable) {
// replacers.remove(variable);
// }
//
// public void unregisterAll(Plugin disablePlugin) {
// Iterator<Replacer> iterator = replacers.values().iterator();
// while (iterator.hasNext()) {
// Plugin plugin = iterator.next().getPlugin();
// if (plugin == disablePlugin) {
// iterator.remove();
// }
// }
// }
//
// public void forceUpdate(String variable, int score) {
// Bukkit.getOnlinePlayers().forEach(player -> forceUpdate(player, variable, score));
// }
//
// public void forceUpdate(String variable, String value) {
// Bukkit.getOnlinePlayers().forEach(player -> forceUpdate(player, variable, value));
// }
//
// public abstract void forceUpdate(Player player, String variable, int score);
//
// public abstract void forceUpdate(Player player, String variable, String value);
//
// public Optional<String> replace(Player player, String variable, boolean complete) throws ReplacerException {
// Replacer replacer = getReplacer(variable);
// if (!complete && replacer.isGlobal() || replacer.isEventVariable() || replacer.isConstant()) {
// return Optional.empty();
// }
//
// try {
// return Optional.of(replacer.replace(player));
// } catch (Exception ex) {
// throw new ReplacerException(ex);
// }
// }
//
// public OptionalInt scoreReplace(Player player, String variable, boolean complete) throws ReplacerException {
// Replacer replacer = getReplacer(variable);
// if (!complete && replacer.isGlobal() || replacer.isEventVariable() || replacer.isConstant()) {
// return OptionalInt.empty();
// }
//
// try {
// return OptionalInt.of(replacer.scoreReplace(player));
// } catch (Exception ex) {
// throw new ReplacerException(ex);
// }
// }
//
// private Replacer getReplacer(String variable) throws UnknownVariableException {
// Replacer replacer = this.replacers.get(variable);
// if (replacer == null) {
// throw new UnknownVariableException(variable);
// }
//
// return replacer;
// }
// }
| import com.github.games647.scoreboardstats.variables.DefaultReplacer;
import com.github.games647.scoreboardstats.variables.DefaultReplacers;
import com.github.games647.scoreboardstats.variables.ReplacerAPI;
import me.ryanhamshire.GriefPrevention.GriefPrevention;
import me.ryanhamshire.GriefPrevention.PlayerData;
import org.bukkit.entity.Player; | package com.github.games647.scoreboardstats.defaults;
@DefaultReplacer(plugin = "GriefPrevention")
public class GriefPreventionVariables extends DefaultReplacers<GriefPrevention> {
| // Path: variables/src/main/java/com/github/games647/scoreboardstats/variables/DefaultReplacers.java
// public abstract class DefaultReplacers<T extends Plugin> {
//
// protected final ReplacerAPI replaceManager;
// protected final T plugin;
//
// public DefaultReplacers(ReplacerAPI replaceManager, T plugin) {
// this.replaceManager = replaceManager;
// this.plugin = plugin;
// }
//
// /**
// * Register all variables that this class can manage
// */
// public abstract void register();
//
// /**
// * Shortcut method to register the variables without the boilerplate of adding the plugin instance and registering
// * it to the manager.
// *
// * @param variable variable name like "online"
// * @return the replacer responsible for this single variable
// */
// protected Replacer register(String variable) {
// Replacer replacer = new Replacer(plugin, variable);
// replaceManager.register(replacer);
// return replacer;
// }
// }
//
// Path: variables/src/main/java/com/github/games647/scoreboardstats/variables/ReplacerAPI.java
// public abstract class ReplacerAPI {
//
// protected final Logger logger;
// protected final Map<String, Replacer> replacers = Maps.newHashMap();
//
// public ReplacerAPI(Logger logger) {
// this.logger = logger;
// }
//
// public void register(Replacer replacer) {
// replacers.put(replacer.getVariable(), replacer);
//
// for (EventReplacer<? extends Event> eventReplacer : replacer.getEventsReplacers().values()) {
// Class<? extends Event> eventClass = eventReplacer.getEventClass();
// Plugin plugin = replacer.getPlugin();
//
// EventExecutor executor = (listener, event) -> eventReplacer.execute(this, event);
//
// Listener listener = new Listener() {};
//
// PluginManager pluginManager = Bukkit.getPluginManager();
// pluginManager.registerEvent(eventClass, listener, HIGHEST, executor, plugin, true);
// }
// }
//
// public void unregister(String variable) {
// replacers.remove(variable);
// }
//
// public void unregisterAll(Plugin disablePlugin) {
// Iterator<Replacer> iterator = replacers.values().iterator();
// while (iterator.hasNext()) {
// Plugin plugin = iterator.next().getPlugin();
// if (plugin == disablePlugin) {
// iterator.remove();
// }
// }
// }
//
// public void forceUpdate(String variable, int score) {
// Bukkit.getOnlinePlayers().forEach(player -> forceUpdate(player, variable, score));
// }
//
// public void forceUpdate(String variable, String value) {
// Bukkit.getOnlinePlayers().forEach(player -> forceUpdate(player, variable, value));
// }
//
// public abstract void forceUpdate(Player player, String variable, int score);
//
// public abstract void forceUpdate(Player player, String variable, String value);
//
// public Optional<String> replace(Player player, String variable, boolean complete) throws ReplacerException {
// Replacer replacer = getReplacer(variable);
// if (!complete && replacer.isGlobal() || replacer.isEventVariable() || replacer.isConstant()) {
// return Optional.empty();
// }
//
// try {
// return Optional.of(replacer.replace(player));
// } catch (Exception ex) {
// throw new ReplacerException(ex);
// }
// }
//
// public OptionalInt scoreReplace(Player player, String variable, boolean complete) throws ReplacerException {
// Replacer replacer = getReplacer(variable);
// if (!complete && replacer.isGlobal() || replacer.isEventVariable() || replacer.isConstant()) {
// return OptionalInt.empty();
// }
//
// try {
// return OptionalInt.of(replacer.scoreReplace(player));
// } catch (Exception ex) {
// throw new ReplacerException(ex);
// }
// }
//
// private Replacer getReplacer(String variable) throws UnknownVariableException {
// Replacer replacer = this.replacers.get(variable);
// if (replacer == null) {
// throw new UnknownVariableException(variable);
// }
//
// return replacer;
// }
// }
// Path: defaults/src/main/java/com/github/games647/scoreboardstats/defaults/GriefPreventionVariables.java
import com.github.games647.scoreboardstats.variables.DefaultReplacer;
import com.github.games647.scoreboardstats.variables.DefaultReplacers;
import com.github.games647.scoreboardstats.variables.ReplacerAPI;
import me.ryanhamshire.GriefPrevention.GriefPrevention;
import me.ryanhamshire.GriefPrevention.PlayerData;
import org.bukkit.entity.Player;
package com.github.games647.scoreboardstats.defaults;
@DefaultReplacer(plugin = "GriefPrevention")
public class GriefPreventionVariables extends DefaultReplacers<GriefPrevention> {
| public GriefPreventionVariables(ReplacerAPI replaceManager, GriefPrevention plugin) { |
games647/ScoreboardStats | defaults/src/main/java/com/github/games647/scoreboardstats/defaults/BukkitGlobalVariables.java | // Path: variables/src/main/java/com/github/games647/scoreboardstats/variables/DefaultReplacers.java
// public abstract class DefaultReplacers<T extends Plugin> {
//
// protected final ReplacerAPI replaceManager;
// protected final T plugin;
//
// public DefaultReplacers(ReplacerAPI replaceManager, T plugin) {
// this.replaceManager = replaceManager;
// this.plugin = plugin;
// }
//
// /**
// * Register all variables that this class can manage
// */
// public abstract void register();
//
// /**
// * Shortcut method to register the variables without the boilerplate of adding the plugin instance and registering
// * it to the manager.
// *
// * @param variable variable name like "online"
// * @return the replacer responsible for this single variable
// */
// protected Replacer register(String variable) {
// Replacer replacer = new Replacer(plugin, variable);
// replaceManager.register(replacer);
// return replacer;
// }
// }
//
// Path: variables/src/main/java/com/github/games647/scoreboardstats/variables/ReplacerAPI.java
// public abstract class ReplacerAPI {
//
// protected final Logger logger;
// protected final Map<String, Replacer> replacers = Maps.newHashMap();
//
// public ReplacerAPI(Logger logger) {
// this.logger = logger;
// }
//
// public void register(Replacer replacer) {
// replacers.put(replacer.getVariable(), replacer);
//
// for (EventReplacer<? extends Event> eventReplacer : replacer.getEventsReplacers().values()) {
// Class<? extends Event> eventClass = eventReplacer.getEventClass();
// Plugin plugin = replacer.getPlugin();
//
// EventExecutor executor = (listener, event) -> eventReplacer.execute(this, event);
//
// Listener listener = new Listener() {};
//
// PluginManager pluginManager = Bukkit.getPluginManager();
// pluginManager.registerEvent(eventClass, listener, HIGHEST, executor, plugin, true);
// }
// }
//
// public void unregister(String variable) {
// replacers.remove(variable);
// }
//
// public void unregisterAll(Plugin disablePlugin) {
// Iterator<Replacer> iterator = replacers.values().iterator();
// while (iterator.hasNext()) {
// Plugin plugin = iterator.next().getPlugin();
// if (plugin == disablePlugin) {
// iterator.remove();
// }
// }
// }
//
// public void forceUpdate(String variable, int score) {
// Bukkit.getOnlinePlayers().forEach(player -> forceUpdate(player, variable, score));
// }
//
// public void forceUpdate(String variable, String value) {
// Bukkit.getOnlinePlayers().forEach(player -> forceUpdate(player, variable, value));
// }
//
// public abstract void forceUpdate(Player player, String variable, int score);
//
// public abstract void forceUpdate(Player player, String variable, String value);
//
// public Optional<String> replace(Player player, String variable, boolean complete) throws ReplacerException {
// Replacer replacer = getReplacer(variable);
// if (!complete && replacer.isGlobal() || replacer.isEventVariable() || replacer.isConstant()) {
// return Optional.empty();
// }
//
// try {
// return Optional.of(replacer.replace(player));
// } catch (Exception ex) {
// throw new ReplacerException(ex);
// }
// }
//
// public OptionalInt scoreReplace(Player player, String variable, boolean complete) throws ReplacerException {
// Replacer replacer = getReplacer(variable);
// if (!complete && replacer.isGlobal() || replacer.isEventVariable() || replacer.isConstant()) {
// return OptionalInt.empty();
// }
//
// try {
// return OptionalInt.of(replacer.scoreReplace(player));
// } catch (Exception ex) {
// throw new ReplacerException(ex);
// }
// }
//
// private Replacer getReplacer(String variable) throws UnknownVariableException {
// Replacer replacer = this.replacers.get(variable);
// if (replacer == null) {
// throw new UnknownVariableException(variable);
// }
//
// return replacer;
// }
// }
| import com.github.games647.scoreboardstats.variables.DefaultReplacer;
import com.github.games647.scoreboardstats.variables.DefaultReplacers;
import com.github.games647.scoreboardstats.variables.ReplacerAPI;
import org.bukkit.Bukkit;
import org.bukkit.event.player.PlayerJoinEvent;
import org.bukkit.event.player.PlayerQuitEvent;
import org.bukkit.plugin.Plugin;
import org.bukkit.util.NumberConversions; | package com.github.games647.scoreboardstats.defaults;
/**
* Replace all Bukkit variables which are the same for players. Currently
* there is no good way to mark variables as global
*/
@DefaultReplacer
public class BukkitGlobalVariables extends DefaultReplacers<Plugin> {
| // Path: variables/src/main/java/com/github/games647/scoreboardstats/variables/DefaultReplacers.java
// public abstract class DefaultReplacers<T extends Plugin> {
//
// protected final ReplacerAPI replaceManager;
// protected final T plugin;
//
// public DefaultReplacers(ReplacerAPI replaceManager, T plugin) {
// this.replaceManager = replaceManager;
// this.plugin = plugin;
// }
//
// /**
// * Register all variables that this class can manage
// */
// public abstract void register();
//
// /**
// * Shortcut method to register the variables without the boilerplate of adding the plugin instance and registering
// * it to the manager.
// *
// * @param variable variable name like "online"
// * @return the replacer responsible for this single variable
// */
// protected Replacer register(String variable) {
// Replacer replacer = new Replacer(plugin, variable);
// replaceManager.register(replacer);
// return replacer;
// }
// }
//
// Path: variables/src/main/java/com/github/games647/scoreboardstats/variables/ReplacerAPI.java
// public abstract class ReplacerAPI {
//
// protected final Logger logger;
// protected final Map<String, Replacer> replacers = Maps.newHashMap();
//
// public ReplacerAPI(Logger logger) {
// this.logger = logger;
// }
//
// public void register(Replacer replacer) {
// replacers.put(replacer.getVariable(), replacer);
//
// for (EventReplacer<? extends Event> eventReplacer : replacer.getEventsReplacers().values()) {
// Class<? extends Event> eventClass = eventReplacer.getEventClass();
// Plugin plugin = replacer.getPlugin();
//
// EventExecutor executor = (listener, event) -> eventReplacer.execute(this, event);
//
// Listener listener = new Listener() {};
//
// PluginManager pluginManager = Bukkit.getPluginManager();
// pluginManager.registerEvent(eventClass, listener, HIGHEST, executor, plugin, true);
// }
// }
//
// public void unregister(String variable) {
// replacers.remove(variable);
// }
//
// public void unregisterAll(Plugin disablePlugin) {
// Iterator<Replacer> iterator = replacers.values().iterator();
// while (iterator.hasNext()) {
// Plugin plugin = iterator.next().getPlugin();
// if (plugin == disablePlugin) {
// iterator.remove();
// }
// }
// }
//
// public void forceUpdate(String variable, int score) {
// Bukkit.getOnlinePlayers().forEach(player -> forceUpdate(player, variable, score));
// }
//
// public void forceUpdate(String variable, String value) {
// Bukkit.getOnlinePlayers().forEach(player -> forceUpdate(player, variable, value));
// }
//
// public abstract void forceUpdate(Player player, String variable, int score);
//
// public abstract void forceUpdate(Player player, String variable, String value);
//
// public Optional<String> replace(Player player, String variable, boolean complete) throws ReplacerException {
// Replacer replacer = getReplacer(variable);
// if (!complete && replacer.isGlobal() || replacer.isEventVariable() || replacer.isConstant()) {
// return Optional.empty();
// }
//
// try {
// return Optional.of(replacer.replace(player));
// } catch (Exception ex) {
// throw new ReplacerException(ex);
// }
// }
//
// public OptionalInt scoreReplace(Player player, String variable, boolean complete) throws ReplacerException {
// Replacer replacer = getReplacer(variable);
// if (!complete && replacer.isGlobal() || replacer.isEventVariable() || replacer.isConstant()) {
// return OptionalInt.empty();
// }
//
// try {
// return OptionalInt.of(replacer.scoreReplace(player));
// } catch (Exception ex) {
// throw new ReplacerException(ex);
// }
// }
//
// private Replacer getReplacer(String variable) throws UnknownVariableException {
// Replacer replacer = this.replacers.get(variable);
// if (replacer == null) {
// throw new UnknownVariableException(variable);
// }
//
// return replacer;
// }
// }
// Path: defaults/src/main/java/com/github/games647/scoreboardstats/defaults/BukkitGlobalVariables.java
import com.github.games647.scoreboardstats.variables.DefaultReplacer;
import com.github.games647.scoreboardstats.variables.DefaultReplacers;
import com.github.games647.scoreboardstats.variables.ReplacerAPI;
import org.bukkit.Bukkit;
import org.bukkit.event.player.PlayerJoinEvent;
import org.bukkit.event.player.PlayerQuitEvent;
import org.bukkit.plugin.Plugin;
import org.bukkit.util.NumberConversions;
package com.github.games647.scoreboardstats.defaults;
/**
* Replace all Bukkit variables which are the same for players. Currently
* there is no good way to mark variables as global
*/
@DefaultReplacer
public class BukkitGlobalVariables extends DefaultReplacers<Plugin> {
| public BukkitGlobalVariables(ReplacerAPI replaceManager, Plugin plugin) { |
games647/ScoreboardStats | defaults/src/main/java/com/github/games647/scoreboardstats/defaults/BukkitVariables.java | // Path: variables/src/main/java/com/github/games647/scoreboardstats/variables/DefaultReplacers.java
// public abstract class DefaultReplacers<T extends Plugin> {
//
// protected final ReplacerAPI replaceManager;
// protected final T plugin;
//
// public DefaultReplacers(ReplacerAPI replaceManager, T plugin) {
// this.replaceManager = replaceManager;
// this.plugin = plugin;
// }
//
// /**
// * Register all variables that this class can manage
// */
// public abstract void register();
//
// /**
// * Shortcut method to register the variables without the boilerplate of adding the plugin instance and registering
// * it to the manager.
// *
// * @param variable variable name like "online"
// * @return the replacer responsible for this single variable
// */
// protected Replacer register(String variable) {
// Replacer replacer = new Replacer(plugin, variable);
// replaceManager.register(replacer);
// return replacer;
// }
// }
//
// Path: variables/src/main/java/com/github/games647/scoreboardstats/variables/ReplacerAPI.java
// public abstract class ReplacerAPI {
//
// protected final Logger logger;
// protected final Map<String, Replacer> replacers = Maps.newHashMap();
//
// public ReplacerAPI(Logger logger) {
// this.logger = logger;
// }
//
// public void register(Replacer replacer) {
// replacers.put(replacer.getVariable(), replacer);
//
// for (EventReplacer<? extends Event> eventReplacer : replacer.getEventsReplacers().values()) {
// Class<? extends Event> eventClass = eventReplacer.getEventClass();
// Plugin plugin = replacer.getPlugin();
//
// EventExecutor executor = (listener, event) -> eventReplacer.execute(this, event);
//
// Listener listener = new Listener() {};
//
// PluginManager pluginManager = Bukkit.getPluginManager();
// pluginManager.registerEvent(eventClass, listener, HIGHEST, executor, plugin, true);
// }
// }
//
// public void unregister(String variable) {
// replacers.remove(variable);
// }
//
// public void unregisterAll(Plugin disablePlugin) {
// Iterator<Replacer> iterator = replacers.values().iterator();
// while (iterator.hasNext()) {
// Plugin plugin = iterator.next().getPlugin();
// if (plugin == disablePlugin) {
// iterator.remove();
// }
// }
// }
//
// public void forceUpdate(String variable, int score) {
// Bukkit.getOnlinePlayers().forEach(player -> forceUpdate(player, variable, score));
// }
//
// public void forceUpdate(String variable, String value) {
// Bukkit.getOnlinePlayers().forEach(player -> forceUpdate(player, variable, value));
// }
//
// public abstract void forceUpdate(Player player, String variable, int score);
//
// public abstract void forceUpdate(Player player, String variable, String value);
//
// public Optional<String> replace(Player player, String variable, boolean complete) throws ReplacerException {
// Replacer replacer = getReplacer(variable);
// if (!complete && replacer.isGlobal() || replacer.isEventVariable() || replacer.isConstant()) {
// return Optional.empty();
// }
//
// try {
// return Optional.of(replacer.replace(player));
// } catch (Exception ex) {
// throw new ReplacerException(ex);
// }
// }
//
// public OptionalInt scoreReplace(Player player, String variable, boolean complete) throws ReplacerException {
// Replacer replacer = getReplacer(variable);
// if (!complete && replacer.isGlobal() || replacer.isEventVariable() || replacer.isConstant()) {
// return OptionalInt.empty();
// }
//
// try {
// return OptionalInt.of(replacer.scoreReplace(player));
// } catch (Exception ex) {
// throw new ReplacerException(ex);
// }
// }
//
// private Replacer getReplacer(String variable) throws UnknownVariableException {
// Replacer replacer = this.replacers.get(variable);
// if (replacer == null) {
// throw new UnknownVariableException(variable);
// }
//
// return replacer;
// }
// }
| import com.github.games647.scoreboardstats.variables.DefaultReplacer;
import com.github.games647.scoreboardstats.variables.DefaultReplacers;
import com.github.games647.scoreboardstats.variables.ReplacerAPI;
import org.bukkit.entity.Player;
import org.bukkit.inventory.ItemStack;
import org.bukkit.plugin.Plugin;
import org.bukkit.util.NumberConversions; | package com.github.games647.scoreboardstats.defaults;
/**
* Replace all Bukkit variables
*/
@DefaultReplacer
public class BukkitVariables extends DefaultReplacers<Plugin> {
private static final int MINUTE_TO_SECOND = 60;
| // Path: variables/src/main/java/com/github/games647/scoreboardstats/variables/DefaultReplacers.java
// public abstract class DefaultReplacers<T extends Plugin> {
//
// protected final ReplacerAPI replaceManager;
// protected final T plugin;
//
// public DefaultReplacers(ReplacerAPI replaceManager, T plugin) {
// this.replaceManager = replaceManager;
// this.plugin = plugin;
// }
//
// /**
// * Register all variables that this class can manage
// */
// public abstract void register();
//
// /**
// * Shortcut method to register the variables without the boilerplate of adding the plugin instance and registering
// * it to the manager.
// *
// * @param variable variable name like "online"
// * @return the replacer responsible for this single variable
// */
// protected Replacer register(String variable) {
// Replacer replacer = new Replacer(plugin, variable);
// replaceManager.register(replacer);
// return replacer;
// }
// }
//
// Path: variables/src/main/java/com/github/games647/scoreboardstats/variables/ReplacerAPI.java
// public abstract class ReplacerAPI {
//
// protected final Logger logger;
// protected final Map<String, Replacer> replacers = Maps.newHashMap();
//
// public ReplacerAPI(Logger logger) {
// this.logger = logger;
// }
//
// public void register(Replacer replacer) {
// replacers.put(replacer.getVariable(), replacer);
//
// for (EventReplacer<? extends Event> eventReplacer : replacer.getEventsReplacers().values()) {
// Class<? extends Event> eventClass = eventReplacer.getEventClass();
// Plugin plugin = replacer.getPlugin();
//
// EventExecutor executor = (listener, event) -> eventReplacer.execute(this, event);
//
// Listener listener = new Listener() {};
//
// PluginManager pluginManager = Bukkit.getPluginManager();
// pluginManager.registerEvent(eventClass, listener, HIGHEST, executor, plugin, true);
// }
// }
//
// public void unregister(String variable) {
// replacers.remove(variable);
// }
//
// public void unregisterAll(Plugin disablePlugin) {
// Iterator<Replacer> iterator = replacers.values().iterator();
// while (iterator.hasNext()) {
// Plugin plugin = iterator.next().getPlugin();
// if (plugin == disablePlugin) {
// iterator.remove();
// }
// }
// }
//
// public void forceUpdate(String variable, int score) {
// Bukkit.getOnlinePlayers().forEach(player -> forceUpdate(player, variable, score));
// }
//
// public void forceUpdate(String variable, String value) {
// Bukkit.getOnlinePlayers().forEach(player -> forceUpdate(player, variable, value));
// }
//
// public abstract void forceUpdate(Player player, String variable, int score);
//
// public abstract void forceUpdate(Player player, String variable, String value);
//
// public Optional<String> replace(Player player, String variable, boolean complete) throws ReplacerException {
// Replacer replacer = getReplacer(variable);
// if (!complete && replacer.isGlobal() || replacer.isEventVariable() || replacer.isConstant()) {
// return Optional.empty();
// }
//
// try {
// return Optional.of(replacer.replace(player));
// } catch (Exception ex) {
// throw new ReplacerException(ex);
// }
// }
//
// public OptionalInt scoreReplace(Player player, String variable, boolean complete) throws ReplacerException {
// Replacer replacer = getReplacer(variable);
// if (!complete && replacer.isGlobal() || replacer.isEventVariable() || replacer.isConstant()) {
// return OptionalInt.empty();
// }
//
// try {
// return OptionalInt.of(replacer.scoreReplace(player));
// } catch (Exception ex) {
// throw new ReplacerException(ex);
// }
// }
//
// private Replacer getReplacer(String variable) throws UnknownVariableException {
// Replacer replacer = this.replacers.get(variable);
// if (replacer == null) {
// throw new UnknownVariableException(variable);
// }
//
// return replacer;
// }
// }
// Path: defaults/src/main/java/com/github/games647/scoreboardstats/defaults/BukkitVariables.java
import com.github.games647.scoreboardstats.variables.DefaultReplacer;
import com.github.games647.scoreboardstats.variables.DefaultReplacers;
import com.github.games647.scoreboardstats.variables.ReplacerAPI;
import org.bukkit.entity.Player;
import org.bukkit.inventory.ItemStack;
import org.bukkit.plugin.Plugin;
import org.bukkit.util.NumberConversions;
package com.github.games647.scoreboardstats.defaults;
/**
* Replace all Bukkit variables
*/
@DefaultReplacer
public class BukkitVariables extends DefaultReplacers<Plugin> {
private static final int MINUTE_TO_SECOND = 60;
| public BukkitVariables(ReplacerAPI replaceManager, Plugin plugin) { |
games647/ScoreboardStats | defaults/src/main/java/com/github/games647/scoreboardstats/defaults/BukkitGamesVariables.java | // Path: variables/src/main/java/com/github/games647/scoreboardstats/variables/DefaultReplacers.java
// public abstract class DefaultReplacers<T extends Plugin> {
//
// protected final ReplacerAPI replaceManager;
// protected final T plugin;
//
// public DefaultReplacers(ReplacerAPI replaceManager, T plugin) {
// this.replaceManager = replaceManager;
// this.plugin = plugin;
// }
//
// /**
// * Register all variables that this class can manage
// */
// public abstract void register();
//
// /**
// * Shortcut method to register the variables without the boilerplate of adding the plugin instance and registering
// * it to the manager.
// *
// * @param variable variable name like "online"
// * @return the replacer responsible for this single variable
// */
// protected Replacer register(String variable) {
// Replacer replacer = new Replacer(plugin, variable);
// replaceManager.register(replacer);
// return replacer;
// }
// }
//
// Path: variables/src/main/java/com/github/games647/scoreboardstats/variables/ReplacerAPI.java
// public abstract class ReplacerAPI {
//
// protected final Logger logger;
// protected final Map<String, Replacer> replacers = Maps.newHashMap();
//
// public ReplacerAPI(Logger logger) {
// this.logger = logger;
// }
//
// public void register(Replacer replacer) {
// replacers.put(replacer.getVariable(), replacer);
//
// for (EventReplacer<? extends Event> eventReplacer : replacer.getEventsReplacers().values()) {
// Class<? extends Event> eventClass = eventReplacer.getEventClass();
// Plugin plugin = replacer.getPlugin();
//
// EventExecutor executor = (listener, event) -> eventReplacer.execute(this, event);
//
// Listener listener = new Listener() {};
//
// PluginManager pluginManager = Bukkit.getPluginManager();
// pluginManager.registerEvent(eventClass, listener, HIGHEST, executor, plugin, true);
// }
// }
//
// public void unregister(String variable) {
// replacers.remove(variable);
// }
//
// public void unregisterAll(Plugin disablePlugin) {
// Iterator<Replacer> iterator = replacers.values().iterator();
// while (iterator.hasNext()) {
// Plugin plugin = iterator.next().getPlugin();
// if (plugin == disablePlugin) {
// iterator.remove();
// }
// }
// }
//
// public void forceUpdate(String variable, int score) {
// Bukkit.getOnlinePlayers().forEach(player -> forceUpdate(player, variable, score));
// }
//
// public void forceUpdate(String variable, String value) {
// Bukkit.getOnlinePlayers().forEach(player -> forceUpdate(player, variable, value));
// }
//
// public abstract void forceUpdate(Player player, String variable, int score);
//
// public abstract void forceUpdate(Player player, String variable, String value);
//
// public Optional<String> replace(Player player, String variable, boolean complete) throws ReplacerException {
// Replacer replacer = getReplacer(variable);
// if (!complete && replacer.isGlobal() || replacer.isEventVariable() || replacer.isConstant()) {
// return Optional.empty();
// }
//
// try {
// return Optional.of(replacer.replace(player));
// } catch (Exception ex) {
// throw new ReplacerException(ex);
// }
// }
//
// public OptionalInt scoreReplace(Player player, String variable, boolean complete) throws ReplacerException {
// Replacer replacer = getReplacer(variable);
// if (!complete && replacer.isGlobal() || replacer.isEventVariable() || replacer.isConstant()) {
// return OptionalInt.empty();
// }
//
// try {
// return OptionalInt.of(replacer.scoreReplace(player));
// } catch (Exception ex) {
// throw new ReplacerException(ex);
// }
// }
//
// private Replacer getReplacer(String variable) throws UnknownVariableException {
// Replacer replacer = this.replacers.get(variable);
// if (replacer == null) {
// throw new UnknownVariableException(variable);
// }
//
// return replacer;
// }
// }
| import com.github.games647.scoreboardstats.variables.DefaultReplacer;
import com.github.games647.scoreboardstats.variables.DefaultReplacers;
import com.github.games647.scoreboardstats.variables.ReplacerAPI;
import de.ftbastler.bukkitgames.api.BukkitGamesAPI;
import de.ftbastler.bukkitgames.api.PlayerBuyKitEvent;
import org.bukkit.plugin.Plugin; | package com.github.games647.scoreboardstats.defaults;
@DefaultReplacer(plugin = "BukkitGames")
public class BukkitGamesVariables extends DefaultReplacers<Plugin> {
private final BukkitGamesAPI bukkitGamesAPI = BukkitGamesAPI.getApi();
| // Path: variables/src/main/java/com/github/games647/scoreboardstats/variables/DefaultReplacers.java
// public abstract class DefaultReplacers<T extends Plugin> {
//
// protected final ReplacerAPI replaceManager;
// protected final T plugin;
//
// public DefaultReplacers(ReplacerAPI replaceManager, T plugin) {
// this.replaceManager = replaceManager;
// this.plugin = plugin;
// }
//
// /**
// * Register all variables that this class can manage
// */
// public abstract void register();
//
// /**
// * Shortcut method to register the variables without the boilerplate of adding the plugin instance and registering
// * it to the manager.
// *
// * @param variable variable name like "online"
// * @return the replacer responsible for this single variable
// */
// protected Replacer register(String variable) {
// Replacer replacer = new Replacer(plugin, variable);
// replaceManager.register(replacer);
// return replacer;
// }
// }
//
// Path: variables/src/main/java/com/github/games647/scoreboardstats/variables/ReplacerAPI.java
// public abstract class ReplacerAPI {
//
// protected final Logger logger;
// protected final Map<String, Replacer> replacers = Maps.newHashMap();
//
// public ReplacerAPI(Logger logger) {
// this.logger = logger;
// }
//
// public void register(Replacer replacer) {
// replacers.put(replacer.getVariable(), replacer);
//
// for (EventReplacer<? extends Event> eventReplacer : replacer.getEventsReplacers().values()) {
// Class<? extends Event> eventClass = eventReplacer.getEventClass();
// Plugin plugin = replacer.getPlugin();
//
// EventExecutor executor = (listener, event) -> eventReplacer.execute(this, event);
//
// Listener listener = new Listener() {};
//
// PluginManager pluginManager = Bukkit.getPluginManager();
// pluginManager.registerEvent(eventClass, listener, HIGHEST, executor, plugin, true);
// }
// }
//
// public void unregister(String variable) {
// replacers.remove(variable);
// }
//
// public void unregisterAll(Plugin disablePlugin) {
// Iterator<Replacer> iterator = replacers.values().iterator();
// while (iterator.hasNext()) {
// Plugin plugin = iterator.next().getPlugin();
// if (plugin == disablePlugin) {
// iterator.remove();
// }
// }
// }
//
// public void forceUpdate(String variable, int score) {
// Bukkit.getOnlinePlayers().forEach(player -> forceUpdate(player, variable, score));
// }
//
// public void forceUpdate(String variable, String value) {
// Bukkit.getOnlinePlayers().forEach(player -> forceUpdate(player, variable, value));
// }
//
// public abstract void forceUpdate(Player player, String variable, int score);
//
// public abstract void forceUpdate(Player player, String variable, String value);
//
// public Optional<String> replace(Player player, String variable, boolean complete) throws ReplacerException {
// Replacer replacer = getReplacer(variable);
// if (!complete && replacer.isGlobal() || replacer.isEventVariable() || replacer.isConstant()) {
// return Optional.empty();
// }
//
// try {
// return Optional.of(replacer.replace(player));
// } catch (Exception ex) {
// throw new ReplacerException(ex);
// }
// }
//
// public OptionalInt scoreReplace(Player player, String variable, boolean complete) throws ReplacerException {
// Replacer replacer = getReplacer(variable);
// if (!complete && replacer.isGlobal() || replacer.isEventVariable() || replacer.isConstant()) {
// return OptionalInt.empty();
// }
//
// try {
// return OptionalInt.of(replacer.scoreReplace(player));
// } catch (Exception ex) {
// throw new ReplacerException(ex);
// }
// }
//
// private Replacer getReplacer(String variable) throws UnknownVariableException {
// Replacer replacer = this.replacers.get(variable);
// if (replacer == null) {
// throw new UnknownVariableException(variable);
// }
//
// return replacer;
// }
// }
// Path: defaults/src/main/java/com/github/games647/scoreboardstats/defaults/BukkitGamesVariables.java
import com.github.games647.scoreboardstats.variables.DefaultReplacer;
import com.github.games647.scoreboardstats.variables.DefaultReplacers;
import com.github.games647.scoreboardstats.variables.ReplacerAPI;
import de.ftbastler.bukkitgames.api.BukkitGamesAPI;
import de.ftbastler.bukkitgames.api.PlayerBuyKitEvent;
import org.bukkit.plugin.Plugin;
package com.github.games647.scoreboardstats.defaults;
@DefaultReplacer(plugin = "BukkitGames")
public class BukkitGamesVariables extends DefaultReplacers<Plugin> {
private final BukkitGamesAPI bukkitGamesAPI = BukkitGamesAPI.getApi();
| public BukkitGamesVariables(ReplacerAPI replaceManager, Plugin plugin) { |
games647/ScoreboardStats | defaults/src/main/java/com/github/games647/scoreboardstats/defaults/BungeeCordVariables.java | // Path: variables/src/main/java/com/github/games647/scoreboardstats/variables/DefaultReplacers.java
// public abstract class DefaultReplacers<T extends Plugin> {
//
// protected final ReplacerAPI replaceManager;
// protected final T plugin;
//
// public DefaultReplacers(ReplacerAPI replaceManager, T plugin) {
// this.replaceManager = replaceManager;
// this.plugin = plugin;
// }
//
// /**
// * Register all variables that this class can manage
// */
// public abstract void register();
//
// /**
// * Shortcut method to register the variables without the boilerplate of adding the plugin instance and registering
// * it to the manager.
// *
// * @param variable variable name like "online"
// * @return the replacer responsible for this single variable
// */
// protected Replacer register(String variable) {
// Replacer replacer = new Replacer(plugin, variable);
// replaceManager.register(replacer);
// return replacer;
// }
// }
//
// Path: variables/src/main/java/com/github/games647/scoreboardstats/variables/ReplacerAPI.java
// public abstract class ReplacerAPI {
//
// protected final Logger logger;
// protected final Map<String, Replacer> replacers = Maps.newHashMap();
//
// public ReplacerAPI(Logger logger) {
// this.logger = logger;
// }
//
// public void register(Replacer replacer) {
// replacers.put(replacer.getVariable(), replacer);
//
// for (EventReplacer<? extends Event> eventReplacer : replacer.getEventsReplacers().values()) {
// Class<? extends Event> eventClass = eventReplacer.getEventClass();
// Plugin plugin = replacer.getPlugin();
//
// EventExecutor executor = (listener, event) -> eventReplacer.execute(this, event);
//
// Listener listener = new Listener() {};
//
// PluginManager pluginManager = Bukkit.getPluginManager();
// pluginManager.registerEvent(eventClass, listener, HIGHEST, executor, plugin, true);
// }
// }
//
// public void unregister(String variable) {
// replacers.remove(variable);
// }
//
// public void unregisterAll(Plugin disablePlugin) {
// Iterator<Replacer> iterator = replacers.values().iterator();
// while (iterator.hasNext()) {
// Plugin plugin = iterator.next().getPlugin();
// if (plugin == disablePlugin) {
// iterator.remove();
// }
// }
// }
//
// public void forceUpdate(String variable, int score) {
// Bukkit.getOnlinePlayers().forEach(player -> forceUpdate(player, variable, score));
// }
//
// public void forceUpdate(String variable, String value) {
// Bukkit.getOnlinePlayers().forEach(player -> forceUpdate(player, variable, value));
// }
//
// public abstract void forceUpdate(Player player, String variable, int score);
//
// public abstract void forceUpdate(Player player, String variable, String value);
//
// public Optional<String> replace(Player player, String variable, boolean complete) throws ReplacerException {
// Replacer replacer = getReplacer(variable);
// if (!complete && replacer.isGlobal() || replacer.isEventVariable() || replacer.isConstant()) {
// return Optional.empty();
// }
//
// try {
// return Optional.of(replacer.replace(player));
// } catch (Exception ex) {
// throw new ReplacerException(ex);
// }
// }
//
// public OptionalInt scoreReplace(Player player, String variable, boolean complete) throws ReplacerException {
// Replacer replacer = getReplacer(variable);
// if (!complete && replacer.isGlobal() || replacer.isEventVariable() || replacer.isConstant()) {
// return OptionalInt.empty();
// }
//
// try {
// return OptionalInt.of(replacer.scoreReplace(player));
// } catch (Exception ex) {
// throw new ReplacerException(ex);
// }
// }
//
// private Replacer getReplacer(String variable) throws UnknownVariableException {
// Replacer replacer = this.replacers.get(variable);
// if (replacer == null) {
// throw new UnknownVariableException(variable);
// }
//
// return replacer;
// }
// }
| import com.github.games647.scoreboardstats.variables.DefaultReplacer;
import com.github.games647.scoreboardstats.variables.DefaultReplacers;
import com.github.games647.scoreboardstats.variables.ReplacerAPI;
import com.google.common.collect.Iterables;
import com.google.common.io.ByteArrayDataInput;
import com.google.common.io.ByteArrayDataOutput;
import com.google.common.io.ByteStreams;
import org.bukkit.Bukkit;
import org.bukkit.entity.Player;
import org.bukkit.plugin.Plugin;
import org.bukkit.plugin.messaging.Messenger;
import org.bukkit.plugin.messaging.PluginMessageListener; | package com.github.games647.scoreboardstats.defaults;
@DefaultReplacer
public class BungeeCordVariables extends DefaultReplacers<Plugin> implements PluginMessageListener, Runnable {
private static final int UPDATE_INTERVAL = 20 * 30;
private static final String BUNGEE_CHANNEL = "BungeeCord";
private int onlinePlayers;
| // Path: variables/src/main/java/com/github/games647/scoreboardstats/variables/DefaultReplacers.java
// public abstract class DefaultReplacers<T extends Plugin> {
//
// protected final ReplacerAPI replaceManager;
// protected final T plugin;
//
// public DefaultReplacers(ReplacerAPI replaceManager, T plugin) {
// this.replaceManager = replaceManager;
// this.plugin = plugin;
// }
//
// /**
// * Register all variables that this class can manage
// */
// public abstract void register();
//
// /**
// * Shortcut method to register the variables without the boilerplate of adding the plugin instance and registering
// * it to the manager.
// *
// * @param variable variable name like "online"
// * @return the replacer responsible for this single variable
// */
// protected Replacer register(String variable) {
// Replacer replacer = new Replacer(plugin, variable);
// replaceManager.register(replacer);
// return replacer;
// }
// }
//
// Path: variables/src/main/java/com/github/games647/scoreboardstats/variables/ReplacerAPI.java
// public abstract class ReplacerAPI {
//
// protected final Logger logger;
// protected final Map<String, Replacer> replacers = Maps.newHashMap();
//
// public ReplacerAPI(Logger logger) {
// this.logger = logger;
// }
//
// public void register(Replacer replacer) {
// replacers.put(replacer.getVariable(), replacer);
//
// for (EventReplacer<? extends Event> eventReplacer : replacer.getEventsReplacers().values()) {
// Class<? extends Event> eventClass = eventReplacer.getEventClass();
// Plugin plugin = replacer.getPlugin();
//
// EventExecutor executor = (listener, event) -> eventReplacer.execute(this, event);
//
// Listener listener = new Listener() {};
//
// PluginManager pluginManager = Bukkit.getPluginManager();
// pluginManager.registerEvent(eventClass, listener, HIGHEST, executor, plugin, true);
// }
// }
//
// public void unregister(String variable) {
// replacers.remove(variable);
// }
//
// public void unregisterAll(Plugin disablePlugin) {
// Iterator<Replacer> iterator = replacers.values().iterator();
// while (iterator.hasNext()) {
// Plugin plugin = iterator.next().getPlugin();
// if (plugin == disablePlugin) {
// iterator.remove();
// }
// }
// }
//
// public void forceUpdate(String variable, int score) {
// Bukkit.getOnlinePlayers().forEach(player -> forceUpdate(player, variable, score));
// }
//
// public void forceUpdate(String variable, String value) {
// Bukkit.getOnlinePlayers().forEach(player -> forceUpdate(player, variable, value));
// }
//
// public abstract void forceUpdate(Player player, String variable, int score);
//
// public abstract void forceUpdate(Player player, String variable, String value);
//
// public Optional<String> replace(Player player, String variable, boolean complete) throws ReplacerException {
// Replacer replacer = getReplacer(variable);
// if (!complete && replacer.isGlobal() || replacer.isEventVariable() || replacer.isConstant()) {
// return Optional.empty();
// }
//
// try {
// return Optional.of(replacer.replace(player));
// } catch (Exception ex) {
// throw new ReplacerException(ex);
// }
// }
//
// public OptionalInt scoreReplace(Player player, String variable, boolean complete) throws ReplacerException {
// Replacer replacer = getReplacer(variable);
// if (!complete && replacer.isGlobal() || replacer.isEventVariable() || replacer.isConstant()) {
// return OptionalInt.empty();
// }
//
// try {
// return OptionalInt.of(replacer.scoreReplace(player));
// } catch (Exception ex) {
// throw new ReplacerException(ex);
// }
// }
//
// private Replacer getReplacer(String variable) throws UnknownVariableException {
// Replacer replacer = this.replacers.get(variable);
// if (replacer == null) {
// throw new UnknownVariableException(variable);
// }
//
// return replacer;
// }
// }
// Path: defaults/src/main/java/com/github/games647/scoreboardstats/defaults/BungeeCordVariables.java
import com.github.games647.scoreboardstats.variables.DefaultReplacer;
import com.github.games647.scoreboardstats.variables.DefaultReplacers;
import com.github.games647.scoreboardstats.variables.ReplacerAPI;
import com.google.common.collect.Iterables;
import com.google.common.io.ByteArrayDataInput;
import com.google.common.io.ByteArrayDataOutput;
import com.google.common.io.ByteStreams;
import org.bukkit.Bukkit;
import org.bukkit.entity.Player;
import org.bukkit.plugin.Plugin;
import org.bukkit.plugin.messaging.Messenger;
import org.bukkit.plugin.messaging.PluginMessageListener;
package com.github.games647.scoreboardstats.defaults;
@DefaultReplacer
public class BungeeCordVariables extends DefaultReplacers<Plugin> implements PluginMessageListener, Runnable {
private static final int UPDATE_INTERVAL = 20 * 30;
private static final String BUNGEE_CHANNEL = "BungeeCord";
private int onlinePlayers;
| public BungeeCordVariables(ReplacerAPI replaceManager, Plugin plugin) { |
games647/ScoreboardStats | defaults/src/main/java/com/github/games647/scoreboardstats/defaults/PlayerPointsVariables.java | // Path: variables/src/main/java/com/github/games647/scoreboardstats/variables/DefaultReplacers.java
// public abstract class DefaultReplacers<T extends Plugin> {
//
// protected final ReplacerAPI replaceManager;
// protected final T plugin;
//
// public DefaultReplacers(ReplacerAPI replaceManager, T plugin) {
// this.replaceManager = replaceManager;
// this.plugin = plugin;
// }
//
// /**
// * Register all variables that this class can manage
// */
// public abstract void register();
//
// /**
// * Shortcut method to register the variables without the boilerplate of adding the plugin instance and registering
// * it to the manager.
// *
// * @param variable variable name like "online"
// * @return the replacer responsible for this single variable
// */
// protected Replacer register(String variable) {
// Replacer replacer = new Replacer(plugin, variable);
// replaceManager.register(replacer);
// return replacer;
// }
// }
//
// Path: variables/src/main/java/com/github/games647/scoreboardstats/variables/ReplacerAPI.java
// public abstract class ReplacerAPI {
//
// protected final Logger logger;
// protected final Map<String, Replacer> replacers = Maps.newHashMap();
//
// public ReplacerAPI(Logger logger) {
// this.logger = logger;
// }
//
// public void register(Replacer replacer) {
// replacers.put(replacer.getVariable(), replacer);
//
// for (EventReplacer<? extends Event> eventReplacer : replacer.getEventsReplacers().values()) {
// Class<? extends Event> eventClass = eventReplacer.getEventClass();
// Plugin plugin = replacer.getPlugin();
//
// EventExecutor executor = (listener, event) -> eventReplacer.execute(this, event);
//
// Listener listener = new Listener() {};
//
// PluginManager pluginManager = Bukkit.getPluginManager();
// pluginManager.registerEvent(eventClass, listener, HIGHEST, executor, plugin, true);
// }
// }
//
// public void unregister(String variable) {
// replacers.remove(variable);
// }
//
// public void unregisterAll(Plugin disablePlugin) {
// Iterator<Replacer> iterator = replacers.values().iterator();
// while (iterator.hasNext()) {
// Plugin plugin = iterator.next().getPlugin();
// if (plugin == disablePlugin) {
// iterator.remove();
// }
// }
// }
//
// public void forceUpdate(String variable, int score) {
// Bukkit.getOnlinePlayers().forEach(player -> forceUpdate(player, variable, score));
// }
//
// public void forceUpdate(String variable, String value) {
// Bukkit.getOnlinePlayers().forEach(player -> forceUpdate(player, variable, value));
// }
//
// public abstract void forceUpdate(Player player, String variable, int score);
//
// public abstract void forceUpdate(Player player, String variable, String value);
//
// public Optional<String> replace(Player player, String variable, boolean complete) throws ReplacerException {
// Replacer replacer = getReplacer(variable);
// if (!complete && replacer.isGlobal() || replacer.isEventVariable() || replacer.isConstant()) {
// return Optional.empty();
// }
//
// try {
// return Optional.of(replacer.replace(player));
// } catch (Exception ex) {
// throw new ReplacerException(ex);
// }
// }
//
// public OptionalInt scoreReplace(Player player, String variable, boolean complete) throws ReplacerException {
// Replacer replacer = getReplacer(variable);
// if (!complete && replacer.isGlobal() || replacer.isEventVariable() || replacer.isConstant()) {
// return OptionalInt.empty();
// }
//
// try {
// return OptionalInt.of(replacer.scoreReplace(player));
// } catch (Exception ex) {
// throw new ReplacerException(ex);
// }
// }
//
// private Replacer getReplacer(String variable) throws UnknownVariableException {
// Replacer replacer = this.replacers.get(variable);
// if (replacer == null) {
// throw new UnknownVariableException(variable);
// }
//
// return replacer;
// }
// }
| import com.github.games647.scoreboardstats.variables.DefaultReplacer;
import com.github.games647.scoreboardstats.variables.DefaultReplacers;
import com.github.games647.scoreboardstats.variables.ReplacerAPI;
import org.black_ixx.playerpoints.PlayerPoints;
import org.black_ixx.playerpoints.event.PlayerPointsChangeEvent;
import org.black_ixx.playerpoints.event.PlayerPointsResetEvent; | package com.github.games647.scoreboardstats.defaults;
/**
* Represents a replacer for the Plugin PlayerPoints
* <p>
* https://dev.bukkit.org/bukkit-plugins/playerpoints/
*/
@DefaultReplacer(plugin = "PlayerPoints")
public class PlayerPointsVariables extends DefaultReplacers<PlayerPoints> {
| // Path: variables/src/main/java/com/github/games647/scoreboardstats/variables/DefaultReplacers.java
// public abstract class DefaultReplacers<T extends Plugin> {
//
// protected final ReplacerAPI replaceManager;
// protected final T plugin;
//
// public DefaultReplacers(ReplacerAPI replaceManager, T plugin) {
// this.replaceManager = replaceManager;
// this.plugin = plugin;
// }
//
// /**
// * Register all variables that this class can manage
// */
// public abstract void register();
//
// /**
// * Shortcut method to register the variables without the boilerplate of adding the plugin instance and registering
// * it to the manager.
// *
// * @param variable variable name like "online"
// * @return the replacer responsible for this single variable
// */
// protected Replacer register(String variable) {
// Replacer replacer = new Replacer(plugin, variable);
// replaceManager.register(replacer);
// return replacer;
// }
// }
//
// Path: variables/src/main/java/com/github/games647/scoreboardstats/variables/ReplacerAPI.java
// public abstract class ReplacerAPI {
//
// protected final Logger logger;
// protected final Map<String, Replacer> replacers = Maps.newHashMap();
//
// public ReplacerAPI(Logger logger) {
// this.logger = logger;
// }
//
// public void register(Replacer replacer) {
// replacers.put(replacer.getVariable(), replacer);
//
// for (EventReplacer<? extends Event> eventReplacer : replacer.getEventsReplacers().values()) {
// Class<? extends Event> eventClass = eventReplacer.getEventClass();
// Plugin plugin = replacer.getPlugin();
//
// EventExecutor executor = (listener, event) -> eventReplacer.execute(this, event);
//
// Listener listener = new Listener() {};
//
// PluginManager pluginManager = Bukkit.getPluginManager();
// pluginManager.registerEvent(eventClass, listener, HIGHEST, executor, plugin, true);
// }
// }
//
// public void unregister(String variable) {
// replacers.remove(variable);
// }
//
// public void unregisterAll(Plugin disablePlugin) {
// Iterator<Replacer> iterator = replacers.values().iterator();
// while (iterator.hasNext()) {
// Plugin plugin = iterator.next().getPlugin();
// if (plugin == disablePlugin) {
// iterator.remove();
// }
// }
// }
//
// public void forceUpdate(String variable, int score) {
// Bukkit.getOnlinePlayers().forEach(player -> forceUpdate(player, variable, score));
// }
//
// public void forceUpdate(String variable, String value) {
// Bukkit.getOnlinePlayers().forEach(player -> forceUpdate(player, variable, value));
// }
//
// public abstract void forceUpdate(Player player, String variable, int score);
//
// public abstract void forceUpdate(Player player, String variable, String value);
//
// public Optional<String> replace(Player player, String variable, boolean complete) throws ReplacerException {
// Replacer replacer = getReplacer(variable);
// if (!complete && replacer.isGlobal() || replacer.isEventVariable() || replacer.isConstant()) {
// return Optional.empty();
// }
//
// try {
// return Optional.of(replacer.replace(player));
// } catch (Exception ex) {
// throw new ReplacerException(ex);
// }
// }
//
// public OptionalInt scoreReplace(Player player, String variable, boolean complete) throws ReplacerException {
// Replacer replacer = getReplacer(variable);
// if (!complete && replacer.isGlobal() || replacer.isEventVariable() || replacer.isConstant()) {
// return OptionalInt.empty();
// }
//
// try {
// return OptionalInt.of(replacer.scoreReplace(player));
// } catch (Exception ex) {
// throw new ReplacerException(ex);
// }
// }
//
// private Replacer getReplacer(String variable) throws UnknownVariableException {
// Replacer replacer = this.replacers.get(variable);
// if (replacer == null) {
// throw new UnknownVariableException(variable);
// }
//
// return replacer;
// }
// }
// Path: defaults/src/main/java/com/github/games647/scoreboardstats/defaults/PlayerPointsVariables.java
import com.github.games647.scoreboardstats.variables.DefaultReplacer;
import com.github.games647.scoreboardstats.variables.DefaultReplacers;
import com.github.games647.scoreboardstats.variables.ReplacerAPI;
import org.black_ixx.playerpoints.PlayerPoints;
import org.black_ixx.playerpoints.event.PlayerPointsChangeEvent;
import org.black_ixx.playerpoints.event.PlayerPointsResetEvent;
package com.github.games647.scoreboardstats.defaults;
/**
* Represents a replacer for the Plugin PlayerPoints
* <p>
* https://dev.bukkit.org/bukkit-plugins/playerpoints/
*/
@DefaultReplacer(plugin = "PlayerPoints")
public class PlayerPointsVariables extends DefaultReplacers<PlayerPoints> {
| public PlayerPointsVariables(ReplacerAPI replaceManager, PlayerPoints plugin) { |
games647/ScoreboardStats | pvp/src/main/java/com/github/games647/scoreboardstats/pvp/StatsLoader.java | // Path: variables/src/main/java/com/github/games647/scoreboardstats/variables/ReplaceManager.java
// public class ReplaceManager extends ReplacerAPI {
//
// private static final String UNSUPPORTED_VERSION = "The Replacer: {} cannot be registered -" +
// " the plugin version isn't supported {} {}";
//
// //todo: only temporarily
// @Deprecated
// private static ReplaceManager instance;
// private final Plugin plugin;
// private final BoardManager boardManager;
//
// /**
// * Creates a new replace manager
// *
// * @param scoreboardManager to manage the scoreboards
// * @param plugin ScoreboardStats plugin
// */
// public ReplaceManager(BoardManager scoreboardManager, Plugin plugin, Logger logger) {
// super(logger);
//
// instance = this;
//
// this.plugin = plugin;
// this.boardManager = scoreboardManager;
//
// Bukkit.getPluginManager().registerEvents(new PluginListener(this), plugin);
// addDefaultReplacers();
// }
//
// @Deprecated
// public static ReplaceManager getInstance() {
// return instance;
// }
//
// public void close() {
// instance = null;
// }
//
// @Override
// public void forceUpdate(Player player, String variable, int score) {
// boardManager.updateVariable(player, variable, score);
// }
//
// @Override
// public void forceUpdate(Player player, String variable, String value) {
// boardManager.updateVariable(player, variable, value);
// }
//
// public void updateGlobals() {
// replacers.values()
// .stream()
// .filter(Replacer::isGlobal)
// .filter(replacer -> !replacer.isEventVariable())
// .forEach(replacer -> {
// int score = replacer.scoreReplace(null);
// String variable = replacer.getVariable();
// Bukkit.getOnlinePlayers().forEach(player -> boardManager.updateVariable(player, variable, score));
// });
// }
//
// private void addDefaultReplacers() {
// Set<String> defaultReplacers = Sets.newHashSet();
// try {
// defaultReplacers = ClassPath.from(getClass().getClassLoader())
// .getTopLevelClasses("com.github.games647.scoreboardstats.defaults")
// .stream()
// .map(ClassInfo::load)
// .filter(DefaultReplacers.class::isAssignableFrom)
// .map(clazz -> (Class<DefaultReplacers<?>>) clazz)
// .filter(this::registerDefault)
// .map(Class::getSimpleName)
// .collect(Collectors.toSet());
// } catch (IOException ioEx) {
// logger.error("Failed to register replacers", ioEx);
// }
//
// logger.info("Registered default replacers: {}", defaultReplacers);
// }
//
// private boolean registerDefault(Class<DefaultReplacers<?>> replacerClass) {
// try {
// DefaultReplacer annotation = replacerClass.getAnnotation(DefaultReplacer.class);
//
// String replacerPluginName = annotation.plugin();
// if (replacerPluginName.isEmpty()) {
// replacerPluginName = plugin.getName();
// }
//
// Plugin replacerPlugin = Bukkit.getPluginManager().getPlugin(replacerPluginName);
// if (replacerPlugin != null) {
// String required = annotation.requiredVersion();
// String version = replacerPlugin.getDescription().getVersion();
// if (!required.isEmpty() && new Version(version).compareTo(new Version(required)) >= 0) {
// logger.info(UNSUPPORTED_VERSION, replacerClass.getSimpleName(), version, required);
// return false;
// }
//
// Constructor<DefaultReplacers<?>> cons = replacerClass.getConstructor(ReplacerAPI.class, Plugin.class);
// cons.newInstance(this, replacerPlugin).register();
// }
//
// return true;
// } catch (Exception | LinkageError replacerException) {
// //only catch this throwable, because they could probably happened
// logger.warn("Cannot register replacer", replacerException);
// }
//
// return false;
// }
// }
| import com.github.games647.scoreboardstats.variables.ReplaceManager;
import java.lang.ref.WeakReference;
import java.time.Instant;
import org.apache.commons.lang.builder.ToStringBuilder;
import org.bukkit.Bukkit;
import org.bukkit.entity.Player;
import org.bukkit.metadata.FixedMetadataValue;
import org.bukkit.plugin.Plugin; | package com.github.games647.scoreboardstats.pvp;
/**
* This class is used for loading the player stats.
*/
public class StatsLoader implements Runnable {
private final Plugin plugin;
private final WeakReference<Player> weakPlayer;
private final WeakReference<Database> weakDatabase;
/**
* Creates a new loader for a specific player
*
* @param plugin the owning plugin to reschedule
* @param player player instance
* @param statsDatabase the pvp database
*/
public StatsLoader(Plugin plugin, Player player, Database statsDatabase) {
this.plugin = plugin;
//don't prevent the garbage collection of this player if he logs out
this.weakPlayer = new WeakReference<>(player);
this.weakDatabase = new WeakReference<>(statsDatabase);
}
@Override
public void run() {
final Player player = weakPlayer.get();
Database statsDatabase = weakDatabase.get();
if (player != null && statsDatabase != null) {
PlayerStats stats = statsDatabase.loadAccount(player)
.orElse(new PlayerStats(player.getUniqueId(), player.getName()));
//update player name on every load, because it's changeable
stats.setPlayername(player.getName());
stats.setLastOnline(Instant.now());
Bukkit.getScheduler().runTask(plugin, () -> {
//possible not thread-safe, so reschedule it while setMetadata is thread-safe
if (player.isOnline()) {
//sets it only if the player is only
player.setMetadata("player_stats", new FixedMetadataValue(plugin, stats)); | // Path: variables/src/main/java/com/github/games647/scoreboardstats/variables/ReplaceManager.java
// public class ReplaceManager extends ReplacerAPI {
//
// private static final String UNSUPPORTED_VERSION = "The Replacer: {} cannot be registered -" +
// " the plugin version isn't supported {} {}";
//
// //todo: only temporarily
// @Deprecated
// private static ReplaceManager instance;
// private final Plugin plugin;
// private final BoardManager boardManager;
//
// /**
// * Creates a new replace manager
// *
// * @param scoreboardManager to manage the scoreboards
// * @param plugin ScoreboardStats plugin
// */
// public ReplaceManager(BoardManager scoreboardManager, Plugin plugin, Logger logger) {
// super(logger);
//
// instance = this;
//
// this.plugin = plugin;
// this.boardManager = scoreboardManager;
//
// Bukkit.getPluginManager().registerEvents(new PluginListener(this), plugin);
// addDefaultReplacers();
// }
//
// @Deprecated
// public static ReplaceManager getInstance() {
// return instance;
// }
//
// public void close() {
// instance = null;
// }
//
// @Override
// public void forceUpdate(Player player, String variable, int score) {
// boardManager.updateVariable(player, variable, score);
// }
//
// @Override
// public void forceUpdate(Player player, String variable, String value) {
// boardManager.updateVariable(player, variable, value);
// }
//
// public void updateGlobals() {
// replacers.values()
// .stream()
// .filter(Replacer::isGlobal)
// .filter(replacer -> !replacer.isEventVariable())
// .forEach(replacer -> {
// int score = replacer.scoreReplace(null);
// String variable = replacer.getVariable();
// Bukkit.getOnlinePlayers().forEach(player -> boardManager.updateVariable(player, variable, score));
// });
// }
//
// private void addDefaultReplacers() {
// Set<String> defaultReplacers = Sets.newHashSet();
// try {
// defaultReplacers = ClassPath.from(getClass().getClassLoader())
// .getTopLevelClasses("com.github.games647.scoreboardstats.defaults")
// .stream()
// .map(ClassInfo::load)
// .filter(DefaultReplacers.class::isAssignableFrom)
// .map(clazz -> (Class<DefaultReplacers<?>>) clazz)
// .filter(this::registerDefault)
// .map(Class::getSimpleName)
// .collect(Collectors.toSet());
// } catch (IOException ioEx) {
// logger.error("Failed to register replacers", ioEx);
// }
//
// logger.info("Registered default replacers: {}", defaultReplacers);
// }
//
// private boolean registerDefault(Class<DefaultReplacers<?>> replacerClass) {
// try {
// DefaultReplacer annotation = replacerClass.getAnnotation(DefaultReplacer.class);
//
// String replacerPluginName = annotation.plugin();
// if (replacerPluginName.isEmpty()) {
// replacerPluginName = plugin.getName();
// }
//
// Plugin replacerPlugin = Bukkit.getPluginManager().getPlugin(replacerPluginName);
// if (replacerPlugin != null) {
// String required = annotation.requiredVersion();
// String version = replacerPlugin.getDescription().getVersion();
// if (!required.isEmpty() && new Version(version).compareTo(new Version(required)) >= 0) {
// logger.info(UNSUPPORTED_VERSION, replacerClass.getSimpleName(), version, required);
// return false;
// }
//
// Constructor<DefaultReplacers<?>> cons = replacerClass.getConstructor(ReplacerAPI.class, Plugin.class);
// cons.newInstance(this, replacerPlugin).register();
// }
//
// return true;
// } catch (Exception | LinkageError replacerException) {
// //only catch this throwable, because they could probably happened
// logger.warn("Cannot register replacer", replacerException);
// }
//
// return false;
// }
// }
// Path: pvp/src/main/java/com/github/games647/scoreboardstats/pvp/StatsLoader.java
import com.github.games647.scoreboardstats.variables.ReplaceManager;
import java.lang.ref.WeakReference;
import java.time.Instant;
import org.apache.commons.lang.builder.ToStringBuilder;
import org.bukkit.Bukkit;
import org.bukkit.entity.Player;
import org.bukkit.metadata.FixedMetadataValue;
import org.bukkit.plugin.Plugin;
package com.github.games647.scoreboardstats.pvp;
/**
* This class is used for loading the player stats.
*/
public class StatsLoader implements Runnable {
private final Plugin plugin;
private final WeakReference<Player> weakPlayer;
private final WeakReference<Database> weakDatabase;
/**
* Creates a new loader for a specific player
*
* @param plugin the owning plugin to reschedule
* @param player player instance
* @param statsDatabase the pvp database
*/
public StatsLoader(Plugin plugin, Player player, Database statsDatabase) {
this.plugin = plugin;
//don't prevent the garbage collection of this player if he logs out
this.weakPlayer = new WeakReference<>(player);
this.weakDatabase = new WeakReference<>(statsDatabase);
}
@Override
public void run() {
final Player player = weakPlayer.get();
Database statsDatabase = weakDatabase.get();
if (player != null && statsDatabase != null) {
PlayerStats stats = statsDatabase.loadAccount(player)
.orElse(new PlayerStats(player.getUniqueId(), player.getName()));
//update player name on every load, because it's changeable
stats.setPlayername(player.getName());
stats.setLastOnline(Instant.now());
Bukkit.getScheduler().runTask(plugin, () -> {
//possible not thread-safe, so reschedule it while setMetadata is thread-safe
if (player.isOnline()) {
//sets it only if the player is only
player.setMetadata("player_stats", new FixedMetadataValue(plugin, stats)); | ReplaceManager.getInstance().forceUpdate(player, "deaths", stats.getDeaths()); |
games647/ScoreboardStats | defaults/src/main/java/com/github/games647/scoreboardstats/defaults/PlayerPingVariable.java | // Path: variables/src/main/java/com/github/games647/scoreboardstats/variables/DefaultReplacers.java
// public abstract class DefaultReplacers<T extends Plugin> {
//
// protected final ReplacerAPI replaceManager;
// protected final T plugin;
//
// public DefaultReplacers(ReplacerAPI replaceManager, T plugin) {
// this.replaceManager = replaceManager;
// this.plugin = plugin;
// }
//
// /**
// * Register all variables that this class can manage
// */
// public abstract void register();
//
// /**
// * Shortcut method to register the variables without the boilerplate of adding the plugin instance and registering
// * it to the manager.
// *
// * @param variable variable name like "online"
// * @return the replacer responsible for this single variable
// */
// protected Replacer register(String variable) {
// Replacer replacer = new Replacer(plugin, variable);
// replaceManager.register(replacer);
// return replacer;
// }
// }
//
// Path: variables/src/main/java/com/github/games647/scoreboardstats/variables/ReplacerAPI.java
// public abstract class ReplacerAPI {
//
// protected final Logger logger;
// protected final Map<String, Replacer> replacers = Maps.newHashMap();
//
// public ReplacerAPI(Logger logger) {
// this.logger = logger;
// }
//
// public void register(Replacer replacer) {
// replacers.put(replacer.getVariable(), replacer);
//
// for (EventReplacer<? extends Event> eventReplacer : replacer.getEventsReplacers().values()) {
// Class<? extends Event> eventClass = eventReplacer.getEventClass();
// Plugin plugin = replacer.getPlugin();
//
// EventExecutor executor = (listener, event) -> eventReplacer.execute(this, event);
//
// Listener listener = new Listener() {};
//
// PluginManager pluginManager = Bukkit.getPluginManager();
// pluginManager.registerEvent(eventClass, listener, HIGHEST, executor, plugin, true);
// }
// }
//
// public void unregister(String variable) {
// replacers.remove(variable);
// }
//
// public void unregisterAll(Plugin disablePlugin) {
// Iterator<Replacer> iterator = replacers.values().iterator();
// while (iterator.hasNext()) {
// Plugin plugin = iterator.next().getPlugin();
// if (plugin == disablePlugin) {
// iterator.remove();
// }
// }
// }
//
// public void forceUpdate(String variable, int score) {
// Bukkit.getOnlinePlayers().forEach(player -> forceUpdate(player, variable, score));
// }
//
// public void forceUpdate(String variable, String value) {
// Bukkit.getOnlinePlayers().forEach(player -> forceUpdate(player, variable, value));
// }
//
// public abstract void forceUpdate(Player player, String variable, int score);
//
// public abstract void forceUpdate(Player player, String variable, String value);
//
// public Optional<String> replace(Player player, String variable, boolean complete) throws ReplacerException {
// Replacer replacer = getReplacer(variable);
// if (!complete && replacer.isGlobal() || replacer.isEventVariable() || replacer.isConstant()) {
// return Optional.empty();
// }
//
// try {
// return Optional.of(replacer.replace(player));
// } catch (Exception ex) {
// throw new ReplacerException(ex);
// }
// }
//
// public OptionalInt scoreReplace(Player player, String variable, boolean complete) throws ReplacerException {
// Replacer replacer = getReplacer(variable);
// if (!complete && replacer.isGlobal() || replacer.isEventVariable() || replacer.isConstant()) {
// return OptionalInt.empty();
// }
//
// try {
// return OptionalInt.of(replacer.scoreReplace(player));
// } catch (Exception ex) {
// throw new ReplacerException(ex);
// }
// }
//
// private Replacer getReplacer(String variable) throws UnknownVariableException {
// Replacer replacer = this.replacers.get(variable);
// if (replacer == null) {
// throw new UnknownVariableException(variable);
// }
//
// return replacer;
// }
// }
| import com.github.games647.scoreboardstats.variables.DefaultReplacer;
import com.github.games647.scoreboardstats.variables.DefaultReplacers;
import com.github.games647.scoreboardstats.variables.ReplacerAPI;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import org.bukkit.entity.Player;
import org.bukkit.plugin.Plugin; | package com.github.games647.scoreboardstats.defaults;
/**
* Replace the ping variable.
*/
@DefaultReplacer
public class PlayerPingVariable extends DefaultReplacers<Plugin> {
private Method getHandleMethod;
private Field pingField;
| // Path: variables/src/main/java/com/github/games647/scoreboardstats/variables/DefaultReplacers.java
// public abstract class DefaultReplacers<T extends Plugin> {
//
// protected final ReplacerAPI replaceManager;
// protected final T plugin;
//
// public DefaultReplacers(ReplacerAPI replaceManager, T plugin) {
// this.replaceManager = replaceManager;
// this.plugin = plugin;
// }
//
// /**
// * Register all variables that this class can manage
// */
// public abstract void register();
//
// /**
// * Shortcut method to register the variables without the boilerplate of adding the plugin instance and registering
// * it to the manager.
// *
// * @param variable variable name like "online"
// * @return the replacer responsible for this single variable
// */
// protected Replacer register(String variable) {
// Replacer replacer = new Replacer(plugin, variable);
// replaceManager.register(replacer);
// return replacer;
// }
// }
//
// Path: variables/src/main/java/com/github/games647/scoreboardstats/variables/ReplacerAPI.java
// public abstract class ReplacerAPI {
//
// protected final Logger logger;
// protected final Map<String, Replacer> replacers = Maps.newHashMap();
//
// public ReplacerAPI(Logger logger) {
// this.logger = logger;
// }
//
// public void register(Replacer replacer) {
// replacers.put(replacer.getVariable(), replacer);
//
// for (EventReplacer<? extends Event> eventReplacer : replacer.getEventsReplacers().values()) {
// Class<? extends Event> eventClass = eventReplacer.getEventClass();
// Plugin plugin = replacer.getPlugin();
//
// EventExecutor executor = (listener, event) -> eventReplacer.execute(this, event);
//
// Listener listener = new Listener() {};
//
// PluginManager pluginManager = Bukkit.getPluginManager();
// pluginManager.registerEvent(eventClass, listener, HIGHEST, executor, plugin, true);
// }
// }
//
// public void unregister(String variable) {
// replacers.remove(variable);
// }
//
// public void unregisterAll(Plugin disablePlugin) {
// Iterator<Replacer> iterator = replacers.values().iterator();
// while (iterator.hasNext()) {
// Plugin plugin = iterator.next().getPlugin();
// if (plugin == disablePlugin) {
// iterator.remove();
// }
// }
// }
//
// public void forceUpdate(String variable, int score) {
// Bukkit.getOnlinePlayers().forEach(player -> forceUpdate(player, variable, score));
// }
//
// public void forceUpdate(String variable, String value) {
// Bukkit.getOnlinePlayers().forEach(player -> forceUpdate(player, variable, value));
// }
//
// public abstract void forceUpdate(Player player, String variable, int score);
//
// public abstract void forceUpdate(Player player, String variable, String value);
//
// public Optional<String> replace(Player player, String variable, boolean complete) throws ReplacerException {
// Replacer replacer = getReplacer(variable);
// if (!complete && replacer.isGlobal() || replacer.isEventVariable() || replacer.isConstant()) {
// return Optional.empty();
// }
//
// try {
// return Optional.of(replacer.replace(player));
// } catch (Exception ex) {
// throw new ReplacerException(ex);
// }
// }
//
// public OptionalInt scoreReplace(Player player, String variable, boolean complete) throws ReplacerException {
// Replacer replacer = getReplacer(variable);
// if (!complete && replacer.isGlobal() || replacer.isEventVariable() || replacer.isConstant()) {
// return OptionalInt.empty();
// }
//
// try {
// return OptionalInt.of(replacer.scoreReplace(player));
// } catch (Exception ex) {
// throw new ReplacerException(ex);
// }
// }
//
// private Replacer getReplacer(String variable) throws UnknownVariableException {
// Replacer replacer = this.replacers.get(variable);
// if (replacer == null) {
// throw new UnknownVariableException(variable);
// }
//
// return replacer;
// }
// }
// Path: defaults/src/main/java/com/github/games647/scoreboardstats/defaults/PlayerPingVariable.java
import com.github.games647.scoreboardstats.variables.DefaultReplacer;
import com.github.games647.scoreboardstats.variables.DefaultReplacers;
import com.github.games647.scoreboardstats.variables.ReplacerAPI;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import org.bukkit.entity.Player;
import org.bukkit.plugin.Plugin;
package com.github.games647.scoreboardstats.defaults;
/**
* Replace the ping variable.
*/
@DefaultReplacer
public class PlayerPingVariable extends DefaultReplacers<Plugin> {
private Method getHandleMethod;
private Field pingField;
| public PlayerPingVariable(ReplacerAPI replaceManager, Plugin plugin) { |
games647/ScoreboardStats | defaults/src/main/java/com/github/games647/scoreboardstats/defaults/McCombatLevelVariables.java | // Path: variables/src/main/java/com/github/games647/scoreboardstats/variables/DefaultReplacers.java
// public abstract class DefaultReplacers<T extends Plugin> {
//
// protected final ReplacerAPI replaceManager;
// protected final T plugin;
//
// public DefaultReplacers(ReplacerAPI replaceManager, T plugin) {
// this.replaceManager = replaceManager;
// this.plugin = plugin;
// }
//
// /**
// * Register all variables that this class can manage
// */
// public abstract void register();
//
// /**
// * Shortcut method to register the variables without the boilerplate of adding the plugin instance and registering
// * it to the manager.
// *
// * @param variable variable name like "online"
// * @return the replacer responsible for this single variable
// */
// protected Replacer register(String variable) {
// Replacer replacer = new Replacer(plugin, variable);
// replaceManager.register(replacer);
// return replacer;
// }
// }
//
// Path: variables/src/main/java/com/github/games647/scoreboardstats/variables/ReplacerAPI.java
// public abstract class ReplacerAPI {
//
// protected final Logger logger;
// protected final Map<String, Replacer> replacers = Maps.newHashMap();
//
// public ReplacerAPI(Logger logger) {
// this.logger = logger;
// }
//
// public void register(Replacer replacer) {
// replacers.put(replacer.getVariable(), replacer);
//
// for (EventReplacer<? extends Event> eventReplacer : replacer.getEventsReplacers().values()) {
// Class<? extends Event> eventClass = eventReplacer.getEventClass();
// Plugin plugin = replacer.getPlugin();
//
// EventExecutor executor = (listener, event) -> eventReplacer.execute(this, event);
//
// Listener listener = new Listener() {};
//
// PluginManager pluginManager = Bukkit.getPluginManager();
// pluginManager.registerEvent(eventClass, listener, HIGHEST, executor, plugin, true);
// }
// }
//
// public void unregister(String variable) {
// replacers.remove(variable);
// }
//
// public void unregisterAll(Plugin disablePlugin) {
// Iterator<Replacer> iterator = replacers.values().iterator();
// while (iterator.hasNext()) {
// Plugin plugin = iterator.next().getPlugin();
// if (plugin == disablePlugin) {
// iterator.remove();
// }
// }
// }
//
// public void forceUpdate(String variable, int score) {
// Bukkit.getOnlinePlayers().forEach(player -> forceUpdate(player, variable, score));
// }
//
// public void forceUpdate(String variable, String value) {
// Bukkit.getOnlinePlayers().forEach(player -> forceUpdate(player, variable, value));
// }
//
// public abstract void forceUpdate(Player player, String variable, int score);
//
// public abstract void forceUpdate(Player player, String variable, String value);
//
// public Optional<String> replace(Player player, String variable, boolean complete) throws ReplacerException {
// Replacer replacer = getReplacer(variable);
// if (!complete && replacer.isGlobal() || replacer.isEventVariable() || replacer.isConstant()) {
// return Optional.empty();
// }
//
// try {
// return Optional.of(replacer.replace(player));
// } catch (Exception ex) {
// throw new ReplacerException(ex);
// }
// }
//
// public OptionalInt scoreReplace(Player player, String variable, boolean complete) throws ReplacerException {
// Replacer replacer = getReplacer(variable);
// if (!complete && replacer.isGlobal() || replacer.isEventVariable() || replacer.isConstant()) {
// return OptionalInt.empty();
// }
//
// try {
// return OptionalInt.of(replacer.scoreReplace(player));
// } catch (Exception ex) {
// throw new ReplacerException(ex);
// }
// }
//
// private Replacer getReplacer(String variable) throws UnknownVariableException {
// Replacer replacer = this.replacers.get(variable);
// if (replacer == null) {
// throw new UnknownVariableException(variable);
// }
//
// return replacer;
// }
// }
| import com.github.games647.scoreboardstats.variables.DefaultReplacer;
import com.github.games647.scoreboardstats.variables.DefaultReplacers;
import com.github.games647.scoreboardstats.variables.ReplacerAPI;
import com.gmail.mrphpfan.mccombatlevel.McCombatLevel;
import com.gmail.mrphpfan.mccombatlevel.PlayerCombatLevelChangeEvent; | package com.github.games647.scoreboardstats.defaults;
@DefaultReplacer(plugin = "mcCombatLevel")
public class McCombatLevelVariables extends DefaultReplacers<McCombatLevel> {
| // Path: variables/src/main/java/com/github/games647/scoreboardstats/variables/DefaultReplacers.java
// public abstract class DefaultReplacers<T extends Plugin> {
//
// protected final ReplacerAPI replaceManager;
// protected final T plugin;
//
// public DefaultReplacers(ReplacerAPI replaceManager, T plugin) {
// this.replaceManager = replaceManager;
// this.plugin = plugin;
// }
//
// /**
// * Register all variables that this class can manage
// */
// public abstract void register();
//
// /**
// * Shortcut method to register the variables without the boilerplate of adding the plugin instance and registering
// * it to the manager.
// *
// * @param variable variable name like "online"
// * @return the replacer responsible for this single variable
// */
// protected Replacer register(String variable) {
// Replacer replacer = new Replacer(plugin, variable);
// replaceManager.register(replacer);
// return replacer;
// }
// }
//
// Path: variables/src/main/java/com/github/games647/scoreboardstats/variables/ReplacerAPI.java
// public abstract class ReplacerAPI {
//
// protected final Logger logger;
// protected final Map<String, Replacer> replacers = Maps.newHashMap();
//
// public ReplacerAPI(Logger logger) {
// this.logger = logger;
// }
//
// public void register(Replacer replacer) {
// replacers.put(replacer.getVariable(), replacer);
//
// for (EventReplacer<? extends Event> eventReplacer : replacer.getEventsReplacers().values()) {
// Class<? extends Event> eventClass = eventReplacer.getEventClass();
// Plugin plugin = replacer.getPlugin();
//
// EventExecutor executor = (listener, event) -> eventReplacer.execute(this, event);
//
// Listener listener = new Listener() {};
//
// PluginManager pluginManager = Bukkit.getPluginManager();
// pluginManager.registerEvent(eventClass, listener, HIGHEST, executor, plugin, true);
// }
// }
//
// public void unregister(String variable) {
// replacers.remove(variable);
// }
//
// public void unregisterAll(Plugin disablePlugin) {
// Iterator<Replacer> iterator = replacers.values().iterator();
// while (iterator.hasNext()) {
// Plugin plugin = iterator.next().getPlugin();
// if (plugin == disablePlugin) {
// iterator.remove();
// }
// }
// }
//
// public void forceUpdate(String variable, int score) {
// Bukkit.getOnlinePlayers().forEach(player -> forceUpdate(player, variable, score));
// }
//
// public void forceUpdate(String variable, String value) {
// Bukkit.getOnlinePlayers().forEach(player -> forceUpdate(player, variable, value));
// }
//
// public abstract void forceUpdate(Player player, String variable, int score);
//
// public abstract void forceUpdate(Player player, String variable, String value);
//
// public Optional<String> replace(Player player, String variable, boolean complete) throws ReplacerException {
// Replacer replacer = getReplacer(variable);
// if (!complete && replacer.isGlobal() || replacer.isEventVariable() || replacer.isConstant()) {
// return Optional.empty();
// }
//
// try {
// return Optional.of(replacer.replace(player));
// } catch (Exception ex) {
// throw new ReplacerException(ex);
// }
// }
//
// public OptionalInt scoreReplace(Player player, String variable, boolean complete) throws ReplacerException {
// Replacer replacer = getReplacer(variable);
// if (!complete && replacer.isGlobal() || replacer.isEventVariable() || replacer.isConstant()) {
// return OptionalInt.empty();
// }
//
// try {
// return OptionalInt.of(replacer.scoreReplace(player));
// } catch (Exception ex) {
// throw new ReplacerException(ex);
// }
// }
//
// private Replacer getReplacer(String variable) throws UnknownVariableException {
// Replacer replacer = this.replacers.get(variable);
// if (replacer == null) {
// throw new UnknownVariableException(variable);
// }
//
// return replacer;
// }
// }
// Path: defaults/src/main/java/com/github/games647/scoreboardstats/defaults/McCombatLevelVariables.java
import com.github.games647.scoreboardstats.variables.DefaultReplacer;
import com.github.games647.scoreboardstats.variables.DefaultReplacers;
import com.github.games647.scoreboardstats.variables.ReplacerAPI;
import com.gmail.mrphpfan.mccombatlevel.McCombatLevel;
import com.gmail.mrphpfan.mccombatlevel.PlayerCombatLevelChangeEvent;
package com.github.games647.scoreboardstats.defaults;
@DefaultReplacer(plugin = "mcCombatLevel")
public class McCombatLevelVariables extends DefaultReplacers<McCombatLevel> {
| public McCombatLevelVariables(ReplacerAPI replaceManager, McCombatLevel plugin) { |
games647/ScoreboardStats | defaults/src/main/java/com/github/games647/scoreboardstats/defaults/PlaceHolderVariables.java | // Path: variables/src/main/java/com/github/games647/scoreboardstats/variables/DefaultReplacers.java
// public abstract class DefaultReplacers<T extends Plugin> {
//
// protected final ReplacerAPI replaceManager;
// protected final T plugin;
//
// public DefaultReplacers(ReplacerAPI replaceManager, T plugin) {
// this.replaceManager = replaceManager;
// this.plugin = plugin;
// }
//
// /**
// * Register all variables that this class can manage
// */
// public abstract void register();
//
// /**
// * Shortcut method to register the variables without the boilerplate of adding the plugin instance and registering
// * it to the manager.
// *
// * @param variable variable name like "online"
// * @return the replacer responsible for this single variable
// */
// protected Replacer register(String variable) {
// Replacer replacer = new Replacer(plugin, variable);
// replaceManager.register(replacer);
// return replacer;
// }
// }
//
// Path: variables/src/main/java/com/github/games647/scoreboardstats/variables/ReplacerAPI.java
// public abstract class ReplacerAPI {
//
// protected final Logger logger;
// protected final Map<String, Replacer> replacers = Maps.newHashMap();
//
// public ReplacerAPI(Logger logger) {
// this.logger = logger;
// }
//
// public void register(Replacer replacer) {
// replacers.put(replacer.getVariable(), replacer);
//
// for (EventReplacer<? extends Event> eventReplacer : replacer.getEventsReplacers().values()) {
// Class<? extends Event> eventClass = eventReplacer.getEventClass();
// Plugin plugin = replacer.getPlugin();
//
// EventExecutor executor = (listener, event) -> eventReplacer.execute(this, event);
//
// Listener listener = new Listener() {};
//
// PluginManager pluginManager = Bukkit.getPluginManager();
// pluginManager.registerEvent(eventClass, listener, HIGHEST, executor, plugin, true);
// }
// }
//
// public void unregister(String variable) {
// replacers.remove(variable);
// }
//
// public void unregisterAll(Plugin disablePlugin) {
// Iterator<Replacer> iterator = replacers.values().iterator();
// while (iterator.hasNext()) {
// Plugin plugin = iterator.next().getPlugin();
// if (plugin == disablePlugin) {
// iterator.remove();
// }
// }
// }
//
// public void forceUpdate(String variable, int score) {
// Bukkit.getOnlinePlayers().forEach(player -> forceUpdate(player, variable, score));
// }
//
// public void forceUpdate(String variable, String value) {
// Bukkit.getOnlinePlayers().forEach(player -> forceUpdate(player, variable, value));
// }
//
// public abstract void forceUpdate(Player player, String variable, int score);
//
// public abstract void forceUpdate(Player player, String variable, String value);
//
// public Optional<String> replace(Player player, String variable, boolean complete) throws ReplacerException {
// Replacer replacer = getReplacer(variable);
// if (!complete && replacer.isGlobal() || replacer.isEventVariable() || replacer.isConstant()) {
// return Optional.empty();
// }
//
// try {
// return Optional.of(replacer.replace(player));
// } catch (Exception ex) {
// throw new ReplacerException(ex);
// }
// }
//
// public OptionalInt scoreReplace(Player player, String variable, boolean complete) throws ReplacerException {
// Replacer replacer = getReplacer(variable);
// if (!complete && replacer.isGlobal() || replacer.isEventVariable() || replacer.isConstant()) {
// return OptionalInt.empty();
// }
//
// try {
// return OptionalInt.of(replacer.scoreReplace(player));
// } catch (Exception ex) {
// throw new ReplacerException(ex);
// }
// }
//
// private Replacer getReplacer(String variable) throws UnknownVariableException {
// Replacer replacer = this.replacers.get(variable);
// if (replacer == null) {
// throw new UnknownVariableException(variable);
// }
//
// return replacer;
// }
// }
| import com.github.games647.scoreboardstats.variables.DefaultReplacer;
import com.github.games647.scoreboardstats.variables.DefaultReplacers;
import com.github.games647.scoreboardstats.variables.ReplacerAPI;
import com.google.common.collect.Sets;
import java.util.Collection;
import java.util.Set;
import me.clip.placeholderapi.PlaceholderAPI;
import me.clip.placeholderapi.PlaceholderHook;
import me.clip.placeholderapi.expansion.PlaceholderExpansion;
import me.clip.placeholderapi.external.EZPlaceholderHook;
import org.bukkit.plugin.Plugin; | package com.github.games647.scoreboardstats.defaults;
@DefaultReplacer(plugin = "PlaceholderAPI")
public class PlaceHolderVariables extends DefaultReplacers<Plugin> {
| // Path: variables/src/main/java/com/github/games647/scoreboardstats/variables/DefaultReplacers.java
// public abstract class DefaultReplacers<T extends Plugin> {
//
// protected final ReplacerAPI replaceManager;
// protected final T plugin;
//
// public DefaultReplacers(ReplacerAPI replaceManager, T plugin) {
// this.replaceManager = replaceManager;
// this.plugin = plugin;
// }
//
// /**
// * Register all variables that this class can manage
// */
// public abstract void register();
//
// /**
// * Shortcut method to register the variables without the boilerplate of adding the plugin instance and registering
// * it to the manager.
// *
// * @param variable variable name like "online"
// * @return the replacer responsible for this single variable
// */
// protected Replacer register(String variable) {
// Replacer replacer = new Replacer(plugin, variable);
// replaceManager.register(replacer);
// return replacer;
// }
// }
//
// Path: variables/src/main/java/com/github/games647/scoreboardstats/variables/ReplacerAPI.java
// public abstract class ReplacerAPI {
//
// protected final Logger logger;
// protected final Map<String, Replacer> replacers = Maps.newHashMap();
//
// public ReplacerAPI(Logger logger) {
// this.logger = logger;
// }
//
// public void register(Replacer replacer) {
// replacers.put(replacer.getVariable(), replacer);
//
// for (EventReplacer<? extends Event> eventReplacer : replacer.getEventsReplacers().values()) {
// Class<? extends Event> eventClass = eventReplacer.getEventClass();
// Plugin plugin = replacer.getPlugin();
//
// EventExecutor executor = (listener, event) -> eventReplacer.execute(this, event);
//
// Listener listener = new Listener() {};
//
// PluginManager pluginManager = Bukkit.getPluginManager();
// pluginManager.registerEvent(eventClass, listener, HIGHEST, executor, plugin, true);
// }
// }
//
// public void unregister(String variable) {
// replacers.remove(variable);
// }
//
// public void unregisterAll(Plugin disablePlugin) {
// Iterator<Replacer> iterator = replacers.values().iterator();
// while (iterator.hasNext()) {
// Plugin plugin = iterator.next().getPlugin();
// if (plugin == disablePlugin) {
// iterator.remove();
// }
// }
// }
//
// public void forceUpdate(String variable, int score) {
// Bukkit.getOnlinePlayers().forEach(player -> forceUpdate(player, variable, score));
// }
//
// public void forceUpdate(String variable, String value) {
// Bukkit.getOnlinePlayers().forEach(player -> forceUpdate(player, variable, value));
// }
//
// public abstract void forceUpdate(Player player, String variable, int score);
//
// public abstract void forceUpdate(Player player, String variable, String value);
//
// public Optional<String> replace(Player player, String variable, boolean complete) throws ReplacerException {
// Replacer replacer = getReplacer(variable);
// if (!complete && replacer.isGlobal() || replacer.isEventVariable() || replacer.isConstant()) {
// return Optional.empty();
// }
//
// try {
// return Optional.of(replacer.replace(player));
// } catch (Exception ex) {
// throw new ReplacerException(ex);
// }
// }
//
// public OptionalInt scoreReplace(Player player, String variable, boolean complete) throws ReplacerException {
// Replacer replacer = getReplacer(variable);
// if (!complete && replacer.isGlobal() || replacer.isEventVariable() || replacer.isConstant()) {
// return OptionalInt.empty();
// }
//
// try {
// return OptionalInt.of(replacer.scoreReplace(player));
// } catch (Exception ex) {
// throw new ReplacerException(ex);
// }
// }
//
// private Replacer getReplacer(String variable) throws UnknownVariableException {
// Replacer replacer = this.replacers.get(variable);
// if (replacer == null) {
// throw new UnknownVariableException(variable);
// }
//
// return replacer;
// }
// }
// Path: defaults/src/main/java/com/github/games647/scoreboardstats/defaults/PlaceHolderVariables.java
import com.github.games647.scoreboardstats.variables.DefaultReplacer;
import com.github.games647.scoreboardstats.variables.DefaultReplacers;
import com.github.games647.scoreboardstats.variables.ReplacerAPI;
import com.google.common.collect.Sets;
import java.util.Collection;
import java.util.Set;
import me.clip.placeholderapi.PlaceholderAPI;
import me.clip.placeholderapi.PlaceholderHook;
import me.clip.placeholderapi.expansion.PlaceholderExpansion;
import me.clip.placeholderapi.external.EZPlaceholderHook;
import org.bukkit.plugin.Plugin;
package com.github.games647.scoreboardstats.defaults;
@DefaultReplacer(plugin = "PlaceholderAPI")
public class PlaceHolderVariables extends DefaultReplacers<Plugin> {
| public PlaceHolderVariables(ReplacerAPI replaceManager, Plugin plugin) { |
gr8pefish/OpenGlider | src/main/java/gr8pefish/openglider/common/network/PacketServerGliding.java | // Path: src/main/java/gr8pefish/openglider/api/helper/GliderHelper.java
// public class GliderHelper {
//
//
// //ToDo: getIGlider/setIGlider
// //return itemstack or IGlider?
//
// /**
// * Get the gliderBasic used, contains all the stats/modifiers of it.
// * Should only be needed when {@link IGliderCapabilityHandler#getIsPlayerGliding} is true.
// * See {@link IGlider} for details.
// * Currently only gets the currently held item of the player when they have it deployed.
// *
// * @return - the IGlider the player is using, null if not using any.
// */
// public static ItemStack getGlider(EntityPlayer player) {
// IGliderCapabilityHandler cap = CapabilityHelper.getGliderCapability(player);
//
// //if gliderBasic deployed
// if (cap != null && cap.getIsGliderDeployed()) {
//
// //if player holding a gliderBasic
// if (player != null && player.getHeldItemMainhand() != null && !player.getHeldItemMainhand().isEmpty() && player.getHeldItemMainhand().getItem() instanceof IGlider) {
//
// //return that held gliderBasic
// return player.getHeldItemMainhand();
// }
// }
// else
// Logger.error("Cannot get gliderBasic used, gliderBasic capability not present.");
// return null;
// }
//
// /**
// * Wrapper method for {@link IGliderCapabilityHandler#getIsPlayerGliding()}, taking into account capabilities.
// *
// * @param player - the player to check
// * @return - True if gliding, False otherwise (includes no capability)
// */
// public static boolean getIsPlayerGliding(EntityPlayer player) {
// IGliderCapabilityHandler cap = CapabilityHelper.getGliderCapability(player);
// if (cap != null)
// return cap.getIsPlayerGliding();
// else
// Logger.error("Cannot get player gliding status, gliderBasic capability not present.");
// return false;
// }
//
// /**
// * Wrapper method for {@link IGliderCapabilityHandler#setIsPlayerGliding(boolean)}, taking into account capabilities.
// *
// * @param player - the player to check
// * @param isGliding - the gliding state to set
// */
// public static void setIsPlayerGliding(EntityPlayer player, boolean isGliding) {
// IGliderCapabilityHandler cap = CapabilityHelper.getGliderCapability(player);
// if (cap != null)
// cap.setIsPlayerGliding(isGliding);
// else
// Logger.error("Cannot set player gliding, gliderBasic capability not present.");
// }
//
// /**
// * Wrapper method for {@link IGliderCapabilityHandler#getIsGliderDeployed()}, taking into account capabilities.
// *
// * @param player - the player to check
// * @return - True if deployed, False otherwise (includes no capability)
// */
// public static boolean getIsGliderDeployed(EntityPlayer player) {
// IGliderCapabilityHandler cap = CapabilityHelper.getGliderCapability(player);
// if (cap != null)
// return cap.getIsGliderDeployed();
// else
// Logger.error("Cannot get gliderBasic deployment status, gliderBasic capability not present.");
// return false;
// }
//
// /**
// * Wrapper method for {@link IGliderCapabilityHandler#setIsGliderDeployed(boolean)}, taking into account capabilities.
// *
// * @param player - the player to check
// * @param isDeployed - the gliderBasic deployment state to set
// */
// public static void setIsGliderDeployed(EntityPlayer player, boolean isDeployed) {
// IGliderCapabilityHandler cap = CapabilityHelper.getGliderCapability(player);
// if (cap != null)
// cap.setIsGliderDeployed(isDeployed);
// else
// Logger.error("Cannot set gliderBasic deployed, gliderBasic capability not present.");
// }
//
// }
| import gr8pefish.openglider.api.helper.GliderHelper;
import io.netty.buffer.ByteBuf;
import net.minecraftforge.fml.common.network.ByteBufUtils;
import net.minecraftforge.fml.common.network.simpleimpl.IMessage;
import net.minecraftforge.fml.common.network.simpleimpl.IMessageHandler;
import net.minecraftforge.fml.common.network.simpleimpl.MessageContext; | package gr8pefish.openglider.common.network;
/**
* [UNUSED]
* Syncs the gliding capability on the server side to a given player.
*/
public class PacketServerGliding implements IMessage {
//the data sent
private byte isGliding;
public final static byte IS_GLIDING = 0;
public final static byte IS_NOT_GLIDING = 1;
public PacketServerGliding() {} //default constructor is necessary
public PacketServerGliding(byte gliding) {
this.isGliding = gliding;
}
@Override
public void fromBytes(ByteBuf buf){
isGliding = (byte) ByteBufUtils.readVarShort(buf);
}
@Override
public void toBytes(ByteBuf buf){
ByteBufUtils.writeVarShort(buf, isGliding);
}
public static class Handler implements IMessageHandler<PacketServerGliding, IMessage> {
@Override
public IMessage onMessage(PacketServerGliding message, MessageContext ctx) {
| // Path: src/main/java/gr8pefish/openglider/api/helper/GliderHelper.java
// public class GliderHelper {
//
//
// //ToDo: getIGlider/setIGlider
// //return itemstack or IGlider?
//
// /**
// * Get the gliderBasic used, contains all the stats/modifiers of it.
// * Should only be needed when {@link IGliderCapabilityHandler#getIsPlayerGliding} is true.
// * See {@link IGlider} for details.
// * Currently only gets the currently held item of the player when they have it deployed.
// *
// * @return - the IGlider the player is using, null if not using any.
// */
// public static ItemStack getGlider(EntityPlayer player) {
// IGliderCapabilityHandler cap = CapabilityHelper.getGliderCapability(player);
//
// //if gliderBasic deployed
// if (cap != null && cap.getIsGliderDeployed()) {
//
// //if player holding a gliderBasic
// if (player != null && player.getHeldItemMainhand() != null && !player.getHeldItemMainhand().isEmpty() && player.getHeldItemMainhand().getItem() instanceof IGlider) {
//
// //return that held gliderBasic
// return player.getHeldItemMainhand();
// }
// }
// else
// Logger.error("Cannot get gliderBasic used, gliderBasic capability not present.");
// return null;
// }
//
// /**
// * Wrapper method for {@link IGliderCapabilityHandler#getIsPlayerGliding()}, taking into account capabilities.
// *
// * @param player - the player to check
// * @return - True if gliding, False otherwise (includes no capability)
// */
// public static boolean getIsPlayerGliding(EntityPlayer player) {
// IGliderCapabilityHandler cap = CapabilityHelper.getGliderCapability(player);
// if (cap != null)
// return cap.getIsPlayerGliding();
// else
// Logger.error("Cannot get player gliding status, gliderBasic capability not present.");
// return false;
// }
//
// /**
// * Wrapper method for {@link IGliderCapabilityHandler#setIsPlayerGliding(boolean)}, taking into account capabilities.
// *
// * @param player - the player to check
// * @param isGliding - the gliding state to set
// */
// public static void setIsPlayerGliding(EntityPlayer player, boolean isGliding) {
// IGliderCapabilityHandler cap = CapabilityHelper.getGliderCapability(player);
// if (cap != null)
// cap.setIsPlayerGliding(isGliding);
// else
// Logger.error("Cannot set player gliding, gliderBasic capability not present.");
// }
//
// /**
// * Wrapper method for {@link IGliderCapabilityHandler#getIsGliderDeployed()}, taking into account capabilities.
// *
// * @param player - the player to check
// * @return - True if deployed, False otherwise (includes no capability)
// */
// public static boolean getIsGliderDeployed(EntityPlayer player) {
// IGliderCapabilityHandler cap = CapabilityHelper.getGliderCapability(player);
// if (cap != null)
// return cap.getIsGliderDeployed();
// else
// Logger.error("Cannot get gliderBasic deployment status, gliderBasic capability not present.");
// return false;
// }
//
// /**
// * Wrapper method for {@link IGliderCapabilityHandler#setIsGliderDeployed(boolean)}, taking into account capabilities.
// *
// * @param player - the player to check
// * @param isDeployed - the gliderBasic deployment state to set
// */
// public static void setIsGliderDeployed(EntityPlayer player, boolean isDeployed) {
// IGliderCapabilityHandler cap = CapabilityHelper.getGliderCapability(player);
// if (cap != null)
// cap.setIsGliderDeployed(isDeployed);
// else
// Logger.error("Cannot set gliderBasic deployed, gliderBasic capability not present.");
// }
//
// }
// Path: src/main/java/gr8pefish/openglider/common/network/PacketServerGliding.java
import gr8pefish.openglider.api.helper.GliderHelper;
import io.netty.buffer.ByteBuf;
import net.minecraftforge.fml.common.network.ByteBufUtils;
import net.minecraftforge.fml.common.network.simpleimpl.IMessage;
import net.minecraftforge.fml.common.network.simpleimpl.IMessageHandler;
import net.minecraftforge.fml.common.network.simpleimpl.MessageContext;
package gr8pefish.openglider.common.network;
/**
* [UNUSED]
* Syncs the gliding capability on the server side to a given player.
*/
public class PacketServerGliding implements IMessage {
//the data sent
private byte isGliding;
public final static byte IS_GLIDING = 0;
public final static byte IS_NOT_GLIDING = 1;
public PacketServerGliding() {} //default constructor is necessary
public PacketServerGliding(byte gliding) {
this.isGliding = gliding;
}
@Override
public void fromBytes(ByteBuf buf){
isGliding = (byte) ByteBufUtils.readVarShort(buf);
}
@Override
public void toBytes(ByteBuf buf){
ByteBufUtils.writeVarShort(buf, isGliding);
}
public static class Handler implements IMessageHandler<PacketServerGliding, IMessage> {
@Override
public IMessage onMessage(PacketServerGliding message, MessageContext ctx) {
| GliderHelper.setIsGliderDeployed(ctx.getServerHandler().player, message.isGliding == IS_GLIDING); |
gr8pefish/OpenGlider | src/main/java/gr8pefish/openglider/common/recipe/RecipeHelper.java | // Path: src/main/java/gr8pefish/openglider/api/item/IGlider.java
// public interface IGlider extends INBTSerializable<NBTTagCompound> {
// //ToDo
//
// //==============Flight==================
//
// //Blocks traveled horizontally per movement time.
// double getHorizontalFlightSpeed();
//
// void setHorizontalFlightSpeed(double speed);
//
// //Blocks traveled vertically per movement time.
// double getVerticalFlightSpeed();
//
// void setVerticalFlightSpeed(double speed);
//
// //Blocks traveled horizontally per movement time when going fast/pressing shift.
// double getShiftHorizontalFlightSpeed();
//
// void setShiftHorizontalFlightSpeed(double speed);
//
// //Blocks traveled vertically per movement time when going fast/pressing shift.
// double getShiftVerticalFlightSpeed();
//
// void setShiftVerticalFlightSpeed(double speed);
//
// //===============Wind====================
//
// double getWindMultiplier();
//
// void setWindMultiplier(double windMultiplier);
//
// double getAirResistance();
//
// void setAirResistance(double airResistance);
//
// //=============Durability================
//
// int getTotalDurability();
//
// void setTotalDurability(int durability);
//
// int getCurrentDurability(ItemStack glider);
//
// void setCurrentDurability(ItemStack glider, int durability);
//
// boolean isBroken(ItemStack glider);
//
// //==============Upgrades====================
// ArrayList<ItemStack> getUpgrades(ItemStack glider);
//
// void removeUpgrade(ItemStack glider, ItemStack upgrade);
//
// void addUpgrade(ItemStack glider, ItemStack upgrade);
//
// //==============Misc=========================
// ResourceLocation getModelTexture(ItemStack glider);
//
// void setModelTexture(ResourceLocation resourceLocation);
//
// }
//
// Path: src/main/java/gr8pefish/openglider/api/upgrade/UpgradeItems.java
// public class UpgradeItems {
//
// private static ArrayList<ItemStack> possibleUpgradeList;
//
// public static void initUpgradesList() {
// possibleUpgradeList = new ArrayList<>();
// // addToUpgradesList(new ItemStack(Items.COMPASS)); //ToDo: Add back with functionality at some point
// }
//
// public static void addToUpgradesList(ItemStack stack) {
// possibleUpgradeList.add(stack);
// }
//
// public static ArrayList<ItemStack> getPossibleUpgradeList() {
// return possibleUpgradeList;
// }
//
// private static void removeFromUpgradesList(ItemStack stack) {
// possibleUpgradeList.remove(stack);
// }
//
// }
| import gr8pefish.openglider.api.item.IGlider;
import gr8pefish.openglider.api.upgrade.UpgradeItems;
import net.minecraft.inventory.InventoryCrafting;
import net.minecraft.item.ItemStack;
import java.util.ArrayList; | package gr8pefish.openglider.common.recipe;
public class RecipeHelper {
/**
* Helper method for getting the first glider in the recipes grid (which will be the one used)
* @param inventoryCrafting - the inventory to search
* @return - the glider to be crafted
*/
public static ItemStack getFirstUpgradableGlider(InventoryCrafting inventoryCrafting) {
for (int i = 0; i < 3; ++i) {
for (int j = 0; j < 3; ++j) {
ItemStack itemstack = inventoryCrafting.getStackInRowAndColumn(j, i); | // Path: src/main/java/gr8pefish/openglider/api/item/IGlider.java
// public interface IGlider extends INBTSerializable<NBTTagCompound> {
// //ToDo
//
// //==============Flight==================
//
// //Blocks traveled horizontally per movement time.
// double getHorizontalFlightSpeed();
//
// void setHorizontalFlightSpeed(double speed);
//
// //Blocks traveled vertically per movement time.
// double getVerticalFlightSpeed();
//
// void setVerticalFlightSpeed(double speed);
//
// //Blocks traveled horizontally per movement time when going fast/pressing shift.
// double getShiftHorizontalFlightSpeed();
//
// void setShiftHorizontalFlightSpeed(double speed);
//
// //Blocks traveled vertically per movement time when going fast/pressing shift.
// double getShiftVerticalFlightSpeed();
//
// void setShiftVerticalFlightSpeed(double speed);
//
// //===============Wind====================
//
// double getWindMultiplier();
//
// void setWindMultiplier(double windMultiplier);
//
// double getAirResistance();
//
// void setAirResistance(double airResistance);
//
// //=============Durability================
//
// int getTotalDurability();
//
// void setTotalDurability(int durability);
//
// int getCurrentDurability(ItemStack glider);
//
// void setCurrentDurability(ItemStack glider, int durability);
//
// boolean isBroken(ItemStack glider);
//
// //==============Upgrades====================
// ArrayList<ItemStack> getUpgrades(ItemStack glider);
//
// void removeUpgrade(ItemStack glider, ItemStack upgrade);
//
// void addUpgrade(ItemStack glider, ItemStack upgrade);
//
// //==============Misc=========================
// ResourceLocation getModelTexture(ItemStack glider);
//
// void setModelTexture(ResourceLocation resourceLocation);
//
// }
//
// Path: src/main/java/gr8pefish/openglider/api/upgrade/UpgradeItems.java
// public class UpgradeItems {
//
// private static ArrayList<ItemStack> possibleUpgradeList;
//
// public static void initUpgradesList() {
// possibleUpgradeList = new ArrayList<>();
// // addToUpgradesList(new ItemStack(Items.COMPASS)); //ToDo: Add back with functionality at some point
// }
//
// public static void addToUpgradesList(ItemStack stack) {
// possibleUpgradeList.add(stack);
// }
//
// public static ArrayList<ItemStack> getPossibleUpgradeList() {
// return possibleUpgradeList;
// }
//
// private static void removeFromUpgradesList(ItemStack stack) {
// possibleUpgradeList.remove(stack);
// }
//
// }
// Path: src/main/java/gr8pefish/openglider/common/recipe/RecipeHelper.java
import gr8pefish.openglider.api.item.IGlider;
import gr8pefish.openglider.api.upgrade.UpgradeItems;
import net.minecraft.inventory.InventoryCrafting;
import net.minecraft.item.ItemStack;
import java.util.ArrayList;
package gr8pefish.openglider.common.recipe;
public class RecipeHelper {
/**
* Helper method for getting the first glider in the recipes grid (which will be the one used)
* @param inventoryCrafting - the inventory to search
* @return - the glider to be crafted
*/
public static ItemStack getFirstUpgradableGlider(InventoryCrafting inventoryCrafting) {
for (int i = 0; i < 3; ++i) {
for (int j = 0; j < 3; ++j) {
ItemStack itemstack = inventoryCrafting.getStackInRowAndColumn(j, i); | if (!itemstack.isEmpty() && (itemstack.getItem() instanceof IGlider)) { |
gr8pefish/OpenGlider | src/main/java/gr8pefish/openglider/common/recipe/RecipeHelper.java | // Path: src/main/java/gr8pefish/openglider/api/item/IGlider.java
// public interface IGlider extends INBTSerializable<NBTTagCompound> {
// //ToDo
//
// //==============Flight==================
//
// //Blocks traveled horizontally per movement time.
// double getHorizontalFlightSpeed();
//
// void setHorizontalFlightSpeed(double speed);
//
// //Blocks traveled vertically per movement time.
// double getVerticalFlightSpeed();
//
// void setVerticalFlightSpeed(double speed);
//
// //Blocks traveled horizontally per movement time when going fast/pressing shift.
// double getShiftHorizontalFlightSpeed();
//
// void setShiftHorizontalFlightSpeed(double speed);
//
// //Blocks traveled vertically per movement time when going fast/pressing shift.
// double getShiftVerticalFlightSpeed();
//
// void setShiftVerticalFlightSpeed(double speed);
//
// //===============Wind====================
//
// double getWindMultiplier();
//
// void setWindMultiplier(double windMultiplier);
//
// double getAirResistance();
//
// void setAirResistance(double airResistance);
//
// //=============Durability================
//
// int getTotalDurability();
//
// void setTotalDurability(int durability);
//
// int getCurrentDurability(ItemStack glider);
//
// void setCurrentDurability(ItemStack glider, int durability);
//
// boolean isBroken(ItemStack glider);
//
// //==============Upgrades====================
// ArrayList<ItemStack> getUpgrades(ItemStack glider);
//
// void removeUpgrade(ItemStack glider, ItemStack upgrade);
//
// void addUpgrade(ItemStack glider, ItemStack upgrade);
//
// //==============Misc=========================
// ResourceLocation getModelTexture(ItemStack glider);
//
// void setModelTexture(ResourceLocation resourceLocation);
//
// }
//
// Path: src/main/java/gr8pefish/openglider/api/upgrade/UpgradeItems.java
// public class UpgradeItems {
//
// private static ArrayList<ItemStack> possibleUpgradeList;
//
// public static void initUpgradesList() {
// possibleUpgradeList = new ArrayList<>();
// // addToUpgradesList(new ItemStack(Items.COMPASS)); //ToDo: Add back with functionality at some point
// }
//
// public static void addToUpgradesList(ItemStack stack) {
// possibleUpgradeList.add(stack);
// }
//
// public static ArrayList<ItemStack> getPossibleUpgradeList() {
// return possibleUpgradeList;
// }
//
// private static void removeFromUpgradesList(ItemStack stack) {
// possibleUpgradeList.remove(stack);
// }
//
// }
| import gr8pefish.openglider.api.item.IGlider;
import gr8pefish.openglider.api.upgrade.UpgradeItems;
import net.minecraft.inventory.InventoryCrafting;
import net.minecraft.item.ItemStack;
import java.util.ArrayList; | package gr8pefish.openglider.common.recipe;
public class RecipeHelper {
/**
* Helper method for getting the first glider in the recipes grid (which will be the one used)
* @param inventoryCrafting - the inventory to search
* @return - the glider to be crafted
*/
public static ItemStack getFirstUpgradableGlider(InventoryCrafting inventoryCrafting) {
for (int i = 0; i < 3; ++i) {
for (int j = 0; j < 3; ++j) {
ItemStack itemstack = inventoryCrafting.getStackInRowAndColumn(j, i);
if (!itemstack.isEmpty() && (itemstack.getItem() instanceof IGlider)) {
return itemstack;
}
}
}
return null;
}
/**
* Helper method for getting the first upgrade in the recipes grid (which will be the one used)
* @param inventoryCrafting - the inventory to search
* @return - the upgrade to be used
*/
public static ItemStack getFirstUpgrade(InventoryCrafting inventoryCrafting){
for (int i = 0; i < 3; ++i) {
for (int j = 0; j < 3; ++j) {
ItemStack itemstack = inventoryCrafting.getStackInRowAndColumn(j, i);
if (!itemstack.isEmpty()) { | // Path: src/main/java/gr8pefish/openglider/api/item/IGlider.java
// public interface IGlider extends INBTSerializable<NBTTagCompound> {
// //ToDo
//
// //==============Flight==================
//
// //Blocks traveled horizontally per movement time.
// double getHorizontalFlightSpeed();
//
// void setHorizontalFlightSpeed(double speed);
//
// //Blocks traveled vertically per movement time.
// double getVerticalFlightSpeed();
//
// void setVerticalFlightSpeed(double speed);
//
// //Blocks traveled horizontally per movement time when going fast/pressing shift.
// double getShiftHorizontalFlightSpeed();
//
// void setShiftHorizontalFlightSpeed(double speed);
//
// //Blocks traveled vertically per movement time when going fast/pressing shift.
// double getShiftVerticalFlightSpeed();
//
// void setShiftVerticalFlightSpeed(double speed);
//
// //===============Wind====================
//
// double getWindMultiplier();
//
// void setWindMultiplier(double windMultiplier);
//
// double getAirResistance();
//
// void setAirResistance(double airResistance);
//
// //=============Durability================
//
// int getTotalDurability();
//
// void setTotalDurability(int durability);
//
// int getCurrentDurability(ItemStack glider);
//
// void setCurrentDurability(ItemStack glider, int durability);
//
// boolean isBroken(ItemStack glider);
//
// //==============Upgrades====================
// ArrayList<ItemStack> getUpgrades(ItemStack glider);
//
// void removeUpgrade(ItemStack glider, ItemStack upgrade);
//
// void addUpgrade(ItemStack glider, ItemStack upgrade);
//
// //==============Misc=========================
// ResourceLocation getModelTexture(ItemStack glider);
//
// void setModelTexture(ResourceLocation resourceLocation);
//
// }
//
// Path: src/main/java/gr8pefish/openglider/api/upgrade/UpgradeItems.java
// public class UpgradeItems {
//
// private static ArrayList<ItemStack> possibleUpgradeList;
//
// public static void initUpgradesList() {
// possibleUpgradeList = new ArrayList<>();
// // addToUpgradesList(new ItemStack(Items.COMPASS)); //ToDo: Add back with functionality at some point
// }
//
// public static void addToUpgradesList(ItemStack stack) {
// possibleUpgradeList.add(stack);
// }
//
// public static ArrayList<ItemStack> getPossibleUpgradeList() {
// return possibleUpgradeList;
// }
//
// private static void removeFromUpgradesList(ItemStack stack) {
// possibleUpgradeList.remove(stack);
// }
//
// }
// Path: src/main/java/gr8pefish/openglider/common/recipe/RecipeHelper.java
import gr8pefish.openglider.api.item.IGlider;
import gr8pefish.openglider.api.upgrade.UpgradeItems;
import net.minecraft.inventory.InventoryCrafting;
import net.minecraft.item.ItemStack;
import java.util.ArrayList;
package gr8pefish.openglider.common.recipe;
public class RecipeHelper {
/**
* Helper method for getting the first glider in the recipes grid (which will be the one used)
* @param inventoryCrafting - the inventory to search
* @return - the glider to be crafted
*/
public static ItemStack getFirstUpgradableGlider(InventoryCrafting inventoryCrafting) {
for (int i = 0; i < 3; ++i) {
for (int j = 0; j < 3; ++j) {
ItemStack itemstack = inventoryCrafting.getStackInRowAndColumn(j, i);
if (!itemstack.isEmpty() && (itemstack.getItem() instanceof IGlider)) {
return itemstack;
}
}
}
return null;
}
/**
* Helper method for getting the first upgrade in the recipes grid (which will be the one used)
* @param inventoryCrafting - the inventory to search
* @return - the upgrade to be used
*/
public static ItemStack getFirstUpgrade(InventoryCrafting inventoryCrafting){
for (int i = 0; i < 3; ++i) {
for (int j = 0; j < 3; ++j) {
ItemStack itemstack = inventoryCrafting.getStackInRowAndColumn(j, i);
if (!itemstack.isEmpty()) { | for (ItemStack upgrade : UpgradeItems.getPossibleUpgradeList()) { |
gr8pefish/OpenGlider | src/main/java/gr8pefish/openglider/common/util/OpenGliderHelper.java | // Path: src/main/java/gr8pefish/openglider/common/lib/ModInfo.java
// public class ModInfo {
//
// public static final String DOMAIN = MODID.toLowerCase(Locale.ENGLISH) + ":"; //for resources
// public static final String VERSION = "@VERSION@";
// public static final String FORGE_UPDATE_JSON_URL = "https://raw.githubusercontent.com/gr8pefish/OpenGlider/1.10/versions/update.json";
// public static final String GUI_FACTORY = "gr8pefish.openglider.client.gui.GuiFactory"; //for in-game config
//
// public static final String COMMON_PROXY = "gr8pefish.openglider.common.proxy.CommonProxy";
// public static final String CLIENT_PROXY = "gr8pefish.openglider.client.proxy.ClientProxy";
//
// public static final String NETWORK_CHANNEL = "opngldr";
//
// public static final String ITEM_GLIDER_BASIC_NAME = "hang_glider_basic";
// public static final String ITEM_GLIDER_ADVANCED_NAME = "hang_glider_advanced";
// public static final String ITEM_GLIDER_PART_NAME = "hang_glider_part";
//
// public static final class NBT_KEYS {
//
// public static final String UPGRADES = "upgrades";
//
// }
//
// }
| import gr8pefish.openglider.common.lib.ModInfo;
import net.minecraft.item.ItemStack;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.nbt.NBTTagList;
import java.util.ArrayList; | package gr8pefish.openglider.common.util;
public class OpenGliderHelper {
public static ArrayList<ItemStack> getUpgradesFromNBT(ItemStack glider) {
ArrayList<ItemStack> upgradesArrayList = new ArrayList<>();
if (glider != null && !glider.isEmpty()) {
NBTTagCompound nbtTagCompound = glider.getTagCompound();
if (nbtTagCompound != null) { | // Path: src/main/java/gr8pefish/openglider/common/lib/ModInfo.java
// public class ModInfo {
//
// public static final String DOMAIN = MODID.toLowerCase(Locale.ENGLISH) + ":"; //for resources
// public static final String VERSION = "@VERSION@";
// public static final String FORGE_UPDATE_JSON_URL = "https://raw.githubusercontent.com/gr8pefish/OpenGlider/1.10/versions/update.json";
// public static final String GUI_FACTORY = "gr8pefish.openglider.client.gui.GuiFactory"; //for in-game config
//
// public static final String COMMON_PROXY = "gr8pefish.openglider.common.proxy.CommonProxy";
// public static final String CLIENT_PROXY = "gr8pefish.openglider.client.proxy.ClientProxy";
//
// public static final String NETWORK_CHANNEL = "opngldr";
//
// public static final String ITEM_GLIDER_BASIC_NAME = "hang_glider_basic";
// public static final String ITEM_GLIDER_ADVANCED_NAME = "hang_glider_advanced";
// public static final String ITEM_GLIDER_PART_NAME = "hang_glider_part";
//
// public static final class NBT_KEYS {
//
// public static final String UPGRADES = "upgrades";
//
// }
//
// }
// Path: src/main/java/gr8pefish/openglider/common/util/OpenGliderHelper.java
import gr8pefish.openglider.common.lib.ModInfo;
import net.minecraft.item.ItemStack;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.nbt.NBTTagList;
import java.util.ArrayList;
package gr8pefish.openglider.common.util;
public class OpenGliderHelper {
public static ArrayList<ItemStack> getUpgradesFromNBT(ItemStack glider) {
ArrayList<ItemStack> upgradesArrayList = new ArrayList<>();
if (glider != null && !glider.isEmpty()) {
NBTTagCompound nbtTagCompound = glider.getTagCompound();
if (nbtTagCompound != null) { | if(nbtTagCompound.hasKey(ModInfo.NBT_KEYS.UPGRADES)) { |
gr8pefish/OpenGlider | src/main/java/gr8pefish/openglider/client/model/ModelBars.java | // Path: src/main/java/gr8pefish/openglider/common/lib/ModInfo.java
// public class ModInfo {
//
// public static final String DOMAIN = MODID.toLowerCase(Locale.ENGLISH) + ":"; //for resources
// public static final String VERSION = "@VERSION@";
// public static final String FORGE_UPDATE_JSON_URL = "https://raw.githubusercontent.com/gr8pefish/OpenGlider/1.10/versions/update.json";
// public static final String GUI_FACTORY = "gr8pefish.openglider.client.gui.GuiFactory"; //for in-game config
//
// public static final String COMMON_PROXY = "gr8pefish.openglider.common.proxy.CommonProxy";
// public static final String CLIENT_PROXY = "gr8pefish.openglider.client.proxy.ClientProxy";
//
// public static final String NETWORK_CHANNEL = "opngldr";
//
// public static final String ITEM_GLIDER_BASIC_NAME = "hang_glider_basic";
// public static final String ITEM_GLIDER_ADVANCED_NAME = "hang_glider_advanced";
// public static final String ITEM_GLIDER_PART_NAME = "hang_glider_part";
//
// public static final class NBT_KEYS {
//
// public static final String UPGRADES = "upgrades";
//
// }
//
// }
//
// Path: src/main/java/gr8pefish/openglider/api/OpenGliderInfo.java
// public static final String MODID = "openglider";
| import gr8pefish.openglider.common.lib.ModInfo;
import net.minecraft.client.model.ModelBase;
import net.minecraft.client.model.ModelRenderer;
import net.minecraft.client.renderer.GlStateManager;
import net.minecraft.entity.Entity;
import net.minecraft.util.ResourceLocation;
import java.util.ArrayList;
import static gr8pefish.openglider.api.OpenGliderInfo.MODID; | package gr8pefish.openglider.client.model;
public class ModelBars extends ModelBase {
private ArrayList<ModelRenderer> parts; | // Path: src/main/java/gr8pefish/openglider/common/lib/ModInfo.java
// public class ModInfo {
//
// public static final String DOMAIN = MODID.toLowerCase(Locale.ENGLISH) + ":"; //for resources
// public static final String VERSION = "@VERSION@";
// public static final String FORGE_UPDATE_JSON_URL = "https://raw.githubusercontent.com/gr8pefish/OpenGlider/1.10/versions/update.json";
// public static final String GUI_FACTORY = "gr8pefish.openglider.client.gui.GuiFactory"; //for in-game config
//
// public static final String COMMON_PROXY = "gr8pefish.openglider.common.proxy.CommonProxy";
// public static final String CLIENT_PROXY = "gr8pefish.openglider.client.proxy.ClientProxy";
//
// public static final String NETWORK_CHANNEL = "opngldr";
//
// public static final String ITEM_GLIDER_BASIC_NAME = "hang_glider_basic";
// public static final String ITEM_GLIDER_ADVANCED_NAME = "hang_glider_advanced";
// public static final String ITEM_GLIDER_PART_NAME = "hang_glider_part";
//
// public static final class NBT_KEYS {
//
// public static final String UPGRADES = "upgrades";
//
// }
//
// }
//
// Path: src/main/java/gr8pefish/openglider/api/OpenGliderInfo.java
// public static final String MODID = "openglider";
// Path: src/main/java/gr8pefish/openglider/client/model/ModelBars.java
import gr8pefish.openglider.common.lib.ModInfo;
import net.minecraft.client.model.ModelBase;
import net.minecraft.client.model.ModelRenderer;
import net.minecraft.client.renderer.GlStateManager;
import net.minecraft.entity.Entity;
import net.minecraft.util.ResourceLocation;
import java.util.ArrayList;
import static gr8pefish.openglider.api.OpenGliderInfo.MODID;
package gr8pefish.openglider.client.model;
public class ModelBars extends ModelBase {
private ArrayList<ModelRenderer> parts; | public static final ResourceLocation MODEL_GLIDER_BARS_RL = new ResourceLocation(MODID, "textures/models/bars.png"); |
gr8pefish/OpenGlider | src/main/java/gr8pefish/openglider/common/registry/CapabilityRegistry.java | // Path: src/main/java/gr8pefish/openglider/common/capabilities/GliderCapabilityImplementation.java
// public final class GliderCapabilityImplementation {
//
// public static void init(){
// CapabilityManager.INSTANCE.register(IGliderCapabilityHandler.class, new Capability.IStorage<IGliderCapabilityHandler>() {
//
// @Override
// public NBTBase writeNBT(Capability<IGliderCapabilityHandler> capability, IGliderCapabilityHandler instance, EnumFacing side) {
// return instance.serializeNBT();
// }
//
// @Override
// public void readNBT(Capability<IGliderCapabilityHandler> capability, IGliderCapabilityHandler instance, EnumFacing side, NBTBase nbt) {
// if (nbt instanceof NBTTagCompound)
// instance.deserializeNBT(((NBTTagCompound) nbt));
// }
// }, DefaultGliderCapImplementation.class);
// }
//
// public static class DefaultGliderCapImplementation implements IGliderCapabilityHandler {
//
// private boolean isPlayerGliding;
// private boolean isGliderDeployed;
//
// public DefaultGliderCapImplementation() {
// this.isPlayerGliding = false;
// this.isGliderDeployed = false;
// }
//
// //Glider data
//
// @Override
// public boolean getIsPlayerGliding() {
// return isGliderDeployed && isPlayerGliding;
// }
//
// @Override
// public void setIsPlayerGliding(boolean isGliding) {
// if (!isGliderDeployed && isGliding)
// Logger.error("Can't set a player to be gliding if they don't have a deployed glider!");
// else
// isPlayerGliding = isGliding;
// }
//
// @Override
// public boolean getIsGliderDeployed() {
// return isGliderDeployed;
// }
//
// @Override
// public void setIsGliderDeployed(boolean isDeployed) {
// if (isPlayerGliding && isDeployed)
// Logger.error("Player is already flying, deploying now is not needed.");
// else
// isGliderDeployed = isDeployed;
// if (!isDeployed) isPlayerGliding = false; //if not deployed, cannot be flying either
// }
//
// //Serializing and Deserializing NBT
//
// private static final String CAP_PLAYER_GLIDING = MODID+".isPlayerGliding";
// private static final String CAP_GLIDER_DEPLOYED = MODID+".isGliderDeployed";
// private static final String CAP_GLIDER_USED = MODID+".gliderUsed";
//
// @Override
// public NBTTagCompound serializeNBT() {
//
// //save the boolean
// NBTTagCompound compound = new NBTTagCompound();
// compound.setBoolean(CAP_PLAYER_GLIDING, isPlayerGliding);
// compound.setBoolean(CAP_GLIDER_DEPLOYED, isGliderDeployed);
//
// //return compound
// return compound;
// }
//
// @Override
// public void deserializeNBT(NBTTagCompound compound) {
//
// //load and set
// setIsPlayerGliding(compound.getBoolean(CAP_PLAYER_GLIDING));
// setIsGliderDeployed(compound.getBoolean(CAP_GLIDER_DEPLOYED));
//
// }
//
// //Sync
//
// @Override
// public void sync(EntityPlayerMP player) {
// PacketHandler.HANDLER.sendTo(new PacketSyncGliderDataToClient(serializeNBT()), player);
// }
//
// }
//
// public static class Provider implements ICapabilitySerializable<NBTTagCompound> {
//
// public static final ResourceLocation NAME = new ResourceLocation(OpenGliderInfo.MODID, "cap");
//
// private final IGliderCapabilityHandler capabilityImplementation = new DefaultGliderCapImplementation();
//
// @Override
// public boolean hasCapability(Capability<?> capability, EnumFacing facing) {
// return capability == GLIDER_CAPABILITY;
// }
//
// @Override
// public <T> T getCapability(Capability<T> capability, EnumFacing facing) {
// if (capability == GLIDER_CAPABILITY) {
// return GLIDER_CAPABILITY.cast(capabilityImplementation);
// }
// return null;
// }
//
// @Override
// public NBTTagCompound serializeNBT() {
// return capabilityImplementation.serializeNBT();
// }
//
// @Override
// public void deserializeNBT(NBTTagCompound nbt) {
// capabilityImplementation.deserializeNBT(nbt);
// }
// }
//
// //make it un-constructable, as it is just a container for the other nested classes and static methods
// private GliderCapabilityImplementation() {}
//
// }
| import gr8pefish.openglider.common.capabilities.GliderCapabilityImplementation; | package gr8pefish.openglider.common.registry;
public class CapabilityRegistry {
public static void registerAllCapabilities(){ | // Path: src/main/java/gr8pefish/openglider/common/capabilities/GliderCapabilityImplementation.java
// public final class GliderCapabilityImplementation {
//
// public static void init(){
// CapabilityManager.INSTANCE.register(IGliderCapabilityHandler.class, new Capability.IStorage<IGliderCapabilityHandler>() {
//
// @Override
// public NBTBase writeNBT(Capability<IGliderCapabilityHandler> capability, IGliderCapabilityHandler instance, EnumFacing side) {
// return instance.serializeNBT();
// }
//
// @Override
// public void readNBT(Capability<IGliderCapabilityHandler> capability, IGliderCapabilityHandler instance, EnumFacing side, NBTBase nbt) {
// if (nbt instanceof NBTTagCompound)
// instance.deserializeNBT(((NBTTagCompound) nbt));
// }
// }, DefaultGliderCapImplementation.class);
// }
//
// public static class DefaultGliderCapImplementation implements IGliderCapabilityHandler {
//
// private boolean isPlayerGliding;
// private boolean isGliderDeployed;
//
// public DefaultGliderCapImplementation() {
// this.isPlayerGliding = false;
// this.isGliderDeployed = false;
// }
//
// //Glider data
//
// @Override
// public boolean getIsPlayerGliding() {
// return isGliderDeployed && isPlayerGliding;
// }
//
// @Override
// public void setIsPlayerGliding(boolean isGliding) {
// if (!isGliderDeployed && isGliding)
// Logger.error("Can't set a player to be gliding if they don't have a deployed glider!");
// else
// isPlayerGliding = isGliding;
// }
//
// @Override
// public boolean getIsGliderDeployed() {
// return isGliderDeployed;
// }
//
// @Override
// public void setIsGliderDeployed(boolean isDeployed) {
// if (isPlayerGliding && isDeployed)
// Logger.error("Player is already flying, deploying now is not needed.");
// else
// isGliderDeployed = isDeployed;
// if (!isDeployed) isPlayerGliding = false; //if not deployed, cannot be flying either
// }
//
// //Serializing and Deserializing NBT
//
// private static final String CAP_PLAYER_GLIDING = MODID+".isPlayerGliding";
// private static final String CAP_GLIDER_DEPLOYED = MODID+".isGliderDeployed";
// private static final String CAP_GLIDER_USED = MODID+".gliderUsed";
//
// @Override
// public NBTTagCompound serializeNBT() {
//
// //save the boolean
// NBTTagCompound compound = new NBTTagCompound();
// compound.setBoolean(CAP_PLAYER_GLIDING, isPlayerGliding);
// compound.setBoolean(CAP_GLIDER_DEPLOYED, isGliderDeployed);
//
// //return compound
// return compound;
// }
//
// @Override
// public void deserializeNBT(NBTTagCompound compound) {
//
// //load and set
// setIsPlayerGliding(compound.getBoolean(CAP_PLAYER_GLIDING));
// setIsGliderDeployed(compound.getBoolean(CAP_GLIDER_DEPLOYED));
//
// }
//
// //Sync
//
// @Override
// public void sync(EntityPlayerMP player) {
// PacketHandler.HANDLER.sendTo(new PacketSyncGliderDataToClient(serializeNBT()), player);
// }
//
// }
//
// public static class Provider implements ICapabilitySerializable<NBTTagCompound> {
//
// public static final ResourceLocation NAME = new ResourceLocation(OpenGliderInfo.MODID, "cap");
//
// private final IGliderCapabilityHandler capabilityImplementation = new DefaultGliderCapImplementation();
//
// @Override
// public boolean hasCapability(Capability<?> capability, EnumFacing facing) {
// return capability == GLIDER_CAPABILITY;
// }
//
// @Override
// public <T> T getCapability(Capability<T> capability, EnumFacing facing) {
// if (capability == GLIDER_CAPABILITY) {
// return GLIDER_CAPABILITY.cast(capabilityImplementation);
// }
// return null;
// }
//
// @Override
// public NBTTagCompound serializeNBT() {
// return capabilityImplementation.serializeNBT();
// }
//
// @Override
// public void deserializeNBT(NBTTagCompound nbt) {
// capabilityImplementation.deserializeNBT(nbt);
// }
// }
//
// //make it un-constructable, as it is just a container for the other nested classes and static methods
// private GliderCapabilityImplementation() {}
//
// }
// Path: src/main/java/gr8pefish/openglider/common/registry/CapabilityRegistry.java
import gr8pefish.openglider.common.capabilities.GliderCapabilityImplementation;
package gr8pefish.openglider.common.registry;
public class CapabilityRegistry {
public static void registerAllCapabilities(){ | GliderCapabilityImplementation.init(); |
gr8pefish/OpenGlider | src/main/java/gr8pefish/openglider/common/item/ItemHangGliderPart.java | // Path: src/main/java/gr8pefish/openglider/common/OpenGlider.java
// @Mod(modid = MODID, name = MOD_NAME, version = ModInfo.VERSION, guiFactory = ModInfo.GUI_FACTORY, acceptedMinecraftVersions = "[1.12,1.13)")//, updateJSON = FORGE_UPDATE_JSON_URL) //disabled version update checker for now, as it was giving false positives
// public class OpenGlider {
//
// //Proxies
// @SidedProxy(clientSide = ModInfo.CLIENT_PROXY, serverSide = ModInfo.COMMON_PROXY)
// public static IProxy proxy;
//
// //Creative Tab
// public static final CreativeTabs creativeTab = new CreativeTabs(MODID) {
//
// @Override
// public ItemStack createIcon() {
// return new ItemStack(ItemRegistry.GLIDER_BASIC);
// }
// };
//
// //Mod Instance
// @Mod.Instance
// public static OpenGlider instance;
//
//
// @Mod.EventHandler
// public void preInit(FMLPreInitializationEvent event) {
//
// //config
// ConfigHandler.init(event.getSuggestedConfigurationFile());
//
// //wind
// WindHelper.initNoiseGenerator();
//
// //register capabilities
// CapabilityRegistry.registerAllCapabilities();
//
// //packets
// PacketHandler.init();
//
// //init renderers and client event handlers
// proxy.preInit(event);
// }
//
//
// @Mod.EventHandler
// public void init(FMLInitializationEvent event) {
//
// //upgrades
// UpgradeItems.initUpgradesList();
//
// //register server events
// MinecraftForge.EVENT_BUS.register(new ServerEventHandler());
// //register config changed event
// MinecraftForge.EVENT_BUS.register(new ConfigHandler());
//
// proxy.init(event);
// }
//
//
// @Mod.EventHandler
// public void postInit(FMLPostInitializationEvent event) {
//
// proxy.postInit(event);
// }
// }
//
// Path: src/main/java/gr8pefish/openglider/common/lib/ModInfo.java
// public class ModInfo {
//
// public static final String DOMAIN = MODID.toLowerCase(Locale.ENGLISH) + ":"; //for resources
// public static final String VERSION = "@VERSION@";
// public static final String FORGE_UPDATE_JSON_URL = "https://raw.githubusercontent.com/gr8pefish/OpenGlider/1.10/versions/update.json";
// public static final String GUI_FACTORY = "gr8pefish.openglider.client.gui.GuiFactory"; //for in-game config
//
// public static final String COMMON_PROXY = "gr8pefish.openglider.common.proxy.CommonProxy";
// public static final String CLIENT_PROXY = "gr8pefish.openglider.client.proxy.ClientProxy";
//
// public static final String NETWORK_CHANNEL = "opngldr";
//
// public static final String ITEM_GLIDER_BASIC_NAME = "hang_glider_basic";
// public static final String ITEM_GLIDER_ADVANCED_NAME = "hang_glider_advanced";
// public static final String ITEM_GLIDER_PART_NAME = "hang_glider_part";
//
// public static final class NBT_KEYS {
//
// public static final String UPGRADES = "upgrades";
//
// }
//
// }
//
// Path: src/main/java/gr8pefish/openglider/api/OpenGliderInfo.java
// public class OpenGliderInfo {
//
// /** The internally used mod ID **/
// public static final String MODID = "openglider";
//
// /** The externally used mod name **/
// public static final String MOD_NAME = "Open Glider";
//
// }
| import gr8pefish.openglider.common.OpenGlider;
import gr8pefish.openglider.common.lib.ModInfo;
import net.minecraft.creativetab.CreativeTabs;
import net.minecraft.item.Item;
import net.minecraft.item.ItemStack;
import net.minecraft.util.NonNullList;
import static gr8pefish.openglider.api.OpenGliderInfo.*; | package gr8pefish.openglider.common.item;
public class ItemHangGliderPart extends Item {
public static String[] names = {"wing_left", "wing_right", "scaffolding"};
public ItemHangGliderPart() {
super(); | // Path: src/main/java/gr8pefish/openglider/common/OpenGlider.java
// @Mod(modid = MODID, name = MOD_NAME, version = ModInfo.VERSION, guiFactory = ModInfo.GUI_FACTORY, acceptedMinecraftVersions = "[1.12,1.13)")//, updateJSON = FORGE_UPDATE_JSON_URL) //disabled version update checker for now, as it was giving false positives
// public class OpenGlider {
//
// //Proxies
// @SidedProxy(clientSide = ModInfo.CLIENT_PROXY, serverSide = ModInfo.COMMON_PROXY)
// public static IProxy proxy;
//
// //Creative Tab
// public static final CreativeTabs creativeTab = new CreativeTabs(MODID) {
//
// @Override
// public ItemStack createIcon() {
// return new ItemStack(ItemRegistry.GLIDER_BASIC);
// }
// };
//
// //Mod Instance
// @Mod.Instance
// public static OpenGlider instance;
//
//
// @Mod.EventHandler
// public void preInit(FMLPreInitializationEvent event) {
//
// //config
// ConfigHandler.init(event.getSuggestedConfigurationFile());
//
// //wind
// WindHelper.initNoiseGenerator();
//
// //register capabilities
// CapabilityRegistry.registerAllCapabilities();
//
// //packets
// PacketHandler.init();
//
// //init renderers and client event handlers
// proxy.preInit(event);
// }
//
//
// @Mod.EventHandler
// public void init(FMLInitializationEvent event) {
//
// //upgrades
// UpgradeItems.initUpgradesList();
//
// //register server events
// MinecraftForge.EVENT_BUS.register(new ServerEventHandler());
// //register config changed event
// MinecraftForge.EVENT_BUS.register(new ConfigHandler());
//
// proxy.init(event);
// }
//
//
// @Mod.EventHandler
// public void postInit(FMLPostInitializationEvent event) {
//
// proxy.postInit(event);
// }
// }
//
// Path: src/main/java/gr8pefish/openglider/common/lib/ModInfo.java
// public class ModInfo {
//
// public static final String DOMAIN = MODID.toLowerCase(Locale.ENGLISH) + ":"; //for resources
// public static final String VERSION = "@VERSION@";
// public static final String FORGE_UPDATE_JSON_URL = "https://raw.githubusercontent.com/gr8pefish/OpenGlider/1.10/versions/update.json";
// public static final String GUI_FACTORY = "gr8pefish.openglider.client.gui.GuiFactory"; //for in-game config
//
// public static final String COMMON_PROXY = "gr8pefish.openglider.common.proxy.CommonProxy";
// public static final String CLIENT_PROXY = "gr8pefish.openglider.client.proxy.ClientProxy";
//
// public static final String NETWORK_CHANNEL = "opngldr";
//
// public static final String ITEM_GLIDER_BASIC_NAME = "hang_glider_basic";
// public static final String ITEM_GLIDER_ADVANCED_NAME = "hang_glider_advanced";
// public static final String ITEM_GLIDER_PART_NAME = "hang_glider_part";
//
// public static final class NBT_KEYS {
//
// public static final String UPGRADES = "upgrades";
//
// }
//
// }
//
// Path: src/main/java/gr8pefish/openglider/api/OpenGliderInfo.java
// public class OpenGliderInfo {
//
// /** The internally used mod ID **/
// public static final String MODID = "openglider";
//
// /** The externally used mod name **/
// public static final String MOD_NAME = "Open Glider";
//
// }
// Path: src/main/java/gr8pefish/openglider/common/item/ItemHangGliderPart.java
import gr8pefish.openglider.common.OpenGlider;
import gr8pefish.openglider.common.lib.ModInfo;
import net.minecraft.creativetab.CreativeTabs;
import net.minecraft.item.Item;
import net.minecraft.item.ItemStack;
import net.minecraft.util.NonNullList;
import static gr8pefish.openglider.api.OpenGliderInfo.*;
package gr8pefish.openglider.common.item;
public class ItemHangGliderPart extends Item {
public static String[] names = {"wing_left", "wing_right", "scaffolding"};
public ItemHangGliderPart() {
super(); | setCreativeTab(OpenGlider.creativeTab); |
gr8pefish/OpenGlider | src/main/java/gr8pefish/openglider/common/item/ItemHangGliderPart.java | // Path: src/main/java/gr8pefish/openglider/common/OpenGlider.java
// @Mod(modid = MODID, name = MOD_NAME, version = ModInfo.VERSION, guiFactory = ModInfo.GUI_FACTORY, acceptedMinecraftVersions = "[1.12,1.13)")//, updateJSON = FORGE_UPDATE_JSON_URL) //disabled version update checker for now, as it was giving false positives
// public class OpenGlider {
//
// //Proxies
// @SidedProxy(clientSide = ModInfo.CLIENT_PROXY, serverSide = ModInfo.COMMON_PROXY)
// public static IProxy proxy;
//
// //Creative Tab
// public static final CreativeTabs creativeTab = new CreativeTabs(MODID) {
//
// @Override
// public ItemStack createIcon() {
// return new ItemStack(ItemRegistry.GLIDER_BASIC);
// }
// };
//
// //Mod Instance
// @Mod.Instance
// public static OpenGlider instance;
//
//
// @Mod.EventHandler
// public void preInit(FMLPreInitializationEvent event) {
//
// //config
// ConfigHandler.init(event.getSuggestedConfigurationFile());
//
// //wind
// WindHelper.initNoiseGenerator();
//
// //register capabilities
// CapabilityRegistry.registerAllCapabilities();
//
// //packets
// PacketHandler.init();
//
// //init renderers and client event handlers
// proxy.preInit(event);
// }
//
//
// @Mod.EventHandler
// public void init(FMLInitializationEvent event) {
//
// //upgrades
// UpgradeItems.initUpgradesList();
//
// //register server events
// MinecraftForge.EVENT_BUS.register(new ServerEventHandler());
// //register config changed event
// MinecraftForge.EVENT_BUS.register(new ConfigHandler());
//
// proxy.init(event);
// }
//
//
// @Mod.EventHandler
// public void postInit(FMLPostInitializationEvent event) {
//
// proxy.postInit(event);
// }
// }
//
// Path: src/main/java/gr8pefish/openglider/common/lib/ModInfo.java
// public class ModInfo {
//
// public static final String DOMAIN = MODID.toLowerCase(Locale.ENGLISH) + ":"; //for resources
// public static final String VERSION = "@VERSION@";
// public static final String FORGE_UPDATE_JSON_URL = "https://raw.githubusercontent.com/gr8pefish/OpenGlider/1.10/versions/update.json";
// public static final String GUI_FACTORY = "gr8pefish.openglider.client.gui.GuiFactory"; //for in-game config
//
// public static final String COMMON_PROXY = "gr8pefish.openglider.common.proxy.CommonProxy";
// public static final String CLIENT_PROXY = "gr8pefish.openglider.client.proxy.ClientProxy";
//
// public static final String NETWORK_CHANNEL = "opngldr";
//
// public static final String ITEM_GLIDER_BASIC_NAME = "hang_glider_basic";
// public static final String ITEM_GLIDER_ADVANCED_NAME = "hang_glider_advanced";
// public static final String ITEM_GLIDER_PART_NAME = "hang_glider_part";
//
// public static final class NBT_KEYS {
//
// public static final String UPGRADES = "upgrades";
//
// }
//
// }
//
// Path: src/main/java/gr8pefish/openglider/api/OpenGliderInfo.java
// public class OpenGliderInfo {
//
// /** The internally used mod ID **/
// public static final String MODID = "openglider";
//
// /** The externally used mod name **/
// public static final String MOD_NAME = "Open Glider";
//
// }
| import gr8pefish.openglider.common.OpenGlider;
import gr8pefish.openglider.common.lib.ModInfo;
import net.minecraft.creativetab.CreativeTabs;
import net.minecraft.item.Item;
import net.minecraft.item.ItemStack;
import net.minecraft.util.NonNullList;
import static gr8pefish.openglider.api.OpenGliderInfo.*; | package gr8pefish.openglider.common.item;
public class ItemHangGliderPart extends Item {
public static String[] names = {"wing_left", "wing_right", "scaffolding"};
public ItemHangGliderPart() {
super();
setCreativeTab(OpenGlider.creativeTab);
setHasSubtypes(true); | // Path: src/main/java/gr8pefish/openglider/common/OpenGlider.java
// @Mod(modid = MODID, name = MOD_NAME, version = ModInfo.VERSION, guiFactory = ModInfo.GUI_FACTORY, acceptedMinecraftVersions = "[1.12,1.13)")//, updateJSON = FORGE_UPDATE_JSON_URL) //disabled version update checker for now, as it was giving false positives
// public class OpenGlider {
//
// //Proxies
// @SidedProxy(clientSide = ModInfo.CLIENT_PROXY, serverSide = ModInfo.COMMON_PROXY)
// public static IProxy proxy;
//
// //Creative Tab
// public static final CreativeTabs creativeTab = new CreativeTabs(MODID) {
//
// @Override
// public ItemStack createIcon() {
// return new ItemStack(ItemRegistry.GLIDER_BASIC);
// }
// };
//
// //Mod Instance
// @Mod.Instance
// public static OpenGlider instance;
//
//
// @Mod.EventHandler
// public void preInit(FMLPreInitializationEvent event) {
//
// //config
// ConfigHandler.init(event.getSuggestedConfigurationFile());
//
// //wind
// WindHelper.initNoiseGenerator();
//
// //register capabilities
// CapabilityRegistry.registerAllCapabilities();
//
// //packets
// PacketHandler.init();
//
// //init renderers and client event handlers
// proxy.preInit(event);
// }
//
//
// @Mod.EventHandler
// public void init(FMLInitializationEvent event) {
//
// //upgrades
// UpgradeItems.initUpgradesList();
//
// //register server events
// MinecraftForge.EVENT_BUS.register(new ServerEventHandler());
// //register config changed event
// MinecraftForge.EVENT_BUS.register(new ConfigHandler());
//
// proxy.init(event);
// }
//
//
// @Mod.EventHandler
// public void postInit(FMLPostInitializationEvent event) {
//
// proxy.postInit(event);
// }
// }
//
// Path: src/main/java/gr8pefish/openglider/common/lib/ModInfo.java
// public class ModInfo {
//
// public static final String DOMAIN = MODID.toLowerCase(Locale.ENGLISH) + ":"; //for resources
// public static final String VERSION = "@VERSION@";
// public static final String FORGE_UPDATE_JSON_URL = "https://raw.githubusercontent.com/gr8pefish/OpenGlider/1.10/versions/update.json";
// public static final String GUI_FACTORY = "gr8pefish.openglider.client.gui.GuiFactory"; //for in-game config
//
// public static final String COMMON_PROXY = "gr8pefish.openglider.common.proxy.CommonProxy";
// public static final String CLIENT_PROXY = "gr8pefish.openglider.client.proxy.ClientProxy";
//
// public static final String NETWORK_CHANNEL = "opngldr";
//
// public static final String ITEM_GLIDER_BASIC_NAME = "hang_glider_basic";
// public static final String ITEM_GLIDER_ADVANCED_NAME = "hang_glider_advanced";
// public static final String ITEM_GLIDER_PART_NAME = "hang_glider_part";
//
// public static final class NBT_KEYS {
//
// public static final String UPGRADES = "upgrades";
//
// }
//
// }
//
// Path: src/main/java/gr8pefish/openglider/api/OpenGliderInfo.java
// public class OpenGliderInfo {
//
// /** The internally used mod ID **/
// public static final String MODID = "openglider";
//
// /** The externally used mod name **/
// public static final String MOD_NAME = "Open Glider";
//
// }
// Path: src/main/java/gr8pefish/openglider/common/item/ItemHangGliderPart.java
import gr8pefish.openglider.common.OpenGlider;
import gr8pefish.openglider.common.lib.ModInfo;
import net.minecraft.creativetab.CreativeTabs;
import net.minecraft.item.Item;
import net.minecraft.item.ItemStack;
import net.minecraft.util.NonNullList;
import static gr8pefish.openglider.api.OpenGliderInfo.*;
package gr8pefish.openglider.common.item;
public class ItemHangGliderPart extends Item {
public static String[] names = {"wing_left", "wing_right", "scaffolding"};
public ItemHangGliderPart() {
super();
setCreativeTab(OpenGlider.creativeTab);
setHasSubtypes(true); | setTranslationKey(MODID +":" + ModInfo.ITEM_GLIDER_PART_NAME+ "."); |
gr8pefish/OpenGlider | src/main/java/gr8pefish/openglider/common/proxy/IProxy.java | // Path: src/main/java/gr8pefish/openglider/api/capabilities/IGliderCapabilityHandler.java
// public interface IGliderCapabilityHandler extends INBTSerializable<NBTTagCompound> {
//
// /**
// * Get the current gliding status of the player.
// * If True, it inherently must mean that the glider is deployed as well.
// *
// * @return - True if the player is gliding, False otherwise.
// */
// boolean getIsPlayerGliding();
//
// /**
// * Set the player's current gliding status.
// * If True, it inherently must mean that the glider is deployed as well.
// *
// * @param isPlayerGliding - True if the player is gliding, False otherwise.
// */
// void setIsPlayerGliding(boolean isPlayerGliding);
//
// /**
// * Get the current deployment status of the glider on the player.
// *
// * @return True is the player has a deployed glider, False otherwise.
// */
// boolean getIsGliderDeployed();
//
// /**
// * Set the player's glider's deployment status.
// *
// * @param isGliderDeployed - True if the glider is deployed, False otherwise.
// */
// void setIsGliderDeployed(boolean isGliderDeployed);
//
// /**
// * Sync the (above) data stored in the capability to a given player.
// *
// * @param player - the player to sync the data to.
// */
// void sync(EntityPlayerMP player);
//
// }
| import gr8pefish.openglider.api.capabilities.IGliderCapabilityHandler;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.world.World;
import net.minecraftforge.fml.common.event.FMLInitializationEvent;
import net.minecraftforge.fml.common.event.FMLPostInitializationEvent;
import net.minecraftforge.fml.common.event.FMLPreInitializationEvent; | package gr8pefish.openglider.common.proxy;
public interface IProxy {
public void preInit(FMLPreInitializationEvent event);
public void init(FMLInitializationEvent event);
public void postInit(FMLPostInitializationEvent event);
public EntityPlayer getClientPlayer();
public World getClientWorld();
| // Path: src/main/java/gr8pefish/openglider/api/capabilities/IGliderCapabilityHandler.java
// public interface IGliderCapabilityHandler extends INBTSerializable<NBTTagCompound> {
//
// /**
// * Get the current gliding status of the player.
// * If True, it inherently must mean that the glider is deployed as well.
// *
// * @return - True if the player is gliding, False otherwise.
// */
// boolean getIsPlayerGliding();
//
// /**
// * Set the player's current gliding status.
// * If True, it inherently must mean that the glider is deployed as well.
// *
// * @param isPlayerGliding - True if the player is gliding, False otherwise.
// */
// void setIsPlayerGliding(boolean isPlayerGliding);
//
// /**
// * Get the current deployment status of the glider on the player.
// *
// * @return True is the player has a deployed glider, False otherwise.
// */
// boolean getIsGliderDeployed();
//
// /**
// * Set the player's glider's deployment status.
// *
// * @param isGliderDeployed - True if the glider is deployed, False otherwise.
// */
// void setIsGliderDeployed(boolean isGliderDeployed);
//
// /**
// * Sync the (above) data stored in the capability to a given player.
// *
// * @param player - the player to sync the data to.
// */
// void sync(EntityPlayerMP player);
//
// }
// Path: src/main/java/gr8pefish/openglider/common/proxy/IProxy.java
import gr8pefish.openglider.api.capabilities.IGliderCapabilityHandler;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.world.World;
import net.minecraftforge.fml.common.event.FMLInitializationEvent;
import net.minecraftforge.fml.common.event.FMLPostInitializationEvent;
import net.minecraftforge.fml.common.event.FMLPreInitializationEvent;
package gr8pefish.openglider.common.proxy;
public interface IProxy {
public void preInit(FMLPreInitializationEvent event);
public void init(FMLInitializationEvent event);
public void postInit(FMLPostInitializationEvent event);
public EntityPlayer getClientPlayer();
public World getClientWorld();
| public IGliderCapabilityHandler getClientGliderCapability(); |
gr8pefish/OpenGlider | src/main/java/gr8pefish/openglider/common/registry/ItemRegistry.java | // Path: src/main/java/gr8pefish/openglider/common/item/ItemHangGliderAdvanced.java
// public class ItemHangGliderAdvanced extends ItemHangGliderBase {
//
// public ItemHangGliderAdvanced() {
// super(ConfigHandler.advancedGliderHorizSpeed, ConfigHandler.advancedGliderVertSpeed, ConfigHandler.advancedGliderShiftHorizSpeed, ConfigHandler.advancedGliderShiftVertSpeed, ConfigHandler.advancedGliderWindModifier, ConfigHandler.advancedGliderAirResistance, ConfigHandler.advancedGliderTotalDurability, ModelGlider.MODEL_GLIDER_ADVANCED_TEXTURE_RL);
// setCreativeTab(OpenGlider.creativeTab);
// setTranslationKey(MODID +":" + ModInfo.ITEM_GLIDER_ADVANCED_NAME);
// }
//
// //ToDo: Needed?
// @Override
// public NBTTagCompound serializeNBT() {
// return null;
// }
//
// @Override
// public void deserializeNBT(NBTTagCompound nbt) {
//
// }
// }
//
// Path: src/main/java/gr8pefish/openglider/common/item/ItemHangGliderBasic.java
// public class ItemHangGliderBasic extends ItemHangGliderBase {
//
// public ItemHangGliderBasic() {
// super(ConfigHandler.basicGliderHorizSpeed, ConfigHandler.basicGliderVertSpeed, ConfigHandler.basicGliderShiftHorizSpeed, ConfigHandler.basicGliderShiftVertSpeed, ConfigHandler.basicGliderWindModifier, ConfigHandler.basicGliderAirResistance, ConfigHandler.basicGliderTotalDurability, ModelGlider.MODEL_GLIDER_BASIC_TEXTURE_RL);
// setCreativeTab(OpenGlider.creativeTab);
// setTranslationKey(MODID +":" + ModInfo.ITEM_GLIDER_BASIC_NAME);
// }
//
// //ToDo: Needed?
// @Override
// public NBTTagCompound serializeNBT() {
// return null;
// }
//
// @Override
// public void deserializeNBT(NBTTagCompound nbt) {
//
// }
// }
//
// Path: src/main/java/gr8pefish/openglider/common/item/ItemHangGliderPart.java
// public class ItemHangGliderPart extends Item {
//
// public static String[] names = {"wing_left", "wing_right", "scaffolding"};
//
// public ItemHangGliderPart() {
// super();
// setCreativeTab(OpenGlider.creativeTab);
// setHasSubtypes(true);
// setTranslationKey(MODID +":" + ModInfo.ITEM_GLIDER_PART_NAME+ ".");
// }
//
// @Override
// public void getSubItems(CreativeTabs tab, NonNullList<ItemStack> subItems) {
// if (isInCreativeTab(tab)) {
// for (int i = 0; i < names.length; i++)
// subItems.add(new ItemStack(this, 1, i));
// }
// }
//
// @Override
// public String getTranslationKey(ItemStack stack) {
// return super.getTranslationKey(stack) + names[stack.getItemDamage()];
// }
//
// }
//
// Path: src/main/java/gr8pefish/openglider/common/lib/ModInfo.java
// public class ModInfo {
//
// public static final String DOMAIN = MODID.toLowerCase(Locale.ENGLISH) + ":"; //for resources
// public static final String VERSION = "@VERSION@";
// public static final String FORGE_UPDATE_JSON_URL = "https://raw.githubusercontent.com/gr8pefish/OpenGlider/1.10/versions/update.json";
// public static final String GUI_FACTORY = "gr8pefish.openglider.client.gui.GuiFactory"; //for in-game config
//
// public static final String COMMON_PROXY = "gr8pefish.openglider.common.proxy.CommonProxy";
// public static final String CLIENT_PROXY = "gr8pefish.openglider.client.proxy.ClientProxy";
//
// public static final String NETWORK_CHANNEL = "opngldr";
//
// public static final String ITEM_GLIDER_BASIC_NAME = "hang_glider_basic";
// public static final String ITEM_GLIDER_ADVANCED_NAME = "hang_glider_advanced";
// public static final String ITEM_GLIDER_PART_NAME = "hang_glider_part";
//
// public static final class NBT_KEYS {
//
// public static final String UPGRADES = "upgrades";
//
// }
//
// }
//
// Path: src/main/java/gr8pefish/openglider/api/OpenGliderInfo.java
// public static final String MODID = "openglider";
| import gr8pefish.openglider.common.item.ItemHangGliderAdvanced;
import gr8pefish.openglider.common.item.ItemHangGliderBasic;
import gr8pefish.openglider.common.item.ItemHangGliderPart;
import gr8pefish.openglider.common.lib.ModInfo;
import net.minecraft.client.renderer.block.model.ModelResourceLocation;
import net.minecraft.item.Item;
import net.minecraftforge.client.event.ModelRegistryEvent;
import net.minecraftforge.client.model.ModelLoader;
import net.minecraftforge.event.RegistryEvent;
import net.minecraftforge.fml.common.Mod;
import net.minecraftforge.fml.common.eventhandler.SubscribeEvent;
import net.minecraftforge.fml.common.registry.GameRegistry;
import net.minecraftforge.fml.relauncher.Side;
import net.minecraftforge.fml.relauncher.SideOnly;
import static gr8pefish.openglider.api.OpenGliderInfo.MODID; | package gr8pefish.openglider.common.registry;
//import gr8pefish.openglider.common.recipe.AddUpgradeToGliderRecipe;
//import gr8pefish.openglider.common.recipe.RemoveUpgradeFromGliderRecipe;
@Mod.EventBusSubscriber
@GameRegistry.ObjectHolder(MODID)
public class ItemRegistry {
// Items | // Path: src/main/java/gr8pefish/openglider/common/item/ItemHangGliderAdvanced.java
// public class ItemHangGliderAdvanced extends ItemHangGliderBase {
//
// public ItemHangGliderAdvanced() {
// super(ConfigHandler.advancedGliderHorizSpeed, ConfigHandler.advancedGliderVertSpeed, ConfigHandler.advancedGliderShiftHorizSpeed, ConfigHandler.advancedGliderShiftVertSpeed, ConfigHandler.advancedGliderWindModifier, ConfigHandler.advancedGliderAirResistance, ConfigHandler.advancedGliderTotalDurability, ModelGlider.MODEL_GLIDER_ADVANCED_TEXTURE_RL);
// setCreativeTab(OpenGlider.creativeTab);
// setTranslationKey(MODID +":" + ModInfo.ITEM_GLIDER_ADVANCED_NAME);
// }
//
// //ToDo: Needed?
// @Override
// public NBTTagCompound serializeNBT() {
// return null;
// }
//
// @Override
// public void deserializeNBT(NBTTagCompound nbt) {
//
// }
// }
//
// Path: src/main/java/gr8pefish/openglider/common/item/ItemHangGliderBasic.java
// public class ItemHangGliderBasic extends ItemHangGliderBase {
//
// public ItemHangGliderBasic() {
// super(ConfigHandler.basicGliderHorizSpeed, ConfigHandler.basicGliderVertSpeed, ConfigHandler.basicGliderShiftHorizSpeed, ConfigHandler.basicGliderShiftVertSpeed, ConfigHandler.basicGliderWindModifier, ConfigHandler.basicGliderAirResistance, ConfigHandler.basicGliderTotalDurability, ModelGlider.MODEL_GLIDER_BASIC_TEXTURE_RL);
// setCreativeTab(OpenGlider.creativeTab);
// setTranslationKey(MODID +":" + ModInfo.ITEM_GLIDER_BASIC_NAME);
// }
//
// //ToDo: Needed?
// @Override
// public NBTTagCompound serializeNBT() {
// return null;
// }
//
// @Override
// public void deserializeNBT(NBTTagCompound nbt) {
//
// }
// }
//
// Path: src/main/java/gr8pefish/openglider/common/item/ItemHangGliderPart.java
// public class ItemHangGliderPart extends Item {
//
// public static String[] names = {"wing_left", "wing_right", "scaffolding"};
//
// public ItemHangGliderPart() {
// super();
// setCreativeTab(OpenGlider.creativeTab);
// setHasSubtypes(true);
// setTranslationKey(MODID +":" + ModInfo.ITEM_GLIDER_PART_NAME+ ".");
// }
//
// @Override
// public void getSubItems(CreativeTabs tab, NonNullList<ItemStack> subItems) {
// if (isInCreativeTab(tab)) {
// for (int i = 0; i < names.length; i++)
// subItems.add(new ItemStack(this, 1, i));
// }
// }
//
// @Override
// public String getTranslationKey(ItemStack stack) {
// return super.getTranslationKey(stack) + names[stack.getItemDamage()];
// }
//
// }
//
// Path: src/main/java/gr8pefish/openglider/common/lib/ModInfo.java
// public class ModInfo {
//
// public static final String DOMAIN = MODID.toLowerCase(Locale.ENGLISH) + ":"; //for resources
// public static final String VERSION = "@VERSION@";
// public static final String FORGE_UPDATE_JSON_URL = "https://raw.githubusercontent.com/gr8pefish/OpenGlider/1.10/versions/update.json";
// public static final String GUI_FACTORY = "gr8pefish.openglider.client.gui.GuiFactory"; //for in-game config
//
// public static final String COMMON_PROXY = "gr8pefish.openglider.common.proxy.CommonProxy";
// public static final String CLIENT_PROXY = "gr8pefish.openglider.client.proxy.ClientProxy";
//
// public static final String NETWORK_CHANNEL = "opngldr";
//
// public static final String ITEM_GLIDER_BASIC_NAME = "hang_glider_basic";
// public static final String ITEM_GLIDER_ADVANCED_NAME = "hang_glider_advanced";
// public static final String ITEM_GLIDER_PART_NAME = "hang_glider_part";
//
// public static final class NBT_KEYS {
//
// public static final String UPGRADES = "upgrades";
//
// }
//
// }
//
// Path: src/main/java/gr8pefish/openglider/api/OpenGliderInfo.java
// public static final String MODID = "openglider";
// Path: src/main/java/gr8pefish/openglider/common/registry/ItemRegistry.java
import gr8pefish.openglider.common.item.ItemHangGliderAdvanced;
import gr8pefish.openglider.common.item.ItemHangGliderBasic;
import gr8pefish.openglider.common.item.ItemHangGliderPart;
import gr8pefish.openglider.common.lib.ModInfo;
import net.minecraft.client.renderer.block.model.ModelResourceLocation;
import net.minecraft.item.Item;
import net.minecraftforge.client.event.ModelRegistryEvent;
import net.minecraftforge.client.model.ModelLoader;
import net.minecraftforge.event.RegistryEvent;
import net.minecraftforge.fml.common.Mod;
import net.minecraftforge.fml.common.eventhandler.SubscribeEvent;
import net.minecraftforge.fml.common.registry.GameRegistry;
import net.minecraftforge.fml.relauncher.Side;
import net.minecraftforge.fml.relauncher.SideOnly;
import static gr8pefish.openglider.api.OpenGliderInfo.MODID;
package gr8pefish.openglider.common.registry;
//import gr8pefish.openglider.common.recipe.AddUpgradeToGliderRecipe;
//import gr8pefish.openglider.common.recipe.RemoveUpgradeFromGliderRecipe;
@Mod.EventBusSubscriber
@GameRegistry.ObjectHolder(MODID)
public class ItemRegistry {
// Items | @GameRegistry.ObjectHolder(ModInfo.ITEM_GLIDER_PART_NAME) |
gr8pefish/OpenGlider | src/main/java/gr8pefish/openglider/common/registry/ItemRegistry.java | // Path: src/main/java/gr8pefish/openglider/common/item/ItemHangGliderAdvanced.java
// public class ItemHangGliderAdvanced extends ItemHangGliderBase {
//
// public ItemHangGliderAdvanced() {
// super(ConfigHandler.advancedGliderHorizSpeed, ConfigHandler.advancedGliderVertSpeed, ConfigHandler.advancedGliderShiftHorizSpeed, ConfigHandler.advancedGliderShiftVertSpeed, ConfigHandler.advancedGliderWindModifier, ConfigHandler.advancedGliderAirResistance, ConfigHandler.advancedGliderTotalDurability, ModelGlider.MODEL_GLIDER_ADVANCED_TEXTURE_RL);
// setCreativeTab(OpenGlider.creativeTab);
// setTranslationKey(MODID +":" + ModInfo.ITEM_GLIDER_ADVANCED_NAME);
// }
//
// //ToDo: Needed?
// @Override
// public NBTTagCompound serializeNBT() {
// return null;
// }
//
// @Override
// public void deserializeNBT(NBTTagCompound nbt) {
//
// }
// }
//
// Path: src/main/java/gr8pefish/openglider/common/item/ItemHangGliderBasic.java
// public class ItemHangGliderBasic extends ItemHangGliderBase {
//
// public ItemHangGliderBasic() {
// super(ConfigHandler.basicGliderHorizSpeed, ConfigHandler.basicGliderVertSpeed, ConfigHandler.basicGliderShiftHorizSpeed, ConfigHandler.basicGliderShiftVertSpeed, ConfigHandler.basicGliderWindModifier, ConfigHandler.basicGliderAirResistance, ConfigHandler.basicGliderTotalDurability, ModelGlider.MODEL_GLIDER_BASIC_TEXTURE_RL);
// setCreativeTab(OpenGlider.creativeTab);
// setTranslationKey(MODID +":" + ModInfo.ITEM_GLIDER_BASIC_NAME);
// }
//
// //ToDo: Needed?
// @Override
// public NBTTagCompound serializeNBT() {
// return null;
// }
//
// @Override
// public void deserializeNBT(NBTTagCompound nbt) {
//
// }
// }
//
// Path: src/main/java/gr8pefish/openglider/common/item/ItemHangGliderPart.java
// public class ItemHangGliderPart extends Item {
//
// public static String[] names = {"wing_left", "wing_right", "scaffolding"};
//
// public ItemHangGliderPart() {
// super();
// setCreativeTab(OpenGlider.creativeTab);
// setHasSubtypes(true);
// setTranslationKey(MODID +":" + ModInfo.ITEM_GLIDER_PART_NAME+ ".");
// }
//
// @Override
// public void getSubItems(CreativeTabs tab, NonNullList<ItemStack> subItems) {
// if (isInCreativeTab(tab)) {
// for (int i = 0; i < names.length; i++)
// subItems.add(new ItemStack(this, 1, i));
// }
// }
//
// @Override
// public String getTranslationKey(ItemStack stack) {
// return super.getTranslationKey(stack) + names[stack.getItemDamage()];
// }
//
// }
//
// Path: src/main/java/gr8pefish/openglider/common/lib/ModInfo.java
// public class ModInfo {
//
// public static final String DOMAIN = MODID.toLowerCase(Locale.ENGLISH) + ":"; //for resources
// public static final String VERSION = "@VERSION@";
// public static final String FORGE_UPDATE_JSON_URL = "https://raw.githubusercontent.com/gr8pefish/OpenGlider/1.10/versions/update.json";
// public static final String GUI_FACTORY = "gr8pefish.openglider.client.gui.GuiFactory"; //for in-game config
//
// public static final String COMMON_PROXY = "gr8pefish.openglider.common.proxy.CommonProxy";
// public static final String CLIENT_PROXY = "gr8pefish.openglider.client.proxy.ClientProxy";
//
// public static final String NETWORK_CHANNEL = "opngldr";
//
// public static final String ITEM_GLIDER_BASIC_NAME = "hang_glider_basic";
// public static final String ITEM_GLIDER_ADVANCED_NAME = "hang_glider_advanced";
// public static final String ITEM_GLIDER_PART_NAME = "hang_glider_part";
//
// public static final class NBT_KEYS {
//
// public static final String UPGRADES = "upgrades";
//
// }
//
// }
//
// Path: src/main/java/gr8pefish/openglider/api/OpenGliderInfo.java
// public static final String MODID = "openglider";
| import gr8pefish.openglider.common.item.ItemHangGliderAdvanced;
import gr8pefish.openglider.common.item.ItemHangGliderBasic;
import gr8pefish.openglider.common.item.ItemHangGliderPart;
import gr8pefish.openglider.common.lib.ModInfo;
import net.minecraft.client.renderer.block.model.ModelResourceLocation;
import net.minecraft.item.Item;
import net.minecraftforge.client.event.ModelRegistryEvent;
import net.minecraftforge.client.model.ModelLoader;
import net.minecraftforge.event.RegistryEvent;
import net.minecraftforge.fml.common.Mod;
import net.minecraftforge.fml.common.eventhandler.SubscribeEvent;
import net.minecraftforge.fml.common.registry.GameRegistry;
import net.minecraftforge.fml.relauncher.Side;
import net.minecraftforge.fml.relauncher.SideOnly;
import static gr8pefish.openglider.api.OpenGliderInfo.MODID; | package gr8pefish.openglider.common.registry;
//import gr8pefish.openglider.common.recipe.AddUpgradeToGliderRecipe;
//import gr8pefish.openglider.common.recipe.RemoveUpgradeFromGliderRecipe;
@Mod.EventBusSubscriber
@GameRegistry.ObjectHolder(MODID)
public class ItemRegistry {
// Items
@GameRegistry.ObjectHolder(ModInfo.ITEM_GLIDER_PART_NAME) | // Path: src/main/java/gr8pefish/openglider/common/item/ItemHangGliderAdvanced.java
// public class ItemHangGliderAdvanced extends ItemHangGliderBase {
//
// public ItemHangGliderAdvanced() {
// super(ConfigHandler.advancedGliderHorizSpeed, ConfigHandler.advancedGliderVertSpeed, ConfigHandler.advancedGliderShiftHorizSpeed, ConfigHandler.advancedGliderShiftVertSpeed, ConfigHandler.advancedGliderWindModifier, ConfigHandler.advancedGliderAirResistance, ConfigHandler.advancedGliderTotalDurability, ModelGlider.MODEL_GLIDER_ADVANCED_TEXTURE_RL);
// setCreativeTab(OpenGlider.creativeTab);
// setTranslationKey(MODID +":" + ModInfo.ITEM_GLIDER_ADVANCED_NAME);
// }
//
// //ToDo: Needed?
// @Override
// public NBTTagCompound serializeNBT() {
// return null;
// }
//
// @Override
// public void deserializeNBT(NBTTagCompound nbt) {
//
// }
// }
//
// Path: src/main/java/gr8pefish/openglider/common/item/ItemHangGliderBasic.java
// public class ItemHangGliderBasic extends ItemHangGliderBase {
//
// public ItemHangGliderBasic() {
// super(ConfigHandler.basicGliderHorizSpeed, ConfigHandler.basicGliderVertSpeed, ConfigHandler.basicGliderShiftHorizSpeed, ConfigHandler.basicGliderShiftVertSpeed, ConfigHandler.basicGliderWindModifier, ConfigHandler.basicGliderAirResistance, ConfigHandler.basicGliderTotalDurability, ModelGlider.MODEL_GLIDER_BASIC_TEXTURE_RL);
// setCreativeTab(OpenGlider.creativeTab);
// setTranslationKey(MODID +":" + ModInfo.ITEM_GLIDER_BASIC_NAME);
// }
//
// //ToDo: Needed?
// @Override
// public NBTTagCompound serializeNBT() {
// return null;
// }
//
// @Override
// public void deserializeNBT(NBTTagCompound nbt) {
//
// }
// }
//
// Path: src/main/java/gr8pefish/openglider/common/item/ItemHangGliderPart.java
// public class ItemHangGliderPart extends Item {
//
// public static String[] names = {"wing_left", "wing_right", "scaffolding"};
//
// public ItemHangGliderPart() {
// super();
// setCreativeTab(OpenGlider.creativeTab);
// setHasSubtypes(true);
// setTranslationKey(MODID +":" + ModInfo.ITEM_GLIDER_PART_NAME+ ".");
// }
//
// @Override
// public void getSubItems(CreativeTabs tab, NonNullList<ItemStack> subItems) {
// if (isInCreativeTab(tab)) {
// for (int i = 0; i < names.length; i++)
// subItems.add(new ItemStack(this, 1, i));
// }
// }
//
// @Override
// public String getTranslationKey(ItemStack stack) {
// return super.getTranslationKey(stack) + names[stack.getItemDamage()];
// }
//
// }
//
// Path: src/main/java/gr8pefish/openglider/common/lib/ModInfo.java
// public class ModInfo {
//
// public static final String DOMAIN = MODID.toLowerCase(Locale.ENGLISH) + ":"; //for resources
// public static final String VERSION = "@VERSION@";
// public static final String FORGE_UPDATE_JSON_URL = "https://raw.githubusercontent.com/gr8pefish/OpenGlider/1.10/versions/update.json";
// public static final String GUI_FACTORY = "gr8pefish.openglider.client.gui.GuiFactory"; //for in-game config
//
// public static final String COMMON_PROXY = "gr8pefish.openglider.common.proxy.CommonProxy";
// public static final String CLIENT_PROXY = "gr8pefish.openglider.client.proxy.ClientProxy";
//
// public static final String NETWORK_CHANNEL = "opngldr";
//
// public static final String ITEM_GLIDER_BASIC_NAME = "hang_glider_basic";
// public static final String ITEM_GLIDER_ADVANCED_NAME = "hang_glider_advanced";
// public static final String ITEM_GLIDER_PART_NAME = "hang_glider_part";
//
// public static final class NBT_KEYS {
//
// public static final String UPGRADES = "upgrades";
//
// }
//
// }
//
// Path: src/main/java/gr8pefish/openglider/api/OpenGliderInfo.java
// public static final String MODID = "openglider";
// Path: src/main/java/gr8pefish/openglider/common/registry/ItemRegistry.java
import gr8pefish.openglider.common.item.ItemHangGliderAdvanced;
import gr8pefish.openglider.common.item.ItemHangGliderBasic;
import gr8pefish.openglider.common.item.ItemHangGliderPart;
import gr8pefish.openglider.common.lib.ModInfo;
import net.minecraft.client.renderer.block.model.ModelResourceLocation;
import net.minecraft.item.Item;
import net.minecraftforge.client.event.ModelRegistryEvent;
import net.minecraftforge.client.model.ModelLoader;
import net.minecraftforge.event.RegistryEvent;
import net.minecraftforge.fml.common.Mod;
import net.minecraftforge.fml.common.eventhandler.SubscribeEvent;
import net.minecraftforge.fml.common.registry.GameRegistry;
import net.minecraftforge.fml.relauncher.Side;
import net.minecraftforge.fml.relauncher.SideOnly;
import static gr8pefish.openglider.api.OpenGliderInfo.MODID;
package gr8pefish.openglider.common.registry;
//import gr8pefish.openglider.common.recipe.AddUpgradeToGliderRecipe;
//import gr8pefish.openglider.common.recipe.RemoveUpgradeFromGliderRecipe;
@Mod.EventBusSubscriber
@GameRegistry.ObjectHolder(MODID)
public class ItemRegistry {
// Items
@GameRegistry.ObjectHolder(ModInfo.ITEM_GLIDER_PART_NAME) | public static final ItemHangGliderPart GLIDER_PART = null; |
gr8pefish/OpenGlider | src/main/java/gr8pefish/openglider/common/registry/ItemRegistry.java | // Path: src/main/java/gr8pefish/openglider/common/item/ItemHangGliderAdvanced.java
// public class ItemHangGliderAdvanced extends ItemHangGliderBase {
//
// public ItemHangGliderAdvanced() {
// super(ConfigHandler.advancedGliderHorizSpeed, ConfigHandler.advancedGliderVertSpeed, ConfigHandler.advancedGliderShiftHorizSpeed, ConfigHandler.advancedGliderShiftVertSpeed, ConfigHandler.advancedGliderWindModifier, ConfigHandler.advancedGliderAirResistance, ConfigHandler.advancedGliderTotalDurability, ModelGlider.MODEL_GLIDER_ADVANCED_TEXTURE_RL);
// setCreativeTab(OpenGlider.creativeTab);
// setTranslationKey(MODID +":" + ModInfo.ITEM_GLIDER_ADVANCED_NAME);
// }
//
// //ToDo: Needed?
// @Override
// public NBTTagCompound serializeNBT() {
// return null;
// }
//
// @Override
// public void deserializeNBT(NBTTagCompound nbt) {
//
// }
// }
//
// Path: src/main/java/gr8pefish/openglider/common/item/ItemHangGliderBasic.java
// public class ItemHangGliderBasic extends ItemHangGliderBase {
//
// public ItemHangGliderBasic() {
// super(ConfigHandler.basicGliderHorizSpeed, ConfigHandler.basicGliderVertSpeed, ConfigHandler.basicGliderShiftHorizSpeed, ConfigHandler.basicGliderShiftVertSpeed, ConfigHandler.basicGliderWindModifier, ConfigHandler.basicGliderAirResistance, ConfigHandler.basicGliderTotalDurability, ModelGlider.MODEL_GLIDER_BASIC_TEXTURE_RL);
// setCreativeTab(OpenGlider.creativeTab);
// setTranslationKey(MODID +":" + ModInfo.ITEM_GLIDER_BASIC_NAME);
// }
//
// //ToDo: Needed?
// @Override
// public NBTTagCompound serializeNBT() {
// return null;
// }
//
// @Override
// public void deserializeNBT(NBTTagCompound nbt) {
//
// }
// }
//
// Path: src/main/java/gr8pefish/openglider/common/item/ItemHangGliderPart.java
// public class ItemHangGliderPart extends Item {
//
// public static String[] names = {"wing_left", "wing_right", "scaffolding"};
//
// public ItemHangGliderPart() {
// super();
// setCreativeTab(OpenGlider.creativeTab);
// setHasSubtypes(true);
// setTranslationKey(MODID +":" + ModInfo.ITEM_GLIDER_PART_NAME+ ".");
// }
//
// @Override
// public void getSubItems(CreativeTabs tab, NonNullList<ItemStack> subItems) {
// if (isInCreativeTab(tab)) {
// for (int i = 0; i < names.length; i++)
// subItems.add(new ItemStack(this, 1, i));
// }
// }
//
// @Override
// public String getTranslationKey(ItemStack stack) {
// return super.getTranslationKey(stack) + names[stack.getItemDamage()];
// }
//
// }
//
// Path: src/main/java/gr8pefish/openglider/common/lib/ModInfo.java
// public class ModInfo {
//
// public static final String DOMAIN = MODID.toLowerCase(Locale.ENGLISH) + ":"; //for resources
// public static final String VERSION = "@VERSION@";
// public static final String FORGE_UPDATE_JSON_URL = "https://raw.githubusercontent.com/gr8pefish/OpenGlider/1.10/versions/update.json";
// public static final String GUI_FACTORY = "gr8pefish.openglider.client.gui.GuiFactory"; //for in-game config
//
// public static final String COMMON_PROXY = "gr8pefish.openglider.common.proxy.CommonProxy";
// public static final String CLIENT_PROXY = "gr8pefish.openglider.client.proxy.ClientProxy";
//
// public static final String NETWORK_CHANNEL = "opngldr";
//
// public static final String ITEM_GLIDER_BASIC_NAME = "hang_glider_basic";
// public static final String ITEM_GLIDER_ADVANCED_NAME = "hang_glider_advanced";
// public static final String ITEM_GLIDER_PART_NAME = "hang_glider_part";
//
// public static final class NBT_KEYS {
//
// public static final String UPGRADES = "upgrades";
//
// }
//
// }
//
// Path: src/main/java/gr8pefish/openglider/api/OpenGliderInfo.java
// public static final String MODID = "openglider";
| import gr8pefish.openglider.common.item.ItemHangGliderAdvanced;
import gr8pefish.openglider.common.item.ItemHangGliderBasic;
import gr8pefish.openglider.common.item.ItemHangGliderPart;
import gr8pefish.openglider.common.lib.ModInfo;
import net.minecraft.client.renderer.block.model.ModelResourceLocation;
import net.minecraft.item.Item;
import net.minecraftforge.client.event.ModelRegistryEvent;
import net.minecraftforge.client.model.ModelLoader;
import net.minecraftforge.event.RegistryEvent;
import net.minecraftforge.fml.common.Mod;
import net.minecraftforge.fml.common.eventhandler.SubscribeEvent;
import net.minecraftforge.fml.common.registry.GameRegistry;
import net.minecraftforge.fml.relauncher.Side;
import net.minecraftforge.fml.relauncher.SideOnly;
import static gr8pefish.openglider.api.OpenGliderInfo.MODID; | package gr8pefish.openglider.common.registry;
//import gr8pefish.openglider.common.recipe.AddUpgradeToGliderRecipe;
//import gr8pefish.openglider.common.recipe.RemoveUpgradeFromGliderRecipe;
@Mod.EventBusSubscriber
@GameRegistry.ObjectHolder(MODID)
public class ItemRegistry {
// Items
@GameRegistry.ObjectHolder(ModInfo.ITEM_GLIDER_PART_NAME)
public static final ItemHangGliderPart GLIDER_PART = null;
@GameRegistry.ObjectHolder(ModInfo.ITEM_GLIDER_BASIC_NAME) | // Path: src/main/java/gr8pefish/openglider/common/item/ItemHangGliderAdvanced.java
// public class ItemHangGliderAdvanced extends ItemHangGliderBase {
//
// public ItemHangGliderAdvanced() {
// super(ConfigHandler.advancedGliderHorizSpeed, ConfigHandler.advancedGliderVertSpeed, ConfigHandler.advancedGliderShiftHorizSpeed, ConfigHandler.advancedGliderShiftVertSpeed, ConfigHandler.advancedGliderWindModifier, ConfigHandler.advancedGliderAirResistance, ConfigHandler.advancedGliderTotalDurability, ModelGlider.MODEL_GLIDER_ADVANCED_TEXTURE_RL);
// setCreativeTab(OpenGlider.creativeTab);
// setTranslationKey(MODID +":" + ModInfo.ITEM_GLIDER_ADVANCED_NAME);
// }
//
// //ToDo: Needed?
// @Override
// public NBTTagCompound serializeNBT() {
// return null;
// }
//
// @Override
// public void deserializeNBT(NBTTagCompound nbt) {
//
// }
// }
//
// Path: src/main/java/gr8pefish/openglider/common/item/ItemHangGliderBasic.java
// public class ItemHangGliderBasic extends ItemHangGliderBase {
//
// public ItemHangGliderBasic() {
// super(ConfigHandler.basicGliderHorizSpeed, ConfigHandler.basicGliderVertSpeed, ConfigHandler.basicGliderShiftHorizSpeed, ConfigHandler.basicGliderShiftVertSpeed, ConfigHandler.basicGliderWindModifier, ConfigHandler.basicGliderAirResistance, ConfigHandler.basicGliderTotalDurability, ModelGlider.MODEL_GLIDER_BASIC_TEXTURE_RL);
// setCreativeTab(OpenGlider.creativeTab);
// setTranslationKey(MODID +":" + ModInfo.ITEM_GLIDER_BASIC_NAME);
// }
//
// //ToDo: Needed?
// @Override
// public NBTTagCompound serializeNBT() {
// return null;
// }
//
// @Override
// public void deserializeNBT(NBTTagCompound nbt) {
//
// }
// }
//
// Path: src/main/java/gr8pefish/openglider/common/item/ItemHangGliderPart.java
// public class ItemHangGliderPart extends Item {
//
// public static String[] names = {"wing_left", "wing_right", "scaffolding"};
//
// public ItemHangGliderPart() {
// super();
// setCreativeTab(OpenGlider.creativeTab);
// setHasSubtypes(true);
// setTranslationKey(MODID +":" + ModInfo.ITEM_GLIDER_PART_NAME+ ".");
// }
//
// @Override
// public void getSubItems(CreativeTabs tab, NonNullList<ItemStack> subItems) {
// if (isInCreativeTab(tab)) {
// for (int i = 0; i < names.length; i++)
// subItems.add(new ItemStack(this, 1, i));
// }
// }
//
// @Override
// public String getTranslationKey(ItemStack stack) {
// return super.getTranslationKey(stack) + names[stack.getItemDamage()];
// }
//
// }
//
// Path: src/main/java/gr8pefish/openglider/common/lib/ModInfo.java
// public class ModInfo {
//
// public static final String DOMAIN = MODID.toLowerCase(Locale.ENGLISH) + ":"; //for resources
// public static final String VERSION = "@VERSION@";
// public static final String FORGE_UPDATE_JSON_URL = "https://raw.githubusercontent.com/gr8pefish/OpenGlider/1.10/versions/update.json";
// public static final String GUI_FACTORY = "gr8pefish.openglider.client.gui.GuiFactory"; //for in-game config
//
// public static final String COMMON_PROXY = "gr8pefish.openglider.common.proxy.CommonProxy";
// public static final String CLIENT_PROXY = "gr8pefish.openglider.client.proxy.ClientProxy";
//
// public static final String NETWORK_CHANNEL = "opngldr";
//
// public static final String ITEM_GLIDER_BASIC_NAME = "hang_glider_basic";
// public static final String ITEM_GLIDER_ADVANCED_NAME = "hang_glider_advanced";
// public static final String ITEM_GLIDER_PART_NAME = "hang_glider_part";
//
// public static final class NBT_KEYS {
//
// public static final String UPGRADES = "upgrades";
//
// }
//
// }
//
// Path: src/main/java/gr8pefish/openglider/api/OpenGliderInfo.java
// public static final String MODID = "openglider";
// Path: src/main/java/gr8pefish/openglider/common/registry/ItemRegistry.java
import gr8pefish.openglider.common.item.ItemHangGliderAdvanced;
import gr8pefish.openglider.common.item.ItemHangGliderBasic;
import gr8pefish.openglider.common.item.ItemHangGliderPart;
import gr8pefish.openglider.common.lib.ModInfo;
import net.minecraft.client.renderer.block.model.ModelResourceLocation;
import net.minecraft.item.Item;
import net.minecraftforge.client.event.ModelRegistryEvent;
import net.minecraftforge.client.model.ModelLoader;
import net.minecraftforge.event.RegistryEvent;
import net.minecraftforge.fml.common.Mod;
import net.minecraftforge.fml.common.eventhandler.SubscribeEvent;
import net.minecraftforge.fml.common.registry.GameRegistry;
import net.minecraftforge.fml.relauncher.Side;
import net.minecraftforge.fml.relauncher.SideOnly;
import static gr8pefish.openglider.api.OpenGliderInfo.MODID;
package gr8pefish.openglider.common.registry;
//import gr8pefish.openglider.common.recipe.AddUpgradeToGliderRecipe;
//import gr8pefish.openglider.common.recipe.RemoveUpgradeFromGliderRecipe;
@Mod.EventBusSubscriber
@GameRegistry.ObjectHolder(MODID)
public class ItemRegistry {
// Items
@GameRegistry.ObjectHolder(ModInfo.ITEM_GLIDER_PART_NAME)
public static final ItemHangGliderPart GLIDER_PART = null;
@GameRegistry.ObjectHolder(ModInfo.ITEM_GLIDER_BASIC_NAME) | public static final ItemHangGliderBasic GLIDER_BASIC = null; |
gr8pefish/OpenGlider | src/main/java/gr8pefish/openglider/common/registry/ItemRegistry.java | // Path: src/main/java/gr8pefish/openglider/common/item/ItemHangGliderAdvanced.java
// public class ItemHangGliderAdvanced extends ItemHangGliderBase {
//
// public ItemHangGliderAdvanced() {
// super(ConfigHandler.advancedGliderHorizSpeed, ConfigHandler.advancedGliderVertSpeed, ConfigHandler.advancedGliderShiftHorizSpeed, ConfigHandler.advancedGliderShiftVertSpeed, ConfigHandler.advancedGliderWindModifier, ConfigHandler.advancedGliderAirResistance, ConfigHandler.advancedGliderTotalDurability, ModelGlider.MODEL_GLIDER_ADVANCED_TEXTURE_RL);
// setCreativeTab(OpenGlider.creativeTab);
// setTranslationKey(MODID +":" + ModInfo.ITEM_GLIDER_ADVANCED_NAME);
// }
//
// //ToDo: Needed?
// @Override
// public NBTTagCompound serializeNBT() {
// return null;
// }
//
// @Override
// public void deserializeNBT(NBTTagCompound nbt) {
//
// }
// }
//
// Path: src/main/java/gr8pefish/openglider/common/item/ItemHangGliderBasic.java
// public class ItemHangGliderBasic extends ItemHangGliderBase {
//
// public ItemHangGliderBasic() {
// super(ConfigHandler.basicGliderHorizSpeed, ConfigHandler.basicGliderVertSpeed, ConfigHandler.basicGliderShiftHorizSpeed, ConfigHandler.basicGliderShiftVertSpeed, ConfigHandler.basicGliderWindModifier, ConfigHandler.basicGliderAirResistance, ConfigHandler.basicGliderTotalDurability, ModelGlider.MODEL_GLIDER_BASIC_TEXTURE_RL);
// setCreativeTab(OpenGlider.creativeTab);
// setTranslationKey(MODID +":" + ModInfo.ITEM_GLIDER_BASIC_NAME);
// }
//
// //ToDo: Needed?
// @Override
// public NBTTagCompound serializeNBT() {
// return null;
// }
//
// @Override
// public void deserializeNBT(NBTTagCompound nbt) {
//
// }
// }
//
// Path: src/main/java/gr8pefish/openglider/common/item/ItemHangGliderPart.java
// public class ItemHangGliderPart extends Item {
//
// public static String[] names = {"wing_left", "wing_right", "scaffolding"};
//
// public ItemHangGliderPart() {
// super();
// setCreativeTab(OpenGlider.creativeTab);
// setHasSubtypes(true);
// setTranslationKey(MODID +":" + ModInfo.ITEM_GLIDER_PART_NAME+ ".");
// }
//
// @Override
// public void getSubItems(CreativeTabs tab, NonNullList<ItemStack> subItems) {
// if (isInCreativeTab(tab)) {
// for (int i = 0; i < names.length; i++)
// subItems.add(new ItemStack(this, 1, i));
// }
// }
//
// @Override
// public String getTranslationKey(ItemStack stack) {
// return super.getTranslationKey(stack) + names[stack.getItemDamage()];
// }
//
// }
//
// Path: src/main/java/gr8pefish/openglider/common/lib/ModInfo.java
// public class ModInfo {
//
// public static final String DOMAIN = MODID.toLowerCase(Locale.ENGLISH) + ":"; //for resources
// public static final String VERSION = "@VERSION@";
// public static final String FORGE_UPDATE_JSON_URL = "https://raw.githubusercontent.com/gr8pefish/OpenGlider/1.10/versions/update.json";
// public static final String GUI_FACTORY = "gr8pefish.openglider.client.gui.GuiFactory"; //for in-game config
//
// public static final String COMMON_PROXY = "gr8pefish.openglider.common.proxy.CommonProxy";
// public static final String CLIENT_PROXY = "gr8pefish.openglider.client.proxy.ClientProxy";
//
// public static final String NETWORK_CHANNEL = "opngldr";
//
// public static final String ITEM_GLIDER_BASIC_NAME = "hang_glider_basic";
// public static final String ITEM_GLIDER_ADVANCED_NAME = "hang_glider_advanced";
// public static final String ITEM_GLIDER_PART_NAME = "hang_glider_part";
//
// public static final class NBT_KEYS {
//
// public static final String UPGRADES = "upgrades";
//
// }
//
// }
//
// Path: src/main/java/gr8pefish/openglider/api/OpenGliderInfo.java
// public static final String MODID = "openglider";
| import gr8pefish.openglider.common.item.ItemHangGliderAdvanced;
import gr8pefish.openglider.common.item.ItemHangGliderBasic;
import gr8pefish.openglider.common.item.ItemHangGliderPart;
import gr8pefish.openglider.common.lib.ModInfo;
import net.minecraft.client.renderer.block.model.ModelResourceLocation;
import net.minecraft.item.Item;
import net.minecraftforge.client.event.ModelRegistryEvent;
import net.minecraftforge.client.model.ModelLoader;
import net.minecraftforge.event.RegistryEvent;
import net.minecraftforge.fml.common.Mod;
import net.minecraftforge.fml.common.eventhandler.SubscribeEvent;
import net.minecraftforge.fml.common.registry.GameRegistry;
import net.minecraftforge.fml.relauncher.Side;
import net.minecraftforge.fml.relauncher.SideOnly;
import static gr8pefish.openglider.api.OpenGliderInfo.MODID; | package gr8pefish.openglider.common.registry;
//import gr8pefish.openglider.common.recipe.AddUpgradeToGliderRecipe;
//import gr8pefish.openglider.common.recipe.RemoveUpgradeFromGliderRecipe;
@Mod.EventBusSubscriber
@GameRegistry.ObjectHolder(MODID)
public class ItemRegistry {
// Items
@GameRegistry.ObjectHolder(ModInfo.ITEM_GLIDER_PART_NAME)
public static final ItemHangGliderPart GLIDER_PART = null;
@GameRegistry.ObjectHolder(ModInfo.ITEM_GLIDER_BASIC_NAME)
public static final ItemHangGliderBasic GLIDER_BASIC = null;
@GameRegistry.ObjectHolder(ModInfo.ITEM_GLIDER_ADVANCED_NAME) | // Path: src/main/java/gr8pefish/openglider/common/item/ItemHangGliderAdvanced.java
// public class ItemHangGliderAdvanced extends ItemHangGliderBase {
//
// public ItemHangGliderAdvanced() {
// super(ConfigHandler.advancedGliderHorizSpeed, ConfigHandler.advancedGliderVertSpeed, ConfigHandler.advancedGliderShiftHorizSpeed, ConfigHandler.advancedGliderShiftVertSpeed, ConfigHandler.advancedGliderWindModifier, ConfigHandler.advancedGliderAirResistance, ConfigHandler.advancedGliderTotalDurability, ModelGlider.MODEL_GLIDER_ADVANCED_TEXTURE_RL);
// setCreativeTab(OpenGlider.creativeTab);
// setTranslationKey(MODID +":" + ModInfo.ITEM_GLIDER_ADVANCED_NAME);
// }
//
// //ToDo: Needed?
// @Override
// public NBTTagCompound serializeNBT() {
// return null;
// }
//
// @Override
// public void deserializeNBT(NBTTagCompound nbt) {
//
// }
// }
//
// Path: src/main/java/gr8pefish/openglider/common/item/ItemHangGliderBasic.java
// public class ItemHangGliderBasic extends ItemHangGliderBase {
//
// public ItemHangGliderBasic() {
// super(ConfigHandler.basicGliderHorizSpeed, ConfigHandler.basicGliderVertSpeed, ConfigHandler.basicGliderShiftHorizSpeed, ConfigHandler.basicGliderShiftVertSpeed, ConfigHandler.basicGliderWindModifier, ConfigHandler.basicGliderAirResistance, ConfigHandler.basicGliderTotalDurability, ModelGlider.MODEL_GLIDER_BASIC_TEXTURE_RL);
// setCreativeTab(OpenGlider.creativeTab);
// setTranslationKey(MODID +":" + ModInfo.ITEM_GLIDER_BASIC_NAME);
// }
//
// //ToDo: Needed?
// @Override
// public NBTTagCompound serializeNBT() {
// return null;
// }
//
// @Override
// public void deserializeNBT(NBTTagCompound nbt) {
//
// }
// }
//
// Path: src/main/java/gr8pefish/openglider/common/item/ItemHangGliderPart.java
// public class ItemHangGliderPart extends Item {
//
// public static String[] names = {"wing_left", "wing_right", "scaffolding"};
//
// public ItemHangGliderPart() {
// super();
// setCreativeTab(OpenGlider.creativeTab);
// setHasSubtypes(true);
// setTranslationKey(MODID +":" + ModInfo.ITEM_GLIDER_PART_NAME+ ".");
// }
//
// @Override
// public void getSubItems(CreativeTabs tab, NonNullList<ItemStack> subItems) {
// if (isInCreativeTab(tab)) {
// for (int i = 0; i < names.length; i++)
// subItems.add(new ItemStack(this, 1, i));
// }
// }
//
// @Override
// public String getTranslationKey(ItemStack stack) {
// return super.getTranslationKey(stack) + names[stack.getItemDamage()];
// }
//
// }
//
// Path: src/main/java/gr8pefish/openglider/common/lib/ModInfo.java
// public class ModInfo {
//
// public static final String DOMAIN = MODID.toLowerCase(Locale.ENGLISH) + ":"; //for resources
// public static final String VERSION = "@VERSION@";
// public static final String FORGE_UPDATE_JSON_URL = "https://raw.githubusercontent.com/gr8pefish/OpenGlider/1.10/versions/update.json";
// public static final String GUI_FACTORY = "gr8pefish.openglider.client.gui.GuiFactory"; //for in-game config
//
// public static final String COMMON_PROXY = "gr8pefish.openglider.common.proxy.CommonProxy";
// public static final String CLIENT_PROXY = "gr8pefish.openglider.client.proxy.ClientProxy";
//
// public static final String NETWORK_CHANNEL = "opngldr";
//
// public static final String ITEM_GLIDER_BASIC_NAME = "hang_glider_basic";
// public static final String ITEM_GLIDER_ADVANCED_NAME = "hang_glider_advanced";
// public static final String ITEM_GLIDER_PART_NAME = "hang_glider_part";
//
// public static final class NBT_KEYS {
//
// public static final String UPGRADES = "upgrades";
//
// }
//
// }
//
// Path: src/main/java/gr8pefish/openglider/api/OpenGliderInfo.java
// public static final String MODID = "openglider";
// Path: src/main/java/gr8pefish/openglider/common/registry/ItemRegistry.java
import gr8pefish.openglider.common.item.ItemHangGliderAdvanced;
import gr8pefish.openglider.common.item.ItemHangGliderBasic;
import gr8pefish.openglider.common.item.ItemHangGliderPart;
import gr8pefish.openglider.common.lib.ModInfo;
import net.minecraft.client.renderer.block.model.ModelResourceLocation;
import net.minecraft.item.Item;
import net.minecraftforge.client.event.ModelRegistryEvent;
import net.minecraftforge.client.model.ModelLoader;
import net.minecraftforge.event.RegistryEvent;
import net.minecraftforge.fml.common.Mod;
import net.minecraftforge.fml.common.eventhandler.SubscribeEvent;
import net.minecraftforge.fml.common.registry.GameRegistry;
import net.minecraftforge.fml.relauncher.Side;
import net.minecraftforge.fml.relauncher.SideOnly;
import static gr8pefish.openglider.api.OpenGliderInfo.MODID;
package gr8pefish.openglider.common.registry;
//import gr8pefish.openglider.common.recipe.AddUpgradeToGliderRecipe;
//import gr8pefish.openglider.common.recipe.RemoveUpgradeFromGliderRecipe;
@Mod.EventBusSubscriber
@GameRegistry.ObjectHolder(MODID)
public class ItemRegistry {
// Items
@GameRegistry.ObjectHolder(ModInfo.ITEM_GLIDER_PART_NAME)
public static final ItemHangGliderPart GLIDER_PART = null;
@GameRegistry.ObjectHolder(ModInfo.ITEM_GLIDER_BASIC_NAME)
public static final ItemHangGliderBasic GLIDER_BASIC = null;
@GameRegistry.ObjectHolder(ModInfo.ITEM_GLIDER_ADVANCED_NAME) | public static final ItemHangGliderAdvanced GLIDER_ADV = null; |
gr8pefish/OpenGlider | src/main/java/gr8pefish/openglider/common/network/PacketSyncGliderDataToClient.java | // Path: src/main/java/gr8pefish/openglider/common/OpenGlider.java
// @Mod(modid = MODID, name = MOD_NAME, version = ModInfo.VERSION, guiFactory = ModInfo.GUI_FACTORY, acceptedMinecraftVersions = "[1.12,1.13)")//, updateJSON = FORGE_UPDATE_JSON_URL) //disabled version update checker for now, as it was giving false positives
// public class OpenGlider {
//
// //Proxies
// @SidedProxy(clientSide = ModInfo.CLIENT_PROXY, serverSide = ModInfo.COMMON_PROXY)
// public static IProxy proxy;
//
// //Creative Tab
// public static final CreativeTabs creativeTab = new CreativeTabs(MODID) {
//
// @Override
// public ItemStack createIcon() {
// return new ItemStack(ItemRegistry.GLIDER_BASIC);
// }
// };
//
// //Mod Instance
// @Mod.Instance
// public static OpenGlider instance;
//
//
// @Mod.EventHandler
// public void preInit(FMLPreInitializationEvent event) {
//
// //config
// ConfigHandler.init(event.getSuggestedConfigurationFile());
//
// //wind
// WindHelper.initNoiseGenerator();
//
// //register capabilities
// CapabilityRegistry.registerAllCapabilities();
//
// //packets
// PacketHandler.init();
//
// //init renderers and client event handlers
// proxy.preInit(event);
// }
//
//
// @Mod.EventHandler
// public void init(FMLInitializationEvent event) {
//
// //upgrades
// UpgradeItems.initUpgradesList();
//
// //register server events
// MinecraftForge.EVENT_BUS.register(new ServerEventHandler());
// //register config changed event
// MinecraftForge.EVENT_BUS.register(new ConfigHandler());
//
// proxy.init(event);
// }
//
//
// @Mod.EventHandler
// public void postInit(FMLPostInitializationEvent event) {
//
// proxy.postInit(event);
// }
// }
//
// Path: src/main/java/gr8pefish/openglider/common/helper/Logger.java
// public class Logger{
//
// public static void log(Level logLevel, Object object){
// FMLLog.log(MOD_NAME, logLevel, String.valueOf(object));
// }
//
// public static void all(Object object){
// log(Level.ALL, object);
// }
//
// public static void debug(Object object){
// log(Level.DEBUG, object);
// }
//
// public static void error(Object object){
// log(Level.ERROR, object);
// }
//
// public static void fatal(Object object){
// log(Level.FATAL, object);
// }
//
// public static void info(Object object){
// log(Level.INFO, object);
// }
//
// public static void off(Object object){
// log(Level.OFF, object);
// }
//
// public static void trace(Object object){
// log(Level.TRACE, object);
// }
//
// public static void warn(Object object){
// log(Level.WARN, object);
// }
// }
| import gr8pefish.openglider.common.OpenGlider;
import gr8pefish.openglider.common.helper.Logger;
import io.netty.buffer.ByteBuf;
import net.minecraft.client.Minecraft;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraftforge.fml.common.network.ByteBufUtils;
import net.minecraftforge.fml.common.network.simpleimpl.IMessage;
import net.minecraftforge.fml.common.network.simpleimpl.IMessageHandler;
import net.minecraftforge.fml.common.network.simpleimpl.MessageContext; | package gr8pefish.openglider.common.network;
public class PacketSyncGliderDataToClient implements IMessage {
private NBTTagCompound nbt;
public PacketSyncGliderDataToClient() {}
public PacketSyncGliderDataToClient(NBTTagCompound nbt) {
this.nbt = nbt;
}
@Override
public void fromBytes(ByteBuf buf) {
nbt = ByteBufUtils.readTag(buf);
}
@Override
public void toBytes(ByteBuf buf) {
ByteBufUtils.writeTag(buf, nbt);
}
public static class Handler implements IMessageHandler<PacketSyncGliderDataToClient, IMessage> {
@Override
public IMessage onMessage(final PacketSyncGliderDataToClient message, MessageContext ctx) {
Minecraft.getMinecraft().addScheduledTask(() -> { | // Path: src/main/java/gr8pefish/openglider/common/OpenGlider.java
// @Mod(modid = MODID, name = MOD_NAME, version = ModInfo.VERSION, guiFactory = ModInfo.GUI_FACTORY, acceptedMinecraftVersions = "[1.12,1.13)")//, updateJSON = FORGE_UPDATE_JSON_URL) //disabled version update checker for now, as it was giving false positives
// public class OpenGlider {
//
// //Proxies
// @SidedProxy(clientSide = ModInfo.CLIENT_PROXY, serverSide = ModInfo.COMMON_PROXY)
// public static IProxy proxy;
//
// //Creative Tab
// public static final CreativeTabs creativeTab = new CreativeTabs(MODID) {
//
// @Override
// public ItemStack createIcon() {
// return new ItemStack(ItemRegistry.GLIDER_BASIC);
// }
// };
//
// //Mod Instance
// @Mod.Instance
// public static OpenGlider instance;
//
//
// @Mod.EventHandler
// public void preInit(FMLPreInitializationEvent event) {
//
// //config
// ConfigHandler.init(event.getSuggestedConfigurationFile());
//
// //wind
// WindHelper.initNoiseGenerator();
//
// //register capabilities
// CapabilityRegistry.registerAllCapabilities();
//
// //packets
// PacketHandler.init();
//
// //init renderers and client event handlers
// proxy.preInit(event);
// }
//
//
// @Mod.EventHandler
// public void init(FMLInitializationEvent event) {
//
// //upgrades
// UpgradeItems.initUpgradesList();
//
// //register server events
// MinecraftForge.EVENT_BUS.register(new ServerEventHandler());
// //register config changed event
// MinecraftForge.EVENT_BUS.register(new ConfigHandler());
//
// proxy.init(event);
// }
//
//
// @Mod.EventHandler
// public void postInit(FMLPostInitializationEvent event) {
//
// proxy.postInit(event);
// }
// }
//
// Path: src/main/java/gr8pefish/openglider/common/helper/Logger.java
// public class Logger{
//
// public static void log(Level logLevel, Object object){
// FMLLog.log(MOD_NAME, logLevel, String.valueOf(object));
// }
//
// public static void all(Object object){
// log(Level.ALL, object);
// }
//
// public static void debug(Object object){
// log(Level.DEBUG, object);
// }
//
// public static void error(Object object){
// log(Level.ERROR, object);
// }
//
// public static void fatal(Object object){
// log(Level.FATAL, object);
// }
//
// public static void info(Object object){
// log(Level.INFO, object);
// }
//
// public static void off(Object object){
// log(Level.OFF, object);
// }
//
// public static void trace(Object object){
// log(Level.TRACE, object);
// }
//
// public static void warn(Object object){
// log(Level.WARN, object);
// }
// }
// Path: src/main/java/gr8pefish/openglider/common/network/PacketSyncGliderDataToClient.java
import gr8pefish.openglider.common.OpenGlider;
import gr8pefish.openglider.common.helper.Logger;
import io.netty.buffer.ByteBuf;
import net.minecraft.client.Minecraft;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraftforge.fml.common.network.ByteBufUtils;
import net.minecraftforge.fml.common.network.simpleimpl.IMessage;
import net.minecraftforge.fml.common.network.simpleimpl.IMessageHandler;
import net.minecraftforge.fml.common.network.simpleimpl.MessageContext;
package gr8pefish.openglider.common.network;
public class PacketSyncGliderDataToClient implements IMessage {
private NBTTagCompound nbt;
public PacketSyncGliderDataToClient() {}
public PacketSyncGliderDataToClient(NBTTagCompound nbt) {
this.nbt = nbt;
}
@Override
public void fromBytes(ByteBuf buf) {
nbt = ByteBufUtils.readTag(buf);
}
@Override
public void toBytes(ByteBuf buf) {
ByteBufUtils.writeTag(buf, nbt);
}
public static class Handler implements IMessageHandler<PacketSyncGliderDataToClient, IMessage> {
@Override
public IMessage onMessage(final PacketSyncGliderDataToClient message, MessageContext ctx) {
Minecraft.getMinecraft().addScheduledTask(() -> { | OpenGlider.proxy.getClientGliderCapability().deserializeNBT(message.nbt); |
gr8pefish/OpenGlider | src/main/java/gr8pefish/openglider/common/network/PacketSyncGliderDataToClient.java | // Path: src/main/java/gr8pefish/openglider/common/OpenGlider.java
// @Mod(modid = MODID, name = MOD_NAME, version = ModInfo.VERSION, guiFactory = ModInfo.GUI_FACTORY, acceptedMinecraftVersions = "[1.12,1.13)")//, updateJSON = FORGE_UPDATE_JSON_URL) //disabled version update checker for now, as it was giving false positives
// public class OpenGlider {
//
// //Proxies
// @SidedProxy(clientSide = ModInfo.CLIENT_PROXY, serverSide = ModInfo.COMMON_PROXY)
// public static IProxy proxy;
//
// //Creative Tab
// public static final CreativeTabs creativeTab = new CreativeTabs(MODID) {
//
// @Override
// public ItemStack createIcon() {
// return new ItemStack(ItemRegistry.GLIDER_BASIC);
// }
// };
//
// //Mod Instance
// @Mod.Instance
// public static OpenGlider instance;
//
//
// @Mod.EventHandler
// public void preInit(FMLPreInitializationEvent event) {
//
// //config
// ConfigHandler.init(event.getSuggestedConfigurationFile());
//
// //wind
// WindHelper.initNoiseGenerator();
//
// //register capabilities
// CapabilityRegistry.registerAllCapabilities();
//
// //packets
// PacketHandler.init();
//
// //init renderers and client event handlers
// proxy.preInit(event);
// }
//
//
// @Mod.EventHandler
// public void init(FMLInitializationEvent event) {
//
// //upgrades
// UpgradeItems.initUpgradesList();
//
// //register server events
// MinecraftForge.EVENT_BUS.register(new ServerEventHandler());
// //register config changed event
// MinecraftForge.EVENT_BUS.register(new ConfigHandler());
//
// proxy.init(event);
// }
//
//
// @Mod.EventHandler
// public void postInit(FMLPostInitializationEvent event) {
//
// proxy.postInit(event);
// }
// }
//
// Path: src/main/java/gr8pefish/openglider/common/helper/Logger.java
// public class Logger{
//
// public static void log(Level logLevel, Object object){
// FMLLog.log(MOD_NAME, logLevel, String.valueOf(object));
// }
//
// public static void all(Object object){
// log(Level.ALL, object);
// }
//
// public static void debug(Object object){
// log(Level.DEBUG, object);
// }
//
// public static void error(Object object){
// log(Level.ERROR, object);
// }
//
// public static void fatal(Object object){
// log(Level.FATAL, object);
// }
//
// public static void info(Object object){
// log(Level.INFO, object);
// }
//
// public static void off(Object object){
// log(Level.OFF, object);
// }
//
// public static void trace(Object object){
// log(Level.TRACE, object);
// }
//
// public static void warn(Object object){
// log(Level.WARN, object);
// }
// }
| import gr8pefish.openglider.common.OpenGlider;
import gr8pefish.openglider.common.helper.Logger;
import io.netty.buffer.ByteBuf;
import net.minecraft.client.Minecraft;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraftforge.fml.common.network.ByteBufUtils;
import net.minecraftforge.fml.common.network.simpleimpl.IMessage;
import net.minecraftforge.fml.common.network.simpleimpl.IMessageHandler;
import net.minecraftforge.fml.common.network.simpleimpl.MessageContext; | package gr8pefish.openglider.common.network;
public class PacketSyncGliderDataToClient implements IMessage {
private NBTTagCompound nbt;
public PacketSyncGliderDataToClient() {}
public PacketSyncGliderDataToClient(NBTTagCompound nbt) {
this.nbt = nbt;
}
@Override
public void fromBytes(ByteBuf buf) {
nbt = ByteBufUtils.readTag(buf);
}
@Override
public void toBytes(ByteBuf buf) {
ByteBufUtils.writeTag(buf, nbt);
}
public static class Handler implements IMessageHandler<PacketSyncGliderDataToClient, IMessage> {
@Override
public IMessage onMessage(final PacketSyncGliderDataToClient message, MessageContext ctx) {
Minecraft.getMinecraft().addScheduledTask(() -> {
OpenGlider.proxy.getClientGliderCapability().deserializeNBT(message.nbt); | // Path: src/main/java/gr8pefish/openglider/common/OpenGlider.java
// @Mod(modid = MODID, name = MOD_NAME, version = ModInfo.VERSION, guiFactory = ModInfo.GUI_FACTORY, acceptedMinecraftVersions = "[1.12,1.13)")//, updateJSON = FORGE_UPDATE_JSON_URL) //disabled version update checker for now, as it was giving false positives
// public class OpenGlider {
//
// //Proxies
// @SidedProxy(clientSide = ModInfo.CLIENT_PROXY, serverSide = ModInfo.COMMON_PROXY)
// public static IProxy proxy;
//
// //Creative Tab
// public static final CreativeTabs creativeTab = new CreativeTabs(MODID) {
//
// @Override
// public ItemStack createIcon() {
// return new ItemStack(ItemRegistry.GLIDER_BASIC);
// }
// };
//
// //Mod Instance
// @Mod.Instance
// public static OpenGlider instance;
//
//
// @Mod.EventHandler
// public void preInit(FMLPreInitializationEvent event) {
//
// //config
// ConfigHandler.init(event.getSuggestedConfigurationFile());
//
// //wind
// WindHelper.initNoiseGenerator();
//
// //register capabilities
// CapabilityRegistry.registerAllCapabilities();
//
// //packets
// PacketHandler.init();
//
// //init renderers and client event handlers
// proxy.preInit(event);
// }
//
//
// @Mod.EventHandler
// public void init(FMLInitializationEvent event) {
//
// //upgrades
// UpgradeItems.initUpgradesList();
//
// //register server events
// MinecraftForge.EVENT_BUS.register(new ServerEventHandler());
// //register config changed event
// MinecraftForge.EVENT_BUS.register(new ConfigHandler());
//
// proxy.init(event);
// }
//
//
// @Mod.EventHandler
// public void postInit(FMLPostInitializationEvent event) {
//
// proxy.postInit(event);
// }
// }
//
// Path: src/main/java/gr8pefish/openglider/common/helper/Logger.java
// public class Logger{
//
// public static void log(Level logLevel, Object object){
// FMLLog.log(MOD_NAME, logLevel, String.valueOf(object));
// }
//
// public static void all(Object object){
// log(Level.ALL, object);
// }
//
// public static void debug(Object object){
// log(Level.DEBUG, object);
// }
//
// public static void error(Object object){
// log(Level.ERROR, object);
// }
//
// public static void fatal(Object object){
// log(Level.FATAL, object);
// }
//
// public static void info(Object object){
// log(Level.INFO, object);
// }
//
// public static void off(Object object){
// log(Level.OFF, object);
// }
//
// public static void trace(Object object){
// log(Level.TRACE, object);
// }
//
// public static void warn(Object object){
// log(Level.WARN, object);
// }
// }
// Path: src/main/java/gr8pefish/openglider/common/network/PacketSyncGliderDataToClient.java
import gr8pefish.openglider.common.OpenGlider;
import gr8pefish.openglider.common.helper.Logger;
import io.netty.buffer.ByteBuf;
import net.minecraft.client.Minecraft;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraftforge.fml.common.network.ByteBufUtils;
import net.minecraftforge.fml.common.network.simpleimpl.IMessage;
import net.minecraftforge.fml.common.network.simpleimpl.IMessageHandler;
import net.minecraftforge.fml.common.network.simpleimpl.MessageContext;
package gr8pefish.openglider.common.network;
public class PacketSyncGliderDataToClient implements IMessage {
private NBTTagCompound nbt;
public PacketSyncGliderDataToClient() {}
public PacketSyncGliderDataToClient(NBTTagCompound nbt) {
this.nbt = nbt;
}
@Override
public void fromBytes(ByteBuf buf) {
nbt = ByteBufUtils.readTag(buf);
}
@Override
public void toBytes(ByteBuf buf) {
ByteBufUtils.writeTag(buf, nbt);
}
public static class Handler implements IMessageHandler<PacketSyncGliderDataToClient, IMessage> {
@Override
public IMessage onMessage(final PacketSyncGliderDataToClient message, MessageContext ctx) {
Minecraft.getMinecraft().addScheduledTask(() -> {
OpenGlider.proxy.getClientGliderCapability().deserializeNBT(message.nbt); | Logger.debug("** RECEIVED GLIDER SYNC INFO CLIENTSIDE **"); |
gr8pefish/OpenGlider | src/main/java/gr8pefish/openglider/common/helper/Logger.java | // Path: src/main/java/gr8pefish/openglider/api/OpenGliderInfo.java
// public static final String MOD_NAME = "Open Glider";
| import net.minecraftforge.fml.common.FMLLog;
import org.apache.logging.log4j.Level;
import static gr8pefish.openglider.api.OpenGliderInfo.MOD_NAME; | package gr8pefish.openglider.common.helper;
/**
* A logger class ot output information to the FML log nicely
*/
public class Logger{
public static void log(Level logLevel, Object object){ | // Path: src/main/java/gr8pefish/openglider/api/OpenGliderInfo.java
// public static final String MOD_NAME = "Open Glider";
// Path: src/main/java/gr8pefish/openglider/common/helper/Logger.java
import net.minecraftforge.fml.common.FMLLog;
import org.apache.logging.log4j.Level;
import static gr8pefish.openglider.api.OpenGliderInfo.MOD_NAME;
package gr8pefish.openglider.common.helper;
/**
* A logger class ot output information to the FML log nicely
*/
public class Logger{
public static void log(Level logLevel, Object object){ | FMLLog.log(MOD_NAME, logLevel, String.valueOf(object)); |
gr8pefish/OpenGlider | src/main/java/gr8pefish/openglider/common/proxy/CommonProxy.java | // Path: src/main/java/gr8pefish/openglider/api/capabilities/IGliderCapabilityHandler.java
// public interface IGliderCapabilityHandler extends INBTSerializable<NBTTagCompound> {
//
// /**
// * Get the current gliding status of the player.
// * If True, it inherently must mean that the glider is deployed as well.
// *
// * @return - True if the player is gliding, False otherwise.
// */
// boolean getIsPlayerGliding();
//
// /**
// * Set the player's current gliding status.
// * If True, it inherently must mean that the glider is deployed as well.
// *
// * @param isPlayerGliding - True if the player is gliding, False otherwise.
// */
// void setIsPlayerGliding(boolean isPlayerGliding);
//
// /**
// * Get the current deployment status of the glider on the player.
// *
// * @return True is the player has a deployed glider, False otherwise.
// */
// boolean getIsGliderDeployed();
//
// /**
// * Set the player's glider's deployment status.
// *
// * @param isGliderDeployed - True if the glider is deployed, False otherwise.
// */
// void setIsGliderDeployed(boolean isGliderDeployed);
//
// /**
// * Sync the (above) data stored in the capability to a given player.
// *
// * @param player - the player to sync the data to.
// */
// void sync(EntityPlayerMP player);
//
// }
| import gr8pefish.openglider.api.capabilities.IGliderCapabilityHandler;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.world.World;
import net.minecraftforge.fml.common.event.FMLInitializationEvent;
import net.minecraftforge.fml.common.event.FMLPostInitializationEvent;
import net.minecraftforge.fml.common.event.FMLPreInitializationEvent; | package gr8pefish.openglider.common.proxy;
public class CommonProxy implements IProxy {
@Override
public void preInit(FMLPreInitializationEvent event) {
}
@Override
public void init(FMLInitializationEvent event) {
}
@Override
public void postInit(FMLPostInitializationEvent event) {
}
@Override
public EntityPlayer getClientPlayer(){
return null; //nothing on server
}
@Override
public World getClientWorld() {
return null; //Nothing on server
}
@Override | // Path: src/main/java/gr8pefish/openglider/api/capabilities/IGliderCapabilityHandler.java
// public interface IGliderCapabilityHandler extends INBTSerializable<NBTTagCompound> {
//
// /**
// * Get the current gliding status of the player.
// * If True, it inherently must mean that the glider is deployed as well.
// *
// * @return - True if the player is gliding, False otherwise.
// */
// boolean getIsPlayerGliding();
//
// /**
// * Set the player's current gliding status.
// * If True, it inherently must mean that the glider is deployed as well.
// *
// * @param isPlayerGliding - True if the player is gliding, False otherwise.
// */
// void setIsPlayerGliding(boolean isPlayerGliding);
//
// /**
// * Get the current deployment status of the glider on the player.
// *
// * @return True is the player has a deployed glider, False otherwise.
// */
// boolean getIsGliderDeployed();
//
// /**
// * Set the player's glider's deployment status.
// *
// * @param isGliderDeployed - True if the glider is deployed, False otherwise.
// */
// void setIsGliderDeployed(boolean isGliderDeployed);
//
// /**
// * Sync the (above) data stored in the capability to a given player.
// *
// * @param player - the player to sync the data to.
// */
// void sync(EntityPlayerMP player);
//
// }
// Path: src/main/java/gr8pefish/openglider/common/proxy/CommonProxy.java
import gr8pefish.openglider.api.capabilities.IGliderCapabilityHandler;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.world.World;
import net.minecraftforge.fml.common.event.FMLInitializationEvent;
import net.minecraftforge.fml.common.event.FMLPostInitializationEvent;
import net.minecraftforge.fml.common.event.FMLPreInitializationEvent;
package gr8pefish.openglider.common.proxy;
public class CommonProxy implements IProxy {
@Override
public void preInit(FMLPreInitializationEvent event) {
}
@Override
public void init(FMLInitializationEvent event) {
}
@Override
public void postInit(FMLPostInitializationEvent event) {
}
@Override
public EntityPlayer getClientPlayer(){
return null; //nothing on server
}
@Override
public World getClientWorld() {
return null; //Nothing on server
}
@Override | public IGliderCapabilityHandler getClientGliderCapability() { |
gr8pefish/OpenGlider | src/main/java/gr8pefish/openglider/common/config/ConfigHandler.java | // Path: src/main/java/gr8pefish/openglider/api/OpenGliderInfo.java
// public static final String MODID = "openglider";
| import net.minecraftforge.common.config.Configuration;
import net.minecraftforge.fml.client.event.ConfigChangedEvent;
import net.minecraftforge.fml.common.eventhandler.SubscribeEvent;
import java.io.File;
import java.util.ArrayList;
import java.util.List;
import static gr8pefish.openglider.api.OpenGliderInfo.MODID; |
//Wind
public static boolean airResistanceEnabled;
public static boolean windEnabled;
public static float windOverallPower;
public static float windGustSize;
public static float windFrequency;
public static float windRainingMultiplier;
public static float windSpeedMultiplier;
public static float windHeightMultiplier;
public static float windDurabilityMultiplier;
//Durability
public static boolean durabilityEnabled;
public static int durabilityPerUse;
public static int durabilityTimeframe;
//Misc
public static boolean heatUpdraftEnabled;
//Client
public static boolean enableRendering3PP;
public static boolean enableRenderingFPP;
public static float gliderVisibilityFPPShiftAmount;
public static boolean disableOffhandRenderingWhenGliding;
public static boolean disableHandleBarRenderingWhenGliding;
public static float shiftSpeedVisualShift;
@SubscribeEvent
public void configChanged(ConfigChangedEvent event) { | // Path: src/main/java/gr8pefish/openglider/api/OpenGliderInfo.java
// public static final String MODID = "openglider";
// Path: src/main/java/gr8pefish/openglider/common/config/ConfigHandler.java
import net.minecraftforge.common.config.Configuration;
import net.minecraftforge.fml.client.event.ConfigChangedEvent;
import net.minecraftforge.fml.common.eventhandler.SubscribeEvent;
import java.io.File;
import java.util.ArrayList;
import java.util.List;
import static gr8pefish.openglider.api.OpenGliderInfo.MODID;
//Wind
public static boolean airResistanceEnabled;
public static boolean windEnabled;
public static float windOverallPower;
public static float windGustSize;
public static float windFrequency;
public static float windRainingMultiplier;
public static float windSpeedMultiplier;
public static float windHeightMultiplier;
public static float windDurabilityMultiplier;
//Durability
public static boolean durabilityEnabled;
public static int durabilityPerUse;
public static int durabilityTimeframe;
//Misc
public static boolean heatUpdraftEnabled;
//Client
public static boolean enableRendering3PP;
public static boolean enableRenderingFPP;
public static float gliderVisibilityFPPShiftAmount;
public static boolean disableOffhandRenderingWhenGliding;
public static boolean disableHandleBarRenderingWhenGliding;
public static float shiftSpeedVisualShift;
@SubscribeEvent
public void configChanged(ConfigChangedEvent event) { | if (event.getModID().equals(MODID)) { |
mkalam-alami/inventory-tweaks | src/minecraft/invtweaks/InvTweaksGuiSettings.java | // Path: src/minecraft/invtweaks/InvTweaksConst.java
// public class InvTweaksConst {
//
// // Mod version
// public static final String MOD_VERSION = "1.50 (1.4.7)";
//
// // Mod tree version
// // Change only when the tree evolves significantly enough to need to override all configs
// public static final String TREE_VERSION = "1.4.0";
//
// // Timing constants
// public static final int RULESET_SWAP_DELAY = 1000;
// public static final int AUTO_REFILL_DELAY = 200;
// public static final int AUTO_REFILL_DAMAGE_TRESHOLD = 5;
// public static final int POLLING_DELAY = 3;
// public static final int POLLING_TIMEOUT = 1500;
// public static final int CHEST_ALGORITHM_SWAP_MAX_INTERVAL = 2000;
// public static final int TOOLTIP_DELAY = 800;
// public static final int INTERRUPT_DELAY = 300;
//
// // File constants
// public static final String MINECRAFT_DIR = getMinecraftDir();
// public static final String MINECRAFT_CONFIG_DIR = MINECRAFT_DIR + "config" + File.separatorChar;
// public static final String CONFIG_PROPS_FILE = MINECRAFT_CONFIG_DIR + "InvTweaks.cfg";
// public static final String CONFIG_RULES_FILE = MINECRAFT_CONFIG_DIR + "InvTweaksRules.txt";
// public static final String CONFIG_TREE_FILE = MINECRAFT_CONFIG_DIR + "InvTweaksTree.txt";
// public static final String OLD_CONFIG_TREE_FILE = MINECRAFT_CONFIG_DIR + "InvTweaksTree.xml";
// public static final String OLDER_CONFIG_RULES_FILE = MINECRAFT_DIR + "InvTweaksRules.txt";
// public static final String OLDER_CONFIG_TREE_FILE = MINECRAFT_DIR + "InvTweaksTree.txt";
// public static final String DEFAULT_CONFIG_FILE = "DefaultConfig.dat";
// public static final String DEFAULT_CONFIG_TREE_FILE = "DefaultTree.dat";
// public static final String HELP_URL = "http://modding.kalam-alami.net/invtweaks";
//
// // Global mod constants
// public static final String INGAME_LOG_PREFIX = "InvTweaks: ";
// public static final Level DEFAULT_LOG_LEVEL = Level.WARNING;
// public static final Level DEBUG = Level.INFO;
// public static final int JIMEOWAN_ID = 54696386; // Used in GUIs
//
// // Minecraft constants
// public static final int INVENTORY_SIZE = 36;
// public static final int INVENTORY_ROW_SIZE = 9;
// public static final int CHEST_ROW_SIZE = INVENTORY_ROW_SIZE;
// public static final int DISPENSER_ROW_SIZE = 3;
// public static final int INVENTORY_HOTBAR_SIZE = INVENTORY_ROW_SIZE;
// public static final int PLAYER_INVENTORY_WINDOW_ID = 0;
// public static final int SLOW_SORTING_DELAY = 30;
//
// /**
// * Returns the Minecraft folder ensuring:
// * - It is an absolute path
// * - It ends with a folder separator
// */
// public static String getMinecraftDir() {
// String absolutePath = Minecraft.getMinecraftDir().getAbsolutePath();
// if (absolutePath.endsWith(".")) {
// return absolutePath.substring(0, absolutePath.length() - 1);
// }
// if (absolutePath.endsWith(File.separator)) {
// return absolutePath;
// } else {
// return absolutePath + File.separatorChar;
// }
// }
//
// }
| import invtweaks.InvTweaksConst;
import java.awt.Desktop;
import java.io.File;
import java.net.URL;
import java.util.List;
import java.util.logging.Logger;
import net.minecraft.client.Minecraft;
import net.minecraft.src.GuiButton;
import net.minecraft.src.GuiScreen;
import org.lwjgl.input.Keyboard;
import org.lwjgl.util.Point; | break;
// Toggle auto-refill before tool break
case ID_BEFORE_BREAK:
toggleBooleanButton(guibutton, InvTweaksConfig.PROP_AUTO_REFILL_BEFORE_BREAK, labelAutoRefillBeforeBreak);
break;
// Toggle shortcuts
case ID_SHORTCUTS:
toggleBooleanButton(guibutton, InvTweaksConfig.PROP_ENABLE_SHORTCUTS, labelShortcuts);
break;
// Shortcuts help
case ID_SHORTCUTS_HELP:
obf.displayGuiScreen(new InvTweaksGuiShortcutsHelp(mc, this, config));
break;
// More options screen
case ID_MORE_OPTIONS:
obf.displayGuiScreen(new InvTweaksGuiSettingsAdvanced(mc, parentScreen, config));
break;
// Sorting bug help screen
case ID_BUG_SORTING:
obf.displayGuiScreen(new InvTweaksGuiModNotWorking(mc, parentScreen, config));
break;
// Open rules configuration in external editor
case ID_EDITRULES:
try { | // Path: src/minecraft/invtweaks/InvTweaksConst.java
// public class InvTweaksConst {
//
// // Mod version
// public static final String MOD_VERSION = "1.50 (1.4.7)";
//
// // Mod tree version
// // Change only when the tree evolves significantly enough to need to override all configs
// public static final String TREE_VERSION = "1.4.0";
//
// // Timing constants
// public static final int RULESET_SWAP_DELAY = 1000;
// public static final int AUTO_REFILL_DELAY = 200;
// public static final int AUTO_REFILL_DAMAGE_TRESHOLD = 5;
// public static final int POLLING_DELAY = 3;
// public static final int POLLING_TIMEOUT = 1500;
// public static final int CHEST_ALGORITHM_SWAP_MAX_INTERVAL = 2000;
// public static final int TOOLTIP_DELAY = 800;
// public static final int INTERRUPT_DELAY = 300;
//
// // File constants
// public static final String MINECRAFT_DIR = getMinecraftDir();
// public static final String MINECRAFT_CONFIG_DIR = MINECRAFT_DIR + "config" + File.separatorChar;
// public static final String CONFIG_PROPS_FILE = MINECRAFT_CONFIG_DIR + "InvTweaks.cfg";
// public static final String CONFIG_RULES_FILE = MINECRAFT_CONFIG_DIR + "InvTweaksRules.txt";
// public static final String CONFIG_TREE_FILE = MINECRAFT_CONFIG_DIR + "InvTweaksTree.txt";
// public static final String OLD_CONFIG_TREE_FILE = MINECRAFT_CONFIG_DIR + "InvTweaksTree.xml";
// public static final String OLDER_CONFIG_RULES_FILE = MINECRAFT_DIR + "InvTweaksRules.txt";
// public static final String OLDER_CONFIG_TREE_FILE = MINECRAFT_DIR + "InvTweaksTree.txt";
// public static final String DEFAULT_CONFIG_FILE = "DefaultConfig.dat";
// public static final String DEFAULT_CONFIG_TREE_FILE = "DefaultTree.dat";
// public static final String HELP_URL = "http://modding.kalam-alami.net/invtweaks";
//
// // Global mod constants
// public static final String INGAME_LOG_PREFIX = "InvTweaks: ";
// public static final Level DEFAULT_LOG_LEVEL = Level.WARNING;
// public static final Level DEBUG = Level.INFO;
// public static final int JIMEOWAN_ID = 54696386; // Used in GUIs
//
// // Minecraft constants
// public static final int INVENTORY_SIZE = 36;
// public static final int INVENTORY_ROW_SIZE = 9;
// public static final int CHEST_ROW_SIZE = INVENTORY_ROW_SIZE;
// public static final int DISPENSER_ROW_SIZE = 3;
// public static final int INVENTORY_HOTBAR_SIZE = INVENTORY_ROW_SIZE;
// public static final int PLAYER_INVENTORY_WINDOW_ID = 0;
// public static final int SLOW_SORTING_DELAY = 30;
//
// /**
// * Returns the Minecraft folder ensuring:
// * - It is an absolute path
// * - It ends with a folder separator
// */
// public static String getMinecraftDir() {
// String absolutePath = Minecraft.getMinecraftDir().getAbsolutePath();
// if (absolutePath.endsWith(".")) {
// return absolutePath.substring(0, absolutePath.length() - 1);
// }
// if (absolutePath.endsWith(File.separator)) {
// return absolutePath;
// } else {
// return absolutePath + File.separatorChar;
// }
// }
//
// }
// Path: src/minecraft/invtweaks/InvTweaksGuiSettings.java
import invtweaks.InvTweaksConst;
import java.awt.Desktop;
import java.io.File;
import java.net.URL;
import java.util.List;
import java.util.logging.Logger;
import net.minecraft.client.Minecraft;
import net.minecraft.src.GuiButton;
import net.minecraft.src.GuiScreen;
import org.lwjgl.input.Keyboard;
import org.lwjgl.util.Point;
break;
// Toggle auto-refill before tool break
case ID_BEFORE_BREAK:
toggleBooleanButton(guibutton, InvTweaksConfig.PROP_AUTO_REFILL_BEFORE_BREAK, labelAutoRefillBeforeBreak);
break;
// Toggle shortcuts
case ID_SHORTCUTS:
toggleBooleanButton(guibutton, InvTweaksConfig.PROP_ENABLE_SHORTCUTS, labelShortcuts);
break;
// Shortcuts help
case ID_SHORTCUTS_HELP:
obf.displayGuiScreen(new InvTweaksGuiShortcutsHelp(mc, this, config));
break;
// More options screen
case ID_MORE_OPTIONS:
obf.displayGuiScreen(new InvTweaksGuiSettingsAdvanced(mc, parentScreen, config));
break;
// Sorting bug help screen
case ID_BUG_SORTING:
obf.displayGuiScreen(new InvTweaksGuiModNotWorking(mc, parentScreen, config));
break;
// Open rules configuration in external editor
case ID_EDITRULES:
try { | Desktop.getDesktop().open(new File(InvTweaksConst.CONFIG_RULES_FILE)); |
bbejeck/Java-7 | src/test/java/bbejeck/nio/files/directory/event/DirectoryEventWatcherImplTest.java | // Path: src/test/java/bbejeck/nio/files/BaseFileTest.java
// public class BaseFileTest {
// protected String baseDir = "test-files";
// protected String dir1 = "dir1";
// protected String dir2 = "dir2";
// protected String fileName;
// protected String fooDir = "foo";
// protected String copyDir = "copy";
// protected String tempDir = "temp";
// protected Path basePath;
// protected Path dir1Path;
// protected Path dir2Path;
// protected Path fooPath;
// protected Path sourcePath;
// protected Path copyPath;
// protected String[] fakeJavaFiles = new String[]{"Code.java", "Foo.java", "Bar.java", "Baz.java"};
// protected String[] textFileNames = new String[]{"persons.csv", "counts.csv", "CountyTaxes.csv"};
//
//
// @Before
// public void setUp() throws Exception {
// createPaths();
// cleanUp();
// createDirectories();
// generateFile(Paths.get(baseDir, fileName), 500);
// generateFiles(basePath, fakeJavaFiles, textFileNames);
// generateFiles(dir1Path, fakeJavaFiles);
// generateFiles(dir2Path, fakeJavaFiles);
// }
//
// protected void createPaths() {
// basePath = Paths.get(baseDir);
// dir1Path = basePath.resolve(dir1);
// dir2Path = basePath.resolve(dir2);
// fileName = "test.txt";
// sourcePath = basePath.resolve(fileName);
// copyPath = basePath.resolve(copyDir);
// fooPath = basePath.resolve(fooDir);
// }
//
// protected void cleanUp() throws Exception {
// DirUtils.deleteIfExists(basePath);
// Files.deleteIfExists(basePath.resolve(Paths.get(copyDir, fooDir)));
// Files.deleteIfExists(basePath.resolve(Paths.get(copyDir, tempDir)));
// Files.deleteIfExists(basePath.resolve(tempDir));
// Files.deleteIfExists(basePath.resolve("tempII"));
// }
//
// protected void createDirectories() throws Exception {
// Files.createDirectories(dir1Path);
// Files.createDirectories(dir2Path);
// Files.createDirectories(copyPath);
// Files.createDirectories(fooPath);
// }
//
// protected void generateFile(Path path, int numberLines) throws Exception {
// FileGenerator.generate(path, numberLines);
// }
//
// protected void generateFiles(Path path, String[]... fileNames) throws Exception {
// for (String[] fileNamesArray : fileNames) {
// for (String fileName : fileNamesArray) {
// generateFile(path.resolve(fileName), 10);
// }
// }
// }
// }
//
// Path: src/main/java/bbejeck/nio/files/event/PathEventContext.java
// public interface PathEventContext {
//
// boolean isValid();
//
// Path getWatchedDirectory();
//
// List<PathEvent> getEvents();
//
// }
//
// Path: src/main/java/bbejeck/nio/files/event/PathEventSubscriber.java
// public interface PathEventSubscriber {
//
// void handlePathEvents(PathEventContext pathEventContext);
// }
| import bbejeck.nio.files.BaseFileTest;
import bbejeck.nio.files.event.PathEventContext;
import bbejeck.nio.files.event.PathEventSubscriber;
import com.google.common.eventbus.EventBus;
import com.google.common.eventbus.Subscribe;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import java.nio.file.Path;
import java.util.*;
import java.util.concurrent.CountDownLatch;
import static org.hamcrest.CoreMatchers.is;
import static org.junit.Assert.assertThat; | package bbejeck.nio.files.directory.event;
/**
* Created by IntelliJ IDEA.
* User: bbejeck
* Date: 2/20/12
* Time: 10:32 PM
*/
//TODO add Test with Phaser to test adding deleting and updating
//TODO add directory on the fly then start watching and add file confirm added to new dir
public class DirectoryEventWatcherImplTest extends BaseFileTest {
private EventBus eventBus;
private DirectoryEventWatcherImpl dirWatcher;
private CountDownLatch doneSignal;
private TestSubscriber subscriber;
@Before
public void setUp() throws Exception {
createPaths();
cleanUp();
createDirectories();
eventBus = new EventBus();
dirWatcher = new DirectoryEventWatcherImpl(eventBus, basePath);
dirWatcher.start();
subscriber = new TestSubscriber();
eventBus.register(subscriber);
doneSignal = new CountDownLatch(3);
}
@Test
public void testDirectoryForWrittenEvents() throws Exception {
Map<Path,String> eventResultsMap = new HashMap<>();
assertThat(dirWatcher.isRunning(), is(true));
generateFile(dir1Path.resolve("newTextFile.txt"), 10);
generateFile(basePath.resolve("newTextFileII.txt"), 10);
generateFile(dir2Path.resolve("newTextFileIII.txt"), 10);
doneSignal.await();
assertThat(subscriber.pathEvents.size(), is(3)); | // Path: src/test/java/bbejeck/nio/files/BaseFileTest.java
// public class BaseFileTest {
// protected String baseDir = "test-files";
// protected String dir1 = "dir1";
// protected String dir2 = "dir2";
// protected String fileName;
// protected String fooDir = "foo";
// protected String copyDir = "copy";
// protected String tempDir = "temp";
// protected Path basePath;
// protected Path dir1Path;
// protected Path dir2Path;
// protected Path fooPath;
// protected Path sourcePath;
// protected Path copyPath;
// protected String[] fakeJavaFiles = new String[]{"Code.java", "Foo.java", "Bar.java", "Baz.java"};
// protected String[] textFileNames = new String[]{"persons.csv", "counts.csv", "CountyTaxes.csv"};
//
//
// @Before
// public void setUp() throws Exception {
// createPaths();
// cleanUp();
// createDirectories();
// generateFile(Paths.get(baseDir, fileName), 500);
// generateFiles(basePath, fakeJavaFiles, textFileNames);
// generateFiles(dir1Path, fakeJavaFiles);
// generateFiles(dir2Path, fakeJavaFiles);
// }
//
// protected void createPaths() {
// basePath = Paths.get(baseDir);
// dir1Path = basePath.resolve(dir1);
// dir2Path = basePath.resolve(dir2);
// fileName = "test.txt";
// sourcePath = basePath.resolve(fileName);
// copyPath = basePath.resolve(copyDir);
// fooPath = basePath.resolve(fooDir);
// }
//
// protected void cleanUp() throws Exception {
// DirUtils.deleteIfExists(basePath);
// Files.deleteIfExists(basePath.resolve(Paths.get(copyDir, fooDir)));
// Files.deleteIfExists(basePath.resolve(Paths.get(copyDir, tempDir)));
// Files.deleteIfExists(basePath.resolve(tempDir));
// Files.deleteIfExists(basePath.resolve("tempII"));
// }
//
// protected void createDirectories() throws Exception {
// Files.createDirectories(dir1Path);
// Files.createDirectories(dir2Path);
// Files.createDirectories(copyPath);
// Files.createDirectories(fooPath);
// }
//
// protected void generateFile(Path path, int numberLines) throws Exception {
// FileGenerator.generate(path, numberLines);
// }
//
// protected void generateFiles(Path path, String[]... fileNames) throws Exception {
// for (String[] fileNamesArray : fileNames) {
// for (String fileName : fileNamesArray) {
// generateFile(path.resolve(fileName), 10);
// }
// }
// }
// }
//
// Path: src/main/java/bbejeck/nio/files/event/PathEventContext.java
// public interface PathEventContext {
//
// boolean isValid();
//
// Path getWatchedDirectory();
//
// List<PathEvent> getEvents();
//
// }
//
// Path: src/main/java/bbejeck/nio/files/event/PathEventSubscriber.java
// public interface PathEventSubscriber {
//
// void handlePathEvents(PathEventContext pathEventContext);
// }
// Path: src/test/java/bbejeck/nio/files/directory/event/DirectoryEventWatcherImplTest.java
import bbejeck.nio.files.BaseFileTest;
import bbejeck.nio.files.event.PathEventContext;
import bbejeck.nio.files.event.PathEventSubscriber;
import com.google.common.eventbus.EventBus;
import com.google.common.eventbus.Subscribe;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import java.nio.file.Path;
import java.util.*;
import java.util.concurrent.CountDownLatch;
import static org.hamcrest.CoreMatchers.is;
import static org.junit.Assert.assertThat;
package bbejeck.nio.files.directory.event;
/**
* Created by IntelliJ IDEA.
* User: bbejeck
* Date: 2/20/12
* Time: 10:32 PM
*/
//TODO add Test with Phaser to test adding deleting and updating
//TODO add directory on the fly then start watching and add file confirm added to new dir
public class DirectoryEventWatcherImplTest extends BaseFileTest {
private EventBus eventBus;
private DirectoryEventWatcherImpl dirWatcher;
private CountDownLatch doneSignal;
private TestSubscriber subscriber;
@Before
public void setUp() throws Exception {
createPaths();
cleanUp();
createDirectories();
eventBus = new EventBus();
dirWatcher = new DirectoryEventWatcherImpl(eventBus, basePath);
dirWatcher.start();
subscriber = new TestSubscriber();
eventBus.register(subscriber);
doneSignal = new CountDownLatch(3);
}
@Test
public void testDirectoryForWrittenEvents() throws Exception {
Map<Path,String> eventResultsMap = new HashMap<>();
assertThat(dirWatcher.isRunning(), is(true));
generateFile(dir1Path.resolve("newTextFile.txt"), 10);
generateFile(basePath.resolve("newTextFileII.txt"), 10);
generateFile(dir2Path.resolve("newTextFileIII.txt"), 10);
doneSignal.await();
assertThat(subscriber.pathEvents.size(), is(3)); | List<PathEventContext> eventContexts = subscriber.pathEvents; |
bbejeck/Java-7 | src/test/java/bbejeck/nio/files/directory/event/DirectoryEventWatcherImplTest.java | // Path: src/test/java/bbejeck/nio/files/BaseFileTest.java
// public class BaseFileTest {
// protected String baseDir = "test-files";
// protected String dir1 = "dir1";
// protected String dir2 = "dir2";
// protected String fileName;
// protected String fooDir = "foo";
// protected String copyDir = "copy";
// protected String tempDir = "temp";
// protected Path basePath;
// protected Path dir1Path;
// protected Path dir2Path;
// protected Path fooPath;
// protected Path sourcePath;
// protected Path copyPath;
// protected String[] fakeJavaFiles = new String[]{"Code.java", "Foo.java", "Bar.java", "Baz.java"};
// protected String[] textFileNames = new String[]{"persons.csv", "counts.csv", "CountyTaxes.csv"};
//
//
// @Before
// public void setUp() throws Exception {
// createPaths();
// cleanUp();
// createDirectories();
// generateFile(Paths.get(baseDir, fileName), 500);
// generateFiles(basePath, fakeJavaFiles, textFileNames);
// generateFiles(dir1Path, fakeJavaFiles);
// generateFiles(dir2Path, fakeJavaFiles);
// }
//
// protected void createPaths() {
// basePath = Paths.get(baseDir);
// dir1Path = basePath.resolve(dir1);
// dir2Path = basePath.resolve(dir2);
// fileName = "test.txt";
// sourcePath = basePath.resolve(fileName);
// copyPath = basePath.resolve(copyDir);
// fooPath = basePath.resolve(fooDir);
// }
//
// protected void cleanUp() throws Exception {
// DirUtils.deleteIfExists(basePath);
// Files.deleteIfExists(basePath.resolve(Paths.get(copyDir, fooDir)));
// Files.deleteIfExists(basePath.resolve(Paths.get(copyDir, tempDir)));
// Files.deleteIfExists(basePath.resolve(tempDir));
// Files.deleteIfExists(basePath.resolve("tempII"));
// }
//
// protected void createDirectories() throws Exception {
// Files.createDirectories(dir1Path);
// Files.createDirectories(dir2Path);
// Files.createDirectories(copyPath);
// Files.createDirectories(fooPath);
// }
//
// protected void generateFile(Path path, int numberLines) throws Exception {
// FileGenerator.generate(path, numberLines);
// }
//
// protected void generateFiles(Path path, String[]... fileNames) throws Exception {
// for (String[] fileNamesArray : fileNames) {
// for (String fileName : fileNamesArray) {
// generateFile(path.resolve(fileName), 10);
// }
// }
// }
// }
//
// Path: src/main/java/bbejeck/nio/files/event/PathEventContext.java
// public interface PathEventContext {
//
// boolean isValid();
//
// Path getWatchedDirectory();
//
// List<PathEvent> getEvents();
//
// }
//
// Path: src/main/java/bbejeck/nio/files/event/PathEventSubscriber.java
// public interface PathEventSubscriber {
//
// void handlePathEvents(PathEventContext pathEventContext);
// }
| import bbejeck.nio.files.BaseFileTest;
import bbejeck.nio.files.event.PathEventContext;
import bbejeck.nio.files.event.PathEventSubscriber;
import com.google.common.eventbus.EventBus;
import com.google.common.eventbus.Subscribe;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import java.nio.file.Path;
import java.util.*;
import java.util.concurrent.CountDownLatch;
import static org.hamcrest.CoreMatchers.is;
import static org.junit.Assert.assertThat; |
}
Set<Path> watchedDirs = eventResultsMap.keySet();
assertThat(watchedDirs.size(),is(3));
assertThat(watchedDirs.contains(dir1Path), is(true));
assertThat(watchedDirs.contains(basePath), is(true));
assertThat(watchedDirs.contains(dir2Path), is(true));
assertThat(eventResultsMap.get(dir1Path), is("newTextFile.txt"));
assertThat(eventResultsMap.get(basePath), is("newTextFileII.txt"));
assertThat(eventResultsMap.get(dir2Path), is("newTextFileIII.txt"));
}
@Test
public void testStop() {
dirWatcher.stop();
Integer count = dirWatcher.getEventCount();
assertThat(count,is(0));
assertThat(dirWatcher.isRunning(),is(false));
}
@After
public void tearDown() throws Exception {
dirWatcher.stop();
}
| // Path: src/test/java/bbejeck/nio/files/BaseFileTest.java
// public class BaseFileTest {
// protected String baseDir = "test-files";
// protected String dir1 = "dir1";
// protected String dir2 = "dir2";
// protected String fileName;
// protected String fooDir = "foo";
// protected String copyDir = "copy";
// protected String tempDir = "temp";
// protected Path basePath;
// protected Path dir1Path;
// protected Path dir2Path;
// protected Path fooPath;
// protected Path sourcePath;
// protected Path copyPath;
// protected String[] fakeJavaFiles = new String[]{"Code.java", "Foo.java", "Bar.java", "Baz.java"};
// protected String[] textFileNames = new String[]{"persons.csv", "counts.csv", "CountyTaxes.csv"};
//
//
// @Before
// public void setUp() throws Exception {
// createPaths();
// cleanUp();
// createDirectories();
// generateFile(Paths.get(baseDir, fileName), 500);
// generateFiles(basePath, fakeJavaFiles, textFileNames);
// generateFiles(dir1Path, fakeJavaFiles);
// generateFiles(dir2Path, fakeJavaFiles);
// }
//
// protected void createPaths() {
// basePath = Paths.get(baseDir);
// dir1Path = basePath.resolve(dir1);
// dir2Path = basePath.resolve(dir2);
// fileName = "test.txt";
// sourcePath = basePath.resolve(fileName);
// copyPath = basePath.resolve(copyDir);
// fooPath = basePath.resolve(fooDir);
// }
//
// protected void cleanUp() throws Exception {
// DirUtils.deleteIfExists(basePath);
// Files.deleteIfExists(basePath.resolve(Paths.get(copyDir, fooDir)));
// Files.deleteIfExists(basePath.resolve(Paths.get(copyDir, tempDir)));
// Files.deleteIfExists(basePath.resolve(tempDir));
// Files.deleteIfExists(basePath.resolve("tempII"));
// }
//
// protected void createDirectories() throws Exception {
// Files.createDirectories(dir1Path);
// Files.createDirectories(dir2Path);
// Files.createDirectories(copyPath);
// Files.createDirectories(fooPath);
// }
//
// protected void generateFile(Path path, int numberLines) throws Exception {
// FileGenerator.generate(path, numberLines);
// }
//
// protected void generateFiles(Path path, String[]... fileNames) throws Exception {
// for (String[] fileNamesArray : fileNames) {
// for (String fileName : fileNamesArray) {
// generateFile(path.resolve(fileName), 10);
// }
// }
// }
// }
//
// Path: src/main/java/bbejeck/nio/files/event/PathEventContext.java
// public interface PathEventContext {
//
// boolean isValid();
//
// Path getWatchedDirectory();
//
// List<PathEvent> getEvents();
//
// }
//
// Path: src/main/java/bbejeck/nio/files/event/PathEventSubscriber.java
// public interface PathEventSubscriber {
//
// void handlePathEvents(PathEventContext pathEventContext);
// }
// Path: src/test/java/bbejeck/nio/files/directory/event/DirectoryEventWatcherImplTest.java
import bbejeck.nio.files.BaseFileTest;
import bbejeck.nio.files.event.PathEventContext;
import bbejeck.nio.files.event.PathEventSubscriber;
import com.google.common.eventbus.EventBus;
import com.google.common.eventbus.Subscribe;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import java.nio.file.Path;
import java.util.*;
import java.util.concurrent.CountDownLatch;
import static org.hamcrest.CoreMatchers.is;
import static org.junit.Assert.assertThat;
}
Set<Path> watchedDirs = eventResultsMap.keySet();
assertThat(watchedDirs.size(),is(3));
assertThat(watchedDirs.contains(dir1Path), is(true));
assertThat(watchedDirs.contains(basePath), is(true));
assertThat(watchedDirs.contains(dir2Path), is(true));
assertThat(eventResultsMap.get(dir1Path), is("newTextFile.txt"));
assertThat(eventResultsMap.get(basePath), is("newTextFileII.txt"));
assertThat(eventResultsMap.get(dir2Path), is("newTextFileIII.txt"));
}
@Test
public void testStop() {
dirWatcher.stop();
Integer count = dirWatcher.getEventCount();
assertThat(count,is(0));
assertThat(dirWatcher.isRunning(),is(false));
}
@After
public void tearDown() throws Exception {
dirWatcher.stop();
}
| private class TestSubscriber implements PathEventSubscriber { |
bbejeck/Java-7 | src/main/java/bbejeck/nio/AsyncSocketTestDriver.java | // Path: src/main/java/bbejeck/nio/channels/AsyncServerSocket.java
// public class AsyncServerSocket {
//
// private int count = 0;
// private CountDownLatch latch = new CountDownLatch(1);
// private int port;
// private String host;
// private AsynchronousChannelGroup channelGroup;
// private AsynchronousServerSocketChannel server;
//
// @Inject
// public AsyncServerSocket(@Port int port, @Host String host) throws Exception {
// this.port = port;
// this.host = host;
// }
//
// public void startServer() throws Exception {
// ExecutorService executorService = Executors.newCachedThreadPool();
// channelGroup = AsynchronousChannelGroup.withThreadPool(executorService);
// server = AsynchronousServerSocketChannel.open(channelGroup);
// server.bind(new InetSocketAddress(host, port));
// server.accept(null, new CompletionHandler<AsynchronousSocketChannel, Object>() {
// @Override
// public void completed(AsynchronousSocketChannel result, Object attachment) {
// server.accept(null, this);
// processConnection(result);
// }
//
// @Override
// public void failed(Throwable exc, Object attachment) {
// exc.printStackTrace();
// }
// });
// latch.await();
// channelGroup.shutdown();
// executorService.shutdownNow();
// System.out.println("AsyncServer shutting down");
// }
//
// private void processConnection(AsynchronousSocketChannel socket) {
// ByteBuffer byteBuffer = ByteBuffer.allocate(1000);
// Future<Integer> read = socket.read(byteBuffer);
// try {
// int totalBytes = read.get();
// String message = getMessageFromBuffer(byteBuffer, totalBytes);
// // System.out.println("Message[" + message + "] received @" + new Date());
// sendEchoResponse(byteBuffer, socket, message);
// if (message.equals("quit")) {
// quit();
// }
// } catch (InterruptedException | ExecutionException e) {
// quit();
// throw new RuntimeException(e);
// }
// }
//
// private void sendEchoResponse(ByteBuffer byteBuffer, AsynchronousSocketChannel socket, String originalMessage) {
// StringBuilder builder = new StringBuilder("You Said >> \"");
// builder.append(originalMessage).append("\"");
// byteBuffer.clear();
// byteBuffer.put(builder.toString().getBytes(Charset.forName("UTF-8")));
// byteBuffer.flip();
// socket.write(byteBuffer);
// }
//
//
// private String getMessageFromBuffer(ByteBuffer byteBuffer, int size) {
// byte[] bytes = new byte[size];
// byteBuffer.flip();
// byteBuffer.get(bytes, 0, size);
// return new String(bytes, Charset.forName("UTF-8"));
// }
//
// private void quit() {
// latch.countDown();
// }
//
// }
//
// Path: src/main/java/bbejeck/nio/channels/AsyncServerTestModule.java
// public class AsyncServerTestModule extends AbstractModule {
//
// @Override
// protected void configure() {
// bind(AsyncServerSocket.class);
// }
// }
//
// Path: src/main/java/bbejeck/nio/sockets/PlainSocketMessageSender.java
// public class PlainSocketMessageSender {
//
// private Socket socket;
// private int port;
// private InetSocketAddress socketAddress;
// private int messageCount;
//
// @Inject
// public PlainSocketMessageSender(@Port int port, @MessageCount int messageCount, @Host String host) {
// this.port = port;
// socketAddress = new InetSocketAddress(host, port);
// this.messageCount = messageCount;
// }
//
// public void sendMessages() throws Exception {
// for (int i = 0; i < messageCount; i++) {
// sendTextMessage("Plain text message from socket");
// }
// sendTextMessage("quit");
// }
//
// private void sendTextMessage(String message) throws Exception {
// socket = new Socket();
// socket.connect(socketAddress);
// BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
// bufferedWriter.write(message);
// bufferedWriter.flush();
// BufferedReader reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
// CharBuffer charBuffer = CharBuffer.allocate(1000);
// reader.read(charBuffer);
// charBuffer.flip();
// // System.out.println("Reply from server "+charBuffer.toString());
// reader.close();
// bufferedWriter.close();
// socket.close();
// }
// }
//
// Path: src/main/java/bbejeck/nio/sockets/PlainSocketModule.java
// public class PlainSocketModule extends AbstractModule {
//
// @Override
// protected void configure() {
// bind(PlainServerSocket.class);
// bind(PlainSocketMessageSender.class);
// }
// }
| import bbejeck.nio.channels.AsyncServerSocket;
import bbejeck.nio.channels.AsyncServerTestModule;
import bbejeck.nio.sockets.PlainSocketMessageSender;
import bbejeck.nio.sockets.PlainSocketModule;
import com.google.common.base.Stopwatch;
import com.google.inject.Guice;
import com.google.inject.Injector;
import java.util.concurrent.Callable;
import java.util.concurrent.FutureTask; | package bbejeck.nio;
/**
* Created by IntelliJ IDEA.
* User: bbejeck
* Date: 3/14/12
* Time: 9:48 PM
*/
public class AsyncSocketTestDriver {
public static void main(String[] args) throws Exception { | // Path: src/main/java/bbejeck/nio/channels/AsyncServerSocket.java
// public class AsyncServerSocket {
//
// private int count = 0;
// private CountDownLatch latch = new CountDownLatch(1);
// private int port;
// private String host;
// private AsynchronousChannelGroup channelGroup;
// private AsynchronousServerSocketChannel server;
//
// @Inject
// public AsyncServerSocket(@Port int port, @Host String host) throws Exception {
// this.port = port;
// this.host = host;
// }
//
// public void startServer() throws Exception {
// ExecutorService executorService = Executors.newCachedThreadPool();
// channelGroup = AsynchronousChannelGroup.withThreadPool(executorService);
// server = AsynchronousServerSocketChannel.open(channelGroup);
// server.bind(new InetSocketAddress(host, port));
// server.accept(null, new CompletionHandler<AsynchronousSocketChannel, Object>() {
// @Override
// public void completed(AsynchronousSocketChannel result, Object attachment) {
// server.accept(null, this);
// processConnection(result);
// }
//
// @Override
// public void failed(Throwable exc, Object attachment) {
// exc.printStackTrace();
// }
// });
// latch.await();
// channelGroup.shutdown();
// executorService.shutdownNow();
// System.out.println("AsyncServer shutting down");
// }
//
// private void processConnection(AsynchronousSocketChannel socket) {
// ByteBuffer byteBuffer = ByteBuffer.allocate(1000);
// Future<Integer> read = socket.read(byteBuffer);
// try {
// int totalBytes = read.get();
// String message = getMessageFromBuffer(byteBuffer, totalBytes);
// // System.out.println("Message[" + message + "] received @" + new Date());
// sendEchoResponse(byteBuffer, socket, message);
// if (message.equals("quit")) {
// quit();
// }
// } catch (InterruptedException | ExecutionException e) {
// quit();
// throw new RuntimeException(e);
// }
// }
//
// private void sendEchoResponse(ByteBuffer byteBuffer, AsynchronousSocketChannel socket, String originalMessage) {
// StringBuilder builder = new StringBuilder("You Said >> \"");
// builder.append(originalMessage).append("\"");
// byteBuffer.clear();
// byteBuffer.put(builder.toString().getBytes(Charset.forName("UTF-8")));
// byteBuffer.flip();
// socket.write(byteBuffer);
// }
//
//
// private String getMessageFromBuffer(ByteBuffer byteBuffer, int size) {
// byte[] bytes = new byte[size];
// byteBuffer.flip();
// byteBuffer.get(bytes, 0, size);
// return new String(bytes, Charset.forName("UTF-8"));
// }
//
// private void quit() {
// latch.countDown();
// }
//
// }
//
// Path: src/main/java/bbejeck/nio/channels/AsyncServerTestModule.java
// public class AsyncServerTestModule extends AbstractModule {
//
// @Override
// protected void configure() {
// bind(AsyncServerSocket.class);
// }
// }
//
// Path: src/main/java/bbejeck/nio/sockets/PlainSocketMessageSender.java
// public class PlainSocketMessageSender {
//
// private Socket socket;
// private int port;
// private InetSocketAddress socketAddress;
// private int messageCount;
//
// @Inject
// public PlainSocketMessageSender(@Port int port, @MessageCount int messageCount, @Host String host) {
// this.port = port;
// socketAddress = new InetSocketAddress(host, port);
// this.messageCount = messageCount;
// }
//
// public void sendMessages() throws Exception {
// for (int i = 0; i < messageCount; i++) {
// sendTextMessage("Plain text message from socket");
// }
// sendTextMessage("quit");
// }
//
// private void sendTextMessage(String message) throws Exception {
// socket = new Socket();
// socket.connect(socketAddress);
// BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
// bufferedWriter.write(message);
// bufferedWriter.flush();
// BufferedReader reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
// CharBuffer charBuffer = CharBuffer.allocate(1000);
// reader.read(charBuffer);
// charBuffer.flip();
// // System.out.println("Reply from server "+charBuffer.toString());
// reader.close();
// bufferedWriter.close();
// socket.close();
// }
// }
//
// Path: src/main/java/bbejeck/nio/sockets/PlainSocketModule.java
// public class PlainSocketModule extends AbstractModule {
//
// @Override
// protected void configure() {
// bind(PlainServerSocket.class);
// bind(PlainSocketMessageSender.class);
// }
// }
// Path: src/main/java/bbejeck/nio/AsyncSocketTestDriver.java
import bbejeck.nio.channels.AsyncServerSocket;
import bbejeck.nio.channels.AsyncServerTestModule;
import bbejeck.nio.sockets.PlainSocketMessageSender;
import bbejeck.nio.sockets.PlainSocketModule;
import com.google.common.base.Stopwatch;
import com.google.inject.Guice;
import com.google.inject.Injector;
import java.util.concurrent.Callable;
import java.util.concurrent.FutureTask;
package bbejeck.nio;
/**
* Created by IntelliJ IDEA.
* User: bbejeck
* Date: 3/14/12
* Time: 9:48 PM
*/
public class AsyncSocketTestDriver {
public static void main(String[] args) throws Exception { | Injector injector = Guice.createInjector(new SocketModule(), new PlainSocketModule(), new AsyncServerTestModule()); |
bbejeck/Java-7 | src/main/java/bbejeck/nio/AsyncSocketTestDriver.java | // Path: src/main/java/bbejeck/nio/channels/AsyncServerSocket.java
// public class AsyncServerSocket {
//
// private int count = 0;
// private CountDownLatch latch = new CountDownLatch(1);
// private int port;
// private String host;
// private AsynchronousChannelGroup channelGroup;
// private AsynchronousServerSocketChannel server;
//
// @Inject
// public AsyncServerSocket(@Port int port, @Host String host) throws Exception {
// this.port = port;
// this.host = host;
// }
//
// public void startServer() throws Exception {
// ExecutorService executorService = Executors.newCachedThreadPool();
// channelGroup = AsynchronousChannelGroup.withThreadPool(executorService);
// server = AsynchronousServerSocketChannel.open(channelGroup);
// server.bind(new InetSocketAddress(host, port));
// server.accept(null, new CompletionHandler<AsynchronousSocketChannel, Object>() {
// @Override
// public void completed(AsynchronousSocketChannel result, Object attachment) {
// server.accept(null, this);
// processConnection(result);
// }
//
// @Override
// public void failed(Throwable exc, Object attachment) {
// exc.printStackTrace();
// }
// });
// latch.await();
// channelGroup.shutdown();
// executorService.shutdownNow();
// System.out.println("AsyncServer shutting down");
// }
//
// private void processConnection(AsynchronousSocketChannel socket) {
// ByteBuffer byteBuffer = ByteBuffer.allocate(1000);
// Future<Integer> read = socket.read(byteBuffer);
// try {
// int totalBytes = read.get();
// String message = getMessageFromBuffer(byteBuffer, totalBytes);
// // System.out.println("Message[" + message + "] received @" + new Date());
// sendEchoResponse(byteBuffer, socket, message);
// if (message.equals("quit")) {
// quit();
// }
// } catch (InterruptedException | ExecutionException e) {
// quit();
// throw new RuntimeException(e);
// }
// }
//
// private void sendEchoResponse(ByteBuffer byteBuffer, AsynchronousSocketChannel socket, String originalMessage) {
// StringBuilder builder = new StringBuilder("You Said >> \"");
// builder.append(originalMessage).append("\"");
// byteBuffer.clear();
// byteBuffer.put(builder.toString().getBytes(Charset.forName("UTF-8")));
// byteBuffer.flip();
// socket.write(byteBuffer);
// }
//
//
// private String getMessageFromBuffer(ByteBuffer byteBuffer, int size) {
// byte[] bytes = new byte[size];
// byteBuffer.flip();
// byteBuffer.get(bytes, 0, size);
// return new String(bytes, Charset.forName("UTF-8"));
// }
//
// private void quit() {
// latch.countDown();
// }
//
// }
//
// Path: src/main/java/bbejeck/nio/channels/AsyncServerTestModule.java
// public class AsyncServerTestModule extends AbstractModule {
//
// @Override
// protected void configure() {
// bind(AsyncServerSocket.class);
// }
// }
//
// Path: src/main/java/bbejeck/nio/sockets/PlainSocketMessageSender.java
// public class PlainSocketMessageSender {
//
// private Socket socket;
// private int port;
// private InetSocketAddress socketAddress;
// private int messageCount;
//
// @Inject
// public PlainSocketMessageSender(@Port int port, @MessageCount int messageCount, @Host String host) {
// this.port = port;
// socketAddress = new InetSocketAddress(host, port);
// this.messageCount = messageCount;
// }
//
// public void sendMessages() throws Exception {
// for (int i = 0; i < messageCount; i++) {
// sendTextMessage("Plain text message from socket");
// }
// sendTextMessage("quit");
// }
//
// private void sendTextMessage(String message) throws Exception {
// socket = new Socket();
// socket.connect(socketAddress);
// BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
// bufferedWriter.write(message);
// bufferedWriter.flush();
// BufferedReader reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
// CharBuffer charBuffer = CharBuffer.allocate(1000);
// reader.read(charBuffer);
// charBuffer.flip();
// // System.out.println("Reply from server "+charBuffer.toString());
// reader.close();
// bufferedWriter.close();
// socket.close();
// }
// }
//
// Path: src/main/java/bbejeck/nio/sockets/PlainSocketModule.java
// public class PlainSocketModule extends AbstractModule {
//
// @Override
// protected void configure() {
// bind(PlainServerSocket.class);
// bind(PlainSocketMessageSender.class);
// }
// }
| import bbejeck.nio.channels.AsyncServerSocket;
import bbejeck.nio.channels.AsyncServerTestModule;
import bbejeck.nio.sockets.PlainSocketMessageSender;
import bbejeck.nio.sockets.PlainSocketModule;
import com.google.common.base.Stopwatch;
import com.google.inject.Guice;
import com.google.inject.Injector;
import java.util.concurrent.Callable;
import java.util.concurrent.FutureTask; | package bbejeck.nio;
/**
* Created by IntelliJ IDEA.
* User: bbejeck
* Date: 3/14/12
* Time: 9:48 PM
*/
public class AsyncSocketTestDriver {
public static void main(String[] args) throws Exception { | // Path: src/main/java/bbejeck/nio/channels/AsyncServerSocket.java
// public class AsyncServerSocket {
//
// private int count = 0;
// private CountDownLatch latch = new CountDownLatch(1);
// private int port;
// private String host;
// private AsynchronousChannelGroup channelGroup;
// private AsynchronousServerSocketChannel server;
//
// @Inject
// public AsyncServerSocket(@Port int port, @Host String host) throws Exception {
// this.port = port;
// this.host = host;
// }
//
// public void startServer() throws Exception {
// ExecutorService executorService = Executors.newCachedThreadPool();
// channelGroup = AsynchronousChannelGroup.withThreadPool(executorService);
// server = AsynchronousServerSocketChannel.open(channelGroup);
// server.bind(new InetSocketAddress(host, port));
// server.accept(null, new CompletionHandler<AsynchronousSocketChannel, Object>() {
// @Override
// public void completed(AsynchronousSocketChannel result, Object attachment) {
// server.accept(null, this);
// processConnection(result);
// }
//
// @Override
// public void failed(Throwable exc, Object attachment) {
// exc.printStackTrace();
// }
// });
// latch.await();
// channelGroup.shutdown();
// executorService.shutdownNow();
// System.out.println("AsyncServer shutting down");
// }
//
// private void processConnection(AsynchronousSocketChannel socket) {
// ByteBuffer byteBuffer = ByteBuffer.allocate(1000);
// Future<Integer> read = socket.read(byteBuffer);
// try {
// int totalBytes = read.get();
// String message = getMessageFromBuffer(byteBuffer, totalBytes);
// // System.out.println("Message[" + message + "] received @" + new Date());
// sendEchoResponse(byteBuffer, socket, message);
// if (message.equals("quit")) {
// quit();
// }
// } catch (InterruptedException | ExecutionException e) {
// quit();
// throw new RuntimeException(e);
// }
// }
//
// private void sendEchoResponse(ByteBuffer byteBuffer, AsynchronousSocketChannel socket, String originalMessage) {
// StringBuilder builder = new StringBuilder("You Said >> \"");
// builder.append(originalMessage).append("\"");
// byteBuffer.clear();
// byteBuffer.put(builder.toString().getBytes(Charset.forName("UTF-8")));
// byteBuffer.flip();
// socket.write(byteBuffer);
// }
//
//
// private String getMessageFromBuffer(ByteBuffer byteBuffer, int size) {
// byte[] bytes = new byte[size];
// byteBuffer.flip();
// byteBuffer.get(bytes, 0, size);
// return new String(bytes, Charset.forName("UTF-8"));
// }
//
// private void quit() {
// latch.countDown();
// }
//
// }
//
// Path: src/main/java/bbejeck/nio/channels/AsyncServerTestModule.java
// public class AsyncServerTestModule extends AbstractModule {
//
// @Override
// protected void configure() {
// bind(AsyncServerSocket.class);
// }
// }
//
// Path: src/main/java/bbejeck/nio/sockets/PlainSocketMessageSender.java
// public class PlainSocketMessageSender {
//
// private Socket socket;
// private int port;
// private InetSocketAddress socketAddress;
// private int messageCount;
//
// @Inject
// public PlainSocketMessageSender(@Port int port, @MessageCount int messageCount, @Host String host) {
// this.port = port;
// socketAddress = new InetSocketAddress(host, port);
// this.messageCount = messageCount;
// }
//
// public void sendMessages() throws Exception {
// for (int i = 0; i < messageCount; i++) {
// sendTextMessage("Plain text message from socket");
// }
// sendTextMessage("quit");
// }
//
// private void sendTextMessage(String message) throws Exception {
// socket = new Socket();
// socket.connect(socketAddress);
// BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
// bufferedWriter.write(message);
// bufferedWriter.flush();
// BufferedReader reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
// CharBuffer charBuffer = CharBuffer.allocate(1000);
// reader.read(charBuffer);
// charBuffer.flip();
// // System.out.println("Reply from server "+charBuffer.toString());
// reader.close();
// bufferedWriter.close();
// socket.close();
// }
// }
//
// Path: src/main/java/bbejeck/nio/sockets/PlainSocketModule.java
// public class PlainSocketModule extends AbstractModule {
//
// @Override
// protected void configure() {
// bind(PlainServerSocket.class);
// bind(PlainSocketMessageSender.class);
// }
// }
// Path: src/main/java/bbejeck/nio/AsyncSocketTestDriver.java
import bbejeck.nio.channels.AsyncServerSocket;
import bbejeck.nio.channels.AsyncServerTestModule;
import bbejeck.nio.sockets.PlainSocketMessageSender;
import bbejeck.nio.sockets.PlainSocketModule;
import com.google.common.base.Stopwatch;
import com.google.inject.Guice;
import com.google.inject.Injector;
import java.util.concurrent.Callable;
import java.util.concurrent.FutureTask;
package bbejeck.nio;
/**
* Created by IntelliJ IDEA.
* User: bbejeck
* Date: 3/14/12
* Time: 9:48 PM
*/
public class AsyncSocketTestDriver {
public static void main(String[] args) throws Exception { | Injector injector = Guice.createInjector(new SocketModule(), new PlainSocketModule(), new AsyncServerTestModule()); |
bbejeck/Java-7 | src/main/java/bbejeck/nio/AsyncSocketTestDriver.java | // Path: src/main/java/bbejeck/nio/channels/AsyncServerSocket.java
// public class AsyncServerSocket {
//
// private int count = 0;
// private CountDownLatch latch = new CountDownLatch(1);
// private int port;
// private String host;
// private AsynchronousChannelGroup channelGroup;
// private AsynchronousServerSocketChannel server;
//
// @Inject
// public AsyncServerSocket(@Port int port, @Host String host) throws Exception {
// this.port = port;
// this.host = host;
// }
//
// public void startServer() throws Exception {
// ExecutorService executorService = Executors.newCachedThreadPool();
// channelGroup = AsynchronousChannelGroup.withThreadPool(executorService);
// server = AsynchronousServerSocketChannel.open(channelGroup);
// server.bind(new InetSocketAddress(host, port));
// server.accept(null, new CompletionHandler<AsynchronousSocketChannel, Object>() {
// @Override
// public void completed(AsynchronousSocketChannel result, Object attachment) {
// server.accept(null, this);
// processConnection(result);
// }
//
// @Override
// public void failed(Throwable exc, Object attachment) {
// exc.printStackTrace();
// }
// });
// latch.await();
// channelGroup.shutdown();
// executorService.shutdownNow();
// System.out.println("AsyncServer shutting down");
// }
//
// private void processConnection(AsynchronousSocketChannel socket) {
// ByteBuffer byteBuffer = ByteBuffer.allocate(1000);
// Future<Integer> read = socket.read(byteBuffer);
// try {
// int totalBytes = read.get();
// String message = getMessageFromBuffer(byteBuffer, totalBytes);
// // System.out.println("Message[" + message + "] received @" + new Date());
// sendEchoResponse(byteBuffer, socket, message);
// if (message.equals("quit")) {
// quit();
// }
// } catch (InterruptedException | ExecutionException e) {
// quit();
// throw new RuntimeException(e);
// }
// }
//
// private void sendEchoResponse(ByteBuffer byteBuffer, AsynchronousSocketChannel socket, String originalMessage) {
// StringBuilder builder = new StringBuilder("You Said >> \"");
// builder.append(originalMessage).append("\"");
// byteBuffer.clear();
// byteBuffer.put(builder.toString().getBytes(Charset.forName("UTF-8")));
// byteBuffer.flip();
// socket.write(byteBuffer);
// }
//
//
// private String getMessageFromBuffer(ByteBuffer byteBuffer, int size) {
// byte[] bytes = new byte[size];
// byteBuffer.flip();
// byteBuffer.get(bytes, 0, size);
// return new String(bytes, Charset.forName("UTF-8"));
// }
//
// private void quit() {
// latch.countDown();
// }
//
// }
//
// Path: src/main/java/bbejeck/nio/channels/AsyncServerTestModule.java
// public class AsyncServerTestModule extends AbstractModule {
//
// @Override
// protected void configure() {
// bind(AsyncServerSocket.class);
// }
// }
//
// Path: src/main/java/bbejeck/nio/sockets/PlainSocketMessageSender.java
// public class PlainSocketMessageSender {
//
// private Socket socket;
// private int port;
// private InetSocketAddress socketAddress;
// private int messageCount;
//
// @Inject
// public PlainSocketMessageSender(@Port int port, @MessageCount int messageCount, @Host String host) {
// this.port = port;
// socketAddress = new InetSocketAddress(host, port);
// this.messageCount = messageCount;
// }
//
// public void sendMessages() throws Exception {
// for (int i = 0; i < messageCount; i++) {
// sendTextMessage("Plain text message from socket");
// }
// sendTextMessage("quit");
// }
//
// private void sendTextMessage(String message) throws Exception {
// socket = new Socket();
// socket.connect(socketAddress);
// BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
// bufferedWriter.write(message);
// bufferedWriter.flush();
// BufferedReader reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
// CharBuffer charBuffer = CharBuffer.allocate(1000);
// reader.read(charBuffer);
// charBuffer.flip();
// // System.out.println("Reply from server "+charBuffer.toString());
// reader.close();
// bufferedWriter.close();
// socket.close();
// }
// }
//
// Path: src/main/java/bbejeck/nio/sockets/PlainSocketModule.java
// public class PlainSocketModule extends AbstractModule {
//
// @Override
// protected void configure() {
// bind(PlainServerSocket.class);
// bind(PlainSocketMessageSender.class);
// }
// }
| import bbejeck.nio.channels.AsyncServerSocket;
import bbejeck.nio.channels.AsyncServerTestModule;
import bbejeck.nio.sockets.PlainSocketMessageSender;
import bbejeck.nio.sockets.PlainSocketModule;
import com.google.common.base.Stopwatch;
import com.google.inject.Guice;
import com.google.inject.Injector;
import java.util.concurrent.Callable;
import java.util.concurrent.FutureTask; | package bbejeck.nio;
/**
* Created by IntelliJ IDEA.
* User: bbejeck
* Date: 3/14/12
* Time: 9:48 PM
*/
public class AsyncSocketTestDriver {
public static void main(String[] args) throws Exception {
Injector injector = Guice.createInjector(new SocketModule(), new PlainSocketModule(), new AsyncServerTestModule()); | // Path: src/main/java/bbejeck/nio/channels/AsyncServerSocket.java
// public class AsyncServerSocket {
//
// private int count = 0;
// private CountDownLatch latch = new CountDownLatch(1);
// private int port;
// private String host;
// private AsynchronousChannelGroup channelGroup;
// private AsynchronousServerSocketChannel server;
//
// @Inject
// public AsyncServerSocket(@Port int port, @Host String host) throws Exception {
// this.port = port;
// this.host = host;
// }
//
// public void startServer() throws Exception {
// ExecutorService executorService = Executors.newCachedThreadPool();
// channelGroup = AsynchronousChannelGroup.withThreadPool(executorService);
// server = AsynchronousServerSocketChannel.open(channelGroup);
// server.bind(new InetSocketAddress(host, port));
// server.accept(null, new CompletionHandler<AsynchronousSocketChannel, Object>() {
// @Override
// public void completed(AsynchronousSocketChannel result, Object attachment) {
// server.accept(null, this);
// processConnection(result);
// }
//
// @Override
// public void failed(Throwable exc, Object attachment) {
// exc.printStackTrace();
// }
// });
// latch.await();
// channelGroup.shutdown();
// executorService.shutdownNow();
// System.out.println("AsyncServer shutting down");
// }
//
// private void processConnection(AsynchronousSocketChannel socket) {
// ByteBuffer byteBuffer = ByteBuffer.allocate(1000);
// Future<Integer> read = socket.read(byteBuffer);
// try {
// int totalBytes = read.get();
// String message = getMessageFromBuffer(byteBuffer, totalBytes);
// // System.out.println("Message[" + message + "] received @" + new Date());
// sendEchoResponse(byteBuffer, socket, message);
// if (message.equals("quit")) {
// quit();
// }
// } catch (InterruptedException | ExecutionException e) {
// quit();
// throw new RuntimeException(e);
// }
// }
//
// private void sendEchoResponse(ByteBuffer byteBuffer, AsynchronousSocketChannel socket, String originalMessage) {
// StringBuilder builder = new StringBuilder("You Said >> \"");
// builder.append(originalMessage).append("\"");
// byteBuffer.clear();
// byteBuffer.put(builder.toString().getBytes(Charset.forName("UTF-8")));
// byteBuffer.flip();
// socket.write(byteBuffer);
// }
//
//
// private String getMessageFromBuffer(ByteBuffer byteBuffer, int size) {
// byte[] bytes = new byte[size];
// byteBuffer.flip();
// byteBuffer.get(bytes, 0, size);
// return new String(bytes, Charset.forName("UTF-8"));
// }
//
// private void quit() {
// latch.countDown();
// }
//
// }
//
// Path: src/main/java/bbejeck/nio/channels/AsyncServerTestModule.java
// public class AsyncServerTestModule extends AbstractModule {
//
// @Override
// protected void configure() {
// bind(AsyncServerSocket.class);
// }
// }
//
// Path: src/main/java/bbejeck/nio/sockets/PlainSocketMessageSender.java
// public class PlainSocketMessageSender {
//
// private Socket socket;
// private int port;
// private InetSocketAddress socketAddress;
// private int messageCount;
//
// @Inject
// public PlainSocketMessageSender(@Port int port, @MessageCount int messageCount, @Host String host) {
// this.port = port;
// socketAddress = new InetSocketAddress(host, port);
// this.messageCount = messageCount;
// }
//
// public void sendMessages() throws Exception {
// for (int i = 0; i < messageCount; i++) {
// sendTextMessage("Plain text message from socket");
// }
// sendTextMessage("quit");
// }
//
// private void sendTextMessage(String message) throws Exception {
// socket = new Socket();
// socket.connect(socketAddress);
// BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
// bufferedWriter.write(message);
// bufferedWriter.flush();
// BufferedReader reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
// CharBuffer charBuffer = CharBuffer.allocate(1000);
// reader.read(charBuffer);
// charBuffer.flip();
// // System.out.println("Reply from server "+charBuffer.toString());
// reader.close();
// bufferedWriter.close();
// socket.close();
// }
// }
//
// Path: src/main/java/bbejeck/nio/sockets/PlainSocketModule.java
// public class PlainSocketModule extends AbstractModule {
//
// @Override
// protected void configure() {
// bind(PlainServerSocket.class);
// bind(PlainSocketMessageSender.class);
// }
// }
// Path: src/main/java/bbejeck/nio/AsyncSocketTestDriver.java
import bbejeck.nio.channels.AsyncServerSocket;
import bbejeck.nio.channels.AsyncServerTestModule;
import bbejeck.nio.sockets.PlainSocketMessageSender;
import bbejeck.nio.sockets.PlainSocketModule;
import com.google.common.base.Stopwatch;
import com.google.inject.Guice;
import com.google.inject.Injector;
import java.util.concurrent.Callable;
import java.util.concurrent.FutureTask;
package bbejeck.nio;
/**
* Created by IntelliJ IDEA.
* User: bbejeck
* Date: 3/14/12
* Time: 9:48 PM
*/
public class AsyncSocketTestDriver {
public static void main(String[] args) throws Exception {
Injector injector = Guice.createInjector(new SocketModule(), new PlainSocketModule(), new AsyncServerTestModule()); | PlainSocketMessageSender messageSender = injector.getInstance(PlainSocketMessageSender.class); |
bbejeck/Java-7 | src/main/java/bbejeck/nio/AsyncSocketTestDriver.java | // Path: src/main/java/bbejeck/nio/channels/AsyncServerSocket.java
// public class AsyncServerSocket {
//
// private int count = 0;
// private CountDownLatch latch = new CountDownLatch(1);
// private int port;
// private String host;
// private AsynchronousChannelGroup channelGroup;
// private AsynchronousServerSocketChannel server;
//
// @Inject
// public AsyncServerSocket(@Port int port, @Host String host) throws Exception {
// this.port = port;
// this.host = host;
// }
//
// public void startServer() throws Exception {
// ExecutorService executorService = Executors.newCachedThreadPool();
// channelGroup = AsynchronousChannelGroup.withThreadPool(executorService);
// server = AsynchronousServerSocketChannel.open(channelGroup);
// server.bind(new InetSocketAddress(host, port));
// server.accept(null, new CompletionHandler<AsynchronousSocketChannel, Object>() {
// @Override
// public void completed(AsynchronousSocketChannel result, Object attachment) {
// server.accept(null, this);
// processConnection(result);
// }
//
// @Override
// public void failed(Throwable exc, Object attachment) {
// exc.printStackTrace();
// }
// });
// latch.await();
// channelGroup.shutdown();
// executorService.shutdownNow();
// System.out.println("AsyncServer shutting down");
// }
//
// private void processConnection(AsynchronousSocketChannel socket) {
// ByteBuffer byteBuffer = ByteBuffer.allocate(1000);
// Future<Integer> read = socket.read(byteBuffer);
// try {
// int totalBytes = read.get();
// String message = getMessageFromBuffer(byteBuffer, totalBytes);
// // System.out.println("Message[" + message + "] received @" + new Date());
// sendEchoResponse(byteBuffer, socket, message);
// if (message.equals("quit")) {
// quit();
// }
// } catch (InterruptedException | ExecutionException e) {
// quit();
// throw new RuntimeException(e);
// }
// }
//
// private void sendEchoResponse(ByteBuffer byteBuffer, AsynchronousSocketChannel socket, String originalMessage) {
// StringBuilder builder = new StringBuilder("You Said >> \"");
// builder.append(originalMessage).append("\"");
// byteBuffer.clear();
// byteBuffer.put(builder.toString().getBytes(Charset.forName("UTF-8")));
// byteBuffer.flip();
// socket.write(byteBuffer);
// }
//
//
// private String getMessageFromBuffer(ByteBuffer byteBuffer, int size) {
// byte[] bytes = new byte[size];
// byteBuffer.flip();
// byteBuffer.get(bytes, 0, size);
// return new String(bytes, Charset.forName("UTF-8"));
// }
//
// private void quit() {
// latch.countDown();
// }
//
// }
//
// Path: src/main/java/bbejeck/nio/channels/AsyncServerTestModule.java
// public class AsyncServerTestModule extends AbstractModule {
//
// @Override
// protected void configure() {
// bind(AsyncServerSocket.class);
// }
// }
//
// Path: src/main/java/bbejeck/nio/sockets/PlainSocketMessageSender.java
// public class PlainSocketMessageSender {
//
// private Socket socket;
// private int port;
// private InetSocketAddress socketAddress;
// private int messageCount;
//
// @Inject
// public PlainSocketMessageSender(@Port int port, @MessageCount int messageCount, @Host String host) {
// this.port = port;
// socketAddress = new InetSocketAddress(host, port);
// this.messageCount = messageCount;
// }
//
// public void sendMessages() throws Exception {
// for (int i = 0; i < messageCount; i++) {
// sendTextMessage("Plain text message from socket");
// }
// sendTextMessage("quit");
// }
//
// private void sendTextMessage(String message) throws Exception {
// socket = new Socket();
// socket.connect(socketAddress);
// BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
// bufferedWriter.write(message);
// bufferedWriter.flush();
// BufferedReader reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
// CharBuffer charBuffer = CharBuffer.allocate(1000);
// reader.read(charBuffer);
// charBuffer.flip();
// // System.out.println("Reply from server "+charBuffer.toString());
// reader.close();
// bufferedWriter.close();
// socket.close();
// }
// }
//
// Path: src/main/java/bbejeck/nio/sockets/PlainSocketModule.java
// public class PlainSocketModule extends AbstractModule {
//
// @Override
// protected void configure() {
// bind(PlainServerSocket.class);
// bind(PlainSocketMessageSender.class);
// }
// }
| import bbejeck.nio.channels.AsyncServerSocket;
import bbejeck.nio.channels.AsyncServerTestModule;
import bbejeck.nio.sockets.PlainSocketMessageSender;
import bbejeck.nio.sockets.PlainSocketModule;
import com.google.common.base.Stopwatch;
import com.google.inject.Guice;
import com.google.inject.Injector;
import java.util.concurrent.Callable;
import java.util.concurrent.FutureTask; | package bbejeck.nio;
/**
* Created by IntelliJ IDEA.
* User: bbejeck
* Date: 3/14/12
* Time: 9:48 PM
*/
public class AsyncSocketTestDriver {
public static void main(String[] args) throws Exception {
Injector injector = Guice.createInjector(new SocketModule(), new PlainSocketModule(), new AsyncServerTestModule());
PlainSocketMessageSender messageSender = injector.getInstance(PlainSocketMessageSender.class); | // Path: src/main/java/bbejeck/nio/channels/AsyncServerSocket.java
// public class AsyncServerSocket {
//
// private int count = 0;
// private CountDownLatch latch = new CountDownLatch(1);
// private int port;
// private String host;
// private AsynchronousChannelGroup channelGroup;
// private AsynchronousServerSocketChannel server;
//
// @Inject
// public AsyncServerSocket(@Port int port, @Host String host) throws Exception {
// this.port = port;
// this.host = host;
// }
//
// public void startServer() throws Exception {
// ExecutorService executorService = Executors.newCachedThreadPool();
// channelGroup = AsynchronousChannelGroup.withThreadPool(executorService);
// server = AsynchronousServerSocketChannel.open(channelGroup);
// server.bind(new InetSocketAddress(host, port));
// server.accept(null, new CompletionHandler<AsynchronousSocketChannel, Object>() {
// @Override
// public void completed(AsynchronousSocketChannel result, Object attachment) {
// server.accept(null, this);
// processConnection(result);
// }
//
// @Override
// public void failed(Throwable exc, Object attachment) {
// exc.printStackTrace();
// }
// });
// latch.await();
// channelGroup.shutdown();
// executorService.shutdownNow();
// System.out.println("AsyncServer shutting down");
// }
//
// private void processConnection(AsynchronousSocketChannel socket) {
// ByteBuffer byteBuffer = ByteBuffer.allocate(1000);
// Future<Integer> read = socket.read(byteBuffer);
// try {
// int totalBytes = read.get();
// String message = getMessageFromBuffer(byteBuffer, totalBytes);
// // System.out.println("Message[" + message + "] received @" + new Date());
// sendEchoResponse(byteBuffer, socket, message);
// if (message.equals("quit")) {
// quit();
// }
// } catch (InterruptedException | ExecutionException e) {
// quit();
// throw new RuntimeException(e);
// }
// }
//
// private void sendEchoResponse(ByteBuffer byteBuffer, AsynchronousSocketChannel socket, String originalMessage) {
// StringBuilder builder = new StringBuilder("You Said >> \"");
// builder.append(originalMessage).append("\"");
// byteBuffer.clear();
// byteBuffer.put(builder.toString().getBytes(Charset.forName("UTF-8")));
// byteBuffer.flip();
// socket.write(byteBuffer);
// }
//
//
// private String getMessageFromBuffer(ByteBuffer byteBuffer, int size) {
// byte[] bytes = new byte[size];
// byteBuffer.flip();
// byteBuffer.get(bytes, 0, size);
// return new String(bytes, Charset.forName("UTF-8"));
// }
//
// private void quit() {
// latch.countDown();
// }
//
// }
//
// Path: src/main/java/bbejeck/nio/channels/AsyncServerTestModule.java
// public class AsyncServerTestModule extends AbstractModule {
//
// @Override
// protected void configure() {
// bind(AsyncServerSocket.class);
// }
// }
//
// Path: src/main/java/bbejeck/nio/sockets/PlainSocketMessageSender.java
// public class PlainSocketMessageSender {
//
// private Socket socket;
// private int port;
// private InetSocketAddress socketAddress;
// private int messageCount;
//
// @Inject
// public PlainSocketMessageSender(@Port int port, @MessageCount int messageCount, @Host String host) {
// this.port = port;
// socketAddress = new InetSocketAddress(host, port);
// this.messageCount = messageCount;
// }
//
// public void sendMessages() throws Exception {
// for (int i = 0; i < messageCount; i++) {
// sendTextMessage("Plain text message from socket");
// }
// sendTextMessage("quit");
// }
//
// private void sendTextMessage(String message) throws Exception {
// socket = new Socket();
// socket.connect(socketAddress);
// BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
// bufferedWriter.write(message);
// bufferedWriter.flush();
// BufferedReader reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
// CharBuffer charBuffer = CharBuffer.allocate(1000);
// reader.read(charBuffer);
// charBuffer.flip();
// // System.out.println("Reply from server "+charBuffer.toString());
// reader.close();
// bufferedWriter.close();
// socket.close();
// }
// }
//
// Path: src/main/java/bbejeck/nio/sockets/PlainSocketModule.java
// public class PlainSocketModule extends AbstractModule {
//
// @Override
// protected void configure() {
// bind(PlainServerSocket.class);
// bind(PlainSocketMessageSender.class);
// }
// }
// Path: src/main/java/bbejeck/nio/AsyncSocketTestDriver.java
import bbejeck.nio.channels.AsyncServerSocket;
import bbejeck.nio.channels.AsyncServerTestModule;
import bbejeck.nio.sockets.PlainSocketMessageSender;
import bbejeck.nio.sockets.PlainSocketModule;
import com.google.common.base.Stopwatch;
import com.google.inject.Guice;
import com.google.inject.Injector;
import java.util.concurrent.Callable;
import java.util.concurrent.FutureTask;
package bbejeck.nio;
/**
* Created by IntelliJ IDEA.
* User: bbejeck
* Date: 3/14/12
* Time: 9:48 PM
*/
public class AsyncSocketTestDriver {
public static void main(String[] args) throws Exception {
Injector injector = Guice.createInjector(new SocketModule(), new PlainSocketModule(), new AsyncServerTestModule());
PlainSocketMessageSender messageSender = injector.getInstance(PlainSocketMessageSender.class); | final AsyncServerSocket asyncServerSocket = injector.getInstance(AsyncServerSocket.class); |
bbejeck/Java-7 | src/main/java/bbejeck/nio/util/DirUtils.java | // Path: src/main/java/bbejeck/nio/files/directory/AsynchronousRecursiveDirectoryStream.java
// public class AsynchronousRecursiveDirectoryStream implements DirectoryStream<Path> {
//
// private LinkedBlockingQueue<Path> pathsBlockingQueue = new LinkedBlockingQueue<>();
// private boolean closed = false;
// private FutureTask<Void> pathTask;
// private Path startPath;
// private Filter filter;
//
// public AsynchronousRecursiveDirectoryStream(Path startPath, String pattern) throws IOException {
// this.filter = FilterBuilder.buildGlobFilter(Objects.requireNonNull(pattern));
// this.startPath = Objects.requireNonNull(startPath);
// }
//
// @Override
// public Iterator<Path> iterator() {
// confirmNotClosed();
// findFiles(startPath, filter);
// return new Iterator<Path>() {
// Path path;
// @Override
// public boolean hasNext() {
// try {
// path = pathsBlockingQueue.poll();
// while (!pathTask.isDone() && path == null) {
// path = pathsBlockingQueue.poll(5, TimeUnit.MILLISECONDS);
// }
// return (path != null);
// } catch (InterruptedException e) {
// Thread.currentThread().interrupt();
// }
// return false;
// }
//
// @Override
// public Path next() {
// return path;
// }
//
// @Override
// public void remove() {
// throw new UnsupportedOperationException("Removal not supported");
// }
// };
// }
//
// private void findFiles(final Path startPath, final Filter filter) {
// pathTask = new FutureTask<>(new Callable<Void>() {
// @Override
// public Void call() throws Exception {
// Files.walkFileTree(startPath, new FunctionVisitor(getFunction(filter)));
// return null;
// }
// });
// start(pathTask);
// }
//
// private Function<Path, FileVisitResult> getFunction(final Filter<Path> filter) {
// return new Function<Path, FileVisitResult>() {
// @Override
// public FileVisitResult apply(Path input) {
// try {
// if (filter.accept(input.getFileName())) {
// pathsBlockingQueue.offer(input);
// }
// } catch (IOException e) {
// throw new RuntimeException(e.getMessage());
// }
// return (pathTask.isCancelled()) ? FileVisitResult.TERMINATE : FileVisitResult.CONTINUE;
// }
// };
// }
//
//
// @Override
// public void close() throws IOException {
// if(pathTask !=null){
// pathTask.cancel(true);
// }
// pathsBlockingQueue.clear();
// pathsBlockingQueue = null;
// pathTask = null;
// filter = null;
// closed = true;
// }
//
// private void start(FutureTask<Void> futureTask) {
// new Thread(futureTask).start();
// }
//
// private void confirmNotClosed() {
// if (closed) {
// throw new IllegalStateException("DirectoryStream has already been closed");
// }
// }
//
// }
| import bbejeck.nio.files.directory.AsynchronousRecursiveDirectoryStream;
import bbejeck.nio.files.visitor.*;
import com.google.common.base.Function;
import com.google.common.base.Predicate;
import java.io.IOException;
import java.nio.file.*;
import java.util.EnumSet;
import java.util.Objects; | * @param function
* @throws IOException
*/
public static void apply(Path target, Function<Path,FileVisitResult> function) throws IOException{
validate(target);
Files.walkFileTree(target,new FunctionVisitor(function));
}
/**
* Traverses the directory structure and will only copy sub-tree structures where the provided predicate is true
* @param from
* @param to
* @param predicate
* @throws IOException
*/
public static void copyWithPredicate(Path from, Path to, Predicate<Path> predicate) throws IOException{
validate(from);
Files.walkFileTree(from, new CopyPredicateVisitor(from,to,predicate));
}
/**
* Returns a DirectoryStream that can iterate over files found recursively based on the pattern provided
* @param startPath the Directory to start from
* @param pattern the glob to match against files
* @return DirectoryStream
* @throws IOException
*/
public static DirectoryStream<Path> glob(Path startPath, String pattern) throws IOException{
validate(startPath); | // Path: src/main/java/bbejeck/nio/files/directory/AsynchronousRecursiveDirectoryStream.java
// public class AsynchronousRecursiveDirectoryStream implements DirectoryStream<Path> {
//
// private LinkedBlockingQueue<Path> pathsBlockingQueue = new LinkedBlockingQueue<>();
// private boolean closed = false;
// private FutureTask<Void> pathTask;
// private Path startPath;
// private Filter filter;
//
// public AsynchronousRecursiveDirectoryStream(Path startPath, String pattern) throws IOException {
// this.filter = FilterBuilder.buildGlobFilter(Objects.requireNonNull(pattern));
// this.startPath = Objects.requireNonNull(startPath);
// }
//
// @Override
// public Iterator<Path> iterator() {
// confirmNotClosed();
// findFiles(startPath, filter);
// return new Iterator<Path>() {
// Path path;
// @Override
// public boolean hasNext() {
// try {
// path = pathsBlockingQueue.poll();
// while (!pathTask.isDone() && path == null) {
// path = pathsBlockingQueue.poll(5, TimeUnit.MILLISECONDS);
// }
// return (path != null);
// } catch (InterruptedException e) {
// Thread.currentThread().interrupt();
// }
// return false;
// }
//
// @Override
// public Path next() {
// return path;
// }
//
// @Override
// public void remove() {
// throw new UnsupportedOperationException("Removal not supported");
// }
// };
// }
//
// private void findFiles(final Path startPath, final Filter filter) {
// pathTask = new FutureTask<>(new Callable<Void>() {
// @Override
// public Void call() throws Exception {
// Files.walkFileTree(startPath, new FunctionVisitor(getFunction(filter)));
// return null;
// }
// });
// start(pathTask);
// }
//
// private Function<Path, FileVisitResult> getFunction(final Filter<Path> filter) {
// return new Function<Path, FileVisitResult>() {
// @Override
// public FileVisitResult apply(Path input) {
// try {
// if (filter.accept(input.getFileName())) {
// pathsBlockingQueue.offer(input);
// }
// } catch (IOException e) {
// throw new RuntimeException(e.getMessage());
// }
// return (pathTask.isCancelled()) ? FileVisitResult.TERMINATE : FileVisitResult.CONTINUE;
// }
// };
// }
//
//
// @Override
// public void close() throws IOException {
// if(pathTask !=null){
// pathTask.cancel(true);
// }
// pathsBlockingQueue.clear();
// pathsBlockingQueue = null;
// pathTask = null;
// filter = null;
// closed = true;
// }
//
// private void start(FutureTask<Void> futureTask) {
// new Thread(futureTask).start();
// }
//
// private void confirmNotClosed() {
// if (closed) {
// throw new IllegalStateException("DirectoryStream has already been closed");
// }
// }
//
// }
// Path: src/main/java/bbejeck/nio/util/DirUtils.java
import bbejeck.nio.files.directory.AsynchronousRecursiveDirectoryStream;
import bbejeck.nio.files.visitor.*;
import com.google.common.base.Function;
import com.google.common.base.Predicate;
import java.io.IOException;
import java.nio.file.*;
import java.util.EnumSet;
import java.util.Objects;
* @param function
* @throws IOException
*/
public static void apply(Path target, Function<Path,FileVisitResult> function) throws IOException{
validate(target);
Files.walkFileTree(target,new FunctionVisitor(function));
}
/**
* Traverses the directory structure and will only copy sub-tree structures where the provided predicate is true
* @param from
* @param to
* @param predicate
* @throws IOException
*/
public static void copyWithPredicate(Path from, Path to, Predicate<Path> predicate) throws IOException{
validate(from);
Files.walkFileTree(from, new CopyPredicateVisitor(from,to,predicate));
}
/**
* Returns a DirectoryStream that can iterate over files found recursively based on the pattern provided
* @param startPath the Directory to start from
* @param pattern the glob to match against files
* @return DirectoryStream
* @throws IOException
*/
public static DirectoryStream<Path> glob(Path startPath, String pattern) throws IOException{
validate(startPath); | return new AsynchronousRecursiveDirectoryStream(startPath,pattern); |
bbejeck/Java-7 | src/test/java/bbejeck/nio/files/directory/event/DirectoryEventWatcherGuiceTest.java | // Path: src/test/java/bbejeck/nio/files/BaseFileTest.java
// public class BaseFileTest {
// protected String baseDir = "test-files";
// protected String dir1 = "dir1";
// protected String dir2 = "dir2";
// protected String fileName;
// protected String fooDir = "foo";
// protected String copyDir = "copy";
// protected String tempDir = "temp";
// protected Path basePath;
// protected Path dir1Path;
// protected Path dir2Path;
// protected Path fooPath;
// protected Path sourcePath;
// protected Path copyPath;
// protected String[] fakeJavaFiles = new String[]{"Code.java", "Foo.java", "Bar.java", "Baz.java"};
// protected String[] textFileNames = new String[]{"persons.csv", "counts.csv", "CountyTaxes.csv"};
//
//
// @Before
// public void setUp() throws Exception {
// createPaths();
// cleanUp();
// createDirectories();
// generateFile(Paths.get(baseDir, fileName), 500);
// generateFiles(basePath, fakeJavaFiles, textFileNames);
// generateFiles(dir1Path, fakeJavaFiles);
// generateFiles(dir2Path, fakeJavaFiles);
// }
//
// protected void createPaths() {
// basePath = Paths.get(baseDir);
// dir1Path = basePath.resolve(dir1);
// dir2Path = basePath.resolve(dir2);
// fileName = "test.txt";
// sourcePath = basePath.resolve(fileName);
// copyPath = basePath.resolve(copyDir);
// fooPath = basePath.resolve(fooDir);
// }
//
// protected void cleanUp() throws Exception {
// DirUtils.deleteIfExists(basePath);
// Files.deleteIfExists(basePath.resolve(Paths.get(copyDir, fooDir)));
// Files.deleteIfExists(basePath.resolve(Paths.get(copyDir, tempDir)));
// Files.deleteIfExists(basePath.resolve(tempDir));
// Files.deleteIfExists(basePath.resolve("tempII"));
// }
//
// protected void createDirectories() throws Exception {
// Files.createDirectories(dir1Path);
// Files.createDirectories(dir2Path);
// Files.createDirectories(copyPath);
// Files.createDirectories(fooPath);
// }
//
// protected void generateFile(Path path, int numberLines) throws Exception {
// FileGenerator.generate(path, numberLines);
// }
//
// protected void generateFiles(Path path, String[]... fileNames) throws Exception {
// for (String[] fileNamesArray : fileNames) {
// for (String fileName : fileNamesArray) {
// generateFile(path.resolve(fileName), 10);
// }
// }
// }
// }
//
// Path: src/main/java/bbejeck/nio/files/event/PathEventContext.java
// public interface PathEventContext {
//
// boolean isValid();
//
// Path getWatchedDirectory();
//
// List<PathEvent> getEvents();
//
// }
//
// Path: src/main/java/bbejeck/nio/files/event/PathEventSubscriber.java
// public interface PathEventSubscriber {
//
// void handlePathEvents(PathEventContext pathEventContext);
// }
| import bbejeck.nio.files.BaseFileTest;
import bbejeck.nio.files.event.PathEventContext;
import bbejeck.nio.files.event.PathEventSubscriber;
import com.google.common.eventbus.EventBus;
import com.google.common.eventbus.Subscribe;
import com.google.inject.Guice;
import com.google.inject.Injector;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import java.nio.file.Path;
import java.util.*;
import java.util.concurrent.CountDownLatch;
import static org.hamcrest.CoreMatchers.is;
import static org.junit.Assert.assertThat; | package bbejeck.nio.files.directory.event;
/**
* Created by IntelliJ IDEA.
* User: bbejeck
* Date: 2/25/12
*/
public class DirectoryEventWatcherGuiceTest extends BaseFileTest {
private DirectoryEventWatcher directoryEventWatcher;
private CountDownLatch latch;
private TestSubscriber subscriber;
@Before
public void setUp() throws Exception {
createPaths();
cleanUp();
createDirectories();
latch = new CountDownLatch(3);
Injector injector = Guice.createInjector(new DirectoryEventModule());
directoryEventWatcher = injector.getInstance(DirectoryEventWatcher.class);
EventBus eventBus = injector.getInstance(EventBus.class);
subscriber = new TestSubscriber();
eventBus.register(subscriber);
directoryEventWatcher.start();
}
@Test
public void testDirectoryForWrittenEvents() throws Exception {
Map<Path, String> eventResultsMap = new HashMap<>();
assertThat(directoryEventWatcher.isRunning(), is(true));
generateFile(dir1Path.resolve("newTextFile.txt"), 10);
generateFile(basePath.resolve("newTextFileII.txt"), 10);
generateFile(dir2Path.resolve("newTextFileIII.txt"), 10);
latch.await();
assertThat(subscriber.pathEvents.size(), is(3)); | // Path: src/test/java/bbejeck/nio/files/BaseFileTest.java
// public class BaseFileTest {
// protected String baseDir = "test-files";
// protected String dir1 = "dir1";
// protected String dir2 = "dir2";
// protected String fileName;
// protected String fooDir = "foo";
// protected String copyDir = "copy";
// protected String tempDir = "temp";
// protected Path basePath;
// protected Path dir1Path;
// protected Path dir2Path;
// protected Path fooPath;
// protected Path sourcePath;
// protected Path copyPath;
// protected String[] fakeJavaFiles = new String[]{"Code.java", "Foo.java", "Bar.java", "Baz.java"};
// protected String[] textFileNames = new String[]{"persons.csv", "counts.csv", "CountyTaxes.csv"};
//
//
// @Before
// public void setUp() throws Exception {
// createPaths();
// cleanUp();
// createDirectories();
// generateFile(Paths.get(baseDir, fileName), 500);
// generateFiles(basePath, fakeJavaFiles, textFileNames);
// generateFiles(dir1Path, fakeJavaFiles);
// generateFiles(dir2Path, fakeJavaFiles);
// }
//
// protected void createPaths() {
// basePath = Paths.get(baseDir);
// dir1Path = basePath.resolve(dir1);
// dir2Path = basePath.resolve(dir2);
// fileName = "test.txt";
// sourcePath = basePath.resolve(fileName);
// copyPath = basePath.resolve(copyDir);
// fooPath = basePath.resolve(fooDir);
// }
//
// protected void cleanUp() throws Exception {
// DirUtils.deleteIfExists(basePath);
// Files.deleteIfExists(basePath.resolve(Paths.get(copyDir, fooDir)));
// Files.deleteIfExists(basePath.resolve(Paths.get(copyDir, tempDir)));
// Files.deleteIfExists(basePath.resolve(tempDir));
// Files.deleteIfExists(basePath.resolve("tempII"));
// }
//
// protected void createDirectories() throws Exception {
// Files.createDirectories(dir1Path);
// Files.createDirectories(dir2Path);
// Files.createDirectories(copyPath);
// Files.createDirectories(fooPath);
// }
//
// protected void generateFile(Path path, int numberLines) throws Exception {
// FileGenerator.generate(path, numberLines);
// }
//
// protected void generateFiles(Path path, String[]... fileNames) throws Exception {
// for (String[] fileNamesArray : fileNames) {
// for (String fileName : fileNamesArray) {
// generateFile(path.resolve(fileName), 10);
// }
// }
// }
// }
//
// Path: src/main/java/bbejeck/nio/files/event/PathEventContext.java
// public interface PathEventContext {
//
// boolean isValid();
//
// Path getWatchedDirectory();
//
// List<PathEvent> getEvents();
//
// }
//
// Path: src/main/java/bbejeck/nio/files/event/PathEventSubscriber.java
// public interface PathEventSubscriber {
//
// void handlePathEvents(PathEventContext pathEventContext);
// }
// Path: src/test/java/bbejeck/nio/files/directory/event/DirectoryEventWatcherGuiceTest.java
import bbejeck.nio.files.BaseFileTest;
import bbejeck.nio.files.event.PathEventContext;
import bbejeck.nio.files.event.PathEventSubscriber;
import com.google.common.eventbus.EventBus;
import com.google.common.eventbus.Subscribe;
import com.google.inject.Guice;
import com.google.inject.Injector;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import java.nio.file.Path;
import java.util.*;
import java.util.concurrent.CountDownLatch;
import static org.hamcrest.CoreMatchers.is;
import static org.junit.Assert.assertThat;
package bbejeck.nio.files.directory.event;
/**
* Created by IntelliJ IDEA.
* User: bbejeck
* Date: 2/25/12
*/
public class DirectoryEventWatcherGuiceTest extends BaseFileTest {
private DirectoryEventWatcher directoryEventWatcher;
private CountDownLatch latch;
private TestSubscriber subscriber;
@Before
public void setUp() throws Exception {
createPaths();
cleanUp();
createDirectories();
latch = new CountDownLatch(3);
Injector injector = Guice.createInjector(new DirectoryEventModule());
directoryEventWatcher = injector.getInstance(DirectoryEventWatcher.class);
EventBus eventBus = injector.getInstance(EventBus.class);
subscriber = new TestSubscriber();
eventBus.register(subscriber);
directoryEventWatcher.start();
}
@Test
public void testDirectoryForWrittenEvents() throws Exception {
Map<Path, String> eventResultsMap = new HashMap<>();
assertThat(directoryEventWatcher.isRunning(), is(true));
generateFile(dir1Path.resolve("newTextFile.txt"), 10);
generateFile(basePath.resolve("newTextFileII.txt"), 10);
generateFile(dir2Path.resolve("newTextFileIII.txt"), 10);
latch.await();
assertThat(subscriber.pathEvents.size(), is(3)); | List<PathEventContext> eventContexts = subscriber.pathEvents; |
bbejeck/Java-7 | src/test/java/bbejeck/nio/files/directory/event/DirectoryEventWatcherGuiceTest.java | // Path: src/test/java/bbejeck/nio/files/BaseFileTest.java
// public class BaseFileTest {
// protected String baseDir = "test-files";
// protected String dir1 = "dir1";
// protected String dir2 = "dir2";
// protected String fileName;
// protected String fooDir = "foo";
// protected String copyDir = "copy";
// protected String tempDir = "temp";
// protected Path basePath;
// protected Path dir1Path;
// protected Path dir2Path;
// protected Path fooPath;
// protected Path sourcePath;
// protected Path copyPath;
// protected String[] fakeJavaFiles = new String[]{"Code.java", "Foo.java", "Bar.java", "Baz.java"};
// protected String[] textFileNames = new String[]{"persons.csv", "counts.csv", "CountyTaxes.csv"};
//
//
// @Before
// public void setUp() throws Exception {
// createPaths();
// cleanUp();
// createDirectories();
// generateFile(Paths.get(baseDir, fileName), 500);
// generateFiles(basePath, fakeJavaFiles, textFileNames);
// generateFiles(dir1Path, fakeJavaFiles);
// generateFiles(dir2Path, fakeJavaFiles);
// }
//
// protected void createPaths() {
// basePath = Paths.get(baseDir);
// dir1Path = basePath.resolve(dir1);
// dir2Path = basePath.resolve(dir2);
// fileName = "test.txt";
// sourcePath = basePath.resolve(fileName);
// copyPath = basePath.resolve(copyDir);
// fooPath = basePath.resolve(fooDir);
// }
//
// protected void cleanUp() throws Exception {
// DirUtils.deleteIfExists(basePath);
// Files.deleteIfExists(basePath.resolve(Paths.get(copyDir, fooDir)));
// Files.deleteIfExists(basePath.resolve(Paths.get(copyDir, tempDir)));
// Files.deleteIfExists(basePath.resolve(tempDir));
// Files.deleteIfExists(basePath.resolve("tempII"));
// }
//
// protected void createDirectories() throws Exception {
// Files.createDirectories(dir1Path);
// Files.createDirectories(dir2Path);
// Files.createDirectories(copyPath);
// Files.createDirectories(fooPath);
// }
//
// protected void generateFile(Path path, int numberLines) throws Exception {
// FileGenerator.generate(path, numberLines);
// }
//
// protected void generateFiles(Path path, String[]... fileNames) throws Exception {
// for (String[] fileNamesArray : fileNames) {
// for (String fileName : fileNamesArray) {
// generateFile(path.resolve(fileName), 10);
// }
// }
// }
// }
//
// Path: src/main/java/bbejeck/nio/files/event/PathEventContext.java
// public interface PathEventContext {
//
// boolean isValid();
//
// Path getWatchedDirectory();
//
// List<PathEvent> getEvents();
//
// }
//
// Path: src/main/java/bbejeck/nio/files/event/PathEventSubscriber.java
// public interface PathEventSubscriber {
//
// void handlePathEvents(PathEventContext pathEventContext);
// }
| import bbejeck.nio.files.BaseFileTest;
import bbejeck.nio.files.event.PathEventContext;
import bbejeck.nio.files.event.PathEventSubscriber;
import com.google.common.eventbus.EventBus;
import com.google.common.eventbus.Subscribe;
import com.google.inject.Guice;
import com.google.inject.Injector;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import java.nio.file.Path;
import java.util.*;
import java.util.concurrent.CountDownLatch;
import static org.hamcrest.CoreMatchers.is;
import static org.junit.Assert.assertThat; | latch.await();
assertThat(subscriber.pathEvents.size(), is(3));
List<PathEventContext> eventContexts = subscriber.pathEvents;
for (PathEventContext eventContext : eventContexts) {
Path dir = eventContext.getWatchedDirectory();
assertThat(eventContext.getEvents().size(), is(1));
Path target = eventContext.getEvents().get(0).getEventTarget();
eventResultsMap.put(dir, target.toString());
}
Set<Path> watchedDirs = eventResultsMap.keySet();
assertThat(watchedDirs.size(), is(3));
assertThat(watchedDirs.contains(dir1Path), is(true));
assertThat(watchedDirs.contains(basePath), is(true));
assertThat(watchedDirs.contains(dir2Path), is(true));
assertThat(eventResultsMap.get(dir1Path), is("newTextFile.txt"));
assertThat(eventResultsMap.get(basePath), is("newTextFileII.txt"));
assertThat(eventResultsMap.get(dir2Path), is("newTextFileIII.txt"));
}
@After
public void tearDown() {
directoryEventWatcher.stop();
}
| // Path: src/test/java/bbejeck/nio/files/BaseFileTest.java
// public class BaseFileTest {
// protected String baseDir = "test-files";
// protected String dir1 = "dir1";
// protected String dir2 = "dir2";
// protected String fileName;
// protected String fooDir = "foo";
// protected String copyDir = "copy";
// protected String tempDir = "temp";
// protected Path basePath;
// protected Path dir1Path;
// protected Path dir2Path;
// protected Path fooPath;
// protected Path sourcePath;
// protected Path copyPath;
// protected String[] fakeJavaFiles = new String[]{"Code.java", "Foo.java", "Bar.java", "Baz.java"};
// protected String[] textFileNames = new String[]{"persons.csv", "counts.csv", "CountyTaxes.csv"};
//
//
// @Before
// public void setUp() throws Exception {
// createPaths();
// cleanUp();
// createDirectories();
// generateFile(Paths.get(baseDir, fileName), 500);
// generateFiles(basePath, fakeJavaFiles, textFileNames);
// generateFiles(dir1Path, fakeJavaFiles);
// generateFiles(dir2Path, fakeJavaFiles);
// }
//
// protected void createPaths() {
// basePath = Paths.get(baseDir);
// dir1Path = basePath.resolve(dir1);
// dir2Path = basePath.resolve(dir2);
// fileName = "test.txt";
// sourcePath = basePath.resolve(fileName);
// copyPath = basePath.resolve(copyDir);
// fooPath = basePath.resolve(fooDir);
// }
//
// protected void cleanUp() throws Exception {
// DirUtils.deleteIfExists(basePath);
// Files.deleteIfExists(basePath.resolve(Paths.get(copyDir, fooDir)));
// Files.deleteIfExists(basePath.resolve(Paths.get(copyDir, tempDir)));
// Files.deleteIfExists(basePath.resolve(tempDir));
// Files.deleteIfExists(basePath.resolve("tempII"));
// }
//
// protected void createDirectories() throws Exception {
// Files.createDirectories(dir1Path);
// Files.createDirectories(dir2Path);
// Files.createDirectories(copyPath);
// Files.createDirectories(fooPath);
// }
//
// protected void generateFile(Path path, int numberLines) throws Exception {
// FileGenerator.generate(path, numberLines);
// }
//
// protected void generateFiles(Path path, String[]... fileNames) throws Exception {
// for (String[] fileNamesArray : fileNames) {
// for (String fileName : fileNamesArray) {
// generateFile(path.resolve(fileName), 10);
// }
// }
// }
// }
//
// Path: src/main/java/bbejeck/nio/files/event/PathEventContext.java
// public interface PathEventContext {
//
// boolean isValid();
//
// Path getWatchedDirectory();
//
// List<PathEvent> getEvents();
//
// }
//
// Path: src/main/java/bbejeck/nio/files/event/PathEventSubscriber.java
// public interface PathEventSubscriber {
//
// void handlePathEvents(PathEventContext pathEventContext);
// }
// Path: src/test/java/bbejeck/nio/files/directory/event/DirectoryEventWatcherGuiceTest.java
import bbejeck.nio.files.BaseFileTest;
import bbejeck.nio.files.event.PathEventContext;
import bbejeck.nio.files.event.PathEventSubscriber;
import com.google.common.eventbus.EventBus;
import com.google.common.eventbus.Subscribe;
import com.google.inject.Guice;
import com.google.inject.Injector;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import java.nio.file.Path;
import java.util.*;
import java.util.concurrent.CountDownLatch;
import static org.hamcrest.CoreMatchers.is;
import static org.junit.Assert.assertThat;
latch.await();
assertThat(subscriber.pathEvents.size(), is(3));
List<PathEventContext> eventContexts = subscriber.pathEvents;
for (PathEventContext eventContext : eventContexts) {
Path dir = eventContext.getWatchedDirectory();
assertThat(eventContext.getEvents().size(), is(1));
Path target = eventContext.getEvents().get(0).getEventTarget();
eventResultsMap.put(dir, target.toString());
}
Set<Path> watchedDirs = eventResultsMap.keySet();
assertThat(watchedDirs.size(), is(3));
assertThat(watchedDirs.contains(dir1Path), is(true));
assertThat(watchedDirs.contains(basePath), is(true));
assertThat(watchedDirs.contains(dir2Path), is(true));
assertThat(eventResultsMap.get(dir1Path), is("newTextFile.txt"));
assertThat(eventResultsMap.get(basePath), is("newTextFileII.txt"));
assertThat(eventResultsMap.get(dir2Path), is("newTextFileIII.txt"));
}
@After
public void tearDown() {
directoryEventWatcher.stop();
}
| private class TestSubscriber implements PathEventSubscriber { |
bbejeck/Java-7 | src/main/java/bbejeck/nio/files/event/PathEventContext.java | // Path: src/main/java/bbejeck/nio/files/directory/event/PathEvent.java
// public class PathEvent {
// private final Path eventTarget;
// private final WatchEvent.Kind type;
//
// PathEvent(Path eventTarget, WatchEvent.Kind type) {
// this.eventTarget = eventTarget;
// this.type = type;
// }
//
// public Path getEventTarget() {
// return eventTarget;
// }
//
// public WatchEvent.Kind getType() {
// return type;
// }
// }
| import bbejeck.nio.files.directory.event.PathEvent;
import java.nio.file.Path;
import java.util.List; | package bbejeck.nio.files.event;
/**
* Created by IntelliJ IDEA.
* User: bbejeck
* Date: 2/20/12
* Time: 10:00 PM
*/
public interface PathEventContext {
boolean isValid();
Path getWatchedDirectory();
| // Path: src/main/java/bbejeck/nio/files/directory/event/PathEvent.java
// public class PathEvent {
// private final Path eventTarget;
// private final WatchEvent.Kind type;
//
// PathEvent(Path eventTarget, WatchEvent.Kind type) {
// this.eventTarget = eventTarget;
// this.type = type;
// }
//
// public Path getEventTarget() {
// return eventTarget;
// }
//
// public WatchEvent.Kind getType() {
// return type;
// }
// }
// Path: src/main/java/bbejeck/nio/files/event/PathEventContext.java
import bbejeck.nio.files.directory.event.PathEvent;
import java.nio.file.Path;
import java.util.List;
package bbejeck.nio.files.event;
/**
* Created by IntelliJ IDEA.
* User: bbejeck
* Date: 2/20/12
* Time: 10:00 PM
*/
public interface PathEventContext {
boolean isValid();
Path getWatchedDirectory();
| List<PathEvent> getEvents(); |
bbejeck/Java-7 | src/test/java/bbejeck/nio/channels/AsyncSocketServerComparisonTest.java | // Path: src/main/java/bbejeck/nio/sockets/PlainServerSocket.java
// public class PlainServerSocket {
//
// private ExecutorService executorService;
// private java.net.ServerSocket server;
// private int port;
// private String host;
//
//
// @Inject
// public PlainServerSocket(@Port int port, @Host String host) {
// this.port = port;
// this.host = host;
// }
//
//
// public void startServer() {
// try {
// initServerSocket();
// this.executorService = Executors.newCachedThreadPool();
// while (!executorService.isShutdown()) {
// Socket socket = server.accept();
// executorService.submit(handleSocketRequest(socket));
// }
// } catch (Exception e) {
// if (!executorService.isShutdown()) {
// e.printStackTrace();
// }
// }
// }
//
// private Callable<Void> handleSocketRequest(final Socket socket) {
// return new Callable<Void>() {
// @Override
// public Void call() throws Exception {
// BufferedReader reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
// CharBuffer charBuffer = CharBuffer.allocate(1000);
// reader.read(charBuffer);
// charBuffer.flip();
// StringBuilder builder = new StringBuilder("You Said >> \"");
// String message = charBuffer.toString();
// // System.out.println("Plain Socket Message[" + message + "] received @" + new Date());
// builder.append(message).append("\"");
// BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
// bufferedWriter.write(builder.toString());
// bufferedWriter.flush();
// if (message.equalsIgnoreCase("quit")) {
// stopServer();
// }
// reader.close();
// bufferedWriter.close();
// socket.close();
// return null;
// }
// };
// }
//
// public void stopServer() throws Exception {
// executorService.shutdownNow();
// server.close();
// }
//
//
// private void initServerSocket() throws Exception {
// server = new ServerSocket(port);
// }
//
// }
//
// Path: src/main/java/bbejeck/nio/sockets/PlainSocketMessageSender.java
// public class PlainSocketMessageSender {
//
// private Socket socket;
// private int port;
// private InetSocketAddress socketAddress;
// private int messageCount;
//
// @Inject
// public PlainSocketMessageSender(@Port int port, @MessageCount int messageCount, @Host String host) {
// this.port = port;
// socketAddress = new InetSocketAddress(host, port);
// this.messageCount = messageCount;
// }
//
// public void sendMessages() throws Exception {
// for (int i = 0; i < messageCount; i++) {
// sendTextMessage("Plain text message from socket");
// }
// sendTextMessage("quit");
// }
//
// private void sendTextMessage(String message) throws Exception {
// socket = new Socket();
// socket.connect(socketAddress);
// BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
// bufferedWriter.write(message);
// bufferedWriter.flush();
// BufferedReader reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
// CharBuffer charBuffer = CharBuffer.allocate(1000);
// reader.read(charBuffer);
// charBuffer.flip();
// // System.out.println("Reply from server "+charBuffer.toString());
// reader.close();
// bufferedWriter.close();
// socket.close();
// }
// }
| import bbejeck.nio.sockets.PlainServerSocket;
import bbejeck.nio.sockets.PlainSocketMessageSender;
import com.google.common.base.Stopwatch;
import org.junit.Ignore;
import org.junit.Test;
import java.util.concurrent.Callable;
import java.util.concurrent.FutureTask;
import java.util.concurrent.TimeUnit; | package bbejeck.nio.channels;
/**
* Created by IntelliJ IDEA.
* User: bbejeck
* Date: 3/15/12
* Time: 11:27 PM
*/
@Ignore
public class AsyncSocketServerComparisonTest {
@Test
public void testAsyncSocketServer() throws Exception { | // Path: src/main/java/bbejeck/nio/sockets/PlainServerSocket.java
// public class PlainServerSocket {
//
// private ExecutorService executorService;
// private java.net.ServerSocket server;
// private int port;
// private String host;
//
//
// @Inject
// public PlainServerSocket(@Port int port, @Host String host) {
// this.port = port;
// this.host = host;
// }
//
//
// public void startServer() {
// try {
// initServerSocket();
// this.executorService = Executors.newCachedThreadPool();
// while (!executorService.isShutdown()) {
// Socket socket = server.accept();
// executorService.submit(handleSocketRequest(socket));
// }
// } catch (Exception e) {
// if (!executorService.isShutdown()) {
// e.printStackTrace();
// }
// }
// }
//
// private Callable<Void> handleSocketRequest(final Socket socket) {
// return new Callable<Void>() {
// @Override
// public Void call() throws Exception {
// BufferedReader reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
// CharBuffer charBuffer = CharBuffer.allocate(1000);
// reader.read(charBuffer);
// charBuffer.flip();
// StringBuilder builder = new StringBuilder("You Said >> \"");
// String message = charBuffer.toString();
// // System.out.println("Plain Socket Message[" + message + "] received @" + new Date());
// builder.append(message).append("\"");
// BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
// bufferedWriter.write(builder.toString());
// bufferedWriter.flush();
// if (message.equalsIgnoreCase("quit")) {
// stopServer();
// }
// reader.close();
// bufferedWriter.close();
// socket.close();
// return null;
// }
// };
// }
//
// public void stopServer() throws Exception {
// executorService.shutdownNow();
// server.close();
// }
//
//
// private void initServerSocket() throws Exception {
// server = new ServerSocket(port);
// }
//
// }
//
// Path: src/main/java/bbejeck/nio/sockets/PlainSocketMessageSender.java
// public class PlainSocketMessageSender {
//
// private Socket socket;
// private int port;
// private InetSocketAddress socketAddress;
// private int messageCount;
//
// @Inject
// public PlainSocketMessageSender(@Port int port, @MessageCount int messageCount, @Host String host) {
// this.port = port;
// socketAddress = new InetSocketAddress(host, port);
// this.messageCount = messageCount;
// }
//
// public void sendMessages() throws Exception {
// for (int i = 0; i < messageCount; i++) {
// sendTextMessage("Plain text message from socket");
// }
// sendTextMessage("quit");
// }
//
// private void sendTextMessage(String message) throws Exception {
// socket = new Socket();
// socket.connect(socketAddress);
// BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
// bufferedWriter.write(message);
// bufferedWriter.flush();
// BufferedReader reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
// CharBuffer charBuffer = CharBuffer.allocate(1000);
// reader.read(charBuffer);
// charBuffer.flip();
// // System.out.println("Reply from server "+charBuffer.toString());
// reader.close();
// bufferedWriter.close();
// socket.close();
// }
// }
// Path: src/test/java/bbejeck/nio/channels/AsyncSocketServerComparisonTest.java
import bbejeck.nio.sockets.PlainServerSocket;
import bbejeck.nio.sockets.PlainSocketMessageSender;
import com.google.common.base.Stopwatch;
import org.junit.Ignore;
import org.junit.Test;
import java.util.concurrent.Callable;
import java.util.concurrent.FutureTask;
import java.util.concurrent.TimeUnit;
package bbejeck.nio.channels;
/**
* Created by IntelliJ IDEA.
* User: bbejeck
* Date: 3/15/12
* Time: 11:27 PM
*/
@Ignore
public class AsyncSocketServerComparisonTest {
@Test
public void testAsyncSocketServer() throws Exception { | PlainSocketMessageSender messageSender = new PlainSocketMessageSender(5000,10000,"localhost"); |
bbejeck/Java-7 | src/test/java/bbejeck/nio/channels/AsyncSocketServerComparisonTest.java | // Path: src/main/java/bbejeck/nio/sockets/PlainServerSocket.java
// public class PlainServerSocket {
//
// private ExecutorService executorService;
// private java.net.ServerSocket server;
// private int port;
// private String host;
//
//
// @Inject
// public PlainServerSocket(@Port int port, @Host String host) {
// this.port = port;
// this.host = host;
// }
//
//
// public void startServer() {
// try {
// initServerSocket();
// this.executorService = Executors.newCachedThreadPool();
// while (!executorService.isShutdown()) {
// Socket socket = server.accept();
// executorService.submit(handleSocketRequest(socket));
// }
// } catch (Exception e) {
// if (!executorService.isShutdown()) {
// e.printStackTrace();
// }
// }
// }
//
// private Callable<Void> handleSocketRequest(final Socket socket) {
// return new Callable<Void>() {
// @Override
// public Void call() throws Exception {
// BufferedReader reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
// CharBuffer charBuffer = CharBuffer.allocate(1000);
// reader.read(charBuffer);
// charBuffer.flip();
// StringBuilder builder = new StringBuilder("You Said >> \"");
// String message = charBuffer.toString();
// // System.out.println("Plain Socket Message[" + message + "] received @" + new Date());
// builder.append(message).append("\"");
// BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
// bufferedWriter.write(builder.toString());
// bufferedWriter.flush();
// if (message.equalsIgnoreCase("quit")) {
// stopServer();
// }
// reader.close();
// bufferedWriter.close();
// socket.close();
// return null;
// }
// };
// }
//
// public void stopServer() throws Exception {
// executorService.shutdownNow();
// server.close();
// }
//
//
// private void initServerSocket() throws Exception {
// server = new ServerSocket(port);
// }
//
// }
//
// Path: src/main/java/bbejeck/nio/sockets/PlainSocketMessageSender.java
// public class PlainSocketMessageSender {
//
// private Socket socket;
// private int port;
// private InetSocketAddress socketAddress;
// private int messageCount;
//
// @Inject
// public PlainSocketMessageSender(@Port int port, @MessageCount int messageCount, @Host String host) {
// this.port = port;
// socketAddress = new InetSocketAddress(host, port);
// this.messageCount = messageCount;
// }
//
// public void sendMessages() throws Exception {
// for (int i = 0; i < messageCount; i++) {
// sendTextMessage("Plain text message from socket");
// }
// sendTextMessage("quit");
// }
//
// private void sendTextMessage(String message) throws Exception {
// socket = new Socket();
// socket.connect(socketAddress);
// BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
// bufferedWriter.write(message);
// bufferedWriter.flush();
// BufferedReader reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
// CharBuffer charBuffer = CharBuffer.allocate(1000);
// reader.read(charBuffer);
// charBuffer.flip();
// // System.out.println("Reply from server "+charBuffer.toString());
// reader.close();
// bufferedWriter.close();
// socket.close();
// }
// }
| import bbejeck.nio.sockets.PlainServerSocket;
import bbejeck.nio.sockets.PlainSocketMessageSender;
import com.google.common.base.Stopwatch;
import org.junit.Ignore;
import org.junit.Test;
import java.util.concurrent.Callable;
import java.util.concurrent.FutureTask;
import java.util.concurrent.TimeUnit; | package bbejeck.nio.channels;
/**
* Created by IntelliJ IDEA.
* User: bbejeck
* Date: 3/15/12
* Time: 11:27 PM
*/
@Ignore
public class AsyncSocketServerComparisonTest {
@Test
public void testAsyncSocketServer() throws Exception {
PlainSocketMessageSender messageSender = new PlainSocketMessageSender(5000,10000,"localhost");
final AsyncServerSocket serverSocket = new AsyncServerSocket(5000,"localhost");
FutureTask<Long> asyncFutureTask = new FutureTask<>(new Callable<Long>() {
@Override
public Long call() throws Exception {
Stopwatch stopwatch = new Stopwatch();
stopwatch.start();
serverSocket.startServer();
stopwatch.stop();
return stopwatch.elapsedTime(TimeUnit.SECONDS);
}
});
System.out.println("Starting the AsyncSocketServer Test");
new Thread(asyncFutureTask).start();
Thread.sleep(1000);
messageSender.sendMessages();
Long time = asyncFutureTask.get();
System.out.println("AsyncServer processed [10000] messages in " + time+" seconds");
}
@Test
@Ignore
public void testPlainSocketServer() throws Exception {
PlainSocketMessageSender messageSender = new PlainSocketMessageSender(5001,10000,"localhost"); | // Path: src/main/java/bbejeck/nio/sockets/PlainServerSocket.java
// public class PlainServerSocket {
//
// private ExecutorService executorService;
// private java.net.ServerSocket server;
// private int port;
// private String host;
//
//
// @Inject
// public PlainServerSocket(@Port int port, @Host String host) {
// this.port = port;
// this.host = host;
// }
//
//
// public void startServer() {
// try {
// initServerSocket();
// this.executorService = Executors.newCachedThreadPool();
// while (!executorService.isShutdown()) {
// Socket socket = server.accept();
// executorService.submit(handleSocketRequest(socket));
// }
// } catch (Exception e) {
// if (!executorService.isShutdown()) {
// e.printStackTrace();
// }
// }
// }
//
// private Callable<Void> handleSocketRequest(final Socket socket) {
// return new Callable<Void>() {
// @Override
// public Void call() throws Exception {
// BufferedReader reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
// CharBuffer charBuffer = CharBuffer.allocate(1000);
// reader.read(charBuffer);
// charBuffer.flip();
// StringBuilder builder = new StringBuilder("You Said >> \"");
// String message = charBuffer.toString();
// // System.out.println("Plain Socket Message[" + message + "] received @" + new Date());
// builder.append(message).append("\"");
// BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
// bufferedWriter.write(builder.toString());
// bufferedWriter.flush();
// if (message.equalsIgnoreCase("quit")) {
// stopServer();
// }
// reader.close();
// bufferedWriter.close();
// socket.close();
// return null;
// }
// };
// }
//
// public void stopServer() throws Exception {
// executorService.shutdownNow();
// server.close();
// }
//
//
// private void initServerSocket() throws Exception {
// server = new ServerSocket(port);
// }
//
// }
//
// Path: src/main/java/bbejeck/nio/sockets/PlainSocketMessageSender.java
// public class PlainSocketMessageSender {
//
// private Socket socket;
// private int port;
// private InetSocketAddress socketAddress;
// private int messageCount;
//
// @Inject
// public PlainSocketMessageSender(@Port int port, @MessageCount int messageCount, @Host String host) {
// this.port = port;
// socketAddress = new InetSocketAddress(host, port);
// this.messageCount = messageCount;
// }
//
// public void sendMessages() throws Exception {
// for (int i = 0; i < messageCount; i++) {
// sendTextMessage("Plain text message from socket");
// }
// sendTextMessage("quit");
// }
//
// private void sendTextMessage(String message) throws Exception {
// socket = new Socket();
// socket.connect(socketAddress);
// BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
// bufferedWriter.write(message);
// bufferedWriter.flush();
// BufferedReader reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
// CharBuffer charBuffer = CharBuffer.allocate(1000);
// reader.read(charBuffer);
// charBuffer.flip();
// // System.out.println("Reply from server "+charBuffer.toString());
// reader.close();
// bufferedWriter.close();
// socket.close();
// }
// }
// Path: src/test/java/bbejeck/nio/channels/AsyncSocketServerComparisonTest.java
import bbejeck.nio.sockets.PlainServerSocket;
import bbejeck.nio.sockets.PlainSocketMessageSender;
import com.google.common.base.Stopwatch;
import org.junit.Ignore;
import org.junit.Test;
import java.util.concurrent.Callable;
import java.util.concurrent.FutureTask;
import java.util.concurrent.TimeUnit;
package bbejeck.nio.channels;
/**
* Created by IntelliJ IDEA.
* User: bbejeck
* Date: 3/15/12
* Time: 11:27 PM
*/
@Ignore
public class AsyncSocketServerComparisonTest {
@Test
public void testAsyncSocketServer() throws Exception {
PlainSocketMessageSender messageSender = new PlainSocketMessageSender(5000,10000,"localhost");
final AsyncServerSocket serverSocket = new AsyncServerSocket(5000,"localhost");
FutureTask<Long> asyncFutureTask = new FutureTask<>(new Callable<Long>() {
@Override
public Long call() throws Exception {
Stopwatch stopwatch = new Stopwatch();
stopwatch.start();
serverSocket.startServer();
stopwatch.stop();
return stopwatch.elapsedTime(TimeUnit.SECONDS);
}
});
System.out.println("Starting the AsyncSocketServer Test");
new Thread(asyncFutureTask).start();
Thread.sleep(1000);
messageSender.sendMessages();
Long time = asyncFutureTask.get();
System.out.println("AsyncServer processed [10000] messages in " + time+" seconds");
}
@Test
@Ignore
public void testPlainSocketServer() throws Exception {
PlainSocketMessageSender messageSender = new PlainSocketMessageSender(5001,10000,"localhost"); | final PlainServerSocket serverSocket = new PlainServerSocket(5001,"localhost"); |
bbejeck/Java-7 | src/main/java/bbejeck/nio/PlainSocketTestDriver.java | // Path: src/main/java/bbejeck/nio/channels/AsyncServerTestModule.java
// public class AsyncServerTestModule extends AbstractModule {
//
// @Override
// protected void configure() {
// bind(AsyncServerSocket.class);
// }
// }
//
// Path: src/main/java/bbejeck/nio/sockets/PlainServerSocket.java
// public class PlainServerSocket {
//
// private ExecutorService executorService;
// private java.net.ServerSocket server;
// private int port;
// private String host;
//
//
// @Inject
// public PlainServerSocket(@Port int port, @Host String host) {
// this.port = port;
// this.host = host;
// }
//
//
// public void startServer() {
// try {
// initServerSocket();
// this.executorService = Executors.newCachedThreadPool();
// while (!executorService.isShutdown()) {
// Socket socket = server.accept();
// executorService.submit(handleSocketRequest(socket));
// }
// } catch (Exception e) {
// if (!executorService.isShutdown()) {
// e.printStackTrace();
// }
// }
// }
//
// private Callable<Void> handleSocketRequest(final Socket socket) {
// return new Callable<Void>() {
// @Override
// public Void call() throws Exception {
// BufferedReader reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
// CharBuffer charBuffer = CharBuffer.allocate(1000);
// reader.read(charBuffer);
// charBuffer.flip();
// StringBuilder builder = new StringBuilder("You Said >> \"");
// String message = charBuffer.toString();
// // System.out.println("Plain Socket Message[" + message + "] received @" + new Date());
// builder.append(message).append("\"");
// BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
// bufferedWriter.write(builder.toString());
// bufferedWriter.flush();
// if (message.equalsIgnoreCase("quit")) {
// stopServer();
// }
// reader.close();
// bufferedWriter.close();
// socket.close();
// return null;
// }
// };
// }
//
// public void stopServer() throws Exception {
// executorService.shutdownNow();
// server.close();
// }
//
//
// private void initServerSocket() throws Exception {
// server = new ServerSocket(port);
// }
//
// }
//
// Path: src/main/java/bbejeck/nio/sockets/PlainSocketMessageSender.java
// public class PlainSocketMessageSender {
//
// private Socket socket;
// private int port;
// private InetSocketAddress socketAddress;
// private int messageCount;
//
// @Inject
// public PlainSocketMessageSender(@Port int port, @MessageCount int messageCount, @Host String host) {
// this.port = port;
// socketAddress = new InetSocketAddress(host, port);
// this.messageCount = messageCount;
// }
//
// public void sendMessages() throws Exception {
// for (int i = 0; i < messageCount; i++) {
// sendTextMessage("Plain text message from socket");
// }
// sendTextMessage("quit");
// }
//
// private void sendTextMessage(String message) throws Exception {
// socket = new Socket();
// socket.connect(socketAddress);
// BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
// bufferedWriter.write(message);
// bufferedWriter.flush();
// BufferedReader reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
// CharBuffer charBuffer = CharBuffer.allocate(1000);
// reader.read(charBuffer);
// charBuffer.flip();
// // System.out.println("Reply from server "+charBuffer.toString());
// reader.close();
// bufferedWriter.close();
// socket.close();
// }
// }
//
// Path: src/main/java/bbejeck/nio/sockets/PlainSocketModule.java
// public class PlainSocketModule extends AbstractModule {
//
// @Override
// protected void configure() {
// bind(PlainServerSocket.class);
// bind(PlainSocketMessageSender.class);
// }
// }
| import bbejeck.nio.channels.AsyncServerTestModule;
import bbejeck.nio.sockets.PlainServerSocket;
import bbejeck.nio.sockets.PlainSocketMessageSender;
import bbejeck.nio.sockets.PlainSocketModule;
import com.google.common.base.Stopwatch;
import com.google.inject.Guice;
import com.google.inject.Injector;
import java.util.concurrent.Callable;
import java.util.concurrent.FutureTask; | package bbejeck.nio;
/**
* Created by IntelliJ IDEA.
* User: bbejeck
* Date: 3/14/12
* Time: 9:48 PM
*/
public class PlainSocketTestDriver {
public static void main(String[] args) throws Exception { | // Path: src/main/java/bbejeck/nio/channels/AsyncServerTestModule.java
// public class AsyncServerTestModule extends AbstractModule {
//
// @Override
// protected void configure() {
// bind(AsyncServerSocket.class);
// }
// }
//
// Path: src/main/java/bbejeck/nio/sockets/PlainServerSocket.java
// public class PlainServerSocket {
//
// private ExecutorService executorService;
// private java.net.ServerSocket server;
// private int port;
// private String host;
//
//
// @Inject
// public PlainServerSocket(@Port int port, @Host String host) {
// this.port = port;
// this.host = host;
// }
//
//
// public void startServer() {
// try {
// initServerSocket();
// this.executorService = Executors.newCachedThreadPool();
// while (!executorService.isShutdown()) {
// Socket socket = server.accept();
// executorService.submit(handleSocketRequest(socket));
// }
// } catch (Exception e) {
// if (!executorService.isShutdown()) {
// e.printStackTrace();
// }
// }
// }
//
// private Callable<Void> handleSocketRequest(final Socket socket) {
// return new Callable<Void>() {
// @Override
// public Void call() throws Exception {
// BufferedReader reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
// CharBuffer charBuffer = CharBuffer.allocate(1000);
// reader.read(charBuffer);
// charBuffer.flip();
// StringBuilder builder = new StringBuilder("You Said >> \"");
// String message = charBuffer.toString();
// // System.out.println("Plain Socket Message[" + message + "] received @" + new Date());
// builder.append(message).append("\"");
// BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
// bufferedWriter.write(builder.toString());
// bufferedWriter.flush();
// if (message.equalsIgnoreCase("quit")) {
// stopServer();
// }
// reader.close();
// bufferedWriter.close();
// socket.close();
// return null;
// }
// };
// }
//
// public void stopServer() throws Exception {
// executorService.shutdownNow();
// server.close();
// }
//
//
// private void initServerSocket() throws Exception {
// server = new ServerSocket(port);
// }
//
// }
//
// Path: src/main/java/bbejeck/nio/sockets/PlainSocketMessageSender.java
// public class PlainSocketMessageSender {
//
// private Socket socket;
// private int port;
// private InetSocketAddress socketAddress;
// private int messageCount;
//
// @Inject
// public PlainSocketMessageSender(@Port int port, @MessageCount int messageCount, @Host String host) {
// this.port = port;
// socketAddress = new InetSocketAddress(host, port);
// this.messageCount = messageCount;
// }
//
// public void sendMessages() throws Exception {
// for (int i = 0; i < messageCount; i++) {
// sendTextMessage("Plain text message from socket");
// }
// sendTextMessage("quit");
// }
//
// private void sendTextMessage(String message) throws Exception {
// socket = new Socket();
// socket.connect(socketAddress);
// BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
// bufferedWriter.write(message);
// bufferedWriter.flush();
// BufferedReader reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
// CharBuffer charBuffer = CharBuffer.allocate(1000);
// reader.read(charBuffer);
// charBuffer.flip();
// // System.out.println("Reply from server "+charBuffer.toString());
// reader.close();
// bufferedWriter.close();
// socket.close();
// }
// }
//
// Path: src/main/java/bbejeck/nio/sockets/PlainSocketModule.java
// public class PlainSocketModule extends AbstractModule {
//
// @Override
// protected void configure() {
// bind(PlainServerSocket.class);
// bind(PlainSocketMessageSender.class);
// }
// }
// Path: src/main/java/bbejeck/nio/PlainSocketTestDriver.java
import bbejeck.nio.channels.AsyncServerTestModule;
import bbejeck.nio.sockets.PlainServerSocket;
import bbejeck.nio.sockets.PlainSocketMessageSender;
import bbejeck.nio.sockets.PlainSocketModule;
import com.google.common.base.Stopwatch;
import com.google.inject.Guice;
import com.google.inject.Injector;
import java.util.concurrent.Callable;
import java.util.concurrent.FutureTask;
package bbejeck.nio;
/**
* Created by IntelliJ IDEA.
* User: bbejeck
* Date: 3/14/12
* Time: 9:48 PM
*/
public class PlainSocketTestDriver {
public static void main(String[] args) throws Exception { | Injector injector = Guice.createInjector(new SocketModule(), new PlainSocketModule(), new AsyncServerTestModule()); |
bbejeck/Java-7 | src/main/java/bbejeck/nio/PlainSocketTestDriver.java | // Path: src/main/java/bbejeck/nio/channels/AsyncServerTestModule.java
// public class AsyncServerTestModule extends AbstractModule {
//
// @Override
// protected void configure() {
// bind(AsyncServerSocket.class);
// }
// }
//
// Path: src/main/java/bbejeck/nio/sockets/PlainServerSocket.java
// public class PlainServerSocket {
//
// private ExecutorService executorService;
// private java.net.ServerSocket server;
// private int port;
// private String host;
//
//
// @Inject
// public PlainServerSocket(@Port int port, @Host String host) {
// this.port = port;
// this.host = host;
// }
//
//
// public void startServer() {
// try {
// initServerSocket();
// this.executorService = Executors.newCachedThreadPool();
// while (!executorService.isShutdown()) {
// Socket socket = server.accept();
// executorService.submit(handleSocketRequest(socket));
// }
// } catch (Exception e) {
// if (!executorService.isShutdown()) {
// e.printStackTrace();
// }
// }
// }
//
// private Callable<Void> handleSocketRequest(final Socket socket) {
// return new Callable<Void>() {
// @Override
// public Void call() throws Exception {
// BufferedReader reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
// CharBuffer charBuffer = CharBuffer.allocate(1000);
// reader.read(charBuffer);
// charBuffer.flip();
// StringBuilder builder = new StringBuilder("You Said >> \"");
// String message = charBuffer.toString();
// // System.out.println("Plain Socket Message[" + message + "] received @" + new Date());
// builder.append(message).append("\"");
// BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
// bufferedWriter.write(builder.toString());
// bufferedWriter.flush();
// if (message.equalsIgnoreCase("quit")) {
// stopServer();
// }
// reader.close();
// bufferedWriter.close();
// socket.close();
// return null;
// }
// };
// }
//
// public void stopServer() throws Exception {
// executorService.shutdownNow();
// server.close();
// }
//
//
// private void initServerSocket() throws Exception {
// server = new ServerSocket(port);
// }
//
// }
//
// Path: src/main/java/bbejeck/nio/sockets/PlainSocketMessageSender.java
// public class PlainSocketMessageSender {
//
// private Socket socket;
// private int port;
// private InetSocketAddress socketAddress;
// private int messageCount;
//
// @Inject
// public PlainSocketMessageSender(@Port int port, @MessageCount int messageCount, @Host String host) {
// this.port = port;
// socketAddress = new InetSocketAddress(host, port);
// this.messageCount = messageCount;
// }
//
// public void sendMessages() throws Exception {
// for (int i = 0; i < messageCount; i++) {
// sendTextMessage("Plain text message from socket");
// }
// sendTextMessage("quit");
// }
//
// private void sendTextMessage(String message) throws Exception {
// socket = new Socket();
// socket.connect(socketAddress);
// BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
// bufferedWriter.write(message);
// bufferedWriter.flush();
// BufferedReader reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
// CharBuffer charBuffer = CharBuffer.allocate(1000);
// reader.read(charBuffer);
// charBuffer.flip();
// // System.out.println("Reply from server "+charBuffer.toString());
// reader.close();
// bufferedWriter.close();
// socket.close();
// }
// }
//
// Path: src/main/java/bbejeck/nio/sockets/PlainSocketModule.java
// public class PlainSocketModule extends AbstractModule {
//
// @Override
// protected void configure() {
// bind(PlainServerSocket.class);
// bind(PlainSocketMessageSender.class);
// }
// }
| import bbejeck.nio.channels.AsyncServerTestModule;
import bbejeck.nio.sockets.PlainServerSocket;
import bbejeck.nio.sockets.PlainSocketMessageSender;
import bbejeck.nio.sockets.PlainSocketModule;
import com.google.common.base.Stopwatch;
import com.google.inject.Guice;
import com.google.inject.Injector;
import java.util.concurrent.Callable;
import java.util.concurrent.FutureTask; | package bbejeck.nio;
/**
* Created by IntelliJ IDEA.
* User: bbejeck
* Date: 3/14/12
* Time: 9:48 PM
*/
public class PlainSocketTestDriver {
public static void main(String[] args) throws Exception { | // Path: src/main/java/bbejeck/nio/channels/AsyncServerTestModule.java
// public class AsyncServerTestModule extends AbstractModule {
//
// @Override
// protected void configure() {
// bind(AsyncServerSocket.class);
// }
// }
//
// Path: src/main/java/bbejeck/nio/sockets/PlainServerSocket.java
// public class PlainServerSocket {
//
// private ExecutorService executorService;
// private java.net.ServerSocket server;
// private int port;
// private String host;
//
//
// @Inject
// public PlainServerSocket(@Port int port, @Host String host) {
// this.port = port;
// this.host = host;
// }
//
//
// public void startServer() {
// try {
// initServerSocket();
// this.executorService = Executors.newCachedThreadPool();
// while (!executorService.isShutdown()) {
// Socket socket = server.accept();
// executorService.submit(handleSocketRequest(socket));
// }
// } catch (Exception e) {
// if (!executorService.isShutdown()) {
// e.printStackTrace();
// }
// }
// }
//
// private Callable<Void> handleSocketRequest(final Socket socket) {
// return new Callable<Void>() {
// @Override
// public Void call() throws Exception {
// BufferedReader reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
// CharBuffer charBuffer = CharBuffer.allocate(1000);
// reader.read(charBuffer);
// charBuffer.flip();
// StringBuilder builder = new StringBuilder("You Said >> \"");
// String message = charBuffer.toString();
// // System.out.println("Plain Socket Message[" + message + "] received @" + new Date());
// builder.append(message).append("\"");
// BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
// bufferedWriter.write(builder.toString());
// bufferedWriter.flush();
// if (message.equalsIgnoreCase("quit")) {
// stopServer();
// }
// reader.close();
// bufferedWriter.close();
// socket.close();
// return null;
// }
// };
// }
//
// public void stopServer() throws Exception {
// executorService.shutdownNow();
// server.close();
// }
//
//
// private void initServerSocket() throws Exception {
// server = new ServerSocket(port);
// }
//
// }
//
// Path: src/main/java/bbejeck/nio/sockets/PlainSocketMessageSender.java
// public class PlainSocketMessageSender {
//
// private Socket socket;
// private int port;
// private InetSocketAddress socketAddress;
// private int messageCount;
//
// @Inject
// public PlainSocketMessageSender(@Port int port, @MessageCount int messageCount, @Host String host) {
// this.port = port;
// socketAddress = new InetSocketAddress(host, port);
// this.messageCount = messageCount;
// }
//
// public void sendMessages() throws Exception {
// for (int i = 0; i < messageCount; i++) {
// sendTextMessage("Plain text message from socket");
// }
// sendTextMessage("quit");
// }
//
// private void sendTextMessage(String message) throws Exception {
// socket = new Socket();
// socket.connect(socketAddress);
// BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
// bufferedWriter.write(message);
// bufferedWriter.flush();
// BufferedReader reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
// CharBuffer charBuffer = CharBuffer.allocate(1000);
// reader.read(charBuffer);
// charBuffer.flip();
// // System.out.println("Reply from server "+charBuffer.toString());
// reader.close();
// bufferedWriter.close();
// socket.close();
// }
// }
//
// Path: src/main/java/bbejeck/nio/sockets/PlainSocketModule.java
// public class PlainSocketModule extends AbstractModule {
//
// @Override
// protected void configure() {
// bind(PlainServerSocket.class);
// bind(PlainSocketMessageSender.class);
// }
// }
// Path: src/main/java/bbejeck/nio/PlainSocketTestDriver.java
import bbejeck.nio.channels.AsyncServerTestModule;
import bbejeck.nio.sockets.PlainServerSocket;
import bbejeck.nio.sockets.PlainSocketMessageSender;
import bbejeck.nio.sockets.PlainSocketModule;
import com.google.common.base.Stopwatch;
import com.google.inject.Guice;
import com.google.inject.Injector;
import java.util.concurrent.Callable;
import java.util.concurrent.FutureTask;
package bbejeck.nio;
/**
* Created by IntelliJ IDEA.
* User: bbejeck
* Date: 3/14/12
* Time: 9:48 PM
*/
public class PlainSocketTestDriver {
public static void main(String[] args) throws Exception { | Injector injector = Guice.createInjector(new SocketModule(), new PlainSocketModule(), new AsyncServerTestModule()); |
bbejeck/Java-7 | src/main/java/bbejeck/nio/PlainSocketTestDriver.java | // Path: src/main/java/bbejeck/nio/channels/AsyncServerTestModule.java
// public class AsyncServerTestModule extends AbstractModule {
//
// @Override
// protected void configure() {
// bind(AsyncServerSocket.class);
// }
// }
//
// Path: src/main/java/bbejeck/nio/sockets/PlainServerSocket.java
// public class PlainServerSocket {
//
// private ExecutorService executorService;
// private java.net.ServerSocket server;
// private int port;
// private String host;
//
//
// @Inject
// public PlainServerSocket(@Port int port, @Host String host) {
// this.port = port;
// this.host = host;
// }
//
//
// public void startServer() {
// try {
// initServerSocket();
// this.executorService = Executors.newCachedThreadPool();
// while (!executorService.isShutdown()) {
// Socket socket = server.accept();
// executorService.submit(handleSocketRequest(socket));
// }
// } catch (Exception e) {
// if (!executorService.isShutdown()) {
// e.printStackTrace();
// }
// }
// }
//
// private Callable<Void> handleSocketRequest(final Socket socket) {
// return new Callable<Void>() {
// @Override
// public Void call() throws Exception {
// BufferedReader reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
// CharBuffer charBuffer = CharBuffer.allocate(1000);
// reader.read(charBuffer);
// charBuffer.flip();
// StringBuilder builder = new StringBuilder("You Said >> \"");
// String message = charBuffer.toString();
// // System.out.println("Plain Socket Message[" + message + "] received @" + new Date());
// builder.append(message).append("\"");
// BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
// bufferedWriter.write(builder.toString());
// bufferedWriter.flush();
// if (message.equalsIgnoreCase("quit")) {
// stopServer();
// }
// reader.close();
// bufferedWriter.close();
// socket.close();
// return null;
// }
// };
// }
//
// public void stopServer() throws Exception {
// executorService.shutdownNow();
// server.close();
// }
//
//
// private void initServerSocket() throws Exception {
// server = new ServerSocket(port);
// }
//
// }
//
// Path: src/main/java/bbejeck/nio/sockets/PlainSocketMessageSender.java
// public class PlainSocketMessageSender {
//
// private Socket socket;
// private int port;
// private InetSocketAddress socketAddress;
// private int messageCount;
//
// @Inject
// public PlainSocketMessageSender(@Port int port, @MessageCount int messageCount, @Host String host) {
// this.port = port;
// socketAddress = new InetSocketAddress(host, port);
// this.messageCount = messageCount;
// }
//
// public void sendMessages() throws Exception {
// for (int i = 0; i < messageCount; i++) {
// sendTextMessage("Plain text message from socket");
// }
// sendTextMessage("quit");
// }
//
// private void sendTextMessage(String message) throws Exception {
// socket = new Socket();
// socket.connect(socketAddress);
// BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
// bufferedWriter.write(message);
// bufferedWriter.flush();
// BufferedReader reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
// CharBuffer charBuffer = CharBuffer.allocate(1000);
// reader.read(charBuffer);
// charBuffer.flip();
// // System.out.println("Reply from server "+charBuffer.toString());
// reader.close();
// bufferedWriter.close();
// socket.close();
// }
// }
//
// Path: src/main/java/bbejeck/nio/sockets/PlainSocketModule.java
// public class PlainSocketModule extends AbstractModule {
//
// @Override
// protected void configure() {
// bind(PlainServerSocket.class);
// bind(PlainSocketMessageSender.class);
// }
// }
| import bbejeck.nio.channels.AsyncServerTestModule;
import bbejeck.nio.sockets.PlainServerSocket;
import bbejeck.nio.sockets.PlainSocketMessageSender;
import bbejeck.nio.sockets.PlainSocketModule;
import com.google.common.base.Stopwatch;
import com.google.inject.Guice;
import com.google.inject.Injector;
import java.util.concurrent.Callable;
import java.util.concurrent.FutureTask; | package bbejeck.nio;
/**
* Created by IntelliJ IDEA.
* User: bbejeck
* Date: 3/14/12
* Time: 9:48 PM
*/
public class PlainSocketTestDriver {
public static void main(String[] args) throws Exception {
Injector injector = Guice.createInjector(new SocketModule(), new PlainSocketModule(), new AsyncServerTestModule()); | // Path: src/main/java/bbejeck/nio/channels/AsyncServerTestModule.java
// public class AsyncServerTestModule extends AbstractModule {
//
// @Override
// protected void configure() {
// bind(AsyncServerSocket.class);
// }
// }
//
// Path: src/main/java/bbejeck/nio/sockets/PlainServerSocket.java
// public class PlainServerSocket {
//
// private ExecutorService executorService;
// private java.net.ServerSocket server;
// private int port;
// private String host;
//
//
// @Inject
// public PlainServerSocket(@Port int port, @Host String host) {
// this.port = port;
// this.host = host;
// }
//
//
// public void startServer() {
// try {
// initServerSocket();
// this.executorService = Executors.newCachedThreadPool();
// while (!executorService.isShutdown()) {
// Socket socket = server.accept();
// executorService.submit(handleSocketRequest(socket));
// }
// } catch (Exception e) {
// if (!executorService.isShutdown()) {
// e.printStackTrace();
// }
// }
// }
//
// private Callable<Void> handleSocketRequest(final Socket socket) {
// return new Callable<Void>() {
// @Override
// public Void call() throws Exception {
// BufferedReader reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
// CharBuffer charBuffer = CharBuffer.allocate(1000);
// reader.read(charBuffer);
// charBuffer.flip();
// StringBuilder builder = new StringBuilder("You Said >> \"");
// String message = charBuffer.toString();
// // System.out.println("Plain Socket Message[" + message + "] received @" + new Date());
// builder.append(message).append("\"");
// BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
// bufferedWriter.write(builder.toString());
// bufferedWriter.flush();
// if (message.equalsIgnoreCase("quit")) {
// stopServer();
// }
// reader.close();
// bufferedWriter.close();
// socket.close();
// return null;
// }
// };
// }
//
// public void stopServer() throws Exception {
// executorService.shutdownNow();
// server.close();
// }
//
//
// private void initServerSocket() throws Exception {
// server = new ServerSocket(port);
// }
//
// }
//
// Path: src/main/java/bbejeck/nio/sockets/PlainSocketMessageSender.java
// public class PlainSocketMessageSender {
//
// private Socket socket;
// private int port;
// private InetSocketAddress socketAddress;
// private int messageCount;
//
// @Inject
// public PlainSocketMessageSender(@Port int port, @MessageCount int messageCount, @Host String host) {
// this.port = port;
// socketAddress = new InetSocketAddress(host, port);
// this.messageCount = messageCount;
// }
//
// public void sendMessages() throws Exception {
// for (int i = 0; i < messageCount; i++) {
// sendTextMessage("Plain text message from socket");
// }
// sendTextMessage("quit");
// }
//
// private void sendTextMessage(String message) throws Exception {
// socket = new Socket();
// socket.connect(socketAddress);
// BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
// bufferedWriter.write(message);
// bufferedWriter.flush();
// BufferedReader reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
// CharBuffer charBuffer = CharBuffer.allocate(1000);
// reader.read(charBuffer);
// charBuffer.flip();
// // System.out.println("Reply from server "+charBuffer.toString());
// reader.close();
// bufferedWriter.close();
// socket.close();
// }
// }
//
// Path: src/main/java/bbejeck/nio/sockets/PlainSocketModule.java
// public class PlainSocketModule extends AbstractModule {
//
// @Override
// protected void configure() {
// bind(PlainServerSocket.class);
// bind(PlainSocketMessageSender.class);
// }
// }
// Path: src/main/java/bbejeck/nio/PlainSocketTestDriver.java
import bbejeck.nio.channels.AsyncServerTestModule;
import bbejeck.nio.sockets.PlainServerSocket;
import bbejeck.nio.sockets.PlainSocketMessageSender;
import bbejeck.nio.sockets.PlainSocketModule;
import com.google.common.base.Stopwatch;
import com.google.inject.Guice;
import com.google.inject.Injector;
import java.util.concurrent.Callable;
import java.util.concurrent.FutureTask;
package bbejeck.nio;
/**
* Created by IntelliJ IDEA.
* User: bbejeck
* Date: 3/14/12
* Time: 9:48 PM
*/
public class PlainSocketTestDriver {
public static void main(String[] args) throws Exception {
Injector injector = Guice.createInjector(new SocketModule(), new PlainSocketModule(), new AsyncServerTestModule()); | PlainSocketMessageSender messageSender = injector.getInstance(PlainSocketMessageSender.class); |
bbejeck/Java-7 | src/main/java/bbejeck/nio/PlainSocketTestDriver.java | // Path: src/main/java/bbejeck/nio/channels/AsyncServerTestModule.java
// public class AsyncServerTestModule extends AbstractModule {
//
// @Override
// protected void configure() {
// bind(AsyncServerSocket.class);
// }
// }
//
// Path: src/main/java/bbejeck/nio/sockets/PlainServerSocket.java
// public class PlainServerSocket {
//
// private ExecutorService executorService;
// private java.net.ServerSocket server;
// private int port;
// private String host;
//
//
// @Inject
// public PlainServerSocket(@Port int port, @Host String host) {
// this.port = port;
// this.host = host;
// }
//
//
// public void startServer() {
// try {
// initServerSocket();
// this.executorService = Executors.newCachedThreadPool();
// while (!executorService.isShutdown()) {
// Socket socket = server.accept();
// executorService.submit(handleSocketRequest(socket));
// }
// } catch (Exception e) {
// if (!executorService.isShutdown()) {
// e.printStackTrace();
// }
// }
// }
//
// private Callable<Void> handleSocketRequest(final Socket socket) {
// return new Callable<Void>() {
// @Override
// public Void call() throws Exception {
// BufferedReader reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
// CharBuffer charBuffer = CharBuffer.allocate(1000);
// reader.read(charBuffer);
// charBuffer.flip();
// StringBuilder builder = new StringBuilder("You Said >> \"");
// String message = charBuffer.toString();
// // System.out.println("Plain Socket Message[" + message + "] received @" + new Date());
// builder.append(message).append("\"");
// BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
// bufferedWriter.write(builder.toString());
// bufferedWriter.flush();
// if (message.equalsIgnoreCase("quit")) {
// stopServer();
// }
// reader.close();
// bufferedWriter.close();
// socket.close();
// return null;
// }
// };
// }
//
// public void stopServer() throws Exception {
// executorService.shutdownNow();
// server.close();
// }
//
//
// private void initServerSocket() throws Exception {
// server = new ServerSocket(port);
// }
//
// }
//
// Path: src/main/java/bbejeck/nio/sockets/PlainSocketMessageSender.java
// public class PlainSocketMessageSender {
//
// private Socket socket;
// private int port;
// private InetSocketAddress socketAddress;
// private int messageCount;
//
// @Inject
// public PlainSocketMessageSender(@Port int port, @MessageCount int messageCount, @Host String host) {
// this.port = port;
// socketAddress = new InetSocketAddress(host, port);
// this.messageCount = messageCount;
// }
//
// public void sendMessages() throws Exception {
// for (int i = 0; i < messageCount; i++) {
// sendTextMessage("Plain text message from socket");
// }
// sendTextMessage("quit");
// }
//
// private void sendTextMessage(String message) throws Exception {
// socket = new Socket();
// socket.connect(socketAddress);
// BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
// bufferedWriter.write(message);
// bufferedWriter.flush();
// BufferedReader reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
// CharBuffer charBuffer = CharBuffer.allocate(1000);
// reader.read(charBuffer);
// charBuffer.flip();
// // System.out.println("Reply from server "+charBuffer.toString());
// reader.close();
// bufferedWriter.close();
// socket.close();
// }
// }
//
// Path: src/main/java/bbejeck/nio/sockets/PlainSocketModule.java
// public class PlainSocketModule extends AbstractModule {
//
// @Override
// protected void configure() {
// bind(PlainServerSocket.class);
// bind(PlainSocketMessageSender.class);
// }
// }
| import bbejeck.nio.channels.AsyncServerTestModule;
import bbejeck.nio.sockets.PlainServerSocket;
import bbejeck.nio.sockets.PlainSocketMessageSender;
import bbejeck.nio.sockets.PlainSocketModule;
import com.google.common.base.Stopwatch;
import com.google.inject.Guice;
import com.google.inject.Injector;
import java.util.concurrent.Callable;
import java.util.concurrent.FutureTask; | package bbejeck.nio;
/**
* Created by IntelliJ IDEA.
* User: bbejeck
* Date: 3/14/12
* Time: 9:48 PM
*/
public class PlainSocketTestDriver {
public static void main(String[] args) throws Exception {
Injector injector = Guice.createInjector(new SocketModule(), new PlainSocketModule(), new AsyncServerTestModule());
PlainSocketMessageSender messageSender = injector.getInstance(PlainSocketMessageSender.class);
System.out.println("Starting the PlainSocketServer Test"); | // Path: src/main/java/bbejeck/nio/channels/AsyncServerTestModule.java
// public class AsyncServerTestModule extends AbstractModule {
//
// @Override
// protected void configure() {
// bind(AsyncServerSocket.class);
// }
// }
//
// Path: src/main/java/bbejeck/nio/sockets/PlainServerSocket.java
// public class PlainServerSocket {
//
// private ExecutorService executorService;
// private java.net.ServerSocket server;
// private int port;
// private String host;
//
//
// @Inject
// public PlainServerSocket(@Port int port, @Host String host) {
// this.port = port;
// this.host = host;
// }
//
//
// public void startServer() {
// try {
// initServerSocket();
// this.executorService = Executors.newCachedThreadPool();
// while (!executorService.isShutdown()) {
// Socket socket = server.accept();
// executorService.submit(handleSocketRequest(socket));
// }
// } catch (Exception e) {
// if (!executorService.isShutdown()) {
// e.printStackTrace();
// }
// }
// }
//
// private Callable<Void> handleSocketRequest(final Socket socket) {
// return new Callable<Void>() {
// @Override
// public Void call() throws Exception {
// BufferedReader reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
// CharBuffer charBuffer = CharBuffer.allocate(1000);
// reader.read(charBuffer);
// charBuffer.flip();
// StringBuilder builder = new StringBuilder("You Said >> \"");
// String message = charBuffer.toString();
// // System.out.println("Plain Socket Message[" + message + "] received @" + new Date());
// builder.append(message).append("\"");
// BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
// bufferedWriter.write(builder.toString());
// bufferedWriter.flush();
// if (message.equalsIgnoreCase("quit")) {
// stopServer();
// }
// reader.close();
// bufferedWriter.close();
// socket.close();
// return null;
// }
// };
// }
//
// public void stopServer() throws Exception {
// executorService.shutdownNow();
// server.close();
// }
//
//
// private void initServerSocket() throws Exception {
// server = new ServerSocket(port);
// }
//
// }
//
// Path: src/main/java/bbejeck/nio/sockets/PlainSocketMessageSender.java
// public class PlainSocketMessageSender {
//
// private Socket socket;
// private int port;
// private InetSocketAddress socketAddress;
// private int messageCount;
//
// @Inject
// public PlainSocketMessageSender(@Port int port, @MessageCount int messageCount, @Host String host) {
// this.port = port;
// socketAddress = new InetSocketAddress(host, port);
// this.messageCount = messageCount;
// }
//
// public void sendMessages() throws Exception {
// for (int i = 0; i < messageCount; i++) {
// sendTextMessage("Plain text message from socket");
// }
// sendTextMessage("quit");
// }
//
// private void sendTextMessage(String message) throws Exception {
// socket = new Socket();
// socket.connect(socketAddress);
// BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
// bufferedWriter.write(message);
// bufferedWriter.flush();
// BufferedReader reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
// CharBuffer charBuffer = CharBuffer.allocate(1000);
// reader.read(charBuffer);
// charBuffer.flip();
// // System.out.println("Reply from server "+charBuffer.toString());
// reader.close();
// bufferedWriter.close();
// socket.close();
// }
// }
//
// Path: src/main/java/bbejeck/nio/sockets/PlainSocketModule.java
// public class PlainSocketModule extends AbstractModule {
//
// @Override
// protected void configure() {
// bind(PlainServerSocket.class);
// bind(PlainSocketMessageSender.class);
// }
// }
// Path: src/main/java/bbejeck/nio/PlainSocketTestDriver.java
import bbejeck.nio.channels.AsyncServerTestModule;
import bbejeck.nio.sockets.PlainServerSocket;
import bbejeck.nio.sockets.PlainSocketMessageSender;
import bbejeck.nio.sockets.PlainSocketModule;
import com.google.common.base.Stopwatch;
import com.google.inject.Guice;
import com.google.inject.Injector;
import java.util.concurrent.Callable;
import java.util.concurrent.FutureTask;
package bbejeck.nio;
/**
* Created by IntelliJ IDEA.
* User: bbejeck
* Date: 3/14/12
* Time: 9:48 PM
*/
public class PlainSocketTestDriver {
public static void main(String[] args) throws Exception {
Injector injector = Guice.createInjector(new SocketModule(), new PlainSocketModule(), new AsyncServerTestModule());
PlainSocketMessageSender messageSender = injector.getInstance(PlainSocketMessageSender.class);
System.out.println("Starting the PlainSocketServer Test"); | final PlainServerSocket plainServerSocket = injector.getInstance(PlainServerSocket.class); |
bbejeck/Java-7 | src/main/java/bbejeck/nio/files/directory/AsynchronousRecursiveDirectoryStream.java | // Path: src/main/java/bbejeck/nio/files/visitor/FunctionVisitor.java
// public class FunctionVisitor extends SimpleFileVisitor<Path> {
//
// Function<Path,FileVisitResult> pathFunction;
//
// public FunctionVisitor(Function<Path, FileVisitResult> pathFunction) {
// this.pathFunction = pathFunction;
// }
//
// @Override
// public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
// return pathFunction.apply(file);
// }
// }
//
// Path: src/main/java/bbejeck/nio/util/FilterBuilder.java
// public class FilterBuilder {
//
// private FilterBuilder() {}
//
// public static DirectoryStream.Filter<Path> buildGlobFilter(String pattern) {
// final PathMatcher pathMatcher = getPathMatcher("glob:"+pattern);
// return new DirectoryStream.Filter<Path>() {
// @Override
// public boolean accept(Path entry) throws IOException {
// return pathMatcher.matches(entry);
// }
// };
// }
//
// public static DirectoryStream.Filter<Path> buildRegexFilter(String pattern) {
// final PathMatcher pathMatcher = getPathMatcher("regex:"+pattern);
// return new DirectoryStream.Filter<Path>() {
// @Override
// public boolean accept(Path entry) throws IOException {
// return pathMatcher.matches(entry);
// }
// };
// }
//
//
// private static PathMatcher getPathMatcher(String pattern) {
// return FileSystems.getDefault().getPathMatcher(pattern);
// }
//
// }
| import bbejeck.nio.files.visitor.FunctionVisitor;
import bbejeck.nio.util.FilterBuilder;
import com.google.common.base.Function;
import java.io.IOException;
import java.nio.file.DirectoryStream;
import java.nio.file.FileVisitResult;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.Iterator;
import java.util.Objects;
import java.util.concurrent.*; | package bbejeck.nio.files.directory;
/**
* Created by IntelliJ IDEA.
* User: bbejeck
* Date: 2/5/12
* Time: 1:05 PM
*/
public class AsynchronousRecursiveDirectoryStream implements DirectoryStream<Path> {
private LinkedBlockingQueue<Path> pathsBlockingQueue = new LinkedBlockingQueue<>();
private boolean closed = false;
private FutureTask<Void> pathTask;
private Path startPath;
private Filter filter;
public AsynchronousRecursiveDirectoryStream(Path startPath, String pattern) throws IOException { | // Path: src/main/java/bbejeck/nio/files/visitor/FunctionVisitor.java
// public class FunctionVisitor extends SimpleFileVisitor<Path> {
//
// Function<Path,FileVisitResult> pathFunction;
//
// public FunctionVisitor(Function<Path, FileVisitResult> pathFunction) {
// this.pathFunction = pathFunction;
// }
//
// @Override
// public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
// return pathFunction.apply(file);
// }
// }
//
// Path: src/main/java/bbejeck/nio/util/FilterBuilder.java
// public class FilterBuilder {
//
// private FilterBuilder() {}
//
// public static DirectoryStream.Filter<Path> buildGlobFilter(String pattern) {
// final PathMatcher pathMatcher = getPathMatcher("glob:"+pattern);
// return new DirectoryStream.Filter<Path>() {
// @Override
// public boolean accept(Path entry) throws IOException {
// return pathMatcher.matches(entry);
// }
// };
// }
//
// public static DirectoryStream.Filter<Path> buildRegexFilter(String pattern) {
// final PathMatcher pathMatcher = getPathMatcher("regex:"+pattern);
// return new DirectoryStream.Filter<Path>() {
// @Override
// public boolean accept(Path entry) throws IOException {
// return pathMatcher.matches(entry);
// }
// };
// }
//
//
// private static PathMatcher getPathMatcher(String pattern) {
// return FileSystems.getDefault().getPathMatcher(pattern);
// }
//
// }
// Path: src/main/java/bbejeck/nio/files/directory/AsynchronousRecursiveDirectoryStream.java
import bbejeck.nio.files.visitor.FunctionVisitor;
import bbejeck.nio.util.FilterBuilder;
import com.google.common.base.Function;
import java.io.IOException;
import java.nio.file.DirectoryStream;
import java.nio.file.FileVisitResult;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.Iterator;
import java.util.Objects;
import java.util.concurrent.*;
package bbejeck.nio.files.directory;
/**
* Created by IntelliJ IDEA.
* User: bbejeck
* Date: 2/5/12
* Time: 1:05 PM
*/
public class AsynchronousRecursiveDirectoryStream implements DirectoryStream<Path> {
private LinkedBlockingQueue<Path> pathsBlockingQueue = new LinkedBlockingQueue<>();
private boolean closed = false;
private FutureTask<Void> pathTask;
private Path startPath;
private Filter filter;
public AsynchronousRecursiveDirectoryStream(Path startPath, String pattern) throws IOException { | this.filter = FilterBuilder.buildGlobFilter(Objects.requireNonNull(pattern)); |
bbejeck/Java-7 | src/main/java/bbejeck/nio/files/directory/AsynchronousRecursiveDirectoryStream.java | // Path: src/main/java/bbejeck/nio/files/visitor/FunctionVisitor.java
// public class FunctionVisitor extends SimpleFileVisitor<Path> {
//
// Function<Path,FileVisitResult> pathFunction;
//
// public FunctionVisitor(Function<Path, FileVisitResult> pathFunction) {
// this.pathFunction = pathFunction;
// }
//
// @Override
// public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
// return pathFunction.apply(file);
// }
// }
//
// Path: src/main/java/bbejeck/nio/util/FilterBuilder.java
// public class FilterBuilder {
//
// private FilterBuilder() {}
//
// public static DirectoryStream.Filter<Path> buildGlobFilter(String pattern) {
// final PathMatcher pathMatcher = getPathMatcher("glob:"+pattern);
// return new DirectoryStream.Filter<Path>() {
// @Override
// public boolean accept(Path entry) throws IOException {
// return pathMatcher.matches(entry);
// }
// };
// }
//
// public static DirectoryStream.Filter<Path> buildRegexFilter(String pattern) {
// final PathMatcher pathMatcher = getPathMatcher("regex:"+pattern);
// return new DirectoryStream.Filter<Path>() {
// @Override
// public boolean accept(Path entry) throws IOException {
// return pathMatcher.matches(entry);
// }
// };
// }
//
//
// private static PathMatcher getPathMatcher(String pattern) {
// return FileSystems.getDefault().getPathMatcher(pattern);
// }
//
// }
| import bbejeck.nio.files.visitor.FunctionVisitor;
import bbejeck.nio.util.FilterBuilder;
import com.google.common.base.Function;
import java.io.IOException;
import java.nio.file.DirectoryStream;
import java.nio.file.FileVisitResult;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.Iterator;
import java.util.Objects;
import java.util.concurrent.*; | @Override
public boolean hasNext() {
try {
path = pathsBlockingQueue.poll();
while (!pathTask.isDone() && path == null) {
path = pathsBlockingQueue.poll(5, TimeUnit.MILLISECONDS);
}
return (path != null);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
return false;
}
@Override
public Path next() {
return path;
}
@Override
public void remove() {
throw new UnsupportedOperationException("Removal not supported");
}
};
}
private void findFiles(final Path startPath, final Filter filter) {
pathTask = new FutureTask<>(new Callable<Void>() {
@Override
public Void call() throws Exception { | // Path: src/main/java/bbejeck/nio/files/visitor/FunctionVisitor.java
// public class FunctionVisitor extends SimpleFileVisitor<Path> {
//
// Function<Path,FileVisitResult> pathFunction;
//
// public FunctionVisitor(Function<Path, FileVisitResult> pathFunction) {
// this.pathFunction = pathFunction;
// }
//
// @Override
// public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
// return pathFunction.apply(file);
// }
// }
//
// Path: src/main/java/bbejeck/nio/util/FilterBuilder.java
// public class FilterBuilder {
//
// private FilterBuilder() {}
//
// public static DirectoryStream.Filter<Path> buildGlobFilter(String pattern) {
// final PathMatcher pathMatcher = getPathMatcher("glob:"+pattern);
// return new DirectoryStream.Filter<Path>() {
// @Override
// public boolean accept(Path entry) throws IOException {
// return pathMatcher.matches(entry);
// }
// };
// }
//
// public static DirectoryStream.Filter<Path> buildRegexFilter(String pattern) {
// final PathMatcher pathMatcher = getPathMatcher("regex:"+pattern);
// return new DirectoryStream.Filter<Path>() {
// @Override
// public boolean accept(Path entry) throws IOException {
// return pathMatcher.matches(entry);
// }
// };
// }
//
//
// private static PathMatcher getPathMatcher(String pattern) {
// return FileSystems.getDefault().getPathMatcher(pattern);
// }
//
// }
// Path: src/main/java/bbejeck/nio/files/directory/AsynchronousRecursiveDirectoryStream.java
import bbejeck.nio.files.visitor.FunctionVisitor;
import bbejeck.nio.util.FilterBuilder;
import com.google.common.base.Function;
import java.io.IOException;
import java.nio.file.DirectoryStream;
import java.nio.file.FileVisitResult;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.Iterator;
import java.util.Objects;
import java.util.concurrent.*;
@Override
public boolean hasNext() {
try {
path = pathsBlockingQueue.poll();
while (!pathTask.isDone() && path == null) {
path = pathsBlockingQueue.poll(5, TimeUnit.MILLISECONDS);
}
return (path != null);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
return false;
}
@Override
public Path next() {
return path;
}
@Override
public void remove() {
throw new UnsupportedOperationException("Removal not supported");
}
};
}
private void findFiles(final Path startPath, final Filter filter) {
pathTask = new FutureTask<>(new Callable<Void>() {
@Override
public Void call() throws Exception { | Files.walkFileTree(startPath, new FunctionVisitor(getFunction(filter))); |
miguelbcr/RxPaparazzo | rx_paparazzo/src/main/java/com/miguelbcr/ui/rx_paparazzo2/entities/FileData.java | // Path: rx_paparazzo/src/main/java/com/miguelbcr/ui/rx_paparazzo2/interactors/Dimensions.java
// public final class Dimensions implements Serializable {
//
// private static final long serialVersionUID = 1L;
//
// private int width;
// private int height;
//
// public Dimensions() {
// }
//
// public Dimensions(int width, int height) {
// this.width = width;
// this.height = height;
// }
//
// public int getWidth() {
// return width;
// }
//
// public void setWidth(int width) {
// this.width = width;
// }
//
// public int getHeight() {
// return height;
// }
//
// public void setHeight(int height) {
// this.height = height;
// }
//
// public boolean hasSize() {
// return width > 0 && height > 0;
// }
// }
| import android.util.Log;
import com.miguelbcr.ui.rx_paparazzo2.interactors.Dimensions;
import java.io.File;
import java.io.Serializable; | package com.miguelbcr.ui.rx_paparazzo2.entities;
public class FileData implements Serializable {
private static final String FILENAME_MIMETYPE = "%s (%s)";
private static final String FILENAME_MIMETYPE_TITLE = "%s (%s) - %s";
private static final String FILENAME_TRANSIENT_MIMETYPE_TITLE = "%s %s (%s) - %s";
private File file;
private String filename;
private String mimeType;
private String title;
private boolean transientFile;
private boolean exceededMaximumFileSize; | // Path: rx_paparazzo/src/main/java/com/miguelbcr/ui/rx_paparazzo2/interactors/Dimensions.java
// public final class Dimensions implements Serializable {
//
// private static final long serialVersionUID = 1L;
//
// private int width;
// private int height;
//
// public Dimensions() {
// }
//
// public Dimensions(int width, int height) {
// this.width = width;
// this.height = height;
// }
//
// public int getWidth() {
// return width;
// }
//
// public void setWidth(int width) {
// this.width = width;
// }
//
// public int getHeight() {
// return height;
// }
//
// public void setHeight(int height) {
// this.height = height;
// }
//
// public boolean hasSize() {
// return width > 0 && height > 0;
// }
// }
// Path: rx_paparazzo/src/main/java/com/miguelbcr/ui/rx_paparazzo2/entities/FileData.java
import android.util.Log;
import com.miguelbcr.ui.rx_paparazzo2.interactors.Dimensions;
import java.io.File;
import java.io.Serializable;
package com.miguelbcr.ui.rx_paparazzo2.entities;
public class FileData implements Serializable {
private static final String FILENAME_MIMETYPE = "%s (%s)";
private static final String FILENAME_MIMETYPE_TITLE = "%s (%s) - %s";
private static final String FILENAME_TRANSIENT_MIMETYPE_TITLE = "%s %s (%s) - %s";
private File file;
private String filename;
private String mimeType;
private String title;
private boolean transientFile;
private boolean exceededMaximumFileSize; | private Dimensions originalDimensions; |
miguelbcr/RxPaparazzo | rx_paparazzo/src/main/java/com/miguelbcr/ui/rx_paparazzo2/interactors/PermissionUtil.java | // Path: rx_paparazzo/src/main/java/com/miguelbcr/ui/rx_paparazzo2/entities/TargetUi.java
// public class TargetUi {
// private Object ui;
//
// public TargetUi(Object ui) {
// this.ui = ui;
// }
//
// public FragmentActivity activity() {
// return fragment() != null ? fragment().getActivity() : (FragmentActivity) ui;
// }
//
// @Nullable
// public Fragment fragment() {
// if (ui instanceof Fragment) {
// return (Fragment) ui;
// }
// return null;
// }
//
// public Object ui() {
// return ui;
// }
//
// public void setUi(Object ui) {
// this.ui = ui;
// }
//
// public Context getContext() {
// return fragment() == null ? activity() : fragment().getContext();
// }
// }
| import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.net.Uri;
import android.os.Build;
import com.miguelbcr.ui.rx_paparazzo2.entities.TargetUi;
import java.util.List; | package com.miguelbcr.ui.rx_paparazzo2.interactors;
public class PermissionUtil {
public static final int READ_WRITE_PERMISSIONS = Intent.FLAG_GRANT_READ_URI_PERMISSION
| Intent.FLAG_GRANT_WRITE_URI_PERMISSION;
| // Path: rx_paparazzo/src/main/java/com/miguelbcr/ui/rx_paparazzo2/entities/TargetUi.java
// public class TargetUi {
// private Object ui;
//
// public TargetUi(Object ui) {
// this.ui = ui;
// }
//
// public FragmentActivity activity() {
// return fragment() != null ? fragment().getActivity() : (FragmentActivity) ui;
// }
//
// @Nullable
// public Fragment fragment() {
// if (ui instanceof Fragment) {
// return (Fragment) ui;
// }
// return null;
// }
//
// public Object ui() {
// return ui;
// }
//
// public void setUi(Object ui) {
// this.ui = ui;
// }
//
// public Context getContext() {
// return fragment() == null ? activity() : fragment().getContext();
// }
// }
// Path: rx_paparazzo/src/main/java/com/miguelbcr/ui/rx_paparazzo2/interactors/PermissionUtil.java
import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.net.Uri;
import android.os.Build;
import com.miguelbcr.ui.rx_paparazzo2.entities.TargetUi;
import java.util.List;
package com.miguelbcr.ui.rx_paparazzo2.interactors;
public class PermissionUtil {
public static final int READ_WRITE_PERMISSIONS = Intent.FLAG_GRANT_READ_URI_PERMISSION
| Intent.FLAG_GRANT_WRITE_URI_PERMISSION;
| public static Intent requestReadWritePermission(TargetUi targetUi, Intent intent, Uri uri) { |
miguelbcr/RxPaparazzo | rx_paparazzo/src/main/java/com/miguelbcr/ui/rx_paparazzo2/workers/Worker.java | // Path: rx_paparazzo/src/main/java/com/miguelbcr/ui/rx_paparazzo2/entities/PermissionDeniedException.java
// public class PermissionDeniedException extends RuntimeException {
// private int code;
//
// public PermissionDeniedException(int code) {
// this.code = code;
// }
//
// public int getCode() {
// return code;
// }
// }
//
// Path: rx_paparazzo/src/main/java/com/miguelbcr/ui/rx_paparazzo2/entities/Response.java
// public class Response<T, D> {
// private final T targetUI;
// private final D data;
// private final int resultCode;
//
// public Response(T targetUI, D data, int resultCode) {
// this.targetUI = targetUI;
// this.data = data;
// this.resultCode = resultCode;
// }
//
// public T targetUI() {
// return targetUI;
// }
//
// public D data() {
// return data;
// }
//
// /**
// * @return <ul>
// * <li>{@link Activity#RESULT_OK}</li>
// * <li>{@link Activity#RESULT_CANCELED}</li>
// * <li>{@link RxPaparazzo#RESULT_DENIED_PERMISSION}</li>
// * <li>{@link RxPaparazzo#RESULT_DENIED_PERMISSION_NEVER_ASK}</li>
// * </ul>
// */
// public int resultCode() {
// return resultCode;
// }
// }
//
// Path: rx_paparazzo/src/main/java/com/miguelbcr/ui/rx_paparazzo2/entities/TargetUi.java
// public class TargetUi {
// private Object ui;
//
// public TargetUi(Object ui) {
// this.ui = ui;
// }
//
// public FragmentActivity activity() {
// return fragment() != null ? fragment().getActivity() : (FragmentActivity) ui;
// }
//
// @Nullable
// public Fragment fragment() {
// if (ui instanceof Fragment) {
// return (Fragment) ui;
// }
// return null;
// }
//
// public Object ui() {
// return ui;
// }
//
// public void setUi(Object ui) {
// this.ui = ui;
// }
//
// public Context getContext() {
// return fragment() == null ? activity() : fragment().getContext();
// }
// }
//
// Path: rx_paparazzo/src/main/java/com/miguelbcr/ui/rx_paparazzo2/entities/UserCanceledException.java
// public class UserCanceledException extends RuntimeException {
// }
| import android.app.Activity;
import com.miguelbcr.ui.rx_paparazzo2.entities.PermissionDeniedException;
import com.miguelbcr.ui.rx_paparazzo2.entities.Response;
import com.miguelbcr.ui.rx_paparazzo2.entities.TargetUi;
import com.miguelbcr.ui.rx_paparazzo2.entities.UserCanceledException;
import io.reactivex.Observable;
import io.reactivex.ObservableSource;
import io.reactivex.ObservableTransformer;
import io.reactivex.exceptions.Exceptions;
import io.reactivex.functions.Function; | /*
* Copyright 2016 Miguel Garcia
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.miguelbcr.ui.rx_paparazzo2.workers;
abstract class Worker {
private final TargetUi targetUi;
public Worker(TargetUi targetUi) {
this.targetUi = targetUi;
}
@SuppressWarnings("unchecked") protected <T> ObservableTransformer<T, T> applyOnError() {
return new ObservableTransformer<T, T>() {
@Override public ObservableSource<T> apply(Observable<T> observable) {
return observable.onErrorResumeNext(
new Function<Throwable, ObservableSource<? extends T>>() {
@Override public ObservableSource<? extends T> apply(Throwable throwable)
throws Exception { | // Path: rx_paparazzo/src/main/java/com/miguelbcr/ui/rx_paparazzo2/entities/PermissionDeniedException.java
// public class PermissionDeniedException extends RuntimeException {
// private int code;
//
// public PermissionDeniedException(int code) {
// this.code = code;
// }
//
// public int getCode() {
// return code;
// }
// }
//
// Path: rx_paparazzo/src/main/java/com/miguelbcr/ui/rx_paparazzo2/entities/Response.java
// public class Response<T, D> {
// private final T targetUI;
// private final D data;
// private final int resultCode;
//
// public Response(T targetUI, D data, int resultCode) {
// this.targetUI = targetUI;
// this.data = data;
// this.resultCode = resultCode;
// }
//
// public T targetUI() {
// return targetUI;
// }
//
// public D data() {
// return data;
// }
//
// /**
// * @return <ul>
// * <li>{@link Activity#RESULT_OK}</li>
// * <li>{@link Activity#RESULT_CANCELED}</li>
// * <li>{@link RxPaparazzo#RESULT_DENIED_PERMISSION}</li>
// * <li>{@link RxPaparazzo#RESULT_DENIED_PERMISSION_NEVER_ASK}</li>
// * </ul>
// */
// public int resultCode() {
// return resultCode;
// }
// }
//
// Path: rx_paparazzo/src/main/java/com/miguelbcr/ui/rx_paparazzo2/entities/TargetUi.java
// public class TargetUi {
// private Object ui;
//
// public TargetUi(Object ui) {
// this.ui = ui;
// }
//
// public FragmentActivity activity() {
// return fragment() != null ? fragment().getActivity() : (FragmentActivity) ui;
// }
//
// @Nullable
// public Fragment fragment() {
// if (ui instanceof Fragment) {
// return (Fragment) ui;
// }
// return null;
// }
//
// public Object ui() {
// return ui;
// }
//
// public void setUi(Object ui) {
// this.ui = ui;
// }
//
// public Context getContext() {
// return fragment() == null ? activity() : fragment().getContext();
// }
// }
//
// Path: rx_paparazzo/src/main/java/com/miguelbcr/ui/rx_paparazzo2/entities/UserCanceledException.java
// public class UserCanceledException extends RuntimeException {
// }
// Path: rx_paparazzo/src/main/java/com/miguelbcr/ui/rx_paparazzo2/workers/Worker.java
import android.app.Activity;
import com.miguelbcr.ui.rx_paparazzo2.entities.PermissionDeniedException;
import com.miguelbcr.ui.rx_paparazzo2.entities.Response;
import com.miguelbcr.ui.rx_paparazzo2.entities.TargetUi;
import com.miguelbcr.ui.rx_paparazzo2.entities.UserCanceledException;
import io.reactivex.Observable;
import io.reactivex.ObservableSource;
import io.reactivex.ObservableTransformer;
import io.reactivex.exceptions.Exceptions;
import io.reactivex.functions.Function;
/*
* Copyright 2016 Miguel Garcia
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.miguelbcr.ui.rx_paparazzo2.workers;
abstract class Worker {
private final TargetUi targetUi;
public Worker(TargetUi targetUi) {
this.targetUi = targetUi;
}
@SuppressWarnings("unchecked") protected <T> ObservableTransformer<T, T> applyOnError() {
return new ObservableTransformer<T, T>() {
@Override public ObservableSource<T> apply(Observable<T> observable) {
return observable.onErrorResumeNext(
new Function<Throwable, ObservableSource<? extends T>>() {
@Override public ObservableSource<? extends T> apply(Throwable throwable)
throws Exception { | if (throwable instanceof UserCanceledException) { |
miguelbcr/RxPaparazzo | rx_paparazzo/src/main/java/com/miguelbcr/ui/rx_paparazzo2/workers/Worker.java | // Path: rx_paparazzo/src/main/java/com/miguelbcr/ui/rx_paparazzo2/entities/PermissionDeniedException.java
// public class PermissionDeniedException extends RuntimeException {
// private int code;
//
// public PermissionDeniedException(int code) {
// this.code = code;
// }
//
// public int getCode() {
// return code;
// }
// }
//
// Path: rx_paparazzo/src/main/java/com/miguelbcr/ui/rx_paparazzo2/entities/Response.java
// public class Response<T, D> {
// private final T targetUI;
// private final D data;
// private final int resultCode;
//
// public Response(T targetUI, D data, int resultCode) {
// this.targetUI = targetUI;
// this.data = data;
// this.resultCode = resultCode;
// }
//
// public T targetUI() {
// return targetUI;
// }
//
// public D data() {
// return data;
// }
//
// /**
// * @return <ul>
// * <li>{@link Activity#RESULT_OK}</li>
// * <li>{@link Activity#RESULT_CANCELED}</li>
// * <li>{@link RxPaparazzo#RESULT_DENIED_PERMISSION}</li>
// * <li>{@link RxPaparazzo#RESULT_DENIED_PERMISSION_NEVER_ASK}</li>
// * </ul>
// */
// public int resultCode() {
// return resultCode;
// }
// }
//
// Path: rx_paparazzo/src/main/java/com/miguelbcr/ui/rx_paparazzo2/entities/TargetUi.java
// public class TargetUi {
// private Object ui;
//
// public TargetUi(Object ui) {
// this.ui = ui;
// }
//
// public FragmentActivity activity() {
// return fragment() != null ? fragment().getActivity() : (FragmentActivity) ui;
// }
//
// @Nullable
// public Fragment fragment() {
// if (ui instanceof Fragment) {
// return (Fragment) ui;
// }
// return null;
// }
//
// public Object ui() {
// return ui;
// }
//
// public void setUi(Object ui) {
// this.ui = ui;
// }
//
// public Context getContext() {
// return fragment() == null ? activity() : fragment().getContext();
// }
// }
//
// Path: rx_paparazzo/src/main/java/com/miguelbcr/ui/rx_paparazzo2/entities/UserCanceledException.java
// public class UserCanceledException extends RuntimeException {
// }
| import android.app.Activity;
import com.miguelbcr.ui.rx_paparazzo2.entities.PermissionDeniedException;
import com.miguelbcr.ui.rx_paparazzo2.entities.Response;
import com.miguelbcr.ui.rx_paparazzo2.entities.TargetUi;
import com.miguelbcr.ui.rx_paparazzo2.entities.UserCanceledException;
import io.reactivex.Observable;
import io.reactivex.ObservableSource;
import io.reactivex.ObservableTransformer;
import io.reactivex.exceptions.Exceptions;
import io.reactivex.functions.Function; | /*
* Copyright 2016 Miguel Garcia
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.miguelbcr.ui.rx_paparazzo2.workers;
abstract class Worker {
private final TargetUi targetUi;
public Worker(TargetUi targetUi) {
this.targetUi = targetUi;
}
@SuppressWarnings("unchecked") protected <T> ObservableTransformer<T, T> applyOnError() {
return new ObservableTransformer<T, T>() {
@Override public ObservableSource<T> apply(Observable<T> observable) {
return observable.onErrorResumeNext(
new Function<Throwable, ObservableSource<? extends T>>() {
@Override public ObservableSource<? extends T> apply(Throwable throwable)
throws Exception {
if (throwable instanceof UserCanceledException) {
return Observable.just( | // Path: rx_paparazzo/src/main/java/com/miguelbcr/ui/rx_paparazzo2/entities/PermissionDeniedException.java
// public class PermissionDeniedException extends RuntimeException {
// private int code;
//
// public PermissionDeniedException(int code) {
// this.code = code;
// }
//
// public int getCode() {
// return code;
// }
// }
//
// Path: rx_paparazzo/src/main/java/com/miguelbcr/ui/rx_paparazzo2/entities/Response.java
// public class Response<T, D> {
// private final T targetUI;
// private final D data;
// private final int resultCode;
//
// public Response(T targetUI, D data, int resultCode) {
// this.targetUI = targetUI;
// this.data = data;
// this.resultCode = resultCode;
// }
//
// public T targetUI() {
// return targetUI;
// }
//
// public D data() {
// return data;
// }
//
// /**
// * @return <ul>
// * <li>{@link Activity#RESULT_OK}</li>
// * <li>{@link Activity#RESULT_CANCELED}</li>
// * <li>{@link RxPaparazzo#RESULT_DENIED_PERMISSION}</li>
// * <li>{@link RxPaparazzo#RESULT_DENIED_PERMISSION_NEVER_ASK}</li>
// * </ul>
// */
// public int resultCode() {
// return resultCode;
// }
// }
//
// Path: rx_paparazzo/src/main/java/com/miguelbcr/ui/rx_paparazzo2/entities/TargetUi.java
// public class TargetUi {
// private Object ui;
//
// public TargetUi(Object ui) {
// this.ui = ui;
// }
//
// public FragmentActivity activity() {
// return fragment() != null ? fragment().getActivity() : (FragmentActivity) ui;
// }
//
// @Nullable
// public Fragment fragment() {
// if (ui instanceof Fragment) {
// return (Fragment) ui;
// }
// return null;
// }
//
// public Object ui() {
// return ui;
// }
//
// public void setUi(Object ui) {
// this.ui = ui;
// }
//
// public Context getContext() {
// return fragment() == null ? activity() : fragment().getContext();
// }
// }
//
// Path: rx_paparazzo/src/main/java/com/miguelbcr/ui/rx_paparazzo2/entities/UserCanceledException.java
// public class UserCanceledException extends RuntimeException {
// }
// Path: rx_paparazzo/src/main/java/com/miguelbcr/ui/rx_paparazzo2/workers/Worker.java
import android.app.Activity;
import com.miguelbcr.ui.rx_paparazzo2.entities.PermissionDeniedException;
import com.miguelbcr.ui.rx_paparazzo2.entities.Response;
import com.miguelbcr.ui.rx_paparazzo2.entities.TargetUi;
import com.miguelbcr.ui.rx_paparazzo2.entities.UserCanceledException;
import io.reactivex.Observable;
import io.reactivex.ObservableSource;
import io.reactivex.ObservableTransformer;
import io.reactivex.exceptions.Exceptions;
import io.reactivex.functions.Function;
/*
* Copyright 2016 Miguel Garcia
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.miguelbcr.ui.rx_paparazzo2.workers;
abstract class Worker {
private final TargetUi targetUi;
public Worker(TargetUi targetUi) {
this.targetUi = targetUi;
}
@SuppressWarnings("unchecked") protected <T> ObservableTransformer<T, T> applyOnError() {
return new ObservableTransformer<T, T>() {
@Override public ObservableSource<T> apply(Observable<T> observable) {
return observable.onErrorResumeNext(
new Function<Throwable, ObservableSource<? extends T>>() {
@Override public ObservableSource<? extends T> apply(Throwable throwable)
throws Exception {
if (throwable instanceof UserCanceledException) {
return Observable.just( | (T) new Response(targetUi.ui(), null, Activity.RESULT_CANCELED)); |
miguelbcr/RxPaparazzo | rx_paparazzo/src/main/java/com/miguelbcr/ui/rx_paparazzo2/workers/Worker.java | // Path: rx_paparazzo/src/main/java/com/miguelbcr/ui/rx_paparazzo2/entities/PermissionDeniedException.java
// public class PermissionDeniedException extends RuntimeException {
// private int code;
//
// public PermissionDeniedException(int code) {
// this.code = code;
// }
//
// public int getCode() {
// return code;
// }
// }
//
// Path: rx_paparazzo/src/main/java/com/miguelbcr/ui/rx_paparazzo2/entities/Response.java
// public class Response<T, D> {
// private final T targetUI;
// private final D data;
// private final int resultCode;
//
// public Response(T targetUI, D data, int resultCode) {
// this.targetUI = targetUI;
// this.data = data;
// this.resultCode = resultCode;
// }
//
// public T targetUI() {
// return targetUI;
// }
//
// public D data() {
// return data;
// }
//
// /**
// * @return <ul>
// * <li>{@link Activity#RESULT_OK}</li>
// * <li>{@link Activity#RESULT_CANCELED}</li>
// * <li>{@link RxPaparazzo#RESULT_DENIED_PERMISSION}</li>
// * <li>{@link RxPaparazzo#RESULT_DENIED_PERMISSION_NEVER_ASK}</li>
// * </ul>
// */
// public int resultCode() {
// return resultCode;
// }
// }
//
// Path: rx_paparazzo/src/main/java/com/miguelbcr/ui/rx_paparazzo2/entities/TargetUi.java
// public class TargetUi {
// private Object ui;
//
// public TargetUi(Object ui) {
// this.ui = ui;
// }
//
// public FragmentActivity activity() {
// return fragment() != null ? fragment().getActivity() : (FragmentActivity) ui;
// }
//
// @Nullable
// public Fragment fragment() {
// if (ui instanceof Fragment) {
// return (Fragment) ui;
// }
// return null;
// }
//
// public Object ui() {
// return ui;
// }
//
// public void setUi(Object ui) {
// this.ui = ui;
// }
//
// public Context getContext() {
// return fragment() == null ? activity() : fragment().getContext();
// }
// }
//
// Path: rx_paparazzo/src/main/java/com/miguelbcr/ui/rx_paparazzo2/entities/UserCanceledException.java
// public class UserCanceledException extends RuntimeException {
// }
| import android.app.Activity;
import com.miguelbcr.ui.rx_paparazzo2.entities.PermissionDeniedException;
import com.miguelbcr.ui.rx_paparazzo2.entities.Response;
import com.miguelbcr.ui.rx_paparazzo2.entities.TargetUi;
import com.miguelbcr.ui.rx_paparazzo2.entities.UserCanceledException;
import io.reactivex.Observable;
import io.reactivex.ObservableSource;
import io.reactivex.ObservableTransformer;
import io.reactivex.exceptions.Exceptions;
import io.reactivex.functions.Function; | /*
* Copyright 2016 Miguel Garcia
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.miguelbcr.ui.rx_paparazzo2.workers;
abstract class Worker {
private final TargetUi targetUi;
public Worker(TargetUi targetUi) {
this.targetUi = targetUi;
}
@SuppressWarnings("unchecked") protected <T> ObservableTransformer<T, T> applyOnError() {
return new ObservableTransformer<T, T>() {
@Override public ObservableSource<T> apply(Observable<T> observable) {
return observable.onErrorResumeNext(
new Function<Throwable, ObservableSource<? extends T>>() {
@Override public ObservableSource<? extends T> apply(Throwable throwable)
throws Exception {
if (throwable instanceof UserCanceledException) {
return Observable.just(
(T) new Response(targetUi.ui(), null, Activity.RESULT_CANCELED)); | // Path: rx_paparazzo/src/main/java/com/miguelbcr/ui/rx_paparazzo2/entities/PermissionDeniedException.java
// public class PermissionDeniedException extends RuntimeException {
// private int code;
//
// public PermissionDeniedException(int code) {
// this.code = code;
// }
//
// public int getCode() {
// return code;
// }
// }
//
// Path: rx_paparazzo/src/main/java/com/miguelbcr/ui/rx_paparazzo2/entities/Response.java
// public class Response<T, D> {
// private final T targetUI;
// private final D data;
// private final int resultCode;
//
// public Response(T targetUI, D data, int resultCode) {
// this.targetUI = targetUI;
// this.data = data;
// this.resultCode = resultCode;
// }
//
// public T targetUI() {
// return targetUI;
// }
//
// public D data() {
// return data;
// }
//
// /**
// * @return <ul>
// * <li>{@link Activity#RESULT_OK}</li>
// * <li>{@link Activity#RESULT_CANCELED}</li>
// * <li>{@link RxPaparazzo#RESULT_DENIED_PERMISSION}</li>
// * <li>{@link RxPaparazzo#RESULT_DENIED_PERMISSION_NEVER_ASK}</li>
// * </ul>
// */
// public int resultCode() {
// return resultCode;
// }
// }
//
// Path: rx_paparazzo/src/main/java/com/miguelbcr/ui/rx_paparazzo2/entities/TargetUi.java
// public class TargetUi {
// private Object ui;
//
// public TargetUi(Object ui) {
// this.ui = ui;
// }
//
// public FragmentActivity activity() {
// return fragment() != null ? fragment().getActivity() : (FragmentActivity) ui;
// }
//
// @Nullable
// public Fragment fragment() {
// if (ui instanceof Fragment) {
// return (Fragment) ui;
// }
// return null;
// }
//
// public Object ui() {
// return ui;
// }
//
// public void setUi(Object ui) {
// this.ui = ui;
// }
//
// public Context getContext() {
// return fragment() == null ? activity() : fragment().getContext();
// }
// }
//
// Path: rx_paparazzo/src/main/java/com/miguelbcr/ui/rx_paparazzo2/entities/UserCanceledException.java
// public class UserCanceledException extends RuntimeException {
// }
// Path: rx_paparazzo/src/main/java/com/miguelbcr/ui/rx_paparazzo2/workers/Worker.java
import android.app.Activity;
import com.miguelbcr.ui.rx_paparazzo2.entities.PermissionDeniedException;
import com.miguelbcr.ui.rx_paparazzo2.entities.Response;
import com.miguelbcr.ui.rx_paparazzo2.entities.TargetUi;
import com.miguelbcr.ui.rx_paparazzo2.entities.UserCanceledException;
import io.reactivex.Observable;
import io.reactivex.ObservableSource;
import io.reactivex.ObservableTransformer;
import io.reactivex.exceptions.Exceptions;
import io.reactivex.functions.Function;
/*
* Copyright 2016 Miguel Garcia
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.miguelbcr.ui.rx_paparazzo2.workers;
abstract class Worker {
private final TargetUi targetUi;
public Worker(TargetUi targetUi) {
this.targetUi = targetUi;
}
@SuppressWarnings("unchecked") protected <T> ObservableTransformer<T, T> applyOnError() {
return new ObservableTransformer<T, T>() {
@Override public ObservableSource<T> apply(Observable<T> observable) {
return observable.onErrorResumeNext(
new Function<Throwable, ObservableSource<? extends T>>() {
@Override public ObservableSource<? extends T> apply(Throwable throwable)
throws Exception {
if (throwable instanceof UserCanceledException) {
return Observable.just(
(T) new Response(targetUi.ui(), null, Activity.RESULT_CANCELED)); | } else if (throwable instanceof PermissionDeniedException) { |
miguelbcr/RxPaparazzo | rx_paparazzo/src/main/java/com/miguelbcr/ui/rx_paparazzo2/entities/Config.java | // Path: rx_paparazzo/src/main/java/com/miguelbcr/ui/rx_paparazzo2/entities/size/ScreenSize.java
// public class ScreenSize implements Size {
// }
//
// Path: rx_paparazzo/src/main/java/com/miguelbcr/ui/rx_paparazzo2/entities/size/Size.java
// public interface Size {
// }
| import android.content.Context;
import com.miguelbcr.ui.rx_paparazzo2.entities.size.ScreenSize;
import com.miguelbcr.ui.rx_paparazzo2.entities.size.Size;
import com.yalantis.ucrop.UCrop; | /*
* Copyright 2016 Miguel Garcia
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.miguelbcr.ui.rx_paparazzo2.entities;
public class Config {
private static final String DEFAULT_FILE_PROVIDER_PATH = "RxPaparazzo";
private static final String DEFAULT_FILE_PROVIDER_AUTHORITIES_SUFFIX = "file_provider";
private static final long NO_FILESIZE_LIMIT = Long.MAX_VALUE;
private UCrop.Options options;
private long maximumFileSize; | // Path: rx_paparazzo/src/main/java/com/miguelbcr/ui/rx_paparazzo2/entities/size/ScreenSize.java
// public class ScreenSize implements Size {
// }
//
// Path: rx_paparazzo/src/main/java/com/miguelbcr/ui/rx_paparazzo2/entities/size/Size.java
// public interface Size {
// }
// Path: rx_paparazzo/src/main/java/com/miguelbcr/ui/rx_paparazzo2/entities/Config.java
import android.content.Context;
import com.miguelbcr.ui.rx_paparazzo2.entities.size.ScreenSize;
import com.miguelbcr.ui.rx_paparazzo2.entities.size.Size;
import com.yalantis.ucrop.UCrop;
/*
* Copyright 2016 Miguel Garcia
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.miguelbcr.ui.rx_paparazzo2.entities;
public class Config {
private static final String DEFAULT_FILE_PROVIDER_PATH = "RxPaparazzo";
private static final String DEFAULT_FILE_PROVIDER_AUTHORITIES_SUFFIX = "file_provider";
private static final long NO_FILESIZE_LIMIT = Long.MAX_VALUE;
private UCrop.Options options;
private long maximumFileSize; | private Size size; |
miguelbcr/RxPaparazzo | rx_paparazzo/src/main/java/com/miguelbcr/ui/rx_paparazzo2/entities/Config.java | // Path: rx_paparazzo/src/main/java/com/miguelbcr/ui/rx_paparazzo2/entities/size/ScreenSize.java
// public class ScreenSize implements Size {
// }
//
// Path: rx_paparazzo/src/main/java/com/miguelbcr/ui/rx_paparazzo2/entities/size/Size.java
// public interface Size {
// }
| import android.content.Context;
import com.miguelbcr.ui.rx_paparazzo2.entities.size.ScreenSize;
import com.miguelbcr.ui.rx_paparazzo2.entities.size.Size;
import com.yalantis.ucrop.UCrop; | /*
* Copyright 2016 Miguel Garcia
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.miguelbcr.ui.rx_paparazzo2.entities;
public class Config {
private static final String DEFAULT_FILE_PROVIDER_PATH = "RxPaparazzo";
private static final String DEFAULT_FILE_PROVIDER_AUTHORITIES_SUFFIX = "file_provider";
private static final long NO_FILESIZE_LIMIT = Long.MAX_VALUE;
private UCrop.Options options;
private long maximumFileSize;
private Size size;
private boolean doCrop;
private boolean failCropIfNotImage;
private boolean useInternalStorage;
private String pickMimeType;
private String[] pickMultipleMimeTypes;
private boolean pickOpenableOnly;
private boolean useDocumentPicker;
private boolean sendToMediaScanner;
private String fileProviderAuthority;
private String fileProviderDirectory;
public Config() { | // Path: rx_paparazzo/src/main/java/com/miguelbcr/ui/rx_paparazzo2/entities/size/ScreenSize.java
// public class ScreenSize implements Size {
// }
//
// Path: rx_paparazzo/src/main/java/com/miguelbcr/ui/rx_paparazzo2/entities/size/Size.java
// public interface Size {
// }
// Path: rx_paparazzo/src/main/java/com/miguelbcr/ui/rx_paparazzo2/entities/Config.java
import android.content.Context;
import com.miguelbcr.ui.rx_paparazzo2.entities.size.ScreenSize;
import com.miguelbcr.ui.rx_paparazzo2.entities.size.Size;
import com.yalantis.ucrop.UCrop;
/*
* Copyright 2016 Miguel Garcia
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.miguelbcr.ui.rx_paparazzo2.entities;
public class Config {
private static final String DEFAULT_FILE_PROVIDER_PATH = "RxPaparazzo";
private static final String DEFAULT_FILE_PROVIDER_AUTHORITIES_SUFFIX = "file_provider";
private static final long NO_FILESIZE_LIMIT = Long.MAX_VALUE;
private UCrop.Options options;
private long maximumFileSize;
private Size size;
private boolean doCrop;
private boolean failCropIfNotImage;
private boolean useInternalStorage;
private String pickMimeType;
private String[] pickMultipleMimeTypes;
private boolean pickOpenableOnly;
private boolean useDocumentPicker;
private boolean sendToMediaScanner;
private String fileProviderAuthority;
private String fileProviderDirectory;
public Config() { | this.size = new ScreenSize(); |
miguelbcr/RxPaparazzo | rx_paparazzo/src/main/java/com/miguelbcr/ui/rx_paparazzo2/interactors/StartIntent.java | // Path: rx_paparazzo/src/main/java/com/miguelbcr/ui/rx_paparazzo2/entities/TargetUi.java
// public class TargetUi {
// private Object ui;
//
// public TargetUi(Object ui) {
// this.ui = ui;
// }
//
// public FragmentActivity activity() {
// return fragment() != null ? fragment().getActivity() : (FragmentActivity) ui;
// }
//
// @Nullable
// public Fragment fragment() {
// if (ui instanceof Fragment) {
// return (Fragment) ui;
// }
// return null;
// }
//
// public Object ui() {
// return ui;
// }
//
// public void setUi(Object ui) {
// this.ui = ui;
// }
//
// public Context getContext() {
// return fragment() == null ? activity() : fragment().getContext();
// }
// }
//
// Path: rx_paparazzo/src/main/java/com/miguelbcr/ui/rx_paparazzo2/entities/UserCanceledException.java
// public class UserCanceledException extends RuntimeException {
// }
| import android.app.Activity;
import android.content.Intent;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentActivity;
import com.miguelbcr.ui.rx_paparazzo2.entities.TargetUi;
import com.miguelbcr.ui.rx_paparazzo2.entities.UserCanceledException;
import io.reactivex.Observable;
import io.reactivex.functions.Function;
import rx_activity_result2.OnPreResult;
import rx_activity_result2.Result;
import rx_activity_result2.RxActivityResult; | StartIntent with(Intent intent, OnPreResult onPreResult) {
this.intent = intent;
this.onPreResult = onPreResult;
return this;
}
@Override public Observable<Intent> react() {
final Fragment fragment = targetUi.fragment();
if (fragment != null) {
return RxActivityResult.on(fragment)
.startIntent(intent, onPreResult)
.map(new Function<Result<Fragment>, Intent>() {
@Override public Intent apply(Result<Fragment> result) throws Exception {
return StartIntent.this.getResponse(result);
}
});
} else {
return RxActivityResult.on(targetUi.activity())
.startIntent(intent, onPreResult)
.map(new Function<Result<FragmentActivity>, Intent>() {
@Override public Intent apply(Result<FragmentActivity> result) throws Exception {
return StartIntent.this.getResponse(result);
}
});
}
}
private Intent getResponse(Result result) {
targetUi.setUi(result.targetUI());
if (result.resultCode() != Activity.RESULT_OK) { | // Path: rx_paparazzo/src/main/java/com/miguelbcr/ui/rx_paparazzo2/entities/TargetUi.java
// public class TargetUi {
// private Object ui;
//
// public TargetUi(Object ui) {
// this.ui = ui;
// }
//
// public FragmentActivity activity() {
// return fragment() != null ? fragment().getActivity() : (FragmentActivity) ui;
// }
//
// @Nullable
// public Fragment fragment() {
// if (ui instanceof Fragment) {
// return (Fragment) ui;
// }
// return null;
// }
//
// public Object ui() {
// return ui;
// }
//
// public void setUi(Object ui) {
// this.ui = ui;
// }
//
// public Context getContext() {
// return fragment() == null ? activity() : fragment().getContext();
// }
// }
//
// Path: rx_paparazzo/src/main/java/com/miguelbcr/ui/rx_paparazzo2/entities/UserCanceledException.java
// public class UserCanceledException extends RuntimeException {
// }
// Path: rx_paparazzo/src/main/java/com/miguelbcr/ui/rx_paparazzo2/interactors/StartIntent.java
import android.app.Activity;
import android.content.Intent;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentActivity;
import com.miguelbcr.ui.rx_paparazzo2.entities.TargetUi;
import com.miguelbcr.ui.rx_paparazzo2.entities.UserCanceledException;
import io.reactivex.Observable;
import io.reactivex.functions.Function;
import rx_activity_result2.OnPreResult;
import rx_activity_result2.Result;
import rx_activity_result2.RxActivityResult;
StartIntent with(Intent intent, OnPreResult onPreResult) {
this.intent = intent;
this.onPreResult = onPreResult;
return this;
}
@Override public Observable<Intent> react() {
final Fragment fragment = targetUi.fragment();
if (fragment != null) {
return RxActivityResult.on(fragment)
.startIntent(intent, onPreResult)
.map(new Function<Result<Fragment>, Intent>() {
@Override public Intent apply(Result<Fragment> result) throws Exception {
return StartIntent.this.getResponse(result);
}
});
} else {
return RxActivityResult.on(targetUi.activity())
.startIntent(intent, onPreResult)
.map(new Function<Result<FragmentActivity>, Intent>() {
@Override public Intent apply(Result<FragmentActivity> result) throws Exception {
return StartIntent.this.getResponse(result);
}
});
}
}
private Intent getResponse(Result result) {
targetUi.setUi(result.targetUI());
if (result.resultCode() != Activity.RESULT_OK) { | throw new UserCanceledException(); |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.