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
idisfkj/HightCopyWX
app/src/main/java/com/idisfkj/hightcopywx/main/FragmentFactory.java
// Path: app/src/main/java/com/idisfkj/hightcopywx/contact/ContactFragment.java // public class ContactFragment extends Fragment { // // @Nullable // @Override // public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // View view = LayoutInflater.from(getContext()).inflate(R.layout.contact_layout, null); // return view; // } // // @Override // public void onDestroyView() { // super.onDestroyView(); // } // } // // Path: app/src/main/java/com/idisfkj/hightcopywx/find/FindFragment.java // public class FindFragment extends Fragment{ // // @Nullable // @Override // public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // View view = LayoutInflater.from(getContext()).inflate(R.layout.find_layout,null); // return view; // } // } // // Path: app/src/main/java/com/idisfkj/hightcopywx/me/MeFragment.java // public class MeFragment extends Fragment{ // // @Nullable // @Override // public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // View view = LayoutInflater.from(getContext()).inflate(R.layout.me_layout,null); // return view; // } // } // // Path: app/src/main/java/com/idisfkj/hightcopywx/wx/widget/WXFragment.java // public class WXFragment extends Fragment implements WXView, LoaderManager.LoaderCallbacks<Cursor> { // @InjectView(R.id.wx_recyclerView) // RecyclerView wxRecyclerView; // private WXAdapter wxAdapter; // private WXPresent mWXPresent; // private WXDataHelper mHelper; // // @Nullable // @Override // public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // View view = LayoutInflater.from(getContext()).inflate(R.layout.wx_layout, null); // ButterKnife.inject(this, view); // init(); // return view; // } // // public void init() { // wxAdapter = new WXAdapter(getContext()); // mWXPresent = new WXPresentImp(this); // wxRecyclerView.setLayoutManager(new LinearLayoutManager(getContext())); // wxRecyclerView.addItemDecoration(new WXItemDecoration(getContext())); // wxRecyclerView.setAdapter(wxAdapter); // wxRecyclerView.addOnItemTouchListener(new OnItemTouchListener(wxRecyclerView) { // @Override // public void onItemListener(RecyclerView.ViewHolder vh) { // Intent intent = new Intent(getActivity(), ChatActivity.class); // Bundle bundle = new Bundle(); // bundle.putInt("_id", vh.getLayoutPosition()+1); // intent.putExtras(bundle); // startActivity(intent); // } // }); // mHelper = new WXDataHelper(getContext()); // getLoaderManager().initLoader(0, null, this); // } // // @Override // public void onDestroyView() { // super.onDestroyView(); // ButterKnife.reset(this); // } // // @Override // public Loader<Cursor> onCreateLoader(int id, Bundle args) { // return mHelper.getCursorLoader(SPUtils.getString("userPhone")); // } // // @Override // public void onLoadFinished(Loader<Cursor> loader, Cursor data) { // if (loader != null && data.getCount() <= 0) { // mWXPresent.initData(mHelper); // } // wxAdapter.changeCursor(data); // } // // @Override // public void onLoaderReset(Loader<Cursor> loader) { // wxAdapter.changeCursor(null); // } // }
import android.support.v4.app.Fragment; import com.idisfkj.hightcopywx.contact.ContactFragment; import com.idisfkj.hightcopywx.find.FindFragment; import com.idisfkj.hightcopywx.me.MeFragment; import com.idisfkj.hightcopywx.wx.widget.WXFragment;
package com.idisfkj.hightcopywx.main; /** * Fragment工厂 * Created by idisfkj on 16/4/19. * Email : [email protected]. */ public class FragmentFactory { private Fragment mFragment; private int mSize; public FragmentFactory(int size) { mSize = size; } public int getSize(){ return mSize; } public Fragment createFragment(int position){ switch (position){ case 0: mFragment = new WXFragment(); break; case 1: mFragment = new ContactFragment(); break; case 2:
// Path: app/src/main/java/com/idisfkj/hightcopywx/contact/ContactFragment.java // public class ContactFragment extends Fragment { // // @Nullable // @Override // public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // View view = LayoutInflater.from(getContext()).inflate(R.layout.contact_layout, null); // return view; // } // // @Override // public void onDestroyView() { // super.onDestroyView(); // } // } // // Path: app/src/main/java/com/idisfkj/hightcopywx/find/FindFragment.java // public class FindFragment extends Fragment{ // // @Nullable // @Override // public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // View view = LayoutInflater.from(getContext()).inflate(R.layout.find_layout,null); // return view; // } // } // // Path: app/src/main/java/com/idisfkj/hightcopywx/me/MeFragment.java // public class MeFragment extends Fragment{ // // @Nullable // @Override // public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // View view = LayoutInflater.from(getContext()).inflate(R.layout.me_layout,null); // return view; // } // } // // Path: app/src/main/java/com/idisfkj/hightcopywx/wx/widget/WXFragment.java // public class WXFragment extends Fragment implements WXView, LoaderManager.LoaderCallbacks<Cursor> { // @InjectView(R.id.wx_recyclerView) // RecyclerView wxRecyclerView; // private WXAdapter wxAdapter; // private WXPresent mWXPresent; // private WXDataHelper mHelper; // // @Nullable // @Override // public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // View view = LayoutInflater.from(getContext()).inflate(R.layout.wx_layout, null); // ButterKnife.inject(this, view); // init(); // return view; // } // // public void init() { // wxAdapter = new WXAdapter(getContext()); // mWXPresent = new WXPresentImp(this); // wxRecyclerView.setLayoutManager(new LinearLayoutManager(getContext())); // wxRecyclerView.addItemDecoration(new WXItemDecoration(getContext())); // wxRecyclerView.setAdapter(wxAdapter); // wxRecyclerView.addOnItemTouchListener(new OnItemTouchListener(wxRecyclerView) { // @Override // public void onItemListener(RecyclerView.ViewHolder vh) { // Intent intent = new Intent(getActivity(), ChatActivity.class); // Bundle bundle = new Bundle(); // bundle.putInt("_id", vh.getLayoutPosition()+1); // intent.putExtras(bundle); // startActivity(intent); // } // }); // mHelper = new WXDataHelper(getContext()); // getLoaderManager().initLoader(0, null, this); // } // // @Override // public void onDestroyView() { // super.onDestroyView(); // ButterKnife.reset(this); // } // // @Override // public Loader<Cursor> onCreateLoader(int id, Bundle args) { // return mHelper.getCursorLoader(SPUtils.getString("userPhone")); // } // // @Override // public void onLoadFinished(Loader<Cursor> loader, Cursor data) { // if (loader != null && data.getCount() <= 0) { // mWXPresent.initData(mHelper); // } // wxAdapter.changeCursor(data); // } // // @Override // public void onLoaderReset(Loader<Cursor> loader) { // wxAdapter.changeCursor(null); // } // } // Path: app/src/main/java/com/idisfkj/hightcopywx/main/FragmentFactory.java import android.support.v4.app.Fragment; import com.idisfkj.hightcopywx.contact.ContactFragment; import com.idisfkj.hightcopywx.find.FindFragment; import com.idisfkj.hightcopywx.me.MeFragment; import com.idisfkj.hightcopywx.wx.widget.WXFragment; package com.idisfkj.hightcopywx.main; /** * Fragment工厂 * Created by idisfkj on 16/4/19. * Email : [email protected]. */ public class FragmentFactory { private Fragment mFragment; private int mSize; public FragmentFactory(int size) { mSize = size; } public int getSize(){ return mSize; } public Fragment createFragment(int position){ switch (position){ case 0: mFragment = new WXFragment(); break; case 1: mFragment = new ContactFragment(); break; case 2:
mFragment = new FindFragment();
idisfkj/HightCopyWX
app/src/main/java/com/idisfkj/hightcopywx/main/FragmentFactory.java
// Path: app/src/main/java/com/idisfkj/hightcopywx/contact/ContactFragment.java // public class ContactFragment extends Fragment { // // @Nullable // @Override // public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // View view = LayoutInflater.from(getContext()).inflate(R.layout.contact_layout, null); // return view; // } // // @Override // public void onDestroyView() { // super.onDestroyView(); // } // } // // Path: app/src/main/java/com/idisfkj/hightcopywx/find/FindFragment.java // public class FindFragment extends Fragment{ // // @Nullable // @Override // public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // View view = LayoutInflater.from(getContext()).inflate(R.layout.find_layout,null); // return view; // } // } // // Path: app/src/main/java/com/idisfkj/hightcopywx/me/MeFragment.java // public class MeFragment extends Fragment{ // // @Nullable // @Override // public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // View view = LayoutInflater.from(getContext()).inflate(R.layout.me_layout,null); // return view; // } // } // // Path: app/src/main/java/com/idisfkj/hightcopywx/wx/widget/WXFragment.java // public class WXFragment extends Fragment implements WXView, LoaderManager.LoaderCallbacks<Cursor> { // @InjectView(R.id.wx_recyclerView) // RecyclerView wxRecyclerView; // private WXAdapter wxAdapter; // private WXPresent mWXPresent; // private WXDataHelper mHelper; // // @Nullable // @Override // public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // View view = LayoutInflater.from(getContext()).inflate(R.layout.wx_layout, null); // ButterKnife.inject(this, view); // init(); // return view; // } // // public void init() { // wxAdapter = new WXAdapter(getContext()); // mWXPresent = new WXPresentImp(this); // wxRecyclerView.setLayoutManager(new LinearLayoutManager(getContext())); // wxRecyclerView.addItemDecoration(new WXItemDecoration(getContext())); // wxRecyclerView.setAdapter(wxAdapter); // wxRecyclerView.addOnItemTouchListener(new OnItemTouchListener(wxRecyclerView) { // @Override // public void onItemListener(RecyclerView.ViewHolder vh) { // Intent intent = new Intent(getActivity(), ChatActivity.class); // Bundle bundle = new Bundle(); // bundle.putInt("_id", vh.getLayoutPosition()+1); // intent.putExtras(bundle); // startActivity(intent); // } // }); // mHelper = new WXDataHelper(getContext()); // getLoaderManager().initLoader(0, null, this); // } // // @Override // public void onDestroyView() { // super.onDestroyView(); // ButterKnife.reset(this); // } // // @Override // public Loader<Cursor> onCreateLoader(int id, Bundle args) { // return mHelper.getCursorLoader(SPUtils.getString("userPhone")); // } // // @Override // public void onLoadFinished(Loader<Cursor> loader, Cursor data) { // if (loader != null && data.getCount() <= 0) { // mWXPresent.initData(mHelper); // } // wxAdapter.changeCursor(data); // } // // @Override // public void onLoaderReset(Loader<Cursor> loader) { // wxAdapter.changeCursor(null); // } // }
import android.support.v4.app.Fragment; import com.idisfkj.hightcopywx.contact.ContactFragment; import com.idisfkj.hightcopywx.find.FindFragment; import com.idisfkj.hightcopywx.me.MeFragment; import com.idisfkj.hightcopywx.wx.widget.WXFragment;
package com.idisfkj.hightcopywx.main; /** * Fragment工厂 * Created by idisfkj on 16/4/19. * Email : [email protected]. */ public class FragmentFactory { private Fragment mFragment; private int mSize; public FragmentFactory(int size) { mSize = size; } public int getSize(){ return mSize; } public Fragment createFragment(int position){ switch (position){ case 0: mFragment = new WXFragment(); break; case 1: mFragment = new ContactFragment(); break; case 2: mFragment = new FindFragment(); break; case 3:
// Path: app/src/main/java/com/idisfkj/hightcopywx/contact/ContactFragment.java // public class ContactFragment extends Fragment { // // @Nullable // @Override // public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // View view = LayoutInflater.from(getContext()).inflate(R.layout.contact_layout, null); // return view; // } // // @Override // public void onDestroyView() { // super.onDestroyView(); // } // } // // Path: app/src/main/java/com/idisfkj/hightcopywx/find/FindFragment.java // public class FindFragment extends Fragment{ // // @Nullable // @Override // public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // View view = LayoutInflater.from(getContext()).inflate(R.layout.find_layout,null); // return view; // } // } // // Path: app/src/main/java/com/idisfkj/hightcopywx/me/MeFragment.java // public class MeFragment extends Fragment{ // // @Nullable // @Override // public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // View view = LayoutInflater.from(getContext()).inflate(R.layout.me_layout,null); // return view; // } // } // // Path: app/src/main/java/com/idisfkj/hightcopywx/wx/widget/WXFragment.java // public class WXFragment extends Fragment implements WXView, LoaderManager.LoaderCallbacks<Cursor> { // @InjectView(R.id.wx_recyclerView) // RecyclerView wxRecyclerView; // private WXAdapter wxAdapter; // private WXPresent mWXPresent; // private WXDataHelper mHelper; // // @Nullable // @Override // public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // View view = LayoutInflater.from(getContext()).inflate(R.layout.wx_layout, null); // ButterKnife.inject(this, view); // init(); // return view; // } // // public void init() { // wxAdapter = new WXAdapter(getContext()); // mWXPresent = new WXPresentImp(this); // wxRecyclerView.setLayoutManager(new LinearLayoutManager(getContext())); // wxRecyclerView.addItemDecoration(new WXItemDecoration(getContext())); // wxRecyclerView.setAdapter(wxAdapter); // wxRecyclerView.addOnItemTouchListener(new OnItemTouchListener(wxRecyclerView) { // @Override // public void onItemListener(RecyclerView.ViewHolder vh) { // Intent intent = new Intent(getActivity(), ChatActivity.class); // Bundle bundle = new Bundle(); // bundle.putInt("_id", vh.getLayoutPosition()+1); // intent.putExtras(bundle); // startActivity(intent); // } // }); // mHelper = new WXDataHelper(getContext()); // getLoaderManager().initLoader(0, null, this); // } // // @Override // public void onDestroyView() { // super.onDestroyView(); // ButterKnife.reset(this); // } // // @Override // public Loader<Cursor> onCreateLoader(int id, Bundle args) { // return mHelper.getCursorLoader(SPUtils.getString("userPhone")); // } // // @Override // public void onLoadFinished(Loader<Cursor> loader, Cursor data) { // if (loader != null && data.getCount() <= 0) { // mWXPresent.initData(mHelper); // } // wxAdapter.changeCursor(data); // } // // @Override // public void onLoaderReset(Loader<Cursor> loader) { // wxAdapter.changeCursor(null); // } // } // Path: app/src/main/java/com/idisfkj/hightcopywx/main/FragmentFactory.java import android.support.v4.app.Fragment; import com.idisfkj.hightcopywx.contact.ContactFragment; import com.idisfkj.hightcopywx.find.FindFragment; import com.idisfkj.hightcopywx.me.MeFragment; import com.idisfkj.hightcopywx.wx.widget.WXFragment; package com.idisfkj.hightcopywx.main; /** * Fragment工厂 * Created by idisfkj on 16/4/19. * Email : [email protected]. */ public class FragmentFactory { private Fragment mFragment; private int mSize; public FragmentFactory(int size) { mSize = size; } public int getSize(){ return mSize; } public Fragment createFragment(int position){ switch (position){ case 0: mFragment = new WXFragment(); break; case 1: mFragment = new ContactFragment(); break; case 2: mFragment = new FindFragment(); break; case 3:
mFragment = new MeFragment();
idisfkj/HightCopyWX
app/src/main/java/com/idisfkj/hightcopywx/util/ToastUtils.java
// Path: app/src/main/java/com/idisfkj/hightcopywx/App.java // public class App extends Application{ // private static Context mContext; // public static final String APP_ID = "2882303761517464903"; // public static final String APP_KEY = "5631746467903"; // public static final String APP_SECRET_KEY = "HxMA7STSUQMLEiDX+zo+5A=="; // public static final String TAG = "com.idisfkj.hightcopywx"; // public static final String DEVELOPER_ID = "/f6ukNwIPpdSmkrgsmklcMbW6WefG01XkxdILDNEUVw="; // public static final String DEVELOPER_NUMBER = "666666"; // public static final String DEVELOPER_NAME = "idisfkj"; // public static final String DEVELOPER_MESSAGE = "欢迎注册高仿微信App,我是该App的开发者,你可以使用添加朋友自行互动测试!如有问题可以在此留言与我。"; // public static final String HELLO_MESSAGE = "你已添加了%s,现在可以开始聊天了"; // public static final String UNREADNUM = "unReadNum"; // public static String mNumber = "-1"; // public static String mRegId = "-1"; // public static SharedPreferences sp; // public static SharedPreferences.Editor editor; // // // @Override // public void onCreate() { // super.onCreate(); // mContext = getApplicationContext(); // sp = getSharedPreferences("userInfo",Context.MODE_PRIVATE); // // //初始化push推送服务 // if(shouldInit()) { // MiPushClient.registerPush(this, APP_ID, APP_KEY); // } // // //小米推送调试日记 // LoggerInterface newLogger = new LoggerInterface() { // @Override // public void setTag(String tag) { // // ignore // } // @Override // public void log(String content, Throwable t) { // Log.d(TAG, content, t); // } // @Override // public void log(String content) { // Log.d(TAG, content); // } // }; // Logger.setLogger(this, newLogger); // // } // // private boolean shouldInit() { // ActivityManager am = ((ActivityManager) getSystemService(Context.ACTIVITY_SERVICE)); // List<ActivityManager.RunningAppProcessInfo> processInfos = am.getRunningAppProcesses(); // String mainProcessName = getPackageName(); // int myPid = android.os.Process.myPid(); // for (ActivityManager.RunningAppProcessInfo info : processInfos) { // if (info.pid == myPid && mainProcessName.equals(info.processName)) { // return true; // } // } // return false; // } // // public static Context getAppContext(){ // return mContext; // } // }
import android.widget.Toast; import com.idisfkj.hightcopywx.App;
package com.idisfkj.hightcopywx.util; /** * Toast工具类 * Created by idisfkj on 16/4/21. * Email : [email protected]. */ public class ToastUtils { public ToastUtils() { } public static void showShort(CharSequence text){
// Path: app/src/main/java/com/idisfkj/hightcopywx/App.java // public class App extends Application{ // private static Context mContext; // public static final String APP_ID = "2882303761517464903"; // public static final String APP_KEY = "5631746467903"; // public static final String APP_SECRET_KEY = "HxMA7STSUQMLEiDX+zo+5A=="; // public static final String TAG = "com.idisfkj.hightcopywx"; // public static final String DEVELOPER_ID = "/f6ukNwIPpdSmkrgsmklcMbW6WefG01XkxdILDNEUVw="; // public static final String DEVELOPER_NUMBER = "666666"; // public static final String DEVELOPER_NAME = "idisfkj"; // public static final String DEVELOPER_MESSAGE = "欢迎注册高仿微信App,我是该App的开发者,你可以使用添加朋友自行互动测试!如有问题可以在此留言与我。"; // public static final String HELLO_MESSAGE = "你已添加了%s,现在可以开始聊天了"; // public static final String UNREADNUM = "unReadNum"; // public static String mNumber = "-1"; // public static String mRegId = "-1"; // public static SharedPreferences sp; // public static SharedPreferences.Editor editor; // // // @Override // public void onCreate() { // super.onCreate(); // mContext = getApplicationContext(); // sp = getSharedPreferences("userInfo",Context.MODE_PRIVATE); // // //初始化push推送服务 // if(shouldInit()) { // MiPushClient.registerPush(this, APP_ID, APP_KEY); // } // // //小米推送调试日记 // LoggerInterface newLogger = new LoggerInterface() { // @Override // public void setTag(String tag) { // // ignore // } // @Override // public void log(String content, Throwable t) { // Log.d(TAG, content, t); // } // @Override // public void log(String content) { // Log.d(TAG, content); // } // }; // Logger.setLogger(this, newLogger); // // } // // private boolean shouldInit() { // ActivityManager am = ((ActivityManager) getSystemService(Context.ACTIVITY_SERVICE)); // List<ActivityManager.RunningAppProcessInfo> processInfos = am.getRunningAppProcesses(); // String mainProcessName = getPackageName(); // int myPid = android.os.Process.myPid(); // for (ActivityManager.RunningAppProcessInfo info : processInfos) { // if (info.pid == myPid && mainProcessName.equals(info.processName)) { // return true; // } // } // return false; // } // // public static Context getAppContext(){ // return mContext; // } // } // Path: app/src/main/java/com/idisfkj/hightcopywx/util/ToastUtils.java import android.widget.Toast; import com.idisfkj.hightcopywx.App; package com.idisfkj.hightcopywx.util; /** * Toast工具类 * Created by idisfkj on 16/4/21. * Email : [email protected]. */ public class ToastUtils { public ToastUtils() { } public static void showShort(CharSequence text){
Toast.makeText(App.getAppContext(),text,Toast.LENGTH_SHORT).show();
idisfkj/HightCopyWX
app/src/main/java/com/idisfkj/hightcopywx/ui/presenter/RegisterPresenterImp.java
// Path: app/src/main/java/com/idisfkj/hightcopywx/ui/model/RegisterModel.java // public interface RegisterModel { // void saveData(RegisterModelImp.saveDataListener listener, EditText... editTexts); // // void sendAll(RegisterModelImp.sendAllListener listener, String userName, String number); // } // // Path: app/src/main/java/com/idisfkj/hightcopywx/ui/model/RegisterModelImp.java // public class RegisterModelImp implements RegisterModel { // private String[] user; // // @Override // public void saveData(saveDataListener listener, EditText... editTexts) { // user = new String[editTexts.length]; // for (int i = 0; i < editTexts.length; i++) { // user[i] = editTexts[i].getText().toString().trim(); // if (user[i].length() <= 0) { // ToastUtils.showShort("昵称、号码或密码不能为空"); // return; // } // } // SPUtils.putString("userName", user[0]) // .putString("userPhone", user[1]) // .putString("userPassword", user[2]) // .commit(); // listener.onSucceed(user[0], user[1]); // } // // @Override // public void sendAll(final sendAllListener listener, String userName, String number) { // JsonObjectRequest request = new JsonObjectRequest(Request.Method.POST, UrlUtils.registerUrl(userName, number) // , null, new Response.Listener<JSONObject>() { // @Override // public void onResponse(JSONObject jsonObject) { // listener.onSendSucceed(); // } // }, new Response.ErrorListener() { // @Override // public void onErrorResponse(VolleyError volleyError) { // listener.onError(); // } // }) { // @Override // public Map<String, String> getHeaders() throws AuthFailureError { // HashMap<String, String> header = new HashMap<>(); // header.put("Authorization", "key=" + App.APP_SECRET_KEY); // return header; // } // }; // VolleyUtils.addQueue(request, "registerRequest"); // } // // public interface saveDataListener { // void onSucceed(String userName, String number); // } // // public interface sendAllListener { // void onSendSucceed(); // // void onError(); // } // } // // Path: app/src/main/java/com/idisfkj/hightcopywx/ui/view/RegisterView.java // public interface RegisterView { // void changeUserNameLine(boolean hasFocus); // // void changeUserPhoneLine(boolean hasFocus); // // void changeUserPasswordLine(boolean hasFocus); // // void jumpMainActivity(); // // void showAlertDialog(); // // void startCrop(Uri uri); // // void setHeadPicture(Intent intent); // // void saveHeadPicture(Bitmap bitmap); // // void showProgressDialog(); // // void hideProgressDialog(); // // void showErrorToast(); // // void showSucceedToast(); // }
import android.content.Intent; import android.graphics.Bitmap; import android.net.Uri; import android.widget.EditText; import com.idisfkj.hightcopywx.R; import com.idisfkj.hightcopywx.ui.model.RegisterModel; import com.idisfkj.hightcopywx.ui.model.RegisterModelImp; import com.idisfkj.hightcopywx.ui.view.RegisterView;
package com.idisfkj.hightcopywx.ui.presenter; /** * Created by idisfkj on 16/4/28. * Email : [email protected]. */ public class RegisterPresenterImp implements RegisterPresenter, RegisterModelImp.saveDataListener, RegisterModelImp.sendAllListener { private RegisterView mRegisterView;
// Path: app/src/main/java/com/idisfkj/hightcopywx/ui/model/RegisterModel.java // public interface RegisterModel { // void saveData(RegisterModelImp.saveDataListener listener, EditText... editTexts); // // void sendAll(RegisterModelImp.sendAllListener listener, String userName, String number); // } // // Path: app/src/main/java/com/idisfkj/hightcopywx/ui/model/RegisterModelImp.java // public class RegisterModelImp implements RegisterModel { // private String[] user; // // @Override // public void saveData(saveDataListener listener, EditText... editTexts) { // user = new String[editTexts.length]; // for (int i = 0; i < editTexts.length; i++) { // user[i] = editTexts[i].getText().toString().trim(); // if (user[i].length() <= 0) { // ToastUtils.showShort("昵称、号码或密码不能为空"); // return; // } // } // SPUtils.putString("userName", user[0]) // .putString("userPhone", user[1]) // .putString("userPassword", user[2]) // .commit(); // listener.onSucceed(user[0], user[1]); // } // // @Override // public void sendAll(final sendAllListener listener, String userName, String number) { // JsonObjectRequest request = new JsonObjectRequest(Request.Method.POST, UrlUtils.registerUrl(userName, number) // , null, new Response.Listener<JSONObject>() { // @Override // public void onResponse(JSONObject jsonObject) { // listener.onSendSucceed(); // } // }, new Response.ErrorListener() { // @Override // public void onErrorResponse(VolleyError volleyError) { // listener.onError(); // } // }) { // @Override // public Map<String, String> getHeaders() throws AuthFailureError { // HashMap<String, String> header = new HashMap<>(); // header.put("Authorization", "key=" + App.APP_SECRET_KEY); // return header; // } // }; // VolleyUtils.addQueue(request, "registerRequest"); // } // // public interface saveDataListener { // void onSucceed(String userName, String number); // } // // public interface sendAllListener { // void onSendSucceed(); // // void onError(); // } // } // // Path: app/src/main/java/com/idisfkj/hightcopywx/ui/view/RegisterView.java // public interface RegisterView { // void changeUserNameLine(boolean hasFocus); // // void changeUserPhoneLine(boolean hasFocus); // // void changeUserPasswordLine(boolean hasFocus); // // void jumpMainActivity(); // // void showAlertDialog(); // // void startCrop(Uri uri); // // void setHeadPicture(Intent intent); // // void saveHeadPicture(Bitmap bitmap); // // void showProgressDialog(); // // void hideProgressDialog(); // // void showErrorToast(); // // void showSucceedToast(); // } // Path: app/src/main/java/com/idisfkj/hightcopywx/ui/presenter/RegisterPresenterImp.java import android.content.Intent; import android.graphics.Bitmap; import android.net.Uri; import android.widget.EditText; import com.idisfkj.hightcopywx.R; import com.idisfkj.hightcopywx.ui.model.RegisterModel; import com.idisfkj.hightcopywx.ui.model.RegisterModelImp; import com.idisfkj.hightcopywx.ui.view.RegisterView; package com.idisfkj.hightcopywx.ui.presenter; /** * Created by idisfkj on 16/4/28. * Email : [email protected]. */ public class RegisterPresenterImp implements RegisterPresenter, RegisterModelImp.saveDataListener, RegisterModelImp.sendAllListener { private RegisterView mRegisterView;
private RegisterModel mRegisterModel;
idisfkj/HightCopyWX
app/src/main/java/com/idisfkj/hightcopywx/adapter/SearchResultAdapter.java
// Path: app/src/main/java/com/idisfkj/hightcopywx/dao/RegisterDataHelper.java // public class RegisterDataHelper extends BaseDataHelper { // // public RegisterDataHelper(Context mContext) { // super(mContext); // } // // @Override // public Uri getContentUri() { // return DataProvider.REGISTERS_CONTENT_URI; // } // // private ContentValues getContentValues(RegisterInfo info) { // ContentValues values = new ContentValues(); // values.put(RegisterDataInfo.USER_NAME, info.getUserName()); // values.put(RegisterDataInfo.NUMBER, info.getNumber()); // values.put(RegisterDataInfo.REGID, info.getRegId()); // return values; // } // // public static final class RegisterDataInfo implements BaseColumns { // // public RegisterDataInfo() { // } // // public static final String TABLE_NAME = "register"; // public static final String USER_NAME = "userName"; // public static final String REGID = "regId"; // public static final String NUMBER = "number"; // public static final SQLiteTable TABLE = new SQLiteTable(TABLE_NAME) // .addColumn(USER_NAME, Column.DataType.TEXT) // .addColumn(NUMBER, Column.DataType.TEXT) // .addColumn(REGID, Column.DataType.TEXT); // } // // public Cursor query(String number, String regId) { // Cursor cursor = query(null, RegisterDataInfo.NUMBER + "=?" + " AND " + RegisterDataInfo.REGID + "=?" // , new String[]{number, regId}, null); // return cursor; // } // // public Cursor query(String number) { // Cursor cursor = query(null, RegisterDataInfo.NUMBER + "=?", new String[]{number}, null); // return cursor; // } // // public void insert(RegisterInfo info) { // ContentValues values = getContentValues(info); // insert(values); // } // // public int update(RegisterInfo info, String number, String regId) { // ContentValues values = getContentValues(info); // int row = update(values, RegisterDataInfo.NUMBER + "=?" + " AND " + RegisterDataInfo.REGID // , new String[]{number}); // return row; // } // // public CursorLoader getCursorLoader(String number) { // return getCursorLoader(null, RegisterDataInfo.NUMBER + "=?", new String[]{number}, RegisterDataInfo._ID + " ASC"); // } // // } // // Path: app/src/main/java/com/idisfkj/hightcopywx/util/CursorUtils.java // public class CursorUtils { // public CursorUtils() { // } // // public static String formatString(Cursor cursor, String columnName) { // String result = cursor.getString(cursor.getColumnIndex(columnName)); // return result; // } // // public static int formatInt(Cursor cursor, String columnName) { // int result = cursor.getInt(cursor.getColumnIndex(columnName)); // return result; // } // }
import android.content.Context; import android.database.Cursor; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.TextView; import com.idisfkj.hightcopywx.R; import com.idisfkj.hightcopywx.dao.RegisterDataHelper; import com.idisfkj.hightcopywx.util.CursorUtils; import butterknife.ButterKnife; import butterknife.InjectView;
package com.idisfkj.hightcopywx.adapter; /** * 搜寻好友适配器 * Created by idisfkj on 16/5/7. * Email : [email protected]. */ public class SearchResultAdapter extends RecyclerViewCursorBaseAdapter<SearchResultAdapter.SearchViewHolder> implements View.OnClickListener { private Context mContext; private SearchItemClickListener listener; public SearchResultAdapter(Context context) { super(context, null); mContext = context; } @Override public void onBindViewHolder(SearchViewHolder holder, Cursor cursor) {
// Path: app/src/main/java/com/idisfkj/hightcopywx/dao/RegisterDataHelper.java // public class RegisterDataHelper extends BaseDataHelper { // // public RegisterDataHelper(Context mContext) { // super(mContext); // } // // @Override // public Uri getContentUri() { // return DataProvider.REGISTERS_CONTENT_URI; // } // // private ContentValues getContentValues(RegisterInfo info) { // ContentValues values = new ContentValues(); // values.put(RegisterDataInfo.USER_NAME, info.getUserName()); // values.put(RegisterDataInfo.NUMBER, info.getNumber()); // values.put(RegisterDataInfo.REGID, info.getRegId()); // return values; // } // // public static final class RegisterDataInfo implements BaseColumns { // // public RegisterDataInfo() { // } // // public static final String TABLE_NAME = "register"; // public static final String USER_NAME = "userName"; // public static final String REGID = "regId"; // public static final String NUMBER = "number"; // public static final SQLiteTable TABLE = new SQLiteTable(TABLE_NAME) // .addColumn(USER_NAME, Column.DataType.TEXT) // .addColumn(NUMBER, Column.DataType.TEXT) // .addColumn(REGID, Column.DataType.TEXT); // } // // public Cursor query(String number, String regId) { // Cursor cursor = query(null, RegisterDataInfo.NUMBER + "=?" + " AND " + RegisterDataInfo.REGID + "=?" // , new String[]{number, regId}, null); // return cursor; // } // // public Cursor query(String number) { // Cursor cursor = query(null, RegisterDataInfo.NUMBER + "=?", new String[]{number}, null); // return cursor; // } // // public void insert(RegisterInfo info) { // ContentValues values = getContentValues(info); // insert(values); // } // // public int update(RegisterInfo info, String number, String regId) { // ContentValues values = getContentValues(info); // int row = update(values, RegisterDataInfo.NUMBER + "=?" + " AND " + RegisterDataInfo.REGID // , new String[]{number}); // return row; // } // // public CursorLoader getCursorLoader(String number) { // return getCursorLoader(null, RegisterDataInfo.NUMBER + "=?", new String[]{number}, RegisterDataInfo._ID + " ASC"); // } // // } // // Path: app/src/main/java/com/idisfkj/hightcopywx/util/CursorUtils.java // public class CursorUtils { // public CursorUtils() { // } // // public static String formatString(Cursor cursor, String columnName) { // String result = cursor.getString(cursor.getColumnIndex(columnName)); // return result; // } // // public static int formatInt(Cursor cursor, String columnName) { // int result = cursor.getInt(cursor.getColumnIndex(columnName)); // return result; // } // } // Path: app/src/main/java/com/idisfkj/hightcopywx/adapter/SearchResultAdapter.java import android.content.Context; import android.database.Cursor; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.TextView; import com.idisfkj.hightcopywx.R; import com.idisfkj.hightcopywx.dao.RegisterDataHelper; import com.idisfkj.hightcopywx.util.CursorUtils; import butterknife.ButterKnife; import butterknife.InjectView; package com.idisfkj.hightcopywx.adapter; /** * 搜寻好友适配器 * Created by idisfkj on 16/5/7. * Email : [email protected]. */ public class SearchResultAdapter extends RecyclerViewCursorBaseAdapter<SearchResultAdapter.SearchViewHolder> implements View.OnClickListener { private Context mContext; private SearchItemClickListener listener; public SearchResultAdapter(Context context) { super(context, null); mContext = context; } @Override public void onBindViewHolder(SearchViewHolder holder, Cursor cursor) {
holder.searchItemName.setText(CursorUtils.formatString(cursor, RegisterDataHelper.RegisterDataInfo.USER_NAME));
idisfkj/HightCopyWX
app/src/main/java/com/idisfkj/hightcopywx/adapter/SearchResultAdapter.java
// Path: app/src/main/java/com/idisfkj/hightcopywx/dao/RegisterDataHelper.java // public class RegisterDataHelper extends BaseDataHelper { // // public RegisterDataHelper(Context mContext) { // super(mContext); // } // // @Override // public Uri getContentUri() { // return DataProvider.REGISTERS_CONTENT_URI; // } // // private ContentValues getContentValues(RegisterInfo info) { // ContentValues values = new ContentValues(); // values.put(RegisterDataInfo.USER_NAME, info.getUserName()); // values.put(RegisterDataInfo.NUMBER, info.getNumber()); // values.put(RegisterDataInfo.REGID, info.getRegId()); // return values; // } // // public static final class RegisterDataInfo implements BaseColumns { // // public RegisterDataInfo() { // } // // public static final String TABLE_NAME = "register"; // public static final String USER_NAME = "userName"; // public static final String REGID = "regId"; // public static final String NUMBER = "number"; // public static final SQLiteTable TABLE = new SQLiteTable(TABLE_NAME) // .addColumn(USER_NAME, Column.DataType.TEXT) // .addColumn(NUMBER, Column.DataType.TEXT) // .addColumn(REGID, Column.DataType.TEXT); // } // // public Cursor query(String number, String regId) { // Cursor cursor = query(null, RegisterDataInfo.NUMBER + "=?" + " AND " + RegisterDataInfo.REGID + "=?" // , new String[]{number, regId}, null); // return cursor; // } // // public Cursor query(String number) { // Cursor cursor = query(null, RegisterDataInfo.NUMBER + "=?", new String[]{number}, null); // return cursor; // } // // public void insert(RegisterInfo info) { // ContentValues values = getContentValues(info); // insert(values); // } // // public int update(RegisterInfo info, String number, String regId) { // ContentValues values = getContentValues(info); // int row = update(values, RegisterDataInfo.NUMBER + "=?" + " AND " + RegisterDataInfo.REGID // , new String[]{number}); // return row; // } // // public CursorLoader getCursorLoader(String number) { // return getCursorLoader(null, RegisterDataInfo.NUMBER + "=?", new String[]{number}, RegisterDataInfo._ID + " ASC"); // } // // } // // Path: app/src/main/java/com/idisfkj/hightcopywx/util/CursorUtils.java // public class CursorUtils { // public CursorUtils() { // } // // public static String formatString(Cursor cursor, String columnName) { // String result = cursor.getString(cursor.getColumnIndex(columnName)); // return result; // } // // public static int formatInt(Cursor cursor, String columnName) { // int result = cursor.getInt(cursor.getColumnIndex(columnName)); // return result; // } // }
import android.content.Context; import android.database.Cursor; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.TextView; import com.idisfkj.hightcopywx.R; import com.idisfkj.hightcopywx.dao.RegisterDataHelper; import com.idisfkj.hightcopywx.util.CursorUtils; import butterknife.ButterKnife; import butterknife.InjectView;
package com.idisfkj.hightcopywx.adapter; /** * 搜寻好友适配器 * Created by idisfkj on 16/5/7. * Email : [email protected]. */ public class SearchResultAdapter extends RecyclerViewCursorBaseAdapter<SearchResultAdapter.SearchViewHolder> implements View.OnClickListener { private Context mContext; private SearchItemClickListener listener; public SearchResultAdapter(Context context) { super(context, null); mContext = context; } @Override public void onBindViewHolder(SearchViewHolder holder, Cursor cursor) {
// Path: app/src/main/java/com/idisfkj/hightcopywx/dao/RegisterDataHelper.java // public class RegisterDataHelper extends BaseDataHelper { // // public RegisterDataHelper(Context mContext) { // super(mContext); // } // // @Override // public Uri getContentUri() { // return DataProvider.REGISTERS_CONTENT_URI; // } // // private ContentValues getContentValues(RegisterInfo info) { // ContentValues values = new ContentValues(); // values.put(RegisterDataInfo.USER_NAME, info.getUserName()); // values.put(RegisterDataInfo.NUMBER, info.getNumber()); // values.put(RegisterDataInfo.REGID, info.getRegId()); // return values; // } // // public static final class RegisterDataInfo implements BaseColumns { // // public RegisterDataInfo() { // } // // public static final String TABLE_NAME = "register"; // public static final String USER_NAME = "userName"; // public static final String REGID = "regId"; // public static final String NUMBER = "number"; // public static final SQLiteTable TABLE = new SQLiteTable(TABLE_NAME) // .addColumn(USER_NAME, Column.DataType.TEXT) // .addColumn(NUMBER, Column.DataType.TEXT) // .addColumn(REGID, Column.DataType.TEXT); // } // // public Cursor query(String number, String regId) { // Cursor cursor = query(null, RegisterDataInfo.NUMBER + "=?" + " AND " + RegisterDataInfo.REGID + "=?" // , new String[]{number, regId}, null); // return cursor; // } // // public Cursor query(String number) { // Cursor cursor = query(null, RegisterDataInfo.NUMBER + "=?", new String[]{number}, null); // return cursor; // } // // public void insert(RegisterInfo info) { // ContentValues values = getContentValues(info); // insert(values); // } // // public int update(RegisterInfo info, String number, String regId) { // ContentValues values = getContentValues(info); // int row = update(values, RegisterDataInfo.NUMBER + "=?" + " AND " + RegisterDataInfo.REGID // , new String[]{number}); // return row; // } // // public CursorLoader getCursorLoader(String number) { // return getCursorLoader(null, RegisterDataInfo.NUMBER + "=?", new String[]{number}, RegisterDataInfo._ID + " ASC"); // } // // } // // Path: app/src/main/java/com/idisfkj/hightcopywx/util/CursorUtils.java // public class CursorUtils { // public CursorUtils() { // } // // public static String formatString(Cursor cursor, String columnName) { // String result = cursor.getString(cursor.getColumnIndex(columnName)); // return result; // } // // public static int formatInt(Cursor cursor, String columnName) { // int result = cursor.getInt(cursor.getColumnIndex(columnName)); // return result; // } // } // Path: app/src/main/java/com/idisfkj/hightcopywx/adapter/SearchResultAdapter.java import android.content.Context; import android.database.Cursor; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.TextView; import com.idisfkj.hightcopywx.R; import com.idisfkj.hightcopywx.dao.RegisterDataHelper; import com.idisfkj.hightcopywx.util.CursorUtils; import butterknife.ButterKnife; import butterknife.InjectView; package com.idisfkj.hightcopywx.adapter; /** * 搜寻好友适配器 * Created by idisfkj on 16/5/7. * Email : [email protected]. */ public class SearchResultAdapter extends RecyclerViewCursorBaseAdapter<SearchResultAdapter.SearchViewHolder> implements View.OnClickListener { private Context mContext; private SearchItemClickListener listener; public SearchResultAdapter(Context context) { super(context, null); mContext = context; } @Override public void onBindViewHolder(SearchViewHolder holder, Cursor cursor) {
holder.searchItemName.setText(CursorUtils.formatString(cursor, RegisterDataHelper.RegisterDataInfo.USER_NAME));
idisfkj/HightCopyWX
app/src/main/java/com/idisfkj/hightcopywx/util/VolleyUtils.java
// Path: app/src/main/java/com/idisfkj/hightcopywx/App.java // public class App extends Application{ // private static Context mContext; // public static final String APP_ID = "2882303761517464903"; // public static final String APP_KEY = "5631746467903"; // public static final String APP_SECRET_KEY = "HxMA7STSUQMLEiDX+zo+5A=="; // public static final String TAG = "com.idisfkj.hightcopywx"; // public static final String DEVELOPER_ID = "/f6ukNwIPpdSmkrgsmklcMbW6WefG01XkxdILDNEUVw="; // public static final String DEVELOPER_NUMBER = "666666"; // public static final String DEVELOPER_NAME = "idisfkj"; // public static final String DEVELOPER_MESSAGE = "欢迎注册高仿微信App,我是该App的开发者,你可以使用添加朋友自行互动测试!如有问题可以在此留言与我。"; // public static final String HELLO_MESSAGE = "你已添加了%s,现在可以开始聊天了"; // public static final String UNREADNUM = "unReadNum"; // public static String mNumber = "-1"; // public static String mRegId = "-1"; // public static SharedPreferences sp; // public static SharedPreferences.Editor editor; // // // @Override // public void onCreate() { // super.onCreate(); // mContext = getApplicationContext(); // sp = getSharedPreferences("userInfo",Context.MODE_PRIVATE); // // //初始化push推送服务 // if(shouldInit()) { // MiPushClient.registerPush(this, APP_ID, APP_KEY); // } // // //小米推送调试日记 // LoggerInterface newLogger = new LoggerInterface() { // @Override // public void setTag(String tag) { // // ignore // } // @Override // public void log(String content, Throwable t) { // Log.d(TAG, content, t); // } // @Override // public void log(String content) { // Log.d(TAG, content); // } // }; // Logger.setLogger(this, newLogger); // // } // // private boolean shouldInit() { // ActivityManager am = ((ActivityManager) getSystemService(Context.ACTIVITY_SERVICE)); // List<ActivityManager.RunningAppProcessInfo> processInfos = am.getRunningAppProcesses(); // String mainProcessName = getPackageName(); // int myPid = android.os.Process.myPid(); // for (ActivityManager.RunningAppProcessInfo info : processInfos) { // if (info.pid == myPid && mainProcessName.equals(info.processName)) { // return true; // } // } // return false; // } // // public static Context getAppContext(){ // return mContext; // } // }
import com.android.volley.Request; import com.android.volley.RequestQueue; import com.android.volley.toolbox.Volley; import com.idisfkj.hightcopywx.App;
package com.idisfkj.hightcopywx.util; /** * Volley网络请求工具类 * Created by idisfkj on 16/4/26. * Email : [email protected]. */ public class VolleyUtils { public VolleyUtils() { }
// Path: app/src/main/java/com/idisfkj/hightcopywx/App.java // public class App extends Application{ // private static Context mContext; // public static final String APP_ID = "2882303761517464903"; // public static final String APP_KEY = "5631746467903"; // public static final String APP_SECRET_KEY = "HxMA7STSUQMLEiDX+zo+5A=="; // public static final String TAG = "com.idisfkj.hightcopywx"; // public static final String DEVELOPER_ID = "/f6ukNwIPpdSmkrgsmklcMbW6WefG01XkxdILDNEUVw="; // public static final String DEVELOPER_NUMBER = "666666"; // public static final String DEVELOPER_NAME = "idisfkj"; // public static final String DEVELOPER_MESSAGE = "欢迎注册高仿微信App,我是该App的开发者,你可以使用添加朋友自行互动测试!如有问题可以在此留言与我。"; // public static final String HELLO_MESSAGE = "你已添加了%s,现在可以开始聊天了"; // public static final String UNREADNUM = "unReadNum"; // public static String mNumber = "-1"; // public static String mRegId = "-1"; // public static SharedPreferences sp; // public static SharedPreferences.Editor editor; // // // @Override // public void onCreate() { // super.onCreate(); // mContext = getApplicationContext(); // sp = getSharedPreferences("userInfo",Context.MODE_PRIVATE); // // //初始化push推送服务 // if(shouldInit()) { // MiPushClient.registerPush(this, APP_ID, APP_KEY); // } // // //小米推送调试日记 // LoggerInterface newLogger = new LoggerInterface() { // @Override // public void setTag(String tag) { // // ignore // } // @Override // public void log(String content, Throwable t) { // Log.d(TAG, content, t); // } // @Override // public void log(String content) { // Log.d(TAG, content); // } // }; // Logger.setLogger(this, newLogger); // // } // // private boolean shouldInit() { // ActivityManager am = ((ActivityManager) getSystemService(Context.ACTIVITY_SERVICE)); // List<ActivityManager.RunningAppProcessInfo> processInfos = am.getRunningAppProcesses(); // String mainProcessName = getPackageName(); // int myPid = android.os.Process.myPid(); // for (ActivityManager.RunningAppProcessInfo info : processInfos) { // if (info.pid == myPid && mainProcessName.equals(info.processName)) { // return true; // } // } // return false; // } // // public static Context getAppContext(){ // return mContext; // } // } // Path: app/src/main/java/com/idisfkj/hightcopywx/util/VolleyUtils.java import com.android.volley.Request; import com.android.volley.RequestQueue; import com.android.volley.toolbox.Volley; import com.idisfkj.hightcopywx.App; package com.idisfkj.hightcopywx.util; /** * Volley网络请求工具类 * Created by idisfkj on 16/4/26. * Email : [email protected]. */ public class VolleyUtils { public VolleyUtils() { }
private static RequestQueue requestQueue = Volley.newRequestQueue(App.getAppContext());
idisfkj/HightCopyWX
app/src/main/java/com/idisfkj/hightcopywx/wx/model/ChatModel.java
// Path: app/src/main/java/com/idisfkj/hightcopywx/beans/ChatMessageInfo.java // public class ChatMessageInfo implements Serializable { // private String message; // /** // * 接收与发送的标识 // */ // private int flag; // private String time; // /** // * 接收该信息的账号 // */ // private String receiverNumber; // private String regId; // /** // * 发送者的账号 // */ // private String sendNumber; // // public ChatMessageInfo() { // } // // public ChatMessageInfo(String message, int flag, String time, String receiverNumber, String regId, String sendNumber) { // this.message = message; // this.flag = flag; // this.time = time; // this.receiverNumber = receiverNumber; // this.regId = regId; // this.sendNumber = sendNumber; // } // // public String getReceiverNumber() { // return receiverNumber; // } // // public void setReceiverNumber(String receiverNumber) { // this.receiverNumber = receiverNumber; // } // // public String getRegId() { // return regId; // } // // public void setRegId(String regId) { // this.regId = regId; // } // // public String getSendNumber() { // return sendNumber; // } // // public void setSendNumber(String sendNumber) { // this.sendNumber = sendNumber; // } // // public String getTime() { // return time; // } // // public void setTime(String time) { // this.time = time; // } // // public String getMessage() { // return message; // } // // public void setMessage(String message) { // this.message = message; // } // // public int getFlag() { // return flag; // } // // public void setFlag(int flag) { // this.flag = flag; // } // } // // Path: app/src/main/java/com/idisfkj/hightcopywx/dao/ChatMessageDataHelper.java // public class ChatMessageDataHelper extends BaseDataHelper { // public ChatMessageDataHelper(Context mContext) { // super(mContext); // } // // @Override // public Uri getContentUri() { // return DataProvider.CHAT_MESSAGES_CONTENT_URI; // } // // public ContentValues getContentValues(ChatMessageInfo info) { // ContentValues values = new ContentValues(); // values.put(ChatMessageDataInfo.MESSAGE, info.getMessage()); // values.put(ChatMessageDataInfo.FLAG, info.getFlag()); // values.put(ChatMessageDataInfo.TIME, info.getTime()); // values.put(ChatMessageDataInfo.RECEIVER_NUMBER, info.getReceiverNumber()); // values.put(ChatMessageDataInfo.REGID, info.getRegId()); // values.put(ChatMessageDataInfo.SEND_NUMBER, info.getSendNumber()); // return values; // } // // public static final class ChatMessageDataInfo implements BaseColumns { // public static final String TABLE_NAME = "chat"; // public static final String MESSAGE = "message"; // public static final String FLAG = "flag"; // public static final String TIME = "time"; // public static final String RECEIVER_NUMBER = "receiverNumber"; // public static final String REGID = "regId"; // public static final String SEND_NUMBER = "sendNumber"; // public static final SQLiteTable TABLE = new SQLiteTable(TABLE_NAME) // .addColumn(MESSAGE, Column.DataType.TEXT) // .addColumn(FLAG, Column.DataType.INTEGER) // .addColumn(TIME, Column.DataType.TEXT) // .addColumn(RECEIVER_NUMBER, Column.DataType.TEXT) // .addColumn(REGID, Column.DataType.TEXT) // .addColumn(SEND_NUMBER, Column.DataType.TEXT); // } // // public Cursor query(String receiverNumber, String regId) { // Cursor cursor = query(new String[]{ChatMessageDataInfo.MESSAGE, ChatMessageDataInfo.TIME}, "(" + ChatMessageDataInfo.RECEIVER_NUMBER + "=?" + " OR " // + ChatMessageDataInfo.SEND_NUMBER + "=?" + ") AND " // + ChatMessageDataInfo.REGID + "=?", new String[]{receiverNumber, receiverNumber, regId}, ChatMessageDataInfo._ID + " DESC"); // return cursor; // } // // public void insert(ChatMessageInfo info) { // ContentValues values = getContentValues(info); // insert(values); // } // // public void bulkInser(ArrayList<ChatMessageInfo> list) { // ArrayList<ContentValues> valuesList = new ArrayList<>(); // for (ChatMessageInfo info : list) { // ContentValues itemValues = getContentValues(info); // valuesList.add(itemValues); // } // ContentValues[] valuesArray = new ContentValues[valuesList.size()]; // bulkInsert(valuesList.toArray(valuesArray)); // } // // public CursorLoader getCursorLoader(String receiverNumber, String regId) { // return getCursorLoader(null, "(" + ChatMessageDataInfo.SEND_NUMBER + "=?" + " OR " // + ChatMessageDataInfo.RECEIVER_NUMBER + "=?" + ") AND " // + ChatMessageDataInfo.REGID + "=?", new String[]{receiverNumber, receiverNumber, regId} // , ChatMessageDataInfo._ID + " ASC"); // } // }
import android.content.Context; import com.idisfkj.hightcopywx.beans.ChatMessageInfo; import com.idisfkj.hightcopywx.dao.ChatMessageDataHelper;
package com.idisfkj.hightcopywx.wx.model; /** * Created by idisfkj on 16/4/25. * Email : [email protected]. */ public interface ChatModel { void requestData(ChatModelImp.requestListener listener, String chatContent, String number, String regId, ChatMessageDataHelper helper);
// Path: app/src/main/java/com/idisfkj/hightcopywx/beans/ChatMessageInfo.java // public class ChatMessageInfo implements Serializable { // private String message; // /** // * 接收与发送的标识 // */ // private int flag; // private String time; // /** // * 接收该信息的账号 // */ // private String receiverNumber; // private String regId; // /** // * 发送者的账号 // */ // private String sendNumber; // // public ChatMessageInfo() { // } // // public ChatMessageInfo(String message, int flag, String time, String receiverNumber, String regId, String sendNumber) { // this.message = message; // this.flag = flag; // this.time = time; // this.receiverNumber = receiverNumber; // this.regId = regId; // this.sendNumber = sendNumber; // } // // public String getReceiverNumber() { // return receiverNumber; // } // // public void setReceiverNumber(String receiverNumber) { // this.receiverNumber = receiverNumber; // } // // public String getRegId() { // return regId; // } // // public void setRegId(String regId) { // this.regId = regId; // } // // public String getSendNumber() { // return sendNumber; // } // // public void setSendNumber(String sendNumber) { // this.sendNumber = sendNumber; // } // // public String getTime() { // return time; // } // // public void setTime(String time) { // this.time = time; // } // // public String getMessage() { // return message; // } // // public void setMessage(String message) { // this.message = message; // } // // public int getFlag() { // return flag; // } // // public void setFlag(int flag) { // this.flag = flag; // } // } // // Path: app/src/main/java/com/idisfkj/hightcopywx/dao/ChatMessageDataHelper.java // public class ChatMessageDataHelper extends BaseDataHelper { // public ChatMessageDataHelper(Context mContext) { // super(mContext); // } // // @Override // public Uri getContentUri() { // return DataProvider.CHAT_MESSAGES_CONTENT_URI; // } // // public ContentValues getContentValues(ChatMessageInfo info) { // ContentValues values = new ContentValues(); // values.put(ChatMessageDataInfo.MESSAGE, info.getMessage()); // values.put(ChatMessageDataInfo.FLAG, info.getFlag()); // values.put(ChatMessageDataInfo.TIME, info.getTime()); // values.put(ChatMessageDataInfo.RECEIVER_NUMBER, info.getReceiverNumber()); // values.put(ChatMessageDataInfo.REGID, info.getRegId()); // values.put(ChatMessageDataInfo.SEND_NUMBER, info.getSendNumber()); // return values; // } // // public static final class ChatMessageDataInfo implements BaseColumns { // public static final String TABLE_NAME = "chat"; // public static final String MESSAGE = "message"; // public static final String FLAG = "flag"; // public static final String TIME = "time"; // public static final String RECEIVER_NUMBER = "receiverNumber"; // public static final String REGID = "regId"; // public static final String SEND_NUMBER = "sendNumber"; // public static final SQLiteTable TABLE = new SQLiteTable(TABLE_NAME) // .addColumn(MESSAGE, Column.DataType.TEXT) // .addColumn(FLAG, Column.DataType.INTEGER) // .addColumn(TIME, Column.DataType.TEXT) // .addColumn(RECEIVER_NUMBER, Column.DataType.TEXT) // .addColumn(REGID, Column.DataType.TEXT) // .addColumn(SEND_NUMBER, Column.DataType.TEXT); // } // // public Cursor query(String receiverNumber, String regId) { // Cursor cursor = query(new String[]{ChatMessageDataInfo.MESSAGE, ChatMessageDataInfo.TIME}, "(" + ChatMessageDataInfo.RECEIVER_NUMBER + "=?" + " OR " // + ChatMessageDataInfo.SEND_NUMBER + "=?" + ") AND " // + ChatMessageDataInfo.REGID + "=?", new String[]{receiverNumber, receiverNumber, regId}, ChatMessageDataInfo._ID + " DESC"); // return cursor; // } // // public void insert(ChatMessageInfo info) { // ContentValues values = getContentValues(info); // insert(values); // } // // public void bulkInser(ArrayList<ChatMessageInfo> list) { // ArrayList<ContentValues> valuesList = new ArrayList<>(); // for (ChatMessageInfo info : list) { // ContentValues itemValues = getContentValues(info); // valuesList.add(itemValues); // } // ContentValues[] valuesArray = new ContentValues[valuesList.size()]; // bulkInsert(valuesList.toArray(valuesArray)); // } // // public CursorLoader getCursorLoader(String receiverNumber, String regId) { // return getCursorLoader(null, "(" + ChatMessageDataInfo.SEND_NUMBER + "=?" + " OR " // + ChatMessageDataInfo.RECEIVER_NUMBER + "=?" + ") AND " // + ChatMessageDataInfo.REGID + "=?", new String[]{receiverNumber, receiverNumber, regId} // , ChatMessageDataInfo._ID + " ASC"); // } // } // Path: app/src/main/java/com/idisfkj/hightcopywx/wx/model/ChatModel.java import android.content.Context; import com.idisfkj.hightcopywx.beans.ChatMessageInfo; import com.idisfkj.hightcopywx.dao.ChatMessageDataHelper; package com.idisfkj.hightcopywx.wx.model; /** * Created by idisfkj on 16/4/25. * Email : [email protected]. */ public interface ChatModel { void requestData(ChatModelImp.requestListener listener, String chatContent, String number, String regId, ChatMessageDataHelper helper);
void insertData(ChatMessageInfo info, ChatMessageDataHelper helper);
idisfkj/HightCopyWX
app/src/main/java/com/idisfkj/hightcopywx/main/PlusActionProvider.java
// Path: app/src/main/java/com/idisfkj/hightcopywx/main/widget/AddFriendsActivity.java // public class AddFriendsActivity extends BaseActivity implements TextWatcher, AddFriendsView { // // @InjectView(R.id.search_friends) // EditText searchFriends; // @InjectView(R.id.search_content) // TextView searchContent; // @InjectView(R.id.start_search) // LinearLayout startSearch; // // private AddFriendsPresenter mPresenter; // private RegisterDataHelper mRegisterHelper; // // @Override // protected void onCreate(Bundle savedInstanceState) { // super.onCreate(savedInstanceState); // setContentView(R.layout.add_friends); // ButterKnife.inject(this); // getActionBar().setTitle(R.string.add_friends); // init(); // } // // public void init() { // mRegisterHelper = new RegisterDataHelper(this); // mPresenter = new AddFriendsPresenterImp(this); // searchFriends.addTextChangedListener(this); // } // // @OnClick(R.id.start_search) // public void onClick() { // mPresenter.switchActicity(searchContent,mRegisterHelper); // } // // @Override // public void beforeTextChanged(CharSequence s, int start, int count, int after) { // // } // // @Override // public void onTextChanged(CharSequence s, int start, int before, int count) { // mPresenter.switchView(s); // } // // @Override // public void afterTextChanged(Editable s) { // // } // // @Override // public void showSearch() { // startSearch.setVisibility(View.VISIBLE); // } // // @Override // public void goneSearch() { // startSearch.setVisibility(View.GONE); // } // // @Override // public void jumpSearchResult(String text) { // Intent intent = new Intent(this,SearchResultActivity.class); // intent.putExtra("searchResult",searchContent.getText().toString()); // startActivity(intent); // } // // @Override // public void changeText(CharSequence text) { // searchContent.setText(text); // } // // @Override // public void showToast(String text) { // ToastUtils.showShort(text); // } // } // // Path: app/src/main/java/com/idisfkj/hightcopywx/util/ToastUtils.java // public class ToastUtils { // // public ToastUtils() { // } // // public static void showShort(CharSequence text){ // Toast.makeText(App.getAppContext(),text,Toast.LENGTH_SHORT).show(); // } // // public static void showLong(CharSequence text){ // Toast.makeText(App.getAppContext(),text,Toast.LENGTH_LONG).show(); // } // }
import android.content.Context; import android.content.Intent; import android.view.ActionProvider; import android.view.Menu; import android.view.MenuItem; import android.view.SubMenu; import android.view.View; import com.idisfkj.hightcopywx.R; import com.idisfkj.hightcopywx.main.widget.AddFriendsActivity; import com.idisfkj.hightcopywx.util.ToastUtils;
@Override public View onCreateActionView() { return null; } @Override public void onPrepareSubMenu(SubMenu subMenu) { subMenu.clear(); subMenu.add(Menu.NONE,0,Menu.NONE,mContext.getString(R.string.multi_chat)) .setIcon(R.drawable.multi_chat) .setOnMenuItemClickListener(this); subMenu.add(Menu.NONE,1,Menu.NONE,mContext.getString(R.string.add_friends)) .setIcon(R.drawable.add_friends) .setOnMenuItemClickListener(this); subMenu.add(Menu.NONE,2,Menu.NONE,mContext.getString(R.string.scan)) .setIcon(R.drawable.scan) .setOnMenuItemClickListener(this); subMenu.add(Menu.NONE,3,Menu.NONE,mContext.getString(R.string.pay_money)) .setIcon(R.drawable.pay_money) .setOnMenuItemClickListener(this); subMenu.add(Menu.NONE,4,Menu.NONE,mContext.getString(R.string.help_devise)) .setIcon(R.drawable.help_advise) .setOnMenuItemClickListener(this); } @Override public boolean onMenuItemClick(MenuItem item) { switch (item.getItemId()){ case 0:
// Path: app/src/main/java/com/idisfkj/hightcopywx/main/widget/AddFriendsActivity.java // public class AddFriendsActivity extends BaseActivity implements TextWatcher, AddFriendsView { // // @InjectView(R.id.search_friends) // EditText searchFriends; // @InjectView(R.id.search_content) // TextView searchContent; // @InjectView(R.id.start_search) // LinearLayout startSearch; // // private AddFriendsPresenter mPresenter; // private RegisterDataHelper mRegisterHelper; // // @Override // protected void onCreate(Bundle savedInstanceState) { // super.onCreate(savedInstanceState); // setContentView(R.layout.add_friends); // ButterKnife.inject(this); // getActionBar().setTitle(R.string.add_friends); // init(); // } // // public void init() { // mRegisterHelper = new RegisterDataHelper(this); // mPresenter = new AddFriendsPresenterImp(this); // searchFriends.addTextChangedListener(this); // } // // @OnClick(R.id.start_search) // public void onClick() { // mPresenter.switchActicity(searchContent,mRegisterHelper); // } // // @Override // public void beforeTextChanged(CharSequence s, int start, int count, int after) { // // } // // @Override // public void onTextChanged(CharSequence s, int start, int before, int count) { // mPresenter.switchView(s); // } // // @Override // public void afterTextChanged(Editable s) { // // } // // @Override // public void showSearch() { // startSearch.setVisibility(View.VISIBLE); // } // // @Override // public void goneSearch() { // startSearch.setVisibility(View.GONE); // } // // @Override // public void jumpSearchResult(String text) { // Intent intent = new Intent(this,SearchResultActivity.class); // intent.putExtra("searchResult",searchContent.getText().toString()); // startActivity(intent); // } // // @Override // public void changeText(CharSequence text) { // searchContent.setText(text); // } // // @Override // public void showToast(String text) { // ToastUtils.showShort(text); // } // } // // Path: app/src/main/java/com/idisfkj/hightcopywx/util/ToastUtils.java // public class ToastUtils { // // public ToastUtils() { // } // // public static void showShort(CharSequence text){ // Toast.makeText(App.getAppContext(),text,Toast.LENGTH_SHORT).show(); // } // // public static void showLong(CharSequence text){ // Toast.makeText(App.getAppContext(),text,Toast.LENGTH_LONG).show(); // } // } // Path: app/src/main/java/com/idisfkj/hightcopywx/main/PlusActionProvider.java import android.content.Context; import android.content.Intent; import android.view.ActionProvider; import android.view.Menu; import android.view.MenuItem; import android.view.SubMenu; import android.view.View; import com.idisfkj.hightcopywx.R; import com.idisfkj.hightcopywx.main.widget.AddFriendsActivity; import com.idisfkj.hightcopywx.util.ToastUtils; @Override public View onCreateActionView() { return null; } @Override public void onPrepareSubMenu(SubMenu subMenu) { subMenu.clear(); subMenu.add(Menu.NONE,0,Menu.NONE,mContext.getString(R.string.multi_chat)) .setIcon(R.drawable.multi_chat) .setOnMenuItemClickListener(this); subMenu.add(Menu.NONE,1,Menu.NONE,mContext.getString(R.string.add_friends)) .setIcon(R.drawable.add_friends) .setOnMenuItemClickListener(this); subMenu.add(Menu.NONE,2,Menu.NONE,mContext.getString(R.string.scan)) .setIcon(R.drawable.scan) .setOnMenuItemClickListener(this); subMenu.add(Menu.NONE,3,Menu.NONE,mContext.getString(R.string.pay_money)) .setIcon(R.drawable.pay_money) .setOnMenuItemClickListener(this); subMenu.add(Menu.NONE,4,Menu.NONE,mContext.getString(R.string.help_devise)) .setIcon(R.drawable.help_advise) .setOnMenuItemClickListener(this); } @Override public boolean onMenuItemClick(MenuItem item) { switch (item.getItemId()){ case 0:
ToastUtils.showShort("打开群聊");
idisfkj/HightCopyWX
app/src/main/java/com/idisfkj/hightcopywx/main/PlusActionProvider.java
// Path: app/src/main/java/com/idisfkj/hightcopywx/main/widget/AddFriendsActivity.java // public class AddFriendsActivity extends BaseActivity implements TextWatcher, AddFriendsView { // // @InjectView(R.id.search_friends) // EditText searchFriends; // @InjectView(R.id.search_content) // TextView searchContent; // @InjectView(R.id.start_search) // LinearLayout startSearch; // // private AddFriendsPresenter mPresenter; // private RegisterDataHelper mRegisterHelper; // // @Override // protected void onCreate(Bundle savedInstanceState) { // super.onCreate(savedInstanceState); // setContentView(R.layout.add_friends); // ButterKnife.inject(this); // getActionBar().setTitle(R.string.add_friends); // init(); // } // // public void init() { // mRegisterHelper = new RegisterDataHelper(this); // mPresenter = new AddFriendsPresenterImp(this); // searchFriends.addTextChangedListener(this); // } // // @OnClick(R.id.start_search) // public void onClick() { // mPresenter.switchActicity(searchContent,mRegisterHelper); // } // // @Override // public void beforeTextChanged(CharSequence s, int start, int count, int after) { // // } // // @Override // public void onTextChanged(CharSequence s, int start, int before, int count) { // mPresenter.switchView(s); // } // // @Override // public void afterTextChanged(Editable s) { // // } // // @Override // public void showSearch() { // startSearch.setVisibility(View.VISIBLE); // } // // @Override // public void goneSearch() { // startSearch.setVisibility(View.GONE); // } // // @Override // public void jumpSearchResult(String text) { // Intent intent = new Intent(this,SearchResultActivity.class); // intent.putExtra("searchResult",searchContent.getText().toString()); // startActivity(intent); // } // // @Override // public void changeText(CharSequence text) { // searchContent.setText(text); // } // // @Override // public void showToast(String text) { // ToastUtils.showShort(text); // } // } // // Path: app/src/main/java/com/idisfkj/hightcopywx/util/ToastUtils.java // public class ToastUtils { // // public ToastUtils() { // } // // public static void showShort(CharSequence text){ // Toast.makeText(App.getAppContext(),text,Toast.LENGTH_SHORT).show(); // } // // public static void showLong(CharSequence text){ // Toast.makeText(App.getAppContext(),text,Toast.LENGTH_LONG).show(); // } // }
import android.content.Context; import android.content.Intent; import android.view.ActionProvider; import android.view.Menu; import android.view.MenuItem; import android.view.SubMenu; import android.view.View; import com.idisfkj.hightcopywx.R; import com.idisfkj.hightcopywx.main.widget.AddFriendsActivity; import com.idisfkj.hightcopywx.util.ToastUtils;
return null; } @Override public void onPrepareSubMenu(SubMenu subMenu) { subMenu.clear(); subMenu.add(Menu.NONE,0,Menu.NONE,mContext.getString(R.string.multi_chat)) .setIcon(R.drawable.multi_chat) .setOnMenuItemClickListener(this); subMenu.add(Menu.NONE,1,Menu.NONE,mContext.getString(R.string.add_friends)) .setIcon(R.drawable.add_friends) .setOnMenuItemClickListener(this); subMenu.add(Menu.NONE,2,Menu.NONE,mContext.getString(R.string.scan)) .setIcon(R.drawable.scan) .setOnMenuItemClickListener(this); subMenu.add(Menu.NONE,3,Menu.NONE,mContext.getString(R.string.pay_money)) .setIcon(R.drawable.pay_money) .setOnMenuItemClickListener(this); subMenu.add(Menu.NONE,4,Menu.NONE,mContext.getString(R.string.help_devise)) .setIcon(R.drawable.help_advise) .setOnMenuItemClickListener(this); } @Override public boolean onMenuItemClick(MenuItem item) { switch (item.getItemId()){ case 0: ToastUtils.showShort("打开群聊"); break; case 1:
// Path: app/src/main/java/com/idisfkj/hightcopywx/main/widget/AddFriendsActivity.java // public class AddFriendsActivity extends BaseActivity implements TextWatcher, AddFriendsView { // // @InjectView(R.id.search_friends) // EditText searchFriends; // @InjectView(R.id.search_content) // TextView searchContent; // @InjectView(R.id.start_search) // LinearLayout startSearch; // // private AddFriendsPresenter mPresenter; // private RegisterDataHelper mRegisterHelper; // // @Override // protected void onCreate(Bundle savedInstanceState) { // super.onCreate(savedInstanceState); // setContentView(R.layout.add_friends); // ButterKnife.inject(this); // getActionBar().setTitle(R.string.add_friends); // init(); // } // // public void init() { // mRegisterHelper = new RegisterDataHelper(this); // mPresenter = new AddFriendsPresenterImp(this); // searchFriends.addTextChangedListener(this); // } // // @OnClick(R.id.start_search) // public void onClick() { // mPresenter.switchActicity(searchContent,mRegisterHelper); // } // // @Override // public void beforeTextChanged(CharSequence s, int start, int count, int after) { // // } // // @Override // public void onTextChanged(CharSequence s, int start, int before, int count) { // mPresenter.switchView(s); // } // // @Override // public void afterTextChanged(Editable s) { // // } // // @Override // public void showSearch() { // startSearch.setVisibility(View.VISIBLE); // } // // @Override // public void goneSearch() { // startSearch.setVisibility(View.GONE); // } // // @Override // public void jumpSearchResult(String text) { // Intent intent = new Intent(this,SearchResultActivity.class); // intent.putExtra("searchResult",searchContent.getText().toString()); // startActivity(intent); // } // // @Override // public void changeText(CharSequence text) { // searchContent.setText(text); // } // // @Override // public void showToast(String text) { // ToastUtils.showShort(text); // } // } // // Path: app/src/main/java/com/idisfkj/hightcopywx/util/ToastUtils.java // public class ToastUtils { // // public ToastUtils() { // } // // public static void showShort(CharSequence text){ // Toast.makeText(App.getAppContext(),text,Toast.LENGTH_SHORT).show(); // } // // public static void showLong(CharSequence text){ // Toast.makeText(App.getAppContext(),text,Toast.LENGTH_LONG).show(); // } // } // Path: app/src/main/java/com/idisfkj/hightcopywx/main/PlusActionProvider.java import android.content.Context; import android.content.Intent; import android.view.ActionProvider; import android.view.Menu; import android.view.MenuItem; import android.view.SubMenu; import android.view.View; import com.idisfkj.hightcopywx.R; import com.idisfkj.hightcopywx.main.widget.AddFriendsActivity; import com.idisfkj.hightcopywx.util.ToastUtils; return null; } @Override public void onPrepareSubMenu(SubMenu subMenu) { subMenu.clear(); subMenu.add(Menu.NONE,0,Menu.NONE,mContext.getString(R.string.multi_chat)) .setIcon(R.drawable.multi_chat) .setOnMenuItemClickListener(this); subMenu.add(Menu.NONE,1,Menu.NONE,mContext.getString(R.string.add_friends)) .setIcon(R.drawable.add_friends) .setOnMenuItemClickListener(this); subMenu.add(Menu.NONE,2,Menu.NONE,mContext.getString(R.string.scan)) .setIcon(R.drawable.scan) .setOnMenuItemClickListener(this); subMenu.add(Menu.NONE,3,Menu.NONE,mContext.getString(R.string.pay_money)) .setIcon(R.drawable.pay_money) .setOnMenuItemClickListener(this); subMenu.add(Menu.NONE,4,Menu.NONE,mContext.getString(R.string.help_devise)) .setIcon(R.drawable.help_advise) .setOnMenuItemClickListener(this); } @Override public boolean onMenuItemClick(MenuItem item) { switch (item.getItemId()){ case 0: ToastUtils.showShort("打开群聊"); break; case 1:
Intent intent = new Intent(mContext, AddFriendsActivity.class);
hantsy/angularjs-springmvc-sample-boot
src/main/java/com/hantsylabs/restexample/springmvc/SwaggerConfig.java
// Path: src/main/java/com/hantsylabs/restexample/springmvc/domain/User.java // @Data // @Builder // @NoArgsConstructor // @AllArgsConstructor // @Entity // @Table(name = "users") // public class User implements UserDetails, Serializable { // // /** // * // */ // private static final long serialVersionUID = 1L; // // @Id() // @GeneratedValue(strategy = GenerationType.IDENTITY) // @Column(name = "id") // private Long id; // // @Column(name = "username") // private String username; // // @Column(name = "password") // private String password; // // @Column(name = "name") // private String name; // // @Column(name = "email") // private String email; // // @Column(name = "role") // private String role; // // @Column(name = "created_date") // @CreatedDate // private LocalDateTime createdDate; // // public String getName() { // if (this.name == null || this.name.trim().length() == 0) { // return this.username; // } // return name; // } // // @Override // public Collection<? extends GrantedAuthority> getAuthorities() { // return Arrays.asList(new SimpleGrantedAuthority("ROLE_" + this.role)); // } // // @Override // public String getPassword() { // return this.password; // } // // @Override // public String getUsername() { // return this.username; // } // // @Override // public boolean isAccountNonExpired() { // return true; // } // // @Override // public boolean isAccountNonLocked() { // return true; // } // // @Override // public boolean isCredentialsNonExpired() { // return true; // } // // @Override // // public boolean isEnabled() { // return true; // } // // // }
import com.google.common.base.Predicate; import com.google.common.base.Predicates; import com.google.common.collect.Lists; import com.hantsylabs.restexample.springmvc.domain.User; import java.time.LocalDateTime; import java.util.ArrayList; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Import; import springfox.bean.validators.configuration.BeanValidatorPluginsConfiguration; import springfox.documentation.builders.ApiInfoBuilder; import springfox.documentation.builders.AuthorizationScopeBuilder; import springfox.documentation.builders.PathSelectors; import springfox.documentation.service.ApiInfo; import springfox.documentation.service.AuthorizationScope; import springfox.documentation.service.BasicAuth; import springfox.documentation.service.Contact; import springfox.documentation.service.SecurityReference; import springfox.documentation.spi.DocumentationType; import springfox.documentation.spi.service.contexts.SecurityContext; import springfox.documentation.spring.web.plugins.Docket; import springfox.documentation.swagger2.annotations.EnableSwagger2;
package com.hantsylabs.restexample.springmvc; @Configuration @EnableSwagger2 //@Profile(value = {"dev", "test", "staging"})// Loads the spring beans required by the framework @Import(BeanValidatorPluginsConfiguration.class) public class SwaggerConfig { @Bean public Docket userApi() { AuthorizationScope[] authScopes = new AuthorizationScope[1]; authScopes[0] = new AuthorizationScopeBuilder() .scope("read") .description("read access") .build(); SecurityReference securityReference = SecurityReference.builder() .reference("test") .scopes(authScopes) .build(); ArrayList<SecurityContext> securityContexts = Lists.newArrayList( SecurityContext.builder() .securityReferences(Lists.newArrayList(securityReference)) .build() ); return new Docket(DocumentationType.SWAGGER_2) .directModelSubstitute(LocalDateTime.class, String.class)
// Path: src/main/java/com/hantsylabs/restexample/springmvc/domain/User.java // @Data // @Builder // @NoArgsConstructor // @AllArgsConstructor // @Entity // @Table(name = "users") // public class User implements UserDetails, Serializable { // // /** // * // */ // private static final long serialVersionUID = 1L; // // @Id() // @GeneratedValue(strategy = GenerationType.IDENTITY) // @Column(name = "id") // private Long id; // // @Column(name = "username") // private String username; // // @Column(name = "password") // private String password; // // @Column(name = "name") // private String name; // // @Column(name = "email") // private String email; // // @Column(name = "role") // private String role; // // @Column(name = "created_date") // @CreatedDate // private LocalDateTime createdDate; // // public String getName() { // if (this.name == null || this.name.trim().length() == 0) { // return this.username; // } // return name; // } // // @Override // public Collection<? extends GrantedAuthority> getAuthorities() { // return Arrays.asList(new SimpleGrantedAuthority("ROLE_" + this.role)); // } // // @Override // public String getPassword() { // return this.password; // } // // @Override // public String getUsername() { // return this.username; // } // // @Override // public boolean isAccountNonExpired() { // return true; // } // // @Override // public boolean isAccountNonLocked() { // return true; // } // // @Override // public boolean isCredentialsNonExpired() { // return true; // } // // @Override // // public boolean isEnabled() { // return true; // } // // // } // Path: src/main/java/com/hantsylabs/restexample/springmvc/SwaggerConfig.java import com.google.common.base.Predicate; import com.google.common.base.Predicates; import com.google.common.collect.Lists; import com.hantsylabs.restexample.springmvc.domain.User; import java.time.LocalDateTime; import java.util.ArrayList; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Import; import springfox.bean.validators.configuration.BeanValidatorPluginsConfiguration; import springfox.documentation.builders.ApiInfoBuilder; import springfox.documentation.builders.AuthorizationScopeBuilder; import springfox.documentation.builders.PathSelectors; import springfox.documentation.service.ApiInfo; import springfox.documentation.service.AuthorizationScope; import springfox.documentation.service.BasicAuth; import springfox.documentation.service.Contact; import springfox.documentation.service.SecurityReference; import springfox.documentation.spi.DocumentationType; import springfox.documentation.spi.service.contexts.SecurityContext; import springfox.documentation.spring.web.plugins.Docket; import springfox.documentation.swagger2.annotations.EnableSwagger2; package com.hantsylabs.restexample.springmvc; @Configuration @EnableSwagger2 //@Profile(value = {"dev", "test", "staging"})// Loads the spring beans required by the framework @Import(BeanValidatorPluginsConfiguration.class) public class SwaggerConfig { @Bean public Docket userApi() { AuthorizationScope[] authScopes = new AuthorizationScope[1]; authScopes[0] = new AuthorizationScopeBuilder() .scope("read") .description("read access") .build(); SecurityReference securityReference = SecurityReference.builder() .reference("test") .scopes(authScopes) .build(); ArrayList<SecurityContext> securityContexts = Lists.newArrayList( SecurityContext.builder() .securityReferences(Lists.newArrayList(securityReference)) .build() ); return new Docket(DocumentationType.SWAGGER_2) .directModelSubstitute(LocalDateTime.class, String.class)
.ignoredParameterTypes(User.class)
hantsy/angularjs-springmvc-sample-boot
src/main/java/com/hantsylabs/restexample/springmvc/api/RestExceptionHandler.java
// Path: src/main/java/com/hantsylabs/restexample/springmvc/ApiErrors.java // public class ApiErrors { // // private static final String PREFIX = "errors."; // // public static final String INVALID_REQUEST = PREFIX + "INVALID_REQUEST"; // // private ApiErrors() {} // // } // // Path: src/main/java/com/hantsylabs/restexample/springmvc/exception/InvalidRequestException.java // public class InvalidRequestException extends RuntimeException { // // private BindingResult errors; // // public InvalidRequestException(BindingResult errors) { // this.errors = errors; // } // // public BindingResult getErrors() { // return errors; // } // // } // // Path: src/main/java/com/hantsylabs/restexample/springmvc/exception/ResourceNotFoundException.java // public class ResourceNotFoundException extends RuntimeException { // // private static final long serialVersionUID = 1L; // // private Long id; // // public ResourceNotFoundException(Long id) { // super(String.format("resource %s was not found", id)); // this.id = id; // } // // public ResourceNotFoundException(String message) { // super(message); // } // // public Long getId() { // return id; // } // } // // Path: src/main/java/com/hantsylabs/restexample/springmvc/exception/UsernameAlreadyUsedException.java // public class UsernameAlreadyUsedException extends RuntimeException { // // private static final long serialVersionUID = 1L; // // private String username; // // public UsernameAlreadyUsedException(String username) { // this.username = username; // } // // public String getUsername() { // return username; // } // // } // // Path: src/main/java/com/hantsylabs/restexample/springmvc/model/ResponseMessage.java // public class ResponseMessage { // // public enum Type { // success, warning, danger, info; // } // // private Type type; // private String text; // private String code; // // public ResponseMessage(Type type, String text) { // this.type = type; // this.text = text; // } // // public ResponseMessage(Type type, String code, String message) { // this.type = type; // this.code = code; // this.text = message; // } // // public String getText() { // return text; // } // // public Type getType() { // return type; // } // // public String getCode() { // return code; // } // // public static ResponseMessage success(String text) { // return new ResponseMessage(Type.success, text); // } // // public static ResponseMessage warning(String text) { // return new ResponseMessage(Type.warning, text); // } // // public static ResponseMessage danger(String text) { // return new ResponseMessage(Type.danger, text); // } // // public static ResponseMessage info(String text) { // return new ResponseMessage(Type.info, text); // } // // private List<Error> errors = new ArrayList<Error>(); // // public List<Error> getErrors() { // return errors; // } // // public void setErrors(List<Error> errors) { // this.errors = errors; // } // // public void addError(String field, String code, String message) { // this.errors.add(new Error(field, code, message)); // } // // class Error { // // private String code; // private String message; // private String field; // // private Error(String field, String code, String message) { // this.field = field; // this.code = code; // this.message = message; // } // // public String getCode() { // return code; // } // // public void setCode(String code) { // this.code = code; // } // // public String getMessage() { // return message; // } // // public void setMessage(String message) { // this.message = message; // } // // public String getField() { // return field; // } // // public void setField(String field) { // this.field = field; // } // // } // // }
import com.hantsylabs.restexample.springmvc.ApiErrors; import com.hantsylabs.restexample.springmvc.exception.InvalidRequestException; import com.hantsylabs.restexample.springmvc.exception.ResourceNotFoundException; import com.hantsylabs.restexample.springmvc.exception.UsernameAlreadyUsedException; import com.hantsylabs.restexample.springmvc.model.ResponseMessage; import java.util.List; import javax.inject.Inject; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.context.MessageSource; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.validation.BindingResult; import org.springframework.validation.FieldError; import org.springframework.web.bind.annotation.ExceptionHandler; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.bind.annotation.RestControllerAdvice; import org.springframework.web.context.request.WebRequest;
package com.hantsylabs.restexample.springmvc.api; /** * Called when an exception occurs during request processing. Transforms exception message into JSON format. */ @RestControllerAdvice() public class RestExceptionHandler { private static final Logger log = LoggerFactory.getLogger(RestExceptionHandler.class); @Inject private MessageSource messageSource; @ExceptionHandler(value = {Exception.class, RuntimeException.class}) //@ResponseBody
// Path: src/main/java/com/hantsylabs/restexample/springmvc/ApiErrors.java // public class ApiErrors { // // private static final String PREFIX = "errors."; // // public static final String INVALID_REQUEST = PREFIX + "INVALID_REQUEST"; // // private ApiErrors() {} // // } // // Path: src/main/java/com/hantsylabs/restexample/springmvc/exception/InvalidRequestException.java // public class InvalidRequestException extends RuntimeException { // // private BindingResult errors; // // public InvalidRequestException(BindingResult errors) { // this.errors = errors; // } // // public BindingResult getErrors() { // return errors; // } // // } // // Path: src/main/java/com/hantsylabs/restexample/springmvc/exception/ResourceNotFoundException.java // public class ResourceNotFoundException extends RuntimeException { // // private static final long serialVersionUID = 1L; // // private Long id; // // public ResourceNotFoundException(Long id) { // super(String.format("resource %s was not found", id)); // this.id = id; // } // // public ResourceNotFoundException(String message) { // super(message); // } // // public Long getId() { // return id; // } // } // // Path: src/main/java/com/hantsylabs/restexample/springmvc/exception/UsernameAlreadyUsedException.java // public class UsernameAlreadyUsedException extends RuntimeException { // // private static final long serialVersionUID = 1L; // // private String username; // // public UsernameAlreadyUsedException(String username) { // this.username = username; // } // // public String getUsername() { // return username; // } // // } // // Path: src/main/java/com/hantsylabs/restexample/springmvc/model/ResponseMessage.java // public class ResponseMessage { // // public enum Type { // success, warning, danger, info; // } // // private Type type; // private String text; // private String code; // // public ResponseMessage(Type type, String text) { // this.type = type; // this.text = text; // } // // public ResponseMessage(Type type, String code, String message) { // this.type = type; // this.code = code; // this.text = message; // } // // public String getText() { // return text; // } // // public Type getType() { // return type; // } // // public String getCode() { // return code; // } // // public static ResponseMessage success(String text) { // return new ResponseMessage(Type.success, text); // } // // public static ResponseMessage warning(String text) { // return new ResponseMessage(Type.warning, text); // } // // public static ResponseMessage danger(String text) { // return new ResponseMessage(Type.danger, text); // } // // public static ResponseMessage info(String text) { // return new ResponseMessage(Type.info, text); // } // // private List<Error> errors = new ArrayList<Error>(); // // public List<Error> getErrors() { // return errors; // } // // public void setErrors(List<Error> errors) { // this.errors = errors; // } // // public void addError(String field, String code, String message) { // this.errors.add(new Error(field, code, message)); // } // // class Error { // // private String code; // private String message; // private String field; // // private Error(String field, String code, String message) { // this.field = field; // this.code = code; // this.message = message; // } // // public String getCode() { // return code; // } // // public void setCode(String code) { // this.code = code; // } // // public String getMessage() { // return message; // } // // public void setMessage(String message) { // this.message = message; // } // // public String getField() { // return field; // } // // public void setField(String field) { // this.field = field; // } // // } // // } // Path: src/main/java/com/hantsylabs/restexample/springmvc/api/RestExceptionHandler.java import com.hantsylabs.restexample.springmvc.ApiErrors; import com.hantsylabs.restexample.springmvc.exception.InvalidRequestException; import com.hantsylabs.restexample.springmvc.exception.ResourceNotFoundException; import com.hantsylabs.restexample.springmvc.exception.UsernameAlreadyUsedException; import com.hantsylabs.restexample.springmvc.model.ResponseMessage; import java.util.List; import javax.inject.Inject; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.context.MessageSource; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.validation.BindingResult; import org.springframework.validation.FieldError; import org.springframework.web.bind.annotation.ExceptionHandler; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.bind.annotation.RestControllerAdvice; import org.springframework.web.context.request.WebRequest; package com.hantsylabs.restexample.springmvc.api; /** * Called when an exception occurs during request processing. Transforms exception message into JSON format. */ @RestControllerAdvice() public class RestExceptionHandler { private static final Logger log = LoggerFactory.getLogger(RestExceptionHandler.class); @Inject private MessageSource messageSource; @ExceptionHandler(value = {Exception.class, RuntimeException.class}) //@ResponseBody
public ResponseEntity<ResponseMessage> handleGenericException(Exception ex, WebRequest request) {
hantsy/angularjs-springmvc-sample-boot
src/main/java/com/hantsylabs/restexample/springmvc/api/RestExceptionHandler.java
// Path: src/main/java/com/hantsylabs/restexample/springmvc/ApiErrors.java // public class ApiErrors { // // private static final String PREFIX = "errors."; // // public static final String INVALID_REQUEST = PREFIX + "INVALID_REQUEST"; // // private ApiErrors() {} // // } // // Path: src/main/java/com/hantsylabs/restexample/springmvc/exception/InvalidRequestException.java // public class InvalidRequestException extends RuntimeException { // // private BindingResult errors; // // public InvalidRequestException(BindingResult errors) { // this.errors = errors; // } // // public BindingResult getErrors() { // return errors; // } // // } // // Path: src/main/java/com/hantsylabs/restexample/springmvc/exception/ResourceNotFoundException.java // public class ResourceNotFoundException extends RuntimeException { // // private static final long serialVersionUID = 1L; // // private Long id; // // public ResourceNotFoundException(Long id) { // super(String.format("resource %s was not found", id)); // this.id = id; // } // // public ResourceNotFoundException(String message) { // super(message); // } // // public Long getId() { // return id; // } // } // // Path: src/main/java/com/hantsylabs/restexample/springmvc/exception/UsernameAlreadyUsedException.java // public class UsernameAlreadyUsedException extends RuntimeException { // // private static final long serialVersionUID = 1L; // // private String username; // // public UsernameAlreadyUsedException(String username) { // this.username = username; // } // // public String getUsername() { // return username; // } // // } // // Path: src/main/java/com/hantsylabs/restexample/springmvc/model/ResponseMessage.java // public class ResponseMessage { // // public enum Type { // success, warning, danger, info; // } // // private Type type; // private String text; // private String code; // // public ResponseMessage(Type type, String text) { // this.type = type; // this.text = text; // } // // public ResponseMessage(Type type, String code, String message) { // this.type = type; // this.code = code; // this.text = message; // } // // public String getText() { // return text; // } // // public Type getType() { // return type; // } // // public String getCode() { // return code; // } // // public static ResponseMessage success(String text) { // return new ResponseMessage(Type.success, text); // } // // public static ResponseMessage warning(String text) { // return new ResponseMessage(Type.warning, text); // } // // public static ResponseMessage danger(String text) { // return new ResponseMessage(Type.danger, text); // } // // public static ResponseMessage info(String text) { // return new ResponseMessage(Type.info, text); // } // // private List<Error> errors = new ArrayList<Error>(); // // public List<Error> getErrors() { // return errors; // } // // public void setErrors(List<Error> errors) { // this.errors = errors; // } // // public void addError(String field, String code, String message) { // this.errors.add(new Error(field, code, message)); // } // // class Error { // // private String code; // private String message; // private String field; // // private Error(String field, String code, String message) { // this.field = field; // this.code = code; // this.message = message; // } // // public String getCode() { // return code; // } // // public void setCode(String code) { // this.code = code; // } // // public String getMessage() { // return message; // } // // public void setMessage(String message) { // this.message = message; // } // // public String getField() { // return field; // } // // public void setField(String field) { // this.field = field; // } // // } // // }
import com.hantsylabs.restexample.springmvc.ApiErrors; import com.hantsylabs.restexample.springmvc.exception.InvalidRequestException; import com.hantsylabs.restexample.springmvc.exception.ResourceNotFoundException; import com.hantsylabs.restexample.springmvc.exception.UsernameAlreadyUsedException; import com.hantsylabs.restexample.springmvc.model.ResponseMessage; import java.util.List; import javax.inject.Inject; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.context.MessageSource; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.validation.BindingResult; import org.springframework.validation.FieldError; import org.springframework.web.bind.annotation.ExceptionHandler; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.bind.annotation.RestControllerAdvice; import org.springframework.web.context.request.WebRequest;
package com.hantsylabs.restexample.springmvc.api; /** * Called when an exception occurs during request processing. Transforms exception message into JSON format. */ @RestControllerAdvice() public class RestExceptionHandler { private static final Logger log = LoggerFactory.getLogger(RestExceptionHandler.class); @Inject private MessageSource messageSource; @ExceptionHandler(value = {Exception.class, RuntimeException.class}) //@ResponseBody public ResponseEntity<ResponseMessage> handleGenericException(Exception ex, WebRequest request) { if (log.isDebugEnabled()) { log.debug("handling exception..."); } return new ResponseEntity<>(new ResponseMessage(ResponseMessage.Type.danger, ex.getMessage()), HttpStatus.BAD_REQUEST); }
// Path: src/main/java/com/hantsylabs/restexample/springmvc/ApiErrors.java // public class ApiErrors { // // private static final String PREFIX = "errors."; // // public static final String INVALID_REQUEST = PREFIX + "INVALID_REQUEST"; // // private ApiErrors() {} // // } // // Path: src/main/java/com/hantsylabs/restexample/springmvc/exception/InvalidRequestException.java // public class InvalidRequestException extends RuntimeException { // // private BindingResult errors; // // public InvalidRequestException(BindingResult errors) { // this.errors = errors; // } // // public BindingResult getErrors() { // return errors; // } // // } // // Path: src/main/java/com/hantsylabs/restexample/springmvc/exception/ResourceNotFoundException.java // public class ResourceNotFoundException extends RuntimeException { // // private static final long serialVersionUID = 1L; // // private Long id; // // public ResourceNotFoundException(Long id) { // super(String.format("resource %s was not found", id)); // this.id = id; // } // // public ResourceNotFoundException(String message) { // super(message); // } // // public Long getId() { // return id; // } // } // // Path: src/main/java/com/hantsylabs/restexample/springmvc/exception/UsernameAlreadyUsedException.java // public class UsernameAlreadyUsedException extends RuntimeException { // // private static final long serialVersionUID = 1L; // // private String username; // // public UsernameAlreadyUsedException(String username) { // this.username = username; // } // // public String getUsername() { // return username; // } // // } // // Path: src/main/java/com/hantsylabs/restexample/springmvc/model/ResponseMessage.java // public class ResponseMessage { // // public enum Type { // success, warning, danger, info; // } // // private Type type; // private String text; // private String code; // // public ResponseMessage(Type type, String text) { // this.type = type; // this.text = text; // } // // public ResponseMessage(Type type, String code, String message) { // this.type = type; // this.code = code; // this.text = message; // } // // public String getText() { // return text; // } // // public Type getType() { // return type; // } // // public String getCode() { // return code; // } // // public static ResponseMessage success(String text) { // return new ResponseMessage(Type.success, text); // } // // public static ResponseMessage warning(String text) { // return new ResponseMessage(Type.warning, text); // } // // public static ResponseMessage danger(String text) { // return new ResponseMessage(Type.danger, text); // } // // public static ResponseMessage info(String text) { // return new ResponseMessage(Type.info, text); // } // // private List<Error> errors = new ArrayList<Error>(); // // public List<Error> getErrors() { // return errors; // } // // public void setErrors(List<Error> errors) { // this.errors = errors; // } // // public void addError(String field, String code, String message) { // this.errors.add(new Error(field, code, message)); // } // // class Error { // // private String code; // private String message; // private String field; // // private Error(String field, String code, String message) { // this.field = field; // this.code = code; // this.message = message; // } // // public String getCode() { // return code; // } // // public void setCode(String code) { // this.code = code; // } // // public String getMessage() { // return message; // } // // public void setMessage(String message) { // this.message = message; // } // // public String getField() { // return field; // } // // public void setField(String field) { // this.field = field; // } // // } // // } // Path: src/main/java/com/hantsylabs/restexample/springmvc/api/RestExceptionHandler.java import com.hantsylabs.restexample.springmvc.ApiErrors; import com.hantsylabs.restexample.springmvc.exception.InvalidRequestException; import com.hantsylabs.restexample.springmvc.exception.ResourceNotFoundException; import com.hantsylabs.restexample.springmvc.exception.UsernameAlreadyUsedException; import com.hantsylabs.restexample.springmvc.model.ResponseMessage; import java.util.List; import javax.inject.Inject; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.context.MessageSource; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.validation.BindingResult; import org.springframework.validation.FieldError; import org.springframework.web.bind.annotation.ExceptionHandler; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.bind.annotation.RestControllerAdvice; import org.springframework.web.context.request.WebRequest; package com.hantsylabs.restexample.springmvc.api; /** * Called when an exception occurs during request processing. Transforms exception message into JSON format. */ @RestControllerAdvice() public class RestExceptionHandler { private static final Logger log = LoggerFactory.getLogger(RestExceptionHandler.class); @Inject private MessageSource messageSource; @ExceptionHandler(value = {Exception.class, RuntimeException.class}) //@ResponseBody public ResponseEntity<ResponseMessage> handleGenericException(Exception ex, WebRequest request) { if (log.isDebugEnabled()) { log.debug("handling exception..."); } return new ResponseEntity<>(new ResponseMessage(ResponseMessage.Type.danger, ex.getMessage()), HttpStatus.BAD_REQUEST); }
@ExceptionHandler(value = {ResourceNotFoundException.class})
hantsy/angularjs-springmvc-sample-boot
src/main/java/com/hantsylabs/restexample/springmvc/api/RestExceptionHandler.java
// Path: src/main/java/com/hantsylabs/restexample/springmvc/ApiErrors.java // public class ApiErrors { // // private static final String PREFIX = "errors."; // // public static final String INVALID_REQUEST = PREFIX + "INVALID_REQUEST"; // // private ApiErrors() {} // // } // // Path: src/main/java/com/hantsylabs/restexample/springmvc/exception/InvalidRequestException.java // public class InvalidRequestException extends RuntimeException { // // private BindingResult errors; // // public InvalidRequestException(BindingResult errors) { // this.errors = errors; // } // // public BindingResult getErrors() { // return errors; // } // // } // // Path: src/main/java/com/hantsylabs/restexample/springmvc/exception/ResourceNotFoundException.java // public class ResourceNotFoundException extends RuntimeException { // // private static final long serialVersionUID = 1L; // // private Long id; // // public ResourceNotFoundException(Long id) { // super(String.format("resource %s was not found", id)); // this.id = id; // } // // public ResourceNotFoundException(String message) { // super(message); // } // // public Long getId() { // return id; // } // } // // Path: src/main/java/com/hantsylabs/restexample/springmvc/exception/UsernameAlreadyUsedException.java // public class UsernameAlreadyUsedException extends RuntimeException { // // private static final long serialVersionUID = 1L; // // private String username; // // public UsernameAlreadyUsedException(String username) { // this.username = username; // } // // public String getUsername() { // return username; // } // // } // // Path: src/main/java/com/hantsylabs/restexample/springmvc/model/ResponseMessage.java // public class ResponseMessage { // // public enum Type { // success, warning, danger, info; // } // // private Type type; // private String text; // private String code; // // public ResponseMessage(Type type, String text) { // this.type = type; // this.text = text; // } // // public ResponseMessage(Type type, String code, String message) { // this.type = type; // this.code = code; // this.text = message; // } // // public String getText() { // return text; // } // // public Type getType() { // return type; // } // // public String getCode() { // return code; // } // // public static ResponseMessage success(String text) { // return new ResponseMessage(Type.success, text); // } // // public static ResponseMessage warning(String text) { // return new ResponseMessage(Type.warning, text); // } // // public static ResponseMessage danger(String text) { // return new ResponseMessage(Type.danger, text); // } // // public static ResponseMessage info(String text) { // return new ResponseMessage(Type.info, text); // } // // private List<Error> errors = new ArrayList<Error>(); // // public List<Error> getErrors() { // return errors; // } // // public void setErrors(List<Error> errors) { // this.errors = errors; // } // // public void addError(String field, String code, String message) { // this.errors.add(new Error(field, code, message)); // } // // class Error { // // private String code; // private String message; // private String field; // // private Error(String field, String code, String message) { // this.field = field; // this.code = code; // this.message = message; // } // // public String getCode() { // return code; // } // // public void setCode(String code) { // this.code = code; // } // // public String getMessage() { // return message; // } // // public void setMessage(String message) { // this.message = message; // } // // public String getField() { // return field; // } // // public void setField(String field) { // this.field = field; // } // // } // // }
import com.hantsylabs.restexample.springmvc.ApiErrors; import com.hantsylabs.restexample.springmvc.exception.InvalidRequestException; import com.hantsylabs.restexample.springmvc.exception.ResourceNotFoundException; import com.hantsylabs.restexample.springmvc.exception.UsernameAlreadyUsedException; import com.hantsylabs.restexample.springmvc.model.ResponseMessage; import java.util.List; import javax.inject.Inject; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.context.MessageSource; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.validation.BindingResult; import org.springframework.validation.FieldError; import org.springframework.web.bind.annotation.ExceptionHandler; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.bind.annotation.RestControllerAdvice; import org.springframework.web.context.request.WebRequest;
package com.hantsylabs.restexample.springmvc.api; /** * Called when an exception occurs during request processing. Transforms exception message into JSON format. */ @RestControllerAdvice() public class RestExceptionHandler { private static final Logger log = LoggerFactory.getLogger(RestExceptionHandler.class); @Inject private MessageSource messageSource; @ExceptionHandler(value = {Exception.class, RuntimeException.class}) //@ResponseBody public ResponseEntity<ResponseMessage> handleGenericException(Exception ex, WebRequest request) { if (log.isDebugEnabled()) { log.debug("handling exception..."); } return new ResponseEntity<>(new ResponseMessage(ResponseMessage.Type.danger, ex.getMessage()), HttpStatus.BAD_REQUEST); } @ExceptionHandler(value = {ResourceNotFoundException.class}) //@ResponseBody public ResponseEntity<ResponseMessage> handleResourceNotFoundException(ResourceNotFoundException ex, WebRequest request) { if (log.isDebugEnabled()) { log.debug("handling ResourceNotFoundException..."); } return new ResponseEntity<>(HttpStatus.NOT_FOUND); }
// Path: src/main/java/com/hantsylabs/restexample/springmvc/ApiErrors.java // public class ApiErrors { // // private static final String PREFIX = "errors."; // // public static final String INVALID_REQUEST = PREFIX + "INVALID_REQUEST"; // // private ApiErrors() {} // // } // // Path: src/main/java/com/hantsylabs/restexample/springmvc/exception/InvalidRequestException.java // public class InvalidRequestException extends RuntimeException { // // private BindingResult errors; // // public InvalidRequestException(BindingResult errors) { // this.errors = errors; // } // // public BindingResult getErrors() { // return errors; // } // // } // // Path: src/main/java/com/hantsylabs/restexample/springmvc/exception/ResourceNotFoundException.java // public class ResourceNotFoundException extends RuntimeException { // // private static final long serialVersionUID = 1L; // // private Long id; // // public ResourceNotFoundException(Long id) { // super(String.format("resource %s was not found", id)); // this.id = id; // } // // public ResourceNotFoundException(String message) { // super(message); // } // // public Long getId() { // return id; // } // } // // Path: src/main/java/com/hantsylabs/restexample/springmvc/exception/UsernameAlreadyUsedException.java // public class UsernameAlreadyUsedException extends RuntimeException { // // private static final long serialVersionUID = 1L; // // private String username; // // public UsernameAlreadyUsedException(String username) { // this.username = username; // } // // public String getUsername() { // return username; // } // // } // // Path: src/main/java/com/hantsylabs/restexample/springmvc/model/ResponseMessage.java // public class ResponseMessage { // // public enum Type { // success, warning, danger, info; // } // // private Type type; // private String text; // private String code; // // public ResponseMessage(Type type, String text) { // this.type = type; // this.text = text; // } // // public ResponseMessage(Type type, String code, String message) { // this.type = type; // this.code = code; // this.text = message; // } // // public String getText() { // return text; // } // // public Type getType() { // return type; // } // // public String getCode() { // return code; // } // // public static ResponseMessage success(String text) { // return new ResponseMessage(Type.success, text); // } // // public static ResponseMessage warning(String text) { // return new ResponseMessage(Type.warning, text); // } // // public static ResponseMessage danger(String text) { // return new ResponseMessage(Type.danger, text); // } // // public static ResponseMessage info(String text) { // return new ResponseMessage(Type.info, text); // } // // private List<Error> errors = new ArrayList<Error>(); // // public List<Error> getErrors() { // return errors; // } // // public void setErrors(List<Error> errors) { // this.errors = errors; // } // // public void addError(String field, String code, String message) { // this.errors.add(new Error(field, code, message)); // } // // class Error { // // private String code; // private String message; // private String field; // // private Error(String field, String code, String message) { // this.field = field; // this.code = code; // this.message = message; // } // // public String getCode() { // return code; // } // // public void setCode(String code) { // this.code = code; // } // // public String getMessage() { // return message; // } // // public void setMessage(String message) { // this.message = message; // } // // public String getField() { // return field; // } // // public void setField(String field) { // this.field = field; // } // // } // // } // Path: src/main/java/com/hantsylabs/restexample/springmvc/api/RestExceptionHandler.java import com.hantsylabs.restexample.springmvc.ApiErrors; import com.hantsylabs.restexample.springmvc.exception.InvalidRequestException; import com.hantsylabs.restexample.springmvc.exception.ResourceNotFoundException; import com.hantsylabs.restexample.springmvc.exception.UsernameAlreadyUsedException; import com.hantsylabs.restexample.springmvc.model.ResponseMessage; import java.util.List; import javax.inject.Inject; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.context.MessageSource; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.validation.BindingResult; import org.springframework.validation.FieldError; import org.springframework.web.bind.annotation.ExceptionHandler; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.bind.annotation.RestControllerAdvice; import org.springframework.web.context.request.WebRequest; package com.hantsylabs.restexample.springmvc.api; /** * Called when an exception occurs during request processing. Transforms exception message into JSON format. */ @RestControllerAdvice() public class RestExceptionHandler { private static final Logger log = LoggerFactory.getLogger(RestExceptionHandler.class); @Inject private MessageSource messageSource; @ExceptionHandler(value = {Exception.class, RuntimeException.class}) //@ResponseBody public ResponseEntity<ResponseMessage> handleGenericException(Exception ex, WebRequest request) { if (log.isDebugEnabled()) { log.debug("handling exception..."); } return new ResponseEntity<>(new ResponseMessage(ResponseMessage.Type.danger, ex.getMessage()), HttpStatus.BAD_REQUEST); } @ExceptionHandler(value = {ResourceNotFoundException.class}) //@ResponseBody public ResponseEntity<ResponseMessage> handleResourceNotFoundException(ResourceNotFoundException ex, WebRequest request) { if (log.isDebugEnabled()) { log.debug("handling ResourceNotFoundException..."); } return new ResponseEntity<>(HttpStatus.NOT_FOUND); }
@ExceptionHandler(value = {UsernameAlreadyUsedException.class})
hantsy/angularjs-springmvc-sample-boot
src/main/java/com/hantsylabs/restexample/springmvc/api/RestExceptionHandler.java
// Path: src/main/java/com/hantsylabs/restexample/springmvc/ApiErrors.java // public class ApiErrors { // // private static final String PREFIX = "errors."; // // public static final String INVALID_REQUEST = PREFIX + "INVALID_REQUEST"; // // private ApiErrors() {} // // } // // Path: src/main/java/com/hantsylabs/restexample/springmvc/exception/InvalidRequestException.java // public class InvalidRequestException extends RuntimeException { // // private BindingResult errors; // // public InvalidRequestException(BindingResult errors) { // this.errors = errors; // } // // public BindingResult getErrors() { // return errors; // } // // } // // Path: src/main/java/com/hantsylabs/restexample/springmvc/exception/ResourceNotFoundException.java // public class ResourceNotFoundException extends RuntimeException { // // private static final long serialVersionUID = 1L; // // private Long id; // // public ResourceNotFoundException(Long id) { // super(String.format("resource %s was not found", id)); // this.id = id; // } // // public ResourceNotFoundException(String message) { // super(message); // } // // public Long getId() { // return id; // } // } // // Path: src/main/java/com/hantsylabs/restexample/springmvc/exception/UsernameAlreadyUsedException.java // public class UsernameAlreadyUsedException extends RuntimeException { // // private static final long serialVersionUID = 1L; // // private String username; // // public UsernameAlreadyUsedException(String username) { // this.username = username; // } // // public String getUsername() { // return username; // } // // } // // Path: src/main/java/com/hantsylabs/restexample/springmvc/model/ResponseMessage.java // public class ResponseMessage { // // public enum Type { // success, warning, danger, info; // } // // private Type type; // private String text; // private String code; // // public ResponseMessage(Type type, String text) { // this.type = type; // this.text = text; // } // // public ResponseMessage(Type type, String code, String message) { // this.type = type; // this.code = code; // this.text = message; // } // // public String getText() { // return text; // } // // public Type getType() { // return type; // } // // public String getCode() { // return code; // } // // public static ResponseMessage success(String text) { // return new ResponseMessage(Type.success, text); // } // // public static ResponseMessage warning(String text) { // return new ResponseMessage(Type.warning, text); // } // // public static ResponseMessage danger(String text) { // return new ResponseMessage(Type.danger, text); // } // // public static ResponseMessage info(String text) { // return new ResponseMessage(Type.info, text); // } // // private List<Error> errors = new ArrayList<Error>(); // // public List<Error> getErrors() { // return errors; // } // // public void setErrors(List<Error> errors) { // this.errors = errors; // } // // public void addError(String field, String code, String message) { // this.errors.add(new Error(field, code, message)); // } // // class Error { // // private String code; // private String message; // private String field; // // private Error(String field, String code, String message) { // this.field = field; // this.code = code; // this.message = message; // } // // public String getCode() { // return code; // } // // public void setCode(String code) { // this.code = code; // } // // public String getMessage() { // return message; // } // // public void setMessage(String message) { // this.message = message; // } // // public String getField() { // return field; // } // // public void setField(String field) { // this.field = field; // } // // } // // }
import com.hantsylabs.restexample.springmvc.ApiErrors; import com.hantsylabs.restexample.springmvc.exception.InvalidRequestException; import com.hantsylabs.restexample.springmvc.exception.ResourceNotFoundException; import com.hantsylabs.restexample.springmvc.exception.UsernameAlreadyUsedException; import com.hantsylabs.restexample.springmvc.model.ResponseMessage; import java.util.List; import javax.inject.Inject; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.context.MessageSource; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.validation.BindingResult; import org.springframework.validation.FieldError; import org.springframework.web.bind.annotation.ExceptionHandler; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.bind.annotation.RestControllerAdvice; import org.springframework.web.context.request.WebRequest;
@ExceptionHandler(value = {ResourceNotFoundException.class}) //@ResponseBody public ResponseEntity<ResponseMessage> handleResourceNotFoundException(ResourceNotFoundException ex, WebRequest request) { if (log.isDebugEnabled()) { log.debug("handling ResourceNotFoundException..."); } return new ResponseEntity<>(HttpStatus.NOT_FOUND); } @ExceptionHandler(value = {UsernameAlreadyUsedException.class}) //@ResponseBody public ResponseEntity<ResponseMessage> handleUsernameExistedException(UsernameAlreadyUsedException ex, WebRequest request) { if (log.isDebugEnabled()) { log.debug("handling UsernameExistedException..."); } ResponseMessage error = ResponseMessage.danger("username existed."); return new ResponseEntity<>(error, HttpStatus.BAD_REQUEST); } @ExceptionHandler(value = {InvalidRequestException.class}) //@ResponseBody public ResponseEntity<ResponseMessage> handleInvalidRequestException(InvalidRequestException ex, WebRequest req) { if (log.isDebugEnabled()) { log.debug("handling InvalidRequestException..."); } ResponseMessage alert = new ResponseMessage( ResponseMessage.Type.danger,
// Path: src/main/java/com/hantsylabs/restexample/springmvc/ApiErrors.java // public class ApiErrors { // // private static final String PREFIX = "errors."; // // public static final String INVALID_REQUEST = PREFIX + "INVALID_REQUEST"; // // private ApiErrors() {} // // } // // Path: src/main/java/com/hantsylabs/restexample/springmvc/exception/InvalidRequestException.java // public class InvalidRequestException extends RuntimeException { // // private BindingResult errors; // // public InvalidRequestException(BindingResult errors) { // this.errors = errors; // } // // public BindingResult getErrors() { // return errors; // } // // } // // Path: src/main/java/com/hantsylabs/restexample/springmvc/exception/ResourceNotFoundException.java // public class ResourceNotFoundException extends RuntimeException { // // private static final long serialVersionUID = 1L; // // private Long id; // // public ResourceNotFoundException(Long id) { // super(String.format("resource %s was not found", id)); // this.id = id; // } // // public ResourceNotFoundException(String message) { // super(message); // } // // public Long getId() { // return id; // } // } // // Path: src/main/java/com/hantsylabs/restexample/springmvc/exception/UsernameAlreadyUsedException.java // public class UsernameAlreadyUsedException extends RuntimeException { // // private static final long serialVersionUID = 1L; // // private String username; // // public UsernameAlreadyUsedException(String username) { // this.username = username; // } // // public String getUsername() { // return username; // } // // } // // Path: src/main/java/com/hantsylabs/restexample/springmvc/model/ResponseMessage.java // public class ResponseMessage { // // public enum Type { // success, warning, danger, info; // } // // private Type type; // private String text; // private String code; // // public ResponseMessage(Type type, String text) { // this.type = type; // this.text = text; // } // // public ResponseMessage(Type type, String code, String message) { // this.type = type; // this.code = code; // this.text = message; // } // // public String getText() { // return text; // } // // public Type getType() { // return type; // } // // public String getCode() { // return code; // } // // public static ResponseMessage success(String text) { // return new ResponseMessage(Type.success, text); // } // // public static ResponseMessage warning(String text) { // return new ResponseMessage(Type.warning, text); // } // // public static ResponseMessage danger(String text) { // return new ResponseMessage(Type.danger, text); // } // // public static ResponseMessage info(String text) { // return new ResponseMessage(Type.info, text); // } // // private List<Error> errors = new ArrayList<Error>(); // // public List<Error> getErrors() { // return errors; // } // // public void setErrors(List<Error> errors) { // this.errors = errors; // } // // public void addError(String field, String code, String message) { // this.errors.add(new Error(field, code, message)); // } // // class Error { // // private String code; // private String message; // private String field; // // private Error(String field, String code, String message) { // this.field = field; // this.code = code; // this.message = message; // } // // public String getCode() { // return code; // } // // public void setCode(String code) { // this.code = code; // } // // public String getMessage() { // return message; // } // // public void setMessage(String message) { // this.message = message; // } // // public String getField() { // return field; // } // // public void setField(String field) { // this.field = field; // } // // } // // } // Path: src/main/java/com/hantsylabs/restexample/springmvc/api/RestExceptionHandler.java import com.hantsylabs.restexample.springmvc.ApiErrors; import com.hantsylabs.restexample.springmvc.exception.InvalidRequestException; import com.hantsylabs.restexample.springmvc.exception.ResourceNotFoundException; import com.hantsylabs.restexample.springmvc.exception.UsernameAlreadyUsedException; import com.hantsylabs.restexample.springmvc.model.ResponseMessage; import java.util.List; import javax.inject.Inject; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.context.MessageSource; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.validation.BindingResult; import org.springframework.validation.FieldError; import org.springframework.web.bind.annotation.ExceptionHandler; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.bind.annotation.RestControllerAdvice; import org.springframework.web.context.request.WebRequest; @ExceptionHandler(value = {ResourceNotFoundException.class}) //@ResponseBody public ResponseEntity<ResponseMessage> handleResourceNotFoundException(ResourceNotFoundException ex, WebRequest request) { if (log.isDebugEnabled()) { log.debug("handling ResourceNotFoundException..."); } return new ResponseEntity<>(HttpStatus.NOT_FOUND); } @ExceptionHandler(value = {UsernameAlreadyUsedException.class}) //@ResponseBody public ResponseEntity<ResponseMessage> handleUsernameExistedException(UsernameAlreadyUsedException ex, WebRequest request) { if (log.isDebugEnabled()) { log.debug("handling UsernameExistedException..."); } ResponseMessage error = ResponseMessage.danger("username existed."); return new ResponseEntity<>(error, HttpStatus.BAD_REQUEST); } @ExceptionHandler(value = {InvalidRequestException.class}) //@ResponseBody public ResponseEntity<ResponseMessage> handleInvalidRequestException(InvalidRequestException ex, WebRequest req) { if (log.isDebugEnabled()) { log.debug("handling InvalidRequestException..."); } ResponseMessage alert = new ResponseMessage( ResponseMessage.Type.danger,
ApiErrors.INVALID_REQUEST,
hantsy/angularjs-springmvc-sample-boot
src/main/java/com/hantsylabs/restexample/springmvc/service/DataImporter.java
// Path: src/main/java/com/hantsylabs/restexample/springmvc/domain/User.java // @Data // @Builder // @NoArgsConstructor // @AllArgsConstructor // @Entity // @Table(name = "users") // public class User implements UserDetails, Serializable { // // /** // * // */ // private static final long serialVersionUID = 1L; // // @Id() // @GeneratedValue(strategy = GenerationType.IDENTITY) // @Column(name = "id") // private Long id; // // @Column(name = "username") // private String username; // // @Column(name = "password") // private String password; // // @Column(name = "name") // private String name; // // @Column(name = "email") // private String email; // // @Column(name = "role") // private String role; // // @Column(name = "created_date") // @CreatedDate // private LocalDateTime createdDate; // // public String getName() { // if (this.name == null || this.name.trim().length() == 0) { // return this.username; // } // return name; // } // // @Override // public Collection<? extends GrantedAuthority> getAuthorities() { // return Arrays.asList(new SimpleGrantedAuthority("ROLE_" + this.role)); // } // // @Override // public String getPassword() { // return this.password; // } // // @Override // public String getUsername() { // return this.username; // } // // @Override // public boolean isAccountNonExpired() { // return true; // } // // @Override // public boolean isAccountNonLocked() { // return true; // } // // @Override // public boolean isCredentialsNonExpired() { // return true; // } // // @Override // // public boolean isEnabled() { // return true; // } // // // } // // Path: src/main/java/com/hantsylabs/restexample/springmvc/repository/UserRepository.java // public interface UserRepository extends JpaRepository<User, Long>, // JpaSpecificationExecutor<User> { // // public User findByUsername(String username); // }
import com.hantsylabs.restexample.springmvc.domain.User; import com.hantsylabs.restexample.springmvc.repository.UserRepository; import javax.inject.Inject; import javax.inject.Named; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.context.ApplicationListener; import org.springframework.context.event.ContextRefreshedEvent; import org.springframework.security.crypto.password.PasswordEncoder;
package com.hantsylabs.restexample.springmvc.service; @Named public class DataImporter implements ApplicationListener<ContextRefreshedEvent> { private static final Logger log = LoggerFactory .getLogger(DataImporter.class); @Inject
// Path: src/main/java/com/hantsylabs/restexample/springmvc/domain/User.java // @Data // @Builder // @NoArgsConstructor // @AllArgsConstructor // @Entity // @Table(name = "users") // public class User implements UserDetails, Serializable { // // /** // * // */ // private static final long serialVersionUID = 1L; // // @Id() // @GeneratedValue(strategy = GenerationType.IDENTITY) // @Column(name = "id") // private Long id; // // @Column(name = "username") // private String username; // // @Column(name = "password") // private String password; // // @Column(name = "name") // private String name; // // @Column(name = "email") // private String email; // // @Column(name = "role") // private String role; // // @Column(name = "created_date") // @CreatedDate // private LocalDateTime createdDate; // // public String getName() { // if (this.name == null || this.name.trim().length() == 0) { // return this.username; // } // return name; // } // // @Override // public Collection<? extends GrantedAuthority> getAuthorities() { // return Arrays.asList(new SimpleGrantedAuthority("ROLE_" + this.role)); // } // // @Override // public String getPassword() { // return this.password; // } // // @Override // public String getUsername() { // return this.username; // } // // @Override // public boolean isAccountNonExpired() { // return true; // } // // @Override // public boolean isAccountNonLocked() { // return true; // } // // @Override // public boolean isCredentialsNonExpired() { // return true; // } // // @Override // // public boolean isEnabled() { // return true; // } // // // } // // Path: src/main/java/com/hantsylabs/restexample/springmvc/repository/UserRepository.java // public interface UserRepository extends JpaRepository<User, Long>, // JpaSpecificationExecutor<User> { // // public User findByUsername(String username); // } // Path: src/main/java/com/hantsylabs/restexample/springmvc/service/DataImporter.java import com.hantsylabs.restexample.springmvc.domain.User; import com.hantsylabs.restexample.springmvc.repository.UserRepository; import javax.inject.Inject; import javax.inject.Named; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.context.ApplicationListener; import org.springframework.context.event.ContextRefreshedEvent; import org.springframework.security.crypto.password.PasswordEncoder; package com.hantsylabs.restexample.springmvc.service; @Named public class DataImporter implements ApplicationListener<ContextRefreshedEvent> { private static final Logger log = LoggerFactory .getLogger(DataImporter.class); @Inject
private UserRepository userRepository;
hantsy/angularjs-springmvc-sample-boot
src/main/java/com/hantsylabs/restexample/springmvc/service/DataImporter.java
// Path: src/main/java/com/hantsylabs/restexample/springmvc/domain/User.java // @Data // @Builder // @NoArgsConstructor // @AllArgsConstructor // @Entity // @Table(name = "users") // public class User implements UserDetails, Serializable { // // /** // * // */ // private static final long serialVersionUID = 1L; // // @Id() // @GeneratedValue(strategy = GenerationType.IDENTITY) // @Column(name = "id") // private Long id; // // @Column(name = "username") // private String username; // // @Column(name = "password") // private String password; // // @Column(name = "name") // private String name; // // @Column(name = "email") // private String email; // // @Column(name = "role") // private String role; // // @Column(name = "created_date") // @CreatedDate // private LocalDateTime createdDate; // // public String getName() { // if (this.name == null || this.name.trim().length() == 0) { // return this.username; // } // return name; // } // // @Override // public Collection<? extends GrantedAuthority> getAuthorities() { // return Arrays.asList(new SimpleGrantedAuthority("ROLE_" + this.role)); // } // // @Override // public String getPassword() { // return this.password; // } // // @Override // public String getUsername() { // return this.username; // } // // @Override // public boolean isAccountNonExpired() { // return true; // } // // @Override // public boolean isAccountNonLocked() { // return true; // } // // @Override // public boolean isCredentialsNonExpired() { // return true; // } // // @Override // // public boolean isEnabled() { // return true; // } // // // } // // Path: src/main/java/com/hantsylabs/restexample/springmvc/repository/UserRepository.java // public interface UserRepository extends JpaRepository<User, Long>, // JpaSpecificationExecutor<User> { // // public User findByUsername(String username); // }
import com.hantsylabs.restexample.springmvc.domain.User; import com.hantsylabs.restexample.springmvc.repository.UserRepository; import javax.inject.Inject; import javax.inject.Named; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.context.ApplicationListener; import org.springframework.context.event.ContextRefreshedEvent; import org.springframework.security.crypto.password.PasswordEncoder;
package com.hantsylabs.restexample.springmvc.service; @Named public class DataImporter implements ApplicationListener<ContextRefreshedEvent> { private static final Logger log = LoggerFactory .getLogger(DataImporter.class); @Inject private UserRepository userRepository; @Inject private PasswordEncoder passwordEncoder; @Override public void onApplicationEvent(ContextRefreshedEvent event) { if (log.isInfoEnabled()) { log.info("importing data into database..."); } Long usersCount = userRepository.count(); if (usersCount == 0) { if (log.isDebugEnabled()) { log.debug("import users data into database..."); } userRepository.save(
// Path: src/main/java/com/hantsylabs/restexample/springmvc/domain/User.java // @Data // @Builder // @NoArgsConstructor // @AllArgsConstructor // @Entity // @Table(name = "users") // public class User implements UserDetails, Serializable { // // /** // * // */ // private static final long serialVersionUID = 1L; // // @Id() // @GeneratedValue(strategy = GenerationType.IDENTITY) // @Column(name = "id") // private Long id; // // @Column(name = "username") // private String username; // // @Column(name = "password") // private String password; // // @Column(name = "name") // private String name; // // @Column(name = "email") // private String email; // // @Column(name = "role") // private String role; // // @Column(name = "created_date") // @CreatedDate // private LocalDateTime createdDate; // // public String getName() { // if (this.name == null || this.name.trim().length() == 0) { // return this.username; // } // return name; // } // // @Override // public Collection<? extends GrantedAuthority> getAuthorities() { // return Arrays.asList(new SimpleGrantedAuthority("ROLE_" + this.role)); // } // // @Override // public String getPassword() { // return this.password; // } // // @Override // public String getUsername() { // return this.username; // } // // @Override // public boolean isAccountNonExpired() { // return true; // } // // @Override // public boolean isAccountNonLocked() { // return true; // } // // @Override // public boolean isCredentialsNonExpired() { // return true; // } // // @Override // // public boolean isEnabled() { // return true; // } // // // } // // Path: src/main/java/com/hantsylabs/restexample/springmvc/repository/UserRepository.java // public interface UserRepository extends JpaRepository<User, Long>, // JpaSpecificationExecutor<User> { // // public User findByUsername(String username); // } // Path: src/main/java/com/hantsylabs/restexample/springmvc/service/DataImporter.java import com.hantsylabs.restexample.springmvc.domain.User; import com.hantsylabs.restexample.springmvc.repository.UserRepository; import javax.inject.Inject; import javax.inject.Named; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.context.ApplicationListener; import org.springframework.context.event.ContextRefreshedEvent; import org.springframework.security.crypto.password.PasswordEncoder; package com.hantsylabs.restexample.springmvc.service; @Named public class DataImporter implements ApplicationListener<ContextRefreshedEvent> { private static final Logger log = LoggerFactory .getLogger(DataImporter.class); @Inject private UserRepository userRepository; @Inject private PasswordEncoder passwordEncoder; @Override public void onApplicationEvent(ContextRefreshedEvent event) { if (log.isInfoEnabled()) { log.info("importing data into database..."); } Long usersCount = userRepository.count(); if (usersCount == 0) { if (log.isDebugEnabled()) { log.debug("import users data into database..."); } userRepository.save(
User.builder()
hantsy/angularjs-springmvc-sample-boot
src/test/java/com/hantsylabs/restexample/springmvc/test/IntegrationTestBase.java
// Path: src/main/java/com/hantsylabs/restexample/springmvc/repository/CommentRepository.java // public interface CommentRepository extends JpaRepository<Comment, Long> { // // public List<Comment> findByPost(Post post); // // public Page<Comment> findByPostId(Long id, Pageable page); // // } // // Path: src/main/java/com/hantsylabs/restexample/springmvc/repository/PostRepository.java // public interface PostRepository extends JpaRepository<Post, Long>,// // JpaSpecificationExecutor<Post>{ // // } // // Path: src/main/java/com/hantsylabs/restexample/springmvc/repository/UserRepository.java // public interface UserRepository extends JpaRepository<User, Long>, // JpaSpecificationExecutor<User> { // // public User findByUsername(String username); // }
import com.hantsylabs.restexample.springmvc.repository.CommentRepository; import com.hantsylabs.restexample.springmvc.repository.PostRepository; import com.hantsylabs.restexample.springmvc.repository.UserRepository; import com.jayway.restassured.RestAssured; import javax.inject.Inject; import org.junit.Before; import org.springframework.beans.factory.annotation.Value; import org.springframework.security.crypto.password.PasswordEncoder;
package com.hantsylabs.restexample.springmvc.test; /** * * @author hantsy */ public class IntegrationTestBase { protected static final String USER_NAME = "admin"; protected final static String PASSWORD = "test123"; @Inject
// Path: src/main/java/com/hantsylabs/restexample/springmvc/repository/CommentRepository.java // public interface CommentRepository extends JpaRepository<Comment, Long> { // // public List<Comment> findByPost(Post post); // // public Page<Comment> findByPostId(Long id, Pageable page); // // } // // Path: src/main/java/com/hantsylabs/restexample/springmvc/repository/PostRepository.java // public interface PostRepository extends JpaRepository<Post, Long>,// // JpaSpecificationExecutor<Post>{ // // } // // Path: src/main/java/com/hantsylabs/restexample/springmvc/repository/UserRepository.java // public interface UserRepository extends JpaRepository<User, Long>, // JpaSpecificationExecutor<User> { // // public User findByUsername(String username); // } // Path: src/test/java/com/hantsylabs/restexample/springmvc/test/IntegrationTestBase.java import com.hantsylabs.restexample.springmvc.repository.CommentRepository; import com.hantsylabs.restexample.springmvc.repository.PostRepository; import com.hantsylabs.restexample.springmvc.repository.UserRepository; import com.jayway.restassured.RestAssured; import javax.inject.Inject; import org.junit.Before; import org.springframework.beans.factory.annotation.Value; import org.springframework.security.crypto.password.PasswordEncoder; package com.hantsylabs.restexample.springmvc.test; /** * * @author hantsy */ public class IntegrationTestBase { protected static final String USER_NAME = "admin"; protected final static String PASSWORD = "test123"; @Inject
PostRepository posts;
hantsy/angularjs-springmvc-sample-boot
src/test/java/com/hantsylabs/restexample/springmvc/test/IntegrationTestBase.java
// Path: src/main/java/com/hantsylabs/restexample/springmvc/repository/CommentRepository.java // public interface CommentRepository extends JpaRepository<Comment, Long> { // // public List<Comment> findByPost(Post post); // // public Page<Comment> findByPostId(Long id, Pageable page); // // } // // Path: src/main/java/com/hantsylabs/restexample/springmvc/repository/PostRepository.java // public interface PostRepository extends JpaRepository<Post, Long>,// // JpaSpecificationExecutor<Post>{ // // } // // Path: src/main/java/com/hantsylabs/restexample/springmvc/repository/UserRepository.java // public interface UserRepository extends JpaRepository<User, Long>, // JpaSpecificationExecutor<User> { // // public User findByUsername(String username); // }
import com.hantsylabs.restexample.springmvc.repository.CommentRepository; import com.hantsylabs.restexample.springmvc.repository.PostRepository; import com.hantsylabs.restexample.springmvc.repository.UserRepository; import com.jayway.restassured.RestAssured; import javax.inject.Inject; import org.junit.Before; import org.springframework.beans.factory.annotation.Value; import org.springframework.security.crypto.password.PasswordEncoder;
package com.hantsylabs.restexample.springmvc.test; /** * * @author hantsy */ public class IntegrationTestBase { protected static final String USER_NAME = "admin"; protected final static String PASSWORD = "test123"; @Inject PostRepository posts; @Inject
// Path: src/main/java/com/hantsylabs/restexample/springmvc/repository/CommentRepository.java // public interface CommentRepository extends JpaRepository<Comment, Long> { // // public List<Comment> findByPost(Post post); // // public Page<Comment> findByPostId(Long id, Pageable page); // // } // // Path: src/main/java/com/hantsylabs/restexample/springmvc/repository/PostRepository.java // public interface PostRepository extends JpaRepository<Post, Long>,// // JpaSpecificationExecutor<Post>{ // // } // // Path: src/main/java/com/hantsylabs/restexample/springmvc/repository/UserRepository.java // public interface UserRepository extends JpaRepository<User, Long>, // JpaSpecificationExecutor<User> { // // public User findByUsername(String username); // } // Path: src/test/java/com/hantsylabs/restexample/springmvc/test/IntegrationTestBase.java import com.hantsylabs.restexample.springmvc.repository.CommentRepository; import com.hantsylabs.restexample.springmvc.repository.PostRepository; import com.hantsylabs.restexample.springmvc.repository.UserRepository; import com.jayway.restassured.RestAssured; import javax.inject.Inject; import org.junit.Before; import org.springframework.beans.factory.annotation.Value; import org.springframework.security.crypto.password.PasswordEncoder; package com.hantsylabs.restexample.springmvc.test; /** * * @author hantsy */ public class IntegrationTestBase { protected static final String USER_NAME = "admin"; protected final static String PASSWORD = "test123"; @Inject PostRepository posts; @Inject
CommentRepository comments;
hantsy/angularjs-springmvc-sample-boot
src/test/java/com/hantsylabs/restexample/springmvc/test/IntegrationTestBase.java
// Path: src/main/java/com/hantsylabs/restexample/springmvc/repository/CommentRepository.java // public interface CommentRepository extends JpaRepository<Comment, Long> { // // public List<Comment> findByPost(Post post); // // public Page<Comment> findByPostId(Long id, Pageable page); // // } // // Path: src/main/java/com/hantsylabs/restexample/springmvc/repository/PostRepository.java // public interface PostRepository extends JpaRepository<Post, Long>,// // JpaSpecificationExecutor<Post>{ // // } // // Path: src/main/java/com/hantsylabs/restexample/springmvc/repository/UserRepository.java // public interface UserRepository extends JpaRepository<User, Long>, // JpaSpecificationExecutor<User> { // // public User findByUsername(String username); // }
import com.hantsylabs.restexample.springmvc.repository.CommentRepository; import com.hantsylabs.restexample.springmvc.repository.PostRepository; import com.hantsylabs.restexample.springmvc.repository.UserRepository; import com.jayway.restassured.RestAssured; import javax.inject.Inject; import org.junit.Before; import org.springframework.beans.factory.annotation.Value; import org.springframework.security.crypto.password.PasswordEncoder;
package com.hantsylabs.restexample.springmvc.test; /** * * @author hantsy */ public class IntegrationTestBase { protected static final String USER_NAME = "admin"; protected final static String PASSWORD = "test123"; @Inject PostRepository posts; @Inject CommentRepository comments; @Inject
// Path: src/main/java/com/hantsylabs/restexample/springmvc/repository/CommentRepository.java // public interface CommentRepository extends JpaRepository<Comment, Long> { // // public List<Comment> findByPost(Post post); // // public Page<Comment> findByPostId(Long id, Pageable page); // // } // // Path: src/main/java/com/hantsylabs/restexample/springmvc/repository/PostRepository.java // public interface PostRepository extends JpaRepository<Post, Long>,// // JpaSpecificationExecutor<Post>{ // // } // // Path: src/main/java/com/hantsylabs/restexample/springmvc/repository/UserRepository.java // public interface UserRepository extends JpaRepository<User, Long>, // JpaSpecificationExecutor<User> { // // public User findByUsername(String username); // } // Path: src/test/java/com/hantsylabs/restexample/springmvc/test/IntegrationTestBase.java import com.hantsylabs.restexample.springmvc.repository.CommentRepository; import com.hantsylabs.restexample.springmvc.repository.PostRepository; import com.hantsylabs.restexample.springmvc.repository.UserRepository; import com.jayway.restassured.RestAssured; import javax.inject.Inject; import org.junit.Before; import org.springframework.beans.factory.annotation.Value; import org.springframework.security.crypto.password.PasswordEncoder; package com.hantsylabs.restexample.springmvc.test; /** * * @author hantsy */ public class IntegrationTestBase { protected static final String USER_NAME = "admin"; protected final static String PASSWORD = "test123"; @Inject PostRepository posts; @Inject CommentRepository comments; @Inject
UserRepository users;
hantsy/angularjs-springmvc-sample-boot
src/test/java/com/hantsylabs/restexample/springmvc/test/jbehave/AbstractSpringJBehaveStory.java
// Path: src/main/java/com/hantsylabs/restexample/springmvc/domain/User.java // @Data // @Builder // @NoArgsConstructor // @AllArgsConstructor // @Entity // @Table(name = "users") // public class User implements UserDetails, Serializable { // // /** // * // */ // private static final long serialVersionUID = 1L; // // @Id() // @GeneratedValue(strategy = GenerationType.IDENTITY) // @Column(name = "id") // private Long id; // // @Column(name = "username") // private String username; // // @Column(name = "password") // private String password; // // @Column(name = "name") // private String name; // // @Column(name = "email") // private String email; // // @Column(name = "role") // private String role; // // @Column(name = "created_date") // @CreatedDate // private LocalDateTime createdDate; // // public String getName() { // if (this.name == null || this.name.trim().length() == 0) { // return this.username; // } // return name; // } // // @Override // public Collection<? extends GrantedAuthority> getAuthorities() { // return Arrays.asList(new SimpleGrantedAuthority("ROLE_" + this.role)); // } // // @Override // public String getPassword() { // return this.password; // } // // @Override // public String getUsername() { // return this.username; // } // // @Override // public boolean isAccountNonExpired() { // return true; // } // // @Override // public boolean isAccountNonLocked() { // return true; // } // // @Override // public boolean isCredentialsNonExpired() { // return true; // } // // @Override // // public boolean isEnabled() { // return true; // } // // // } // // Path: src/main/java/com/hantsylabs/restexample/springmvc/repository/CommentRepository.java // public interface CommentRepository extends JpaRepository<Comment, Long> { // // public List<Comment> findByPost(Post post); // // public Page<Comment> findByPostId(Long id, Pageable page); // // } // // Path: src/main/java/com/hantsylabs/restexample/springmvc/repository/PostRepository.java // public interface PostRepository extends JpaRepository<Post, Long>,// // JpaSpecificationExecutor<Post>{ // // } // // Path: src/main/java/com/hantsylabs/restexample/springmvc/repository/UserRepository.java // public interface UserRepository extends JpaRepository<User, Long>, // JpaSpecificationExecutor<User> { // // public User findByUsername(String username); // }
import com.hantsylabs.restexample.springmvc.domain.User; import com.hantsylabs.restexample.springmvc.repository.CommentRepository; import com.hantsylabs.restexample.springmvc.repository.PostRepository; import com.hantsylabs.restexample.springmvc.repository.UserRepository; import org.jbehave.core.configuration.Configuration; import org.jbehave.core.configuration.MostUsefulConfiguration; import org.jbehave.core.embedder.Embedder; import org.jbehave.core.embedder.EmbedderControls; import org.jbehave.core.io.*; import org.jbehave.core.junit.JUnitStory; import org.jbehave.core.reporters.FilePrintStreamFactory.ResolveToPackagedName; import org.jbehave.core.reporters.StoryReporterBuilder; import org.jbehave.core.steps.ParameterControls; import java.util.Arrays; import javax.inject.Inject; import lombok.extern.slf4j.Slf4j; import static org.jbehave.core.reporters.Format.*; import org.jbehave.core.steps.InjectableStepsFactory; import org.jbehave.core.steps.InstanceStepsFactory; import org.springframework.security.crypto.password.PasswordEncoder;
package com.hantsylabs.restexample.springmvc.test.jbehave; @Slf4j public abstract class AbstractSpringJBehaveStory extends JUnitStory { @Inject
// Path: src/main/java/com/hantsylabs/restexample/springmvc/domain/User.java // @Data // @Builder // @NoArgsConstructor // @AllArgsConstructor // @Entity // @Table(name = "users") // public class User implements UserDetails, Serializable { // // /** // * // */ // private static final long serialVersionUID = 1L; // // @Id() // @GeneratedValue(strategy = GenerationType.IDENTITY) // @Column(name = "id") // private Long id; // // @Column(name = "username") // private String username; // // @Column(name = "password") // private String password; // // @Column(name = "name") // private String name; // // @Column(name = "email") // private String email; // // @Column(name = "role") // private String role; // // @Column(name = "created_date") // @CreatedDate // private LocalDateTime createdDate; // // public String getName() { // if (this.name == null || this.name.trim().length() == 0) { // return this.username; // } // return name; // } // // @Override // public Collection<? extends GrantedAuthority> getAuthorities() { // return Arrays.asList(new SimpleGrantedAuthority("ROLE_" + this.role)); // } // // @Override // public String getPassword() { // return this.password; // } // // @Override // public String getUsername() { // return this.username; // } // // @Override // public boolean isAccountNonExpired() { // return true; // } // // @Override // public boolean isAccountNonLocked() { // return true; // } // // @Override // public boolean isCredentialsNonExpired() { // return true; // } // // @Override // // public boolean isEnabled() { // return true; // } // // // } // // Path: src/main/java/com/hantsylabs/restexample/springmvc/repository/CommentRepository.java // public interface CommentRepository extends JpaRepository<Comment, Long> { // // public List<Comment> findByPost(Post post); // // public Page<Comment> findByPostId(Long id, Pageable page); // // } // // Path: src/main/java/com/hantsylabs/restexample/springmvc/repository/PostRepository.java // public interface PostRepository extends JpaRepository<Post, Long>,// // JpaSpecificationExecutor<Post>{ // // } // // Path: src/main/java/com/hantsylabs/restexample/springmvc/repository/UserRepository.java // public interface UserRepository extends JpaRepository<User, Long>, // JpaSpecificationExecutor<User> { // // public User findByUsername(String username); // } // Path: src/test/java/com/hantsylabs/restexample/springmvc/test/jbehave/AbstractSpringJBehaveStory.java import com.hantsylabs.restexample.springmvc.domain.User; import com.hantsylabs.restexample.springmvc.repository.CommentRepository; import com.hantsylabs.restexample.springmvc.repository.PostRepository; import com.hantsylabs.restexample.springmvc.repository.UserRepository; import org.jbehave.core.configuration.Configuration; import org.jbehave.core.configuration.MostUsefulConfiguration; import org.jbehave.core.embedder.Embedder; import org.jbehave.core.embedder.EmbedderControls; import org.jbehave.core.io.*; import org.jbehave.core.junit.JUnitStory; import org.jbehave.core.reporters.FilePrintStreamFactory.ResolveToPackagedName; import org.jbehave.core.reporters.StoryReporterBuilder; import org.jbehave.core.steps.ParameterControls; import java.util.Arrays; import javax.inject.Inject; import lombok.extern.slf4j.Slf4j; import static org.jbehave.core.reporters.Format.*; import org.jbehave.core.steps.InjectableStepsFactory; import org.jbehave.core.steps.InstanceStepsFactory; import org.springframework.security.crypto.password.PasswordEncoder; package com.hantsylabs.restexample.springmvc.test.jbehave; @Slf4j public abstract class AbstractSpringJBehaveStory extends JUnitStory { @Inject
PostRepository posts;
hantsy/angularjs-springmvc-sample-boot
src/test/java/com/hantsylabs/restexample/springmvc/test/jbehave/AbstractSpringJBehaveStory.java
// Path: src/main/java/com/hantsylabs/restexample/springmvc/domain/User.java // @Data // @Builder // @NoArgsConstructor // @AllArgsConstructor // @Entity // @Table(name = "users") // public class User implements UserDetails, Serializable { // // /** // * // */ // private static final long serialVersionUID = 1L; // // @Id() // @GeneratedValue(strategy = GenerationType.IDENTITY) // @Column(name = "id") // private Long id; // // @Column(name = "username") // private String username; // // @Column(name = "password") // private String password; // // @Column(name = "name") // private String name; // // @Column(name = "email") // private String email; // // @Column(name = "role") // private String role; // // @Column(name = "created_date") // @CreatedDate // private LocalDateTime createdDate; // // public String getName() { // if (this.name == null || this.name.trim().length() == 0) { // return this.username; // } // return name; // } // // @Override // public Collection<? extends GrantedAuthority> getAuthorities() { // return Arrays.asList(new SimpleGrantedAuthority("ROLE_" + this.role)); // } // // @Override // public String getPassword() { // return this.password; // } // // @Override // public String getUsername() { // return this.username; // } // // @Override // public boolean isAccountNonExpired() { // return true; // } // // @Override // public boolean isAccountNonLocked() { // return true; // } // // @Override // public boolean isCredentialsNonExpired() { // return true; // } // // @Override // // public boolean isEnabled() { // return true; // } // // // } // // Path: src/main/java/com/hantsylabs/restexample/springmvc/repository/CommentRepository.java // public interface CommentRepository extends JpaRepository<Comment, Long> { // // public List<Comment> findByPost(Post post); // // public Page<Comment> findByPostId(Long id, Pageable page); // // } // // Path: src/main/java/com/hantsylabs/restexample/springmvc/repository/PostRepository.java // public interface PostRepository extends JpaRepository<Post, Long>,// // JpaSpecificationExecutor<Post>{ // // } // // Path: src/main/java/com/hantsylabs/restexample/springmvc/repository/UserRepository.java // public interface UserRepository extends JpaRepository<User, Long>, // JpaSpecificationExecutor<User> { // // public User findByUsername(String username); // }
import com.hantsylabs.restexample.springmvc.domain.User; import com.hantsylabs.restexample.springmvc.repository.CommentRepository; import com.hantsylabs.restexample.springmvc.repository.PostRepository; import com.hantsylabs.restexample.springmvc.repository.UserRepository; import org.jbehave.core.configuration.Configuration; import org.jbehave.core.configuration.MostUsefulConfiguration; import org.jbehave.core.embedder.Embedder; import org.jbehave.core.embedder.EmbedderControls; import org.jbehave.core.io.*; import org.jbehave.core.junit.JUnitStory; import org.jbehave.core.reporters.FilePrintStreamFactory.ResolveToPackagedName; import org.jbehave.core.reporters.StoryReporterBuilder; import org.jbehave.core.steps.ParameterControls; import java.util.Arrays; import javax.inject.Inject; import lombok.extern.slf4j.Slf4j; import static org.jbehave.core.reporters.Format.*; import org.jbehave.core.steps.InjectableStepsFactory; import org.jbehave.core.steps.InstanceStepsFactory; import org.springframework.security.crypto.password.PasswordEncoder;
package com.hantsylabs.restexample.springmvc.test.jbehave; @Slf4j public abstract class AbstractSpringJBehaveStory extends JUnitStory { @Inject PostRepository posts; @Inject
// Path: src/main/java/com/hantsylabs/restexample/springmvc/domain/User.java // @Data // @Builder // @NoArgsConstructor // @AllArgsConstructor // @Entity // @Table(name = "users") // public class User implements UserDetails, Serializable { // // /** // * // */ // private static final long serialVersionUID = 1L; // // @Id() // @GeneratedValue(strategy = GenerationType.IDENTITY) // @Column(name = "id") // private Long id; // // @Column(name = "username") // private String username; // // @Column(name = "password") // private String password; // // @Column(name = "name") // private String name; // // @Column(name = "email") // private String email; // // @Column(name = "role") // private String role; // // @Column(name = "created_date") // @CreatedDate // private LocalDateTime createdDate; // // public String getName() { // if (this.name == null || this.name.trim().length() == 0) { // return this.username; // } // return name; // } // // @Override // public Collection<? extends GrantedAuthority> getAuthorities() { // return Arrays.asList(new SimpleGrantedAuthority("ROLE_" + this.role)); // } // // @Override // public String getPassword() { // return this.password; // } // // @Override // public String getUsername() { // return this.username; // } // // @Override // public boolean isAccountNonExpired() { // return true; // } // // @Override // public boolean isAccountNonLocked() { // return true; // } // // @Override // public boolean isCredentialsNonExpired() { // return true; // } // // @Override // // public boolean isEnabled() { // return true; // } // // // } // // Path: src/main/java/com/hantsylabs/restexample/springmvc/repository/CommentRepository.java // public interface CommentRepository extends JpaRepository<Comment, Long> { // // public List<Comment> findByPost(Post post); // // public Page<Comment> findByPostId(Long id, Pageable page); // // } // // Path: src/main/java/com/hantsylabs/restexample/springmvc/repository/PostRepository.java // public interface PostRepository extends JpaRepository<Post, Long>,// // JpaSpecificationExecutor<Post>{ // // } // // Path: src/main/java/com/hantsylabs/restexample/springmvc/repository/UserRepository.java // public interface UserRepository extends JpaRepository<User, Long>, // JpaSpecificationExecutor<User> { // // public User findByUsername(String username); // } // Path: src/test/java/com/hantsylabs/restexample/springmvc/test/jbehave/AbstractSpringJBehaveStory.java import com.hantsylabs.restexample.springmvc.domain.User; import com.hantsylabs.restexample.springmvc.repository.CommentRepository; import com.hantsylabs.restexample.springmvc.repository.PostRepository; import com.hantsylabs.restexample.springmvc.repository.UserRepository; import org.jbehave.core.configuration.Configuration; import org.jbehave.core.configuration.MostUsefulConfiguration; import org.jbehave.core.embedder.Embedder; import org.jbehave.core.embedder.EmbedderControls; import org.jbehave.core.io.*; import org.jbehave.core.junit.JUnitStory; import org.jbehave.core.reporters.FilePrintStreamFactory.ResolveToPackagedName; import org.jbehave.core.reporters.StoryReporterBuilder; import org.jbehave.core.steps.ParameterControls; import java.util.Arrays; import javax.inject.Inject; import lombok.extern.slf4j.Slf4j; import static org.jbehave.core.reporters.Format.*; import org.jbehave.core.steps.InjectableStepsFactory; import org.jbehave.core.steps.InstanceStepsFactory; import org.springframework.security.crypto.password.PasswordEncoder; package com.hantsylabs.restexample.springmvc.test.jbehave; @Slf4j public abstract class AbstractSpringJBehaveStory extends JUnitStory { @Inject PostRepository posts; @Inject
CommentRepository comments;
hantsy/angularjs-springmvc-sample-boot
src/test/java/com/hantsylabs/restexample/springmvc/test/jbehave/AbstractSpringJBehaveStory.java
// Path: src/main/java/com/hantsylabs/restexample/springmvc/domain/User.java // @Data // @Builder // @NoArgsConstructor // @AllArgsConstructor // @Entity // @Table(name = "users") // public class User implements UserDetails, Serializable { // // /** // * // */ // private static final long serialVersionUID = 1L; // // @Id() // @GeneratedValue(strategy = GenerationType.IDENTITY) // @Column(name = "id") // private Long id; // // @Column(name = "username") // private String username; // // @Column(name = "password") // private String password; // // @Column(name = "name") // private String name; // // @Column(name = "email") // private String email; // // @Column(name = "role") // private String role; // // @Column(name = "created_date") // @CreatedDate // private LocalDateTime createdDate; // // public String getName() { // if (this.name == null || this.name.trim().length() == 0) { // return this.username; // } // return name; // } // // @Override // public Collection<? extends GrantedAuthority> getAuthorities() { // return Arrays.asList(new SimpleGrantedAuthority("ROLE_" + this.role)); // } // // @Override // public String getPassword() { // return this.password; // } // // @Override // public String getUsername() { // return this.username; // } // // @Override // public boolean isAccountNonExpired() { // return true; // } // // @Override // public boolean isAccountNonLocked() { // return true; // } // // @Override // public boolean isCredentialsNonExpired() { // return true; // } // // @Override // // public boolean isEnabled() { // return true; // } // // // } // // Path: src/main/java/com/hantsylabs/restexample/springmvc/repository/CommentRepository.java // public interface CommentRepository extends JpaRepository<Comment, Long> { // // public List<Comment> findByPost(Post post); // // public Page<Comment> findByPostId(Long id, Pageable page); // // } // // Path: src/main/java/com/hantsylabs/restexample/springmvc/repository/PostRepository.java // public interface PostRepository extends JpaRepository<Post, Long>,// // JpaSpecificationExecutor<Post>{ // // } // // Path: src/main/java/com/hantsylabs/restexample/springmvc/repository/UserRepository.java // public interface UserRepository extends JpaRepository<User, Long>, // JpaSpecificationExecutor<User> { // // public User findByUsername(String username); // }
import com.hantsylabs.restexample.springmvc.domain.User; import com.hantsylabs.restexample.springmvc.repository.CommentRepository; import com.hantsylabs.restexample.springmvc.repository.PostRepository; import com.hantsylabs.restexample.springmvc.repository.UserRepository; import org.jbehave.core.configuration.Configuration; import org.jbehave.core.configuration.MostUsefulConfiguration; import org.jbehave.core.embedder.Embedder; import org.jbehave.core.embedder.EmbedderControls; import org.jbehave.core.io.*; import org.jbehave.core.junit.JUnitStory; import org.jbehave.core.reporters.FilePrintStreamFactory.ResolveToPackagedName; import org.jbehave.core.reporters.StoryReporterBuilder; import org.jbehave.core.steps.ParameterControls; import java.util.Arrays; import javax.inject.Inject; import lombok.extern.slf4j.Slf4j; import static org.jbehave.core.reporters.Format.*; import org.jbehave.core.steps.InjectableStepsFactory; import org.jbehave.core.steps.InstanceStepsFactory; import org.springframework.security.crypto.password.PasswordEncoder;
package com.hantsylabs.restexample.springmvc.test.jbehave; @Slf4j public abstract class AbstractSpringJBehaveStory extends JUnitStory { @Inject PostRepository posts; @Inject CommentRepository comments; @Inject
// Path: src/main/java/com/hantsylabs/restexample/springmvc/domain/User.java // @Data // @Builder // @NoArgsConstructor // @AllArgsConstructor // @Entity // @Table(name = "users") // public class User implements UserDetails, Serializable { // // /** // * // */ // private static final long serialVersionUID = 1L; // // @Id() // @GeneratedValue(strategy = GenerationType.IDENTITY) // @Column(name = "id") // private Long id; // // @Column(name = "username") // private String username; // // @Column(name = "password") // private String password; // // @Column(name = "name") // private String name; // // @Column(name = "email") // private String email; // // @Column(name = "role") // private String role; // // @Column(name = "created_date") // @CreatedDate // private LocalDateTime createdDate; // // public String getName() { // if (this.name == null || this.name.trim().length() == 0) { // return this.username; // } // return name; // } // // @Override // public Collection<? extends GrantedAuthority> getAuthorities() { // return Arrays.asList(new SimpleGrantedAuthority("ROLE_" + this.role)); // } // // @Override // public String getPassword() { // return this.password; // } // // @Override // public String getUsername() { // return this.username; // } // // @Override // public boolean isAccountNonExpired() { // return true; // } // // @Override // public boolean isAccountNonLocked() { // return true; // } // // @Override // public boolean isCredentialsNonExpired() { // return true; // } // // @Override // // public boolean isEnabled() { // return true; // } // // // } // // Path: src/main/java/com/hantsylabs/restexample/springmvc/repository/CommentRepository.java // public interface CommentRepository extends JpaRepository<Comment, Long> { // // public List<Comment> findByPost(Post post); // // public Page<Comment> findByPostId(Long id, Pageable page); // // } // // Path: src/main/java/com/hantsylabs/restexample/springmvc/repository/PostRepository.java // public interface PostRepository extends JpaRepository<Post, Long>,// // JpaSpecificationExecutor<Post>{ // // } // // Path: src/main/java/com/hantsylabs/restexample/springmvc/repository/UserRepository.java // public interface UserRepository extends JpaRepository<User, Long>, // JpaSpecificationExecutor<User> { // // public User findByUsername(String username); // } // Path: src/test/java/com/hantsylabs/restexample/springmvc/test/jbehave/AbstractSpringJBehaveStory.java import com.hantsylabs.restexample.springmvc.domain.User; import com.hantsylabs.restexample.springmvc.repository.CommentRepository; import com.hantsylabs.restexample.springmvc.repository.PostRepository; import com.hantsylabs.restexample.springmvc.repository.UserRepository; import org.jbehave.core.configuration.Configuration; import org.jbehave.core.configuration.MostUsefulConfiguration; import org.jbehave.core.embedder.Embedder; import org.jbehave.core.embedder.EmbedderControls; import org.jbehave.core.io.*; import org.jbehave.core.junit.JUnitStory; import org.jbehave.core.reporters.FilePrintStreamFactory.ResolveToPackagedName; import org.jbehave.core.reporters.StoryReporterBuilder; import org.jbehave.core.steps.ParameterControls; import java.util.Arrays; import javax.inject.Inject; import lombok.extern.slf4j.Slf4j; import static org.jbehave.core.reporters.Format.*; import org.jbehave.core.steps.InjectableStepsFactory; import org.jbehave.core.steps.InstanceStepsFactory; import org.springframework.security.crypto.password.PasswordEncoder; package com.hantsylabs.restexample.springmvc.test.jbehave; @Slf4j public abstract class AbstractSpringJBehaveStory extends JUnitStory { @Inject PostRepository posts; @Inject CommentRepository comments; @Inject
UserRepository users;
hantsy/angularjs-springmvc-sample-boot
src/test/java/com/hantsylabs/restexample/springmvc/test/jbehave/AbstractSpringJBehaveStory.java
// Path: src/main/java/com/hantsylabs/restexample/springmvc/domain/User.java // @Data // @Builder // @NoArgsConstructor // @AllArgsConstructor // @Entity // @Table(name = "users") // public class User implements UserDetails, Serializable { // // /** // * // */ // private static final long serialVersionUID = 1L; // // @Id() // @GeneratedValue(strategy = GenerationType.IDENTITY) // @Column(name = "id") // private Long id; // // @Column(name = "username") // private String username; // // @Column(name = "password") // private String password; // // @Column(name = "name") // private String name; // // @Column(name = "email") // private String email; // // @Column(name = "role") // private String role; // // @Column(name = "created_date") // @CreatedDate // private LocalDateTime createdDate; // // public String getName() { // if (this.name == null || this.name.trim().length() == 0) { // return this.username; // } // return name; // } // // @Override // public Collection<? extends GrantedAuthority> getAuthorities() { // return Arrays.asList(new SimpleGrantedAuthority("ROLE_" + this.role)); // } // // @Override // public String getPassword() { // return this.password; // } // // @Override // public String getUsername() { // return this.username; // } // // @Override // public boolean isAccountNonExpired() { // return true; // } // // @Override // public boolean isAccountNonLocked() { // return true; // } // // @Override // public boolean isCredentialsNonExpired() { // return true; // } // // @Override // // public boolean isEnabled() { // return true; // } // // // } // // Path: src/main/java/com/hantsylabs/restexample/springmvc/repository/CommentRepository.java // public interface CommentRepository extends JpaRepository<Comment, Long> { // // public List<Comment> findByPost(Post post); // // public Page<Comment> findByPostId(Long id, Pageable page); // // } // // Path: src/main/java/com/hantsylabs/restexample/springmvc/repository/PostRepository.java // public interface PostRepository extends JpaRepository<Post, Long>,// // JpaSpecificationExecutor<Post>{ // // } // // Path: src/main/java/com/hantsylabs/restexample/springmvc/repository/UserRepository.java // public interface UserRepository extends JpaRepository<User, Long>, // JpaSpecificationExecutor<User> { // // public User findByUsername(String username); // }
import com.hantsylabs.restexample.springmvc.domain.User; import com.hantsylabs.restexample.springmvc.repository.CommentRepository; import com.hantsylabs.restexample.springmvc.repository.PostRepository; import com.hantsylabs.restexample.springmvc.repository.UserRepository; import org.jbehave.core.configuration.Configuration; import org.jbehave.core.configuration.MostUsefulConfiguration; import org.jbehave.core.embedder.Embedder; import org.jbehave.core.embedder.EmbedderControls; import org.jbehave.core.io.*; import org.jbehave.core.junit.JUnitStory; import org.jbehave.core.reporters.FilePrintStreamFactory.ResolveToPackagedName; import org.jbehave.core.reporters.StoryReporterBuilder; import org.jbehave.core.steps.ParameterControls; import java.util.Arrays; import javax.inject.Inject; import lombok.extern.slf4j.Slf4j; import static org.jbehave.core.reporters.Format.*; import org.jbehave.core.steps.InjectableStepsFactory; import org.jbehave.core.steps.InstanceStepsFactory; import org.springframework.security.crypto.password.PasswordEncoder;
package com.hantsylabs.restexample.springmvc.test.jbehave; @Slf4j public abstract class AbstractSpringJBehaveStory extends JUnitStory { @Inject PostRepository posts; @Inject CommentRepository comments; @Inject UserRepository users; @Inject PasswordEncoder passwordEncoder; public void clearData() { log.debug("clearing data..."); comments.deleteAllInBatch(); posts.deleteAllInBatch(); users.deleteAllInBatch(); } public void initData() { users.save(
// Path: src/main/java/com/hantsylabs/restexample/springmvc/domain/User.java // @Data // @Builder // @NoArgsConstructor // @AllArgsConstructor // @Entity // @Table(name = "users") // public class User implements UserDetails, Serializable { // // /** // * // */ // private static final long serialVersionUID = 1L; // // @Id() // @GeneratedValue(strategy = GenerationType.IDENTITY) // @Column(name = "id") // private Long id; // // @Column(name = "username") // private String username; // // @Column(name = "password") // private String password; // // @Column(name = "name") // private String name; // // @Column(name = "email") // private String email; // // @Column(name = "role") // private String role; // // @Column(name = "created_date") // @CreatedDate // private LocalDateTime createdDate; // // public String getName() { // if (this.name == null || this.name.trim().length() == 0) { // return this.username; // } // return name; // } // // @Override // public Collection<? extends GrantedAuthority> getAuthorities() { // return Arrays.asList(new SimpleGrantedAuthority("ROLE_" + this.role)); // } // // @Override // public String getPassword() { // return this.password; // } // // @Override // public String getUsername() { // return this.username; // } // // @Override // public boolean isAccountNonExpired() { // return true; // } // // @Override // public boolean isAccountNonLocked() { // return true; // } // // @Override // public boolean isCredentialsNonExpired() { // return true; // } // // @Override // // public boolean isEnabled() { // return true; // } // // // } // // Path: src/main/java/com/hantsylabs/restexample/springmvc/repository/CommentRepository.java // public interface CommentRepository extends JpaRepository<Comment, Long> { // // public List<Comment> findByPost(Post post); // // public Page<Comment> findByPostId(Long id, Pageable page); // // } // // Path: src/main/java/com/hantsylabs/restexample/springmvc/repository/PostRepository.java // public interface PostRepository extends JpaRepository<Post, Long>,// // JpaSpecificationExecutor<Post>{ // // } // // Path: src/main/java/com/hantsylabs/restexample/springmvc/repository/UserRepository.java // public interface UserRepository extends JpaRepository<User, Long>, // JpaSpecificationExecutor<User> { // // public User findByUsername(String username); // } // Path: src/test/java/com/hantsylabs/restexample/springmvc/test/jbehave/AbstractSpringJBehaveStory.java import com.hantsylabs.restexample.springmvc.domain.User; import com.hantsylabs.restexample.springmvc.repository.CommentRepository; import com.hantsylabs.restexample.springmvc.repository.PostRepository; import com.hantsylabs.restexample.springmvc.repository.UserRepository; import org.jbehave.core.configuration.Configuration; import org.jbehave.core.configuration.MostUsefulConfiguration; import org.jbehave.core.embedder.Embedder; import org.jbehave.core.embedder.EmbedderControls; import org.jbehave.core.io.*; import org.jbehave.core.junit.JUnitStory; import org.jbehave.core.reporters.FilePrintStreamFactory.ResolveToPackagedName; import org.jbehave.core.reporters.StoryReporterBuilder; import org.jbehave.core.steps.ParameterControls; import java.util.Arrays; import javax.inject.Inject; import lombok.extern.slf4j.Slf4j; import static org.jbehave.core.reporters.Format.*; import org.jbehave.core.steps.InjectableStepsFactory; import org.jbehave.core.steps.InstanceStepsFactory; import org.springframework.security.crypto.password.PasswordEncoder; package com.hantsylabs.restexample.springmvc.test.jbehave; @Slf4j public abstract class AbstractSpringJBehaveStory extends JUnitStory { @Inject PostRepository posts; @Inject CommentRepository comments; @Inject UserRepository users; @Inject PasswordEncoder passwordEncoder; public void clearData() { log.debug("clearing data..."); comments.deleteAllInBatch(); posts.deleteAllInBatch(); users.deleteAllInBatch(); } public void initData() { users.save(
User.builder()
hantsy/angularjs-springmvc-sample-boot
src/main/java/com/hantsylabs/restexample/springmvc/repository/PostSpecifications.java
// Path: src/main/java/com/hantsylabs/restexample/springmvc/domain/Post.java // @Data // @Builder // @NoArgsConstructor // @AllArgsConstructor // @Entity // @Table(name = "posts") // public class Post implements Serializable { // // /** // * // */ // private static final long serialVersionUID = 1L; // // public enum Status { // // DRAFT, // PUBLISHED // } // // public Post(String title, String content) { // this.title = title; // this.content = content; // } // // @Id() // @GeneratedValue(strategy = GenerationType.IDENTITY) // @Column(name = "id") // private Long id; // // @Column(name = "title") // private String title; // // @Column(name = "content") // @Size(max = 2000) // private String content; // // @Column(name = "status") // @Enumerated // private Status status = Status.DRAFT; // // @ManyToOne // @JoinColumn(name = "created_by") // @CreatedBy // private User createdBy; // // @Column(name = "created_date") // @CreatedDate // private LocalDateTime createdDate; // // @ManyToOne // @JoinColumn(name = "last_modified_by") // @LastModifiedBy // private User lastModifiedBy; // // @Column(name = "last_modified_date") // @LastModifiedDate // private LocalDateTime lastModifiedDate; // // }
import com.hantsylabs.restexample.springmvc.domain.Post; import com.hantsylabs.restexample.springmvc.domain.Post_; import java.util.ArrayList; import java.util.List; import javax.persistence.criteria.CriteriaBuilder; import javax.persistence.criteria.CriteriaQuery; import javax.persistence.criteria.Predicate; import javax.persistence.criteria.Root; import org.springframework.data.jpa.domain.Specification; import org.springframework.util.StringUtils;
package com.hantsylabs.restexample.springmvc.repository; /** * * @author Hantsy Bai<[email protected]> * */ public class PostSpecifications { private PostSpecifications() {}
// Path: src/main/java/com/hantsylabs/restexample/springmvc/domain/Post.java // @Data // @Builder // @NoArgsConstructor // @AllArgsConstructor // @Entity // @Table(name = "posts") // public class Post implements Serializable { // // /** // * // */ // private static final long serialVersionUID = 1L; // // public enum Status { // // DRAFT, // PUBLISHED // } // // public Post(String title, String content) { // this.title = title; // this.content = content; // } // // @Id() // @GeneratedValue(strategy = GenerationType.IDENTITY) // @Column(name = "id") // private Long id; // // @Column(name = "title") // private String title; // // @Column(name = "content") // @Size(max = 2000) // private String content; // // @Column(name = "status") // @Enumerated // private Status status = Status.DRAFT; // // @ManyToOne // @JoinColumn(name = "created_by") // @CreatedBy // private User createdBy; // // @Column(name = "created_date") // @CreatedDate // private LocalDateTime createdDate; // // @ManyToOne // @JoinColumn(name = "last_modified_by") // @LastModifiedBy // private User lastModifiedBy; // // @Column(name = "last_modified_date") // @LastModifiedDate // private LocalDateTime lastModifiedDate; // // } // Path: src/main/java/com/hantsylabs/restexample/springmvc/repository/PostSpecifications.java import com.hantsylabs.restexample.springmvc.domain.Post; import com.hantsylabs.restexample.springmvc.domain.Post_; import java.util.ArrayList; import java.util.List; import javax.persistence.criteria.CriteriaBuilder; import javax.persistence.criteria.CriteriaQuery; import javax.persistence.criteria.Predicate; import javax.persistence.criteria.Root; import org.springframework.data.jpa.domain.Specification; import org.springframework.util.StringUtils; package com.hantsylabs.restexample.springmvc.repository; /** * * @author Hantsy Bai<[email protected]> * */ public class PostSpecifications { private PostSpecifications() {}
public static Specification<Post> filterByKeywordAndStatus(
hantsy/angularjs-springmvc-sample-boot
src/main/java/com/hantsylabs/restexample/springmvc/api/post/CommentController.java
// Path: src/main/java/com/hantsylabs/restexample/springmvc/Constants.java // public class Constants { // // /** // * prefix of REST API // */ // public static final String URI_API_PREFIX = "/api"; // // public static final String URI_SELF = "/me"; // // public static final String URI_USERS = "/users"; // // public static final String URI_POSTS = "/posts"; // // public static final String URI_COMMENTS = "/comments"; // // private Constants() {} // // } // // Path: src/main/java/com/hantsylabs/restexample/springmvc/service/BlogService.java // @Service // @Transactional // public class BlogService { // // private static final Logger log = LoggerFactory.getLogger(BlogService.class); // // //@Inject // private PostRepository postRepository; // // //@Inject // private CommentRepository commentRepository; // // @Inject //no need in Spring 4.3 // public BlogService(PostRepository postRepository, CommentRepository commentRepository) { // this.postRepository = postRepository; // this.commentRepository = commentRepository; // } // // public Page<PostDetails> searchPostsByCriteria(String q, Post.Status status, Pageable page) { // // log.debug("search posts by keyword@" + q + ", page @" + page); // // Page<Post> posts = postRepository.findAll(PostSpecifications.filterByKeywordAndStatus(q, status), // page); // // if (log.isDebugEnabled()) { // log.debug("get posts size @" + posts.getTotalElements()); // } // // return DTOUtils.mapPage(posts, PostDetails.class); // } // // public PostDetails savePost(PostForm form) { // // log.debug("save post @" + form); // // Post post = DTOUtils.map(form, Post.class); // // Post saved = postRepository.save(post); // // log.debug("saved post id is @" + saved); // // return DTOUtils.map(saved, PostDetails.class); // // } // // public PostDetails updatePost(Long id, PostForm form) { // Assert.notNull(id, "post id can not be null"); // // log.debug("updating post of @" + id + ", posst content @" + form); // // Post post = postRepository.findOne(id); // DTOUtils.mapTo(form, post); // // Post saved = postRepository.save(post); // // log.debug("updated post@" + saved); // // return DTOUtils.map(saved, PostDetails.class); // } // // public PostDetails findPostById(Long id) { // Assert.notNull(id, "post id can not be null"); // // log.debug("find post by id@" + id); // // Post post = postRepository.findOne(id); // // if (post == null) { // throw new ResourceNotFoundException(id); // } // // return DTOUtils.map(post, PostDetails.class); // } // // public Page<CommentDetails> findCommentsByPostId(Long id, Pageable page) { // // log.debug("find comments by post id@" + id); // // Page<Comment> comments = commentRepository.findByPostId(id, page); // // if (log.isDebugEnabled()) { // log.debug("found results@" + comments.getTotalElements()); // } // // return DTOUtils.mapPage(comments, CommentDetails.class); // } // // public CommentDetails saveCommentOfPost(Long id, CommentForm fm) { // Assert.notNull(id, "post id can not be null"); // // log.debug("find post by id@" + id); // // Post post = postRepository.findOne(id); // // if (post == null) { // throw new ResourceNotFoundException(id); // } // // Comment comment = DTOUtils.map(fm, Comment.class); // // comment.setPost(post); // // comment = commentRepository.save(comment); // // if (log.isDebugEnabled()) { // log.debug("comment saved@" + comment); // } // // return DTOUtils.map(comment, CommentDetails.class); // } // // public void deletePostById(Long id) { // Assert.notNull(id, "post id can not be null"); // // log.debug("find post by id@" + id); // // Post post = postRepository.findOne(id); // // if (post == null) { // throw new ResourceNotFoundException(id); // } // // postRepository.delete(post); // } // // public void deleteCommentById(Long id) { // Assert.notNull(id, "comment id can not be null"); // // if (log.isDebugEnabled()) { // log.debug("delete comment by id@" + id); // } // // Comment comment = commentRepository.findOne(id); // // if (comment == null) { // throw new ResourceNotFoundException(id); // } // // commentRepository.delete(comment); // } // }
import com.hantsylabs.restexample.springmvc.Constants; import com.hantsylabs.restexample.springmvc.service.BlogService; import javax.inject.Inject; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController;
package com.hantsylabs.restexample.springmvc.api.post; @RestController @RequestMapping(value = Constants.URI_API_PREFIX + Constants.URI_COMMENTS) public class CommentController { private static final Logger log = LoggerFactory .getLogger(CommentController.class); @Inject
// Path: src/main/java/com/hantsylabs/restexample/springmvc/Constants.java // public class Constants { // // /** // * prefix of REST API // */ // public static final String URI_API_PREFIX = "/api"; // // public static final String URI_SELF = "/me"; // // public static final String URI_USERS = "/users"; // // public static final String URI_POSTS = "/posts"; // // public static final String URI_COMMENTS = "/comments"; // // private Constants() {} // // } // // Path: src/main/java/com/hantsylabs/restexample/springmvc/service/BlogService.java // @Service // @Transactional // public class BlogService { // // private static final Logger log = LoggerFactory.getLogger(BlogService.class); // // //@Inject // private PostRepository postRepository; // // //@Inject // private CommentRepository commentRepository; // // @Inject //no need in Spring 4.3 // public BlogService(PostRepository postRepository, CommentRepository commentRepository) { // this.postRepository = postRepository; // this.commentRepository = commentRepository; // } // // public Page<PostDetails> searchPostsByCriteria(String q, Post.Status status, Pageable page) { // // log.debug("search posts by keyword@" + q + ", page @" + page); // // Page<Post> posts = postRepository.findAll(PostSpecifications.filterByKeywordAndStatus(q, status), // page); // // if (log.isDebugEnabled()) { // log.debug("get posts size @" + posts.getTotalElements()); // } // // return DTOUtils.mapPage(posts, PostDetails.class); // } // // public PostDetails savePost(PostForm form) { // // log.debug("save post @" + form); // // Post post = DTOUtils.map(form, Post.class); // // Post saved = postRepository.save(post); // // log.debug("saved post id is @" + saved); // // return DTOUtils.map(saved, PostDetails.class); // // } // // public PostDetails updatePost(Long id, PostForm form) { // Assert.notNull(id, "post id can not be null"); // // log.debug("updating post of @" + id + ", posst content @" + form); // // Post post = postRepository.findOne(id); // DTOUtils.mapTo(form, post); // // Post saved = postRepository.save(post); // // log.debug("updated post@" + saved); // // return DTOUtils.map(saved, PostDetails.class); // } // // public PostDetails findPostById(Long id) { // Assert.notNull(id, "post id can not be null"); // // log.debug("find post by id@" + id); // // Post post = postRepository.findOne(id); // // if (post == null) { // throw new ResourceNotFoundException(id); // } // // return DTOUtils.map(post, PostDetails.class); // } // // public Page<CommentDetails> findCommentsByPostId(Long id, Pageable page) { // // log.debug("find comments by post id@" + id); // // Page<Comment> comments = commentRepository.findByPostId(id, page); // // if (log.isDebugEnabled()) { // log.debug("found results@" + comments.getTotalElements()); // } // // return DTOUtils.mapPage(comments, CommentDetails.class); // } // // public CommentDetails saveCommentOfPost(Long id, CommentForm fm) { // Assert.notNull(id, "post id can not be null"); // // log.debug("find post by id@" + id); // // Post post = postRepository.findOne(id); // // if (post == null) { // throw new ResourceNotFoundException(id); // } // // Comment comment = DTOUtils.map(fm, Comment.class); // // comment.setPost(post); // // comment = commentRepository.save(comment); // // if (log.isDebugEnabled()) { // log.debug("comment saved@" + comment); // } // // return DTOUtils.map(comment, CommentDetails.class); // } // // public void deletePostById(Long id) { // Assert.notNull(id, "post id can not be null"); // // log.debug("find post by id@" + id); // // Post post = postRepository.findOne(id); // // if (post == null) { // throw new ResourceNotFoundException(id); // } // // postRepository.delete(post); // } // // public void deleteCommentById(Long id) { // Assert.notNull(id, "comment id can not be null"); // // if (log.isDebugEnabled()) { // log.debug("delete comment by id@" + id); // } // // Comment comment = commentRepository.findOne(id); // // if (comment == null) { // throw new ResourceNotFoundException(id); // } // // commentRepository.delete(comment); // } // } // Path: src/main/java/com/hantsylabs/restexample/springmvc/api/post/CommentController.java import com.hantsylabs.restexample.springmvc.Constants; import com.hantsylabs.restexample.springmvc.service.BlogService; import javax.inject.Inject; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; package com.hantsylabs.restexample.springmvc.api.post; @RestController @RequestMapping(value = Constants.URI_API_PREFIX + Constants.URI_COMMENTS) public class CommentController { private static final Logger log = LoggerFactory .getLogger(CommentController.class); @Inject
private BlogService blogService;
hantsy/angularjs-springmvc-sample-boot
src/test/java/com/hantsylabs/restexample/springmvc/test/testassured/RestAssuredApplicationTest.java
// Path: src/main/java/com/hantsylabs/restexample/springmvc/model/PostForm.java // @Data // @Builder // @NoArgsConstructor // @AllArgsConstructor // public class PostForm implements Serializable { // // /** // * // */ // private static final long serialVersionUID = 1L; // // @NotNull // @NotEmpty // private String title; // // @NotNull // @NotEmpty // private String content; // // } // // Path: src/main/java/com/hantsylabs/restexample/springmvc/repository/PostRepository.java // public interface PostRepository extends JpaRepository<Post, Long>,// // JpaSpecificationExecutor<Post>{ // // } // // Path: src/test/java/com/hantsylabs/restexample/springmvc/test/WebIntegrationTestBase.java // public class WebIntegrationTestBase extends IntegrationTestBase { // // @LocalServerPort // protected int port; // // @Before // public void setup() { // clearData(); // initData(); // } // // }
import com.hantsylabs.restexample.springmvc.model.PostForm; import com.hantsylabs.restexample.springmvc.repository.PostRepository; import com.hantsylabs.restexample.springmvc.test.WebIntegrationTestBase; import com.jayway.restassured.RestAssured; import com.jayway.restassured.http.ContentType; import org.apache.http.HttpStatus; import org.junit.Before; import org.junit.Test; import com.jayway.restassured.response.Response; import javax.inject.Inject; import static org.hamcrest.CoreMatchers.containsString; import static com.jayway.restassured.RestAssured.given; import lombok.extern.slf4j.Slf4j; import static org.hamcrest.CoreMatchers.is; import org.junit.runner.RunWith; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.boot.test.context.SpringBootTest.WebEnvironment; import org.springframework.test.context.junit4.SpringRunner;
package com.hantsylabs.restexample.springmvc.test.testassured; @RunWith(SpringRunner.class) @SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT) @Slf4j
// Path: src/main/java/com/hantsylabs/restexample/springmvc/model/PostForm.java // @Data // @Builder // @NoArgsConstructor // @AllArgsConstructor // public class PostForm implements Serializable { // // /** // * // */ // private static final long serialVersionUID = 1L; // // @NotNull // @NotEmpty // private String title; // // @NotNull // @NotEmpty // private String content; // // } // // Path: src/main/java/com/hantsylabs/restexample/springmvc/repository/PostRepository.java // public interface PostRepository extends JpaRepository<Post, Long>,// // JpaSpecificationExecutor<Post>{ // // } // // Path: src/test/java/com/hantsylabs/restexample/springmvc/test/WebIntegrationTestBase.java // public class WebIntegrationTestBase extends IntegrationTestBase { // // @LocalServerPort // protected int port; // // @Before // public void setup() { // clearData(); // initData(); // } // // } // Path: src/test/java/com/hantsylabs/restexample/springmvc/test/testassured/RestAssuredApplicationTest.java import com.hantsylabs.restexample.springmvc.model.PostForm; import com.hantsylabs.restexample.springmvc.repository.PostRepository; import com.hantsylabs.restexample.springmvc.test.WebIntegrationTestBase; import com.jayway.restassured.RestAssured; import com.jayway.restassured.http.ContentType; import org.apache.http.HttpStatus; import org.junit.Before; import org.junit.Test; import com.jayway.restassured.response.Response; import javax.inject.Inject; import static org.hamcrest.CoreMatchers.containsString; import static com.jayway.restassured.RestAssured.given; import lombok.extern.slf4j.Slf4j; import static org.hamcrest.CoreMatchers.is; import org.junit.runner.RunWith; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.boot.test.context.SpringBootTest.WebEnvironment; import org.springframework.test.context.junit4.SpringRunner; package com.hantsylabs.restexample.springmvc.test.testassured; @RunWith(SpringRunner.class) @SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT) @Slf4j
public class RestAssuredApplicationTest extends WebIntegrationTestBase {
hantsy/angularjs-springmvc-sample-boot
src/test/java/com/hantsylabs/restexample/springmvc/test/testassured/RestAssuredApplicationTest.java
// Path: src/main/java/com/hantsylabs/restexample/springmvc/model/PostForm.java // @Data // @Builder // @NoArgsConstructor // @AllArgsConstructor // public class PostForm implements Serializable { // // /** // * // */ // private static final long serialVersionUID = 1L; // // @NotNull // @NotEmpty // private String title; // // @NotNull // @NotEmpty // private String content; // // } // // Path: src/main/java/com/hantsylabs/restexample/springmvc/repository/PostRepository.java // public interface PostRepository extends JpaRepository<Post, Long>,// // JpaSpecificationExecutor<Post>{ // // } // // Path: src/test/java/com/hantsylabs/restexample/springmvc/test/WebIntegrationTestBase.java // public class WebIntegrationTestBase extends IntegrationTestBase { // // @LocalServerPort // protected int port; // // @Before // public void setup() { // clearData(); // initData(); // } // // }
import com.hantsylabs.restexample.springmvc.model.PostForm; import com.hantsylabs.restexample.springmvc.repository.PostRepository; import com.hantsylabs.restexample.springmvc.test.WebIntegrationTestBase; import com.jayway.restassured.RestAssured; import com.jayway.restassured.http.ContentType; import org.apache.http.HttpStatus; import org.junit.Before; import org.junit.Test; import com.jayway.restassured.response.Response; import javax.inject.Inject; import static org.hamcrest.CoreMatchers.containsString; import static com.jayway.restassured.RestAssured.given; import lombok.extern.slf4j.Slf4j; import static org.hamcrest.CoreMatchers.is; import org.junit.runner.RunWith; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.boot.test.context.SpringBootTest.WebEnvironment; import org.springframework.test.context.junit4.SpringRunner;
@Test public void testDeletePostNotExisted() { String location = "/api/posts/1000"; given() .auth().basic(USER_NAME, PASSWORD) .contentType(ContentType.JSON) .when() .delete(location) .then() .assertThat() .statusCode(HttpStatus.SC_NOT_FOUND); } @Test public void testGetPostNotExisted() { String location = "/api/posts/1000"; given() .auth().basic(USER_NAME, PASSWORD) .contentType(ContentType.JSON) .when() .get(location) .then() .assertThat() .statusCode(HttpStatus.SC_NOT_FOUND); } @Test public void testPostFormInValid() {
// Path: src/main/java/com/hantsylabs/restexample/springmvc/model/PostForm.java // @Data // @Builder // @NoArgsConstructor // @AllArgsConstructor // public class PostForm implements Serializable { // // /** // * // */ // private static final long serialVersionUID = 1L; // // @NotNull // @NotEmpty // private String title; // // @NotNull // @NotEmpty // private String content; // // } // // Path: src/main/java/com/hantsylabs/restexample/springmvc/repository/PostRepository.java // public interface PostRepository extends JpaRepository<Post, Long>,// // JpaSpecificationExecutor<Post>{ // // } // // Path: src/test/java/com/hantsylabs/restexample/springmvc/test/WebIntegrationTestBase.java // public class WebIntegrationTestBase extends IntegrationTestBase { // // @LocalServerPort // protected int port; // // @Before // public void setup() { // clearData(); // initData(); // } // // } // Path: src/test/java/com/hantsylabs/restexample/springmvc/test/testassured/RestAssuredApplicationTest.java import com.hantsylabs.restexample.springmvc.model.PostForm; import com.hantsylabs.restexample.springmvc.repository.PostRepository; import com.hantsylabs.restexample.springmvc.test.WebIntegrationTestBase; import com.jayway.restassured.RestAssured; import com.jayway.restassured.http.ContentType; import org.apache.http.HttpStatus; import org.junit.Before; import org.junit.Test; import com.jayway.restassured.response.Response; import javax.inject.Inject; import static org.hamcrest.CoreMatchers.containsString; import static com.jayway.restassured.RestAssured.given; import lombok.extern.slf4j.Slf4j; import static org.hamcrest.CoreMatchers.is; import org.junit.runner.RunWith; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.boot.test.context.SpringBootTest.WebEnvironment; import org.springframework.test.context.junit4.SpringRunner; @Test public void testDeletePostNotExisted() { String location = "/api/posts/1000"; given() .auth().basic(USER_NAME, PASSWORD) .contentType(ContentType.JSON) .when() .delete(location) .then() .assertThat() .statusCode(HttpStatus.SC_NOT_FOUND); } @Test public void testGetPostNotExisted() { String location = "/api/posts/1000"; given() .auth().basic(USER_NAME, PASSWORD) .contentType(ContentType.JSON) .when() .get(location) .then() .assertThat() .statusCode(HttpStatus.SC_NOT_FOUND); } @Test public void testPostFormInValid() {
PostForm form = new PostForm();
hantsy/angularjs-springmvc-sample-boot
src/test/java/com/hantsylabs/restexample/springmvc/test/slice/SimpleRestClientTest.java
// Path: src/main/java/com/hantsylabs/restexample/springmvc/model/PostDetails.java // @Data // @Builder // @NoArgsConstructor // @AllArgsConstructor // public class PostDetails implements Serializable { // // /** // * // */ // private static final long serialVersionUID = 1L; // // private Long id; // // private String title; // // private String content; // // private String status; // // private SimpleUserDetails createdBy; // // private LocalDateTime createdDate; // // private SimpleUserDetails lastModifiedBy; // // private LocalDateTime lastModifiedDate; // // } // // Path: src/test/java/com/hantsylabs/restexample/springmvc/test/slice/SimpleRestClientTest.java // @TestComponent // static class ClientBlogService { // // RestTemplate restTemplate; // // @Inject // public ClientBlogService(RestTemplateBuilder builder) { // this.restTemplate = builder.build(); // } // // public PostDetails getPostById(Long id) { // ResponseEntity<PostDetails> postResponse = this.restTemplate.getForEntity("/api/posts/" + id, PostDetails.class); // return postResponse.getBody(); // } // // }
import com.hantsylabs.restexample.springmvc.model.PostDetails; import com.hantsylabs.restexample.springmvc.test.slice.SimpleRestClientTest.ClientBlogService; import javax.inject.Inject; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.http.MediaType; import lombok.extern.slf4j.Slf4j; import static org.assertj.core.api.Assertions.assertThat; import org.springframework.boot.test.autoconfigure.web.client.RestClientTest; import org.springframework.boot.test.context.TestComponent; import org.springframework.boot.web.client.RestTemplateBuilder; import org.springframework.http.ResponseEntity; import org.springframework.test.context.junit4.SpringRunner; import org.springframework.test.web.client.MockRestServiceServer; import static org.springframework.test.web.client.match.MockRestRequestMatchers.requestTo; import static org.springframework.test.web.client.response.MockRestResponseCreators.withSuccess; import org.springframework.web.client.RestTemplate;
package com.hantsylabs.restexample.springmvc.test.slice; @RunWith(SpringRunner.class) @RestClientTest(ClientBlogService.class) @Slf4j // @AutoConfigureWebClient(registerRestTemplate=true) public class SimpleRestClientTest { @Inject private ClientBlogService service; // @Inject // RestTemplateBuilder builder; @Inject private MockRestServiceServer server; @Test public void testGetPostById() throws Exception { this.server.expect(requestTo("/api/posts/1")) .andRespond(withSuccess("{\"id\":\"1\",\"title\":\"test title\",\"content\":\"test content\"}", MediaType.APPLICATION_JSON));
// Path: src/main/java/com/hantsylabs/restexample/springmvc/model/PostDetails.java // @Data // @Builder // @NoArgsConstructor // @AllArgsConstructor // public class PostDetails implements Serializable { // // /** // * // */ // private static final long serialVersionUID = 1L; // // private Long id; // // private String title; // // private String content; // // private String status; // // private SimpleUserDetails createdBy; // // private LocalDateTime createdDate; // // private SimpleUserDetails lastModifiedBy; // // private LocalDateTime lastModifiedDate; // // } // // Path: src/test/java/com/hantsylabs/restexample/springmvc/test/slice/SimpleRestClientTest.java // @TestComponent // static class ClientBlogService { // // RestTemplate restTemplate; // // @Inject // public ClientBlogService(RestTemplateBuilder builder) { // this.restTemplate = builder.build(); // } // // public PostDetails getPostById(Long id) { // ResponseEntity<PostDetails> postResponse = this.restTemplate.getForEntity("/api/posts/" + id, PostDetails.class); // return postResponse.getBody(); // } // // } // Path: src/test/java/com/hantsylabs/restexample/springmvc/test/slice/SimpleRestClientTest.java import com.hantsylabs.restexample.springmvc.model.PostDetails; import com.hantsylabs.restexample.springmvc.test.slice.SimpleRestClientTest.ClientBlogService; import javax.inject.Inject; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.http.MediaType; import lombok.extern.slf4j.Slf4j; import static org.assertj.core.api.Assertions.assertThat; import org.springframework.boot.test.autoconfigure.web.client.RestClientTest; import org.springframework.boot.test.context.TestComponent; import org.springframework.boot.web.client.RestTemplateBuilder; import org.springframework.http.ResponseEntity; import org.springframework.test.context.junit4.SpringRunner; import org.springframework.test.web.client.MockRestServiceServer; import static org.springframework.test.web.client.match.MockRestRequestMatchers.requestTo; import static org.springframework.test.web.client.response.MockRestResponseCreators.withSuccess; import org.springframework.web.client.RestTemplate; package com.hantsylabs.restexample.springmvc.test.slice; @RunWith(SpringRunner.class) @RestClientTest(ClientBlogService.class) @Slf4j // @AutoConfigureWebClient(registerRestTemplate=true) public class SimpleRestClientTest { @Inject private ClientBlogService service; // @Inject // RestTemplateBuilder builder; @Inject private MockRestServiceServer server; @Test public void testGetPostById() throws Exception { this.server.expect(requestTo("/api/posts/1")) .andRespond(withSuccess("{\"id\":\"1\",\"title\":\"test title\",\"content\":\"test content\"}", MediaType.APPLICATION_JSON));
PostDetails post = this.service.getPostById(1L);
hantsy/angularjs-springmvc-sample-boot
src/main/java/com/hantsylabs/restexample/springmvc/JpaConfig.java
// Path: src/main/java/com/hantsylabs/restexample/springmvc/domain/User.java // @Data // @Builder // @NoArgsConstructor // @AllArgsConstructor // @Entity // @Table(name = "users") // public class User implements UserDetails, Serializable { // // /** // * // */ // private static final long serialVersionUID = 1L; // // @Id() // @GeneratedValue(strategy = GenerationType.IDENTITY) // @Column(name = "id") // private Long id; // // @Column(name = "username") // private String username; // // @Column(name = "password") // private String password; // // @Column(name = "name") // private String name; // // @Column(name = "email") // private String email; // // @Column(name = "role") // private String role; // // @Column(name = "created_date") // @CreatedDate // private LocalDateTime createdDate; // // public String getName() { // if (this.name == null || this.name.trim().length() == 0) { // return this.username; // } // return name; // } // // @Override // public Collection<? extends GrantedAuthority> getAuthorities() { // return Arrays.asList(new SimpleGrantedAuthority("ROLE_" + this.role)); // } // // @Override // public String getPassword() { // return this.password; // } // // @Override // public String getUsername() { // return this.username; // } // // @Override // public boolean isAccountNonExpired() { // return true; // } // // @Override // public boolean isAccountNonLocked() { // return true; // } // // @Override // public boolean isCredentialsNonExpired() { // return true; // } // // @Override // // public boolean isEnabled() { // return true; // } // // // } // // Path: src/main/java/com/hantsylabs/restexample/springmvc/security/SecurityUtil.java // public class SecurityUtil { // // private SecurityUtil() {} // // public static User currentUser() { // Authentication auth = SecurityContextHolder.getContext() // .getAuthentication(); // if (auth == null) { // return null; // } // // if (auth instanceof AnonymousAuthenticationToken) { // return null; // } // // return (User) auth.getPrincipal(); // } // }
import com.hantsylabs.restexample.springmvc.domain.User; import com.hantsylabs.restexample.springmvc.security.SecurityUtil; import org.springframework.boot.autoconfigure.domain.EntityScan; import org.springframework.context.annotation.AdviceMode; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.data.domain.AuditorAware; import org.springframework.data.jpa.convert.threeten.Jsr310JpaConverters; import org.springframework.data.jpa.repository.config.EnableJpaAuditing; import org.springframework.transaction.annotation.EnableTransactionManagement;
package com.hantsylabs.restexample.springmvc; /** * * @author hantsy */ @Configuration @EnableTransactionManagement(mode = AdviceMode.ASPECTJ)
// Path: src/main/java/com/hantsylabs/restexample/springmvc/domain/User.java // @Data // @Builder // @NoArgsConstructor // @AllArgsConstructor // @Entity // @Table(name = "users") // public class User implements UserDetails, Serializable { // // /** // * // */ // private static final long serialVersionUID = 1L; // // @Id() // @GeneratedValue(strategy = GenerationType.IDENTITY) // @Column(name = "id") // private Long id; // // @Column(name = "username") // private String username; // // @Column(name = "password") // private String password; // // @Column(name = "name") // private String name; // // @Column(name = "email") // private String email; // // @Column(name = "role") // private String role; // // @Column(name = "created_date") // @CreatedDate // private LocalDateTime createdDate; // // public String getName() { // if (this.name == null || this.name.trim().length() == 0) { // return this.username; // } // return name; // } // // @Override // public Collection<? extends GrantedAuthority> getAuthorities() { // return Arrays.asList(new SimpleGrantedAuthority("ROLE_" + this.role)); // } // // @Override // public String getPassword() { // return this.password; // } // // @Override // public String getUsername() { // return this.username; // } // // @Override // public boolean isAccountNonExpired() { // return true; // } // // @Override // public boolean isAccountNonLocked() { // return true; // } // // @Override // public boolean isCredentialsNonExpired() { // return true; // } // // @Override // // public boolean isEnabled() { // return true; // } // // // } // // Path: src/main/java/com/hantsylabs/restexample/springmvc/security/SecurityUtil.java // public class SecurityUtil { // // private SecurityUtil() {} // // public static User currentUser() { // Authentication auth = SecurityContextHolder.getContext() // .getAuthentication(); // if (auth == null) { // return null; // } // // if (auth instanceof AnonymousAuthenticationToken) { // return null; // } // // return (User) auth.getPrincipal(); // } // } // Path: src/main/java/com/hantsylabs/restexample/springmvc/JpaConfig.java import com.hantsylabs.restexample.springmvc.domain.User; import com.hantsylabs.restexample.springmvc.security.SecurityUtil; import org.springframework.boot.autoconfigure.domain.EntityScan; import org.springframework.context.annotation.AdviceMode; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.data.domain.AuditorAware; import org.springframework.data.jpa.convert.threeten.Jsr310JpaConverters; import org.springframework.data.jpa.repository.config.EnableJpaAuditing; import org.springframework.transaction.annotation.EnableTransactionManagement; package com.hantsylabs.restexample.springmvc; /** * * @author hantsy */ @Configuration @EnableTransactionManagement(mode = AdviceMode.ASPECTJ)
@EntityScan(basePackageClasses = {User.class, Jsr310JpaConverters.class})
hantsy/angularjs-springmvc-sample-boot
src/main/java/com/hantsylabs/restexample/springmvc/JpaConfig.java
// Path: src/main/java/com/hantsylabs/restexample/springmvc/domain/User.java // @Data // @Builder // @NoArgsConstructor // @AllArgsConstructor // @Entity // @Table(name = "users") // public class User implements UserDetails, Serializable { // // /** // * // */ // private static final long serialVersionUID = 1L; // // @Id() // @GeneratedValue(strategy = GenerationType.IDENTITY) // @Column(name = "id") // private Long id; // // @Column(name = "username") // private String username; // // @Column(name = "password") // private String password; // // @Column(name = "name") // private String name; // // @Column(name = "email") // private String email; // // @Column(name = "role") // private String role; // // @Column(name = "created_date") // @CreatedDate // private LocalDateTime createdDate; // // public String getName() { // if (this.name == null || this.name.trim().length() == 0) { // return this.username; // } // return name; // } // // @Override // public Collection<? extends GrantedAuthority> getAuthorities() { // return Arrays.asList(new SimpleGrantedAuthority("ROLE_" + this.role)); // } // // @Override // public String getPassword() { // return this.password; // } // // @Override // public String getUsername() { // return this.username; // } // // @Override // public boolean isAccountNonExpired() { // return true; // } // // @Override // public boolean isAccountNonLocked() { // return true; // } // // @Override // public boolean isCredentialsNonExpired() { // return true; // } // // @Override // // public boolean isEnabled() { // return true; // } // // // } // // Path: src/main/java/com/hantsylabs/restexample/springmvc/security/SecurityUtil.java // public class SecurityUtil { // // private SecurityUtil() {} // // public static User currentUser() { // Authentication auth = SecurityContextHolder.getContext() // .getAuthentication(); // if (auth == null) { // return null; // } // // if (auth instanceof AnonymousAuthenticationToken) { // return null; // } // // return (User) auth.getPrincipal(); // } // }
import com.hantsylabs.restexample.springmvc.domain.User; import com.hantsylabs.restexample.springmvc.security.SecurityUtil; import org.springframework.boot.autoconfigure.domain.EntityScan; import org.springframework.context.annotation.AdviceMode; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.data.domain.AuditorAware; import org.springframework.data.jpa.convert.threeten.Jsr310JpaConverters; import org.springframework.data.jpa.repository.config.EnableJpaAuditing; import org.springframework.transaction.annotation.EnableTransactionManagement;
package com.hantsylabs.restexample.springmvc; /** * * @author hantsy */ @Configuration @EnableTransactionManagement(mode = AdviceMode.ASPECTJ) @EntityScan(basePackageClasses = {User.class, Jsr310JpaConverters.class}) @EnableJpaAuditing(auditorAwareRef = "auditor") public class JpaConfig { @Bean public AuditorAware<User> auditor() {
// Path: src/main/java/com/hantsylabs/restexample/springmvc/domain/User.java // @Data // @Builder // @NoArgsConstructor // @AllArgsConstructor // @Entity // @Table(name = "users") // public class User implements UserDetails, Serializable { // // /** // * // */ // private static final long serialVersionUID = 1L; // // @Id() // @GeneratedValue(strategy = GenerationType.IDENTITY) // @Column(name = "id") // private Long id; // // @Column(name = "username") // private String username; // // @Column(name = "password") // private String password; // // @Column(name = "name") // private String name; // // @Column(name = "email") // private String email; // // @Column(name = "role") // private String role; // // @Column(name = "created_date") // @CreatedDate // private LocalDateTime createdDate; // // public String getName() { // if (this.name == null || this.name.trim().length() == 0) { // return this.username; // } // return name; // } // // @Override // public Collection<? extends GrantedAuthority> getAuthorities() { // return Arrays.asList(new SimpleGrantedAuthority("ROLE_" + this.role)); // } // // @Override // public String getPassword() { // return this.password; // } // // @Override // public String getUsername() { // return this.username; // } // // @Override // public boolean isAccountNonExpired() { // return true; // } // // @Override // public boolean isAccountNonLocked() { // return true; // } // // @Override // public boolean isCredentialsNonExpired() { // return true; // } // // @Override // // public boolean isEnabled() { // return true; // } // // // } // // Path: src/main/java/com/hantsylabs/restexample/springmvc/security/SecurityUtil.java // public class SecurityUtil { // // private SecurityUtil() {} // // public static User currentUser() { // Authentication auth = SecurityContextHolder.getContext() // .getAuthentication(); // if (auth == null) { // return null; // } // // if (auth instanceof AnonymousAuthenticationToken) { // return null; // } // // return (User) auth.getPrincipal(); // } // } // Path: src/main/java/com/hantsylabs/restexample/springmvc/JpaConfig.java import com.hantsylabs.restexample.springmvc.domain.User; import com.hantsylabs.restexample.springmvc.security.SecurityUtil; import org.springframework.boot.autoconfigure.domain.EntityScan; import org.springframework.context.annotation.AdviceMode; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.data.domain.AuditorAware; import org.springframework.data.jpa.convert.threeten.Jsr310JpaConverters; import org.springframework.data.jpa.repository.config.EnableJpaAuditing; import org.springframework.transaction.annotation.EnableTransactionManagement; package com.hantsylabs.restexample.springmvc; /** * * @author hantsy */ @Configuration @EnableTransactionManagement(mode = AdviceMode.ASPECTJ) @EntityScan(basePackageClasses = {User.class, Jsr310JpaConverters.class}) @EnableJpaAuditing(auditorAwareRef = "auditor") public class JpaConfig { @Bean public AuditorAware<User> auditor() {
return () -> SecurityUtil.currentUser();
hantsy/angularjs-springmvc-sample-boot
src/test/java/com/hantsylabs/restexample/springmvc/test/jbehave/stories/PostStory.java
// Path: src/main/java/com/hantsylabs/restexample/springmvc/repository/PostRepository.java // public interface PostRepository extends JpaRepository<Post, Long>,// // JpaSpecificationExecutor<Post>{ // // } // // Path: src/test/java/com/hantsylabs/restexample/springmvc/test/jbehave/AbstractSpringJBehaveStory.java // @Slf4j // public abstract class AbstractSpringJBehaveStory extends JUnitStory { // // @Inject // PostRepository posts; // // @Inject // CommentRepository comments; // // @Inject // UserRepository users; // // @Inject // PasswordEncoder passwordEncoder; // // public void clearData() { // log.debug("clearing data..."); // // comments.deleteAllInBatch(); // posts.deleteAllInBatch(); // users.deleteAllInBatch(); // } // // public void initData() { // // users.save( // User.builder() // .username("admin") // .password(passwordEncoder.encode("test123")) // .name("Administrator") // .role("ADMIN") // .build() // ); // } // // private static final String STORY_TIMEOUT_IN_SECONDS = "120"; // // public AbstractSpringJBehaveStory() { // Embedder embedder = new Embedder(); // embedder.useEmbedderControls(embedderControls()); // embedder.useMetaFilters(Arrays.asList("-skip")); // useEmbedder(embedder); // } // // @Override // public Configuration configuration() { // return new MostUsefulConfiguration() // .useStoryPathResolver(storyPathResolver()) // .useStoryLoader(storyLoader()) // .useStoryReporterBuilder(storyReporterBuilder()) // .useParameterControls(parameterControls()); // } // // @Override // public InjectableStepsFactory stepsFactory() { // return new InstanceStepsFactory(configuration(), getSteps()); // } // // private EmbedderControls embedderControls() { // return new EmbedderControls() // .doIgnoreFailureInView(false) // .doIgnoreFailureInStories(false) // .doVerboseFailures(true) // .doVerboseFiltering(true) // .useStoryTimeouts(STORY_TIMEOUT_IN_SECONDS); // } // // private ParameterControls parameterControls() { // return new ParameterControls() // .useDelimiterNamedParameters(true); // } // // private StoryPathResolver storyPathResolver() { // return new UnderscoredCamelCaseResolver(); // } // // private StoryLoader storyLoader() { // return new LoadFromClasspath(); // } // // private StoryReporterBuilder storyReporterBuilder() { // return new StoryReporterBuilder() // .withCodeLocation(CodeLocations.codeLocationFromClass(this.getClass())) // .withPathResolver(new ResolveToPackagedName()) // .withFailureTrace(true) // .withDefaultFormats() // .withFormats(IDE_CONSOLE, TXT, HTML); // } // // public abstract Object[] getSteps(); // } // // Path: src/test/java/com/hantsylabs/restexample/springmvc/test/jbehave/steps/PostSteps.java // public class PostSteps { // // PostRepository postRepository; // // TestRestTemplate restTemplate; // // String baseUrl; // // public PostSteps(PostRepository postRepository, // TestRestTemplate restTemplate, // String baseUrl) { // this.postRepository = postRepository; // this.restTemplate = restTemplate; // this.baseUrl = baseUrl; // } // // ResponseEntity<String> reponseEntity; // // @Given("post title is $title and content is $content") // public void savePost(@Named("title") String title, @Named("content") String content) { // postRepository.save(new Post(title, content)); // } // // @When("GET $path") // public void getPost(@Named("path") String path) { // reponseEntity = restTemplate.getForEntity(baseUrl + path, String.class); // } // // @Then("response status is $code") // public void responseCode(@Named("code") int code) { // assertTrue(reponseEntity.getStatusCode().value() == code); // } // // @Then("response body contains $body") // public void responseBody(@Named("body") String body) { // assertTrue(reponseEntity.getBody().contains(body)); // } // // }
import com.hantsylabs.restexample.springmvc.repository.PostRepository; import com.hantsylabs.restexample.springmvc.test.jbehave.AcceptanceTest; import com.hantsylabs.restexample.springmvc.test.jbehave.AbstractSpringJBehaveStory; import com.hantsylabs.restexample.springmvc.test.jbehave.steps.PostSteps; import javax.inject.Inject; import org.junit.Before; import org.junit.runner.RunWith; import org.springframework.boot.context.embedded.LocalServerPort; import org.springframework.boot.test.web.client.TestRestTemplate; import org.springframework.boot.test.web.client.TestRestTemplate.HttpClientOption; import org.springframework.test.context.junit4.SpringRunner;
package com.hantsylabs.restexample.springmvc.test.jbehave.stories; @RunWith(SpringRunner.class) @AcceptanceTest
// Path: src/main/java/com/hantsylabs/restexample/springmvc/repository/PostRepository.java // public interface PostRepository extends JpaRepository<Post, Long>,// // JpaSpecificationExecutor<Post>{ // // } // // Path: src/test/java/com/hantsylabs/restexample/springmvc/test/jbehave/AbstractSpringJBehaveStory.java // @Slf4j // public abstract class AbstractSpringJBehaveStory extends JUnitStory { // // @Inject // PostRepository posts; // // @Inject // CommentRepository comments; // // @Inject // UserRepository users; // // @Inject // PasswordEncoder passwordEncoder; // // public void clearData() { // log.debug("clearing data..."); // // comments.deleteAllInBatch(); // posts.deleteAllInBatch(); // users.deleteAllInBatch(); // } // // public void initData() { // // users.save( // User.builder() // .username("admin") // .password(passwordEncoder.encode("test123")) // .name("Administrator") // .role("ADMIN") // .build() // ); // } // // private static final String STORY_TIMEOUT_IN_SECONDS = "120"; // // public AbstractSpringJBehaveStory() { // Embedder embedder = new Embedder(); // embedder.useEmbedderControls(embedderControls()); // embedder.useMetaFilters(Arrays.asList("-skip")); // useEmbedder(embedder); // } // // @Override // public Configuration configuration() { // return new MostUsefulConfiguration() // .useStoryPathResolver(storyPathResolver()) // .useStoryLoader(storyLoader()) // .useStoryReporterBuilder(storyReporterBuilder()) // .useParameterControls(parameterControls()); // } // // @Override // public InjectableStepsFactory stepsFactory() { // return new InstanceStepsFactory(configuration(), getSteps()); // } // // private EmbedderControls embedderControls() { // return new EmbedderControls() // .doIgnoreFailureInView(false) // .doIgnoreFailureInStories(false) // .doVerboseFailures(true) // .doVerboseFiltering(true) // .useStoryTimeouts(STORY_TIMEOUT_IN_SECONDS); // } // // private ParameterControls parameterControls() { // return new ParameterControls() // .useDelimiterNamedParameters(true); // } // // private StoryPathResolver storyPathResolver() { // return new UnderscoredCamelCaseResolver(); // } // // private StoryLoader storyLoader() { // return new LoadFromClasspath(); // } // // private StoryReporterBuilder storyReporterBuilder() { // return new StoryReporterBuilder() // .withCodeLocation(CodeLocations.codeLocationFromClass(this.getClass())) // .withPathResolver(new ResolveToPackagedName()) // .withFailureTrace(true) // .withDefaultFormats() // .withFormats(IDE_CONSOLE, TXT, HTML); // } // // public abstract Object[] getSteps(); // } // // Path: src/test/java/com/hantsylabs/restexample/springmvc/test/jbehave/steps/PostSteps.java // public class PostSteps { // // PostRepository postRepository; // // TestRestTemplate restTemplate; // // String baseUrl; // // public PostSteps(PostRepository postRepository, // TestRestTemplate restTemplate, // String baseUrl) { // this.postRepository = postRepository; // this.restTemplate = restTemplate; // this.baseUrl = baseUrl; // } // // ResponseEntity<String> reponseEntity; // // @Given("post title is $title and content is $content") // public void savePost(@Named("title") String title, @Named("content") String content) { // postRepository.save(new Post(title, content)); // } // // @When("GET $path") // public void getPost(@Named("path") String path) { // reponseEntity = restTemplate.getForEntity(baseUrl + path, String.class); // } // // @Then("response status is $code") // public void responseCode(@Named("code") int code) { // assertTrue(reponseEntity.getStatusCode().value() == code); // } // // @Then("response body contains $body") // public void responseBody(@Named("body") String body) { // assertTrue(reponseEntity.getBody().contains(body)); // } // // } // Path: src/test/java/com/hantsylabs/restexample/springmvc/test/jbehave/stories/PostStory.java import com.hantsylabs.restexample.springmvc.repository.PostRepository; import com.hantsylabs.restexample.springmvc.test.jbehave.AcceptanceTest; import com.hantsylabs.restexample.springmvc.test.jbehave.AbstractSpringJBehaveStory; import com.hantsylabs.restexample.springmvc.test.jbehave.steps.PostSteps; import javax.inject.Inject; import org.junit.Before; import org.junit.runner.RunWith; import org.springframework.boot.context.embedded.LocalServerPort; import org.springframework.boot.test.web.client.TestRestTemplate; import org.springframework.boot.test.web.client.TestRestTemplate.HttpClientOption; import org.springframework.test.context.junit4.SpringRunner; package com.hantsylabs.restexample.springmvc.test.jbehave.stories; @RunWith(SpringRunner.class) @AcceptanceTest
public class PostStory extends AbstractSpringJBehaveStory {
hantsy/angularjs-springmvc-sample-boot
src/test/java/com/hantsylabs/restexample/springmvc/test/jbehave/stories/PostStory.java
// Path: src/main/java/com/hantsylabs/restexample/springmvc/repository/PostRepository.java // public interface PostRepository extends JpaRepository<Post, Long>,// // JpaSpecificationExecutor<Post>{ // // } // // Path: src/test/java/com/hantsylabs/restexample/springmvc/test/jbehave/AbstractSpringJBehaveStory.java // @Slf4j // public abstract class AbstractSpringJBehaveStory extends JUnitStory { // // @Inject // PostRepository posts; // // @Inject // CommentRepository comments; // // @Inject // UserRepository users; // // @Inject // PasswordEncoder passwordEncoder; // // public void clearData() { // log.debug("clearing data..."); // // comments.deleteAllInBatch(); // posts.deleteAllInBatch(); // users.deleteAllInBatch(); // } // // public void initData() { // // users.save( // User.builder() // .username("admin") // .password(passwordEncoder.encode("test123")) // .name("Administrator") // .role("ADMIN") // .build() // ); // } // // private static final String STORY_TIMEOUT_IN_SECONDS = "120"; // // public AbstractSpringJBehaveStory() { // Embedder embedder = new Embedder(); // embedder.useEmbedderControls(embedderControls()); // embedder.useMetaFilters(Arrays.asList("-skip")); // useEmbedder(embedder); // } // // @Override // public Configuration configuration() { // return new MostUsefulConfiguration() // .useStoryPathResolver(storyPathResolver()) // .useStoryLoader(storyLoader()) // .useStoryReporterBuilder(storyReporterBuilder()) // .useParameterControls(parameterControls()); // } // // @Override // public InjectableStepsFactory stepsFactory() { // return new InstanceStepsFactory(configuration(), getSteps()); // } // // private EmbedderControls embedderControls() { // return new EmbedderControls() // .doIgnoreFailureInView(false) // .doIgnoreFailureInStories(false) // .doVerboseFailures(true) // .doVerboseFiltering(true) // .useStoryTimeouts(STORY_TIMEOUT_IN_SECONDS); // } // // private ParameterControls parameterControls() { // return new ParameterControls() // .useDelimiterNamedParameters(true); // } // // private StoryPathResolver storyPathResolver() { // return new UnderscoredCamelCaseResolver(); // } // // private StoryLoader storyLoader() { // return new LoadFromClasspath(); // } // // private StoryReporterBuilder storyReporterBuilder() { // return new StoryReporterBuilder() // .withCodeLocation(CodeLocations.codeLocationFromClass(this.getClass())) // .withPathResolver(new ResolveToPackagedName()) // .withFailureTrace(true) // .withDefaultFormats() // .withFormats(IDE_CONSOLE, TXT, HTML); // } // // public abstract Object[] getSteps(); // } // // Path: src/test/java/com/hantsylabs/restexample/springmvc/test/jbehave/steps/PostSteps.java // public class PostSteps { // // PostRepository postRepository; // // TestRestTemplate restTemplate; // // String baseUrl; // // public PostSteps(PostRepository postRepository, // TestRestTemplate restTemplate, // String baseUrl) { // this.postRepository = postRepository; // this.restTemplate = restTemplate; // this.baseUrl = baseUrl; // } // // ResponseEntity<String> reponseEntity; // // @Given("post title is $title and content is $content") // public void savePost(@Named("title") String title, @Named("content") String content) { // postRepository.save(new Post(title, content)); // } // // @When("GET $path") // public void getPost(@Named("path") String path) { // reponseEntity = restTemplate.getForEntity(baseUrl + path, String.class); // } // // @Then("response status is $code") // public void responseCode(@Named("code") int code) { // assertTrue(reponseEntity.getStatusCode().value() == code); // } // // @Then("response body contains $body") // public void responseBody(@Named("body") String body) { // assertTrue(reponseEntity.getBody().contains(body)); // } // // }
import com.hantsylabs.restexample.springmvc.repository.PostRepository; import com.hantsylabs.restexample.springmvc.test.jbehave.AcceptanceTest; import com.hantsylabs.restexample.springmvc.test.jbehave.AbstractSpringJBehaveStory; import com.hantsylabs.restexample.springmvc.test.jbehave.steps.PostSteps; import javax.inject.Inject; import org.junit.Before; import org.junit.runner.RunWith; import org.springframework.boot.context.embedded.LocalServerPort; import org.springframework.boot.test.web.client.TestRestTemplate; import org.springframework.boot.test.web.client.TestRestTemplate.HttpClientOption; import org.springframework.test.context.junit4.SpringRunner;
package com.hantsylabs.restexample.springmvc.test.jbehave.stories; @RunWith(SpringRunner.class) @AcceptanceTest public class PostStory extends AbstractSpringJBehaveStory { @Inject
// Path: src/main/java/com/hantsylabs/restexample/springmvc/repository/PostRepository.java // public interface PostRepository extends JpaRepository<Post, Long>,// // JpaSpecificationExecutor<Post>{ // // } // // Path: src/test/java/com/hantsylabs/restexample/springmvc/test/jbehave/AbstractSpringJBehaveStory.java // @Slf4j // public abstract class AbstractSpringJBehaveStory extends JUnitStory { // // @Inject // PostRepository posts; // // @Inject // CommentRepository comments; // // @Inject // UserRepository users; // // @Inject // PasswordEncoder passwordEncoder; // // public void clearData() { // log.debug("clearing data..."); // // comments.deleteAllInBatch(); // posts.deleteAllInBatch(); // users.deleteAllInBatch(); // } // // public void initData() { // // users.save( // User.builder() // .username("admin") // .password(passwordEncoder.encode("test123")) // .name("Administrator") // .role("ADMIN") // .build() // ); // } // // private static final String STORY_TIMEOUT_IN_SECONDS = "120"; // // public AbstractSpringJBehaveStory() { // Embedder embedder = new Embedder(); // embedder.useEmbedderControls(embedderControls()); // embedder.useMetaFilters(Arrays.asList("-skip")); // useEmbedder(embedder); // } // // @Override // public Configuration configuration() { // return new MostUsefulConfiguration() // .useStoryPathResolver(storyPathResolver()) // .useStoryLoader(storyLoader()) // .useStoryReporterBuilder(storyReporterBuilder()) // .useParameterControls(parameterControls()); // } // // @Override // public InjectableStepsFactory stepsFactory() { // return new InstanceStepsFactory(configuration(), getSteps()); // } // // private EmbedderControls embedderControls() { // return new EmbedderControls() // .doIgnoreFailureInView(false) // .doIgnoreFailureInStories(false) // .doVerboseFailures(true) // .doVerboseFiltering(true) // .useStoryTimeouts(STORY_TIMEOUT_IN_SECONDS); // } // // private ParameterControls parameterControls() { // return new ParameterControls() // .useDelimiterNamedParameters(true); // } // // private StoryPathResolver storyPathResolver() { // return new UnderscoredCamelCaseResolver(); // } // // private StoryLoader storyLoader() { // return new LoadFromClasspath(); // } // // private StoryReporterBuilder storyReporterBuilder() { // return new StoryReporterBuilder() // .withCodeLocation(CodeLocations.codeLocationFromClass(this.getClass())) // .withPathResolver(new ResolveToPackagedName()) // .withFailureTrace(true) // .withDefaultFormats() // .withFormats(IDE_CONSOLE, TXT, HTML); // } // // public abstract Object[] getSteps(); // } // // Path: src/test/java/com/hantsylabs/restexample/springmvc/test/jbehave/steps/PostSteps.java // public class PostSteps { // // PostRepository postRepository; // // TestRestTemplate restTemplate; // // String baseUrl; // // public PostSteps(PostRepository postRepository, // TestRestTemplate restTemplate, // String baseUrl) { // this.postRepository = postRepository; // this.restTemplate = restTemplate; // this.baseUrl = baseUrl; // } // // ResponseEntity<String> reponseEntity; // // @Given("post title is $title and content is $content") // public void savePost(@Named("title") String title, @Named("content") String content) { // postRepository.save(new Post(title, content)); // } // // @When("GET $path") // public void getPost(@Named("path") String path) { // reponseEntity = restTemplate.getForEntity(baseUrl + path, String.class); // } // // @Then("response status is $code") // public void responseCode(@Named("code") int code) { // assertTrue(reponseEntity.getStatusCode().value() == code); // } // // @Then("response body contains $body") // public void responseBody(@Named("body") String body) { // assertTrue(reponseEntity.getBody().contains(body)); // } // // } // Path: src/test/java/com/hantsylabs/restexample/springmvc/test/jbehave/stories/PostStory.java import com.hantsylabs.restexample.springmvc.repository.PostRepository; import com.hantsylabs.restexample.springmvc.test.jbehave.AcceptanceTest; import com.hantsylabs.restexample.springmvc.test.jbehave.AbstractSpringJBehaveStory; import com.hantsylabs.restexample.springmvc.test.jbehave.steps.PostSteps; import javax.inject.Inject; import org.junit.Before; import org.junit.runner.RunWith; import org.springframework.boot.context.embedded.LocalServerPort; import org.springframework.boot.test.web.client.TestRestTemplate; import org.springframework.boot.test.web.client.TestRestTemplate.HttpClientOption; import org.springframework.test.context.junit4.SpringRunner; package com.hantsylabs.restexample.springmvc.test.jbehave.stories; @RunWith(SpringRunner.class) @AcceptanceTest public class PostStory extends AbstractSpringJBehaveStory { @Inject
PostRepository postRepository;
hantsy/angularjs-springmvc-sample-boot
src/test/java/com/hantsylabs/restexample/springmvc/test/jbehave/stories/PostStory.java
// Path: src/main/java/com/hantsylabs/restexample/springmvc/repository/PostRepository.java // public interface PostRepository extends JpaRepository<Post, Long>,// // JpaSpecificationExecutor<Post>{ // // } // // Path: src/test/java/com/hantsylabs/restexample/springmvc/test/jbehave/AbstractSpringJBehaveStory.java // @Slf4j // public abstract class AbstractSpringJBehaveStory extends JUnitStory { // // @Inject // PostRepository posts; // // @Inject // CommentRepository comments; // // @Inject // UserRepository users; // // @Inject // PasswordEncoder passwordEncoder; // // public void clearData() { // log.debug("clearing data..."); // // comments.deleteAllInBatch(); // posts.deleteAllInBatch(); // users.deleteAllInBatch(); // } // // public void initData() { // // users.save( // User.builder() // .username("admin") // .password(passwordEncoder.encode("test123")) // .name("Administrator") // .role("ADMIN") // .build() // ); // } // // private static final String STORY_TIMEOUT_IN_SECONDS = "120"; // // public AbstractSpringJBehaveStory() { // Embedder embedder = new Embedder(); // embedder.useEmbedderControls(embedderControls()); // embedder.useMetaFilters(Arrays.asList("-skip")); // useEmbedder(embedder); // } // // @Override // public Configuration configuration() { // return new MostUsefulConfiguration() // .useStoryPathResolver(storyPathResolver()) // .useStoryLoader(storyLoader()) // .useStoryReporterBuilder(storyReporterBuilder()) // .useParameterControls(parameterControls()); // } // // @Override // public InjectableStepsFactory stepsFactory() { // return new InstanceStepsFactory(configuration(), getSteps()); // } // // private EmbedderControls embedderControls() { // return new EmbedderControls() // .doIgnoreFailureInView(false) // .doIgnoreFailureInStories(false) // .doVerboseFailures(true) // .doVerboseFiltering(true) // .useStoryTimeouts(STORY_TIMEOUT_IN_SECONDS); // } // // private ParameterControls parameterControls() { // return new ParameterControls() // .useDelimiterNamedParameters(true); // } // // private StoryPathResolver storyPathResolver() { // return new UnderscoredCamelCaseResolver(); // } // // private StoryLoader storyLoader() { // return new LoadFromClasspath(); // } // // private StoryReporterBuilder storyReporterBuilder() { // return new StoryReporterBuilder() // .withCodeLocation(CodeLocations.codeLocationFromClass(this.getClass())) // .withPathResolver(new ResolveToPackagedName()) // .withFailureTrace(true) // .withDefaultFormats() // .withFormats(IDE_CONSOLE, TXT, HTML); // } // // public abstract Object[] getSteps(); // } // // Path: src/test/java/com/hantsylabs/restexample/springmvc/test/jbehave/steps/PostSteps.java // public class PostSteps { // // PostRepository postRepository; // // TestRestTemplate restTemplate; // // String baseUrl; // // public PostSteps(PostRepository postRepository, // TestRestTemplate restTemplate, // String baseUrl) { // this.postRepository = postRepository; // this.restTemplate = restTemplate; // this.baseUrl = baseUrl; // } // // ResponseEntity<String> reponseEntity; // // @Given("post title is $title and content is $content") // public void savePost(@Named("title") String title, @Named("content") String content) { // postRepository.save(new Post(title, content)); // } // // @When("GET $path") // public void getPost(@Named("path") String path) { // reponseEntity = restTemplate.getForEntity(baseUrl + path, String.class); // } // // @Then("response status is $code") // public void responseCode(@Named("code") int code) { // assertTrue(reponseEntity.getStatusCode().value() == code); // } // // @Then("response body contains $body") // public void responseBody(@Named("body") String body) { // assertTrue(reponseEntity.getBody().contains(body)); // } // // }
import com.hantsylabs.restexample.springmvc.repository.PostRepository; import com.hantsylabs.restexample.springmvc.test.jbehave.AcceptanceTest; import com.hantsylabs.restexample.springmvc.test.jbehave.AbstractSpringJBehaveStory; import com.hantsylabs.restexample.springmvc.test.jbehave.steps.PostSteps; import javax.inject.Inject; import org.junit.Before; import org.junit.runner.RunWith; import org.springframework.boot.context.embedded.LocalServerPort; import org.springframework.boot.test.web.client.TestRestTemplate; import org.springframework.boot.test.web.client.TestRestTemplate.HttpClientOption; import org.springframework.test.context.junit4.SpringRunner;
package com.hantsylabs.restexample.springmvc.test.jbehave.stories; @RunWith(SpringRunner.class) @AcceptanceTest public class PostStory extends AbstractSpringJBehaveStory { @Inject PostRepository postRepository; TestRestTemplate restTemplate; String baseUrl; @LocalServerPort int port; @Before public void setup() { clearData(); initData(); this.baseUrl = "http://localhost:" + port; this.restTemplate = new TestRestTemplate("admin", "test123", new HttpClientOption[]{}); } @Override public Object[] getSteps() {
// Path: src/main/java/com/hantsylabs/restexample/springmvc/repository/PostRepository.java // public interface PostRepository extends JpaRepository<Post, Long>,// // JpaSpecificationExecutor<Post>{ // // } // // Path: src/test/java/com/hantsylabs/restexample/springmvc/test/jbehave/AbstractSpringJBehaveStory.java // @Slf4j // public abstract class AbstractSpringJBehaveStory extends JUnitStory { // // @Inject // PostRepository posts; // // @Inject // CommentRepository comments; // // @Inject // UserRepository users; // // @Inject // PasswordEncoder passwordEncoder; // // public void clearData() { // log.debug("clearing data..."); // // comments.deleteAllInBatch(); // posts.deleteAllInBatch(); // users.deleteAllInBatch(); // } // // public void initData() { // // users.save( // User.builder() // .username("admin") // .password(passwordEncoder.encode("test123")) // .name("Administrator") // .role("ADMIN") // .build() // ); // } // // private static final String STORY_TIMEOUT_IN_SECONDS = "120"; // // public AbstractSpringJBehaveStory() { // Embedder embedder = new Embedder(); // embedder.useEmbedderControls(embedderControls()); // embedder.useMetaFilters(Arrays.asList("-skip")); // useEmbedder(embedder); // } // // @Override // public Configuration configuration() { // return new MostUsefulConfiguration() // .useStoryPathResolver(storyPathResolver()) // .useStoryLoader(storyLoader()) // .useStoryReporterBuilder(storyReporterBuilder()) // .useParameterControls(parameterControls()); // } // // @Override // public InjectableStepsFactory stepsFactory() { // return new InstanceStepsFactory(configuration(), getSteps()); // } // // private EmbedderControls embedderControls() { // return new EmbedderControls() // .doIgnoreFailureInView(false) // .doIgnoreFailureInStories(false) // .doVerboseFailures(true) // .doVerboseFiltering(true) // .useStoryTimeouts(STORY_TIMEOUT_IN_SECONDS); // } // // private ParameterControls parameterControls() { // return new ParameterControls() // .useDelimiterNamedParameters(true); // } // // private StoryPathResolver storyPathResolver() { // return new UnderscoredCamelCaseResolver(); // } // // private StoryLoader storyLoader() { // return new LoadFromClasspath(); // } // // private StoryReporterBuilder storyReporterBuilder() { // return new StoryReporterBuilder() // .withCodeLocation(CodeLocations.codeLocationFromClass(this.getClass())) // .withPathResolver(new ResolveToPackagedName()) // .withFailureTrace(true) // .withDefaultFormats() // .withFormats(IDE_CONSOLE, TXT, HTML); // } // // public abstract Object[] getSteps(); // } // // Path: src/test/java/com/hantsylabs/restexample/springmvc/test/jbehave/steps/PostSteps.java // public class PostSteps { // // PostRepository postRepository; // // TestRestTemplate restTemplate; // // String baseUrl; // // public PostSteps(PostRepository postRepository, // TestRestTemplate restTemplate, // String baseUrl) { // this.postRepository = postRepository; // this.restTemplate = restTemplate; // this.baseUrl = baseUrl; // } // // ResponseEntity<String> reponseEntity; // // @Given("post title is $title and content is $content") // public void savePost(@Named("title") String title, @Named("content") String content) { // postRepository.save(new Post(title, content)); // } // // @When("GET $path") // public void getPost(@Named("path") String path) { // reponseEntity = restTemplate.getForEntity(baseUrl + path, String.class); // } // // @Then("response status is $code") // public void responseCode(@Named("code") int code) { // assertTrue(reponseEntity.getStatusCode().value() == code); // } // // @Then("response body contains $body") // public void responseBody(@Named("body") String body) { // assertTrue(reponseEntity.getBody().contains(body)); // } // // } // Path: src/test/java/com/hantsylabs/restexample/springmvc/test/jbehave/stories/PostStory.java import com.hantsylabs.restexample.springmvc.repository.PostRepository; import com.hantsylabs.restexample.springmvc.test.jbehave.AcceptanceTest; import com.hantsylabs.restexample.springmvc.test.jbehave.AbstractSpringJBehaveStory; import com.hantsylabs.restexample.springmvc.test.jbehave.steps.PostSteps; import javax.inject.Inject; import org.junit.Before; import org.junit.runner.RunWith; import org.springframework.boot.context.embedded.LocalServerPort; import org.springframework.boot.test.web.client.TestRestTemplate; import org.springframework.boot.test.web.client.TestRestTemplate.HttpClientOption; import org.springframework.test.context.junit4.SpringRunner; package com.hantsylabs.restexample.springmvc.test.jbehave.stories; @RunWith(SpringRunner.class) @AcceptanceTest public class PostStory extends AbstractSpringJBehaveStory { @Inject PostRepository postRepository; TestRestTemplate restTemplate; String baseUrl; @LocalServerPort int port; @Before public void setup() { clearData(); initData(); this.baseUrl = "http://localhost:" + port; this.restTemplate = new TestRestTemplate("admin", "test123", new HttpClientOption[]{}); } @Override public Object[] getSteps() {
return new Object[]{new PostSteps(postRepository, restTemplate, baseUrl)};
hantsy/angularjs-springmvc-sample-boot
src/main/java/com/hantsylabs/restexample/springmvc/security/SecurityUtil.java
// Path: src/main/java/com/hantsylabs/restexample/springmvc/domain/User.java // @Data // @Builder // @NoArgsConstructor // @AllArgsConstructor // @Entity // @Table(name = "users") // public class User implements UserDetails, Serializable { // // /** // * // */ // private static final long serialVersionUID = 1L; // // @Id() // @GeneratedValue(strategy = GenerationType.IDENTITY) // @Column(name = "id") // private Long id; // // @Column(name = "username") // private String username; // // @Column(name = "password") // private String password; // // @Column(name = "name") // private String name; // // @Column(name = "email") // private String email; // // @Column(name = "role") // private String role; // // @Column(name = "created_date") // @CreatedDate // private LocalDateTime createdDate; // // public String getName() { // if (this.name == null || this.name.trim().length() == 0) { // return this.username; // } // return name; // } // // @Override // public Collection<? extends GrantedAuthority> getAuthorities() { // return Arrays.asList(new SimpleGrantedAuthority("ROLE_" + this.role)); // } // // @Override // public String getPassword() { // return this.password; // } // // @Override // public String getUsername() { // return this.username; // } // // @Override // public boolean isAccountNonExpired() { // return true; // } // // @Override // public boolean isAccountNonLocked() { // return true; // } // // @Override // public boolean isCredentialsNonExpired() { // return true; // } // // @Override // // public boolean isEnabled() { // return true; // } // // // }
import com.hantsylabs.restexample.springmvc.domain.User; import org.springframework.security.authentication.AnonymousAuthenticationToken; import org.springframework.security.core.Authentication; import org.springframework.security.core.context.SecurityContextHolder;
package com.hantsylabs.restexample.springmvc.security; public class SecurityUtil { private SecurityUtil() {}
// Path: src/main/java/com/hantsylabs/restexample/springmvc/domain/User.java // @Data // @Builder // @NoArgsConstructor // @AllArgsConstructor // @Entity // @Table(name = "users") // public class User implements UserDetails, Serializable { // // /** // * // */ // private static final long serialVersionUID = 1L; // // @Id() // @GeneratedValue(strategy = GenerationType.IDENTITY) // @Column(name = "id") // private Long id; // // @Column(name = "username") // private String username; // // @Column(name = "password") // private String password; // // @Column(name = "name") // private String name; // // @Column(name = "email") // private String email; // // @Column(name = "role") // private String role; // // @Column(name = "created_date") // @CreatedDate // private LocalDateTime createdDate; // // public String getName() { // if (this.name == null || this.name.trim().length() == 0) { // return this.username; // } // return name; // } // // @Override // public Collection<? extends GrantedAuthority> getAuthorities() { // return Arrays.asList(new SimpleGrantedAuthority("ROLE_" + this.role)); // } // // @Override // public String getPassword() { // return this.password; // } // // @Override // public String getUsername() { // return this.username; // } // // @Override // public boolean isAccountNonExpired() { // return true; // } // // @Override // public boolean isAccountNonLocked() { // return true; // } // // @Override // public boolean isCredentialsNonExpired() { // return true; // } // // @Override // // public boolean isEnabled() { // return true; // } // // // } // Path: src/main/java/com/hantsylabs/restexample/springmvc/security/SecurityUtil.java import com.hantsylabs.restexample.springmvc.domain.User; import org.springframework.security.authentication.AnonymousAuthenticationToken; import org.springframework.security.core.Authentication; import org.springframework.security.core.context.SecurityContextHolder; package com.hantsylabs.restexample.springmvc.security; public class SecurityUtil { private SecurityUtil() {}
public static User currentUser() {
hantsy/angularjs-springmvc-sample-boot
src/main/java/com/hantsylabs/restexample/springmvc/repository/UserSpecifications.java
// Path: src/main/java/com/hantsylabs/restexample/springmvc/domain/User.java // @Data // @Builder // @NoArgsConstructor // @AllArgsConstructor // @Entity // @Table(name = "users") // public class User implements UserDetails, Serializable { // // /** // * // */ // private static final long serialVersionUID = 1L; // // @Id() // @GeneratedValue(strategy = GenerationType.IDENTITY) // @Column(name = "id") // private Long id; // // @Column(name = "username") // private String username; // // @Column(name = "password") // private String password; // // @Column(name = "name") // private String name; // // @Column(name = "email") // private String email; // // @Column(name = "role") // private String role; // // @Column(name = "created_date") // @CreatedDate // private LocalDateTime createdDate; // // public String getName() { // if (this.name == null || this.name.trim().length() == 0) { // return this.username; // } // return name; // } // // @Override // public Collection<? extends GrantedAuthority> getAuthorities() { // return Arrays.asList(new SimpleGrantedAuthority("ROLE_" + this.role)); // } // // @Override // public String getPassword() { // return this.password; // } // // @Override // public String getUsername() { // return this.username; // } // // @Override // public boolean isAccountNonExpired() { // return true; // } // // @Override // public boolean isAccountNonLocked() { // return true; // } // // @Override // public boolean isCredentialsNonExpired() { // return true; // } // // @Override // // public boolean isEnabled() { // return true; // } // // // }
import com.hantsylabs.restexample.springmvc.domain.User; import com.hantsylabs.restexample.springmvc.domain.User_; import java.util.ArrayList; import java.util.List; import javax.persistence.criteria.CriteriaBuilder; import javax.persistence.criteria.CriteriaQuery; import javax.persistence.criteria.Predicate; import javax.persistence.criteria.Root; import org.springframework.data.jpa.domain.Specification; import org.springframework.util.StringUtils;
package com.hantsylabs.restexample.springmvc.repository; /** * * @author Hantsy Bai<[email protected]> * */ public class UserSpecifications { private UserSpecifications() {}
// Path: src/main/java/com/hantsylabs/restexample/springmvc/domain/User.java // @Data // @Builder // @NoArgsConstructor // @AllArgsConstructor // @Entity // @Table(name = "users") // public class User implements UserDetails, Serializable { // // /** // * // */ // private static final long serialVersionUID = 1L; // // @Id() // @GeneratedValue(strategy = GenerationType.IDENTITY) // @Column(name = "id") // private Long id; // // @Column(name = "username") // private String username; // // @Column(name = "password") // private String password; // // @Column(name = "name") // private String name; // // @Column(name = "email") // private String email; // // @Column(name = "role") // private String role; // // @Column(name = "created_date") // @CreatedDate // private LocalDateTime createdDate; // // public String getName() { // if (this.name == null || this.name.trim().length() == 0) { // return this.username; // } // return name; // } // // @Override // public Collection<? extends GrantedAuthority> getAuthorities() { // return Arrays.asList(new SimpleGrantedAuthority("ROLE_" + this.role)); // } // // @Override // public String getPassword() { // return this.password; // } // // @Override // public String getUsername() { // return this.username; // } // // @Override // public boolean isAccountNonExpired() { // return true; // } // // @Override // public boolean isAccountNonLocked() { // return true; // } // // @Override // public boolean isCredentialsNonExpired() { // return true; // } // // @Override // // public boolean isEnabled() { // return true; // } // // // } // Path: src/main/java/com/hantsylabs/restexample/springmvc/repository/UserSpecifications.java import com.hantsylabs.restexample.springmvc.domain.User; import com.hantsylabs.restexample.springmvc.domain.User_; import java.util.ArrayList; import java.util.List; import javax.persistence.criteria.CriteriaBuilder; import javax.persistence.criteria.CriteriaQuery; import javax.persistence.criteria.Predicate; import javax.persistence.criteria.Root; import org.springframework.data.jpa.domain.Specification; import org.springframework.util.StringUtils; package com.hantsylabs.restexample.springmvc.repository; /** * * @author Hantsy Bai<[email protected]> * */ public class UserSpecifications { private UserSpecifications() {}
public static Specification<User> filterUsersByKeyword(
hantsy/angularjs-springmvc-sample-boot
src/main/java/com/hantsylabs/restexample/springmvc/security/SimpleUserDetailsServiceImpl.java
// Path: src/main/java/com/hantsylabs/restexample/springmvc/domain/User.java // @Data // @Builder // @NoArgsConstructor // @AllArgsConstructor // @Entity // @Table(name = "users") // public class User implements UserDetails, Serializable { // // /** // * // */ // private static final long serialVersionUID = 1L; // // @Id() // @GeneratedValue(strategy = GenerationType.IDENTITY) // @Column(name = "id") // private Long id; // // @Column(name = "username") // private String username; // // @Column(name = "password") // private String password; // // @Column(name = "name") // private String name; // // @Column(name = "email") // private String email; // // @Column(name = "role") // private String role; // // @Column(name = "created_date") // @CreatedDate // private LocalDateTime createdDate; // // public String getName() { // if (this.name == null || this.name.trim().length() == 0) { // return this.username; // } // return name; // } // // @Override // public Collection<? extends GrantedAuthority> getAuthorities() { // return Arrays.asList(new SimpleGrantedAuthority("ROLE_" + this.role)); // } // // @Override // public String getPassword() { // return this.password; // } // // @Override // public String getUsername() { // return this.username; // } // // @Override // public boolean isAccountNonExpired() { // return true; // } // // @Override // public boolean isAccountNonLocked() { // return true; // } // // @Override // public boolean isCredentialsNonExpired() { // return true; // } // // @Override // // public boolean isEnabled() { // return true; // } // // // } // // Path: src/main/java/com/hantsylabs/restexample/springmvc/repository/UserRepository.java // public interface UserRepository extends JpaRepository<User, Long>, // JpaSpecificationExecutor<User> { // // public User findByUsername(String username); // }
import com.hantsylabs.restexample.springmvc.domain.User; import com.hantsylabs.restexample.springmvc.repository.UserRepository; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.security.core.userdetails.UserDetails; import org.springframework.security.core.userdetails.UserDetailsService; import org.springframework.security.core.userdetails.UsernameNotFoundException; import org.springframework.stereotype.Component;
package com.hantsylabs.restexample.springmvc.security; @Component public class SimpleUserDetailsServiceImpl implements UserDetailsService { private static final Logger log = LoggerFactory.getLogger(SimpleUserDetailsServiceImpl.class);
// Path: src/main/java/com/hantsylabs/restexample/springmvc/domain/User.java // @Data // @Builder // @NoArgsConstructor // @AllArgsConstructor // @Entity // @Table(name = "users") // public class User implements UserDetails, Serializable { // // /** // * // */ // private static final long serialVersionUID = 1L; // // @Id() // @GeneratedValue(strategy = GenerationType.IDENTITY) // @Column(name = "id") // private Long id; // // @Column(name = "username") // private String username; // // @Column(name = "password") // private String password; // // @Column(name = "name") // private String name; // // @Column(name = "email") // private String email; // // @Column(name = "role") // private String role; // // @Column(name = "created_date") // @CreatedDate // private LocalDateTime createdDate; // // public String getName() { // if (this.name == null || this.name.trim().length() == 0) { // return this.username; // } // return name; // } // // @Override // public Collection<? extends GrantedAuthority> getAuthorities() { // return Arrays.asList(new SimpleGrantedAuthority("ROLE_" + this.role)); // } // // @Override // public String getPassword() { // return this.password; // } // // @Override // public String getUsername() { // return this.username; // } // // @Override // public boolean isAccountNonExpired() { // return true; // } // // @Override // public boolean isAccountNonLocked() { // return true; // } // // @Override // public boolean isCredentialsNonExpired() { // return true; // } // // @Override // // public boolean isEnabled() { // return true; // } // // // } // // Path: src/main/java/com/hantsylabs/restexample/springmvc/repository/UserRepository.java // public interface UserRepository extends JpaRepository<User, Long>, // JpaSpecificationExecutor<User> { // // public User findByUsername(String username); // } // Path: src/main/java/com/hantsylabs/restexample/springmvc/security/SimpleUserDetailsServiceImpl.java import com.hantsylabs.restexample.springmvc.domain.User; import com.hantsylabs.restexample.springmvc.repository.UserRepository; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.security.core.userdetails.UserDetails; import org.springframework.security.core.userdetails.UserDetailsService; import org.springframework.security.core.userdetails.UsernameNotFoundException; import org.springframework.stereotype.Component; package com.hantsylabs.restexample.springmvc.security; @Component public class SimpleUserDetailsServiceImpl implements UserDetailsService { private static final Logger log = LoggerFactory.getLogger(SimpleUserDetailsServiceImpl.class);
private UserRepository userRepository;
hantsy/angularjs-springmvc-sample-boot
src/main/java/com/hantsylabs/restexample/springmvc/security/SimpleUserDetailsServiceImpl.java
// Path: src/main/java/com/hantsylabs/restexample/springmvc/domain/User.java // @Data // @Builder // @NoArgsConstructor // @AllArgsConstructor // @Entity // @Table(name = "users") // public class User implements UserDetails, Serializable { // // /** // * // */ // private static final long serialVersionUID = 1L; // // @Id() // @GeneratedValue(strategy = GenerationType.IDENTITY) // @Column(name = "id") // private Long id; // // @Column(name = "username") // private String username; // // @Column(name = "password") // private String password; // // @Column(name = "name") // private String name; // // @Column(name = "email") // private String email; // // @Column(name = "role") // private String role; // // @Column(name = "created_date") // @CreatedDate // private LocalDateTime createdDate; // // public String getName() { // if (this.name == null || this.name.trim().length() == 0) { // return this.username; // } // return name; // } // // @Override // public Collection<? extends GrantedAuthority> getAuthorities() { // return Arrays.asList(new SimpleGrantedAuthority("ROLE_" + this.role)); // } // // @Override // public String getPassword() { // return this.password; // } // // @Override // public String getUsername() { // return this.username; // } // // @Override // public boolean isAccountNonExpired() { // return true; // } // // @Override // public boolean isAccountNonLocked() { // return true; // } // // @Override // public boolean isCredentialsNonExpired() { // return true; // } // // @Override // // public boolean isEnabled() { // return true; // } // // // } // // Path: src/main/java/com/hantsylabs/restexample/springmvc/repository/UserRepository.java // public interface UserRepository extends JpaRepository<User, Long>, // JpaSpecificationExecutor<User> { // // public User findByUsername(String username); // }
import com.hantsylabs.restexample.springmvc.domain.User; import com.hantsylabs.restexample.springmvc.repository.UserRepository; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.security.core.userdetails.UserDetails; import org.springframework.security.core.userdetails.UserDetailsService; import org.springframework.security.core.userdetails.UsernameNotFoundException; import org.springframework.stereotype.Component;
package com.hantsylabs.restexample.springmvc.security; @Component public class SimpleUserDetailsServiceImpl implements UserDetailsService { private static final Logger log = LoggerFactory.getLogger(SimpleUserDetailsServiceImpl.class); private UserRepository userRepository; public SimpleUserDetailsServiceImpl(UserRepository userRepository) { this.userRepository = userRepository; } @Override public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
// Path: src/main/java/com/hantsylabs/restexample/springmvc/domain/User.java // @Data // @Builder // @NoArgsConstructor // @AllArgsConstructor // @Entity // @Table(name = "users") // public class User implements UserDetails, Serializable { // // /** // * // */ // private static final long serialVersionUID = 1L; // // @Id() // @GeneratedValue(strategy = GenerationType.IDENTITY) // @Column(name = "id") // private Long id; // // @Column(name = "username") // private String username; // // @Column(name = "password") // private String password; // // @Column(name = "name") // private String name; // // @Column(name = "email") // private String email; // // @Column(name = "role") // private String role; // // @Column(name = "created_date") // @CreatedDate // private LocalDateTime createdDate; // // public String getName() { // if (this.name == null || this.name.trim().length() == 0) { // return this.username; // } // return name; // } // // @Override // public Collection<? extends GrantedAuthority> getAuthorities() { // return Arrays.asList(new SimpleGrantedAuthority("ROLE_" + this.role)); // } // // @Override // public String getPassword() { // return this.password; // } // // @Override // public String getUsername() { // return this.username; // } // // @Override // public boolean isAccountNonExpired() { // return true; // } // // @Override // public boolean isAccountNonLocked() { // return true; // } // // @Override // public boolean isCredentialsNonExpired() { // return true; // } // // @Override // // public boolean isEnabled() { // return true; // } // // // } // // Path: src/main/java/com/hantsylabs/restexample/springmvc/repository/UserRepository.java // public interface UserRepository extends JpaRepository<User, Long>, // JpaSpecificationExecutor<User> { // // public User findByUsername(String username); // } // Path: src/main/java/com/hantsylabs/restexample/springmvc/security/SimpleUserDetailsServiceImpl.java import com.hantsylabs.restexample.springmvc.domain.User; import com.hantsylabs.restexample.springmvc.repository.UserRepository; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.security.core.userdetails.UserDetails; import org.springframework.security.core.userdetails.UserDetailsService; import org.springframework.security.core.userdetails.UsernameNotFoundException; import org.springframework.stereotype.Component; package com.hantsylabs.restexample.springmvc.security; @Component public class SimpleUserDetailsServiceImpl implements UserDetailsService { private static final Logger log = LoggerFactory.getLogger(SimpleUserDetailsServiceImpl.class); private UserRepository userRepository; public SimpleUserDetailsServiceImpl(UserRepository userRepository) { this.userRepository = userRepository; } @Override public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
User user = userRepository.findByUsername(username);
hantsy/angularjs-springmvc-sample-boot
src/test/java/com/hantsylabs/restexample/springmvc/test/slice/SimpleDataJpaTest.java
// Path: src/main/java/com/hantsylabs/restexample/springmvc/repository/CommentRepository.java // public interface CommentRepository extends JpaRepository<Comment, Long> { // // public List<Comment> findByPost(Post post); // // public Page<Comment> findByPostId(Long id, Pageable page); // // } // // Path: src/main/java/com/hantsylabs/restexample/springmvc/repository/PostRepository.java // public interface PostRepository extends JpaRepository<Post, Long>,// // JpaSpecificationExecutor<Post>{ // // } // // Path: src/test/java/com/hantsylabs/restexample/springmvc/test/Fixtures.java // public class Fixtures { // // public static User createUser(String username, String password) { // return User.builder() // .username(username) // .password(password) // .name("test user") // .email("[email protected]") // .build(); // } // // public static UserForm createUserForm(String username, String password) { // return UserForm.builder() // .username(username) // .password(password) // .name("test user") // .email("[email protected]") // .build(); // } // // public static PasswordForm createPasswordForm(String oldPassword, String newPassword) { // return PasswordForm.builder() // .oldPassword(oldPassword) // .newPassword(newPassword) // .build(); // } // // public static Post createPost(Long id, String title, String content) { // return Post.builder() // .id(id) // .title(title) // .content(content) // .status(Post.Status.DRAFT) // .build(); // } // }
import com.hantsylabs.restexample.springmvc.repository.CommentRepository; import com.hantsylabs.restexample.springmvc.repository.PostRepository; import com.hantsylabs.restexample.springmvc.test.Fixtures; import javax.inject.Inject; import lombok.extern.slf4j.Slf4j; import static org.junit.Assert.assertEquals; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTest; import org.springframework.boot.test.autoconfigure.orm.jpa.TestEntityManager; import org.springframework.test.context.junit4.SpringRunner;
package com.hantsylabs.restexample.springmvc.test.slice; /** * * @author hantsy */ @RunWith(SpringRunner.class) @DataJpaTest() @Slf4j public class SimpleDataJpaTest { @Inject private TestEntityManager em; @Inject
// Path: src/main/java/com/hantsylabs/restexample/springmvc/repository/CommentRepository.java // public interface CommentRepository extends JpaRepository<Comment, Long> { // // public List<Comment> findByPost(Post post); // // public Page<Comment> findByPostId(Long id, Pageable page); // // } // // Path: src/main/java/com/hantsylabs/restexample/springmvc/repository/PostRepository.java // public interface PostRepository extends JpaRepository<Post, Long>,// // JpaSpecificationExecutor<Post>{ // // } // // Path: src/test/java/com/hantsylabs/restexample/springmvc/test/Fixtures.java // public class Fixtures { // // public static User createUser(String username, String password) { // return User.builder() // .username(username) // .password(password) // .name("test user") // .email("[email protected]") // .build(); // } // // public static UserForm createUserForm(String username, String password) { // return UserForm.builder() // .username(username) // .password(password) // .name("test user") // .email("[email protected]") // .build(); // } // // public static PasswordForm createPasswordForm(String oldPassword, String newPassword) { // return PasswordForm.builder() // .oldPassword(oldPassword) // .newPassword(newPassword) // .build(); // } // // public static Post createPost(Long id, String title, String content) { // return Post.builder() // .id(id) // .title(title) // .content(content) // .status(Post.Status.DRAFT) // .build(); // } // } // Path: src/test/java/com/hantsylabs/restexample/springmvc/test/slice/SimpleDataJpaTest.java import com.hantsylabs.restexample.springmvc.repository.CommentRepository; import com.hantsylabs.restexample.springmvc.repository.PostRepository; import com.hantsylabs.restexample.springmvc.test.Fixtures; import javax.inject.Inject; import lombok.extern.slf4j.Slf4j; import static org.junit.Assert.assertEquals; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTest; import org.springframework.boot.test.autoconfigure.orm.jpa.TestEntityManager; import org.springframework.test.context.junit4.SpringRunner; package com.hantsylabs.restexample.springmvc.test.slice; /** * * @author hantsy */ @RunWith(SpringRunner.class) @DataJpaTest() @Slf4j public class SimpleDataJpaTest { @Inject private TestEntityManager em; @Inject
private PostRepository posts;
hantsy/angularjs-springmvc-sample-boot
src/test/java/com/hantsylabs/restexample/springmvc/test/slice/SimpleDataJpaTest.java
// Path: src/main/java/com/hantsylabs/restexample/springmvc/repository/CommentRepository.java // public interface CommentRepository extends JpaRepository<Comment, Long> { // // public List<Comment> findByPost(Post post); // // public Page<Comment> findByPostId(Long id, Pageable page); // // } // // Path: src/main/java/com/hantsylabs/restexample/springmvc/repository/PostRepository.java // public interface PostRepository extends JpaRepository<Post, Long>,// // JpaSpecificationExecutor<Post>{ // // } // // Path: src/test/java/com/hantsylabs/restexample/springmvc/test/Fixtures.java // public class Fixtures { // // public static User createUser(String username, String password) { // return User.builder() // .username(username) // .password(password) // .name("test user") // .email("[email protected]") // .build(); // } // // public static UserForm createUserForm(String username, String password) { // return UserForm.builder() // .username(username) // .password(password) // .name("test user") // .email("[email protected]") // .build(); // } // // public static PasswordForm createPasswordForm(String oldPassword, String newPassword) { // return PasswordForm.builder() // .oldPassword(oldPassword) // .newPassword(newPassword) // .build(); // } // // public static Post createPost(Long id, String title, String content) { // return Post.builder() // .id(id) // .title(title) // .content(content) // .status(Post.Status.DRAFT) // .build(); // } // }
import com.hantsylabs.restexample.springmvc.repository.CommentRepository; import com.hantsylabs.restexample.springmvc.repository.PostRepository; import com.hantsylabs.restexample.springmvc.test.Fixtures; import javax.inject.Inject; import lombok.extern.slf4j.Slf4j; import static org.junit.Assert.assertEquals; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTest; import org.springframework.boot.test.autoconfigure.orm.jpa.TestEntityManager; import org.springframework.test.context.junit4.SpringRunner;
package com.hantsylabs.restexample.springmvc.test.slice; /** * * @author hantsy */ @RunWith(SpringRunner.class) @DataJpaTest() @Slf4j public class SimpleDataJpaTest { @Inject private TestEntityManager em; @Inject private PostRepository posts; @Inject
// Path: src/main/java/com/hantsylabs/restexample/springmvc/repository/CommentRepository.java // public interface CommentRepository extends JpaRepository<Comment, Long> { // // public List<Comment> findByPost(Post post); // // public Page<Comment> findByPostId(Long id, Pageable page); // // } // // Path: src/main/java/com/hantsylabs/restexample/springmvc/repository/PostRepository.java // public interface PostRepository extends JpaRepository<Post, Long>,// // JpaSpecificationExecutor<Post>{ // // } // // Path: src/test/java/com/hantsylabs/restexample/springmvc/test/Fixtures.java // public class Fixtures { // // public static User createUser(String username, String password) { // return User.builder() // .username(username) // .password(password) // .name("test user") // .email("[email protected]") // .build(); // } // // public static UserForm createUserForm(String username, String password) { // return UserForm.builder() // .username(username) // .password(password) // .name("test user") // .email("[email protected]") // .build(); // } // // public static PasswordForm createPasswordForm(String oldPassword, String newPassword) { // return PasswordForm.builder() // .oldPassword(oldPassword) // .newPassword(newPassword) // .build(); // } // // public static Post createPost(Long id, String title, String content) { // return Post.builder() // .id(id) // .title(title) // .content(content) // .status(Post.Status.DRAFT) // .build(); // } // } // Path: src/test/java/com/hantsylabs/restexample/springmvc/test/slice/SimpleDataJpaTest.java import com.hantsylabs.restexample.springmvc.repository.CommentRepository; import com.hantsylabs.restexample.springmvc.repository.PostRepository; import com.hantsylabs.restexample.springmvc.test.Fixtures; import javax.inject.Inject; import lombok.extern.slf4j.Slf4j; import static org.junit.Assert.assertEquals; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTest; import org.springframework.boot.test.autoconfigure.orm.jpa.TestEntityManager; import org.springframework.test.context.junit4.SpringRunner; package com.hantsylabs.restexample.springmvc.test.slice; /** * * @author hantsy */ @RunWith(SpringRunner.class) @DataJpaTest() @Slf4j public class SimpleDataJpaTest { @Inject private TestEntityManager em; @Inject private PostRepository posts; @Inject
private CommentRepository comments;
hantsy/angularjs-springmvc-sample-boot
src/test/java/com/hantsylabs/restexample/springmvc/test/slice/SimpleDataJpaTest.java
// Path: src/main/java/com/hantsylabs/restexample/springmvc/repository/CommentRepository.java // public interface CommentRepository extends JpaRepository<Comment, Long> { // // public List<Comment> findByPost(Post post); // // public Page<Comment> findByPostId(Long id, Pageable page); // // } // // Path: src/main/java/com/hantsylabs/restexample/springmvc/repository/PostRepository.java // public interface PostRepository extends JpaRepository<Post, Long>,// // JpaSpecificationExecutor<Post>{ // // } // // Path: src/test/java/com/hantsylabs/restexample/springmvc/test/Fixtures.java // public class Fixtures { // // public static User createUser(String username, String password) { // return User.builder() // .username(username) // .password(password) // .name("test user") // .email("[email protected]") // .build(); // } // // public static UserForm createUserForm(String username, String password) { // return UserForm.builder() // .username(username) // .password(password) // .name("test user") // .email("[email protected]") // .build(); // } // // public static PasswordForm createPasswordForm(String oldPassword, String newPassword) { // return PasswordForm.builder() // .oldPassword(oldPassword) // .newPassword(newPassword) // .build(); // } // // public static Post createPost(Long id, String title, String content) { // return Post.builder() // .id(id) // .title(title) // .content(content) // .status(Post.Status.DRAFT) // .build(); // } // }
import com.hantsylabs.restexample.springmvc.repository.CommentRepository; import com.hantsylabs.restexample.springmvc.repository.PostRepository; import com.hantsylabs.restexample.springmvc.test.Fixtures; import javax.inject.Inject; import lombok.extern.slf4j.Slf4j; import static org.junit.Assert.assertEquals; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTest; import org.springframework.boot.test.autoconfigure.orm.jpa.TestEntityManager; import org.springframework.test.context.junit4.SpringRunner;
package com.hantsylabs.restexample.springmvc.test.slice; /** * * @author hantsy */ @RunWith(SpringRunner.class) @DataJpaTest() @Slf4j public class SimpleDataJpaTest { @Inject private TestEntityManager em; @Inject private PostRepository posts; @Inject private CommentRepository comments; @Before public void setUp() { comments.deleteAllInBatch(); posts.deleteAllInBatch();
// Path: src/main/java/com/hantsylabs/restexample/springmvc/repository/CommentRepository.java // public interface CommentRepository extends JpaRepository<Comment, Long> { // // public List<Comment> findByPost(Post post); // // public Page<Comment> findByPostId(Long id, Pageable page); // // } // // Path: src/main/java/com/hantsylabs/restexample/springmvc/repository/PostRepository.java // public interface PostRepository extends JpaRepository<Post, Long>,// // JpaSpecificationExecutor<Post>{ // // } // // Path: src/test/java/com/hantsylabs/restexample/springmvc/test/Fixtures.java // public class Fixtures { // // public static User createUser(String username, String password) { // return User.builder() // .username(username) // .password(password) // .name("test user") // .email("[email protected]") // .build(); // } // // public static UserForm createUserForm(String username, String password) { // return UserForm.builder() // .username(username) // .password(password) // .name("test user") // .email("[email protected]") // .build(); // } // // public static PasswordForm createPasswordForm(String oldPassword, String newPassword) { // return PasswordForm.builder() // .oldPassword(oldPassword) // .newPassword(newPassword) // .build(); // } // // public static Post createPost(Long id, String title, String content) { // return Post.builder() // .id(id) // .title(title) // .content(content) // .status(Post.Status.DRAFT) // .build(); // } // } // Path: src/test/java/com/hantsylabs/restexample/springmvc/test/slice/SimpleDataJpaTest.java import com.hantsylabs.restexample.springmvc.repository.CommentRepository; import com.hantsylabs.restexample.springmvc.repository.PostRepository; import com.hantsylabs.restexample.springmvc.test.Fixtures; import javax.inject.Inject; import lombok.extern.slf4j.Slf4j; import static org.junit.Assert.assertEquals; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTest; import org.springframework.boot.test.autoconfigure.orm.jpa.TestEntityManager; import org.springframework.test.context.junit4.SpringRunner; package com.hantsylabs.restexample.springmvc.test.slice; /** * * @author hantsy */ @RunWith(SpringRunner.class) @DataJpaTest() @Slf4j public class SimpleDataJpaTest { @Inject private TestEntityManager em; @Inject private PostRepository posts; @Inject private CommentRepository comments; @Before public void setUp() { comments.deleteAllInBatch(); posts.deleteAllInBatch();
em.persist(Fixtures.createPost(null, "title", "content"));
hantsy/angularjs-springmvc-sample-boot
src/test/java/com/hantsylabs/restexample/springmvc/test/jbehave/steps/PostSteps.java
// Path: src/main/java/com/hantsylabs/restexample/springmvc/domain/Post.java // @Data // @Builder // @NoArgsConstructor // @AllArgsConstructor // @Entity // @Table(name = "posts") // public class Post implements Serializable { // // /** // * // */ // private static final long serialVersionUID = 1L; // // public enum Status { // // DRAFT, // PUBLISHED // } // // public Post(String title, String content) { // this.title = title; // this.content = content; // } // // @Id() // @GeneratedValue(strategy = GenerationType.IDENTITY) // @Column(name = "id") // private Long id; // // @Column(name = "title") // private String title; // // @Column(name = "content") // @Size(max = 2000) // private String content; // // @Column(name = "status") // @Enumerated // private Status status = Status.DRAFT; // // @ManyToOne // @JoinColumn(name = "created_by") // @CreatedBy // private User createdBy; // // @Column(name = "created_date") // @CreatedDate // private LocalDateTime createdDate; // // @ManyToOne // @JoinColumn(name = "last_modified_by") // @LastModifiedBy // private User lastModifiedBy; // // @Column(name = "last_modified_date") // @LastModifiedDate // private LocalDateTime lastModifiedDate; // // } // // Path: src/main/java/com/hantsylabs/restexample/springmvc/repository/PostRepository.java // public interface PostRepository extends JpaRepository<Post, Long>,// // JpaSpecificationExecutor<Post>{ // // }
import com.hantsylabs.restexample.springmvc.domain.Post; import com.hantsylabs.restexample.springmvc.repository.PostRepository; import org.jbehave.core.annotations.Given; import org.jbehave.core.annotations.Named; import org.jbehave.core.annotations.Then; import org.jbehave.core.annotations.When; import static org.junit.Assert.assertTrue; import org.springframework.boot.test.web.client.TestRestTemplate; import org.springframework.http.ResponseEntity;
package com.hantsylabs.restexample.springmvc.test.jbehave.steps; public class PostSteps { PostRepository postRepository; TestRestTemplate restTemplate; String baseUrl; public PostSteps(PostRepository postRepository, TestRestTemplate restTemplate, String baseUrl) { this.postRepository = postRepository; this.restTemplate = restTemplate; this.baseUrl = baseUrl; } ResponseEntity<String> reponseEntity; @Given("post title is $title and content is $content") public void savePost(@Named("title") String title, @Named("content") String content) {
// Path: src/main/java/com/hantsylabs/restexample/springmvc/domain/Post.java // @Data // @Builder // @NoArgsConstructor // @AllArgsConstructor // @Entity // @Table(name = "posts") // public class Post implements Serializable { // // /** // * // */ // private static final long serialVersionUID = 1L; // // public enum Status { // // DRAFT, // PUBLISHED // } // // public Post(String title, String content) { // this.title = title; // this.content = content; // } // // @Id() // @GeneratedValue(strategy = GenerationType.IDENTITY) // @Column(name = "id") // private Long id; // // @Column(name = "title") // private String title; // // @Column(name = "content") // @Size(max = 2000) // private String content; // // @Column(name = "status") // @Enumerated // private Status status = Status.DRAFT; // // @ManyToOne // @JoinColumn(name = "created_by") // @CreatedBy // private User createdBy; // // @Column(name = "created_date") // @CreatedDate // private LocalDateTime createdDate; // // @ManyToOne // @JoinColumn(name = "last_modified_by") // @LastModifiedBy // private User lastModifiedBy; // // @Column(name = "last_modified_date") // @LastModifiedDate // private LocalDateTime lastModifiedDate; // // } // // Path: src/main/java/com/hantsylabs/restexample/springmvc/repository/PostRepository.java // public interface PostRepository extends JpaRepository<Post, Long>,// // JpaSpecificationExecutor<Post>{ // // } // Path: src/test/java/com/hantsylabs/restexample/springmvc/test/jbehave/steps/PostSteps.java import com.hantsylabs.restexample.springmvc.domain.Post; import com.hantsylabs.restexample.springmvc.repository.PostRepository; import org.jbehave.core.annotations.Given; import org.jbehave.core.annotations.Named; import org.jbehave.core.annotations.Then; import org.jbehave.core.annotations.When; import static org.junit.Assert.assertTrue; import org.springframework.boot.test.web.client.TestRestTemplate; import org.springframework.http.ResponseEntity; package com.hantsylabs.restexample.springmvc.test.jbehave.steps; public class PostSteps { PostRepository postRepository; TestRestTemplate restTemplate; String baseUrl; public PostSteps(PostRepository postRepository, TestRestTemplate restTemplate, String baseUrl) { this.postRepository = postRepository; this.restTemplate = restTemplate; this.baseUrl = baseUrl; } ResponseEntity<String> reponseEntity; @Given("post title is $title and content is $content") public void savePost(@Named("title") String title, @Named("content") String content) {
postRepository.save(new Post(title, content));
hantsy/angularjs-springmvc-sample-boot
src/test/java/com/hantsylabs/restexample/springmvc/test/Fixtures.java
// Path: src/main/java/com/hantsylabs/restexample/springmvc/domain/Post.java // @Data // @Builder // @NoArgsConstructor // @AllArgsConstructor // @Entity // @Table(name = "posts") // public class Post implements Serializable { // // /** // * // */ // private static final long serialVersionUID = 1L; // // public enum Status { // // DRAFT, // PUBLISHED // } // // public Post(String title, String content) { // this.title = title; // this.content = content; // } // // @Id() // @GeneratedValue(strategy = GenerationType.IDENTITY) // @Column(name = "id") // private Long id; // // @Column(name = "title") // private String title; // // @Column(name = "content") // @Size(max = 2000) // private String content; // // @Column(name = "status") // @Enumerated // private Status status = Status.DRAFT; // // @ManyToOne // @JoinColumn(name = "created_by") // @CreatedBy // private User createdBy; // // @Column(name = "created_date") // @CreatedDate // private LocalDateTime createdDate; // // @ManyToOne // @JoinColumn(name = "last_modified_by") // @LastModifiedBy // private User lastModifiedBy; // // @Column(name = "last_modified_date") // @LastModifiedDate // private LocalDateTime lastModifiedDate; // // } // // Path: src/main/java/com/hantsylabs/restexample/springmvc/domain/User.java // @Data // @Builder // @NoArgsConstructor // @AllArgsConstructor // @Entity // @Table(name = "users") // public class User implements UserDetails, Serializable { // // /** // * // */ // private static final long serialVersionUID = 1L; // // @Id() // @GeneratedValue(strategy = GenerationType.IDENTITY) // @Column(name = "id") // private Long id; // // @Column(name = "username") // private String username; // // @Column(name = "password") // private String password; // // @Column(name = "name") // private String name; // // @Column(name = "email") // private String email; // // @Column(name = "role") // private String role; // // @Column(name = "created_date") // @CreatedDate // private LocalDateTime createdDate; // // public String getName() { // if (this.name == null || this.name.trim().length() == 0) { // return this.username; // } // return name; // } // // @Override // public Collection<? extends GrantedAuthority> getAuthorities() { // return Arrays.asList(new SimpleGrantedAuthority("ROLE_" + this.role)); // } // // @Override // public String getPassword() { // return this.password; // } // // @Override // public String getUsername() { // return this.username; // } // // @Override // public boolean isAccountNonExpired() { // return true; // } // // @Override // public boolean isAccountNonLocked() { // return true; // } // // @Override // public boolean isCredentialsNonExpired() { // return true; // } // // @Override // // public boolean isEnabled() { // return true; // } // // // } // // Path: src/main/java/com/hantsylabs/restexample/springmvc/model/PasswordForm.java // @Data // @Builder // @NoArgsConstructor // @AllArgsConstructor // public class PasswordForm implements Serializable { // // private static final long serialVersionUID = 1L; // // @NotNull // @NotEmpty // private String oldPassword; // // @NotNull // @NotEmpty // private String newPassword; // // public String getOldPassword() { // return oldPassword; // } // // } // // Path: src/main/java/com/hantsylabs/restexample/springmvc/model/UserForm.java // @Data // @Builder // @NoArgsConstructor // @AllArgsConstructor // public class UserForm implements Serializable { // // private static final long serialVersionUID = 1L; // // @NotNull // private String username; // // @NotNull // private String password; // // @NotNull // private String name; // // @NotNull // @Email // private String email; // // @NotNull // private String role; // }
import com.hantsylabs.restexample.springmvc.domain.Post; import com.hantsylabs.restexample.springmvc.domain.User; import com.hantsylabs.restexample.springmvc.model.PasswordForm; import com.hantsylabs.restexample.springmvc.model.UserForm;
package com.hantsylabs.restexample.springmvc.test; public class Fixtures { public static User createUser(String username, String password) { return User.builder() .username(username) .password(password) .name("test user") .email("[email protected]") .build(); }
// Path: src/main/java/com/hantsylabs/restexample/springmvc/domain/Post.java // @Data // @Builder // @NoArgsConstructor // @AllArgsConstructor // @Entity // @Table(name = "posts") // public class Post implements Serializable { // // /** // * // */ // private static final long serialVersionUID = 1L; // // public enum Status { // // DRAFT, // PUBLISHED // } // // public Post(String title, String content) { // this.title = title; // this.content = content; // } // // @Id() // @GeneratedValue(strategy = GenerationType.IDENTITY) // @Column(name = "id") // private Long id; // // @Column(name = "title") // private String title; // // @Column(name = "content") // @Size(max = 2000) // private String content; // // @Column(name = "status") // @Enumerated // private Status status = Status.DRAFT; // // @ManyToOne // @JoinColumn(name = "created_by") // @CreatedBy // private User createdBy; // // @Column(name = "created_date") // @CreatedDate // private LocalDateTime createdDate; // // @ManyToOne // @JoinColumn(name = "last_modified_by") // @LastModifiedBy // private User lastModifiedBy; // // @Column(name = "last_modified_date") // @LastModifiedDate // private LocalDateTime lastModifiedDate; // // } // // Path: src/main/java/com/hantsylabs/restexample/springmvc/domain/User.java // @Data // @Builder // @NoArgsConstructor // @AllArgsConstructor // @Entity // @Table(name = "users") // public class User implements UserDetails, Serializable { // // /** // * // */ // private static final long serialVersionUID = 1L; // // @Id() // @GeneratedValue(strategy = GenerationType.IDENTITY) // @Column(name = "id") // private Long id; // // @Column(name = "username") // private String username; // // @Column(name = "password") // private String password; // // @Column(name = "name") // private String name; // // @Column(name = "email") // private String email; // // @Column(name = "role") // private String role; // // @Column(name = "created_date") // @CreatedDate // private LocalDateTime createdDate; // // public String getName() { // if (this.name == null || this.name.trim().length() == 0) { // return this.username; // } // return name; // } // // @Override // public Collection<? extends GrantedAuthority> getAuthorities() { // return Arrays.asList(new SimpleGrantedAuthority("ROLE_" + this.role)); // } // // @Override // public String getPassword() { // return this.password; // } // // @Override // public String getUsername() { // return this.username; // } // // @Override // public boolean isAccountNonExpired() { // return true; // } // // @Override // public boolean isAccountNonLocked() { // return true; // } // // @Override // public boolean isCredentialsNonExpired() { // return true; // } // // @Override // // public boolean isEnabled() { // return true; // } // // // } // // Path: src/main/java/com/hantsylabs/restexample/springmvc/model/PasswordForm.java // @Data // @Builder // @NoArgsConstructor // @AllArgsConstructor // public class PasswordForm implements Serializable { // // private static final long serialVersionUID = 1L; // // @NotNull // @NotEmpty // private String oldPassword; // // @NotNull // @NotEmpty // private String newPassword; // // public String getOldPassword() { // return oldPassword; // } // // } // // Path: src/main/java/com/hantsylabs/restexample/springmvc/model/UserForm.java // @Data // @Builder // @NoArgsConstructor // @AllArgsConstructor // public class UserForm implements Serializable { // // private static final long serialVersionUID = 1L; // // @NotNull // private String username; // // @NotNull // private String password; // // @NotNull // private String name; // // @NotNull // @Email // private String email; // // @NotNull // private String role; // } // Path: src/test/java/com/hantsylabs/restexample/springmvc/test/Fixtures.java import com.hantsylabs.restexample.springmvc.domain.Post; import com.hantsylabs.restexample.springmvc.domain.User; import com.hantsylabs.restexample.springmvc.model.PasswordForm; import com.hantsylabs.restexample.springmvc.model.UserForm; package com.hantsylabs.restexample.springmvc.test; public class Fixtures { public static User createUser(String username, String password) { return User.builder() .username(username) .password(password) .name("test user") .email("[email protected]") .build(); }
public static UserForm createUserForm(String username, String password) {
hantsy/angularjs-springmvc-sample-boot
src/test/java/com/hantsylabs/restexample/springmvc/test/Fixtures.java
// Path: src/main/java/com/hantsylabs/restexample/springmvc/domain/Post.java // @Data // @Builder // @NoArgsConstructor // @AllArgsConstructor // @Entity // @Table(name = "posts") // public class Post implements Serializable { // // /** // * // */ // private static final long serialVersionUID = 1L; // // public enum Status { // // DRAFT, // PUBLISHED // } // // public Post(String title, String content) { // this.title = title; // this.content = content; // } // // @Id() // @GeneratedValue(strategy = GenerationType.IDENTITY) // @Column(name = "id") // private Long id; // // @Column(name = "title") // private String title; // // @Column(name = "content") // @Size(max = 2000) // private String content; // // @Column(name = "status") // @Enumerated // private Status status = Status.DRAFT; // // @ManyToOne // @JoinColumn(name = "created_by") // @CreatedBy // private User createdBy; // // @Column(name = "created_date") // @CreatedDate // private LocalDateTime createdDate; // // @ManyToOne // @JoinColumn(name = "last_modified_by") // @LastModifiedBy // private User lastModifiedBy; // // @Column(name = "last_modified_date") // @LastModifiedDate // private LocalDateTime lastModifiedDate; // // } // // Path: src/main/java/com/hantsylabs/restexample/springmvc/domain/User.java // @Data // @Builder // @NoArgsConstructor // @AllArgsConstructor // @Entity // @Table(name = "users") // public class User implements UserDetails, Serializable { // // /** // * // */ // private static final long serialVersionUID = 1L; // // @Id() // @GeneratedValue(strategy = GenerationType.IDENTITY) // @Column(name = "id") // private Long id; // // @Column(name = "username") // private String username; // // @Column(name = "password") // private String password; // // @Column(name = "name") // private String name; // // @Column(name = "email") // private String email; // // @Column(name = "role") // private String role; // // @Column(name = "created_date") // @CreatedDate // private LocalDateTime createdDate; // // public String getName() { // if (this.name == null || this.name.trim().length() == 0) { // return this.username; // } // return name; // } // // @Override // public Collection<? extends GrantedAuthority> getAuthorities() { // return Arrays.asList(new SimpleGrantedAuthority("ROLE_" + this.role)); // } // // @Override // public String getPassword() { // return this.password; // } // // @Override // public String getUsername() { // return this.username; // } // // @Override // public boolean isAccountNonExpired() { // return true; // } // // @Override // public boolean isAccountNonLocked() { // return true; // } // // @Override // public boolean isCredentialsNonExpired() { // return true; // } // // @Override // // public boolean isEnabled() { // return true; // } // // // } // // Path: src/main/java/com/hantsylabs/restexample/springmvc/model/PasswordForm.java // @Data // @Builder // @NoArgsConstructor // @AllArgsConstructor // public class PasswordForm implements Serializable { // // private static final long serialVersionUID = 1L; // // @NotNull // @NotEmpty // private String oldPassword; // // @NotNull // @NotEmpty // private String newPassword; // // public String getOldPassword() { // return oldPassword; // } // // } // // Path: src/main/java/com/hantsylabs/restexample/springmvc/model/UserForm.java // @Data // @Builder // @NoArgsConstructor // @AllArgsConstructor // public class UserForm implements Serializable { // // private static final long serialVersionUID = 1L; // // @NotNull // private String username; // // @NotNull // private String password; // // @NotNull // private String name; // // @NotNull // @Email // private String email; // // @NotNull // private String role; // }
import com.hantsylabs.restexample.springmvc.domain.Post; import com.hantsylabs.restexample.springmvc.domain.User; import com.hantsylabs.restexample.springmvc.model.PasswordForm; import com.hantsylabs.restexample.springmvc.model.UserForm;
package com.hantsylabs.restexample.springmvc.test; public class Fixtures { public static User createUser(String username, String password) { return User.builder() .username(username) .password(password) .name("test user") .email("[email protected]") .build(); } public static UserForm createUserForm(String username, String password) { return UserForm.builder() .username(username) .password(password) .name("test user") .email("[email protected]") .build(); }
// Path: src/main/java/com/hantsylabs/restexample/springmvc/domain/Post.java // @Data // @Builder // @NoArgsConstructor // @AllArgsConstructor // @Entity // @Table(name = "posts") // public class Post implements Serializable { // // /** // * // */ // private static final long serialVersionUID = 1L; // // public enum Status { // // DRAFT, // PUBLISHED // } // // public Post(String title, String content) { // this.title = title; // this.content = content; // } // // @Id() // @GeneratedValue(strategy = GenerationType.IDENTITY) // @Column(name = "id") // private Long id; // // @Column(name = "title") // private String title; // // @Column(name = "content") // @Size(max = 2000) // private String content; // // @Column(name = "status") // @Enumerated // private Status status = Status.DRAFT; // // @ManyToOne // @JoinColumn(name = "created_by") // @CreatedBy // private User createdBy; // // @Column(name = "created_date") // @CreatedDate // private LocalDateTime createdDate; // // @ManyToOne // @JoinColumn(name = "last_modified_by") // @LastModifiedBy // private User lastModifiedBy; // // @Column(name = "last_modified_date") // @LastModifiedDate // private LocalDateTime lastModifiedDate; // // } // // Path: src/main/java/com/hantsylabs/restexample/springmvc/domain/User.java // @Data // @Builder // @NoArgsConstructor // @AllArgsConstructor // @Entity // @Table(name = "users") // public class User implements UserDetails, Serializable { // // /** // * // */ // private static final long serialVersionUID = 1L; // // @Id() // @GeneratedValue(strategy = GenerationType.IDENTITY) // @Column(name = "id") // private Long id; // // @Column(name = "username") // private String username; // // @Column(name = "password") // private String password; // // @Column(name = "name") // private String name; // // @Column(name = "email") // private String email; // // @Column(name = "role") // private String role; // // @Column(name = "created_date") // @CreatedDate // private LocalDateTime createdDate; // // public String getName() { // if (this.name == null || this.name.trim().length() == 0) { // return this.username; // } // return name; // } // // @Override // public Collection<? extends GrantedAuthority> getAuthorities() { // return Arrays.asList(new SimpleGrantedAuthority("ROLE_" + this.role)); // } // // @Override // public String getPassword() { // return this.password; // } // // @Override // public String getUsername() { // return this.username; // } // // @Override // public boolean isAccountNonExpired() { // return true; // } // // @Override // public boolean isAccountNonLocked() { // return true; // } // // @Override // public boolean isCredentialsNonExpired() { // return true; // } // // @Override // // public boolean isEnabled() { // return true; // } // // // } // // Path: src/main/java/com/hantsylabs/restexample/springmvc/model/PasswordForm.java // @Data // @Builder // @NoArgsConstructor // @AllArgsConstructor // public class PasswordForm implements Serializable { // // private static final long serialVersionUID = 1L; // // @NotNull // @NotEmpty // private String oldPassword; // // @NotNull // @NotEmpty // private String newPassword; // // public String getOldPassword() { // return oldPassword; // } // // } // // Path: src/main/java/com/hantsylabs/restexample/springmvc/model/UserForm.java // @Data // @Builder // @NoArgsConstructor // @AllArgsConstructor // public class UserForm implements Serializable { // // private static final long serialVersionUID = 1L; // // @NotNull // private String username; // // @NotNull // private String password; // // @NotNull // private String name; // // @NotNull // @Email // private String email; // // @NotNull // private String role; // } // Path: src/test/java/com/hantsylabs/restexample/springmvc/test/Fixtures.java import com.hantsylabs.restexample.springmvc.domain.Post; import com.hantsylabs.restexample.springmvc.domain.User; import com.hantsylabs.restexample.springmvc.model.PasswordForm; import com.hantsylabs.restexample.springmvc.model.UserForm; package com.hantsylabs.restexample.springmvc.test; public class Fixtures { public static User createUser(String username, String password) { return User.builder() .username(username) .password(password) .name("test user") .email("[email protected]") .build(); } public static UserForm createUserForm(String username, String password) { return UserForm.builder() .username(username) .password(password) .name("test user") .email("[email protected]") .build(); }
public static PasswordForm createPasswordForm(String oldPassword, String newPassword) {
hantsy/angularjs-springmvc-sample-boot
src/test/java/com/hantsylabs/restexample/springmvc/test/Fixtures.java
// Path: src/main/java/com/hantsylabs/restexample/springmvc/domain/Post.java // @Data // @Builder // @NoArgsConstructor // @AllArgsConstructor // @Entity // @Table(name = "posts") // public class Post implements Serializable { // // /** // * // */ // private static final long serialVersionUID = 1L; // // public enum Status { // // DRAFT, // PUBLISHED // } // // public Post(String title, String content) { // this.title = title; // this.content = content; // } // // @Id() // @GeneratedValue(strategy = GenerationType.IDENTITY) // @Column(name = "id") // private Long id; // // @Column(name = "title") // private String title; // // @Column(name = "content") // @Size(max = 2000) // private String content; // // @Column(name = "status") // @Enumerated // private Status status = Status.DRAFT; // // @ManyToOne // @JoinColumn(name = "created_by") // @CreatedBy // private User createdBy; // // @Column(name = "created_date") // @CreatedDate // private LocalDateTime createdDate; // // @ManyToOne // @JoinColumn(name = "last_modified_by") // @LastModifiedBy // private User lastModifiedBy; // // @Column(name = "last_modified_date") // @LastModifiedDate // private LocalDateTime lastModifiedDate; // // } // // Path: src/main/java/com/hantsylabs/restexample/springmvc/domain/User.java // @Data // @Builder // @NoArgsConstructor // @AllArgsConstructor // @Entity // @Table(name = "users") // public class User implements UserDetails, Serializable { // // /** // * // */ // private static final long serialVersionUID = 1L; // // @Id() // @GeneratedValue(strategy = GenerationType.IDENTITY) // @Column(name = "id") // private Long id; // // @Column(name = "username") // private String username; // // @Column(name = "password") // private String password; // // @Column(name = "name") // private String name; // // @Column(name = "email") // private String email; // // @Column(name = "role") // private String role; // // @Column(name = "created_date") // @CreatedDate // private LocalDateTime createdDate; // // public String getName() { // if (this.name == null || this.name.trim().length() == 0) { // return this.username; // } // return name; // } // // @Override // public Collection<? extends GrantedAuthority> getAuthorities() { // return Arrays.asList(new SimpleGrantedAuthority("ROLE_" + this.role)); // } // // @Override // public String getPassword() { // return this.password; // } // // @Override // public String getUsername() { // return this.username; // } // // @Override // public boolean isAccountNonExpired() { // return true; // } // // @Override // public boolean isAccountNonLocked() { // return true; // } // // @Override // public boolean isCredentialsNonExpired() { // return true; // } // // @Override // // public boolean isEnabled() { // return true; // } // // // } // // Path: src/main/java/com/hantsylabs/restexample/springmvc/model/PasswordForm.java // @Data // @Builder // @NoArgsConstructor // @AllArgsConstructor // public class PasswordForm implements Serializable { // // private static final long serialVersionUID = 1L; // // @NotNull // @NotEmpty // private String oldPassword; // // @NotNull // @NotEmpty // private String newPassword; // // public String getOldPassword() { // return oldPassword; // } // // } // // Path: src/main/java/com/hantsylabs/restexample/springmvc/model/UserForm.java // @Data // @Builder // @NoArgsConstructor // @AllArgsConstructor // public class UserForm implements Serializable { // // private static final long serialVersionUID = 1L; // // @NotNull // private String username; // // @NotNull // private String password; // // @NotNull // private String name; // // @NotNull // @Email // private String email; // // @NotNull // private String role; // }
import com.hantsylabs.restexample.springmvc.domain.Post; import com.hantsylabs.restexample.springmvc.domain.User; import com.hantsylabs.restexample.springmvc.model.PasswordForm; import com.hantsylabs.restexample.springmvc.model.UserForm;
package com.hantsylabs.restexample.springmvc.test; public class Fixtures { public static User createUser(String username, String password) { return User.builder() .username(username) .password(password) .name("test user") .email("[email protected]") .build(); } public static UserForm createUserForm(String username, String password) { return UserForm.builder() .username(username) .password(password) .name("test user") .email("[email protected]") .build(); } public static PasswordForm createPasswordForm(String oldPassword, String newPassword) { return PasswordForm.builder() .oldPassword(oldPassword) .newPassword(newPassword) .build(); }
// Path: src/main/java/com/hantsylabs/restexample/springmvc/domain/Post.java // @Data // @Builder // @NoArgsConstructor // @AllArgsConstructor // @Entity // @Table(name = "posts") // public class Post implements Serializable { // // /** // * // */ // private static final long serialVersionUID = 1L; // // public enum Status { // // DRAFT, // PUBLISHED // } // // public Post(String title, String content) { // this.title = title; // this.content = content; // } // // @Id() // @GeneratedValue(strategy = GenerationType.IDENTITY) // @Column(name = "id") // private Long id; // // @Column(name = "title") // private String title; // // @Column(name = "content") // @Size(max = 2000) // private String content; // // @Column(name = "status") // @Enumerated // private Status status = Status.DRAFT; // // @ManyToOne // @JoinColumn(name = "created_by") // @CreatedBy // private User createdBy; // // @Column(name = "created_date") // @CreatedDate // private LocalDateTime createdDate; // // @ManyToOne // @JoinColumn(name = "last_modified_by") // @LastModifiedBy // private User lastModifiedBy; // // @Column(name = "last_modified_date") // @LastModifiedDate // private LocalDateTime lastModifiedDate; // // } // // Path: src/main/java/com/hantsylabs/restexample/springmvc/domain/User.java // @Data // @Builder // @NoArgsConstructor // @AllArgsConstructor // @Entity // @Table(name = "users") // public class User implements UserDetails, Serializable { // // /** // * // */ // private static final long serialVersionUID = 1L; // // @Id() // @GeneratedValue(strategy = GenerationType.IDENTITY) // @Column(name = "id") // private Long id; // // @Column(name = "username") // private String username; // // @Column(name = "password") // private String password; // // @Column(name = "name") // private String name; // // @Column(name = "email") // private String email; // // @Column(name = "role") // private String role; // // @Column(name = "created_date") // @CreatedDate // private LocalDateTime createdDate; // // public String getName() { // if (this.name == null || this.name.trim().length() == 0) { // return this.username; // } // return name; // } // // @Override // public Collection<? extends GrantedAuthority> getAuthorities() { // return Arrays.asList(new SimpleGrantedAuthority("ROLE_" + this.role)); // } // // @Override // public String getPassword() { // return this.password; // } // // @Override // public String getUsername() { // return this.username; // } // // @Override // public boolean isAccountNonExpired() { // return true; // } // // @Override // public boolean isAccountNonLocked() { // return true; // } // // @Override // public boolean isCredentialsNonExpired() { // return true; // } // // @Override // // public boolean isEnabled() { // return true; // } // // // } // // Path: src/main/java/com/hantsylabs/restexample/springmvc/model/PasswordForm.java // @Data // @Builder // @NoArgsConstructor // @AllArgsConstructor // public class PasswordForm implements Serializable { // // private static final long serialVersionUID = 1L; // // @NotNull // @NotEmpty // private String oldPassword; // // @NotNull // @NotEmpty // private String newPassword; // // public String getOldPassword() { // return oldPassword; // } // // } // // Path: src/main/java/com/hantsylabs/restexample/springmvc/model/UserForm.java // @Data // @Builder // @NoArgsConstructor // @AllArgsConstructor // public class UserForm implements Serializable { // // private static final long serialVersionUID = 1L; // // @NotNull // private String username; // // @NotNull // private String password; // // @NotNull // private String name; // // @NotNull // @Email // private String email; // // @NotNull // private String role; // } // Path: src/test/java/com/hantsylabs/restexample/springmvc/test/Fixtures.java import com.hantsylabs.restexample.springmvc.domain.Post; import com.hantsylabs.restexample.springmvc.domain.User; import com.hantsylabs.restexample.springmvc.model.PasswordForm; import com.hantsylabs.restexample.springmvc.model.UserForm; package com.hantsylabs.restexample.springmvc.test; public class Fixtures { public static User createUser(String username, String password) { return User.builder() .username(username) .password(password) .name("test user") .email("[email protected]") .build(); } public static UserForm createUserForm(String username, String password) { return UserForm.builder() .username(username) .password(password) .name("test user") .email("[email protected]") .build(); } public static PasswordForm createPasswordForm(String oldPassword, String newPassword) { return PasswordForm.builder() .oldPassword(oldPassword) .newPassword(newPassword) .build(); }
public static Post createPost(Long id, String title, String content) {
google/java-monitoring-client-library
metrics/src/main/java/com/google/monitoring/metrics/ImmutableDistribution.java
// Path: metrics/src/main/java/com/google/monitoring/metrics/MetricsUtils.java // static void checkDouble(double value) { // checkArgument( // !Double.isInfinite(value) && !Double.isNaN(value) && !NEGATIVE_ZERO.equals(value), // "value must be finite, not NaN, and not -0.0"); // }
import static com.google.common.base.Preconditions.checkArgument; import static com.google.monitoring.metrics.MetricsUtils.checkDouble; import com.google.auto.value.AutoValue; import com.google.common.annotations.VisibleForTesting; import com.google.common.collect.ImmutableRangeMap; import javax.annotation.concurrent.ThreadSafe;
// Copyright 2017 Google LLC. All Rights Reserved. // // 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.monitoring.metrics; /** * An immutable {@link Distribution}. Instances of this class can used to create {@link MetricPoint} * instances, and should be used when exporting values to a {@link MetricWriter}. * * @see MutableDistribution */ @ThreadSafe @AutoValue public abstract class ImmutableDistribution implements Distribution { public static ImmutableDistribution copyOf(Distribution distribution) { return new AutoValue_ImmutableDistribution( distribution.mean(), distribution.sumOfSquaredDeviation(), distribution.count(), distribution.intervalCounts(), distribution.distributionFitter()); } @VisibleForTesting static ImmutableDistribution create( double mean, double sumOfSquaredDeviation, long count, ImmutableRangeMap<Double, Long> intervalCounts, DistributionFitter distributionFitter) {
// Path: metrics/src/main/java/com/google/monitoring/metrics/MetricsUtils.java // static void checkDouble(double value) { // checkArgument( // !Double.isInfinite(value) && !Double.isNaN(value) && !NEGATIVE_ZERO.equals(value), // "value must be finite, not NaN, and not -0.0"); // } // Path: metrics/src/main/java/com/google/monitoring/metrics/ImmutableDistribution.java import static com.google.common.base.Preconditions.checkArgument; import static com.google.monitoring.metrics.MetricsUtils.checkDouble; import com.google.auto.value.AutoValue; import com.google.common.annotations.VisibleForTesting; import com.google.common.collect.ImmutableRangeMap; import javax.annotation.concurrent.ThreadSafe; // Copyright 2017 Google LLC. All Rights Reserved. // // 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.monitoring.metrics; /** * An immutable {@link Distribution}. Instances of this class can used to create {@link MetricPoint} * instances, and should be used when exporting values to a {@link MetricWriter}. * * @see MutableDistribution */ @ThreadSafe @AutoValue public abstract class ImmutableDistribution implements Distribution { public static ImmutableDistribution copyOf(Distribution distribution) { return new AutoValue_ImmutableDistribution( distribution.mean(), distribution.sumOfSquaredDeviation(), distribution.count(), distribution.intervalCounts(), distribution.distributionFitter()); } @VisibleForTesting static ImmutableDistribution create( double mean, double sumOfSquaredDeviation, long count, ImmutableRangeMap<Double, Long> intervalCounts, DistributionFitter distributionFitter) {
checkDouble(mean);
google/java-monitoring-client-library
metrics/src/main/java/com/google/monitoring/metrics/ExponentialFitter.java
// Path: metrics/src/main/java/com/google/monitoring/metrics/MetricsUtils.java // static void checkDouble(double value) { // checkArgument( // !Double.isInfinite(value) && !Double.isNaN(value) && !NEGATIVE_ZERO.equals(value), // "value must be finite, not NaN, and not -0.0"); // }
import static com.google.common.base.Preconditions.checkArgument; import static com.google.monitoring.metrics.MetricsUtils.checkDouble; import com.google.auto.value.AutoValue; import com.google.common.collect.ImmutableSortedSet;
// Copyright 2017 Google LLC. All Rights Reserved. // // 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.monitoring.metrics; /** * Models a {@link DistributionFitter} with intervals of exponentially increasing size. * * <p>The interval boundaries are defined by {@code scale * Math.pow(base, i)} for {@code i} in * {@code [0, numFiniteIntervals]}. * * <p>For example, an {@link ExponentialFitter} with {@code numFiniteIntervals=3, base=4.0, * scale=1.5} represents a histogram with intervals {@code (-inf, 1.5), [1.5, 6), [6, 24), [24, 96), * [96, +inf)}. */ @AutoValue public abstract class ExponentialFitter implements DistributionFitter { /** * Create a new {@link ExponentialFitter}. * * @param numFiniteIntervals the number of intervals, excluding the underflow and overflow * intervals * @param base the base of the exponent * @param scale a multiplicative factor for the exponential function * @throws IllegalArgumentException if {@code numFiniteIntervals <= 0}, {@code width <= 0} or * {@code base <= 1} */ public static ExponentialFitter create(int numFiniteIntervals, double base, double scale) { checkArgument(numFiniteIntervals > 0, "numFiniteIntervals must be greater than 0"); checkArgument(scale != 0, "scale must not be 0"); checkArgument(base > 1, "base must be greater than 1");
// Path: metrics/src/main/java/com/google/monitoring/metrics/MetricsUtils.java // static void checkDouble(double value) { // checkArgument( // !Double.isInfinite(value) && !Double.isNaN(value) && !NEGATIVE_ZERO.equals(value), // "value must be finite, not NaN, and not -0.0"); // } // Path: metrics/src/main/java/com/google/monitoring/metrics/ExponentialFitter.java import static com.google.common.base.Preconditions.checkArgument; import static com.google.monitoring.metrics.MetricsUtils.checkDouble; import com.google.auto.value.AutoValue; import com.google.common.collect.ImmutableSortedSet; // Copyright 2017 Google LLC. All Rights Reserved. // // 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.monitoring.metrics; /** * Models a {@link DistributionFitter} with intervals of exponentially increasing size. * * <p>The interval boundaries are defined by {@code scale * Math.pow(base, i)} for {@code i} in * {@code [0, numFiniteIntervals]}. * * <p>For example, an {@link ExponentialFitter} with {@code numFiniteIntervals=3, base=4.0, * scale=1.5} represents a histogram with intervals {@code (-inf, 1.5), [1.5, 6), [6, 24), [24, 96), * [96, +inf)}. */ @AutoValue public abstract class ExponentialFitter implements DistributionFitter { /** * Create a new {@link ExponentialFitter}. * * @param numFiniteIntervals the number of intervals, excluding the underflow and overflow * intervals * @param base the base of the exponent * @param scale a multiplicative factor for the exponential function * @throws IllegalArgumentException if {@code numFiniteIntervals <= 0}, {@code width <= 0} or * {@code base <= 1} */ public static ExponentialFitter create(int numFiniteIntervals, double base, double scale) { checkArgument(numFiniteIntervals > 0, "numFiniteIntervals must be greater than 0"); checkArgument(scale != 0, "scale must not be 0"); checkArgument(base > 1, "base must be greater than 1");
checkDouble(base);
google/java-monitoring-client-library
contrib/src/main/java/com/google/monitoring/metrics/contrib/LongMetricSubject.java
// Path: metrics/src/main/java/com/google/monitoring/metrics/Metric.java // public interface Metric<V> { // // /** // * Returns the latest {@link MetricPoint} instances for every label-value combination tracked for // * this metric. // */ // ImmutableList<MetricPoint<V>> getTimestampedValues(); // // /** Returns the count of values being stored with this metric. */ // int getCardinality(); // // /** Returns the schema of this metric. */ // MetricSchema getMetricSchema(); // // /** // * Returns the type for the value of this metric, which would otherwise be erased at compile-time. // * This is useful for implementors of {@link MetricWriter}. // */ // Class<V> getValueClass(); // } // // Path: metrics/src/main/java/com/google/monitoring/metrics/MetricPoint.java // @AutoValue // public abstract class MetricPoint<V> implements Comparable<MetricPoint<V>> { // // /** // * Returns a new {@link MetricPoint} representing a value at a specific {@link Instant}. // * // * <p>Callers should insure that the count of {@code labelValues} matches the count of labels for // * the given metric. // */ // @VisibleForTesting // public static <V> MetricPoint<V> create( // Metric<V> metric, ImmutableList<String> labelValues, Instant timestamp, V value) { // MetricsUtils.checkLabelValuesLength(metric, labelValues); // // return new AutoValue_MetricPoint<>( // metric, labelValues, Range.openClosed(timestamp, timestamp), value); // } // // /** // * Returns a new {@link MetricPoint} representing a value over an {@link Range} from {@code // * startTime} to {@code endTime}. // * // * <p>Callers should insure that the count of {@code labelValues} matches the count of labels for // * the given metric. // */ // @VisibleForTesting // public static <V> MetricPoint<V> create( // Metric<V> metric, // ImmutableList<String> labelValues, // Instant startTime, // Instant endTime, // V value) { // MetricsUtils.checkLabelValuesLength(metric, labelValues); // // return new AutoValue_MetricPoint<>( // metric, labelValues, Range.openClosed(startTime, endTime), value); // } // // public abstract Metric<V> metric(); // // public abstract ImmutableList<String> labelValues(); // // public abstract Range<Instant> interval(); // // public abstract V value(); // // @Override // public int compareTo(MetricPoint<V> other) { // int minLength = Math.min(this.labelValues().size(), other.labelValues().size()); // for (int index = 0; index < minLength; index++) { // int comparisonResult = // this.labelValues().get(index).compareTo(other.labelValues().get(index)); // if (comparisonResult != 0) { // return comparisonResult; // } // } // return Integer.compare(this.labelValues().size(), other.labelValues().size()); // } // }
import static com.google.common.truth.Truth.assertAbout; import com.google.common.truth.FailureMetadata; import com.google.common.truth.Subject; import com.google.monitoring.metrics.Metric; import com.google.monitoring.metrics.MetricPoint; import javax.annotation.Nullable;
// Copyright 2017 Google LLC. All Rights Reserved. // // 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.monitoring.metrics.contrib; /** * Truth subject for {@link Long} {@link Metric} instances. * * <p>For use with the Google <a href="https://google.github.io/truth/">Truth</a> framework. Usage: * * <pre> assertThat(myLongMetric) * .hasValueForLabels(5, "label1", "label2", "label3") * .and() * .hasAnyValueForLabels("label1", "label2", "label4") * .and() * .hasNoOtherValues(); * assertThat(myLongMetric) * .doesNotHaveAnyValueForLabels("label1", "label2"); * </pre> * * <p>The assertions treat a value of 0 as no value at all. This is not how the data is actually * stored; zero is a valid value for incrementable metrics, and they do in fact have a value of zero * after they are reset. But it's difficult to write assertions about expected metric data when any * number of zero values can also be present, so they are screened out for convenience. */ public final class LongMetricSubject extends AbstractMetricSubject<Long, LongMetricSubject> { /** Static shortcut method for {@link Long} metrics. */ public static LongMetricSubject assertThat(@Nullable Metric<Long> metric) { return assertAbout(LongMetricSubject::new).that(metric); } private LongMetricSubject(FailureMetadata metadata, Metric<Long> actual) { super(metadata, actual); } /** * Asserts that the metric has a given value for the specified label values. This is a convenience * method that takes a long instead of a Long, for ease of use. */ public And<LongMetricSubject> hasValueForLabels(long value, String... labels) { return hasValueForLabels(Long.valueOf(value), labels); } /** * Returns an indication to {@link AbstractMetricSubject#hasNoOtherValues} on whether a {@link * MetricPoint} has a non-zero value. */ @Override
// Path: metrics/src/main/java/com/google/monitoring/metrics/Metric.java // public interface Metric<V> { // // /** // * Returns the latest {@link MetricPoint} instances for every label-value combination tracked for // * this metric. // */ // ImmutableList<MetricPoint<V>> getTimestampedValues(); // // /** Returns the count of values being stored with this metric. */ // int getCardinality(); // // /** Returns the schema of this metric. */ // MetricSchema getMetricSchema(); // // /** // * Returns the type for the value of this metric, which would otherwise be erased at compile-time. // * This is useful for implementors of {@link MetricWriter}. // */ // Class<V> getValueClass(); // } // // Path: metrics/src/main/java/com/google/monitoring/metrics/MetricPoint.java // @AutoValue // public abstract class MetricPoint<V> implements Comparable<MetricPoint<V>> { // // /** // * Returns a new {@link MetricPoint} representing a value at a specific {@link Instant}. // * // * <p>Callers should insure that the count of {@code labelValues} matches the count of labels for // * the given metric. // */ // @VisibleForTesting // public static <V> MetricPoint<V> create( // Metric<V> metric, ImmutableList<String> labelValues, Instant timestamp, V value) { // MetricsUtils.checkLabelValuesLength(metric, labelValues); // // return new AutoValue_MetricPoint<>( // metric, labelValues, Range.openClosed(timestamp, timestamp), value); // } // // /** // * Returns a new {@link MetricPoint} representing a value over an {@link Range} from {@code // * startTime} to {@code endTime}. // * // * <p>Callers should insure that the count of {@code labelValues} matches the count of labels for // * the given metric. // */ // @VisibleForTesting // public static <V> MetricPoint<V> create( // Metric<V> metric, // ImmutableList<String> labelValues, // Instant startTime, // Instant endTime, // V value) { // MetricsUtils.checkLabelValuesLength(metric, labelValues); // // return new AutoValue_MetricPoint<>( // metric, labelValues, Range.openClosed(startTime, endTime), value); // } // // public abstract Metric<V> metric(); // // public abstract ImmutableList<String> labelValues(); // // public abstract Range<Instant> interval(); // // public abstract V value(); // // @Override // public int compareTo(MetricPoint<V> other) { // int minLength = Math.min(this.labelValues().size(), other.labelValues().size()); // for (int index = 0; index < minLength; index++) { // int comparisonResult = // this.labelValues().get(index).compareTo(other.labelValues().get(index)); // if (comparisonResult != 0) { // return comparisonResult; // } // } // return Integer.compare(this.labelValues().size(), other.labelValues().size()); // } // } // Path: contrib/src/main/java/com/google/monitoring/metrics/contrib/LongMetricSubject.java import static com.google.common.truth.Truth.assertAbout; import com.google.common.truth.FailureMetadata; import com.google.common.truth.Subject; import com.google.monitoring.metrics.Metric; import com.google.monitoring.metrics.MetricPoint; import javax.annotation.Nullable; // Copyright 2017 Google LLC. All Rights Reserved. // // 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.monitoring.metrics.contrib; /** * Truth subject for {@link Long} {@link Metric} instances. * * <p>For use with the Google <a href="https://google.github.io/truth/">Truth</a> framework. Usage: * * <pre> assertThat(myLongMetric) * .hasValueForLabels(5, "label1", "label2", "label3") * .and() * .hasAnyValueForLabels("label1", "label2", "label4") * .and() * .hasNoOtherValues(); * assertThat(myLongMetric) * .doesNotHaveAnyValueForLabels("label1", "label2"); * </pre> * * <p>The assertions treat a value of 0 as no value at all. This is not how the data is actually * stored; zero is a valid value for incrementable metrics, and they do in fact have a value of zero * after they are reset. But it's difficult to write assertions about expected metric data when any * number of zero values can also be present, so they are screened out for convenience. */ public final class LongMetricSubject extends AbstractMetricSubject<Long, LongMetricSubject> { /** Static shortcut method for {@link Long} metrics. */ public static LongMetricSubject assertThat(@Nullable Metric<Long> metric) { return assertAbout(LongMetricSubject::new).that(metric); } private LongMetricSubject(FailureMetadata metadata, Metric<Long> actual) { super(metadata, actual); } /** * Asserts that the metric has a given value for the specified label values. This is a convenience * method that takes a long instead of a Long, for ease of use. */ public And<LongMetricSubject> hasValueForLabels(long value, String... labels) { return hasValueForLabels(Long.valueOf(value), labels); } /** * Returns an indication to {@link AbstractMetricSubject#hasNoOtherValues} on whether a {@link * MetricPoint} has a non-zero value. */ @Override
protected boolean hasDefaultValue(MetricPoint<Long> metricPoint) {
google/java-monitoring-client-library
metrics/src/main/java/com/google/monitoring/metrics/AbstractMetric.java
// Path: metrics/src/main/java/com/google/monitoring/metrics/MetricSchema.java // public enum Kind { // CUMULATIVE, // GAUGE, // }
import com.google.common.base.MoreObjects; import com.google.common.collect.ImmutableSet; import com.google.monitoring.metrics.MetricSchema.Kind;
// Copyright 2017 Google LLC. All Rights Reserved. // // 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.monitoring.metrics; abstract class AbstractMetric<V> implements Metric<V> { private final Class<V> valueClass; private final MetricSchema metricSchema; AbstractMetric( String name, String description, String valueDisplayName,
// Path: metrics/src/main/java/com/google/monitoring/metrics/MetricSchema.java // public enum Kind { // CUMULATIVE, // GAUGE, // } // Path: metrics/src/main/java/com/google/monitoring/metrics/AbstractMetric.java import com.google.common.base.MoreObjects; import com.google.common.collect.ImmutableSet; import com.google.monitoring.metrics.MetricSchema.Kind; // Copyright 2017 Google LLC. All Rights Reserved. // // 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.monitoring.metrics; abstract class AbstractMetric<V> implements Metric<V> { private final Class<V> valueClass; private final MetricSchema metricSchema; AbstractMetric( String name, String description, String valueDisplayName,
Kind kind,
google/java-monitoring-client-library
metrics/src/main/java/com/google/monitoring/metrics/MutableDistribution.java
// Path: metrics/src/main/java/com/google/monitoring/metrics/MetricsUtils.java // static void checkDouble(double value) { // checkArgument( // !Double.isInfinite(value) && !Double.isNaN(value) && !NEGATIVE_ZERO.equals(value), // "value must be finite, not NaN, and not -0.0"); // }
import static com.google.common.base.Preconditions.checkArgument; import static com.google.common.base.Preconditions.checkNotNull; import static com.google.monitoring.metrics.MetricsUtils.checkDouble; import com.google.common.collect.ImmutableRangeMap; import com.google.common.collect.ImmutableSortedSet; import com.google.common.collect.Ordering; import com.google.common.collect.Range; import com.google.common.collect.TreeRangeMap; import com.google.common.primitives.Doubles; import java.util.Map; import javax.annotation.concurrent.NotThreadSafe;
// Copyright 2017 Google LLC. All Rights Reserved. // // 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.monitoring.metrics; /** * A mutable {@link Distribution}. Instances of this class <b>should not</b> be used to construct * {@link MetricPoint} instances as {@link MetricPoint} instances are supposed to represent * immutable values. * * @see ImmutableDistribution */ @NotThreadSafe public final class MutableDistribution implements Distribution { private final TreeRangeMap<Double, Long> intervalCounts; private final DistributionFitter distributionFitter; private double sumOfSquaredDeviation = 0.0; private double mean = 0.0; private long count = 0; /** Constructs an empty Distribution with the specified {@link DistributionFitter}. */ public MutableDistribution(DistributionFitter distributionFitter) { this.distributionFitter = checkNotNull(distributionFitter); ImmutableSortedSet<Double> boundaries = distributionFitter.boundaries(); checkArgument(boundaries.size() > 0); checkArgument(Ordering.natural().isOrdered(boundaries)); this.intervalCounts = TreeRangeMap.create(); double[] boundariesArray = Doubles.toArray(distributionFitter.boundaries()); // Add underflow and overflow intervals this.intervalCounts.put(Range.lessThan(boundariesArray[0]), 0L); this.intervalCounts.put(Range.atLeast(boundariesArray[boundariesArray.length - 1]), 0L); // Add finite intervals for (int i = 1; i < boundariesArray.length; i++) { this.intervalCounts.put(Range.closedOpen(boundariesArray[i - 1], boundariesArray[i]), 0L); } } public void add(double value) { add(value, 1L); } public void add(double value, long numSamples) { checkArgument(numSamples >= 0, "numSamples must be non-negative");
// Path: metrics/src/main/java/com/google/monitoring/metrics/MetricsUtils.java // static void checkDouble(double value) { // checkArgument( // !Double.isInfinite(value) && !Double.isNaN(value) && !NEGATIVE_ZERO.equals(value), // "value must be finite, not NaN, and not -0.0"); // } // Path: metrics/src/main/java/com/google/monitoring/metrics/MutableDistribution.java import static com.google.common.base.Preconditions.checkArgument; import static com.google.common.base.Preconditions.checkNotNull; import static com.google.monitoring.metrics.MetricsUtils.checkDouble; import com.google.common.collect.ImmutableRangeMap; import com.google.common.collect.ImmutableSortedSet; import com.google.common.collect.Ordering; import com.google.common.collect.Range; import com.google.common.collect.TreeRangeMap; import com.google.common.primitives.Doubles; import java.util.Map; import javax.annotation.concurrent.NotThreadSafe; // Copyright 2017 Google LLC. All Rights Reserved. // // 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.monitoring.metrics; /** * A mutable {@link Distribution}. Instances of this class <b>should not</b> be used to construct * {@link MetricPoint} instances as {@link MetricPoint} instances are supposed to represent * immutable values. * * @see ImmutableDistribution */ @NotThreadSafe public final class MutableDistribution implements Distribution { private final TreeRangeMap<Double, Long> intervalCounts; private final DistributionFitter distributionFitter; private double sumOfSquaredDeviation = 0.0; private double mean = 0.0; private long count = 0; /** Constructs an empty Distribution with the specified {@link DistributionFitter}. */ public MutableDistribution(DistributionFitter distributionFitter) { this.distributionFitter = checkNotNull(distributionFitter); ImmutableSortedSet<Double> boundaries = distributionFitter.boundaries(); checkArgument(boundaries.size() > 0); checkArgument(Ordering.natural().isOrdered(boundaries)); this.intervalCounts = TreeRangeMap.create(); double[] boundariesArray = Doubles.toArray(distributionFitter.boundaries()); // Add underflow and overflow intervals this.intervalCounts.put(Range.lessThan(boundariesArray[0]), 0L); this.intervalCounts.put(Range.atLeast(boundariesArray[boundariesArray.length - 1]), 0L); // Add finite intervals for (int i = 1; i < boundariesArray.length; i++) { this.intervalCounts.put(Range.closedOpen(boundariesArray[i - 1], boundariesArray[i]), 0L); } } public void add(double value) { add(value, 1L); } public void add(double value, long numSamples) { checkArgument(numSamples >= 0, "numSamples must be non-negative");
checkDouble(value);
google/java-monitoring-client-library
contrib/src/main/java/com/google/monitoring/metrics/contrib/AbstractMetricSubject.java
// Path: metrics/src/main/java/com/google/monitoring/metrics/Metric.java // public interface Metric<V> { // // /** // * Returns the latest {@link MetricPoint} instances for every label-value combination tracked for // * this metric. // */ // ImmutableList<MetricPoint<V>> getTimestampedValues(); // // /** Returns the count of values being stored with this metric. */ // int getCardinality(); // // /** Returns the schema of this metric. */ // MetricSchema getMetricSchema(); // // /** // * Returns the type for the value of this metric, which would otherwise be erased at compile-time. // * This is useful for implementors of {@link MetricWriter}. // */ // Class<V> getValueClass(); // } // // Path: metrics/src/main/java/com/google/monitoring/metrics/MetricPoint.java // @AutoValue // public abstract class MetricPoint<V> implements Comparable<MetricPoint<V>> { // // /** // * Returns a new {@link MetricPoint} representing a value at a specific {@link Instant}. // * // * <p>Callers should insure that the count of {@code labelValues} matches the count of labels for // * the given metric. // */ // @VisibleForTesting // public static <V> MetricPoint<V> create( // Metric<V> metric, ImmutableList<String> labelValues, Instant timestamp, V value) { // MetricsUtils.checkLabelValuesLength(metric, labelValues); // // return new AutoValue_MetricPoint<>( // metric, labelValues, Range.openClosed(timestamp, timestamp), value); // } // // /** // * Returns a new {@link MetricPoint} representing a value over an {@link Range} from {@code // * startTime} to {@code endTime}. // * // * <p>Callers should insure that the count of {@code labelValues} matches the count of labels for // * the given metric. // */ // @VisibleForTesting // public static <V> MetricPoint<V> create( // Metric<V> metric, // ImmutableList<String> labelValues, // Instant startTime, // Instant endTime, // V value) { // MetricsUtils.checkLabelValuesLength(metric, labelValues); // // return new AutoValue_MetricPoint<>( // metric, labelValues, Range.openClosed(startTime, endTime), value); // } // // public abstract Metric<V> metric(); // // public abstract ImmutableList<String> labelValues(); // // public abstract Range<Instant> interval(); // // public abstract V value(); // // @Override // public int compareTo(MetricPoint<V> other) { // int minLength = Math.min(this.labelValues().size(), other.labelValues().size()); // for (int index = 0; index < minLength; index++) { // int comparisonResult = // this.labelValues().get(index).compareTo(other.labelValues().get(index)); // if (comparisonResult != 0) { // return comparisonResult; // } // } // return Integer.compare(this.labelValues().size(), other.labelValues().size()); // } // }
import static com.google.common.base.Preconditions.checkNotNull; import com.google.common.base.Function; import com.google.common.base.Joiner; import com.google.common.collect.ImmutableList; import com.google.common.collect.Lists; import com.google.common.collect.Ordering; import com.google.common.truth.FailureMetadata; import com.google.common.truth.Subject; import com.google.monitoring.metrics.Metric; import com.google.monitoring.metrics.MetricPoint; import java.util.HashSet; import java.util.Set; import javax.annotation.Nullable;
// Copyright 2017 Google LLC. All Rights Reserved. // // 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.monitoring.metrics.contrib; /** * Base truth subject for asserting things about {@link Metric} instances. * * <p>For use with the Google <a href="https://google.github.io/truth/">Truth</a> framework. */ abstract class AbstractMetricSubject<T, S extends AbstractMetricSubject<T, S>> extends Subject<S, Metric<T>> { /** And chainer to allow fluent assertions. */ public static class And<S extends AbstractMetricSubject<?, S>> { private final S subject; And(S subject) { this.subject = subject; } public S and() { return subject; } } @SuppressWarnings("unchecked") And<S> andChainer() { return new And<>((S) this); } /** * List of label value tuples about which an assertion has been made so far. * * <p>Used to track what tuples have been seen, in order to support hasNoOtherValues() assertions. */ protected final Set<ImmutableList<String>> expectedNondefaultLabelTuples = new HashSet<>(); /** * Function to convert a metric point to a nice string representation for use in error messages. */
// Path: metrics/src/main/java/com/google/monitoring/metrics/Metric.java // public interface Metric<V> { // // /** // * Returns the latest {@link MetricPoint} instances for every label-value combination tracked for // * this metric. // */ // ImmutableList<MetricPoint<V>> getTimestampedValues(); // // /** Returns the count of values being stored with this metric. */ // int getCardinality(); // // /** Returns the schema of this metric. */ // MetricSchema getMetricSchema(); // // /** // * Returns the type for the value of this metric, which would otherwise be erased at compile-time. // * This is useful for implementors of {@link MetricWriter}. // */ // Class<V> getValueClass(); // } // // Path: metrics/src/main/java/com/google/monitoring/metrics/MetricPoint.java // @AutoValue // public abstract class MetricPoint<V> implements Comparable<MetricPoint<V>> { // // /** // * Returns a new {@link MetricPoint} representing a value at a specific {@link Instant}. // * // * <p>Callers should insure that the count of {@code labelValues} matches the count of labels for // * the given metric. // */ // @VisibleForTesting // public static <V> MetricPoint<V> create( // Metric<V> metric, ImmutableList<String> labelValues, Instant timestamp, V value) { // MetricsUtils.checkLabelValuesLength(metric, labelValues); // // return new AutoValue_MetricPoint<>( // metric, labelValues, Range.openClosed(timestamp, timestamp), value); // } // // /** // * Returns a new {@link MetricPoint} representing a value over an {@link Range} from {@code // * startTime} to {@code endTime}. // * // * <p>Callers should insure that the count of {@code labelValues} matches the count of labels for // * the given metric. // */ // @VisibleForTesting // public static <V> MetricPoint<V> create( // Metric<V> metric, // ImmutableList<String> labelValues, // Instant startTime, // Instant endTime, // V value) { // MetricsUtils.checkLabelValuesLength(metric, labelValues); // // return new AutoValue_MetricPoint<>( // metric, labelValues, Range.openClosed(startTime, endTime), value); // } // // public abstract Metric<V> metric(); // // public abstract ImmutableList<String> labelValues(); // // public abstract Range<Instant> interval(); // // public abstract V value(); // // @Override // public int compareTo(MetricPoint<V> other) { // int minLength = Math.min(this.labelValues().size(), other.labelValues().size()); // for (int index = 0; index < minLength; index++) { // int comparisonResult = // this.labelValues().get(index).compareTo(other.labelValues().get(index)); // if (comparisonResult != 0) { // return comparisonResult; // } // } // return Integer.compare(this.labelValues().size(), other.labelValues().size()); // } // } // Path: contrib/src/main/java/com/google/monitoring/metrics/contrib/AbstractMetricSubject.java import static com.google.common.base.Preconditions.checkNotNull; import com.google.common.base.Function; import com.google.common.base.Joiner; import com.google.common.collect.ImmutableList; import com.google.common.collect.Lists; import com.google.common.collect.Ordering; import com.google.common.truth.FailureMetadata; import com.google.common.truth.Subject; import com.google.monitoring.metrics.Metric; import com.google.monitoring.metrics.MetricPoint; import java.util.HashSet; import java.util.Set; import javax.annotation.Nullable; // Copyright 2017 Google LLC. All Rights Reserved. // // 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.monitoring.metrics.contrib; /** * Base truth subject for asserting things about {@link Metric} instances. * * <p>For use with the Google <a href="https://google.github.io/truth/">Truth</a> framework. */ abstract class AbstractMetricSubject<T, S extends AbstractMetricSubject<T, S>> extends Subject<S, Metric<T>> { /** And chainer to allow fluent assertions. */ public static class And<S extends AbstractMetricSubject<?, S>> { private final S subject; And(S subject) { this.subject = subject; } public S and() { return subject; } } @SuppressWarnings("unchecked") And<S> andChainer() { return new And<>((S) this); } /** * List of label value tuples about which an assertion has been made so far. * * <p>Used to track what tuples have been seen, in order to support hasNoOtherValues() assertions. */ protected final Set<ImmutableList<String>> expectedNondefaultLabelTuples = new HashSet<>(); /** * Function to convert a metric point to a nice string representation for use in error messages. */
protected final Function<MetricPoint<T>, String> metricPointConverter =
google/java-monitoring-client-library
metrics/src/main/java/com/google/monitoring/metrics/LinearFitter.java
// Path: metrics/src/main/java/com/google/monitoring/metrics/MetricsUtils.java // static void checkDouble(double value) { // checkArgument( // !Double.isInfinite(value) && !Double.isNaN(value) && !NEGATIVE_ZERO.equals(value), // "value must be finite, not NaN, and not -0.0"); // }
import static com.google.common.base.Preconditions.checkArgument; import static com.google.monitoring.metrics.MetricsUtils.checkDouble; import com.google.auto.value.AutoValue; import com.google.common.collect.ImmutableSortedSet;
// Copyright 2017 Google LLC. All Rights Reserved. // // 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.monitoring.metrics; /** * Models a {@link DistributionFitter} with equally sized intervals. * * <p>The interval boundaries are defined by {@code width * i + offset} for {@code i} in {@code [0, * numFiniteIntervals}. * * <p>For example, a {@link LinearFitter} with {@code numFiniteIntervals=2, width=10, offset=5} * represents a histogram with intervals {@code (-inf, 5), [5, 15), [15, 25), [25, +inf)}. */ @AutoValue public abstract class LinearFitter implements DistributionFitter { /** * Create a new {@link LinearFitter}. * * @param numFiniteIntervals the number of intervals, excluding the underflow and overflow * intervals * @param width the width of each interval * @param offset the start value of the first interval * @throws IllegalArgumentException if {@code numFiniteIntervals <= 0} or {@code width <= 0} */ public static LinearFitter create(int numFiniteIntervals, double width, double offset) { checkArgument(numFiniteIntervals > 0, "numFiniteIntervals must be greater than 0"); checkArgument(width > 0, "width must be greater than 0");
// Path: metrics/src/main/java/com/google/monitoring/metrics/MetricsUtils.java // static void checkDouble(double value) { // checkArgument( // !Double.isInfinite(value) && !Double.isNaN(value) && !NEGATIVE_ZERO.equals(value), // "value must be finite, not NaN, and not -0.0"); // } // Path: metrics/src/main/java/com/google/monitoring/metrics/LinearFitter.java import static com.google.common.base.Preconditions.checkArgument; import static com.google.monitoring.metrics.MetricsUtils.checkDouble; import com.google.auto.value.AutoValue; import com.google.common.collect.ImmutableSortedSet; // Copyright 2017 Google LLC. All Rights Reserved. // // 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.monitoring.metrics; /** * Models a {@link DistributionFitter} with equally sized intervals. * * <p>The interval boundaries are defined by {@code width * i + offset} for {@code i} in {@code [0, * numFiniteIntervals}. * * <p>For example, a {@link LinearFitter} with {@code numFiniteIntervals=2, width=10, offset=5} * represents a histogram with intervals {@code (-inf, 5), [5, 15), [15, 25), [25, +inf)}. */ @AutoValue public abstract class LinearFitter implements DistributionFitter { /** * Create a new {@link LinearFitter}. * * @param numFiniteIntervals the number of intervals, excluding the underflow and overflow * intervals * @param width the width of each interval * @param offset the start value of the first interval * @throws IllegalArgumentException if {@code numFiniteIntervals <= 0} or {@code width <= 0} */ public static LinearFitter create(int numFiniteIntervals, double width, double offset) { checkArgument(numFiniteIntervals > 0, "numFiniteIntervals must be greater than 0"); checkArgument(width > 0, "width must be greater than 0");
checkDouble(offset);
google/java-monitoring-client-library
metrics/src/main/java/com/google/monitoring/metrics/StoredMetric.java
// Path: metrics/src/main/java/com/google/monitoring/metrics/MetricSchema.java // public enum Kind { // CUMULATIVE, // GAUGE, // }
import com.google.common.annotations.VisibleForTesting; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableList.Builder; import com.google.common.collect.ImmutableSet; import com.google.monitoring.metrics.MetricSchema.Kind; import java.time.Instant; import java.util.Map.Entry; import java.util.concurrent.ConcurrentHashMap; import javax.annotation.concurrent.ThreadSafe;
// Copyright 2017 Google LLC. All Rights Reserved. // // 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.monitoring.metrics; /** * A metric which is stateful. * * <p>The values are stored and set over time. This metric is generally suitable for state * indicators, such as indicating that a server is in a RUNNING state or in a STOPPED state. * * <p>See {@link Counter} for a subclass which is suitable for stateful incremental values. * * <p>The {@link MetricPoint#interval()} of values of instances of this metric will always have a * start time equal to the end time, since the metric value represents a point-in-time snapshot with * no relationship to prior values. */ @ThreadSafe public class StoredMetric<V> extends AbstractMetric<V> implements SettableMetric<V> { private final ConcurrentHashMap<ImmutableList<String>, V> values = new ConcurrentHashMap<>(); StoredMetric( String name, String description, String valueDisplayName, ImmutableSet<LabelDescriptor> labels, Class<V> valueClass) {
// Path: metrics/src/main/java/com/google/monitoring/metrics/MetricSchema.java // public enum Kind { // CUMULATIVE, // GAUGE, // } // Path: metrics/src/main/java/com/google/monitoring/metrics/StoredMetric.java import com.google.common.annotations.VisibleForTesting; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableList.Builder; import com.google.common.collect.ImmutableSet; import com.google.monitoring.metrics.MetricSchema.Kind; import java.time.Instant; import java.util.Map.Entry; import java.util.concurrent.ConcurrentHashMap; import javax.annotation.concurrent.ThreadSafe; // Copyright 2017 Google LLC. All Rights Reserved. // // 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.monitoring.metrics; /** * A metric which is stateful. * * <p>The values are stored and set over time. This metric is generally suitable for state * indicators, such as indicating that a server is in a RUNNING state or in a STOPPED state. * * <p>See {@link Counter} for a subclass which is suitable for stateful incremental values. * * <p>The {@link MetricPoint#interval()} of values of instances of this metric will always have a * start time equal to the end time, since the metric value represents a point-in-time snapshot with * no relationship to prior values. */ @ThreadSafe public class StoredMetric<V> extends AbstractMetric<V> implements SettableMetric<V> { private final ConcurrentHashMap<ImmutableList<String>, V> values = new ConcurrentHashMap<>(); StoredMetric( String name, String description, String valueDisplayName, ImmutableSet<LabelDescriptor> labels, Class<V> valueClass) {
super(name, description, valueDisplayName, Kind.GAUGE, labels, valueClass);
google/java-monitoring-client-library
metrics/src/main/java/com/google/monitoring/metrics/EventMetric.java
// Path: metrics/src/main/java/com/google/monitoring/metrics/MetricsUtils.java // static final int DEFAULT_CONCURRENCY_LEVEL = 16; // // Path: metrics/src/main/java/com/google/monitoring/metrics/MetricsUtils.java // static <K, V> ConcurrentHashMap<K, V> newConcurrentHashMap(int concurrencyLevel) { // return new ConcurrentHashMap<>(HASHMAP_INITIAL_CAPACITY, HASHMAP_LOAD_FACTOR, concurrencyLevel); // } // // Path: metrics/src/main/java/com/google/monitoring/metrics/MetricSchema.java // public enum Kind { // CUMULATIVE, // GAUGE, // }
import static com.google.monitoring.metrics.MetricsUtils.DEFAULT_CONCURRENCY_LEVEL; import static com.google.monitoring.metrics.MetricsUtils.newConcurrentHashMap; import com.google.common.annotations.VisibleForTesting; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableSet; import com.google.common.collect.Ordering; import com.google.common.util.concurrent.Striped; import com.google.monitoring.metrics.MetricSchema.Kind; import java.time.Instant; import java.util.Map.Entry; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.locks.Lock;
// Copyright 2017 Google LLC. All Rights Reserved. // // 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.monitoring.metrics; /** * A metric which stores {@link Distribution} values. The values are stateful and meant to be * updated incrementally via the {@link EventMetric#record(double, String...)} method. * * <p>This metric class is generally suitable for recording aggregations of data about a * quantitative aspect of an event. For example, this metric would be suitable for recording the * latency distribution for a request over the network. * * <p>The {@link MutableDistribution} values tracked by this metric can be reset with {@link * EventMetric#reset()}. */ public class EventMetric extends AbstractMetric<Distribution> { /** * Default {@link DistributionFitter} suitable for latency measurements. * * <p>The finite range of this fitter is from 1 to 4^16 (4294967296). */ public static final DistributionFitter DEFAULT_FITTER = ExponentialFitter.create(16, 4.0, 1.0); private final ConcurrentHashMap<ImmutableList<String>, Instant> valueStartTimestamps =
// Path: metrics/src/main/java/com/google/monitoring/metrics/MetricsUtils.java // static final int DEFAULT_CONCURRENCY_LEVEL = 16; // // Path: metrics/src/main/java/com/google/monitoring/metrics/MetricsUtils.java // static <K, V> ConcurrentHashMap<K, V> newConcurrentHashMap(int concurrencyLevel) { // return new ConcurrentHashMap<>(HASHMAP_INITIAL_CAPACITY, HASHMAP_LOAD_FACTOR, concurrencyLevel); // } // // Path: metrics/src/main/java/com/google/monitoring/metrics/MetricSchema.java // public enum Kind { // CUMULATIVE, // GAUGE, // } // Path: metrics/src/main/java/com/google/monitoring/metrics/EventMetric.java import static com.google.monitoring.metrics.MetricsUtils.DEFAULT_CONCURRENCY_LEVEL; import static com.google.monitoring.metrics.MetricsUtils.newConcurrentHashMap; import com.google.common.annotations.VisibleForTesting; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableSet; import com.google.common.collect.Ordering; import com.google.common.util.concurrent.Striped; import com.google.monitoring.metrics.MetricSchema.Kind; import java.time.Instant; import java.util.Map.Entry; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.locks.Lock; // Copyright 2017 Google LLC. All Rights Reserved. // // 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.monitoring.metrics; /** * A metric which stores {@link Distribution} values. The values are stateful and meant to be * updated incrementally via the {@link EventMetric#record(double, String...)} method. * * <p>This metric class is generally suitable for recording aggregations of data about a * quantitative aspect of an event. For example, this metric would be suitable for recording the * latency distribution for a request over the network. * * <p>The {@link MutableDistribution} values tracked by this metric can be reset with {@link * EventMetric#reset()}. */ public class EventMetric extends AbstractMetric<Distribution> { /** * Default {@link DistributionFitter} suitable for latency measurements. * * <p>The finite range of this fitter is from 1 to 4^16 (4294967296). */ public static final DistributionFitter DEFAULT_FITTER = ExponentialFitter.create(16, 4.0, 1.0); private final ConcurrentHashMap<ImmutableList<String>, Instant> valueStartTimestamps =
newConcurrentHashMap(DEFAULT_CONCURRENCY_LEVEL);
google/java-monitoring-client-library
metrics/src/main/java/com/google/monitoring/metrics/EventMetric.java
// Path: metrics/src/main/java/com/google/monitoring/metrics/MetricsUtils.java // static final int DEFAULT_CONCURRENCY_LEVEL = 16; // // Path: metrics/src/main/java/com/google/monitoring/metrics/MetricsUtils.java // static <K, V> ConcurrentHashMap<K, V> newConcurrentHashMap(int concurrencyLevel) { // return new ConcurrentHashMap<>(HASHMAP_INITIAL_CAPACITY, HASHMAP_LOAD_FACTOR, concurrencyLevel); // } // // Path: metrics/src/main/java/com/google/monitoring/metrics/MetricSchema.java // public enum Kind { // CUMULATIVE, // GAUGE, // }
import static com.google.monitoring.metrics.MetricsUtils.DEFAULT_CONCURRENCY_LEVEL; import static com.google.monitoring.metrics.MetricsUtils.newConcurrentHashMap; import com.google.common.annotations.VisibleForTesting; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableSet; import com.google.common.collect.Ordering; import com.google.common.util.concurrent.Striped; import com.google.monitoring.metrics.MetricSchema.Kind; import java.time.Instant; import java.util.Map.Entry; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.locks.Lock;
// Copyright 2017 Google LLC. All Rights Reserved. // // 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.monitoring.metrics; /** * A metric which stores {@link Distribution} values. The values are stateful and meant to be * updated incrementally via the {@link EventMetric#record(double, String...)} method. * * <p>This metric class is generally suitable for recording aggregations of data about a * quantitative aspect of an event. For example, this metric would be suitable for recording the * latency distribution for a request over the network. * * <p>The {@link MutableDistribution} values tracked by this metric can be reset with {@link * EventMetric#reset()}. */ public class EventMetric extends AbstractMetric<Distribution> { /** * Default {@link DistributionFitter} suitable for latency measurements. * * <p>The finite range of this fitter is from 1 to 4^16 (4294967296). */ public static final DistributionFitter DEFAULT_FITTER = ExponentialFitter.create(16, 4.0, 1.0); private final ConcurrentHashMap<ImmutableList<String>, Instant> valueStartTimestamps =
// Path: metrics/src/main/java/com/google/monitoring/metrics/MetricsUtils.java // static final int DEFAULT_CONCURRENCY_LEVEL = 16; // // Path: metrics/src/main/java/com/google/monitoring/metrics/MetricsUtils.java // static <K, V> ConcurrentHashMap<K, V> newConcurrentHashMap(int concurrencyLevel) { // return new ConcurrentHashMap<>(HASHMAP_INITIAL_CAPACITY, HASHMAP_LOAD_FACTOR, concurrencyLevel); // } // // Path: metrics/src/main/java/com/google/monitoring/metrics/MetricSchema.java // public enum Kind { // CUMULATIVE, // GAUGE, // } // Path: metrics/src/main/java/com/google/monitoring/metrics/EventMetric.java import static com.google.monitoring.metrics.MetricsUtils.DEFAULT_CONCURRENCY_LEVEL; import static com.google.monitoring.metrics.MetricsUtils.newConcurrentHashMap; import com.google.common.annotations.VisibleForTesting; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableSet; import com.google.common.collect.Ordering; import com.google.common.util.concurrent.Striped; import com.google.monitoring.metrics.MetricSchema.Kind; import java.time.Instant; import java.util.Map.Entry; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.locks.Lock; // Copyright 2017 Google LLC. All Rights Reserved. // // 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.monitoring.metrics; /** * A metric which stores {@link Distribution} values. The values are stateful and meant to be * updated incrementally via the {@link EventMetric#record(double, String...)} method. * * <p>This metric class is generally suitable for recording aggregations of data about a * quantitative aspect of an event. For example, this metric would be suitable for recording the * latency distribution for a request over the network. * * <p>The {@link MutableDistribution} values tracked by this metric can be reset with {@link * EventMetric#reset()}. */ public class EventMetric extends AbstractMetric<Distribution> { /** * Default {@link DistributionFitter} suitable for latency measurements. * * <p>The finite range of this fitter is from 1 to 4^16 (4294967296). */ public static final DistributionFitter DEFAULT_FITTER = ExponentialFitter.create(16, 4.0, 1.0); private final ConcurrentHashMap<ImmutableList<String>, Instant> valueStartTimestamps =
newConcurrentHashMap(DEFAULT_CONCURRENCY_LEVEL);
google/java-monitoring-client-library
metrics/src/main/java/com/google/monitoring/metrics/EventMetric.java
// Path: metrics/src/main/java/com/google/monitoring/metrics/MetricsUtils.java // static final int DEFAULT_CONCURRENCY_LEVEL = 16; // // Path: metrics/src/main/java/com/google/monitoring/metrics/MetricsUtils.java // static <K, V> ConcurrentHashMap<K, V> newConcurrentHashMap(int concurrencyLevel) { // return new ConcurrentHashMap<>(HASHMAP_INITIAL_CAPACITY, HASHMAP_LOAD_FACTOR, concurrencyLevel); // } // // Path: metrics/src/main/java/com/google/monitoring/metrics/MetricSchema.java // public enum Kind { // CUMULATIVE, // GAUGE, // }
import static com.google.monitoring.metrics.MetricsUtils.DEFAULT_CONCURRENCY_LEVEL; import static com.google.monitoring.metrics.MetricsUtils.newConcurrentHashMap; import com.google.common.annotations.VisibleForTesting; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableSet; import com.google.common.collect.Ordering; import com.google.common.util.concurrent.Striped; import com.google.monitoring.metrics.MetricSchema.Kind; import java.time.Instant; import java.util.Map.Entry; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.locks.Lock;
// Copyright 2017 Google LLC. All Rights Reserved. // // 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.monitoring.metrics; /** * A metric which stores {@link Distribution} values. The values are stateful and meant to be * updated incrementally via the {@link EventMetric#record(double, String...)} method. * * <p>This metric class is generally suitable for recording aggregations of data about a * quantitative aspect of an event. For example, this metric would be suitable for recording the * latency distribution for a request over the network. * * <p>The {@link MutableDistribution} values tracked by this metric can be reset with {@link * EventMetric#reset()}. */ public class EventMetric extends AbstractMetric<Distribution> { /** * Default {@link DistributionFitter} suitable for latency measurements. * * <p>The finite range of this fitter is from 1 to 4^16 (4294967296). */ public static final DistributionFitter DEFAULT_FITTER = ExponentialFitter.create(16, 4.0, 1.0); private final ConcurrentHashMap<ImmutableList<String>, Instant> valueStartTimestamps = newConcurrentHashMap(DEFAULT_CONCURRENCY_LEVEL); private final ConcurrentHashMap<ImmutableList<String>, MutableDistribution> values = newConcurrentHashMap(DEFAULT_CONCURRENCY_LEVEL); private final DistributionFitter distributionFitter; /** * A fine-grained lock to ensure that {@code values} and {@code valueStartTimestamps} are modified * and read in a critical section. The initialization parameter is the concurrency level, set to * match the default concurrency level of {@link ConcurrentHashMap}. * * @see Striped */ private final Striped<Lock> valueLocks = Striped.lock(DEFAULT_CONCURRENCY_LEVEL); EventMetric( String name, String description, String valueDisplayName, DistributionFitter distributionFitter, ImmutableSet<LabelDescriptor> labels) {
// Path: metrics/src/main/java/com/google/monitoring/metrics/MetricsUtils.java // static final int DEFAULT_CONCURRENCY_LEVEL = 16; // // Path: metrics/src/main/java/com/google/monitoring/metrics/MetricsUtils.java // static <K, V> ConcurrentHashMap<K, V> newConcurrentHashMap(int concurrencyLevel) { // return new ConcurrentHashMap<>(HASHMAP_INITIAL_CAPACITY, HASHMAP_LOAD_FACTOR, concurrencyLevel); // } // // Path: metrics/src/main/java/com/google/monitoring/metrics/MetricSchema.java // public enum Kind { // CUMULATIVE, // GAUGE, // } // Path: metrics/src/main/java/com/google/monitoring/metrics/EventMetric.java import static com.google.monitoring.metrics.MetricsUtils.DEFAULT_CONCURRENCY_LEVEL; import static com.google.monitoring.metrics.MetricsUtils.newConcurrentHashMap; import com.google.common.annotations.VisibleForTesting; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableSet; import com.google.common.collect.Ordering; import com.google.common.util.concurrent.Striped; import com.google.monitoring.metrics.MetricSchema.Kind; import java.time.Instant; import java.util.Map.Entry; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.locks.Lock; // Copyright 2017 Google LLC. All Rights Reserved. // // 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.monitoring.metrics; /** * A metric which stores {@link Distribution} values. The values are stateful and meant to be * updated incrementally via the {@link EventMetric#record(double, String...)} method. * * <p>This metric class is generally suitable for recording aggregations of data about a * quantitative aspect of an event. For example, this metric would be suitable for recording the * latency distribution for a request over the network. * * <p>The {@link MutableDistribution} values tracked by this metric can be reset with {@link * EventMetric#reset()}. */ public class EventMetric extends AbstractMetric<Distribution> { /** * Default {@link DistributionFitter} suitable for latency measurements. * * <p>The finite range of this fitter is from 1 to 4^16 (4294967296). */ public static final DistributionFitter DEFAULT_FITTER = ExponentialFitter.create(16, 4.0, 1.0); private final ConcurrentHashMap<ImmutableList<String>, Instant> valueStartTimestamps = newConcurrentHashMap(DEFAULT_CONCURRENCY_LEVEL); private final ConcurrentHashMap<ImmutableList<String>, MutableDistribution> values = newConcurrentHashMap(DEFAULT_CONCURRENCY_LEVEL); private final DistributionFitter distributionFitter; /** * A fine-grained lock to ensure that {@code values} and {@code valueStartTimestamps} are modified * and read in a critical section. The initialization parameter is the concurrency level, set to * match the default concurrency level of {@link ConcurrentHashMap}. * * @see Striped */ private final Striped<Lock> valueLocks = Striped.lock(DEFAULT_CONCURRENCY_LEVEL); EventMetric( String name, String description, String valueDisplayName, DistributionFitter distributionFitter, ImmutableSet<LabelDescriptor> labels) {
super(name, description, valueDisplayName, Kind.CUMULATIVE, labels, Distribution.class);
google/java-monitoring-client-library
metrics/src/main/java/com/google/monitoring/metrics/CustomFitter.java
// Path: metrics/src/main/java/com/google/monitoring/metrics/MetricsUtils.java // static void checkDouble(double value) { // checkArgument( // !Double.isInfinite(value) && !Double.isNaN(value) && !NEGATIVE_ZERO.equals(value), // "value must be finite, not NaN, and not -0.0"); // }
import static com.google.common.base.Preconditions.checkArgument; import static com.google.monitoring.metrics.MetricsUtils.checkDouble; import com.google.auto.value.AutoValue; import com.google.common.collect.ImmutableSet; import com.google.common.collect.ImmutableSortedSet; import com.google.common.collect.Ordering;
// Copyright 2017 Google LLC. All Rights Reserved. // // 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.monitoring.metrics; /** * Models a {@link DistributionFitter} with arbitrary sized intervals. * * <p>If only only one boundary is provided, then the fitter will consist of an overflow and * underflow interval separated by that boundary. */ @AutoValue public abstract class CustomFitter implements DistributionFitter { /** * Create a new {@link CustomFitter} with the given interval boundaries. * * @param boundaries is a sorted list of interval boundaries * @throws IllegalArgumentException if {@code boundaries} is empty or not sorted in ascending * order, or if a value in the set is infinite, {@code NaN}, or {@code -0.0}. */ public static CustomFitter create(ImmutableSet<Double> boundaries) { checkArgument(boundaries.size() > 0, "boundaries must not be empty"); checkArgument(Ordering.natural().isOrdered(boundaries), "boundaries must be sorted"); for (Double d : boundaries) {
// Path: metrics/src/main/java/com/google/monitoring/metrics/MetricsUtils.java // static void checkDouble(double value) { // checkArgument( // !Double.isInfinite(value) && !Double.isNaN(value) && !NEGATIVE_ZERO.equals(value), // "value must be finite, not NaN, and not -0.0"); // } // Path: metrics/src/main/java/com/google/monitoring/metrics/CustomFitter.java import static com.google.common.base.Preconditions.checkArgument; import static com.google.monitoring.metrics.MetricsUtils.checkDouble; import com.google.auto.value.AutoValue; import com.google.common.collect.ImmutableSet; import com.google.common.collect.ImmutableSortedSet; import com.google.common.collect.Ordering; // Copyright 2017 Google LLC. All Rights Reserved. // // 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.monitoring.metrics; /** * Models a {@link DistributionFitter} with arbitrary sized intervals. * * <p>If only only one boundary is provided, then the fitter will consist of an overflow and * underflow interval separated by that boundary. */ @AutoValue public abstract class CustomFitter implements DistributionFitter { /** * Create a new {@link CustomFitter} with the given interval boundaries. * * @param boundaries is a sorted list of interval boundaries * @throws IllegalArgumentException if {@code boundaries} is empty or not sorted in ascending * order, or if a value in the set is infinite, {@code NaN}, or {@code -0.0}. */ public static CustomFitter create(ImmutableSet<Double> boundaries) { checkArgument(boundaries.size() > 0, "boundaries must not be empty"); checkArgument(Ordering.natural().isOrdered(boundaries), "boundaries must be sorted"); for (Double d : boundaries) {
checkDouble(d);
google/java-monitoring-client-library
metrics/src/main/java/com/google/monitoring/metrics/Counter.java
// Path: metrics/src/main/java/com/google/monitoring/metrics/MetricsUtils.java // static final int DEFAULT_CONCURRENCY_LEVEL = 16; // // Path: metrics/src/main/java/com/google/monitoring/metrics/MetricsUtils.java // static <K, V> ConcurrentHashMap<K, V> newConcurrentHashMap(int concurrencyLevel) { // return new ConcurrentHashMap<>(HASHMAP_INITIAL_CAPACITY, HASHMAP_LOAD_FACTOR, concurrencyLevel); // } // // Path: metrics/src/main/java/com/google/monitoring/metrics/MetricSchema.java // public enum Kind { // CUMULATIVE, // GAUGE, // }
import static com.google.common.base.Preconditions.checkArgument; import static com.google.monitoring.metrics.MetricsUtils.DEFAULT_CONCURRENCY_LEVEL; import static com.google.monitoring.metrics.MetricsUtils.newConcurrentHashMap; import com.google.common.annotations.VisibleForTesting; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableSet; import com.google.common.collect.Ordering; import com.google.common.util.concurrent.AtomicLongMap; import com.google.common.util.concurrent.Striped; import com.google.monitoring.metrics.MetricSchema.Kind; import java.time.Instant; import java.util.Map.Entry; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.locks.Lock; import javax.annotation.concurrent.ThreadSafe;
// Copyright 2017 Google LLC. All Rights Reserved. // // 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.monitoring.metrics; /** * A metric which stores Long values. It is stateful and can be changed in increments. * * <p>This metric is generally suitable for counters, such as requests served or errors generated. * * <p>The start of the {@link MetricPoint#interval()} of values of instances of this metric will be * set to the time that the metric was first set or last {@link #reset()}. */ @ThreadSafe public final class Counter extends AbstractMetric<Long> implements SettableMetric<Long>, IncrementableMetric { /** * A map of the {@link Counter} values, with a list of label values as the keys. * * <p>This should be modified in a critical section with {@code valueStartTimestamps} so that the * values are in sync. */ private final AtomicLongMap<ImmutableList<String>> values = AtomicLongMap.create(); /** * A map of the {@link Instant} that each value was created, with a list of label values as the * keys. The start timestamp (as part of the {@link MetricPoint#interval()} can be used by * implementations of {@link MetricWriter} to encode resets of monotonic counters. */ private final ConcurrentHashMap<ImmutableList<String>, Instant> valueStartTimestamps =
// Path: metrics/src/main/java/com/google/monitoring/metrics/MetricsUtils.java // static final int DEFAULT_CONCURRENCY_LEVEL = 16; // // Path: metrics/src/main/java/com/google/monitoring/metrics/MetricsUtils.java // static <K, V> ConcurrentHashMap<K, V> newConcurrentHashMap(int concurrencyLevel) { // return new ConcurrentHashMap<>(HASHMAP_INITIAL_CAPACITY, HASHMAP_LOAD_FACTOR, concurrencyLevel); // } // // Path: metrics/src/main/java/com/google/monitoring/metrics/MetricSchema.java // public enum Kind { // CUMULATIVE, // GAUGE, // } // Path: metrics/src/main/java/com/google/monitoring/metrics/Counter.java import static com.google.common.base.Preconditions.checkArgument; import static com.google.monitoring.metrics.MetricsUtils.DEFAULT_CONCURRENCY_LEVEL; import static com.google.monitoring.metrics.MetricsUtils.newConcurrentHashMap; import com.google.common.annotations.VisibleForTesting; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableSet; import com.google.common.collect.Ordering; import com.google.common.util.concurrent.AtomicLongMap; import com.google.common.util.concurrent.Striped; import com.google.monitoring.metrics.MetricSchema.Kind; import java.time.Instant; import java.util.Map.Entry; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.locks.Lock; import javax.annotation.concurrent.ThreadSafe; // Copyright 2017 Google LLC. All Rights Reserved. // // 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.monitoring.metrics; /** * A metric which stores Long values. It is stateful and can be changed in increments. * * <p>This metric is generally suitable for counters, such as requests served or errors generated. * * <p>The start of the {@link MetricPoint#interval()} of values of instances of this metric will be * set to the time that the metric was first set or last {@link #reset()}. */ @ThreadSafe public final class Counter extends AbstractMetric<Long> implements SettableMetric<Long>, IncrementableMetric { /** * A map of the {@link Counter} values, with a list of label values as the keys. * * <p>This should be modified in a critical section with {@code valueStartTimestamps} so that the * values are in sync. */ private final AtomicLongMap<ImmutableList<String>> values = AtomicLongMap.create(); /** * A map of the {@link Instant} that each value was created, with a list of label values as the * keys. The start timestamp (as part of the {@link MetricPoint#interval()} can be used by * implementations of {@link MetricWriter} to encode resets of monotonic counters. */ private final ConcurrentHashMap<ImmutableList<String>, Instant> valueStartTimestamps =
newConcurrentHashMap(DEFAULT_CONCURRENCY_LEVEL);
google/java-monitoring-client-library
metrics/src/main/java/com/google/monitoring/metrics/Counter.java
// Path: metrics/src/main/java/com/google/monitoring/metrics/MetricsUtils.java // static final int DEFAULT_CONCURRENCY_LEVEL = 16; // // Path: metrics/src/main/java/com/google/monitoring/metrics/MetricsUtils.java // static <K, V> ConcurrentHashMap<K, V> newConcurrentHashMap(int concurrencyLevel) { // return new ConcurrentHashMap<>(HASHMAP_INITIAL_CAPACITY, HASHMAP_LOAD_FACTOR, concurrencyLevel); // } // // Path: metrics/src/main/java/com/google/monitoring/metrics/MetricSchema.java // public enum Kind { // CUMULATIVE, // GAUGE, // }
import static com.google.common.base.Preconditions.checkArgument; import static com.google.monitoring.metrics.MetricsUtils.DEFAULT_CONCURRENCY_LEVEL; import static com.google.monitoring.metrics.MetricsUtils.newConcurrentHashMap; import com.google.common.annotations.VisibleForTesting; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableSet; import com.google.common.collect.Ordering; import com.google.common.util.concurrent.AtomicLongMap; import com.google.common.util.concurrent.Striped; import com.google.monitoring.metrics.MetricSchema.Kind; import java.time.Instant; import java.util.Map.Entry; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.locks.Lock; import javax.annotation.concurrent.ThreadSafe;
// Copyright 2017 Google LLC. All Rights Reserved. // // 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.monitoring.metrics; /** * A metric which stores Long values. It is stateful and can be changed in increments. * * <p>This metric is generally suitable for counters, such as requests served or errors generated. * * <p>The start of the {@link MetricPoint#interval()} of values of instances of this metric will be * set to the time that the metric was first set or last {@link #reset()}. */ @ThreadSafe public final class Counter extends AbstractMetric<Long> implements SettableMetric<Long>, IncrementableMetric { /** * A map of the {@link Counter} values, with a list of label values as the keys. * * <p>This should be modified in a critical section with {@code valueStartTimestamps} so that the * values are in sync. */ private final AtomicLongMap<ImmutableList<String>> values = AtomicLongMap.create(); /** * A map of the {@link Instant} that each value was created, with a list of label values as the * keys. The start timestamp (as part of the {@link MetricPoint#interval()} can be used by * implementations of {@link MetricWriter} to encode resets of monotonic counters. */ private final ConcurrentHashMap<ImmutableList<String>, Instant> valueStartTimestamps =
// Path: metrics/src/main/java/com/google/monitoring/metrics/MetricsUtils.java // static final int DEFAULT_CONCURRENCY_LEVEL = 16; // // Path: metrics/src/main/java/com/google/monitoring/metrics/MetricsUtils.java // static <K, V> ConcurrentHashMap<K, V> newConcurrentHashMap(int concurrencyLevel) { // return new ConcurrentHashMap<>(HASHMAP_INITIAL_CAPACITY, HASHMAP_LOAD_FACTOR, concurrencyLevel); // } // // Path: metrics/src/main/java/com/google/monitoring/metrics/MetricSchema.java // public enum Kind { // CUMULATIVE, // GAUGE, // } // Path: metrics/src/main/java/com/google/monitoring/metrics/Counter.java import static com.google.common.base.Preconditions.checkArgument; import static com.google.monitoring.metrics.MetricsUtils.DEFAULT_CONCURRENCY_LEVEL; import static com.google.monitoring.metrics.MetricsUtils.newConcurrentHashMap; import com.google.common.annotations.VisibleForTesting; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableSet; import com.google.common.collect.Ordering; import com.google.common.util.concurrent.AtomicLongMap; import com.google.common.util.concurrent.Striped; import com.google.monitoring.metrics.MetricSchema.Kind; import java.time.Instant; import java.util.Map.Entry; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.locks.Lock; import javax.annotation.concurrent.ThreadSafe; // Copyright 2017 Google LLC. All Rights Reserved. // // 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.monitoring.metrics; /** * A metric which stores Long values. It is stateful and can be changed in increments. * * <p>This metric is generally suitable for counters, such as requests served or errors generated. * * <p>The start of the {@link MetricPoint#interval()} of values of instances of this metric will be * set to the time that the metric was first set or last {@link #reset()}. */ @ThreadSafe public final class Counter extends AbstractMetric<Long> implements SettableMetric<Long>, IncrementableMetric { /** * A map of the {@link Counter} values, with a list of label values as the keys. * * <p>This should be modified in a critical section with {@code valueStartTimestamps} so that the * values are in sync. */ private final AtomicLongMap<ImmutableList<String>> values = AtomicLongMap.create(); /** * A map of the {@link Instant} that each value was created, with a list of label values as the * keys. The start timestamp (as part of the {@link MetricPoint#interval()} can be used by * implementations of {@link MetricWriter} to encode resets of monotonic counters. */ private final ConcurrentHashMap<ImmutableList<String>, Instant> valueStartTimestamps =
newConcurrentHashMap(DEFAULT_CONCURRENCY_LEVEL);
google/java-monitoring-client-library
metrics/src/main/java/com/google/monitoring/metrics/Counter.java
// Path: metrics/src/main/java/com/google/monitoring/metrics/MetricsUtils.java // static final int DEFAULT_CONCURRENCY_LEVEL = 16; // // Path: metrics/src/main/java/com/google/monitoring/metrics/MetricsUtils.java // static <K, V> ConcurrentHashMap<K, V> newConcurrentHashMap(int concurrencyLevel) { // return new ConcurrentHashMap<>(HASHMAP_INITIAL_CAPACITY, HASHMAP_LOAD_FACTOR, concurrencyLevel); // } // // Path: metrics/src/main/java/com/google/monitoring/metrics/MetricSchema.java // public enum Kind { // CUMULATIVE, // GAUGE, // }
import static com.google.common.base.Preconditions.checkArgument; import static com.google.monitoring.metrics.MetricsUtils.DEFAULT_CONCURRENCY_LEVEL; import static com.google.monitoring.metrics.MetricsUtils.newConcurrentHashMap; import com.google.common.annotations.VisibleForTesting; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableSet; import com.google.common.collect.Ordering; import com.google.common.util.concurrent.AtomicLongMap; import com.google.common.util.concurrent.Striped; import com.google.monitoring.metrics.MetricSchema.Kind; import java.time.Instant; import java.util.Map.Entry; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.locks.Lock; import javax.annotation.concurrent.ThreadSafe;
// Copyright 2017 Google LLC. All Rights Reserved. // // 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.monitoring.metrics; /** * A metric which stores Long values. It is stateful and can be changed in increments. * * <p>This metric is generally suitable for counters, such as requests served or errors generated. * * <p>The start of the {@link MetricPoint#interval()} of values of instances of this metric will be * set to the time that the metric was first set or last {@link #reset()}. */ @ThreadSafe public final class Counter extends AbstractMetric<Long> implements SettableMetric<Long>, IncrementableMetric { /** * A map of the {@link Counter} values, with a list of label values as the keys. * * <p>This should be modified in a critical section with {@code valueStartTimestamps} so that the * values are in sync. */ private final AtomicLongMap<ImmutableList<String>> values = AtomicLongMap.create(); /** * A map of the {@link Instant} that each value was created, with a list of label values as the * keys. The start timestamp (as part of the {@link MetricPoint#interval()} can be used by * implementations of {@link MetricWriter} to encode resets of monotonic counters. */ private final ConcurrentHashMap<ImmutableList<String>, Instant> valueStartTimestamps = newConcurrentHashMap(DEFAULT_CONCURRENCY_LEVEL); /** * A fine-grained lock to ensure that {@code values} and {@code valueStartTimestamps} are modified * and read in a critical section. The initialization parameter is the concurrency level, set to * match the default concurrency level of {@link ConcurrentHashMap}. * * @see Striped */ private final Striped<Lock> valueLocks = Striped.lock(DEFAULT_CONCURRENCY_LEVEL); /** * Constructs a new Counter. * * <p>Note that the order of the labels is significant. */ Counter( String name, String description, String valueDisplayName, ImmutableSet<LabelDescriptor> labels) {
// Path: metrics/src/main/java/com/google/monitoring/metrics/MetricsUtils.java // static final int DEFAULT_CONCURRENCY_LEVEL = 16; // // Path: metrics/src/main/java/com/google/monitoring/metrics/MetricsUtils.java // static <K, V> ConcurrentHashMap<K, V> newConcurrentHashMap(int concurrencyLevel) { // return new ConcurrentHashMap<>(HASHMAP_INITIAL_CAPACITY, HASHMAP_LOAD_FACTOR, concurrencyLevel); // } // // Path: metrics/src/main/java/com/google/monitoring/metrics/MetricSchema.java // public enum Kind { // CUMULATIVE, // GAUGE, // } // Path: metrics/src/main/java/com/google/monitoring/metrics/Counter.java import static com.google.common.base.Preconditions.checkArgument; import static com.google.monitoring.metrics.MetricsUtils.DEFAULT_CONCURRENCY_LEVEL; import static com.google.monitoring.metrics.MetricsUtils.newConcurrentHashMap; import com.google.common.annotations.VisibleForTesting; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableSet; import com.google.common.collect.Ordering; import com.google.common.util.concurrent.AtomicLongMap; import com.google.common.util.concurrent.Striped; import com.google.monitoring.metrics.MetricSchema.Kind; import java.time.Instant; import java.util.Map.Entry; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.locks.Lock; import javax.annotation.concurrent.ThreadSafe; // Copyright 2017 Google LLC. All Rights Reserved. // // 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.monitoring.metrics; /** * A metric which stores Long values. It is stateful and can be changed in increments. * * <p>This metric is generally suitable for counters, such as requests served or errors generated. * * <p>The start of the {@link MetricPoint#interval()} of values of instances of this metric will be * set to the time that the metric was first set or last {@link #reset()}. */ @ThreadSafe public final class Counter extends AbstractMetric<Long> implements SettableMetric<Long>, IncrementableMetric { /** * A map of the {@link Counter} values, with a list of label values as the keys. * * <p>This should be modified in a critical section with {@code valueStartTimestamps} so that the * values are in sync. */ private final AtomicLongMap<ImmutableList<String>> values = AtomicLongMap.create(); /** * A map of the {@link Instant} that each value was created, with a list of label values as the * keys. The start timestamp (as part of the {@link MetricPoint#interval()} can be used by * implementations of {@link MetricWriter} to encode resets of monotonic counters. */ private final ConcurrentHashMap<ImmutableList<String>, Instant> valueStartTimestamps = newConcurrentHashMap(DEFAULT_CONCURRENCY_LEVEL); /** * A fine-grained lock to ensure that {@code values} and {@code valueStartTimestamps} are modified * and read in a critical section. The initialization parameter is the concurrency level, set to * match the default concurrency level of {@link ConcurrentHashMap}. * * @see Striped */ private final Striped<Lock> valueLocks = Striped.lock(DEFAULT_CONCURRENCY_LEVEL); /** * Constructs a new Counter. * * <p>Note that the order of the labels is significant. */ Counter( String name, String description, String valueDisplayName, ImmutableSet<LabelDescriptor> labels) {
super(name, description, valueDisplayName, Kind.CUMULATIVE, labels, Long.class);
google/java-monitoring-client-library
metrics/src/test/java/com/google/monitoring/metrics/MetricRegistryImplTest.java
// Path: metrics/src/main/java/com/google/monitoring/metrics/MetricSchema.java // public enum Kind { // CUMULATIVE, // GAUGE, // }
import static com.google.common.truth.Truth.assertThat; import static org.junit.Assert.assertThrows; import static org.mockito.Mockito.mock; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableMap; import com.google.common.collect.ImmutableSet; import com.google.monitoring.metrics.MetricSchema.Kind; import org.junit.After; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.JUnit4;
AbstractMetric<?> metric = mock(AbstractMetric.class); MetricRegistryImpl.getDefault().registerMetric("/test/metric", metric); assertThat(MetricRegistryImpl.getDefault().getRegisteredMetrics()).containsExactly(metric); MetricRegistryImpl.getDefault().unregisterMetric("/test/metric"); assertThat(MetricRegistryImpl.getDefault().getRegisteredMetrics()).isEmpty(); } @Test public void testNewGauge_createsGauge() { Metric<?> testGauge = MetricRegistryImpl.getDefault() .newGauge( "/test_metric", "test_description", "test_valuedisplayname", ImmutableSet.of(label), () -> ImmutableMap.of(ImmutableList.of("foo"), 1L), Long.class); assertThat(testGauge.getValueClass()).isSameInstanceAs(Long.class); assertThat(testGauge.getMetricSchema()) .isEqualTo( MetricSchema.create( "/test_metric", "test_description", "test_valuedisplayname",
// Path: metrics/src/main/java/com/google/monitoring/metrics/MetricSchema.java // public enum Kind { // CUMULATIVE, // GAUGE, // } // Path: metrics/src/test/java/com/google/monitoring/metrics/MetricRegistryImplTest.java import static com.google.common.truth.Truth.assertThat; import static org.junit.Assert.assertThrows; import static org.mockito.Mockito.mock; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableMap; import com.google.common.collect.ImmutableSet; import com.google.monitoring.metrics.MetricSchema.Kind; import org.junit.After; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; AbstractMetric<?> metric = mock(AbstractMetric.class); MetricRegistryImpl.getDefault().registerMetric("/test/metric", metric); assertThat(MetricRegistryImpl.getDefault().getRegisteredMetrics()).containsExactly(metric); MetricRegistryImpl.getDefault().unregisterMetric("/test/metric"); assertThat(MetricRegistryImpl.getDefault().getRegisteredMetrics()).isEmpty(); } @Test public void testNewGauge_createsGauge() { Metric<?> testGauge = MetricRegistryImpl.getDefault() .newGauge( "/test_metric", "test_description", "test_valuedisplayname", ImmutableSet.of(label), () -> ImmutableMap.of(ImmutableList.of("foo"), 1L), Long.class); assertThat(testGauge.getValueClass()).isSameInstanceAs(Long.class); assertThat(testGauge.getMetricSchema()) .isEqualTo( MetricSchema.create( "/test_metric", "test_description", "test_valuedisplayname",
Kind.GAUGE,
google/java-monitoring-client-library
metrics/src/main/java/com/google/monitoring/metrics/VirtualMetric.java
// Path: metrics/src/main/java/com/google/monitoring/metrics/MetricSchema.java // public enum Kind { // CUMULATIVE, // GAUGE, // }
import com.google.common.annotations.VisibleForTesting; import com.google.common.base.Supplier; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableMap; import com.google.common.collect.ImmutableSet; import com.google.monitoring.metrics.MetricSchema.Kind; import java.time.Instant; import java.util.Map.Entry; import javax.annotation.concurrent.ThreadSafe;
// Copyright 2017 Google LLC. All Rights Reserved. // // 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.monitoring.metrics; /** * A metric whose value is computed at sample-time. * * <p>This pattern works well for gauge-like metrics, such as CPU usage, memory usage, and file * descriptor counts. * * <p>The {@link MetricPoint#interval()} of values of instances of this metric will always have a * start time equal to the end time, since the metric value represents a point-in-time snapshot with * no relationship to prior values. */ @ThreadSafe public final class VirtualMetric<V> extends AbstractMetric<V> { private final Supplier<ImmutableMap<ImmutableList<String>, V>> valuesSupplier; /** * Local cache of the count of values so that we don't have to evaluate the callback function to * get the metric's cardinality. */ private volatile int cardinality; VirtualMetric( String name, String description, String valueDisplayName, ImmutableSet<LabelDescriptor> labels, Supplier<ImmutableMap<ImmutableList<String>, V>> valuesSupplier, Class<V> valueClass) {
// Path: metrics/src/main/java/com/google/monitoring/metrics/MetricSchema.java // public enum Kind { // CUMULATIVE, // GAUGE, // } // Path: metrics/src/main/java/com/google/monitoring/metrics/VirtualMetric.java import com.google.common.annotations.VisibleForTesting; import com.google.common.base.Supplier; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableMap; import com.google.common.collect.ImmutableSet; import com.google.monitoring.metrics.MetricSchema.Kind; import java.time.Instant; import java.util.Map.Entry; import javax.annotation.concurrent.ThreadSafe; // Copyright 2017 Google LLC. All Rights Reserved. // // 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.monitoring.metrics; /** * A metric whose value is computed at sample-time. * * <p>This pattern works well for gauge-like metrics, such as CPU usage, memory usage, and file * descriptor counts. * * <p>The {@link MetricPoint#interval()} of values of instances of this metric will always have a * start time equal to the end time, since the metric value represents a point-in-time snapshot with * no relationship to prior values. */ @ThreadSafe public final class VirtualMetric<V> extends AbstractMetric<V> { private final Supplier<ImmutableMap<ImmutableList<String>, V>> valuesSupplier; /** * Local cache of the count of values so that we don't have to evaluate the callback function to * get the metric's cardinality. */ private volatile int cardinality; VirtualMetric( String name, String description, String valueDisplayName, ImmutableSet<LabelDescriptor> labels, Supplier<ImmutableMap<ImmutableList<String>, V>> valuesSupplier, Class<V> valueClass) {
super(name, description, valueDisplayName, Kind.GAUGE, labels, valueClass);
aparo/elasticsearch-cookbook-third-edition
chapter_17/analysis_plugin/src/main/java/org/elasticsearch/plugin/analysis/AnalysisPlugin.java
// Path: chapter_17/analysis_plugin/src/main/java/org/elasticsearch/index/analysis/CustomEnglishAnalyzerProvider.java // public class CustomEnglishAnalyzerProvider extends AbstractIndexAnalyzerProvider<EnglishAnalyzer> { // public static String NAME = "custom_english"; // // private final EnglishAnalyzer analyzer; // // public CustomEnglishAnalyzerProvider(IndexSettings indexSettings, Environment env, String name, Settings settings, boolean useSmart) { // super(indexSettings, name, settings); // // analyzer = new EnglishAnalyzer( // Analysis.parseStopWords(env, settings, EnglishAnalyzer.getDefaultStopSet(), true), // Analysis.parseStemExclusion(settings, CharArraySet.EMPTY_SET)); // } // // public static CustomEnglishAnalyzerProvider getCustomEnglishAnalyzerProvider(IndexSettings indexSettings, Environment env, String name, Settings settings) { // return new CustomEnglishAnalyzerProvider(indexSettings, env, name, settings, true); // } // // @Override // public EnglishAnalyzer get() { // return this.analyzer; // } // }
import org.apache.lucene.analysis.Analyzer; import org.elasticsearch.index.analysis.AnalyzerProvider; import org.elasticsearch.index.analysis.CustomEnglishAnalyzerProvider; import org.elasticsearch.indices.analysis.AnalysisModule; import org.elasticsearch.plugins.Plugin; import java.util.HashMap; import java.util.Map;
package org.elasticsearch.plugin.analysis; public class AnalysisPlugin extends Plugin implements org.elasticsearch.plugins.AnalysisPlugin { @Override public Map<String, AnalysisModule.AnalysisProvider<AnalyzerProvider<? extends Analyzer>>> getAnalyzers() { Map<String, AnalysisModule.AnalysisProvider<AnalyzerProvider<? extends Analyzer>>> analyzers = new HashMap();
// Path: chapter_17/analysis_plugin/src/main/java/org/elasticsearch/index/analysis/CustomEnglishAnalyzerProvider.java // public class CustomEnglishAnalyzerProvider extends AbstractIndexAnalyzerProvider<EnglishAnalyzer> { // public static String NAME = "custom_english"; // // private final EnglishAnalyzer analyzer; // // public CustomEnglishAnalyzerProvider(IndexSettings indexSettings, Environment env, String name, Settings settings, boolean useSmart) { // super(indexSettings, name, settings); // // analyzer = new EnglishAnalyzer( // Analysis.parseStopWords(env, settings, EnglishAnalyzer.getDefaultStopSet(), true), // Analysis.parseStemExclusion(settings, CharArraySet.EMPTY_SET)); // } // // public static CustomEnglishAnalyzerProvider getCustomEnglishAnalyzerProvider(IndexSettings indexSettings, Environment env, String name, Settings settings) { // return new CustomEnglishAnalyzerProvider(indexSettings, env, name, settings, true); // } // // @Override // public EnglishAnalyzer get() { // return this.analyzer; // } // } // Path: chapter_17/analysis_plugin/src/main/java/org/elasticsearch/plugin/analysis/AnalysisPlugin.java import org.apache.lucene.analysis.Analyzer; import org.elasticsearch.index.analysis.AnalyzerProvider; import org.elasticsearch.index.analysis.CustomEnglishAnalyzerProvider; import org.elasticsearch.indices.analysis.AnalysisModule; import org.elasticsearch.plugins.Plugin; import java.util.HashMap; import java.util.Map; package org.elasticsearch.plugin.analysis; public class AnalysisPlugin extends Plugin implements org.elasticsearch.plugins.AnalysisPlugin { @Override public Map<String, AnalysisModule.AnalysisProvider<AnalyzerProvider<? extends Analyzer>>> getAnalyzers() { Map<String, AnalysisModule.AnalysisProvider<AnalyzerProvider<? extends Analyzer>>> analyzers = new HashMap();
analyzers.put(CustomEnglishAnalyzerProvider.NAME, CustomEnglishAnalyzerProvider::getCustomEnglishAnalyzerProvider);
aparo/elasticsearch-cookbook-third-edition
chapter_17/rest_plugin/src/main/java/org/elasticsearch/plugin/simple/RestPlugin.java
// Path: chapter_17/rest_plugin/src/main/java/org/elasticsearch/action/simple/SimpleAction.java // public class SimpleAction extends Action<SimpleRequest, SimpleResponse, SimpleRequestBuilder> { // // public static final SimpleAction INSTANCE = new SimpleAction(); // public static final String NAME = "custom:indices/simple"; // // private SimpleAction() { // super(NAME); // } // // @Override // public SimpleResponse newResponse() { // return new SimpleResponse(); // } // // @Override // public SimpleRequestBuilder newRequestBuilder(ElasticsearchClient elasticsearchClient) { // return new SimpleRequestBuilder(elasticsearchClient, this); // } // // } // // Path: chapter_17/rest_plugin/src/main/java/org/elasticsearch/action/simple/TransportSimpleAction.java // public class TransportSimpleAction // extends TransportBroadcastByNodeAction<SimpleRequest, SimpleResponse, ShardSimpleResponse> { // // private final IndicesService indicesService; // // @Inject // public TransportSimpleAction(Settings settings, ThreadPool threadPool, ClusterService clusterService, // TransportService transportService, IndicesService indicesService, // ActionFilters actionFilters, IndexNameExpressionResolver indexNameExpressionResolver) { // super(settings, SimpleAction.NAME, threadPool, clusterService, transportService, actionFilters, // indexNameExpressionResolver, SimpleRequest::new, ThreadPool.Names.SEARCH); // this.indicesService = indicesService; // } // // // @Override // protected SimpleResponse newResponse(SimpleRequest request, int totalShards, int successfulShards, int failedShards, List<ShardSimpleResponse> shardSimpleResponses, List<ShardOperationFailedException> shardFailures, ClusterState clusterState) { // Set<String> simple = new HashSet<String>(); // for (ShardSimpleResponse shardSimpleResponse : shardSimpleResponses) { // simple.addAll(shardSimpleResponse.getTermList()); // } // // return new SimpleResponse(totalShards, successfulShards, failedShards, shardFailures, simple); // } // // @Override // protected ShardSimpleResponse shardOperation(SimpleRequest request, ShardRouting shardRouting) throws IOException { // IndexService indexService = indicesService.indexServiceSafe(shardRouting.shardId().getIndex()); // IndexShard indexShard = indexService.getShard(shardRouting.shardId().id()); // indexShard.store().directory(); // Set<String> set = new HashSet<String>(); // set.add(request.getField() + "_" + shardRouting.shardId()); // return new ShardSimpleResponse(shardRouting, set); // } // // // @Override // protected ShardSimpleResponse readShardResult(StreamInput in) throws IOException { // return ShardSimpleResponse.readShardResult(in); // } // // @Override // protected SimpleRequest readRequestFrom(StreamInput in) throws IOException { // SimpleRequest request = new SimpleRequest(); // request.readFrom(in); // return request; // } // // @Override // protected ShardsIterator shards(ClusterState clusterState, SimpleRequest request, String[] concreteIndices) { // return clusterState.routingTable().allShards(concreteIndices); // } // // @Override // protected ClusterBlockException checkGlobalBlock(ClusterState state, SimpleRequest request) { // return state.blocks().globalBlockedException(ClusterBlockLevel.METADATA_READ); // } // // @Override // protected ClusterBlockException checkRequestBlock(ClusterState state, SimpleRequest request, String[] concreteIndices) { // return state.blocks().indicesBlockedException(ClusterBlockLevel.METADATA_READ, concreteIndices); // } // } // // Path: chapter_17/rest_plugin/src/main/java/org/elasticsearch/rest/RestSimpleAction.java // public class RestSimpleAction extends BaseRestHandler { // @Inject // public RestSimpleAction(Settings settings, Client client, RestController controller) { // super(settings); // controller.registerHandler(POST, "/_simple", this); // controller.registerHandler(POST, "/{index}/_simple", this); // controller.registerHandler(POST, "/_simple/{field}", this); // controller.registerHandler(GET, "/_simple", this); // controller.registerHandler(GET, "/{index}/_simple", this); // controller.registerHandler(GET, "/_simple/{field}", this); // } // // @Override // protected RestChannelConsumer prepareRequest(RestRequest request, NodeClient client) throws IOException { // final SimpleRequest simpleRequest = new SimpleRequest(Strings.splitStringByCommaToArray(request.param("index"))); // simpleRequest.setField(request.param("field")); // return channel -> client.execute(SimpleAction.INSTANCE, simpleRequest, new RestBuilderListener<SimpleResponse>(channel){ // @Override // public RestResponse buildResponse(SimpleResponse simpleResponse, XContentBuilder builder) throws Exception { // try { // builder.startObject(); // builder.field("ok", true); // builder.array("terms", simpleResponse.getSimple().toArray()); // builder.endObject(); // // } catch (Exception e) { // onFailure(e); // } // return new BytesRestResponse(OK, builder); // } // }); // } // }
import org.elasticsearch.action.ActionRequest; import org.elasticsearch.action.ActionResponse; import org.elasticsearch.action.simple.SimpleAction; import org.elasticsearch.action.simple.TransportSimpleAction; import org.elasticsearch.plugins.ActionPlugin; import org.elasticsearch.plugins.Plugin; import org.elasticsearch.rest.RestHandler; import org.elasticsearch.rest.RestSimpleAction; import java.util.List; import static java.util.Collections.singletonList;
package org.elasticsearch.plugin.simple; public class RestPlugin extends Plugin implements ActionPlugin { @Override public List<Class<? extends RestHandler>> getRestHandlers() {
// Path: chapter_17/rest_plugin/src/main/java/org/elasticsearch/action/simple/SimpleAction.java // public class SimpleAction extends Action<SimpleRequest, SimpleResponse, SimpleRequestBuilder> { // // public static final SimpleAction INSTANCE = new SimpleAction(); // public static final String NAME = "custom:indices/simple"; // // private SimpleAction() { // super(NAME); // } // // @Override // public SimpleResponse newResponse() { // return new SimpleResponse(); // } // // @Override // public SimpleRequestBuilder newRequestBuilder(ElasticsearchClient elasticsearchClient) { // return new SimpleRequestBuilder(elasticsearchClient, this); // } // // } // // Path: chapter_17/rest_plugin/src/main/java/org/elasticsearch/action/simple/TransportSimpleAction.java // public class TransportSimpleAction // extends TransportBroadcastByNodeAction<SimpleRequest, SimpleResponse, ShardSimpleResponse> { // // private final IndicesService indicesService; // // @Inject // public TransportSimpleAction(Settings settings, ThreadPool threadPool, ClusterService clusterService, // TransportService transportService, IndicesService indicesService, // ActionFilters actionFilters, IndexNameExpressionResolver indexNameExpressionResolver) { // super(settings, SimpleAction.NAME, threadPool, clusterService, transportService, actionFilters, // indexNameExpressionResolver, SimpleRequest::new, ThreadPool.Names.SEARCH); // this.indicesService = indicesService; // } // // // @Override // protected SimpleResponse newResponse(SimpleRequest request, int totalShards, int successfulShards, int failedShards, List<ShardSimpleResponse> shardSimpleResponses, List<ShardOperationFailedException> shardFailures, ClusterState clusterState) { // Set<String> simple = new HashSet<String>(); // for (ShardSimpleResponse shardSimpleResponse : shardSimpleResponses) { // simple.addAll(shardSimpleResponse.getTermList()); // } // // return new SimpleResponse(totalShards, successfulShards, failedShards, shardFailures, simple); // } // // @Override // protected ShardSimpleResponse shardOperation(SimpleRequest request, ShardRouting shardRouting) throws IOException { // IndexService indexService = indicesService.indexServiceSafe(shardRouting.shardId().getIndex()); // IndexShard indexShard = indexService.getShard(shardRouting.shardId().id()); // indexShard.store().directory(); // Set<String> set = new HashSet<String>(); // set.add(request.getField() + "_" + shardRouting.shardId()); // return new ShardSimpleResponse(shardRouting, set); // } // // // @Override // protected ShardSimpleResponse readShardResult(StreamInput in) throws IOException { // return ShardSimpleResponse.readShardResult(in); // } // // @Override // protected SimpleRequest readRequestFrom(StreamInput in) throws IOException { // SimpleRequest request = new SimpleRequest(); // request.readFrom(in); // return request; // } // // @Override // protected ShardsIterator shards(ClusterState clusterState, SimpleRequest request, String[] concreteIndices) { // return clusterState.routingTable().allShards(concreteIndices); // } // // @Override // protected ClusterBlockException checkGlobalBlock(ClusterState state, SimpleRequest request) { // return state.blocks().globalBlockedException(ClusterBlockLevel.METADATA_READ); // } // // @Override // protected ClusterBlockException checkRequestBlock(ClusterState state, SimpleRequest request, String[] concreteIndices) { // return state.blocks().indicesBlockedException(ClusterBlockLevel.METADATA_READ, concreteIndices); // } // } // // Path: chapter_17/rest_plugin/src/main/java/org/elasticsearch/rest/RestSimpleAction.java // public class RestSimpleAction extends BaseRestHandler { // @Inject // public RestSimpleAction(Settings settings, Client client, RestController controller) { // super(settings); // controller.registerHandler(POST, "/_simple", this); // controller.registerHandler(POST, "/{index}/_simple", this); // controller.registerHandler(POST, "/_simple/{field}", this); // controller.registerHandler(GET, "/_simple", this); // controller.registerHandler(GET, "/{index}/_simple", this); // controller.registerHandler(GET, "/_simple/{field}", this); // } // // @Override // protected RestChannelConsumer prepareRequest(RestRequest request, NodeClient client) throws IOException { // final SimpleRequest simpleRequest = new SimpleRequest(Strings.splitStringByCommaToArray(request.param("index"))); // simpleRequest.setField(request.param("field")); // return channel -> client.execute(SimpleAction.INSTANCE, simpleRequest, new RestBuilderListener<SimpleResponse>(channel){ // @Override // public RestResponse buildResponse(SimpleResponse simpleResponse, XContentBuilder builder) throws Exception { // try { // builder.startObject(); // builder.field("ok", true); // builder.array("terms", simpleResponse.getSimple().toArray()); // builder.endObject(); // // } catch (Exception e) { // onFailure(e); // } // return new BytesRestResponse(OK, builder); // } // }); // } // } // Path: chapter_17/rest_plugin/src/main/java/org/elasticsearch/plugin/simple/RestPlugin.java import org.elasticsearch.action.ActionRequest; import org.elasticsearch.action.ActionResponse; import org.elasticsearch.action.simple.SimpleAction; import org.elasticsearch.action.simple.TransportSimpleAction; import org.elasticsearch.plugins.ActionPlugin; import org.elasticsearch.plugins.Plugin; import org.elasticsearch.rest.RestHandler; import org.elasticsearch.rest.RestSimpleAction; import java.util.List; import static java.util.Collections.singletonList; package org.elasticsearch.plugin.simple; public class RestPlugin extends Plugin implements ActionPlugin { @Override public List<Class<? extends RestHandler>> getRestHandlers() {
return singletonList(RestSimpleAction.class);
aparo/elasticsearch-cookbook-third-edition
chapter_17/rest_plugin/src/main/java/org/elasticsearch/plugin/simple/RestPlugin.java
// Path: chapter_17/rest_plugin/src/main/java/org/elasticsearch/action/simple/SimpleAction.java // public class SimpleAction extends Action<SimpleRequest, SimpleResponse, SimpleRequestBuilder> { // // public static final SimpleAction INSTANCE = new SimpleAction(); // public static final String NAME = "custom:indices/simple"; // // private SimpleAction() { // super(NAME); // } // // @Override // public SimpleResponse newResponse() { // return new SimpleResponse(); // } // // @Override // public SimpleRequestBuilder newRequestBuilder(ElasticsearchClient elasticsearchClient) { // return new SimpleRequestBuilder(elasticsearchClient, this); // } // // } // // Path: chapter_17/rest_plugin/src/main/java/org/elasticsearch/action/simple/TransportSimpleAction.java // public class TransportSimpleAction // extends TransportBroadcastByNodeAction<SimpleRequest, SimpleResponse, ShardSimpleResponse> { // // private final IndicesService indicesService; // // @Inject // public TransportSimpleAction(Settings settings, ThreadPool threadPool, ClusterService clusterService, // TransportService transportService, IndicesService indicesService, // ActionFilters actionFilters, IndexNameExpressionResolver indexNameExpressionResolver) { // super(settings, SimpleAction.NAME, threadPool, clusterService, transportService, actionFilters, // indexNameExpressionResolver, SimpleRequest::new, ThreadPool.Names.SEARCH); // this.indicesService = indicesService; // } // // // @Override // protected SimpleResponse newResponse(SimpleRequest request, int totalShards, int successfulShards, int failedShards, List<ShardSimpleResponse> shardSimpleResponses, List<ShardOperationFailedException> shardFailures, ClusterState clusterState) { // Set<String> simple = new HashSet<String>(); // for (ShardSimpleResponse shardSimpleResponse : shardSimpleResponses) { // simple.addAll(shardSimpleResponse.getTermList()); // } // // return new SimpleResponse(totalShards, successfulShards, failedShards, shardFailures, simple); // } // // @Override // protected ShardSimpleResponse shardOperation(SimpleRequest request, ShardRouting shardRouting) throws IOException { // IndexService indexService = indicesService.indexServiceSafe(shardRouting.shardId().getIndex()); // IndexShard indexShard = indexService.getShard(shardRouting.shardId().id()); // indexShard.store().directory(); // Set<String> set = new HashSet<String>(); // set.add(request.getField() + "_" + shardRouting.shardId()); // return new ShardSimpleResponse(shardRouting, set); // } // // // @Override // protected ShardSimpleResponse readShardResult(StreamInput in) throws IOException { // return ShardSimpleResponse.readShardResult(in); // } // // @Override // protected SimpleRequest readRequestFrom(StreamInput in) throws IOException { // SimpleRequest request = new SimpleRequest(); // request.readFrom(in); // return request; // } // // @Override // protected ShardsIterator shards(ClusterState clusterState, SimpleRequest request, String[] concreteIndices) { // return clusterState.routingTable().allShards(concreteIndices); // } // // @Override // protected ClusterBlockException checkGlobalBlock(ClusterState state, SimpleRequest request) { // return state.blocks().globalBlockedException(ClusterBlockLevel.METADATA_READ); // } // // @Override // protected ClusterBlockException checkRequestBlock(ClusterState state, SimpleRequest request, String[] concreteIndices) { // return state.blocks().indicesBlockedException(ClusterBlockLevel.METADATA_READ, concreteIndices); // } // } // // Path: chapter_17/rest_plugin/src/main/java/org/elasticsearch/rest/RestSimpleAction.java // public class RestSimpleAction extends BaseRestHandler { // @Inject // public RestSimpleAction(Settings settings, Client client, RestController controller) { // super(settings); // controller.registerHandler(POST, "/_simple", this); // controller.registerHandler(POST, "/{index}/_simple", this); // controller.registerHandler(POST, "/_simple/{field}", this); // controller.registerHandler(GET, "/_simple", this); // controller.registerHandler(GET, "/{index}/_simple", this); // controller.registerHandler(GET, "/_simple/{field}", this); // } // // @Override // protected RestChannelConsumer prepareRequest(RestRequest request, NodeClient client) throws IOException { // final SimpleRequest simpleRequest = new SimpleRequest(Strings.splitStringByCommaToArray(request.param("index"))); // simpleRequest.setField(request.param("field")); // return channel -> client.execute(SimpleAction.INSTANCE, simpleRequest, new RestBuilderListener<SimpleResponse>(channel){ // @Override // public RestResponse buildResponse(SimpleResponse simpleResponse, XContentBuilder builder) throws Exception { // try { // builder.startObject(); // builder.field("ok", true); // builder.array("terms", simpleResponse.getSimple().toArray()); // builder.endObject(); // // } catch (Exception e) { // onFailure(e); // } // return new BytesRestResponse(OK, builder); // } // }); // } // }
import org.elasticsearch.action.ActionRequest; import org.elasticsearch.action.ActionResponse; import org.elasticsearch.action.simple.SimpleAction; import org.elasticsearch.action.simple.TransportSimpleAction; import org.elasticsearch.plugins.ActionPlugin; import org.elasticsearch.plugins.Plugin; import org.elasticsearch.rest.RestHandler; import org.elasticsearch.rest.RestSimpleAction; import java.util.List; import static java.util.Collections.singletonList;
package org.elasticsearch.plugin.simple; public class RestPlugin extends Plugin implements ActionPlugin { @Override public List<Class<? extends RestHandler>> getRestHandlers() { return singletonList(RestSimpleAction.class); } @Override public List<ActionHandler<? extends ActionRequest<?>, ? extends ActionResponse>> getActions() {
// Path: chapter_17/rest_plugin/src/main/java/org/elasticsearch/action/simple/SimpleAction.java // public class SimpleAction extends Action<SimpleRequest, SimpleResponse, SimpleRequestBuilder> { // // public static final SimpleAction INSTANCE = new SimpleAction(); // public static final String NAME = "custom:indices/simple"; // // private SimpleAction() { // super(NAME); // } // // @Override // public SimpleResponse newResponse() { // return new SimpleResponse(); // } // // @Override // public SimpleRequestBuilder newRequestBuilder(ElasticsearchClient elasticsearchClient) { // return new SimpleRequestBuilder(elasticsearchClient, this); // } // // } // // Path: chapter_17/rest_plugin/src/main/java/org/elasticsearch/action/simple/TransportSimpleAction.java // public class TransportSimpleAction // extends TransportBroadcastByNodeAction<SimpleRequest, SimpleResponse, ShardSimpleResponse> { // // private final IndicesService indicesService; // // @Inject // public TransportSimpleAction(Settings settings, ThreadPool threadPool, ClusterService clusterService, // TransportService transportService, IndicesService indicesService, // ActionFilters actionFilters, IndexNameExpressionResolver indexNameExpressionResolver) { // super(settings, SimpleAction.NAME, threadPool, clusterService, transportService, actionFilters, // indexNameExpressionResolver, SimpleRequest::new, ThreadPool.Names.SEARCH); // this.indicesService = indicesService; // } // // // @Override // protected SimpleResponse newResponse(SimpleRequest request, int totalShards, int successfulShards, int failedShards, List<ShardSimpleResponse> shardSimpleResponses, List<ShardOperationFailedException> shardFailures, ClusterState clusterState) { // Set<String> simple = new HashSet<String>(); // for (ShardSimpleResponse shardSimpleResponse : shardSimpleResponses) { // simple.addAll(shardSimpleResponse.getTermList()); // } // // return new SimpleResponse(totalShards, successfulShards, failedShards, shardFailures, simple); // } // // @Override // protected ShardSimpleResponse shardOperation(SimpleRequest request, ShardRouting shardRouting) throws IOException { // IndexService indexService = indicesService.indexServiceSafe(shardRouting.shardId().getIndex()); // IndexShard indexShard = indexService.getShard(shardRouting.shardId().id()); // indexShard.store().directory(); // Set<String> set = new HashSet<String>(); // set.add(request.getField() + "_" + shardRouting.shardId()); // return new ShardSimpleResponse(shardRouting, set); // } // // // @Override // protected ShardSimpleResponse readShardResult(StreamInput in) throws IOException { // return ShardSimpleResponse.readShardResult(in); // } // // @Override // protected SimpleRequest readRequestFrom(StreamInput in) throws IOException { // SimpleRequest request = new SimpleRequest(); // request.readFrom(in); // return request; // } // // @Override // protected ShardsIterator shards(ClusterState clusterState, SimpleRequest request, String[] concreteIndices) { // return clusterState.routingTable().allShards(concreteIndices); // } // // @Override // protected ClusterBlockException checkGlobalBlock(ClusterState state, SimpleRequest request) { // return state.blocks().globalBlockedException(ClusterBlockLevel.METADATA_READ); // } // // @Override // protected ClusterBlockException checkRequestBlock(ClusterState state, SimpleRequest request, String[] concreteIndices) { // return state.blocks().indicesBlockedException(ClusterBlockLevel.METADATA_READ, concreteIndices); // } // } // // Path: chapter_17/rest_plugin/src/main/java/org/elasticsearch/rest/RestSimpleAction.java // public class RestSimpleAction extends BaseRestHandler { // @Inject // public RestSimpleAction(Settings settings, Client client, RestController controller) { // super(settings); // controller.registerHandler(POST, "/_simple", this); // controller.registerHandler(POST, "/{index}/_simple", this); // controller.registerHandler(POST, "/_simple/{field}", this); // controller.registerHandler(GET, "/_simple", this); // controller.registerHandler(GET, "/{index}/_simple", this); // controller.registerHandler(GET, "/_simple/{field}", this); // } // // @Override // protected RestChannelConsumer prepareRequest(RestRequest request, NodeClient client) throws IOException { // final SimpleRequest simpleRequest = new SimpleRequest(Strings.splitStringByCommaToArray(request.param("index"))); // simpleRequest.setField(request.param("field")); // return channel -> client.execute(SimpleAction.INSTANCE, simpleRequest, new RestBuilderListener<SimpleResponse>(channel){ // @Override // public RestResponse buildResponse(SimpleResponse simpleResponse, XContentBuilder builder) throws Exception { // try { // builder.startObject(); // builder.field("ok", true); // builder.array("terms", simpleResponse.getSimple().toArray()); // builder.endObject(); // // } catch (Exception e) { // onFailure(e); // } // return new BytesRestResponse(OK, builder); // } // }); // } // } // Path: chapter_17/rest_plugin/src/main/java/org/elasticsearch/plugin/simple/RestPlugin.java import org.elasticsearch.action.ActionRequest; import org.elasticsearch.action.ActionResponse; import org.elasticsearch.action.simple.SimpleAction; import org.elasticsearch.action.simple.TransportSimpleAction; import org.elasticsearch.plugins.ActionPlugin; import org.elasticsearch.plugins.Plugin; import org.elasticsearch.rest.RestHandler; import org.elasticsearch.rest.RestSimpleAction; import java.util.List; import static java.util.Collections.singletonList; package org.elasticsearch.plugin.simple; public class RestPlugin extends Plugin implements ActionPlugin { @Override public List<Class<? extends RestHandler>> getRestHandlers() { return singletonList(RestSimpleAction.class); } @Override public List<ActionHandler<? extends ActionRequest<?>, ? extends ActionResponse>> getActions() {
return singletonList(new ActionHandler<>(SimpleAction.INSTANCE, TransportSimpleAction.class));
aparo/elasticsearch-cookbook-third-edition
chapter_17/rest_plugin/src/main/java/org/elasticsearch/plugin/simple/RestPlugin.java
// Path: chapter_17/rest_plugin/src/main/java/org/elasticsearch/action/simple/SimpleAction.java // public class SimpleAction extends Action<SimpleRequest, SimpleResponse, SimpleRequestBuilder> { // // public static final SimpleAction INSTANCE = new SimpleAction(); // public static final String NAME = "custom:indices/simple"; // // private SimpleAction() { // super(NAME); // } // // @Override // public SimpleResponse newResponse() { // return new SimpleResponse(); // } // // @Override // public SimpleRequestBuilder newRequestBuilder(ElasticsearchClient elasticsearchClient) { // return new SimpleRequestBuilder(elasticsearchClient, this); // } // // } // // Path: chapter_17/rest_plugin/src/main/java/org/elasticsearch/action/simple/TransportSimpleAction.java // public class TransportSimpleAction // extends TransportBroadcastByNodeAction<SimpleRequest, SimpleResponse, ShardSimpleResponse> { // // private final IndicesService indicesService; // // @Inject // public TransportSimpleAction(Settings settings, ThreadPool threadPool, ClusterService clusterService, // TransportService transportService, IndicesService indicesService, // ActionFilters actionFilters, IndexNameExpressionResolver indexNameExpressionResolver) { // super(settings, SimpleAction.NAME, threadPool, clusterService, transportService, actionFilters, // indexNameExpressionResolver, SimpleRequest::new, ThreadPool.Names.SEARCH); // this.indicesService = indicesService; // } // // // @Override // protected SimpleResponse newResponse(SimpleRequest request, int totalShards, int successfulShards, int failedShards, List<ShardSimpleResponse> shardSimpleResponses, List<ShardOperationFailedException> shardFailures, ClusterState clusterState) { // Set<String> simple = new HashSet<String>(); // for (ShardSimpleResponse shardSimpleResponse : shardSimpleResponses) { // simple.addAll(shardSimpleResponse.getTermList()); // } // // return new SimpleResponse(totalShards, successfulShards, failedShards, shardFailures, simple); // } // // @Override // protected ShardSimpleResponse shardOperation(SimpleRequest request, ShardRouting shardRouting) throws IOException { // IndexService indexService = indicesService.indexServiceSafe(shardRouting.shardId().getIndex()); // IndexShard indexShard = indexService.getShard(shardRouting.shardId().id()); // indexShard.store().directory(); // Set<String> set = new HashSet<String>(); // set.add(request.getField() + "_" + shardRouting.shardId()); // return new ShardSimpleResponse(shardRouting, set); // } // // // @Override // protected ShardSimpleResponse readShardResult(StreamInput in) throws IOException { // return ShardSimpleResponse.readShardResult(in); // } // // @Override // protected SimpleRequest readRequestFrom(StreamInput in) throws IOException { // SimpleRequest request = new SimpleRequest(); // request.readFrom(in); // return request; // } // // @Override // protected ShardsIterator shards(ClusterState clusterState, SimpleRequest request, String[] concreteIndices) { // return clusterState.routingTable().allShards(concreteIndices); // } // // @Override // protected ClusterBlockException checkGlobalBlock(ClusterState state, SimpleRequest request) { // return state.blocks().globalBlockedException(ClusterBlockLevel.METADATA_READ); // } // // @Override // protected ClusterBlockException checkRequestBlock(ClusterState state, SimpleRequest request, String[] concreteIndices) { // return state.blocks().indicesBlockedException(ClusterBlockLevel.METADATA_READ, concreteIndices); // } // } // // Path: chapter_17/rest_plugin/src/main/java/org/elasticsearch/rest/RestSimpleAction.java // public class RestSimpleAction extends BaseRestHandler { // @Inject // public RestSimpleAction(Settings settings, Client client, RestController controller) { // super(settings); // controller.registerHandler(POST, "/_simple", this); // controller.registerHandler(POST, "/{index}/_simple", this); // controller.registerHandler(POST, "/_simple/{field}", this); // controller.registerHandler(GET, "/_simple", this); // controller.registerHandler(GET, "/{index}/_simple", this); // controller.registerHandler(GET, "/_simple/{field}", this); // } // // @Override // protected RestChannelConsumer prepareRequest(RestRequest request, NodeClient client) throws IOException { // final SimpleRequest simpleRequest = new SimpleRequest(Strings.splitStringByCommaToArray(request.param("index"))); // simpleRequest.setField(request.param("field")); // return channel -> client.execute(SimpleAction.INSTANCE, simpleRequest, new RestBuilderListener<SimpleResponse>(channel){ // @Override // public RestResponse buildResponse(SimpleResponse simpleResponse, XContentBuilder builder) throws Exception { // try { // builder.startObject(); // builder.field("ok", true); // builder.array("terms", simpleResponse.getSimple().toArray()); // builder.endObject(); // // } catch (Exception e) { // onFailure(e); // } // return new BytesRestResponse(OK, builder); // } // }); // } // }
import org.elasticsearch.action.ActionRequest; import org.elasticsearch.action.ActionResponse; import org.elasticsearch.action.simple.SimpleAction; import org.elasticsearch.action.simple.TransportSimpleAction; import org.elasticsearch.plugins.ActionPlugin; import org.elasticsearch.plugins.Plugin; import org.elasticsearch.rest.RestHandler; import org.elasticsearch.rest.RestSimpleAction; import java.util.List; import static java.util.Collections.singletonList;
package org.elasticsearch.plugin.simple; public class RestPlugin extends Plugin implements ActionPlugin { @Override public List<Class<? extends RestHandler>> getRestHandlers() { return singletonList(RestSimpleAction.class); } @Override public List<ActionHandler<? extends ActionRequest<?>, ? extends ActionResponse>> getActions() {
// Path: chapter_17/rest_plugin/src/main/java/org/elasticsearch/action/simple/SimpleAction.java // public class SimpleAction extends Action<SimpleRequest, SimpleResponse, SimpleRequestBuilder> { // // public static final SimpleAction INSTANCE = new SimpleAction(); // public static final String NAME = "custom:indices/simple"; // // private SimpleAction() { // super(NAME); // } // // @Override // public SimpleResponse newResponse() { // return new SimpleResponse(); // } // // @Override // public SimpleRequestBuilder newRequestBuilder(ElasticsearchClient elasticsearchClient) { // return new SimpleRequestBuilder(elasticsearchClient, this); // } // // } // // Path: chapter_17/rest_plugin/src/main/java/org/elasticsearch/action/simple/TransportSimpleAction.java // public class TransportSimpleAction // extends TransportBroadcastByNodeAction<SimpleRequest, SimpleResponse, ShardSimpleResponse> { // // private final IndicesService indicesService; // // @Inject // public TransportSimpleAction(Settings settings, ThreadPool threadPool, ClusterService clusterService, // TransportService transportService, IndicesService indicesService, // ActionFilters actionFilters, IndexNameExpressionResolver indexNameExpressionResolver) { // super(settings, SimpleAction.NAME, threadPool, clusterService, transportService, actionFilters, // indexNameExpressionResolver, SimpleRequest::new, ThreadPool.Names.SEARCH); // this.indicesService = indicesService; // } // // // @Override // protected SimpleResponse newResponse(SimpleRequest request, int totalShards, int successfulShards, int failedShards, List<ShardSimpleResponse> shardSimpleResponses, List<ShardOperationFailedException> shardFailures, ClusterState clusterState) { // Set<String> simple = new HashSet<String>(); // for (ShardSimpleResponse shardSimpleResponse : shardSimpleResponses) { // simple.addAll(shardSimpleResponse.getTermList()); // } // // return new SimpleResponse(totalShards, successfulShards, failedShards, shardFailures, simple); // } // // @Override // protected ShardSimpleResponse shardOperation(SimpleRequest request, ShardRouting shardRouting) throws IOException { // IndexService indexService = indicesService.indexServiceSafe(shardRouting.shardId().getIndex()); // IndexShard indexShard = indexService.getShard(shardRouting.shardId().id()); // indexShard.store().directory(); // Set<String> set = new HashSet<String>(); // set.add(request.getField() + "_" + shardRouting.shardId()); // return new ShardSimpleResponse(shardRouting, set); // } // // // @Override // protected ShardSimpleResponse readShardResult(StreamInput in) throws IOException { // return ShardSimpleResponse.readShardResult(in); // } // // @Override // protected SimpleRequest readRequestFrom(StreamInput in) throws IOException { // SimpleRequest request = new SimpleRequest(); // request.readFrom(in); // return request; // } // // @Override // protected ShardsIterator shards(ClusterState clusterState, SimpleRequest request, String[] concreteIndices) { // return clusterState.routingTable().allShards(concreteIndices); // } // // @Override // protected ClusterBlockException checkGlobalBlock(ClusterState state, SimpleRequest request) { // return state.blocks().globalBlockedException(ClusterBlockLevel.METADATA_READ); // } // // @Override // protected ClusterBlockException checkRequestBlock(ClusterState state, SimpleRequest request, String[] concreteIndices) { // return state.blocks().indicesBlockedException(ClusterBlockLevel.METADATA_READ, concreteIndices); // } // } // // Path: chapter_17/rest_plugin/src/main/java/org/elasticsearch/rest/RestSimpleAction.java // public class RestSimpleAction extends BaseRestHandler { // @Inject // public RestSimpleAction(Settings settings, Client client, RestController controller) { // super(settings); // controller.registerHandler(POST, "/_simple", this); // controller.registerHandler(POST, "/{index}/_simple", this); // controller.registerHandler(POST, "/_simple/{field}", this); // controller.registerHandler(GET, "/_simple", this); // controller.registerHandler(GET, "/{index}/_simple", this); // controller.registerHandler(GET, "/_simple/{field}", this); // } // // @Override // protected RestChannelConsumer prepareRequest(RestRequest request, NodeClient client) throws IOException { // final SimpleRequest simpleRequest = new SimpleRequest(Strings.splitStringByCommaToArray(request.param("index"))); // simpleRequest.setField(request.param("field")); // return channel -> client.execute(SimpleAction.INSTANCE, simpleRequest, new RestBuilderListener<SimpleResponse>(channel){ // @Override // public RestResponse buildResponse(SimpleResponse simpleResponse, XContentBuilder builder) throws Exception { // try { // builder.startObject(); // builder.field("ok", true); // builder.array("terms", simpleResponse.getSimple().toArray()); // builder.endObject(); // // } catch (Exception e) { // onFailure(e); // } // return new BytesRestResponse(OK, builder); // } // }); // } // } // Path: chapter_17/rest_plugin/src/main/java/org/elasticsearch/plugin/simple/RestPlugin.java import org.elasticsearch.action.ActionRequest; import org.elasticsearch.action.ActionResponse; import org.elasticsearch.action.simple.SimpleAction; import org.elasticsearch.action.simple.TransportSimpleAction; import org.elasticsearch.plugins.ActionPlugin; import org.elasticsearch.plugins.Plugin; import org.elasticsearch.rest.RestHandler; import org.elasticsearch.rest.RestSimpleAction; import java.util.List; import static java.util.Collections.singletonList; package org.elasticsearch.plugin.simple; public class RestPlugin extends Plugin implements ActionPlugin { @Override public List<Class<? extends RestHandler>> getRestHandlers() { return singletonList(RestSimpleAction.class); } @Override public List<ActionHandler<? extends ActionRequest<?>, ? extends ActionResponse>> getActions() {
return singletonList(new ActionHandler<>(SimpleAction.INSTANCE, TransportSimpleAction.class));
aparo/elasticsearch-cookbook-third-edition
chapter_17/rest_plugin/src/main/java/org/elasticsearch/rest/RestSimpleAction.java
// Path: chapter_17/rest_plugin/src/main/java/org/elasticsearch/action/simple/SimpleAction.java // public class SimpleAction extends Action<SimpleRequest, SimpleResponse, SimpleRequestBuilder> { // // public static final SimpleAction INSTANCE = new SimpleAction(); // public static final String NAME = "custom:indices/simple"; // // private SimpleAction() { // super(NAME); // } // // @Override // public SimpleResponse newResponse() { // return new SimpleResponse(); // } // // @Override // public SimpleRequestBuilder newRequestBuilder(ElasticsearchClient elasticsearchClient) { // return new SimpleRequestBuilder(elasticsearchClient, this); // } // // } // // Path: chapter_17/rest_plugin/src/main/java/org/elasticsearch/action/simple/SimpleRequest.java // public class SimpleRequest extends BroadcastRequest<SimpleRequest> { // // private String field; // // SimpleRequest() { // } // // public SimpleRequest(String... indices) { // super(indices); // } // // public void setField(String field) { // this.field = field; // } // // public String getField() { // return field; // } // // @Override // public void readFrom(StreamInput in) throws IOException { // super.readFrom(in); // field = in.readString(); // } // // @Override // public void writeTo(StreamOutput out) throws IOException { // super.writeTo(out); // out.writeString(field); // } // } // // Path: chapter_17/rest_plugin/src/main/java/org/elasticsearch/action/simple/SimpleResponse.java // public class SimpleResponse extends BroadcastResponse { // // private Set<String> simple; // // SimpleResponse() { // } // // SimpleResponse(int totalShards, int successfulShards, int failedShards, List<ShardOperationFailedException> shardFailures, Set<String> simple) { // super(totalShards, successfulShards, failedShards, shardFailures); // this.simple = simple; // } // // public Set<String> getSimple() { // return simple; // } // // @Override // public void readFrom(StreamInput in) throws IOException { // super.readFrom(in); // int n = in.readInt(); // simple = new HashSet<String>(); // for (int i = 0; i < n; i++) { // simple.add(in.readString()); // } // } // // @Override // public void writeTo(StreamOutput out) throws IOException { // super.writeTo(out); // out.writeInt(simple.size()); // for (String t : simple) { // out.writeString(t); // } // } // }
import org.elasticsearch.action.simple.SimpleAction; import org.elasticsearch.action.simple.SimpleRequest; import org.elasticsearch.action.simple.SimpleResponse; import org.elasticsearch.client.Client; import org.elasticsearch.client.node.NodeClient; import org.elasticsearch.common.Strings; import org.elasticsearch.common.inject.Inject; import org.elasticsearch.common.settings.Settings; import org.elasticsearch.common.xcontent.XContentBuilder; import org.elasticsearch.rest.action.RestBuilderListener; import java.io.IOException; import static org.elasticsearch.rest.RestRequest.Method.GET; import static org.elasticsearch.rest.RestRequest.Method.POST; import static org.elasticsearch.rest.RestStatus.OK;
package org.elasticsearch.rest; public class RestSimpleAction extends BaseRestHandler { @Inject public RestSimpleAction(Settings settings, Client client, RestController controller) { super(settings); controller.registerHandler(POST, "/_simple", this); controller.registerHandler(POST, "/{index}/_simple", this); controller.registerHandler(POST, "/_simple/{field}", this); controller.registerHandler(GET, "/_simple", this); controller.registerHandler(GET, "/{index}/_simple", this); controller.registerHandler(GET, "/_simple/{field}", this); } @Override protected RestChannelConsumer prepareRequest(RestRequest request, NodeClient client) throws IOException {
// Path: chapter_17/rest_plugin/src/main/java/org/elasticsearch/action/simple/SimpleAction.java // public class SimpleAction extends Action<SimpleRequest, SimpleResponse, SimpleRequestBuilder> { // // public static final SimpleAction INSTANCE = new SimpleAction(); // public static final String NAME = "custom:indices/simple"; // // private SimpleAction() { // super(NAME); // } // // @Override // public SimpleResponse newResponse() { // return new SimpleResponse(); // } // // @Override // public SimpleRequestBuilder newRequestBuilder(ElasticsearchClient elasticsearchClient) { // return new SimpleRequestBuilder(elasticsearchClient, this); // } // // } // // Path: chapter_17/rest_plugin/src/main/java/org/elasticsearch/action/simple/SimpleRequest.java // public class SimpleRequest extends BroadcastRequest<SimpleRequest> { // // private String field; // // SimpleRequest() { // } // // public SimpleRequest(String... indices) { // super(indices); // } // // public void setField(String field) { // this.field = field; // } // // public String getField() { // return field; // } // // @Override // public void readFrom(StreamInput in) throws IOException { // super.readFrom(in); // field = in.readString(); // } // // @Override // public void writeTo(StreamOutput out) throws IOException { // super.writeTo(out); // out.writeString(field); // } // } // // Path: chapter_17/rest_plugin/src/main/java/org/elasticsearch/action/simple/SimpleResponse.java // public class SimpleResponse extends BroadcastResponse { // // private Set<String> simple; // // SimpleResponse() { // } // // SimpleResponse(int totalShards, int successfulShards, int failedShards, List<ShardOperationFailedException> shardFailures, Set<String> simple) { // super(totalShards, successfulShards, failedShards, shardFailures); // this.simple = simple; // } // // public Set<String> getSimple() { // return simple; // } // // @Override // public void readFrom(StreamInput in) throws IOException { // super.readFrom(in); // int n = in.readInt(); // simple = new HashSet<String>(); // for (int i = 0; i < n; i++) { // simple.add(in.readString()); // } // } // // @Override // public void writeTo(StreamOutput out) throws IOException { // super.writeTo(out); // out.writeInt(simple.size()); // for (String t : simple) { // out.writeString(t); // } // } // } // Path: chapter_17/rest_plugin/src/main/java/org/elasticsearch/rest/RestSimpleAction.java import org.elasticsearch.action.simple.SimpleAction; import org.elasticsearch.action.simple.SimpleRequest; import org.elasticsearch.action.simple.SimpleResponse; import org.elasticsearch.client.Client; import org.elasticsearch.client.node.NodeClient; import org.elasticsearch.common.Strings; import org.elasticsearch.common.inject.Inject; import org.elasticsearch.common.settings.Settings; import org.elasticsearch.common.xcontent.XContentBuilder; import org.elasticsearch.rest.action.RestBuilderListener; import java.io.IOException; import static org.elasticsearch.rest.RestRequest.Method.GET; import static org.elasticsearch.rest.RestRequest.Method.POST; import static org.elasticsearch.rest.RestStatus.OK; package org.elasticsearch.rest; public class RestSimpleAction extends BaseRestHandler { @Inject public RestSimpleAction(Settings settings, Client client, RestController controller) { super(settings); controller.registerHandler(POST, "/_simple", this); controller.registerHandler(POST, "/{index}/_simple", this); controller.registerHandler(POST, "/_simple/{field}", this); controller.registerHandler(GET, "/_simple", this); controller.registerHandler(GET, "/{index}/_simple", this); controller.registerHandler(GET, "/_simple/{field}", this); } @Override protected RestChannelConsumer prepareRequest(RestRequest request, NodeClient client) throws IOException {
final SimpleRequest simpleRequest = new SimpleRequest(Strings.splitStringByCommaToArray(request.param("index")));
aparo/elasticsearch-cookbook-third-edition
chapter_17/rest_plugin/src/main/java/org/elasticsearch/rest/RestSimpleAction.java
// Path: chapter_17/rest_plugin/src/main/java/org/elasticsearch/action/simple/SimpleAction.java // public class SimpleAction extends Action<SimpleRequest, SimpleResponse, SimpleRequestBuilder> { // // public static final SimpleAction INSTANCE = new SimpleAction(); // public static final String NAME = "custom:indices/simple"; // // private SimpleAction() { // super(NAME); // } // // @Override // public SimpleResponse newResponse() { // return new SimpleResponse(); // } // // @Override // public SimpleRequestBuilder newRequestBuilder(ElasticsearchClient elasticsearchClient) { // return new SimpleRequestBuilder(elasticsearchClient, this); // } // // } // // Path: chapter_17/rest_plugin/src/main/java/org/elasticsearch/action/simple/SimpleRequest.java // public class SimpleRequest extends BroadcastRequest<SimpleRequest> { // // private String field; // // SimpleRequest() { // } // // public SimpleRequest(String... indices) { // super(indices); // } // // public void setField(String field) { // this.field = field; // } // // public String getField() { // return field; // } // // @Override // public void readFrom(StreamInput in) throws IOException { // super.readFrom(in); // field = in.readString(); // } // // @Override // public void writeTo(StreamOutput out) throws IOException { // super.writeTo(out); // out.writeString(field); // } // } // // Path: chapter_17/rest_plugin/src/main/java/org/elasticsearch/action/simple/SimpleResponse.java // public class SimpleResponse extends BroadcastResponse { // // private Set<String> simple; // // SimpleResponse() { // } // // SimpleResponse(int totalShards, int successfulShards, int failedShards, List<ShardOperationFailedException> shardFailures, Set<String> simple) { // super(totalShards, successfulShards, failedShards, shardFailures); // this.simple = simple; // } // // public Set<String> getSimple() { // return simple; // } // // @Override // public void readFrom(StreamInput in) throws IOException { // super.readFrom(in); // int n = in.readInt(); // simple = new HashSet<String>(); // for (int i = 0; i < n; i++) { // simple.add(in.readString()); // } // } // // @Override // public void writeTo(StreamOutput out) throws IOException { // super.writeTo(out); // out.writeInt(simple.size()); // for (String t : simple) { // out.writeString(t); // } // } // }
import org.elasticsearch.action.simple.SimpleAction; import org.elasticsearch.action.simple.SimpleRequest; import org.elasticsearch.action.simple.SimpleResponse; import org.elasticsearch.client.Client; import org.elasticsearch.client.node.NodeClient; import org.elasticsearch.common.Strings; import org.elasticsearch.common.inject.Inject; import org.elasticsearch.common.settings.Settings; import org.elasticsearch.common.xcontent.XContentBuilder; import org.elasticsearch.rest.action.RestBuilderListener; import java.io.IOException; import static org.elasticsearch.rest.RestRequest.Method.GET; import static org.elasticsearch.rest.RestRequest.Method.POST; import static org.elasticsearch.rest.RestStatus.OK;
package org.elasticsearch.rest; public class RestSimpleAction extends BaseRestHandler { @Inject public RestSimpleAction(Settings settings, Client client, RestController controller) { super(settings); controller.registerHandler(POST, "/_simple", this); controller.registerHandler(POST, "/{index}/_simple", this); controller.registerHandler(POST, "/_simple/{field}", this); controller.registerHandler(GET, "/_simple", this); controller.registerHandler(GET, "/{index}/_simple", this); controller.registerHandler(GET, "/_simple/{field}", this); } @Override protected RestChannelConsumer prepareRequest(RestRequest request, NodeClient client) throws IOException { final SimpleRequest simpleRequest = new SimpleRequest(Strings.splitStringByCommaToArray(request.param("index"))); simpleRequest.setField(request.param("field"));
// Path: chapter_17/rest_plugin/src/main/java/org/elasticsearch/action/simple/SimpleAction.java // public class SimpleAction extends Action<SimpleRequest, SimpleResponse, SimpleRequestBuilder> { // // public static final SimpleAction INSTANCE = new SimpleAction(); // public static final String NAME = "custom:indices/simple"; // // private SimpleAction() { // super(NAME); // } // // @Override // public SimpleResponse newResponse() { // return new SimpleResponse(); // } // // @Override // public SimpleRequestBuilder newRequestBuilder(ElasticsearchClient elasticsearchClient) { // return new SimpleRequestBuilder(elasticsearchClient, this); // } // // } // // Path: chapter_17/rest_plugin/src/main/java/org/elasticsearch/action/simple/SimpleRequest.java // public class SimpleRequest extends BroadcastRequest<SimpleRequest> { // // private String field; // // SimpleRequest() { // } // // public SimpleRequest(String... indices) { // super(indices); // } // // public void setField(String field) { // this.field = field; // } // // public String getField() { // return field; // } // // @Override // public void readFrom(StreamInput in) throws IOException { // super.readFrom(in); // field = in.readString(); // } // // @Override // public void writeTo(StreamOutput out) throws IOException { // super.writeTo(out); // out.writeString(field); // } // } // // Path: chapter_17/rest_plugin/src/main/java/org/elasticsearch/action/simple/SimpleResponse.java // public class SimpleResponse extends BroadcastResponse { // // private Set<String> simple; // // SimpleResponse() { // } // // SimpleResponse(int totalShards, int successfulShards, int failedShards, List<ShardOperationFailedException> shardFailures, Set<String> simple) { // super(totalShards, successfulShards, failedShards, shardFailures); // this.simple = simple; // } // // public Set<String> getSimple() { // return simple; // } // // @Override // public void readFrom(StreamInput in) throws IOException { // super.readFrom(in); // int n = in.readInt(); // simple = new HashSet<String>(); // for (int i = 0; i < n; i++) { // simple.add(in.readString()); // } // } // // @Override // public void writeTo(StreamOutput out) throws IOException { // super.writeTo(out); // out.writeInt(simple.size()); // for (String t : simple) { // out.writeString(t); // } // } // } // Path: chapter_17/rest_plugin/src/main/java/org/elasticsearch/rest/RestSimpleAction.java import org.elasticsearch.action.simple.SimpleAction; import org.elasticsearch.action.simple.SimpleRequest; import org.elasticsearch.action.simple.SimpleResponse; import org.elasticsearch.client.Client; import org.elasticsearch.client.node.NodeClient; import org.elasticsearch.common.Strings; import org.elasticsearch.common.inject.Inject; import org.elasticsearch.common.settings.Settings; import org.elasticsearch.common.xcontent.XContentBuilder; import org.elasticsearch.rest.action.RestBuilderListener; import java.io.IOException; import static org.elasticsearch.rest.RestRequest.Method.GET; import static org.elasticsearch.rest.RestRequest.Method.POST; import static org.elasticsearch.rest.RestStatus.OK; package org.elasticsearch.rest; public class RestSimpleAction extends BaseRestHandler { @Inject public RestSimpleAction(Settings settings, Client client, RestController controller) { super(settings); controller.registerHandler(POST, "/_simple", this); controller.registerHandler(POST, "/{index}/_simple", this); controller.registerHandler(POST, "/_simple/{field}", this); controller.registerHandler(GET, "/_simple", this); controller.registerHandler(GET, "/{index}/_simple", this); controller.registerHandler(GET, "/_simple/{field}", this); } @Override protected RestChannelConsumer prepareRequest(RestRequest request, NodeClient client) throws IOException { final SimpleRequest simpleRequest = new SimpleRequest(Strings.splitStringByCommaToArray(request.param("index"))); simpleRequest.setField(request.param("field"));
return channel -> client.execute(SimpleAction.INSTANCE, simpleRequest, new RestBuilderListener<SimpleResponse>(channel){
aparo/elasticsearch-cookbook-third-edition
chapter_17/rest_plugin/src/main/java/org/elasticsearch/rest/RestSimpleAction.java
// Path: chapter_17/rest_plugin/src/main/java/org/elasticsearch/action/simple/SimpleAction.java // public class SimpleAction extends Action<SimpleRequest, SimpleResponse, SimpleRequestBuilder> { // // public static final SimpleAction INSTANCE = new SimpleAction(); // public static final String NAME = "custom:indices/simple"; // // private SimpleAction() { // super(NAME); // } // // @Override // public SimpleResponse newResponse() { // return new SimpleResponse(); // } // // @Override // public SimpleRequestBuilder newRequestBuilder(ElasticsearchClient elasticsearchClient) { // return new SimpleRequestBuilder(elasticsearchClient, this); // } // // } // // Path: chapter_17/rest_plugin/src/main/java/org/elasticsearch/action/simple/SimpleRequest.java // public class SimpleRequest extends BroadcastRequest<SimpleRequest> { // // private String field; // // SimpleRequest() { // } // // public SimpleRequest(String... indices) { // super(indices); // } // // public void setField(String field) { // this.field = field; // } // // public String getField() { // return field; // } // // @Override // public void readFrom(StreamInput in) throws IOException { // super.readFrom(in); // field = in.readString(); // } // // @Override // public void writeTo(StreamOutput out) throws IOException { // super.writeTo(out); // out.writeString(field); // } // } // // Path: chapter_17/rest_plugin/src/main/java/org/elasticsearch/action/simple/SimpleResponse.java // public class SimpleResponse extends BroadcastResponse { // // private Set<String> simple; // // SimpleResponse() { // } // // SimpleResponse(int totalShards, int successfulShards, int failedShards, List<ShardOperationFailedException> shardFailures, Set<String> simple) { // super(totalShards, successfulShards, failedShards, shardFailures); // this.simple = simple; // } // // public Set<String> getSimple() { // return simple; // } // // @Override // public void readFrom(StreamInput in) throws IOException { // super.readFrom(in); // int n = in.readInt(); // simple = new HashSet<String>(); // for (int i = 0; i < n; i++) { // simple.add(in.readString()); // } // } // // @Override // public void writeTo(StreamOutput out) throws IOException { // super.writeTo(out); // out.writeInt(simple.size()); // for (String t : simple) { // out.writeString(t); // } // } // }
import org.elasticsearch.action.simple.SimpleAction; import org.elasticsearch.action.simple.SimpleRequest; import org.elasticsearch.action.simple.SimpleResponse; import org.elasticsearch.client.Client; import org.elasticsearch.client.node.NodeClient; import org.elasticsearch.common.Strings; import org.elasticsearch.common.inject.Inject; import org.elasticsearch.common.settings.Settings; import org.elasticsearch.common.xcontent.XContentBuilder; import org.elasticsearch.rest.action.RestBuilderListener; import java.io.IOException; import static org.elasticsearch.rest.RestRequest.Method.GET; import static org.elasticsearch.rest.RestRequest.Method.POST; import static org.elasticsearch.rest.RestStatus.OK;
package org.elasticsearch.rest; public class RestSimpleAction extends BaseRestHandler { @Inject public RestSimpleAction(Settings settings, Client client, RestController controller) { super(settings); controller.registerHandler(POST, "/_simple", this); controller.registerHandler(POST, "/{index}/_simple", this); controller.registerHandler(POST, "/_simple/{field}", this); controller.registerHandler(GET, "/_simple", this); controller.registerHandler(GET, "/{index}/_simple", this); controller.registerHandler(GET, "/_simple/{field}", this); } @Override protected RestChannelConsumer prepareRequest(RestRequest request, NodeClient client) throws IOException { final SimpleRequest simpleRequest = new SimpleRequest(Strings.splitStringByCommaToArray(request.param("index"))); simpleRequest.setField(request.param("field"));
// Path: chapter_17/rest_plugin/src/main/java/org/elasticsearch/action/simple/SimpleAction.java // public class SimpleAction extends Action<SimpleRequest, SimpleResponse, SimpleRequestBuilder> { // // public static final SimpleAction INSTANCE = new SimpleAction(); // public static final String NAME = "custom:indices/simple"; // // private SimpleAction() { // super(NAME); // } // // @Override // public SimpleResponse newResponse() { // return new SimpleResponse(); // } // // @Override // public SimpleRequestBuilder newRequestBuilder(ElasticsearchClient elasticsearchClient) { // return new SimpleRequestBuilder(elasticsearchClient, this); // } // // } // // Path: chapter_17/rest_plugin/src/main/java/org/elasticsearch/action/simple/SimpleRequest.java // public class SimpleRequest extends BroadcastRequest<SimpleRequest> { // // private String field; // // SimpleRequest() { // } // // public SimpleRequest(String... indices) { // super(indices); // } // // public void setField(String field) { // this.field = field; // } // // public String getField() { // return field; // } // // @Override // public void readFrom(StreamInput in) throws IOException { // super.readFrom(in); // field = in.readString(); // } // // @Override // public void writeTo(StreamOutput out) throws IOException { // super.writeTo(out); // out.writeString(field); // } // } // // Path: chapter_17/rest_plugin/src/main/java/org/elasticsearch/action/simple/SimpleResponse.java // public class SimpleResponse extends BroadcastResponse { // // private Set<String> simple; // // SimpleResponse() { // } // // SimpleResponse(int totalShards, int successfulShards, int failedShards, List<ShardOperationFailedException> shardFailures, Set<String> simple) { // super(totalShards, successfulShards, failedShards, shardFailures); // this.simple = simple; // } // // public Set<String> getSimple() { // return simple; // } // // @Override // public void readFrom(StreamInput in) throws IOException { // super.readFrom(in); // int n = in.readInt(); // simple = new HashSet<String>(); // for (int i = 0; i < n; i++) { // simple.add(in.readString()); // } // } // // @Override // public void writeTo(StreamOutput out) throws IOException { // super.writeTo(out); // out.writeInt(simple.size()); // for (String t : simple) { // out.writeString(t); // } // } // } // Path: chapter_17/rest_plugin/src/main/java/org/elasticsearch/rest/RestSimpleAction.java import org.elasticsearch.action.simple.SimpleAction; import org.elasticsearch.action.simple.SimpleRequest; import org.elasticsearch.action.simple.SimpleResponse; import org.elasticsearch.client.Client; import org.elasticsearch.client.node.NodeClient; import org.elasticsearch.common.Strings; import org.elasticsearch.common.inject.Inject; import org.elasticsearch.common.settings.Settings; import org.elasticsearch.common.xcontent.XContentBuilder; import org.elasticsearch.rest.action.RestBuilderListener; import java.io.IOException; import static org.elasticsearch.rest.RestRequest.Method.GET; import static org.elasticsearch.rest.RestRequest.Method.POST; import static org.elasticsearch.rest.RestStatus.OK; package org.elasticsearch.rest; public class RestSimpleAction extends BaseRestHandler { @Inject public RestSimpleAction(Settings settings, Client client, RestController controller) { super(settings); controller.registerHandler(POST, "/_simple", this); controller.registerHandler(POST, "/{index}/_simple", this); controller.registerHandler(POST, "/_simple/{field}", this); controller.registerHandler(GET, "/_simple", this); controller.registerHandler(GET, "/{index}/_simple", this); controller.registerHandler(GET, "/_simple/{field}", this); } @Override protected RestChannelConsumer prepareRequest(RestRequest request, NodeClient client) throws IOException { final SimpleRequest simpleRequest = new SimpleRequest(Strings.splitStringByCommaToArray(request.param("index"))); simpleRequest.setField(request.param("field"));
return channel -> client.execute(SimpleAction.INSTANCE, simpleRequest, new RestBuilderListener<SimpleResponse>(channel){
aparo/elasticsearch-cookbook-third-edition
chapter_17/ingest_plugin/src/main/java/org/elasticsearch/plugin/ingest/MyIngestPlugin.java
// Path: chapter_17/ingest_plugin/src/main/java/com/packtpub/ingest/InitialProcessor.java // public final class InitialProcessor extends AbstractProcessor { // // public static final String TYPE = "initial"; // // private final String field; // private final String targetField; // private final boolean ignoreMissing; // // InitialProcessor(String tag, String field, String targetField, boolean ignoreMissing) { // super(tag); // this.field = field; // this.targetField = targetField; // this.ignoreMissing = ignoreMissing; // } // // String getField() { // return field; // } // // String getTargetField() { // return targetField; // } // // boolean isIgnoreMissing() { // return ignoreMissing; // } // // @Override // public void execute(IngestDocument document) { // if (document.hasField(field, true) == false) { // if (ignoreMissing) { // return; // } else { // throw new IllegalArgumentException("field [" + field + "] doesn't exist"); // } // } // // We fail here if the target field point to an array slot that is out of range. // // If we didn't do this then we would fail if we set the value in the target_field // // and then on failure processors would not see that value we tried to rename as we already // // removed it. // if (document.hasField(targetField, true)) { // throw new IllegalArgumentException("field [" + targetField + "] already exists"); // } // // Object value = document.getFieldValue(field, Object.class); // if( value!=null && value instanceof String ) { // String myValue=value.toString().trim(); // if(myValue.length()>1){ // try { // document.setFieldValue(targetField, myValue.substring(0,1).toLowerCase()); // } catch (Exception e) { // // setting the value back to the original field shouldn't as we just fetched it from that field: // document.setFieldValue(field, value); // throw e; // } // } // } // } // // @Override // public String getType() { // return TYPE; // } // // public static final class Factory implements Processor.Factory { // @Override // public InitialProcessor create(Map<String, Processor.Factory> registry, String processorTag, // Map<String, Object> config) throws Exception { // String field = ConfigurationUtils.readStringProperty(TYPE, processorTag, config, "field"); // String targetField = ConfigurationUtils.readStringProperty(TYPE, processorTag, config, "target_field"); // boolean ignoreMissing = ConfigurationUtils.readBooleanProperty(TYPE, processorTag, config, "ignore_missing", false); // return new InitialProcessor(processorTag, field, targetField, ignoreMissing); // } // } // }
import com.packtpub.ingest.InitialProcessor; import org.elasticsearch.ingest.Processor; import org.elasticsearch.plugins.IngestPlugin; import org.elasticsearch.plugins.Plugin; import java.util.Collections; import java.util.Map;
package org.elasticsearch.plugin.ingest; public class MyIngestPlugin extends Plugin implements IngestPlugin { @Override public Map<String, Processor.Factory> getProcessors(Processor.Parameters parameters) {
// Path: chapter_17/ingest_plugin/src/main/java/com/packtpub/ingest/InitialProcessor.java // public final class InitialProcessor extends AbstractProcessor { // // public static final String TYPE = "initial"; // // private final String field; // private final String targetField; // private final boolean ignoreMissing; // // InitialProcessor(String tag, String field, String targetField, boolean ignoreMissing) { // super(tag); // this.field = field; // this.targetField = targetField; // this.ignoreMissing = ignoreMissing; // } // // String getField() { // return field; // } // // String getTargetField() { // return targetField; // } // // boolean isIgnoreMissing() { // return ignoreMissing; // } // // @Override // public void execute(IngestDocument document) { // if (document.hasField(field, true) == false) { // if (ignoreMissing) { // return; // } else { // throw new IllegalArgumentException("field [" + field + "] doesn't exist"); // } // } // // We fail here if the target field point to an array slot that is out of range. // // If we didn't do this then we would fail if we set the value in the target_field // // and then on failure processors would not see that value we tried to rename as we already // // removed it. // if (document.hasField(targetField, true)) { // throw new IllegalArgumentException("field [" + targetField + "] already exists"); // } // // Object value = document.getFieldValue(field, Object.class); // if( value!=null && value instanceof String ) { // String myValue=value.toString().trim(); // if(myValue.length()>1){ // try { // document.setFieldValue(targetField, myValue.substring(0,1).toLowerCase()); // } catch (Exception e) { // // setting the value back to the original field shouldn't as we just fetched it from that field: // document.setFieldValue(field, value); // throw e; // } // } // } // } // // @Override // public String getType() { // return TYPE; // } // // public static final class Factory implements Processor.Factory { // @Override // public InitialProcessor create(Map<String, Processor.Factory> registry, String processorTag, // Map<String, Object> config) throws Exception { // String field = ConfigurationUtils.readStringProperty(TYPE, processorTag, config, "field"); // String targetField = ConfigurationUtils.readStringProperty(TYPE, processorTag, config, "target_field"); // boolean ignoreMissing = ConfigurationUtils.readBooleanProperty(TYPE, processorTag, config, "ignore_missing", false); // return new InitialProcessor(processorTag, field, targetField, ignoreMissing); // } // } // } // Path: chapter_17/ingest_plugin/src/main/java/org/elasticsearch/plugin/ingest/MyIngestPlugin.java import com.packtpub.ingest.InitialProcessor; import org.elasticsearch.ingest.Processor; import org.elasticsearch.plugins.IngestPlugin; import org.elasticsearch.plugins.Plugin; import java.util.Collections; import java.util.Map; package org.elasticsearch.plugin.ingest; public class MyIngestPlugin extends Plugin implements IngestPlugin { @Override public Map<String, Processor.Factory> getProcessors(Processor.Parameters parameters) {
return Collections.singletonMap(InitialProcessor.TYPE,
Nilhcem/droidconde-2016
app/src/test/java/com/nilhcem/droidconde/ui/schedule/day/ScheduleDayPresenterTest.java
// Path: app/src/main/java/com/nilhcem/droidconde/data/app/model/ScheduleDay.java // @Value // public class ScheduleDay implements Parcelable { // // public static final Parcelable.Creator<ScheduleDay> CREATOR = new Parcelable.Creator<ScheduleDay>() { // public ScheduleDay createFromParcel(Parcel source) { // return new ScheduleDay(source); // } // // public ScheduleDay[] newArray(int size) { // return new ScheduleDay[size]; // } // }; // // LocalDate day; // List<ScheduleSlot> slots; // // public ScheduleDay(LocalDate day, List<ScheduleSlot> slots) { // this.day = day; // this.slots = slots; // } // // protected ScheduleDay(Parcel in) { // day = (LocalDate) in.readSerializable(); // slots = in.createTypedArrayList(ScheduleSlot.CREATOR); // } // // @Override // public int describeContents() { // return 0; // } // // @Override // public void writeToParcel(Parcel dest, int flags) { // dest.writeSerializable(day); // dest.writeTypedList(slots); // } // } // // Path: app/src/main/java/com/nilhcem/droidconde/data/app/model/ScheduleSlot.java // @Value // public class ScheduleSlot implements Parcelable { // // public static final Parcelable.Creator<ScheduleSlot> CREATOR = new Parcelable.Creator<ScheduleSlot>() { // public ScheduleSlot createFromParcel(Parcel source) { // return new ScheduleSlot(source); // } // // public ScheduleSlot[] newArray(int size) { // return new ScheduleSlot[size]; // } // }; // // LocalDateTime time; // List<Session> sessions; // // public ScheduleSlot(LocalDateTime time, List<Session> sessions) { // this.time = time; // this.sessions = sessions; // } // // protected ScheduleSlot(Parcel in) { // time = (LocalDateTime) in.readSerializable(); // sessions = in.createTypedArrayList(Session.CREATOR); // } // // @Override // public int describeContents() { // return 0; // } // // @Override // public void writeToParcel(Parcel dest, int flags) { // dest.writeSerializable(time); // dest.writeTypedList(sessions); // } // }
import android.os.Build; import com.nilhcem.droidconde.BuildConfig; import com.nilhcem.droidconde.data.app.model.ScheduleDay; import com.nilhcem.droidconde.data.app.model.ScheduleSlot; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.Mock; import org.mockito.MockitoAnnotations; import org.robolectric.RobolectricGradleTestRunner; import org.robolectric.annotation.Config; import org.threeten.bp.LocalDate; import java.util.ArrayList; import java.util.List; import static org.mockito.Mockito.verify;
package com.nilhcem.droidconde.ui.schedule.day; @RunWith(RobolectricGradleTestRunner.class) @Config(constants = BuildConfig.class, sdk = Build.VERSION_CODES.LOLLIPOP) public class ScheduleDayPresenterTest { @Mock ScheduleDayMvp.View view; private ScheduleDayPresenter presenter;
// Path: app/src/main/java/com/nilhcem/droidconde/data/app/model/ScheduleDay.java // @Value // public class ScheduleDay implements Parcelable { // // public static final Parcelable.Creator<ScheduleDay> CREATOR = new Parcelable.Creator<ScheduleDay>() { // public ScheduleDay createFromParcel(Parcel source) { // return new ScheduleDay(source); // } // // public ScheduleDay[] newArray(int size) { // return new ScheduleDay[size]; // } // }; // // LocalDate day; // List<ScheduleSlot> slots; // // public ScheduleDay(LocalDate day, List<ScheduleSlot> slots) { // this.day = day; // this.slots = slots; // } // // protected ScheduleDay(Parcel in) { // day = (LocalDate) in.readSerializable(); // slots = in.createTypedArrayList(ScheduleSlot.CREATOR); // } // // @Override // public int describeContents() { // return 0; // } // // @Override // public void writeToParcel(Parcel dest, int flags) { // dest.writeSerializable(day); // dest.writeTypedList(slots); // } // } // // Path: app/src/main/java/com/nilhcem/droidconde/data/app/model/ScheduleSlot.java // @Value // public class ScheduleSlot implements Parcelable { // // public static final Parcelable.Creator<ScheduleSlot> CREATOR = new Parcelable.Creator<ScheduleSlot>() { // public ScheduleSlot createFromParcel(Parcel source) { // return new ScheduleSlot(source); // } // // public ScheduleSlot[] newArray(int size) { // return new ScheduleSlot[size]; // } // }; // // LocalDateTime time; // List<Session> sessions; // // public ScheduleSlot(LocalDateTime time, List<Session> sessions) { // this.time = time; // this.sessions = sessions; // } // // protected ScheduleSlot(Parcel in) { // time = (LocalDateTime) in.readSerializable(); // sessions = in.createTypedArrayList(Session.CREATOR); // } // // @Override // public int describeContents() { // return 0; // } // // @Override // public void writeToParcel(Parcel dest, int flags) { // dest.writeSerializable(time); // dest.writeTypedList(sessions); // } // } // Path: app/src/test/java/com/nilhcem/droidconde/ui/schedule/day/ScheduleDayPresenterTest.java import android.os.Build; import com.nilhcem.droidconde.BuildConfig; import com.nilhcem.droidconde.data.app.model.ScheduleDay; import com.nilhcem.droidconde.data.app.model.ScheduleSlot; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.Mock; import org.mockito.MockitoAnnotations; import org.robolectric.RobolectricGradleTestRunner; import org.robolectric.annotation.Config; import org.threeten.bp.LocalDate; import java.util.ArrayList; import java.util.List; import static org.mockito.Mockito.verify; package com.nilhcem.droidconde.ui.schedule.day; @RunWith(RobolectricGradleTestRunner.class) @Config(constants = BuildConfig.class, sdk = Build.VERSION_CODES.LOLLIPOP) public class ScheduleDayPresenterTest { @Mock ScheduleDayMvp.View view; private ScheduleDayPresenter presenter;
private final List<ScheduleSlot> slots = new ArrayList<>();
Nilhcem/droidconde-2016
app/src/test/java/com/nilhcem/droidconde/ui/schedule/day/ScheduleDayPresenterTest.java
// Path: app/src/main/java/com/nilhcem/droidconde/data/app/model/ScheduleDay.java // @Value // public class ScheduleDay implements Parcelable { // // public static final Parcelable.Creator<ScheduleDay> CREATOR = new Parcelable.Creator<ScheduleDay>() { // public ScheduleDay createFromParcel(Parcel source) { // return new ScheduleDay(source); // } // // public ScheduleDay[] newArray(int size) { // return new ScheduleDay[size]; // } // }; // // LocalDate day; // List<ScheduleSlot> slots; // // public ScheduleDay(LocalDate day, List<ScheduleSlot> slots) { // this.day = day; // this.slots = slots; // } // // protected ScheduleDay(Parcel in) { // day = (LocalDate) in.readSerializable(); // slots = in.createTypedArrayList(ScheduleSlot.CREATOR); // } // // @Override // public int describeContents() { // return 0; // } // // @Override // public void writeToParcel(Parcel dest, int flags) { // dest.writeSerializable(day); // dest.writeTypedList(slots); // } // } // // Path: app/src/main/java/com/nilhcem/droidconde/data/app/model/ScheduleSlot.java // @Value // public class ScheduleSlot implements Parcelable { // // public static final Parcelable.Creator<ScheduleSlot> CREATOR = new Parcelable.Creator<ScheduleSlot>() { // public ScheduleSlot createFromParcel(Parcel source) { // return new ScheduleSlot(source); // } // // public ScheduleSlot[] newArray(int size) { // return new ScheduleSlot[size]; // } // }; // // LocalDateTime time; // List<Session> sessions; // // public ScheduleSlot(LocalDateTime time, List<Session> sessions) { // this.time = time; // this.sessions = sessions; // } // // protected ScheduleSlot(Parcel in) { // time = (LocalDateTime) in.readSerializable(); // sessions = in.createTypedArrayList(Session.CREATOR); // } // // @Override // public int describeContents() { // return 0; // } // // @Override // public void writeToParcel(Parcel dest, int flags) { // dest.writeSerializable(time); // dest.writeTypedList(sessions); // } // }
import android.os.Build; import com.nilhcem.droidconde.BuildConfig; import com.nilhcem.droidconde.data.app.model.ScheduleDay; import com.nilhcem.droidconde.data.app.model.ScheduleSlot; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.Mock; import org.mockito.MockitoAnnotations; import org.robolectric.RobolectricGradleTestRunner; import org.robolectric.annotation.Config; import org.threeten.bp.LocalDate; import java.util.ArrayList; import java.util.List; import static org.mockito.Mockito.verify;
package com.nilhcem.droidconde.ui.schedule.day; @RunWith(RobolectricGradleTestRunner.class) @Config(constants = BuildConfig.class, sdk = Build.VERSION_CODES.LOLLIPOP) public class ScheduleDayPresenterTest { @Mock ScheduleDayMvp.View view; private ScheduleDayPresenter presenter; private final List<ScheduleSlot> slots = new ArrayList<>(); @Before public void setup() { MockitoAnnotations.initMocks(this);
// Path: app/src/main/java/com/nilhcem/droidconde/data/app/model/ScheduleDay.java // @Value // public class ScheduleDay implements Parcelable { // // public static final Parcelable.Creator<ScheduleDay> CREATOR = new Parcelable.Creator<ScheduleDay>() { // public ScheduleDay createFromParcel(Parcel source) { // return new ScheduleDay(source); // } // // public ScheduleDay[] newArray(int size) { // return new ScheduleDay[size]; // } // }; // // LocalDate day; // List<ScheduleSlot> slots; // // public ScheduleDay(LocalDate day, List<ScheduleSlot> slots) { // this.day = day; // this.slots = slots; // } // // protected ScheduleDay(Parcel in) { // day = (LocalDate) in.readSerializable(); // slots = in.createTypedArrayList(ScheduleSlot.CREATOR); // } // // @Override // public int describeContents() { // return 0; // } // // @Override // public void writeToParcel(Parcel dest, int flags) { // dest.writeSerializable(day); // dest.writeTypedList(slots); // } // } // // Path: app/src/main/java/com/nilhcem/droidconde/data/app/model/ScheduleSlot.java // @Value // public class ScheduleSlot implements Parcelable { // // public static final Parcelable.Creator<ScheduleSlot> CREATOR = new Parcelable.Creator<ScheduleSlot>() { // public ScheduleSlot createFromParcel(Parcel source) { // return new ScheduleSlot(source); // } // // public ScheduleSlot[] newArray(int size) { // return new ScheduleSlot[size]; // } // }; // // LocalDateTime time; // List<Session> sessions; // // public ScheduleSlot(LocalDateTime time, List<Session> sessions) { // this.time = time; // this.sessions = sessions; // } // // protected ScheduleSlot(Parcel in) { // time = (LocalDateTime) in.readSerializable(); // sessions = in.createTypedArrayList(Session.CREATOR); // } // // @Override // public int describeContents() { // return 0; // } // // @Override // public void writeToParcel(Parcel dest, int flags) { // dest.writeSerializable(time); // dest.writeTypedList(sessions); // } // } // Path: app/src/test/java/com/nilhcem/droidconde/ui/schedule/day/ScheduleDayPresenterTest.java import android.os.Build; import com.nilhcem.droidconde.BuildConfig; import com.nilhcem.droidconde.data.app.model.ScheduleDay; import com.nilhcem.droidconde.data.app.model.ScheduleSlot; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.Mock; import org.mockito.MockitoAnnotations; import org.robolectric.RobolectricGradleTestRunner; import org.robolectric.annotation.Config; import org.threeten.bp.LocalDate; import java.util.ArrayList; import java.util.List; import static org.mockito.Mockito.verify; package com.nilhcem.droidconde.ui.schedule.day; @RunWith(RobolectricGradleTestRunner.class) @Config(constants = BuildConfig.class, sdk = Build.VERSION_CODES.LOLLIPOP) public class ScheduleDayPresenterTest { @Mock ScheduleDayMvp.View view; private ScheduleDayPresenter presenter; private final List<ScheduleSlot> slots = new ArrayList<>(); @Before public void setup() { MockitoAnnotations.initMocks(this);
ScheduleDay scheduleDay = new ScheduleDay(LocalDate.now(), slots);
Nilhcem/droidconde-2016
app/src/internal/java/com/nilhcem/droidconde/core/dagger/AppComponent.java
// Path: app/src/main/java/com/nilhcem/droidconde/DroidconApp.java // @DebugLog // public class DroidconApp extends Application { // // private AppComponent component; // // public static DroidconApp get(Context context) { // return (DroidconApp) context.getApplicationContext(); // } // // @Override // public void onCreate() { // super.onCreate(); // AndroidThreeTen.init(this); // initGraph(); // initLogger(); // } // // public AppComponent component() { // return component; // } // // private void initGraph() { // component = AppComponent.Initializer.init(this); // } // // private void initLogger() { // Timber.plant(new Timber.DebugTree()); // } // } // // Path: app/src/main/java/com/nilhcem/droidconde/core/dagger/module/ApiModule.java // @Module // public final class ApiModule { // // @Provides @Singleton ApiEndpoint provideApiEndpoint(Application context) { // return ApiEndpoint.get(context); // } // // @Provides @Singleton Retrofit provideRetrofit(OkHttpClient client, Moshi moshi, ApiEndpoint endpoint) { // return new Retrofit.Builder() // .client(client) // .baseUrl(endpoint.url) // .addConverterFactory(MoshiConverterFactory.create(moshi)) // .addCallAdapterFactory(RxJavaCallAdapterFactory.create()) // .build(); // } // // @Provides @Singleton // DroidconService provideDroidconService(Retrofit retrofit) { // return retrofit.create(DroidconService.class); // } // } // // Path: app/src/main/java/com/nilhcem/droidconde/core/dagger/module/AppModule.java // @Module // public final class AppModule { // // private final DroidconApp app; // // public AppModule(DroidconApp app) { // this.app = app; // } // // @Provides @Singleton Application provideApplication() { // return app; // } // } // // Path: app/src/main/java/com/nilhcem/droidconde/core/dagger/module/DataModule.java // @Module(includes = OkHttpModule.class) // public final class DataModule { // // private static final long DISK_CACHE_SIZE = 31_457_280; // 30MB // // @Provides @Singleton SharedPreferences provideSharedPreferences(Application app) { // return PreferenceManager.getDefaultSharedPreferences(app); // } // // @Provides @Singleton Moshi provideMoshi(LocalDateTimeAdapter localDateTimeAdapter) { // return new Moshi.Builder() // .add(localDateTimeAdapter) // .build(); // } // // @Provides @Singleton OkHttpClient.Builder provideOkHttpClientBuilder(Application app) { // File cacheDir = new File(app.getCacheDir(), "http"); // Cache cache = new Cache(cacheDir, DISK_CACHE_SIZE); // return new OkHttpClient.Builder().cache(cache); // } // // @Provides @Singleton Picasso providePicasso(Application app, OkHttpClient client) { // return new Picasso.Builder(app) // .downloader(new OkHttp3Downloader(client)) // .listener((picasso, uri, e) -> Timber.e(e, "Failed to load image: %s", uri)) // .build(); // } // } // // Path: app/src/main/java/com/nilhcem/droidconde/core/dagger/module/DatabaseModule.java // @Module // public class DatabaseModule { // // static final String TAG = "database"; // // @Provides @Singleton SQLiteOpenHelper provideSQLiteOpenHelper(Application application) { // return new DbOpenHelper(application); // } // // @Provides @Singleton SqlBrite provideSqlBrite() { // return SqlBrite.create(Timber.tag(TAG)::v); // } // // @Provides @Singleton BriteDatabase provideBriteDatabase(SqlBrite sqlBrite, SQLiteOpenHelper helper) { // return sqlBrite.wrapDatabaseHelper(helper, Schedulers.immediate()); // } // }
import com.nilhcem.droidconde.DroidconApp; import com.nilhcem.droidconde.core.dagger.module.ApiModule; import com.nilhcem.droidconde.core.dagger.module.AppModule; import com.nilhcem.droidconde.core.dagger.module.DataModule; import com.nilhcem.droidconde.core.dagger.module.DatabaseModule; import javax.inject.Singleton; import dagger.Component;
package com.nilhcem.droidconde.core.dagger; @Singleton @Component(modules = {AppModule.class, ApiModule.class, DataModule.class, DatabaseModule.class}) public interface AppComponent extends InternalAppGraph { /** * An initializer that creates the internal graph from an application. */ final class Initializer { private Initializer() { throw new UnsupportedOperationException(); }
// Path: app/src/main/java/com/nilhcem/droidconde/DroidconApp.java // @DebugLog // public class DroidconApp extends Application { // // private AppComponent component; // // public static DroidconApp get(Context context) { // return (DroidconApp) context.getApplicationContext(); // } // // @Override // public void onCreate() { // super.onCreate(); // AndroidThreeTen.init(this); // initGraph(); // initLogger(); // } // // public AppComponent component() { // return component; // } // // private void initGraph() { // component = AppComponent.Initializer.init(this); // } // // private void initLogger() { // Timber.plant(new Timber.DebugTree()); // } // } // // Path: app/src/main/java/com/nilhcem/droidconde/core/dagger/module/ApiModule.java // @Module // public final class ApiModule { // // @Provides @Singleton ApiEndpoint provideApiEndpoint(Application context) { // return ApiEndpoint.get(context); // } // // @Provides @Singleton Retrofit provideRetrofit(OkHttpClient client, Moshi moshi, ApiEndpoint endpoint) { // return new Retrofit.Builder() // .client(client) // .baseUrl(endpoint.url) // .addConverterFactory(MoshiConverterFactory.create(moshi)) // .addCallAdapterFactory(RxJavaCallAdapterFactory.create()) // .build(); // } // // @Provides @Singleton // DroidconService provideDroidconService(Retrofit retrofit) { // return retrofit.create(DroidconService.class); // } // } // // Path: app/src/main/java/com/nilhcem/droidconde/core/dagger/module/AppModule.java // @Module // public final class AppModule { // // private final DroidconApp app; // // public AppModule(DroidconApp app) { // this.app = app; // } // // @Provides @Singleton Application provideApplication() { // return app; // } // } // // Path: app/src/main/java/com/nilhcem/droidconde/core/dagger/module/DataModule.java // @Module(includes = OkHttpModule.class) // public final class DataModule { // // private static final long DISK_CACHE_SIZE = 31_457_280; // 30MB // // @Provides @Singleton SharedPreferences provideSharedPreferences(Application app) { // return PreferenceManager.getDefaultSharedPreferences(app); // } // // @Provides @Singleton Moshi provideMoshi(LocalDateTimeAdapter localDateTimeAdapter) { // return new Moshi.Builder() // .add(localDateTimeAdapter) // .build(); // } // // @Provides @Singleton OkHttpClient.Builder provideOkHttpClientBuilder(Application app) { // File cacheDir = new File(app.getCacheDir(), "http"); // Cache cache = new Cache(cacheDir, DISK_CACHE_SIZE); // return new OkHttpClient.Builder().cache(cache); // } // // @Provides @Singleton Picasso providePicasso(Application app, OkHttpClient client) { // return new Picasso.Builder(app) // .downloader(new OkHttp3Downloader(client)) // .listener((picasso, uri, e) -> Timber.e(e, "Failed to load image: %s", uri)) // .build(); // } // } // // Path: app/src/main/java/com/nilhcem/droidconde/core/dagger/module/DatabaseModule.java // @Module // public class DatabaseModule { // // static final String TAG = "database"; // // @Provides @Singleton SQLiteOpenHelper provideSQLiteOpenHelper(Application application) { // return new DbOpenHelper(application); // } // // @Provides @Singleton SqlBrite provideSqlBrite() { // return SqlBrite.create(Timber.tag(TAG)::v); // } // // @Provides @Singleton BriteDatabase provideBriteDatabase(SqlBrite sqlBrite, SQLiteOpenHelper helper) { // return sqlBrite.wrapDatabaseHelper(helper, Schedulers.immediate()); // } // } // Path: app/src/internal/java/com/nilhcem/droidconde/core/dagger/AppComponent.java import com.nilhcem.droidconde.DroidconApp; import com.nilhcem.droidconde.core.dagger.module.ApiModule; import com.nilhcem.droidconde.core.dagger.module.AppModule; import com.nilhcem.droidconde.core.dagger.module.DataModule; import com.nilhcem.droidconde.core.dagger.module.DatabaseModule; import javax.inject.Singleton; import dagger.Component; package com.nilhcem.droidconde.core.dagger; @Singleton @Component(modules = {AppModule.class, ApiModule.class, DataModule.class, DatabaseModule.class}) public interface AppComponent extends InternalAppGraph { /** * An initializer that creates the internal graph from an application. */ final class Initializer { private Initializer() { throw new UnsupportedOperationException(); }
public static AppComponent init(DroidconApp app) {
Nilhcem/droidconde-2016
app/src/main/java/com/nilhcem/droidconde/core/dagger/module/AppModule.java
// Path: app/src/main/java/com/nilhcem/droidconde/DroidconApp.java // @DebugLog // public class DroidconApp extends Application { // // private AppComponent component; // // public static DroidconApp get(Context context) { // return (DroidconApp) context.getApplicationContext(); // } // // @Override // public void onCreate() { // super.onCreate(); // AndroidThreeTen.init(this); // initGraph(); // initLogger(); // } // // public AppComponent component() { // return component; // } // // private void initGraph() { // component = AppComponent.Initializer.init(this); // } // // private void initLogger() { // Timber.plant(new Timber.DebugTree()); // } // }
import android.app.Application; import com.nilhcem.droidconde.DroidconApp; import javax.inject.Singleton; import dagger.Module; import dagger.Provides;
package com.nilhcem.droidconde.core.dagger.module; @Module public final class AppModule {
// Path: app/src/main/java/com/nilhcem/droidconde/DroidconApp.java // @DebugLog // public class DroidconApp extends Application { // // private AppComponent component; // // public static DroidconApp get(Context context) { // return (DroidconApp) context.getApplicationContext(); // } // // @Override // public void onCreate() { // super.onCreate(); // AndroidThreeTen.init(this); // initGraph(); // initLogger(); // } // // public AppComponent component() { // return component; // } // // private void initGraph() { // component = AppComponent.Initializer.init(this); // } // // private void initLogger() { // Timber.plant(new Timber.DebugTree()); // } // } // Path: app/src/main/java/com/nilhcem/droidconde/core/dagger/module/AppModule.java import android.app.Application; import com.nilhcem.droidconde.DroidconApp; import javax.inject.Singleton; import dagger.Module; import dagger.Provides; package com.nilhcem.droidconde.core.dagger.module; @Module public final class AppModule {
private final DroidconApp app;
Nilhcem/droidconde-2016
app/src/internal/java/com/nilhcem/droidconde/data/network/ApiEndpoint.java
// Path: app/src/main/java/com/nilhcem/droidconde/utils/Preconditions.java // public final class Preconditions { // // private Preconditions() { // throw new UnsupportedOperationException(); // } // // /** // * Ensures the truth of an expression involving one or more parameters to the calling method. // * // * @param expression a boolean expression // * @throws IllegalArgumentException if {@code expression} is false // */ // public static void checkArgument(boolean expression) { // if (!expression) { // throw new IllegalArgumentException(); // } // } // // public static void checkNotOnMainThread() { // if (BuildConfig.DEBUG && isOnMainThread()) { // throw new IllegalStateException("This method must not be called on the main thread"); // } // } // // private static boolean isOnMainThread() { // return Thread.currentThread() == Looper.getMainLooper().getThread(); // } // }
import android.annotation.SuppressLint; import android.content.Context; import android.content.SharedPreferences; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import com.nilhcem.droidconde.BuildConfig; import com.nilhcem.droidconde.utils.Preconditions; import lombok.ToString;
package com.nilhcem.droidconde.data.network; @ToString public enum ApiEndpoint { PROD(BuildConfig.API_ENDPOINT), MOCK(BuildConfig.MOCK_ENDPOINT), CUSTOM(null); private static final String PREFS_NAME = "api_endpoint"; private static final String PREFS_KEY_NAME = "name"; private static final String PREFS_KEY_URL = "url"; public String url; ApiEndpoint(String url) { this.url = url; } public static ApiEndpoint get(Context context) { SharedPreferences prefs = context.getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE); String prefsName = prefs.getString(PREFS_KEY_NAME, null); if (prefsName != null) { ApiEndpoint endpoint = valueOf(prefsName); if (endpoint == CUSTOM) { endpoint.url = prefs.getString(PREFS_KEY_URL, null); } return endpoint; } return PROD; } public static void persist(Context context, @NonNull ApiEndpoint endpoint) {
// Path: app/src/main/java/com/nilhcem/droidconde/utils/Preconditions.java // public final class Preconditions { // // private Preconditions() { // throw new UnsupportedOperationException(); // } // // /** // * Ensures the truth of an expression involving one or more parameters to the calling method. // * // * @param expression a boolean expression // * @throws IllegalArgumentException if {@code expression} is false // */ // public static void checkArgument(boolean expression) { // if (!expression) { // throw new IllegalArgumentException(); // } // } // // public static void checkNotOnMainThread() { // if (BuildConfig.DEBUG && isOnMainThread()) { // throw new IllegalStateException("This method must not be called on the main thread"); // } // } // // private static boolean isOnMainThread() { // return Thread.currentThread() == Looper.getMainLooper().getThread(); // } // } // Path: app/src/internal/java/com/nilhcem/droidconde/data/network/ApiEndpoint.java import android.annotation.SuppressLint; import android.content.Context; import android.content.SharedPreferences; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import com.nilhcem.droidconde.BuildConfig; import com.nilhcem.droidconde.utils.Preconditions; import lombok.ToString; package com.nilhcem.droidconde.data.network; @ToString public enum ApiEndpoint { PROD(BuildConfig.API_ENDPOINT), MOCK(BuildConfig.MOCK_ENDPOINT), CUSTOM(null); private static final String PREFS_NAME = "api_endpoint"; private static final String PREFS_KEY_NAME = "name"; private static final String PREFS_KEY_URL = "url"; public String url; ApiEndpoint(String url) { this.url = url; } public static ApiEndpoint get(Context context) { SharedPreferences prefs = context.getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE); String prefsName = prefs.getString(PREFS_KEY_NAME, null); if (prefsName != null) { ApiEndpoint endpoint = valueOf(prefsName); if (endpoint == CUSTOM) { endpoint.url = prefs.getString(PREFS_KEY_URL, null); } return endpoint; } return PROD; } public static void persist(Context context, @NonNull ApiEndpoint endpoint) {
Preconditions.checkArgument(endpoint != CUSTOM);
Nilhcem/droidconde-2016
app/src/main/java/com/nilhcem/droidconde/ui/schedule/pager/SchedulePagerPresenter.java
// Path: app/src/main/java/com/nilhcem/droidconde/data/app/DataProvider.java // @Singleton // public class DataProvider { // // private final AppMapper appMapper; // private final NetworkMapper networkMapper; // private final DroidconService service; // private final SpeakersDao speakersDao; // private final SessionsDao sessionsDao; // private final DataProviderCache cache; // // @Inject // public DataProvider(AppMapper appMapper, NetworkMapper networkMapper, DroidconService service, SpeakersDao speakersDao, SessionsDao sessionsDao) { // this.appMapper = appMapper; // this.networkMapper = networkMapper; // this.service = service; // this.speakersDao = speakersDao; // this.sessionsDao = sessionsDao; // this.cache = new DataProviderCache(); // } // // public Observable<Schedule> getSchedule() { // sessionsDao.initSelectedSessionsMemory(); // return getSessions().map(appMapper::toSchedule); // } // // public Observable<List<Speaker>> getSpeakers() { // return Observable.create(subscriber -> speakersDao.getSpeakers().subscribe(speakers -> { // if (!speakers.isEmpty()) { // subscriber.onNext(speakers); // } // // if (!subscriber.isUnsubscribed()) { // getSpeakersFromNetwork(subscriber); // } // subscriber.onCompleted(); // }, subscriber::onError)); // } // // private void getSpeakersFromNetwork(Subscriber<? super List<Speaker>> subscriber) { // List<Speaker> fromCache = cache.getSpeakers(); // if (fromCache == null) { // service.loadSpeakers() // .map(networkMapper::toAppSpeakers) // .subscribe(speakers -> { // subscriber.onNext(speakers); // speakersDao.saveSpeakers(speakers); // cache.saveSpeakers(speakers); // }, throwable -> Timber.e(throwable, "Error getting speakers from network")); // } else { // subscriber.onNext(fromCache); // } // } // // private Observable<List<Session>> getSessions() { // return Observable.create(subscriber -> sessionsDao.getSessions().subscribe(sessions -> { // if (!sessions.isEmpty()) { // subscriber.onNext(sessions); // } // // if (!subscriber.isUnsubscribed()) { // getSessionsFromNetwork(subscriber); // } // subscriber.onCompleted(); // }, subscriber::onError)); // } // // private void getSessionsFromNetwork(Subscriber<? super List<Session>> subscriber) { // List<Session> fromCache = cache.getSessions(); // if (fromCache == null) { // Observable.zip( // service.loadSessions(), // getSpeakers().last().map(appMapper::speakersToMap), // networkMapper::toAppSessions) // .subscribe(sessions -> { // subscriber.onNext(sessions); // sessionsDao.saveSessions(sessions); // cache.saveSessions(sessions); // }, throwable -> Timber.e(throwable, "Error getting sessions from network")); // } else { // subscriber.onNext(fromCache); // } // } // } // // Path: app/src/main/java/com/nilhcem/droidconde/data/app/model/Schedule.java // public class Schedule extends ArrayList<ScheduleDay> implements Parcelable { // // public static final Parcelable.Creator<Schedule> CREATOR = new Parcelable.Creator<Schedule>() { // public Schedule createFromParcel(Parcel source) { // return new Schedule(source); // } // // public Schedule[] newArray(int size) { // return new Schedule[size]; // } // }; // // public Schedule() { // } // // protected Schedule(Parcel in) { // addAll(in.createTypedArrayList(ScheduleDay.CREATOR)); // } // // @Override // public int describeContents() { // return 0; // } // // @Override // public void writeToParcel(Parcel dest, int flags) { // dest.writeTypedList(this); // } // } // // Path: app/src/main/java/com/nilhcem/droidconde/ui/BaseFragmentPresenter.java // public abstract class BaseFragmentPresenter<V> extends BasePresenter<V> { // // public BaseFragmentPresenter(V view) { // super(view); // } // // @CallSuper // public void onCreate(Bundle savedInstanceState) { // if (savedInstanceState != null) { // Icepick.restoreInstanceState(this, savedInstanceState); // } // } // // public void onViewCreated(View view, @Nullable Bundle savedInstanceState) { // // Nothing to do by default // } // // public void onStart() { // // Nothing to do by default // } // // public void onResume() { // // Nothing to do by default // } // // public void onStop() { // // Nothing to do by default // } // // @CallSuper // public void onSaveInstanceState(Bundle outState) { // Icepick.saveInstanceState(this, outState); // } // }
import android.os.Bundle; import android.support.annotation.Nullable; import android.view.View; import com.nilhcem.droidconde.data.app.DataProvider; import com.nilhcem.droidconde.data.app.model.Schedule; import com.nilhcem.droidconde.ui.BaseFragmentPresenter; import icepick.State; import rx.Subscription; import rx.android.schedulers.AndroidSchedulers; import rx.schedulers.Schedulers; import timber.log.Timber;
package com.nilhcem.droidconde.ui.schedule.pager; public class SchedulePagerPresenter extends BaseFragmentPresenter<SchedulePagerMvp.View> implements SchedulePagerMvp.Presenter { @State Schedule schedule;
// Path: app/src/main/java/com/nilhcem/droidconde/data/app/DataProvider.java // @Singleton // public class DataProvider { // // private final AppMapper appMapper; // private final NetworkMapper networkMapper; // private final DroidconService service; // private final SpeakersDao speakersDao; // private final SessionsDao sessionsDao; // private final DataProviderCache cache; // // @Inject // public DataProvider(AppMapper appMapper, NetworkMapper networkMapper, DroidconService service, SpeakersDao speakersDao, SessionsDao sessionsDao) { // this.appMapper = appMapper; // this.networkMapper = networkMapper; // this.service = service; // this.speakersDao = speakersDao; // this.sessionsDao = sessionsDao; // this.cache = new DataProviderCache(); // } // // public Observable<Schedule> getSchedule() { // sessionsDao.initSelectedSessionsMemory(); // return getSessions().map(appMapper::toSchedule); // } // // public Observable<List<Speaker>> getSpeakers() { // return Observable.create(subscriber -> speakersDao.getSpeakers().subscribe(speakers -> { // if (!speakers.isEmpty()) { // subscriber.onNext(speakers); // } // // if (!subscriber.isUnsubscribed()) { // getSpeakersFromNetwork(subscriber); // } // subscriber.onCompleted(); // }, subscriber::onError)); // } // // private void getSpeakersFromNetwork(Subscriber<? super List<Speaker>> subscriber) { // List<Speaker> fromCache = cache.getSpeakers(); // if (fromCache == null) { // service.loadSpeakers() // .map(networkMapper::toAppSpeakers) // .subscribe(speakers -> { // subscriber.onNext(speakers); // speakersDao.saveSpeakers(speakers); // cache.saveSpeakers(speakers); // }, throwable -> Timber.e(throwable, "Error getting speakers from network")); // } else { // subscriber.onNext(fromCache); // } // } // // private Observable<List<Session>> getSessions() { // return Observable.create(subscriber -> sessionsDao.getSessions().subscribe(sessions -> { // if (!sessions.isEmpty()) { // subscriber.onNext(sessions); // } // // if (!subscriber.isUnsubscribed()) { // getSessionsFromNetwork(subscriber); // } // subscriber.onCompleted(); // }, subscriber::onError)); // } // // private void getSessionsFromNetwork(Subscriber<? super List<Session>> subscriber) { // List<Session> fromCache = cache.getSessions(); // if (fromCache == null) { // Observable.zip( // service.loadSessions(), // getSpeakers().last().map(appMapper::speakersToMap), // networkMapper::toAppSessions) // .subscribe(sessions -> { // subscriber.onNext(sessions); // sessionsDao.saveSessions(sessions); // cache.saveSessions(sessions); // }, throwable -> Timber.e(throwable, "Error getting sessions from network")); // } else { // subscriber.onNext(fromCache); // } // } // } // // Path: app/src/main/java/com/nilhcem/droidconde/data/app/model/Schedule.java // public class Schedule extends ArrayList<ScheduleDay> implements Parcelable { // // public static final Parcelable.Creator<Schedule> CREATOR = new Parcelable.Creator<Schedule>() { // public Schedule createFromParcel(Parcel source) { // return new Schedule(source); // } // // public Schedule[] newArray(int size) { // return new Schedule[size]; // } // }; // // public Schedule() { // } // // protected Schedule(Parcel in) { // addAll(in.createTypedArrayList(ScheduleDay.CREATOR)); // } // // @Override // public int describeContents() { // return 0; // } // // @Override // public void writeToParcel(Parcel dest, int flags) { // dest.writeTypedList(this); // } // } // // Path: app/src/main/java/com/nilhcem/droidconde/ui/BaseFragmentPresenter.java // public abstract class BaseFragmentPresenter<V> extends BasePresenter<V> { // // public BaseFragmentPresenter(V view) { // super(view); // } // // @CallSuper // public void onCreate(Bundle savedInstanceState) { // if (savedInstanceState != null) { // Icepick.restoreInstanceState(this, savedInstanceState); // } // } // // public void onViewCreated(View view, @Nullable Bundle savedInstanceState) { // // Nothing to do by default // } // // public void onStart() { // // Nothing to do by default // } // // public void onResume() { // // Nothing to do by default // } // // public void onStop() { // // Nothing to do by default // } // // @CallSuper // public void onSaveInstanceState(Bundle outState) { // Icepick.saveInstanceState(this, outState); // } // } // Path: app/src/main/java/com/nilhcem/droidconde/ui/schedule/pager/SchedulePagerPresenter.java import android.os.Bundle; import android.support.annotation.Nullable; import android.view.View; import com.nilhcem.droidconde.data.app.DataProvider; import com.nilhcem.droidconde.data.app.model.Schedule; import com.nilhcem.droidconde.ui.BaseFragmentPresenter; import icepick.State; import rx.Subscription; import rx.android.schedulers.AndroidSchedulers; import rx.schedulers.Schedulers; import timber.log.Timber; package com.nilhcem.droidconde.ui.schedule.pager; public class SchedulePagerPresenter extends BaseFragmentPresenter<SchedulePagerMvp.View> implements SchedulePagerMvp.Presenter { @State Schedule schedule;
private final DataProvider dataProvider;
Nilhcem/droidconde-2016
app/src/main/java/com/nilhcem/droidconde/ui/schedule/day/ScheduleDayEntrySpeaker.java
// Path: app/src/main/java/com/nilhcem/droidconde/data/app/model/Speaker.java // @Value // public class Speaker implements Parcelable { // // public static final Parcelable.Creator<Speaker> CREATOR = new Parcelable.Creator<Speaker>() { // public Speaker createFromParcel(Parcel source) { // return new Speaker(source); // } // // public Speaker[] newArray(int size) { // return new Speaker[size]; // } // }; // // int id; // String name; // String title; // String bio; // String website; // String twitter; // String github; // String photo; // // public Speaker(int id, String name, String title, String bio, String website, String twitter, String github, String photo) { // this.id = id; // this.name = name; // this.title = title; // this.bio = bio; // this.website = website; // this.twitter = twitter; // this.github = github; // this.photo = photo; // } // // protected Speaker(Parcel in) { // id = in.readInt(); // name = in.readString(); // title = in.readString(); // bio = in.readString(); // website = in.readString(); // twitter = in.readString(); // github = in.readString(); // photo = in.readString(); // } // // @Override // public int describeContents() { // return 0; // } // // @Override // public void writeToParcel(Parcel dest, int flags) { // dest.writeInt(id); // dest.writeString(name); // dest.writeString(title); // dest.writeString(bio); // dest.writeString(website); // dest.writeString(twitter); // dest.writeString(github); // dest.writeString(photo); // } // } // // Path: app/src/main/java/com/nilhcem/droidconde/ui/core/picasso/CircleTransformation.java // public class CircleTransformation implements Transformation { // // @Override // public Bitmap transform(Bitmap source) { // int size = Math.min(source.getWidth(), source.getHeight()); // // int x = (source.getWidth() - size) / 2; // int y = (source.getHeight() - size) / 2; // // Bitmap squaredBitmap = Bitmap.createBitmap(source, x, y, size, size); // if (squaredBitmap != source) { // source.recycle(); // } // // Bitmap.Config config = source.getConfig() != null ? source.getConfig() : Bitmap.Config.ARGB_8888; // Bitmap bitmap = Bitmap.createBitmap(size, size, config); // // Canvas canvas = new Canvas(bitmap); // Paint paint = new Paint(); // BitmapShader shader = new BitmapShader(squaredBitmap, BitmapShader.TileMode.CLAMP, BitmapShader.TileMode.CLAMP); // paint.setShader(shader); // paint.setAntiAlias(true); // // float r = size / 2f; // canvas.drawCircle(r, r, r, paint); // // squaredBitmap.recycle(); // return bitmap; // } // // @Override // public String key() { // return "circle"; // } // }
import android.content.Context; import android.text.TextUtils; import android.util.TypedValue; import android.view.LayoutInflater; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.TextView; import com.nilhcem.droidconde.R; import com.nilhcem.droidconde.data.app.model.Speaker; import com.nilhcem.droidconde.ui.core.picasso.CircleTransformation; import com.squareup.picasso.Picasso; import butterknife.BindView; import butterknife.ButterKnife;
package com.nilhcem.droidconde.ui.schedule.day; public class ScheduleDayEntrySpeaker extends LinearLayout { @BindView(R.id.schedule_day_entry_speaker_photo) ImageView photo; @BindView(R.id.schedule_day_entry_speaker_name) TextView name;
// Path: app/src/main/java/com/nilhcem/droidconde/data/app/model/Speaker.java // @Value // public class Speaker implements Parcelable { // // public static final Parcelable.Creator<Speaker> CREATOR = new Parcelable.Creator<Speaker>() { // public Speaker createFromParcel(Parcel source) { // return new Speaker(source); // } // // public Speaker[] newArray(int size) { // return new Speaker[size]; // } // }; // // int id; // String name; // String title; // String bio; // String website; // String twitter; // String github; // String photo; // // public Speaker(int id, String name, String title, String bio, String website, String twitter, String github, String photo) { // this.id = id; // this.name = name; // this.title = title; // this.bio = bio; // this.website = website; // this.twitter = twitter; // this.github = github; // this.photo = photo; // } // // protected Speaker(Parcel in) { // id = in.readInt(); // name = in.readString(); // title = in.readString(); // bio = in.readString(); // website = in.readString(); // twitter = in.readString(); // github = in.readString(); // photo = in.readString(); // } // // @Override // public int describeContents() { // return 0; // } // // @Override // public void writeToParcel(Parcel dest, int flags) { // dest.writeInt(id); // dest.writeString(name); // dest.writeString(title); // dest.writeString(bio); // dest.writeString(website); // dest.writeString(twitter); // dest.writeString(github); // dest.writeString(photo); // } // } // // Path: app/src/main/java/com/nilhcem/droidconde/ui/core/picasso/CircleTransformation.java // public class CircleTransformation implements Transformation { // // @Override // public Bitmap transform(Bitmap source) { // int size = Math.min(source.getWidth(), source.getHeight()); // // int x = (source.getWidth() - size) / 2; // int y = (source.getHeight() - size) / 2; // // Bitmap squaredBitmap = Bitmap.createBitmap(source, x, y, size, size); // if (squaredBitmap != source) { // source.recycle(); // } // // Bitmap.Config config = source.getConfig() != null ? source.getConfig() : Bitmap.Config.ARGB_8888; // Bitmap bitmap = Bitmap.createBitmap(size, size, config); // // Canvas canvas = new Canvas(bitmap); // Paint paint = new Paint(); // BitmapShader shader = new BitmapShader(squaredBitmap, BitmapShader.TileMode.CLAMP, BitmapShader.TileMode.CLAMP); // paint.setShader(shader); // paint.setAntiAlias(true); // // float r = size / 2f; // canvas.drawCircle(r, r, r, paint); // // squaredBitmap.recycle(); // return bitmap; // } // // @Override // public String key() { // return "circle"; // } // } // Path: app/src/main/java/com/nilhcem/droidconde/ui/schedule/day/ScheduleDayEntrySpeaker.java import android.content.Context; import android.text.TextUtils; import android.util.TypedValue; import android.view.LayoutInflater; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.TextView; import com.nilhcem.droidconde.R; import com.nilhcem.droidconde.data.app.model.Speaker; import com.nilhcem.droidconde.ui.core.picasso.CircleTransformation; import com.squareup.picasso.Picasso; import butterknife.BindView; import butterknife.ButterKnife; package com.nilhcem.droidconde.ui.schedule.day; public class ScheduleDayEntrySpeaker extends LinearLayout { @BindView(R.id.schedule_day_entry_speaker_photo) ImageView photo; @BindView(R.id.schedule_day_entry_speaker_name) TextView name;
public ScheduleDayEntrySpeaker(Context context, Speaker speaker, Picasso picasso) {
Nilhcem/droidconde-2016
app/src/main/java/com/nilhcem/droidconde/ui/schedule/day/ScheduleDayEntrySpeaker.java
// Path: app/src/main/java/com/nilhcem/droidconde/data/app/model/Speaker.java // @Value // public class Speaker implements Parcelable { // // public static final Parcelable.Creator<Speaker> CREATOR = new Parcelable.Creator<Speaker>() { // public Speaker createFromParcel(Parcel source) { // return new Speaker(source); // } // // public Speaker[] newArray(int size) { // return new Speaker[size]; // } // }; // // int id; // String name; // String title; // String bio; // String website; // String twitter; // String github; // String photo; // // public Speaker(int id, String name, String title, String bio, String website, String twitter, String github, String photo) { // this.id = id; // this.name = name; // this.title = title; // this.bio = bio; // this.website = website; // this.twitter = twitter; // this.github = github; // this.photo = photo; // } // // protected Speaker(Parcel in) { // id = in.readInt(); // name = in.readString(); // title = in.readString(); // bio = in.readString(); // website = in.readString(); // twitter = in.readString(); // github = in.readString(); // photo = in.readString(); // } // // @Override // public int describeContents() { // return 0; // } // // @Override // public void writeToParcel(Parcel dest, int flags) { // dest.writeInt(id); // dest.writeString(name); // dest.writeString(title); // dest.writeString(bio); // dest.writeString(website); // dest.writeString(twitter); // dest.writeString(github); // dest.writeString(photo); // } // } // // Path: app/src/main/java/com/nilhcem/droidconde/ui/core/picasso/CircleTransformation.java // public class CircleTransformation implements Transformation { // // @Override // public Bitmap transform(Bitmap source) { // int size = Math.min(source.getWidth(), source.getHeight()); // // int x = (source.getWidth() - size) / 2; // int y = (source.getHeight() - size) / 2; // // Bitmap squaredBitmap = Bitmap.createBitmap(source, x, y, size, size); // if (squaredBitmap != source) { // source.recycle(); // } // // Bitmap.Config config = source.getConfig() != null ? source.getConfig() : Bitmap.Config.ARGB_8888; // Bitmap bitmap = Bitmap.createBitmap(size, size, config); // // Canvas canvas = new Canvas(bitmap); // Paint paint = new Paint(); // BitmapShader shader = new BitmapShader(squaredBitmap, BitmapShader.TileMode.CLAMP, BitmapShader.TileMode.CLAMP); // paint.setShader(shader); // paint.setAntiAlias(true); // // float r = size / 2f; // canvas.drawCircle(r, r, r, paint); // // squaredBitmap.recycle(); // return bitmap; // } // // @Override // public String key() { // return "circle"; // } // }
import android.content.Context; import android.text.TextUtils; import android.util.TypedValue; import android.view.LayoutInflater; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.TextView; import com.nilhcem.droidconde.R; import com.nilhcem.droidconde.data.app.model.Speaker; import com.nilhcem.droidconde.ui.core.picasso.CircleTransformation; import com.squareup.picasso.Picasso; import butterknife.BindView; import butterknife.ButterKnife;
package com.nilhcem.droidconde.ui.schedule.day; public class ScheduleDayEntrySpeaker extends LinearLayout { @BindView(R.id.schedule_day_entry_speaker_photo) ImageView photo; @BindView(R.id.schedule_day_entry_speaker_name) TextView name; public ScheduleDayEntrySpeaker(Context context, Speaker speaker, Picasso picasso) { super(context); setOrientation(HORIZONTAL); int padding = Math.round(TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 4, context.getResources().getDisplayMetrics())); setPadding(0, padding, 0, padding); LayoutInflater.from(context).inflate(R.layout.schedule_day_entry_speaker, this); ButterKnife.bind(this, this); bind(speaker, picasso); } private void bind(Speaker speaker, Picasso picasso) { String photoUrl = speaker.getPhoto(); if (!TextUtils.isEmpty(photoUrl)) {
// Path: app/src/main/java/com/nilhcem/droidconde/data/app/model/Speaker.java // @Value // public class Speaker implements Parcelable { // // public static final Parcelable.Creator<Speaker> CREATOR = new Parcelable.Creator<Speaker>() { // public Speaker createFromParcel(Parcel source) { // return new Speaker(source); // } // // public Speaker[] newArray(int size) { // return new Speaker[size]; // } // }; // // int id; // String name; // String title; // String bio; // String website; // String twitter; // String github; // String photo; // // public Speaker(int id, String name, String title, String bio, String website, String twitter, String github, String photo) { // this.id = id; // this.name = name; // this.title = title; // this.bio = bio; // this.website = website; // this.twitter = twitter; // this.github = github; // this.photo = photo; // } // // protected Speaker(Parcel in) { // id = in.readInt(); // name = in.readString(); // title = in.readString(); // bio = in.readString(); // website = in.readString(); // twitter = in.readString(); // github = in.readString(); // photo = in.readString(); // } // // @Override // public int describeContents() { // return 0; // } // // @Override // public void writeToParcel(Parcel dest, int flags) { // dest.writeInt(id); // dest.writeString(name); // dest.writeString(title); // dest.writeString(bio); // dest.writeString(website); // dest.writeString(twitter); // dest.writeString(github); // dest.writeString(photo); // } // } // // Path: app/src/main/java/com/nilhcem/droidconde/ui/core/picasso/CircleTransformation.java // public class CircleTransformation implements Transformation { // // @Override // public Bitmap transform(Bitmap source) { // int size = Math.min(source.getWidth(), source.getHeight()); // // int x = (source.getWidth() - size) / 2; // int y = (source.getHeight() - size) / 2; // // Bitmap squaredBitmap = Bitmap.createBitmap(source, x, y, size, size); // if (squaredBitmap != source) { // source.recycle(); // } // // Bitmap.Config config = source.getConfig() != null ? source.getConfig() : Bitmap.Config.ARGB_8888; // Bitmap bitmap = Bitmap.createBitmap(size, size, config); // // Canvas canvas = new Canvas(bitmap); // Paint paint = new Paint(); // BitmapShader shader = new BitmapShader(squaredBitmap, BitmapShader.TileMode.CLAMP, BitmapShader.TileMode.CLAMP); // paint.setShader(shader); // paint.setAntiAlias(true); // // float r = size / 2f; // canvas.drawCircle(r, r, r, paint); // // squaredBitmap.recycle(); // return bitmap; // } // // @Override // public String key() { // return "circle"; // } // } // Path: app/src/main/java/com/nilhcem/droidconde/ui/schedule/day/ScheduleDayEntrySpeaker.java import android.content.Context; import android.text.TextUtils; import android.util.TypedValue; import android.view.LayoutInflater; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.TextView; import com.nilhcem.droidconde.R; import com.nilhcem.droidconde.data.app.model.Speaker; import com.nilhcem.droidconde.ui.core.picasso.CircleTransformation; import com.squareup.picasso.Picasso; import butterknife.BindView; import butterknife.ButterKnife; package com.nilhcem.droidconde.ui.schedule.day; public class ScheduleDayEntrySpeaker extends LinearLayout { @BindView(R.id.schedule_day_entry_speaker_photo) ImageView photo; @BindView(R.id.schedule_day_entry_speaker_name) TextView name; public ScheduleDayEntrySpeaker(Context context, Speaker speaker, Picasso picasso) { super(context); setOrientation(HORIZONTAL); int padding = Math.round(TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 4, context.getResources().getDisplayMetrics())); setPadding(0, padding, 0, padding); LayoutInflater.from(context).inflate(R.layout.schedule_day_entry_speaker, this); ButterKnife.bind(this, this); bind(speaker, picasso); } private void bind(Speaker speaker, Picasso picasso) { String photoUrl = speaker.getPhoto(); if (!TextUtils.isEmpty(photoUrl)) {
picasso.load(photoUrl).transform(new CircleTransformation()).into(photo);
Nilhcem/droidconde-2016
app/src/main/java/com/nilhcem/droidconde/core/dagger/module/DataModule.java
// Path: app/src/internal/java/com/nilhcem/droidconde/core/dagger/OkHttpModule.java // @Module // public class OkHttpModule { // // @Provides @Singleton OkHttpClient provideOkHttpClient(OkHttpClient.Builder builder) { // return builder.addNetworkInterceptor(new StethoInterceptor()).build(); // } // } // // Path: app/src/main/java/com/nilhcem/droidconde/core/moshi/LocalDateTimeAdapter.java // @Singleton // public class LocalDateTimeAdapter { // // private final DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm", Locale.US); // // @Inject // public LocalDateTimeAdapter() { // } // // @ToJson // public String toText(LocalDateTime dateTime) { // return dateTime.format(formatter); // } // // @FromJson // public LocalDateTime fromText(String text) { // return LocalDateTime.parse(text, formatter); // } // }
import android.app.Application; import android.content.SharedPreferences; import android.support.v7.preference.PreferenceManager; import com.jakewharton.picasso.OkHttp3Downloader; import com.nilhcem.droidconde.core.dagger.OkHttpModule; import com.nilhcem.droidconde.core.moshi.LocalDateTimeAdapter; import com.squareup.moshi.Moshi; import com.squareup.picasso.Picasso; import java.io.File; import javax.inject.Singleton; import dagger.Module; import dagger.Provides; import okhttp3.Cache; import okhttp3.OkHttpClient; import timber.log.Timber;
package com.nilhcem.droidconde.core.dagger.module; @Module(includes = OkHttpModule.class) public final class DataModule { private static final long DISK_CACHE_SIZE = 31_457_280; // 30MB @Provides @Singleton SharedPreferences provideSharedPreferences(Application app) { return PreferenceManager.getDefaultSharedPreferences(app); }
// Path: app/src/internal/java/com/nilhcem/droidconde/core/dagger/OkHttpModule.java // @Module // public class OkHttpModule { // // @Provides @Singleton OkHttpClient provideOkHttpClient(OkHttpClient.Builder builder) { // return builder.addNetworkInterceptor(new StethoInterceptor()).build(); // } // } // // Path: app/src/main/java/com/nilhcem/droidconde/core/moshi/LocalDateTimeAdapter.java // @Singleton // public class LocalDateTimeAdapter { // // private final DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm", Locale.US); // // @Inject // public LocalDateTimeAdapter() { // } // // @ToJson // public String toText(LocalDateTime dateTime) { // return dateTime.format(formatter); // } // // @FromJson // public LocalDateTime fromText(String text) { // return LocalDateTime.parse(text, formatter); // } // } // Path: app/src/main/java/com/nilhcem/droidconde/core/dagger/module/DataModule.java import android.app.Application; import android.content.SharedPreferences; import android.support.v7.preference.PreferenceManager; import com.jakewharton.picasso.OkHttp3Downloader; import com.nilhcem.droidconde.core.dagger.OkHttpModule; import com.nilhcem.droidconde.core.moshi.LocalDateTimeAdapter; import com.squareup.moshi.Moshi; import com.squareup.picasso.Picasso; import java.io.File; import javax.inject.Singleton; import dagger.Module; import dagger.Provides; import okhttp3.Cache; import okhttp3.OkHttpClient; import timber.log.Timber; package com.nilhcem.droidconde.core.dagger.module; @Module(includes = OkHttpModule.class) public final class DataModule { private static final long DISK_CACHE_SIZE = 31_457_280; // 30MB @Provides @Singleton SharedPreferences provideSharedPreferences(Application app) { return PreferenceManager.getDefaultSharedPreferences(app); }
@Provides @Singleton Moshi provideMoshi(LocalDateTimeAdapter localDateTimeAdapter) {
Nilhcem/droidconde-2016
app/src/main/java/com/nilhcem/droidconde/ui/schedule/day/ScheduleDayFragmentAdapterMySessions.java
// Path: app/src/main/java/com/nilhcem/droidconde/data/app/SelectedSessionsMemory.java // @Singleton // public class SelectedSessionsMemory { // // private final Map<LocalDateTime, Integer> selectedSessions = new ConcurrentHashMap<>(); // // @Inject // public SelectedSessionsMemory() { // } // // public boolean isSelected(Session session) { // Integer sessionId = selectedSessions.get(session.getFromTime()); // return sessionId != null && session.getId() == sessionId; // } // // public void setSelectedSessions(Map<LocalDateTime, Integer> selectedSessions) { // this.selectedSessions.clear(); // this.selectedSessions.putAll(selectedSessions); // } // // public Integer get(LocalDateTime slotTime) { // return selectedSessions.get(slotTime); // } // // public void toggleSessionState(com.nilhcem.droidconde.data.app.model.Session session, boolean insert) { // selectedSessions.remove(session.getFromTime()); // if (insert) { // selectedSessions.put(session.getFromTime(), session.getId()); // } // } // } // // Path: app/src/main/java/com/nilhcem/droidconde/data/app/model/Room.java // public enum Room { // // NONE(0, ""), // STAGE_1(1, "Stage 1"), // STAGE_2(2, "Stage 2"), // STAGE_3(3, "Stage 3"), // STAGE_4(4, "Stage 4"), // WORKSPACE(5, "Workspace"); // // public final int id; // public final String label; // // Room(int id, String label) { // this.id = id; // this.label = label; // } // // public static Room getFromId(int id) { // for (Room room : Room.values()) { // if (room.id == id) { // return room; // } // } // return NONE; // } // // public static Room getFromLabel(@NonNull String label) { // for (Room room : Room.values()) { // if (label.equals(room.label)) { // return room; // } // } // return NONE; // } // } // // Path: app/src/main/java/com/nilhcem/droidconde/data/app/model/ScheduleSlot.java // @Value // public class ScheduleSlot implements Parcelable { // // public static final Parcelable.Creator<ScheduleSlot> CREATOR = new Parcelable.Creator<ScheduleSlot>() { // public ScheduleSlot createFromParcel(Parcel source) { // return new ScheduleSlot(source); // } // // public ScheduleSlot[] newArray(int size) { // return new ScheduleSlot[size]; // } // }; // // LocalDateTime time; // List<Session> sessions; // // public ScheduleSlot(LocalDateTime time, List<Session> sessions) { // this.time = time; // this.sessions = sessions; // } // // protected ScheduleSlot(Parcel in) { // time = (LocalDateTime) in.readSerializable(); // sessions = in.createTypedArrayList(Session.CREATOR); // } // // @Override // public int describeContents() { // return 0; // } // // @Override // public void writeToParcel(Parcel dest, int flags) { // dest.writeSerializable(time); // dest.writeTypedList(sessions); // } // } // // Path: app/src/main/java/com/nilhcem/droidconde/data/app/model/Session.java // @Value // public class Session implements Parcelable { // // public static final Parcelable.Creator<Session> CREATOR = new Parcelable.Creator<Session>() { // public Session createFromParcel(Parcel source) { // return new Session(source); // } // // public Session[] newArray(int size) { // return new Session[size]; // } // }; // // int id; // String room; // List<Speaker> speakers; // String title; // String description; // LocalDateTime fromTime; // LocalDateTime toTime; // // public Session(int id, String room, List<Speaker> speakers, String title, String description, LocalDateTime fromTime, LocalDateTime toTime) { // this.id = id; // this.room = room; // this.speakers = speakers; // this.title = title; // this.description = description; // this.fromTime = fromTime; // this.toTime = toTime; // } // // protected Session(Parcel in) { // id = in.readInt(); // room = in.readString(); // speakers = in.createTypedArrayList(Speaker.CREATOR); // title = in.readString(); // description = in.readString(); // fromTime = (LocalDateTime) in.readSerializable(); // toTime = (LocalDateTime) in.readSerializable(); // } // // @Override // public int describeContents() { // return 0; // } // // @Override // public void writeToParcel(Parcel dest, int flags) { // dest.writeInt(id); // dest.writeString(room); // dest.writeTypedList(speakers); // dest.writeString(title); // dest.writeString(description); // dest.writeSerializable(fromTime); // dest.writeSerializable(toTime); // } // }
import android.support.v7.widget.RecyclerView; import android.view.ViewGroup; import com.nilhcem.droidconde.data.app.SelectedSessionsMemory; import com.nilhcem.droidconde.data.app.model.Room; import com.nilhcem.droidconde.data.app.model.ScheduleSlot; import com.nilhcem.droidconde.data.app.model.Session; import com.squareup.picasso.Picasso; import org.threeten.bp.LocalDateTime; import java.util.List; import static java8.util.stream.StreamSupport.stream;
package com.nilhcem.droidconde.ui.schedule.day; public class ScheduleDayFragmentAdapterMySessions extends RecyclerView.Adapter<ScheduleDayEntry> { private final List<ScheduleSlot> slots;
// Path: app/src/main/java/com/nilhcem/droidconde/data/app/SelectedSessionsMemory.java // @Singleton // public class SelectedSessionsMemory { // // private final Map<LocalDateTime, Integer> selectedSessions = new ConcurrentHashMap<>(); // // @Inject // public SelectedSessionsMemory() { // } // // public boolean isSelected(Session session) { // Integer sessionId = selectedSessions.get(session.getFromTime()); // return sessionId != null && session.getId() == sessionId; // } // // public void setSelectedSessions(Map<LocalDateTime, Integer> selectedSessions) { // this.selectedSessions.clear(); // this.selectedSessions.putAll(selectedSessions); // } // // public Integer get(LocalDateTime slotTime) { // return selectedSessions.get(slotTime); // } // // public void toggleSessionState(com.nilhcem.droidconde.data.app.model.Session session, boolean insert) { // selectedSessions.remove(session.getFromTime()); // if (insert) { // selectedSessions.put(session.getFromTime(), session.getId()); // } // } // } // // Path: app/src/main/java/com/nilhcem/droidconde/data/app/model/Room.java // public enum Room { // // NONE(0, ""), // STAGE_1(1, "Stage 1"), // STAGE_2(2, "Stage 2"), // STAGE_3(3, "Stage 3"), // STAGE_4(4, "Stage 4"), // WORKSPACE(5, "Workspace"); // // public final int id; // public final String label; // // Room(int id, String label) { // this.id = id; // this.label = label; // } // // public static Room getFromId(int id) { // for (Room room : Room.values()) { // if (room.id == id) { // return room; // } // } // return NONE; // } // // public static Room getFromLabel(@NonNull String label) { // for (Room room : Room.values()) { // if (label.equals(room.label)) { // return room; // } // } // return NONE; // } // } // // Path: app/src/main/java/com/nilhcem/droidconde/data/app/model/ScheduleSlot.java // @Value // public class ScheduleSlot implements Parcelable { // // public static final Parcelable.Creator<ScheduleSlot> CREATOR = new Parcelable.Creator<ScheduleSlot>() { // public ScheduleSlot createFromParcel(Parcel source) { // return new ScheduleSlot(source); // } // // public ScheduleSlot[] newArray(int size) { // return new ScheduleSlot[size]; // } // }; // // LocalDateTime time; // List<Session> sessions; // // public ScheduleSlot(LocalDateTime time, List<Session> sessions) { // this.time = time; // this.sessions = sessions; // } // // protected ScheduleSlot(Parcel in) { // time = (LocalDateTime) in.readSerializable(); // sessions = in.createTypedArrayList(Session.CREATOR); // } // // @Override // public int describeContents() { // return 0; // } // // @Override // public void writeToParcel(Parcel dest, int flags) { // dest.writeSerializable(time); // dest.writeTypedList(sessions); // } // } // // Path: app/src/main/java/com/nilhcem/droidconde/data/app/model/Session.java // @Value // public class Session implements Parcelable { // // public static final Parcelable.Creator<Session> CREATOR = new Parcelable.Creator<Session>() { // public Session createFromParcel(Parcel source) { // return new Session(source); // } // // public Session[] newArray(int size) { // return new Session[size]; // } // }; // // int id; // String room; // List<Speaker> speakers; // String title; // String description; // LocalDateTime fromTime; // LocalDateTime toTime; // // public Session(int id, String room, List<Speaker> speakers, String title, String description, LocalDateTime fromTime, LocalDateTime toTime) { // this.id = id; // this.room = room; // this.speakers = speakers; // this.title = title; // this.description = description; // this.fromTime = fromTime; // this.toTime = toTime; // } // // protected Session(Parcel in) { // id = in.readInt(); // room = in.readString(); // speakers = in.createTypedArrayList(Speaker.CREATOR); // title = in.readString(); // description = in.readString(); // fromTime = (LocalDateTime) in.readSerializable(); // toTime = (LocalDateTime) in.readSerializable(); // } // // @Override // public int describeContents() { // return 0; // } // // @Override // public void writeToParcel(Parcel dest, int flags) { // dest.writeInt(id); // dest.writeString(room); // dest.writeTypedList(speakers); // dest.writeString(title); // dest.writeString(description); // dest.writeSerializable(fromTime); // dest.writeSerializable(toTime); // } // } // Path: app/src/main/java/com/nilhcem/droidconde/ui/schedule/day/ScheduleDayFragmentAdapterMySessions.java import android.support.v7.widget.RecyclerView; import android.view.ViewGroup; import com.nilhcem.droidconde.data.app.SelectedSessionsMemory; import com.nilhcem.droidconde.data.app.model.Room; import com.nilhcem.droidconde.data.app.model.ScheduleSlot; import com.nilhcem.droidconde.data.app.model.Session; import com.squareup.picasso.Picasso; import org.threeten.bp.LocalDateTime; import java.util.List; import static java8.util.stream.StreamSupport.stream; package com.nilhcem.droidconde.ui.schedule.day; public class ScheduleDayFragmentAdapterMySessions extends RecyclerView.Adapter<ScheduleDayEntry> { private final List<ScheduleSlot> slots;
private final SelectedSessionsMemory selectedSessionsMemory;
Nilhcem/droidconde-2016
app/src/main/java/com/nilhcem/droidconde/ui/settings/SettingsPresenter.java
// Path: app/src/main/java/com/nilhcem/droidconde/receiver/BootReceiver.java // @DebugLog // public class BootReceiver extends BroadcastReceiver { // // @Inject SessionsReminder sessionsReminder; // // public BootReceiver() { // } // // public static void enable(Context context) { // setActivationState(context, PackageManager.COMPONENT_ENABLED_STATE_ENABLED); // } // // public static void disable(Context context) { // setActivationState(context, PackageManager.COMPONENT_ENABLED_STATE_DISABLED); // } // // private static void setActivationState(Context context, int state) { // ComponentName componentName = new ComponentName(context, BootReceiver.class); // PackageManager pm = context.getPackageManager(); // pm.setComponentEnabledSetting(componentName, state, PackageManager.DONT_KILL_APP); // } // // @Override // public void onReceive(Context context, Intent intent) { // DroidconApp.get(context).component().inject(this); // sessionsReminder.enableSessionReminder(); // } // } // // Path: app/src/main/java/com/nilhcem/droidconde/receiver/reminder/SessionsReminder.java // @Singleton // public class SessionsReminder { // // private final Context context; // private final SessionsDao sessionsDao; // private final SharedPreferences preferences; // private final AlarmManager alarmManager; // // @Inject // public SessionsReminder(Application app, SessionsDao sessionsDao, SharedPreferences preferences) { // this.context = app; // this.sessionsDao = sessionsDao; // this.preferences = preferences; // alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE); // } // // public boolean isEnabled() { // return preferences.getBoolean(context.getString(R.string.settings_notify_key), false); // } // // public void enableSessionReminder() { // performOnSelectedSessions(this::addSessionReminder); // } // // public void disableSessionReminder() { // performOnSelectedSessions(this::removeSessionReminder); // } // // public void addSessionReminder(@NonNull Session session) { // if (!isEnabled()) { // Timber.d("SessionsReminder is not enable, skip adding session"); // return; // } // // PendingIntent intent = createSessionReminderIntent(session); // LocalDateTime now = LocalDateTime.now(); // LocalDateTime sessionStartTime = session.getFromTime().minusMinutes(3); // if (!sessionStartTime.isAfter(now)) { // Timber.w("Do not set reminder for passed session"); // return; // } // Timber.d("Setting reminder on %s", sessionStartTime); // App.setExactAlarm(alarmManager, sessionStartTime.atZone(ZoneOffset.systemDefault()).toInstant().toEpochMilli(), intent); // } // // public void removeSessionReminder(@NonNull Session session) { // Timber.d("Cancelling reminder on %s", session.getFromTime().minusMinutes(3)); // createSessionReminderIntent(session).cancel(); // } // // private PendingIntent createSessionReminderIntent(@NonNull Session session) { // Intent intent = new ReminderReceiverIntentBuilder(session).build(context); // return PendingIntent.getBroadcast(context, session.getId(), intent, PendingIntent.FLAG_UPDATE_CURRENT); // } // // private void performOnSelectedSessions(Action1<? super Session> onNext) { // sessionsDao.getSelectedSessions() // .flatMap(Observable::from) // .subscribeOn(Schedulers.io()) // .observeOn(Schedulers.computation()) // .subscribe(onNext, throwable -> Timber.e(throwable, "Error getting sessions")); // } // } // // Path: app/src/main/java/com/nilhcem/droidconde/ui/BasePresenter.java // public abstract class BasePresenter<V> { // // protected final V view; // // public BasePresenter(V view) { // this.view = view; // } // } // // Path: app/src/main/java/com/nilhcem/droidconde/utils/App.java // public final class App { // // private App() { // throw new UnsupportedOperationException(); // } // // public static boolean isCompatible(int apiLevel) { // return android.os.Build.VERSION.SDK_INT >= apiLevel; // } // // public static String getVersion() { // String version = String.format(Locale.US, "%s (#%d)", BuildConfig.VERSION_NAME, BuildConfig.VERSION_CODE); // if (BuildConfig.INTERNAL_BUILD) { // version = String.format(Locale.US, "%s — commit %s", version, BuildConfig.GIT_SHA); // } // return version; // } // // public static void setExactAlarm(AlarmManager alarmManager, long triggerAtMillis, PendingIntent operation) { // if (isCompatible(Build.VERSION_CODES.KITKAT)) { // alarmManager.setExact(AlarmManager.RTC_WAKEUP, triggerAtMillis, operation); // } else { // alarmManager.set(AlarmManager.RTC_WAKEUP, triggerAtMillis, operation); // } // } // // @Nullable // public static String getPhotoUrl(@Nullable Session session) { // String photoUrl = null; // if (session != null) { // List<Speaker> speakers = session.getSpeakers(); // if (speakers != null && !speakers.isEmpty()) { // photoUrl = speakers.get(0).getPhoto(); // } // } // return photoUrl; // } // }
import android.content.Context; import com.nilhcem.droidconde.receiver.BootReceiver; import com.nilhcem.droidconde.receiver.reminder.SessionsReminder; import com.nilhcem.droidconde.ui.BasePresenter; import com.nilhcem.droidconde.utils.App;
package com.nilhcem.droidconde.ui.settings; public class SettingsPresenter extends BasePresenter<SettingsMvp.View> implements SettingsMvp.Presenter { private final Context context;
// Path: app/src/main/java/com/nilhcem/droidconde/receiver/BootReceiver.java // @DebugLog // public class BootReceiver extends BroadcastReceiver { // // @Inject SessionsReminder sessionsReminder; // // public BootReceiver() { // } // // public static void enable(Context context) { // setActivationState(context, PackageManager.COMPONENT_ENABLED_STATE_ENABLED); // } // // public static void disable(Context context) { // setActivationState(context, PackageManager.COMPONENT_ENABLED_STATE_DISABLED); // } // // private static void setActivationState(Context context, int state) { // ComponentName componentName = new ComponentName(context, BootReceiver.class); // PackageManager pm = context.getPackageManager(); // pm.setComponentEnabledSetting(componentName, state, PackageManager.DONT_KILL_APP); // } // // @Override // public void onReceive(Context context, Intent intent) { // DroidconApp.get(context).component().inject(this); // sessionsReminder.enableSessionReminder(); // } // } // // Path: app/src/main/java/com/nilhcem/droidconde/receiver/reminder/SessionsReminder.java // @Singleton // public class SessionsReminder { // // private final Context context; // private final SessionsDao sessionsDao; // private final SharedPreferences preferences; // private final AlarmManager alarmManager; // // @Inject // public SessionsReminder(Application app, SessionsDao sessionsDao, SharedPreferences preferences) { // this.context = app; // this.sessionsDao = sessionsDao; // this.preferences = preferences; // alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE); // } // // public boolean isEnabled() { // return preferences.getBoolean(context.getString(R.string.settings_notify_key), false); // } // // public void enableSessionReminder() { // performOnSelectedSessions(this::addSessionReminder); // } // // public void disableSessionReminder() { // performOnSelectedSessions(this::removeSessionReminder); // } // // public void addSessionReminder(@NonNull Session session) { // if (!isEnabled()) { // Timber.d("SessionsReminder is not enable, skip adding session"); // return; // } // // PendingIntent intent = createSessionReminderIntent(session); // LocalDateTime now = LocalDateTime.now(); // LocalDateTime sessionStartTime = session.getFromTime().minusMinutes(3); // if (!sessionStartTime.isAfter(now)) { // Timber.w("Do not set reminder for passed session"); // return; // } // Timber.d("Setting reminder on %s", sessionStartTime); // App.setExactAlarm(alarmManager, sessionStartTime.atZone(ZoneOffset.systemDefault()).toInstant().toEpochMilli(), intent); // } // // public void removeSessionReminder(@NonNull Session session) { // Timber.d("Cancelling reminder on %s", session.getFromTime().minusMinutes(3)); // createSessionReminderIntent(session).cancel(); // } // // private PendingIntent createSessionReminderIntent(@NonNull Session session) { // Intent intent = new ReminderReceiverIntentBuilder(session).build(context); // return PendingIntent.getBroadcast(context, session.getId(), intent, PendingIntent.FLAG_UPDATE_CURRENT); // } // // private void performOnSelectedSessions(Action1<? super Session> onNext) { // sessionsDao.getSelectedSessions() // .flatMap(Observable::from) // .subscribeOn(Schedulers.io()) // .observeOn(Schedulers.computation()) // .subscribe(onNext, throwable -> Timber.e(throwable, "Error getting sessions")); // } // } // // Path: app/src/main/java/com/nilhcem/droidconde/ui/BasePresenter.java // public abstract class BasePresenter<V> { // // protected final V view; // // public BasePresenter(V view) { // this.view = view; // } // } // // Path: app/src/main/java/com/nilhcem/droidconde/utils/App.java // public final class App { // // private App() { // throw new UnsupportedOperationException(); // } // // public static boolean isCompatible(int apiLevel) { // return android.os.Build.VERSION.SDK_INT >= apiLevel; // } // // public static String getVersion() { // String version = String.format(Locale.US, "%s (#%d)", BuildConfig.VERSION_NAME, BuildConfig.VERSION_CODE); // if (BuildConfig.INTERNAL_BUILD) { // version = String.format(Locale.US, "%s — commit %s", version, BuildConfig.GIT_SHA); // } // return version; // } // // public static void setExactAlarm(AlarmManager alarmManager, long triggerAtMillis, PendingIntent operation) { // if (isCompatible(Build.VERSION_CODES.KITKAT)) { // alarmManager.setExact(AlarmManager.RTC_WAKEUP, triggerAtMillis, operation); // } else { // alarmManager.set(AlarmManager.RTC_WAKEUP, triggerAtMillis, operation); // } // } // // @Nullable // public static String getPhotoUrl(@Nullable Session session) { // String photoUrl = null; // if (session != null) { // List<Speaker> speakers = session.getSpeakers(); // if (speakers != null && !speakers.isEmpty()) { // photoUrl = speakers.get(0).getPhoto(); // } // } // return photoUrl; // } // } // Path: app/src/main/java/com/nilhcem/droidconde/ui/settings/SettingsPresenter.java import android.content.Context; import com.nilhcem.droidconde.receiver.BootReceiver; import com.nilhcem.droidconde.receiver.reminder.SessionsReminder; import com.nilhcem.droidconde.ui.BasePresenter; import com.nilhcem.droidconde.utils.App; package com.nilhcem.droidconde.ui.settings; public class SettingsPresenter extends BasePresenter<SettingsMvp.View> implements SettingsMvp.Presenter { private final Context context;
private final SessionsReminder sessionsReminder;
Nilhcem/droidconde-2016
app/src/main/java/com/nilhcem/droidconde/ui/settings/SettingsPresenter.java
// Path: app/src/main/java/com/nilhcem/droidconde/receiver/BootReceiver.java // @DebugLog // public class BootReceiver extends BroadcastReceiver { // // @Inject SessionsReminder sessionsReminder; // // public BootReceiver() { // } // // public static void enable(Context context) { // setActivationState(context, PackageManager.COMPONENT_ENABLED_STATE_ENABLED); // } // // public static void disable(Context context) { // setActivationState(context, PackageManager.COMPONENT_ENABLED_STATE_DISABLED); // } // // private static void setActivationState(Context context, int state) { // ComponentName componentName = new ComponentName(context, BootReceiver.class); // PackageManager pm = context.getPackageManager(); // pm.setComponentEnabledSetting(componentName, state, PackageManager.DONT_KILL_APP); // } // // @Override // public void onReceive(Context context, Intent intent) { // DroidconApp.get(context).component().inject(this); // sessionsReminder.enableSessionReminder(); // } // } // // Path: app/src/main/java/com/nilhcem/droidconde/receiver/reminder/SessionsReminder.java // @Singleton // public class SessionsReminder { // // private final Context context; // private final SessionsDao sessionsDao; // private final SharedPreferences preferences; // private final AlarmManager alarmManager; // // @Inject // public SessionsReminder(Application app, SessionsDao sessionsDao, SharedPreferences preferences) { // this.context = app; // this.sessionsDao = sessionsDao; // this.preferences = preferences; // alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE); // } // // public boolean isEnabled() { // return preferences.getBoolean(context.getString(R.string.settings_notify_key), false); // } // // public void enableSessionReminder() { // performOnSelectedSessions(this::addSessionReminder); // } // // public void disableSessionReminder() { // performOnSelectedSessions(this::removeSessionReminder); // } // // public void addSessionReminder(@NonNull Session session) { // if (!isEnabled()) { // Timber.d("SessionsReminder is not enable, skip adding session"); // return; // } // // PendingIntent intent = createSessionReminderIntent(session); // LocalDateTime now = LocalDateTime.now(); // LocalDateTime sessionStartTime = session.getFromTime().minusMinutes(3); // if (!sessionStartTime.isAfter(now)) { // Timber.w("Do not set reminder for passed session"); // return; // } // Timber.d("Setting reminder on %s", sessionStartTime); // App.setExactAlarm(alarmManager, sessionStartTime.atZone(ZoneOffset.systemDefault()).toInstant().toEpochMilli(), intent); // } // // public void removeSessionReminder(@NonNull Session session) { // Timber.d("Cancelling reminder on %s", session.getFromTime().minusMinutes(3)); // createSessionReminderIntent(session).cancel(); // } // // private PendingIntent createSessionReminderIntent(@NonNull Session session) { // Intent intent = new ReminderReceiverIntentBuilder(session).build(context); // return PendingIntent.getBroadcast(context, session.getId(), intent, PendingIntent.FLAG_UPDATE_CURRENT); // } // // private void performOnSelectedSessions(Action1<? super Session> onNext) { // sessionsDao.getSelectedSessions() // .flatMap(Observable::from) // .subscribeOn(Schedulers.io()) // .observeOn(Schedulers.computation()) // .subscribe(onNext, throwable -> Timber.e(throwable, "Error getting sessions")); // } // } // // Path: app/src/main/java/com/nilhcem/droidconde/ui/BasePresenter.java // public abstract class BasePresenter<V> { // // protected final V view; // // public BasePresenter(V view) { // this.view = view; // } // } // // Path: app/src/main/java/com/nilhcem/droidconde/utils/App.java // public final class App { // // private App() { // throw new UnsupportedOperationException(); // } // // public static boolean isCompatible(int apiLevel) { // return android.os.Build.VERSION.SDK_INT >= apiLevel; // } // // public static String getVersion() { // String version = String.format(Locale.US, "%s (#%d)", BuildConfig.VERSION_NAME, BuildConfig.VERSION_CODE); // if (BuildConfig.INTERNAL_BUILD) { // version = String.format(Locale.US, "%s — commit %s", version, BuildConfig.GIT_SHA); // } // return version; // } // // public static void setExactAlarm(AlarmManager alarmManager, long triggerAtMillis, PendingIntent operation) { // if (isCompatible(Build.VERSION_CODES.KITKAT)) { // alarmManager.setExact(AlarmManager.RTC_WAKEUP, triggerAtMillis, operation); // } else { // alarmManager.set(AlarmManager.RTC_WAKEUP, triggerAtMillis, operation); // } // } // // @Nullable // public static String getPhotoUrl(@Nullable Session session) { // String photoUrl = null; // if (session != null) { // List<Speaker> speakers = session.getSpeakers(); // if (speakers != null && !speakers.isEmpty()) { // photoUrl = speakers.get(0).getPhoto(); // } // } // return photoUrl; // } // }
import android.content.Context; import com.nilhcem.droidconde.receiver.BootReceiver; import com.nilhcem.droidconde.receiver.reminder.SessionsReminder; import com.nilhcem.droidconde.ui.BasePresenter; import com.nilhcem.droidconde.utils.App;
package com.nilhcem.droidconde.ui.settings; public class SettingsPresenter extends BasePresenter<SettingsMvp.View> implements SettingsMvp.Presenter { private final Context context; private final SessionsReminder sessionsReminder; public SettingsPresenter(Context context, SettingsMvp.View view, SessionsReminder sessionsReminder) { super(view); this.context = context; this.sessionsReminder = sessionsReminder; } @Override public void onCreate() {
// Path: app/src/main/java/com/nilhcem/droidconde/receiver/BootReceiver.java // @DebugLog // public class BootReceiver extends BroadcastReceiver { // // @Inject SessionsReminder sessionsReminder; // // public BootReceiver() { // } // // public static void enable(Context context) { // setActivationState(context, PackageManager.COMPONENT_ENABLED_STATE_ENABLED); // } // // public static void disable(Context context) { // setActivationState(context, PackageManager.COMPONENT_ENABLED_STATE_DISABLED); // } // // private static void setActivationState(Context context, int state) { // ComponentName componentName = new ComponentName(context, BootReceiver.class); // PackageManager pm = context.getPackageManager(); // pm.setComponentEnabledSetting(componentName, state, PackageManager.DONT_KILL_APP); // } // // @Override // public void onReceive(Context context, Intent intent) { // DroidconApp.get(context).component().inject(this); // sessionsReminder.enableSessionReminder(); // } // } // // Path: app/src/main/java/com/nilhcem/droidconde/receiver/reminder/SessionsReminder.java // @Singleton // public class SessionsReminder { // // private final Context context; // private final SessionsDao sessionsDao; // private final SharedPreferences preferences; // private final AlarmManager alarmManager; // // @Inject // public SessionsReminder(Application app, SessionsDao sessionsDao, SharedPreferences preferences) { // this.context = app; // this.sessionsDao = sessionsDao; // this.preferences = preferences; // alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE); // } // // public boolean isEnabled() { // return preferences.getBoolean(context.getString(R.string.settings_notify_key), false); // } // // public void enableSessionReminder() { // performOnSelectedSessions(this::addSessionReminder); // } // // public void disableSessionReminder() { // performOnSelectedSessions(this::removeSessionReminder); // } // // public void addSessionReminder(@NonNull Session session) { // if (!isEnabled()) { // Timber.d("SessionsReminder is not enable, skip adding session"); // return; // } // // PendingIntent intent = createSessionReminderIntent(session); // LocalDateTime now = LocalDateTime.now(); // LocalDateTime sessionStartTime = session.getFromTime().minusMinutes(3); // if (!sessionStartTime.isAfter(now)) { // Timber.w("Do not set reminder for passed session"); // return; // } // Timber.d("Setting reminder on %s", sessionStartTime); // App.setExactAlarm(alarmManager, sessionStartTime.atZone(ZoneOffset.systemDefault()).toInstant().toEpochMilli(), intent); // } // // public void removeSessionReminder(@NonNull Session session) { // Timber.d("Cancelling reminder on %s", session.getFromTime().minusMinutes(3)); // createSessionReminderIntent(session).cancel(); // } // // private PendingIntent createSessionReminderIntent(@NonNull Session session) { // Intent intent = new ReminderReceiverIntentBuilder(session).build(context); // return PendingIntent.getBroadcast(context, session.getId(), intent, PendingIntent.FLAG_UPDATE_CURRENT); // } // // private void performOnSelectedSessions(Action1<? super Session> onNext) { // sessionsDao.getSelectedSessions() // .flatMap(Observable::from) // .subscribeOn(Schedulers.io()) // .observeOn(Schedulers.computation()) // .subscribe(onNext, throwable -> Timber.e(throwable, "Error getting sessions")); // } // } // // Path: app/src/main/java/com/nilhcem/droidconde/ui/BasePresenter.java // public abstract class BasePresenter<V> { // // protected final V view; // // public BasePresenter(V view) { // this.view = view; // } // } // // Path: app/src/main/java/com/nilhcem/droidconde/utils/App.java // public final class App { // // private App() { // throw new UnsupportedOperationException(); // } // // public static boolean isCompatible(int apiLevel) { // return android.os.Build.VERSION.SDK_INT >= apiLevel; // } // // public static String getVersion() { // String version = String.format(Locale.US, "%s (#%d)", BuildConfig.VERSION_NAME, BuildConfig.VERSION_CODE); // if (BuildConfig.INTERNAL_BUILD) { // version = String.format(Locale.US, "%s — commit %s", version, BuildConfig.GIT_SHA); // } // return version; // } // // public static void setExactAlarm(AlarmManager alarmManager, long triggerAtMillis, PendingIntent operation) { // if (isCompatible(Build.VERSION_CODES.KITKAT)) { // alarmManager.setExact(AlarmManager.RTC_WAKEUP, triggerAtMillis, operation); // } else { // alarmManager.set(AlarmManager.RTC_WAKEUP, triggerAtMillis, operation); // } // } // // @Nullable // public static String getPhotoUrl(@Nullable Session session) { // String photoUrl = null; // if (session != null) { // List<Speaker> speakers = session.getSpeakers(); // if (speakers != null && !speakers.isEmpty()) { // photoUrl = speakers.get(0).getPhoto(); // } // } // return photoUrl; // } // } // Path: app/src/main/java/com/nilhcem/droidconde/ui/settings/SettingsPresenter.java import android.content.Context; import com.nilhcem.droidconde.receiver.BootReceiver; import com.nilhcem.droidconde.receiver.reminder.SessionsReminder; import com.nilhcem.droidconde.ui.BasePresenter; import com.nilhcem.droidconde.utils.App; package com.nilhcem.droidconde.ui.settings; public class SettingsPresenter extends BasePresenter<SettingsMvp.View> implements SettingsMvp.Presenter { private final Context context; private final SessionsReminder sessionsReminder; public SettingsPresenter(Context context, SettingsMvp.View view, SessionsReminder sessionsReminder) { super(view); this.context = context; this.sessionsReminder = sessionsReminder; } @Override public void onCreate() {
view.setAppVersion(App.getVersion());
Nilhcem/droidconde-2016
app/src/production/java/com/nilhcem/droidconde/core/dagger/AppComponent.java
// Path: app/src/main/java/com/nilhcem/droidconde/DroidconApp.java // @DebugLog // public class DroidconApp extends Application { // // private AppComponent component; // // public static DroidconApp get(Context context) { // return (DroidconApp) context.getApplicationContext(); // } // // @Override // public void onCreate() { // super.onCreate(); // AndroidThreeTen.init(this); // initGraph(); // initLogger(); // } // // public AppComponent component() { // return component; // } // // private void initGraph() { // component = AppComponent.Initializer.init(this); // } // // private void initLogger() { // Timber.plant(new Timber.DebugTree()); // } // } // // Path: app/src/main/java/com/nilhcem/droidconde/core/dagger/module/ApiModule.java // @Module // public final class ApiModule { // // @Provides @Singleton ApiEndpoint provideApiEndpoint(Application context) { // return ApiEndpoint.get(context); // } // // @Provides @Singleton Retrofit provideRetrofit(OkHttpClient client, Moshi moshi, ApiEndpoint endpoint) { // return new Retrofit.Builder() // .client(client) // .baseUrl(endpoint.url) // .addConverterFactory(MoshiConverterFactory.create(moshi)) // .addCallAdapterFactory(RxJavaCallAdapterFactory.create()) // .build(); // } // // @Provides @Singleton // DroidconService provideDroidconService(Retrofit retrofit) { // return retrofit.create(DroidconService.class); // } // } // // Path: app/src/main/java/com/nilhcem/droidconde/core/dagger/module/AppModule.java // @Module // public final class AppModule { // // private final DroidconApp app; // // public AppModule(DroidconApp app) { // this.app = app; // } // // @Provides @Singleton Application provideApplication() { // return app; // } // } // // Path: app/src/main/java/com/nilhcem/droidconde/core/dagger/module/DataModule.java // @Module(includes = OkHttpModule.class) // public final class DataModule { // // private static final long DISK_CACHE_SIZE = 31_457_280; // 30MB // // @Provides @Singleton SharedPreferences provideSharedPreferences(Application app) { // return PreferenceManager.getDefaultSharedPreferences(app); // } // // @Provides @Singleton Moshi provideMoshi(LocalDateTimeAdapter localDateTimeAdapter) { // return new Moshi.Builder() // .add(localDateTimeAdapter) // .build(); // } // // @Provides @Singleton OkHttpClient.Builder provideOkHttpClientBuilder(Application app) { // File cacheDir = new File(app.getCacheDir(), "http"); // Cache cache = new Cache(cacheDir, DISK_CACHE_SIZE); // return new OkHttpClient.Builder().cache(cache); // } // // @Provides @Singleton Picasso providePicasso(Application app, OkHttpClient client) { // return new Picasso.Builder(app) // .downloader(new OkHttp3Downloader(client)) // .listener((picasso, uri, e) -> Timber.e(e, "Failed to load image: %s", uri)) // .build(); // } // } // // Path: app/src/main/java/com/nilhcem/droidconde/core/dagger/module/DatabaseModule.java // @Module // public class DatabaseModule { // // static final String TAG = "database"; // // @Provides @Singleton SQLiteOpenHelper provideSQLiteOpenHelper(Application application) { // return new DbOpenHelper(application); // } // // @Provides @Singleton SqlBrite provideSqlBrite() { // return SqlBrite.create(Timber.tag(TAG)::v); // } // // @Provides @Singleton BriteDatabase provideBriteDatabase(SqlBrite sqlBrite, SQLiteOpenHelper helper) { // return sqlBrite.wrapDatabaseHelper(helper, Schedulers.immediate()); // } // }
import com.nilhcem.droidconde.DroidconApp; import com.nilhcem.droidconde.core.dagger.module.ApiModule; import com.nilhcem.droidconde.core.dagger.module.AppModule; import com.nilhcem.droidconde.core.dagger.module.DataModule; import com.nilhcem.droidconde.core.dagger.module.DatabaseModule; import javax.inject.Singleton; import dagger.Component;
package com.nilhcem.droidconde.core.dagger; @Singleton @Component(modules = {AppModule.class, ApiModule.class, DataModule.class, DatabaseModule.class}) public interface AppComponent extends AppGraph { /** * An initializer that creates the production graph from an application. */ final class Initializer { private Initializer() { throw new UnsupportedOperationException(); }
// Path: app/src/main/java/com/nilhcem/droidconde/DroidconApp.java // @DebugLog // public class DroidconApp extends Application { // // private AppComponent component; // // public static DroidconApp get(Context context) { // return (DroidconApp) context.getApplicationContext(); // } // // @Override // public void onCreate() { // super.onCreate(); // AndroidThreeTen.init(this); // initGraph(); // initLogger(); // } // // public AppComponent component() { // return component; // } // // private void initGraph() { // component = AppComponent.Initializer.init(this); // } // // private void initLogger() { // Timber.plant(new Timber.DebugTree()); // } // } // // Path: app/src/main/java/com/nilhcem/droidconde/core/dagger/module/ApiModule.java // @Module // public final class ApiModule { // // @Provides @Singleton ApiEndpoint provideApiEndpoint(Application context) { // return ApiEndpoint.get(context); // } // // @Provides @Singleton Retrofit provideRetrofit(OkHttpClient client, Moshi moshi, ApiEndpoint endpoint) { // return new Retrofit.Builder() // .client(client) // .baseUrl(endpoint.url) // .addConverterFactory(MoshiConverterFactory.create(moshi)) // .addCallAdapterFactory(RxJavaCallAdapterFactory.create()) // .build(); // } // // @Provides @Singleton // DroidconService provideDroidconService(Retrofit retrofit) { // return retrofit.create(DroidconService.class); // } // } // // Path: app/src/main/java/com/nilhcem/droidconde/core/dagger/module/AppModule.java // @Module // public final class AppModule { // // private final DroidconApp app; // // public AppModule(DroidconApp app) { // this.app = app; // } // // @Provides @Singleton Application provideApplication() { // return app; // } // } // // Path: app/src/main/java/com/nilhcem/droidconde/core/dagger/module/DataModule.java // @Module(includes = OkHttpModule.class) // public final class DataModule { // // private static final long DISK_CACHE_SIZE = 31_457_280; // 30MB // // @Provides @Singleton SharedPreferences provideSharedPreferences(Application app) { // return PreferenceManager.getDefaultSharedPreferences(app); // } // // @Provides @Singleton Moshi provideMoshi(LocalDateTimeAdapter localDateTimeAdapter) { // return new Moshi.Builder() // .add(localDateTimeAdapter) // .build(); // } // // @Provides @Singleton OkHttpClient.Builder provideOkHttpClientBuilder(Application app) { // File cacheDir = new File(app.getCacheDir(), "http"); // Cache cache = new Cache(cacheDir, DISK_CACHE_SIZE); // return new OkHttpClient.Builder().cache(cache); // } // // @Provides @Singleton Picasso providePicasso(Application app, OkHttpClient client) { // return new Picasso.Builder(app) // .downloader(new OkHttp3Downloader(client)) // .listener((picasso, uri, e) -> Timber.e(e, "Failed to load image: %s", uri)) // .build(); // } // } // // Path: app/src/main/java/com/nilhcem/droidconde/core/dagger/module/DatabaseModule.java // @Module // public class DatabaseModule { // // static final String TAG = "database"; // // @Provides @Singleton SQLiteOpenHelper provideSQLiteOpenHelper(Application application) { // return new DbOpenHelper(application); // } // // @Provides @Singleton SqlBrite provideSqlBrite() { // return SqlBrite.create(Timber.tag(TAG)::v); // } // // @Provides @Singleton BriteDatabase provideBriteDatabase(SqlBrite sqlBrite, SQLiteOpenHelper helper) { // return sqlBrite.wrapDatabaseHelper(helper, Schedulers.immediate()); // } // } // Path: app/src/production/java/com/nilhcem/droidconde/core/dagger/AppComponent.java import com.nilhcem.droidconde.DroidconApp; import com.nilhcem.droidconde.core.dagger.module.ApiModule; import com.nilhcem.droidconde.core.dagger.module.AppModule; import com.nilhcem.droidconde.core.dagger.module.DataModule; import com.nilhcem.droidconde.core.dagger.module.DatabaseModule; import javax.inject.Singleton; import dagger.Component; package com.nilhcem.droidconde.core.dagger; @Singleton @Component(modules = {AppModule.class, ApiModule.class, DataModule.class, DatabaseModule.class}) public interface AppComponent extends AppGraph { /** * An initializer that creates the production graph from an application. */ final class Initializer { private Initializer() { throw new UnsupportedOperationException(); }
public static AppComponent init(DroidconApp app) {
Nilhcem/droidconde-2016
app/src/main/java/com/nilhcem/droidconde/ui/speakers/list/SpeakersListEntry.java
// Path: app/src/main/java/com/nilhcem/droidconde/data/app/model/Speaker.java // @Value // public class Speaker implements Parcelable { // // public static final Parcelable.Creator<Speaker> CREATOR = new Parcelable.Creator<Speaker>() { // public Speaker createFromParcel(Parcel source) { // return new Speaker(source); // } // // public Speaker[] newArray(int size) { // return new Speaker[size]; // } // }; // // int id; // String name; // String title; // String bio; // String website; // String twitter; // String github; // String photo; // // public Speaker(int id, String name, String title, String bio, String website, String twitter, String github, String photo) { // this.id = id; // this.name = name; // this.title = title; // this.bio = bio; // this.website = website; // this.twitter = twitter; // this.github = github; // this.photo = photo; // } // // protected Speaker(Parcel in) { // id = in.readInt(); // name = in.readString(); // title = in.readString(); // bio = in.readString(); // website = in.readString(); // twitter = in.readString(); // github = in.readString(); // photo = in.readString(); // } // // @Override // public int describeContents() { // return 0; // } // // @Override // public void writeToParcel(Parcel dest, int flags) { // dest.writeInt(id); // dest.writeString(name); // dest.writeString(title); // dest.writeString(bio); // dest.writeString(website); // dest.writeString(twitter); // dest.writeString(github); // dest.writeString(photo); // } // } // // Path: app/src/main/java/com/nilhcem/droidconde/ui/core/recyclerview/BaseViewHolder.java // public abstract class BaseViewHolder extends RecyclerView.ViewHolder { // // public BaseViewHolder(ViewGroup parent, @LayoutRes int layout) { // super(LayoutInflater.from(parent.getContext()).inflate(layout, parent, false)); // ButterKnife.bind(this, itemView); // } // }
import android.text.TextUtils; import android.view.ViewGroup; import android.widget.ImageView; import android.widget.TextView; import com.nilhcem.droidconde.R; import com.nilhcem.droidconde.data.app.model.Speaker; import com.nilhcem.droidconde.ui.core.recyclerview.BaseViewHolder; import com.squareup.picasso.Picasso; import butterknife.BindView;
package com.nilhcem.droidconde.ui.speakers.list; public class SpeakersListEntry extends BaseViewHolder { @BindView(R.id.speakers_list_entry_photo) ImageView photo; @BindView(R.id.speakers_list_entry_name) TextView name; private final Picasso picasso; public SpeakersListEntry(ViewGroup parent, Picasso picasso) { super(parent, R.layout.speakers_list_entry); this.picasso = picasso; }
// Path: app/src/main/java/com/nilhcem/droidconde/data/app/model/Speaker.java // @Value // public class Speaker implements Parcelable { // // public static final Parcelable.Creator<Speaker> CREATOR = new Parcelable.Creator<Speaker>() { // public Speaker createFromParcel(Parcel source) { // return new Speaker(source); // } // // public Speaker[] newArray(int size) { // return new Speaker[size]; // } // }; // // int id; // String name; // String title; // String bio; // String website; // String twitter; // String github; // String photo; // // public Speaker(int id, String name, String title, String bio, String website, String twitter, String github, String photo) { // this.id = id; // this.name = name; // this.title = title; // this.bio = bio; // this.website = website; // this.twitter = twitter; // this.github = github; // this.photo = photo; // } // // protected Speaker(Parcel in) { // id = in.readInt(); // name = in.readString(); // title = in.readString(); // bio = in.readString(); // website = in.readString(); // twitter = in.readString(); // github = in.readString(); // photo = in.readString(); // } // // @Override // public int describeContents() { // return 0; // } // // @Override // public void writeToParcel(Parcel dest, int flags) { // dest.writeInt(id); // dest.writeString(name); // dest.writeString(title); // dest.writeString(bio); // dest.writeString(website); // dest.writeString(twitter); // dest.writeString(github); // dest.writeString(photo); // } // } // // Path: app/src/main/java/com/nilhcem/droidconde/ui/core/recyclerview/BaseViewHolder.java // public abstract class BaseViewHolder extends RecyclerView.ViewHolder { // // public BaseViewHolder(ViewGroup parent, @LayoutRes int layout) { // super(LayoutInflater.from(parent.getContext()).inflate(layout, parent, false)); // ButterKnife.bind(this, itemView); // } // } // Path: app/src/main/java/com/nilhcem/droidconde/ui/speakers/list/SpeakersListEntry.java import android.text.TextUtils; import android.view.ViewGroup; import android.widget.ImageView; import android.widget.TextView; import com.nilhcem.droidconde.R; import com.nilhcem.droidconde.data.app.model.Speaker; import com.nilhcem.droidconde.ui.core.recyclerview.BaseViewHolder; import com.squareup.picasso.Picasso; import butterknife.BindView; package com.nilhcem.droidconde.ui.speakers.list; public class SpeakersListEntry extends BaseViewHolder { @BindView(R.id.speakers_list_entry_photo) ImageView photo; @BindView(R.id.speakers_list_entry_name) TextView name; private final Picasso picasso; public SpeakersListEntry(ViewGroup parent, Picasso picasso) { super(parent, R.layout.speakers_list_entry); this.picasso = picasso; }
public void bindSpeaker(Speaker speaker) {
Nilhcem/droidconde-2016
app/src/test/java/com/nilhcem/droidconde/utils/AppTest.java
// Path: app/src/main/java/com/nilhcem/droidconde/data/app/model/Session.java // @Value // public class Session implements Parcelable { // // public static final Parcelable.Creator<Session> CREATOR = new Parcelable.Creator<Session>() { // public Session createFromParcel(Parcel source) { // return new Session(source); // } // // public Session[] newArray(int size) { // return new Session[size]; // } // }; // // int id; // String room; // List<Speaker> speakers; // String title; // String description; // LocalDateTime fromTime; // LocalDateTime toTime; // // public Session(int id, String room, List<Speaker> speakers, String title, String description, LocalDateTime fromTime, LocalDateTime toTime) { // this.id = id; // this.room = room; // this.speakers = speakers; // this.title = title; // this.description = description; // this.fromTime = fromTime; // this.toTime = toTime; // } // // protected Session(Parcel in) { // id = in.readInt(); // room = in.readString(); // speakers = in.createTypedArrayList(Speaker.CREATOR); // title = in.readString(); // description = in.readString(); // fromTime = (LocalDateTime) in.readSerializable(); // toTime = (LocalDateTime) in.readSerializable(); // } // // @Override // public int describeContents() { // return 0; // } // // @Override // public void writeToParcel(Parcel dest, int flags) { // dest.writeInt(id); // dest.writeString(room); // dest.writeTypedList(speakers); // dest.writeString(title); // dest.writeString(description); // dest.writeSerializable(fromTime); // dest.writeSerializable(toTime); // } // } // // Path: app/src/main/java/com/nilhcem/droidconde/data/app/model/Speaker.java // @Value // public class Speaker implements Parcelable { // // public static final Parcelable.Creator<Speaker> CREATOR = new Parcelable.Creator<Speaker>() { // public Speaker createFromParcel(Parcel source) { // return new Speaker(source); // } // // public Speaker[] newArray(int size) { // return new Speaker[size]; // } // }; // // int id; // String name; // String title; // String bio; // String website; // String twitter; // String github; // String photo; // // public Speaker(int id, String name, String title, String bio, String website, String twitter, String github, String photo) { // this.id = id; // this.name = name; // this.title = title; // this.bio = bio; // this.website = website; // this.twitter = twitter; // this.github = github; // this.photo = photo; // } // // protected Speaker(Parcel in) { // id = in.readInt(); // name = in.readString(); // title = in.readString(); // bio = in.readString(); // website = in.readString(); // twitter = in.readString(); // github = in.readString(); // photo = in.readString(); // } // // @Override // public int describeContents() { // return 0; // } // // @Override // public void writeToParcel(Parcel dest, int flags) { // dest.writeInt(id); // dest.writeString(name); // dest.writeString(title); // dest.writeString(bio); // dest.writeString(website); // dest.writeString(twitter); // dest.writeString(github); // dest.writeString(photo); // } // }
import com.nilhcem.droidconde.BuildConfig; import com.nilhcem.droidconde.data.app.model.Session; import com.nilhcem.droidconde.data.app.model.Speaker; import org.junit.Test; import java.util.ArrayList; import java.util.Arrays; import static com.google.common.truth.Truth.assertThat; import static com.google.common.truth.TruthJUnit.assume;
package com.nilhcem.droidconde.utils; public class AppTest { @Test public void should_return_true_when_api_is_compatible() { // Given int apiLevelCompatible = android.os.Build.VERSION.SDK_INT; int apiLevelBelow = android.os.Build.VERSION.SDK_INT - 1; // When boolean result1 = App.isCompatible(apiLevelCompatible); boolean result2 = App.isCompatible(apiLevelBelow); // Then assertThat(result1).isTrue(); assertThat(result2).isTrue(); } @Test public void should_return_false_when_api_is_incompatible() { // Given int apiLevelIncompatible = android.os.Build.VERSION.SDK_INT + 1; // When boolean result = App.isCompatible(apiLevelIncompatible); // Then assertThat(result).isFalse(); } @Test public void should_return_formatted_string_version() { // Given assume().withFailureMessage("Do not test internal builds").that(BuildConfig.INTERNAL_BUILD).isFalse(); String expected = BuildConfig.VERSION_NAME + " (#" + BuildConfig.VERSION_CODE + ")"; // When String version = App.getVersion(); // Then assertThat(version).isEqualTo(expected); } @Test public void should_return_null_photourl_when_giving_invalid_data() { // Given
// Path: app/src/main/java/com/nilhcem/droidconde/data/app/model/Session.java // @Value // public class Session implements Parcelable { // // public static final Parcelable.Creator<Session> CREATOR = new Parcelable.Creator<Session>() { // public Session createFromParcel(Parcel source) { // return new Session(source); // } // // public Session[] newArray(int size) { // return new Session[size]; // } // }; // // int id; // String room; // List<Speaker> speakers; // String title; // String description; // LocalDateTime fromTime; // LocalDateTime toTime; // // public Session(int id, String room, List<Speaker> speakers, String title, String description, LocalDateTime fromTime, LocalDateTime toTime) { // this.id = id; // this.room = room; // this.speakers = speakers; // this.title = title; // this.description = description; // this.fromTime = fromTime; // this.toTime = toTime; // } // // protected Session(Parcel in) { // id = in.readInt(); // room = in.readString(); // speakers = in.createTypedArrayList(Speaker.CREATOR); // title = in.readString(); // description = in.readString(); // fromTime = (LocalDateTime) in.readSerializable(); // toTime = (LocalDateTime) in.readSerializable(); // } // // @Override // public int describeContents() { // return 0; // } // // @Override // public void writeToParcel(Parcel dest, int flags) { // dest.writeInt(id); // dest.writeString(room); // dest.writeTypedList(speakers); // dest.writeString(title); // dest.writeString(description); // dest.writeSerializable(fromTime); // dest.writeSerializable(toTime); // } // } // // Path: app/src/main/java/com/nilhcem/droidconde/data/app/model/Speaker.java // @Value // public class Speaker implements Parcelable { // // public static final Parcelable.Creator<Speaker> CREATOR = new Parcelable.Creator<Speaker>() { // public Speaker createFromParcel(Parcel source) { // return new Speaker(source); // } // // public Speaker[] newArray(int size) { // return new Speaker[size]; // } // }; // // int id; // String name; // String title; // String bio; // String website; // String twitter; // String github; // String photo; // // public Speaker(int id, String name, String title, String bio, String website, String twitter, String github, String photo) { // this.id = id; // this.name = name; // this.title = title; // this.bio = bio; // this.website = website; // this.twitter = twitter; // this.github = github; // this.photo = photo; // } // // protected Speaker(Parcel in) { // id = in.readInt(); // name = in.readString(); // title = in.readString(); // bio = in.readString(); // website = in.readString(); // twitter = in.readString(); // github = in.readString(); // photo = in.readString(); // } // // @Override // public int describeContents() { // return 0; // } // // @Override // public void writeToParcel(Parcel dest, int flags) { // dest.writeInt(id); // dest.writeString(name); // dest.writeString(title); // dest.writeString(bio); // dest.writeString(website); // dest.writeString(twitter); // dest.writeString(github); // dest.writeString(photo); // } // } // Path: app/src/test/java/com/nilhcem/droidconde/utils/AppTest.java import com.nilhcem.droidconde.BuildConfig; import com.nilhcem.droidconde.data.app.model.Session; import com.nilhcem.droidconde.data.app.model.Speaker; import org.junit.Test; import java.util.ArrayList; import java.util.Arrays; import static com.google.common.truth.Truth.assertThat; import static com.google.common.truth.TruthJUnit.assume; package com.nilhcem.droidconde.utils; public class AppTest { @Test public void should_return_true_when_api_is_compatible() { // Given int apiLevelCompatible = android.os.Build.VERSION.SDK_INT; int apiLevelBelow = android.os.Build.VERSION.SDK_INT - 1; // When boolean result1 = App.isCompatible(apiLevelCompatible); boolean result2 = App.isCompatible(apiLevelBelow); // Then assertThat(result1).isTrue(); assertThat(result2).isTrue(); } @Test public void should_return_false_when_api_is_incompatible() { // Given int apiLevelIncompatible = android.os.Build.VERSION.SDK_INT + 1; // When boolean result = App.isCompatible(apiLevelIncompatible); // Then assertThat(result).isFalse(); } @Test public void should_return_formatted_string_version() { // Given assume().withFailureMessage("Do not test internal builds").that(BuildConfig.INTERNAL_BUILD).isFalse(); String expected = BuildConfig.VERSION_NAME + " (#" + BuildConfig.VERSION_CODE + ")"; // When String version = App.getVersion(); // Then assertThat(version).isEqualTo(expected); } @Test public void should_return_null_photourl_when_giving_invalid_data() { // Given
Session session1 = null;
Nilhcem/droidconde-2016
app/src/test/java/com/nilhcem/droidconde/utils/AppTest.java
// Path: app/src/main/java/com/nilhcem/droidconde/data/app/model/Session.java // @Value // public class Session implements Parcelable { // // public static final Parcelable.Creator<Session> CREATOR = new Parcelable.Creator<Session>() { // public Session createFromParcel(Parcel source) { // return new Session(source); // } // // public Session[] newArray(int size) { // return new Session[size]; // } // }; // // int id; // String room; // List<Speaker> speakers; // String title; // String description; // LocalDateTime fromTime; // LocalDateTime toTime; // // public Session(int id, String room, List<Speaker> speakers, String title, String description, LocalDateTime fromTime, LocalDateTime toTime) { // this.id = id; // this.room = room; // this.speakers = speakers; // this.title = title; // this.description = description; // this.fromTime = fromTime; // this.toTime = toTime; // } // // protected Session(Parcel in) { // id = in.readInt(); // room = in.readString(); // speakers = in.createTypedArrayList(Speaker.CREATOR); // title = in.readString(); // description = in.readString(); // fromTime = (LocalDateTime) in.readSerializable(); // toTime = (LocalDateTime) in.readSerializable(); // } // // @Override // public int describeContents() { // return 0; // } // // @Override // public void writeToParcel(Parcel dest, int flags) { // dest.writeInt(id); // dest.writeString(room); // dest.writeTypedList(speakers); // dest.writeString(title); // dest.writeString(description); // dest.writeSerializable(fromTime); // dest.writeSerializable(toTime); // } // } // // Path: app/src/main/java/com/nilhcem/droidconde/data/app/model/Speaker.java // @Value // public class Speaker implements Parcelable { // // public static final Parcelable.Creator<Speaker> CREATOR = new Parcelable.Creator<Speaker>() { // public Speaker createFromParcel(Parcel source) { // return new Speaker(source); // } // // public Speaker[] newArray(int size) { // return new Speaker[size]; // } // }; // // int id; // String name; // String title; // String bio; // String website; // String twitter; // String github; // String photo; // // public Speaker(int id, String name, String title, String bio, String website, String twitter, String github, String photo) { // this.id = id; // this.name = name; // this.title = title; // this.bio = bio; // this.website = website; // this.twitter = twitter; // this.github = github; // this.photo = photo; // } // // protected Speaker(Parcel in) { // id = in.readInt(); // name = in.readString(); // title = in.readString(); // bio = in.readString(); // website = in.readString(); // twitter = in.readString(); // github = in.readString(); // photo = in.readString(); // } // // @Override // public int describeContents() { // return 0; // } // // @Override // public void writeToParcel(Parcel dest, int flags) { // dest.writeInt(id); // dest.writeString(name); // dest.writeString(title); // dest.writeString(bio); // dest.writeString(website); // dest.writeString(twitter); // dest.writeString(github); // dest.writeString(photo); // } // }
import com.nilhcem.droidconde.BuildConfig; import com.nilhcem.droidconde.data.app.model.Session; import com.nilhcem.droidconde.data.app.model.Speaker; import org.junit.Test; import java.util.ArrayList; import java.util.Arrays; import static com.google.common.truth.Truth.assertThat; import static com.google.common.truth.TruthJUnit.assume;
String expected = BuildConfig.VERSION_NAME + " (#" + BuildConfig.VERSION_CODE + ")"; // When String version = App.getVersion(); // Then assertThat(version).isEqualTo(expected); } @Test public void should_return_null_photourl_when_giving_invalid_data() { // Given Session session1 = null; Session session2 = new Session(3, "room1", null, "title", "description", null, null); Session session3 = new Session(3, "room1", new ArrayList<>(), "title", "description", null, null); // When String result1 = App.getPhotoUrl(session1); String result2 = App.getPhotoUrl(session2); String result3 = App.getPhotoUrl(session3); // Then assertThat(result1).isNull(); assertThat(result2).isNull(); assertThat(result3).isNull(); } @Test public void should_return_photo_url_of_first_speaker() { // Given
// Path: app/src/main/java/com/nilhcem/droidconde/data/app/model/Session.java // @Value // public class Session implements Parcelable { // // public static final Parcelable.Creator<Session> CREATOR = new Parcelable.Creator<Session>() { // public Session createFromParcel(Parcel source) { // return new Session(source); // } // // public Session[] newArray(int size) { // return new Session[size]; // } // }; // // int id; // String room; // List<Speaker> speakers; // String title; // String description; // LocalDateTime fromTime; // LocalDateTime toTime; // // public Session(int id, String room, List<Speaker> speakers, String title, String description, LocalDateTime fromTime, LocalDateTime toTime) { // this.id = id; // this.room = room; // this.speakers = speakers; // this.title = title; // this.description = description; // this.fromTime = fromTime; // this.toTime = toTime; // } // // protected Session(Parcel in) { // id = in.readInt(); // room = in.readString(); // speakers = in.createTypedArrayList(Speaker.CREATOR); // title = in.readString(); // description = in.readString(); // fromTime = (LocalDateTime) in.readSerializable(); // toTime = (LocalDateTime) in.readSerializable(); // } // // @Override // public int describeContents() { // return 0; // } // // @Override // public void writeToParcel(Parcel dest, int flags) { // dest.writeInt(id); // dest.writeString(room); // dest.writeTypedList(speakers); // dest.writeString(title); // dest.writeString(description); // dest.writeSerializable(fromTime); // dest.writeSerializable(toTime); // } // } // // Path: app/src/main/java/com/nilhcem/droidconde/data/app/model/Speaker.java // @Value // public class Speaker implements Parcelable { // // public static final Parcelable.Creator<Speaker> CREATOR = new Parcelable.Creator<Speaker>() { // public Speaker createFromParcel(Parcel source) { // return new Speaker(source); // } // // public Speaker[] newArray(int size) { // return new Speaker[size]; // } // }; // // int id; // String name; // String title; // String bio; // String website; // String twitter; // String github; // String photo; // // public Speaker(int id, String name, String title, String bio, String website, String twitter, String github, String photo) { // this.id = id; // this.name = name; // this.title = title; // this.bio = bio; // this.website = website; // this.twitter = twitter; // this.github = github; // this.photo = photo; // } // // protected Speaker(Parcel in) { // id = in.readInt(); // name = in.readString(); // title = in.readString(); // bio = in.readString(); // website = in.readString(); // twitter = in.readString(); // github = in.readString(); // photo = in.readString(); // } // // @Override // public int describeContents() { // return 0; // } // // @Override // public void writeToParcel(Parcel dest, int flags) { // dest.writeInt(id); // dest.writeString(name); // dest.writeString(title); // dest.writeString(bio); // dest.writeString(website); // dest.writeString(twitter); // dest.writeString(github); // dest.writeString(photo); // } // } // Path: app/src/test/java/com/nilhcem/droidconde/utils/AppTest.java import com.nilhcem.droidconde.BuildConfig; import com.nilhcem.droidconde.data.app.model.Session; import com.nilhcem.droidconde.data.app.model.Speaker; import org.junit.Test; import java.util.ArrayList; import java.util.Arrays; import static com.google.common.truth.Truth.assertThat; import static com.google.common.truth.TruthJUnit.assume; String expected = BuildConfig.VERSION_NAME + " (#" + BuildConfig.VERSION_CODE + ")"; // When String version = App.getVersion(); // Then assertThat(version).isEqualTo(expected); } @Test public void should_return_null_photourl_when_giving_invalid_data() { // Given Session session1 = null; Session session2 = new Session(3, "room1", null, "title", "description", null, null); Session session3 = new Session(3, "room1", new ArrayList<>(), "title", "description", null, null); // When String result1 = App.getPhotoUrl(session1); String result2 = App.getPhotoUrl(session2); String result3 = App.getPhotoUrl(session3); // Then assertThat(result1).isNull(); assertThat(result2).isNull(); assertThat(result3).isNull(); } @Test public void should_return_photo_url_of_first_speaker() { // Given
Speaker speaker1 = new Speaker(1, null, null, null, null, null, null, "photo1");
Nilhcem/droidconde-2016
app/src/main/java/com/nilhcem/droidconde/data/database/model/Speaker.java
// Path: app/src/main/java/com/nilhcem/droidconde/utils/Database.java // public class Database { // // private Database() { // throw new UnsupportedOperationException(); // } // // public static String getString(Cursor cursor, String columnName) { // return cursor.getString(cursor.getColumnIndexOrThrow(columnName)); // } // // public static int getInt(Cursor cursor, String columnName) { // return cursor.getInt(cursor.getColumnIndexOrThrow(columnName)); // } // }
import android.content.ContentValues; import android.database.Cursor; import com.nilhcem.droidconde.utils.Database; import rx.functions.Func1;
package com.nilhcem.droidconde.data.database.model; public class Speaker { public static final String TABLE = "speakers"; public static final String ID = "_id"; public static final String NAME = "name"; public static final String TITLE = "title"; public static final String BIO = "bio"; public static final String WEBSITE = "website"; public static final String TWITTER = "twitter"; public static final String GITHUB = "github"; public static final String PHOTO = "photo"; public static final Func1<Cursor, Speaker> MAPPER = cursor -> {
// Path: app/src/main/java/com/nilhcem/droidconde/utils/Database.java // public class Database { // // private Database() { // throw new UnsupportedOperationException(); // } // // public static String getString(Cursor cursor, String columnName) { // return cursor.getString(cursor.getColumnIndexOrThrow(columnName)); // } // // public static int getInt(Cursor cursor, String columnName) { // return cursor.getInt(cursor.getColumnIndexOrThrow(columnName)); // } // } // Path: app/src/main/java/com/nilhcem/droidconde/data/database/model/Speaker.java import android.content.ContentValues; import android.database.Cursor; import com.nilhcem.droidconde.utils.Database; import rx.functions.Func1; package com.nilhcem.droidconde.data.database.model; public class Speaker { public static final String TABLE = "speakers"; public static final String ID = "_id"; public static final String NAME = "name"; public static final String TITLE = "title"; public static final String BIO = "bio"; public static final String WEBSITE = "website"; public static final String TWITTER = "twitter"; public static final String GITHUB = "github"; public static final String PHOTO = "photo"; public static final Func1<Cursor, Speaker> MAPPER = cursor -> {
int id = Database.getInt(cursor, ID);
Nilhcem/droidconde-2016
app/src/test/java/com/nilhcem/droidconde/data/app/DataProviderCacheTest.java
// Path: app/src/main/java/com/nilhcem/droidconde/data/app/model/Session.java // @Value // public class Session implements Parcelable { // // public static final Parcelable.Creator<Session> CREATOR = new Parcelable.Creator<Session>() { // public Session createFromParcel(Parcel source) { // return new Session(source); // } // // public Session[] newArray(int size) { // return new Session[size]; // } // }; // // int id; // String room; // List<Speaker> speakers; // String title; // String description; // LocalDateTime fromTime; // LocalDateTime toTime; // // public Session(int id, String room, List<Speaker> speakers, String title, String description, LocalDateTime fromTime, LocalDateTime toTime) { // this.id = id; // this.room = room; // this.speakers = speakers; // this.title = title; // this.description = description; // this.fromTime = fromTime; // this.toTime = toTime; // } // // protected Session(Parcel in) { // id = in.readInt(); // room = in.readString(); // speakers = in.createTypedArrayList(Speaker.CREATOR); // title = in.readString(); // description = in.readString(); // fromTime = (LocalDateTime) in.readSerializable(); // toTime = (LocalDateTime) in.readSerializable(); // } // // @Override // public int describeContents() { // return 0; // } // // @Override // public void writeToParcel(Parcel dest, int flags) { // dest.writeInt(id); // dest.writeString(room); // dest.writeTypedList(speakers); // dest.writeString(title); // dest.writeString(description); // dest.writeSerializable(fromTime); // dest.writeSerializable(toTime); // } // } // // Path: app/src/main/java/com/nilhcem/droidconde/data/app/model/Speaker.java // @Value // public class Speaker implements Parcelable { // // public static final Parcelable.Creator<Speaker> CREATOR = new Parcelable.Creator<Speaker>() { // public Speaker createFromParcel(Parcel source) { // return new Speaker(source); // } // // public Speaker[] newArray(int size) { // return new Speaker[size]; // } // }; // // int id; // String name; // String title; // String bio; // String website; // String twitter; // String github; // String photo; // // public Speaker(int id, String name, String title, String bio, String website, String twitter, String github, String photo) { // this.id = id; // this.name = name; // this.title = title; // this.bio = bio; // this.website = website; // this.twitter = twitter; // this.github = github; // this.photo = photo; // } // // protected Speaker(Parcel in) { // id = in.readInt(); // name = in.readString(); // title = in.readString(); // bio = in.readString(); // website = in.readString(); // twitter = in.readString(); // github = in.readString(); // photo = in.readString(); // } // // @Override // public int describeContents() { // return 0; // } // // @Override // public void writeToParcel(Parcel dest, int flags) { // dest.writeInt(id); // dest.writeString(name); // dest.writeString(title); // dest.writeString(bio); // dest.writeString(website); // dest.writeString(twitter); // dest.writeString(github); // dest.writeString(photo); // } // }
import android.os.Build; import com.nilhcem.droidconde.BuildConfig; import com.nilhcem.droidconde.data.app.model.Session; import com.nilhcem.droidconde.data.app.model.Speaker; import org.junit.Test; import org.junit.runner.RunWith; import org.robolectric.RobolectricGradleTestRunner; import org.robolectric.annotation.Config; import org.threeten.bp.LocalDateTime; import java.util.Arrays; import java.util.List; import static com.google.common.truth.Truth.assertThat;
package com.nilhcem.droidconde.data.app; @RunWith(RobolectricGradleTestRunner.class) @Config(constants = BuildConfig.class, sdk = Build.VERSION_CODES.LOLLIPOP) public class DataProviderCacheTest { private final DataProviderCache cache = new DataProviderCache();
// Path: app/src/main/java/com/nilhcem/droidconde/data/app/model/Session.java // @Value // public class Session implements Parcelable { // // public static final Parcelable.Creator<Session> CREATOR = new Parcelable.Creator<Session>() { // public Session createFromParcel(Parcel source) { // return new Session(source); // } // // public Session[] newArray(int size) { // return new Session[size]; // } // }; // // int id; // String room; // List<Speaker> speakers; // String title; // String description; // LocalDateTime fromTime; // LocalDateTime toTime; // // public Session(int id, String room, List<Speaker> speakers, String title, String description, LocalDateTime fromTime, LocalDateTime toTime) { // this.id = id; // this.room = room; // this.speakers = speakers; // this.title = title; // this.description = description; // this.fromTime = fromTime; // this.toTime = toTime; // } // // protected Session(Parcel in) { // id = in.readInt(); // room = in.readString(); // speakers = in.createTypedArrayList(Speaker.CREATOR); // title = in.readString(); // description = in.readString(); // fromTime = (LocalDateTime) in.readSerializable(); // toTime = (LocalDateTime) in.readSerializable(); // } // // @Override // public int describeContents() { // return 0; // } // // @Override // public void writeToParcel(Parcel dest, int flags) { // dest.writeInt(id); // dest.writeString(room); // dest.writeTypedList(speakers); // dest.writeString(title); // dest.writeString(description); // dest.writeSerializable(fromTime); // dest.writeSerializable(toTime); // } // } // // Path: app/src/main/java/com/nilhcem/droidconde/data/app/model/Speaker.java // @Value // public class Speaker implements Parcelable { // // public static final Parcelable.Creator<Speaker> CREATOR = new Parcelable.Creator<Speaker>() { // public Speaker createFromParcel(Parcel source) { // return new Speaker(source); // } // // public Speaker[] newArray(int size) { // return new Speaker[size]; // } // }; // // int id; // String name; // String title; // String bio; // String website; // String twitter; // String github; // String photo; // // public Speaker(int id, String name, String title, String bio, String website, String twitter, String github, String photo) { // this.id = id; // this.name = name; // this.title = title; // this.bio = bio; // this.website = website; // this.twitter = twitter; // this.github = github; // this.photo = photo; // } // // protected Speaker(Parcel in) { // id = in.readInt(); // name = in.readString(); // title = in.readString(); // bio = in.readString(); // website = in.readString(); // twitter = in.readString(); // github = in.readString(); // photo = in.readString(); // } // // @Override // public int describeContents() { // return 0; // } // // @Override // public void writeToParcel(Parcel dest, int flags) { // dest.writeInt(id); // dest.writeString(name); // dest.writeString(title); // dest.writeString(bio); // dest.writeString(website); // dest.writeString(twitter); // dest.writeString(github); // dest.writeString(photo); // } // } // Path: app/src/test/java/com/nilhcem/droidconde/data/app/DataProviderCacheTest.java import android.os.Build; import com.nilhcem.droidconde.BuildConfig; import com.nilhcem.droidconde.data.app.model.Session; import com.nilhcem.droidconde.data.app.model.Speaker; import org.junit.Test; import org.junit.runner.RunWith; import org.robolectric.RobolectricGradleTestRunner; import org.robolectric.annotation.Config; import org.threeten.bp.LocalDateTime; import java.util.Arrays; import java.util.List; import static com.google.common.truth.Truth.assertThat; package com.nilhcem.droidconde.data.app; @RunWith(RobolectricGradleTestRunner.class) @Config(constants = BuildConfig.class, sdk = Build.VERSION_CODES.LOLLIPOP) public class DataProviderCacheTest { private final DataProviderCache cache = new DataProviderCache();
private final Session session1 = new Session(1, null, null, null, null, null, null);
Nilhcem/droidconde-2016
app/src/test/java/com/nilhcem/droidconde/data/app/DataProviderCacheTest.java
// Path: app/src/main/java/com/nilhcem/droidconde/data/app/model/Session.java // @Value // public class Session implements Parcelable { // // public static final Parcelable.Creator<Session> CREATOR = new Parcelable.Creator<Session>() { // public Session createFromParcel(Parcel source) { // return new Session(source); // } // // public Session[] newArray(int size) { // return new Session[size]; // } // }; // // int id; // String room; // List<Speaker> speakers; // String title; // String description; // LocalDateTime fromTime; // LocalDateTime toTime; // // public Session(int id, String room, List<Speaker> speakers, String title, String description, LocalDateTime fromTime, LocalDateTime toTime) { // this.id = id; // this.room = room; // this.speakers = speakers; // this.title = title; // this.description = description; // this.fromTime = fromTime; // this.toTime = toTime; // } // // protected Session(Parcel in) { // id = in.readInt(); // room = in.readString(); // speakers = in.createTypedArrayList(Speaker.CREATOR); // title = in.readString(); // description = in.readString(); // fromTime = (LocalDateTime) in.readSerializable(); // toTime = (LocalDateTime) in.readSerializable(); // } // // @Override // public int describeContents() { // return 0; // } // // @Override // public void writeToParcel(Parcel dest, int flags) { // dest.writeInt(id); // dest.writeString(room); // dest.writeTypedList(speakers); // dest.writeString(title); // dest.writeString(description); // dest.writeSerializable(fromTime); // dest.writeSerializable(toTime); // } // } // // Path: app/src/main/java/com/nilhcem/droidconde/data/app/model/Speaker.java // @Value // public class Speaker implements Parcelable { // // public static final Parcelable.Creator<Speaker> CREATOR = new Parcelable.Creator<Speaker>() { // public Speaker createFromParcel(Parcel source) { // return new Speaker(source); // } // // public Speaker[] newArray(int size) { // return new Speaker[size]; // } // }; // // int id; // String name; // String title; // String bio; // String website; // String twitter; // String github; // String photo; // // public Speaker(int id, String name, String title, String bio, String website, String twitter, String github, String photo) { // this.id = id; // this.name = name; // this.title = title; // this.bio = bio; // this.website = website; // this.twitter = twitter; // this.github = github; // this.photo = photo; // } // // protected Speaker(Parcel in) { // id = in.readInt(); // name = in.readString(); // title = in.readString(); // bio = in.readString(); // website = in.readString(); // twitter = in.readString(); // github = in.readString(); // photo = in.readString(); // } // // @Override // public int describeContents() { // return 0; // } // // @Override // public void writeToParcel(Parcel dest, int flags) { // dest.writeInt(id); // dest.writeString(name); // dest.writeString(title); // dest.writeString(bio); // dest.writeString(website); // dest.writeString(twitter); // dest.writeString(github); // dest.writeString(photo); // } // }
import android.os.Build; import com.nilhcem.droidconde.BuildConfig; import com.nilhcem.droidconde.data.app.model.Session; import com.nilhcem.droidconde.data.app.model.Speaker; import org.junit.Test; import org.junit.runner.RunWith; import org.robolectric.RobolectricGradleTestRunner; import org.robolectric.annotation.Config; import org.threeten.bp.LocalDateTime; import java.util.Arrays; import java.util.List; import static com.google.common.truth.Truth.assertThat;
package com.nilhcem.droidconde.data.app; @RunWith(RobolectricGradleTestRunner.class) @Config(constants = BuildConfig.class, sdk = Build.VERSION_CODES.LOLLIPOP) public class DataProviderCacheTest { private final DataProviderCache cache = new DataProviderCache(); private final Session session1 = new Session(1, null, null, null, null, null, null); private final Session session2 = new Session(2, null, null, null, null, null, null); private final List<Session> sessions = Arrays.asList(session1, session2);
// Path: app/src/main/java/com/nilhcem/droidconde/data/app/model/Session.java // @Value // public class Session implements Parcelable { // // public static final Parcelable.Creator<Session> CREATOR = new Parcelable.Creator<Session>() { // public Session createFromParcel(Parcel source) { // return new Session(source); // } // // public Session[] newArray(int size) { // return new Session[size]; // } // }; // // int id; // String room; // List<Speaker> speakers; // String title; // String description; // LocalDateTime fromTime; // LocalDateTime toTime; // // public Session(int id, String room, List<Speaker> speakers, String title, String description, LocalDateTime fromTime, LocalDateTime toTime) { // this.id = id; // this.room = room; // this.speakers = speakers; // this.title = title; // this.description = description; // this.fromTime = fromTime; // this.toTime = toTime; // } // // protected Session(Parcel in) { // id = in.readInt(); // room = in.readString(); // speakers = in.createTypedArrayList(Speaker.CREATOR); // title = in.readString(); // description = in.readString(); // fromTime = (LocalDateTime) in.readSerializable(); // toTime = (LocalDateTime) in.readSerializable(); // } // // @Override // public int describeContents() { // return 0; // } // // @Override // public void writeToParcel(Parcel dest, int flags) { // dest.writeInt(id); // dest.writeString(room); // dest.writeTypedList(speakers); // dest.writeString(title); // dest.writeString(description); // dest.writeSerializable(fromTime); // dest.writeSerializable(toTime); // } // } // // Path: app/src/main/java/com/nilhcem/droidconde/data/app/model/Speaker.java // @Value // public class Speaker implements Parcelable { // // public static final Parcelable.Creator<Speaker> CREATOR = new Parcelable.Creator<Speaker>() { // public Speaker createFromParcel(Parcel source) { // return new Speaker(source); // } // // public Speaker[] newArray(int size) { // return new Speaker[size]; // } // }; // // int id; // String name; // String title; // String bio; // String website; // String twitter; // String github; // String photo; // // public Speaker(int id, String name, String title, String bio, String website, String twitter, String github, String photo) { // this.id = id; // this.name = name; // this.title = title; // this.bio = bio; // this.website = website; // this.twitter = twitter; // this.github = github; // this.photo = photo; // } // // protected Speaker(Parcel in) { // id = in.readInt(); // name = in.readString(); // title = in.readString(); // bio = in.readString(); // website = in.readString(); // twitter = in.readString(); // github = in.readString(); // photo = in.readString(); // } // // @Override // public int describeContents() { // return 0; // } // // @Override // public void writeToParcel(Parcel dest, int flags) { // dest.writeInt(id); // dest.writeString(name); // dest.writeString(title); // dest.writeString(bio); // dest.writeString(website); // dest.writeString(twitter); // dest.writeString(github); // dest.writeString(photo); // } // } // Path: app/src/test/java/com/nilhcem/droidconde/data/app/DataProviderCacheTest.java import android.os.Build; import com.nilhcem.droidconde.BuildConfig; import com.nilhcem.droidconde.data.app.model.Session; import com.nilhcem.droidconde.data.app.model.Speaker; import org.junit.Test; import org.junit.runner.RunWith; import org.robolectric.RobolectricGradleTestRunner; import org.robolectric.annotation.Config; import org.threeten.bp.LocalDateTime; import java.util.Arrays; import java.util.List; import static com.google.common.truth.Truth.assertThat; package com.nilhcem.droidconde.data.app; @RunWith(RobolectricGradleTestRunner.class) @Config(constants = BuildConfig.class, sdk = Build.VERSION_CODES.LOLLIPOP) public class DataProviderCacheTest { private final DataProviderCache cache = new DataProviderCache(); private final Session session1 = new Session(1, null, null, null, null, null, null); private final Session session2 = new Session(2, null, null, null, null, null, null); private final List<Session> sessions = Arrays.asList(session1, session2);
private final Speaker speaker1 = new Speaker(1, null, null, null, null, null, null, null);
Nilhcem/droidconde-2016
app/src/main/java/com/nilhcem/droidconde/data/network/DroidconService.java
// Path: app/src/main/java/com/nilhcem/droidconde/data/network/model/Session.java // @Value // public class Session { // // int id; // LocalDateTime startAt; // int duration; // int roomId; // List<Integer> speakersId; // String title; // String description; // } // // Path: app/src/main/java/com/nilhcem/droidconde/data/network/model/Speaker.java // @Value // public class Speaker { // // int id; // String name; // String title; // String bio; // String website; // String twitter; // String github; // String photo; // }
import com.nilhcem.droidconde.data.network.model.Session; import com.nilhcem.droidconde.data.network.model.Speaker; import java.util.List; import retrofit2.http.GET; import rx.Observable;
package com.nilhcem.droidconde.data.network; public interface DroidconService { @GET("sessions")
// Path: app/src/main/java/com/nilhcem/droidconde/data/network/model/Session.java // @Value // public class Session { // // int id; // LocalDateTime startAt; // int duration; // int roomId; // List<Integer> speakersId; // String title; // String description; // } // // Path: app/src/main/java/com/nilhcem/droidconde/data/network/model/Speaker.java // @Value // public class Speaker { // // int id; // String name; // String title; // String bio; // String website; // String twitter; // String github; // String photo; // } // Path: app/src/main/java/com/nilhcem/droidconde/data/network/DroidconService.java import com.nilhcem.droidconde.data.network.model.Session; import com.nilhcem.droidconde.data.network.model.Speaker; import java.util.List; import retrofit2.http.GET; import rx.Observable; package com.nilhcem.droidconde.data.network; public interface DroidconService { @GET("sessions")
Observable<List<Session>> loadSessions();
Nilhcem/droidconde-2016
app/src/main/java/com/nilhcem/droidconde/data/network/DroidconService.java
// Path: app/src/main/java/com/nilhcem/droidconde/data/network/model/Session.java // @Value // public class Session { // // int id; // LocalDateTime startAt; // int duration; // int roomId; // List<Integer> speakersId; // String title; // String description; // } // // Path: app/src/main/java/com/nilhcem/droidconde/data/network/model/Speaker.java // @Value // public class Speaker { // // int id; // String name; // String title; // String bio; // String website; // String twitter; // String github; // String photo; // }
import com.nilhcem.droidconde.data.network.model.Session; import com.nilhcem.droidconde.data.network.model.Speaker; import java.util.List; import retrofit2.http.GET; import rx.Observable;
package com.nilhcem.droidconde.data.network; public interface DroidconService { @GET("sessions") Observable<List<Session>> loadSessions(); @GET("speakers")
// Path: app/src/main/java/com/nilhcem/droidconde/data/network/model/Session.java // @Value // public class Session { // // int id; // LocalDateTime startAt; // int duration; // int roomId; // List<Integer> speakersId; // String title; // String description; // } // // Path: app/src/main/java/com/nilhcem/droidconde/data/network/model/Speaker.java // @Value // public class Speaker { // // int id; // String name; // String title; // String bio; // String website; // String twitter; // String github; // String photo; // } // Path: app/src/main/java/com/nilhcem/droidconde/data/network/DroidconService.java import com.nilhcem.droidconde.data.network.model.Session; import com.nilhcem.droidconde.data.network.model.Speaker; import java.util.List; import retrofit2.http.GET; import rx.Observable; package com.nilhcem.droidconde.data.network; public interface DroidconService { @GET("sessions") Observable<List<Session>> loadSessions(); @GET("speakers")
Observable<List<Speaker>> loadSpeakers();
Nilhcem/droidconde-2016
app/src/main/java/com/nilhcem/droidconde/core/dagger/module/DatabaseModule.java
// Path: app/src/main/java/com/nilhcem/droidconde/data/database/DbOpenHelper.java // public class DbOpenHelper extends SQLiteOpenHelper { // // private static final String NAME = "droidcon.db"; // private static final int VERSION = 1; // // public DbOpenHelper(Context context) { // super(context, NAME, null, VERSION); // } // // @Override // public void onCreate(SQLiteDatabase db) { // createSpeakersTable(db); // createSessionsTable(db); // createSelectedSessionsTable(db); // } // // @Override // public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { // } // // private void createSpeakersTable(SQLiteDatabase db) { // db.execSQL("CREATE TABLE " + Speaker.TABLE + " (" + // Speaker.ID + " INTEGER PRIMARY KEY," + // Speaker.NAME + " VARCHAR," + // Speaker.TITLE + " VARCHAR," + // Speaker.BIO + " VARCHAR," + // Speaker.WEBSITE + " VARCHAR," + // Speaker.TWITTER + " VARCHAR," + // Speaker.GITHUB + " VARCHAR," + // Speaker.PHOTO + " VARCHAR);"); // } // // private void createSessionsTable(SQLiteDatabase db) { // db.execSQL("CREATE TABLE " + Session.TABLE + " (" + // Session.ID + " INTEGER PRIMARY KEY," + // Session.START_AT + " VARCHAR," + // Session.DURATION + " INTEGER," + // Session.ROOM_ID + " INTEGER," + // Session.SPEAKERS_IDS + " VARCHAR," + // Session.TITLE + " VARCHAR," + // Session.DESCRIPTION + " VARCHAR);"); // } // // private void createSelectedSessionsTable(SQLiteDatabase db) { // db.execSQL("CREATE TABLE " + SelectedSession.TABLE + " (" + // SelectedSession.ID + " INTEGER PRIMARY KEY AUTOINCREMENT," + // SelectedSession.SLOT_TIME + " VARCHAR," + // SelectedSession.SESSION_ID + " INTEGER);"); // } // }
import android.app.Application; import android.database.sqlite.SQLiteOpenHelper; import com.nilhcem.droidconde.data.database.DbOpenHelper; import com.squareup.sqlbrite.BriteDatabase; import com.squareup.sqlbrite.SqlBrite; import javax.inject.Singleton; import dagger.Module; import dagger.Provides; import rx.schedulers.Schedulers; import timber.log.Timber;
package com.nilhcem.droidconde.core.dagger.module; @Module public class DatabaseModule { static final String TAG = "database"; @Provides @Singleton SQLiteOpenHelper provideSQLiteOpenHelper(Application application) {
// Path: app/src/main/java/com/nilhcem/droidconde/data/database/DbOpenHelper.java // public class DbOpenHelper extends SQLiteOpenHelper { // // private static final String NAME = "droidcon.db"; // private static final int VERSION = 1; // // public DbOpenHelper(Context context) { // super(context, NAME, null, VERSION); // } // // @Override // public void onCreate(SQLiteDatabase db) { // createSpeakersTable(db); // createSessionsTable(db); // createSelectedSessionsTable(db); // } // // @Override // public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { // } // // private void createSpeakersTable(SQLiteDatabase db) { // db.execSQL("CREATE TABLE " + Speaker.TABLE + " (" + // Speaker.ID + " INTEGER PRIMARY KEY," + // Speaker.NAME + " VARCHAR," + // Speaker.TITLE + " VARCHAR," + // Speaker.BIO + " VARCHAR," + // Speaker.WEBSITE + " VARCHAR," + // Speaker.TWITTER + " VARCHAR," + // Speaker.GITHUB + " VARCHAR," + // Speaker.PHOTO + " VARCHAR);"); // } // // private void createSessionsTable(SQLiteDatabase db) { // db.execSQL("CREATE TABLE " + Session.TABLE + " (" + // Session.ID + " INTEGER PRIMARY KEY," + // Session.START_AT + " VARCHAR," + // Session.DURATION + " INTEGER," + // Session.ROOM_ID + " INTEGER," + // Session.SPEAKERS_IDS + " VARCHAR," + // Session.TITLE + " VARCHAR," + // Session.DESCRIPTION + " VARCHAR);"); // } // // private void createSelectedSessionsTable(SQLiteDatabase db) { // db.execSQL("CREATE TABLE " + SelectedSession.TABLE + " (" + // SelectedSession.ID + " INTEGER PRIMARY KEY AUTOINCREMENT," + // SelectedSession.SLOT_TIME + " VARCHAR," + // SelectedSession.SESSION_ID + " INTEGER);"); // } // } // Path: app/src/main/java/com/nilhcem/droidconde/core/dagger/module/DatabaseModule.java import android.app.Application; import android.database.sqlite.SQLiteOpenHelper; import com.nilhcem.droidconde.data.database.DbOpenHelper; import com.squareup.sqlbrite.BriteDatabase; import com.squareup.sqlbrite.SqlBrite; import javax.inject.Singleton; import dagger.Module; import dagger.Provides; import rx.schedulers.Schedulers; import timber.log.Timber; package com.nilhcem.droidconde.core.dagger.module; @Module public class DatabaseModule { static final String TAG = "database"; @Provides @Singleton SQLiteOpenHelper provideSQLiteOpenHelper(Application application) {
return new DbOpenHelper(application);
Nilhcem/droidconde-2016
app/src/main/java/com/nilhcem/droidconde/core/dagger/module/ApiModule.java
// Path: app/src/internal/java/com/nilhcem/droidconde/data/network/ApiEndpoint.java // @ToString // public enum ApiEndpoint { // // PROD(BuildConfig.API_ENDPOINT), // MOCK(BuildConfig.MOCK_ENDPOINT), // CUSTOM(null); // // private static final String PREFS_NAME = "api_endpoint"; // private static final String PREFS_KEY_NAME = "name"; // private static final String PREFS_KEY_URL = "url"; // // public String url; // // ApiEndpoint(String url) { // this.url = url; // } // // public static ApiEndpoint get(Context context) { // SharedPreferences prefs = context.getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE); // String prefsName = prefs.getString(PREFS_KEY_NAME, null); // if (prefsName != null) { // ApiEndpoint endpoint = valueOf(prefsName); // if (endpoint == CUSTOM) { // endpoint.url = prefs.getString(PREFS_KEY_URL, null); // } // return endpoint; // } // return PROD; // } // // public static void persist(Context context, @NonNull ApiEndpoint endpoint) { // Preconditions.checkArgument(endpoint != CUSTOM); // persistEndpoint(context, endpoint, null); // } // // public static void persist(Context context, @NonNull String url) { // persistEndpoint(context, CUSTOM, url); // } // // @SuppressLint("CommitPrefEdits") // private static void persistEndpoint(Context context, @NonNull ApiEndpoint endpoint, @Nullable String url) { // SharedPreferences.Editor editor = context.getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE).edit(); // editor.putString(PREFS_KEY_NAME, endpoint.name()); // // if (url == null) { // editor.remove(PREFS_KEY_URL); // } else { // editor.putString(PREFS_KEY_URL, url); // } // // editor.commit(); // } // } // // Path: app/src/main/java/com/nilhcem/droidconde/data/network/DroidconService.java // public interface DroidconService { // // @GET("sessions") // Observable<List<Session>> loadSessions(); // // @GET("speakers") // Observable<List<Speaker>> loadSpeakers(); // }
import android.app.Application; import com.nilhcem.droidconde.data.network.ApiEndpoint; import com.nilhcem.droidconde.data.network.DroidconService; import com.squareup.moshi.Moshi; import javax.inject.Singleton; import dagger.Module; import dagger.Provides; import okhttp3.OkHttpClient; import retrofit2.Retrofit; import retrofit2.adapter.rxjava.RxJavaCallAdapterFactory; import retrofit2.converter.moshi.MoshiConverterFactory;
package com.nilhcem.droidconde.core.dagger.module; @Module public final class ApiModule {
// Path: app/src/internal/java/com/nilhcem/droidconde/data/network/ApiEndpoint.java // @ToString // public enum ApiEndpoint { // // PROD(BuildConfig.API_ENDPOINT), // MOCK(BuildConfig.MOCK_ENDPOINT), // CUSTOM(null); // // private static final String PREFS_NAME = "api_endpoint"; // private static final String PREFS_KEY_NAME = "name"; // private static final String PREFS_KEY_URL = "url"; // // public String url; // // ApiEndpoint(String url) { // this.url = url; // } // // public static ApiEndpoint get(Context context) { // SharedPreferences prefs = context.getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE); // String prefsName = prefs.getString(PREFS_KEY_NAME, null); // if (prefsName != null) { // ApiEndpoint endpoint = valueOf(prefsName); // if (endpoint == CUSTOM) { // endpoint.url = prefs.getString(PREFS_KEY_URL, null); // } // return endpoint; // } // return PROD; // } // // public static void persist(Context context, @NonNull ApiEndpoint endpoint) { // Preconditions.checkArgument(endpoint != CUSTOM); // persistEndpoint(context, endpoint, null); // } // // public static void persist(Context context, @NonNull String url) { // persistEndpoint(context, CUSTOM, url); // } // // @SuppressLint("CommitPrefEdits") // private static void persistEndpoint(Context context, @NonNull ApiEndpoint endpoint, @Nullable String url) { // SharedPreferences.Editor editor = context.getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE).edit(); // editor.putString(PREFS_KEY_NAME, endpoint.name()); // // if (url == null) { // editor.remove(PREFS_KEY_URL); // } else { // editor.putString(PREFS_KEY_URL, url); // } // // editor.commit(); // } // } // // Path: app/src/main/java/com/nilhcem/droidconde/data/network/DroidconService.java // public interface DroidconService { // // @GET("sessions") // Observable<List<Session>> loadSessions(); // // @GET("speakers") // Observable<List<Speaker>> loadSpeakers(); // } // Path: app/src/main/java/com/nilhcem/droidconde/core/dagger/module/ApiModule.java import android.app.Application; import com.nilhcem.droidconde.data.network.ApiEndpoint; import com.nilhcem.droidconde.data.network.DroidconService; import com.squareup.moshi.Moshi; import javax.inject.Singleton; import dagger.Module; import dagger.Provides; import okhttp3.OkHttpClient; import retrofit2.Retrofit; import retrofit2.adapter.rxjava.RxJavaCallAdapterFactory; import retrofit2.converter.moshi.MoshiConverterFactory; package com.nilhcem.droidconde.core.dagger.module; @Module public final class ApiModule {
@Provides @Singleton ApiEndpoint provideApiEndpoint(Application context) {
Nilhcem/droidconde-2016
app/src/main/java/com/nilhcem/droidconde/core/dagger/module/ApiModule.java
// Path: app/src/internal/java/com/nilhcem/droidconde/data/network/ApiEndpoint.java // @ToString // public enum ApiEndpoint { // // PROD(BuildConfig.API_ENDPOINT), // MOCK(BuildConfig.MOCK_ENDPOINT), // CUSTOM(null); // // private static final String PREFS_NAME = "api_endpoint"; // private static final String PREFS_KEY_NAME = "name"; // private static final String PREFS_KEY_URL = "url"; // // public String url; // // ApiEndpoint(String url) { // this.url = url; // } // // public static ApiEndpoint get(Context context) { // SharedPreferences prefs = context.getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE); // String prefsName = prefs.getString(PREFS_KEY_NAME, null); // if (prefsName != null) { // ApiEndpoint endpoint = valueOf(prefsName); // if (endpoint == CUSTOM) { // endpoint.url = prefs.getString(PREFS_KEY_URL, null); // } // return endpoint; // } // return PROD; // } // // public static void persist(Context context, @NonNull ApiEndpoint endpoint) { // Preconditions.checkArgument(endpoint != CUSTOM); // persistEndpoint(context, endpoint, null); // } // // public static void persist(Context context, @NonNull String url) { // persistEndpoint(context, CUSTOM, url); // } // // @SuppressLint("CommitPrefEdits") // private static void persistEndpoint(Context context, @NonNull ApiEndpoint endpoint, @Nullable String url) { // SharedPreferences.Editor editor = context.getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE).edit(); // editor.putString(PREFS_KEY_NAME, endpoint.name()); // // if (url == null) { // editor.remove(PREFS_KEY_URL); // } else { // editor.putString(PREFS_KEY_URL, url); // } // // editor.commit(); // } // } // // Path: app/src/main/java/com/nilhcem/droidconde/data/network/DroidconService.java // public interface DroidconService { // // @GET("sessions") // Observable<List<Session>> loadSessions(); // // @GET("speakers") // Observable<List<Speaker>> loadSpeakers(); // }
import android.app.Application; import com.nilhcem.droidconde.data.network.ApiEndpoint; import com.nilhcem.droidconde.data.network.DroidconService; import com.squareup.moshi.Moshi; import javax.inject.Singleton; import dagger.Module; import dagger.Provides; import okhttp3.OkHttpClient; import retrofit2.Retrofit; import retrofit2.adapter.rxjava.RxJavaCallAdapterFactory; import retrofit2.converter.moshi.MoshiConverterFactory;
package com.nilhcem.droidconde.core.dagger.module; @Module public final class ApiModule { @Provides @Singleton ApiEndpoint provideApiEndpoint(Application context) { return ApiEndpoint.get(context); } @Provides @Singleton Retrofit provideRetrofit(OkHttpClient client, Moshi moshi, ApiEndpoint endpoint) { return new Retrofit.Builder() .client(client) .baseUrl(endpoint.url) .addConverterFactory(MoshiConverterFactory.create(moshi)) .addCallAdapterFactory(RxJavaCallAdapterFactory.create()) .build(); } @Provides @Singleton
// Path: app/src/internal/java/com/nilhcem/droidconde/data/network/ApiEndpoint.java // @ToString // public enum ApiEndpoint { // // PROD(BuildConfig.API_ENDPOINT), // MOCK(BuildConfig.MOCK_ENDPOINT), // CUSTOM(null); // // private static final String PREFS_NAME = "api_endpoint"; // private static final String PREFS_KEY_NAME = "name"; // private static final String PREFS_KEY_URL = "url"; // // public String url; // // ApiEndpoint(String url) { // this.url = url; // } // // public static ApiEndpoint get(Context context) { // SharedPreferences prefs = context.getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE); // String prefsName = prefs.getString(PREFS_KEY_NAME, null); // if (prefsName != null) { // ApiEndpoint endpoint = valueOf(prefsName); // if (endpoint == CUSTOM) { // endpoint.url = prefs.getString(PREFS_KEY_URL, null); // } // return endpoint; // } // return PROD; // } // // public static void persist(Context context, @NonNull ApiEndpoint endpoint) { // Preconditions.checkArgument(endpoint != CUSTOM); // persistEndpoint(context, endpoint, null); // } // // public static void persist(Context context, @NonNull String url) { // persistEndpoint(context, CUSTOM, url); // } // // @SuppressLint("CommitPrefEdits") // private static void persistEndpoint(Context context, @NonNull ApiEndpoint endpoint, @Nullable String url) { // SharedPreferences.Editor editor = context.getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE).edit(); // editor.putString(PREFS_KEY_NAME, endpoint.name()); // // if (url == null) { // editor.remove(PREFS_KEY_URL); // } else { // editor.putString(PREFS_KEY_URL, url); // } // // editor.commit(); // } // } // // Path: app/src/main/java/com/nilhcem/droidconde/data/network/DroidconService.java // public interface DroidconService { // // @GET("sessions") // Observable<List<Session>> loadSessions(); // // @GET("speakers") // Observable<List<Speaker>> loadSpeakers(); // } // Path: app/src/main/java/com/nilhcem/droidconde/core/dagger/module/ApiModule.java import android.app.Application; import com.nilhcem.droidconde.data.network.ApiEndpoint; import com.nilhcem.droidconde.data.network.DroidconService; import com.squareup.moshi.Moshi; import javax.inject.Singleton; import dagger.Module; import dagger.Provides; import okhttp3.OkHttpClient; import retrofit2.Retrofit; import retrofit2.adapter.rxjava.RxJavaCallAdapterFactory; import retrofit2.converter.moshi.MoshiConverterFactory; package com.nilhcem.droidconde.core.dagger.module; @Module public final class ApiModule { @Provides @Singleton ApiEndpoint provideApiEndpoint(Application context) { return ApiEndpoint.get(context); } @Provides @Singleton Retrofit provideRetrofit(OkHttpClient client, Moshi moshi, ApiEndpoint endpoint) { return new Retrofit.Builder() .client(client) .baseUrl(endpoint.url) .addConverterFactory(MoshiConverterFactory.create(moshi)) .addCallAdapterFactory(RxJavaCallAdapterFactory.create()) .build(); } @Provides @Singleton
DroidconService provideDroidconService(Retrofit retrofit) {
Nilhcem/droidconde-2016
app/src/test/java/com/nilhcem/droidconde/data/app/SelectedSessionsMemoryTest.java
// Path: app/src/main/java/com/nilhcem/droidconde/data/app/model/Session.java // @Value // public class Session implements Parcelable { // // public static final Parcelable.Creator<Session> CREATOR = new Parcelable.Creator<Session>() { // public Session createFromParcel(Parcel source) { // return new Session(source); // } // // public Session[] newArray(int size) { // return new Session[size]; // } // }; // // int id; // String room; // List<Speaker> speakers; // String title; // String description; // LocalDateTime fromTime; // LocalDateTime toTime; // // public Session(int id, String room, List<Speaker> speakers, String title, String description, LocalDateTime fromTime, LocalDateTime toTime) { // this.id = id; // this.room = room; // this.speakers = speakers; // this.title = title; // this.description = description; // this.fromTime = fromTime; // this.toTime = toTime; // } // // protected Session(Parcel in) { // id = in.readInt(); // room = in.readString(); // speakers = in.createTypedArrayList(Speaker.CREATOR); // title = in.readString(); // description = in.readString(); // fromTime = (LocalDateTime) in.readSerializable(); // toTime = (LocalDateTime) in.readSerializable(); // } // // @Override // public int describeContents() { // return 0; // } // // @Override // public void writeToParcel(Parcel dest, int flags) { // dest.writeInt(id); // dest.writeString(room); // dest.writeTypedList(speakers); // dest.writeString(title); // dest.writeString(description); // dest.writeSerializable(fromTime); // dest.writeSerializable(toTime); // } // }
import android.os.Build; import com.nilhcem.droidconde.BuildConfig; import com.nilhcem.droidconde.data.app.model.Session; import org.junit.Test; import org.junit.runner.RunWith; import org.robolectric.RobolectricGradleTestRunner; import org.robolectric.annotation.Config; import org.threeten.bp.LocalDateTime; import java.util.HashMap; import java.util.Map; import static com.google.common.truth.Truth.assertThat;
package com.nilhcem.droidconde.data.app; @RunWith(RobolectricGradleTestRunner.class) @Config(constants = BuildConfig.class, sdk = Build.VERSION_CODES.LOLLIPOP) public class SelectedSessionsMemoryTest { private final SelectedSessionsMemory memory = new SelectedSessionsMemory(); @Test public void should_set_selected_sessions() { // Given LocalDateTime now = LocalDateTime.now(); Map<LocalDateTime, Integer> map = new HashMap<>(); map.put(now, 1); // When assertThat(memory.get(now)).isNull(); memory.setSelectedSessions(map); // Then assertThat(memory.get(now)).isEqualTo(1); } @Test public void should_remove_previous_session_when_adding_a_new_one_for_the_same_slot_time() { // Given LocalDateTime now = LocalDateTime.now(); Map<LocalDateTime, Integer> map = new HashMap<>(); map.put(now, 1); memory.setSelectedSessions(map);
// Path: app/src/main/java/com/nilhcem/droidconde/data/app/model/Session.java // @Value // public class Session implements Parcelable { // // public static final Parcelable.Creator<Session> CREATOR = new Parcelable.Creator<Session>() { // public Session createFromParcel(Parcel source) { // return new Session(source); // } // // public Session[] newArray(int size) { // return new Session[size]; // } // }; // // int id; // String room; // List<Speaker> speakers; // String title; // String description; // LocalDateTime fromTime; // LocalDateTime toTime; // // public Session(int id, String room, List<Speaker> speakers, String title, String description, LocalDateTime fromTime, LocalDateTime toTime) { // this.id = id; // this.room = room; // this.speakers = speakers; // this.title = title; // this.description = description; // this.fromTime = fromTime; // this.toTime = toTime; // } // // protected Session(Parcel in) { // id = in.readInt(); // room = in.readString(); // speakers = in.createTypedArrayList(Speaker.CREATOR); // title = in.readString(); // description = in.readString(); // fromTime = (LocalDateTime) in.readSerializable(); // toTime = (LocalDateTime) in.readSerializable(); // } // // @Override // public int describeContents() { // return 0; // } // // @Override // public void writeToParcel(Parcel dest, int flags) { // dest.writeInt(id); // dest.writeString(room); // dest.writeTypedList(speakers); // dest.writeString(title); // dest.writeString(description); // dest.writeSerializable(fromTime); // dest.writeSerializable(toTime); // } // } // Path: app/src/test/java/com/nilhcem/droidconde/data/app/SelectedSessionsMemoryTest.java import android.os.Build; import com.nilhcem.droidconde.BuildConfig; import com.nilhcem.droidconde.data.app.model.Session; import org.junit.Test; import org.junit.runner.RunWith; import org.robolectric.RobolectricGradleTestRunner; import org.robolectric.annotation.Config; import org.threeten.bp.LocalDateTime; import java.util.HashMap; import java.util.Map; import static com.google.common.truth.Truth.assertThat; package com.nilhcem.droidconde.data.app; @RunWith(RobolectricGradleTestRunner.class) @Config(constants = BuildConfig.class, sdk = Build.VERSION_CODES.LOLLIPOP) public class SelectedSessionsMemoryTest { private final SelectedSessionsMemory memory = new SelectedSessionsMemory(); @Test public void should_set_selected_sessions() { // Given LocalDateTime now = LocalDateTime.now(); Map<LocalDateTime, Integer> map = new HashMap<>(); map.put(now, 1); // When assertThat(memory.get(now)).isNull(); memory.setSelectedSessions(map); // Then assertThat(memory.get(now)).isEqualTo(1); } @Test public void should_remove_previous_session_when_adding_a_new_one_for_the_same_slot_time() { // Given LocalDateTime now = LocalDateTime.now(); Map<LocalDateTime, Integer> map = new HashMap<>(); map.put(now, 1); memory.setSelectedSessions(map);
Session toAdd = new Session(3, null, null, null, null, now, now.plusMinutes(30));
Nilhcem/droidconde-2016
app/src/main/java/com/nilhcem/droidconde/ui/venue/ZoomableImageActivity.java
// Path: app/src/main/java/com/nilhcem/droidconde/ui/BaseActivity.java // public abstract class BaseActivity<P extends BaseActivityPresenter> extends AppCompatActivity { // // protected P presenter; // // protected abstract P newPresenter(); // // @Override // protected void onCreate(@Nullable Bundle savedInstanceState) { // super.onCreate(savedInstanceState); // presenter = newPresenter(); // } // // @Override // protected void onPostCreate(@Nullable Bundle savedInstanceState) { // super.onPostCreate(savedInstanceState); // presenter.onPostCreate(savedInstanceState); // } // // @Override // protected void onResume() { // super.onResume(); // presenter.onResume(); // } // // @Override // protected void onSaveInstanceState(Bundle outState) { // super.onSaveInstanceState(outState); // presenter.onSaveInstanceState(outState); // } // // @Override // protected void onRestoreInstanceState(Bundle savedInstanceState) { // super.onRestoreInstanceState(savedInstanceState); // presenter.onRestoreInstanceState(savedInstanceState); // } // // @Override // public void setContentView(@LayoutRes int layoutResID) { // super.setContentView(layoutResID); // ButterKnife.bind(this); // } // // @Override // public boolean onOptionsItemSelected(MenuItem item) { // if (item.getItemId() == android.R.id.home) { // onBackPressed(); // return true; // } // return super.onOptionsItemSelected(item); // } // // @Override // public void onBackPressed() { // if (presenter.onBackPressed()) { // return; // } // super.onBackPressed(); // } // // @Override // protected void onDestroy() { // presenter = null; // super.onDestroy(); // } // } // // Path: app/src/main/java/com/nilhcem/droidconde/ui/BaseActivityPresenter.java // public abstract class BaseActivityPresenter<V> extends BasePresenter<V> { // // public BaseActivityPresenter(V view) { // super(view); // } // // public void onPostCreate(Bundle savedInstanceState) { // // Nothing to do by default // } // // public void onResume() { // // Nothing to do by default // } // // @CallSuper // public void onSaveInstanceState(Bundle outState) { // Icepick.saveInstanceState(this, outState); // } // // @CallSuper // public void onRestoreInstanceState(Bundle savedInstanceState) { // Icepick.restoreInstanceState(this, savedInstanceState); // } // // public void onNavigationItemSelected(@IdRes int itemId) { // // Nothing to do by default // } // // public boolean onBackPressed() { // return false; // } // }
import android.os.Bundle; import android.support.annotation.Nullable; import android.support.v4.content.ContextCompat; import com.nilhcem.droidconde.R; import com.nilhcem.droidconde.ui.BaseActivity; import com.nilhcem.droidconde.ui.BaseActivityPresenter; import se.emilsjolander.intentbuilder.IntentBuilder; import uk.co.senab.photoview.PhotoView;
package com.nilhcem.droidconde.ui.venue; @IntentBuilder public class ZoomableImageActivity extends BaseActivity<ZoomableImageActivity.ZoomableImageActivityPresenter> { @Override protected void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); ZoomableImageActivityIntentBuilder.inject(getIntent(), this); PhotoView view = new PhotoView(this); view.setImageDrawable(ContextCompat.getDrawable(this, R.drawable.venue_rooms)); view.setBackgroundColor(ContextCompat.getColor(this, android.R.color.white)); getSupportActionBar().setTitle(R.string.venue_see_rooms); setContentView(view); } @Override protected ZoomableImageActivityPresenter newPresenter() { return new ZoomableImageActivityPresenter(this); }
// Path: app/src/main/java/com/nilhcem/droidconde/ui/BaseActivity.java // public abstract class BaseActivity<P extends BaseActivityPresenter> extends AppCompatActivity { // // protected P presenter; // // protected abstract P newPresenter(); // // @Override // protected void onCreate(@Nullable Bundle savedInstanceState) { // super.onCreate(savedInstanceState); // presenter = newPresenter(); // } // // @Override // protected void onPostCreate(@Nullable Bundle savedInstanceState) { // super.onPostCreate(savedInstanceState); // presenter.onPostCreate(savedInstanceState); // } // // @Override // protected void onResume() { // super.onResume(); // presenter.onResume(); // } // // @Override // protected void onSaveInstanceState(Bundle outState) { // super.onSaveInstanceState(outState); // presenter.onSaveInstanceState(outState); // } // // @Override // protected void onRestoreInstanceState(Bundle savedInstanceState) { // super.onRestoreInstanceState(savedInstanceState); // presenter.onRestoreInstanceState(savedInstanceState); // } // // @Override // public void setContentView(@LayoutRes int layoutResID) { // super.setContentView(layoutResID); // ButterKnife.bind(this); // } // // @Override // public boolean onOptionsItemSelected(MenuItem item) { // if (item.getItemId() == android.R.id.home) { // onBackPressed(); // return true; // } // return super.onOptionsItemSelected(item); // } // // @Override // public void onBackPressed() { // if (presenter.onBackPressed()) { // return; // } // super.onBackPressed(); // } // // @Override // protected void onDestroy() { // presenter = null; // super.onDestroy(); // } // } // // Path: app/src/main/java/com/nilhcem/droidconde/ui/BaseActivityPresenter.java // public abstract class BaseActivityPresenter<V> extends BasePresenter<V> { // // public BaseActivityPresenter(V view) { // super(view); // } // // public void onPostCreate(Bundle savedInstanceState) { // // Nothing to do by default // } // // public void onResume() { // // Nothing to do by default // } // // @CallSuper // public void onSaveInstanceState(Bundle outState) { // Icepick.saveInstanceState(this, outState); // } // // @CallSuper // public void onRestoreInstanceState(Bundle savedInstanceState) { // Icepick.restoreInstanceState(this, savedInstanceState); // } // // public void onNavigationItemSelected(@IdRes int itemId) { // // Nothing to do by default // } // // public boolean onBackPressed() { // return false; // } // } // Path: app/src/main/java/com/nilhcem/droidconde/ui/venue/ZoomableImageActivity.java import android.os.Bundle; import android.support.annotation.Nullable; import android.support.v4.content.ContextCompat; import com.nilhcem.droidconde.R; import com.nilhcem.droidconde.ui.BaseActivity; import com.nilhcem.droidconde.ui.BaseActivityPresenter; import se.emilsjolander.intentbuilder.IntentBuilder; import uk.co.senab.photoview.PhotoView; package com.nilhcem.droidconde.ui.venue; @IntentBuilder public class ZoomableImageActivity extends BaseActivity<ZoomableImageActivity.ZoomableImageActivityPresenter> { @Override protected void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); ZoomableImageActivityIntentBuilder.inject(getIntent(), this); PhotoView view = new PhotoView(this); view.setImageDrawable(ContextCompat.getDrawable(this, R.drawable.venue_rooms)); view.setBackgroundColor(ContextCompat.getColor(this, android.R.color.white)); getSupportActionBar().setTitle(R.string.venue_see_rooms); setContentView(view); } @Override protected ZoomableImageActivityPresenter newPresenter() { return new ZoomableImageActivityPresenter(this); }
static class ZoomableImageActivityPresenter extends BaseActivityPresenter<ZoomableImageActivity> {
Nilhcem/droidconde-2016
app/src/main/java/com/nilhcem/droidconde/data/app/SelectedSessionsMemory.java
// Path: app/src/main/java/com/nilhcem/droidconde/data/app/model/Session.java // @Value // public class Session implements Parcelable { // // public static final Parcelable.Creator<Session> CREATOR = new Parcelable.Creator<Session>() { // public Session createFromParcel(Parcel source) { // return new Session(source); // } // // public Session[] newArray(int size) { // return new Session[size]; // } // }; // // int id; // String room; // List<Speaker> speakers; // String title; // String description; // LocalDateTime fromTime; // LocalDateTime toTime; // // public Session(int id, String room, List<Speaker> speakers, String title, String description, LocalDateTime fromTime, LocalDateTime toTime) { // this.id = id; // this.room = room; // this.speakers = speakers; // this.title = title; // this.description = description; // this.fromTime = fromTime; // this.toTime = toTime; // } // // protected Session(Parcel in) { // id = in.readInt(); // room = in.readString(); // speakers = in.createTypedArrayList(Speaker.CREATOR); // title = in.readString(); // description = in.readString(); // fromTime = (LocalDateTime) in.readSerializable(); // toTime = (LocalDateTime) in.readSerializable(); // } // // @Override // public int describeContents() { // return 0; // } // // @Override // public void writeToParcel(Parcel dest, int flags) { // dest.writeInt(id); // dest.writeString(room); // dest.writeTypedList(speakers); // dest.writeString(title); // dest.writeString(description); // dest.writeSerializable(fromTime); // dest.writeSerializable(toTime); // } // }
import com.nilhcem.droidconde.data.app.model.Session; import org.threeten.bp.LocalDateTime; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; import javax.inject.Inject; import javax.inject.Singleton;
package com.nilhcem.droidconde.data.app; @Singleton public class SelectedSessionsMemory { private final Map<LocalDateTime, Integer> selectedSessions = new ConcurrentHashMap<>(); @Inject public SelectedSessionsMemory() { }
// Path: app/src/main/java/com/nilhcem/droidconde/data/app/model/Session.java // @Value // public class Session implements Parcelable { // // public static final Parcelable.Creator<Session> CREATOR = new Parcelable.Creator<Session>() { // public Session createFromParcel(Parcel source) { // return new Session(source); // } // // public Session[] newArray(int size) { // return new Session[size]; // } // }; // // int id; // String room; // List<Speaker> speakers; // String title; // String description; // LocalDateTime fromTime; // LocalDateTime toTime; // // public Session(int id, String room, List<Speaker> speakers, String title, String description, LocalDateTime fromTime, LocalDateTime toTime) { // this.id = id; // this.room = room; // this.speakers = speakers; // this.title = title; // this.description = description; // this.fromTime = fromTime; // this.toTime = toTime; // } // // protected Session(Parcel in) { // id = in.readInt(); // room = in.readString(); // speakers = in.createTypedArrayList(Speaker.CREATOR); // title = in.readString(); // description = in.readString(); // fromTime = (LocalDateTime) in.readSerializable(); // toTime = (LocalDateTime) in.readSerializable(); // } // // @Override // public int describeContents() { // return 0; // } // // @Override // public void writeToParcel(Parcel dest, int flags) { // dest.writeInt(id); // dest.writeString(room); // dest.writeTypedList(speakers); // dest.writeString(title); // dest.writeString(description); // dest.writeSerializable(fromTime); // dest.writeSerializable(toTime); // } // } // Path: app/src/main/java/com/nilhcem/droidconde/data/app/SelectedSessionsMemory.java import com.nilhcem.droidconde.data.app.model.Session; import org.threeten.bp.LocalDateTime; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; import javax.inject.Inject; import javax.inject.Singleton; package com.nilhcem.droidconde.data.app; @Singleton public class SelectedSessionsMemory { private final Map<LocalDateTime, Integer> selectedSessions = new ConcurrentHashMap<>(); @Inject public SelectedSessionsMemory() { }
public boolean isSelected(Session session) {
Nilhcem/droidconde-2016
app/src/main/java/com/nilhcem/droidconde/data/database/model/SelectedSession.java
// Path: app/src/main/java/com/nilhcem/droidconde/utils/Database.java // public class Database { // // private Database() { // throw new UnsupportedOperationException(); // } // // public static String getString(Cursor cursor, String columnName) { // return cursor.getString(cursor.getColumnIndexOrThrow(columnName)); // } // // public static int getInt(Cursor cursor, String columnName) { // return cursor.getInt(cursor.getColumnIndexOrThrow(columnName)); // } // }
import android.content.ContentValues; import android.database.Cursor; import com.nilhcem.droidconde.utils.Database; import rx.functions.Func1;
package com.nilhcem.droidconde.data.database.model; public class SelectedSession { public static final String TABLE = "selected_sessions"; public static final String ID = "_id"; public static final String SLOT_TIME = "slot_time"; public static final String SESSION_ID = "session_id"; public static final Func1<Cursor, SelectedSession> MAPPER = cursor -> {
// Path: app/src/main/java/com/nilhcem/droidconde/utils/Database.java // public class Database { // // private Database() { // throw new UnsupportedOperationException(); // } // // public static String getString(Cursor cursor, String columnName) { // return cursor.getString(cursor.getColumnIndexOrThrow(columnName)); // } // // public static int getInt(Cursor cursor, String columnName) { // return cursor.getInt(cursor.getColumnIndexOrThrow(columnName)); // } // } // Path: app/src/main/java/com/nilhcem/droidconde/data/database/model/SelectedSession.java import android.content.ContentValues; import android.database.Cursor; import com.nilhcem.droidconde.utils.Database; import rx.functions.Func1; package com.nilhcem.droidconde.data.database.model; public class SelectedSession { public static final String TABLE = "selected_sessions"; public static final String ID = "_id"; public static final String SLOT_TIME = "slot_time"; public static final String SESSION_ID = "session_id"; public static final Func1<Cursor, SelectedSession> MAPPER = cursor -> {
String slotTime = Database.getString(cursor, SLOT_TIME);
Nilhcem/droidconde-2016
app/src/main/java/com/nilhcem/droidconde/ui/sessions/details/SessionDetailsMvp.java
// Path: app/src/main/java/com/nilhcem/droidconde/data/app/model/Session.java // @Value // public class Session implements Parcelable { // // public static final Parcelable.Creator<Session> CREATOR = new Parcelable.Creator<Session>() { // public Session createFromParcel(Parcel source) { // return new Session(source); // } // // public Session[] newArray(int size) { // return new Session[size]; // } // }; // // int id; // String room; // List<Speaker> speakers; // String title; // String description; // LocalDateTime fromTime; // LocalDateTime toTime; // // public Session(int id, String room, List<Speaker> speakers, String title, String description, LocalDateTime fromTime, LocalDateTime toTime) { // this.id = id; // this.room = room; // this.speakers = speakers; // this.title = title; // this.description = description; // this.fromTime = fromTime; // this.toTime = toTime; // } // // protected Session(Parcel in) { // id = in.readInt(); // room = in.readString(); // speakers = in.createTypedArrayList(Speaker.CREATOR); // title = in.readString(); // description = in.readString(); // fromTime = (LocalDateTime) in.readSerializable(); // toTime = (LocalDateTime) in.readSerializable(); // } // // @Override // public int describeContents() { // return 0; // } // // @Override // public void writeToParcel(Parcel dest, int flags) { // dest.writeInt(id); // dest.writeString(room); // dest.writeTypedList(speakers); // dest.writeString(title); // dest.writeString(description); // dest.writeSerializable(fromTime); // dest.writeSerializable(toTime); // } // }
import android.support.annotation.StringRes; import com.nilhcem.droidconde.data.app.model.Session;
package com.nilhcem.droidconde.ui.sessions.details; public interface SessionDetailsMvp { interface View {
// Path: app/src/main/java/com/nilhcem/droidconde/data/app/model/Session.java // @Value // public class Session implements Parcelable { // // public static final Parcelable.Creator<Session> CREATOR = new Parcelable.Creator<Session>() { // public Session createFromParcel(Parcel source) { // return new Session(source); // } // // public Session[] newArray(int size) { // return new Session[size]; // } // }; // // int id; // String room; // List<Speaker> speakers; // String title; // String description; // LocalDateTime fromTime; // LocalDateTime toTime; // // public Session(int id, String room, List<Speaker> speakers, String title, String description, LocalDateTime fromTime, LocalDateTime toTime) { // this.id = id; // this.room = room; // this.speakers = speakers; // this.title = title; // this.description = description; // this.fromTime = fromTime; // this.toTime = toTime; // } // // protected Session(Parcel in) { // id = in.readInt(); // room = in.readString(); // speakers = in.createTypedArrayList(Speaker.CREATOR); // title = in.readString(); // description = in.readString(); // fromTime = (LocalDateTime) in.readSerializable(); // toTime = (LocalDateTime) in.readSerializable(); // } // // @Override // public int describeContents() { // return 0; // } // // @Override // public void writeToParcel(Parcel dest, int flags) { // dest.writeInt(id); // dest.writeString(room); // dest.writeTypedList(speakers); // dest.writeString(title); // dest.writeString(description); // dest.writeSerializable(fromTime); // dest.writeSerializable(toTime); // } // } // Path: app/src/main/java/com/nilhcem/droidconde/ui/sessions/details/SessionDetailsMvp.java import android.support.annotation.StringRes; import com.nilhcem.droidconde.data.app.model.Session; package com.nilhcem.droidconde.ui.sessions.details; public interface SessionDetailsMvp { interface View {
void bindSessionDetails(Session session);
Nilhcem/droidconde-2016
app/src/main/java/com/nilhcem/droidconde/data/app/DataProviderCache.java
// Path: app/src/main/java/com/nilhcem/droidconde/data/app/model/Session.java // @Value // public class Session implements Parcelable { // // public static final Parcelable.Creator<Session> CREATOR = new Parcelable.Creator<Session>() { // public Session createFromParcel(Parcel source) { // return new Session(source); // } // // public Session[] newArray(int size) { // return new Session[size]; // } // }; // // int id; // String room; // List<Speaker> speakers; // String title; // String description; // LocalDateTime fromTime; // LocalDateTime toTime; // // public Session(int id, String room, List<Speaker> speakers, String title, String description, LocalDateTime fromTime, LocalDateTime toTime) { // this.id = id; // this.room = room; // this.speakers = speakers; // this.title = title; // this.description = description; // this.fromTime = fromTime; // this.toTime = toTime; // } // // protected Session(Parcel in) { // id = in.readInt(); // room = in.readString(); // speakers = in.createTypedArrayList(Speaker.CREATOR); // title = in.readString(); // description = in.readString(); // fromTime = (LocalDateTime) in.readSerializable(); // toTime = (LocalDateTime) in.readSerializable(); // } // // @Override // public int describeContents() { // return 0; // } // // @Override // public void writeToParcel(Parcel dest, int flags) { // dest.writeInt(id); // dest.writeString(room); // dest.writeTypedList(speakers); // dest.writeString(title); // dest.writeString(description); // dest.writeSerializable(fromTime); // dest.writeSerializable(toTime); // } // } // // Path: app/src/main/java/com/nilhcem/droidconde/data/app/model/Speaker.java // @Value // public class Speaker implements Parcelable { // // public static final Parcelable.Creator<Speaker> CREATOR = new Parcelable.Creator<Speaker>() { // public Speaker createFromParcel(Parcel source) { // return new Speaker(source); // } // // public Speaker[] newArray(int size) { // return new Speaker[size]; // } // }; // // int id; // String name; // String title; // String bio; // String website; // String twitter; // String github; // String photo; // // public Speaker(int id, String name, String title, String bio, String website, String twitter, String github, String photo) { // this.id = id; // this.name = name; // this.title = title; // this.bio = bio; // this.website = website; // this.twitter = twitter; // this.github = github; // this.photo = photo; // } // // protected Speaker(Parcel in) { // id = in.readInt(); // name = in.readString(); // title = in.readString(); // bio = in.readString(); // website = in.readString(); // twitter = in.readString(); // github = in.readString(); // photo = in.readString(); // } // // @Override // public int describeContents() { // return 0; // } // // @Override // public void writeToParcel(Parcel dest, int flags) { // dest.writeInt(id); // dest.writeString(name); // dest.writeString(title); // dest.writeString(bio); // dest.writeString(website); // dest.writeString(twitter); // dest.writeString(github); // dest.writeString(photo); // } // }
import com.nilhcem.droidconde.data.app.model.Session; import com.nilhcem.droidconde.data.app.model.Speaker; import org.threeten.bp.LocalDateTime; import java.util.List; import timber.log.Timber;
package com.nilhcem.droidconde.data.app; public class DataProviderCache { private static final long CACHE_DURATION_MN = 10;
// Path: app/src/main/java/com/nilhcem/droidconde/data/app/model/Session.java // @Value // public class Session implements Parcelable { // // public static final Parcelable.Creator<Session> CREATOR = new Parcelable.Creator<Session>() { // public Session createFromParcel(Parcel source) { // return new Session(source); // } // // public Session[] newArray(int size) { // return new Session[size]; // } // }; // // int id; // String room; // List<Speaker> speakers; // String title; // String description; // LocalDateTime fromTime; // LocalDateTime toTime; // // public Session(int id, String room, List<Speaker> speakers, String title, String description, LocalDateTime fromTime, LocalDateTime toTime) { // this.id = id; // this.room = room; // this.speakers = speakers; // this.title = title; // this.description = description; // this.fromTime = fromTime; // this.toTime = toTime; // } // // protected Session(Parcel in) { // id = in.readInt(); // room = in.readString(); // speakers = in.createTypedArrayList(Speaker.CREATOR); // title = in.readString(); // description = in.readString(); // fromTime = (LocalDateTime) in.readSerializable(); // toTime = (LocalDateTime) in.readSerializable(); // } // // @Override // public int describeContents() { // return 0; // } // // @Override // public void writeToParcel(Parcel dest, int flags) { // dest.writeInt(id); // dest.writeString(room); // dest.writeTypedList(speakers); // dest.writeString(title); // dest.writeString(description); // dest.writeSerializable(fromTime); // dest.writeSerializable(toTime); // } // } // // Path: app/src/main/java/com/nilhcem/droidconde/data/app/model/Speaker.java // @Value // public class Speaker implements Parcelable { // // public static final Parcelable.Creator<Speaker> CREATOR = new Parcelable.Creator<Speaker>() { // public Speaker createFromParcel(Parcel source) { // return new Speaker(source); // } // // public Speaker[] newArray(int size) { // return new Speaker[size]; // } // }; // // int id; // String name; // String title; // String bio; // String website; // String twitter; // String github; // String photo; // // public Speaker(int id, String name, String title, String bio, String website, String twitter, String github, String photo) { // this.id = id; // this.name = name; // this.title = title; // this.bio = bio; // this.website = website; // this.twitter = twitter; // this.github = github; // this.photo = photo; // } // // protected Speaker(Parcel in) { // id = in.readInt(); // name = in.readString(); // title = in.readString(); // bio = in.readString(); // website = in.readString(); // twitter = in.readString(); // github = in.readString(); // photo = in.readString(); // } // // @Override // public int describeContents() { // return 0; // } // // @Override // public void writeToParcel(Parcel dest, int flags) { // dest.writeInt(id); // dest.writeString(name); // dest.writeString(title); // dest.writeString(bio); // dest.writeString(website); // dest.writeString(twitter); // dest.writeString(github); // dest.writeString(photo); // } // } // Path: app/src/main/java/com/nilhcem/droidconde/data/app/DataProviderCache.java import com.nilhcem.droidconde.data.app.model.Session; import com.nilhcem.droidconde.data.app.model.Speaker; import org.threeten.bp.LocalDateTime; import java.util.List; import timber.log.Timber; package com.nilhcem.droidconde.data.app; public class DataProviderCache { private static final long CACHE_DURATION_MN = 10;
List<Session> sessions;