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 |
|---|---|---|---|---|---|---|
dichengsiyu/LightMe | src/com/hellodev/lightme/view/GuidePagerAdapter.java | // Path: src/com/hellodev/lightme/FlashApp.java
// public class FlashApp extends Application {
// private static Context mContext ;
// @Override
// public void onCreate() {
// super.onCreate();
// mContext = getApplicationContext();
// }
//
// public static Context getContext() {
// return mContext;
// }
// }
| import android.content.Context;
import android.support.v4.view.PagerAdapter;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import com.hellodev.lightme.FlashApp;
import com.hellodev.lightme.R; | package com.hellodev.lightme.view;
public class GuidePagerAdapter extends PagerAdapter implements OnClickListener {
private int[] IMG_RES;
private int pageCount;
private Context appContext;
private boolean fromSettingFlag;
private OnGuideViewClickListener listener;
public GuidePagerAdapter(int[] imgRes, boolean fromSetting,
OnGuideViewClickListener listener) { | // Path: src/com/hellodev/lightme/FlashApp.java
// public class FlashApp extends Application {
// private static Context mContext ;
// @Override
// public void onCreate() {
// super.onCreate();
// mContext = getApplicationContext();
// }
//
// public static Context getContext() {
// return mContext;
// }
// }
// Path: src/com/hellodev/lightme/view/GuidePagerAdapter.java
import android.content.Context;
import android.support.v4.view.PagerAdapter;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import com.hellodev.lightme.FlashApp;
import com.hellodev.lightme.R;
package com.hellodev.lightme.view;
public class GuidePagerAdapter extends PagerAdapter implements OnClickListener {
private int[] IMG_RES;
private int pageCount;
private Context appContext;
private boolean fromSettingFlag;
private OnGuideViewClickListener listener;
public GuidePagerAdapter(int[] imgRes, boolean fromSetting,
OnGuideViewClickListener listener) { | appContext = FlashApp.getContext(); |
dichengsiyu/LightMe | src/com/hellodev/lightme/util/MDisplayHelper.java | // Path: src/com/hellodev/lightme/FlashApp.java
// public class FlashApp extends Application {
// private static Context mContext ;
// @Override
// public void onCreate() {
// super.onCreate();
// mContext = getApplicationContext();
// }
//
// public static Context getContext() {
// return mContext;
// }
// }
| import android.content.Context;
import android.util.DisplayMetrics;
import com.hellodev.lightme.FlashApp; | package com.hellodev.lightme.util;
public class MDisplayHelper {
private DisplayMetrics displayMetrics;
private int screenWidth = 0;
private float density = 0;
public MDisplayHelper() { | // Path: src/com/hellodev/lightme/FlashApp.java
// public class FlashApp extends Application {
// private static Context mContext ;
// @Override
// public void onCreate() {
// super.onCreate();
// mContext = getApplicationContext();
// }
//
// public static Context getContext() {
// return mContext;
// }
// }
// Path: src/com/hellodev/lightme/util/MDisplayHelper.java
import android.content.Context;
import android.util.DisplayMetrics;
import com.hellodev.lightme.FlashApp;
package com.hellodev.lightme.util;
public class MDisplayHelper {
private DisplayMetrics displayMetrics;
private int screenWidth = 0;
private float density = 0;
public MDisplayHelper() { | Context context = FlashApp.getContext(); |
dichengsiyu/LightMe | src/com/hellodev/lightme/util/MPreferenceManager.java | // Path: src/com/hellodev/lightme/FlashApp.java
// public class FlashApp extends Application {
// private static Context mContext ;
// @Override
// public void onCreate() {
// super.onCreate();
// mContext = getApplicationContext();
// }
//
// public static Context getContext() {
// return mContext;
// }
// }
| import com.hellodev.lightme.FlashApp;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.graphics.Point;
import android.preference.PreferenceManager; | package com.hellodev.lightme.util;
public class MPreferenceManager {
private static MPreferenceManager mInstance;
private SharedPreferences mPrefs;
public final static String KEY_AUTO_CLOSE = "auto_close";
public final static String KEY_AUTO_CLOSE_TIME = "auto_close_time";
public final static String KEY_SHOW_LAUNCHER_PANEL = "show_launcher_panel";
public final static String KEY_PANEL_X = "panel_x";
public final static String KEY_PANEL_Y = "panel_y";
public final static String KEY_SHOW_KEYGUARD_PANEL = "show_keyguard_panel";
public final static String KEY_KEYGURAD_SHOCK_ENABLE = "enable_keyguard_shock";
public final static String KEY_VERSION_CODE = "version_code";
public final static String KEY_FIRST_START_DATE = "first_start_date";
public final static String KEY_FIRST_SHOW_LAUNCHER = "first_show_launcher";
public final static String KEY_FIRST_SHOW_KEYGUARD = "first_show_keyguard";
public final static String KEY_ENABLE_SWITCH_SOUND = "enable_switch_sound";
public final static String KEY_NEED_REFRESH_SETTING = "key_need_refresh_setting";
public final static String KEY_LOCAL_LISENSE_STATE = "local_lisense_state";
public final static String KEY_LISENSE_EXPIRED_TIMEMILLS = "lisense_expired_timemills";
private MPreferenceManager() { | // Path: src/com/hellodev/lightme/FlashApp.java
// public class FlashApp extends Application {
// private static Context mContext ;
// @Override
// public void onCreate() {
// super.onCreate();
// mContext = getApplicationContext();
// }
//
// public static Context getContext() {
// return mContext;
// }
// }
// Path: src/com/hellodev/lightme/util/MPreferenceManager.java
import com.hellodev.lightme.FlashApp;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.graphics.Point;
import android.preference.PreferenceManager;
package com.hellodev.lightme.util;
public class MPreferenceManager {
private static MPreferenceManager mInstance;
private SharedPreferences mPrefs;
public final static String KEY_AUTO_CLOSE = "auto_close";
public final static String KEY_AUTO_CLOSE_TIME = "auto_close_time";
public final static String KEY_SHOW_LAUNCHER_PANEL = "show_launcher_panel";
public final static String KEY_PANEL_X = "panel_x";
public final static String KEY_PANEL_Y = "panel_y";
public final static String KEY_SHOW_KEYGUARD_PANEL = "show_keyguard_panel";
public final static String KEY_KEYGURAD_SHOCK_ENABLE = "enable_keyguard_shock";
public final static String KEY_VERSION_CODE = "version_code";
public final static String KEY_FIRST_START_DATE = "first_start_date";
public final static String KEY_FIRST_SHOW_LAUNCHER = "first_show_launcher";
public final static String KEY_FIRST_SHOW_KEYGUARD = "first_show_keyguard";
public final static String KEY_ENABLE_SWITCH_SOUND = "enable_switch_sound";
public final static String KEY_NEED_REFRESH_SETTING = "key_need_refresh_setting";
public final static String KEY_LOCAL_LISENSE_STATE = "local_lisense_state";
public final static String KEY_LISENSE_EXPIRED_TIMEMILLS = "lisense_expired_timemills";
private MPreferenceManager() { | mPrefs =PreferenceManager.getDefaultSharedPreferences(FlashApp.getContext()); |
dichengsiyu/LightMe | src/com/hellodev/lightme/receiver/SystemReceiver.java | // Path: src/com/hellodev/lightme/service/ServiceHelper.java
// public class ServiceHelper {
// public static void startLauncherPanelService() {
// Intent intent = new Intent(PanelService.ACTION_LAUNCHER);
// intent.putExtra(PanelService.CONTROL_TYPE_KEY,
// PanelService.CONTROL_TYPE_START);
// FlashApp.getContext().startService(intent);
// }
//
// public static void stopLauncherPanelService() {
// Intent intent = new Intent(PanelService.ACTION_LAUNCHER);
// intent.putExtra(PanelService.CONTROL_TYPE_KEY,
// PanelService.CONTROL_TYPE_STOP);
// FlashApp.getContext().startService(intent);
// }
//
// public static void startKeyguardPanelService() {
// Intent intent = new Intent(PanelService.ACTION_KEYGUARD);
// intent.putExtra(PanelService.CONTROL_TYPE_KEY,
// PanelService.CONTROL_TYPE_START);
// FlashApp.getContext().startService(intent);
// }
//
// public static void stopKeyguardPanelService() {
// Intent intent = new Intent(PanelService.ACTION_KEYGUARD);
// intent.putExtra(PanelService.CONTROL_TYPE_KEY,
// PanelService.CONTROL_TYPE_STOP);
// FlashApp.getContext().startService(intent);
// }
//
// public static void callPanelServiceWhenScreenOn() {
// Intent intent = new Intent(PanelService.ACTION_PANEL_SERVICE);
// intent.putExtra(PanelService.CONTROL_TYPE_KEY,
// PanelService.CONTROL_TYPE_SCREEN_ON);
// FlashApp.getContext().startService(intent);
// }
//
// public static void callPanelServiceWhenScreenOff() {
// Intent intent = new Intent(PanelService.ACTION_PANEL_SERVICE);
// intent.putExtra(PanelService.CONTROL_TYPE_KEY,
// PanelService.CONTROL_TYPE_SCREEN_OFF);
// FlashApp.getContext().startService(intent);
// }
//
// public static void callPanelServiceWhenUserPresent() {
// Intent intent = new Intent(PanelService.ACTION_PANEL_SERVICE);
// intent.putExtra(PanelService.CONTROL_TYPE_KEY,
// PanelService.CONTROL_TYPE_USER_PRESENT);
// FlashApp.getContext().startService(intent);
// }
//
// /*
// * service启动入口
// * 1. MainActivity界面,用户点击桌面icon进入
// * 2. 重启,boot_complete广播
// *
// *
// */
// public static void startPanelService() {
// MPreferenceManager mPrefsMgr = MPreferenceManager.getInstance();
// boolean isLauncherPanelService = mPrefsMgr.isLauncherPanelShown();
// boolean isKeyguardPanelService = mPrefsMgr.isKeyguardPanelShown();
// if (isLauncherPanelService && isKeyguardPanelService) {
// Intent intent = new Intent(PanelService.ACTION_PANEL_SERVICE);
// intent.putExtra(PanelService.CONTROL_TYPE_KEY,
// PanelService.CONTROL_TYPE_START);
// FlashApp.getContext().startService(intent);
// } else if (isLauncherPanelService) {
// startLauncherPanelService();
// } else if (isKeyguardPanelService) {
// startKeyguardPanelService();
// }
// }
//
// public static void stopPanelService() {
// Intent intent = new Intent(PanelService.ACTION_PANEL_SERVICE);
// intent.putExtra(PanelService.CONTROL_TYPE_KEY,
// PanelService.CONTROL_TYPE_STOP);
// FlashApp.getContext().startService(intent);
// }
//
// public static Intent getAutoCloseIntent() {
// Intent requestIntent = new Intent(
// ControlService.ACTION_AUTO_CLOSE);
// requestIntent.putExtra(ControlService.CONTROL_TYPE_KEY, ControlService.CONTROL_TYPE_SHOW_ACDIALOG);
// return requestIntent;
// }
// }
| import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.util.Log;
import com.hellodev.lightme.service.ServiceHelper; | package com.hellodev.lightme.receiver;
public class SystemReceiver extends BroadcastReceiver {
private final static String TAG = "SystemReceiver";
@Override
public void onReceive(Context context, Intent intent) {
String action = intent != null ? intent.getAction(): null;
if(Intent.ACTION_BOOT_COMPLETED.equals(action)) { | // Path: src/com/hellodev/lightme/service/ServiceHelper.java
// public class ServiceHelper {
// public static void startLauncherPanelService() {
// Intent intent = new Intent(PanelService.ACTION_LAUNCHER);
// intent.putExtra(PanelService.CONTROL_TYPE_KEY,
// PanelService.CONTROL_TYPE_START);
// FlashApp.getContext().startService(intent);
// }
//
// public static void stopLauncherPanelService() {
// Intent intent = new Intent(PanelService.ACTION_LAUNCHER);
// intent.putExtra(PanelService.CONTROL_TYPE_KEY,
// PanelService.CONTROL_TYPE_STOP);
// FlashApp.getContext().startService(intent);
// }
//
// public static void startKeyguardPanelService() {
// Intent intent = new Intent(PanelService.ACTION_KEYGUARD);
// intent.putExtra(PanelService.CONTROL_TYPE_KEY,
// PanelService.CONTROL_TYPE_START);
// FlashApp.getContext().startService(intent);
// }
//
// public static void stopKeyguardPanelService() {
// Intent intent = new Intent(PanelService.ACTION_KEYGUARD);
// intent.putExtra(PanelService.CONTROL_TYPE_KEY,
// PanelService.CONTROL_TYPE_STOP);
// FlashApp.getContext().startService(intent);
// }
//
// public static void callPanelServiceWhenScreenOn() {
// Intent intent = new Intent(PanelService.ACTION_PANEL_SERVICE);
// intent.putExtra(PanelService.CONTROL_TYPE_KEY,
// PanelService.CONTROL_TYPE_SCREEN_ON);
// FlashApp.getContext().startService(intent);
// }
//
// public static void callPanelServiceWhenScreenOff() {
// Intent intent = new Intent(PanelService.ACTION_PANEL_SERVICE);
// intent.putExtra(PanelService.CONTROL_TYPE_KEY,
// PanelService.CONTROL_TYPE_SCREEN_OFF);
// FlashApp.getContext().startService(intent);
// }
//
// public static void callPanelServiceWhenUserPresent() {
// Intent intent = new Intent(PanelService.ACTION_PANEL_SERVICE);
// intent.putExtra(PanelService.CONTROL_TYPE_KEY,
// PanelService.CONTROL_TYPE_USER_PRESENT);
// FlashApp.getContext().startService(intent);
// }
//
// /*
// * service启动入口
// * 1. MainActivity界面,用户点击桌面icon进入
// * 2. 重启,boot_complete广播
// *
// *
// */
// public static void startPanelService() {
// MPreferenceManager mPrefsMgr = MPreferenceManager.getInstance();
// boolean isLauncherPanelService = mPrefsMgr.isLauncherPanelShown();
// boolean isKeyguardPanelService = mPrefsMgr.isKeyguardPanelShown();
// if (isLauncherPanelService && isKeyguardPanelService) {
// Intent intent = new Intent(PanelService.ACTION_PANEL_SERVICE);
// intent.putExtra(PanelService.CONTROL_TYPE_KEY,
// PanelService.CONTROL_TYPE_START);
// FlashApp.getContext().startService(intent);
// } else if (isLauncherPanelService) {
// startLauncherPanelService();
// } else if (isKeyguardPanelService) {
// startKeyguardPanelService();
// }
// }
//
// public static void stopPanelService() {
// Intent intent = new Intent(PanelService.ACTION_PANEL_SERVICE);
// intent.putExtra(PanelService.CONTROL_TYPE_KEY,
// PanelService.CONTROL_TYPE_STOP);
// FlashApp.getContext().startService(intent);
// }
//
// public static Intent getAutoCloseIntent() {
// Intent requestIntent = new Intent(
// ControlService.ACTION_AUTO_CLOSE);
// requestIntent.putExtra(ControlService.CONTROL_TYPE_KEY, ControlService.CONTROL_TYPE_SHOW_ACDIALOG);
// return requestIntent;
// }
// }
// Path: src/com/hellodev/lightme/receiver/SystemReceiver.java
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.util.Log;
import com.hellodev.lightme.service.ServiceHelper;
package com.hellodev.lightme.receiver;
public class SystemReceiver extends BroadcastReceiver {
private final static String TAG = "SystemReceiver";
@Override
public void onReceive(Context context, Intent intent) {
String action = intent != null ? intent.getAction(): null;
if(Intent.ACTION_BOOT_COMPLETED.equals(action)) { | ServiceHelper.startPanelService(); |
dichengsiyu/LightMe | smartbar/SmartbarDemo/src/com/meizu/smartbar/ActionBarCustomTabOnTop.java | // Path: smartbar/SmartbarDemo/src/com/meizu/smartbar/tab/ContactsActivity.java
// public class ContactsActivity extends Activity {
//
// @Override
// public void onCreate(Bundle savedInstanceState) {
// super.onCreate(savedInstanceState);
//
// setContentView(R.layout.text_content_contacts);
// EditText text = (EditText)findViewById(android.R.id.text1);
// text.setText("Contacts1");
// }
//
// @Override
// protected void onResume() {
// getParent().getActionBar().setTitle("Contacts title");
// super.onResume();
// }
// }
//
// Path: smartbar/SmartbarDemo/src/com/meizu/smartbar/tab/DialerActivity.java
// public class DialerActivity extends Activity {
//
// @Override
// public void onCreate(Bundle savedInstanceState) {
// super.onCreate(savedInstanceState);
//
// setContentView(R.layout.text_content);
// TextView text = (TextView)findViewById(android.R.id.text1);
// text.setText("Dialer");
// }
//
// @Override
// protected void onResume() {
// getParent().getActionBar().setTitle("Dialer title");
// super.onResume();
// }
// }
| import com.meizu.smartbar.tab.ContactsActivity;
import com.meizu.smartbar.tab.DialerActivity;
import android.app.TabActivity;
import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.TabHost; | package com.meizu.smartbar;
public class ActionBarCustomTabOnTop extends TabActivity {
private final static int TAB_INDEX_RECENT = 0;
private final static int TAB_INDEX_CONTACTS = 1;
private final static int TAB_INDEX_DIALER = 2;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.tab_content);
final TabHost tabHost = getTabHost();
tabHost.addTab(tabHost.newTabSpec("recent").setIndicator("recent")
.setContent(new Intent(this, CustomTabOnTopActivity.class)));
tabHost.addTab(tabHost.newTabSpec("contacts").setIndicator("contacts") | // Path: smartbar/SmartbarDemo/src/com/meizu/smartbar/tab/ContactsActivity.java
// public class ContactsActivity extends Activity {
//
// @Override
// public void onCreate(Bundle savedInstanceState) {
// super.onCreate(savedInstanceState);
//
// setContentView(R.layout.text_content_contacts);
// EditText text = (EditText)findViewById(android.R.id.text1);
// text.setText("Contacts1");
// }
//
// @Override
// protected void onResume() {
// getParent().getActionBar().setTitle("Contacts title");
// super.onResume();
// }
// }
//
// Path: smartbar/SmartbarDemo/src/com/meizu/smartbar/tab/DialerActivity.java
// public class DialerActivity extends Activity {
//
// @Override
// public void onCreate(Bundle savedInstanceState) {
// super.onCreate(savedInstanceState);
//
// setContentView(R.layout.text_content);
// TextView text = (TextView)findViewById(android.R.id.text1);
// text.setText("Dialer");
// }
//
// @Override
// protected void onResume() {
// getParent().getActionBar().setTitle("Dialer title");
// super.onResume();
// }
// }
// Path: smartbar/SmartbarDemo/src/com/meizu/smartbar/ActionBarCustomTabOnTop.java
import com.meizu.smartbar.tab.ContactsActivity;
import com.meizu.smartbar.tab.DialerActivity;
import android.app.TabActivity;
import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.TabHost;
package com.meizu.smartbar;
public class ActionBarCustomTabOnTop extends TabActivity {
private final static int TAB_INDEX_RECENT = 0;
private final static int TAB_INDEX_CONTACTS = 1;
private final static int TAB_INDEX_DIALER = 2;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.tab_content);
final TabHost tabHost = getTabHost();
tabHost.addTab(tabHost.newTabSpec("recent").setIndicator("recent")
.setContent(new Intent(this, CustomTabOnTopActivity.class)));
tabHost.addTab(tabHost.newTabSpec("contacts").setIndicator("contacts") | .setContent(new Intent(this, ContactsActivity.class))); |
dichengsiyu/LightMe | smartbar/SmartbarDemo/src/com/meizu/smartbar/ActionBarCustomTabOnTop.java | // Path: smartbar/SmartbarDemo/src/com/meizu/smartbar/tab/ContactsActivity.java
// public class ContactsActivity extends Activity {
//
// @Override
// public void onCreate(Bundle savedInstanceState) {
// super.onCreate(savedInstanceState);
//
// setContentView(R.layout.text_content_contacts);
// EditText text = (EditText)findViewById(android.R.id.text1);
// text.setText("Contacts1");
// }
//
// @Override
// protected void onResume() {
// getParent().getActionBar().setTitle("Contacts title");
// super.onResume();
// }
// }
//
// Path: smartbar/SmartbarDemo/src/com/meizu/smartbar/tab/DialerActivity.java
// public class DialerActivity extends Activity {
//
// @Override
// public void onCreate(Bundle savedInstanceState) {
// super.onCreate(savedInstanceState);
//
// setContentView(R.layout.text_content);
// TextView text = (TextView)findViewById(android.R.id.text1);
// text.setText("Dialer");
// }
//
// @Override
// protected void onResume() {
// getParent().getActionBar().setTitle("Dialer title");
// super.onResume();
// }
// }
| import com.meizu.smartbar.tab.ContactsActivity;
import com.meizu.smartbar.tab.DialerActivity;
import android.app.TabActivity;
import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.TabHost; | package com.meizu.smartbar;
public class ActionBarCustomTabOnTop extends TabActivity {
private final static int TAB_INDEX_RECENT = 0;
private final static int TAB_INDEX_CONTACTS = 1;
private final static int TAB_INDEX_DIALER = 2;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.tab_content);
final TabHost tabHost = getTabHost();
tabHost.addTab(tabHost.newTabSpec("recent").setIndicator("recent")
.setContent(new Intent(this, CustomTabOnTopActivity.class)));
tabHost.addTab(tabHost.newTabSpec("contacts").setIndicator("contacts")
.setContent(new Intent(this, ContactsActivity.class)));
tabHost.addTab(tabHost.newTabSpec("dialer").setIndicator("dialer") | // Path: smartbar/SmartbarDemo/src/com/meizu/smartbar/tab/ContactsActivity.java
// public class ContactsActivity extends Activity {
//
// @Override
// public void onCreate(Bundle savedInstanceState) {
// super.onCreate(savedInstanceState);
//
// setContentView(R.layout.text_content_contacts);
// EditText text = (EditText)findViewById(android.R.id.text1);
// text.setText("Contacts1");
// }
//
// @Override
// protected void onResume() {
// getParent().getActionBar().setTitle("Contacts title");
// super.onResume();
// }
// }
//
// Path: smartbar/SmartbarDemo/src/com/meizu/smartbar/tab/DialerActivity.java
// public class DialerActivity extends Activity {
//
// @Override
// public void onCreate(Bundle savedInstanceState) {
// super.onCreate(savedInstanceState);
//
// setContentView(R.layout.text_content);
// TextView text = (TextView)findViewById(android.R.id.text1);
// text.setText("Dialer");
// }
//
// @Override
// protected void onResume() {
// getParent().getActionBar().setTitle("Dialer title");
// super.onResume();
// }
// }
// Path: smartbar/SmartbarDemo/src/com/meizu/smartbar/ActionBarCustomTabOnTop.java
import com.meizu.smartbar.tab.ContactsActivity;
import com.meizu.smartbar.tab.DialerActivity;
import android.app.TabActivity;
import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.TabHost;
package com.meizu.smartbar;
public class ActionBarCustomTabOnTop extends TabActivity {
private final static int TAB_INDEX_RECENT = 0;
private final static int TAB_INDEX_CONTACTS = 1;
private final static int TAB_INDEX_DIALER = 2;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.tab_content);
final TabHost tabHost = getTabHost();
tabHost.addTab(tabHost.newTabSpec("recent").setIndicator("recent")
.setContent(new Intent(this, CustomTabOnTopActivity.class)));
tabHost.addTab(tabHost.newTabSpec("contacts").setIndicator("contacts")
.setContent(new Intent(this, ContactsActivity.class)));
tabHost.addTab(tabHost.newTabSpec("dialer").setIndicator("dialer") | .setContent(new Intent(this, DialerActivity.class))); |
oharaandrew314/TinkerTime | src/io/andrewohara/tinkertime/io/kspLauncher/OsxExecStrategy.java | // Path: src/io/andrewohara/tinkertime/models/ConfigData.java
// @DatabaseTable(tableName = "config")
// public class ConfigData extends BaseDaoEnabled<ConfigData, Integer> {
//
// public static final int NUM_CONCURRENT_DOWNLOADS = 4;
//
// /////////////
// // Columns //
// /////////////
//
// ConfigData() { /* Used by ormlite */ }
//
// public ConfigData(Dao<ConfigData, Integer> dao) throws SQLException{
// setDao(dao);
// create();
// }
//
// @DatabaseField(id=true)
// private int id;
//
// @DatabaseField(canBeNull = false)
// private boolean checkForAppUpdatesOnStartup = true, checkForModUpdatesOnStartup = true;
//
// @DatabaseField(foreign = true, foreignAutoRefresh=true)
// private Installation selectedInstallation;
//
// @DatabaseField
// private String launchArguments;
//
// /////////////
// // Setters //
// /////////////
//
// public void setLaunchArguments(String args) throws SQLException{
// this.launchArguments = args;
// update();
// }
//
// public void setCheckForAppUpdatesOnStartup(boolean check) throws SQLException{
// this.checkForAppUpdatesOnStartup = check;
// update();
// }
//
// public void setCheckForModUpdatesOnStartup(boolean check) throws SQLException{
// this.checkForModUpdatesOnStartup = check;
// update();
// }
//
// public void setSelectedInstallation(Installation newInstallation) throws SQLException{
// this.selectedInstallation = newInstallation;
// update();
// }
//
// /////////////
// // Getters //
// /////////////
//
// public boolean isCheckForAppUpdatesOnStartup(){
// return checkForAppUpdatesOnStartup;
// }
//
// public boolean isCheckForModUpdatesOnStartup(){
// return checkForModUpdatesOnStartup;
// }
//
// public Installation getSelectedInstallation() {
// return selectedInstallation;
// }
//
// public String getLaunchArguments(){
// return launchArguments;
// }
//
// }
| import io.andrewohara.tinkertime.models.ConfigData;
import java.nio.file.Path;
import java.util.Arrays;
import java.util.List; | package io.andrewohara.tinkertime.io.kspLauncher;
public class OsxExecStrategy extends GameExecStrategy {
@Override | // Path: src/io/andrewohara/tinkertime/models/ConfigData.java
// @DatabaseTable(tableName = "config")
// public class ConfigData extends BaseDaoEnabled<ConfigData, Integer> {
//
// public static final int NUM_CONCURRENT_DOWNLOADS = 4;
//
// /////////////
// // Columns //
// /////////////
//
// ConfigData() { /* Used by ormlite */ }
//
// public ConfigData(Dao<ConfigData, Integer> dao) throws SQLException{
// setDao(dao);
// create();
// }
//
// @DatabaseField(id=true)
// private int id;
//
// @DatabaseField(canBeNull = false)
// private boolean checkForAppUpdatesOnStartup = true, checkForModUpdatesOnStartup = true;
//
// @DatabaseField(foreign = true, foreignAutoRefresh=true)
// private Installation selectedInstallation;
//
// @DatabaseField
// private String launchArguments;
//
// /////////////
// // Setters //
// /////////////
//
// public void setLaunchArguments(String args) throws SQLException{
// this.launchArguments = args;
// update();
// }
//
// public void setCheckForAppUpdatesOnStartup(boolean check) throws SQLException{
// this.checkForAppUpdatesOnStartup = check;
// update();
// }
//
// public void setCheckForModUpdatesOnStartup(boolean check) throws SQLException{
// this.checkForModUpdatesOnStartup = check;
// update();
// }
//
// public void setSelectedInstallation(Installation newInstallation) throws SQLException{
// this.selectedInstallation = newInstallation;
// update();
// }
//
// /////////////
// // Getters //
// /////////////
//
// public boolean isCheckForAppUpdatesOnStartup(){
// return checkForAppUpdatesOnStartup;
// }
//
// public boolean isCheckForModUpdatesOnStartup(){
// return checkForModUpdatesOnStartup;
// }
//
// public Installation getSelectedInstallation() {
// return selectedInstallation;
// }
//
// public String getLaunchArguments(){
// return launchArguments;
// }
//
// }
// Path: src/io/andrewohara/tinkertime/io/kspLauncher/OsxExecStrategy.java
import io.andrewohara.tinkertime.models.ConfigData;
import java.nio.file.Path;
import java.util.Arrays;
import java.util.List;
package io.andrewohara.tinkertime.io.kspLauncher;
public class OsxExecStrategy extends GameExecStrategy {
@Override | protected List<String> getCommands(ConfigData config) { |
oharaandrew314/TinkerTime | src/io/andrewohara/tinkertime/io/crawlers/KerbalStuffCrawler.java | // Path: src/io/andrewohara/tinkertime/io/crawlers/pageLoaders/PageLoader.java
// public abstract class PageLoader<T> {
//
// public static final int CACHING_EXIPIRY_MINUTES = 1;
// private final LoadingCache<URL, T> cache;
//
// public PageLoader(){
// System.setProperty("http.agent", "TinkerTime Mod Manager Agent");
// cache = CacheBuilder.newBuilder()
// .expireAfterAccess(CACHING_EXIPIRY_MINUTES, TimeUnit.MINUTES)
// .build(
// new CacheLoader<URL, T>() {
// @Override
// public T load(URL url) throws IOException {
// return loadPage(url);
// }
// });
// }
//
// protected abstract T loadPage(URL url) throws IOException;
//
// public T getPage(URL url) throws IOException {
// try {
// return cache.get(url);
// } catch (ExecutionException e) {
// throw new IOException(e);
// }
// }
// }
| import io.andrewohara.tinkertime.io.crawlers.pageLoaders.PageLoader;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Collection;
import java.util.Date;
import java.util.LinkedList;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject; | package io.andrewohara.tinkertime.io.crawlers;
public class KerbalStuffCrawler extends Crawler<JsonElement>{
private static Pattern ID_PATTERN = Pattern.compile("(mod/)(\\d+)(/*)");
private URL cachedApiUrl = null;
| // Path: src/io/andrewohara/tinkertime/io/crawlers/pageLoaders/PageLoader.java
// public abstract class PageLoader<T> {
//
// public static final int CACHING_EXIPIRY_MINUTES = 1;
// private final LoadingCache<URL, T> cache;
//
// public PageLoader(){
// System.setProperty("http.agent", "TinkerTime Mod Manager Agent");
// cache = CacheBuilder.newBuilder()
// .expireAfterAccess(CACHING_EXIPIRY_MINUTES, TimeUnit.MINUTES)
// .build(
// new CacheLoader<URL, T>() {
// @Override
// public T load(URL url) throws IOException {
// return loadPage(url);
// }
// });
// }
//
// protected abstract T loadPage(URL url) throws IOException;
//
// public T getPage(URL url) throws IOException {
// try {
// return cache.get(url);
// } catch (ExecutionException e) {
// throw new IOException(e);
// }
// }
// }
// Path: src/io/andrewohara/tinkertime/io/crawlers/KerbalStuffCrawler.java
import io.andrewohara.tinkertime.io.crawlers.pageLoaders.PageLoader;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Collection;
import java.util.Date;
import java.util.LinkedList;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
package io.andrewohara.tinkertime.io.crawlers;
public class KerbalStuffCrawler extends Crawler<JsonElement>{
private static Pattern ID_PATTERN = Pattern.compile("(mod/)(\\d+)(/*)");
private URL cachedApiUrl = null;
| public KerbalStuffCrawler(URL url, PageLoader<JsonElement> pageLoader) { |
oharaandrew314/TinkerTime | src/io/andrewohara/tinkertime/io/kspLauncher/WindowsExecStrategy.java | // Path: src/io/andrewohara/tinkertime/models/ConfigData.java
// @DatabaseTable(tableName = "config")
// public class ConfigData extends BaseDaoEnabled<ConfigData, Integer> {
//
// public static final int NUM_CONCURRENT_DOWNLOADS = 4;
//
// /////////////
// // Columns //
// /////////////
//
// ConfigData() { /* Used by ormlite */ }
//
// public ConfigData(Dao<ConfigData, Integer> dao) throws SQLException{
// setDao(dao);
// create();
// }
//
// @DatabaseField(id=true)
// private int id;
//
// @DatabaseField(canBeNull = false)
// private boolean checkForAppUpdatesOnStartup = true, checkForModUpdatesOnStartup = true;
//
// @DatabaseField(foreign = true, foreignAutoRefresh=true)
// private Installation selectedInstallation;
//
// @DatabaseField
// private String launchArguments;
//
// /////////////
// // Setters //
// /////////////
//
// public void setLaunchArguments(String args) throws SQLException{
// this.launchArguments = args;
// update();
// }
//
// public void setCheckForAppUpdatesOnStartup(boolean check) throws SQLException{
// this.checkForAppUpdatesOnStartup = check;
// update();
// }
//
// public void setCheckForModUpdatesOnStartup(boolean check) throws SQLException{
// this.checkForModUpdatesOnStartup = check;
// update();
// }
//
// public void setSelectedInstallation(Installation newInstallation) throws SQLException{
// this.selectedInstallation = newInstallation;
// update();
// }
//
// /////////////
// // Getters //
// /////////////
//
// public boolean isCheckForAppUpdatesOnStartup(){
// return checkForAppUpdatesOnStartup;
// }
//
// public boolean isCheckForModUpdatesOnStartup(){
// return checkForModUpdatesOnStartup;
// }
//
// public Installation getSelectedInstallation() {
// return selectedInstallation;
// }
//
// public String getLaunchArguments(){
// return launchArguments;
// }
//
// }
| import io.andrewohara.tinkertime.models.ConfigData;
import java.util.Arrays;
import java.util.List; | package io.andrewohara.tinkertime.io.kspLauncher;
public class WindowsExecStrategy extends GameExecStrategy {
@Override | // Path: src/io/andrewohara/tinkertime/models/ConfigData.java
// @DatabaseTable(tableName = "config")
// public class ConfigData extends BaseDaoEnabled<ConfigData, Integer> {
//
// public static final int NUM_CONCURRENT_DOWNLOADS = 4;
//
// /////////////
// // Columns //
// /////////////
//
// ConfigData() { /* Used by ormlite */ }
//
// public ConfigData(Dao<ConfigData, Integer> dao) throws SQLException{
// setDao(dao);
// create();
// }
//
// @DatabaseField(id=true)
// private int id;
//
// @DatabaseField(canBeNull = false)
// private boolean checkForAppUpdatesOnStartup = true, checkForModUpdatesOnStartup = true;
//
// @DatabaseField(foreign = true, foreignAutoRefresh=true)
// private Installation selectedInstallation;
//
// @DatabaseField
// private String launchArguments;
//
// /////////////
// // Setters //
// /////////////
//
// public void setLaunchArguments(String args) throws SQLException{
// this.launchArguments = args;
// update();
// }
//
// public void setCheckForAppUpdatesOnStartup(boolean check) throws SQLException{
// this.checkForAppUpdatesOnStartup = check;
// update();
// }
//
// public void setCheckForModUpdatesOnStartup(boolean check) throws SQLException{
// this.checkForModUpdatesOnStartup = check;
// update();
// }
//
// public void setSelectedInstallation(Installation newInstallation) throws SQLException{
// this.selectedInstallation = newInstallation;
// update();
// }
//
// /////////////
// // Getters //
// /////////////
//
// public boolean isCheckForAppUpdatesOnStartup(){
// return checkForAppUpdatesOnStartup;
// }
//
// public boolean isCheckForModUpdatesOnStartup(){
// return checkForModUpdatesOnStartup;
// }
//
// public Installation getSelectedInstallation() {
// return selectedInstallation;
// }
//
// public String getLaunchArguments(){
// return launchArguments;
// }
//
// }
// Path: src/io/andrewohara/tinkertime/io/kspLauncher/WindowsExecStrategy.java
import io.andrewohara.tinkertime.models.ConfigData;
import java.util.Arrays;
import java.util.List;
package io.andrewohara.tinkertime.io.kspLauncher;
public class WindowsExecStrategy extends GameExecStrategy {
@Override | protected List<String> getCommands(ConfigData config) { |
oharaandrew314/TinkerTime | src/io/andrewohara/tinkertime/io/kspLauncher/LinuxExecStrategy.java | // Path: src/io/andrewohara/tinkertime/models/ConfigData.java
// @DatabaseTable(tableName = "config")
// public class ConfigData extends BaseDaoEnabled<ConfigData, Integer> {
//
// public static final int NUM_CONCURRENT_DOWNLOADS = 4;
//
// /////////////
// // Columns //
// /////////////
//
// ConfigData() { /* Used by ormlite */ }
//
// public ConfigData(Dao<ConfigData, Integer> dao) throws SQLException{
// setDao(dao);
// create();
// }
//
// @DatabaseField(id=true)
// private int id;
//
// @DatabaseField(canBeNull = false)
// private boolean checkForAppUpdatesOnStartup = true, checkForModUpdatesOnStartup = true;
//
// @DatabaseField(foreign = true, foreignAutoRefresh=true)
// private Installation selectedInstallation;
//
// @DatabaseField
// private String launchArguments;
//
// /////////////
// // Setters //
// /////////////
//
// public void setLaunchArguments(String args) throws SQLException{
// this.launchArguments = args;
// update();
// }
//
// public void setCheckForAppUpdatesOnStartup(boolean check) throws SQLException{
// this.checkForAppUpdatesOnStartup = check;
// update();
// }
//
// public void setCheckForModUpdatesOnStartup(boolean check) throws SQLException{
// this.checkForModUpdatesOnStartup = check;
// update();
// }
//
// public void setSelectedInstallation(Installation newInstallation) throws SQLException{
// this.selectedInstallation = newInstallation;
// update();
// }
//
// /////////////
// // Getters //
// /////////////
//
// public boolean isCheckForAppUpdatesOnStartup(){
// return checkForAppUpdatesOnStartup;
// }
//
// public boolean isCheckForModUpdatesOnStartup(){
// return checkForModUpdatesOnStartup;
// }
//
// public Installation getSelectedInstallation() {
// return selectedInstallation;
// }
//
// public String getLaunchArguments(){
// return launchArguments;
// }
//
// }
| import io.andrewohara.tinkertime.models.ConfigData;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.nio.file.Path;
import java.util.Arrays;
import java.util.List; | package io.andrewohara.tinkertime.io.kspLauncher;
public class LinuxExecStrategy extends GameExecStrategy {
@Override | // Path: src/io/andrewohara/tinkertime/models/ConfigData.java
// @DatabaseTable(tableName = "config")
// public class ConfigData extends BaseDaoEnabled<ConfigData, Integer> {
//
// public static final int NUM_CONCURRENT_DOWNLOADS = 4;
//
// /////////////
// // Columns //
// /////////////
//
// ConfigData() { /* Used by ormlite */ }
//
// public ConfigData(Dao<ConfigData, Integer> dao) throws SQLException{
// setDao(dao);
// create();
// }
//
// @DatabaseField(id=true)
// private int id;
//
// @DatabaseField(canBeNull = false)
// private boolean checkForAppUpdatesOnStartup = true, checkForModUpdatesOnStartup = true;
//
// @DatabaseField(foreign = true, foreignAutoRefresh=true)
// private Installation selectedInstallation;
//
// @DatabaseField
// private String launchArguments;
//
// /////////////
// // Setters //
// /////////////
//
// public void setLaunchArguments(String args) throws SQLException{
// this.launchArguments = args;
// update();
// }
//
// public void setCheckForAppUpdatesOnStartup(boolean check) throws SQLException{
// this.checkForAppUpdatesOnStartup = check;
// update();
// }
//
// public void setCheckForModUpdatesOnStartup(boolean check) throws SQLException{
// this.checkForModUpdatesOnStartup = check;
// update();
// }
//
// public void setSelectedInstallation(Installation newInstallation) throws SQLException{
// this.selectedInstallation = newInstallation;
// update();
// }
//
// /////////////
// // Getters //
// /////////////
//
// public boolean isCheckForAppUpdatesOnStartup(){
// return checkForAppUpdatesOnStartup;
// }
//
// public boolean isCheckForModUpdatesOnStartup(){
// return checkForModUpdatesOnStartup;
// }
//
// public Installation getSelectedInstallation() {
// return selectedInstallation;
// }
//
// public String getLaunchArguments(){
// return launchArguments;
// }
//
// }
// Path: src/io/andrewohara/tinkertime/io/kspLauncher/LinuxExecStrategy.java
import io.andrewohara.tinkertime.models.ConfigData;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.nio.file.Path;
import java.util.Arrays;
import java.util.List;
package io.andrewohara.tinkertime.io.kspLauncher;
public class LinuxExecStrategy extends GameExecStrategy {
@Override | protected List<String> getCommands(ConfigData config) { |
oharaandrew314/TinkerTime | src/io/andrewohara/tinkertime/controllers/workflows/TaskLauncher.java | // Path: src/io/andrewohara/tinkertime/controllers/ModUpdateCoordinator.java
// @Singleton
// public class ModUpdateCoordinator extends TaskCallback implements ModUpdateHandler {
//
// private final ConfigData config;
//
// private ModUpdateHandler modSelector, installationView;
// private ModListCellRenderer modListCellRenderer;
//
// @Inject
// protected ModUpdateCoordinator(ConfigData config){
// this.config = config;
// }
//
// public void setListeners(ModSelectorPanelController modSelector, ModListCellRenderer modListCellRender, SelectedInstallationView installationView){
// this.modSelector = modSelector;
// this.modListCellRenderer = modListCellRender;
// this.installationView = installationView;
// }
//
// @Override
// public void changeInstallation(Installation newInstallation){
// try {
// config.setSelectedInstallation(newInstallation);
// modSelector.changeInstallation(newInstallation);
// installationView.changeInstallation(newInstallation);
// } catch (SQLException e){
// throw new RuntimeException(e);
// }
// }
//
// @Override
// protected void processTaskEvent(TaskEvent event) {
// modListCellRenderer.handleTaskEvent(event);
// }
// }
| import io.andrewohara.common.workflows.tasks.WorkflowBuilder;
import io.andrewohara.tinkertime.controllers.ModUpdateCoordinator;
import java.util.concurrent.Executor;
import java.util.concurrent.ThreadPoolExecutor;
import com.google.inject.Inject; | package io.andrewohara.tinkertime.controllers.workflows;
public class TaskLauncher {
private final ThreadPoolExecutor downloadExecutor;
private final Executor fileExecutor; | // Path: src/io/andrewohara/tinkertime/controllers/ModUpdateCoordinator.java
// @Singleton
// public class ModUpdateCoordinator extends TaskCallback implements ModUpdateHandler {
//
// private final ConfigData config;
//
// private ModUpdateHandler modSelector, installationView;
// private ModListCellRenderer modListCellRenderer;
//
// @Inject
// protected ModUpdateCoordinator(ConfigData config){
// this.config = config;
// }
//
// public void setListeners(ModSelectorPanelController modSelector, ModListCellRenderer modListCellRender, SelectedInstallationView installationView){
// this.modSelector = modSelector;
// this.modListCellRenderer = modListCellRender;
// this.installationView = installationView;
// }
//
// @Override
// public void changeInstallation(Installation newInstallation){
// try {
// config.setSelectedInstallation(newInstallation);
// modSelector.changeInstallation(newInstallation);
// installationView.changeInstallation(newInstallation);
// } catch (SQLException e){
// throw new RuntimeException(e);
// }
// }
//
// @Override
// protected void processTaskEvent(TaskEvent event) {
// modListCellRenderer.handleTaskEvent(event);
// }
// }
// Path: src/io/andrewohara/tinkertime/controllers/workflows/TaskLauncher.java
import io.andrewohara.common.workflows.tasks.WorkflowBuilder;
import io.andrewohara.tinkertime.controllers.ModUpdateCoordinator;
import java.util.concurrent.Executor;
import java.util.concurrent.ThreadPoolExecutor;
import com.google.inject.Inject;
package io.andrewohara.tinkertime.controllers.workflows;
public class TaskLauncher {
private final ThreadPoolExecutor downloadExecutor;
private final Executor fileExecutor; | private final ModUpdateCoordinator modUpdateCoordinator; |
oharaandrew314/TinkerTime | src/io/andrewohara/tinkertime/io/crawlers/JenkinsCrawler.java | // Path: src/io/andrewohara/tinkertime/io/crawlers/pageLoaders/PageLoader.java
// public abstract class PageLoader<T> {
//
// public static final int CACHING_EXIPIRY_MINUTES = 1;
// private final LoadingCache<URL, T> cache;
//
// public PageLoader(){
// System.setProperty("http.agent", "TinkerTime Mod Manager Agent");
// cache = CacheBuilder.newBuilder()
// .expireAfterAccess(CACHING_EXIPIRY_MINUTES, TimeUnit.MINUTES)
// .build(
// new CacheLoader<URL, T>() {
// @Override
// public T load(URL url) throws IOException {
// return loadPage(url);
// }
// });
// }
//
// protected abstract T loadPage(URL url) throws IOException;
//
// public T getPage(URL url) throws IOException {
// try {
// return cache.get(url);
// } catch (ExecutionException e) {
// throw new IOException(e);
// }
// }
// }
| import io.andrewohara.common.version.Version;
import io.andrewohara.common.version.VersionParser;
import io.andrewohara.tinkertime.io.crawlers.pageLoaders.PageLoader;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Calendar;
import java.util.Collection;
import java.util.Date;
import java.util.LinkedList;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject; | package io.andrewohara.tinkertime.io.crawlers;
/**
* Crawler for gathering file data from a Jenkins Json Artifact.
*
* @author Andrew O'Hara
*/
public class JenkinsCrawler extends Crawler<JsonElement> {
private JsonObject cachedJson;
| // Path: src/io/andrewohara/tinkertime/io/crawlers/pageLoaders/PageLoader.java
// public abstract class PageLoader<T> {
//
// public static final int CACHING_EXIPIRY_MINUTES = 1;
// private final LoadingCache<URL, T> cache;
//
// public PageLoader(){
// System.setProperty("http.agent", "TinkerTime Mod Manager Agent");
// cache = CacheBuilder.newBuilder()
// .expireAfterAccess(CACHING_EXIPIRY_MINUTES, TimeUnit.MINUTES)
// .build(
// new CacheLoader<URL, T>() {
// @Override
// public T load(URL url) throws IOException {
// return loadPage(url);
// }
// });
// }
//
// protected abstract T loadPage(URL url) throws IOException;
//
// public T getPage(URL url) throws IOException {
// try {
// return cache.get(url);
// } catch (ExecutionException e) {
// throw new IOException(e);
// }
// }
// }
// Path: src/io/andrewohara/tinkertime/io/crawlers/JenkinsCrawler.java
import io.andrewohara.common.version.Version;
import io.andrewohara.common.version.VersionParser;
import io.andrewohara.tinkertime.io.crawlers.pageLoaders.PageLoader;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Calendar;
import java.util.Collection;
import java.util.Date;
import java.util.LinkedList;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
package io.andrewohara.tinkertime.io.crawlers;
/**
* Crawler for gathering file data from a Jenkins Json Artifact.
*
* @author Andrew O'Hara
*/
public class JenkinsCrawler extends Crawler<JsonElement> {
private JsonObject cachedJson;
| public JenkinsCrawler(URL url, PageLoader<JsonElement> pageLoader) { |
oharaandrew314/TinkerTime | test/io/andrewohara/tinkertime/TestDatabaseMigrationIntegration.java | // Path: src/io/andrewohara/tinkertime/TinkerTimeLauncher.java
// public static class DatabaseMigrator implements Runnable {
//
// private final DbConnectionString connectionString;
//
// @Inject
// DatabaseMigrator(DbConnectionString connectionString){
// this.connectionString = connectionString;
// }
//
// @Override
// public void run() {
// // Perform Database Migration
// Flyway flyway = new Flyway();
// flyway.setBaselineOnMigrate(true);
// flyway.setLocations("io/andrewohara/tinkertime/db/migration");
// flyway.setDataSource(connectionString.getUrl(), null, null);
// try {
// flyway.migrate();
// } catch (FlywayException e){
// flyway.repair();
// throw e;
// }
// }
// }
//
// Path: src/io/andrewohara/tinkertime/db/DbConnectionString.java
// public interface DbConnectionString {
//
// public String getUrl();
//
// }
| import io.andrewohara.tinkertime.TinkerTimeLauncher.DatabaseMigrator;
import io.andrewohara.tinkertime.db.DbConnectionString;
import org.junit.Before;
import org.junit.Test; | package io.andrewohara.tinkertime;
public class TestDatabaseMigrationIntegration {
private DatabaseMigrator migrator;
@Before
public void setup(){ | // Path: src/io/andrewohara/tinkertime/TinkerTimeLauncher.java
// public static class DatabaseMigrator implements Runnable {
//
// private final DbConnectionString connectionString;
//
// @Inject
// DatabaseMigrator(DbConnectionString connectionString){
// this.connectionString = connectionString;
// }
//
// @Override
// public void run() {
// // Perform Database Migration
// Flyway flyway = new Flyway();
// flyway.setBaselineOnMigrate(true);
// flyway.setLocations("io/andrewohara/tinkertime/db/migration");
// flyway.setDataSource(connectionString.getUrl(), null, null);
// try {
// flyway.migrate();
// } catch (FlywayException e){
// flyway.repair();
// throw e;
// }
// }
// }
//
// Path: src/io/andrewohara/tinkertime/db/DbConnectionString.java
// public interface DbConnectionString {
//
// public String getUrl();
//
// }
// Path: test/io/andrewohara/tinkertime/TestDatabaseMigrationIntegration.java
import io.andrewohara.tinkertime.TinkerTimeLauncher.DatabaseMigrator;
import io.andrewohara.tinkertime.db.DbConnectionString;
import org.junit.Before;
import org.junit.Test;
package io.andrewohara.tinkertime;
public class TestDatabaseMigrationIntegration {
private DatabaseMigrator migrator;
@Before
public void setup(){ | DbConnectionString connectionString = new DbConnectionString(){ |
oharaandrew314/TinkerTime | test/io/andrewohara/tinkertime/testUtil/StaticAssetSelector.java | // Path: src/io/andrewohara/tinkertime/io/crawlers/Crawler.java
// public static class Asset {
// public final String fileName;
// public final URL downloadLink;
//
// protected Asset(String fileName, URL downloadLink){
// this.fileName = fileName;
// this.downloadLink = downloadLink;
// }
//
// @Override
// public String toString(){
// return fileName;
// }
// }
//
// Path: src/io/andrewohara/tinkertime/io/crawlers/Crawler.java
// public static interface AssetSelector {
//
// public Asset selectAsset(String modName, Collection<Asset> assets);
// }
| import io.andrewohara.tinkertime.io.crawlers.Crawler.Asset;
import io.andrewohara.tinkertime.io.crawlers.Crawler.AssetSelector;
import java.util.ArrayList;
import java.util.Collection; | package io.andrewohara.tinkertime.testUtil;
public class StaticAssetSelector implements AssetSelector {
@Override | // Path: src/io/andrewohara/tinkertime/io/crawlers/Crawler.java
// public static class Asset {
// public final String fileName;
// public final URL downloadLink;
//
// protected Asset(String fileName, URL downloadLink){
// this.fileName = fileName;
// this.downloadLink = downloadLink;
// }
//
// @Override
// public String toString(){
// return fileName;
// }
// }
//
// Path: src/io/andrewohara/tinkertime/io/crawlers/Crawler.java
// public static interface AssetSelector {
//
// public Asset selectAsset(String modName, Collection<Asset> assets);
// }
// Path: test/io/andrewohara/tinkertime/testUtil/StaticAssetSelector.java
import io.andrewohara.tinkertime.io.crawlers.Crawler.Asset;
import io.andrewohara.tinkertime.io.crawlers.Crawler.AssetSelector;
import java.util.ArrayList;
import java.util.Collection;
package io.andrewohara.tinkertime.testUtil;
public class StaticAssetSelector implements AssetSelector {
@Override | public Asset selectAsset(String modName, Collection<Asset> assets) { |
oharaandrew314/TinkerTime | src/io/andrewohara/tinkertime/views/SelectedInstallationView.java | // Path: src/io/andrewohara/tinkertime/controllers/ModUpdateHandler.java
// public interface ModUpdateHandler {
//
// public void changeInstallation(Installation installation);
//
// }
//
// Path: src/io/andrewohara/tinkertime/models/Installation.java
// @DatabaseTable(tableName = "installations")
// public class Installation extends BaseDaoEnabled<Installation, Integer>{
//
// @DatabaseField(generatedId=true)
// private int id;
//
// @DatabaseField(canBeNull=false)
// private String name, path;
//
// @ForeignCollectionField(eager = true)
// private Collection<Mod> mods = new LinkedList<>();
//
// Installation() { /* Required by ormlite */ }
//
// public Installation(String name, Path path, Dao<Installation, Integer> dao) throws InvalidGameDataPathException, SQLException{
// this.name = name;
//
// if (!path.endsWith("GameData")) {
// throw new InvalidGameDataPathException(path, "Must be a GameData Path");
// } else if (!path.toFile().isDirectory()){
// throw new InvalidGameDataPathException(path, "Must be an existing directory");
// }
// this.path = path.toString();
//
// setDao(dao);
// create();
// }
//
// /////////////
// // Setters //
// /////////////
//
// public void rename(String name) throws SQLException{
// this.name = name;
// update();
// }
//
// public void addMod(Mod mod) throws SQLException{
// if (!mods.contains(mod)){
// mods.add(mod);
// update();
// }
// }
//
// public void removeMod(Mod mod) throws SQLException{
// mods.remove(mod);
// update();
// }
//
// /////////////
// // Getters //
// /////////////
//
// public String getName(){
// return name;
// }
//
// public Path getGameDataPath(){
// return Paths.get(path);
// }
//
// public Collection<Mod> getMods(){
// return new LinkedList<>(mods);
// }
//
// public Path getModZipsPath(){
// return getGameDataPath().getParent().resolve(TinkerTimeLauncher.SAFE_NAME + "-ModCache");
// }
//
// /////////
// // Dao //
// /////////
//
// @Override
// public int delete() throws SQLException {
// for (Mod mod : getMods()){
// mod.delete();
// }
// return super.delete();
// }
//
// ////////////
// // Object //
// ////////////
//
// @Override
// public String toString(){
// return getName();
// }
//
// @Override
// public boolean equals(Object o){
// return o instanceof Installation && ((Installation)o).id == id;
// }
//
// ////////////////
// // Exceptions //
// ////////////////
//
// @SuppressWarnings("serial")
// public static class InvalidGameDataPathException extends Exception {
//
// public InvalidGameDataPathException(Path path, String reason){
// super(String.format("The GameDataPath: %s, is invalid: %s", path, reason));
// }
// }
// }
| import io.andrewohara.common.views.DecoratedComponent;
import io.andrewohara.tinkertime.controllers.ModUpdateHandler;
import io.andrewohara.tinkertime.models.Installation;
import javax.swing.JLabel;
import com.google.inject.Singleton; | package io.andrewohara.tinkertime.views;
@Singleton
public class SelectedInstallationView implements DecoratedComponent<JLabel>, ModUpdateHandler{
private final JLabel label = new JLabel();
public SelectedInstallationView() {
changeInstallation(null);
}
@Override
public JLabel getComponent() {
return label;
}
@Override | // Path: src/io/andrewohara/tinkertime/controllers/ModUpdateHandler.java
// public interface ModUpdateHandler {
//
// public void changeInstallation(Installation installation);
//
// }
//
// Path: src/io/andrewohara/tinkertime/models/Installation.java
// @DatabaseTable(tableName = "installations")
// public class Installation extends BaseDaoEnabled<Installation, Integer>{
//
// @DatabaseField(generatedId=true)
// private int id;
//
// @DatabaseField(canBeNull=false)
// private String name, path;
//
// @ForeignCollectionField(eager = true)
// private Collection<Mod> mods = new LinkedList<>();
//
// Installation() { /* Required by ormlite */ }
//
// public Installation(String name, Path path, Dao<Installation, Integer> dao) throws InvalidGameDataPathException, SQLException{
// this.name = name;
//
// if (!path.endsWith("GameData")) {
// throw new InvalidGameDataPathException(path, "Must be a GameData Path");
// } else if (!path.toFile().isDirectory()){
// throw new InvalidGameDataPathException(path, "Must be an existing directory");
// }
// this.path = path.toString();
//
// setDao(dao);
// create();
// }
//
// /////////////
// // Setters //
// /////////////
//
// public void rename(String name) throws SQLException{
// this.name = name;
// update();
// }
//
// public void addMod(Mod mod) throws SQLException{
// if (!mods.contains(mod)){
// mods.add(mod);
// update();
// }
// }
//
// public void removeMod(Mod mod) throws SQLException{
// mods.remove(mod);
// update();
// }
//
// /////////////
// // Getters //
// /////////////
//
// public String getName(){
// return name;
// }
//
// public Path getGameDataPath(){
// return Paths.get(path);
// }
//
// public Collection<Mod> getMods(){
// return new LinkedList<>(mods);
// }
//
// public Path getModZipsPath(){
// return getGameDataPath().getParent().resolve(TinkerTimeLauncher.SAFE_NAME + "-ModCache");
// }
//
// /////////
// // Dao //
// /////////
//
// @Override
// public int delete() throws SQLException {
// for (Mod mod : getMods()){
// mod.delete();
// }
// return super.delete();
// }
//
// ////////////
// // Object //
// ////////////
//
// @Override
// public String toString(){
// return getName();
// }
//
// @Override
// public boolean equals(Object o){
// return o instanceof Installation && ((Installation)o).id == id;
// }
//
// ////////////////
// // Exceptions //
// ////////////////
//
// @SuppressWarnings("serial")
// public static class InvalidGameDataPathException extends Exception {
//
// public InvalidGameDataPathException(Path path, String reason){
// super(String.format("The GameDataPath: %s, is invalid: %s", path, reason));
// }
// }
// }
// Path: src/io/andrewohara/tinkertime/views/SelectedInstallationView.java
import io.andrewohara.common.views.DecoratedComponent;
import io.andrewohara.tinkertime.controllers.ModUpdateHandler;
import io.andrewohara.tinkertime.models.Installation;
import javax.swing.JLabel;
import com.google.inject.Singleton;
package io.andrewohara.tinkertime.views;
@Singleton
public class SelectedInstallationView implements DecoratedComponent<JLabel>, ModUpdateHandler{
private final JLabel label = new JLabel();
public SelectedInstallationView() {
changeInstallation(null);
}
@Override
public JLabel getComponent() {
return label;
}
@Override | public void changeInstallation(Installation installation) { |
jboss-integration/fuse-bxms-integ | switchyard/switchyard-component-common-knowledge/src/main/java/org/switchyard/component/common/knowledge/config/builder/RemoteConfigurationBuilder.java | // Path: switchyard/switchyard-component-common-knowledge/src/main/java/org/switchyard/component/common/knowledge/config/model/ExtraJaxbClassesModel.java
// public interface ExtraJaxbClassesModel extends Model {
//
// /** The "extraJaxbClasses" name. */
// public static final String EXTRA_JAXB_CLASSES = "extraJaxbClasses";
//
// /** Gets the child extraJaxbClass models.
// *
// * @return the child extraJaxbClass models */
// public List<ExtraJaxbClassModel> getExtraJaxbClasses();
//
// /** Adds a child extraJaxbClass model.
// *
// * @param extraJaxbClass the child extraJaxbClass model
// * @return this ExtraJaxbClassesModel (useful for chaining) */
// public ExtraJaxbClassesModel addExtraJaxbClass(ExtraJaxbClassModel extraJaxbClass);
//
// }
//
// Path: switchyard/switchyard-component-common-knowledge/src/main/java/org/switchyard/component/common/knowledge/config/model/RemoteModel.java
// public interface RemoteModel extends Model {
//
// /** Gets the deploymentId attribute.
// *
// * @return the deploymentId attribute */
// public String getDeploymentId();
//
// /** Sets the deploymentId attribute.
// *
// * @param deploymentId the deploymentId attribute
// * @return this RemoteModel (useful for chaining) */
// public RemoteModel setDeploymentId(String deploymentId);
//
// /** Gets the userName attribute.
// *
// * @return the userName attribute */
// public String getUserName();
//
// /** Sets the userName attribute.
// *
// * @param userName the userName attribute
// * @return this RemoteModel (useful for chaining) */
// public RemoteModel setUserName(String userName);
//
// /** Gets the password attribute.
// *
// * @return the password attribute */
// public String getPassword();
//
// /** Sets the password attribute.
// *
// * @param password the password attribute
// * @return this RemoteModel (useful for chaining) */
// public RemoteModel setPassword(String password);
//
// /** Gets the timeout attribute.
// *
// * @return the timeout attribute */
// public Integer getTimeout();
//
// /** Sets the timeout attribute.
// *
// * @param timeout the timeout attribute
// * @return this RemoteModel (useful for chaining) */
// public RemoteModel setTimeout(Integer timeout);
//
// /** Gets the child extraJaxbClasses model.
// *
// * @return the child extraJaxbClasses model */
// public ExtraJaxbClassesModel getExtraJaxbClasses();
//
// /** Sets the child extraJaxbClasses model.
// *
// * @param extraJaxbClasses the child extraJaxbClasses model
// * @return this RemoteModel (useful for chaining) */
// public RemoteModel setExtraJaxbClasses(ExtraJaxbClassesModel extraJaxbClasses);
//
// }
| import java.net.MalformedURLException;
import java.net.URL;
import java.util.LinkedHashSet;
import java.util.Properties;
import java.util.Set;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import org.kie.api.runtime.manager.RuntimeEngine;
import org.kie.remote.client.api.RemoteJmsRuntimeEngineBuilder;
import org.kie.remote.client.api.RemoteRestRuntimeEngineBuilder;
import org.kie.remote.client.api.RemoteRuntimeEngineBuilder;
import org.kie.services.client.api.RemoteRuntimeEngineFactory;
import org.kie.services.client.api.command.RemoteConfiguration;
import org.kie.services.client.api.command.RemoteRuntimeEngine;
import org.switchyard.common.type.reflect.Access;
import org.switchyard.common.type.reflect.FieldAccess;
import org.switchyard.component.common.knowledge.config.model.ExtraJaxbClassModel;
import org.switchyard.component.common.knowledge.config.model.ExtraJaxbClassesModel;
import org.switchyard.component.common.knowledge.config.model.RemoteJmsModel;
import org.switchyard.component.common.knowledge.config.model.RemoteModel;
import org.switchyard.component.common.knowledge.config.model.RemoteRestModel; | /*
* Copyright 2014 Red Hat Inc. and/or its affiliates and other contributors.
* 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 org.switchyard.component.common.knowledge.config.builder;
/** RemoteConfigurationBuilder.
*
* @author David Ward <<a href="mailto:dward@jboss.org">dward@jboss.org</a>> © 2014 Red Hat Inc. */
public class RemoteConfigurationBuilder extends KnowledgeBuilder {
private final RemoteConfiguration _remoteConfiguration;
/** Creates a new RemoteConfigurationBuilder.
*
* @param classLoader classLoader
* @param remoteModel remoteModel */ | // Path: switchyard/switchyard-component-common-knowledge/src/main/java/org/switchyard/component/common/knowledge/config/model/ExtraJaxbClassesModel.java
// public interface ExtraJaxbClassesModel extends Model {
//
// /** The "extraJaxbClasses" name. */
// public static final String EXTRA_JAXB_CLASSES = "extraJaxbClasses";
//
// /** Gets the child extraJaxbClass models.
// *
// * @return the child extraJaxbClass models */
// public List<ExtraJaxbClassModel> getExtraJaxbClasses();
//
// /** Adds a child extraJaxbClass model.
// *
// * @param extraJaxbClass the child extraJaxbClass model
// * @return this ExtraJaxbClassesModel (useful for chaining) */
// public ExtraJaxbClassesModel addExtraJaxbClass(ExtraJaxbClassModel extraJaxbClass);
//
// }
//
// Path: switchyard/switchyard-component-common-knowledge/src/main/java/org/switchyard/component/common/knowledge/config/model/RemoteModel.java
// public interface RemoteModel extends Model {
//
// /** Gets the deploymentId attribute.
// *
// * @return the deploymentId attribute */
// public String getDeploymentId();
//
// /** Sets the deploymentId attribute.
// *
// * @param deploymentId the deploymentId attribute
// * @return this RemoteModel (useful for chaining) */
// public RemoteModel setDeploymentId(String deploymentId);
//
// /** Gets the userName attribute.
// *
// * @return the userName attribute */
// public String getUserName();
//
// /** Sets the userName attribute.
// *
// * @param userName the userName attribute
// * @return this RemoteModel (useful for chaining) */
// public RemoteModel setUserName(String userName);
//
// /** Gets the password attribute.
// *
// * @return the password attribute */
// public String getPassword();
//
// /** Sets the password attribute.
// *
// * @param password the password attribute
// * @return this RemoteModel (useful for chaining) */
// public RemoteModel setPassword(String password);
//
// /** Gets the timeout attribute.
// *
// * @return the timeout attribute */
// public Integer getTimeout();
//
// /** Sets the timeout attribute.
// *
// * @param timeout the timeout attribute
// * @return this RemoteModel (useful for chaining) */
// public RemoteModel setTimeout(Integer timeout);
//
// /** Gets the child extraJaxbClasses model.
// *
// * @return the child extraJaxbClasses model */
// public ExtraJaxbClassesModel getExtraJaxbClasses();
//
// /** Sets the child extraJaxbClasses model.
// *
// * @param extraJaxbClasses the child extraJaxbClasses model
// * @return this RemoteModel (useful for chaining) */
// public RemoteModel setExtraJaxbClasses(ExtraJaxbClassesModel extraJaxbClasses);
//
// }
// Path: switchyard/switchyard-component-common-knowledge/src/main/java/org/switchyard/component/common/knowledge/config/builder/RemoteConfigurationBuilder.java
import java.net.MalformedURLException;
import java.net.URL;
import java.util.LinkedHashSet;
import java.util.Properties;
import java.util.Set;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import org.kie.api.runtime.manager.RuntimeEngine;
import org.kie.remote.client.api.RemoteJmsRuntimeEngineBuilder;
import org.kie.remote.client.api.RemoteRestRuntimeEngineBuilder;
import org.kie.remote.client.api.RemoteRuntimeEngineBuilder;
import org.kie.services.client.api.RemoteRuntimeEngineFactory;
import org.kie.services.client.api.command.RemoteConfiguration;
import org.kie.services.client.api.command.RemoteRuntimeEngine;
import org.switchyard.common.type.reflect.Access;
import org.switchyard.common.type.reflect.FieldAccess;
import org.switchyard.component.common.knowledge.config.model.ExtraJaxbClassModel;
import org.switchyard.component.common.knowledge.config.model.ExtraJaxbClassesModel;
import org.switchyard.component.common.knowledge.config.model.RemoteJmsModel;
import org.switchyard.component.common.knowledge.config.model.RemoteModel;
import org.switchyard.component.common.knowledge.config.model.RemoteRestModel;
/*
* Copyright 2014 Red Hat Inc. and/or its affiliates and other contributors.
* 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 org.switchyard.component.common.knowledge.config.builder;
/** RemoteConfigurationBuilder.
*
* @author David Ward <<a href="mailto:dward@jboss.org">dward@jboss.org</a>> © 2014 Red Hat Inc. */
public class RemoteConfigurationBuilder extends KnowledgeBuilder {
private final RemoteConfiguration _remoteConfiguration;
/** Creates a new RemoteConfigurationBuilder.
*
* @param classLoader classLoader
* @param remoteModel remoteModel */ | public RemoteConfigurationBuilder(ClassLoader classLoader, RemoteModel remoteModel) { |
jboss-integration/fuse-bxms-integ | switchyard/switchyard-component-common-knowledge/src/main/java/org/switchyard/component/common/knowledge/config/builder/RemoteConfigurationBuilder.java | // Path: switchyard/switchyard-component-common-knowledge/src/main/java/org/switchyard/component/common/knowledge/config/model/ExtraJaxbClassesModel.java
// public interface ExtraJaxbClassesModel extends Model {
//
// /** The "extraJaxbClasses" name. */
// public static final String EXTRA_JAXB_CLASSES = "extraJaxbClasses";
//
// /** Gets the child extraJaxbClass models.
// *
// * @return the child extraJaxbClass models */
// public List<ExtraJaxbClassModel> getExtraJaxbClasses();
//
// /** Adds a child extraJaxbClass model.
// *
// * @param extraJaxbClass the child extraJaxbClass model
// * @return this ExtraJaxbClassesModel (useful for chaining) */
// public ExtraJaxbClassesModel addExtraJaxbClass(ExtraJaxbClassModel extraJaxbClass);
//
// }
//
// Path: switchyard/switchyard-component-common-knowledge/src/main/java/org/switchyard/component/common/knowledge/config/model/RemoteModel.java
// public interface RemoteModel extends Model {
//
// /** Gets the deploymentId attribute.
// *
// * @return the deploymentId attribute */
// public String getDeploymentId();
//
// /** Sets the deploymentId attribute.
// *
// * @param deploymentId the deploymentId attribute
// * @return this RemoteModel (useful for chaining) */
// public RemoteModel setDeploymentId(String deploymentId);
//
// /** Gets the userName attribute.
// *
// * @return the userName attribute */
// public String getUserName();
//
// /** Sets the userName attribute.
// *
// * @param userName the userName attribute
// * @return this RemoteModel (useful for chaining) */
// public RemoteModel setUserName(String userName);
//
// /** Gets the password attribute.
// *
// * @return the password attribute */
// public String getPassword();
//
// /** Sets the password attribute.
// *
// * @param password the password attribute
// * @return this RemoteModel (useful for chaining) */
// public RemoteModel setPassword(String password);
//
// /** Gets the timeout attribute.
// *
// * @return the timeout attribute */
// public Integer getTimeout();
//
// /** Sets the timeout attribute.
// *
// * @param timeout the timeout attribute
// * @return this RemoteModel (useful for chaining) */
// public RemoteModel setTimeout(Integer timeout);
//
// /** Gets the child extraJaxbClasses model.
// *
// * @return the child extraJaxbClasses model */
// public ExtraJaxbClassesModel getExtraJaxbClasses();
//
// /** Sets the child extraJaxbClasses model.
// *
// * @param extraJaxbClasses the child extraJaxbClasses model
// * @return this RemoteModel (useful for chaining) */
// public RemoteModel setExtraJaxbClasses(ExtraJaxbClassesModel extraJaxbClasses);
//
// }
| import java.net.MalformedURLException;
import java.net.URL;
import java.util.LinkedHashSet;
import java.util.Properties;
import java.util.Set;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import org.kie.api.runtime.manager.RuntimeEngine;
import org.kie.remote.client.api.RemoteJmsRuntimeEngineBuilder;
import org.kie.remote.client.api.RemoteRestRuntimeEngineBuilder;
import org.kie.remote.client.api.RemoteRuntimeEngineBuilder;
import org.kie.services.client.api.RemoteRuntimeEngineFactory;
import org.kie.services.client.api.command.RemoteConfiguration;
import org.kie.services.client.api.command.RemoteRuntimeEngine;
import org.switchyard.common.type.reflect.Access;
import org.switchyard.common.type.reflect.FieldAccess;
import org.switchyard.component.common.knowledge.config.model.ExtraJaxbClassModel;
import org.switchyard.component.common.knowledge.config.model.ExtraJaxbClassesModel;
import org.switchyard.component.common.knowledge.config.model.RemoteJmsModel;
import org.switchyard.component.common.knowledge.config.model.RemoteModel;
import org.switchyard.component.common.knowledge.config.model.RemoteRestModel; | if (truststoreLocation != null) {
builder.addTruststoreLocation(truststoreLocation);
}
return ctx;
}
@SuppressWarnings("deprecation")
private void configRemoteRest(RemoteRestRuntimeEngineBuilder builder, RemoteRestModel model) {
configRemote(builder, model);
try {
builder.addUrl(new URL(model.getUrl()));
} catch (MalformedURLException mue) {
throw new RuntimeException(mue);
}
}
private void configRemote(RemoteRuntimeEngineBuilder<?, ?> builder, RemoteModel model) {
builder.addDeploymentId(model.getDeploymentId());
String userName = model.getUserName();
if (userName != null) {
builder.addUserName(userName);
}
String password = model.getPassword();
if (password != null) {
builder.addPassword(password);
}
Integer timeout = model.getTimeout();
if (timeout != null) {
builder.addTimeout(timeout.intValue());
} | // Path: switchyard/switchyard-component-common-knowledge/src/main/java/org/switchyard/component/common/knowledge/config/model/ExtraJaxbClassesModel.java
// public interface ExtraJaxbClassesModel extends Model {
//
// /** The "extraJaxbClasses" name. */
// public static final String EXTRA_JAXB_CLASSES = "extraJaxbClasses";
//
// /** Gets the child extraJaxbClass models.
// *
// * @return the child extraJaxbClass models */
// public List<ExtraJaxbClassModel> getExtraJaxbClasses();
//
// /** Adds a child extraJaxbClass model.
// *
// * @param extraJaxbClass the child extraJaxbClass model
// * @return this ExtraJaxbClassesModel (useful for chaining) */
// public ExtraJaxbClassesModel addExtraJaxbClass(ExtraJaxbClassModel extraJaxbClass);
//
// }
//
// Path: switchyard/switchyard-component-common-knowledge/src/main/java/org/switchyard/component/common/knowledge/config/model/RemoteModel.java
// public interface RemoteModel extends Model {
//
// /** Gets the deploymentId attribute.
// *
// * @return the deploymentId attribute */
// public String getDeploymentId();
//
// /** Sets the deploymentId attribute.
// *
// * @param deploymentId the deploymentId attribute
// * @return this RemoteModel (useful for chaining) */
// public RemoteModel setDeploymentId(String deploymentId);
//
// /** Gets the userName attribute.
// *
// * @return the userName attribute */
// public String getUserName();
//
// /** Sets the userName attribute.
// *
// * @param userName the userName attribute
// * @return this RemoteModel (useful for chaining) */
// public RemoteModel setUserName(String userName);
//
// /** Gets the password attribute.
// *
// * @return the password attribute */
// public String getPassword();
//
// /** Sets the password attribute.
// *
// * @param password the password attribute
// * @return this RemoteModel (useful for chaining) */
// public RemoteModel setPassword(String password);
//
// /** Gets the timeout attribute.
// *
// * @return the timeout attribute */
// public Integer getTimeout();
//
// /** Sets the timeout attribute.
// *
// * @param timeout the timeout attribute
// * @return this RemoteModel (useful for chaining) */
// public RemoteModel setTimeout(Integer timeout);
//
// /** Gets the child extraJaxbClasses model.
// *
// * @return the child extraJaxbClasses model */
// public ExtraJaxbClassesModel getExtraJaxbClasses();
//
// /** Sets the child extraJaxbClasses model.
// *
// * @param extraJaxbClasses the child extraJaxbClasses model
// * @return this RemoteModel (useful for chaining) */
// public RemoteModel setExtraJaxbClasses(ExtraJaxbClassesModel extraJaxbClasses);
//
// }
// Path: switchyard/switchyard-component-common-knowledge/src/main/java/org/switchyard/component/common/knowledge/config/builder/RemoteConfigurationBuilder.java
import java.net.MalformedURLException;
import java.net.URL;
import java.util.LinkedHashSet;
import java.util.Properties;
import java.util.Set;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import org.kie.api.runtime.manager.RuntimeEngine;
import org.kie.remote.client.api.RemoteJmsRuntimeEngineBuilder;
import org.kie.remote.client.api.RemoteRestRuntimeEngineBuilder;
import org.kie.remote.client.api.RemoteRuntimeEngineBuilder;
import org.kie.services.client.api.RemoteRuntimeEngineFactory;
import org.kie.services.client.api.command.RemoteConfiguration;
import org.kie.services.client.api.command.RemoteRuntimeEngine;
import org.switchyard.common.type.reflect.Access;
import org.switchyard.common.type.reflect.FieldAccess;
import org.switchyard.component.common.knowledge.config.model.ExtraJaxbClassModel;
import org.switchyard.component.common.knowledge.config.model.ExtraJaxbClassesModel;
import org.switchyard.component.common.knowledge.config.model.RemoteJmsModel;
import org.switchyard.component.common.knowledge.config.model.RemoteModel;
import org.switchyard.component.common.knowledge.config.model.RemoteRestModel;
if (truststoreLocation != null) {
builder.addTruststoreLocation(truststoreLocation);
}
return ctx;
}
@SuppressWarnings("deprecation")
private void configRemoteRest(RemoteRestRuntimeEngineBuilder builder, RemoteRestModel model) {
configRemote(builder, model);
try {
builder.addUrl(new URL(model.getUrl()));
} catch (MalformedURLException mue) {
throw new RuntimeException(mue);
}
}
private void configRemote(RemoteRuntimeEngineBuilder<?, ?> builder, RemoteModel model) {
builder.addDeploymentId(model.getDeploymentId());
String userName = model.getUserName();
if (userName != null) {
builder.addUserName(userName);
}
String password = model.getPassword();
if (password != null) {
builder.addPassword(password);
}
Integer timeout = model.getTimeout();
if (timeout != null) {
builder.addTimeout(timeout.intValue());
} | ExtraJaxbClassesModel extraJaxbClasses = model.getExtraJaxbClasses(); |
jboss-integration/fuse-bxms-integ | camel/kie-camel/src/test/java/org/kie/camel/component/CamelEndpointWithMarshallersTest.java | // Path: camel/kie-camel/src/test/java/org/kie/pipeline/camel/Person.java
// @XmlRootElement
// public class Person {
// private String name;
// private Integer age;
//
// public Person() {
// }
//
// public Person(String name) {
// super();
// this.name = name;
// }
//
// public Person(String name, int age) {
// super();
// this.name = name;
// this.age = age;
// }
//
// public String getName() {
// return name;
// }
//
// public void setName(String name) {
// this.name = name;
// }
//
// public void setAge(Integer age) {
// this.age = age;
// }
//
// public Integer getAge() {
// return age;
// }
//
// @Override
// public String toString() {
// return "Person [age=" + age + ", name=" + name + "]";
// }
//
// }
| import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
import org.apache.camel.builder.RouteBuilder;
import org.apache.camel.model.DataFormatDefinition;
import org.drools.core.command.impl.GenericCommand;
import org.drools.core.command.runtime.BatchExecutionCommandImpl;
import org.drools.core.command.runtime.rule.InsertObjectCommand;
import org.drools.core.common.InternalFactHandle;
import org.kie.api.runtime.KieSession;
import org.kie.pipeline.camel.Person;
import org.junit.Test;
import org.kie.internal.runtime.StatefulKnowledgeSession;
import org.kie.api.runtime.ExecutionResults;
import org.kie.internal.runtime.helper.BatchExecutionHelper;
import org.kie.api.runtime.rule.FactHandle;
import com.thoughtworks.xstream.XStream;
import com.thoughtworks.xstream.converters.Converter;
import com.thoughtworks.xstream.converters.MarshallingContext;
import com.thoughtworks.xstream.converters.UnmarshallingContext;
import com.thoughtworks.xstream.io.HierarchicalStreamReader;
import com.thoughtworks.xstream.io.HierarchicalStreamWriter; | /*
* Copyright 2010 JBoss Inc
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/*
* 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.
* under the License.
*/
package org.kie.camel.component;
public class CamelEndpointWithMarshallersTest extends KieCamelTestSupport {
private String handle;
@Test
public void testSimple() {
}
@Test
public void testSessionInsert() throws Exception {
String cmd = "";
cmd += "<batch-execution lookup=\"ksession1\">\n";
cmd += " <insert out-identifier=\"salaboy\">\n";
cmd += " <org.kie.pipeline.camel.Person>\n";
cmd += " <name>salaboy</name>\n";
cmd += " </org.kie.pipeline.camel.Person>\n";
cmd += " </insert>\n";
cmd += " <fire-all-rules/>\n";
cmd += "</batch-execution>\n";
String outXml = new String((byte[])template.requestBody("direct:test-with-session", cmd));
ExecutionResults result = (ExecutionResults)BatchExecutionHelper.newXStreamMarshaller().fromXML(outXml); | // Path: camel/kie-camel/src/test/java/org/kie/pipeline/camel/Person.java
// @XmlRootElement
// public class Person {
// private String name;
// private Integer age;
//
// public Person() {
// }
//
// public Person(String name) {
// super();
// this.name = name;
// }
//
// public Person(String name, int age) {
// super();
// this.name = name;
// this.age = age;
// }
//
// public String getName() {
// return name;
// }
//
// public void setName(String name) {
// this.name = name;
// }
//
// public void setAge(Integer age) {
// this.age = age;
// }
//
// public Integer getAge() {
// return age;
// }
//
// @Override
// public String toString() {
// return "Person [age=" + age + ", name=" + name + "]";
// }
//
// }
// Path: camel/kie-camel/src/test/java/org/kie/camel/component/CamelEndpointWithMarshallersTest.java
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
import org.apache.camel.builder.RouteBuilder;
import org.apache.camel.model.DataFormatDefinition;
import org.drools.core.command.impl.GenericCommand;
import org.drools.core.command.runtime.BatchExecutionCommandImpl;
import org.drools.core.command.runtime.rule.InsertObjectCommand;
import org.drools.core.common.InternalFactHandle;
import org.kie.api.runtime.KieSession;
import org.kie.pipeline.camel.Person;
import org.junit.Test;
import org.kie.internal.runtime.StatefulKnowledgeSession;
import org.kie.api.runtime.ExecutionResults;
import org.kie.internal.runtime.helper.BatchExecutionHelper;
import org.kie.api.runtime.rule.FactHandle;
import com.thoughtworks.xstream.XStream;
import com.thoughtworks.xstream.converters.Converter;
import com.thoughtworks.xstream.converters.MarshallingContext;
import com.thoughtworks.xstream.converters.UnmarshallingContext;
import com.thoughtworks.xstream.io.HierarchicalStreamReader;
import com.thoughtworks.xstream.io.HierarchicalStreamWriter;
/*
* Copyright 2010 JBoss Inc
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/*
* 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.
* under the License.
*/
package org.kie.camel.component;
public class CamelEndpointWithMarshallersTest extends KieCamelTestSupport {
private String handle;
@Test
public void testSimple() {
}
@Test
public void testSessionInsert() throws Exception {
String cmd = "";
cmd += "<batch-execution lookup=\"ksession1\">\n";
cmd += " <insert out-identifier=\"salaboy\">\n";
cmd += " <org.kie.pipeline.camel.Person>\n";
cmd += " <name>salaboy</name>\n";
cmd += " </org.kie.pipeline.camel.Person>\n";
cmd += " </insert>\n";
cmd += " <fire-all-rules/>\n";
cmd += "</batch-execution>\n";
String outXml = new String((byte[])template.requestBody("direct:test-with-session", cmd));
ExecutionResults result = (ExecutionResults)BatchExecutionHelper.newXStreamMarshaller().fromXML(outXml); | Person person = (Person)result.getValue("salaboy"); |
jboss-integration/fuse-bxms-integ | quickstarts/switchyard-bpm-service/src/main/java/org/switchyard/quickstarts/bpm/service/BackOrderBean.java | // Path: quickstarts/switchyard-bpm-service/src/main/java/org/switchyard/quickstarts/bpm/service/data/Order.java
// @XmlAccessorType(XmlAccessType.FIELD)
// @XmlType(name = "", propOrder = { "orderId", "itemId", "quantity" })
// @XmlRootElement(name = "submitOrder")
// public class Order {
//
// /** The order id. */
// @XmlElement(required = true)
// private String orderId;
//
// /** The item id. */
// @XmlElement(required = true)
// private String itemId;
//
// /** The quantity. */
// private int quantity;
//
// /**
// * Gets the value of the orderId property.
// *
// * @return possible object is {@link String }
// *
// */
// public String getOrderId() {
// return orderId;
// }
//
// /**
// * Sets the value of the orderId property.
// *
// * @param value allowed object is {@link String }
// *
// */
// public void setOrderId(String value) {
// this.orderId = value;
// }
//
// /**
// * Gets the value of the itemId property.
// *
// * @return possible object is {@link String }
// *
// */
// public String getItemId() {
// return itemId;
// }
//
// /**
// * Sets the value of the itemId property.
// *
// * @param value allowed object is {@link String }
// *
// */
// public void setItemId(String value) {
// this.itemId = value;
// }
//
// /**
// * Gets the value of the quantity property.
// *
// * @return the quantity
// */
// public int getQuantity() {
// return quantity;
// }
//
// /**
// * Sets the value of the quantity property.
// *
// * @param value the new quantity
// */
// public void setQuantity(int value) {
// this.quantity = value;
// }
//
// }
| import org.switchyard.component.bean.Service;
import org.switchyard.quickstarts.bpm.service.data.Order;
import org.switchyard.quickstarts.bpm.service.data.OrderAck; | /*
* JBoss, Home of Professional Open Source
* Copyright 2013, Red Hat, Inc. and/or its affiliates, and individual
* contributors by the @authors tag. See the copyright.txt in the
* distribution for a full listing of individual contributors.
*
* 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 org.switchyard.quickstarts.bpm.service;
/**
* The Class BackOrderBean.
*/
@Service(BackOrder.class)
public class BackOrderBean implements org.switchyard.quickstarts.bpm.service.BackOrder {
/** The Constant HOLD_STATUS. */
public static final String HOLD_STATUS = "Insufficient quantity on hand - order has been placed on hold.";
@Override | // Path: quickstarts/switchyard-bpm-service/src/main/java/org/switchyard/quickstarts/bpm/service/data/Order.java
// @XmlAccessorType(XmlAccessType.FIELD)
// @XmlType(name = "", propOrder = { "orderId", "itemId", "quantity" })
// @XmlRootElement(name = "submitOrder")
// public class Order {
//
// /** The order id. */
// @XmlElement(required = true)
// private String orderId;
//
// /** The item id. */
// @XmlElement(required = true)
// private String itemId;
//
// /** The quantity. */
// private int quantity;
//
// /**
// * Gets the value of the orderId property.
// *
// * @return possible object is {@link String }
// *
// */
// public String getOrderId() {
// return orderId;
// }
//
// /**
// * Sets the value of the orderId property.
// *
// * @param value allowed object is {@link String }
// *
// */
// public void setOrderId(String value) {
// this.orderId = value;
// }
//
// /**
// * Gets the value of the itemId property.
// *
// * @return possible object is {@link String }
// *
// */
// public String getItemId() {
// return itemId;
// }
//
// /**
// * Sets the value of the itemId property.
// *
// * @param value allowed object is {@link String }
// *
// */
// public void setItemId(String value) {
// this.itemId = value;
// }
//
// /**
// * Gets the value of the quantity property.
// *
// * @return the quantity
// */
// public int getQuantity() {
// return quantity;
// }
//
// /**
// * Sets the value of the quantity property.
// *
// * @param value the new quantity
// */
// public void setQuantity(int value) {
// this.quantity = value;
// }
//
// }
// Path: quickstarts/switchyard-bpm-service/src/main/java/org/switchyard/quickstarts/bpm/service/BackOrderBean.java
import org.switchyard.component.bean.Service;
import org.switchyard.quickstarts.bpm.service.data.Order;
import org.switchyard.quickstarts.bpm.service.data.OrderAck;
/*
* JBoss, Home of Professional Open Source
* Copyright 2013, Red Hat, Inc. and/or its affiliates, and individual
* contributors by the @authors tag. See the copyright.txt in the
* distribution for a full listing of individual contributors.
*
* 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 org.switchyard.quickstarts.bpm.service;
/**
* The Class BackOrderBean.
*/
@Service(BackOrder.class)
public class BackOrderBean implements org.switchyard.quickstarts.bpm.service.BackOrder {
/** The Constant HOLD_STATUS. */
public static final String HOLD_STATUS = "Insufficient quantity on hand - order has been placed on hold.";
@Override | public OrderAck hold(Order order) { |
jboss-integration/fuse-bxms-integ | camel/jbpm-workitems-camel/src/main/java/org/jbpm/process/workitem/camel/CamelHandlerFactory.java | // Path: camel/jbpm-workitems-camel/src/main/java/org/jbpm/process/workitem/camel/uri/SQLURIMapper.java
// public class SQLURIMapper extends URIMapper {
// // sql:select * from table where id=# order by name[?options]
//
// public SQLURIMapper() {
// super("sql");
// }
//
// @Override
// public URI toURI(Map<String, Object> options) throws URISyntaxException {
// String query = (String)options.get("query");
// options.remove("query");
//
// String path = query;
// return prepareCamelUri(path, options);
// }
//
// }
| import org.jbpm.process.workitem.camel.request.FTPRequestPayloadMapper;
import org.jbpm.process.workitem.camel.request.RequestPayloadMapper;
import org.jbpm.process.workitem.camel.uri.CXFURIMapper;
import org.jbpm.process.workitem.camel.uri.FTPURIMapper;
import org.jbpm.process.workitem.camel.uri.FileURIMapper;
import org.jbpm.process.workitem.camel.uri.GenericURIMapper;
import org.jbpm.process.workitem.camel.uri.JMSURIMapper;
import org.jbpm.process.workitem.camel.uri.SQLURIMapper;
import org.jbpm.process.workitem.camel.uri.XSLTURIMapper; | /*
* Copyright 2016 Red Hat Inc. and/or its affiliates and other contributors.
* 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 org.jbpm.process.workitem.camel;
public class CamelHandlerFactory {
public static CamelHandler sftpHandler() {
return new CamelHandler(new FTPURIMapper("sftp"), new FTPRequestPayloadMapper("payload"));
}
public static CamelHandler ftpHandler() {
return new CamelHandler(new FTPURIMapper("ftp"), new FTPRequestPayloadMapper("payload"));
}
public static CamelHandler ftpsHandler() {
return new CamelHandler(new FTPURIMapper("ftps"), new FTPRequestPayloadMapper("payload"));
}
public static CamelHandler cxfHandler() {
return new CamelHandler(new CXFURIMapper(), new RequestPayloadMapper("payload"));
}
public static CamelHandler fileHandler() {
return new CamelHandler(new FileURIMapper(), new RequestPayloadMapper("payload"));
}
public static CamelHandler xsltHandler() {
return new CamelHandler(new XSLTURIMapper(), new RequestPayloadMapper("payload"));
}
public static CamelHandler jmsHandler() {
return new CamelHandler(new JMSURIMapper(), new RequestPayloadMapper("payload"));
}
public static CamelHandler sqlHandler() { | // Path: camel/jbpm-workitems-camel/src/main/java/org/jbpm/process/workitem/camel/uri/SQLURIMapper.java
// public class SQLURIMapper extends URIMapper {
// // sql:select * from table where id=# order by name[?options]
//
// public SQLURIMapper() {
// super("sql");
// }
//
// @Override
// public URI toURI(Map<String, Object> options) throws URISyntaxException {
// String query = (String)options.get("query");
// options.remove("query");
//
// String path = query;
// return prepareCamelUri(path, options);
// }
//
// }
// Path: camel/jbpm-workitems-camel/src/main/java/org/jbpm/process/workitem/camel/CamelHandlerFactory.java
import org.jbpm.process.workitem.camel.request.FTPRequestPayloadMapper;
import org.jbpm.process.workitem.camel.request.RequestPayloadMapper;
import org.jbpm.process.workitem.camel.uri.CXFURIMapper;
import org.jbpm.process.workitem.camel.uri.FTPURIMapper;
import org.jbpm.process.workitem.camel.uri.FileURIMapper;
import org.jbpm.process.workitem.camel.uri.GenericURIMapper;
import org.jbpm.process.workitem.camel.uri.JMSURIMapper;
import org.jbpm.process.workitem.camel.uri.SQLURIMapper;
import org.jbpm.process.workitem.camel.uri.XSLTURIMapper;
/*
* Copyright 2016 Red Hat Inc. and/or its affiliates and other contributors.
* 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 org.jbpm.process.workitem.camel;
public class CamelHandlerFactory {
public static CamelHandler sftpHandler() {
return new CamelHandler(new FTPURIMapper("sftp"), new FTPRequestPayloadMapper("payload"));
}
public static CamelHandler ftpHandler() {
return new CamelHandler(new FTPURIMapper("ftp"), new FTPRequestPayloadMapper("payload"));
}
public static CamelHandler ftpsHandler() {
return new CamelHandler(new FTPURIMapper("ftps"), new FTPRequestPayloadMapper("payload"));
}
public static CamelHandler cxfHandler() {
return new CamelHandler(new CXFURIMapper(), new RequestPayloadMapper("payload"));
}
public static CamelHandler fileHandler() {
return new CamelHandler(new FileURIMapper(), new RequestPayloadMapper("payload"));
}
public static CamelHandler xsltHandler() {
return new CamelHandler(new XSLTURIMapper(), new RequestPayloadMapper("payload"));
}
public static CamelHandler jmsHandler() {
return new CamelHandler(new JMSURIMapper(), new RequestPayloadMapper("payload"));
}
public static CamelHandler sqlHandler() { | return new CamelHandler(new SQLURIMapper(), new RequestPayloadMapper("payload")); |
jboss-integration/fuse-bxms-integ | switchyard/switchyard-component-common-knowledge/src/main/java/org/switchyard/component/common/knowledge/config/builder/PropertiesBuilder.java | // Path: switchyard/switchyard-component-common-knowledge/src/main/java/org/switchyard/component/common/knowledge/config/model/KnowledgeComponentImplementationModel.java
// public interface KnowledgeComponentImplementationModel extends ComponentImplementationModel {
//
// /** Gets the "persistent" attribute.
// *
// * @return the "persistent" attribute */
// public boolean isPersistent();
//
// /** Sets the "persistent" attribute.
// *
// * @param persistent the "persistent" attribute
// * @return this instance (useful for chaining) */
// public KnowledgeComponentImplementationModel setPersistent(boolean persistent);
//
// /** Gets the "processId" attribute.
// *
// * @return the "processId" attribute */
// public String getProcessId();
//
// /** Sets the "processId" attribute.
// *
// * @param processId the "processId" attribute
// * @return this instance (useful for chaining) */
// public KnowledgeComponentImplementationModel setProcessId(String processId);
//
// /** Gets the child channels model.
// *
// * @return the child channels model */
// public ChannelsModel getChannels();
//
// /** Sets the child channels model.
// *
// * @param channels the child channels model
// * @return this KnowledgeComponentImplementationModel (useful for chaining) */
// public KnowledgeComponentImplementationModel setChannels(ChannelsModel channels);
//
// /** Gets the child listeners model.
// *
// * @return the child listeners model */
// public ListenersModel getListeners();
//
// /** Sets the child listeners model.
// *
// * @param listeners the child listeners model
// * @return this KnowledgeComponentImplementationModel (useful for chaining) */
// public KnowledgeComponentImplementationModel setListeners(ListenersModel listeners);
//
// /** Gets the child loggers model.
// *
// * @return the child loggers model */
// public LoggersModel getLoggers();
//
// /** Sets the child loggers model.
// *
// * @param loggers the child loggers model
// * @return this KnowledgeComponentImplementationModel (useful for chaining) */
// public KnowledgeComponentImplementationModel setLoggers(LoggersModel loggers);
//
// /** Gets the child manifest model.
// *
// * @return the child manifest model */
// public ManifestModel getManifest();
//
// /** Sets the child manifest model.
// *
// * @param manifest the child manifest model
// * @return this KnowledgeComponentImplementationModel (useful for chaining) */
// public KnowledgeComponentImplementationModel setManifest(ManifestModel manifest);
//
// /** Gets the child operations model.
// *
// * @return the child operations model */
// public OperationsModel getOperations();
//
// /** Sets the child operations model.
// *
// * @param operations the child operations model
// * @return this KnowledgeComponentImplementationModel (useful for chaining) */
// public KnowledgeComponentImplementationModel setOperations(OperationsModel operations);
//
// /** Gets the child properties model.
// *
// * @return the child properties model */
// public PropertiesModel getProperties();
//
// /** Sets the child properties model.
// *
// * @param properties the child properties model
// * @return this KnowledgeComponentImplementationModel (useful for chaining) */
// public KnowledgeComponentImplementationModel setProperties(PropertiesModel properties);
//
// /** Gets the child userGroupCallback model.
// *
// * @return the child userGroupCallback model */
// public UserGroupCallbackModel getUserGroupCallback();
//
// /** Sets the child userGroupCallback model.
// *
// * @param userGroupCallback the child userGroupCallback model
// * @return this instance (useful for chaining) */
// public KnowledgeComponentImplementationModel setUserGroupCallback(UserGroupCallbackModel userGroupCallback);
//
// /** Gets the child workItemHandlers model.
// *
// * @return the child workItemHandlers model */
// public WorkItemHandlersModel getWorkItemHandlers();
//
// /** Sets the child workItemHandlers model.
// *
// * @param workItemHandlers the child workItemHandlers model
// * @return this instance (useful for chaining) */
// public KnowledgeComponentImplementationModel setWorkItemHandlers(WorkItemHandlersModel workItemHandlers);
//
// }
| import org.switchyard.component.common.knowledge.config.model.KnowledgeComponentImplementationModel;
import org.switchyard.config.model.property.PropertiesModel;
import java.util.Properties; | return this;
}
/** Builds a Properties.
*
* @return a Properties */
public Properties build() {
Properties buildProperties = new Properties();
merge(_defaultProperties, buildProperties);
merge(_modelProperties, buildProperties);
merge(_overrideProperties, buildProperties);
return buildProperties;
}
private void merge(Properties fromProperties, Properties toProperties) {
if (fromProperties != null && toProperties != null) {
for (Object key : fromProperties.keySet()) {
String name = (String)key;
String value = fromProperties.getProperty(name);
if (value != null) {
toProperties.put(name, value);
}
}
}
}
/** Creates a PropertiesBuilder.
*
* @param implementationModel implementationModel
* @return a PropertiesBuilder */ | // Path: switchyard/switchyard-component-common-knowledge/src/main/java/org/switchyard/component/common/knowledge/config/model/KnowledgeComponentImplementationModel.java
// public interface KnowledgeComponentImplementationModel extends ComponentImplementationModel {
//
// /** Gets the "persistent" attribute.
// *
// * @return the "persistent" attribute */
// public boolean isPersistent();
//
// /** Sets the "persistent" attribute.
// *
// * @param persistent the "persistent" attribute
// * @return this instance (useful for chaining) */
// public KnowledgeComponentImplementationModel setPersistent(boolean persistent);
//
// /** Gets the "processId" attribute.
// *
// * @return the "processId" attribute */
// public String getProcessId();
//
// /** Sets the "processId" attribute.
// *
// * @param processId the "processId" attribute
// * @return this instance (useful for chaining) */
// public KnowledgeComponentImplementationModel setProcessId(String processId);
//
// /** Gets the child channels model.
// *
// * @return the child channels model */
// public ChannelsModel getChannels();
//
// /** Sets the child channels model.
// *
// * @param channels the child channels model
// * @return this KnowledgeComponentImplementationModel (useful for chaining) */
// public KnowledgeComponentImplementationModel setChannels(ChannelsModel channels);
//
// /** Gets the child listeners model.
// *
// * @return the child listeners model */
// public ListenersModel getListeners();
//
// /** Sets the child listeners model.
// *
// * @param listeners the child listeners model
// * @return this KnowledgeComponentImplementationModel (useful for chaining) */
// public KnowledgeComponentImplementationModel setListeners(ListenersModel listeners);
//
// /** Gets the child loggers model.
// *
// * @return the child loggers model */
// public LoggersModel getLoggers();
//
// /** Sets the child loggers model.
// *
// * @param loggers the child loggers model
// * @return this KnowledgeComponentImplementationModel (useful for chaining) */
// public KnowledgeComponentImplementationModel setLoggers(LoggersModel loggers);
//
// /** Gets the child manifest model.
// *
// * @return the child manifest model */
// public ManifestModel getManifest();
//
// /** Sets the child manifest model.
// *
// * @param manifest the child manifest model
// * @return this KnowledgeComponentImplementationModel (useful for chaining) */
// public KnowledgeComponentImplementationModel setManifest(ManifestModel manifest);
//
// /** Gets the child operations model.
// *
// * @return the child operations model */
// public OperationsModel getOperations();
//
// /** Sets the child operations model.
// *
// * @param operations the child operations model
// * @return this KnowledgeComponentImplementationModel (useful for chaining) */
// public KnowledgeComponentImplementationModel setOperations(OperationsModel operations);
//
// /** Gets the child properties model.
// *
// * @return the child properties model */
// public PropertiesModel getProperties();
//
// /** Sets the child properties model.
// *
// * @param properties the child properties model
// * @return this KnowledgeComponentImplementationModel (useful for chaining) */
// public KnowledgeComponentImplementationModel setProperties(PropertiesModel properties);
//
// /** Gets the child userGroupCallback model.
// *
// * @return the child userGroupCallback model */
// public UserGroupCallbackModel getUserGroupCallback();
//
// /** Sets the child userGroupCallback model.
// *
// * @param userGroupCallback the child userGroupCallback model
// * @return this instance (useful for chaining) */
// public KnowledgeComponentImplementationModel setUserGroupCallback(UserGroupCallbackModel userGroupCallback);
//
// /** Gets the child workItemHandlers model.
// *
// * @return the child workItemHandlers model */
// public WorkItemHandlersModel getWorkItemHandlers();
//
// /** Sets the child workItemHandlers model.
// *
// * @param workItemHandlers the child workItemHandlers model
// * @return this instance (useful for chaining) */
// public KnowledgeComponentImplementationModel setWorkItemHandlers(WorkItemHandlersModel workItemHandlers);
//
// }
// Path: switchyard/switchyard-component-common-knowledge/src/main/java/org/switchyard/component/common/knowledge/config/builder/PropertiesBuilder.java
import org.switchyard.component.common.knowledge.config.model.KnowledgeComponentImplementationModel;
import org.switchyard.config.model.property.PropertiesModel;
import java.util.Properties;
return this;
}
/** Builds a Properties.
*
* @return a Properties */
public Properties build() {
Properties buildProperties = new Properties();
merge(_defaultProperties, buildProperties);
merge(_modelProperties, buildProperties);
merge(_overrideProperties, buildProperties);
return buildProperties;
}
private void merge(Properties fromProperties, Properties toProperties) {
if (fromProperties != null && toProperties != null) {
for (Object key : fromProperties.keySet()) {
String name = (String)key;
String value = fromProperties.getProperty(name);
if (value != null) {
toProperties.put(name, value);
}
}
}
}
/** Creates a PropertiesBuilder.
*
* @param implementationModel implementationModel
* @return a PropertiesBuilder */ | public static PropertiesBuilder builder(KnowledgeComponentImplementationModel implementationModel) { |
jboss-integration/fuse-bxms-integ | quickstarts/switchyard-bpm-service/src/test/java/org/switchyard/quickstarts/bpm/service/ProcessOrderTest.java | // Path: quickstarts/switchyard-bpm-service/src/main/java/org/switchyard/quickstarts/bpm/service/data/Order.java
// @XmlAccessorType(XmlAccessType.FIELD)
// @XmlType(name = "", propOrder = { "orderId", "itemId", "quantity" })
// @XmlRootElement(name = "submitOrder")
// public class Order {
//
// /** The order id. */
// @XmlElement(required = true)
// private String orderId;
//
// /** The item id. */
// @XmlElement(required = true)
// private String itemId;
//
// /** The quantity. */
// private int quantity;
//
// /**
// * Gets the value of the orderId property.
// *
// * @return possible object is {@link String }
// *
// */
// public String getOrderId() {
// return orderId;
// }
//
// /**
// * Sets the value of the orderId property.
// *
// * @param value allowed object is {@link String }
// *
// */
// public void setOrderId(String value) {
// this.orderId = value;
// }
//
// /**
// * Gets the value of the itemId property.
// *
// * @return possible object is {@link String }
// *
// */
// public String getItemId() {
// return itemId;
// }
//
// /**
// * Sets the value of the itemId property.
// *
// * @param value allowed object is {@link String }
// *
// */
// public void setItemId(String value) {
// this.itemId = value;
// }
//
// /**
// * Gets the value of the quantity property.
// *
// * @return the quantity
// */
// public int getQuantity() {
// return quantity;
// }
//
// /**
// * Sets the value of the quantity property.
// *
// * @param value the new quantity
// */
// public void setQuantity(int value) {
// this.quantity = value;
// }
//
// }
| import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.switchyard.quickstarts.bpm.service.data.Order;
import org.switchyard.quickstarts.bpm.service.data.OrderAck;
import org.switchyard.test.BeforeDeploy;
import org.switchyard.test.Invoker;
import org.switchyard.test.ServiceOperation;
import org.switchyard.test.SwitchYardRunner;
import org.switchyard.test.SwitchYardTestCaseConfig;
import org.switchyard.component.test.mixins.cdi.CDIMixIn; | /*
* JBoss, Home of Professional Open Source
* Copyright 2013, Red Hat, Inc. and/or its affiliates, and individual
* contributors by the @authors tag. See the copyright.txt in the
* distribution for a full listing of individual contributors.
*
* 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 org.switchyard.quickstarts.bpm.service;
/**
* The Class ProcessOrderTest.
*/
@RunWith(SwitchYardRunner.class)
@SwitchYardTestCaseConfig(mixins = CDIMixIn.class, config = SwitchYardTestCaseConfig.SWITCHYARD_XML)
public class ProcessOrderTest {
/** The service. */
@ServiceOperation("ProcessOrder.submitOrder")
private Invoker service;
/**
* Sets the properties.
*/
@BeforeDeploy
public void setProperties() {
System.setProperty("org.switchyard.component.http.standalone.port", "18001");
}
/**
* Order shipped.
*/
@Test
public void orderShipped() { | // Path: quickstarts/switchyard-bpm-service/src/main/java/org/switchyard/quickstarts/bpm/service/data/Order.java
// @XmlAccessorType(XmlAccessType.FIELD)
// @XmlType(name = "", propOrder = { "orderId", "itemId", "quantity" })
// @XmlRootElement(name = "submitOrder")
// public class Order {
//
// /** The order id. */
// @XmlElement(required = true)
// private String orderId;
//
// /** The item id. */
// @XmlElement(required = true)
// private String itemId;
//
// /** The quantity. */
// private int quantity;
//
// /**
// * Gets the value of the orderId property.
// *
// * @return possible object is {@link String }
// *
// */
// public String getOrderId() {
// return orderId;
// }
//
// /**
// * Sets the value of the orderId property.
// *
// * @param value allowed object is {@link String }
// *
// */
// public void setOrderId(String value) {
// this.orderId = value;
// }
//
// /**
// * Gets the value of the itemId property.
// *
// * @return possible object is {@link String }
// *
// */
// public String getItemId() {
// return itemId;
// }
//
// /**
// * Sets the value of the itemId property.
// *
// * @param value allowed object is {@link String }
// *
// */
// public void setItemId(String value) {
// this.itemId = value;
// }
//
// /**
// * Gets the value of the quantity property.
// *
// * @return the quantity
// */
// public int getQuantity() {
// return quantity;
// }
//
// /**
// * Sets the value of the quantity property.
// *
// * @param value the new quantity
// */
// public void setQuantity(int value) {
// this.quantity = value;
// }
//
// }
// Path: quickstarts/switchyard-bpm-service/src/test/java/org/switchyard/quickstarts/bpm/service/ProcessOrderTest.java
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.switchyard.quickstarts.bpm.service.data.Order;
import org.switchyard.quickstarts.bpm.service.data.OrderAck;
import org.switchyard.test.BeforeDeploy;
import org.switchyard.test.Invoker;
import org.switchyard.test.ServiceOperation;
import org.switchyard.test.SwitchYardRunner;
import org.switchyard.test.SwitchYardTestCaseConfig;
import org.switchyard.component.test.mixins.cdi.CDIMixIn;
/*
* JBoss, Home of Professional Open Source
* Copyright 2013, Red Hat, Inc. and/or its affiliates, and individual
* contributors by the @authors tag. See the copyright.txt in the
* distribution for a full listing of individual contributors.
*
* 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 org.switchyard.quickstarts.bpm.service;
/**
* The Class ProcessOrderTest.
*/
@RunWith(SwitchYardRunner.class)
@SwitchYardTestCaseConfig(mixins = CDIMixIn.class, config = SwitchYardTestCaseConfig.SWITCHYARD_XML)
public class ProcessOrderTest {
/** The service. */
@ServiceOperation("ProcessOrder.submitOrder")
private Invoker service;
/**
* Sets the properties.
*/
@BeforeDeploy
public void setProperties() {
System.setProperty("org.switchyard.component.http.standalone.port", "18001");
}
/**
* Order shipped.
*/
@Test
public void orderShipped() { | Order order = new Order(); |
jboss-integration/fuse-bxms-integ | switchyard/switchyard-component-common-knowledge/src/main/java/org/switchyard/component/common/knowledge/config/model/v2/V2RemoteJmsModel.java | // Path: switchyard/switchyard-component-common-knowledge/src/main/java/org/switchyard/component/common/knowledge/config/model/RemoteModel.java
// public interface RemoteModel extends Model {
//
// /** Gets the deploymentId attribute.
// *
// * @return the deploymentId attribute */
// public String getDeploymentId();
//
// /** Sets the deploymentId attribute.
// *
// * @param deploymentId the deploymentId attribute
// * @return this RemoteModel (useful for chaining) */
// public RemoteModel setDeploymentId(String deploymentId);
//
// /** Gets the userName attribute.
// *
// * @return the userName attribute */
// public String getUserName();
//
// /** Sets the userName attribute.
// *
// * @param userName the userName attribute
// * @return this RemoteModel (useful for chaining) */
// public RemoteModel setUserName(String userName);
//
// /** Gets the password attribute.
// *
// * @return the password attribute */
// public String getPassword();
//
// /** Sets the password attribute.
// *
// * @param password the password attribute
// * @return this RemoteModel (useful for chaining) */
// public RemoteModel setPassword(String password);
//
// /** Gets the timeout attribute.
// *
// * @return the timeout attribute */
// public Integer getTimeout();
//
// /** Sets the timeout attribute.
// *
// * @param timeout the timeout attribute
// * @return this RemoteModel (useful for chaining) */
// public RemoteModel setTimeout(Integer timeout);
//
// /** Gets the child extraJaxbClasses model.
// *
// * @return the child extraJaxbClasses model */
// public ExtraJaxbClassesModel getExtraJaxbClasses();
//
// /** Sets the child extraJaxbClasses model.
// *
// * @param extraJaxbClasses the child extraJaxbClasses model
// * @return this RemoteModel (useful for chaining) */
// public RemoteModel setExtraJaxbClasses(ExtraJaxbClassesModel extraJaxbClasses);
//
// }
| import org.switchyard.config.Configuration;
import org.switchyard.config.model.Descriptor;
import org.switchyard.component.common.knowledge.config.model.RemoteJmsModel;
import org.switchyard.component.common.knowledge.config.model.RemoteModel; | /*
* Copyright 2014 Red Hat Inc. and/or its affiliates and other contributors.
* 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 org.switchyard.component.common.knowledge.config.model.v2;
/** The 2nd version RemoteJmsModel.
*
* @author David Ward <<a href="mailto:dward@jboss.org">dward@jboss.org</a>> © 2014 Red Hat Inc. */
public class V2RemoteJmsModel extends V2RemoteModel implements RemoteJmsModel {
/** Constructs a new V2JmsRemoteModel of the specified namespace.
*
* @param namespace the namespace */
public V2RemoteJmsModel(String namespace) {
super(namespace, REMOTE_JMS);
}
/** Constructs a new V2RemoteJmsModel with the specified Configuration and Descriptor.
*
* @param config the Configuration
* @param desc the Descriptor */
public V2RemoteJmsModel(Configuration config, Descriptor desc) {
super(config, desc);
}
/** {@inheritDoc} */
@Override
public String getHostName() {
return getModelAttribute("hostName");
}
/** {@inheritDoc} */
@Override
public RemoteJmsModel setHostName(String hostName) {
setModelAttribute("hostName", hostName);
return this;
}
/** {@inheritDoc} */
@Override
public Integer getRemotingPort() {
String rp = getModelAttribute("remotingPort");
return rp != null ? Integer.valueOf(rp) : null;
}
/** {@inheritDoc} */
@Override | // Path: switchyard/switchyard-component-common-knowledge/src/main/java/org/switchyard/component/common/knowledge/config/model/RemoteModel.java
// public interface RemoteModel extends Model {
//
// /** Gets the deploymentId attribute.
// *
// * @return the deploymentId attribute */
// public String getDeploymentId();
//
// /** Sets the deploymentId attribute.
// *
// * @param deploymentId the deploymentId attribute
// * @return this RemoteModel (useful for chaining) */
// public RemoteModel setDeploymentId(String deploymentId);
//
// /** Gets the userName attribute.
// *
// * @return the userName attribute */
// public String getUserName();
//
// /** Sets the userName attribute.
// *
// * @param userName the userName attribute
// * @return this RemoteModel (useful for chaining) */
// public RemoteModel setUserName(String userName);
//
// /** Gets the password attribute.
// *
// * @return the password attribute */
// public String getPassword();
//
// /** Sets the password attribute.
// *
// * @param password the password attribute
// * @return this RemoteModel (useful for chaining) */
// public RemoteModel setPassword(String password);
//
// /** Gets the timeout attribute.
// *
// * @return the timeout attribute */
// public Integer getTimeout();
//
// /** Sets the timeout attribute.
// *
// * @param timeout the timeout attribute
// * @return this RemoteModel (useful for chaining) */
// public RemoteModel setTimeout(Integer timeout);
//
// /** Gets the child extraJaxbClasses model.
// *
// * @return the child extraJaxbClasses model */
// public ExtraJaxbClassesModel getExtraJaxbClasses();
//
// /** Sets the child extraJaxbClasses model.
// *
// * @param extraJaxbClasses the child extraJaxbClasses model
// * @return this RemoteModel (useful for chaining) */
// public RemoteModel setExtraJaxbClasses(ExtraJaxbClassesModel extraJaxbClasses);
//
// }
// Path: switchyard/switchyard-component-common-knowledge/src/main/java/org/switchyard/component/common/knowledge/config/model/v2/V2RemoteJmsModel.java
import org.switchyard.config.Configuration;
import org.switchyard.config.model.Descriptor;
import org.switchyard.component.common.knowledge.config.model.RemoteJmsModel;
import org.switchyard.component.common.knowledge.config.model.RemoteModel;
/*
* Copyright 2014 Red Hat Inc. and/or its affiliates and other contributors.
* 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 org.switchyard.component.common.knowledge.config.model.v2;
/** The 2nd version RemoteJmsModel.
*
* @author David Ward <<a href="mailto:dward@jboss.org">dward@jboss.org</a>> © 2014 Red Hat Inc. */
public class V2RemoteJmsModel extends V2RemoteModel implements RemoteJmsModel {
/** Constructs a new V2JmsRemoteModel of the specified namespace.
*
* @param namespace the namespace */
public V2RemoteJmsModel(String namespace) {
super(namespace, REMOTE_JMS);
}
/** Constructs a new V2RemoteJmsModel with the specified Configuration and Descriptor.
*
* @param config the Configuration
* @param desc the Descriptor */
public V2RemoteJmsModel(Configuration config, Descriptor desc) {
super(config, desc);
}
/** {@inheritDoc} */
@Override
public String getHostName() {
return getModelAttribute("hostName");
}
/** {@inheritDoc} */
@Override
public RemoteJmsModel setHostName(String hostName) {
setModelAttribute("hostName", hostName);
return this;
}
/** {@inheritDoc} */
@Override
public Integer getRemotingPort() {
String rp = getModelAttribute("remotingPort");
return rp != null ? Integer.valueOf(rp) : null;
}
/** {@inheritDoc} */
@Override | public RemoteModel setRemotingPort(Integer remotingPort) { |
jboss-integration/fuse-bxms-integ | camel/kie-camel/src/test/java/org/kie/camel/component/XStreamBatchExecutionTest.java | // Path: camel/kie-camel/src/test/java/org/kie/camel/testdomain/TestVariable.java
// @Ignore
// @XmlRootElement
// public class TestVariable {
//
// private String name;
//
// public TestVariable() {
//
// }
//
// public TestVariable(String name) {
// this.name = name;
// }
//
// public String getName() {
// return name;
// }
//
// public void setName(String name) {
// this.name = name;
// }
//
// }
| import com.thoughtworks.xstream.XStream;
import org.apache.camel.builder.RouteBuilder;
import org.apache.camel.test.junit4.CamelTestSupport;
import org.custommonkey.xmlunit.Diff;
import org.custommonkey.xmlunit.XMLAssert;
import org.custommonkey.xmlunit.XMLUnit;
import org.custommonkey.xmlunit.examples.RecursiveElementNameAndTextQualifier;
import org.drools.core.command.impl.CommandBasedStatefulKnowledgeSession;
import org.drools.core.command.runtime.rule.ModifyCommand;
import org.drools.core.common.InternalFactHandle;
import org.drools.core.impl.InternalKnowledgeBase;
import org.drools.core.impl.StatefulKnowledgeSessionImpl;
import org.drools.core.impl.StatelessKnowledgeSessionImpl;
import org.drools.core.runtime.help.impl.XStreamXML;
import org.jbpm.process.core.context.variable.VariableScope;
import org.jbpm.process.instance.context.variable.VariableScopeInstance;
import org.junit.Before;
import org.junit.Ignore;
import org.junit.Test;
import org.kie.api.KieServices;
import org.kie.api.builder.KieBuilder;
import org.kie.api.builder.KieFileSystem;
import org.kie.api.builder.Message;
import org.kie.api.io.Resource;
import org.kie.api.io.ResourceType;
import org.kie.api.runtime.CommandExecutor;
import org.kie.api.runtime.ExecutionResults;
import org.kie.api.runtime.KieSession;
import org.kie.api.runtime.StatelessKieSession;
import org.kie.api.runtime.process.ProcessInstance;
import org.kie.api.runtime.process.WorkItem;
import org.kie.api.runtime.process.WorkItemHandler;
import org.kie.api.runtime.process.WorkItemManager;
import org.kie.api.runtime.process.WorkflowProcessInstance;
import org.kie.api.runtime.rule.FactHandle;
import org.kie.api.runtime.rule.QueryResultsRow;
import org.kie.camel.component.cxf.CxfRestTest;
import org.kie.camel.testdomain.Cheese;
import org.kie.camel.testdomain.Person;
import org.kie.camel.testdomain.TestVariable;
import org.kie.internal.io.ResourceFactory;
import org.kie.internal.runtime.helper.BatchExecutionHelper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.xml.sax.SAXException;
import javax.naming.Context;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set; | Set expectedList = new HashSet();
expectedList.add(stilton25);
expectedList.add(stilton30);
assertEquals(expectedList, new HashSet(list));
// brie should not have changed
Cheese brie10 = new Cheese("brie", 10);
brie10.setOldPrice(5);
assertEquals(brie10, result.getValue("outBrie"));
}
@Test
public void testProcess() throws SAXException, IOException {
String str = "";
str += "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n";
str += "<process xmlns=\"http://drools.org/drools-5.0/process\"\n";
str += " xmlns:xs=\"http://www.w3.org/2001/XMLSchema-instance\"\n";
str += " xs:schemaLocation=\"http://drools.org/drools-5.0/process drools-processes-5.0.xsd\"\n";
str += " type=\"RuleFlow\" name=\"flow\" id=\"org.drools.actions\" package-name=\"org.drools\" version=\"1\" >\n";
str += "\n";
str += " <header>\n";
str += " <imports>\n";
str += " <import name=\"org.kie.camel.testdomain.TestVariable\" />\n";
str += " </imports>\n";
str += " <globals>\n";
str += " <global identifier=\"list\" type=\"java.util.List\" />\n";
str += " </globals>\n";
str += " <variables>\n";
str += " <variable name=\"person\" >\n"; | // Path: camel/kie-camel/src/test/java/org/kie/camel/testdomain/TestVariable.java
// @Ignore
// @XmlRootElement
// public class TestVariable {
//
// private String name;
//
// public TestVariable() {
//
// }
//
// public TestVariable(String name) {
// this.name = name;
// }
//
// public String getName() {
// return name;
// }
//
// public void setName(String name) {
// this.name = name;
// }
//
// }
// Path: camel/kie-camel/src/test/java/org/kie/camel/component/XStreamBatchExecutionTest.java
import com.thoughtworks.xstream.XStream;
import org.apache.camel.builder.RouteBuilder;
import org.apache.camel.test.junit4.CamelTestSupport;
import org.custommonkey.xmlunit.Diff;
import org.custommonkey.xmlunit.XMLAssert;
import org.custommonkey.xmlunit.XMLUnit;
import org.custommonkey.xmlunit.examples.RecursiveElementNameAndTextQualifier;
import org.drools.core.command.impl.CommandBasedStatefulKnowledgeSession;
import org.drools.core.command.runtime.rule.ModifyCommand;
import org.drools.core.common.InternalFactHandle;
import org.drools.core.impl.InternalKnowledgeBase;
import org.drools.core.impl.StatefulKnowledgeSessionImpl;
import org.drools.core.impl.StatelessKnowledgeSessionImpl;
import org.drools.core.runtime.help.impl.XStreamXML;
import org.jbpm.process.core.context.variable.VariableScope;
import org.jbpm.process.instance.context.variable.VariableScopeInstance;
import org.junit.Before;
import org.junit.Ignore;
import org.junit.Test;
import org.kie.api.KieServices;
import org.kie.api.builder.KieBuilder;
import org.kie.api.builder.KieFileSystem;
import org.kie.api.builder.Message;
import org.kie.api.io.Resource;
import org.kie.api.io.ResourceType;
import org.kie.api.runtime.CommandExecutor;
import org.kie.api.runtime.ExecutionResults;
import org.kie.api.runtime.KieSession;
import org.kie.api.runtime.StatelessKieSession;
import org.kie.api.runtime.process.ProcessInstance;
import org.kie.api.runtime.process.WorkItem;
import org.kie.api.runtime.process.WorkItemHandler;
import org.kie.api.runtime.process.WorkItemManager;
import org.kie.api.runtime.process.WorkflowProcessInstance;
import org.kie.api.runtime.rule.FactHandle;
import org.kie.api.runtime.rule.QueryResultsRow;
import org.kie.camel.component.cxf.CxfRestTest;
import org.kie.camel.testdomain.Cheese;
import org.kie.camel.testdomain.Person;
import org.kie.camel.testdomain.TestVariable;
import org.kie.internal.io.ResourceFactory;
import org.kie.internal.runtime.helper.BatchExecutionHelper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.xml.sax.SAXException;
import javax.naming.Context;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
Set expectedList = new HashSet();
expectedList.add(stilton25);
expectedList.add(stilton30);
assertEquals(expectedList, new HashSet(list));
// brie should not have changed
Cheese brie10 = new Cheese("brie", 10);
brie10.setOldPrice(5);
assertEquals(brie10, result.getValue("outBrie"));
}
@Test
public void testProcess() throws SAXException, IOException {
String str = "";
str += "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n";
str += "<process xmlns=\"http://drools.org/drools-5.0/process\"\n";
str += " xmlns:xs=\"http://www.w3.org/2001/XMLSchema-instance\"\n";
str += " xs:schemaLocation=\"http://drools.org/drools-5.0/process drools-processes-5.0.xsd\"\n";
str += " type=\"RuleFlow\" name=\"flow\" id=\"org.drools.actions\" package-name=\"org.drools\" version=\"1\" >\n";
str += "\n";
str += " <header>\n";
str += " <imports>\n";
str += " <import name=\"org.kie.camel.testdomain.TestVariable\" />\n";
str += " </imports>\n";
str += " <globals>\n";
str += " <global identifier=\"list\" type=\"java.util.List\" />\n";
str += " </globals>\n";
str += " <variables>\n";
str += " <variable name=\"person\" >\n"; | str += " <type name=\"org.drools.core.process.core.datatype.impl.type.ObjectDataType\" className=\"TestVariable\" />\n"; |
fabioz/eclipse.spellchecker | src/eclipse/spellchecker/engine/PersistentSpellDictionary.java | // Path: src/eclipse/spellchecker/Activator.java
// public class Activator extends AbstractUIPlugin {
//
// public static final String ID_PLUGIN = "eclipse.spellchecker";
// private static Activator plugin; // The shared instance.
//
// /**
// * The constructor.
// */
// public Activator() {
// super();
// plugin = this;
// }
//
// @Override
// public void start(BundleContext context) throws Exception {
// super.start(context);
// }
//
// /**
// * This is called when the plugin is being stopped.
// *
// * @see org.osgi.framework.BundleActivator#stop(org.osgi.framework.BundleContext)
// */
// @Override
// public void stop(BundleContext context) throws Exception {
// try {
// if (fDialogsFormToolkit != null) {
// fDialogsFormToolkit.dispose();
// fDialogsFormToolkit = null;
// }
//
// } finally {
// super.stop(context);
// }
// }
//
// public static Activator getDefault() {
// return plugin;
// }
//
// public static void logErrorMessage(String message) {
// IStatus s = new Status(IStatus.ERROR, ID_PLUGIN, message);
// plugin.getLog().log(s);
// }
//
// public static IWorkbenchWindow getActiveWorkbenchWindow() {
// return getDefault().getWorkbench().getActiveWorkbenchWindow();
// }
//
// public static Shell getActiveWorkbenchShell() {
// IWorkbenchWindow window = getActiveWorkbenchWindow();
// if (window != null) {
// return window.getShell();
// }
// return null;
// }
//
// public static void log(Exception ex) {
// IStatus s = new Status(IStatus.ERROR, ID_PLUGIN, ex.getMessage(), ex);
// plugin.getLog().log(s);
// }
//
// public static void log(IStatus status) {
// plugin.getLog().log(status);
// }
//
// private FormToolkit fDialogsFormToolkit;
//
// public FormToolkit getDialogsFormToolkit() {
// if (fDialogsFormToolkit == null) {
// FormColors colors = new FormColors(Display.getCurrent());
// colors.setBackground(null);
// colors.setForeground(null);
// fDialogsFormToolkit = new FormToolkit(colors);
// }
// return fDialogsFormToolkit;
// }
//
// public static IWorkspace getWorkspace() {
// return ResourcesPlugin.getWorkspace();
// }
//
// }
| import java.io.FileOutputStream;
import java.io.IOException;
import java.net.URL;
import java.nio.ByteBuffer;
import java.nio.charset.Charset;
import eclipse.spellchecker.Activator; | /*
* @see eclipse.spellchecker.engine.ISpellDictionary#addWord(java.lang.String)
*/
@Override
public void addWord(final String word) {
if (isCorrect(word))
return;
FileOutputStream fileStream= null;
try {
Charset charset= Charset.forName(getEncoding());
ByteBuffer byteBuffer= charset.encode(word + "\n"); //$NON-NLS-1$
int size= byteBuffer.limit();
final byte[] byteArray;
if (byteBuffer.hasArray())
byteArray= byteBuffer.array();
else {
byteArray= new byte[size];
byteBuffer.get(byteArray);
}
fileStream= new FileOutputStream(fLocation.getPath(), true);
// Encoding UTF-16 charset writes a BOM. In which case we need to cut it away if the file isn't empty
int bomCutSize= 0;
if (!isEmpty() && "UTF-16".equals(charset.name())) //$NON-NLS-1$
bomCutSize= 2;
fileStream.write(byteArray, bomCutSize, size - bomCutSize);
} catch (IOException exception) { | // Path: src/eclipse/spellchecker/Activator.java
// public class Activator extends AbstractUIPlugin {
//
// public static final String ID_PLUGIN = "eclipse.spellchecker";
// private static Activator plugin; // The shared instance.
//
// /**
// * The constructor.
// */
// public Activator() {
// super();
// plugin = this;
// }
//
// @Override
// public void start(BundleContext context) throws Exception {
// super.start(context);
// }
//
// /**
// * This is called when the plugin is being stopped.
// *
// * @see org.osgi.framework.BundleActivator#stop(org.osgi.framework.BundleContext)
// */
// @Override
// public void stop(BundleContext context) throws Exception {
// try {
// if (fDialogsFormToolkit != null) {
// fDialogsFormToolkit.dispose();
// fDialogsFormToolkit = null;
// }
//
// } finally {
// super.stop(context);
// }
// }
//
// public static Activator getDefault() {
// return plugin;
// }
//
// public static void logErrorMessage(String message) {
// IStatus s = new Status(IStatus.ERROR, ID_PLUGIN, message);
// plugin.getLog().log(s);
// }
//
// public static IWorkbenchWindow getActiveWorkbenchWindow() {
// return getDefault().getWorkbench().getActiveWorkbenchWindow();
// }
//
// public static Shell getActiveWorkbenchShell() {
// IWorkbenchWindow window = getActiveWorkbenchWindow();
// if (window != null) {
// return window.getShell();
// }
// return null;
// }
//
// public static void log(Exception ex) {
// IStatus s = new Status(IStatus.ERROR, ID_PLUGIN, ex.getMessage(), ex);
// plugin.getLog().log(s);
// }
//
// public static void log(IStatus status) {
// plugin.getLog().log(status);
// }
//
// private FormToolkit fDialogsFormToolkit;
//
// public FormToolkit getDialogsFormToolkit() {
// if (fDialogsFormToolkit == null) {
// FormColors colors = new FormColors(Display.getCurrent());
// colors.setBackground(null);
// colors.setForeground(null);
// fDialogsFormToolkit = new FormToolkit(colors);
// }
// return fDialogsFormToolkit;
// }
//
// public static IWorkspace getWorkspace() {
// return ResourcesPlugin.getWorkspace();
// }
//
// }
// Path: src/eclipse/spellchecker/engine/PersistentSpellDictionary.java
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.URL;
import java.nio.ByteBuffer;
import java.nio.charset.Charset;
import eclipse.spellchecker.Activator;
/*
* @see eclipse.spellchecker.engine.ISpellDictionary#addWord(java.lang.String)
*/
@Override
public void addWord(final String word) {
if (isCorrect(word))
return;
FileOutputStream fileStream= null;
try {
Charset charset= Charset.forName(getEncoding());
ByteBuffer byteBuffer= charset.encode(word + "\n"); //$NON-NLS-1$
int size= byteBuffer.limit();
final byte[] byteArray;
if (byteBuffer.hasArray())
byteArray= byteBuffer.array();
else {
byteArray= new byte[size];
byteBuffer.get(byteArray);
}
fileStream= new FileOutputStream(fLocation.getPath(), true);
// Encoding UTF-16 charset writes a BOM. In which case we need to cut it away if the file isn't empty
int bomCutSize= 0;
if (!isEmpty() && "UTF-16".equals(charset.name())) //$NON-NLS-1$
bomCutSize= 2;
fileStream.write(byteArray, bomCutSize, size - bomCutSize);
} catch (IOException exception) { | Activator.log(exception); |
fabioz/eclipse.spellchecker | src/eclipse/spellchecker/TextSpellingEngine.java | // Path: src/eclipse/spellchecker/engine/ISpellChecker.java
// public interface ISpellChecker {
//
// /**
// * Adds a dictionary to the list of active dictionaries.
// *
// * @param dictionary
// * The dictionary to add
// */
// void addDictionary(ISpellDictionary dictionary);
//
// /**
// * Returns whether this spell checker accepts word additions.
// *
// * @return <code>true</code> if word additions are accepted, <code>false</code> otherwise
// */
// boolean acceptsWords();
//
// /**
// * Adds the specified word to the set of correct words.
// *
// * @param word
// * The word to add to the set of correct words
// */
// void addWord(String word);
//
// /**
// * Checks the specified word until calling <code>ignoreWord(String)</code>.
// *
// * @param word
// * The word to check
// */
// void checkWord(String word);
//
// /**
// * Checks the spelling with the spell check iterator. Implementations must
// * be thread safe as this may be called inside a reconciler thread.
// *
// * @param listener the spell event listener
// * @param iterator the iterator to use for spell checking
// */
// void execute(ISpellEventListener listener, ISpellCheckIterator iterator);
//
// /**
// * Returns the ranked proposals for a word.
// *
// * @param word
// * The word to retrieve the proposals for
// * @param sentence
// * <code>true</code> iff the proposals should start a
// * sentence, <code>false</code> otherwise
// * @return Set of ranked proposals for the word
// */
// Set<RankedWordProposal> getProposals(String word, boolean sentence);
//
// /**
// * Ignores the specified word until calling <code>checkWord(String)</code>.
// *
// * @param word
// * The word to ignore
// */
// void ignoreWord(String word);
//
// /**
// * Is the specified word correctly spelled? Implementations must be thread
// * safe as this may be called from within a reconciler thread.
// *
// * @param word
// * The word to check its spelling
// * @return <code>true</code> iff the word is correctly spelled, <code>false</code>
// * otherwise
// */
// boolean isCorrect(String word);
//
// /**
// * Remove a dictionary from the list of active dictionaries.
// *
// * @param dictionary
// * The dictionary to remove
// */
// void removeDictionary(ISpellDictionary dictionary);
//
// /**
// * Returns the current locale of the spell check engine.
// *
// * @return The current locale of the engine
// * @since 3.3
// */
// Locale getLocale();
// }
| import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.jface.text.IDocument;
import org.eclipse.jface.text.IRegion;
import org.eclipse.ui.texteditor.spelling.ISpellingProblemCollector;
import eclipse.spellchecker.engine.ISpellChecker; | /*******************************************************************************
* Copyright (c) 2000, 2011 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*******************************************************************************/
package eclipse.spellchecker;
/**
* Text spelling engine
*
* @since 3.1
*/
public class TextSpellingEngine extends SpellingEngine {
/*
* @see eclipse.spellchecker.SpellingEngine#check(org.eclipse.jface.text.IDocument, org.eclipse.jface.text.IRegion[], eclipse.spellchecker.engine.ISpellChecker, org.eclipse.ui.texteditor.spelling.ISpellingProblemCollector, org.eclipse.core.runtime.IProgressMonitor)
*/
@Override | // Path: src/eclipse/spellchecker/engine/ISpellChecker.java
// public interface ISpellChecker {
//
// /**
// * Adds a dictionary to the list of active dictionaries.
// *
// * @param dictionary
// * The dictionary to add
// */
// void addDictionary(ISpellDictionary dictionary);
//
// /**
// * Returns whether this spell checker accepts word additions.
// *
// * @return <code>true</code> if word additions are accepted, <code>false</code> otherwise
// */
// boolean acceptsWords();
//
// /**
// * Adds the specified word to the set of correct words.
// *
// * @param word
// * The word to add to the set of correct words
// */
// void addWord(String word);
//
// /**
// * Checks the specified word until calling <code>ignoreWord(String)</code>.
// *
// * @param word
// * The word to check
// */
// void checkWord(String word);
//
// /**
// * Checks the spelling with the spell check iterator. Implementations must
// * be thread safe as this may be called inside a reconciler thread.
// *
// * @param listener the spell event listener
// * @param iterator the iterator to use for spell checking
// */
// void execute(ISpellEventListener listener, ISpellCheckIterator iterator);
//
// /**
// * Returns the ranked proposals for a word.
// *
// * @param word
// * The word to retrieve the proposals for
// * @param sentence
// * <code>true</code> iff the proposals should start a
// * sentence, <code>false</code> otherwise
// * @return Set of ranked proposals for the word
// */
// Set<RankedWordProposal> getProposals(String word, boolean sentence);
//
// /**
// * Ignores the specified word until calling <code>checkWord(String)</code>.
// *
// * @param word
// * The word to ignore
// */
// void ignoreWord(String word);
//
// /**
// * Is the specified word correctly spelled? Implementations must be thread
// * safe as this may be called from within a reconciler thread.
// *
// * @param word
// * The word to check its spelling
// * @return <code>true</code> iff the word is correctly spelled, <code>false</code>
// * otherwise
// */
// boolean isCorrect(String word);
//
// /**
// * Remove a dictionary from the list of active dictionaries.
// *
// * @param dictionary
// * The dictionary to remove
// */
// void removeDictionary(ISpellDictionary dictionary);
//
// /**
// * Returns the current locale of the spell check engine.
// *
// * @return The current locale of the engine
// * @since 3.3
// */
// Locale getLocale();
// }
// Path: src/eclipse/spellchecker/TextSpellingEngine.java
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.jface.text.IDocument;
import org.eclipse.jface.text.IRegion;
import org.eclipse.ui.texteditor.spelling.ISpellingProblemCollector;
import eclipse.spellchecker.engine.ISpellChecker;
/*******************************************************************************
* Copyright (c) 2000, 2011 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*******************************************************************************/
package eclipse.spellchecker;
/**
* Text spelling engine
*
* @since 3.1
*/
public class TextSpellingEngine extends SpellingEngine {
/*
* @see eclipse.spellchecker.SpellingEngine#check(org.eclipse.jface.text.IDocument, org.eclipse.jface.text.IRegion[], eclipse.spellchecker.engine.ISpellChecker, org.eclipse.ui.texteditor.spelling.ISpellingProblemCollector, org.eclipse.core.runtime.IProgressMonitor)
*/
@Override | protected void check(IDocument document, IRegion[] regions, ISpellChecker checker, ISpellingProblemCollector collector, IProgressMonitor monitor) { |
fabioz/eclipse.spellchecker | src/eclipse/spellchecker/preferences/ScrolledPageContent.java | // Path: src/eclipse/spellchecker/Activator.java
// public class Activator extends AbstractUIPlugin {
//
// public static final String ID_PLUGIN = "eclipse.spellchecker";
// private static Activator plugin; // The shared instance.
//
// /**
// * The constructor.
// */
// public Activator() {
// super();
// plugin = this;
// }
//
// @Override
// public void start(BundleContext context) throws Exception {
// super.start(context);
// }
//
// /**
// * This is called when the plugin is being stopped.
// *
// * @see org.osgi.framework.BundleActivator#stop(org.osgi.framework.BundleContext)
// */
// @Override
// public void stop(BundleContext context) throws Exception {
// try {
// if (fDialogsFormToolkit != null) {
// fDialogsFormToolkit.dispose();
// fDialogsFormToolkit = null;
// }
//
// } finally {
// super.stop(context);
// }
// }
//
// public static Activator getDefault() {
// return plugin;
// }
//
// public static void logErrorMessage(String message) {
// IStatus s = new Status(IStatus.ERROR, ID_PLUGIN, message);
// plugin.getLog().log(s);
// }
//
// public static IWorkbenchWindow getActiveWorkbenchWindow() {
// return getDefault().getWorkbench().getActiveWorkbenchWindow();
// }
//
// public static Shell getActiveWorkbenchShell() {
// IWorkbenchWindow window = getActiveWorkbenchWindow();
// if (window != null) {
// return window.getShell();
// }
// return null;
// }
//
// public static void log(Exception ex) {
// IStatus s = new Status(IStatus.ERROR, ID_PLUGIN, ex.getMessage(), ex);
// plugin.getLog().log(s);
// }
//
// public static void log(IStatus status) {
// plugin.getLog().log(status);
// }
//
// private FormToolkit fDialogsFormToolkit;
//
// public FormToolkit getDialogsFormToolkit() {
// if (fDialogsFormToolkit == null) {
// FormColors colors = new FormColors(Display.getCurrent());
// colors.setBackground(null);
// colors.setForeground(null);
// fDialogsFormToolkit = new FormToolkit(colors);
// }
// return fDialogsFormToolkit;
// }
//
// public static IWorkspace getWorkspace() {
// return ResourcesPlugin.getWorkspace();
// }
//
// }
| import org.eclipse.swt.SWT;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
import org.eclipse.ui.forms.widgets.FormToolkit;
import org.eclipse.ui.forms.widgets.SharedScrolledComposite;
import eclipse.spellchecker.Activator; | /*******************************************************************************
* Copyright (c) 2000, 2008 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*******************************************************************************/
package eclipse.spellchecker.preferences;
public class ScrolledPageContent extends SharedScrolledComposite {
private FormToolkit fToolkit;
public ScrolledPageContent(Composite parent) {
this(parent, SWT.V_SCROLL | SWT.H_SCROLL);
}
public ScrolledPageContent(Composite parent, int style) {
super(parent, style);
setFont(parent.getFont());
| // Path: src/eclipse/spellchecker/Activator.java
// public class Activator extends AbstractUIPlugin {
//
// public static final String ID_PLUGIN = "eclipse.spellchecker";
// private static Activator plugin; // The shared instance.
//
// /**
// * The constructor.
// */
// public Activator() {
// super();
// plugin = this;
// }
//
// @Override
// public void start(BundleContext context) throws Exception {
// super.start(context);
// }
//
// /**
// * This is called when the plugin is being stopped.
// *
// * @see org.osgi.framework.BundleActivator#stop(org.osgi.framework.BundleContext)
// */
// @Override
// public void stop(BundleContext context) throws Exception {
// try {
// if (fDialogsFormToolkit != null) {
// fDialogsFormToolkit.dispose();
// fDialogsFormToolkit = null;
// }
//
// } finally {
// super.stop(context);
// }
// }
//
// public static Activator getDefault() {
// return plugin;
// }
//
// public static void logErrorMessage(String message) {
// IStatus s = new Status(IStatus.ERROR, ID_PLUGIN, message);
// plugin.getLog().log(s);
// }
//
// public static IWorkbenchWindow getActiveWorkbenchWindow() {
// return getDefault().getWorkbench().getActiveWorkbenchWindow();
// }
//
// public static Shell getActiveWorkbenchShell() {
// IWorkbenchWindow window = getActiveWorkbenchWindow();
// if (window != null) {
// return window.getShell();
// }
// return null;
// }
//
// public static void log(Exception ex) {
// IStatus s = new Status(IStatus.ERROR, ID_PLUGIN, ex.getMessage(), ex);
// plugin.getLog().log(s);
// }
//
// public static void log(IStatus status) {
// plugin.getLog().log(status);
// }
//
// private FormToolkit fDialogsFormToolkit;
//
// public FormToolkit getDialogsFormToolkit() {
// if (fDialogsFormToolkit == null) {
// FormColors colors = new FormColors(Display.getCurrent());
// colors.setBackground(null);
// colors.setForeground(null);
// fDialogsFormToolkit = new FormToolkit(colors);
// }
// return fDialogsFormToolkit;
// }
//
// public static IWorkspace getWorkspace() {
// return ResourcesPlugin.getWorkspace();
// }
//
// }
// Path: src/eclipse/spellchecker/preferences/ScrolledPageContent.java
import org.eclipse.swt.SWT;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
import org.eclipse.ui.forms.widgets.FormToolkit;
import org.eclipse.ui.forms.widgets.SharedScrolledComposite;
import eclipse.spellchecker.Activator;
/*******************************************************************************
* Copyright (c) 2000, 2008 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*******************************************************************************/
package eclipse.spellchecker.preferences;
public class ScrolledPageContent extends SharedScrolledComposite {
private FormToolkit fToolkit;
public ScrolledPageContent(Composite parent) {
this(parent, SWT.V_SCROLL | SWT.H_SCROLL);
}
public ScrolledPageContent(Composite parent, int style) {
super(parent, style);
setFont(parent.getFont());
| fToolkit= Activator.getDefault().getDialogsFormToolkit(); |
fabioz/eclipse.spellchecker | src/eclipse/spellchecker/etc/StatusInfo.java | // Path: src/eclipse/spellchecker/Activator.java
// public class Activator extends AbstractUIPlugin {
//
// public static final String ID_PLUGIN = "eclipse.spellchecker";
// private static Activator plugin; // The shared instance.
//
// /**
// * The constructor.
// */
// public Activator() {
// super();
// plugin = this;
// }
//
// @Override
// public void start(BundleContext context) throws Exception {
// super.start(context);
// }
//
// /**
// * This is called when the plugin is being stopped.
// *
// * @see org.osgi.framework.BundleActivator#stop(org.osgi.framework.BundleContext)
// */
// @Override
// public void stop(BundleContext context) throws Exception {
// try {
// if (fDialogsFormToolkit != null) {
// fDialogsFormToolkit.dispose();
// fDialogsFormToolkit = null;
// }
//
// } finally {
// super.stop(context);
// }
// }
//
// public static Activator getDefault() {
// return plugin;
// }
//
// public static void logErrorMessage(String message) {
// IStatus s = new Status(IStatus.ERROR, ID_PLUGIN, message);
// plugin.getLog().log(s);
// }
//
// public static IWorkbenchWindow getActiveWorkbenchWindow() {
// return getDefault().getWorkbench().getActiveWorkbenchWindow();
// }
//
// public static Shell getActiveWorkbenchShell() {
// IWorkbenchWindow window = getActiveWorkbenchWindow();
// if (window != null) {
// return window.getShell();
// }
// return null;
// }
//
// public static void log(Exception ex) {
// IStatus s = new Status(IStatus.ERROR, ID_PLUGIN, ex.getMessage(), ex);
// plugin.getLog().log(s);
// }
//
// public static void log(IStatus status) {
// plugin.getLog().log(status);
// }
//
// private FormToolkit fDialogsFormToolkit;
//
// public FormToolkit getDialogsFormToolkit() {
// if (fDialogsFormToolkit == null) {
// FormColors colors = new FormColors(Display.getCurrent());
// colors.setBackground(null);
// colors.setForeground(null);
// fDialogsFormToolkit = new FormToolkit(colors);
// }
// return fDialogsFormToolkit;
// }
//
// public static IWorkspace getWorkspace() {
// return ResourcesPlugin.getWorkspace();
// }
//
// }
| import org.eclipse.core.runtime.Assert;
import org.eclipse.core.runtime.IStatus;
import eclipse.spellchecker.Activator; | fStatusMessage= null;
fSeverity= IStatus.OK;
}
/*
* @see IStatus#matches(int)
*/
public boolean matches(int severityMask) {
return (fSeverity & severityMask) != 0;
}
/**
* Returns always <code>false</code>.
* @see IStatus#isMultiStatus()
*/
public boolean isMultiStatus() {
return false;
}
/*
* @see IStatus#getSeverity()
*/
public int getSeverity() {
return fSeverity;
}
/*
* @see IStatus#getPlugin()
*/
public String getPlugin() { | // Path: src/eclipse/spellchecker/Activator.java
// public class Activator extends AbstractUIPlugin {
//
// public static final String ID_PLUGIN = "eclipse.spellchecker";
// private static Activator plugin; // The shared instance.
//
// /**
// * The constructor.
// */
// public Activator() {
// super();
// plugin = this;
// }
//
// @Override
// public void start(BundleContext context) throws Exception {
// super.start(context);
// }
//
// /**
// * This is called when the plugin is being stopped.
// *
// * @see org.osgi.framework.BundleActivator#stop(org.osgi.framework.BundleContext)
// */
// @Override
// public void stop(BundleContext context) throws Exception {
// try {
// if (fDialogsFormToolkit != null) {
// fDialogsFormToolkit.dispose();
// fDialogsFormToolkit = null;
// }
//
// } finally {
// super.stop(context);
// }
// }
//
// public static Activator getDefault() {
// return plugin;
// }
//
// public static void logErrorMessage(String message) {
// IStatus s = new Status(IStatus.ERROR, ID_PLUGIN, message);
// plugin.getLog().log(s);
// }
//
// public static IWorkbenchWindow getActiveWorkbenchWindow() {
// return getDefault().getWorkbench().getActiveWorkbenchWindow();
// }
//
// public static Shell getActiveWorkbenchShell() {
// IWorkbenchWindow window = getActiveWorkbenchWindow();
// if (window != null) {
// return window.getShell();
// }
// return null;
// }
//
// public static void log(Exception ex) {
// IStatus s = new Status(IStatus.ERROR, ID_PLUGIN, ex.getMessage(), ex);
// plugin.getLog().log(s);
// }
//
// public static void log(IStatus status) {
// plugin.getLog().log(status);
// }
//
// private FormToolkit fDialogsFormToolkit;
//
// public FormToolkit getDialogsFormToolkit() {
// if (fDialogsFormToolkit == null) {
// FormColors colors = new FormColors(Display.getCurrent());
// colors.setBackground(null);
// colors.setForeground(null);
// fDialogsFormToolkit = new FormToolkit(colors);
// }
// return fDialogsFormToolkit;
// }
//
// public static IWorkspace getWorkspace() {
// return ResourcesPlugin.getWorkspace();
// }
//
// }
// Path: src/eclipse/spellchecker/etc/StatusInfo.java
import org.eclipse.core.runtime.Assert;
import org.eclipse.core.runtime.IStatus;
import eclipse.spellchecker.Activator;
fStatusMessage= null;
fSeverity= IStatus.OK;
}
/*
* @see IStatus#matches(int)
*/
public boolean matches(int severityMask) {
return (fSeverity & severityMask) != 0;
}
/**
* Returns always <code>false</code>.
* @see IStatus#isMultiStatus()
*/
public boolean isMultiStatus() {
return false;
}
/*
* @see IStatus#getSeverity()
*/
public int getSeverity() {
return fSeverity;
}
/*
* @see IStatus#getPlugin()
*/
public String getPlugin() { | return Activator.ID_PLUGIN; |
fabioz/eclipse.spellchecker | src/eclipse/spellchecker/etc/JavaPluginImages.java | // Path: src/eclipse/spellchecker/Activator.java
// public class Activator extends AbstractUIPlugin {
//
// public static final String ID_PLUGIN = "eclipse.spellchecker";
// private static Activator plugin; // The shared instance.
//
// /**
// * The constructor.
// */
// public Activator() {
// super();
// plugin = this;
// }
//
// @Override
// public void start(BundleContext context) throws Exception {
// super.start(context);
// }
//
// /**
// * This is called when the plugin is being stopped.
// *
// * @see org.osgi.framework.BundleActivator#stop(org.osgi.framework.BundleContext)
// */
// @Override
// public void stop(BundleContext context) throws Exception {
// try {
// if (fDialogsFormToolkit != null) {
// fDialogsFormToolkit.dispose();
// fDialogsFormToolkit = null;
// }
//
// } finally {
// super.stop(context);
// }
// }
//
// public static Activator getDefault() {
// return plugin;
// }
//
// public static void logErrorMessage(String message) {
// IStatus s = new Status(IStatus.ERROR, ID_PLUGIN, message);
// plugin.getLog().log(s);
// }
//
// public static IWorkbenchWindow getActiveWorkbenchWindow() {
// return getDefault().getWorkbench().getActiveWorkbenchWindow();
// }
//
// public static Shell getActiveWorkbenchShell() {
// IWorkbenchWindow window = getActiveWorkbenchWindow();
// if (window != null) {
// return window.getShell();
// }
// return null;
// }
//
// public static void log(Exception ex) {
// IStatus s = new Status(IStatus.ERROR, ID_PLUGIN, ex.getMessage(), ex);
// plugin.getLog().log(s);
// }
//
// public static void log(IStatus status) {
// plugin.getLog().log(status);
// }
//
// private FormToolkit fDialogsFormToolkit;
//
// public FormToolkit getDialogsFormToolkit() {
// if (fDialogsFormToolkit == null) {
// FormColors colors = new FormColors(Display.getCurrent());
// colors.setBackground(null);
// colors.setForeground(null);
// fDialogsFormToolkit = new FormToolkit(colors);
// }
// return fDialogsFormToolkit;
// }
//
// public static IWorkspace getWorkspace() {
// return ResourcesPlugin.getWorkspace();
// }
//
// }
| import java.net.URL;
import java.util.HashMap;
import java.util.Iterator;
import org.osgi.framework.Bundle;
import org.eclipse.swt.graphics.Image;
import org.eclipse.swt.graphics.ImageData;
import org.eclipse.core.runtime.FileLocator;
import org.eclipse.core.runtime.IPath;
import org.eclipse.core.runtime.Path;
import org.eclipse.jface.action.IAction;
import org.eclipse.jface.resource.ImageDescriptor;
import org.eclipse.jface.resource.ImageRegistry;
import eclipse.spellchecker.Activator; | //---- Helper methods to access icons on the file system --------------------------------------
private static void setImageDescriptors(IAction action, String type, String relPath) {
ImageDescriptor id= create("d" + type, relPath, false); //$NON-NLS-1$
if (id != null)
action.setDisabledImageDescriptor(id);
/*
* id= create("c" + type, relPath, false); //$NON-NLS-1$
* if (id != null)
* action.setHoverImageDescriptor(id);
*/
ImageDescriptor descriptor= create("e" + type, relPath, true); //$NON-NLS-1$
action.setHoverImageDescriptor(descriptor);
action.setImageDescriptor(descriptor);
}
private static ImageDescriptor createManagedFromKey(String prefix, String key) {
return createManaged(prefix, key.substring(NAME_PREFIX_LENGTH), key);
}
private static ImageDescriptor createManaged(String prefix, String name, String key) {
ImageDescriptor result= create(prefix, name, true);
if (fgAvoidSWTErrorMap == null) {
fgAvoidSWTErrorMap= new HashMap<String, ImageDescriptor>();
}
fgAvoidSWTErrorMap.put(key, result);
if (fgImageRegistry != null) { | // Path: src/eclipse/spellchecker/Activator.java
// public class Activator extends AbstractUIPlugin {
//
// public static final String ID_PLUGIN = "eclipse.spellchecker";
// private static Activator plugin; // The shared instance.
//
// /**
// * The constructor.
// */
// public Activator() {
// super();
// plugin = this;
// }
//
// @Override
// public void start(BundleContext context) throws Exception {
// super.start(context);
// }
//
// /**
// * This is called when the plugin is being stopped.
// *
// * @see org.osgi.framework.BundleActivator#stop(org.osgi.framework.BundleContext)
// */
// @Override
// public void stop(BundleContext context) throws Exception {
// try {
// if (fDialogsFormToolkit != null) {
// fDialogsFormToolkit.dispose();
// fDialogsFormToolkit = null;
// }
//
// } finally {
// super.stop(context);
// }
// }
//
// public static Activator getDefault() {
// return plugin;
// }
//
// public static void logErrorMessage(String message) {
// IStatus s = new Status(IStatus.ERROR, ID_PLUGIN, message);
// plugin.getLog().log(s);
// }
//
// public static IWorkbenchWindow getActiveWorkbenchWindow() {
// return getDefault().getWorkbench().getActiveWorkbenchWindow();
// }
//
// public static Shell getActiveWorkbenchShell() {
// IWorkbenchWindow window = getActiveWorkbenchWindow();
// if (window != null) {
// return window.getShell();
// }
// return null;
// }
//
// public static void log(Exception ex) {
// IStatus s = new Status(IStatus.ERROR, ID_PLUGIN, ex.getMessage(), ex);
// plugin.getLog().log(s);
// }
//
// public static void log(IStatus status) {
// plugin.getLog().log(status);
// }
//
// private FormToolkit fDialogsFormToolkit;
//
// public FormToolkit getDialogsFormToolkit() {
// if (fDialogsFormToolkit == null) {
// FormColors colors = new FormColors(Display.getCurrent());
// colors.setBackground(null);
// colors.setForeground(null);
// fDialogsFormToolkit = new FormToolkit(colors);
// }
// return fDialogsFormToolkit;
// }
//
// public static IWorkspace getWorkspace() {
// return ResourcesPlugin.getWorkspace();
// }
//
// }
// Path: src/eclipse/spellchecker/etc/JavaPluginImages.java
import java.net.URL;
import java.util.HashMap;
import java.util.Iterator;
import org.osgi.framework.Bundle;
import org.eclipse.swt.graphics.Image;
import org.eclipse.swt.graphics.ImageData;
import org.eclipse.core.runtime.FileLocator;
import org.eclipse.core.runtime.IPath;
import org.eclipse.core.runtime.Path;
import org.eclipse.jface.action.IAction;
import org.eclipse.jface.resource.ImageDescriptor;
import org.eclipse.jface.resource.ImageRegistry;
import eclipse.spellchecker.Activator;
//---- Helper methods to access icons on the file system --------------------------------------
private static void setImageDescriptors(IAction action, String type, String relPath) {
ImageDescriptor id= create("d" + type, relPath, false); //$NON-NLS-1$
if (id != null)
action.setDisabledImageDescriptor(id);
/*
* id= create("c" + type, relPath, false); //$NON-NLS-1$
* if (id != null)
* action.setHoverImageDescriptor(id);
*/
ImageDescriptor descriptor= create("e" + type, relPath, true); //$NON-NLS-1$
action.setHoverImageDescriptor(descriptor);
action.setImageDescriptor(descriptor);
}
private static ImageDescriptor createManagedFromKey(String prefix, String key) {
return createManaged(prefix, key.substring(NAME_PREFIX_LENGTH), key);
}
private static ImageDescriptor createManaged(String prefix, String name, String key) {
ImageDescriptor result= create(prefix, name, true);
if (fgAvoidSWTErrorMap == null) {
fgAvoidSWTErrorMap= new HashMap<String, ImageDescriptor>();
}
fgAvoidSWTErrorMap.put(key, result);
if (fgImageRegistry != null) { | Activator.logErrorMessage("Image registry already defined"); //$NON-NLS-1$ |
crazyhitty/Munch | app/src/main/java/com/crazyhitty/chdev/ks/munch/article/IArticleInteractor.java | // Path: app/src/main/java/com/crazyhitty/chdev/ks/munch/models/FeedItem.java
// public class FeedItem {
// private String itemTitle, itemDesc, itemSourceUrl, itemLink, itemImgUrl, itemCategory, itemSource, itemPubDate, itemWebDesc, itemWebDescSync;
// private int itemCategoryImgId, itemBgId;
//
// public String getItemTitle() {
// if (itemTitle == null) {
// return "";
// }
// return itemTitle;
// }
//
// public void setItemTitle(String itemTitle) {
// this.itemTitle = itemTitle;
// }
//
// public String getItemDesc() {
// if (itemDesc == null) {
// return "";
// }
// return itemDesc;
// }
//
// public void setItemDesc(String itemDesc) {
// this.itemDesc = itemDesc;
// }
//
// public String getItemSourceUrl() {
// if (itemSourceUrl == null) {
// return "";
// }
// return itemSourceUrl;
// }
//
// public void setItemSourceUrl(String itemSourceUrl) {
// this.itemSourceUrl = itemSourceUrl;
// }
//
// public String getItemLink() {
// if (itemLink == null) {
// return "";
// }
// return itemLink;
// }
//
// public void setItemLink(String itemLink) {
// this.itemLink = itemLink;
// }
//
// public String getItemImgUrl() {
// if (itemImgUrl == null) {
// return "";
// }
// return itemImgUrl;
// }
//
// public void setItemImgUrl(String itemImgUrl) {
// this.itemImgUrl = itemImgUrl;
// }
//
// public String getItemCategory() {
// if (itemCategory == null) {
// return "";
// }
// return itemCategory;
// }
//
// public void setItemCategory(String itemCategory) {
// this.itemCategory = itemCategory;
// }
//
// public String getItemSource() {
// if (itemSource == null) {
// return "";
// }
// return itemSource;
// }
//
// public void setItemSource(String itemSource) {
// this.itemSource = itemSource;
// }
//
// public String getItemPubDate() {
// if (itemPubDate == null) {
// return "";
// }
// return itemPubDate;
// }
//
// public void setItemPubDate(String itemPubDate) {
// this.itemPubDate = itemPubDate;
// }
//
// public int getItemCategoryImgId() {
// return itemCategoryImgId;
// }
//
// public void setItemCategoryImgId(int itemCategoryImgId) {
// this.itemCategoryImgId = itemCategoryImgId;
// }
//
// public int getItemBgId() {
// return itemBgId;
// }
//
// public void setItemBgId(int itemBgId) {
// this.itemBgId = itemBgId;
// }
//
// public String getItemWebDesc() {
// return itemWebDesc;
// }
//
// public void setItemWebDesc(String itemWebDesc) {
// this.itemWebDesc = itemWebDesc;
// }
//
// public String getItemWebDescSync() {
// return itemWebDescSync;
// }
//
// public void setItemWebDescSync(String itemWebDescSync) {
// this.itemWebDescSync = itemWebDescSync;
// }
// }
| import android.content.Context;
import com.crazyhitty.chdev.ks.munch.models.FeedItem; | package com.crazyhitty.chdev.ks.munch.article;
/**
* Created by Kartik_ch on 12/2/2015.
*/
public interface IArticleInteractor {
void loadArticleAsync(OnArticleLoadedListener onArticleLoadedListener, Context context, String url);
void articleLoaded(String articleBody);
void articleLoadingFailed(String message);
| // Path: app/src/main/java/com/crazyhitty/chdev/ks/munch/models/FeedItem.java
// public class FeedItem {
// private String itemTitle, itemDesc, itemSourceUrl, itemLink, itemImgUrl, itemCategory, itemSource, itemPubDate, itemWebDesc, itemWebDescSync;
// private int itemCategoryImgId, itemBgId;
//
// public String getItemTitle() {
// if (itemTitle == null) {
// return "";
// }
// return itemTitle;
// }
//
// public void setItemTitle(String itemTitle) {
// this.itemTitle = itemTitle;
// }
//
// public String getItemDesc() {
// if (itemDesc == null) {
// return "";
// }
// return itemDesc;
// }
//
// public void setItemDesc(String itemDesc) {
// this.itemDesc = itemDesc;
// }
//
// public String getItemSourceUrl() {
// if (itemSourceUrl == null) {
// return "";
// }
// return itemSourceUrl;
// }
//
// public void setItemSourceUrl(String itemSourceUrl) {
// this.itemSourceUrl = itemSourceUrl;
// }
//
// public String getItemLink() {
// if (itemLink == null) {
// return "";
// }
// return itemLink;
// }
//
// public void setItemLink(String itemLink) {
// this.itemLink = itemLink;
// }
//
// public String getItemImgUrl() {
// if (itemImgUrl == null) {
// return "";
// }
// return itemImgUrl;
// }
//
// public void setItemImgUrl(String itemImgUrl) {
// this.itemImgUrl = itemImgUrl;
// }
//
// public String getItemCategory() {
// if (itemCategory == null) {
// return "";
// }
// return itemCategory;
// }
//
// public void setItemCategory(String itemCategory) {
// this.itemCategory = itemCategory;
// }
//
// public String getItemSource() {
// if (itemSource == null) {
// return "";
// }
// return itemSource;
// }
//
// public void setItemSource(String itemSource) {
// this.itemSource = itemSource;
// }
//
// public String getItemPubDate() {
// if (itemPubDate == null) {
// return "";
// }
// return itemPubDate;
// }
//
// public void setItemPubDate(String itemPubDate) {
// this.itemPubDate = itemPubDate;
// }
//
// public int getItemCategoryImgId() {
// return itemCategoryImgId;
// }
//
// public void setItemCategoryImgId(int itemCategoryImgId) {
// this.itemCategoryImgId = itemCategoryImgId;
// }
//
// public int getItemBgId() {
// return itemBgId;
// }
//
// public void setItemBgId(int itemBgId) {
// this.itemBgId = itemBgId;
// }
//
// public String getItemWebDesc() {
// return itemWebDesc;
// }
//
// public void setItemWebDesc(String itemWebDesc) {
// this.itemWebDesc = itemWebDesc;
// }
//
// public String getItemWebDescSync() {
// return itemWebDescSync;
// }
//
// public void setItemWebDescSync(String itemWebDescSync) {
// this.itemWebDescSync = itemWebDescSync;
// }
// }
// Path: app/src/main/java/com/crazyhitty/chdev/ks/munch/article/IArticleInteractor.java
import android.content.Context;
import com.crazyhitty.chdev.ks.munch.models.FeedItem;
package com.crazyhitty.chdev.ks.munch.article;
/**
* Created by Kartik_ch on 12/2/2015.
*/
public interface IArticleInteractor {
void loadArticleAsync(OnArticleLoadedListener onArticleLoadedListener, Context context, String url);
void articleLoaded(String articleBody);
void articleLoadingFailed(String message);
| void archiveArticleInDb(OnArticleArchivedListener onArticleArchivedListener, Context context, FeedItem feedItem, String article); |
crazyhitty/Munch | app/src/main/java/com/crazyhitty/chdev/ks/munch/feeds/IFeedsLoaderInteractor.java | // Path: app/src/main/java/com/crazyhitty/chdev/ks/munch/models/SourceItem.java
// public class SourceItem {
// private String sourceName, sourceUrl, sourceCategoryName, sourceDateAdded;
// private int sourceCategoryImgId;
//
// public int getSourceCategoryImgId() {
// return sourceCategoryImgId;
// }
//
// public void setSourceCategoryImgId(int sourceCategoryImgId) {
// this.sourceCategoryImgId = sourceCategoryImgId;
// }
//
// public String getSourceName() {
// return sourceName;
// }
//
// public void setSourceName(String sourceName) {
// this.sourceName = sourceName;
// }
//
// public String getSourceUrl() {
// return sourceUrl;
// }
//
// public void setSourceUrl(String sourceUrl) {
// this.sourceUrl = sourceUrl;
// }
//
// public String getSourceDateAdded() {
// return sourceDateAdded;
// }
//
// public void setSourceDateAdded(String sourceDateAdded) {
// this.sourceDateAdded = sourceDateAdded;
// }
//
// public String getSourceCategoryName() {
// return sourceCategoryName;
// }
//
// public void setSourceCategoryName(String sourceCategoryName) {
// this.sourceCategoryName = sourceCategoryName;
// }
// }
| import com.crazyhitty.chdev.ks.munch.models.SourceItem;
import java.util.List; | package com.crazyhitty.chdev.ks.munch.feeds;
/**
* Created by Kartik_ch on 11/5/2015.
*/
public interface IFeedsLoaderInteractor {
void loadFeedsFromDb(final OnFeedsLoadedListener onFeedsLoadedListener);
void loadFeedsFromDbBySource(final OnFeedsLoadedListener onFeedsLoadedListener, String source);
| // Path: app/src/main/java/com/crazyhitty/chdev/ks/munch/models/SourceItem.java
// public class SourceItem {
// private String sourceName, sourceUrl, sourceCategoryName, sourceDateAdded;
// private int sourceCategoryImgId;
//
// public int getSourceCategoryImgId() {
// return sourceCategoryImgId;
// }
//
// public void setSourceCategoryImgId(int sourceCategoryImgId) {
// this.sourceCategoryImgId = sourceCategoryImgId;
// }
//
// public String getSourceName() {
// return sourceName;
// }
//
// public void setSourceName(String sourceName) {
// this.sourceName = sourceName;
// }
//
// public String getSourceUrl() {
// return sourceUrl;
// }
//
// public void setSourceUrl(String sourceUrl) {
// this.sourceUrl = sourceUrl;
// }
//
// public String getSourceDateAdded() {
// return sourceDateAdded;
// }
//
// public void setSourceDateAdded(String sourceDateAdded) {
// this.sourceDateAdded = sourceDateAdded;
// }
//
// public String getSourceCategoryName() {
// return sourceCategoryName;
// }
//
// public void setSourceCategoryName(String sourceCategoryName) {
// this.sourceCategoryName = sourceCategoryName;
// }
// }
// Path: app/src/main/java/com/crazyhitty/chdev/ks/munch/feeds/IFeedsLoaderInteractor.java
import com.crazyhitty.chdev.ks.munch.models.SourceItem;
import java.util.List;
package com.crazyhitty.chdev.ks.munch.feeds;
/**
* Created by Kartik_ch on 11/5/2015.
*/
public interface IFeedsLoaderInteractor {
void loadFeedsFromDb(final OnFeedsLoadedListener onFeedsLoadedListener);
void loadFeedsFromDbBySource(final OnFeedsLoadedListener onFeedsLoadedListener, String source);
| void loadFeedsAsync(OnFeedsLoadedListener onFeedsLoadedListener, List<SourceItem> sourceItems); |
crazyhitty/Munch | app/src/main/java/com/crazyhitty/chdev/ks/munch/utils/comparator/FeedPubDateComparator.java | // Path: app/src/main/java/com/crazyhitty/chdev/ks/munch/models/FeedItem.java
// public class FeedItem {
// private String itemTitle, itemDesc, itemSourceUrl, itemLink, itemImgUrl, itemCategory, itemSource, itemPubDate, itemWebDesc, itemWebDescSync;
// private int itemCategoryImgId, itemBgId;
//
// public String getItemTitle() {
// if (itemTitle == null) {
// return "";
// }
// return itemTitle;
// }
//
// public void setItemTitle(String itemTitle) {
// this.itemTitle = itemTitle;
// }
//
// public String getItemDesc() {
// if (itemDesc == null) {
// return "";
// }
// return itemDesc;
// }
//
// public void setItemDesc(String itemDesc) {
// this.itemDesc = itemDesc;
// }
//
// public String getItemSourceUrl() {
// if (itemSourceUrl == null) {
// return "";
// }
// return itemSourceUrl;
// }
//
// public void setItemSourceUrl(String itemSourceUrl) {
// this.itemSourceUrl = itemSourceUrl;
// }
//
// public String getItemLink() {
// if (itemLink == null) {
// return "";
// }
// return itemLink;
// }
//
// public void setItemLink(String itemLink) {
// this.itemLink = itemLink;
// }
//
// public String getItemImgUrl() {
// if (itemImgUrl == null) {
// return "";
// }
// return itemImgUrl;
// }
//
// public void setItemImgUrl(String itemImgUrl) {
// this.itemImgUrl = itemImgUrl;
// }
//
// public String getItemCategory() {
// if (itemCategory == null) {
// return "";
// }
// return itemCategory;
// }
//
// public void setItemCategory(String itemCategory) {
// this.itemCategory = itemCategory;
// }
//
// public String getItemSource() {
// if (itemSource == null) {
// return "";
// }
// return itemSource;
// }
//
// public void setItemSource(String itemSource) {
// this.itemSource = itemSource;
// }
//
// public String getItemPubDate() {
// if (itemPubDate == null) {
// return "";
// }
// return itemPubDate;
// }
//
// public void setItemPubDate(String itemPubDate) {
// this.itemPubDate = itemPubDate;
// }
//
// public int getItemCategoryImgId() {
// return itemCategoryImgId;
// }
//
// public void setItemCategoryImgId(int itemCategoryImgId) {
// this.itemCategoryImgId = itemCategoryImgId;
// }
//
// public int getItemBgId() {
// return itemBgId;
// }
//
// public void setItemBgId(int itemBgId) {
// this.itemBgId = itemBgId;
// }
//
// public String getItemWebDesc() {
// return itemWebDesc;
// }
//
// public void setItemWebDesc(String itemWebDesc) {
// this.itemWebDesc = itemWebDesc;
// }
//
// public String getItemWebDescSync() {
// return itemWebDescSync;
// }
//
// public void setItemWebDescSync(String itemWebDescSync) {
// this.itemWebDescSync = itemWebDescSync;
// }
// }
//
// Path: app/src/main/java/com/crazyhitty/chdev/ks/munch/utils/DateUtil.java
// public class DateUtil {
// String formatRfc2822 = "EEE, dd MMM yyyy HH:mm:ss Z";
// String formatLocal = "EEE, d MMM yyyy";
// private String date;
//
// public String getCurrDate() {
// date = new SimpleDateFormat("dd/MM/yyyy hh:mm:ss").format(new Date());
// return date;
// }
//
// //converts rss publish date into a readable format
// public String getDate(String pubDate) throws ParseException {
// Date date = getDateObj(pubDate);
// return new SimpleDateFormat(formatLocal).format(date);
// }
//
// //get Date object from pub date
// public Date getDateObj(String pubDate) throws ParseException {
// SimpleDateFormat pubDateFormat = new SimpleDateFormat(formatRfc2822, Locale.ENGLISH); //rss spec
// Date date = null;
// try {
// date = pubDateFormat.parse(pubDate);
// } catch (ParseException e) {
// pubDateFormat = new SimpleDateFormat(formatLocal); //fallback
// date = pubDateFormat.parse(pubDate);
// }
// return date;
// }
// }
| import com.crazyhitty.chdev.ks.munch.models.FeedItem;
import com.crazyhitty.chdev.ks.munch.utils.DateUtil;
import java.text.ParseException;
import java.util.Comparator;
import java.util.Date; | package com.crazyhitty.chdev.ks.munch.utils.comparator;
/**
* Created by Kartik_ch on 1/6/2016.
*/
public class FeedPubDateComparator implements Comparator<FeedItem> {
//Reverse date sorting(latest to oldest)
@Override
public int compare(FeedItem feedItem1, FeedItem feedItem2) {
try { | // Path: app/src/main/java/com/crazyhitty/chdev/ks/munch/models/FeedItem.java
// public class FeedItem {
// private String itemTitle, itemDesc, itemSourceUrl, itemLink, itemImgUrl, itemCategory, itemSource, itemPubDate, itemWebDesc, itemWebDescSync;
// private int itemCategoryImgId, itemBgId;
//
// public String getItemTitle() {
// if (itemTitle == null) {
// return "";
// }
// return itemTitle;
// }
//
// public void setItemTitle(String itemTitle) {
// this.itemTitle = itemTitle;
// }
//
// public String getItemDesc() {
// if (itemDesc == null) {
// return "";
// }
// return itemDesc;
// }
//
// public void setItemDesc(String itemDesc) {
// this.itemDesc = itemDesc;
// }
//
// public String getItemSourceUrl() {
// if (itemSourceUrl == null) {
// return "";
// }
// return itemSourceUrl;
// }
//
// public void setItemSourceUrl(String itemSourceUrl) {
// this.itemSourceUrl = itemSourceUrl;
// }
//
// public String getItemLink() {
// if (itemLink == null) {
// return "";
// }
// return itemLink;
// }
//
// public void setItemLink(String itemLink) {
// this.itemLink = itemLink;
// }
//
// public String getItemImgUrl() {
// if (itemImgUrl == null) {
// return "";
// }
// return itemImgUrl;
// }
//
// public void setItemImgUrl(String itemImgUrl) {
// this.itemImgUrl = itemImgUrl;
// }
//
// public String getItemCategory() {
// if (itemCategory == null) {
// return "";
// }
// return itemCategory;
// }
//
// public void setItemCategory(String itemCategory) {
// this.itemCategory = itemCategory;
// }
//
// public String getItemSource() {
// if (itemSource == null) {
// return "";
// }
// return itemSource;
// }
//
// public void setItemSource(String itemSource) {
// this.itemSource = itemSource;
// }
//
// public String getItemPubDate() {
// if (itemPubDate == null) {
// return "";
// }
// return itemPubDate;
// }
//
// public void setItemPubDate(String itemPubDate) {
// this.itemPubDate = itemPubDate;
// }
//
// public int getItemCategoryImgId() {
// return itemCategoryImgId;
// }
//
// public void setItemCategoryImgId(int itemCategoryImgId) {
// this.itemCategoryImgId = itemCategoryImgId;
// }
//
// public int getItemBgId() {
// return itemBgId;
// }
//
// public void setItemBgId(int itemBgId) {
// this.itemBgId = itemBgId;
// }
//
// public String getItemWebDesc() {
// return itemWebDesc;
// }
//
// public void setItemWebDesc(String itemWebDesc) {
// this.itemWebDesc = itemWebDesc;
// }
//
// public String getItemWebDescSync() {
// return itemWebDescSync;
// }
//
// public void setItemWebDescSync(String itemWebDescSync) {
// this.itemWebDescSync = itemWebDescSync;
// }
// }
//
// Path: app/src/main/java/com/crazyhitty/chdev/ks/munch/utils/DateUtil.java
// public class DateUtil {
// String formatRfc2822 = "EEE, dd MMM yyyy HH:mm:ss Z";
// String formatLocal = "EEE, d MMM yyyy";
// private String date;
//
// public String getCurrDate() {
// date = new SimpleDateFormat("dd/MM/yyyy hh:mm:ss").format(new Date());
// return date;
// }
//
// //converts rss publish date into a readable format
// public String getDate(String pubDate) throws ParseException {
// Date date = getDateObj(pubDate);
// return new SimpleDateFormat(formatLocal).format(date);
// }
//
// //get Date object from pub date
// public Date getDateObj(String pubDate) throws ParseException {
// SimpleDateFormat pubDateFormat = new SimpleDateFormat(formatRfc2822, Locale.ENGLISH); //rss spec
// Date date = null;
// try {
// date = pubDateFormat.parse(pubDate);
// } catch (ParseException e) {
// pubDateFormat = new SimpleDateFormat(formatLocal); //fallback
// date = pubDateFormat.parse(pubDate);
// }
// return date;
// }
// }
// Path: app/src/main/java/com/crazyhitty/chdev/ks/munch/utils/comparator/FeedPubDateComparator.java
import com.crazyhitty.chdev.ks.munch.models.FeedItem;
import com.crazyhitty.chdev.ks.munch.utils.DateUtil;
import java.text.ParseException;
import java.util.Comparator;
import java.util.Date;
package com.crazyhitty.chdev.ks.munch.utils.comparator;
/**
* Created by Kartik_ch on 1/6/2016.
*/
public class FeedPubDateComparator implements Comparator<FeedItem> {
//Reverse date sorting(latest to oldest)
@Override
public int compare(FeedItem feedItem1, FeedItem feedItem2) {
try { | Date date1 = new DateUtil().getDateObj(feedItem1.getItemPubDate()); |
crazyhitty/Munch | app/src/main/java/com/crazyhitty/chdev/ks/munch/curatedfeeds/CuratedFeedsInteractor.java | // Path: app/src/main/java/com/crazyhitty/chdev/ks/munch/models/SourceItem.java
// public class SourceItem {
// private String sourceName, sourceUrl, sourceCategoryName, sourceDateAdded;
// private int sourceCategoryImgId;
//
// public int getSourceCategoryImgId() {
// return sourceCategoryImgId;
// }
//
// public void setSourceCategoryImgId(int sourceCategoryImgId) {
// this.sourceCategoryImgId = sourceCategoryImgId;
// }
//
// public String getSourceName() {
// return sourceName;
// }
//
// public void setSourceName(String sourceName) {
// this.sourceName = sourceName;
// }
//
// public String getSourceUrl() {
// return sourceUrl;
// }
//
// public void setSourceUrl(String sourceUrl) {
// this.sourceUrl = sourceUrl;
// }
//
// public String getSourceDateAdded() {
// return sourceDateAdded;
// }
//
// public void setSourceDateAdded(String sourceDateAdded) {
// this.sourceDateAdded = sourceDateAdded;
// }
//
// public String getSourceCategoryName() {
// return sourceCategoryName;
// }
//
// public void setSourceCategoryName(String sourceCategoryName) {
// this.sourceCategoryName = sourceCategoryName;
// }
// }
//
// Path: app/src/main/java/com/crazyhitty/chdev/ks/munch/utils/DateUtil.java
// public class DateUtil {
// String formatRfc2822 = "EEE, dd MMM yyyy HH:mm:ss Z";
// String formatLocal = "EEE, d MMM yyyy";
// private String date;
//
// public String getCurrDate() {
// date = new SimpleDateFormat("dd/MM/yyyy hh:mm:ss").format(new Date());
// return date;
// }
//
// //converts rss publish date into a readable format
// public String getDate(String pubDate) throws ParseException {
// Date date = getDateObj(pubDate);
// return new SimpleDateFormat(formatLocal).format(date);
// }
//
// //get Date object from pub date
// public Date getDateObj(String pubDate) throws ParseException {
// SimpleDateFormat pubDateFormat = new SimpleDateFormat(formatRfc2822, Locale.ENGLISH); //rss spec
// Date date = null;
// try {
// date = pubDateFormat.parse(pubDate);
// } catch (ParseException e) {
// pubDateFormat = new SimpleDateFormat(formatLocal); //fallback
// date = pubDateFormat.parse(pubDate);
// }
// return date;
// }
// }
| import android.content.Context;
import android.os.Handler;
import com.crazyhitty.chdev.ks.munch.models.SourceItem;
import com.crazyhitty.chdev.ks.munch.utils.DateUtil;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response; | @Override
public void onResponse(Response response) throws IOException {
if (response.isSuccessful()) {
final String responseStr = response.body().string();
//run on the ui thread
new Handler(mContext.getMainLooper()).post(new Runnable() {
@Override
public void run() {
parseCuratedFeedsJson(responseStr);
}
});
} else {
final String responseMsg = response.message();
//run on the ui thread
new Handler(mContext.getMainLooper()).post(new Runnable() {
@Override
public void run() {
mOnCuratedFeedsRetrievedListener.onFailure(responseMsg);
}
});
}
}
private void parseCuratedFeedsJson(String curatedFeedsResponseStr) {
try {
JSONObject mainJsonObject = new JSONObject(curatedFeedsResponseStr);
double version = ((Number) mainJsonObject.get(VERSION)).doubleValue();
String releaseDate = mainJsonObject.getString(RELEASE_DATE);
String lastModified = mainJsonObject.getString(LAST_MODIFIED);
| // Path: app/src/main/java/com/crazyhitty/chdev/ks/munch/models/SourceItem.java
// public class SourceItem {
// private String sourceName, sourceUrl, sourceCategoryName, sourceDateAdded;
// private int sourceCategoryImgId;
//
// public int getSourceCategoryImgId() {
// return sourceCategoryImgId;
// }
//
// public void setSourceCategoryImgId(int sourceCategoryImgId) {
// this.sourceCategoryImgId = sourceCategoryImgId;
// }
//
// public String getSourceName() {
// return sourceName;
// }
//
// public void setSourceName(String sourceName) {
// this.sourceName = sourceName;
// }
//
// public String getSourceUrl() {
// return sourceUrl;
// }
//
// public void setSourceUrl(String sourceUrl) {
// this.sourceUrl = sourceUrl;
// }
//
// public String getSourceDateAdded() {
// return sourceDateAdded;
// }
//
// public void setSourceDateAdded(String sourceDateAdded) {
// this.sourceDateAdded = sourceDateAdded;
// }
//
// public String getSourceCategoryName() {
// return sourceCategoryName;
// }
//
// public void setSourceCategoryName(String sourceCategoryName) {
// this.sourceCategoryName = sourceCategoryName;
// }
// }
//
// Path: app/src/main/java/com/crazyhitty/chdev/ks/munch/utils/DateUtil.java
// public class DateUtil {
// String formatRfc2822 = "EEE, dd MMM yyyy HH:mm:ss Z";
// String formatLocal = "EEE, d MMM yyyy";
// private String date;
//
// public String getCurrDate() {
// date = new SimpleDateFormat("dd/MM/yyyy hh:mm:ss").format(new Date());
// return date;
// }
//
// //converts rss publish date into a readable format
// public String getDate(String pubDate) throws ParseException {
// Date date = getDateObj(pubDate);
// return new SimpleDateFormat(formatLocal).format(date);
// }
//
// //get Date object from pub date
// public Date getDateObj(String pubDate) throws ParseException {
// SimpleDateFormat pubDateFormat = new SimpleDateFormat(formatRfc2822, Locale.ENGLISH); //rss spec
// Date date = null;
// try {
// date = pubDateFormat.parse(pubDate);
// } catch (ParseException e) {
// pubDateFormat = new SimpleDateFormat(formatLocal); //fallback
// date = pubDateFormat.parse(pubDate);
// }
// return date;
// }
// }
// Path: app/src/main/java/com/crazyhitty/chdev/ks/munch/curatedfeeds/CuratedFeedsInteractor.java
import android.content.Context;
import android.os.Handler;
import com.crazyhitty.chdev.ks.munch.models.SourceItem;
import com.crazyhitty.chdev.ks.munch.utils.DateUtil;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
@Override
public void onResponse(Response response) throws IOException {
if (response.isSuccessful()) {
final String responseStr = response.body().string();
//run on the ui thread
new Handler(mContext.getMainLooper()).post(new Runnable() {
@Override
public void run() {
parseCuratedFeedsJson(responseStr);
}
});
} else {
final String responseMsg = response.message();
//run on the ui thread
new Handler(mContext.getMainLooper()).post(new Runnable() {
@Override
public void run() {
mOnCuratedFeedsRetrievedListener.onFailure(responseMsg);
}
});
}
}
private void parseCuratedFeedsJson(String curatedFeedsResponseStr) {
try {
JSONObject mainJsonObject = new JSONObject(curatedFeedsResponseStr);
double version = ((Number) mainJsonObject.get(VERSION)).doubleValue();
String releaseDate = mainJsonObject.getString(RELEASE_DATE);
String lastModified = mainJsonObject.getString(LAST_MODIFIED);
| List<SourceItem> sourceItems = new ArrayList<>(); |
crazyhitty/Munch | app/src/main/java/com/crazyhitty/chdev/ks/munch/curatedfeeds/CuratedFeedsInteractor.java | // Path: app/src/main/java/com/crazyhitty/chdev/ks/munch/models/SourceItem.java
// public class SourceItem {
// private String sourceName, sourceUrl, sourceCategoryName, sourceDateAdded;
// private int sourceCategoryImgId;
//
// public int getSourceCategoryImgId() {
// return sourceCategoryImgId;
// }
//
// public void setSourceCategoryImgId(int sourceCategoryImgId) {
// this.sourceCategoryImgId = sourceCategoryImgId;
// }
//
// public String getSourceName() {
// return sourceName;
// }
//
// public void setSourceName(String sourceName) {
// this.sourceName = sourceName;
// }
//
// public String getSourceUrl() {
// return sourceUrl;
// }
//
// public void setSourceUrl(String sourceUrl) {
// this.sourceUrl = sourceUrl;
// }
//
// public String getSourceDateAdded() {
// return sourceDateAdded;
// }
//
// public void setSourceDateAdded(String sourceDateAdded) {
// this.sourceDateAdded = sourceDateAdded;
// }
//
// public String getSourceCategoryName() {
// return sourceCategoryName;
// }
//
// public void setSourceCategoryName(String sourceCategoryName) {
// this.sourceCategoryName = sourceCategoryName;
// }
// }
//
// Path: app/src/main/java/com/crazyhitty/chdev/ks/munch/utils/DateUtil.java
// public class DateUtil {
// String formatRfc2822 = "EEE, dd MMM yyyy HH:mm:ss Z";
// String formatLocal = "EEE, d MMM yyyy";
// private String date;
//
// public String getCurrDate() {
// date = new SimpleDateFormat("dd/MM/yyyy hh:mm:ss").format(new Date());
// return date;
// }
//
// //converts rss publish date into a readable format
// public String getDate(String pubDate) throws ParseException {
// Date date = getDateObj(pubDate);
// return new SimpleDateFormat(formatLocal).format(date);
// }
//
// //get Date object from pub date
// public Date getDateObj(String pubDate) throws ParseException {
// SimpleDateFormat pubDateFormat = new SimpleDateFormat(formatRfc2822, Locale.ENGLISH); //rss spec
// Date date = null;
// try {
// date = pubDateFormat.parse(pubDate);
// } catch (ParseException e) {
// pubDateFormat = new SimpleDateFormat(formatLocal); //fallback
// date = pubDateFormat.parse(pubDate);
// }
// return date;
// }
// }
| import android.content.Context;
import android.os.Handler;
import com.crazyhitty.chdev.ks.munch.models.SourceItem;
import com.crazyhitty.chdev.ks.munch.utils.DateUtil;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response; | final String responseMsg = response.message();
//run on the ui thread
new Handler(mContext.getMainLooper()).post(new Runnable() {
@Override
public void run() {
mOnCuratedFeedsRetrievedListener.onFailure(responseMsg);
}
});
}
}
private void parseCuratedFeedsJson(String curatedFeedsResponseStr) {
try {
JSONObject mainJsonObject = new JSONObject(curatedFeedsResponseStr);
double version = ((Number) mainJsonObject.get(VERSION)).doubleValue();
String releaseDate = mainJsonObject.getString(RELEASE_DATE);
String lastModified = mainJsonObject.getString(LAST_MODIFIED);
List<SourceItem> sourceItems = new ArrayList<>();
JSONArray curatedFeedsJsonObject = mainJsonObject.getJSONArray(CURATED_FEEDS);
for (int i = 0; i < curatedFeedsJsonObject.length(); i++) {
String sourceName = curatedFeedsJsonObject.getJSONObject(i).getString(SOURCE_NAME);
String sourceUrl = curatedFeedsJsonObject.getJSONObject(i).getString(SOURCE_URL);
String sourceCategory = curatedFeedsJsonObject.getJSONObject(i).getString(SOURCE_CATEGORY);
SourceItem sourceItem = new SourceItem();
sourceItem.setSourceName(sourceName);
sourceItem.setSourceUrl(sourceUrl);
sourceItem.setSourceCategoryName(sourceCategory); | // Path: app/src/main/java/com/crazyhitty/chdev/ks/munch/models/SourceItem.java
// public class SourceItem {
// private String sourceName, sourceUrl, sourceCategoryName, sourceDateAdded;
// private int sourceCategoryImgId;
//
// public int getSourceCategoryImgId() {
// return sourceCategoryImgId;
// }
//
// public void setSourceCategoryImgId(int sourceCategoryImgId) {
// this.sourceCategoryImgId = sourceCategoryImgId;
// }
//
// public String getSourceName() {
// return sourceName;
// }
//
// public void setSourceName(String sourceName) {
// this.sourceName = sourceName;
// }
//
// public String getSourceUrl() {
// return sourceUrl;
// }
//
// public void setSourceUrl(String sourceUrl) {
// this.sourceUrl = sourceUrl;
// }
//
// public String getSourceDateAdded() {
// return sourceDateAdded;
// }
//
// public void setSourceDateAdded(String sourceDateAdded) {
// this.sourceDateAdded = sourceDateAdded;
// }
//
// public String getSourceCategoryName() {
// return sourceCategoryName;
// }
//
// public void setSourceCategoryName(String sourceCategoryName) {
// this.sourceCategoryName = sourceCategoryName;
// }
// }
//
// Path: app/src/main/java/com/crazyhitty/chdev/ks/munch/utils/DateUtil.java
// public class DateUtil {
// String formatRfc2822 = "EEE, dd MMM yyyy HH:mm:ss Z";
// String formatLocal = "EEE, d MMM yyyy";
// private String date;
//
// public String getCurrDate() {
// date = new SimpleDateFormat("dd/MM/yyyy hh:mm:ss").format(new Date());
// return date;
// }
//
// //converts rss publish date into a readable format
// public String getDate(String pubDate) throws ParseException {
// Date date = getDateObj(pubDate);
// return new SimpleDateFormat(formatLocal).format(date);
// }
//
// //get Date object from pub date
// public Date getDateObj(String pubDate) throws ParseException {
// SimpleDateFormat pubDateFormat = new SimpleDateFormat(formatRfc2822, Locale.ENGLISH); //rss spec
// Date date = null;
// try {
// date = pubDateFormat.parse(pubDate);
// } catch (ParseException e) {
// pubDateFormat = new SimpleDateFormat(formatLocal); //fallback
// date = pubDateFormat.parse(pubDate);
// }
// return date;
// }
// }
// Path: app/src/main/java/com/crazyhitty/chdev/ks/munch/curatedfeeds/CuratedFeedsInteractor.java
import android.content.Context;
import android.os.Handler;
import com.crazyhitty.chdev.ks.munch.models.SourceItem;
import com.crazyhitty.chdev.ks.munch.utils.DateUtil;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
final String responseMsg = response.message();
//run on the ui thread
new Handler(mContext.getMainLooper()).post(new Runnable() {
@Override
public void run() {
mOnCuratedFeedsRetrievedListener.onFailure(responseMsg);
}
});
}
}
private void parseCuratedFeedsJson(String curatedFeedsResponseStr) {
try {
JSONObject mainJsonObject = new JSONObject(curatedFeedsResponseStr);
double version = ((Number) mainJsonObject.get(VERSION)).doubleValue();
String releaseDate = mainJsonObject.getString(RELEASE_DATE);
String lastModified = mainJsonObject.getString(LAST_MODIFIED);
List<SourceItem> sourceItems = new ArrayList<>();
JSONArray curatedFeedsJsonObject = mainJsonObject.getJSONArray(CURATED_FEEDS);
for (int i = 0; i < curatedFeedsJsonObject.length(); i++) {
String sourceName = curatedFeedsJsonObject.getJSONObject(i).getString(SOURCE_NAME);
String sourceUrl = curatedFeedsJsonObject.getJSONObject(i).getString(SOURCE_URL);
String sourceCategory = curatedFeedsJsonObject.getJSONObject(i).getString(SOURCE_CATEGORY);
SourceItem sourceItem = new SourceItem();
sourceItem.setSourceName(sourceName);
sourceItem.setSourceUrl(sourceUrl);
sourceItem.setSourceCategoryName(sourceCategory); | sourceItem.setSourceDateAdded(new DateUtil().getCurrDate()); |
crazyhitty/Munch | app/src/main/java/com/crazyhitty/chdev/ks/munch/importopml/ImportOpmlInteractor.java | // Path: app/src/main/java/com/crazyhitty/chdev/ks/munch/models/SourceItem.java
// public class SourceItem {
// private String sourceName, sourceUrl, sourceCategoryName, sourceDateAdded;
// private int sourceCategoryImgId;
//
// public int getSourceCategoryImgId() {
// return sourceCategoryImgId;
// }
//
// public void setSourceCategoryImgId(int sourceCategoryImgId) {
// this.sourceCategoryImgId = sourceCategoryImgId;
// }
//
// public String getSourceName() {
// return sourceName;
// }
//
// public void setSourceName(String sourceName) {
// this.sourceName = sourceName;
// }
//
// public String getSourceUrl() {
// return sourceUrl;
// }
//
// public void setSourceUrl(String sourceUrl) {
// this.sourceUrl = sourceUrl;
// }
//
// public String getSourceDateAdded() {
// return sourceDateAdded;
// }
//
// public void setSourceDateAdded(String sourceDateAdded) {
// this.sourceDateAdded = sourceDateAdded;
// }
//
// public String getSourceCategoryName() {
// return sourceCategoryName;
// }
//
// public void setSourceCategoryName(String sourceCategoryName) {
// this.sourceCategoryName = sourceCategoryName;
// }
// }
//
// Path: app/src/main/java/com/crazyhitty/chdev/ks/munch/utils/DateUtil.java
// public class DateUtil {
// String formatRfc2822 = "EEE, dd MMM yyyy HH:mm:ss Z";
// String formatLocal = "EEE, d MMM yyyy";
// private String date;
//
// public String getCurrDate() {
// date = new SimpleDateFormat("dd/MM/yyyy hh:mm:ss").format(new Date());
// return date;
// }
//
// //converts rss publish date into a readable format
// public String getDate(String pubDate) throws ParseException {
// Date date = getDateObj(pubDate);
// return new SimpleDateFormat(formatLocal).format(date);
// }
//
// //get Date object from pub date
// public Date getDateObj(String pubDate) throws ParseException {
// SimpleDateFormat pubDateFormat = new SimpleDateFormat(formatRfc2822, Locale.ENGLISH); //rss spec
// Date date = null;
// try {
// date = pubDateFormat.parse(pubDate);
// } catch (ParseException e) {
// pubDateFormat = new SimpleDateFormat(formatLocal); //fallback
// date = pubDateFormat.parse(pubDate);
// }
// return date;
// }
// }
| import android.content.Context;
import android.os.AsyncTask;
import android.util.Log;
import android.webkit.MimeTypeMap;
import com.afollestad.materialdialogs.DialogAction;
import com.afollestad.materialdialogs.MaterialDialog;
import com.crazyhitty.chdev.ks.munch.R;
import com.crazyhitty.chdev.ks.munch.models.SourceItem;
import com.crazyhitty.chdev.ks.munch.utils.DateUtil;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.parser.Parser;
import org.jsoup.select.Elements;
import java.io.File;
import java.io.IOException;
import java.net.MalformedURLException;
import java.util.ArrayList;
import java.util.List; | @Override
protected void onPreExecute() {
super.onPreExecute();
}
@Override
protected String doInBackground(String... strings) {
Document opmlDocument = null;
try {
if (mUrl != null) {
opmlDocument = Jsoup.connect(mUrl).parser(Parser.xmlParser()).get();
} else {
opmlDocument = Jsoup.parse(mFile, "UTF-8");
}
} catch (IOException e) {
e.printStackTrace();
return e.getMessage();
}
if (opmlDocument != null) {
mOpmlItems = opmlDocument.select("outline");
}
return "success";
}
@Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
mLoadingDialog.dismiss();
if (s.equals("success")) {
Log.e("Opml Items", String.valueOf(mOpmlItems.size())); | // Path: app/src/main/java/com/crazyhitty/chdev/ks/munch/models/SourceItem.java
// public class SourceItem {
// private String sourceName, sourceUrl, sourceCategoryName, sourceDateAdded;
// private int sourceCategoryImgId;
//
// public int getSourceCategoryImgId() {
// return sourceCategoryImgId;
// }
//
// public void setSourceCategoryImgId(int sourceCategoryImgId) {
// this.sourceCategoryImgId = sourceCategoryImgId;
// }
//
// public String getSourceName() {
// return sourceName;
// }
//
// public void setSourceName(String sourceName) {
// this.sourceName = sourceName;
// }
//
// public String getSourceUrl() {
// return sourceUrl;
// }
//
// public void setSourceUrl(String sourceUrl) {
// this.sourceUrl = sourceUrl;
// }
//
// public String getSourceDateAdded() {
// return sourceDateAdded;
// }
//
// public void setSourceDateAdded(String sourceDateAdded) {
// this.sourceDateAdded = sourceDateAdded;
// }
//
// public String getSourceCategoryName() {
// return sourceCategoryName;
// }
//
// public void setSourceCategoryName(String sourceCategoryName) {
// this.sourceCategoryName = sourceCategoryName;
// }
// }
//
// Path: app/src/main/java/com/crazyhitty/chdev/ks/munch/utils/DateUtil.java
// public class DateUtil {
// String formatRfc2822 = "EEE, dd MMM yyyy HH:mm:ss Z";
// String formatLocal = "EEE, d MMM yyyy";
// private String date;
//
// public String getCurrDate() {
// date = new SimpleDateFormat("dd/MM/yyyy hh:mm:ss").format(new Date());
// return date;
// }
//
// //converts rss publish date into a readable format
// public String getDate(String pubDate) throws ParseException {
// Date date = getDateObj(pubDate);
// return new SimpleDateFormat(formatLocal).format(date);
// }
//
// //get Date object from pub date
// public Date getDateObj(String pubDate) throws ParseException {
// SimpleDateFormat pubDateFormat = new SimpleDateFormat(formatRfc2822, Locale.ENGLISH); //rss spec
// Date date = null;
// try {
// date = pubDateFormat.parse(pubDate);
// } catch (ParseException e) {
// pubDateFormat = new SimpleDateFormat(formatLocal); //fallback
// date = pubDateFormat.parse(pubDate);
// }
// return date;
// }
// }
// Path: app/src/main/java/com/crazyhitty/chdev/ks/munch/importopml/ImportOpmlInteractor.java
import android.content.Context;
import android.os.AsyncTask;
import android.util.Log;
import android.webkit.MimeTypeMap;
import com.afollestad.materialdialogs.DialogAction;
import com.afollestad.materialdialogs.MaterialDialog;
import com.crazyhitty.chdev.ks.munch.R;
import com.crazyhitty.chdev.ks.munch.models.SourceItem;
import com.crazyhitty.chdev.ks.munch.utils.DateUtil;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.parser.Parser;
import org.jsoup.select.Elements;
import java.io.File;
import java.io.IOException;
import java.net.MalformedURLException;
import java.util.ArrayList;
import java.util.List;
@Override
protected void onPreExecute() {
super.onPreExecute();
}
@Override
protected String doInBackground(String... strings) {
Document opmlDocument = null;
try {
if (mUrl != null) {
opmlDocument = Jsoup.connect(mUrl).parser(Parser.xmlParser()).get();
} else {
opmlDocument = Jsoup.parse(mFile, "UTF-8");
}
} catch (IOException e) {
e.printStackTrace();
return e.getMessage();
}
if (opmlDocument != null) {
mOpmlItems = opmlDocument.select("outline");
}
return "success";
}
@Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
mLoadingDialog.dismiss();
if (s.equals("success")) {
Log.e("Opml Items", String.valueOf(mOpmlItems.size())); | List<SourceItem> sourceItems = new ArrayList<>(); |
crazyhitty/Munch | app/src/main/java/com/crazyhitty/chdev/ks/munch/importopml/ImportOpmlInteractor.java | // Path: app/src/main/java/com/crazyhitty/chdev/ks/munch/models/SourceItem.java
// public class SourceItem {
// private String sourceName, sourceUrl, sourceCategoryName, sourceDateAdded;
// private int sourceCategoryImgId;
//
// public int getSourceCategoryImgId() {
// return sourceCategoryImgId;
// }
//
// public void setSourceCategoryImgId(int sourceCategoryImgId) {
// this.sourceCategoryImgId = sourceCategoryImgId;
// }
//
// public String getSourceName() {
// return sourceName;
// }
//
// public void setSourceName(String sourceName) {
// this.sourceName = sourceName;
// }
//
// public String getSourceUrl() {
// return sourceUrl;
// }
//
// public void setSourceUrl(String sourceUrl) {
// this.sourceUrl = sourceUrl;
// }
//
// public String getSourceDateAdded() {
// return sourceDateAdded;
// }
//
// public void setSourceDateAdded(String sourceDateAdded) {
// this.sourceDateAdded = sourceDateAdded;
// }
//
// public String getSourceCategoryName() {
// return sourceCategoryName;
// }
//
// public void setSourceCategoryName(String sourceCategoryName) {
// this.sourceCategoryName = sourceCategoryName;
// }
// }
//
// Path: app/src/main/java/com/crazyhitty/chdev/ks/munch/utils/DateUtil.java
// public class DateUtil {
// String formatRfc2822 = "EEE, dd MMM yyyy HH:mm:ss Z";
// String formatLocal = "EEE, d MMM yyyy";
// private String date;
//
// public String getCurrDate() {
// date = new SimpleDateFormat("dd/MM/yyyy hh:mm:ss").format(new Date());
// return date;
// }
//
// //converts rss publish date into a readable format
// public String getDate(String pubDate) throws ParseException {
// Date date = getDateObj(pubDate);
// return new SimpleDateFormat(formatLocal).format(date);
// }
//
// //get Date object from pub date
// public Date getDateObj(String pubDate) throws ParseException {
// SimpleDateFormat pubDateFormat = new SimpleDateFormat(formatRfc2822, Locale.ENGLISH); //rss spec
// Date date = null;
// try {
// date = pubDateFormat.parse(pubDate);
// } catch (ParseException e) {
// pubDateFormat = new SimpleDateFormat(formatLocal); //fallback
// date = pubDateFormat.parse(pubDate);
// }
// return date;
// }
// }
| import android.content.Context;
import android.os.AsyncTask;
import android.util.Log;
import android.webkit.MimeTypeMap;
import com.afollestad.materialdialogs.DialogAction;
import com.afollestad.materialdialogs.MaterialDialog;
import com.crazyhitty.chdev.ks.munch.R;
import com.crazyhitty.chdev.ks.munch.models.SourceItem;
import com.crazyhitty.chdev.ks.munch.utils.DateUtil;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.parser.Parser;
import org.jsoup.select.Elements;
import java.io.File;
import java.io.IOException;
import java.net.MalformedURLException;
import java.util.ArrayList;
import java.util.List; | } catch (IOException e) {
e.printStackTrace();
return e.getMessage();
}
if (opmlDocument != null) {
mOpmlItems = opmlDocument.select("outline");
}
return "success";
}
@Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
mLoadingDialog.dismiss();
if (s.equals("success")) {
Log.e("Opml Items", String.valueOf(mOpmlItems.size()));
List<SourceItem> sourceItems = new ArrayList<>();
for (Element opmlItem : mOpmlItems) {
String title = opmlItem.attr("text");
String url = null;
if (!opmlItem.attr("xmlUrl").isEmpty()) {
url = opmlItem.attr("xmlUrl");
} else if (opmlItem.attr("url").isEmpty()) {
url = opmlItem.attr("url");
}
if (url != null) {
SourceItem sourceItem = new SourceItem();
sourceItem.setSourceName(title);
sourceItem.setSourceUrl(url);
sourceItem.setSourceCategoryName(UNKNOWN); | // Path: app/src/main/java/com/crazyhitty/chdev/ks/munch/models/SourceItem.java
// public class SourceItem {
// private String sourceName, sourceUrl, sourceCategoryName, sourceDateAdded;
// private int sourceCategoryImgId;
//
// public int getSourceCategoryImgId() {
// return sourceCategoryImgId;
// }
//
// public void setSourceCategoryImgId(int sourceCategoryImgId) {
// this.sourceCategoryImgId = sourceCategoryImgId;
// }
//
// public String getSourceName() {
// return sourceName;
// }
//
// public void setSourceName(String sourceName) {
// this.sourceName = sourceName;
// }
//
// public String getSourceUrl() {
// return sourceUrl;
// }
//
// public void setSourceUrl(String sourceUrl) {
// this.sourceUrl = sourceUrl;
// }
//
// public String getSourceDateAdded() {
// return sourceDateAdded;
// }
//
// public void setSourceDateAdded(String sourceDateAdded) {
// this.sourceDateAdded = sourceDateAdded;
// }
//
// public String getSourceCategoryName() {
// return sourceCategoryName;
// }
//
// public void setSourceCategoryName(String sourceCategoryName) {
// this.sourceCategoryName = sourceCategoryName;
// }
// }
//
// Path: app/src/main/java/com/crazyhitty/chdev/ks/munch/utils/DateUtil.java
// public class DateUtil {
// String formatRfc2822 = "EEE, dd MMM yyyy HH:mm:ss Z";
// String formatLocal = "EEE, d MMM yyyy";
// private String date;
//
// public String getCurrDate() {
// date = new SimpleDateFormat("dd/MM/yyyy hh:mm:ss").format(new Date());
// return date;
// }
//
// //converts rss publish date into a readable format
// public String getDate(String pubDate) throws ParseException {
// Date date = getDateObj(pubDate);
// return new SimpleDateFormat(formatLocal).format(date);
// }
//
// //get Date object from pub date
// public Date getDateObj(String pubDate) throws ParseException {
// SimpleDateFormat pubDateFormat = new SimpleDateFormat(formatRfc2822, Locale.ENGLISH); //rss spec
// Date date = null;
// try {
// date = pubDateFormat.parse(pubDate);
// } catch (ParseException e) {
// pubDateFormat = new SimpleDateFormat(formatLocal); //fallback
// date = pubDateFormat.parse(pubDate);
// }
// return date;
// }
// }
// Path: app/src/main/java/com/crazyhitty/chdev/ks/munch/importopml/ImportOpmlInteractor.java
import android.content.Context;
import android.os.AsyncTask;
import android.util.Log;
import android.webkit.MimeTypeMap;
import com.afollestad.materialdialogs.DialogAction;
import com.afollestad.materialdialogs.MaterialDialog;
import com.crazyhitty.chdev.ks.munch.R;
import com.crazyhitty.chdev.ks.munch.models.SourceItem;
import com.crazyhitty.chdev.ks.munch.utils.DateUtil;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.parser.Parser;
import org.jsoup.select.Elements;
import java.io.File;
import java.io.IOException;
import java.net.MalformedURLException;
import java.util.ArrayList;
import java.util.List;
} catch (IOException e) {
e.printStackTrace();
return e.getMessage();
}
if (opmlDocument != null) {
mOpmlItems = opmlDocument.select("outline");
}
return "success";
}
@Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
mLoadingDialog.dismiss();
if (s.equals("success")) {
Log.e("Opml Items", String.valueOf(mOpmlItems.size()));
List<SourceItem> sourceItems = new ArrayList<>();
for (Element opmlItem : mOpmlItems) {
String title = opmlItem.attr("text");
String url = null;
if (!opmlItem.attr("xmlUrl").isEmpty()) {
url = opmlItem.attr("xmlUrl");
} else if (opmlItem.attr("url").isEmpty()) {
url = opmlItem.attr("url");
}
if (url != null) {
SourceItem sourceItem = new SourceItem();
sourceItem.setSourceName(title);
sourceItem.setSourceUrl(url);
sourceItem.setSourceCategoryName(UNKNOWN); | sourceItem.setSourceDateAdded(new DateUtil().getCurrDate()); |
crazyhitty/Munch | app/src/main/java/com/crazyhitty/chdev/ks/munch/sources/ISourceView.java | // Path: app/src/main/java/com/crazyhitty/chdev/ks/munch/models/SourceItem.java
// public class SourceItem {
// private String sourceName, sourceUrl, sourceCategoryName, sourceDateAdded;
// private int sourceCategoryImgId;
//
// public int getSourceCategoryImgId() {
// return sourceCategoryImgId;
// }
//
// public void setSourceCategoryImgId(int sourceCategoryImgId) {
// this.sourceCategoryImgId = sourceCategoryImgId;
// }
//
// public String getSourceName() {
// return sourceName;
// }
//
// public void setSourceName(String sourceName) {
// this.sourceName = sourceName;
// }
//
// public String getSourceUrl() {
// return sourceUrl;
// }
//
// public void setSourceUrl(String sourceUrl) {
// this.sourceUrl = sourceUrl;
// }
//
// public String getSourceDateAdded() {
// return sourceDateAdded;
// }
//
// public void setSourceDateAdded(String sourceDateAdded) {
// this.sourceDateAdded = sourceDateAdded;
// }
//
// public String getSourceCategoryName() {
// return sourceCategoryName;
// }
//
// public void setSourceCategoryName(String sourceCategoryName) {
// this.sourceCategoryName = sourceCategoryName;
// }
// }
| import com.crazyhitty.chdev.ks.munch.models.SourceItem;
import java.util.List; | package com.crazyhitty.chdev.ks.munch.sources;
/**
* Created by Kartik_ch on 11/8/2015.
*/
public interface ISourceView {
void dataSourceSaved(String message);
void dataSourceSaveFailed(String message);
void dataSourceLoaded(List<String> sourceNames);
| // Path: app/src/main/java/com/crazyhitty/chdev/ks/munch/models/SourceItem.java
// public class SourceItem {
// private String sourceName, sourceUrl, sourceCategoryName, sourceDateAdded;
// private int sourceCategoryImgId;
//
// public int getSourceCategoryImgId() {
// return sourceCategoryImgId;
// }
//
// public void setSourceCategoryImgId(int sourceCategoryImgId) {
// this.sourceCategoryImgId = sourceCategoryImgId;
// }
//
// public String getSourceName() {
// return sourceName;
// }
//
// public void setSourceName(String sourceName) {
// this.sourceName = sourceName;
// }
//
// public String getSourceUrl() {
// return sourceUrl;
// }
//
// public void setSourceUrl(String sourceUrl) {
// this.sourceUrl = sourceUrl;
// }
//
// public String getSourceDateAdded() {
// return sourceDateAdded;
// }
//
// public void setSourceDateAdded(String sourceDateAdded) {
// this.sourceDateAdded = sourceDateAdded;
// }
//
// public String getSourceCategoryName() {
// return sourceCategoryName;
// }
//
// public void setSourceCategoryName(String sourceCategoryName) {
// this.sourceCategoryName = sourceCategoryName;
// }
// }
// Path: app/src/main/java/com/crazyhitty/chdev/ks/munch/sources/ISourceView.java
import com.crazyhitty.chdev.ks.munch.models.SourceItem;
import java.util.List;
package com.crazyhitty.chdev.ks.munch.sources;
/**
* Created by Kartik_ch on 11/8/2015.
*/
public interface ISourceView {
void dataSourceSaved(String message);
void dataSourceSaveFailed(String message);
void dataSourceLoaded(List<String> sourceNames);
| void dataSourceItemsLoaded(List<SourceItem> sourceItems); |
crazyhitty/Munch | app/src/main/java/com/crazyhitty/chdev/ks/munch/ui/adapters/SplashPagerAdapter.java | // Path: app/src/main/java/com/crazyhitty/chdev/ks/munch/ui/fragments/SplashFragment.java
// public class SplashFragment extends Fragment {
//
// private static final String ARG_SECTION_NUMBER = "section_number";
// @Bind(R.id.relative_layout_fragment_splash)
// RelativeLayout relativeLayoutSplash;
// @Bind(R.id.text_view_splash_title)
// TextView txtSplashTitle;
// @Bind(R.id.text_view_splash_desc)
// TextView txtSplashDesc;
// @Bind(R.id.image_view_splash)
// ImageView imgSplash;
// @Bind(R.id.image_view_empty_dot_1)
// ImageView imgEmptyDot1;
// @Bind(R.id.image_view_empty_dot_2)
// ImageView imgEmptyDot2;
// @Bind(R.id.image_view_empty_dot_3)
// ImageView imgEmptyDot3;
// @Bind(R.id.image_view_selected_dot_1)
// ImageView imgSelectedDot1;
// @Bind(R.id.image_view_selected_dot_2)
// ImageView imgSelectedDot2;
// @Bind(R.id.image_view_selected_dot_3)
// ImageView imgSelectedDot3;
//
// /**
// * Returns a new instance of this fragment for the given section
// * number.
// */
// public static SplashFragment newInstance(int sectionNumber) {
// SplashFragment fragment = new SplashFragment();
// Bundle args = new Bundle();
// args.putInt(ARG_SECTION_NUMBER, sectionNumber);
// fragment.setArguments(args);
// return fragment;
// }
//
// @Override
// public View onCreateView(LayoutInflater inflater, ViewGroup container,
// Bundle savedInstanceState) {
// View view = inflater.inflate(R.layout.fragment_splash, container, false);
// ButterKnife.bind(this, view);
// return view;
// }
//
// @Override
// public void onActivityCreated(Bundle savedInstanceState) {
// super.onActivityCreated(savedInstanceState);
// int sectionNumber = getArguments().getInt(ARG_SECTION_NUMBER);
// txtSplashTitle.setText(getString(R.string.section_format, sectionNumber));
//
// switch (sectionNumber) {
// case 1:
// txtSplashTitle.setText(R.string.splash_title_1);
// txtSplashDesc.setText(R.string.splash_desc_1);
// imgSplash.setImageResource(R.drawable.splash_1);
// relativeLayoutSplash.setBackgroundColor(ContextCompat.getColor(getActivity(), R.color.md_blue_grey_500));
// imgSelectedDot1.setVisibility(View.VISIBLE);
// imgSelectedDot2.setVisibility(View.INVISIBLE);
// imgSelectedDot3.setVisibility(View.INVISIBLE);
// break;
// case 2:
// txtSplashTitle.setText(R.string.splash_title_2);
// txtSplashDesc.setText(R.string.splash_desc_2);
// imgSplash.setImageResource(R.drawable.splash_2);
// relativeLayoutSplash.setBackgroundColor(ContextCompat.getColor(getActivity(), R.color.colorAccent));
// imgSelectedDot1.setVisibility(View.INVISIBLE);
// imgSelectedDot2.setVisibility(View.VISIBLE);
// imgSelectedDot3.setVisibility(View.INVISIBLE);
// break;
// case 3:
// txtSplashTitle.setText(R.string.splash_title_3);
// txtSplashDesc.setText(R.string.splash_desc_3);
// imgSplash.setImageResource(R.drawable.splash_3);
// relativeLayoutSplash.setBackgroundColor(ContextCompat.getColor(getActivity(), R.color.colorPrimary));
// imgSelectedDot1.setVisibility(View.INVISIBLE);
// imgSelectedDot2.setVisibility(View.INVISIBLE);
// imgSelectedDot3.setVisibility(View.VISIBLE);
// break;
// }
// }
// }
| import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import com.crazyhitty.chdev.ks.munch.ui.fragments.SplashFragment; | package com.crazyhitty.chdev.ks.munch.ui.adapters;
/**
* Created by Kartik_ch on 12/17/2015.
*/
public class SplashPagerAdapter extends FragmentPagerAdapter {
public SplashPagerAdapter(FragmentManager fm) {
super(fm);
}
@Override
public Fragment getItem(int position) {
// getItem is called to instantiate the fragment for the given page.
// Return a PlaceholderFragment (defined as a static inner class below). | // Path: app/src/main/java/com/crazyhitty/chdev/ks/munch/ui/fragments/SplashFragment.java
// public class SplashFragment extends Fragment {
//
// private static final String ARG_SECTION_NUMBER = "section_number";
// @Bind(R.id.relative_layout_fragment_splash)
// RelativeLayout relativeLayoutSplash;
// @Bind(R.id.text_view_splash_title)
// TextView txtSplashTitle;
// @Bind(R.id.text_view_splash_desc)
// TextView txtSplashDesc;
// @Bind(R.id.image_view_splash)
// ImageView imgSplash;
// @Bind(R.id.image_view_empty_dot_1)
// ImageView imgEmptyDot1;
// @Bind(R.id.image_view_empty_dot_2)
// ImageView imgEmptyDot2;
// @Bind(R.id.image_view_empty_dot_3)
// ImageView imgEmptyDot3;
// @Bind(R.id.image_view_selected_dot_1)
// ImageView imgSelectedDot1;
// @Bind(R.id.image_view_selected_dot_2)
// ImageView imgSelectedDot2;
// @Bind(R.id.image_view_selected_dot_3)
// ImageView imgSelectedDot3;
//
// /**
// * Returns a new instance of this fragment for the given section
// * number.
// */
// public static SplashFragment newInstance(int sectionNumber) {
// SplashFragment fragment = new SplashFragment();
// Bundle args = new Bundle();
// args.putInt(ARG_SECTION_NUMBER, sectionNumber);
// fragment.setArguments(args);
// return fragment;
// }
//
// @Override
// public View onCreateView(LayoutInflater inflater, ViewGroup container,
// Bundle savedInstanceState) {
// View view = inflater.inflate(R.layout.fragment_splash, container, false);
// ButterKnife.bind(this, view);
// return view;
// }
//
// @Override
// public void onActivityCreated(Bundle savedInstanceState) {
// super.onActivityCreated(savedInstanceState);
// int sectionNumber = getArguments().getInt(ARG_SECTION_NUMBER);
// txtSplashTitle.setText(getString(R.string.section_format, sectionNumber));
//
// switch (sectionNumber) {
// case 1:
// txtSplashTitle.setText(R.string.splash_title_1);
// txtSplashDesc.setText(R.string.splash_desc_1);
// imgSplash.setImageResource(R.drawable.splash_1);
// relativeLayoutSplash.setBackgroundColor(ContextCompat.getColor(getActivity(), R.color.md_blue_grey_500));
// imgSelectedDot1.setVisibility(View.VISIBLE);
// imgSelectedDot2.setVisibility(View.INVISIBLE);
// imgSelectedDot3.setVisibility(View.INVISIBLE);
// break;
// case 2:
// txtSplashTitle.setText(R.string.splash_title_2);
// txtSplashDesc.setText(R.string.splash_desc_2);
// imgSplash.setImageResource(R.drawable.splash_2);
// relativeLayoutSplash.setBackgroundColor(ContextCompat.getColor(getActivity(), R.color.colorAccent));
// imgSelectedDot1.setVisibility(View.INVISIBLE);
// imgSelectedDot2.setVisibility(View.VISIBLE);
// imgSelectedDot3.setVisibility(View.INVISIBLE);
// break;
// case 3:
// txtSplashTitle.setText(R.string.splash_title_3);
// txtSplashDesc.setText(R.string.splash_desc_3);
// imgSplash.setImageResource(R.drawable.splash_3);
// relativeLayoutSplash.setBackgroundColor(ContextCompat.getColor(getActivity(), R.color.colorPrimary));
// imgSelectedDot1.setVisibility(View.INVISIBLE);
// imgSelectedDot2.setVisibility(View.INVISIBLE);
// imgSelectedDot3.setVisibility(View.VISIBLE);
// break;
// }
// }
// }
// Path: app/src/main/java/com/crazyhitty/chdev/ks/munch/ui/adapters/SplashPagerAdapter.java
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import com.crazyhitty.chdev.ks.munch.ui.fragments.SplashFragment;
package com.crazyhitty.chdev.ks.munch.ui.adapters;
/**
* Created by Kartik_ch on 12/17/2015.
*/
public class SplashPagerAdapter extends FragmentPagerAdapter {
public SplashPagerAdapter(FragmentManager fm) {
super(fm);
}
@Override
public Fragment getItem(int position) {
// getItem is called to instantiate the fragment for the given page.
// Return a PlaceholderFragment (defined as a static inner class below). | return SplashFragment.newInstance(position + 1); |
crazyhitty/Munch | app/src/main/java/com/crazyhitty/chdev/ks/munch/sources/OnSourcesLoadedListener.java | // Path: app/src/main/java/com/crazyhitty/chdev/ks/munch/models/SourceItem.java
// public class SourceItem {
// private String sourceName, sourceUrl, sourceCategoryName, sourceDateAdded;
// private int sourceCategoryImgId;
//
// public int getSourceCategoryImgId() {
// return sourceCategoryImgId;
// }
//
// public void setSourceCategoryImgId(int sourceCategoryImgId) {
// this.sourceCategoryImgId = sourceCategoryImgId;
// }
//
// public String getSourceName() {
// return sourceName;
// }
//
// public void setSourceName(String sourceName) {
// this.sourceName = sourceName;
// }
//
// public String getSourceUrl() {
// return sourceUrl;
// }
//
// public void setSourceUrl(String sourceUrl) {
// this.sourceUrl = sourceUrl;
// }
//
// public String getSourceDateAdded() {
// return sourceDateAdded;
// }
//
// public void setSourceDateAdded(String sourceDateAdded) {
// this.sourceDateAdded = sourceDateAdded;
// }
//
// public String getSourceCategoryName() {
// return sourceCategoryName;
// }
//
// public void setSourceCategoryName(String sourceCategoryName) {
// this.sourceCategoryName = sourceCategoryName;
// }
// }
| import com.crazyhitty.chdev.ks.munch.models.SourceItem;
import java.util.List; | package com.crazyhitty.chdev.ks.munch.sources;
/**
* Created by Kartik_ch on 11/18/2015.
*/
public interface OnSourcesLoadedListener {
void onSourceLoaded(List<String> sourceNames);
| // Path: app/src/main/java/com/crazyhitty/chdev/ks/munch/models/SourceItem.java
// public class SourceItem {
// private String sourceName, sourceUrl, sourceCategoryName, sourceDateAdded;
// private int sourceCategoryImgId;
//
// public int getSourceCategoryImgId() {
// return sourceCategoryImgId;
// }
//
// public void setSourceCategoryImgId(int sourceCategoryImgId) {
// this.sourceCategoryImgId = sourceCategoryImgId;
// }
//
// public String getSourceName() {
// return sourceName;
// }
//
// public void setSourceName(String sourceName) {
// this.sourceName = sourceName;
// }
//
// public String getSourceUrl() {
// return sourceUrl;
// }
//
// public void setSourceUrl(String sourceUrl) {
// this.sourceUrl = sourceUrl;
// }
//
// public String getSourceDateAdded() {
// return sourceDateAdded;
// }
//
// public void setSourceDateAdded(String sourceDateAdded) {
// this.sourceDateAdded = sourceDateAdded;
// }
//
// public String getSourceCategoryName() {
// return sourceCategoryName;
// }
//
// public void setSourceCategoryName(String sourceCategoryName) {
// this.sourceCategoryName = sourceCategoryName;
// }
// }
// Path: app/src/main/java/com/crazyhitty/chdev/ks/munch/sources/OnSourcesLoadedListener.java
import com.crazyhitty.chdev.ks.munch.models.SourceItem;
import java.util.List;
package com.crazyhitty.chdev.ks.munch.sources;
/**
* Created by Kartik_ch on 11/18/2015.
*/
public interface OnSourcesLoadedListener {
void onSourceLoaded(List<String> sourceNames);
| void onSourceItemsLoaded(List<SourceItem> sourceItems); |
crazyhitty/Munch | app/src/main/java/com/crazyhitty/chdev/ks/munch/archive/ArchivePresenter.java | // Path: app/src/main/java/com/crazyhitty/chdev/ks/munch/models/FeedItem.java
// public class FeedItem {
// private String itemTitle, itemDesc, itemSourceUrl, itemLink, itemImgUrl, itemCategory, itemSource, itemPubDate, itemWebDesc, itemWebDescSync;
// private int itemCategoryImgId, itemBgId;
//
// public String getItemTitle() {
// if (itemTitle == null) {
// return "";
// }
// return itemTitle;
// }
//
// public void setItemTitle(String itemTitle) {
// this.itemTitle = itemTitle;
// }
//
// public String getItemDesc() {
// if (itemDesc == null) {
// return "";
// }
// return itemDesc;
// }
//
// public void setItemDesc(String itemDesc) {
// this.itemDesc = itemDesc;
// }
//
// public String getItemSourceUrl() {
// if (itemSourceUrl == null) {
// return "";
// }
// return itemSourceUrl;
// }
//
// public void setItemSourceUrl(String itemSourceUrl) {
// this.itemSourceUrl = itemSourceUrl;
// }
//
// public String getItemLink() {
// if (itemLink == null) {
// return "";
// }
// return itemLink;
// }
//
// public void setItemLink(String itemLink) {
// this.itemLink = itemLink;
// }
//
// public String getItemImgUrl() {
// if (itemImgUrl == null) {
// return "";
// }
// return itemImgUrl;
// }
//
// public void setItemImgUrl(String itemImgUrl) {
// this.itemImgUrl = itemImgUrl;
// }
//
// public String getItemCategory() {
// if (itemCategory == null) {
// return "";
// }
// return itemCategory;
// }
//
// public void setItemCategory(String itemCategory) {
// this.itemCategory = itemCategory;
// }
//
// public String getItemSource() {
// if (itemSource == null) {
// return "";
// }
// return itemSource;
// }
//
// public void setItemSource(String itemSource) {
// this.itemSource = itemSource;
// }
//
// public String getItemPubDate() {
// if (itemPubDate == null) {
// return "";
// }
// return itemPubDate;
// }
//
// public void setItemPubDate(String itemPubDate) {
// this.itemPubDate = itemPubDate;
// }
//
// public int getItemCategoryImgId() {
// return itemCategoryImgId;
// }
//
// public void setItemCategoryImgId(int itemCategoryImgId) {
// this.itemCategoryImgId = itemCategoryImgId;
// }
//
// public int getItemBgId() {
// return itemBgId;
// }
//
// public void setItemBgId(int itemBgId) {
// this.itemBgId = itemBgId;
// }
//
// public String getItemWebDesc() {
// return itemWebDesc;
// }
//
// public void setItemWebDesc(String itemWebDesc) {
// this.itemWebDesc = itemWebDesc;
// }
//
// public String getItemWebDescSync() {
// return itemWebDescSync;
// }
//
// public void setItemWebDescSync(String itemWebDescSync) {
// this.itemWebDescSync = itemWebDescSync;
// }
// }
| import android.content.Context;
import com.crazyhitty.chdev.ks.munch.models.FeedItem;
import java.util.List; | package com.crazyhitty.chdev.ks.munch.archive;
/**
* Created by Kartik_ch on 12/9/2015.
*/
public class ArchivePresenter implements IArchivePresenter, OnArticleRetrievedListener {
private IArchiveView mView;
private ArchiveInteractor mArchiveInteractor;
public ArchivePresenter(IArchiveView view) {
this.mView = view;
mArchiveInteractor = new ArchiveInteractor();
}
public void attemptArchiveRetrieval(Context context) {
mArchiveInteractor.retrieveArchiveFromDb(this, context);
}
@Override | // Path: app/src/main/java/com/crazyhitty/chdev/ks/munch/models/FeedItem.java
// public class FeedItem {
// private String itemTitle, itemDesc, itemSourceUrl, itemLink, itemImgUrl, itemCategory, itemSource, itemPubDate, itemWebDesc, itemWebDescSync;
// private int itemCategoryImgId, itemBgId;
//
// public String getItemTitle() {
// if (itemTitle == null) {
// return "";
// }
// return itemTitle;
// }
//
// public void setItemTitle(String itemTitle) {
// this.itemTitle = itemTitle;
// }
//
// public String getItemDesc() {
// if (itemDesc == null) {
// return "";
// }
// return itemDesc;
// }
//
// public void setItemDesc(String itemDesc) {
// this.itemDesc = itemDesc;
// }
//
// public String getItemSourceUrl() {
// if (itemSourceUrl == null) {
// return "";
// }
// return itemSourceUrl;
// }
//
// public void setItemSourceUrl(String itemSourceUrl) {
// this.itemSourceUrl = itemSourceUrl;
// }
//
// public String getItemLink() {
// if (itemLink == null) {
// return "";
// }
// return itemLink;
// }
//
// public void setItemLink(String itemLink) {
// this.itemLink = itemLink;
// }
//
// public String getItemImgUrl() {
// if (itemImgUrl == null) {
// return "";
// }
// return itemImgUrl;
// }
//
// public void setItemImgUrl(String itemImgUrl) {
// this.itemImgUrl = itemImgUrl;
// }
//
// public String getItemCategory() {
// if (itemCategory == null) {
// return "";
// }
// return itemCategory;
// }
//
// public void setItemCategory(String itemCategory) {
// this.itemCategory = itemCategory;
// }
//
// public String getItemSource() {
// if (itemSource == null) {
// return "";
// }
// return itemSource;
// }
//
// public void setItemSource(String itemSource) {
// this.itemSource = itemSource;
// }
//
// public String getItemPubDate() {
// if (itemPubDate == null) {
// return "";
// }
// return itemPubDate;
// }
//
// public void setItemPubDate(String itemPubDate) {
// this.itemPubDate = itemPubDate;
// }
//
// public int getItemCategoryImgId() {
// return itemCategoryImgId;
// }
//
// public void setItemCategoryImgId(int itemCategoryImgId) {
// this.itemCategoryImgId = itemCategoryImgId;
// }
//
// public int getItemBgId() {
// return itemBgId;
// }
//
// public void setItemBgId(int itemBgId) {
// this.itemBgId = itemBgId;
// }
//
// public String getItemWebDesc() {
// return itemWebDesc;
// }
//
// public void setItemWebDesc(String itemWebDesc) {
// this.itemWebDesc = itemWebDesc;
// }
//
// public String getItemWebDescSync() {
// return itemWebDescSync;
// }
//
// public void setItemWebDescSync(String itemWebDescSync) {
// this.itemWebDescSync = itemWebDescSync;
// }
// }
// Path: app/src/main/java/com/crazyhitty/chdev/ks/munch/archive/ArchivePresenter.java
import android.content.Context;
import com.crazyhitty.chdev.ks.munch.models.FeedItem;
import java.util.List;
package com.crazyhitty.chdev.ks.munch.archive;
/**
* Created by Kartik_ch on 12/9/2015.
*/
public class ArchivePresenter implements IArchivePresenter, OnArticleRetrievedListener {
private IArchiveView mView;
private ArchiveInteractor mArchiveInteractor;
public ArchivePresenter(IArchiveView view) {
this.mView = view;
mArchiveInteractor = new ArchiveInteractor();
}
public void attemptArchiveRetrieval(Context context) {
mArchiveInteractor.retrieveArchiveFromDb(this, context);
}
@Override | public void onSuccess(List<FeedItem> feedItems) { |
crazyhitty/Munch | app/src/main/java/com/crazyhitty/chdev/ks/munch/feeds/IFeedsPresenter.java | // Path: app/src/main/java/com/crazyhitty/chdev/ks/munch/models/FeedItem.java
// public class FeedItem {
// private String itemTitle, itemDesc, itemSourceUrl, itemLink, itemImgUrl, itemCategory, itemSource, itemPubDate, itemWebDesc, itemWebDescSync;
// private int itemCategoryImgId, itemBgId;
//
// public String getItemTitle() {
// if (itemTitle == null) {
// return "";
// }
// return itemTitle;
// }
//
// public void setItemTitle(String itemTitle) {
// this.itemTitle = itemTitle;
// }
//
// public String getItemDesc() {
// if (itemDesc == null) {
// return "";
// }
// return itemDesc;
// }
//
// public void setItemDesc(String itemDesc) {
// this.itemDesc = itemDesc;
// }
//
// public String getItemSourceUrl() {
// if (itemSourceUrl == null) {
// return "";
// }
// return itemSourceUrl;
// }
//
// public void setItemSourceUrl(String itemSourceUrl) {
// this.itemSourceUrl = itemSourceUrl;
// }
//
// public String getItemLink() {
// if (itemLink == null) {
// return "";
// }
// return itemLink;
// }
//
// public void setItemLink(String itemLink) {
// this.itemLink = itemLink;
// }
//
// public String getItemImgUrl() {
// if (itemImgUrl == null) {
// return "";
// }
// return itemImgUrl;
// }
//
// public void setItemImgUrl(String itemImgUrl) {
// this.itemImgUrl = itemImgUrl;
// }
//
// public String getItemCategory() {
// if (itemCategory == null) {
// return "";
// }
// return itemCategory;
// }
//
// public void setItemCategory(String itemCategory) {
// this.itemCategory = itemCategory;
// }
//
// public String getItemSource() {
// if (itemSource == null) {
// return "";
// }
// return itemSource;
// }
//
// public void setItemSource(String itemSource) {
// this.itemSource = itemSource;
// }
//
// public String getItemPubDate() {
// if (itemPubDate == null) {
// return "";
// }
// return itemPubDate;
// }
//
// public void setItemPubDate(String itemPubDate) {
// this.itemPubDate = itemPubDate;
// }
//
// public int getItemCategoryImgId() {
// return itemCategoryImgId;
// }
//
// public void setItemCategoryImgId(int itemCategoryImgId) {
// this.itemCategoryImgId = itemCategoryImgId;
// }
//
// public int getItemBgId() {
// return itemBgId;
// }
//
// public void setItemBgId(int itemBgId) {
// this.itemBgId = itemBgId;
// }
//
// public String getItemWebDesc() {
// return itemWebDesc;
// }
//
// public void setItemWebDesc(String itemWebDesc) {
// this.itemWebDesc = itemWebDesc;
// }
//
// public String getItemWebDescSync() {
// return itemWebDescSync;
// }
//
// public void setItemWebDescSync(String itemWebDescSync) {
// this.itemWebDescSync = itemWebDescSync;
// }
// }
| import com.crazyhitty.chdev.ks.munch.models.FeedItem; | package com.crazyhitty.chdev.ks.munch.feeds;
/**
* Created by Kartik_ch on 11/4/2015.
*/
public interface IFeedsPresenter {
void attemptFeedLoading();
void attemptFeedLoading(String source);
void attemptFeedLoadingFromDb();
void attemptFeedLoadingFromDbBySource(String source);
void deleteFeeds();
| // Path: app/src/main/java/com/crazyhitty/chdev/ks/munch/models/FeedItem.java
// public class FeedItem {
// private String itemTitle, itemDesc, itemSourceUrl, itemLink, itemImgUrl, itemCategory, itemSource, itemPubDate, itemWebDesc, itemWebDescSync;
// private int itemCategoryImgId, itemBgId;
//
// public String getItemTitle() {
// if (itemTitle == null) {
// return "";
// }
// return itemTitle;
// }
//
// public void setItemTitle(String itemTitle) {
// this.itemTitle = itemTitle;
// }
//
// public String getItemDesc() {
// if (itemDesc == null) {
// return "";
// }
// return itemDesc;
// }
//
// public void setItemDesc(String itemDesc) {
// this.itemDesc = itemDesc;
// }
//
// public String getItemSourceUrl() {
// if (itemSourceUrl == null) {
// return "";
// }
// return itemSourceUrl;
// }
//
// public void setItemSourceUrl(String itemSourceUrl) {
// this.itemSourceUrl = itemSourceUrl;
// }
//
// public String getItemLink() {
// if (itemLink == null) {
// return "";
// }
// return itemLink;
// }
//
// public void setItemLink(String itemLink) {
// this.itemLink = itemLink;
// }
//
// public String getItemImgUrl() {
// if (itemImgUrl == null) {
// return "";
// }
// return itemImgUrl;
// }
//
// public void setItemImgUrl(String itemImgUrl) {
// this.itemImgUrl = itemImgUrl;
// }
//
// public String getItemCategory() {
// if (itemCategory == null) {
// return "";
// }
// return itemCategory;
// }
//
// public void setItemCategory(String itemCategory) {
// this.itemCategory = itemCategory;
// }
//
// public String getItemSource() {
// if (itemSource == null) {
// return "";
// }
// return itemSource;
// }
//
// public void setItemSource(String itemSource) {
// this.itemSource = itemSource;
// }
//
// public String getItemPubDate() {
// if (itemPubDate == null) {
// return "";
// }
// return itemPubDate;
// }
//
// public void setItemPubDate(String itemPubDate) {
// this.itemPubDate = itemPubDate;
// }
//
// public int getItemCategoryImgId() {
// return itemCategoryImgId;
// }
//
// public void setItemCategoryImgId(int itemCategoryImgId) {
// this.itemCategoryImgId = itemCategoryImgId;
// }
//
// public int getItemBgId() {
// return itemBgId;
// }
//
// public void setItemBgId(int itemBgId) {
// this.itemBgId = itemBgId;
// }
//
// public String getItemWebDesc() {
// return itemWebDesc;
// }
//
// public void setItemWebDesc(String itemWebDesc) {
// this.itemWebDesc = itemWebDesc;
// }
//
// public String getItemWebDescSync() {
// return itemWebDescSync;
// }
//
// public void setItemWebDescSync(String itemWebDescSync) {
// this.itemWebDescSync = itemWebDescSync;
// }
// }
// Path: app/src/main/java/com/crazyhitty/chdev/ks/munch/feeds/IFeedsPresenter.java
import com.crazyhitty.chdev.ks.munch.models.FeedItem;
package com.crazyhitty.chdev.ks.munch.feeds;
/**
* Created by Kartik_ch on 11/4/2015.
*/
public interface IFeedsPresenter {
void attemptFeedLoading();
void attemptFeedLoading(String source);
void attemptFeedLoadingFromDb();
void attemptFeedLoadingFromDbBySource(String source);
void deleteFeeds();
| void deleteSelectedFeed(FeedItem feedItem); |
crazyhitty/Munch | app/src/main/java/com/crazyhitty/chdev/ks/munch/article/IArticlePresenter.java | // Path: app/src/main/java/com/crazyhitty/chdev/ks/munch/models/FeedItem.java
// public class FeedItem {
// private String itemTitle, itemDesc, itemSourceUrl, itemLink, itemImgUrl, itemCategory, itemSource, itemPubDate, itemWebDesc, itemWebDescSync;
// private int itemCategoryImgId, itemBgId;
//
// public String getItemTitle() {
// if (itemTitle == null) {
// return "";
// }
// return itemTitle;
// }
//
// public void setItemTitle(String itemTitle) {
// this.itemTitle = itemTitle;
// }
//
// public String getItemDesc() {
// if (itemDesc == null) {
// return "";
// }
// return itemDesc;
// }
//
// public void setItemDesc(String itemDesc) {
// this.itemDesc = itemDesc;
// }
//
// public String getItemSourceUrl() {
// if (itemSourceUrl == null) {
// return "";
// }
// return itemSourceUrl;
// }
//
// public void setItemSourceUrl(String itemSourceUrl) {
// this.itemSourceUrl = itemSourceUrl;
// }
//
// public String getItemLink() {
// if (itemLink == null) {
// return "";
// }
// return itemLink;
// }
//
// public void setItemLink(String itemLink) {
// this.itemLink = itemLink;
// }
//
// public String getItemImgUrl() {
// if (itemImgUrl == null) {
// return "";
// }
// return itemImgUrl;
// }
//
// public void setItemImgUrl(String itemImgUrl) {
// this.itemImgUrl = itemImgUrl;
// }
//
// public String getItemCategory() {
// if (itemCategory == null) {
// return "";
// }
// return itemCategory;
// }
//
// public void setItemCategory(String itemCategory) {
// this.itemCategory = itemCategory;
// }
//
// public String getItemSource() {
// if (itemSource == null) {
// return "";
// }
// return itemSource;
// }
//
// public void setItemSource(String itemSource) {
// this.itemSource = itemSource;
// }
//
// public String getItemPubDate() {
// if (itemPubDate == null) {
// return "";
// }
// return itemPubDate;
// }
//
// public void setItemPubDate(String itemPubDate) {
// this.itemPubDate = itemPubDate;
// }
//
// public int getItemCategoryImgId() {
// return itemCategoryImgId;
// }
//
// public void setItemCategoryImgId(int itemCategoryImgId) {
// this.itemCategoryImgId = itemCategoryImgId;
// }
//
// public int getItemBgId() {
// return itemBgId;
// }
//
// public void setItemBgId(int itemBgId) {
// this.itemBgId = itemBgId;
// }
//
// public String getItemWebDesc() {
// return itemWebDesc;
// }
//
// public void setItemWebDesc(String itemWebDesc) {
// this.itemWebDesc = itemWebDesc;
// }
//
// public String getItemWebDescSync() {
// return itemWebDescSync;
// }
//
// public void setItemWebDescSync(String itemWebDescSync) {
// this.itemWebDescSync = itemWebDescSync;
// }
// }
| import com.crazyhitty.chdev.ks.munch.models.FeedItem; | package com.crazyhitty.chdev.ks.munch.article;
/**
* Created by Kartik_ch on 12/2/2015.
*/
public interface IArticlePresenter {
void attemptArticleLoading(String url);
| // Path: app/src/main/java/com/crazyhitty/chdev/ks/munch/models/FeedItem.java
// public class FeedItem {
// private String itemTitle, itemDesc, itemSourceUrl, itemLink, itemImgUrl, itemCategory, itemSource, itemPubDate, itemWebDesc, itemWebDescSync;
// private int itemCategoryImgId, itemBgId;
//
// public String getItemTitle() {
// if (itemTitle == null) {
// return "";
// }
// return itemTitle;
// }
//
// public void setItemTitle(String itemTitle) {
// this.itemTitle = itemTitle;
// }
//
// public String getItemDesc() {
// if (itemDesc == null) {
// return "";
// }
// return itemDesc;
// }
//
// public void setItemDesc(String itemDesc) {
// this.itemDesc = itemDesc;
// }
//
// public String getItemSourceUrl() {
// if (itemSourceUrl == null) {
// return "";
// }
// return itemSourceUrl;
// }
//
// public void setItemSourceUrl(String itemSourceUrl) {
// this.itemSourceUrl = itemSourceUrl;
// }
//
// public String getItemLink() {
// if (itemLink == null) {
// return "";
// }
// return itemLink;
// }
//
// public void setItemLink(String itemLink) {
// this.itemLink = itemLink;
// }
//
// public String getItemImgUrl() {
// if (itemImgUrl == null) {
// return "";
// }
// return itemImgUrl;
// }
//
// public void setItemImgUrl(String itemImgUrl) {
// this.itemImgUrl = itemImgUrl;
// }
//
// public String getItemCategory() {
// if (itemCategory == null) {
// return "";
// }
// return itemCategory;
// }
//
// public void setItemCategory(String itemCategory) {
// this.itemCategory = itemCategory;
// }
//
// public String getItemSource() {
// if (itemSource == null) {
// return "";
// }
// return itemSource;
// }
//
// public void setItemSource(String itemSource) {
// this.itemSource = itemSource;
// }
//
// public String getItemPubDate() {
// if (itemPubDate == null) {
// return "";
// }
// return itemPubDate;
// }
//
// public void setItemPubDate(String itemPubDate) {
// this.itemPubDate = itemPubDate;
// }
//
// public int getItemCategoryImgId() {
// return itemCategoryImgId;
// }
//
// public void setItemCategoryImgId(int itemCategoryImgId) {
// this.itemCategoryImgId = itemCategoryImgId;
// }
//
// public int getItemBgId() {
// return itemBgId;
// }
//
// public void setItemBgId(int itemBgId) {
// this.itemBgId = itemBgId;
// }
//
// public String getItemWebDesc() {
// return itemWebDesc;
// }
//
// public void setItemWebDesc(String itemWebDesc) {
// this.itemWebDesc = itemWebDesc;
// }
//
// public String getItemWebDescSync() {
// return itemWebDescSync;
// }
//
// public void setItemWebDescSync(String itemWebDescSync) {
// this.itemWebDescSync = itemWebDescSync;
// }
// }
// Path: app/src/main/java/com/crazyhitty/chdev/ks/munch/article/IArticlePresenter.java
import com.crazyhitty.chdev.ks.munch.models.FeedItem;
package com.crazyhitty.chdev.ks.munch.article;
/**
* Created by Kartik_ch on 12/2/2015.
*/
public interface IArticlePresenter {
void attemptArticleLoading(String url);
| void archiveArticle(FeedItem feedItem, String article); |
crazyhitty/Munch | app/src/main/java/com/crazyhitty/chdev/ks/munch/receivers/SyncArticlesReceiver.java | // Path: app/src/main/java/com/crazyhitty/chdev/ks/munch/services/SyncArticlesIntentService.java
// public class SyncArticlesIntentService extends IntentService {
// private static final int NOTIFICATION_ID = 1346;
// public static boolean STATUS = true;
// private MaterialDialog sSyncDialog;
// private NotificationCompat.Builder mBuilder;
// private NotificationManager mNotificationManager;
//
// public SyncArticlesIntentService() {
// super("SyncArticlesIntentService");
// }
//
// private void initNotification() {
// //Create an Intent for the BroadcastReceiver
// Intent buttonIntent = new Intent(this, SyncArticlesReceiver.class);
// buttonIntent.putExtra("notificationId", NOTIFICATION_ID);
//
// //Create the PendingIntent
// PendingIntent actionPendingIntent = PendingIntent.getBroadcast(this, 0, buttonIntent, 0);
//
// mBuilder = new NotificationCompat.Builder(this);
// mBuilder.setSmallIcon(R.drawable.ic_sync_24dp);
// mBuilder.setContentTitle(getString(R.string.syncing_feeds));
// mBuilder.setContentText(getString(R.string.downloading_feeds));
// mBuilder.setProgress(100, 0, true);
// mBuilder.addAction(R.drawable.ic_close_24dp, getString(R.string.cancel), actionPendingIntent);
// mBuilder.setOngoing(true);
//
// mNotificationManager =
// (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
// // mId allows you to update the notification later on.
// mNotificationManager.notify(NOTIFICATION_ID, mBuilder.build());
// }
//
// private void initCompleteNotification() {
// mBuilder = null;
// mBuilder = new NotificationCompat.Builder(this);
// mBuilder.setOngoing(false);
// mBuilder.setSmallIcon(R.drawable.ic_done_all_24dp);
// mBuilder.setContentTitle(getString(R.string.feeds_synced));
// mBuilder.setContentText(getString(R.string.download_complete));
// Notification notification = mBuilder.build();
// notification.flags = Notification.FLAG_AUTO_CANCEL;
// mNotificationManager.notify(NOTIFICATION_ID, notification);
// }
//
// @Override
// protected void onHandleIntent(Intent intent) {
// if (intent != null) {
// initNotification();
// final String[] articleLinks;
// try {
// STATUS = true;
// articleLinks = new DatabaseUtil(this).getFeedLinks();
// handleActionStartSync(articleLinks);
// } catch (Exception e) {
// e.printStackTrace();
// }
// }
// }
//
// private void handleActionStartSync(String[] articleLinks) {
// if (articleLinks != null) {
// parseWebArticle(articleLinks, 0);
// }
// }
//
// private void updateNotification(int percentageDone) {
// mBuilder.setProgress(100, percentageDone, false);
// mNotificationManager.notify(NOTIFICATION_ID, mBuilder.build());
// }
//
// private int getPercentage(int position, int items) {
// return (position * 100) / items;
// }
//
// private void parseWebArticle(String[] links, int position) {
// if (position != links.length - 1 && STATUS) {
// try {
// Document htmlDocument = Jsoup.connect(links[position]).get();
// Elements paragraphs = htmlDocument.select("p");
// String body = "";
// for (Element paragraph : paragraphs) {
// String para = paragraph.text().trim();
// if (!para.isEmpty()) {
// body += para + "\n\n";
// }
// }
// try {
// //FeedItem feedItem = new DatabaseUtil(this).getFeedByLink(links[position]);
// FeedItem feedItem = new FeedItem();
// feedItem.setItemLink(links[position]);
// feedItem.setItemWebDescSync(body);
// DatabaseUtil databaseUtil = new DatabaseUtil(this);
// databaseUtil.saveFeedArticleDesc(feedItem);
// databaseUtil.saveArticle(databaseUtil.getFeedByLink(links[position]), feedItem.getItemWebDescSync());
// } catch (Exception e) {
// e.printStackTrace();
// }
// } catch (IOException e) {
// e.printStackTrace();
// }
// //updateNotification(getPercentage(position, links.length));
// parseWebArticle(links, position + 1);
// } else {
// //stop service here
// stopSelf();
// initCompleteNotification();
// //mNotificationManager.cancel(NOTIFICATION_ID);
// }
// }
// }
| import android.app.NotificationManager;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import com.crazyhitty.chdev.ks.munch.services.SyncArticlesIntentService; | package com.crazyhitty.chdev.ks.munch.receivers;
public class SyncArticlesReceiver extends BroadcastReceiver {
public SyncArticlesReceiver() {
}
@Override
public void onReceive(Context context, Intent intent) {
int notificationId = intent.getIntExtra("notificationId", 0);
//Cancel the notification
NotificationManager manager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
manager.cancel(notificationId);
| // Path: app/src/main/java/com/crazyhitty/chdev/ks/munch/services/SyncArticlesIntentService.java
// public class SyncArticlesIntentService extends IntentService {
// private static final int NOTIFICATION_ID = 1346;
// public static boolean STATUS = true;
// private MaterialDialog sSyncDialog;
// private NotificationCompat.Builder mBuilder;
// private NotificationManager mNotificationManager;
//
// public SyncArticlesIntentService() {
// super("SyncArticlesIntentService");
// }
//
// private void initNotification() {
// //Create an Intent for the BroadcastReceiver
// Intent buttonIntent = new Intent(this, SyncArticlesReceiver.class);
// buttonIntent.putExtra("notificationId", NOTIFICATION_ID);
//
// //Create the PendingIntent
// PendingIntent actionPendingIntent = PendingIntent.getBroadcast(this, 0, buttonIntent, 0);
//
// mBuilder = new NotificationCompat.Builder(this);
// mBuilder.setSmallIcon(R.drawable.ic_sync_24dp);
// mBuilder.setContentTitle(getString(R.string.syncing_feeds));
// mBuilder.setContentText(getString(R.string.downloading_feeds));
// mBuilder.setProgress(100, 0, true);
// mBuilder.addAction(R.drawable.ic_close_24dp, getString(R.string.cancel), actionPendingIntent);
// mBuilder.setOngoing(true);
//
// mNotificationManager =
// (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
// // mId allows you to update the notification later on.
// mNotificationManager.notify(NOTIFICATION_ID, mBuilder.build());
// }
//
// private void initCompleteNotification() {
// mBuilder = null;
// mBuilder = new NotificationCompat.Builder(this);
// mBuilder.setOngoing(false);
// mBuilder.setSmallIcon(R.drawable.ic_done_all_24dp);
// mBuilder.setContentTitle(getString(R.string.feeds_synced));
// mBuilder.setContentText(getString(R.string.download_complete));
// Notification notification = mBuilder.build();
// notification.flags = Notification.FLAG_AUTO_CANCEL;
// mNotificationManager.notify(NOTIFICATION_ID, notification);
// }
//
// @Override
// protected void onHandleIntent(Intent intent) {
// if (intent != null) {
// initNotification();
// final String[] articleLinks;
// try {
// STATUS = true;
// articleLinks = new DatabaseUtil(this).getFeedLinks();
// handleActionStartSync(articleLinks);
// } catch (Exception e) {
// e.printStackTrace();
// }
// }
// }
//
// private void handleActionStartSync(String[] articleLinks) {
// if (articleLinks != null) {
// parseWebArticle(articleLinks, 0);
// }
// }
//
// private void updateNotification(int percentageDone) {
// mBuilder.setProgress(100, percentageDone, false);
// mNotificationManager.notify(NOTIFICATION_ID, mBuilder.build());
// }
//
// private int getPercentage(int position, int items) {
// return (position * 100) / items;
// }
//
// private void parseWebArticle(String[] links, int position) {
// if (position != links.length - 1 && STATUS) {
// try {
// Document htmlDocument = Jsoup.connect(links[position]).get();
// Elements paragraphs = htmlDocument.select("p");
// String body = "";
// for (Element paragraph : paragraphs) {
// String para = paragraph.text().trim();
// if (!para.isEmpty()) {
// body += para + "\n\n";
// }
// }
// try {
// //FeedItem feedItem = new DatabaseUtil(this).getFeedByLink(links[position]);
// FeedItem feedItem = new FeedItem();
// feedItem.setItemLink(links[position]);
// feedItem.setItemWebDescSync(body);
// DatabaseUtil databaseUtil = new DatabaseUtil(this);
// databaseUtil.saveFeedArticleDesc(feedItem);
// databaseUtil.saveArticle(databaseUtil.getFeedByLink(links[position]), feedItem.getItemWebDescSync());
// } catch (Exception e) {
// e.printStackTrace();
// }
// } catch (IOException e) {
// e.printStackTrace();
// }
// //updateNotification(getPercentage(position, links.length));
// parseWebArticle(links, position + 1);
// } else {
// //stop service here
// stopSelf();
// initCompleteNotification();
// //mNotificationManager.cancel(NOTIFICATION_ID);
// }
// }
// }
// Path: app/src/main/java/com/crazyhitty/chdev/ks/munch/receivers/SyncArticlesReceiver.java
import android.app.NotificationManager;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import com.crazyhitty.chdev.ks.munch.services.SyncArticlesIntentService;
package com.crazyhitty.chdev.ks.munch.receivers;
public class SyncArticlesReceiver extends BroadcastReceiver {
public SyncArticlesReceiver() {
}
@Override
public void onReceive(Context context, Intent intent) {
int notificationId = intent.getIntExtra("notificationId", 0);
//Cancel the notification
NotificationManager manager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
manager.cancel(notificationId);
| SyncArticlesIntentService.STATUS = false; |
crazyhitty/Munch | app/src/main/java/com/crazyhitty/chdev/ks/munch/ui/views/CustomCheckBoxListPreferenceDialog.java | // Path: app/src/main/java/com/crazyhitty/chdev/ks/munch/curatedfeeds/CuratedFeedsPresenter.java
// public class CuratedFeedsPresenter implements ICuratedFeedsPresenter, OnCuratedFeedsRetrievedListener {
// private ICuratedFeedsView mView;
//
// public CuratedFeedsPresenter(ICuratedFeedsView mView) {
// this.mView = mView;
// }
//
// public void attemptCuratedFeedsLoading(Context context) {
// CuratedFeedsInteractor curatedFeedsInteractor = new CuratedFeedsInteractor();
// curatedFeedsInteractor.fetchCuratedFeedsFromServer(this, context);
// }
//
// @Override
// public void onSuccess(List<SourceItem> sourceItems) {
// mView.onFeedsLoaded(sourceItems);
// }
//
// @Override
// public void onFailure(String message) {
// mView.onFeedsLoadingFailure(message);
// }
// }
//
// Path: app/src/main/java/com/crazyhitty/chdev/ks/munch/curatedfeeds/ICuratedFeedsView.java
// public interface ICuratedFeedsView {
// void onFeedsLoaded(List<SourceItem> sourceItems);
//
// void onFeedsLoadingFailure(String message);
// }
//
// Path: app/src/main/java/com/crazyhitty/chdev/ks/munch/models/SourceItem.java
// public class SourceItem {
// private String sourceName, sourceUrl, sourceCategoryName, sourceDateAdded;
// private int sourceCategoryImgId;
//
// public int getSourceCategoryImgId() {
// return sourceCategoryImgId;
// }
//
// public void setSourceCategoryImgId(int sourceCategoryImgId) {
// this.sourceCategoryImgId = sourceCategoryImgId;
// }
//
// public String getSourceName() {
// return sourceName;
// }
//
// public void setSourceName(String sourceName) {
// this.sourceName = sourceName;
// }
//
// public String getSourceUrl() {
// return sourceUrl;
// }
//
// public void setSourceUrl(String sourceUrl) {
// this.sourceUrl = sourceUrl;
// }
//
// public String getSourceDateAdded() {
// return sourceDateAdded;
// }
//
// public void setSourceDateAdded(String sourceDateAdded) {
// this.sourceDateAdded = sourceDateAdded;
// }
//
// public String getSourceCategoryName() {
// return sourceCategoryName;
// }
//
// public void setSourceCategoryName(String sourceCategoryName) {
// this.sourceCategoryName = sourceCategoryName;
// }
// }
| import android.content.Context;
import android.content.SharedPreferences;
import android.preference.MultiSelectListPreference;
import android.preference.Preference;
import android.preference.PreferenceManager;
import android.util.AttributeSet;
import android.util.Log;
import android.widget.Toast;
import com.crazyhitty.chdev.ks.munch.R;
import com.crazyhitty.chdev.ks.munch.curatedfeeds.CuratedFeedsPresenter;
import com.crazyhitty.chdev.ks.munch.curatedfeeds.ICuratedFeedsView;
import com.crazyhitty.chdev.ks.munch.models.SourceItem;
import java.util.List;
import java.util.Set; | package com.crazyhitty.chdev.ks.munch.ui.views;
/**
* Created by Kartik_ch on 12/29/2015.
*/
public class CustomCheckBoxListPreferenceDialog extends MultiSelectListPreference implements ICuratedFeedsView, Preference.OnPreferenceClickListener {
private CuratedFeedsPresenter mCuratedFeedsPresenter;
public CustomCheckBoxListPreferenceDialog(Context context, AttributeSet attrs) {
super(context, attrs);
setOnPreferenceClickListener(this);
if (mCuratedFeedsPresenter == null) {
mCuratedFeedsPresenter = new CuratedFeedsPresenter(this);
}
mCuratedFeedsPresenter.attemptCuratedFeedsLoading(getContext());
}
@Override | // Path: app/src/main/java/com/crazyhitty/chdev/ks/munch/curatedfeeds/CuratedFeedsPresenter.java
// public class CuratedFeedsPresenter implements ICuratedFeedsPresenter, OnCuratedFeedsRetrievedListener {
// private ICuratedFeedsView mView;
//
// public CuratedFeedsPresenter(ICuratedFeedsView mView) {
// this.mView = mView;
// }
//
// public void attemptCuratedFeedsLoading(Context context) {
// CuratedFeedsInteractor curatedFeedsInteractor = new CuratedFeedsInteractor();
// curatedFeedsInteractor.fetchCuratedFeedsFromServer(this, context);
// }
//
// @Override
// public void onSuccess(List<SourceItem> sourceItems) {
// mView.onFeedsLoaded(sourceItems);
// }
//
// @Override
// public void onFailure(String message) {
// mView.onFeedsLoadingFailure(message);
// }
// }
//
// Path: app/src/main/java/com/crazyhitty/chdev/ks/munch/curatedfeeds/ICuratedFeedsView.java
// public interface ICuratedFeedsView {
// void onFeedsLoaded(List<SourceItem> sourceItems);
//
// void onFeedsLoadingFailure(String message);
// }
//
// Path: app/src/main/java/com/crazyhitty/chdev/ks/munch/models/SourceItem.java
// public class SourceItem {
// private String sourceName, sourceUrl, sourceCategoryName, sourceDateAdded;
// private int sourceCategoryImgId;
//
// public int getSourceCategoryImgId() {
// return sourceCategoryImgId;
// }
//
// public void setSourceCategoryImgId(int sourceCategoryImgId) {
// this.sourceCategoryImgId = sourceCategoryImgId;
// }
//
// public String getSourceName() {
// return sourceName;
// }
//
// public void setSourceName(String sourceName) {
// this.sourceName = sourceName;
// }
//
// public String getSourceUrl() {
// return sourceUrl;
// }
//
// public void setSourceUrl(String sourceUrl) {
// this.sourceUrl = sourceUrl;
// }
//
// public String getSourceDateAdded() {
// return sourceDateAdded;
// }
//
// public void setSourceDateAdded(String sourceDateAdded) {
// this.sourceDateAdded = sourceDateAdded;
// }
//
// public String getSourceCategoryName() {
// return sourceCategoryName;
// }
//
// public void setSourceCategoryName(String sourceCategoryName) {
// this.sourceCategoryName = sourceCategoryName;
// }
// }
// Path: app/src/main/java/com/crazyhitty/chdev/ks/munch/ui/views/CustomCheckBoxListPreferenceDialog.java
import android.content.Context;
import android.content.SharedPreferences;
import android.preference.MultiSelectListPreference;
import android.preference.Preference;
import android.preference.PreferenceManager;
import android.util.AttributeSet;
import android.util.Log;
import android.widget.Toast;
import com.crazyhitty.chdev.ks.munch.R;
import com.crazyhitty.chdev.ks.munch.curatedfeeds.CuratedFeedsPresenter;
import com.crazyhitty.chdev.ks.munch.curatedfeeds.ICuratedFeedsView;
import com.crazyhitty.chdev.ks.munch.models.SourceItem;
import java.util.List;
import java.util.Set;
package com.crazyhitty.chdev.ks.munch.ui.views;
/**
* Created by Kartik_ch on 12/29/2015.
*/
public class CustomCheckBoxListPreferenceDialog extends MultiSelectListPreference implements ICuratedFeedsView, Preference.OnPreferenceClickListener {
private CuratedFeedsPresenter mCuratedFeedsPresenter;
public CustomCheckBoxListPreferenceDialog(Context context, AttributeSet attrs) {
super(context, attrs);
setOnPreferenceClickListener(this);
if (mCuratedFeedsPresenter == null) {
mCuratedFeedsPresenter = new CuratedFeedsPresenter(this);
}
mCuratedFeedsPresenter.attemptCuratedFeedsLoading(getContext());
}
@Override | public void onFeedsLoaded(List<SourceItem> sourceItems) { |
crazyhitty/Munch | app/src/main/java/com/crazyhitty/chdev/ks/munch/curatedfeeds/CuratedFeedsPresenter.java | // Path: app/src/main/java/com/crazyhitty/chdev/ks/munch/models/SourceItem.java
// public class SourceItem {
// private String sourceName, sourceUrl, sourceCategoryName, sourceDateAdded;
// private int sourceCategoryImgId;
//
// public int getSourceCategoryImgId() {
// return sourceCategoryImgId;
// }
//
// public void setSourceCategoryImgId(int sourceCategoryImgId) {
// this.sourceCategoryImgId = sourceCategoryImgId;
// }
//
// public String getSourceName() {
// return sourceName;
// }
//
// public void setSourceName(String sourceName) {
// this.sourceName = sourceName;
// }
//
// public String getSourceUrl() {
// return sourceUrl;
// }
//
// public void setSourceUrl(String sourceUrl) {
// this.sourceUrl = sourceUrl;
// }
//
// public String getSourceDateAdded() {
// return sourceDateAdded;
// }
//
// public void setSourceDateAdded(String sourceDateAdded) {
// this.sourceDateAdded = sourceDateAdded;
// }
//
// public String getSourceCategoryName() {
// return sourceCategoryName;
// }
//
// public void setSourceCategoryName(String sourceCategoryName) {
// this.sourceCategoryName = sourceCategoryName;
// }
// }
| import android.content.Context;
import com.crazyhitty.chdev.ks.munch.models.SourceItem;
import java.util.List; | package com.crazyhitty.chdev.ks.munch.curatedfeeds;
/**
* Created by Kartik_ch on 1/3/2016.
*/
public class CuratedFeedsPresenter implements ICuratedFeedsPresenter, OnCuratedFeedsRetrievedListener {
private ICuratedFeedsView mView;
public CuratedFeedsPresenter(ICuratedFeedsView mView) {
this.mView = mView;
}
public void attemptCuratedFeedsLoading(Context context) {
CuratedFeedsInteractor curatedFeedsInteractor = new CuratedFeedsInteractor();
curatedFeedsInteractor.fetchCuratedFeedsFromServer(this, context);
}
@Override | // Path: app/src/main/java/com/crazyhitty/chdev/ks/munch/models/SourceItem.java
// public class SourceItem {
// private String sourceName, sourceUrl, sourceCategoryName, sourceDateAdded;
// private int sourceCategoryImgId;
//
// public int getSourceCategoryImgId() {
// return sourceCategoryImgId;
// }
//
// public void setSourceCategoryImgId(int sourceCategoryImgId) {
// this.sourceCategoryImgId = sourceCategoryImgId;
// }
//
// public String getSourceName() {
// return sourceName;
// }
//
// public void setSourceName(String sourceName) {
// this.sourceName = sourceName;
// }
//
// public String getSourceUrl() {
// return sourceUrl;
// }
//
// public void setSourceUrl(String sourceUrl) {
// this.sourceUrl = sourceUrl;
// }
//
// public String getSourceDateAdded() {
// return sourceDateAdded;
// }
//
// public void setSourceDateAdded(String sourceDateAdded) {
// this.sourceDateAdded = sourceDateAdded;
// }
//
// public String getSourceCategoryName() {
// return sourceCategoryName;
// }
//
// public void setSourceCategoryName(String sourceCategoryName) {
// this.sourceCategoryName = sourceCategoryName;
// }
// }
// Path: app/src/main/java/com/crazyhitty/chdev/ks/munch/curatedfeeds/CuratedFeedsPresenter.java
import android.content.Context;
import com.crazyhitty.chdev.ks.munch.models.SourceItem;
import java.util.List;
package com.crazyhitty.chdev.ks.munch.curatedfeeds;
/**
* Created by Kartik_ch on 1/3/2016.
*/
public class CuratedFeedsPresenter implements ICuratedFeedsPresenter, OnCuratedFeedsRetrievedListener {
private ICuratedFeedsView mView;
public CuratedFeedsPresenter(ICuratedFeedsView mView) {
this.mView = mView;
}
public void attemptCuratedFeedsLoading(Context context) {
CuratedFeedsInteractor curatedFeedsInteractor = new CuratedFeedsInteractor();
curatedFeedsInteractor.fetchCuratedFeedsFromServer(this, context);
}
@Override | public void onSuccess(List<SourceItem> sourceItems) { |
crazyhitty/Munch | app/src/main/java/com/crazyhitty/chdev/ks/munch/article/ArticlePresenter.java | // Path: app/src/main/java/com/crazyhitty/chdev/ks/munch/models/FeedItem.java
// public class FeedItem {
// private String itemTitle, itemDesc, itemSourceUrl, itemLink, itemImgUrl, itemCategory, itemSource, itemPubDate, itemWebDesc, itemWebDescSync;
// private int itemCategoryImgId, itemBgId;
//
// public String getItemTitle() {
// if (itemTitle == null) {
// return "";
// }
// return itemTitle;
// }
//
// public void setItemTitle(String itemTitle) {
// this.itemTitle = itemTitle;
// }
//
// public String getItemDesc() {
// if (itemDesc == null) {
// return "";
// }
// return itemDesc;
// }
//
// public void setItemDesc(String itemDesc) {
// this.itemDesc = itemDesc;
// }
//
// public String getItemSourceUrl() {
// if (itemSourceUrl == null) {
// return "";
// }
// return itemSourceUrl;
// }
//
// public void setItemSourceUrl(String itemSourceUrl) {
// this.itemSourceUrl = itemSourceUrl;
// }
//
// public String getItemLink() {
// if (itemLink == null) {
// return "";
// }
// return itemLink;
// }
//
// public void setItemLink(String itemLink) {
// this.itemLink = itemLink;
// }
//
// public String getItemImgUrl() {
// if (itemImgUrl == null) {
// return "";
// }
// return itemImgUrl;
// }
//
// public void setItemImgUrl(String itemImgUrl) {
// this.itemImgUrl = itemImgUrl;
// }
//
// public String getItemCategory() {
// if (itemCategory == null) {
// return "";
// }
// return itemCategory;
// }
//
// public void setItemCategory(String itemCategory) {
// this.itemCategory = itemCategory;
// }
//
// public String getItemSource() {
// if (itemSource == null) {
// return "";
// }
// return itemSource;
// }
//
// public void setItemSource(String itemSource) {
// this.itemSource = itemSource;
// }
//
// public String getItemPubDate() {
// if (itemPubDate == null) {
// return "";
// }
// return itemPubDate;
// }
//
// public void setItemPubDate(String itemPubDate) {
// this.itemPubDate = itemPubDate;
// }
//
// public int getItemCategoryImgId() {
// return itemCategoryImgId;
// }
//
// public void setItemCategoryImgId(int itemCategoryImgId) {
// this.itemCategoryImgId = itemCategoryImgId;
// }
//
// public int getItemBgId() {
// return itemBgId;
// }
//
// public void setItemBgId(int itemBgId) {
// this.itemBgId = itemBgId;
// }
//
// public String getItemWebDesc() {
// return itemWebDesc;
// }
//
// public void setItemWebDesc(String itemWebDesc) {
// this.itemWebDesc = itemWebDesc;
// }
//
// public String getItemWebDescSync() {
// return itemWebDescSync;
// }
//
// public void setItemWebDescSync(String itemWebDescSync) {
// this.itemWebDescSync = itemWebDescSync;
// }
// }
| import android.content.Context;
import com.afollestad.materialdialogs.DialogAction;
import com.afollestad.materialdialogs.MaterialDialog;
import com.crazyhitty.chdev.ks.munch.R;
import com.crazyhitty.chdev.ks.munch.models.FeedItem; | package com.crazyhitty.chdev.ks.munch.article;
/**
* Created by Kartik_ch on 12/2/2015.
*/
public class ArticlePresenter implements IArticlePresenter, OnArticleLoadedListener, OnArticleArchivedListener, OnArticleRemoveListener {
private Context mContext;
private IArticleView mView;
private ArticleInteractor mArticleInteractor;
public ArticlePresenter(Context context, IArticleView view) {
this.mContext = context;
this.mView = view;
this.mArticleInteractor = new ArticleInteractor();
}
public void attemptArticleLoading(String url) {
mArticleInteractor.loadArticleAsync(this, mContext, url);
}
@Override
public void onSuccess(String message, String articleBody) {
mView.onArticleLoaded(articleBody);
}
@Override
public void onFailure(String message) {
mView.onArticleFailedToLoad(message);
}
| // Path: app/src/main/java/com/crazyhitty/chdev/ks/munch/models/FeedItem.java
// public class FeedItem {
// private String itemTitle, itemDesc, itemSourceUrl, itemLink, itemImgUrl, itemCategory, itemSource, itemPubDate, itemWebDesc, itemWebDescSync;
// private int itemCategoryImgId, itemBgId;
//
// public String getItemTitle() {
// if (itemTitle == null) {
// return "";
// }
// return itemTitle;
// }
//
// public void setItemTitle(String itemTitle) {
// this.itemTitle = itemTitle;
// }
//
// public String getItemDesc() {
// if (itemDesc == null) {
// return "";
// }
// return itemDesc;
// }
//
// public void setItemDesc(String itemDesc) {
// this.itemDesc = itemDesc;
// }
//
// public String getItemSourceUrl() {
// if (itemSourceUrl == null) {
// return "";
// }
// return itemSourceUrl;
// }
//
// public void setItemSourceUrl(String itemSourceUrl) {
// this.itemSourceUrl = itemSourceUrl;
// }
//
// public String getItemLink() {
// if (itemLink == null) {
// return "";
// }
// return itemLink;
// }
//
// public void setItemLink(String itemLink) {
// this.itemLink = itemLink;
// }
//
// public String getItemImgUrl() {
// if (itemImgUrl == null) {
// return "";
// }
// return itemImgUrl;
// }
//
// public void setItemImgUrl(String itemImgUrl) {
// this.itemImgUrl = itemImgUrl;
// }
//
// public String getItemCategory() {
// if (itemCategory == null) {
// return "";
// }
// return itemCategory;
// }
//
// public void setItemCategory(String itemCategory) {
// this.itemCategory = itemCategory;
// }
//
// public String getItemSource() {
// if (itemSource == null) {
// return "";
// }
// return itemSource;
// }
//
// public void setItemSource(String itemSource) {
// this.itemSource = itemSource;
// }
//
// public String getItemPubDate() {
// if (itemPubDate == null) {
// return "";
// }
// return itemPubDate;
// }
//
// public void setItemPubDate(String itemPubDate) {
// this.itemPubDate = itemPubDate;
// }
//
// public int getItemCategoryImgId() {
// return itemCategoryImgId;
// }
//
// public void setItemCategoryImgId(int itemCategoryImgId) {
// this.itemCategoryImgId = itemCategoryImgId;
// }
//
// public int getItemBgId() {
// return itemBgId;
// }
//
// public void setItemBgId(int itemBgId) {
// this.itemBgId = itemBgId;
// }
//
// public String getItemWebDesc() {
// return itemWebDesc;
// }
//
// public void setItemWebDesc(String itemWebDesc) {
// this.itemWebDesc = itemWebDesc;
// }
//
// public String getItemWebDescSync() {
// return itemWebDescSync;
// }
//
// public void setItemWebDescSync(String itemWebDescSync) {
// this.itemWebDescSync = itemWebDescSync;
// }
// }
// Path: app/src/main/java/com/crazyhitty/chdev/ks/munch/article/ArticlePresenter.java
import android.content.Context;
import com.afollestad.materialdialogs.DialogAction;
import com.afollestad.materialdialogs.MaterialDialog;
import com.crazyhitty.chdev.ks.munch.R;
import com.crazyhitty.chdev.ks.munch.models.FeedItem;
package com.crazyhitty.chdev.ks.munch.article;
/**
* Created by Kartik_ch on 12/2/2015.
*/
public class ArticlePresenter implements IArticlePresenter, OnArticleLoadedListener, OnArticleArchivedListener, OnArticleRemoveListener {
private Context mContext;
private IArticleView mView;
private ArticleInteractor mArticleInteractor;
public ArticlePresenter(Context context, IArticleView view) {
this.mContext = context;
this.mView = view;
this.mArticleInteractor = new ArticleInteractor();
}
public void attemptArticleLoading(String url) {
mArticleInteractor.loadArticleAsync(this, mContext, url);
}
@Override
public void onSuccess(String message, String articleBody) {
mView.onArticleLoaded(articleBody);
}
@Override
public void onFailure(String message) {
mView.onArticleFailedToLoad(message);
}
| public void archiveArticle(FeedItem feedItem, String article) { |
GoodGrind/ghostwriter | ghostwriter-test-java-v7/src/test/java/io/ghostwriter/EnvironmentExcludeTest.java | // Path: ghostwriter-test-java-v7/src/test/java/io/ghostwriter/excluded/ExcludedPackageClass.java
// @Include // explicitly @Include, just to make sure this does not meddle with the package exclude mechanism
// public class ExcludedPackageClass {
//
// public int meaningOfLife() {
// return 42;
// }
//
// }
//
// Path: ghostwriter-test-java-v7/src/test/java/io/ghostwriter/excluded/nested/ExcludedNestedPackageClass.java
// @Include // explicitly @Include, just to make sure this does not meddle with the package exclude mechanism
// public class ExcludedNestedPackageClass {
//
// public int meaningOfLife() {
// return 42;
// }
//
// }
//
// Path: ghostwriter-test-java-v7/src/main/java/io/ghostwriter/test/TestBase.java
// public class TestBase {
//
// public static final int NUMBER_OF_ENTRIES_PER_TRACED_PARAMETER = 2; // first value should be the name, the second one is the value of the parameter
//
// @BeforeClass
// public static void setup() {
// // switch to the in-memory implementation, so we can do unit testing.
// GhostWriter.setTracerProvider(InMemoryTracerProvider.INSTANCE);
// }
//
// @Before
// public void configureInMemoryTracer() {
// fetchedPreparedInMemoryTracer();
// }
//
// //FIXME(snorbi07): refactor to a more meaningful name... the difficulty is coming up with one
// public InMemoryTracer fetchedPreparedInMemoryTracer() {
// InMemoryTracer tracer = InMemoryTracerProvider.INSTANCE.getTracer();
// // we only need value change tracker in the specific tests and there we enable it manually
// tracer.disableValueChangeTracking();
// // make sure that entering/exiting tracing is enabled.
// tracer.enableEnteringExitingTracking();
// // we clear manually because the @Test method is also traced and it pollutes the entering logs.
// tracer.clearMessages();
//
// return tracer;
// }
//
// public void disableValueChangeTracking() {
// InMemoryTracerProvider.INSTANCE.getTracer().disableValueChangeTracking();
// }
//
// public void enableValueChangeTracking() {
// InMemoryTracerProvider.INSTANCE.getTracer().enableValueChangeTracking();
// }
//
// }
| import io.ghostwriter.excluded.ExcludedPackageClass;
import io.ghostwriter.excluded.nested.ExcludedNestedPackageClass;
import io.ghostwriter.test.TestBase;
import org.junit.Test;
import java.util.*;
import static org.junit.Assert.assertEquals; | package io.ghostwriter;
public class EnvironmentExcludeTest extends TestBase {
@Test
public void testExcludedPackageClass() {
final InMemoryTracer inMemoryTracer = fetchedPreparedInMemoryTracer();
inMemoryTracer.clearMessages(); | // Path: ghostwriter-test-java-v7/src/test/java/io/ghostwriter/excluded/ExcludedPackageClass.java
// @Include // explicitly @Include, just to make sure this does not meddle with the package exclude mechanism
// public class ExcludedPackageClass {
//
// public int meaningOfLife() {
// return 42;
// }
//
// }
//
// Path: ghostwriter-test-java-v7/src/test/java/io/ghostwriter/excluded/nested/ExcludedNestedPackageClass.java
// @Include // explicitly @Include, just to make sure this does not meddle with the package exclude mechanism
// public class ExcludedNestedPackageClass {
//
// public int meaningOfLife() {
// return 42;
// }
//
// }
//
// Path: ghostwriter-test-java-v7/src/main/java/io/ghostwriter/test/TestBase.java
// public class TestBase {
//
// public static final int NUMBER_OF_ENTRIES_PER_TRACED_PARAMETER = 2; // first value should be the name, the second one is the value of the parameter
//
// @BeforeClass
// public static void setup() {
// // switch to the in-memory implementation, so we can do unit testing.
// GhostWriter.setTracerProvider(InMemoryTracerProvider.INSTANCE);
// }
//
// @Before
// public void configureInMemoryTracer() {
// fetchedPreparedInMemoryTracer();
// }
//
// //FIXME(snorbi07): refactor to a more meaningful name... the difficulty is coming up with one
// public InMemoryTracer fetchedPreparedInMemoryTracer() {
// InMemoryTracer tracer = InMemoryTracerProvider.INSTANCE.getTracer();
// // we only need value change tracker in the specific tests and there we enable it manually
// tracer.disableValueChangeTracking();
// // make sure that entering/exiting tracing is enabled.
// tracer.enableEnteringExitingTracking();
// // we clear manually because the @Test method is also traced and it pollutes the entering logs.
// tracer.clearMessages();
//
// return tracer;
// }
//
// public void disableValueChangeTracking() {
// InMemoryTracerProvider.INSTANCE.getTracer().disableValueChangeTracking();
// }
//
// public void enableValueChangeTracking() {
// InMemoryTracerProvider.INSTANCE.getTracer().enableValueChangeTracking();
// }
//
// }
// Path: ghostwriter-test-java-v7/src/test/java/io/ghostwriter/EnvironmentExcludeTest.java
import io.ghostwriter.excluded.ExcludedPackageClass;
import io.ghostwriter.excluded.nested.ExcludedNestedPackageClass;
import io.ghostwriter.test.TestBase;
import org.junit.Test;
import java.util.*;
import static org.junit.Assert.assertEquals;
package io.ghostwriter;
public class EnvironmentExcludeTest extends TestBase {
@Test
public void testExcludedPackageClass() {
final InMemoryTracer inMemoryTracer = fetchedPreparedInMemoryTracer();
inMemoryTracer.clearMessages(); | ExcludedPackageClass someVal = new ExcludedPackageClass(); |
GoodGrind/ghostwriter | ghostwriter-test-java-v7/src/test/java/io/ghostwriter/EnvironmentExcludeTest.java | // Path: ghostwriter-test-java-v7/src/test/java/io/ghostwriter/excluded/ExcludedPackageClass.java
// @Include // explicitly @Include, just to make sure this does not meddle with the package exclude mechanism
// public class ExcludedPackageClass {
//
// public int meaningOfLife() {
// return 42;
// }
//
// }
//
// Path: ghostwriter-test-java-v7/src/test/java/io/ghostwriter/excluded/nested/ExcludedNestedPackageClass.java
// @Include // explicitly @Include, just to make sure this does not meddle with the package exclude mechanism
// public class ExcludedNestedPackageClass {
//
// public int meaningOfLife() {
// return 42;
// }
//
// }
//
// Path: ghostwriter-test-java-v7/src/main/java/io/ghostwriter/test/TestBase.java
// public class TestBase {
//
// public static final int NUMBER_OF_ENTRIES_PER_TRACED_PARAMETER = 2; // first value should be the name, the second one is the value of the parameter
//
// @BeforeClass
// public static void setup() {
// // switch to the in-memory implementation, so we can do unit testing.
// GhostWriter.setTracerProvider(InMemoryTracerProvider.INSTANCE);
// }
//
// @Before
// public void configureInMemoryTracer() {
// fetchedPreparedInMemoryTracer();
// }
//
// //FIXME(snorbi07): refactor to a more meaningful name... the difficulty is coming up with one
// public InMemoryTracer fetchedPreparedInMemoryTracer() {
// InMemoryTracer tracer = InMemoryTracerProvider.INSTANCE.getTracer();
// // we only need value change tracker in the specific tests and there we enable it manually
// tracer.disableValueChangeTracking();
// // make sure that entering/exiting tracing is enabled.
// tracer.enableEnteringExitingTracking();
// // we clear manually because the @Test method is also traced and it pollutes the entering logs.
// tracer.clearMessages();
//
// return tracer;
// }
//
// public void disableValueChangeTracking() {
// InMemoryTracerProvider.INSTANCE.getTracer().disableValueChangeTracking();
// }
//
// public void enableValueChangeTracking() {
// InMemoryTracerProvider.INSTANCE.getTracer().enableValueChangeTracking();
// }
//
// }
| import io.ghostwriter.excluded.ExcludedPackageClass;
import io.ghostwriter.excluded.nested.ExcludedNestedPackageClass;
import io.ghostwriter.test.TestBase;
import org.junit.Test;
import java.util.*;
import static org.junit.Assert.assertEquals; | package io.ghostwriter;
public class EnvironmentExcludeTest extends TestBase {
@Test
public void testExcludedPackageClass() {
final InMemoryTracer inMemoryTracer = fetchedPreparedInMemoryTracer();
inMemoryTracer.clearMessages();
ExcludedPackageClass someVal = new ExcludedPackageClass();
someVal.meaningOfLife();
final int numMessages = inMemoryTracer.numberOfMessages();
assertEquals("Class in excluded package should not produce GW events!",
Collections.emptyList(), new ArrayList<>(inMemoryTracer.getMessages()));
}
@Test
public void testExcludedNestedPackageClass() {
final InMemoryTracer inMemoryTracer = fetchedPreparedInMemoryTracer();
inMemoryTracer.clearMessages(); | // Path: ghostwriter-test-java-v7/src/test/java/io/ghostwriter/excluded/ExcludedPackageClass.java
// @Include // explicitly @Include, just to make sure this does not meddle with the package exclude mechanism
// public class ExcludedPackageClass {
//
// public int meaningOfLife() {
// return 42;
// }
//
// }
//
// Path: ghostwriter-test-java-v7/src/test/java/io/ghostwriter/excluded/nested/ExcludedNestedPackageClass.java
// @Include // explicitly @Include, just to make sure this does not meddle with the package exclude mechanism
// public class ExcludedNestedPackageClass {
//
// public int meaningOfLife() {
// return 42;
// }
//
// }
//
// Path: ghostwriter-test-java-v7/src/main/java/io/ghostwriter/test/TestBase.java
// public class TestBase {
//
// public static final int NUMBER_OF_ENTRIES_PER_TRACED_PARAMETER = 2; // first value should be the name, the second one is the value of the parameter
//
// @BeforeClass
// public static void setup() {
// // switch to the in-memory implementation, so we can do unit testing.
// GhostWriter.setTracerProvider(InMemoryTracerProvider.INSTANCE);
// }
//
// @Before
// public void configureInMemoryTracer() {
// fetchedPreparedInMemoryTracer();
// }
//
// //FIXME(snorbi07): refactor to a more meaningful name... the difficulty is coming up with one
// public InMemoryTracer fetchedPreparedInMemoryTracer() {
// InMemoryTracer tracer = InMemoryTracerProvider.INSTANCE.getTracer();
// // we only need value change tracker in the specific tests and there we enable it manually
// tracer.disableValueChangeTracking();
// // make sure that entering/exiting tracing is enabled.
// tracer.enableEnteringExitingTracking();
// // we clear manually because the @Test method is also traced and it pollutes the entering logs.
// tracer.clearMessages();
//
// return tracer;
// }
//
// public void disableValueChangeTracking() {
// InMemoryTracerProvider.INSTANCE.getTracer().disableValueChangeTracking();
// }
//
// public void enableValueChangeTracking() {
// InMemoryTracerProvider.INSTANCE.getTracer().enableValueChangeTracking();
// }
//
// }
// Path: ghostwriter-test-java-v7/src/test/java/io/ghostwriter/EnvironmentExcludeTest.java
import io.ghostwriter.excluded.ExcludedPackageClass;
import io.ghostwriter.excluded.nested.ExcludedNestedPackageClass;
import io.ghostwriter.test.TestBase;
import org.junit.Test;
import java.util.*;
import static org.junit.Assert.assertEquals;
package io.ghostwriter;
public class EnvironmentExcludeTest extends TestBase {
@Test
public void testExcludedPackageClass() {
final InMemoryTracer inMemoryTracer = fetchedPreparedInMemoryTracer();
inMemoryTracer.clearMessages();
ExcludedPackageClass someVal = new ExcludedPackageClass();
someVal.meaningOfLife();
final int numMessages = inMemoryTracer.numberOfMessages();
assertEquals("Class in excluded package should not produce GW events!",
Collections.emptyList(), new ArrayList<>(inMemoryTracer.getMessages()));
}
@Test
public void testExcludedNestedPackageClass() {
final InMemoryTracer inMemoryTracer = fetchedPreparedInMemoryTracer();
inMemoryTracer.clearMessages(); | ExcludedNestedPackageClass someVal = new ExcludedNestedPackageClass(); |
GoodGrind/ghostwriter | ghostwriter-jdk-v7/src/main/java/io/ghostwriter/openjdk/v7/ast/compiler/JavaCompilerHelper.java | // Path: ghostwriter-jdk-v7/src/main/java/io/ghostwriter/openjdk/v7/model/Method.java
// public class Method extends AstModel<JCMethodDecl> {
// private final String name;
// private final Clazz clazz;
// private final List<Parameter> parameters;
//
// public Method(String name, Clazz clazz, List<Parameter> parameters, JCMethodDecl representation) {
// super(representation);
// Objects.requireNonNull(clazz, "Must provide a valid class AST model!");
// Objects.requireNonNull(name, "Must provide a valid parameter name!");
// if ("".equals(name)) {
// throw new IllegalArgumentException("Must provide a non-empty method name!");
// }
//
// this.name = name;
// this.clazz = clazz;
// this.parameters = parameters;
// }
//
// public Clazz getClazz() {
// return clazz;
// }
//
// public String getName() {
// return name;
// }
//
// public List<Parameter> getParameters() {
// return parameters;
// }
//
// @Override
// public String toString() {
// return "Method [class=" + clazz.getFullyQualifiedClassName() + ", name=" + name + ", parameters=" + parameters + "]";
// }
//
// }
| import com.sun.tools.javac.tree.JCTree;
import com.sun.tools.javac.util.List;
import io.ghostwriter.openjdk.v7.model.Method;
import java.util.Objects; | package io.ghostwriter.openjdk.v7.ast.compiler;
/**
* Contains helper methods that are used to deduce information about existing code and code model or
* create Java language representations of various elements.
* Helper methods built on the {@code JavaCompiler} interface are collected in this file.
*/
public class JavaCompilerHelper {
private static final String EXCLUDE_ANNOTATION_TYPE = "io.ghostwriter.annotation.Exclude";
private static final String TIMEOUT_ANNOTATION_TYPE = "io.ghostwriter.annotation.Timeout";
private static final String INCLUDE_ANNOTATION_TYPE = "io.ghostwriter.annotation.Include";
private final JavaCompiler javac;
public JavaCompilerHelper(JavaCompiler javac) {
this.javac = Objects.requireNonNull(javac);
}
| // Path: ghostwriter-jdk-v7/src/main/java/io/ghostwriter/openjdk/v7/model/Method.java
// public class Method extends AstModel<JCMethodDecl> {
// private final String name;
// private final Clazz clazz;
// private final List<Parameter> parameters;
//
// public Method(String name, Clazz clazz, List<Parameter> parameters, JCMethodDecl representation) {
// super(representation);
// Objects.requireNonNull(clazz, "Must provide a valid class AST model!");
// Objects.requireNonNull(name, "Must provide a valid parameter name!");
// if ("".equals(name)) {
// throw new IllegalArgumentException("Must provide a non-empty method name!");
// }
//
// this.name = name;
// this.clazz = clazz;
// this.parameters = parameters;
// }
//
// public Clazz getClazz() {
// return clazz;
// }
//
// public String getName() {
// return name;
// }
//
// public List<Parameter> getParameters() {
// return parameters;
// }
//
// @Override
// public String toString() {
// return "Method [class=" + clazz.getFullyQualifiedClassName() + ", name=" + name + ", parameters=" + parameters + "]";
// }
//
// }
// Path: ghostwriter-jdk-v7/src/main/java/io/ghostwriter/openjdk/v7/ast/compiler/JavaCompilerHelper.java
import com.sun.tools.javac.tree.JCTree;
import com.sun.tools.javac.util.List;
import io.ghostwriter.openjdk.v7.model.Method;
import java.util.Objects;
package io.ghostwriter.openjdk.v7.ast.compiler;
/**
* Contains helper methods that are used to deduce information about existing code and code model or
* create Java language representations of various elements.
* Helper methods built on the {@code JavaCompiler} interface are collected in this file.
*/
public class JavaCompilerHelper {
private static final String EXCLUDE_ANNOTATION_TYPE = "io.ghostwriter.annotation.Exclude";
private static final String TIMEOUT_ANNOTATION_TYPE = "io.ghostwriter.annotation.Timeout";
private static final String INCLUDE_ANNOTATION_TYPE = "io.ghostwriter.annotation.Include";
private final JavaCompiler javac;
public JavaCompilerHelper(JavaCompiler javac) {
this.javac = Objects.requireNonNull(javac);
}
| public JCTree.JCLiteral methodName(Method model) { |
GoodGrind/ghostwriter | ghostwriter-jdk-v8/src/main/java/io/ghostwriter/openjdk/v8/ast/translator/Lambdas.java | // Path: ghostwriter-jdk-v7/src/main/java/io/ghostwriter/openjdk/v7/model/Method.java
// public class Method extends AstModel<JCMethodDecl> {
// private final String name;
// private final Clazz clazz;
// private final List<Parameter> parameters;
//
// public Method(String name, Clazz clazz, List<Parameter> parameters, JCMethodDecl representation) {
// super(representation);
// Objects.requireNonNull(clazz, "Must provide a valid class AST model!");
// Objects.requireNonNull(name, "Must provide a valid parameter name!");
// if ("".equals(name)) {
// throw new IllegalArgumentException("Must provide a non-empty method name!");
// }
//
// this.name = name;
// this.clazz = clazz;
// this.parameters = parameters;
// }
//
// public Clazz getClazz() {
// return clazz;
// }
//
// public String getName() {
// return name;
// }
//
// public List<Parameter> getParameters() {
// return parameters;
// }
//
// @Override
// public String toString() {
// return "Method [class=" + clazz.getFullyQualifiedClassName() + ", name=" + name + ", parameters=" + parameters + "]";
// }
//
// }
| import com.sun.tools.javac.tree.JCTree;
import io.ghostwriter.openjdk.v7.model.Method;
import java.util.stream.Collectors; | package io.ghostwriter.openjdk.v8.ast.translator;
class Lambdas {
private Lambdas() {
throw new UnsupportedOperationException("class is not designed for instantiation");
}
| // Path: ghostwriter-jdk-v7/src/main/java/io/ghostwriter/openjdk/v7/model/Method.java
// public class Method extends AstModel<JCMethodDecl> {
// private final String name;
// private final Clazz clazz;
// private final List<Parameter> parameters;
//
// public Method(String name, Clazz clazz, List<Parameter> parameters, JCMethodDecl representation) {
// super(representation);
// Objects.requireNonNull(clazz, "Must provide a valid class AST model!");
// Objects.requireNonNull(name, "Must provide a valid parameter name!");
// if ("".equals(name)) {
// throw new IllegalArgumentException("Must provide a non-empty method name!");
// }
//
// this.name = name;
// this.clazz = clazz;
// this.parameters = parameters;
// }
//
// public Clazz getClazz() {
// return clazz;
// }
//
// public String getName() {
// return name;
// }
//
// public List<Parameter> getParameters() {
// return parameters;
// }
//
// @Override
// public String toString() {
// return "Method [class=" + clazz.getFullyQualifiedClassName() + ", name=" + name + ", parameters=" + parameters + "]";
// }
//
// }
// Path: ghostwriter-jdk-v8/src/main/java/io/ghostwriter/openjdk/v8/ast/translator/Lambdas.java
import com.sun.tools.javac.tree.JCTree;
import io.ghostwriter.openjdk.v7.model.Method;
import java.util.stream.Collectors;
package io.ghostwriter.openjdk.v8.ast.translator;
class Lambdas {
private Lambdas() {
throw new UnsupportedOperationException("class is not designed for instantiation");
}
| static public String nameFor(Method model, JCTree.JCLambda visitedLambda) { |
GoodGrind/ghostwriter | ghostwriter-test-java-v7/src/main/java/io/ghostwriter/test/TestBase.java | // Path: ghostwriter-test-java-v7/src/main/java/io/ghostwriter/InMemoryTracer.java
// public class InMemoryTracer implements Tracer {
//
// private final Queue<Message<?>> messageStack;
// // by default we don't want to generate more messages then necessary for testing
// private boolean doTrackValueChanges = false;
//
// private boolean doTrackEnteringExiting = true;
//
// public InMemoryTracer() {
// messageStack = Collections.asLifoQueue(new ArrayDeque<Message<?>>());
// }
//
// public Message<?> popMessage() {
// return messageStack.remove();
// }
//
// public void pushMessage(Message<?> msg) {
// messageStack.add(msg);
// }
//
// public void clearMessages() {
// messageStack.clear();
// }
//
// public void enableValueChangeTracking() {
// doTrackValueChanges = true;
// }
//
// public void disableValueChangeTracking() {
// doTrackValueChanges = false;
// }
//
// public void enableEnteringExitingTracking() {
// doTrackEnteringExiting = true;
// }
//
// public void disableEnteringExitingTracking() {
// doTrackEnteringExiting = false;
// }
//
// public int numberOfMessages() {
// return messageStack.size();
// }
//
// public Queue<Message<?>> getMessages() {
// return messageStack;
// }
//
// @Override
// public void entering(Object source, String method, Object... params) {
// if (!doTrackEnteringExiting) {
// return;
// }
//
// EnteringMessage enteringMessage;
// if (params.length == 0) {
// enteringMessage = new EnteringMessage(source, method);
// }
// else {
// EnteringMessage.Payload payload = new EnteringMessage.Payload(params);
// enteringMessage = new EnteringMessage(source, method, payload);
// }
//
// pushMessage(enteringMessage);
// }
//
// @Override
// public void exiting(Object source, String method) {
// if (!doTrackEnteringExiting) {
// return;
// }
//
// ExitingMessage exitingMessage = new ExitingMessage(source, method);
// pushMessage(exitingMessage);
// }
//
// @Override
// public void valueChange(Object source, String method, String variable, Object newValue) {
// if (!doTrackValueChanges) {
// return;
// }
//
// ValueChangeMessage valueChangeMessage = new ValueChangeMessage(source, method, new ValueChangeMessage.Payload(variable, newValue));
// pushMessage(valueChangeMessage);
// }
//
// @Override
// public <T> void returning(Object source, String method, T returnValue) {
// ReturningMessage returningMessage = new ReturningMessage(source, method, returnValue);
// pushMessage(returningMessage);
// }
//
// @Override
// public void onError(Object source, String method, Throwable error) {
// OnErrorMessage onErrorMessage = new OnErrorMessage(source, method, error);
// pushMessage(onErrorMessage);
// }
//
// @Override
// public void timeout(Object source, String method, long timeoutThreshold, long timeout) {
// TimeoutMessage timeoutMessage = new TimeoutMessage(source, method, new Object[]{timeoutThreshold, timeout});
// pushMessage(timeoutMessage);
// }
// }
//
// Path: ghostwriter-test-java-v7/src/main/java/io/ghostwriter/InMemoryTracerProvider.java
// public enum InMemoryTracerProvider implements TracerProvider<InMemoryTracer> {
// INSTANCE;
//
// private final InMemoryTracer tracer;
//
// InMemoryTracerProvider() {
// tracer = new InMemoryTracer();
// }
//
// @Override
// public InMemoryTracer getTracer() {
// return tracer;
// }
//
// }
| import io.ghostwriter.GhostWriter;
import io.ghostwriter.InMemoryTracer;
import io.ghostwriter.InMemoryTracerProvider;
import org.junit.Before;
import org.junit.BeforeClass; | package io.ghostwriter.test;
/**
* Main reason for this class to be under main and not test is to exclude it from GW instrumentation
*/
public class TestBase {
public static final int NUMBER_OF_ENTRIES_PER_TRACED_PARAMETER = 2; // first value should be the name, the second one is the value of the parameter
@BeforeClass
public static void setup() {
// switch to the in-memory implementation, so we can do unit testing. | // Path: ghostwriter-test-java-v7/src/main/java/io/ghostwriter/InMemoryTracer.java
// public class InMemoryTracer implements Tracer {
//
// private final Queue<Message<?>> messageStack;
// // by default we don't want to generate more messages then necessary for testing
// private boolean doTrackValueChanges = false;
//
// private boolean doTrackEnteringExiting = true;
//
// public InMemoryTracer() {
// messageStack = Collections.asLifoQueue(new ArrayDeque<Message<?>>());
// }
//
// public Message<?> popMessage() {
// return messageStack.remove();
// }
//
// public void pushMessage(Message<?> msg) {
// messageStack.add(msg);
// }
//
// public void clearMessages() {
// messageStack.clear();
// }
//
// public void enableValueChangeTracking() {
// doTrackValueChanges = true;
// }
//
// public void disableValueChangeTracking() {
// doTrackValueChanges = false;
// }
//
// public void enableEnteringExitingTracking() {
// doTrackEnteringExiting = true;
// }
//
// public void disableEnteringExitingTracking() {
// doTrackEnteringExiting = false;
// }
//
// public int numberOfMessages() {
// return messageStack.size();
// }
//
// public Queue<Message<?>> getMessages() {
// return messageStack;
// }
//
// @Override
// public void entering(Object source, String method, Object... params) {
// if (!doTrackEnteringExiting) {
// return;
// }
//
// EnteringMessage enteringMessage;
// if (params.length == 0) {
// enteringMessage = new EnteringMessage(source, method);
// }
// else {
// EnteringMessage.Payload payload = new EnteringMessage.Payload(params);
// enteringMessage = new EnteringMessage(source, method, payload);
// }
//
// pushMessage(enteringMessage);
// }
//
// @Override
// public void exiting(Object source, String method) {
// if (!doTrackEnteringExiting) {
// return;
// }
//
// ExitingMessage exitingMessage = new ExitingMessage(source, method);
// pushMessage(exitingMessage);
// }
//
// @Override
// public void valueChange(Object source, String method, String variable, Object newValue) {
// if (!doTrackValueChanges) {
// return;
// }
//
// ValueChangeMessage valueChangeMessage = new ValueChangeMessage(source, method, new ValueChangeMessage.Payload(variable, newValue));
// pushMessage(valueChangeMessage);
// }
//
// @Override
// public <T> void returning(Object source, String method, T returnValue) {
// ReturningMessage returningMessage = new ReturningMessage(source, method, returnValue);
// pushMessage(returningMessage);
// }
//
// @Override
// public void onError(Object source, String method, Throwable error) {
// OnErrorMessage onErrorMessage = new OnErrorMessage(source, method, error);
// pushMessage(onErrorMessage);
// }
//
// @Override
// public void timeout(Object source, String method, long timeoutThreshold, long timeout) {
// TimeoutMessage timeoutMessage = new TimeoutMessage(source, method, new Object[]{timeoutThreshold, timeout});
// pushMessage(timeoutMessage);
// }
// }
//
// Path: ghostwriter-test-java-v7/src/main/java/io/ghostwriter/InMemoryTracerProvider.java
// public enum InMemoryTracerProvider implements TracerProvider<InMemoryTracer> {
// INSTANCE;
//
// private final InMemoryTracer tracer;
//
// InMemoryTracerProvider() {
// tracer = new InMemoryTracer();
// }
//
// @Override
// public InMemoryTracer getTracer() {
// return tracer;
// }
//
// }
// Path: ghostwriter-test-java-v7/src/main/java/io/ghostwriter/test/TestBase.java
import io.ghostwriter.GhostWriter;
import io.ghostwriter.InMemoryTracer;
import io.ghostwriter.InMemoryTracerProvider;
import org.junit.Before;
import org.junit.BeforeClass;
package io.ghostwriter.test;
/**
* Main reason for this class to be under main and not test is to exclude it from GW instrumentation
*/
public class TestBase {
public static final int NUMBER_OF_ENTRIES_PER_TRACED_PARAMETER = 2; // first value should be the name, the second one is the value of the parameter
@BeforeClass
public static void setup() {
// switch to the in-memory implementation, so we can do unit testing. | GhostWriter.setTracerProvider(InMemoryTracerProvider.INSTANCE); |
GoodGrind/ghostwriter | ghostwriter-test-java-v7/src/main/java/io/ghostwriter/test/TestBase.java | // Path: ghostwriter-test-java-v7/src/main/java/io/ghostwriter/InMemoryTracer.java
// public class InMemoryTracer implements Tracer {
//
// private final Queue<Message<?>> messageStack;
// // by default we don't want to generate more messages then necessary for testing
// private boolean doTrackValueChanges = false;
//
// private boolean doTrackEnteringExiting = true;
//
// public InMemoryTracer() {
// messageStack = Collections.asLifoQueue(new ArrayDeque<Message<?>>());
// }
//
// public Message<?> popMessage() {
// return messageStack.remove();
// }
//
// public void pushMessage(Message<?> msg) {
// messageStack.add(msg);
// }
//
// public void clearMessages() {
// messageStack.clear();
// }
//
// public void enableValueChangeTracking() {
// doTrackValueChanges = true;
// }
//
// public void disableValueChangeTracking() {
// doTrackValueChanges = false;
// }
//
// public void enableEnteringExitingTracking() {
// doTrackEnteringExiting = true;
// }
//
// public void disableEnteringExitingTracking() {
// doTrackEnteringExiting = false;
// }
//
// public int numberOfMessages() {
// return messageStack.size();
// }
//
// public Queue<Message<?>> getMessages() {
// return messageStack;
// }
//
// @Override
// public void entering(Object source, String method, Object... params) {
// if (!doTrackEnteringExiting) {
// return;
// }
//
// EnteringMessage enteringMessage;
// if (params.length == 0) {
// enteringMessage = new EnteringMessage(source, method);
// }
// else {
// EnteringMessage.Payload payload = new EnteringMessage.Payload(params);
// enteringMessage = new EnteringMessage(source, method, payload);
// }
//
// pushMessage(enteringMessage);
// }
//
// @Override
// public void exiting(Object source, String method) {
// if (!doTrackEnteringExiting) {
// return;
// }
//
// ExitingMessage exitingMessage = new ExitingMessage(source, method);
// pushMessage(exitingMessage);
// }
//
// @Override
// public void valueChange(Object source, String method, String variable, Object newValue) {
// if (!doTrackValueChanges) {
// return;
// }
//
// ValueChangeMessage valueChangeMessage = new ValueChangeMessage(source, method, new ValueChangeMessage.Payload(variable, newValue));
// pushMessage(valueChangeMessage);
// }
//
// @Override
// public <T> void returning(Object source, String method, T returnValue) {
// ReturningMessage returningMessage = new ReturningMessage(source, method, returnValue);
// pushMessage(returningMessage);
// }
//
// @Override
// public void onError(Object source, String method, Throwable error) {
// OnErrorMessage onErrorMessage = new OnErrorMessage(source, method, error);
// pushMessage(onErrorMessage);
// }
//
// @Override
// public void timeout(Object source, String method, long timeoutThreshold, long timeout) {
// TimeoutMessage timeoutMessage = new TimeoutMessage(source, method, new Object[]{timeoutThreshold, timeout});
// pushMessage(timeoutMessage);
// }
// }
//
// Path: ghostwriter-test-java-v7/src/main/java/io/ghostwriter/InMemoryTracerProvider.java
// public enum InMemoryTracerProvider implements TracerProvider<InMemoryTracer> {
// INSTANCE;
//
// private final InMemoryTracer tracer;
//
// InMemoryTracerProvider() {
// tracer = new InMemoryTracer();
// }
//
// @Override
// public InMemoryTracer getTracer() {
// return tracer;
// }
//
// }
| import io.ghostwriter.GhostWriter;
import io.ghostwriter.InMemoryTracer;
import io.ghostwriter.InMemoryTracerProvider;
import org.junit.Before;
import org.junit.BeforeClass; | package io.ghostwriter.test;
/**
* Main reason for this class to be under main and not test is to exclude it from GW instrumentation
*/
public class TestBase {
public static final int NUMBER_OF_ENTRIES_PER_TRACED_PARAMETER = 2; // first value should be the name, the second one is the value of the parameter
@BeforeClass
public static void setup() {
// switch to the in-memory implementation, so we can do unit testing.
GhostWriter.setTracerProvider(InMemoryTracerProvider.INSTANCE);
}
@Before
public void configureInMemoryTracer() {
fetchedPreparedInMemoryTracer();
}
//FIXME(snorbi07): refactor to a more meaningful name... the difficulty is coming up with one | // Path: ghostwriter-test-java-v7/src/main/java/io/ghostwriter/InMemoryTracer.java
// public class InMemoryTracer implements Tracer {
//
// private final Queue<Message<?>> messageStack;
// // by default we don't want to generate more messages then necessary for testing
// private boolean doTrackValueChanges = false;
//
// private boolean doTrackEnteringExiting = true;
//
// public InMemoryTracer() {
// messageStack = Collections.asLifoQueue(new ArrayDeque<Message<?>>());
// }
//
// public Message<?> popMessage() {
// return messageStack.remove();
// }
//
// public void pushMessage(Message<?> msg) {
// messageStack.add(msg);
// }
//
// public void clearMessages() {
// messageStack.clear();
// }
//
// public void enableValueChangeTracking() {
// doTrackValueChanges = true;
// }
//
// public void disableValueChangeTracking() {
// doTrackValueChanges = false;
// }
//
// public void enableEnteringExitingTracking() {
// doTrackEnteringExiting = true;
// }
//
// public void disableEnteringExitingTracking() {
// doTrackEnteringExiting = false;
// }
//
// public int numberOfMessages() {
// return messageStack.size();
// }
//
// public Queue<Message<?>> getMessages() {
// return messageStack;
// }
//
// @Override
// public void entering(Object source, String method, Object... params) {
// if (!doTrackEnteringExiting) {
// return;
// }
//
// EnteringMessage enteringMessage;
// if (params.length == 0) {
// enteringMessage = new EnteringMessage(source, method);
// }
// else {
// EnteringMessage.Payload payload = new EnteringMessage.Payload(params);
// enteringMessage = new EnteringMessage(source, method, payload);
// }
//
// pushMessage(enteringMessage);
// }
//
// @Override
// public void exiting(Object source, String method) {
// if (!doTrackEnteringExiting) {
// return;
// }
//
// ExitingMessage exitingMessage = new ExitingMessage(source, method);
// pushMessage(exitingMessage);
// }
//
// @Override
// public void valueChange(Object source, String method, String variable, Object newValue) {
// if (!doTrackValueChanges) {
// return;
// }
//
// ValueChangeMessage valueChangeMessage = new ValueChangeMessage(source, method, new ValueChangeMessage.Payload(variable, newValue));
// pushMessage(valueChangeMessage);
// }
//
// @Override
// public <T> void returning(Object source, String method, T returnValue) {
// ReturningMessage returningMessage = new ReturningMessage(source, method, returnValue);
// pushMessage(returningMessage);
// }
//
// @Override
// public void onError(Object source, String method, Throwable error) {
// OnErrorMessage onErrorMessage = new OnErrorMessage(source, method, error);
// pushMessage(onErrorMessage);
// }
//
// @Override
// public void timeout(Object source, String method, long timeoutThreshold, long timeout) {
// TimeoutMessage timeoutMessage = new TimeoutMessage(source, method, new Object[]{timeoutThreshold, timeout});
// pushMessage(timeoutMessage);
// }
// }
//
// Path: ghostwriter-test-java-v7/src/main/java/io/ghostwriter/InMemoryTracerProvider.java
// public enum InMemoryTracerProvider implements TracerProvider<InMemoryTracer> {
// INSTANCE;
//
// private final InMemoryTracer tracer;
//
// InMemoryTracerProvider() {
// tracer = new InMemoryTracer();
// }
//
// @Override
// public InMemoryTracer getTracer() {
// return tracer;
// }
//
// }
// Path: ghostwriter-test-java-v7/src/main/java/io/ghostwriter/test/TestBase.java
import io.ghostwriter.GhostWriter;
import io.ghostwriter.InMemoryTracer;
import io.ghostwriter.InMemoryTracerProvider;
import org.junit.Before;
import org.junit.BeforeClass;
package io.ghostwriter.test;
/**
* Main reason for this class to be under main and not test is to exclude it from GW instrumentation
*/
public class TestBase {
public static final int NUMBER_OF_ENTRIES_PER_TRACED_PARAMETER = 2; // first value should be the name, the second one is the value of the parameter
@BeforeClass
public static void setup() {
// switch to the in-memory implementation, so we can do unit testing.
GhostWriter.setTracerProvider(InMemoryTracerProvider.INSTANCE);
}
@Before
public void configureInMemoryTracer() {
fetchedPreparedInMemoryTracer();
}
//FIXME(snorbi07): refactor to a more meaningful name... the difficulty is coming up with one | public InMemoryTracer fetchedPreparedInMemoryTracer() { |
GoodGrind/ghostwriter | ghostwriter-jdk-v8/src/main/java/io/ghostwriter/openjdk/v8/GhostWriterAnnotationProcessor.java | // Path: ghostwriter-jdk-v7/src/main/java/io/ghostwriter/openjdk/v7/common/Instrumenter.java
// public interface Instrumenter {
//
// abstract class Option {
// public static final String GHOSTWRITER_EXCLUDE = "GHOSTWRITER_EXCLUDE";
// public static final String GHOSTWRITER_TRACE_VALUE_CHANGE = "GHOSTWRITER_TRACE_VALUE_CHANGE";
// public static final String GHOSTWRITER_TRACE_ON_ERROR = "GHOSTWRITER_TRACE_ON_ERROR";
// public static final String GHOSTWRITER_TRACE_RETURNING = "GHOSTWRITER_TRACE_RETURNING";
// public static final String GHOSTWRITER_ANNOTATED_ONLY = "GHOSTWRITER_ANNOTATED_ONLY";
// public static final String GHOSTWRITER_EXCLUDE_METHODS = "GHOSTWRITER_EXCLUDE_METHODS";
// public static final String GHOSTWRITER_INSTRUMENT = "GHOSTWRITER_INSTRUMENT";
// public static final String GHOSTWRITER_VERBOSE = "GHOSTWRITER_VERBOSE";
// public static final String GHOSTWRITER_SHORT_METHOD_LIMIT = "GHOSTWRITER_SHORT_METHOD_LIMIT";
// }
//
// void initialize(ProcessingEnvironment processingEnv);
//
// void process(Element element);
//
// boolean doInstrument();
// }
| import io.ghostwriter.annotation.Exclude;
import io.ghostwriter.openjdk.v7.common.Instrumenter;
import javax.annotation.processing.SupportedAnnotationTypes;
import javax.annotation.processing.SupportedOptions;
import javax.annotation.processing.SupportedSourceVersion;
import javax.lang.model.SourceVersion; | package io.ghostwriter.openjdk.v8;
@SupportedAnnotationTypes("*")
@SupportedSourceVersion(SourceVersion.RELEASE_8) | // Path: ghostwriter-jdk-v7/src/main/java/io/ghostwriter/openjdk/v7/common/Instrumenter.java
// public interface Instrumenter {
//
// abstract class Option {
// public static final String GHOSTWRITER_EXCLUDE = "GHOSTWRITER_EXCLUDE";
// public static final String GHOSTWRITER_TRACE_VALUE_CHANGE = "GHOSTWRITER_TRACE_VALUE_CHANGE";
// public static final String GHOSTWRITER_TRACE_ON_ERROR = "GHOSTWRITER_TRACE_ON_ERROR";
// public static final String GHOSTWRITER_TRACE_RETURNING = "GHOSTWRITER_TRACE_RETURNING";
// public static final String GHOSTWRITER_ANNOTATED_ONLY = "GHOSTWRITER_ANNOTATED_ONLY";
// public static final String GHOSTWRITER_EXCLUDE_METHODS = "GHOSTWRITER_EXCLUDE_METHODS";
// public static final String GHOSTWRITER_INSTRUMENT = "GHOSTWRITER_INSTRUMENT";
// public static final String GHOSTWRITER_VERBOSE = "GHOSTWRITER_VERBOSE";
// public static final String GHOSTWRITER_SHORT_METHOD_LIMIT = "GHOSTWRITER_SHORT_METHOD_LIMIT";
// }
//
// void initialize(ProcessingEnvironment processingEnv);
//
// void process(Element element);
//
// boolean doInstrument();
// }
// Path: ghostwriter-jdk-v8/src/main/java/io/ghostwriter/openjdk/v8/GhostWriterAnnotationProcessor.java
import io.ghostwriter.annotation.Exclude;
import io.ghostwriter.openjdk.v7.common.Instrumenter;
import javax.annotation.processing.SupportedAnnotationTypes;
import javax.annotation.processing.SupportedOptions;
import javax.annotation.processing.SupportedSourceVersion;
import javax.lang.model.SourceVersion;
package io.ghostwriter.openjdk.v8;
@SupportedAnnotationTypes("*")
@SupportedSourceVersion(SourceVersion.RELEASE_8) | @SupportedOptions({Instrumenter.Option.GHOSTWRITER_ANNOTATED_ONLY, |
GoodGrind/ghostwriter | ghostwriter-test-java-v7/src/test/java/io/ghostwriter/EnteringTest.java | // Path: ghostwriter-test-java-v7/src/main/java/io/ghostwriter/message/EnteringMessage.java
// public class EnteringMessage extends Message<EnteringMessage.BasePayload> {
//
// public EnteringMessage(Object source, String method) {
// this(source, method, NoParameters.INSTANCE);
// }
//
// public EnteringMessage(Object source, String method, BasePayload payload) {
// super(source, method, payload);
// }
//
// public boolean hasParameters() {
// BasePayload payload = getPayload();
// return !NoParameters.INSTANCE.equals(payload);
// }
//
// @Override
// public String toString() {
// return super.toString() + getPayload().toString();
// }
//
// public static abstract class BasePayload {
//
// protected BasePayload() {
// }
//
// public abstract Object[] getParameters();
//
// }
//
// // cannot use enum for the singleton pattern since that doesn't support 'extend'
// protected static class NoParameters extends BasePayload {
// public static NoParameters INSTANCE = new NoParameters();
//
// private NoParameters() {
// }
//
// @Override
// public Object[] getParameters() {
// return null;
// }
//
// @Override
// public String toString() {
// return "()";
// }
// }
//
// public static class Payload extends BasePayload {
//
// final private Object[] parameters;
//
// public Payload(Object[] parameters) {
// this.parameters = parameters;
// }
//
// public Object[] getParameters() {
// return parameters;
// }
//
// @Override
// public String toString() {
// StringBuffer sb = new StringBuffer();
// sb.append(super.toString()).append("(");
// final int UPPER_BOUND = parameters.length - 1;
// final int SIZE_OF_ENTRY_PAIRS = 2;
// for (int i = 0; i < UPPER_BOUND; i += SIZE_OF_ENTRY_PAIRS) {
// Object name = parameters[i];
// Object value = parameters[i + 1];
// sb.append(name).append(" = ").append(value);
// if (i != UPPER_BOUND - 1) {
// sb.append(", ");
// }
// }
// sb.append(")");
//
// return sb.toString();
// }
// }
// }
//
// Path: ghostwriter-test-java-v7/src/main/java/io/ghostwriter/message/Message.java
// public class Message<T> {
//
// final private Object source;
//
// final private String method;
//
// final private T payload;
//
// public Message(Object source, String method, T payload) {
// this.source = source;
// this.method = method;
// this.payload = payload;
// }
//
// public Object getSource() {
// return source;
// }
//
// public String getMethod() {
// return method;
// }
//
// public T getPayload() {
// return payload;
// }
//
// @Override
// public String toString() {
// StringBuffer sb = new StringBuffer();
// sb.append(this.getClass().getSimpleName().toString())
// // .append(String.valueOf(source))
// .append(".")
// .append(method);
//
// return sb.toString();
// }
// }
//
// Path: ghostwriter-test-java-v7/src/main/java/io/ghostwriter/test/TestBase.java
// public class TestBase {
//
// public static final int NUMBER_OF_ENTRIES_PER_TRACED_PARAMETER = 2; // first value should be the name, the second one is the value of the parameter
//
// @BeforeClass
// public static void setup() {
// // switch to the in-memory implementation, so we can do unit testing.
// GhostWriter.setTracerProvider(InMemoryTracerProvider.INSTANCE);
// }
//
// @Before
// public void configureInMemoryTracer() {
// fetchedPreparedInMemoryTracer();
// }
//
// //FIXME(snorbi07): refactor to a more meaningful name... the difficulty is coming up with one
// public InMemoryTracer fetchedPreparedInMemoryTracer() {
// InMemoryTracer tracer = InMemoryTracerProvider.INSTANCE.getTracer();
// // we only need value change tracker in the specific tests and there we enable it manually
// tracer.disableValueChangeTracking();
// // make sure that entering/exiting tracing is enabled.
// tracer.enableEnteringExitingTracking();
// // we clear manually because the @Test method is also traced and it pollutes the entering logs.
// tracer.clearMessages();
//
// return tracer;
// }
//
// public void disableValueChangeTracking() {
// InMemoryTracerProvider.INSTANCE.getTracer().disableValueChangeTracking();
// }
//
// public void enableValueChangeTracking() {
// InMemoryTracerProvider.INSTANCE.getTracer().enableValueChangeTracking();
// }
//
// }
| import io.ghostwriter.message.EnteringMessage;
import io.ghostwriter.message.Message;
import io.ghostwriter.test.TestBase;
import org.junit.Test;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import static org.junit.Assert.assertTrue; | package io.ghostwriter;
public class EnteringTest extends TestBase {
@Test
public void testMethodWithNoParametersAndNoResultEntering() {
InMemoryTracer inMemoryTracer = fetchedPreparedInMemoryTracer();
methodWithNoParametersAndNoResult();
// pop the unused exitingMessage
inMemoryTracer.popMessage(); | // Path: ghostwriter-test-java-v7/src/main/java/io/ghostwriter/message/EnteringMessage.java
// public class EnteringMessage extends Message<EnteringMessage.BasePayload> {
//
// public EnteringMessage(Object source, String method) {
// this(source, method, NoParameters.INSTANCE);
// }
//
// public EnteringMessage(Object source, String method, BasePayload payload) {
// super(source, method, payload);
// }
//
// public boolean hasParameters() {
// BasePayload payload = getPayload();
// return !NoParameters.INSTANCE.equals(payload);
// }
//
// @Override
// public String toString() {
// return super.toString() + getPayload().toString();
// }
//
// public static abstract class BasePayload {
//
// protected BasePayload() {
// }
//
// public abstract Object[] getParameters();
//
// }
//
// // cannot use enum for the singleton pattern since that doesn't support 'extend'
// protected static class NoParameters extends BasePayload {
// public static NoParameters INSTANCE = new NoParameters();
//
// private NoParameters() {
// }
//
// @Override
// public Object[] getParameters() {
// return null;
// }
//
// @Override
// public String toString() {
// return "()";
// }
// }
//
// public static class Payload extends BasePayload {
//
// final private Object[] parameters;
//
// public Payload(Object[] parameters) {
// this.parameters = parameters;
// }
//
// public Object[] getParameters() {
// return parameters;
// }
//
// @Override
// public String toString() {
// StringBuffer sb = new StringBuffer();
// sb.append(super.toString()).append("(");
// final int UPPER_BOUND = parameters.length - 1;
// final int SIZE_OF_ENTRY_PAIRS = 2;
// for (int i = 0; i < UPPER_BOUND; i += SIZE_OF_ENTRY_PAIRS) {
// Object name = parameters[i];
// Object value = parameters[i + 1];
// sb.append(name).append(" = ").append(value);
// if (i != UPPER_BOUND - 1) {
// sb.append(", ");
// }
// }
// sb.append(")");
//
// return sb.toString();
// }
// }
// }
//
// Path: ghostwriter-test-java-v7/src/main/java/io/ghostwriter/message/Message.java
// public class Message<T> {
//
// final private Object source;
//
// final private String method;
//
// final private T payload;
//
// public Message(Object source, String method, T payload) {
// this.source = source;
// this.method = method;
// this.payload = payload;
// }
//
// public Object getSource() {
// return source;
// }
//
// public String getMethod() {
// return method;
// }
//
// public T getPayload() {
// return payload;
// }
//
// @Override
// public String toString() {
// StringBuffer sb = new StringBuffer();
// sb.append(this.getClass().getSimpleName().toString())
// // .append(String.valueOf(source))
// .append(".")
// .append(method);
//
// return sb.toString();
// }
// }
//
// Path: ghostwriter-test-java-v7/src/main/java/io/ghostwriter/test/TestBase.java
// public class TestBase {
//
// public static final int NUMBER_OF_ENTRIES_PER_TRACED_PARAMETER = 2; // first value should be the name, the second one is the value of the parameter
//
// @BeforeClass
// public static void setup() {
// // switch to the in-memory implementation, so we can do unit testing.
// GhostWriter.setTracerProvider(InMemoryTracerProvider.INSTANCE);
// }
//
// @Before
// public void configureInMemoryTracer() {
// fetchedPreparedInMemoryTracer();
// }
//
// //FIXME(snorbi07): refactor to a more meaningful name... the difficulty is coming up with one
// public InMemoryTracer fetchedPreparedInMemoryTracer() {
// InMemoryTracer tracer = InMemoryTracerProvider.INSTANCE.getTracer();
// // we only need value change tracker in the specific tests and there we enable it manually
// tracer.disableValueChangeTracking();
// // make sure that entering/exiting tracing is enabled.
// tracer.enableEnteringExitingTracking();
// // we clear manually because the @Test method is also traced and it pollutes the entering logs.
// tracer.clearMessages();
//
// return tracer;
// }
//
// public void disableValueChangeTracking() {
// InMemoryTracerProvider.INSTANCE.getTracer().disableValueChangeTracking();
// }
//
// public void enableValueChangeTracking() {
// InMemoryTracerProvider.INSTANCE.getTracer().enableValueChangeTracking();
// }
//
// }
// Path: ghostwriter-test-java-v7/src/test/java/io/ghostwriter/EnteringTest.java
import io.ghostwriter.message.EnteringMessage;
import io.ghostwriter.message.Message;
import io.ghostwriter.test.TestBase;
import org.junit.Test;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import static org.junit.Assert.assertTrue;
package io.ghostwriter;
public class EnteringTest extends TestBase {
@Test
public void testMethodWithNoParametersAndNoResultEntering() {
InMemoryTracer inMemoryTracer = fetchedPreparedInMemoryTracer();
methodWithNoParametersAndNoResult();
// pop the unused exitingMessage
inMemoryTracer.popMessage(); | Message<?> enteringMessage = inMemoryTracer.popMessage(); |
GoodGrind/ghostwriter | ghostwriter-test-java-v7/src/test/java/io/ghostwriter/EnteringTest.java | // Path: ghostwriter-test-java-v7/src/main/java/io/ghostwriter/message/EnteringMessage.java
// public class EnteringMessage extends Message<EnteringMessage.BasePayload> {
//
// public EnteringMessage(Object source, String method) {
// this(source, method, NoParameters.INSTANCE);
// }
//
// public EnteringMessage(Object source, String method, BasePayload payload) {
// super(source, method, payload);
// }
//
// public boolean hasParameters() {
// BasePayload payload = getPayload();
// return !NoParameters.INSTANCE.equals(payload);
// }
//
// @Override
// public String toString() {
// return super.toString() + getPayload().toString();
// }
//
// public static abstract class BasePayload {
//
// protected BasePayload() {
// }
//
// public abstract Object[] getParameters();
//
// }
//
// // cannot use enum for the singleton pattern since that doesn't support 'extend'
// protected static class NoParameters extends BasePayload {
// public static NoParameters INSTANCE = new NoParameters();
//
// private NoParameters() {
// }
//
// @Override
// public Object[] getParameters() {
// return null;
// }
//
// @Override
// public String toString() {
// return "()";
// }
// }
//
// public static class Payload extends BasePayload {
//
// final private Object[] parameters;
//
// public Payload(Object[] parameters) {
// this.parameters = parameters;
// }
//
// public Object[] getParameters() {
// return parameters;
// }
//
// @Override
// public String toString() {
// StringBuffer sb = new StringBuffer();
// sb.append(super.toString()).append("(");
// final int UPPER_BOUND = parameters.length - 1;
// final int SIZE_OF_ENTRY_PAIRS = 2;
// for (int i = 0; i < UPPER_BOUND; i += SIZE_OF_ENTRY_PAIRS) {
// Object name = parameters[i];
// Object value = parameters[i + 1];
// sb.append(name).append(" = ").append(value);
// if (i != UPPER_BOUND - 1) {
// sb.append(", ");
// }
// }
// sb.append(")");
//
// return sb.toString();
// }
// }
// }
//
// Path: ghostwriter-test-java-v7/src/main/java/io/ghostwriter/message/Message.java
// public class Message<T> {
//
// final private Object source;
//
// final private String method;
//
// final private T payload;
//
// public Message(Object source, String method, T payload) {
// this.source = source;
// this.method = method;
// this.payload = payload;
// }
//
// public Object getSource() {
// return source;
// }
//
// public String getMethod() {
// return method;
// }
//
// public T getPayload() {
// return payload;
// }
//
// @Override
// public String toString() {
// StringBuffer sb = new StringBuffer();
// sb.append(this.getClass().getSimpleName().toString())
// // .append(String.valueOf(source))
// .append(".")
// .append(method);
//
// return sb.toString();
// }
// }
//
// Path: ghostwriter-test-java-v7/src/main/java/io/ghostwriter/test/TestBase.java
// public class TestBase {
//
// public static final int NUMBER_OF_ENTRIES_PER_TRACED_PARAMETER = 2; // first value should be the name, the second one is the value of the parameter
//
// @BeforeClass
// public static void setup() {
// // switch to the in-memory implementation, so we can do unit testing.
// GhostWriter.setTracerProvider(InMemoryTracerProvider.INSTANCE);
// }
//
// @Before
// public void configureInMemoryTracer() {
// fetchedPreparedInMemoryTracer();
// }
//
// //FIXME(snorbi07): refactor to a more meaningful name... the difficulty is coming up with one
// public InMemoryTracer fetchedPreparedInMemoryTracer() {
// InMemoryTracer tracer = InMemoryTracerProvider.INSTANCE.getTracer();
// // we only need value change tracker in the specific tests and there we enable it manually
// tracer.disableValueChangeTracking();
// // make sure that entering/exiting tracing is enabled.
// tracer.enableEnteringExitingTracking();
// // we clear manually because the @Test method is also traced and it pollutes the entering logs.
// tracer.clearMessages();
//
// return tracer;
// }
//
// public void disableValueChangeTracking() {
// InMemoryTracerProvider.INSTANCE.getTracer().disableValueChangeTracking();
// }
//
// public void enableValueChangeTracking() {
// InMemoryTracerProvider.INSTANCE.getTracer().enableValueChangeTracking();
// }
//
// }
| import io.ghostwriter.message.EnteringMessage;
import io.ghostwriter.message.Message;
import io.ghostwriter.test.TestBase;
import org.junit.Test;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import static org.junit.Assert.assertTrue; | package io.ghostwriter;
public class EnteringTest extends TestBase {
@Test
public void testMethodWithNoParametersAndNoResultEntering() {
InMemoryTracer inMemoryTracer = fetchedPreparedInMemoryTracer();
methodWithNoParametersAndNoResult();
// pop the unused exitingMessage
inMemoryTracer.popMessage();
Message<?> enteringMessage = inMemoryTracer.popMessage(); | // Path: ghostwriter-test-java-v7/src/main/java/io/ghostwriter/message/EnteringMessage.java
// public class EnteringMessage extends Message<EnteringMessage.BasePayload> {
//
// public EnteringMessage(Object source, String method) {
// this(source, method, NoParameters.INSTANCE);
// }
//
// public EnteringMessage(Object source, String method, BasePayload payload) {
// super(source, method, payload);
// }
//
// public boolean hasParameters() {
// BasePayload payload = getPayload();
// return !NoParameters.INSTANCE.equals(payload);
// }
//
// @Override
// public String toString() {
// return super.toString() + getPayload().toString();
// }
//
// public static abstract class BasePayload {
//
// protected BasePayload() {
// }
//
// public abstract Object[] getParameters();
//
// }
//
// // cannot use enum for the singleton pattern since that doesn't support 'extend'
// protected static class NoParameters extends BasePayload {
// public static NoParameters INSTANCE = new NoParameters();
//
// private NoParameters() {
// }
//
// @Override
// public Object[] getParameters() {
// return null;
// }
//
// @Override
// public String toString() {
// return "()";
// }
// }
//
// public static class Payload extends BasePayload {
//
// final private Object[] parameters;
//
// public Payload(Object[] parameters) {
// this.parameters = parameters;
// }
//
// public Object[] getParameters() {
// return parameters;
// }
//
// @Override
// public String toString() {
// StringBuffer sb = new StringBuffer();
// sb.append(super.toString()).append("(");
// final int UPPER_BOUND = parameters.length - 1;
// final int SIZE_OF_ENTRY_PAIRS = 2;
// for (int i = 0; i < UPPER_BOUND; i += SIZE_OF_ENTRY_PAIRS) {
// Object name = parameters[i];
// Object value = parameters[i + 1];
// sb.append(name).append(" = ").append(value);
// if (i != UPPER_BOUND - 1) {
// sb.append(", ");
// }
// }
// sb.append(")");
//
// return sb.toString();
// }
// }
// }
//
// Path: ghostwriter-test-java-v7/src/main/java/io/ghostwriter/message/Message.java
// public class Message<T> {
//
// final private Object source;
//
// final private String method;
//
// final private T payload;
//
// public Message(Object source, String method, T payload) {
// this.source = source;
// this.method = method;
// this.payload = payload;
// }
//
// public Object getSource() {
// return source;
// }
//
// public String getMethod() {
// return method;
// }
//
// public T getPayload() {
// return payload;
// }
//
// @Override
// public String toString() {
// StringBuffer sb = new StringBuffer();
// sb.append(this.getClass().getSimpleName().toString())
// // .append(String.valueOf(source))
// .append(".")
// .append(method);
//
// return sb.toString();
// }
// }
//
// Path: ghostwriter-test-java-v7/src/main/java/io/ghostwriter/test/TestBase.java
// public class TestBase {
//
// public static final int NUMBER_OF_ENTRIES_PER_TRACED_PARAMETER = 2; // first value should be the name, the second one is the value of the parameter
//
// @BeforeClass
// public static void setup() {
// // switch to the in-memory implementation, so we can do unit testing.
// GhostWriter.setTracerProvider(InMemoryTracerProvider.INSTANCE);
// }
//
// @Before
// public void configureInMemoryTracer() {
// fetchedPreparedInMemoryTracer();
// }
//
// //FIXME(snorbi07): refactor to a more meaningful name... the difficulty is coming up with one
// public InMemoryTracer fetchedPreparedInMemoryTracer() {
// InMemoryTracer tracer = InMemoryTracerProvider.INSTANCE.getTracer();
// // we only need value change tracker in the specific tests and there we enable it manually
// tracer.disableValueChangeTracking();
// // make sure that entering/exiting tracing is enabled.
// tracer.enableEnteringExitingTracking();
// // we clear manually because the @Test method is also traced and it pollutes the entering logs.
// tracer.clearMessages();
//
// return tracer;
// }
//
// public void disableValueChangeTracking() {
// InMemoryTracerProvider.INSTANCE.getTracer().disableValueChangeTracking();
// }
//
// public void enableValueChangeTracking() {
// InMemoryTracerProvider.INSTANCE.getTracer().enableValueChangeTracking();
// }
//
// }
// Path: ghostwriter-test-java-v7/src/test/java/io/ghostwriter/EnteringTest.java
import io.ghostwriter.message.EnteringMessage;
import io.ghostwriter.message.Message;
import io.ghostwriter.test.TestBase;
import org.junit.Test;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import static org.junit.Assert.assertTrue;
package io.ghostwriter;
public class EnteringTest extends TestBase {
@Test
public void testMethodWithNoParametersAndNoResultEntering() {
InMemoryTracer inMemoryTracer = fetchedPreparedInMemoryTracer();
methodWithNoParametersAndNoResult();
// pop the unused exitingMessage
inMemoryTracer.popMessage();
Message<?> enteringMessage = inMemoryTracer.popMessage(); | boolean isEnteringMessage = enteringMessage instanceof EnteringMessage; |
GoodGrind/ghostwriter | ghostwriter-jdk-v7/src/main/java/io/ghostwriter/openjdk/v7/GhostWriterAnnotationProcessor.java | // Path: ghostwriter-jdk-v7/src/main/java/io/ghostwriter/openjdk/v7/common/Instrumenter.java
// public interface Instrumenter {
//
// abstract class Option {
// public static final String GHOSTWRITER_EXCLUDE = "GHOSTWRITER_EXCLUDE";
// public static final String GHOSTWRITER_TRACE_VALUE_CHANGE = "GHOSTWRITER_TRACE_VALUE_CHANGE";
// public static final String GHOSTWRITER_TRACE_ON_ERROR = "GHOSTWRITER_TRACE_ON_ERROR";
// public static final String GHOSTWRITER_TRACE_RETURNING = "GHOSTWRITER_TRACE_RETURNING";
// public static final String GHOSTWRITER_ANNOTATED_ONLY = "GHOSTWRITER_ANNOTATED_ONLY";
// public static final String GHOSTWRITER_EXCLUDE_METHODS = "GHOSTWRITER_EXCLUDE_METHODS";
// public static final String GHOSTWRITER_INSTRUMENT = "GHOSTWRITER_INSTRUMENT";
// public static final String GHOSTWRITER_VERBOSE = "GHOSTWRITER_VERBOSE";
// public static final String GHOSTWRITER_SHORT_METHOD_LIMIT = "GHOSTWRITER_SHORT_METHOD_LIMIT";
// }
//
// void initialize(ProcessingEnvironment processingEnv);
//
// void process(Element element);
//
// boolean doInstrument();
// }
//
// Path: ghostwriter-jdk-v7/src/main/java/io/ghostwriter/openjdk/v7/common/Logger.java
// public enum Logger {
// ;
//
// private static Messager messager;
//
// private static boolean doVerboseLogging = false;
//
// private static String format(Class<?> klass, String method, String message) {
// final int INITIAL_CAPACITY = 32;
// StringBuilder sb = new StringBuilder(INITIAL_CAPACITY);
// if (klass != null) {
// sb.append(klass.getName());
// sb.append(".");
// }
// sb.append(method);
// sb.append(": ");
// sb.append(message);
//
// return sb.toString();
// }
//
// public static void note(Class<?> type, String method, String message) {
// if (!doVerboseLogging) {
// return;
// }
//
// validateState();
// String output = format(type, method, message);
// messager.printMessage(Diagnostic.Kind.NOTE, output);
// }
//
// public static void warning(Class<?> type, String method, String message) {
// validateState();
// String output = format(type, method, message);
// messager.printMessage(Diagnostic.Kind.MANDATORY_WARNING, output);
// }
//
// /**
// * Display an error message.
// *
// * @param type - class that produced the error
// * @param method - method that produced the error
// * @param message - error description
// */
// public static void error(Class<?> type, String method, String message) {
// validateState();
// String output = format(type, method, message);
// messager.printMessage(Diagnostic.Kind.ERROR, output);
// }
//
// public static void initialize(Messager msg, boolean verbose) {
// if (msg == null) {
// throw new IllegalArgumentException("Cannot initialize with null!");
// }
// messager = msg;
// doVerboseLogging = verbose;
// }
//
// private static void validateState() {
// if (messager == null) {
// throw new IllegalStateException("Logger has not been initialized!");
// }
// }
//
// }
| import io.ghostwriter.openjdk.v7.common.Instrumenter;
import io.ghostwriter.openjdk.v7.common.Logger;
import javax.annotation.processing.*;
import javax.lang.model.SourceVersion;
import javax.lang.model.element.Element;
import javax.lang.model.element.ElementKind;
import javax.lang.model.element.TypeElement;
import java.util.Set; | package io.ghostwriter.openjdk.v7;
@SupportedAnnotationTypes("*")
@SupportedSourceVersion(SourceVersion.RELEASE_7) | // Path: ghostwriter-jdk-v7/src/main/java/io/ghostwriter/openjdk/v7/common/Instrumenter.java
// public interface Instrumenter {
//
// abstract class Option {
// public static final String GHOSTWRITER_EXCLUDE = "GHOSTWRITER_EXCLUDE";
// public static final String GHOSTWRITER_TRACE_VALUE_CHANGE = "GHOSTWRITER_TRACE_VALUE_CHANGE";
// public static final String GHOSTWRITER_TRACE_ON_ERROR = "GHOSTWRITER_TRACE_ON_ERROR";
// public static final String GHOSTWRITER_TRACE_RETURNING = "GHOSTWRITER_TRACE_RETURNING";
// public static final String GHOSTWRITER_ANNOTATED_ONLY = "GHOSTWRITER_ANNOTATED_ONLY";
// public static final String GHOSTWRITER_EXCLUDE_METHODS = "GHOSTWRITER_EXCLUDE_METHODS";
// public static final String GHOSTWRITER_INSTRUMENT = "GHOSTWRITER_INSTRUMENT";
// public static final String GHOSTWRITER_VERBOSE = "GHOSTWRITER_VERBOSE";
// public static final String GHOSTWRITER_SHORT_METHOD_LIMIT = "GHOSTWRITER_SHORT_METHOD_LIMIT";
// }
//
// void initialize(ProcessingEnvironment processingEnv);
//
// void process(Element element);
//
// boolean doInstrument();
// }
//
// Path: ghostwriter-jdk-v7/src/main/java/io/ghostwriter/openjdk/v7/common/Logger.java
// public enum Logger {
// ;
//
// private static Messager messager;
//
// private static boolean doVerboseLogging = false;
//
// private static String format(Class<?> klass, String method, String message) {
// final int INITIAL_CAPACITY = 32;
// StringBuilder sb = new StringBuilder(INITIAL_CAPACITY);
// if (klass != null) {
// sb.append(klass.getName());
// sb.append(".");
// }
// sb.append(method);
// sb.append(": ");
// sb.append(message);
//
// return sb.toString();
// }
//
// public static void note(Class<?> type, String method, String message) {
// if (!doVerboseLogging) {
// return;
// }
//
// validateState();
// String output = format(type, method, message);
// messager.printMessage(Diagnostic.Kind.NOTE, output);
// }
//
// public static void warning(Class<?> type, String method, String message) {
// validateState();
// String output = format(type, method, message);
// messager.printMessage(Diagnostic.Kind.MANDATORY_WARNING, output);
// }
//
// /**
// * Display an error message.
// *
// * @param type - class that produced the error
// * @param method - method that produced the error
// * @param message - error description
// */
// public static void error(Class<?> type, String method, String message) {
// validateState();
// String output = format(type, method, message);
// messager.printMessage(Diagnostic.Kind.ERROR, output);
// }
//
// public static void initialize(Messager msg, boolean verbose) {
// if (msg == null) {
// throw new IllegalArgumentException("Cannot initialize with null!");
// }
// messager = msg;
// doVerboseLogging = verbose;
// }
//
// private static void validateState() {
// if (messager == null) {
// throw new IllegalStateException("Logger has not been initialized!");
// }
// }
//
// }
// Path: ghostwriter-jdk-v7/src/main/java/io/ghostwriter/openjdk/v7/GhostWriterAnnotationProcessor.java
import io.ghostwriter.openjdk.v7.common.Instrumenter;
import io.ghostwriter.openjdk.v7.common.Logger;
import javax.annotation.processing.*;
import javax.lang.model.SourceVersion;
import javax.lang.model.element.Element;
import javax.lang.model.element.ElementKind;
import javax.lang.model.element.TypeElement;
import java.util.Set;
package io.ghostwriter.openjdk.v7;
@SupportedAnnotationTypes("*")
@SupportedSourceVersion(SourceVersion.RELEASE_7) | @SupportedOptions({Instrumenter.Option.GHOSTWRITER_ANNOTATED_ONLY, |
GoodGrind/ghostwriter | ghostwriter-jdk-v7/src/main/java/io/ghostwriter/openjdk/v7/GhostWriterAnnotationProcessor.java | // Path: ghostwriter-jdk-v7/src/main/java/io/ghostwriter/openjdk/v7/common/Instrumenter.java
// public interface Instrumenter {
//
// abstract class Option {
// public static final String GHOSTWRITER_EXCLUDE = "GHOSTWRITER_EXCLUDE";
// public static final String GHOSTWRITER_TRACE_VALUE_CHANGE = "GHOSTWRITER_TRACE_VALUE_CHANGE";
// public static final String GHOSTWRITER_TRACE_ON_ERROR = "GHOSTWRITER_TRACE_ON_ERROR";
// public static final String GHOSTWRITER_TRACE_RETURNING = "GHOSTWRITER_TRACE_RETURNING";
// public static final String GHOSTWRITER_ANNOTATED_ONLY = "GHOSTWRITER_ANNOTATED_ONLY";
// public static final String GHOSTWRITER_EXCLUDE_METHODS = "GHOSTWRITER_EXCLUDE_METHODS";
// public static final String GHOSTWRITER_INSTRUMENT = "GHOSTWRITER_INSTRUMENT";
// public static final String GHOSTWRITER_VERBOSE = "GHOSTWRITER_VERBOSE";
// public static final String GHOSTWRITER_SHORT_METHOD_LIMIT = "GHOSTWRITER_SHORT_METHOD_LIMIT";
// }
//
// void initialize(ProcessingEnvironment processingEnv);
//
// void process(Element element);
//
// boolean doInstrument();
// }
//
// Path: ghostwriter-jdk-v7/src/main/java/io/ghostwriter/openjdk/v7/common/Logger.java
// public enum Logger {
// ;
//
// private static Messager messager;
//
// private static boolean doVerboseLogging = false;
//
// private static String format(Class<?> klass, String method, String message) {
// final int INITIAL_CAPACITY = 32;
// StringBuilder sb = new StringBuilder(INITIAL_CAPACITY);
// if (klass != null) {
// sb.append(klass.getName());
// sb.append(".");
// }
// sb.append(method);
// sb.append(": ");
// sb.append(message);
//
// return sb.toString();
// }
//
// public static void note(Class<?> type, String method, String message) {
// if (!doVerboseLogging) {
// return;
// }
//
// validateState();
// String output = format(type, method, message);
// messager.printMessage(Diagnostic.Kind.NOTE, output);
// }
//
// public static void warning(Class<?> type, String method, String message) {
// validateState();
// String output = format(type, method, message);
// messager.printMessage(Diagnostic.Kind.MANDATORY_WARNING, output);
// }
//
// /**
// * Display an error message.
// *
// * @param type - class that produced the error
// * @param method - method that produced the error
// * @param message - error description
// */
// public static void error(Class<?> type, String method, String message) {
// validateState();
// String output = format(type, method, message);
// messager.printMessage(Diagnostic.Kind.ERROR, output);
// }
//
// public static void initialize(Messager msg, boolean verbose) {
// if (msg == null) {
// throw new IllegalArgumentException("Cannot initialize with null!");
// }
// messager = msg;
// doVerboseLogging = verbose;
// }
//
// private static void validateState() {
// if (messager == null) {
// throw new IllegalStateException("Logger has not been initialized!");
// }
// }
//
// }
| import io.ghostwriter.openjdk.v7.common.Instrumenter;
import io.ghostwriter.openjdk.v7.common.Logger;
import javax.annotation.processing.*;
import javax.lang.model.SourceVersion;
import javax.lang.model.element.Element;
import javax.lang.model.element.ElementKind;
import javax.lang.model.element.TypeElement;
import java.util.Set; | public class GhostWriterAnnotationProcessor extends AbstractProcessor {
// part of the Annotation processor API. Since GhostWriter just hijacks the processor pipeline
// we take care not to claim any annotations and thus always return false.
protected static boolean NO_ANNOTATIONS_CLAIMED = false;
private Instrumenter instrumenter;
public GhostWriterAnnotationProcessor(Instrumenter instrumenter) {
this.instrumenter = instrumenter;
}
public GhostWriterAnnotationProcessor() {
this(new Javac7Instrumenter());
}
@Override
public synchronized void init(ProcessingEnvironment processingEnv) {
super.init(processingEnv);
instrumenter.initialize(processingEnv);
}
@Override
public boolean process(Set<? extends TypeElement> annotations, RoundEnvironment roundEnv) {
if (roundEnv.processingOver()) {
return NO_ANNOTATIONS_CLAIMED;
}
if (!instrumenter.doInstrument()) { | // Path: ghostwriter-jdk-v7/src/main/java/io/ghostwriter/openjdk/v7/common/Instrumenter.java
// public interface Instrumenter {
//
// abstract class Option {
// public static final String GHOSTWRITER_EXCLUDE = "GHOSTWRITER_EXCLUDE";
// public static final String GHOSTWRITER_TRACE_VALUE_CHANGE = "GHOSTWRITER_TRACE_VALUE_CHANGE";
// public static final String GHOSTWRITER_TRACE_ON_ERROR = "GHOSTWRITER_TRACE_ON_ERROR";
// public static final String GHOSTWRITER_TRACE_RETURNING = "GHOSTWRITER_TRACE_RETURNING";
// public static final String GHOSTWRITER_ANNOTATED_ONLY = "GHOSTWRITER_ANNOTATED_ONLY";
// public static final String GHOSTWRITER_EXCLUDE_METHODS = "GHOSTWRITER_EXCLUDE_METHODS";
// public static final String GHOSTWRITER_INSTRUMENT = "GHOSTWRITER_INSTRUMENT";
// public static final String GHOSTWRITER_VERBOSE = "GHOSTWRITER_VERBOSE";
// public static final String GHOSTWRITER_SHORT_METHOD_LIMIT = "GHOSTWRITER_SHORT_METHOD_LIMIT";
// }
//
// void initialize(ProcessingEnvironment processingEnv);
//
// void process(Element element);
//
// boolean doInstrument();
// }
//
// Path: ghostwriter-jdk-v7/src/main/java/io/ghostwriter/openjdk/v7/common/Logger.java
// public enum Logger {
// ;
//
// private static Messager messager;
//
// private static boolean doVerboseLogging = false;
//
// private static String format(Class<?> klass, String method, String message) {
// final int INITIAL_CAPACITY = 32;
// StringBuilder sb = new StringBuilder(INITIAL_CAPACITY);
// if (klass != null) {
// sb.append(klass.getName());
// sb.append(".");
// }
// sb.append(method);
// sb.append(": ");
// sb.append(message);
//
// return sb.toString();
// }
//
// public static void note(Class<?> type, String method, String message) {
// if (!doVerboseLogging) {
// return;
// }
//
// validateState();
// String output = format(type, method, message);
// messager.printMessage(Diagnostic.Kind.NOTE, output);
// }
//
// public static void warning(Class<?> type, String method, String message) {
// validateState();
// String output = format(type, method, message);
// messager.printMessage(Diagnostic.Kind.MANDATORY_WARNING, output);
// }
//
// /**
// * Display an error message.
// *
// * @param type - class that produced the error
// * @param method - method that produced the error
// * @param message - error description
// */
// public static void error(Class<?> type, String method, String message) {
// validateState();
// String output = format(type, method, message);
// messager.printMessage(Diagnostic.Kind.ERROR, output);
// }
//
// public static void initialize(Messager msg, boolean verbose) {
// if (msg == null) {
// throw new IllegalArgumentException("Cannot initialize with null!");
// }
// messager = msg;
// doVerboseLogging = verbose;
// }
//
// private static void validateState() {
// if (messager == null) {
// throw new IllegalStateException("Logger has not been initialized!");
// }
// }
//
// }
// Path: ghostwriter-jdk-v7/src/main/java/io/ghostwriter/openjdk/v7/GhostWriterAnnotationProcessor.java
import io.ghostwriter.openjdk.v7.common.Instrumenter;
import io.ghostwriter.openjdk.v7.common.Logger;
import javax.annotation.processing.*;
import javax.lang.model.SourceVersion;
import javax.lang.model.element.Element;
import javax.lang.model.element.ElementKind;
import javax.lang.model.element.TypeElement;
import java.util.Set;
public class GhostWriterAnnotationProcessor extends AbstractProcessor {
// part of the Annotation processor API. Since GhostWriter just hijacks the processor pipeline
// we take care not to claim any annotations and thus always return false.
protected static boolean NO_ANNOTATIONS_CLAIMED = false;
private Instrumenter instrumenter;
public GhostWriterAnnotationProcessor(Instrumenter instrumenter) {
this.instrumenter = instrumenter;
}
public GhostWriterAnnotationProcessor() {
this(new Javac7Instrumenter());
}
@Override
public synchronized void init(ProcessingEnvironment processingEnv) {
super.init(processingEnv);
instrumenter.initialize(processingEnv);
}
@Override
public boolean process(Set<? extends TypeElement> annotations, RoundEnvironment roundEnv) {
if (roundEnv.processingOver()) {
return NO_ANNOTATIONS_CLAIMED;
}
if (!instrumenter.doInstrument()) { | Logger.note(getClass(), "process", "skipping processing..."); |
GoodGrind/ghostwriter | ghostwriter-jdk-v7/src/main/java/io/ghostwriter/openjdk/v7/ast/compiler/Javac.java | // Path: ghostwriter-jdk-v7/src/main/java/io/ghostwriter/openjdk/v7/common/Logger.java
// public enum Logger {
// ;
//
// private static Messager messager;
//
// private static boolean doVerboseLogging = false;
//
// private static String format(Class<?> klass, String method, String message) {
// final int INITIAL_CAPACITY = 32;
// StringBuilder sb = new StringBuilder(INITIAL_CAPACITY);
// if (klass != null) {
// sb.append(klass.getName());
// sb.append(".");
// }
// sb.append(method);
// sb.append(": ");
// sb.append(message);
//
// return sb.toString();
// }
//
// public static void note(Class<?> type, String method, String message) {
// if (!doVerboseLogging) {
// return;
// }
//
// validateState();
// String output = format(type, method, message);
// messager.printMessage(Diagnostic.Kind.NOTE, output);
// }
//
// public static void warning(Class<?> type, String method, String message) {
// validateState();
// String output = format(type, method, message);
// messager.printMessage(Diagnostic.Kind.MANDATORY_WARNING, output);
// }
//
// /**
// * Display an error message.
// *
// * @param type - class that produced the error
// * @param method - method that produced the error
// * @param message - error description
// */
// public static void error(Class<?> type, String method, String message) {
// validateState();
// String output = format(type, method, message);
// messager.printMessage(Diagnostic.Kind.ERROR, output);
// }
//
// public static void initialize(Messager msg, boolean verbose) {
// if (msg == null) {
// throw new IllegalArgumentException("Cannot initialize with null!");
// }
// messager = msg;
// doVerboseLogging = verbose;
// }
//
// private static void validateState() {
// if (messager == null) {
// throw new IllegalStateException("Logger has not been initialized!");
// }
// }
//
// }
| import com.sun.tools.javac.code.Flags;
import com.sun.tools.javac.code.Type;
import com.sun.tools.javac.code.TypeTags;
import com.sun.tools.javac.model.JavacElements;
import com.sun.tools.javac.processing.JavacProcessingEnvironment;
import com.sun.tools.javac.tree.JCTree;
import com.sun.tools.javac.tree.JCTree.*;
import com.sun.tools.javac.tree.TreeMaker;
import com.sun.tools.javac.util.Context;
import com.sun.tools.javac.util.List;
import com.sun.tools.javac.util.Name;
import io.ghostwriter.openjdk.v7.common.Logger;
import javax.annotation.processing.ProcessingEnvironment;
import javax.lang.model.type.TypeKind;
import java.util.Map; | break;
case FLOAT:
wrapper = Float.class;
break;
case DOUBLE:
wrapper = Double.class;
break;
case BOOLEAN:
wrapper = Boolean.class;
break;
case VOID:
wrapper = Void.class;
break;
default:
throw new IllegalArgumentException("Unsupported primitive type: " + type);
}
assert wrapper != null;
return wrapper;
}
@Override
public JCExpression methodReturnType(JCMethodDecl method) {
JCExpression resultTypeExpression = method.restype;
JCExpression resultType = declarationType(resultTypeExpression); | // Path: ghostwriter-jdk-v7/src/main/java/io/ghostwriter/openjdk/v7/common/Logger.java
// public enum Logger {
// ;
//
// private static Messager messager;
//
// private static boolean doVerboseLogging = false;
//
// private static String format(Class<?> klass, String method, String message) {
// final int INITIAL_CAPACITY = 32;
// StringBuilder sb = new StringBuilder(INITIAL_CAPACITY);
// if (klass != null) {
// sb.append(klass.getName());
// sb.append(".");
// }
// sb.append(method);
// sb.append(": ");
// sb.append(message);
//
// return sb.toString();
// }
//
// public static void note(Class<?> type, String method, String message) {
// if (!doVerboseLogging) {
// return;
// }
//
// validateState();
// String output = format(type, method, message);
// messager.printMessage(Diagnostic.Kind.NOTE, output);
// }
//
// public static void warning(Class<?> type, String method, String message) {
// validateState();
// String output = format(type, method, message);
// messager.printMessage(Diagnostic.Kind.MANDATORY_WARNING, output);
// }
//
// /**
// * Display an error message.
// *
// * @param type - class that produced the error
// * @param method - method that produced the error
// * @param message - error description
// */
// public static void error(Class<?> type, String method, String message) {
// validateState();
// String output = format(type, method, message);
// messager.printMessage(Diagnostic.Kind.ERROR, output);
// }
//
// public static void initialize(Messager msg, boolean verbose) {
// if (msg == null) {
// throw new IllegalArgumentException("Cannot initialize with null!");
// }
// messager = msg;
// doVerboseLogging = verbose;
// }
//
// private static void validateState() {
// if (messager == null) {
// throw new IllegalStateException("Logger has not been initialized!");
// }
// }
//
// }
// Path: ghostwriter-jdk-v7/src/main/java/io/ghostwriter/openjdk/v7/ast/compiler/Javac.java
import com.sun.tools.javac.code.Flags;
import com.sun.tools.javac.code.Type;
import com.sun.tools.javac.code.TypeTags;
import com.sun.tools.javac.model.JavacElements;
import com.sun.tools.javac.processing.JavacProcessingEnvironment;
import com.sun.tools.javac.tree.JCTree;
import com.sun.tools.javac.tree.JCTree.*;
import com.sun.tools.javac.tree.TreeMaker;
import com.sun.tools.javac.util.Context;
import com.sun.tools.javac.util.List;
import com.sun.tools.javac.util.Name;
import io.ghostwriter.openjdk.v7.common.Logger;
import javax.annotation.processing.ProcessingEnvironment;
import javax.lang.model.type.TypeKind;
import java.util.Map;
break;
case FLOAT:
wrapper = Float.class;
break;
case DOUBLE:
wrapper = Double.class;
break;
case BOOLEAN:
wrapper = Boolean.class;
break;
case VOID:
wrapper = Void.class;
break;
default:
throw new IllegalArgumentException("Unsupported primitive type: " + type);
}
assert wrapper != null;
return wrapper;
}
@Override
public JCExpression methodReturnType(JCMethodDecl method) {
JCExpression resultTypeExpression = method.restype;
JCExpression resultType = declarationType(resultTypeExpression); | Logger.note(getClass(), "methodReturnType", resultType.toString()); |
GoodGrind/ghostwriter | ghostwriter-jdk-v7/src/main/java/io/ghostwriter/openjdk/v7/ast/collector/Collector.java | // Path: ghostwriter-jdk-v7/src/main/java/io/ghostwriter/openjdk/v7/common/Logger.java
// public enum Logger {
// ;
//
// private static Messager messager;
//
// private static boolean doVerboseLogging = false;
//
// private static String format(Class<?> klass, String method, String message) {
// final int INITIAL_CAPACITY = 32;
// StringBuilder sb = new StringBuilder(INITIAL_CAPACITY);
// if (klass != null) {
// sb.append(klass.getName());
// sb.append(".");
// }
// sb.append(method);
// sb.append(": ");
// sb.append(message);
//
// return sb.toString();
// }
//
// public static void note(Class<?> type, String method, String message) {
// if (!doVerboseLogging) {
// return;
// }
//
// validateState();
// String output = format(type, method, message);
// messager.printMessage(Diagnostic.Kind.NOTE, output);
// }
//
// public static void warning(Class<?> type, String method, String message) {
// validateState();
// String output = format(type, method, message);
// messager.printMessage(Diagnostic.Kind.MANDATORY_WARNING, output);
// }
//
// /**
// * Display an error message.
// *
// * @param type - class that produced the error
// * @param method - method that produced the error
// * @param message - error description
// */
// public static void error(Class<?> type, String method, String message) {
// validateState();
// String output = format(type, method, message);
// messager.printMessage(Diagnostic.Kind.ERROR, output);
// }
//
// public static void initialize(Messager msg, boolean verbose) {
// if (msg == null) {
// throw new IllegalArgumentException("Cannot initialize with null!");
// }
// messager = msg;
// doVerboseLogging = verbose;
// }
//
// private static void validateState() {
// if (messager == null) {
// throw new IllegalStateException("Logger has not been initialized!");
// }
// }
//
// }
| import com.sun.tools.javac.tree.JCTree;
import com.sun.tools.javac.tree.TreeTranslator;
import io.ghostwriter.openjdk.v7.common.Logger;
import java.util.*; | package io.ghostwriter.openjdk.v7.ast.collector;
public class Collector<T> extends TreeTranslator implements Iterable<T> {
final private List<T> items = new ArrayList<>();
final private JCTree rootElement;
// the Collector is lazy because of initialization requirements
private boolean hasExecuted = false;
public Collector(JCTree rootElement) {
super();
this.rootElement = Objects.requireNonNull(rootElement);
}
protected Collector<T> execute() {
rootElement.accept(this);
return this;
}
protected void collect(T item) {
if (item == null) { | // Path: ghostwriter-jdk-v7/src/main/java/io/ghostwriter/openjdk/v7/common/Logger.java
// public enum Logger {
// ;
//
// private static Messager messager;
//
// private static boolean doVerboseLogging = false;
//
// private static String format(Class<?> klass, String method, String message) {
// final int INITIAL_CAPACITY = 32;
// StringBuilder sb = new StringBuilder(INITIAL_CAPACITY);
// if (klass != null) {
// sb.append(klass.getName());
// sb.append(".");
// }
// sb.append(method);
// sb.append(": ");
// sb.append(message);
//
// return sb.toString();
// }
//
// public static void note(Class<?> type, String method, String message) {
// if (!doVerboseLogging) {
// return;
// }
//
// validateState();
// String output = format(type, method, message);
// messager.printMessage(Diagnostic.Kind.NOTE, output);
// }
//
// public static void warning(Class<?> type, String method, String message) {
// validateState();
// String output = format(type, method, message);
// messager.printMessage(Diagnostic.Kind.MANDATORY_WARNING, output);
// }
//
// /**
// * Display an error message.
// *
// * @param type - class that produced the error
// * @param method - method that produced the error
// * @param message - error description
// */
// public static void error(Class<?> type, String method, String message) {
// validateState();
// String output = format(type, method, message);
// messager.printMessage(Diagnostic.Kind.ERROR, output);
// }
//
// public static void initialize(Messager msg, boolean verbose) {
// if (msg == null) {
// throw new IllegalArgumentException("Cannot initialize with null!");
// }
// messager = msg;
// doVerboseLogging = verbose;
// }
//
// private static void validateState() {
// if (messager == null) {
// throw new IllegalStateException("Logger has not been initialized!");
// }
// }
//
// }
// Path: ghostwriter-jdk-v7/src/main/java/io/ghostwriter/openjdk/v7/ast/collector/Collector.java
import com.sun.tools.javac.tree.JCTree;
import com.sun.tools.javac.tree.TreeTranslator;
import io.ghostwriter.openjdk.v7.common.Logger;
import java.util.*;
package io.ghostwriter.openjdk.v7.ast.collector;
public class Collector<T> extends TreeTranslator implements Iterable<T> {
final private List<T> items = new ArrayList<>();
final private JCTree rootElement;
// the Collector is lazy because of initialization requirements
private boolean hasExecuted = false;
public Collector(JCTree rootElement) {
super();
this.rootElement = Objects.requireNonNull(rootElement);
}
protected Collector<T> execute() {
rootElement.accept(this);
return this;
}
protected void collect(T item) {
if (item == null) { | Logger.warning(getClass(), "collect", "tried to collect null item! Skipping!"); |
GoodGrind/ghostwriter | ghostwriter-test-java-v7/src/test/java/io/ghostwriter/OnErrorTest.java | // Path: ghostwriter-test-java-v7/src/main/java/io/ghostwriter/message/Message.java
// public class Message<T> {
//
// final private Object source;
//
// final private String method;
//
// final private T payload;
//
// public Message(Object source, String method, T payload) {
// this.source = source;
// this.method = method;
// this.payload = payload;
// }
//
// public Object getSource() {
// return source;
// }
//
// public String getMethod() {
// return method;
// }
//
// public T getPayload() {
// return payload;
// }
//
// @Override
// public String toString() {
// StringBuffer sb = new StringBuffer();
// sb.append(this.getClass().getSimpleName().toString())
// // .append(String.valueOf(source))
// .append(".")
// .append(method);
//
// return sb.toString();
// }
// }
//
// Path: ghostwriter-test-java-v7/src/main/java/io/ghostwriter/message/OnErrorMessage.java
// public class OnErrorMessage extends Message<Throwable> {
//
// public OnErrorMessage(Object source, String method, Throwable payload) {
// super(source, method, payload);
// }
//
// @Override
// public String toString() {
// return super.toString() + ": threw " + getPayload().toString();
// }
// }
//
// Path: ghostwriter-test-java-v7/src/main/java/io/ghostwriter/test/TestBase.java
// public class TestBase {
//
// public static final int NUMBER_OF_ENTRIES_PER_TRACED_PARAMETER = 2; // first value should be the name, the second one is the value of the parameter
//
// @BeforeClass
// public static void setup() {
// // switch to the in-memory implementation, so we can do unit testing.
// GhostWriter.setTracerProvider(InMemoryTracerProvider.INSTANCE);
// }
//
// @Before
// public void configureInMemoryTracer() {
// fetchedPreparedInMemoryTracer();
// }
//
// //FIXME(snorbi07): refactor to a more meaningful name... the difficulty is coming up with one
// public InMemoryTracer fetchedPreparedInMemoryTracer() {
// InMemoryTracer tracer = InMemoryTracerProvider.INSTANCE.getTracer();
// // we only need value change tracker in the specific tests and there we enable it manually
// tracer.disableValueChangeTracking();
// // make sure that entering/exiting tracing is enabled.
// tracer.enableEnteringExitingTracking();
// // we clear manually because the @Test method is also traced and it pollutes the entering logs.
// tracer.clearMessages();
//
// return tracer;
// }
//
// public void disableValueChangeTracking() {
// InMemoryTracerProvider.INSTANCE.getTracer().disableValueChangeTracking();
// }
//
// public void enableValueChangeTracking() {
// InMemoryTracerProvider.INSTANCE.getTracer().enableValueChangeTracking();
// }
//
// }
| import io.ghostwriter.message.Message;
import io.ghostwriter.message.OnErrorMessage;
import io.ghostwriter.test.TestBase;
import org.junit.Test;
import static org.junit.Assert.assertTrue; | package io.ghostwriter;
public class OnErrorTest extends TestBase {
@Test
public void testDereferenceNull() {
InMemoryTracer inMemoryTracer = fetchedPreparedInMemoryTracer();
boolean expectedExceptionTypeCaught = false;
try {
dereferenceNull();
}
catch (NullPointerException e) { // we intentionally throw a NPE and catch it to see whether it is logged by GW.
expectedExceptionTypeCaught = true;
}
assertTrue("Expected error did not occur", expectedExceptionTypeCaught);
// pop the unused exitingMessage triggered by "dereferenceNull" call
inMemoryTracer.popMessage();
| // Path: ghostwriter-test-java-v7/src/main/java/io/ghostwriter/message/Message.java
// public class Message<T> {
//
// final private Object source;
//
// final private String method;
//
// final private T payload;
//
// public Message(Object source, String method, T payload) {
// this.source = source;
// this.method = method;
// this.payload = payload;
// }
//
// public Object getSource() {
// return source;
// }
//
// public String getMethod() {
// return method;
// }
//
// public T getPayload() {
// return payload;
// }
//
// @Override
// public String toString() {
// StringBuffer sb = new StringBuffer();
// sb.append(this.getClass().getSimpleName().toString())
// // .append(String.valueOf(source))
// .append(".")
// .append(method);
//
// return sb.toString();
// }
// }
//
// Path: ghostwriter-test-java-v7/src/main/java/io/ghostwriter/message/OnErrorMessage.java
// public class OnErrorMessage extends Message<Throwable> {
//
// public OnErrorMessage(Object source, String method, Throwable payload) {
// super(source, method, payload);
// }
//
// @Override
// public String toString() {
// return super.toString() + ": threw " + getPayload().toString();
// }
// }
//
// Path: ghostwriter-test-java-v7/src/main/java/io/ghostwriter/test/TestBase.java
// public class TestBase {
//
// public static final int NUMBER_OF_ENTRIES_PER_TRACED_PARAMETER = 2; // first value should be the name, the second one is the value of the parameter
//
// @BeforeClass
// public static void setup() {
// // switch to the in-memory implementation, so we can do unit testing.
// GhostWriter.setTracerProvider(InMemoryTracerProvider.INSTANCE);
// }
//
// @Before
// public void configureInMemoryTracer() {
// fetchedPreparedInMemoryTracer();
// }
//
// //FIXME(snorbi07): refactor to a more meaningful name... the difficulty is coming up with one
// public InMemoryTracer fetchedPreparedInMemoryTracer() {
// InMemoryTracer tracer = InMemoryTracerProvider.INSTANCE.getTracer();
// // we only need value change tracker in the specific tests and there we enable it manually
// tracer.disableValueChangeTracking();
// // make sure that entering/exiting tracing is enabled.
// tracer.enableEnteringExitingTracking();
// // we clear manually because the @Test method is also traced and it pollutes the entering logs.
// tracer.clearMessages();
//
// return tracer;
// }
//
// public void disableValueChangeTracking() {
// InMemoryTracerProvider.INSTANCE.getTracer().disableValueChangeTracking();
// }
//
// public void enableValueChangeTracking() {
// InMemoryTracerProvider.INSTANCE.getTracer().enableValueChangeTracking();
// }
//
// }
// Path: ghostwriter-test-java-v7/src/test/java/io/ghostwriter/OnErrorTest.java
import io.ghostwriter.message.Message;
import io.ghostwriter.message.OnErrorMessage;
import io.ghostwriter.test.TestBase;
import org.junit.Test;
import static org.junit.Assert.assertTrue;
package io.ghostwriter;
public class OnErrorTest extends TestBase {
@Test
public void testDereferenceNull() {
InMemoryTracer inMemoryTracer = fetchedPreparedInMemoryTracer();
boolean expectedExceptionTypeCaught = false;
try {
dereferenceNull();
}
catch (NullPointerException e) { // we intentionally throw a NPE and catch it to see whether it is logged by GW.
expectedExceptionTypeCaught = true;
}
assertTrue("Expected error did not occur", expectedExceptionTypeCaught);
// pop the unused exitingMessage triggered by "dereferenceNull" call
inMemoryTracer.popMessage();
| Message<?> onErrorMessage = inMemoryTracer.popMessage(); |
GoodGrind/ghostwriter | ghostwriter-test-java-v7/src/test/java/io/ghostwriter/OnErrorTest.java | // Path: ghostwriter-test-java-v7/src/main/java/io/ghostwriter/message/Message.java
// public class Message<T> {
//
// final private Object source;
//
// final private String method;
//
// final private T payload;
//
// public Message(Object source, String method, T payload) {
// this.source = source;
// this.method = method;
// this.payload = payload;
// }
//
// public Object getSource() {
// return source;
// }
//
// public String getMethod() {
// return method;
// }
//
// public T getPayload() {
// return payload;
// }
//
// @Override
// public String toString() {
// StringBuffer sb = new StringBuffer();
// sb.append(this.getClass().getSimpleName().toString())
// // .append(String.valueOf(source))
// .append(".")
// .append(method);
//
// return sb.toString();
// }
// }
//
// Path: ghostwriter-test-java-v7/src/main/java/io/ghostwriter/message/OnErrorMessage.java
// public class OnErrorMessage extends Message<Throwable> {
//
// public OnErrorMessage(Object source, String method, Throwable payload) {
// super(source, method, payload);
// }
//
// @Override
// public String toString() {
// return super.toString() + ": threw " + getPayload().toString();
// }
// }
//
// Path: ghostwriter-test-java-v7/src/main/java/io/ghostwriter/test/TestBase.java
// public class TestBase {
//
// public static final int NUMBER_OF_ENTRIES_PER_TRACED_PARAMETER = 2; // first value should be the name, the second one is the value of the parameter
//
// @BeforeClass
// public static void setup() {
// // switch to the in-memory implementation, so we can do unit testing.
// GhostWriter.setTracerProvider(InMemoryTracerProvider.INSTANCE);
// }
//
// @Before
// public void configureInMemoryTracer() {
// fetchedPreparedInMemoryTracer();
// }
//
// //FIXME(snorbi07): refactor to a more meaningful name... the difficulty is coming up with one
// public InMemoryTracer fetchedPreparedInMemoryTracer() {
// InMemoryTracer tracer = InMemoryTracerProvider.INSTANCE.getTracer();
// // we only need value change tracker in the specific tests and there we enable it manually
// tracer.disableValueChangeTracking();
// // make sure that entering/exiting tracing is enabled.
// tracer.enableEnteringExitingTracking();
// // we clear manually because the @Test method is also traced and it pollutes the entering logs.
// tracer.clearMessages();
//
// return tracer;
// }
//
// public void disableValueChangeTracking() {
// InMemoryTracerProvider.INSTANCE.getTracer().disableValueChangeTracking();
// }
//
// public void enableValueChangeTracking() {
// InMemoryTracerProvider.INSTANCE.getTracer().enableValueChangeTracking();
// }
//
// }
| import io.ghostwriter.message.Message;
import io.ghostwriter.message.OnErrorMessage;
import io.ghostwriter.test.TestBase;
import org.junit.Test;
import static org.junit.Assert.assertTrue; | package io.ghostwriter;
public class OnErrorTest extends TestBase {
@Test
public void testDereferenceNull() {
InMemoryTracer inMemoryTracer = fetchedPreparedInMemoryTracer();
boolean expectedExceptionTypeCaught = false;
try {
dereferenceNull();
}
catch (NullPointerException e) { // we intentionally throw a NPE and catch it to see whether it is logged by GW.
expectedExceptionTypeCaught = true;
}
assertTrue("Expected error did not occur", expectedExceptionTypeCaught);
// pop the unused exitingMessage triggered by "dereferenceNull" call
inMemoryTracer.popMessage();
Message<?> onErrorMessage = inMemoryTracer.popMessage();
// verify message type | // Path: ghostwriter-test-java-v7/src/main/java/io/ghostwriter/message/Message.java
// public class Message<T> {
//
// final private Object source;
//
// final private String method;
//
// final private T payload;
//
// public Message(Object source, String method, T payload) {
// this.source = source;
// this.method = method;
// this.payload = payload;
// }
//
// public Object getSource() {
// return source;
// }
//
// public String getMethod() {
// return method;
// }
//
// public T getPayload() {
// return payload;
// }
//
// @Override
// public String toString() {
// StringBuffer sb = new StringBuffer();
// sb.append(this.getClass().getSimpleName().toString())
// // .append(String.valueOf(source))
// .append(".")
// .append(method);
//
// return sb.toString();
// }
// }
//
// Path: ghostwriter-test-java-v7/src/main/java/io/ghostwriter/message/OnErrorMessage.java
// public class OnErrorMessage extends Message<Throwable> {
//
// public OnErrorMessage(Object source, String method, Throwable payload) {
// super(source, method, payload);
// }
//
// @Override
// public String toString() {
// return super.toString() + ": threw " + getPayload().toString();
// }
// }
//
// Path: ghostwriter-test-java-v7/src/main/java/io/ghostwriter/test/TestBase.java
// public class TestBase {
//
// public static final int NUMBER_OF_ENTRIES_PER_TRACED_PARAMETER = 2; // first value should be the name, the second one is the value of the parameter
//
// @BeforeClass
// public static void setup() {
// // switch to the in-memory implementation, so we can do unit testing.
// GhostWriter.setTracerProvider(InMemoryTracerProvider.INSTANCE);
// }
//
// @Before
// public void configureInMemoryTracer() {
// fetchedPreparedInMemoryTracer();
// }
//
// //FIXME(snorbi07): refactor to a more meaningful name... the difficulty is coming up with one
// public InMemoryTracer fetchedPreparedInMemoryTracer() {
// InMemoryTracer tracer = InMemoryTracerProvider.INSTANCE.getTracer();
// // we only need value change tracker in the specific tests and there we enable it manually
// tracer.disableValueChangeTracking();
// // make sure that entering/exiting tracing is enabled.
// tracer.enableEnteringExitingTracking();
// // we clear manually because the @Test method is also traced and it pollutes the entering logs.
// tracer.clearMessages();
//
// return tracer;
// }
//
// public void disableValueChangeTracking() {
// InMemoryTracerProvider.INSTANCE.getTracer().disableValueChangeTracking();
// }
//
// public void enableValueChangeTracking() {
// InMemoryTracerProvider.INSTANCE.getTracer().enableValueChangeTracking();
// }
//
// }
// Path: ghostwriter-test-java-v7/src/test/java/io/ghostwriter/OnErrorTest.java
import io.ghostwriter.message.Message;
import io.ghostwriter.message.OnErrorMessage;
import io.ghostwriter.test.TestBase;
import org.junit.Test;
import static org.junit.Assert.assertTrue;
package io.ghostwriter;
public class OnErrorTest extends TestBase {
@Test
public void testDereferenceNull() {
InMemoryTracer inMemoryTracer = fetchedPreparedInMemoryTracer();
boolean expectedExceptionTypeCaught = false;
try {
dereferenceNull();
}
catch (NullPointerException e) { // we intentionally throw a NPE and catch it to see whether it is logged by GW.
expectedExceptionTypeCaught = true;
}
assertTrue("Expected error did not occur", expectedExceptionTypeCaught);
// pop the unused exitingMessage triggered by "dereferenceNull" call
inMemoryTracer.popMessage();
Message<?> onErrorMessage = inMemoryTracer.popMessage();
// verify message type | assertTrue("Invalid message type: " + onErrorMessage.getClass(), onErrorMessage instanceof OnErrorMessage); |
GoodGrind/ghostwriter | ghostwriter-test-java-v7/src/main/java/io/ghostwriter/test/MessageSequenceAsserter.java | // Path: ghostwriter-test-java-v7/src/main/java/io/ghostwriter/InMemoryTracer.java
// public class InMemoryTracer implements Tracer {
//
// private final Queue<Message<?>> messageStack;
// // by default we don't want to generate more messages then necessary for testing
// private boolean doTrackValueChanges = false;
//
// private boolean doTrackEnteringExiting = true;
//
// public InMemoryTracer() {
// messageStack = Collections.asLifoQueue(new ArrayDeque<Message<?>>());
// }
//
// public Message<?> popMessage() {
// return messageStack.remove();
// }
//
// public void pushMessage(Message<?> msg) {
// messageStack.add(msg);
// }
//
// public void clearMessages() {
// messageStack.clear();
// }
//
// public void enableValueChangeTracking() {
// doTrackValueChanges = true;
// }
//
// public void disableValueChangeTracking() {
// doTrackValueChanges = false;
// }
//
// public void enableEnteringExitingTracking() {
// doTrackEnteringExiting = true;
// }
//
// public void disableEnteringExitingTracking() {
// doTrackEnteringExiting = false;
// }
//
// public int numberOfMessages() {
// return messageStack.size();
// }
//
// public Queue<Message<?>> getMessages() {
// return messageStack;
// }
//
// @Override
// public void entering(Object source, String method, Object... params) {
// if (!doTrackEnteringExiting) {
// return;
// }
//
// EnteringMessage enteringMessage;
// if (params.length == 0) {
// enteringMessage = new EnteringMessage(source, method);
// }
// else {
// EnteringMessage.Payload payload = new EnteringMessage.Payload(params);
// enteringMessage = new EnteringMessage(source, method, payload);
// }
//
// pushMessage(enteringMessage);
// }
//
// @Override
// public void exiting(Object source, String method) {
// if (!doTrackEnteringExiting) {
// return;
// }
//
// ExitingMessage exitingMessage = new ExitingMessage(source, method);
// pushMessage(exitingMessage);
// }
//
// @Override
// public void valueChange(Object source, String method, String variable, Object newValue) {
// if (!doTrackValueChanges) {
// return;
// }
//
// ValueChangeMessage valueChangeMessage = new ValueChangeMessage(source, method, new ValueChangeMessage.Payload(variable, newValue));
// pushMessage(valueChangeMessage);
// }
//
// @Override
// public <T> void returning(Object source, String method, T returnValue) {
// ReturningMessage returningMessage = new ReturningMessage(source, method, returnValue);
// pushMessage(returningMessage);
// }
//
// @Override
// public void onError(Object source, String method, Throwable error) {
// OnErrorMessage onErrorMessage = new OnErrorMessage(source, method, error);
// pushMessage(onErrorMessage);
// }
//
// @Override
// public void timeout(Object source, String method, long timeoutThreshold, long timeout) {
// TimeoutMessage timeoutMessage = new TimeoutMessage(source, method, new Object[]{timeoutThreshold, timeout});
// pushMessage(timeoutMessage);
// }
// }
//
// Path: ghostwriter-test-java-v7/src/main/java/io/ghostwriter/InMemoryTracerProvider.java
// public enum InMemoryTracerProvider implements TracerProvider<InMemoryTracer> {
// INSTANCE;
//
// private final InMemoryTracer tracer;
//
// InMemoryTracerProvider() {
// tracer = new InMemoryTracer();
// }
//
// @Override
// public InMemoryTracer getTracer() {
// return tracer;
// }
//
// }
| import io.ghostwriter.InMemoryTracer;
import io.ghostwriter.InMemoryTracerProvider;
import io.ghostwriter.message.*;
import java.util.*;
import static org.junit.Assert.assertTrue; | package io.ghostwriter.test;
public class MessageSequenceAsserter {
public static final int NUMBER_OF_ENTRIES_PER_TRACED_PARAMETER = 2; // first value should be the name, the second one is the value of the parameter
private final Iterator<Message<?>> messages;
| // Path: ghostwriter-test-java-v7/src/main/java/io/ghostwriter/InMemoryTracer.java
// public class InMemoryTracer implements Tracer {
//
// private final Queue<Message<?>> messageStack;
// // by default we don't want to generate more messages then necessary for testing
// private boolean doTrackValueChanges = false;
//
// private boolean doTrackEnteringExiting = true;
//
// public InMemoryTracer() {
// messageStack = Collections.asLifoQueue(new ArrayDeque<Message<?>>());
// }
//
// public Message<?> popMessage() {
// return messageStack.remove();
// }
//
// public void pushMessage(Message<?> msg) {
// messageStack.add(msg);
// }
//
// public void clearMessages() {
// messageStack.clear();
// }
//
// public void enableValueChangeTracking() {
// doTrackValueChanges = true;
// }
//
// public void disableValueChangeTracking() {
// doTrackValueChanges = false;
// }
//
// public void enableEnteringExitingTracking() {
// doTrackEnteringExiting = true;
// }
//
// public void disableEnteringExitingTracking() {
// doTrackEnteringExiting = false;
// }
//
// public int numberOfMessages() {
// return messageStack.size();
// }
//
// public Queue<Message<?>> getMessages() {
// return messageStack;
// }
//
// @Override
// public void entering(Object source, String method, Object... params) {
// if (!doTrackEnteringExiting) {
// return;
// }
//
// EnteringMessage enteringMessage;
// if (params.length == 0) {
// enteringMessage = new EnteringMessage(source, method);
// }
// else {
// EnteringMessage.Payload payload = new EnteringMessage.Payload(params);
// enteringMessage = new EnteringMessage(source, method, payload);
// }
//
// pushMessage(enteringMessage);
// }
//
// @Override
// public void exiting(Object source, String method) {
// if (!doTrackEnteringExiting) {
// return;
// }
//
// ExitingMessage exitingMessage = new ExitingMessage(source, method);
// pushMessage(exitingMessage);
// }
//
// @Override
// public void valueChange(Object source, String method, String variable, Object newValue) {
// if (!doTrackValueChanges) {
// return;
// }
//
// ValueChangeMessage valueChangeMessage = new ValueChangeMessage(source, method, new ValueChangeMessage.Payload(variable, newValue));
// pushMessage(valueChangeMessage);
// }
//
// @Override
// public <T> void returning(Object source, String method, T returnValue) {
// ReturningMessage returningMessage = new ReturningMessage(source, method, returnValue);
// pushMessage(returningMessage);
// }
//
// @Override
// public void onError(Object source, String method, Throwable error) {
// OnErrorMessage onErrorMessage = new OnErrorMessage(source, method, error);
// pushMessage(onErrorMessage);
// }
//
// @Override
// public void timeout(Object source, String method, long timeoutThreshold, long timeout) {
// TimeoutMessage timeoutMessage = new TimeoutMessage(source, method, new Object[]{timeoutThreshold, timeout});
// pushMessage(timeoutMessage);
// }
// }
//
// Path: ghostwriter-test-java-v7/src/main/java/io/ghostwriter/InMemoryTracerProvider.java
// public enum InMemoryTracerProvider implements TracerProvider<InMemoryTracer> {
// INSTANCE;
//
// private final InMemoryTracer tracer;
//
// InMemoryTracerProvider() {
// tracer = new InMemoryTracer();
// }
//
// @Override
// public InMemoryTracer getTracer() {
// return tracer;
// }
//
// }
// Path: ghostwriter-test-java-v7/src/main/java/io/ghostwriter/test/MessageSequenceAsserter.java
import io.ghostwriter.InMemoryTracer;
import io.ghostwriter.InMemoryTracerProvider;
import io.ghostwriter.message.*;
import java.util.*;
import static org.junit.Assert.assertTrue;
package io.ghostwriter.test;
public class MessageSequenceAsserter {
public static final int NUMBER_OF_ENTRIES_PER_TRACED_PARAMETER = 2; // first value should be the name, the second one is the value of the parameter
private final Iterator<Message<?>> messages;
| static private InMemoryTracer getTracer() { |
GoodGrind/ghostwriter | ghostwriter-test-java-v7/src/main/java/io/ghostwriter/test/MessageSequenceAsserter.java | // Path: ghostwriter-test-java-v7/src/main/java/io/ghostwriter/InMemoryTracer.java
// public class InMemoryTracer implements Tracer {
//
// private final Queue<Message<?>> messageStack;
// // by default we don't want to generate more messages then necessary for testing
// private boolean doTrackValueChanges = false;
//
// private boolean doTrackEnteringExiting = true;
//
// public InMemoryTracer() {
// messageStack = Collections.asLifoQueue(new ArrayDeque<Message<?>>());
// }
//
// public Message<?> popMessage() {
// return messageStack.remove();
// }
//
// public void pushMessage(Message<?> msg) {
// messageStack.add(msg);
// }
//
// public void clearMessages() {
// messageStack.clear();
// }
//
// public void enableValueChangeTracking() {
// doTrackValueChanges = true;
// }
//
// public void disableValueChangeTracking() {
// doTrackValueChanges = false;
// }
//
// public void enableEnteringExitingTracking() {
// doTrackEnteringExiting = true;
// }
//
// public void disableEnteringExitingTracking() {
// doTrackEnteringExiting = false;
// }
//
// public int numberOfMessages() {
// return messageStack.size();
// }
//
// public Queue<Message<?>> getMessages() {
// return messageStack;
// }
//
// @Override
// public void entering(Object source, String method, Object... params) {
// if (!doTrackEnteringExiting) {
// return;
// }
//
// EnteringMessage enteringMessage;
// if (params.length == 0) {
// enteringMessage = new EnteringMessage(source, method);
// }
// else {
// EnteringMessage.Payload payload = new EnteringMessage.Payload(params);
// enteringMessage = new EnteringMessage(source, method, payload);
// }
//
// pushMessage(enteringMessage);
// }
//
// @Override
// public void exiting(Object source, String method) {
// if (!doTrackEnteringExiting) {
// return;
// }
//
// ExitingMessage exitingMessage = new ExitingMessage(source, method);
// pushMessage(exitingMessage);
// }
//
// @Override
// public void valueChange(Object source, String method, String variable, Object newValue) {
// if (!doTrackValueChanges) {
// return;
// }
//
// ValueChangeMessage valueChangeMessage = new ValueChangeMessage(source, method, new ValueChangeMessage.Payload(variable, newValue));
// pushMessage(valueChangeMessage);
// }
//
// @Override
// public <T> void returning(Object source, String method, T returnValue) {
// ReturningMessage returningMessage = new ReturningMessage(source, method, returnValue);
// pushMessage(returningMessage);
// }
//
// @Override
// public void onError(Object source, String method, Throwable error) {
// OnErrorMessage onErrorMessage = new OnErrorMessage(source, method, error);
// pushMessage(onErrorMessage);
// }
//
// @Override
// public void timeout(Object source, String method, long timeoutThreshold, long timeout) {
// TimeoutMessage timeoutMessage = new TimeoutMessage(source, method, new Object[]{timeoutThreshold, timeout});
// pushMessage(timeoutMessage);
// }
// }
//
// Path: ghostwriter-test-java-v7/src/main/java/io/ghostwriter/InMemoryTracerProvider.java
// public enum InMemoryTracerProvider implements TracerProvider<InMemoryTracer> {
// INSTANCE;
//
// private final InMemoryTracer tracer;
//
// InMemoryTracerProvider() {
// tracer = new InMemoryTracer();
// }
//
// @Override
// public InMemoryTracer getTracer() {
// return tracer;
// }
//
// }
| import io.ghostwriter.InMemoryTracer;
import io.ghostwriter.InMemoryTracerProvider;
import io.ghostwriter.message.*;
import java.util.*;
import static org.junit.Assert.assertTrue; | package io.ghostwriter.test;
public class MessageSequenceAsserter {
public static final int NUMBER_OF_ENTRIES_PER_TRACED_PARAMETER = 2; // first value should be the name, the second one is the value of the parameter
private final Iterator<Message<?>> messages;
static private InMemoryTracer getTracer() { | // Path: ghostwriter-test-java-v7/src/main/java/io/ghostwriter/InMemoryTracer.java
// public class InMemoryTracer implements Tracer {
//
// private final Queue<Message<?>> messageStack;
// // by default we don't want to generate more messages then necessary for testing
// private boolean doTrackValueChanges = false;
//
// private boolean doTrackEnteringExiting = true;
//
// public InMemoryTracer() {
// messageStack = Collections.asLifoQueue(new ArrayDeque<Message<?>>());
// }
//
// public Message<?> popMessage() {
// return messageStack.remove();
// }
//
// public void pushMessage(Message<?> msg) {
// messageStack.add(msg);
// }
//
// public void clearMessages() {
// messageStack.clear();
// }
//
// public void enableValueChangeTracking() {
// doTrackValueChanges = true;
// }
//
// public void disableValueChangeTracking() {
// doTrackValueChanges = false;
// }
//
// public void enableEnteringExitingTracking() {
// doTrackEnteringExiting = true;
// }
//
// public void disableEnteringExitingTracking() {
// doTrackEnteringExiting = false;
// }
//
// public int numberOfMessages() {
// return messageStack.size();
// }
//
// public Queue<Message<?>> getMessages() {
// return messageStack;
// }
//
// @Override
// public void entering(Object source, String method, Object... params) {
// if (!doTrackEnteringExiting) {
// return;
// }
//
// EnteringMessage enteringMessage;
// if (params.length == 0) {
// enteringMessage = new EnteringMessage(source, method);
// }
// else {
// EnteringMessage.Payload payload = new EnteringMessage.Payload(params);
// enteringMessage = new EnteringMessage(source, method, payload);
// }
//
// pushMessage(enteringMessage);
// }
//
// @Override
// public void exiting(Object source, String method) {
// if (!doTrackEnteringExiting) {
// return;
// }
//
// ExitingMessage exitingMessage = new ExitingMessage(source, method);
// pushMessage(exitingMessage);
// }
//
// @Override
// public void valueChange(Object source, String method, String variable, Object newValue) {
// if (!doTrackValueChanges) {
// return;
// }
//
// ValueChangeMessage valueChangeMessage = new ValueChangeMessage(source, method, new ValueChangeMessage.Payload(variable, newValue));
// pushMessage(valueChangeMessage);
// }
//
// @Override
// public <T> void returning(Object source, String method, T returnValue) {
// ReturningMessage returningMessage = new ReturningMessage(source, method, returnValue);
// pushMessage(returningMessage);
// }
//
// @Override
// public void onError(Object source, String method, Throwable error) {
// OnErrorMessage onErrorMessage = new OnErrorMessage(source, method, error);
// pushMessage(onErrorMessage);
// }
//
// @Override
// public void timeout(Object source, String method, long timeoutThreshold, long timeout) {
// TimeoutMessage timeoutMessage = new TimeoutMessage(source, method, new Object[]{timeoutThreshold, timeout});
// pushMessage(timeoutMessage);
// }
// }
//
// Path: ghostwriter-test-java-v7/src/main/java/io/ghostwriter/InMemoryTracerProvider.java
// public enum InMemoryTracerProvider implements TracerProvider<InMemoryTracer> {
// INSTANCE;
//
// private final InMemoryTracer tracer;
//
// InMemoryTracerProvider() {
// tracer = new InMemoryTracer();
// }
//
// @Override
// public InMemoryTracer getTracer() {
// return tracer;
// }
//
// }
// Path: ghostwriter-test-java-v7/src/main/java/io/ghostwriter/test/MessageSequenceAsserter.java
import io.ghostwriter.InMemoryTracer;
import io.ghostwriter.InMemoryTracerProvider;
import io.ghostwriter.message.*;
import java.util.*;
import static org.junit.Assert.assertTrue;
package io.ghostwriter.test;
public class MessageSequenceAsserter {
public static final int NUMBER_OF_ENTRIES_PER_TRACED_PARAMETER = 2; // first value should be the name, the second one is the value of the parameter
private final Iterator<Message<?>> messages;
static private InMemoryTracer getTracer() { | return InMemoryTracerProvider.INSTANCE.getTracer(); |
andrzejchm/RESTMock | androidsample/src/main/java/io/appflate/restmock/androidsample/view/activities/MainActivity.java | // Path: androidsample/src/main/java/io/appflate/restmock/androidsample/SampleApplication.java
// public class SampleApplication extends Application {
// private static final String BASE_URL = "https://api.github.com/";
// static AppComponent appComponent;
//
// @Override
// public void onCreate() {
// super.onCreate();
// setupGraph();
// }
//
// protected void setupGraph() {
// appComponent = DaggerAppComponent.builder()
// .appModule(new AppModule(BASE_URL, null, null))
// .build();
// }
//
// public static AppComponent getComponent() {
// return appComponent;
// }
// }
//
// Path: androidsample/src/main/java/io/appflate/restmock/androidsample/domain/GithubApi.java
// public interface GithubApi {
//
// @GET("users/{username}")
// Call<User> getUserProfile(@Path("username") String username);
//
// @GET("users/{username}/repos")
// Call<List<Repository>> getUserRepos(@Path("username") String username);
//
// }
//
// Path: androidsample/src/main/java/io/appflate/restmock/androidsample/model/User.java
// public class User {
// @SerializedName("login") public String login;
// @SerializedName("id") public int id;
// @SerializedName("avatar_url") public String avatarUrl;
// @SerializedName("gravatar_id") public String gravatarId;
// @SerializedName("url") public String url;
// @SerializedName("html_url") public String htmlUrl;
// @SerializedName("followers_url") public String followersUrl;
// @SerializedName("following_url") public String followingUrl;
// @SerializedName("gists_url") public String gistsUrl;
// @SerializedName("starred_url") public String starredUrl;
// @SerializedName("subscriptions_url") public String subscriptionsUrl;
// @SerializedName("organizations_url") public String organizationsUrl;
// @SerializedName("repos_url") public String reposUrl;
// @SerializedName("events_url") public String eventsUrl;
// @SerializedName("received_events_url") public String receivedEventsUrl;
// @SerializedName("type") public String type;
// @SerializedName("site_admin") public boolean siteAdmin;
// @SerializedName("name") public String name;
// @SerializedName("company") public String company;
// @SerializedName("blog") public String blog;
// @SerializedName("location") public String location;
// @SerializedName("email") public String email;
// @SerializedName("hireable") public boolean hireable;
// @SerializedName("bio") public String bio;
// @SerializedName("public_repos") public int publicRepos;
// @SerializedName("public_gists") public int publicGists;
// @SerializedName("followers") public int followers;
// @SerializedName("following") public int following;
// @SerializedName("created_at") public String createdAt;
// @SerializedName("updated_at") public String updatedAt;
// }
//
// Path: androidsample/src/main/java/io/appflate/restmock/androidsample/utils/Utils.java
// public class Utils {
// public static void hideKeyboard(Activity activity) {
// InputMethodManager inputManager =
// (InputMethodManager) activity.getSystemService(Context.INPUT_METHOD_SERVICE);
// inputManager.hideSoftInputFromWindow(
// activity.findViewById(android.R.id.content).getWindowToken(),
// InputMethodManager.HIDE_NOT_ALWAYS);
// }
// }
| import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.ViewAnimator;
import java.util.Locale;
import javax.inject.Inject;
import androidx.appcompat.app.AppCompatActivity;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import io.appflate.restmock.androidsample.R;
import io.appflate.restmock.androidsample.SampleApplication;
import io.appflate.restmock.androidsample.domain.GithubApi;
import io.appflate.restmock.androidsample.model.User;
import io.appflate.restmock.androidsample.utils.Utils;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response; | /*
* Copyright (C) 2016 Appflate.io
*
* 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 io.appflate.restmock.androidsample.view.activities;
public class MainActivity extends AppCompatActivity {
private static final int POSITION_CONTENT_VIEW = 0;
private static final int POSITION_PROGRESS_VIEW = 1; | // Path: androidsample/src/main/java/io/appflate/restmock/androidsample/SampleApplication.java
// public class SampleApplication extends Application {
// private static final String BASE_URL = "https://api.github.com/";
// static AppComponent appComponent;
//
// @Override
// public void onCreate() {
// super.onCreate();
// setupGraph();
// }
//
// protected void setupGraph() {
// appComponent = DaggerAppComponent.builder()
// .appModule(new AppModule(BASE_URL, null, null))
// .build();
// }
//
// public static AppComponent getComponent() {
// return appComponent;
// }
// }
//
// Path: androidsample/src/main/java/io/appflate/restmock/androidsample/domain/GithubApi.java
// public interface GithubApi {
//
// @GET("users/{username}")
// Call<User> getUserProfile(@Path("username") String username);
//
// @GET("users/{username}/repos")
// Call<List<Repository>> getUserRepos(@Path("username") String username);
//
// }
//
// Path: androidsample/src/main/java/io/appflate/restmock/androidsample/model/User.java
// public class User {
// @SerializedName("login") public String login;
// @SerializedName("id") public int id;
// @SerializedName("avatar_url") public String avatarUrl;
// @SerializedName("gravatar_id") public String gravatarId;
// @SerializedName("url") public String url;
// @SerializedName("html_url") public String htmlUrl;
// @SerializedName("followers_url") public String followersUrl;
// @SerializedName("following_url") public String followingUrl;
// @SerializedName("gists_url") public String gistsUrl;
// @SerializedName("starred_url") public String starredUrl;
// @SerializedName("subscriptions_url") public String subscriptionsUrl;
// @SerializedName("organizations_url") public String organizationsUrl;
// @SerializedName("repos_url") public String reposUrl;
// @SerializedName("events_url") public String eventsUrl;
// @SerializedName("received_events_url") public String receivedEventsUrl;
// @SerializedName("type") public String type;
// @SerializedName("site_admin") public boolean siteAdmin;
// @SerializedName("name") public String name;
// @SerializedName("company") public String company;
// @SerializedName("blog") public String blog;
// @SerializedName("location") public String location;
// @SerializedName("email") public String email;
// @SerializedName("hireable") public boolean hireable;
// @SerializedName("bio") public String bio;
// @SerializedName("public_repos") public int publicRepos;
// @SerializedName("public_gists") public int publicGists;
// @SerializedName("followers") public int followers;
// @SerializedName("following") public int following;
// @SerializedName("created_at") public String createdAt;
// @SerializedName("updated_at") public String updatedAt;
// }
//
// Path: androidsample/src/main/java/io/appflate/restmock/androidsample/utils/Utils.java
// public class Utils {
// public static void hideKeyboard(Activity activity) {
// InputMethodManager inputManager =
// (InputMethodManager) activity.getSystemService(Context.INPUT_METHOD_SERVICE);
// inputManager.hideSoftInputFromWindow(
// activity.findViewById(android.R.id.content).getWindowToken(),
// InputMethodManager.HIDE_NOT_ALWAYS);
// }
// }
// Path: androidsample/src/main/java/io/appflate/restmock/androidsample/view/activities/MainActivity.java
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.ViewAnimator;
import java.util.Locale;
import javax.inject.Inject;
import androidx.appcompat.app.AppCompatActivity;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import io.appflate.restmock.androidsample.R;
import io.appflate.restmock.androidsample.SampleApplication;
import io.appflate.restmock.androidsample.domain.GithubApi;
import io.appflate.restmock.androidsample.model.User;
import io.appflate.restmock.androidsample.utils.Utils;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
/*
* Copyright (C) 2016 Appflate.io
*
* 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 io.appflate.restmock.androidsample.view.activities;
public class MainActivity extends AppCompatActivity {
private static final int POSITION_CONTENT_VIEW = 0;
private static final int POSITION_PROGRESS_VIEW = 1; | @Inject GithubApi githubApi; |
andrzejchm/RESTMock | androidsample/src/main/java/io/appflate/restmock/androidsample/view/activities/MainActivity.java | // Path: androidsample/src/main/java/io/appflate/restmock/androidsample/SampleApplication.java
// public class SampleApplication extends Application {
// private static final String BASE_URL = "https://api.github.com/";
// static AppComponent appComponent;
//
// @Override
// public void onCreate() {
// super.onCreate();
// setupGraph();
// }
//
// protected void setupGraph() {
// appComponent = DaggerAppComponent.builder()
// .appModule(new AppModule(BASE_URL, null, null))
// .build();
// }
//
// public static AppComponent getComponent() {
// return appComponent;
// }
// }
//
// Path: androidsample/src/main/java/io/appflate/restmock/androidsample/domain/GithubApi.java
// public interface GithubApi {
//
// @GET("users/{username}")
// Call<User> getUserProfile(@Path("username") String username);
//
// @GET("users/{username}/repos")
// Call<List<Repository>> getUserRepos(@Path("username") String username);
//
// }
//
// Path: androidsample/src/main/java/io/appflate/restmock/androidsample/model/User.java
// public class User {
// @SerializedName("login") public String login;
// @SerializedName("id") public int id;
// @SerializedName("avatar_url") public String avatarUrl;
// @SerializedName("gravatar_id") public String gravatarId;
// @SerializedName("url") public String url;
// @SerializedName("html_url") public String htmlUrl;
// @SerializedName("followers_url") public String followersUrl;
// @SerializedName("following_url") public String followingUrl;
// @SerializedName("gists_url") public String gistsUrl;
// @SerializedName("starred_url") public String starredUrl;
// @SerializedName("subscriptions_url") public String subscriptionsUrl;
// @SerializedName("organizations_url") public String organizationsUrl;
// @SerializedName("repos_url") public String reposUrl;
// @SerializedName("events_url") public String eventsUrl;
// @SerializedName("received_events_url") public String receivedEventsUrl;
// @SerializedName("type") public String type;
// @SerializedName("site_admin") public boolean siteAdmin;
// @SerializedName("name") public String name;
// @SerializedName("company") public String company;
// @SerializedName("blog") public String blog;
// @SerializedName("location") public String location;
// @SerializedName("email") public String email;
// @SerializedName("hireable") public boolean hireable;
// @SerializedName("bio") public String bio;
// @SerializedName("public_repos") public int publicRepos;
// @SerializedName("public_gists") public int publicGists;
// @SerializedName("followers") public int followers;
// @SerializedName("following") public int following;
// @SerializedName("created_at") public String createdAt;
// @SerializedName("updated_at") public String updatedAt;
// }
//
// Path: androidsample/src/main/java/io/appflate/restmock/androidsample/utils/Utils.java
// public class Utils {
// public static void hideKeyboard(Activity activity) {
// InputMethodManager inputManager =
// (InputMethodManager) activity.getSystemService(Context.INPUT_METHOD_SERVICE);
// inputManager.hideSoftInputFromWindow(
// activity.findViewById(android.R.id.content).getWindowToken(),
// InputMethodManager.HIDE_NOT_ALWAYS);
// }
// }
| import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.ViewAnimator;
import java.util.Locale;
import javax.inject.Inject;
import androidx.appcompat.app.AppCompatActivity;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import io.appflate.restmock.androidsample.R;
import io.appflate.restmock.androidsample.SampleApplication;
import io.appflate.restmock.androidsample.domain.GithubApi;
import io.appflate.restmock.androidsample.model.User;
import io.appflate.restmock.androidsample.utils.Utils;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response; | /*
* Copyright (C) 2016 Appflate.io
*
* 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 io.appflate.restmock.androidsample.view.activities;
public class MainActivity extends AppCompatActivity {
private static final int POSITION_CONTENT_VIEW = 0;
private static final int POSITION_PROGRESS_VIEW = 1;
@Inject GithubApi githubApi;
@BindView(R.id.fullNameText) TextView fullNameTextView;
@BindView(R.id.showReposButton) Button showReposButton;
@BindView(R.id.usernameEditText) EditText usernameEditText;
@BindView(R.id.resultAnimator) ViewAnimator resultAnimator;
private String currentUsername;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ButterKnife.bind(this); | // Path: androidsample/src/main/java/io/appflate/restmock/androidsample/SampleApplication.java
// public class SampleApplication extends Application {
// private static final String BASE_URL = "https://api.github.com/";
// static AppComponent appComponent;
//
// @Override
// public void onCreate() {
// super.onCreate();
// setupGraph();
// }
//
// protected void setupGraph() {
// appComponent = DaggerAppComponent.builder()
// .appModule(new AppModule(BASE_URL, null, null))
// .build();
// }
//
// public static AppComponent getComponent() {
// return appComponent;
// }
// }
//
// Path: androidsample/src/main/java/io/appflate/restmock/androidsample/domain/GithubApi.java
// public interface GithubApi {
//
// @GET("users/{username}")
// Call<User> getUserProfile(@Path("username") String username);
//
// @GET("users/{username}/repos")
// Call<List<Repository>> getUserRepos(@Path("username") String username);
//
// }
//
// Path: androidsample/src/main/java/io/appflate/restmock/androidsample/model/User.java
// public class User {
// @SerializedName("login") public String login;
// @SerializedName("id") public int id;
// @SerializedName("avatar_url") public String avatarUrl;
// @SerializedName("gravatar_id") public String gravatarId;
// @SerializedName("url") public String url;
// @SerializedName("html_url") public String htmlUrl;
// @SerializedName("followers_url") public String followersUrl;
// @SerializedName("following_url") public String followingUrl;
// @SerializedName("gists_url") public String gistsUrl;
// @SerializedName("starred_url") public String starredUrl;
// @SerializedName("subscriptions_url") public String subscriptionsUrl;
// @SerializedName("organizations_url") public String organizationsUrl;
// @SerializedName("repos_url") public String reposUrl;
// @SerializedName("events_url") public String eventsUrl;
// @SerializedName("received_events_url") public String receivedEventsUrl;
// @SerializedName("type") public String type;
// @SerializedName("site_admin") public boolean siteAdmin;
// @SerializedName("name") public String name;
// @SerializedName("company") public String company;
// @SerializedName("blog") public String blog;
// @SerializedName("location") public String location;
// @SerializedName("email") public String email;
// @SerializedName("hireable") public boolean hireable;
// @SerializedName("bio") public String bio;
// @SerializedName("public_repos") public int publicRepos;
// @SerializedName("public_gists") public int publicGists;
// @SerializedName("followers") public int followers;
// @SerializedName("following") public int following;
// @SerializedName("created_at") public String createdAt;
// @SerializedName("updated_at") public String updatedAt;
// }
//
// Path: androidsample/src/main/java/io/appflate/restmock/androidsample/utils/Utils.java
// public class Utils {
// public static void hideKeyboard(Activity activity) {
// InputMethodManager inputManager =
// (InputMethodManager) activity.getSystemService(Context.INPUT_METHOD_SERVICE);
// inputManager.hideSoftInputFromWindow(
// activity.findViewById(android.R.id.content).getWindowToken(),
// InputMethodManager.HIDE_NOT_ALWAYS);
// }
// }
// Path: androidsample/src/main/java/io/appflate/restmock/androidsample/view/activities/MainActivity.java
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.ViewAnimator;
import java.util.Locale;
import javax.inject.Inject;
import androidx.appcompat.app.AppCompatActivity;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import io.appflate.restmock.androidsample.R;
import io.appflate.restmock.androidsample.SampleApplication;
import io.appflate.restmock.androidsample.domain.GithubApi;
import io.appflate.restmock.androidsample.model.User;
import io.appflate.restmock.androidsample.utils.Utils;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
/*
* Copyright (C) 2016 Appflate.io
*
* 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 io.appflate.restmock.androidsample.view.activities;
public class MainActivity extends AppCompatActivity {
private static final int POSITION_CONTENT_VIEW = 0;
private static final int POSITION_PROGRESS_VIEW = 1;
@Inject GithubApi githubApi;
@BindView(R.id.fullNameText) TextView fullNameTextView;
@BindView(R.id.showReposButton) Button showReposButton;
@BindView(R.id.usernameEditText) EditText usernameEditText;
@BindView(R.id.resultAnimator) ViewAnimator resultAnimator;
private String currentUsername;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ButterKnife.bind(this); | SampleApplication.getComponent().inject(this); |
andrzejchm/RESTMock | androidsample/src/main/java/io/appflate/restmock/androidsample/view/activities/MainActivity.java | // Path: androidsample/src/main/java/io/appflate/restmock/androidsample/SampleApplication.java
// public class SampleApplication extends Application {
// private static final String BASE_URL = "https://api.github.com/";
// static AppComponent appComponent;
//
// @Override
// public void onCreate() {
// super.onCreate();
// setupGraph();
// }
//
// protected void setupGraph() {
// appComponent = DaggerAppComponent.builder()
// .appModule(new AppModule(BASE_URL, null, null))
// .build();
// }
//
// public static AppComponent getComponent() {
// return appComponent;
// }
// }
//
// Path: androidsample/src/main/java/io/appflate/restmock/androidsample/domain/GithubApi.java
// public interface GithubApi {
//
// @GET("users/{username}")
// Call<User> getUserProfile(@Path("username") String username);
//
// @GET("users/{username}/repos")
// Call<List<Repository>> getUserRepos(@Path("username") String username);
//
// }
//
// Path: androidsample/src/main/java/io/appflate/restmock/androidsample/model/User.java
// public class User {
// @SerializedName("login") public String login;
// @SerializedName("id") public int id;
// @SerializedName("avatar_url") public String avatarUrl;
// @SerializedName("gravatar_id") public String gravatarId;
// @SerializedName("url") public String url;
// @SerializedName("html_url") public String htmlUrl;
// @SerializedName("followers_url") public String followersUrl;
// @SerializedName("following_url") public String followingUrl;
// @SerializedName("gists_url") public String gistsUrl;
// @SerializedName("starred_url") public String starredUrl;
// @SerializedName("subscriptions_url") public String subscriptionsUrl;
// @SerializedName("organizations_url") public String organizationsUrl;
// @SerializedName("repos_url") public String reposUrl;
// @SerializedName("events_url") public String eventsUrl;
// @SerializedName("received_events_url") public String receivedEventsUrl;
// @SerializedName("type") public String type;
// @SerializedName("site_admin") public boolean siteAdmin;
// @SerializedName("name") public String name;
// @SerializedName("company") public String company;
// @SerializedName("blog") public String blog;
// @SerializedName("location") public String location;
// @SerializedName("email") public String email;
// @SerializedName("hireable") public boolean hireable;
// @SerializedName("bio") public String bio;
// @SerializedName("public_repos") public int publicRepos;
// @SerializedName("public_gists") public int publicGists;
// @SerializedName("followers") public int followers;
// @SerializedName("following") public int following;
// @SerializedName("created_at") public String createdAt;
// @SerializedName("updated_at") public String updatedAt;
// }
//
// Path: androidsample/src/main/java/io/appflate/restmock/androidsample/utils/Utils.java
// public class Utils {
// public static void hideKeyboard(Activity activity) {
// InputMethodManager inputManager =
// (InputMethodManager) activity.getSystemService(Context.INPUT_METHOD_SERVICE);
// inputManager.hideSoftInputFromWindow(
// activity.findViewById(android.R.id.content).getWindowToken(),
// InputMethodManager.HIDE_NOT_ALWAYS);
// }
// }
| import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.ViewAnimator;
import java.util.Locale;
import javax.inject.Inject;
import androidx.appcompat.app.AppCompatActivity;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import io.appflate.restmock.androidsample.R;
import io.appflate.restmock.androidsample.SampleApplication;
import io.appflate.restmock.androidsample.domain.GithubApi;
import io.appflate.restmock.androidsample.model.User;
import io.appflate.restmock.androidsample.utils.Utils;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response; | /*
* Copyright (C) 2016 Appflate.io
*
* 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 io.appflate.restmock.androidsample.view.activities;
public class MainActivity extends AppCompatActivity {
private static final int POSITION_CONTENT_VIEW = 0;
private static final int POSITION_PROGRESS_VIEW = 1;
@Inject GithubApi githubApi;
@BindView(R.id.fullNameText) TextView fullNameTextView;
@BindView(R.id.showReposButton) Button showReposButton;
@BindView(R.id.usernameEditText) EditText usernameEditText;
@BindView(R.id.resultAnimator) ViewAnimator resultAnimator;
private String currentUsername;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ButterKnife.bind(this);
SampleApplication.getComponent().inject(this);
}
@OnClick(R.id.submitButton)
public void onSubmitClicked() { | // Path: androidsample/src/main/java/io/appflate/restmock/androidsample/SampleApplication.java
// public class SampleApplication extends Application {
// private static final String BASE_URL = "https://api.github.com/";
// static AppComponent appComponent;
//
// @Override
// public void onCreate() {
// super.onCreate();
// setupGraph();
// }
//
// protected void setupGraph() {
// appComponent = DaggerAppComponent.builder()
// .appModule(new AppModule(BASE_URL, null, null))
// .build();
// }
//
// public static AppComponent getComponent() {
// return appComponent;
// }
// }
//
// Path: androidsample/src/main/java/io/appflate/restmock/androidsample/domain/GithubApi.java
// public interface GithubApi {
//
// @GET("users/{username}")
// Call<User> getUserProfile(@Path("username") String username);
//
// @GET("users/{username}/repos")
// Call<List<Repository>> getUserRepos(@Path("username") String username);
//
// }
//
// Path: androidsample/src/main/java/io/appflate/restmock/androidsample/model/User.java
// public class User {
// @SerializedName("login") public String login;
// @SerializedName("id") public int id;
// @SerializedName("avatar_url") public String avatarUrl;
// @SerializedName("gravatar_id") public String gravatarId;
// @SerializedName("url") public String url;
// @SerializedName("html_url") public String htmlUrl;
// @SerializedName("followers_url") public String followersUrl;
// @SerializedName("following_url") public String followingUrl;
// @SerializedName("gists_url") public String gistsUrl;
// @SerializedName("starred_url") public String starredUrl;
// @SerializedName("subscriptions_url") public String subscriptionsUrl;
// @SerializedName("organizations_url") public String organizationsUrl;
// @SerializedName("repos_url") public String reposUrl;
// @SerializedName("events_url") public String eventsUrl;
// @SerializedName("received_events_url") public String receivedEventsUrl;
// @SerializedName("type") public String type;
// @SerializedName("site_admin") public boolean siteAdmin;
// @SerializedName("name") public String name;
// @SerializedName("company") public String company;
// @SerializedName("blog") public String blog;
// @SerializedName("location") public String location;
// @SerializedName("email") public String email;
// @SerializedName("hireable") public boolean hireable;
// @SerializedName("bio") public String bio;
// @SerializedName("public_repos") public int publicRepos;
// @SerializedName("public_gists") public int publicGists;
// @SerializedName("followers") public int followers;
// @SerializedName("following") public int following;
// @SerializedName("created_at") public String createdAt;
// @SerializedName("updated_at") public String updatedAt;
// }
//
// Path: androidsample/src/main/java/io/appflate/restmock/androidsample/utils/Utils.java
// public class Utils {
// public static void hideKeyboard(Activity activity) {
// InputMethodManager inputManager =
// (InputMethodManager) activity.getSystemService(Context.INPUT_METHOD_SERVICE);
// inputManager.hideSoftInputFromWindow(
// activity.findViewById(android.R.id.content).getWindowToken(),
// InputMethodManager.HIDE_NOT_ALWAYS);
// }
// }
// Path: androidsample/src/main/java/io/appflate/restmock/androidsample/view/activities/MainActivity.java
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.ViewAnimator;
import java.util.Locale;
import javax.inject.Inject;
import androidx.appcompat.app.AppCompatActivity;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import io.appflate.restmock.androidsample.R;
import io.appflate.restmock.androidsample.SampleApplication;
import io.appflate.restmock.androidsample.domain.GithubApi;
import io.appflate.restmock.androidsample.model.User;
import io.appflate.restmock.androidsample.utils.Utils;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
/*
* Copyright (C) 2016 Appflate.io
*
* 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 io.appflate.restmock.androidsample.view.activities;
public class MainActivity extends AppCompatActivity {
private static final int POSITION_CONTENT_VIEW = 0;
private static final int POSITION_PROGRESS_VIEW = 1;
@Inject GithubApi githubApi;
@BindView(R.id.fullNameText) TextView fullNameTextView;
@BindView(R.id.showReposButton) Button showReposButton;
@BindView(R.id.usernameEditText) EditText usernameEditText;
@BindView(R.id.resultAnimator) ViewAnimator resultAnimator;
private String currentUsername;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ButterKnife.bind(this);
SampleApplication.getComponent().inject(this);
}
@OnClick(R.id.submitButton)
public void onSubmitClicked() { | Utils.hideKeyboard(this); |
andrzejchm/RESTMock | androidsample/src/main/java/io/appflate/restmock/androidsample/view/activities/MainActivity.java | // Path: androidsample/src/main/java/io/appflate/restmock/androidsample/SampleApplication.java
// public class SampleApplication extends Application {
// private static final String BASE_URL = "https://api.github.com/";
// static AppComponent appComponent;
//
// @Override
// public void onCreate() {
// super.onCreate();
// setupGraph();
// }
//
// protected void setupGraph() {
// appComponent = DaggerAppComponent.builder()
// .appModule(new AppModule(BASE_URL, null, null))
// .build();
// }
//
// public static AppComponent getComponent() {
// return appComponent;
// }
// }
//
// Path: androidsample/src/main/java/io/appflate/restmock/androidsample/domain/GithubApi.java
// public interface GithubApi {
//
// @GET("users/{username}")
// Call<User> getUserProfile(@Path("username") String username);
//
// @GET("users/{username}/repos")
// Call<List<Repository>> getUserRepos(@Path("username") String username);
//
// }
//
// Path: androidsample/src/main/java/io/appflate/restmock/androidsample/model/User.java
// public class User {
// @SerializedName("login") public String login;
// @SerializedName("id") public int id;
// @SerializedName("avatar_url") public String avatarUrl;
// @SerializedName("gravatar_id") public String gravatarId;
// @SerializedName("url") public String url;
// @SerializedName("html_url") public String htmlUrl;
// @SerializedName("followers_url") public String followersUrl;
// @SerializedName("following_url") public String followingUrl;
// @SerializedName("gists_url") public String gistsUrl;
// @SerializedName("starred_url") public String starredUrl;
// @SerializedName("subscriptions_url") public String subscriptionsUrl;
// @SerializedName("organizations_url") public String organizationsUrl;
// @SerializedName("repos_url") public String reposUrl;
// @SerializedName("events_url") public String eventsUrl;
// @SerializedName("received_events_url") public String receivedEventsUrl;
// @SerializedName("type") public String type;
// @SerializedName("site_admin") public boolean siteAdmin;
// @SerializedName("name") public String name;
// @SerializedName("company") public String company;
// @SerializedName("blog") public String blog;
// @SerializedName("location") public String location;
// @SerializedName("email") public String email;
// @SerializedName("hireable") public boolean hireable;
// @SerializedName("bio") public String bio;
// @SerializedName("public_repos") public int publicRepos;
// @SerializedName("public_gists") public int publicGists;
// @SerializedName("followers") public int followers;
// @SerializedName("following") public int following;
// @SerializedName("created_at") public String createdAt;
// @SerializedName("updated_at") public String updatedAt;
// }
//
// Path: androidsample/src/main/java/io/appflate/restmock/androidsample/utils/Utils.java
// public class Utils {
// public static void hideKeyboard(Activity activity) {
// InputMethodManager inputManager =
// (InputMethodManager) activity.getSystemService(Context.INPUT_METHOD_SERVICE);
// inputManager.hideSoftInputFromWindow(
// activity.findViewById(android.R.id.content).getWindowToken(),
// InputMethodManager.HIDE_NOT_ALWAYS);
// }
// }
| import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.ViewAnimator;
import java.util.Locale;
import javax.inject.Inject;
import androidx.appcompat.app.AppCompatActivity;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import io.appflate.restmock.androidsample.R;
import io.appflate.restmock.androidsample.SampleApplication;
import io.appflate.restmock.androidsample.domain.GithubApi;
import io.appflate.restmock.androidsample.model.User;
import io.appflate.restmock.androidsample.utils.Utils;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response; | /*
* Copyright (C) 2016 Appflate.io
*
* 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 io.appflate.restmock.androidsample.view.activities;
public class MainActivity extends AppCompatActivity {
private static final int POSITION_CONTENT_VIEW = 0;
private static final int POSITION_PROGRESS_VIEW = 1;
@Inject GithubApi githubApi;
@BindView(R.id.fullNameText) TextView fullNameTextView;
@BindView(R.id.showReposButton) Button showReposButton;
@BindView(R.id.usernameEditText) EditText usernameEditText;
@BindView(R.id.resultAnimator) ViewAnimator resultAnimator;
private String currentUsername;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ButterKnife.bind(this);
SampleApplication.getComponent().inject(this);
}
@OnClick(R.id.submitButton)
public void onSubmitClicked() {
Utils.hideKeyboard(this);
currentUsername = usernameEditText.getText().toString();
resultAnimator.setDisplayedChild(POSITION_PROGRESS_VIEW); | // Path: androidsample/src/main/java/io/appflate/restmock/androidsample/SampleApplication.java
// public class SampleApplication extends Application {
// private static final String BASE_URL = "https://api.github.com/";
// static AppComponent appComponent;
//
// @Override
// public void onCreate() {
// super.onCreate();
// setupGraph();
// }
//
// protected void setupGraph() {
// appComponent = DaggerAppComponent.builder()
// .appModule(new AppModule(BASE_URL, null, null))
// .build();
// }
//
// public static AppComponent getComponent() {
// return appComponent;
// }
// }
//
// Path: androidsample/src/main/java/io/appflate/restmock/androidsample/domain/GithubApi.java
// public interface GithubApi {
//
// @GET("users/{username}")
// Call<User> getUserProfile(@Path("username") String username);
//
// @GET("users/{username}/repos")
// Call<List<Repository>> getUserRepos(@Path("username") String username);
//
// }
//
// Path: androidsample/src/main/java/io/appflate/restmock/androidsample/model/User.java
// public class User {
// @SerializedName("login") public String login;
// @SerializedName("id") public int id;
// @SerializedName("avatar_url") public String avatarUrl;
// @SerializedName("gravatar_id") public String gravatarId;
// @SerializedName("url") public String url;
// @SerializedName("html_url") public String htmlUrl;
// @SerializedName("followers_url") public String followersUrl;
// @SerializedName("following_url") public String followingUrl;
// @SerializedName("gists_url") public String gistsUrl;
// @SerializedName("starred_url") public String starredUrl;
// @SerializedName("subscriptions_url") public String subscriptionsUrl;
// @SerializedName("organizations_url") public String organizationsUrl;
// @SerializedName("repos_url") public String reposUrl;
// @SerializedName("events_url") public String eventsUrl;
// @SerializedName("received_events_url") public String receivedEventsUrl;
// @SerializedName("type") public String type;
// @SerializedName("site_admin") public boolean siteAdmin;
// @SerializedName("name") public String name;
// @SerializedName("company") public String company;
// @SerializedName("blog") public String blog;
// @SerializedName("location") public String location;
// @SerializedName("email") public String email;
// @SerializedName("hireable") public boolean hireable;
// @SerializedName("bio") public String bio;
// @SerializedName("public_repos") public int publicRepos;
// @SerializedName("public_gists") public int publicGists;
// @SerializedName("followers") public int followers;
// @SerializedName("following") public int following;
// @SerializedName("created_at") public String createdAt;
// @SerializedName("updated_at") public String updatedAt;
// }
//
// Path: androidsample/src/main/java/io/appflate/restmock/androidsample/utils/Utils.java
// public class Utils {
// public static void hideKeyboard(Activity activity) {
// InputMethodManager inputManager =
// (InputMethodManager) activity.getSystemService(Context.INPUT_METHOD_SERVICE);
// inputManager.hideSoftInputFromWindow(
// activity.findViewById(android.R.id.content).getWindowToken(),
// InputMethodManager.HIDE_NOT_ALWAYS);
// }
// }
// Path: androidsample/src/main/java/io/appflate/restmock/androidsample/view/activities/MainActivity.java
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.ViewAnimator;
import java.util.Locale;
import javax.inject.Inject;
import androidx.appcompat.app.AppCompatActivity;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import io.appflate.restmock.androidsample.R;
import io.appflate.restmock.androidsample.SampleApplication;
import io.appflate.restmock.androidsample.domain.GithubApi;
import io.appflate.restmock.androidsample.model.User;
import io.appflate.restmock.androidsample.utils.Utils;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
/*
* Copyright (C) 2016 Appflate.io
*
* 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 io.appflate.restmock.androidsample.view.activities;
public class MainActivity extends AppCompatActivity {
private static final int POSITION_CONTENT_VIEW = 0;
private static final int POSITION_PROGRESS_VIEW = 1;
@Inject GithubApi githubApi;
@BindView(R.id.fullNameText) TextView fullNameTextView;
@BindView(R.id.showReposButton) Button showReposButton;
@BindView(R.id.usernameEditText) EditText usernameEditText;
@BindView(R.id.resultAnimator) ViewAnimator resultAnimator;
private String currentUsername;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ButterKnife.bind(this);
SampleApplication.getComponent().inject(this);
}
@OnClick(R.id.submitButton)
public void onSubmitClicked() {
Utils.hideKeyboard(this);
currentUsername = usernameEditText.getText().toString();
resultAnimator.setDisplayedChild(POSITION_PROGRESS_VIEW); | githubApi.getUserProfile(currentUsername).enqueue(new Callback<User>() { |
andrzejchm/RESTMock | core/src/test/java/io/appflate/restmock/RequestsChainTest.java | // Path: core/src/test/java/io/appflate/restmock/utils/TestUtils.java
// public class TestUtils {
//
// private static final RequestBody EMPTY_JSON_BODY = RequestBody.create(MediaType.parse("application/json; charset=utf-8"), "");
// private static OkHttpClient okHttpClient =
// new OkHttpClient.Builder()
// .sslSocketFactory(RESTMockServer.getSSLSocketFactory(), RESTMockServer.getTrustManager())
// .protocols(Collections.singletonList(Protocol.HTTP_1_1))
// .build();
//
// public static Response get(String path) throws IOException {
// path = normalizePath(path);
// return executeSync(requestBuilder().url(RESTMockServer.getUrl() + path).build());
// }
//
// public static Response get(String path, Map.Entry<String, String>... headers) throws IOException {
// path = normalizePath(path);
// Request.Builder builder = new Request.Builder().url(RESTMockServer.getUrl() + path);
// for (Map.Entry<String, String> entry : headers) {
// builder.addHeader(entry.getKey(), entry.getValue());
// }
// return executeSync(builder.build());
// }
//
// public static Response post(String path) throws IOException {
// path = normalizePath(path);
// return executeSync(requestBuilder().url(RESTMockServer.getUrl() + path).method("POST", EMPTY_JSON_BODY).build());
// }
//
// public static Response put(String path) throws IOException {
// path = normalizePath(path);
// return executeSync(requestBuilder().url(RESTMockServer.getUrl() + path).method("PUT", EMPTY_JSON_BODY).build());
// }
//
// public static Response delete(String path) throws IOException {
// path = normalizePath(path);
// return executeSync(requestBuilder().url(RESTMockServer.getUrl() + path).method("DELETE", null).build());
// }
//
// public static Response head(String path) throws IOException {
// path = normalizePath(path);
// return executeSync(requestBuilder().url(RESTMockServer.getUrl() + path).method("HEAD", null).build());
// }
//
// private static Response executeSync(Request request) throws IOException {
// return okHttpClient.newCall(request).execute();
// }
//
// public static void assertNotMocked(Response response) throws IOException {
// assertResponseWithBodyContains(response, 500, RESTMockServer.RESPONSE_NOT_MOCKED);
// }
//
// public static void assertNotMockedNoBody(Response response) throws IOException {
// assertResponseCodeIs(response, 500);
// }
//
// public static void assertMultipleMatches(Response response) throws IOException {
// assertResponseWithBodyContains(response, 500, RESTMockServer.MORE_THAN_ONE_RESPONSE_ERROR);
// }
//
// public static void assertResponseCodeIs(Response response, int code) {
// assertEquals(code, response.code());
// }
//
// public static void assertResponseWithBodyContains(Response response, int code, String body) throws IOException {
// assertEquals(code, response.code());
// assertTrue(response.body().string().contains(body));
// }
//
// private static String normalizePath(String path) {
// if (path.startsWith("/")) {
// path = "/" + path;
// }
// return path;
// }
//
// private static Request.Builder requestBuilder() {
// return new Request.Builder().addHeader("Connection", "close");
// }
// }
//
// Path: core/src/main/java/io/appflate/restmock/utils/RequestMatchers.java
// public static RequestMatcher pathEndsWith(final String urlPart) {
// return new RequestMatcher("path ends with: " + urlPart) {
//
// @Override
// protected boolean matchesSafely(RecordedRequest item) {
// String urlPartWithoutEndingSlash = urlPart.replaceAll("/$", "");
// String itemPathWithoutEndingSlash = item.getPath().replaceAll("/$", "");
// return itemPathWithoutEndingSlash.toLowerCase(Locale.US).endsWith(urlPartWithoutEndingSlash.toLowerCase(Locale.US));
// }
// };
// }
| import okhttp3.mockwebserver.MockResponse;
import static io.appflate.restmock.utils.RequestMatchers.pathEndsWith;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.spy;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
import java.io.IOException;
import java.util.Arrays;
import java.util.Collection;
import java.util.Objects;
import java.util.concurrent.TimeUnit;
import io.appflate.restmock.utils.TestUtils;
import okhttp3.Response; | /*
* Copyright (C) 2016 Appflate.io
*
* 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 io.appflate.restmock;
/**
* Created by andrzejchm on 26/04/16.
*/
@RunWith(Parameterized.class)
public class RequestsChainTest {
private static final String path = "sample";
private final boolean useHttps;
@Parameterized.Parameters(name = "useHttps={0}")
public static Collection<Object> data() {
return Arrays.asList(new Object[]{
true, false
});
}
public RequestsChainTest(boolean useHttps) {
this.useHttps = useHttps;
}
@Before
public void setup() {
RESTMockFileParser fileParser = mock(RESTMockFileParser.class);
RESTMockServerStarter.startSync(fileParser, new RESTMockOptions.Builder().useHttps(useHttps).build());
RESTMockServer.dispatcher = spy(RESTMockServer.dispatcher);
}
@After
public void teardown() throws IOException {
RESTMockServer.shutdown();
}
@Test
public void noResponsesReturnsNotMocked() throws Exception { | // Path: core/src/test/java/io/appflate/restmock/utils/TestUtils.java
// public class TestUtils {
//
// private static final RequestBody EMPTY_JSON_BODY = RequestBody.create(MediaType.parse("application/json; charset=utf-8"), "");
// private static OkHttpClient okHttpClient =
// new OkHttpClient.Builder()
// .sslSocketFactory(RESTMockServer.getSSLSocketFactory(), RESTMockServer.getTrustManager())
// .protocols(Collections.singletonList(Protocol.HTTP_1_1))
// .build();
//
// public static Response get(String path) throws IOException {
// path = normalizePath(path);
// return executeSync(requestBuilder().url(RESTMockServer.getUrl() + path).build());
// }
//
// public static Response get(String path, Map.Entry<String, String>... headers) throws IOException {
// path = normalizePath(path);
// Request.Builder builder = new Request.Builder().url(RESTMockServer.getUrl() + path);
// for (Map.Entry<String, String> entry : headers) {
// builder.addHeader(entry.getKey(), entry.getValue());
// }
// return executeSync(builder.build());
// }
//
// public static Response post(String path) throws IOException {
// path = normalizePath(path);
// return executeSync(requestBuilder().url(RESTMockServer.getUrl() + path).method("POST", EMPTY_JSON_BODY).build());
// }
//
// public static Response put(String path) throws IOException {
// path = normalizePath(path);
// return executeSync(requestBuilder().url(RESTMockServer.getUrl() + path).method("PUT", EMPTY_JSON_BODY).build());
// }
//
// public static Response delete(String path) throws IOException {
// path = normalizePath(path);
// return executeSync(requestBuilder().url(RESTMockServer.getUrl() + path).method("DELETE", null).build());
// }
//
// public static Response head(String path) throws IOException {
// path = normalizePath(path);
// return executeSync(requestBuilder().url(RESTMockServer.getUrl() + path).method("HEAD", null).build());
// }
//
// private static Response executeSync(Request request) throws IOException {
// return okHttpClient.newCall(request).execute();
// }
//
// public static void assertNotMocked(Response response) throws IOException {
// assertResponseWithBodyContains(response, 500, RESTMockServer.RESPONSE_NOT_MOCKED);
// }
//
// public static void assertNotMockedNoBody(Response response) throws IOException {
// assertResponseCodeIs(response, 500);
// }
//
// public static void assertMultipleMatches(Response response) throws IOException {
// assertResponseWithBodyContains(response, 500, RESTMockServer.MORE_THAN_ONE_RESPONSE_ERROR);
// }
//
// public static void assertResponseCodeIs(Response response, int code) {
// assertEquals(code, response.code());
// }
//
// public static void assertResponseWithBodyContains(Response response, int code, String body) throws IOException {
// assertEquals(code, response.code());
// assertTrue(response.body().string().contains(body));
// }
//
// private static String normalizePath(String path) {
// if (path.startsWith("/")) {
// path = "/" + path;
// }
// return path;
// }
//
// private static Request.Builder requestBuilder() {
// return new Request.Builder().addHeader("Connection", "close");
// }
// }
//
// Path: core/src/main/java/io/appflate/restmock/utils/RequestMatchers.java
// public static RequestMatcher pathEndsWith(final String urlPart) {
// return new RequestMatcher("path ends with: " + urlPart) {
//
// @Override
// protected boolean matchesSafely(RecordedRequest item) {
// String urlPartWithoutEndingSlash = urlPart.replaceAll("/$", "");
// String itemPathWithoutEndingSlash = item.getPath().replaceAll("/$", "");
// return itemPathWithoutEndingSlash.toLowerCase(Locale.US).endsWith(urlPartWithoutEndingSlash.toLowerCase(Locale.US));
// }
// };
// }
// Path: core/src/test/java/io/appflate/restmock/RequestsChainTest.java
import okhttp3.mockwebserver.MockResponse;
import static io.appflate.restmock.utils.RequestMatchers.pathEndsWith;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.spy;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
import java.io.IOException;
import java.util.Arrays;
import java.util.Collection;
import java.util.Objects;
import java.util.concurrent.TimeUnit;
import io.appflate.restmock.utils.TestUtils;
import okhttp3.Response;
/*
* Copyright (C) 2016 Appflate.io
*
* 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 io.appflate.restmock;
/**
* Created by andrzejchm on 26/04/16.
*/
@RunWith(Parameterized.class)
public class RequestsChainTest {
private static final String path = "sample";
private final boolean useHttps;
@Parameterized.Parameters(name = "useHttps={0}")
public static Collection<Object> data() {
return Arrays.asList(new Object[]{
true, false
});
}
public RequestsChainTest(boolean useHttps) {
this.useHttps = useHttps;
}
@Before
public void setup() {
RESTMockFileParser fileParser = mock(RESTMockFileParser.class);
RESTMockServerStarter.startSync(fileParser, new RESTMockOptions.Builder().useHttps(useHttps).build());
RESTMockServer.dispatcher = spy(RESTMockServer.dispatcher);
}
@After
public void teardown() throws IOException {
RESTMockServer.shutdown();
}
@Test
public void noResponsesReturnsNotMocked() throws Exception { | RESTMockServer.whenRequested(pathEndsWith(path)).thenReturn((MockResponse) null); |
andrzejchm/RESTMock | core/src/test/java/io/appflate/restmock/RESTMockServerTest.java | // Path: core/src/test/java/io/appflate/restmock/utils/TestUtils.java
// public class TestUtils {
//
// private static final RequestBody EMPTY_JSON_BODY = RequestBody.create(MediaType.parse("application/json; charset=utf-8"), "");
// private static OkHttpClient okHttpClient =
// new OkHttpClient.Builder()
// .sslSocketFactory(RESTMockServer.getSSLSocketFactory(), RESTMockServer.getTrustManager())
// .protocols(Collections.singletonList(Protocol.HTTP_1_1))
// .build();
//
// public static Response get(String path) throws IOException {
// path = normalizePath(path);
// return executeSync(requestBuilder().url(RESTMockServer.getUrl() + path).build());
// }
//
// public static Response get(String path, Map.Entry<String, String>... headers) throws IOException {
// path = normalizePath(path);
// Request.Builder builder = new Request.Builder().url(RESTMockServer.getUrl() + path);
// for (Map.Entry<String, String> entry : headers) {
// builder.addHeader(entry.getKey(), entry.getValue());
// }
// return executeSync(builder.build());
// }
//
// public static Response post(String path) throws IOException {
// path = normalizePath(path);
// return executeSync(requestBuilder().url(RESTMockServer.getUrl() + path).method("POST", EMPTY_JSON_BODY).build());
// }
//
// public static Response put(String path) throws IOException {
// path = normalizePath(path);
// return executeSync(requestBuilder().url(RESTMockServer.getUrl() + path).method("PUT", EMPTY_JSON_BODY).build());
// }
//
// public static Response delete(String path) throws IOException {
// path = normalizePath(path);
// return executeSync(requestBuilder().url(RESTMockServer.getUrl() + path).method("DELETE", null).build());
// }
//
// public static Response head(String path) throws IOException {
// path = normalizePath(path);
// return executeSync(requestBuilder().url(RESTMockServer.getUrl() + path).method("HEAD", null).build());
// }
//
// private static Response executeSync(Request request) throws IOException {
// return okHttpClient.newCall(request).execute();
// }
//
// public static void assertNotMocked(Response response) throws IOException {
// assertResponseWithBodyContains(response, 500, RESTMockServer.RESPONSE_NOT_MOCKED);
// }
//
// public static void assertNotMockedNoBody(Response response) throws IOException {
// assertResponseCodeIs(response, 500);
// }
//
// public static void assertMultipleMatches(Response response) throws IOException {
// assertResponseWithBodyContains(response, 500, RESTMockServer.MORE_THAN_ONE_RESPONSE_ERROR);
// }
//
// public static void assertResponseCodeIs(Response response, int code) {
// assertEquals(code, response.code());
// }
//
// public static void assertResponseWithBodyContains(Response response, int code, String body) throws IOException {
// assertEquals(code, response.code());
// assertTrue(response.body().string().contains(body));
// }
//
// private static String normalizePath(String path) {
// if (path.startsWith("/")) {
// path = "/" + path;
// }
// return path;
// }
//
// private static Request.Builder requestBuilder() {
// return new Request.Builder().addHeader("Connection", "close");
// }
// }
//
// Path: core/src/main/java/io/appflate/restmock/utils/RequestMatchers.java
// public static RequestMatcher pathEndsWith(final String urlPart) {
// return new RequestMatcher("path ends with: " + urlPart) {
//
// @Override
// protected boolean matchesSafely(RecordedRequest item) {
// String urlPartWithoutEndingSlash = urlPart.replaceAll("/$", "");
// String itemPathWithoutEndingSlash = item.getPath().replaceAll("/$", "");
// return itemPathWithoutEndingSlash.toLowerCase(Locale.US).endsWith(urlPartWithoutEndingSlash.toLowerCase(Locale.US));
// }
// };
// }
| import io.appflate.restmock.utils.TestUtils;
import java.io.IOException;
import java.util.AbstractMap;
import java.util.Arrays;
import java.util.Collection;
import okhttp3.Response;
import okhttp3.mockwebserver.MockResponse;
import okhttp3.mockwebserver.RecordedRequest;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
import static io.appflate.restmock.utils.RequestMatchers.pathEndsWith;
import static junit.framework.TestCase.assertEquals;
import static junit.framework.TestCase.assertNotNull;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.spy;
import static org.mockito.Mockito.verify; | public static Collection<Object> data() {
return Arrays.asList(new Object[] {
true, false
});
}
public RESTMockServerTest(boolean useHttps) {
this.useHttps = useHttps;
}
@Before
public void setup() {
fileParser = mock(RESTMockFileParser.class);
RESTMockServerStarter.startSync(fileParser, new RESTMockOptions.Builder().useHttps(useHttps).build());
RESTMockServer.dispatcher = spy(RESTMockServer.dispatcher);
}
@After
public void teardown() throws IOException {
RESTMockServer.shutdown();
}
@Test
public void testWhenGET() throws Exception {
String path = "/sample";
String worksBody = "works";
MatchableCall matchableCall = RESTMockServer.whenGET(pathEndsWith(path));
assertNotNull(matchableCall);
assertEquals(0, matchableCall.getNumberOfAnswers());
verify(RESTMockServer.dispatcher, never()).addMatchableCall(matchableCall); | // Path: core/src/test/java/io/appflate/restmock/utils/TestUtils.java
// public class TestUtils {
//
// private static final RequestBody EMPTY_JSON_BODY = RequestBody.create(MediaType.parse("application/json; charset=utf-8"), "");
// private static OkHttpClient okHttpClient =
// new OkHttpClient.Builder()
// .sslSocketFactory(RESTMockServer.getSSLSocketFactory(), RESTMockServer.getTrustManager())
// .protocols(Collections.singletonList(Protocol.HTTP_1_1))
// .build();
//
// public static Response get(String path) throws IOException {
// path = normalizePath(path);
// return executeSync(requestBuilder().url(RESTMockServer.getUrl() + path).build());
// }
//
// public static Response get(String path, Map.Entry<String, String>... headers) throws IOException {
// path = normalizePath(path);
// Request.Builder builder = new Request.Builder().url(RESTMockServer.getUrl() + path);
// for (Map.Entry<String, String> entry : headers) {
// builder.addHeader(entry.getKey(), entry.getValue());
// }
// return executeSync(builder.build());
// }
//
// public static Response post(String path) throws IOException {
// path = normalizePath(path);
// return executeSync(requestBuilder().url(RESTMockServer.getUrl() + path).method("POST", EMPTY_JSON_BODY).build());
// }
//
// public static Response put(String path) throws IOException {
// path = normalizePath(path);
// return executeSync(requestBuilder().url(RESTMockServer.getUrl() + path).method("PUT", EMPTY_JSON_BODY).build());
// }
//
// public static Response delete(String path) throws IOException {
// path = normalizePath(path);
// return executeSync(requestBuilder().url(RESTMockServer.getUrl() + path).method("DELETE", null).build());
// }
//
// public static Response head(String path) throws IOException {
// path = normalizePath(path);
// return executeSync(requestBuilder().url(RESTMockServer.getUrl() + path).method("HEAD", null).build());
// }
//
// private static Response executeSync(Request request) throws IOException {
// return okHttpClient.newCall(request).execute();
// }
//
// public static void assertNotMocked(Response response) throws IOException {
// assertResponseWithBodyContains(response, 500, RESTMockServer.RESPONSE_NOT_MOCKED);
// }
//
// public static void assertNotMockedNoBody(Response response) throws IOException {
// assertResponseCodeIs(response, 500);
// }
//
// public static void assertMultipleMatches(Response response) throws IOException {
// assertResponseWithBodyContains(response, 500, RESTMockServer.MORE_THAN_ONE_RESPONSE_ERROR);
// }
//
// public static void assertResponseCodeIs(Response response, int code) {
// assertEquals(code, response.code());
// }
//
// public static void assertResponseWithBodyContains(Response response, int code, String body) throws IOException {
// assertEquals(code, response.code());
// assertTrue(response.body().string().contains(body));
// }
//
// private static String normalizePath(String path) {
// if (path.startsWith("/")) {
// path = "/" + path;
// }
// return path;
// }
//
// private static Request.Builder requestBuilder() {
// return new Request.Builder().addHeader("Connection", "close");
// }
// }
//
// Path: core/src/main/java/io/appflate/restmock/utils/RequestMatchers.java
// public static RequestMatcher pathEndsWith(final String urlPart) {
// return new RequestMatcher("path ends with: " + urlPart) {
//
// @Override
// protected boolean matchesSafely(RecordedRequest item) {
// String urlPartWithoutEndingSlash = urlPart.replaceAll("/$", "");
// String itemPathWithoutEndingSlash = item.getPath().replaceAll("/$", "");
// return itemPathWithoutEndingSlash.toLowerCase(Locale.US).endsWith(urlPartWithoutEndingSlash.toLowerCase(Locale.US));
// }
// };
// }
// Path: core/src/test/java/io/appflate/restmock/RESTMockServerTest.java
import io.appflate.restmock.utils.TestUtils;
import java.io.IOException;
import java.util.AbstractMap;
import java.util.Arrays;
import java.util.Collection;
import okhttp3.Response;
import okhttp3.mockwebserver.MockResponse;
import okhttp3.mockwebserver.RecordedRequest;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
import static io.appflate.restmock.utils.RequestMatchers.pathEndsWith;
import static junit.framework.TestCase.assertEquals;
import static junit.framework.TestCase.assertNotNull;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.spy;
import static org.mockito.Mockito.verify;
public static Collection<Object> data() {
return Arrays.asList(new Object[] {
true, false
});
}
public RESTMockServerTest(boolean useHttps) {
this.useHttps = useHttps;
}
@Before
public void setup() {
fileParser = mock(RESTMockFileParser.class);
RESTMockServerStarter.startSync(fileParser, new RESTMockOptions.Builder().useHttps(useHttps).build());
RESTMockServer.dispatcher = spy(RESTMockServer.dispatcher);
}
@After
public void teardown() throws IOException {
RESTMockServer.shutdown();
}
@Test
public void testWhenGET() throws Exception {
String path = "/sample";
String worksBody = "works";
MatchableCall matchableCall = RESTMockServer.whenGET(pathEndsWith(path));
assertNotNull(matchableCall);
assertEquals(0, matchableCall.getNumberOfAnswers());
verify(RESTMockServer.dispatcher, never()).addMatchableCall(matchableCall); | TestUtils.assertNotMocked(TestUtils.get(path)); |
andrzejchm/RESTMock | core/src/test/java/io/appflate/restmock/QueryParamTest.java | // Path: core/src/main/java/io/appflate/restmock/utils/QueryParam.java
// public class QueryParam {
//
// private final String key;
// private final List<String> values;
//
// public QueryParam(String key, List<String> values) {
// this.key = key;
// this.values = values;
// }
//
// public QueryParam(String key, String... values) {
// this.key = key;
// this.values = new LinkedList<>();
//
// for (String val : values) {
// this.values.add(val);
// }
// }
//
// @Override
// public boolean equals(Object other) {
// if (!(other instanceof QueryParam)) {
// return false;
// }
//
// QueryParam otherQueryParam = (QueryParam) other;
//
// if (this == other) {
// return true;
// }
//
// if (!this.key.equals(otherQueryParam.key)) {
// return false;
// }
//
// if (this.values.size() != otherQueryParam.values.size()) {
// return false;
// }
//
// for (String nextVal : this.values) {
// if (!otherQueryParam.values.contains(nextVal)) {
// return false;
// }
// }
//
// return true;
// }
//
// @Override
// public int hashCode() {
// int result = 17;
// result = 37 * result + (key == null ? 0 : key.hashCode());
// result = 37 * result + (values == null ? 0 : values.hashCode());
//
// return result;
// }
//
// public String getKey() {
// return this.key;
// }
//
// public List<String> getValues() {
// return this.values;
// }
// }
//
// Path: core/src/main/java/io/appflate/restmock/utils/RestMockUtils.java
// public final class RestMockUtils {
//
// public static MockResponse createResponseFromFile(RESTMockFileParser RESTMockFileParser, String jsonFilePath,
// int responseCode) throws Exception {
// String fileContents = RESTMockFileParser.readJsonFile(jsonFilePath);
// return new MockResponse().setResponseCode(responseCode).setBody(fileContents);
// }
//
// /**
// * Extract query parameters from a {@link URL}.
// *
// * @param url The {@link URL} to retrieve query parameters for.
// * @return A {@link List} of {@link QueryParam} objects. Each parameter has one key, and zero or
// * more values.
// * @throws UnsupportedEncodingException If unable to decode from UTF-8. This should never happen.
// */
// public static List<QueryParam> splitQuery(URL url) throws UnsupportedEncodingException {
// final Map<String, List<String>> queryPairs = new LinkedHashMap<>();
//
// String query = url.getQuery();
// if (query == null || query.trim().length() == 0) {
// return Collections.emptyList();
// }
//
// final String[] pairs = query.split("&");
// for (String pair : pairs) {
// final int idx = pair.indexOf("=");
// final String key = idx > 0 ? URLDecoder.decode(pair.substring(0, idx), "UTF-8") : pair;
// List<String> valueList = new LinkedList<>();
//
// if (queryPairs.containsKey(key)) {
// valueList = queryPairs.get(key);
// }
//
// final String value = idx > 0 && pair.length() > idx + 1 ? URLDecoder.decode(pair.substring(idx + 1), "UTF-8") : null;
// valueList.add(value);
//
// queryPairs.put(key, valueList);
// }
//
// List<QueryParam> finalParamList = new LinkedList<>();
// for (Map.Entry<String, List<String>> entry : queryPairs.entrySet()) {
// QueryParam nextFinalParam = new QueryParam(entry.getKey(), entry.getValue());
// finalParamList.add(nextFinalParam);
// }
//
// return finalParamList;
// }
//
// private RestMockUtils() {
// throw new UnsupportedOperationException("(╯‵Д′)╯ PLEASE STAHP!");
//
// }
// }
| import org.junit.Test;
import java.net.URL;
import java.util.List;
import io.appflate.restmock.utils.QueryParam;
import io.appflate.restmock.utils.RestMockUtils;
import static junit.framework.TestCase.assertTrue;
import static org.junit.Assert.assertEquals; | package io.appflate.restmock;
public class QueryParamTest {
@Test
public void testBasicQueryParamSplit() throws Exception {
URL url = new URL("https://www.jwir3.com/someRequest?flag=true&session_length=2");
| // Path: core/src/main/java/io/appflate/restmock/utils/QueryParam.java
// public class QueryParam {
//
// private final String key;
// private final List<String> values;
//
// public QueryParam(String key, List<String> values) {
// this.key = key;
// this.values = values;
// }
//
// public QueryParam(String key, String... values) {
// this.key = key;
// this.values = new LinkedList<>();
//
// for (String val : values) {
// this.values.add(val);
// }
// }
//
// @Override
// public boolean equals(Object other) {
// if (!(other instanceof QueryParam)) {
// return false;
// }
//
// QueryParam otherQueryParam = (QueryParam) other;
//
// if (this == other) {
// return true;
// }
//
// if (!this.key.equals(otherQueryParam.key)) {
// return false;
// }
//
// if (this.values.size() != otherQueryParam.values.size()) {
// return false;
// }
//
// for (String nextVal : this.values) {
// if (!otherQueryParam.values.contains(nextVal)) {
// return false;
// }
// }
//
// return true;
// }
//
// @Override
// public int hashCode() {
// int result = 17;
// result = 37 * result + (key == null ? 0 : key.hashCode());
// result = 37 * result + (values == null ? 0 : values.hashCode());
//
// return result;
// }
//
// public String getKey() {
// return this.key;
// }
//
// public List<String> getValues() {
// return this.values;
// }
// }
//
// Path: core/src/main/java/io/appflate/restmock/utils/RestMockUtils.java
// public final class RestMockUtils {
//
// public static MockResponse createResponseFromFile(RESTMockFileParser RESTMockFileParser, String jsonFilePath,
// int responseCode) throws Exception {
// String fileContents = RESTMockFileParser.readJsonFile(jsonFilePath);
// return new MockResponse().setResponseCode(responseCode).setBody(fileContents);
// }
//
// /**
// * Extract query parameters from a {@link URL}.
// *
// * @param url The {@link URL} to retrieve query parameters for.
// * @return A {@link List} of {@link QueryParam} objects. Each parameter has one key, and zero or
// * more values.
// * @throws UnsupportedEncodingException If unable to decode from UTF-8. This should never happen.
// */
// public static List<QueryParam> splitQuery(URL url) throws UnsupportedEncodingException {
// final Map<String, List<String>> queryPairs = new LinkedHashMap<>();
//
// String query = url.getQuery();
// if (query == null || query.trim().length() == 0) {
// return Collections.emptyList();
// }
//
// final String[] pairs = query.split("&");
// for (String pair : pairs) {
// final int idx = pair.indexOf("=");
// final String key = idx > 0 ? URLDecoder.decode(pair.substring(0, idx), "UTF-8") : pair;
// List<String> valueList = new LinkedList<>();
//
// if (queryPairs.containsKey(key)) {
// valueList = queryPairs.get(key);
// }
//
// final String value = idx > 0 && pair.length() > idx + 1 ? URLDecoder.decode(pair.substring(idx + 1), "UTF-8") : null;
// valueList.add(value);
//
// queryPairs.put(key, valueList);
// }
//
// List<QueryParam> finalParamList = new LinkedList<>();
// for (Map.Entry<String, List<String>> entry : queryPairs.entrySet()) {
// QueryParam nextFinalParam = new QueryParam(entry.getKey(), entry.getValue());
// finalParamList.add(nextFinalParam);
// }
//
// return finalParamList;
// }
//
// private RestMockUtils() {
// throw new UnsupportedOperationException("(╯‵Д′)╯ PLEASE STAHP!");
//
// }
// }
// Path: core/src/test/java/io/appflate/restmock/QueryParamTest.java
import org.junit.Test;
import java.net.URL;
import java.util.List;
import io.appflate.restmock.utils.QueryParam;
import io.appflate.restmock.utils.RestMockUtils;
import static junit.framework.TestCase.assertTrue;
import static org.junit.Assert.assertEquals;
package io.appflate.restmock;
public class QueryParamTest {
@Test
public void testBasicQueryParamSplit() throws Exception {
URL url = new URL("https://www.jwir3.com/someRequest?flag=true&session_length=2");
| List<QueryParam> params = RestMockUtils.splitQuery(url); |
andrzejchm/RESTMock | core/src/test/java/io/appflate/restmock/QueryParamTest.java | // Path: core/src/main/java/io/appflate/restmock/utils/QueryParam.java
// public class QueryParam {
//
// private final String key;
// private final List<String> values;
//
// public QueryParam(String key, List<String> values) {
// this.key = key;
// this.values = values;
// }
//
// public QueryParam(String key, String... values) {
// this.key = key;
// this.values = new LinkedList<>();
//
// for (String val : values) {
// this.values.add(val);
// }
// }
//
// @Override
// public boolean equals(Object other) {
// if (!(other instanceof QueryParam)) {
// return false;
// }
//
// QueryParam otherQueryParam = (QueryParam) other;
//
// if (this == other) {
// return true;
// }
//
// if (!this.key.equals(otherQueryParam.key)) {
// return false;
// }
//
// if (this.values.size() != otherQueryParam.values.size()) {
// return false;
// }
//
// for (String nextVal : this.values) {
// if (!otherQueryParam.values.contains(nextVal)) {
// return false;
// }
// }
//
// return true;
// }
//
// @Override
// public int hashCode() {
// int result = 17;
// result = 37 * result + (key == null ? 0 : key.hashCode());
// result = 37 * result + (values == null ? 0 : values.hashCode());
//
// return result;
// }
//
// public String getKey() {
// return this.key;
// }
//
// public List<String> getValues() {
// return this.values;
// }
// }
//
// Path: core/src/main/java/io/appflate/restmock/utils/RestMockUtils.java
// public final class RestMockUtils {
//
// public static MockResponse createResponseFromFile(RESTMockFileParser RESTMockFileParser, String jsonFilePath,
// int responseCode) throws Exception {
// String fileContents = RESTMockFileParser.readJsonFile(jsonFilePath);
// return new MockResponse().setResponseCode(responseCode).setBody(fileContents);
// }
//
// /**
// * Extract query parameters from a {@link URL}.
// *
// * @param url The {@link URL} to retrieve query parameters for.
// * @return A {@link List} of {@link QueryParam} objects. Each parameter has one key, and zero or
// * more values.
// * @throws UnsupportedEncodingException If unable to decode from UTF-8. This should never happen.
// */
// public static List<QueryParam> splitQuery(URL url) throws UnsupportedEncodingException {
// final Map<String, List<String>> queryPairs = new LinkedHashMap<>();
//
// String query = url.getQuery();
// if (query == null || query.trim().length() == 0) {
// return Collections.emptyList();
// }
//
// final String[] pairs = query.split("&");
// for (String pair : pairs) {
// final int idx = pair.indexOf("=");
// final String key = idx > 0 ? URLDecoder.decode(pair.substring(0, idx), "UTF-8") : pair;
// List<String> valueList = new LinkedList<>();
//
// if (queryPairs.containsKey(key)) {
// valueList = queryPairs.get(key);
// }
//
// final String value = idx > 0 && pair.length() > idx + 1 ? URLDecoder.decode(pair.substring(idx + 1), "UTF-8") : null;
// valueList.add(value);
//
// queryPairs.put(key, valueList);
// }
//
// List<QueryParam> finalParamList = new LinkedList<>();
// for (Map.Entry<String, List<String>> entry : queryPairs.entrySet()) {
// QueryParam nextFinalParam = new QueryParam(entry.getKey(), entry.getValue());
// finalParamList.add(nextFinalParam);
// }
//
// return finalParamList;
// }
//
// private RestMockUtils() {
// throw new UnsupportedOperationException("(╯‵Д′)╯ PLEASE STAHP!");
//
// }
// }
| import org.junit.Test;
import java.net.URL;
import java.util.List;
import io.appflate.restmock.utils.QueryParam;
import io.appflate.restmock.utils.RestMockUtils;
import static junit.framework.TestCase.assertTrue;
import static org.junit.Assert.assertEquals; | package io.appflate.restmock;
public class QueryParamTest {
@Test
public void testBasicQueryParamSplit() throws Exception {
URL url = new URL("https://www.jwir3.com/someRequest?flag=true&session_length=2");
| // Path: core/src/main/java/io/appflate/restmock/utils/QueryParam.java
// public class QueryParam {
//
// private final String key;
// private final List<String> values;
//
// public QueryParam(String key, List<String> values) {
// this.key = key;
// this.values = values;
// }
//
// public QueryParam(String key, String... values) {
// this.key = key;
// this.values = new LinkedList<>();
//
// for (String val : values) {
// this.values.add(val);
// }
// }
//
// @Override
// public boolean equals(Object other) {
// if (!(other instanceof QueryParam)) {
// return false;
// }
//
// QueryParam otherQueryParam = (QueryParam) other;
//
// if (this == other) {
// return true;
// }
//
// if (!this.key.equals(otherQueryParam.key)) {
// return false;
// }
//
// if (this.values.size() != otherQueryParam.values.size()) {
// return false;
// }
//
// for (String nextVal : this.values) {
// if (!otherQueryParam.values.contains(nextVal)) {
// return false;
// }
// }
//
// return true;
// }
//
// @Override
// public int hashCode() {
// int result = 17;
// result = 37 * result + (key == null ? 0 : key.hashCode());
// result = 37 * result + (values == null ? 0 : values.hashCode());
//
// return result;
// }
//
// public String getKey() {
// return this.key;
// }
//
// public List<String> getValues() {
// return this.values;
// }
// }
//
// Path: core/src/main/java/io/appflate/restmock/utils/RestMockUtils.java
// public final class RestMockUtils {
//
// public static MockResponse createResponseFromFile(RESTMockFileParser RESTMockFileParser, String jsonFilePath,
// int responseCode) throws Exception {
// String fileContents = RESTMockFileParser.readJsonFile(jsonFilePath);
// return new MockResponse().setResponseCode(responseCode).setBody(fileContents);
// }
//
// /**
// * Extract query parameters from a {@link URL}.
// *
// * @param url The {@link URL} to retrieve query parameters for.
// * @return A {@link List} of {@link QueryParam} objects. Each parameter has one key, and zero or
// * more values.
// * @throws UnsupportedEncodingException If unable to decode from UTF-8. This should never happen.
// */
// public static List<QueryParam> splitQuery(URL url) throws UnsupportedEncodingException {
// final Map<String, List<String>> queryPairs = new LinkedHashMap<>();
//
// String query = url.getQuery();
// if (query == null || query.trim().length() == 0) {
// return Collections.emptyList();
// }
//
// final String[] pairs = query.split("&");
// for (String pair : pairs) {
// final int idx = pair.indexOf("=");
// final String key = idx > 0 ? URLDecoder.decode(pair.substring(0, idx), "UTF-8") : pair;
// List<String> valueList = new LinkedList<>();
//
// if (queryPairs.containsKey(key)) {
// valueList = queryPairs.get(key);
// }
//
// final String value = idx > 0 && pair.length() > idx + 1 ? URLDecoder.decode(pair.substring(idx + 1), "UTF-8") : null;
// valueList.add(value);
//
// queryPairs.put(key, valueList);
// }
//
// List<QueryParam> finalParamList = new LinkedList<>();
// for (Map.Entry<String, List<String>> entry : queryPairs.entrySet()) {
// QueryParam nextFinalParam = new QueryParam(entry.getKey(), entry.getValue());
// finalParamList.add(nextFinalParam);
// }
//
// return finalParamList;
// }
//
// private RestMockUtils() {
// throw new UnsupportedOperationException("(╯‵Д′)╯ PLEASE STAHP!");
//
// }
// }
// Path: core/src/test/java/io/appflate/restmock/QueryParamTest.java
import org.junit.Test;
import java.net.URL;
import java.util.List;
import io.appflate.restmock.utils.QueryParam;
import io.appflate.restmock.utils.RestMockUtils;
import static junit.framework.TestCase.assertTrue;
import static org.junit.Assert.assertEquals;
package io.appflate.restmock;
public class QueryParamTest {
@Test
public void testBasicQueryParamSplit() throws Exception {
URL url = new URL("https://www.jwir3.com/someRequest?flag=true&session_length=2");
| List<QueryParam> params = RestMockUtils.splitQuery(url); |
andrzejchm/RESTMock | androidsample/src/main/java/io/appflate/restmock/androidsample/SampleApplication.java | // Path: androidsample/src/main/java/io/appflate/restmock/androidsample/di/AppComponent.java
// @Singleton
// @Component(modules = { AppModule.class})
// public interface AppComponent {
// GithubApi getRestService();
//
// void inject(MainActivity mainActivity);
// void inject(ReposActivity reposActivity);
// }
//
// Path: androidsample/src/main/java/io/appflate/restmock/androidsample/di/AppModule.java
// @Module
// public class AppModule {
//
// private String baseUrl;
//
// private SSLSocketFactory socketFactory;
//
// private X509TrustManager trustManager;
//
// public AppModule(String baseUrl, SSLSocketFactory socketFactory, X509TrustManager trustManager) {
// this.baseUrl = baseUrl;
// this.socketFactory = socketFactory;
// this.trustManager = trustManager;
// }
//
// @Provides
// GithubApi provideRestService() {
// HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor();
// interceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
// OkHttpClient.Builder clientBuilder = new OkHttpClient.Builder();
// if (socketFactory != null && trustManager != null) {
// clientBuilder.sslSocketFactory(socketFactory, trustManager);
// }
// clientBuilder.addInterceptor(interceptor);
//
// Retrofit retrofit = new Retrofit.Builder().baseUrl(baseUrl)
// .client(clientBuilder.build())
// .addConverterFactory(GsonConverterFactory.create())
// .build();
//
// return retrofit.create(GithubApi.class);
// }
// }
| import android.app.Application;
import io.appflate.restmock.androidsample.di.AppComponent;
import io.appflate.restmock.androidsample.di.AppModule;
import io.appflate.restmock.androidsample.di.DaggerAppComponent; | /*
* Copyright (C) 2016 Appflate.io
*
* 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 io.appflate.restmock.androidsample;
/**
* Created by andrzejchm on 22/04/16.
*/
public class SampleApplication extends Application {
private static final String BASE_URL = "https://api.github.com/"; | // Path: androidsample/src/main/java/io/appflate/restmock/androidsample/di/AppComponent.java
// @Singleton
// @Component(modules = { AppModule.class})
// public interface AppComponent {
// GithubApi getRestService();
//
// void inject(MainActivity mainActivity);
// void inject(ReposActivity reposActivity);
// }
//
// Path: androidsample/src/main/java/io/appflate/restmock/androidsample/di/AppModule.java
// @Module
// public class AppModule {
//
// private String baseUrl;
//
// private SSLSocketFactory socketFactory;
//
// private X509TrustManager trustManager;
//
// public AppModule(String baseUrl, SSLSocketFactory socketFactory, X509TrustManager trustManager) {
// this.baseUrl = baseUrl;
// this.socketFactory = socketFactory;
// this.trustManager = trustManager;
// }
//
// @Provides
// GithubApi provideRestService() {
// HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor();
// interceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
// OkHttpClient.Builder clientBuilder = new OkHttpClient.Builder();
// if (socketFactory != null && trustManager != null) {
// clientBuilder.sslSocketFactory(socketFactory, trustManager);
// }
// clientBuilder.addInterceptor(interceptor);
//
// Retrofit retrofit = new Retrofit.Builder().baseUrl(baseUrl)
// .client(clientBuilder.build())
// .addConverterFactory(GsonConverterFactory.create())
// .build();
//
// return retrofit.create(GithubApi.class);
// }
// }
// Path: androidsample/src/main/java/io/appflate/restmock/androidsample/SampleApplication.java
import android.app.Application;
import io.appflate.restmock.androidsample.di.AppComponent;
import io.appflate.restmock.androidsample.di.AppModule;
import io.appflate.restmock.androidsample.di.DaggerAppComponent;
/*
* Copyright (C) 2016 Appflate.io
*
* 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 io.appflate.restmock.androidsample;
/**
* Created by andrzejchm on 22/04/16.
*/
public class SampleApplication extends Application {
private static final String BASE_URL = "https://api.github.com/"; | static AppComponent appComponent; |
andrzejchm/RESTMock | androidsample/src/main/java/io/appflate/restmock/androidsample/SampleApplication.java | // Path: androidsample/src/main/java/io/appflate/restmock/androidsample/di/AppComponent.java
// @Singleton
// @Component(modules = { AppModule.class})
// public interface AppComponent {
// GithubApi getRestService();
//
// void inject(MainActivity mainActivity);
// void inject(ReposActivity reposActivity);
// }
//
// Path: androidsample/src/main/java/io/appflate/restmock/androidsample/di/AppModule.java
// @Module
// public class AppModule {
//
// private String baseUrl;
//
// private SSLSocketFactory socketFactory;
//
// private X509TrustManager trustManager;
//
// public AppModule(String baseUrl, SSLSocketFactory socketFactory, X509TrustManager trustManager) {
// this.baseUrl = baseUrl;
// this.socketFactory = socketFactory;
// this.trustManager = trustManager;
// }
//
// @Provides
// GithubApi provideRestService() {
// HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor();
// interceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
// OkHttpClient.Builder clientBuilder = new OkHttpClient.Builder();
// if (socketFactory != null && trustManager != null) {
// clientBuilder.sslSocketFactory(socketFactory, trustManager);
// }
// clientBuilder.addInterceptor(interceptor);
//
// Retrofit retrofit = new Retrofit.Builder().baseUrl(baseUrl)
// .client(clientBuilder.build())
// .addConverterFactory(GsonConverterFactory.create())
// .build();
//
// return retrofit.create(GithubApi.class);
// }
// }
| import android.app.Application;
import io.appflate.restmock.androidsample.di.AppComponent;
import io.appflate.restmock.androidsample.di.AppModule;
import io.appflate.restmock.androidsample.di.DaggerAppComponent; | /*
* Copyright (C) 2016 Appflate.io
*
* 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 io.appflate.restmock.androidsample;
/**
* Created by andrzejchm on 22/04/16.
*/
public class SampleApplication extends Application {
private static final String BASE_URL = "https://api.github.com/";
static AppComponent appComponent;
@Override
public void onCreate() {
super.onCreate();
setupGraph();
}
protected void setupGraph() {
appComponent = DaggerAppComponent.builder() | // Path: androidsample/src/main/java/io/appflate/restmock/androidsample/di/AppComponent.java
// @Singleton
// @Component(modules = { AppModule.class})
// public interface AppComponent {
// GithubApi getRestService();
//
// void inject(MainActivity mainActivity);
// void inject(ReposActivity reposActivity);
// }
//
// Path: androidsample/src/main/java/io/appflate/restmock/androidsample/di/AppModule.java
// @Module
// public class AppModule {
//
// private String baseUrl;
//
// private SSLSocketFactory socketFactory;
//
// private X509TrustManager trustManager;
//
// public AppModule(String baseUrl, SSLSocketFactory socketFactory, X509TrustManager trustManager) {
// this.baseUrl = baseUrl;
// this.socketFactory = socketFactory;
// this.trustManager = trustManager;
// }
//
// @Provides
// GithubApi provideRestService() {
// HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor();
// interceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
// OkHttpClient.Builder clientBuilder = new OkHttpClient.Builder();
// if (socketFactory != null && trustManager != null) {
// clientBuilder.sslSocketFactory(socketFactory, trustManager);
// }
// clientBuilder.addInterceptor(interceptor);
//
// Retrofit retrofit = new Retrofit.Builder().baseUrl(baseUrl)
// .client(clientBuilder.build())
// .addConverterFactory(GsonConverterFactory.create())
// .build();
//
// return retrofit.create(GithubApi.class);
// }
// }
// Path: androidsample/src/main/java/io/appflate/restmock/androidsample/SampleApplication.java
import android.app.Application;
import io.appflate.restmock.androidsample.di.AppComponent;
import io.appflate.restmock.androidsample.di.AppModule;
import io.appflate.restmock.androidsample.di.DaggerAppComponent;
/*
* Copyright (C) 2016 Appflate.io
*
* 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 io.appflate.restmock.androidsample;
/**
* Created by andrzejchm on 22/04/16.
*/
public class SampleApplication extends Application {
private static final String BASE_URL = "https://api.github.com/";
static AppComponent appComponent;
@Override
public void onCreate() {
super.onCreate();
setupGraph();
}
protected void setupGraph() {
appComponent = DaggerAppComponent.builder() | .appModule(new AppModule(BASE_URL, null, null)) |
andrzejchm/RESTMock | core/src/test/java/io/appflate/restmock/utils/RequestMatchersTest.java | // Path: core/src/main/java/io/appflate/restmock/utils/RequestMatchers.java
// public static RequestMatcher hasHeaderNames(final String... headerNames) {
// return new RequestMatcher("has headers: " + Arrays.toString(headerNames)) {
//
// @Override
// protected boolean matchesSafely(RecordedRequest item) {
// if (headerNames == null) {
// throw new IllegalArgumentException("You did not specify any header names");
// }
// if (headerNames.length > 0 && item.getHeaders() == null) {
// return false;
// }
// for (String header : headerNames) {
// if (item.getHeader(header) == null) {
// return false;
// }
// }
// return true;
// }
// };
// }
| import java.util.Collections;
import okio.Buffer;
import org.junit.Test;
import org.mockito.Mockito;
import java.io.IOException;
import java.net.InetAddress;
import java.net.Socket;
import okhttp3.Headers;
import okhttp3.mockwebserver.RecordedRequest;
import static io.appflate.restmock.utils.RequestMatchers.hasHeaderNames;
import static junit.framework.Assert.assertFalse;
import static junit.framework.TestCase.assertTrue;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when; | @Test
public void shouldMatchProperSubsetOfQueryParametersNames() throws IOException {
// given
RecordedRequest recordedRequest = createRecordedRequest("/foo/?bar=bar&baz=baz&boo=boo");
// when
RequestMatcher matcher = RequestMatchers.hasQueryParameterNames("bar", "baz");
// then
assertTrue(matcher.matches(recordedRequest));
}
@Test
public void shouldNotMatchInproperSubsetOfQueryParametersNames() throws IOException {
// given
RecordedRequest recordedRequest = createRecordedRequest("/foo/?bar=bar&baz=baz&boo=boo");
// when
RequestMatcher matcher = RequestMatchers.hasQueryParameterNames("bar", "ban");
// then
assertFalse(matcher.matches(recordedRequest));
}
@Test
public void hasHeaderNamesFailWhenNoHeaders() {
//given
RecordedRequest request = createRecordedRequest("/path");
//when | // Path: core/src/main/java/io/appflate/restmock/utils/RequestMatchers.java
// public static RequestMatcher hasHeaderNames(final String... headerNames) {
// return new RequestMatcher("has headers: " + Arrays.toString(headerNames)) {
//
// @Override
// protected boolean matchesSafely(RecordedRequest item) {
// if (headerNames == null) {
// throw new IllegalArgumentException("You did not specify any header names");
// }
// if (headerNames.length > 0 && item.getHeaders() == null) {
// return false;
// }
// for (String header : headerNames) {
// if (item.getHeader(header) == null) {
// return false;
// }
// }
// return true;
// }
// };
// }
// Path: core/src/test/java/io/appflate/restmock/utils/RequestMatchersTest.java
import java.util.Collections;
import okio.Buffer;
import org.junit.Test;
import org.mockito.Mockito;
import java.io.IOException;
import java.net.InetAddress;
import java.net.Socket;
import okhttp3.Headers;
import okhttp3.mockwebserver.RecordedRequest;
import static io.appflate.restmock.utils.RequestMatchers.hasHeaderNames;
import static junit.framework.Assert.assertFalse;
import static junit.framework.TestCase.assertTrue;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
@Test
public void shouldMatchProperSubsetOfQueryParametersNames() throws IOException {
// given
RecordedRequest recordedRequest = createRecordedRequest("/foo/?bar=bar&baz=baz&boo=boo");
// when
RequestMatcher matcher = RequestMatchers.hasQueryParameterNames("bar", "baz");
// then
assertTrue(matcher.matches(recordedRequest));
}
@Test
public void shouldNotMatchInproperSubsetOfQueryParametersNames() throws IOException {
// given
RecordedRequest recordedRequest = createRecordedRequest("/foo/?bar=bar&baz=baz&boo=boo");
// when
RequestMatcher matcher = RequestMatchers.hasQueryParameterNames("bar", "ban");
// then
assertFalse(matcher.matches(recordedRequest));
}
@Test
public void hasHeaderNamesFailWhenNoHeaders() {
//given
RecordedRequest request = createRecordedRequest("/path");
//when | RequestMatcher matcher = hasHeaderNames("header1"); |
andrzejchm/RESTMock | android/src/main/java/io/appflate/restmock/android/RESTMockTestRunner.java | // Path: core/src/main/java/io/appflate/restmock/RESTMockOptions.java
// public class RESTMockOptions {
// private boolean useHttps;
// private SSLSocketFactory socketFactory;
// private X509TrustManager trustManager;
//
// private RESTMockOptions(final Builder builder) {
// setUseHttps(builder.useHttps);
// setSocketFactory(builder.socketFactory);
// setTrustManager(builder.trustManager);
// }
//
// public boolean isUseHttps() {
// return useHttps;
// }
//
// public void setUseHttps(final boolean useHttps) {
// this.useHttps = useHttps;
// }
//
// /**
// * Returns the sslSocketFactory used by RESTMockServer. If you didn't specify your own with #setSSlSocketFactory(SSSLSocketFactory)
// * method, then a default one will be created
// * You can set this socket factory in your HTTP client in order to be able to perform proper SSL handshakes with mockwebserver
// *
// * @return SSLSocketFactory used by the RESTMockServer
// */
// public SSLSocketFactory getSocketFactory() {
// return socketFactory;
// }
//
// public void setSocketFactory(final SSLSocketFactory socketFactory) {
// this.socketFactory = socketFactory;
// }
//
// /**
// * Returns the trustManager used in conjunction with sslSocketFactory. It is set up to trust the certificates produces by the
// * sslSocketFactory returned in `getSocketFactory().
// */
// public X509TrustManager getTrustManager() {
// return trustManager;
// }
//
// public void setTrustManager(final X509TrustManager trustManager) {
// this.trustManager = trustManager;
// }
//
// public static final class Builder {
// private boolean useHttps;
// private SSLSocketFactory socketFactory;
// private X509TrustManager trustManager;
//
// public Builder() {
// }
//
// public Builder useHttps(final boolean val) {
// useHttps = val;
// return this;
// }
//
// public Builder socketFactory(final SSLSocketFactory val) {
// socketFactory = val;
// return this;
// }
//
// public Builder trustManager(final X509TrustManager val) {
// trustManager = val;
// return this;
// }
//
// public RESTMockOptions build() {
// return new RESTMockOptions(this);
// }
// }
// }
//
// Path: core/src/main/java/io/appflate/restmock/RESTMockServerStarter.java
// public class RESTMockServerStarter {
//
// public static final int KEEP_ALIVE_TIME = 60;
//
// public static void startSync(final RESTMockFileParser mocksFileParser) {
// startSync(mocksFileParser, null,
// new RESTMockOptions.Builder().build());
// }
//
// public static void startSync(final RESTMockFileParser mocksFileParser, RESTMockOptions options) {
// startSync(mocksFileParser, null, options);
// }
//
// public static void startSync(final RESTMockFileParser mocksFileParser, final RESTMockLogger logger) {
// startSync(mocksFileParser, logger, new RESTMockOptions.Builder().build());
// }
//
// public static void startSync(
// final RESTMockFileParser mocksFileParser,
// final RESTMockLogger logger,
// final RESTMockOptions restMockOptions
// ) {
// // it has to be like that since Android prevents starting testServer on main Thread.
// ThreadPoolExecutor threadPoolExecutor =
// new ThreadPoolExecutor(1, 1, KEEP_ALIVE_TIME, TimeUnit.SECONDS, new LinkedBlockingQueue<Runnable>(1));
//
// threadPoolExecutor.execute(new Runnable() {
//
// @Override
// public void run() {
// try {
// RESTMockServer.init(mocksFileParser, logger, restMockOptions);
// } catch (IOException e) {
// RESTMockServer.getLogger().error("Server start error", e);
// throw new RuntimeException(e);
// }
// }
// });
// try {
// threadPoolExecutor.shutdown();
// if (!threadPoolExecutor.awaitTermination(KEEP_ALIVE_TIME, TimeUnit.SECONDS)) {
// throw new RuntimeException("mock server didn't manage to start within the given timeout (60 seconds)");
// }
// } catch (InterruptedException e) {
// RESTMockServer.getLogger().error("Server start error", e);
// throw new RuntimeException(e);
// }
// }
//
// private RESTMockServerStarter() {
// }
// }
| import android.os.Bundle;
import androidx.test.runner.AndroidJUnitRunner;
import io.appflate.restmock.RESTMockOptions;
import io.appflate.restmock.RESTMockServerStarter; | /*
* Copyright (C) 2016 Appflate.io
*
* 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 io.appflate.restmock.android;
/**
* Created by andrzejchm on 22/04/16.
*/
public class RESTMockTestRunner extends AndroidJUnitRunner {
@Override
public void onCreate(Bundle arguments) {
super.onCreate(arguments); | // Path: core/src/main/java/io/appflate/restmock/RESTMockOptions.java
// public class RESTMockOptions {
// private boolean useHttps;
// private SSLSocketFactory socketFactory;
// private X509TrustManager trustManager;
//
// private RESTMockOptions(final Builder builder) {
// setUseHttps(builder.useHttps);
// setSocketFactory(builder.socketFactory);
// setTrustManager(builder.trustManager);
// }
//
// public boolean isUseHttps() {
// return useHttps;
// }
//
// public void setUseHttps(final boolean useHttps) {
// this.useHttps = useHttps;
// }
//
// /**
// * Returns the sslSocketFactory used by RESTMockServer. If you didn't specify your own with #setSSlSocketFactory(SSSLSocketFactory)
// * method, then a default one will be created
// * You can set this socket factory in your HTTP client in order to be able to perform proper SSL handshakes with mockwebserver
// *
// * @return SSLSocketFactory used by the RESTMockServer
// */
// public SSLSocketFactory getSocketFactory() {
// return socketFactory;
// }
//
// public void setSocketFactory(final SSLSocketFactory socketFactory) {
// this.socketFactory = socketFactory;
// }
//
// /**
// * Returns the trustManager used in conjunction with sslSocketFactory. It is set up to trust the certificates produces by the
// * sslSocketFactory returned in `getSocketFactory().
// */
// public X509TrustManager getTrustManager() {
// return trustManager;
// }
//
// public void setTrustManager(final X509TrustManager trustManager) {
// this.trustManager = trustManager;
// }
//
// public static final class Builder {
// private boolean useHttps;
// private SSLSocketFactory socketFactory;
// private X509TrustManager trustManager;
//
// public Builder() {
// }
//
// public Builder useHttps(final boolean val) {
// useHttps = val;
// return this;
// }
//
// public Builder socketFactory(final SSLSocketFactory val) {
// socketFactory = val;
// return this;
// }
//
// public Builder trustManager(final X509TrustManager val) {
// trustManager = val;
// return this;
// }
//
// public RESTMockOptions build() {
// return new RESTMockOptions(this);
// }
// }
// }
//
// Path: core/src/main/java/io/appflate/restmock/RESTMockServerStarter.java
// public class RESTMockServerStarter {
//
// public static final int KEEP_ALIVE_TIME = 60;
//
// public static void startSync(final RESTMockFileParser mocksFileParser) {
// startSync(mocksFileParser, null,
// new RESTMockOptions.Builder().build());
// }
//
// public static void startSync(final RESTMockFileParser mocksFileParser, RESTMockOptions options) {
// startSync(mocksFileParser, null, options);
// }
//
// public static void startSync(final RESTMockFileParser mocksFileParser, final RESTMockLogger logger) {
// startSync(mocksFileParser, logger, new RESTMockOptions.Builder().build());
// }
//
// public static void startSync(
// final RESTMockFileParser mocksFileParser,
// final RESTMockLogger logger,
// final RESTMockOptions restMockOptions
// ) {
// // it has to be like that since Android prevents starting testServer on main Thread.
// ThreadPoolExecutor threadPoolExecutor =
// new ThreadPoolExecutor(1, 1, KEEP_ALIVE_TIME, TimeUnit.SECONDS, new LinkedBlockingQueue<Runnable>(1));
//
// threadPoolExecutor.execute(new Runnable() {
//
// @Override
// public void run() {
// try {
// RESTMockServer.init(mocksFileParser, logger, restMockOptions);
// } catch (IOException e) {
// RESTMockServer.getLogger().error("Server start error", e);
// throw new RuntimeException(e);
// }
// }
// });
// try {
// threadPoolExecutor.shutdown();
// if (!threadPoolExecutor.awaitTermination(KEEP_ALIVE_TIME, TimeUnit.SECONDS)) {
// throw new RuntimeException("mock server didn't manage to start within the given timeout (60 seconds)");
// }
// } catch (InterruptedException e) {
// RESTMockServer.getLogger().error("Server start error", e);
// throw new RuntimeException(e);
// }
// }
//
// private RESTMockServerStarter() {
// }
// }
// Path: android/src/main/java/io/appflate/restmock/android/RESTMockTestRunner.java
import android.os.Bundle;
import androidx.test.runner.AndroidJUnitRunner;
import io.appflate.restmock.RESTMockOptions;
import io.appflate.restmock.RESTMockServerStarter;
/*
* Copyright (C) 2016 Appflate.io
*
* 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 io.appflate.restmock.android;
/**
* Created by andrzejchm on 22/04/16.
*/
public class RESTMockTestRunner extends AndroidJUnitRunner {
@Override
public void onCreate(Bundle arguments) {
super.onCreate(arguments); | RESTMockServerStarter.startSync(new AndroidAssetsFileParser(getContext()), new AndroidLogger(), |
andrzejchm/RESTMock | android/src/main/java/io/appflate/restmock/android/RESTMockTestRunner.java | // Path: core/src/main/java/io/appflate/restmock/RESTMockOptions.java
// public class RESTMockOptions {
// private boolean useHttps;
// private SSLSocketFactory socketFactory;
// private X509TrustManager trustManager;
//
// private RESTMockOptions(final Builder builder) {
// setUseHttps(builder.useHttps);
// setSocketFactory(builder.socketFactory);
// setTrustManager(builder.trustManager);
// }
//
// public boolean isUseHttps() {
// return useHttps;
// }
//
// public void setUseHttps(final boolean useHttps) {
// this.useHttps = useHttps;
// }
//
// /**
// * Returns the sslSocketFactory used by RESTMockServer. If you didn't specify your own with #setSSlSocketFactory(SSSLSocketFactory)
// * method, then a default one will be created
// * You can set this socket factory in your HTTP client in order to be able to perform proper SSL handshakes with mockwebserver
// *
// * @return SSLSocketFactory used by the RESTMockServer
// */
// public SSLSocketFactory getSocketFactory() {
// return socketFactory;
// }
//
// public void setSocketFactory(final SSLSocketFactory socketFactory) {
// this.socketFactory = socketFactory;
// }
//
// /**
// * Returns the trustManager used in conjunction with sslSocketFactory. It is set up to trust the certificates produces by the
// * sslSocketFactory returned in `getSocketFactory().
// */
// public X509TrustManager getTrustManager() {
// return trustManager;
// }
//
// public void setTrustManager(final X509TrustManager trustManager) {
// this.trustManager = trustManager;
// }
//
// public static final class Builder {
// private boolean useHttps;
// private SSLSocketFactory socketFactory;
// private X509TrustManager trustManager;
//
// public Builder() {
// }
//
// public Builder useHttps(final boolean val) {
// useHttps = val;
// return this;
// }
//
// public Builder socketFactory(final SSLSocketFactory val) {
// socketFactory = val;
// return this;
// }
//
// public Builder trustManager(final X509TrustManager val) {
// trustManager = val;
// return this;
// }
//
// public RESTMockOptions build() {
// return new RESTMockOptions(this);
// }
// }
// }
//
// Path: core/src/main/java/io/appflate/restmock/RESTMockServerStarter.java
// public class RESTMockServerStarter {
//
// public static final int KEEP_ALIVE_TIME = 60;
//
// public static void startSync(final RESTMockFileParser mocksFileParser) {
// startSync(mocksFileParser, null,
// new RESTMockOptions.Builder().build());
// }
//
// public static void startSync(final RESTMockFileParser mocksFileParser, RESTMockOptions options) {
// startSync(mocksFileParser, null, options);
// }
//
// public static void startSync(final RESTMockFileParser mocksFileParser, final RESTMockLogger logger) {
// startSync(mocksFileParser, logger, new RESTMockOptions.Builder().build());
// }
//
// public static void startSync(
// final RESTMockFileParser mocksFileParser,
// final RESTMockLogger logger,
// final RESTMockOptions restMockOptions
// ) {
// // it has to be like that since Android prevents starting testServer on main Thread.
// ThreadPoolExecutor threadPoolExecutor =
// new ThreadPoolExecutor(1, 1, KEEP_ALIVE_TIME, TimeUnit.SECONDS, new LinkedBlockingQueue<Runnable>(1));
//
// threadPoolExecutor.execute(new Runnable() {
//
// @Override
// public void run() {
// try {
// RESTMockServer.init(mocksFileParser, logger, restMockOptions);
// } catch (IOException e) {
// RESTMockServer.getLogger().error("Server start error", e);
// throw new RuntimeException(e);
// }
// }
// });
// try {
// threadPoolExecutor.shutdown();
// if (!threadPoolExecutor.awaitTermination(KEEP_ALIVE_TIME, TimeUnit.SECONDS)) {
// throw new RuntimeException("mock server didn't manage to start within the given timeout (60 seconds)");
// }
// } catch (InterruptedException e) {
// RESTMockServer.getLogger().error("Server start error", e);
// throw new RuntimeException(e);
// }
// }
//
// private RESTMockServerStarter() {
// }
// }
| import android.os.Bundle;
import androidx.test.runner.AndroidJUnitRunner;
import io.appflate.restmock.RESTMockOptions;
import io.appflate.restmock.RESTMockServerStarter; | /*
* Copyright (C) 2016 Appflate.io
*
* 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 io.appflate.restmock.android;
/**
* Created by andrzejchm on 22/04/16.
*/
public class RESTMockTestRunner extends AndroidJUnitRunner {
@Override
public void onCreate(Bundle arguments) {
super.onCreate(arguments);
RESTMockServerStarter.startSync(new AndroidAssetsFileParser(getContext()), new AndroidLogger(), | // Path: core/src/main/java/io/appflate/restmock/RESTMockOptions.java
// public class RESTMockOptions {
// private boolean useHttps;
// private SSLSocketFactory socketFactory;
// private X509TrustManager trustManager;
//
// private RESTMockOptions(final Builder builder) {
// setUseHttps(builder.useHttps);
// setSocketFactory(builder.socketFactory);
// setTrustManager(builder.trustManager);
// }
//
// public boolean isUseHttps() {
// return useHttps;
// }
//
// public void setUseHttps(final boolean useHttps) {
// this.useHttps = useHttps;
// }
//
// /**
// * Returns the sslSocketFactory used by RESTMockServer. If you didn't specify your own with #setSSlSocketFactory(SSSLSocketFactory)
// * method, then a default one will be created
// * You can set this socket factory in your HTTP client in order to be able to perform proper SSL handshakes with mockwebserver
// *
// * @return SSLSocketFactory used by the RESTMockServer
// */
// public SSLSocketFactory getSocketFactory() {
// return socketFactory;
// }
//
// public void setSocketFactory(final SSLSocketFactory socketFactory) {
// this.socketFactory = socketFactory;
// }
//
// /**
// * Returns the trustManager used in conjunction with sslSocketFactory. It is set up to trust the certificates produces by the
// * sslSocketFactory returned in `getSocketFactory().
// */
// public X509TrustManager getTrustManager() {
// return trustManager;
// }
//
// public void setTrustManager(final X509TrustManager trustManager) {
// this.trustManager = trustManager;
// }
//
// public static final class Builder {
// private boolean useHttps;
// private SSLSocketFactory socketFactory;
// private X509TrustManager trustManager;
//
// public Builder() {
// }
//
// public Builder useHttps(final boolean val) {
// useHttps = val;
// return this;
// }
//
// public Builder socketFactory(final SSLSocketFactory val) {
// socketFactory = val;
// return this;
// }
//
// public Builder trustManager(final X509TrustManager val) {
// trustManager = val;
// return this;
// }
//
// public RESTMockOptions build() {
// return new RESTMockOptions(this);
// }
// }
// }
//
// Path: core/src/main/java/io/appflate/restmock/RESTMockServerStarter.java
// public class RESTMockServerStarter {
//
// public static final int KEEP_ALIVE_TIME = 60;
//
// public static void startSync(final RESTMockFileParser mocksFileParser) {
// startSync(mocksFileParser, null,
// new RESTMockOptions.Builder().build());
// }
//
// public static void startSync(final RESTMockFileParser mocksFileParser, RESTMockOptions options) {
// startSync(mocksFileParser, null, options);
// }
//
// public static void startSync(final RESTMockFileParser mocksFileParser, final RESTMockLogger logger) {
// startSync(mocksFileParser, logger, new RESTMockOptions.Builder().build());
// }
//
// public static void startSync(
// final RESTMockFileParser mocksFileParser,
// final RESTMockLogger logger,
// final RESTMockOptions restMockOptions
// ) {
// // it has to be like that since Android prevents starting testServer on main Thread.
// ThreadPoolExecutor threadPoolExecutor =
// new ThreadPoolExecutor(1, 1, KEEP_ALIVE_TIME, TimeUnit.SECONDS, new LinkedBlockingQueue<Runnable>(1));
//
// threadPoolExecutor.execute(new Runnable() {
//
// @Override
// public void run() {
// try {
// RESTMockServer.init(mocksFileParser, logger, restMockOptions);
// } catch (IOException e) {
// RESTMockServer.getLogger().error("Server start error", e);
// throw new RuntimeException(e);
// }
// }
// });
// try {
// threadPoolExecutor.shutdown();
// if (!threadPoolExecutor.awaitTermination(KEEP_ALIVE_TIME, TimeUnit.SECONDS)) {
// throw new RuntimeException("mock server didn't manage to start within the given timeout (60 seconds)");
// }
// } catch (InterruptedException e) {
// RESTMockServer.getLogger().error("Server start error", e);
// throw new RuntimeException(e);
// }
// }
//
// private RESTMockServerStarter() {
// }
// }
// Path: android/src/main/java/io/appflate/restmock/android/RESTMockTestRunner.java
import android.os.Bundle;
import androidx.test.runner.AndroidJUnitRunner;
import io.appflate.restmock.RESTMockOptions;
import io.appflate.restmock.RESTMockServerStarter;
/*
* Copyright (C) 2016 Appflate.io
*
* 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 io.appflate.restmock.android;
/**
* Created by andrzejchm on 22/04/16.
*/
public class RESTMockTestRunner extends AndroidJUnitRunner {
@Override
public void onCreate(Bundle arguments) {
super.onCreate(arguments);
RESTMockServerStarter.startSync(new AndroidAssetsFileParser(getContext()), new AndroidLogger(), | new RESTMockOptions.Builder() |
andrzejchm/RESTMock | core/src/main/java/io/appflate/restmock/MatchableCall.java | // Path: core/src/main/java/io/appflate/restmock/utils/RequestMatcher.java
// public abstract class RequestMatcher extends TypeSafeMatcher<RecordedRequest> {
//
// private final String description;
//
// public RequestMatcher(String description) {
// this.description = description;
// }
//
// @Override
// public void describeTo(Description description) {
// description.appendText(this.description);
// }
// }
//
// Path: core/src/main/java/io/appflate/restmock/utils/RestMockUtils.java
// public final class RestMockUtils {
//
// public static MockResponse createResponseFromFile(RESTMockFileParser RESTMockFileParser, String jsonFilePath,
// int responseCode) throws Exception {
// String fileContents = RESTMockFileParser.readJsonFile(jsonFilePath);
// return new MockResponse().setResponseCode(responseCode).setBody(fileContents);
// }
//
// /**
// * Extract query parameters from a {@link URL}.
// *
// * @param url The {@link URL} to retrieve query parameters for.
// * @return A {@link List} of {@link QueryParam} objects. Each parameter has one key, and zero or
// * more values.
// * @throws UnsupportedEncodingException If unable to decode from UTF-8. This should never happen.
// */
// public static List<QueryParam> splitQuery(URL url) throws UnsupportedEncodingException {
// final Map<String, List<String>> queryPairs = new LinkedHashMap<>();
//
// String query = url.getQuery();
// if (query == null || query.trim().length() == 0) {
// return Collections.emptyList();
// }
//
// final String[] pairs = query.split("&");
// for (String pair : pairs) {
// final int idx = pair.indexOf("=");
// final String key = idx > 0 ? URLDecoder.decode(pair.substring(0, idx), "UTF-8") : pair;
// List<String> valueList = new LinkedList<>();
//
// if (queryPairs.containsKey(key)) {
// valueList = queryPairs.get(key);
// }
//
// final String value = idx > 0 && pair.length() > idx + 1 ? URLDecoder.decode(pair.substring(idx + 1), "UTF-8") : null;
// valueList.add(value);
//
// queryPairs.put(key, valueList);
// }
//
// List<QueryParam> finalParamList = new LinkedList<>();
// for (Map.Entry<String, List<String>> entry : queryPairs.entrySet()) {
// QueryParam nextFinalParam = new QueryParam(entry.getKey(), entry.getValue());
// finalParamList.add(nextFinalParam);
// }
//
// return finalParamList;
// }
//
// private RestMockUtils() {
// throw new UnsupportedOperationException("(╯‵Д′)╯ PLEASE STAHP!");
//
// }
// }
| import org.hamcrest.Matcher;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.concurrent.TimeUnit;
import io.appflate.restmock.utils.RequestMatcher;
import io.appflate.restmock.utils.RestMockUtils;
import okhttp3.mockwebserver.MockResponse;
import okhttp3.mockwebserver.RecordedRequest; | *
* <p>If you specify more than one response, each consecutive call to server will return next response from the list, if number of
* requests exceeds number of specified responses, the last response will be repeated</p>
*
* @param jsonFiles a comma-separated list of files' path to return. {@link RESTMockFileParser} is responsible of reading files for
* given paths.
* @return a {@link MatchableCall} that will return given {@code jsonFile} as a response.
*/
public MatchableCall thenReturnFile(String... jsonFiles) {
return thenReturnFile(200, jsonFiles);
}
/**
* Makes this MatchableCall return the {@code jsonFile}'s contents with the {@code responseCode} as a http status code.
*
* <p>This {@code MatchableCall} will be automatically scheduled within the {@code RESTMockServer} if you want to prevent that, see
* {@link MatchableCall#dontSet()}</p>
*
* <p>If you specify more than one response, each consecutive call to server will return next response from the list, if number of
* requests exceeds number of specified responses, the last response will be repeated</p>
*
* @param responseCode http status code
* @param jsonFiles a comma-separated list of json files' paths that will be returned. {@link RESTMockFileParser} is responsible of
* reading files for given paths.
* @return this {@code MatchableCall}
*/
public MatchableCall thenReturnFile(int responseCode, String... jsonFiles) {
List<MockResponse> responseFromFiles = new ArrayList<>(jsonFiles.length);
for (String jsonFile : jsonFiles) {
try { | // Path: core/src/main/java/io/appflate/restmock/utils/RequestMatcher.java
// public abstract class RequestMatcher extends TypeSafeMatcher<RecordedRequest> {
//
// private final String description;
//
// public RequestMatcher(String description) {
// this.description = description;
// }
//
// @Override
// public void describeTo(Description description) {
// description.appendText(this.description);
// }
// }
//
// Path: core/src/main/java/io/appflate/restmock/utils/RestMockUtils.java
// public final class RestMockUtils {
//
// public static MockResponse createResponseFromFile(RESTMockFileParser RESTMockFileParser, String jsonFilePath,
// int responseCode) throws Exception {
// String fileContents = RESTMockFileParser.readJsonFile(jsonFilePath);
// return new MockResponse().setResponseCode(responseCode).setBody(fileContents);
// }
//
// /**
// * Extract query parameters from a {@link URL}.
// *
// * @param url The {@link URL} to retrieve query parameters for.
// * @return A {@link List} of {@link QueryParam} objects. Each parameter has one key, and zero or
// * more values.
// * @throws UnsupportedEncodingException If unable to decode from UTF-8. This should never happen.
// */
// public static List<QueryParam> splitQuery(URL url) throws UnsupportedEncodingException {
// final Map<String, List<String>> queryPairs = new LinkedHashMap<>();
//
// String query = url.getQuery();
// if (query == null || query.trim().length() == 0) {
// return Collections.emptyList();
// }
//
// final String[] pairs = query.split("&");
// for (String pair : pairs) {
// final int idx = pair.indexOf("=");
// final String key = idx > 0 ? URLDecoder.decode(pair.substring(0, idx), "UTF-8") : pair;
// List<String> valueList = new LinkedList<>();
//
// if (queryPairs.containsKey(key)) {
// valueList = queryPairs.get(key);
// }
//
// final String value = idx > 0 && pair.length() > idx + 1 ? URLDecoder.decode(pair.substring(idx + 1), "UTF-8") : null;
// valueList.add(value);
//
// queryPairs.put(key, valueList);
// }
//
// List<QueryParam> finalParamList = new LinkedList<>();
// for (Map.Entry<String, List<String>> entry : queryPairs.entrySet()) {
// QueryParam nextFinalParam = new QueryParam(entry.getKey(), entry.getValue());
// finalParamList.add(nextFinalParam);
// }
//
// return finalParamList;
// }
//
// private RestMockUtils() {
// throw new UnsupportedOperationException("(╯‵Д′)╯ PLEASE STAHP!");
//
// }
// }
// Path: core/src/main/java/io/appflate/restmock/MatchableCall.java
import org.hamcrest.Matcher;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.concurrent.TimeUnit;
import io.appflate.restmock.utils.RequestMatcher;
import io.appflate.restmock.utils.RestMockUtils;
import okhttp3.mockwebserver.MockResponse;
import okhttp3.mockwebserver.RecordedRequest;
*
* <p>If you specify more than one response, each consecutive call to server will return next response from the list, if number of
* requests exceeds number of specified responses, the last response will be repeated</p>
*
* @param jsonFiles a comma-separated list of files' path to return. {@link RESTMockFileParser} is responsible of reading files for
* given paths.
* @return a {@link MatchableCall} that will return given {@code jsonFile} as a response.
*/
public MatchableCall thenReturnFile(String... jsonFiles) {
return thenReturnFile(200, jsonFiles);
}
/**
* Makes this MatchableCall return the {@code jsonFile}'s contents with the {@code responseCode} as a http status code.
*
* <p>This {@code MatchableCall} will be automatically scheduled within the {@code RESTMockServer} if you want to prevent that, see
* {@link MatchableCall#dontSet()}</p>
*
* <p>If you specify more than one response, each consecutive call to server will return next response from the list, if number of
* requests exceeds number of specified responses, the last response will be repeated</p>
*
* @param responseCode http status code
* @param jsonFiles a comma-separated list of json files' paths that will be returned. {@link RESTMockFileParser} is responsible of
* reading files for given paths.
* @return this {@code MatchableCall}
*/
public MatchableCall thenReturnFile(int responseCode, String... jsonFiles) {
List<MockResponse> responseFromFiles = new ArrayList<>(jsonFiles.length);
for (String jsonFile : jsonFiles) {
try { | responseFromFiles.add(RestMockUtils.createResponseFromFile(RESTMockFileParser, jsonFile, responseCode)); |
andrzejchm/RESTMock | core/src/main/java/io/appflate/restmock/RESTMockServer.java | // Path: core/src/main/java/io/appflate/restmock/logging/NOOpLogger.java
// public class NOOpLogger implements RESTMockLogger {
//
// @Override
// public void log(String message) {
// //intentionally empty
// }
//
// @Override
// public void error(String errorMessage) {
// //intentionally empty
// }
//
// @Override
// public void error(String errorMessage, Throwable exception) {
// //intentionally empty
// }
// }
//
// Path: core/src/main/java/io/appflate/restmock/logging/RESTMockLogger.java
// public interface RESTMockLogger {
//
// void log(String message);
//
// void error(String errorMessage);
//
// void error(String errorMessage, Throwable exception);
// }
//
// Path: core/src/main/java/io/appflate/restmock/utils/RequestMatchers.java
// public static RequestMatcher isDELETE() {
// return httpMethodIs("DELETE");
// }
//
// Path: core/src/main/java/io/appflate/restmock/utils/RequestMatchers.java
// public static RequestMatcher isGET() {
// return httpMethodIs("GET");
// }
//
// Path: core/src/main/java/io/appflate/restmock/utils/RequestMatchers.java
// public static RequestMatcher isHEAD() {
// return httpMethodIs("HEAD");
// }
//
// Path: core/src/main/java/io/appflate/restmock/utils/RequestMatchers.java
// public static RequestMatcher isPATCH() {
// return httpMethodIs("PATCH");
// }
//
// Path: core/src/main/java/io/appflate/restmock/utils/RequestMatchers.java
// public static RequestMatcher isPOST() {
// return httpMethodIs("POST");
// }
//
// Path: core/src/main/java/io/appflate/restmock/utils/RequestMatchers.java
// public static RequestMatcher isPUT() {
// return httpMethodIs("PUT");
// }
| import static io.appflate.restmock.utils.RequestMatchers.isPUT;
import static org.hamcrest.core.AllOf.allOf;
import io.appflate.restmock.logging.NOOpLogger;
import io.appflate.restmock.logging.RESTMockLogger;
import java.io.IOException;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.X509TrustManager;
import okhttp3.mockwebserver.MockWebServer;
import okhttp3.mockwebserver.RecordedRequest;
import org.hamcrest.Matcher;
import static io.appflate.restmock.utils.RequestMatchers.isDELETE;
import static io.appflate.restmock.utils.RequestMatchers.isGET;
import static io.appflate.restmock.utils.RequestMatchers.isHEAD;
import static io.appflate.restmock.utils.RequestMatchers.isPATCH;
import static io.appflate.restmock.utils.RequestMatchers.isPOST; | /*
* Copyright (C) 2016 Appflate.io
*
* 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 io.appflate.restmock;
@SuppressWarnings("unused")
public class RESTMockServer {
public static final String RESPONSE_NOT_MOCKED = "NOT MOCKED";
public static final String MORE_THAN_ONE_RESPONSE_ERROR = "There are more than one response matching this request: ";
static MockWebServer mockWebServer;
static MatchableCallsRequestDispatcher dispatcher;
private static String serverBaseUrl;
private static RESTMockFileParser RESTMockFileParser; | // Path: core/src/main/java/io/appflate/restmock/logging/NOOpLogger.java
// public class NOOpLogger implements RESTMockLogger {
//
// @Override
// public void log(String message) {
// //intentionally empty
// }
//
// @Override
// public void error(String errorMessage) {
// //intentionally empty
// }
//
// @Override
// public void error(String errorMessage, Throwable exception) {
// //intentionally empty
// }
// }
//
// Path: core/src/main/java/io/appflate/restmock/logging/RESTMockLogger.java
// public interface RESTMockLogger {
//
// void log(String message);
//
// void error(String errorMessage);
//
// void error(String errorMessage, Throwable exception);
// }
//
// Path: core/src/main/java/io/appflate/restmock/utils/RequestMatchers.java
// public static RequestMatcher isDELETE() {
// return httpMethodIs("DELETE");
// }
//
// Path: core/src/main/java/io/appflate/restmock/utils/RequestMatchers.java
// public static RequestMatcher isGET() {
// return httpMethodIs("GET");
// }
//
// Path: core/src/main/java/io/appflate/restmock/utils/RequestMatchers.java
// public static RequestMatcher isHEAD() {
// return httpMethodIs("HEAD");
// }
//
// Path: core/src/main/java/io/appflate/restmock/utils/RequestMatchers.java
// public static RequestMatcher isPATCH() {
// return httpMethodIs("PATCH");
// }
//
// Path: core/src/main/java/io/appflate/restmock/utils/RequestMatchers.java
// public static RequestMatcher isPOST() {
// return httpMethodIs("POST");
// }
//
// Path: core/src/main/java/io/appflate/restmock/utils/RequestMatchers.java
// public static RequestMatcher isPUT() {
// return httpMethodIs("PUT");
// }
// Path: core/src/main/java/io/appflate/restmock/RESTMockServer.java
import static io.appflate.restmock.utils.RequestMatchers.isPUT;
import static org.hamcrest.core.AllOf.allOf;
import io.appflate.restmock.logging.NOOpLogger;
import io.appflate.restmock.logging.RESTMockLogger;
import java.io.IOException;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.X509TrustManager;
import okhttp3.mockwebserver.MockWebServer;
import okhttp3.mockwebserver.RecordedRequest;
import org.hamcrest.Matcher;
import static io.appflate.restmock.utils.RequestMatchers.isDELETE;
import static io.appflate.restmock.utils.RequestMatchers.isGET;
import static io.appflate.restmock.utils.RequestMatchers.isHEAD;
import static io.appflate.restmock.utils.RequestMatchers.isPATCH;
import static io.appflate.restmock.utils.RequestMatchers.isPOST;
/*
* Copyright (C) 2016 Appflate.io
*
* 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 io.appflate.restmock;
@SuppressWarnings("unused")
public class RESTMockServer {
public static final String RESPONSE_NOT_MOCKED = "NOT MOCKED";
public static final String MORE_THAN_ONE_RESPONSE_ERROR = "There are more than one response matching this request: ";
static MockWebServer mockWebServer;
static MatchableCallsRequestDispatcher dispatcher;
private static String serverBaseUrl;
private static RESTMockFileParser RESTMockFileParser; | private static RESTMockLogger logger = new NOOpLogger(); |
andrzejchm/RESTMock | core/src/main/java/io/appflate/restmock/RESTMockServer.java | // Path: core/src/main/java/io/appflate/restmock/logging/NOOpLogger.java
// public class NOOpLogger implements RESTMockLogger {
//
// @Override
// public void log(String message) {
// //intentionally empty
// }
//
// @Override
// public void error(String errorMessage) {
// //intentionally empty
// }
//
// @Override
// public void error(String errorMessage, Throwable exception) {
// //intentionally empty
// }
// }
//
// Path: core/src/main/java/io/appflate/restmock/logging/RESTMockLogger.java
// public interface RESTMockLogger {
//
// void log(String message);
//
// void error(String errorMessage);
//
// void error(String errorMessage, Throwable exception);
// }
//
// Path: core/src/main/java/io/appflate/restmock/utils/RequestMatchers.java
// public static RequestMatcher isDELETE() {
// return httpMethodIs("DELETE");
// }
//
// Path: core/src/main/java/io/appflate/restmock/utils/RequestMatchers.java
// public static RequestMatcher isGET() {
// return httpMethodIs("GET");
// }
//
// Path: core/src/main/java/io/appflate/restmock/utils/RequestMatchers.java
// public static RequestMatcher isHEAD() {
// return httpMethodIs("HEAD");
// }
//
// Path: core/src/main/java/io/appflate/restmock/utils/RequestMatchers.java
// public static RequestMatcher isPATCH() {
// return httpMethodIs("PATCH");
// }
//
// Path: core/src/main/java/io/appflate/restmock/utils/RequestMatchers.java
// public static RequestMatcher isPOST() {
// return httpMethodIs("POST");
// }
//
// Path: core/src/main/java/io/appflate/restmock/utils/RequestMatchers.java
// public static RequestMatcher isPUT() {
// return httpMethodIs("PUT");
// }
| import static io.appflate.restmock.utils.RequestMatchers.isPUT;
import static org.hamcrest.core.AllOf.allOf;
import io.appflate.restmock.logging.NOOpLogger;
import io.appflate.restmock.logging.RESTMockLogger;
import java.io.IOException;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.X509TrustManager;
import okhttp3.mockwebserver.MockWebServer;
import okhttp3.mockwebserver.RecordedRequest;
import org.hamcrest.Matcher;
import static io.appflate.restmock.utils.RequestMatchers.isDELETE;
import static io.appflate.restmock.utils.RequestMatchers.isGET;
import static io.appflate.restmock.utils.RequestMatchers.isHEAD;
import static io.appflate.restmock.utils.RequestMatchers.isPATCH;
import static io.appflate.restmock.utils.RequestMatchers.isPOST; | /*
* Copyright (C) 2016 Appflate.io
*
* 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 io.appflate.restmock;
@SuppressWarnings("unused")
public class RESTMockServer {
public static final String RESPONSE_NOT_MOCKED = "NOT MOCKED";
public static final String MORE_THAN_ONE_RESPONSE_ERROR = "There are more than one response matching this request: ";
static MockWebServer mockWebServer;
static MatchableCallsRequestDispatcher dispatcher;
private static String serverBaseUrl;
private static RESTMockFileParser RESTMockFileParser; | // Path: core/src/main/java/io/appflate/restmock/logging/NOOpLogger.java
// public class NOOpLogger implements RESTMockLogger {
//
// @Override
// public void log(String message) {
// //intentionally empty
// }
//
// @Override
// public void error(String errorMessage) {
// //intentionally empty
// }
//
// @Override
// public void error(String errorMessage, Throwable exception) {
// //intentionally empty
// }
// }
//
// Path: core/src/main/java/io/appflate/restmock/logging/RESTMockLogger.java
// public interface RESTMockLogger {
//
// void log(String message);
//
// void error(String errorMessage);
//
// void error(String errorMessage, Throwable exception);
// }
//
// Path: core/src/main/java/io/appflate/restmock/utils/RequestMatchers.java
// public static RequestMatcher isDELETE() {
// return httpMethodIs("DELETE");
// }
//
// Path: core/src/main/java/io/appflate/restmock/utils/RequestMatchers.java
// public static RequestMatcher isGET() {
// return httpMethodIs("GET");
// }
//
// Path: core/src/main/java/io/appflate/restmock/utils/RequestMatchers.java
// public static RequestMatcher isHEAD() {
// return httpMethodIs("HEAD");
// }
//
// Path: core/src/main/java/io/appflate/restmock/utils/RequestMatchers.java
// public static RequestMatcher isPATCH() {
// return httpMethodIs("PATCH");
// }
//
// Path: core/src/main/java/io/appflate/restmock/utils/RequestMatchers.java
// public static RequestMatcher isPOST() {
// return httpMethodIs("POST");
// }
//
// Path: core/src/main/java/io/appflate/restmock/utils/RequestMatchers.java
// public static RequestMatcher isPUT() {
// return httpMethodIs("PUT");
// }
// Path: core/src/main/java/io/appflate/restmock/RESTMockServer.java
import static io.appflate.restmock.utils.RequestMatchers.isPUT;
import static org.hamcrest.core.AllOf.allOf;
import io.appflate.restmock.logging.NOOpLogger;
import io.appflate.restmock.logging.RESTMockLogger;
import java.io.IOException;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.X509TrustManager;
import okhttp3.mockwebserver.MockWebServer;
import okhttp3.mockwebserver.RecordedRequest;
import org.hamcrest.Matcher;
import static io.appflate.restmock.utils.RequestMatchers.isDELETE;
import static io.appflate.restmock.utils.RequestMatchers.isGET;
import static io.appflate.restmock.utils.RequestMatchers.isHEAD;
import static io.appflate.restmock.utils.RequestMatchers.isPATCH;
import static io.appflate.restmock.utils.RequestMatchers.isPOST;
/*
* Copyright (C) 2016 Appflate.io
*
* 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 io.appflate.restmock;
@SuppressWarnings("unused")
public class RESTMockServer {
public static final String RESPONSE_NOT_MOCKED = "NOT MOCKED";
public static final String MORE_THAN_ONE_RESPONSE_ERROR = "There are more than one response matching this request: ";
static MockWebServer mockWebServer;
static MatchableCallsRequestDispatcher dispatcher;
private static String serverBaseUrl;
private static RESTMockFileParser RESTMockFileParser; | private static RESTMockLogger logger = new NOOpLogger(); |
andrzejchm/RESTMock | core/src/main/java/io/appflate/restmock/RESTMockServer.java | // Path: core/src/main/java/io/appflate/restmock/logging/NOOpLogger.java
// public class NOOpLogger implements RESTMockLogger {
//
// @Override
// public void log(String message) {
// //intentionally empty
// }
//
// @Override
// public void error(String errorMessage) {
// //intentionally empty
// }
//
// @Override
// public void error(String errorMessage, Throwable exception) {
// //intentionally empty
// }
// }
//
// Path: core/src/main/java/io/appflate/restmock/logging/RESTMockLogger.java
// public interface RESTMockLogger {
//
// void log(String message);
//
// void error(String errorMessage);
//
// void error(String errorMessage, Throwable exception);
// }
//
// Path: core/src/main/java/io/appflate/restmock/utils/RequestMatchers.java
// public static RequestMatcher isDELETE() {
// return httpMethodIs("DELETE");
// }
//
// Path: core/src/main/java/io/appflate/restmock/utils/RequestMatchers.java
// public static RequestMatcher isGET() {
// return httpMethodIs("GET");
// }
//
// Path: core/src/main/java/io/appflate/restmock/utils/RequestMatchers.java
// public static RequestMatcher isHEAD() {
// return httpMethodIs("HEAD");
// }
//
// Path: core/src/main/java/io/appflate/restmock/utils/RequestMatchers.java
// public static RequestMatcher isPATCH() {
// return httpMethodIs("PATCH");
// }
//
// Path: core/src/main/java/io/appflate/restmock/utils/RequestMatchers.java
// public static RequestMatcher isPOST() {
// return httpMethodIs("POST");
// }
//
// Path: core/src/main/java/io/appflate/restmock/utils/RequestMatchers.java
// public static RequestMatcher isPUT() {
// return httpMethodIs("PUT");
// }
| import static io.appflate.restmock.utils.RequestMatchers.isPUT;
import static org.hamcrest.core.AllOf.allOf;
import io.appflate.restmock.logging.NOOpLogger;
import io.appflate.restmock.logging.RESTMockLogger;
import java.io.IOException;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.X509TrustManager;
import okhttp3.mockwebserver.MockWebServer;
import okhttp3.mockwebserver.RecordedRequest;
import org.hamcrest.Matcher;
import static io.appflate.restmock.utils.RequestMatchers.isDELETE;
import static io.appflate.restmock.utils.RequestMatchers.isGET;
import static io.appflate.restmock.utils.RequestMatchers.isHEAD;
import static io.appflate.restmock.utils.RequestMatchers.isPATCH;
import static io.appflate.restmock.utils.RequestMatchers.isPOST; | * @param replacement {@code MatchableCall} to be added to {@code RESTMockServer}
*/
public static void replaceMatchableCall(MatchableCall call, MatchableCall replacement) {
removeMatchableCall(call);
dispatcher.addMatchableCall(replacement);
}
/**
* @return this {@code RESTMockServer} url to use as an endpoint in your tests, or null, if the instance wasn't started yet
*/
public static String getUrl() {
return serverBaseUrl;
}
/**
* adds {@code call} to this {@code RESTMockServer}
*
* @param call to be added to this {@code RESTMockServer}
*/
public static void addMatchableCall(final MatchableCall call) {
dispatcher.addMatchableCall(call);
}
/**
* Helper method to create MatchableCall that will be matched only for GET requests along with the specified {@code requestMatcher}
*
* @param requestMatcher matcher to match a GET request
* @return {@code MatchableCall} that will match GET requests along with {@code requestMatcher}
*/
public static MatchableCall whenGET(Matcher<RecordedRequest> requestMatcher) { | // Path: core/src/main/java/io/appflate/restmock/logging/NOOpLogger.java
// public class NOOpLogger implements RESTMockLogger {
//
// @Override
// public void log(String message) {
// //intentionally empty
// }
//
// @Override
// public void error(String errorMessage) {
// //intentionally empty
// }
//
// @Override
// public void error(String errorMessage, Throwable exception) {
// //intentionally empty
// }
// }
//
// Path: core/src/main/java/io/appflate/restmock/logging/RESTMockLogger.java
// public interface RESTMockLogger {
//
// void log(String message);
//
// void error(String errorMessage);
//
// void error(String errorMessage, Throwable exception);
// }
//
// Path: core/src/main/java/io/appflate/restmock/utils/RequestMatchers.java
// public static RequestMatcher isDELETE() {
// return httpMethodIs("DELETE");
// }
//
// Path: core/src/main/java/io/appflate/restmock/utils/RequestMatchers.java
// public static RequestMatcher isGET() {
// return httpMethodIs("GET");
// }
//
// Path: core/src/main/java/io/appflate/restmock/utils/RequestMatchers.java
// public static RequestMatcher isHEAD() {
// return httpMethodIs("HEAD");
// }
//
// Path: core/src/main/java/io/appflate/restmock/utils/RequestMatchers.java
// public static RequestMatcher isPATCH() {
// return httpMethodIs("PATCH");
// }
//
// Path: core/src/main/java/io/appflate/restmock/utils/RequestMatchers.java
// public static RequestMatcher isPOST() {
// return httpMethodIs("POST");
// }
//
// Path: core/src/main/java/io/appflate/restmock/utils/RequestMatchers.java
// public static RequestMatcher isPUT() {
// return httpMethodIs("PUT");
// }
// Path: core/src/main/java/io/appflate/restmock/RESTMockServer.java
import static io.appflate.restmock.utils.RequestMatchers.isPUT;
import static org.hamcrest.core.AllOf.allOf;
import io.appflate.restmock.logging.NOOpLogger;
import io.appflate.restmock.logging.RESTMockLogger;
import java.io.IOException;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.X509TrustManager;
import okhttp3.mockwebserver.MockWebServer;
import okhttp3.mockwebserver.RecordedRequest;
import org.hamcrest.Matcher;
import static io.appflate.restmock.utils.RequestMatchers.isDELETE;
import static io.appflate.restmock.utils.RequestMatchers.isGET;
import static io.appflate.restmock.utils.RequestMatchers.isHEAD;
import static io.appflate.restmock.utils.RequestMatchers.isPATCH;
import static io.appflate.restmock.utils.RequestMatchers.isPOST;
* @param replacement {@code MatchableCall} to be added to {@code RESTMockServer}
*/
public static void replaceMatchableCall(MatchableCall call, MatchableCall replacement) {
removeMatchableCall(call);
dispatcher.addMatchableCall(replacement);
}
/**
* @return this {@code RESTMockServer} url to use as an endpoint in your tests, or null, if the instance wasn't started yet
*/
public static String getUrl() {
return serverBaseUrl;
}
/**
* adds {@code call} to this {@code RESTMockServer}
*
* @param call to be added to this {@code RESTMockServer}
*/
public static void addMatchableCall(final MatchableCall call) {
dispatcher.addMatchableCall(call);
}
/**
* Helper method to create MatchableCall that will be matched only for GET requests along with the specified {@code requestMatcher}
*
* @param requestMatcher matcher to match a GET request
* @return {@code MatchableCall} that will match GET requests along with {@code requestMatcher}
*/
public static MatchableCall whenGET(Matcher<RecordedRequest> requestMatcher) { | return RESTMockServer.whenRequested(allOf(isGET(), requestMatcher)); |
andrzejchm/RESTMock | core/src/main/java/io/appflate/restmock/RESTMockServer.java | // Path: core/src/main/java/io/appflate/restmock/logging/NOOpLogger.java
// public class NOOpLogger implements RESTMockLogger {
//
// @Override
// public void log(String message) {
// //intentionally empty
// }
//
// @Override
// public void error(String errorMessage) {
// //intentionally empty
// }
//
// @Override
// public void error(String errorMessage, Throwable exception) {
// //intentionally empty
// }
// }
//
// Path: core/src/main/java/io/appflate/restmock/logging/RESTMockLogger.java
// public interface RESTMockLogger {
//
// void log(String message);
//
// void error(String errorMessage);
//
// void error(String errorMessage, Throwable exception);
// }
//
// Path: core/src/main/java/io/appflate/restmock/utils/RequestMatchers.java
// public static RequestMatcher isDELETE() {
// return httpMethodIs("DELETE");
// }
//
// Path: core/src/main/java/io/appflate/restmock/utils/RequestMatchers.java
// public static RequestMatcher isGET() {
// return httpMethodIs("GET");
// }
//
// Path: core/src/main/java/io/appflate/restmock/utils/RequestMatchers.java
// public static RequestMatcher isHEAD() {
// return httpMethodIs("HEAD");
// }
//
// Path: core/src/main/java/io/appflate/restmock/utils/RequestMatchers.java
// public static RequestMatcher isPATCH() {
// return httpMethodIs("PATCH");
// }
//
// Path: core/src/main/java/io/appflate/restmock/utils/RequestMatchers.java
// public static RequestMatcher isPOST() {
// return httpMethodIs("POST");
// }
//
// Path: core/src/main/java/io/appflate/restmock/utils/RequestMatchers.java
// public static RequestMatcher isPUT() {
// return httpMethodIs("PUT");
// }
| import static io.appflate.restmock.utils.RequestMatchers.isPUT;
import static org.hamcrest.core.AllOf.allOf;
import io.appflate.restmock.logging.NOOpLogger;
import io.appflate.restmock.logging.RESTMockLogger;
import java.io.IOException;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.X509TrustManager;
import okhttp3.mockwebserver.MockWebServer;
import okhttp3.mockwebserver.RecordedRequest;
import org.hamcrest.Matcher;
import static io.appflate.restmock.utils.RequestMatchers.isDELETE;
import static io.appflate.restmock.utils.RequestMatchers.isGET;
import static io.appflate.restmock.utils.RequestMatchers.isHEAD;
import static io.appflate.restmock.utils.RequestMatchers.isPATCH;
import static io.appflate.restmock.utils.RequestMatchers.isPOST; | public static String getUrl() {
return serverBaseUrl;
}
/**
* adds {@code call} to this {@code RESTMockServer}
*
* @param call to be added to this {@code RESTMockServer}
*/
public static void addMatchableCall(final MatchableCall call) {
dispatcher.addMatchableCall(call);
}
/**
* Helper method to create MatchableCall that will be matched only for GET requests along with the specified {@code requestMatcher}
*
* @param requestMatcher matcher to match a GET request
* @return {@code MatchableCall} that will match GET requests along with {@code requestMatcher}
*/
public static MatchableCall whenGET(Matcher<RecordedRequest> requestMatcher) {
return RESTMockServer.whenRequested(allOf(isGET(), requestMatcher));
}
/**
* Helper method to create MatchableCall that will be matched only for POST requests along with the specified {@code requestMatcher}
*
* @param requestMatcher matcher to match a POST request
* @return {@code MatchableCall} that will match POST requests along with {@code requestMatcher}
*/
public static MatchableCall whenPOST(Matcher<RecordedRequest> requestMatcher) { | // Path: core/src/main/java/io/appflate/restmock/logging/NOOpLogger.java
// public class NOOpLogger implements RESTMockLogger {
//
// @Override
// public void log(String message) {
// //intentionally empty
// }
//
// @Override
// public void error(String errorMessage) {
// //intentionally empty
// }
//
// @Override
// public void error(String errorMessage, Throwable exception) {
// //intentionally empty
// }
// }
//
// Path: core/src/main/java/io/appflate/restmock/logging/RESTMockLogger.java
// public interface RESTMockLogger {
//
// void log(String message);
//
// void error(String errorMessage);
//
// void error(String errorMessage, Throwable exception);
// }
//
// Path: core/src/main/java/io/appflate/restmock/utils/RequestMatchers.java
// public static RequestMatcher isDELETE() {
// return httpMethodIs("DELETE");
// }
//
// Path: core/src/main/java/io/appflate/restmock/utils/RequestMatchers.java
// public static RequestMatcher isGET() {
// return httpMethodIs("GET");
// }
//
// Path: core/src/main/java/io/appflate/restmock/utils/RequestMatchers.java
// public static RequestMatcher isHEAD() {
// return httpMethodIs("HEAD");
// }
//
// Path: core/src/main/java/io/appflate/restmock/utils/RequestMatchers.java
// public static RequestMatcher isPATCH() {
// return httpMethodIs("PATCH");
// }
//
// Path: core/src/main/java/io/appflate/restmock/utils/RequestMatchers.java
// public static RequestMatcher isPOST() {
// return httpMethodIs("POST");
// }
//
// Path: core/src/main/java/io/appflate/restmock/utils/RequestMatchers.java
// public static RequestMatcher isPUT() {
// return httpMethodIs("PUT");
// }
// Path: core/src/main/java/io/appflate/restmock/RESTMockServer.java
import static io.appflate.restmock.utils.RequestMatchers.isPUT;
import static org.hamcrest.core.AllOf.allOf;
import io.appflate.restmock.logging.NOOpLogger;
import io.appflate.restmock.logging.RESTMockLogger;
import java.io.IOException;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.X509TrustManager;
import okhttp3.mockwebserver.MockWebServer;
import okhttp3.mockwebserver.RecordedRequest;
import org.hamcrest.Matcher;
import static io.appflate.restmock.utils.RequestMatchers.isDELETE;
import static io.appflate.restmock.utils.RequestMatchers.isGET;
import static io.appflate.restmock.utils.RequestMatchers.isHEAD;
import static io.appflate.restmock.utils.RequestMatchers.isPATCH;
import static io.appflate.restmock.utils.RequestMatchers.isPOST;
public static String getUrl() {
return serverBaseUrl;
}
/**
* adds {@code call} to this {@code RESTMockServer}
*
* @param call to be added to this {@code RESTMockServer}
*/
public static void addMatchableCall(final MatchableCall call) {
dispatcher.addMatchableCall(call);
}
/**
* Helper method to create MatchableCall that will be matched only for GET requests along with the specified {@code requestMatcher}
*
* @param requestMatcher matcher to match a GET request
* @return {@code MatchableCall} that will match GET requests along with {@code requestMatcher}
*/
public static MatchableCall whenGET(Matcher<RecordedRequest> requestMatcher) {
return RESTMockServer.whenRequested(allOf(isGET(), requestMatcher));
}
/**
* Helper method to create MatchableCall that will be matched only for POST requests along with the specified {@code requestMatcher}
*
* @param requestMatcher matcher to match a POST request
* @return {@code MatchableCall} that will match POST requests along with {@code requestMatcher}
*/
public static MatchableCall whenPOST(Matcher<RecordedRequest> requestMatcher) { | return RESTMockServer.whenRequested(allOf(isPOST(), requestMatcher)); |
andrzejchm/RESTMock | core/src/main/java/io/appflate/restmock/RESTMockServer.java | // Path: core/src/main/java/io/appflate/restmock/logging/NOOpLogger.java
// public class NOOpLogger implements RESTMockLogger {
//
// @Override
// public void log(String message) {
// //intentionally empty
// }
//
// @Override
// public void error(String errorMessage) {
// //intentionally empty
// }
//
// @Override
// public void error(String errorMessage, Throwable exception) {
// //intentionally empty
// }
// }
//
// Path: core/src/main/java/io/appflate/restmock/logging/RESTMockLogger.java
// public interface RESTMockLogger {
//
// void log(String message);
//
// void error(String errorMessage);
//
// void error(String errorMessage, Throwable exception);
// }
//
// Path: core/src/main/java/io/appflate/restmock/utils/RequestMatchers.java
// public static RequestMatcher isDELETE() {
// return httpMethodIs("DELETE");
// }
//
// Path: core/src/main/java/io/appflate/restmock/utils/RequestMatchers.java
// public static RequestMatcher isGET() {
// return httpMethodIs("GET");
// }
//
// Path: core/src/main/java/io/appflate/restmock/utils/RequestMatchers.java
// public static RequestMatcher isHEAD() {
// return httpMethodIs("HEAD");
// }
//
// Path: core/src/main/java/io/appflate/restmock/utils/RequestMatchers.java
// public static RequestMatcher isPATCH() {
// return httpMethodIs("PATCH");
// }
//
// Path: core/src/main/java/io/appflate/restmock/utils/RequestMatchers.java
// public static RequestMatcher isPOST() {
// return httpMethodIs("POST");
// }
//
// Path: core/src/main/java/io/appflate/restmock/utils/RequestMatchers.java
// public static RequestMatcher isPUT() {
// return httpMethodIs("PUT");
// }
| import static io.appflate.restmock.utils.RequestMatchers.isPUT;
import static org.hamcrest.core.AllOf.allOf;
import io.appflate.restmock.logging.NOOpLogger;
import io.appflate.restmock.logging.RESTMockLogger;
import java.io.IOException;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.X509TrustManager;
import okhttp3.mockwebserver.MockWebServer;
import okhttp3.mockwebserver.RecordedRequest;
import org.hamcrest.Matcher;
import static io.appflate.restmock.utils.RequestMatchers.isDELETE;
import static io.appflate.restmock.utils.RequestMatchers.isGET;
import static io.appflate.restmock.utils.RequestMatchers.isHEAD;
import static io.appflate.restmock.utils.RequestMatchers.isPATCH;
import static io.appflate.restmock.utils.RequestMatchers.isPOST; | dispatcher.addMatchableCall(call);
}
/**
* Helper method to create MatchableCall that will be matched only for GET requests along with the specified {@code requestMatcher}
*
* @param requestMatcher matcher to match a GET request
* @return {@code MatchableCall} that will match GET requests along with {@code requestMatcher}
*/
public static MatchableCall whenGET(Matcher<RecordedRequest> requestMatcher) {
return RESTMockServer.whenRequested(allOf(isGET(), requestMatcher));
}
/**
* Helper method to create MatchableCall that will be matched only for POST requests along with the specified {@code requestMatcher}
*
* @param requestMatcher matcher to match a POST request
* @return {@code MatchableCall} that will match POST requests along with {@code requestMatcher}
*/
public static MatchableCall whenPOST(Matcher<RecordedRequest> requestMatcher) {
return RESTMockServer.whenRequested(allOf(isPOST(), requestMatcher));
}
/**
* Helper method to create MatchableCall that will be matched only for PUT requests along with the specified {@code requestMatcher}
*
* @param requestMatcher matcher to match a PUT request
* @return {@code MatchableCall} that will match PUT requests along with {@code requestMatcher}
*/
public static MatchableCall whenPUT(Matcher<RecordedRequest> requestMatcher) { | // Path: core/src/main/java/io/appflate/restmock/logging/NOOpLogger.java
// public class NOOpLogger implements RESTMockLogger {
//
// @Override
// public void log(String message) {
// //intentionally empty
// }
//
// @Override
// public void error(String errorMessage) {
// //intentionally empty
// }
//
// @Override
// public void error(String errorMessage, Throwable exception) {
// //intentionally empty
// }
// }
//
// Path: core/src/main/java/io/appflate/restmock/logging/RESTMockLogger.java
// public interface RESTMockLogger {
//
// void log(String message);
//
// void error(String errorMessage);
//
// void error(String errorMessage, Throwable exception);
// }
//
// Path: core/src/main/java/io/appflate/restmock/utils/RequestMatchers.java
// public static RequestMatcher isDELETE() {
// return httpMethodIs("DELETE");
// }
//
// Path: core/src/main/java/io/appflate/restmock/utils/RequestMatchers.java
// public static RequestMatcher isGET() {
// return httpMethodIs("GET");
// }
//
// Path: core/src/main/java/io/appflate/restmock/utils/RequestMatchers.java
// public static RequestMatcher isHEAD() {
// return httpMethodIs("HEAD");
// }
//
// Path: core/src/main/java/io/appflate/restmock/utils/RequestMatchers.java
// public static RequestMatcher isPATCH() {
// return httpMethodIs("PATCH");
// }
//
// Path: core/src/main/java/io/appflate/restmock/utils/RequestMatchers.java
// public static RequestMatcher isPOST() {
// return httpMethodIs("POST");
// }
//
// Path: core/src/main/java/io/appflate/restmock/utils/RequestMatchers.java
// public static RequestMatcher isPUT() {
// return httpMethodIs("PUT");
// }
// Path: core/src/main/java/io/appflate/restmock/RESTMockServer.java
import static io.appflate.restmock.utils.RequestMatchers.isPUT;
import static org.hamcrest.core.AllOf.allOf;
import io.appflate.restmock.logging.NOOpLogger;
import io.appflate.restmock.logging.RESTMockLogger;
import java.io.IOException;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.X509TrustManager;
import okhttp3.mockwebserver.MockWebServer;
import okhttp3.mockwebserver.RecordedRequest;
import org.hamcrest.Matcher;
import static io.appflate.restmock.utils.RequestMatchers.isDELETE;
import static io.appflate.restmock.utils.RequestMatchers.isGET;
import static io.appflate.restmock.utils.RequestMatchers.isHEAD;
import static io.appflate.restmock.utils.RequestMatchers.isPATCH;
import static io.appflate.restmock.utils.RequestMatchers.isPOST;
dispatcher.addMatchableCall(call);
}
/**
* Helper method to create MatchableCall that will be matched only for GET requests along with the specified {@code requestMatcher}
*
* @param requestMatcher matcher to match a GET request
* @return {@code MatchableCall} that will match GET requests along with {@code requestMatcher}
*/
public static MatchableCall whenGET(Matcher<RecordedRequest> requestMatcher) {
return RESTMockServer.whenRequested(allOf(isGET(), requestMatcher));
}
/**
* Helper method to create MatchableCall that will be matched only for POST requests along with the specified {@code requestMatcher}
*
* @param requestMatcher matcher to match a POST request
* @return {@code MatchableCall} that will match POST requests along with {@code requestMatcher}
*/
public static MatchableCall whenPOST(Matcher<RecordedRequest> requestMatcher) {
return RESTMockServer.whenRequested(allOf(isPOST(), requestMatcher));
}
/**
* Helper method to create MatchableCall that will be matched only for PUT requests along with the specified {@code requestMatcher}
*
* @param requestMatcher matcher to match a PUT request
* @return {@code MatchableCall} that will match PUT requests along with {@code requestMatcher}
*/
public static MatchableCall whenPUT(Matcher<RecordedRequest> requestMatcher) { | return RESTMockServer.whenRequested(allOf(isPUT(), requestMatcher)); |
andrzejchm/RESTMock | core/src/main/java/io/appflate/restmock/RESTMockServer.java | // Path: core/src/main/java/io/appflate/restmock/logging/NOOpLogger.java
// public class NOOpLogger implements RESTMockLogger {
//
// @Override
// public void log(String message) {
// //intentionally empty
// }
//
// @Override
// public void error(String errorMessage) {
// //intentionally empty
// }
//
// @Override
// public void error(String errorMessage, Throwable exception) {
// //intentionally empty
// }
// }
//
// Path: core/src/main/java/io/appflate/restmock/logging/RESTMockLogger.java
// public interface RESTMockLogger {
//
// void log(String message);
//
// void error(String errorMessage);
//
// void error(String errorMessage, Throwable exception);
// }
//
// Path: core/src/main/java/io/appflate/restmock/utils/RequestMatchers.java
// public static RequestMatcher isDELETE() {
// return httpMethodIs("DELETE");
// }
//
// Path: core/src/main/java/io/appflate/restmock/utils/RequestMatchers.java
// public static RequestMatcher isGET() {
// return httpMethodIs("GET");
// }
//
// Path: core/src/main/java/io/appflate/restmock/utils/RequestMatchers.java
// public static RequestMatcher isHEAD() {
// return httpMethodIs("HEAD");
// }
//
// Path: core/src/main/java/io/appflate/restmock/utils/RequestMatchers.java
// public static RequestMatcher isPATCH() {
// return httpMethodIs("PATCH");
// }
//
// Path: core/src/main/java/io/appflate/restmock/utils/RequestMatchers.java
// public static RequestMatcher isPOST() {
// return httpMethodIs("POST");
// }
//
// Path: core/src/main/java/io/appflate/restmock/utils/RequestMatchers.java
// public static RequestMatcher isPUT() {
// return httpMethodIs("PUT");
// }
| import static io.appflate.restmock.utils.RequestMatchers.isPUT;
import static org.hamcrest.core.AllOf.allOf;
import io.appflate.restmock.logging.NOOpLogger;
import io.appflate.restmock.logging.RESTMockLogger;
import java.io.IOException;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.X509TrustManager;
import okhttp3.mockwebserver.MockWebServer;
import okhttp3.mockwebserver.RecordedRequest;
import org.hamcrest.Matcher;
import static io.appflate.restmock.utils.RequestMatchers.isDELETE;
import static io.appflate.restmock.utils.RequestMatchers.isGET;
import static io.appflate.restmock.utils.RequestMatchers.isHEAD;
import static io.appflate.restmock.utils.RequestMatchers.isPATCH;
import static io.appflate.restmock.utils.RequestMatchers.isPOST; | return RESTMockServer.whenRequested(allOf(isGET(), requestMatcher));
}
/**
* Helper method to create MatchableCall that will be matched only for POST requests along with the specified {@code requestMatcher}
*
* @param requestMatcher matcher to match a POST request
* @return {@code MatchableCall} that will match POST requests along with {@code requestMatcher}
*/
public static MatchableCall whenPOST(Matcher<RecordedRequest> requestMatcher) {
return RESTMockServer.whenRequested(allOf(isPOST(), requestMatcher));
}
/**
* Helper method to create MatchableCall that will be matched only for PUT requests along with the specified {@code requestMatcher}
*
* @param requestMatcher matcher to match a PUT request
* @return {@code MatchableCall} that will match PUT requests along with {@code requestMatcher}
*/
public static MatchableCall whenPUT(Matcher<RecordedRequest> requestMatcher) {
return RESTMockServer.whenRequested(allOf(isPUT(), requestMatcher));
}
/**
* Helper method to create MatchableCall that will be matched only for PATCH requests along with the specified {@code requestMatcher}
*
* @param requestMatcher matcher to match a PATCH request
* @return {@code MatchableCall} that will match PATCH requests along with {@code requestMatcher}
*/
public static MatchableCall whenPATCH(Matcher<RecordedRequest> requestMatcher) { | // Path: core/src/main/java/io/appflate/restmock/logging/NOOpLogger.java
// public class NOOpLogger implements RESTMockLogger {
//
// @Override
// public void log(String message) {
// //intentionally empty
// }
//
// @Override
// public void error(String errorMessage) {
// //intentionally empty
// }
//
// @Override
// public void error(String errorMessage, Throwable exception) {
// //intentionally empty
// }
// }
//
// Path: core/src/main/java/io/appflate/restmock/logging/RESTMockLogger.java
// public interface RESTMockLogger {
//
// void log(String message);
//
// void error(String errorMessage);
//
// void error(String errorMessage, Throwable exception);
// }
//
// Path: core/src/main/java/io/appflate/restmock/utils/RequestMatchers.java
// public static RequestMatcher isDELETE() {
// return httpMethodIs("DELETE");
// }
//
// Path: core/src/main/java/io/appflate/restmock/utils/RequestMatchers.java
// public static RequestMatcher isGET() {
// return httpMethodIs("GET");
// }
//
// Path: core/src/main/java/io/appflate/restmock/utils/RequestMatchers.java
// public static RequestMatcher isHEAD() {
// return httpMethodIs("HEAD");
// }
//
// Path: core/src/main/java/io/appflate/restmock/utils/RequestMatchers.java
// public static RequestMatcher isPATCH() {
// return httpMethodIs("PATCH");
// }
//
// Path: core/src/main/java/io/appflate/restmock/utils/RequestMatchers.java
// public static RequestMatcher isPOST() {
// return httpMethodIs("POST");
// }
//
// Path: core/src/main/java/io/appflate/restmock/utils/RequestMatchers.java
// public static RequestMatcher isPUT() {
// return httpMethodIs("PUT");
// }
// Path: core/src/main/java/io/appflate/restmock/RESTMockServer.java
import static io.appflate.restmock.utils.RequestMatchers.isPUT;
import static org.hamcrest.core.AllOf.allOf;
import io.appflate.restmock.logging.NOOpLogger;
import io.appflate.restmock.logging.RESTMockLogger;
import java.io.IOException;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.X509TrustManager;
import okhttp3.mockwebserver.MockWebServer;
import okhttp3.mockwebserver.RecordedRequest;
import org.hamcrest.Matcher;
import static io.appflate.restmock.utils.RequestMatchers.isDELETE;
import static io.appflate.restmock.utils.RequestMatchers.isGET;
import static io.appflate.restmock.utils.RequestMatchers.isHEAD;
import static io.appflate.restmock.utils.RequestMatchers.isPATCH;
import static io.appflate.restmock.utils.RequestMatchers.isPOST;
return RESTMockServer.whenRequested(allOf(isGET(), requestMatcher));
}
/**
* Helper method to create MatchableCall that will be matched only for POST requests along with the specified {@code requestMatcher}
*
* @param requestMatcher matcher to match a POST request
* @return {@code MatchableCall} that will match POST requests along with {@code requestMatcher}
*/
public static MatchableCall whenPOST(Matcher<RecordedRequest> requestMatcher) {
return RESTMockServer.whenRequested(allOf(isPOST(), requestMatcher));
}
/**
* Helper method to create MatchableCall that will be matched only for PUT requests along with the specified {@code requestMatcher}
*
* @param requestMatcher matcher to match a PUT request
* @return {@code MatchableCall} that will match PUT requests along with {@code requestMatcher}
*/
public static MatchableCall whenPUT(Matcher<RecordedRequest> requestMatcher) {
return RESTMockServer.whenRequested(allOf(isPUT(), requestMatcher));
}
/**
* Helper method to create MatchableCall that will be matched only for PATCH requests along with the specified {@code requestMatcher}
*
* @param requestMatcher matcher to match a PATCH request
* @return {@code MatchableCall} that will match PATCH requests along with {@code requestMatcher}
*/
public static MatchableCall whenPATCH(Matcher<RecordedRequest> requestMatcher) { | return RESTMockServer.whenRequested(allOf(isPATCH(), requestMatcher)); |
andrzejchm/RESTMock | core/src/main/java/io/appflate/restmock/RESTMockServer.java | // Path: core/src/main/java/io/appflate/restmock/logging/NOOpLogger.java
// public class NOOpLogger implements RESTMockLogger {
//
// @Override
// public void log(String message) {
// //intentionally empty
// }
//
// @Override
// public void error(String errorMessage) {
// //intentionally empty
// }
//
// @Override
// public void error(String errorMessage, Throwable exception) {
// //intentionally empty
// }
// }
//
// Path: core/src/main/java/io/appflate/restmock/logging/RESTMockLogger.java
// public interface RESTMockLogger {
//
// void log(String message);
//
// void error(String errorMessage);
//
// void error(String errorMessage, Throwable exception);
// }
//
// Path: core/src/main/java/io/appflate/restmock/utils/RequestMatchers.java
// public static RequestMatcher isDELETE() {
// return httpMethodIs("DELETE");
// }
//
// Path: core/src/main/java/io/appflate/restmock/utils/RequestMatchers.java
// public static RequestMatcher isGET() {
// return httpMethodIs("GET");
// }
//
// Path: core/src/main/java/io/appflate/restmock/utils/RequestMatchers.java
// public static RequestMatcher isHEAD() {
// return httpMethodIs("HEAD");
// }
//
// Path: core/src/main/java/io/appflate/restmock/utils/RequestMatchers.java
// public static RequestMatcher isPATCH() {
// return httpMethodIs("PATCH");
// }
//
// Path: core/src/main/java/io/appflate/restmock/utils/RequestMatchers.java
// public static RequestMatcher isPOST() {
// return httpMethodIs("POST");
// }
//
// Path: core/src/main/java/io/appflate/restmock/utils/RequestMatchers.java
// public static RequestMatcher isPUT() {
// return httpMethodIs("PUT");
// }
| import static io.appflate.restmock.utils.RequestMatchers.isPUT;
import static org.hamcrest.core.AllOf.allOf;
import io.appflate.restmock.logging.NOOpLogger;
import io.appflate.restmock.logging.RESTMockLogger;
import java.io.IOException;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.X509TrustManager;
import okhttp3.mockwebserver.MockWebServer;
import okhttp3.mockwebserver.RecordedRequest;
import org.hamcrest.Matcher;
import static io.appflate.restmock.utils.RequestMatchers.isDELETE;
import static io.appflate.restmock.utils.RequestMatchers.isGET;
import static io.appflate.restmock.utils.RequestMatchers.isHEAD;
import static io.appflate.restmock.utils.RequestMatchers.isPATCH;
import static io.appflate.restmock.utils.RequestMatchers.isPOST; | return RESTMockServer.whenRequested(allOf(isPOST(), requestMatcher));
}
/**
* Helper method to create MatchableCall that will be matched only for PUT requests along with the specified {@code requestMatcher}
*
* @param requestMatcher matcher to match a PUT request
* @return {@code MatchableCall} that will match PUT requests along with {@code requestMatcher}
*/
public static MatchableCall whenPUT(Matcher<RecordedRequest> requestMatcher) {
return RESTMockServer.whenRequested(allOf(isPUT(), requestMatcher));
}
/**
* Helper method to create MatchableCall that will be matched only for PATCH requests along with the specified {@code requestMatcher}
*
* @param requestMatcher matcher to match a PATCH request
* @return {@code MatchableCall} that will match PATCH requests along with {@code requestMatcher}
*/
public static MatchableCall whenPATCH(Matcher<RecordedRequest> requestMatcher) {
return RESTMockServer.whenRequested(allOf(isPATCH(), requestMatcher));
}
/**
* Helper method to create MatchableCall that will be matched only for DELETE requests along with the specified {@code requestMatcher}
*
* @param requestMatcher matcher to match a DELETE request
* @return {@code MatchableCall} that will match DELETE requests along with {@code requestMatcher}
*/
public static MatchableCall whenDELETE(Matcher<RecordedRequest> requestMatcher) { | // Path: core/src/main/java/io/appflate/restmock/logging/NOOpLogger.java
// public class NOOpLogger implements RESTMockLogger {
//
// @Override
// public void log(String message) {
// //intentionally empty
// }
//
// @Override
// public void error(String errorMessage) {
// //intentionally empty
// }
//
// @Override
// public void error(String errorMessage, Throwable exception) {
// //intentionally empty
// }
// }
//
// Path: core/src/main/java/io/appflate/restmock/logging/RESTMockLogger.java
// public interface RESTMockLogger {
//
// void log(String message);
//
// void error(String errorMessage);
//
// void error(String errorMessage, Throwable exception);
// }
//
// Path: core/src/main/java/io/appflate/restmock/utils/RequestMatchers.java
// public static RequestMatcher isDELETE() {
// return httpMethodIs("DELETE");
// }
//
// Path: core/src/main/java/io/appflate/restmock/utils/RequestMatchers.java
// public static RequestMatcher isGET() {
// return httpMethodIs("GET");
// }
//
// Path: core/src/main/java/io/appflate/restmock/utils/RequestMatchers.java
// public static RequestMatcher isHEAD() {
// return httpMethodIs("HEAD");
// }
//
// Path: core/src/main/java/io/appflate/restmock/utils/RequestMatchers.java
// public static RequestMatcher isPATCH() {
// return httpMethodIs("PATCH");
// }
//
// Path: core/src/main/java/io/appflate/restmock/utils/RequestMatchers.java
// public static RequestMatcher isPOST() {
// return httpMethodIs("POST");
// }
//
// Path: core/src/main/java/io/appflate/restmock/utils/RequestMatchers.java
// public static RequestMatcher isPUT() {
// return httpMethodIs("PUT");
// }
// Path: core/src/main/java/io/appflate/restmock/RESTMockServer.java
import static io.appflate.restmock.utils.RequestMatchers.isPUT;
import static org.hamcrest.core.AllOf.allOf;
import io.appflate.restmock.logging.NOOpLogger;
import io.appflate.restmock.logging.RESTMockLogger;
import java.io.IOException;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.X509TrustManager;
import okhttp3.mockwebserver.MockWebServer;
import okhttp3.mockwebserver.RecordedRequest;
import org.hamcrest.Matcher;
import static io.appflate.restmock.utils.RequestMatchers.isDELETE;
import static io.appflate.restmock.utils.RequestMatchers.isGET;
import static io.appflate.restmock.utils.RequestMatchers.isHEAD;
import static io.appflate.restmock.utils.RequestMatchers.isPATCH;
import static io.appflate.restmock.utils.RequestMatchers.isPOST;
return RESTMockServer.whenRequested(allOf(isPOST(), requestMatcher));
}
/**
* Helper method to create MatchableCall that will be matched only for PUT requests along with the specified {@code requestMatcher}
*
* @param requestMatcher matcher to match a PUT request
* @return {@code MatchableCall} that will match PUT requests along with {@code requestMatcher}
*/
public static MatchableCall whenPUT(Matcher<RecordedRequest> requestMatcher) {
return RESTMockServer.whenRequested(allOf(isPUT(), requestMatcher));
}
/**
* Helper method to create MatchableCall that will be matched only for PATCH requests along with the specified {@code requestMatcher}
*
* @param requestMatcher matcher to match a PATCH request
* @return {@code MatchableCall} that will match PATCH requests along with {@code requestMatcher}
*/
public static MatchableCall whenPATCH(Matcher<RecordedRequest> requestMatcher) {
return RESTMockServer.whenRequested(allOf(isPATCH(), requestMatcher));
}
/**
* Helper method to create MatchableCall that will be matched only for DELETE requests along with the specified {@code requestMatcher}
*
* @param requestMatcher matcher to match a DELETE request
* @return {@code MatchableCall} that will match DELETE requests along with {@code requestMatcher}
*/
public static MatchableCall whenDELETE(Matcher<RecordedRequest> requestMatcher) { | return RESTMockServer.whenRequested(allOf(isDELETE(), requestMatcher)); |
andrzejchm/RESTMock | core/src/main/java/io/appflate/restmock/RESTMockServer.java | // Path: core/src/main/java/io/appflate/restmock/logging/NOOpLogger.java
// public class NOOpLogger implements RESTMockLogger {
//
// @Override
// public void log(String message) {
// //intentionally empty
// }
//
// @Override
// public void error(String errorMessage) {
// //intentionally empty
// }
//
// @Override
// public void error(String errorMessage, Throwable exception) {
// //intentionally empty
// }
// }
//
// Path: core/src/main/java/io/appflate/restmock/logging/RESTMockLogger.java
// public interface RESTMockLogger {
//
// void log(String message);
//
// void error(String errorMessage);
//
// void error(String errorMessage, Throwable exception);
// }
//
// Path: core/src/main/java/io/appflate/restmock/utils/RequestMatchers.java
// public static RequestMatcher isDELETE() {
// return httpMethodIs("DELETE");
// }
//
// Path: core/src/main/java/io/appflate/restmock/utils/RequestMatchers.java
// public static RequestMatcher isGET() {
// return httpMethodIs("GET");
// }
//
// Path: core/src/main/java/io/appflate/restmock/utils/RequestMatchers.java
// public static RequestMatcher isHEAD() {
// return httpMethodIs("HEAD");
// }
//
// Path: core/src/main/java/io/appflate/restmock/utils/RequestMatchers.java
// public static RequestMatcher isPATCH() {
// return httpMethodIs("PATCH");
// }
//
// Path: core/src/main/java/io/appflate/restmock/utils/RequestMatchers.java
// public static RequestMatcher isPOST() {
// return httpMethodIs("POST");
// }
//
// Path: core/src/main/java/io/appflate/restmock/utils/RequestMatchers.java
// public static RequestMatcher isPUT() {
// return httpMethodIs("PUT");
// }
| import static io.appflate.restmock.utils.RequestMatchers.isPUT;
import static org.hamcrest.core.AllOf.allOf;
import io.appflate.restmock.logging.NOOpLogger;
import io.appflate.restmock.logging.RESTMockLogger;
import java.io.IOException;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.X509TrustManager;
import okhttp3.mockwebserver.MockWebServer;
import okhttp3.mockwebserver.RecordedRequest;
import org.hamcrest.Matcher;
import static io.appflate.restmock.utils.RequestMatchers.isDELETE;
import static io.appflate.restmock.utils.RequestMatchers.isGET;
import static io.appflate.restmock.utils.RequestMatchers.isHEAD;
import static io.appflate.restmock.utils.RequestMatchers.isPATCH;
import static io.appflate.restmock.utils.RequestMatchers.isPOST; | * Helper method to create MatchableCall that will be matched only for PUT requests along with the specified {@code requestMatcher}
*
* @param requestMatcher matcher to match a PUT request
* @return {@code MatchableCall} that will match PUT requests along with {@code requestMatcher}
*/
public static MatchableCall whenPUT(Matcher<RecordedRequest> requestMatcher) {
return RESTMockServer.whenRequested(allOf(isPUT(), requestMatcher));
}
/**
* Helper method to create MatchableCall that will be matched only for PATCH requests along with the specified {@code requestMatcher}
*
* @param requestMatcher matcher to match a PATCH request
* @return {@code MatchableCall} that will match PATCH requests along with {@code requestMatcher}
*/
public static MatchableCall whenPATCH(Matcher<RecordedRequest> requestMatcher) {
return RESTMockServer.whenRequested(allOf(isPATCH(), requestMatcher));
}
/**
* Helper method to create MatchableCall that will be matched only for DELETE requests along with the specified {@code requestMatcher}
*
* @param requestMatcher matcher to match a DELETE request
* @return {@code MatchableCall} that will match DELETE requests along with {@code requestMatcher}
*/
public static MatchableCall whenDELETE(Matcher<RecordedRequest> requestMatcher) {
return RESTMockServer.whenRequested(allOf(isDELETE(), requestMatcher));
}
public static MatchableCall whenHEAD(Matcher<RecordedRequest> requestMatcher) { | // Path: core/src/main/java/io/appflate/restmock/logging/NOOpLogger.java
// public class NOOpLogger implements RESTMockLogger {
//
// @Override
// public void log(String message) {
// //intentionally empty
// }
//
// @Override
// public void error(String errorMessage) {
// //intentionally empty
// }
//
// @Override
// public void error(String errorMessage, Throwable exception) {
// //intentionally empty
// }
// }
//
// Path: core/src/main/java/io/appflate/restmock/logging/RESTMockLogger.java
// public interface RESTMockLogger {
//
// void log(String message);
//
// void error(String errorMessage);
//
// void error(String errorMessage, Throwable exception);
// }
//
// Path: core/src/main/java/io/appflate/restmock/utils/RequestMatchers.java
// public static RequestMatcher isDELETE() {
// return httpMethodIs("DELETE");
// }
//
// Path: core/src/main/java/io/appflate/restmock/utils/RequestMatchers.java
// public static RequestMatcher isGET() {
// return httpMethodIs("GET");
// }
//
// Path: core/src/main/java/io/appflate/restmock/utils/RequestMatchers.java
// public static RequestMatcher isHEAD() {
// return httpMethodIs("HEAD");
// }
//
// Path: core/src/main/java/io/appflate/restmock/utils/RequestMatchers.java
// public static RequestMatcher isPATCH() {
// return httpMethodIs("PATCH");
// }
//
// Path: core/src/main/java/io/appflate/restmock/utils/RequestMatchers.java
// public static RequestMatcher isPOST() {
// return httpMethodIs("POST");
// }
//
// Path: core/src/main/java/io/appflate/restmock/utils/RequestMatchers.java
// public static RequestMatcher isPUT() {
// return httpMethodIs("PUT");
// }
// Path: core/src/main/java/io/appflate/restmock/RESTMockServer.java
import static io.appflate.restmock.utils.RequestMatchers.isPUT;
import static org.hamcrest.core.AllOf.allOf;
import io.appflate.restmock.logging.NOOpLogger;
import io.appflate.restmock.logging.RESTMockLogger;
import java.io.IOException;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.X509TrustManager;
import okhttp3.mockwebserver.MockWebServer;
import okhttp3.mockwebserver.RecordedRequest;
import org.hamcrest.Matcher;
import static io.appflate.restmock.utils.RequestMatchers.isDELETE;
import static io.appflate.restmock.utils.RequestMatchers.isGET;
import static io.appflate.restmock.utils.RequestMatchers.isHEAD;
import static io.appflate.restmock.utils.RequestMatchers.isPATCH;
import static io.appflate.restmock.utils.RequestMatchers.isPOST;
* Helper method to create MatchableCall that will be matched only for PUT requests along with the specified {@code requestMatcher}
*
* @param requestMatcher matcher to match a PUT request
* @return {@code MatchableCall} that will match PUT requests along with {@code requestMatcher}
*/
public static MatchableCall whenPUT(Matcher<RecordedRequest> requestMatcher) {
return RESTMockServer.whenRequested(allOf(isPUT(), requestMatcher));
}
/**
* Helper method to create MatchableCall that will be matched only for PATCH requests along with the specified {@code requestMatcher}
*
* @param requestMatcher matcher to match a PATCH request
* @return {@code MatchableCall} that will match PATCH requests along with {@code requestMatcher}
*/
public static MatchableCall whenPATCH(Matcher<RecordedRequest> requestMatcher) {
return RESTMockServer.whenRequested(allOf(isPATCH(), requestMatcher));
}
/**
* Helper method to create MatchableCall that will be matched only for DELETE requests along with the specified {@code requestMatcher}
*
* @param requestMatcher matcher to match a DELETE request
* @return {@code MatchableCall} that will match DELETE requests along with {@code requestMatcher}
*/
public static MatchableCall whenDELETE(Matcher<RecordedRequest> requestMatcher) {
return RESTMockServer.whenRequested(allOf(isDELETE(), requestMatcher));
}
public static MatchableCall whenHEAD(Matcher<RecordedRequest> requestMatcher) { | return RESTMockServer.whenRequested(allOf(isHEAD(), requestMatcher)); |
andrzejchm/RESTMock | core/src/main/java/io/appflate/restmock/RESTMockServerStarter.java | // Path: core/src/main/java/io/appflate/restmock/logging/RESTMockLogger.java
// public interface RESTMockLogger {
//
// void log(String message);
//
// void error(String errorMessage);
//
// void error(String errorMessage, Throwable exception);
// }
| import io.appflate.restmock.logging.RESTMockLogger;
import java.io.IOException;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit; | /*
* Copyright (C) 2016 Appflate.io
*
* 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 io.appflate.restmock;
public class RESTMockServerStarter {
public static final int KEEP_ALIVE_TIME = 60;
public static void startSync(final RESTMockFileParser mocksFileParser) {
startSync(mocksFileParser, null,
new RESTMockOptions.Builder().build());
}
public static void startSync(final RESTMockFileParser mocksFileParser, RESTMockOptions options) {
startSync(mocksFileParser, null, options);
}
| // Path: core/src/main/java/io/appflate/restmock/logging/RESTMockLogger.java
// public interface RESTMockLogger {
//
// void log(String message);
//
// void error(String errorMessage);
//
// void error(String errorMessage, Throwable exception);
// }
// Path: core/src/main/java/io/appflate/restmock/RESTMockServerStarter.java
import io.appflate.restmock.logging.RESTMockLogger;
import java.io.IOException;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
/*
* Copyright (C) 2016 Appflate.io
*
* 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 io.appflate.restmock;
public class RESTMockServerStarter {
public static final int KEEP_ALIVE_TIME = 60;
public static void startSync(final RESTMockFileParser mocksFileParser) {
startSync(mocksFileParser, null,
new RESTMockOptions.Builder().build());
}
public static void startSync(final RESTMockFileParser mocksFileParser, RESTMockOptions options) {
startSync(mocksFileParser, null, options);
}
| public static void startSync(final RESTMockFileParser mocksFileParser, final RESTMockLogger logger) { |
andrzejchm/RESTMock | androidsample/src/main/java/io/appflate/restmock/androidsample/di/AppModule.java | // Path: androidsample/src/main/java/io/appflate/restmock/androidsample/domain/GithubApi.java
// public interface GithubApi {
//
// @GET("users/{username}")
// Call<User> getUserProfile(@Path("username") String username);
//
// @GET("users/{username}/repos")
// Call<List<Repository>> getUserRepos(@Path("username") String username);
//
// }
| import dagger.Module;
import dagger.Provides;
import io.appflate.restmock.androidsample.domain.GithubApi;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.X509TrustManager;
import okhttp3.OkHttpClient;
import okhttp3.logging.HttpLoggingInterceptor;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory; | /*
* Copyright (C) 2016 Appflate.io
*
* 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 io.appflate.restmock.androidsample.di;
/**
* Created by andrzejchm on 23/04/16.
*/
@Module
public class AppModule {
private String baseUrl;
private SSLSocketFactory socketFactory;
private X509TrustManager trustManager;
public AppModule(String baseUrl, SSLSocketFactory socketFactory, X509TrustManager trustManager) {
this.baseUrl = baseUrl;
this.socketFactory = socketFactory;
this.trustManager = trustManager;
}
@Provides | // Path: androidsample/src/main/java/io/appflate/restmock/androidsample/domain/GithubApi.java
// public interface GithubApi {
//
// @GET("users/{username}")
// Call<User> getUserProfile(@Path("username") String username);
//
// @GET("users/{username}/repos")
// Call<List<Repository>> getUserRepos(@Path("username") String username);
//
// }
// Path: androidsample/src/main/java/io/appflate/restmock/androidsample/di/AppModule.java
import dagger.Module;
import dagger.Provides;
import io.appflate.restmock.androidsample.domain.GithubApi;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.X509TrustManager;
import okhttp3.OkHttpClient;
import okhttp3.logging.HttpLoggingInterceptor;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;
/*
* Copyright (C) 2016 Appflate.io
*
* 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 io.appflate.restmock.androidsample.di;
/**
* Created by andrzejchm on 23/04/16.
*/
@Module
public class AppModule {
private String baseUrl;
private SSLSocketFactory socketFactory;
private X509TrustManager trustManager;
public AppModule(String baseUrl, SSLSocketFactory socketFactory, X509TrustManager trustManager) {
this.baseUrl = baseUrl;
this.socketFactory = socketFactory;
this.trustManager = trustManager;
}
@Provides | GithubApi provideRestService() { |
andrzejchm/RESTMock | androidsample/src/main/java/io/appflate/restmock/androidsample/di/AppComponent.java | // Path: androidsample/src/main/java/io/appflate/restmock/androidsample/view/activities/MainActivity.java
// public class MainActivity extends AppCompatActivity {
//
// private static final int POSITION_CONTENT_VIEW = 0;
// private static final int POSITION_PROGRESS_VIEW = 1;
// @Inject GithubApi githubApi;
//
// @BindView(R.id.fullNameText) TextView fullNameTextView;
// @BindView(R.id.showReposButton) Button showReposButton;
// @BindView(R.id.usernameEditText) EditText usernameEditText;
// @BindView(R.id.resultAnimator) ViewAnimator resultAnimator;
// private String currentUsername;
//
// @Override
// protected void onCreate(Bundle savedInstanceState) {
// super.onCreate(savedInstanceState);
// setContentView(R.layout.activity_main);
// ButterKnife.bind(this);
// SampleApplication.getComponent().inject(this);
// }
//
// @OnClick(R.id.submitButton)
// public void onSubmitClicked() {
// Utils.hideKeyboard(this);
// currentUsername = usernameEditText.getText().toString();
// resultAnimator.setDisplayedChild(POSITION_PROGRESS_VIEW);
// githubApi.getUserProfile(currentUsername).enqueue(new Callback<User>() {
// @Override
// public void onResponse(Call<User> call,
// Response<User> response) {
// if (response.isSuccessful()) {
// User body = response.body();
// String name = body.name == null ? body.login : body.name;
// fullNameTextView.setText(String.format(Locale.US,
// "Hello %s!",
// name));
// showReposButton.setVisibility(View.VISIBLE);
// resultAnimator.setDisplayedChild(POSITION_CONTENT_VIEW);
// } else {
// onRequestError();
// }
// }
//
// @Override
// public void onFailure(Call<User> call,
// Throwable t) {
// onRequestError();
// }
// });
// }
//
// @OnClick(R.id.showReposButton)
// public void onShowReposClicked() {
// startActivity(ReposActivity.intent(this, currentUsername));
//
// }
//
// private void onRequestError() {
// fullNameTextView.setText(R.string.something_went_wrong);
// showReposButton.setVisibility(View.GONE);
// resultAnimator.setDisplayedChild(POSITION_CONTENT_VIEW);
// }
//
// public GithubApi getApi() {
// return githubApi;
// }
// }
//
// Path: androidsample/src/main/java/io/appflate/restmock/androidsample/view/activities/ReposActivity.java
// public class ReposActivity extends AppCompatActivity implements Callback<List<Repository>> {
//
// private static final String PARAM_USERNAME = "username";
// private String username;
//
// @Inject GithubApi githubApi;
//
// @BindView(R.id.reposRecyclerView) RecyclerView reposRecyclerView;
// @BindView(R.id.reposAnimator) ViewAnimator reposAnimator;
//
// @Override
// protected void onCreate(Bundle savedInstanceState) {
// super.onCreate(savedInstanceState);
// setContentView(R.layout.activity_repos);
// ButterKnife.bind(this);
// SampleApplication.getComponent().inject(this);
// if (getIntent() != null) {
// username = getIntent().getStringExtra(PARAM_USERNAME);
// }
// setTitle(username);
// githubApi.getUserRepos(username).enqueue(this);
// }
//
// public static Intent intent(Activity activity, String username) {
// Intent intent = new Intent(activity, ReposActivity.class);
// intent.putExtra(PARAM_USERNAME, username);
// return intent;
// }
//
// @Override
// public void onResponse(Call<List<Repository>> call, Response<List<Repository>> response) {
// if (response.isSuccessful()) {
// reposRecyclerView.setLayoutManager(new LinearLayoutManager(this, RecyclerView.VERTICAL, false));
// reposRecyclerView.setAdapter(new ReposRecyclerAdapter(response.body()));
// reposAnimator.setDisplayedChild(1);
// } else {
// onResponseFailure();
// }
// }
//
// @Override
// public void onFailure(Call<List<Repository>> call, Throwable t) {
// onResponseFailure();
// }
//
// private void onResponseFailure() {
// Toast.makeText(this, "Something went wrong", Toast.LENGTH_LONG).show();
// }
// }
//
// Path: androidsample/src/main/java/io/appflate/restmock/androidsample/domain/GithubApi.java
// public interface GithubApi {
//
// @GET("users/{username}")
// Call<User> getUserProfile(@Path("username") String username);
//
// @GET("users/{username}/repos")
// Call<List<Repository>> getUserRepos(@Path("username") String username);
//
// }
| import javax.inject.Singleton;
import dagger.Component;
import io.appflate.restmock.androidsample.view.activities.MainActivity;
import io.appflate.restmock.androidsample.view.activities.ReposActivity;
import io.appflate.restmock.androidsample.domain.GithubApi; | /*
* Copyright (C) 2016 Appflate.io
*
* 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 io.appflate.restmock.androidsample.di;
/**
* Created by andrzejchm on 23/04/16.
*/
@Singleton
@Component(modules = { AppModule.class})
public interface AppComponent { | // Path: androidsample/src/main/java/io/appflate/restmock/androidsample/view/activities/MainActivity.java
// public class MainActivity extends AppCompatActivity {
//
// private static final int POSITION_CONTENT_VIEW = 0;
// private static final int POSITION_PROGRESS_VIEW = 1;
// @Inject GithubApi githubApi;
//
// @BindView(R.id.fullNameText) TextView fullNameTextView;
// @BindView(R.id.showReposButton) Button showReposButton;
// @BindView(R.id.usernameEditText) EditText usernameEditText;
// @BindView(R.id.resultAnimator) ViewAnimator resultAnimator;
// private String currentUsername;
//
// @Override
// protected void onCreate(Bundle savedInstanceState) {
// super.onCreate(savedInstanceState);
// setContentView(R.layout.activity_main);
// ButterKnife.bind(this);
// SampleApplication.getComponent().inject(this);
// }
//
// @OnClick(R.id.submitButton)
// public void onSubmitClicked() {
// Utils.hideKeyboard(this);
// currentUsername = usernameEditText.getText().toString();
// resultAnimator.setDisplayedChild(POSITION_PROGRESS_VIEW);
// githubApi.getUserProfile(currentUsername).enqueue(new Callback<User>() {
// @Override
// public void onResponse(Call<User> call,
// Response<User> response) {
// if (response.isSuccessful()) {
// User body = response.body();
// String name = body.name == null ? body.login : body.name;
// fullNameTextView.setText(String.format(Locale.US,
// "Hello %s!",
// name));
// showReposButton.setVisibility(View.VISIBLE);
// resultAnimator.setDisplayedChild(POSITION_CONTENT_VIEW);
// } else {
// onRequestError();
// }
// }
//
// @Override
// public void onFailure(Call<User> call,
// Throwable t) {
// onRequestError();
// }
// });
// }
//
// @OnClick(R.id.showReposButton)
// public void onShowReposClicked() {
// startActivity(ReposActivity.intent(this, currentUsername));
//
// }
//
// private void onRequestError() {
// fullNameTextView.setText(R.string.something_went_wrong);
// showReposButton.setVisibility(View.GONE);
// resultAnimator.setDisplayedChild(POSITION_CONTENT_VIEW);
// }
//
// public GithubApi getApi() {
// return githubApi;
// }
// }
//
// Path: androidsample/src/main/java/io/appflate/restmock/androidsample/view/activities/ReposActivity.java
// public class ReposActivity extends AppCompatActivity implements Callback<List<Repository>> {
//
// private static final String PARAM_USERNAME = "username";
// private String username;
//
// @Inject GithubApi githubApi;
//
// @BindView(R.id.reposRecyclerView) RecyclerView reposRecyclerView;
// @BindView(R.id.reposAnimator) ViewAnimator reposAnimator;
//
// @Override
// protected void onCreate(Bundle savedInstanceState) {
// super.onCreate(savedInstanceState);
// setContentView(R.layout.activity_repos);
// ButterKnife.bind(this);
// SampleApplication.getComponent().inject(this);
// if (getIntent() != null) {
// username = getIntent().getStringExtra(PARAM_USERNAME);
// }
// setTitle(username);
// githubApi.getUserRepos(username).enqueue(this);
// }
//
// public static Intent intent(Activity activity, String username) {
// Intent intent = new Intent(activity, ReposActivity.class);
// intent.putExtra(PARAM_USERNAME, username);
// return intent;
// }
//
// @Override
// public void onResponse(Call<List<Repository>> call, Response<List<Repository>> response) {
// if (response.isSuccessful()) {
// reposRecyclerView.setLayoutManager(new LinearLayoutManager(this, RecyclerView.VERTICAL, false));
// reposRecyclerView.setAdapter(new ReposRecyclerAdapter(response.body()));
// reposAnimator.setDisplayedChild(1);
// } else {
// onResponseFailure();
// }
// }
//
// @Override
// public void onFailure(Call<List<Repository>> call, Throwable t) {
// onResponseFailure();
// }
//
// private void onResponseFailure() {
// Toast.makeText(this, "Something went wrong", Toast.LENGTH_LONG).show();
// }
// }
//
// Path: androidsample/src/main/java/io/appflate/restmock/androidsample/domain/GithubApi.java
// public interface GithubApi {
//
// @GET("users/{username}")
// Call<User> getUserProfile(@Path("username") String username);
//
// @GET("users/{username}/repos")
// Call<List<Repository>> getUserRepos(@Path("username") String username);
//
// }
// Path: androidsample/src/main/java/io/appflate/restmock/androidsample/di/AppComponent.java
import javax.inject.Singleton;
import dagger.Component;
import io.appflate.restmock.androidsample.view.activities.MainActivity;
import io.appflate.restmock.androidsample.view.activities.ReposActivity;
import io.appflate.restmock.androidsample.domain.GithubApi;
/*
* Copyright (C) 2016 Appflate.io
*
* 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 io.appflate.restmock.androidsample.di;
/**
* Created by andrzejchm on 23/04/16.
*/
@Singleton
@Component(modules = { AppModule.class})
public interface AppComponent { | GithubApi getRestService(); |
andrzejchm/RESTMock | androidsample/src/main/java/io/appflate/restmock/androidsample/di/AppComponent.java | // Path: androidsample/src/main/java/io/appflate/restmock/androidsample/view/activities/MainActivity.java
// public class MainActivity extends AppCompatActivity {
//
// private static final int POSITION_CONTENT_VIEW = 0;
// private static final int POSITION_PROGRESS_VIEW = 1;
// @Inject GithubApi githubApi;
//
// @BindView(R.id.fullNameText) TextView fullNameTextView;
// @BindView(R.id.showReposButton) Button showReposButton;
// @BindView(R.id.usernameEditText) EditText usernameEditText;
// @BindView(R.id.resultAnimator) ViewAnimator resultAnimator;
// private String currentUsername;
//
// @Override
// protected void onCreate(Bundle savedInstanceState) {
// super.onCreate(savedInstanceState);
// setContentView(R.layout.activity_main);
// ButterKnife.bind(this);
// SampleApplication.getComponent().inject(this);
// }
//
// @OnClick(R.id.submitButton)
// public void onSubmitClicked() {
// Utils.hideKeyboard(this);
// currentUsername = usernameEditText.getText().toString();
// resultAnimator.setDisplayedChild(POSITION_PROGRESS_VIEW);
// githubApi.getUserProfile(currentUsername).enqueue(new Callback<User>() {
// @Override
// public void onResponse(Call<User> call,
// Response<User> response) {
// if (response.isSuccessful()) {
// User body = response.body();
// String name = body.name == null ? body.login : body.name;
// fullNameTextView.setText(String.format(Locale.US,
// "Hello %s!",
// name));
// showReposButton.setVisibility(View.VISIBLE);
// resultAnimator.setDisplayedChild(POSITION_CONTENT_VIEW);
// } else {
// onRequestError();
// }
// }
//
// @Override
// public void onFailure(Call<User> call,
// Throwable t) {
// onRequestError();
// }
// });
// }
//
// @OnClick(R.id.showReposButton)
// public void onShowReposClicked() {
// startActivity(ReposActivity.intent(this, currentUsername));
//
// }
//
// private void onRequestError() {
// fullNameTextView.setText(R.string.something_went_wrong);
// showReposButton.setVisibility(View.GONE);
// resultAnimator.setDisplayedChild(POSITION_CONTENT_VIEW);
// }
//
// public GithubApi getApi() {
// return githubApi;
// }
// }
//
// Path: androidsample/src/main/java/io/appflate/restmock/androidsample/view/activities/ReposActivity.java
// public class ReposActivity extends AppCompatActivity implements Callback<List<Repository>> {
//
// private static final String PARAM_USERNAME = "username";
// private String username;
//
// @Inject GithubApi githubApi;
//
// @BindView(R.id.reposRecyclerView) RecyclerView reposRecyclerView;
// @BindView(R.id.reposAnimator) ViewAnimator reposAnimator;
//
// @Override
// protected void onCreate(Bundle savedInstanceState) {
// super.onCreate(savedInstanceState);
// setContentView(R.layout.activity_repos);
// ButterKnife.bind(this);
// SampleApplication.getComponent().inject(this);
// if (getIntent() != null) {
// username = getIntent().getStringExtra(PARAM_USERNAME);
// }
// setTitle(username);
// githubApi.getUserRepos(username).enqueue(this);
// }
//
// public static Intent intent(Activity activity, String username) {
// Intent intent = new Intent(activity, ReposActivity.class);
// intent.putExtra(PARAM_USERNAME, username);
// return intent;
// }
//
// @Override
// public void onResponse(Call<List<Repository>> call, Response<List<Repository>> response) {
// if (response.isSuccessful()) {
// reposRecyclerView.setLayoutManager(new LinearLayoutManager(this, RecyclerView.VERTICAL, false));
// reposRecyclerView.setAdapter(new ReposRecyclerAdapter(response.body()));
// reposAnimator.setDisplayedChild(1);
// } else {
// onResponseFailure();
// }
// }
//
// @Override
// public void onFailure(Call<List<Repository>> call, Throwable t) {
// onResponseFailure();
// }
//
// private void onResponseFailure() {
// Toast.makeText(this, "Something went wrong", Toast.LENGTH_LONG).show();
// }
// }
//
// Path: androidsample/src/main/java/io/appflate/restmock/androidsample/domain/GithubApi.java
// public interface GithubApi {
//
// @GET("users/{username}")
// Call<User> getUserProfile(@Path("username") String username);
//
// @GET("users/{username}/repos")
// Call<List<Repository>> getUserRepos(@Path("username") String username);
//
// }
| import javax.inject.Singleton;
import dagger.Component;
import io.appflate.restmock.androidsample.view.activities.MainActivity;
import io.appflate.restmock.androidsample.view.activities.ReposActivity;
import io.appflate.restmock.androidsample.domain.GithubApi; | /*
* Copyright (C) 2016 Appflate.io
*
* 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 io.appflate.restmock.androidsample.di;
/**
* Created by andrzejchm on 23/04/16.
*/
@Singleton
@Component(modules = { AppModule.class})
public interface AppComponent {
GithubApi getRestService();
| // Path: androidsample/src/main/java/io/appflate/restmock/androidsample/view/activities/MainActivity.java
// public class MainActivity extends AppCompatActivity {
//
// private static final int POSITION_CONTENT_VIEW = 0;
// private static final int POSITION_PROGRESS_VIEW = 1;
// @Inject GithubApi githubApi;
//
// @BindView(R.id.fullNameText) TextView fullNameTextView;
// @BindView(R.id.showReposButton) Button showReposButton;
// @BindView(R.id.usernameEditText) EditText usernameEditText;
// @BindView(R.id.resultAnimator) ViewAnimator resultAnimator;
// private String currentUsername;
//
// @Override
// protected void onCreate(Bundle savedInstanceState) {
// super.onCreate(savedInstanceState);
// setContentView(R.layout.activity_main);
// ButterKnife.bind(this);
// SampleApplication.getComponent().inject(this);
// }
//
// @OnClick(R.id.submitButton)
// public void onSubmitClicked() {
// Utils.hideKeyboard(this);
// currentUsername = usernameEditText.getText().toString();
// resultAnimator.setDisplayedChild(POSITION_PROGRESS_VIEW);
// githubApi.getUserProfile(currentUsername).enqueue(new Callback<User>() {
// @Override
// public void onResponse(Call<User> call,
// Response<User> response) {
// if (response.isSuccessful()) {
// User body = response.body();
// String name = body.name == null ? body.login : body.name;
// fullNameTextView.setText(String.format(Locale.US,
// "Hello %s!",
// name));
// showReposButton.setVisibility(View.VISIBLE);
// resultAnimator.setDisplayedChild(POSITION_CONTENT_VIEW);
// } else {
// onRequestError();
// }
// }
//
// @Override
// public void onFailure(Call<User> call,
// Throwable t) {
// onRequestError();
// }
// });
// }
//
// @OnClick(R.id.showReposButton)
// public void onShowReposClicked() {
// startActivity(ReposActivity.intent(this, currentUsername));
//
// }
//
// private void onRequestError() {
// fullNameTextView.setText(R.string.something_went_wrong);
// showReposButton.setVisibility(View.GONE);
// resultAnimator.setDisplayedChild(POSITION_CONTENT_VIEW);
// }
//
// public GithubApi getApi() {
// return githubApi;
// }
// }
//
// Path: androidsample/src/main/java/io/appflate/restmock/androidsample/view/activities/ReposActivity.java
// public class ReposActivity extends AppCompatActivity implements Callback<List<Repository>> {
//
// private static final String PARAM_USERNAME = "username";
// private String username;
//
// @Inject GithubApi githubApi;
//
// @BindView(R.id.reposRecyclerView) RecyclerView reposRecyclerView;
// @BindView(R.id.reposAnimator) ViewAnimator reposAnimator;
//
// @Override
// protected void onCreate(Bundle savedInstanceState) {
// super.onCreate(savedInstanceState);
// setContentView(R.layout.activity_repos);
// ButterKnife.bind(this);
// SampleApplication.getComponent().inject(this);
// if (getIntent() != null) {
// username = getIntent().getStringExtra(PARAM_USERNAME);
// }
// setTitle(username);
// githubApi.getUserRepos(username).enqueue(this);
// }
//
// public static Intent intent(Activity activity, String username) {
// Intent intent = new Intent(activity, ReposActivity.class);
// intent.putExtra(PARAM_USERNAME, username);
// return intent;
// }
//
// @Override
// public void onResponse(Call<List<Repository>> call, Response<List<Repository>> response) {
// if (response.isSuccessful()) {
// reposRecyclerView.setLayoutManager(new LinearLayoutManager(this, RecyclerView.VERTICAL, false));
// reposRecyclerView.setAdapter(new ReposRecyclerAdapter(response.body()));
// reposAnimator.setDisplayedChild(1);
// } else {
// onResponseFailure();
// }
// }
//
// @Override
// public void onFailure(Call<List<Repository>> call, Throwable t) {
// onResponseFailure();
// }
//
// private void onResponseFailure() {
// Toast.makeText(this, "Something went wrong", Toast.LENGTH_LONG).show();
// }
// }
//
// Path: androidsample/src/main/java/io/appflate/restmock/androidsample/domain/GithubApi.java
// public interface GithubApi {
//
// @GET("users/{username}")
// Call<User> getUserProfile(@Path("username") String username);
//
// @GET("users/{username}/repos")
// Call<List<Repository>> getUserRepos(@Path("username") String username);
//
// }
// Path: androidsample/src/main/java/io/appflate/restmock/androidsample/di/AppComponent.java
import javax.inject.Singleton;
import dagger.Component;
import io.appflate.restmock.androidsample.view.activities.MainActivity;
import io.appflate.restmock.androidsample.view.activities.ReposActivity;
import io.appflate.restmock.androidsample.domain.GithubApi;
/*
* Copyright (C) 2016 Appflate.io
*
* 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 io.appflate.restmock.androidsample.di;
/**
* Created by andrzejchm on 23/04/16.
*/
@Singleton
@Component(modules = { AppModule.class})
public interface AppComponent {
GithubApi getRestService();
| void inject(MainActivity mainActivity); |
andrzejchm/RESTMock | androidsample/src/main/java/io/appflate/restmock/androidsample/di/AppComponent.java | // Path: androidsample/src/main/java/io/appflate/restmock/androidsample/view/activities/MainActivity.java
// public class MainActivity extends AppCompatActivity {
//
// private static final int POSITION_CONTENT_VIEW = 0;
// private static final int POSITION_PROGRESS_VIEW = 1;
// @Inject GithubApi githubApi;
//
// @BindView(R.id.fullNameText) TextView fullNameTextView;
// @BindView(R.id.showReposButton) Button showReposButton;
// @BindView(R.id.usernameEditText) EditText usernameEditText;
// @BindView(R.id.resultAnimator) ViewAnimator resultAnimator;
// private String currentUsername;
//
// @Override
// protected void onCreate(Bundle savedInstanceState) {
// super.onCreate(savedInstanceState);
// setContentView(R.layout.activity_main);
// ButterKnife.bind(this);
// SampleApplication.getComponent().inject(this);
// }
//
// @OnClick(R.id.submitButton)
// public void onSubmitClicked() {
// Utils.hideKeyboard(this);
// currentUsername = usernameEditText.getText().toString();
// resultAnimator.setDisplayedChild(POSITION_PROGRESS_VIEW);
// githubApi.getUserProfile(currentUsername).enqueue(new Callback<User>() {
// @Override
// public void onResponse(Call<User> call,
// Response<User> response) {
// if (response.isSuccessful()) {
// User body = response.body();
// String name = body.name == null ? body.login : body.name;
// fullNameTextView.setText(String.format(Locale.US,
// "Hello %s!",
// name));
// showReposButton.setVisibility(View.VISIBLE);
// resultAnimator.setDisplayedChild(POSITION_CONTENT_VIEW);
// } else {
// onRequestError();
// }
// }
//
// @Override
// public void onFailure(Call<User> call,
// Throwable t) {
// onRequestError();
// }
// });
// }
//
// @OnClick(R.id.showReposButton)
// public void onShowReposClicked() {
// startActivity(ReposActivity.intent(this, currentUsername));
//
// }
//
// private void onRequestError() {
// fullNameTextView.setText(R.string.something_went_wrong);
// showReposButton.setVisibility(View.GONE);
// resultAnimator.setDisplayedChild(POSITION_CONTENT_VIEW);
// }
//
// public GithubApi getApi() {
// return githubApi;
// }
// }
//
// Path: androidsample/src/main/java/io/appflate/restmock/androidsample/view/activities/ReposActivity.java
// public class ReposActivity extends AppCompatActivity implements Callback<List<Repository>> {
//
// private static final String PARAM_USERNAME = "username";
// private String username;
//
// @Inject GithubApi githubApi;
//
// @BindView(R.id.reposRecyclerView) RecyclerView reposRecyclerView;
// @BindView(R.id.reposAnimator) ViewAnimator reposAnimator;
//
// @Override
// protected void onCreate(Bundle savedInstanceState) {
// super.onCreate(savedInstanceState);
// setContentView(R.layout.activity_repos);
// ButterKnife.bind(this);
// SampleApplication.getComponent().inject(this);
// if (getIntent() != null) {
// username = getIntent().getStringExtra(PARAM_USERNAME);
// }
// setTitle(username);
// githubApi.getUserRepos(username).enqueue(this);
// }
//
// public static Intent intent(Activity activity, String username) {
// Intent intent = new Intent(activity, ReposActivity.class);
// intent.putExtra(PARAM_USERNAME, username);
// return intent;
// }
//
// @Override
// public void onResponse(Call<List<Repository>> call, Response<List<Repository>> response) {
// if (response.isSuccessful()) {
// reposRecyclerView.setLayoutManager(new LinearLayoutManager(this, RecyclerView.VERTICAL, false));
// reposRecyclerView.setAdapter(new ReposRecyclerAdapter(response.body()));
// reposAnimator.setDisplayedChild(1);
// } else {
// onResponseFailure();
// }
// }
//
// @Override
// public void onFailure(Call<List<Repository>> call, Throwable t) {
// onResponseFailure();
// }
//
// private void onResponseFailure() {
// Toast.makeText(this, "Something went wrong", Toast.LENGTH_LONG).show();
// }
// }
//
// Path: androidsample/src/main/java/io/appflate/restmock/androidsample/domain/GithubApi.java
// public interface GithubApi {
//
// @GET("users/{username}")
// Call<User> getUserProfile(@Path("username") String username);
//
// @GET("users/{username}/repos")
// Call<List<Repository>> getUserRepos(@Path("username") String username);
//
// }
| import javax.inject.Singleton;
import dagger.Component;
import io.appflate.restmock.androidsample.view.activities.MainActivity;
import io.appflate.restmock.androidsample.view.activities.ReposActivity;
import io.appflate.restmock.androidsample.domain.GithubApi; | /*
* Copyright (C) 2016 Appflate.io
*
* 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 io.appflate.restmock.androidsample.di;
/**
* Created by andrzejchm on 23/04/16.
*/
@Singleton
@Component(modules = { AppModule.class})
public interface AppComponent {
GithubApi getRestService();
void inject(MainActivity mainActivity); | // Path: androidsample/src/main/java/io/appflate/restmock/androidsample/view/activities/MainActivity.java
// public class MainActivity extends AppCompatActivity {
//
// private static final int POSITION_CONTENT_VIEW = 0;
// private static final int POSITION_PROGRESS_VIEW = 1;
// @Inject GithubApi githubApi;
//
// @BindView(R.id.fullNameText) TextView fullNameTextView;
// @BindView(R.id.showReposButton) Button showReposButton;
// @BindView(R.id.usernameEditText) EditText usernameEditText;
// @BindView(R.id.resultAnimator) ViewAnimator resultAnimator;
// private String currentUsername;
//
// @Override
// protected void onCreate(Bundle savedInstanceState) {
// super.onCreate(savedInstanceState);
// setContentView(R.layout.activity_main);
// ButterKnife.bind(this);
// SampleApplication.getComponent().inject(this);
// }
//
// @OnClick(R.id.submitButton)
// public void onSubmitClicked() {
// Utils.hideKeyboard(this);
// currentUsername = usernameEditText.getText().toString();
// resultAnimator.setDisplayedChild(POSITION_PROGRESS_VIEW);
// githubApi.getUserProfile(currentUsername).enqueue(new Callback<User>() {
// @Override
// public void onResponse(Call<User> call,
// Response<User> response) {
// if (response.isSuccessful()) {
// User body = response.body();
// String name = body.name == null ? body.login : body.name;
// fullNameTextView.setText(String.format(Locale.US,
// "Hello %s!",
// name));
// showReposButton.setVisibility(View.VISIBLE);
// resultAnimator.setDisplayedChild(POSITION_CONTENT_VIEW);
// } else {
// onRequestError();
// }
// }
//
// @Override
// public void onFailure(Call<User> call,
// Throwable t) {
// onRequestError();
// }
// });
// }
//
// @OnClick(R.id.showReposButton)
// public void onShowReposClicked() {
// startActivity(ReposActivity.intent(this, currentUsername));
//
// }
//
// private void onRequestError() {
// fullNameTextView.setText(R.string.something_went_wrong);
// showReposButton.setVisibility(View.GONE);
// resultAnimator.setDisplayedChild(POSITION_CONTENT_VIEW);
// }
//
// public GithubApi getApi() {
// return githubApi;
// }
// }
//
// Path: androidsample/src/main/java/io/appflate/restmock/androidsample/view/activities/ReposActivity.java
// public class ReposActivity extends AppCompatActivity implements Callback<List<Repository>> {
//
// private static final String PARAM_USERNAME = "username";
// private String username;
//
// @Inject GithubApi githubApi;
//
// @BindView(R.id.reposRecyclerView) RecyclerView reposRecyclerView;
// @BindView(R.id.reposAnimator) ViewAnimator reposAnimator;
//
// @Override
// protected void onCreate(Bundle savedInstanceState) {
// super.onCreate(savedInstanceState);
// setContentView(R.layout.activity_repos);
// ButterKnife.bind(this);
// SampleApplication.getComponent().inject(this);
// if (getIntent() != null) {
// username = getIntent().getStringExtra(PARAM_USERNAME);
// }
// setTitle(username);
// githubApi.getUserRepos(username).enqueue(this);
// }
//
// public static Intent intent(Activity activity, String username) {
// Intent intent = new Intent(activity, ReposActivity.class);
// intent.putExtra(PARAM_USERNAME, username);
// return intent;
// }
//
// @Override
// public void onResponse(Call<List<Repository>> call, Response<List<Repository>> response) {
// if (response.isSuccessful()) {
// reposRecyclerView.setLayoutManager(new LinearLayoutManager(this, RecyclerView.VERTICAL, false));
// reposRecyclerView.setAdapter(new ReposRecyclerAdapter(response.body()));
// reposAnimator.setDisplayedChild(1);
// } else {
// onResponseFailure();
// }
// }
//
// @Override
// public void onFailure(Call<List<Repository>> call, Throwable t) {
// onResponseFailure();
// }
//
// private void onResponseFailure() {
// Toast.makeText(this, "Something went wrong", Toast.LENGTH_LONG).show();
// }
// }
//
// Path: androidsample/src/main/java/io/appflate/restmock/androidsample/domain/GithubApi.java
// public interface GithubApi {
//
// @GET("users/{username}")
// Call<User> getUserProfile(@Path("username") String username);
//
// @GET("users/{username}/repos")
// Call<List<Repository>> getUserRepos(@Path("username") String username);
//
// }
// Path: androidsample/src/main/java/io/appflate/restmock/androidsample/di/AppComponent.java
import javax.inject.Singleton;
import dagger.Component;
import io.appflate.restmock.androidsample.view.activities.MainActivity;
import io.appflate.restmock.androidsample.view.activities.ReposActivity;
import io.appflate.restmock.androidsample.domain.GithubApi;
/*
* Copyright (C) 2016 Appflate.io
*
* 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 io.appflate.restmock.androidsample.di;
/**
* Created by andrzejchm on 23/04/16.
*/
@Singleton
@Component(modules = { AppModule.class})
public interface AppComponent {
GithubApi getRestService();
void inject(MainActivity mainActivity); | void inject(ReposActivity reposActivity); |
tmurakami/dexopener | examples/multiproject/test/src/main/java/com/example/dexopener/multiproject/test/BaseMyAndroidJUnitRunner.java | // Path: dexopener/src/main/java/com/github/tmurakami/dexopener/DexOpener.java
// public final class DexOpener {
//
// private static final String[] REFUSED_PACKAGES = {
// MY_PACKAGE_PREFIX,
// // Android
// "android.",
// "androidx.",
// "com.android.",
// "com.google.android.",
// "com.sun.",
// "dalvik.",
// "java.",
// "javax.",
// "libcore.",
// "org.apache.commons.logging.",
// "org.apache.harmony.",
// "org.apache.http.",
// "org.ccil.cowan.tagsoup.",
// "org.json.",
// "org.kxml2.io.",
// "org.w3c.dom.",
// "org.xml.sax.",
// "org.xmlpull.v1.",
// "sun.",
// // JUnit 4
// "junit.",
// "org.hamcrest.",
// "org.junit.",
// };
//
// private static final Executor EXECUTOR;
//
// static {
// final AtomicInteger count = new AtomicInteger();
// int availableProcessors = Runtime.getRuntime().availableProcessors();
// int nThreads = Math.max(1, Math.min(availableProcessors, 4)); // 1 to 4
// EXECUTOR = Executors.newFixedThreadPool(
// nThreads, r -> new Thread(r, "DexOpener #" + count.incrementAndGet()));
// }
//
// private DexOpener() {
// throw new AssertionError("Do not instantiate");
// }
//
// /**
// * Provides the ability to mock your final classes.
// *
// * @param instrumentation the {@link Instrumentation} instance of your AndroidJUnitRunner
// * subclass
// * @throws IllegalStateException if this method is called twice or is called in an
// * inappropriate location
// * @throws UnsupportedOperationException if the given {@link Instrumentation} instance belongs
// * to a special package such as 'android'
// * @apiNote This method must be called first on the
// * {@link Instrumentation#newApplication(ClassLoader, String, Context)
// * newApplication(ClassLoader, String, Context)} method overridden in your AndroidJUnitRunner
// * subclass.
// */
// public static void install(@NonNull Instrumentation instrumentation) {
// Context context = instrumentation.getTargetContext();
// if (context == null) {
// String instrumentationName = instrumentation.getClass().getSimpleName();
// throw new IllegalStateException(
// "The " + instrumentationName + " instance has not yet been initialized");
// }
// Context app = context.getApplicationContext();
// if (app != null) {
// throw new IllegalStateException(
// "The " + app.getClass().getSimpleName() + " instance has already been created");
// }
// ClassLoader loader = context.getClassLoader();
// for (ClassLoader l = loader; l != null; l = l.getParent()) {
// if (l instanceof ClassInjector) {
// throw new IllegalStateException("Already installed");
// }
// }
// DexNameFilter dexNameFilter = createDexNameFilter(instrumentation.getClass());
// ClassPath classPath = new ClassPath(context, dexNameFilter, new DexFileLoader(), EXECUTOR);
// ClassLoaderHelper.setParent(loader, new ClassInjector(loader, classPath));
// }
//
// private static DexNameFilter createDexNameFilter(Class<?> rootClass) {
// String className = rootClass.getName();
// int lastDotPos = className.lastIndexOf('.');
// String packageName = lastDotPos == -1 ? null : className.substring(0, lastDotPos);
// if (isSupportedPackage(packageName)) {
// Logger logger = Loggers.get();
// if (logger.isLoggable(Level.FINEST)) {
// logger.finest("The final classes under " + packageName + " will be opened");
// }
// return new DexNameFilter(packageName, rootClass);
// }
// throw new UnsupportedOperationException(
// "Install to an Instrumentation instance the package of which is " + packageName);
// }
//
// private static boolean isSupportedPackage(String packageName) {
// if (packageName == null || packageName.indexOf('.') == -1) {
// return false;
// }
// for (String pkg : REFUSED_PACKAGES) {
// if (packageName.startsWith(pkg)) {
// return false;
// }
// }
// return true;
// }
//
// }
| import android.app.Application;
import android.content.Context;
import androidx.test.runner.AndroidJUnitRunner;
import com.github.tmurakami.dexopener.DexOpener; | /*
* Copyright 2016 Tsuyoshi Murakami
*
* 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.example.dexopener.multiproject.test;
// This is the base test runner for `app` and `lib` runners.
public class BaseMyAndroidJUnitRunner extends AndroidJUnitRunner {
protected BaseMyAndroidJUnitRunner() {
}
@Override
public Application newApplication(ClassLoader cl, String className, Context context)
throws ClassNotFoundException, IllegalAccessException, InstantiationException { | // Path: dexopener/src/main/java/com/github/tmurakami/dexopener/DexOpener.java
// public final class DexOpener {
//
// private static final String[] REFUSED_PACKAGES = {
// MY_PACKAGE_PREFIX,
// // Android
// "android.",
// "androidx.",
// "com.android.",
// "com.google.android.",
// "com.sun.",
// "dalvik.",
// "java.",
// "javax.",
// "libcore.",
// "org.apache.commons.logging.",
// "org.apache.harmony.",
// "org.apache.http.",
// "org.ccil.cowan.tagsoup.",
// "org.json.",
// "org.kxml2.io.",
// "org.w3c.dom.",
// "org.xml.sax.",
// "org.xmlpull.v1.",
// "sun.",
// // JUnit 4
// "junit.",
// "org.hamcrest.",
// "org.junit.",
// };
//
// private static final Executor EXECUTOR;
//
// static {
// final AtomicInteger count = new AtomicInteger();
// int availableProcessors = Runtime.getRuntime().availableProcessors();
// int nThreads = Math.max(1, Math.min(availableProcessors, 4)); // 1 to 4
// EXECUTOR = Executors.newFixedThreadPool(
// nThreads, r -> new Thread(r, "DexOpener #" + count.incrementAndGet()));
// }
//
// private DexOpener() {
// throw new AssertionError("Do not instantiate");
// }
//
// /**
// * Provides the ability to mock your final classes.
// *
// * @param instrumentation the {@link Instrumentation} instance of your AndroidJUnitRunner
// * subclass
// * @throws IllegalStateException if this method is called twice or is called in an
// * inappropriate location
// * @throws UnsupportedOperationException if the given {@link Instrumentation} instance belongs
// * to a special package such as 'android'
// * @apiNote This method must be called first on the
// * {@link Instrumentation#newApplication(ClassLoader, String, Context)
// * newApplication(ClassLoader, String, Context)} method overridden in your AndroidJUnitRunner
// * subclass.
// */
// public static void install(@NonNull Instrumentation instrumentation) {
// Context context = instrumentation.getTargetContext();
// if (context == null) {
// String instrumentationName = instrumentation.getClass().getSimpleName();
// throw new IllegalStateException(
// "The " + instrumentationName + " instance has not yet been initialized");
// }
// Context app = context.getApplicationContext();
// if (app != null) {
// throw new IllegalStateException(
// "The " + app.getClass().getSimpleName() + " instance has already been created");
// }
// ClassLoader loader = context.getClassLoader();
// for (ClassLoader l = loader; l != null; l = l.getParent()) {
// if (l instanceof ClassInjector) {
// throw new IllegalStateException("Already installed");
// }
// }
// DexNameFilter dexNameFilter = createDexNameFilter(instrumentation.getClass());
// ClassPath classPath = new ClassPath(context, dexNameFilter, new DexFileLoader(), EXECUTOR);
// ClassLoaderHelper.setParent(loader, new ClassInjector(loader, classPath));
// }
//
// private static DexNameFilter createDexNameFilter(Class<?> rootClass) {
// String className = rootClass.getName();
// int lastDotPos = className.lastIndexOf('.');
// String packageName = lastDotPos == -1 ? null : className.substring(0, lastDotPos);
// if (isSupportedPackage(packageName)) {
// Logger logger = Loggers.get();
// if (logger.isLoggable(Level.FINEST)) {
// logger.finest("The final classes under " + packageName + " will be opened");
// }
// return new DexNameFilter(packageName, rootClass);
// }
// throw new UnsupportedOperationException(
// "Install to an Instrumentation instance the package of which is " + packageName);
// }
//
// private static boolean isSupportedPackage(String packageName) {
// if (packageName == null || packageName.indexOf('.') == -1) {
// return false;
// }
// for (String pkg : REFUSED_PACKAGES) {
// if (packageName.startsWith(pkg)) {
// return false;
// }
// }
// return true;
// }
//
// }
// Path: examples/multiproject/test/src/main/java/com/example/dexopener/multiproject/test/BaseMyAndroidJUnitRunner.java
import android.app.Application;
import android.content.Context;
import androidx.test.runner.AndroidJUnitRunner;
import com.github.tmurakami.dexopener.DexOpener;
/*
* Copyright 2016 Tsuyoshi Murakami
*
* 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.example.dexopener.multiproject.test;
// This is the base test runner for `app` and `lib` runners.
public class BaseMyAndroidJUnitRunner extends AndroidJUnitRunner {
protected BaseMyAndroidJUnitRunner() {
}
@Override
public Application newApplication(ClassLoader cl, String className, Context context)
throws ClassNotFoundException, IllegalAccessException, InstantiationException { | DexOpener.install(this); // Call me first! |
tmurakami/dexopener | dexopener/src/test/java/com/github/tmurakami/dexopener/DexNameFilterTest.java | // Path: dexopener/src/test/java/test/MyClass.java
// public class MyClass {
// }
| import org.jf.dexlib2.analysis.reflection.util.ReflectionUtils;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
import java.util.Arrays;
import test.MyClass;
import static org.junit.Assert.assertSame; | /*
* Copyright 2016 Tsuyoshi Murakami
*
* 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.github.tmurakami.dexopener;
@RunWith(Parameterized.class)
public class DexNameFilterTest {
private static final boolean ALLOW = true;
private static final boolean DENY = false;
| // Path: dexopener/src/test/java/test/MyClass.java
// public class MyClass {
// }
// Path: dexopener/src/test/java/com/github/tmurakami/dexopener/DexNameFilterTest.java
import org.jf.dexlib2.analysis.reflection.util.ReflectionUtils;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
import java.util.Arrays;
import test.MyClass;
import static org.junit.Assert.assertSame;
/*
* Copyright 2016 Tsuyoshi Murakami
*
* 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.github.tmurakami.dexopener;
@RunWith(Parameterized.class)
public class DexNameFilterTest {
private static final boolean ALLOW = true;
private static final boolean DENY = false;
| private final DexNameFilter testTarget = new DexNameFilter("test", MyClass.class); |
tmurakami/dexopener | examples/atsl/src/androidTest/java/com/example/dexopener/atsl/MyAndroidJUnitRunner.java | // Path: dexopener/src/main/java/com/github/tmurakami/dexopener/DexOpener.java
// public final class DexOpener {
//
// private static final String[] REFUSED_PACKAGES = {
// MY_PACKAGE_PREFIX,
// // Android
// "android.",
// "androidx.",
// "com.android.",
// "com.google.android.",
// "com.sun.",
// "dalvik.",
// "java.",
// "javax.",
// "libcore.",
// "org.apache.commons.logging.",
// "org.apache.harmony.",
// "org.apache.http.",
// "org.ccil.cowan.tagsoup.",
// "org.json.",
// "org.kxml2.io.",
// "org.w3c.dom.",
// "org.xml.sax.",
// "org.xmlpull.v1.",
// "sun.",
// // JUnit 4
// "junit.",
// "org.hamcrest.",
// "org.junit.",
// };
//
// private static final Executor EXECUTOR;
//
// static {
// final AtomicInteger count = new AtomicInteger();
// int availableProcessors = Runtime.getRuntime().availableProcessors();
// int nThreads = Math.max(1, Math.min(availableProcessors, 4)); // 1 to 4
// EXECUTOR = Executors.newFixedThreadPool(
// nThreads, r -> new Thread(r, "DexOpener #" + count.incrementAndGet()));
// }
//
// private DexOpener() {
// throw new AssertionError("Do not instantiate");
// }
//
// /**
// * Provides the ability to mock your final classes.
// *
// * @param instrumentation the {@link Instrumentation} instance of your AndroidJUnitRunner
// * subclass
// * @throws IllegalStateException if this method is called twice or is called in an
// * inappropriate location
// * @throws UnsupportedOperationException if the given {@link Instrumentation} instance belongs
// * to a special package such as 'android'
// * @apiNote This method must be called first on the
// * {@link Instrumentation#newApplication(ClassLoader, String, Context)
// * newApplication(ClassLoader, String, Context)} method overridden in your AndroidJUnitRunner
// * subclass.
// */
// public static void install(@NonNull Instrumentation instrumentation) {
// Context context = instrumentation.getTargetContext();
// if (context == null) {
// String instrumentationName = instrumentation.getClass().getSimpleName();
// throw new IllegalStateException(
// "The " + instrumentationName + " instance has not yet been initialized");
// }
// Context app = context.getApplicationContext();
// if (app != null) {
// throw new IllegalStateException(
// "The " + app.getClass().getSimpleName() + " instance has already been created");
// }
// ClassLoader loader = context.getClassLoader();
// for (ClassLoader l = loader; l != null; l = l.getParent()) {
// if (l instanceof ClassInjector) {
// throw new IllegalStateException("Already installed");
// }
// }
// DexNameFilter dexNameFilter = createDexNameFilter(instrumentation.getClass());
// ClassPath classPath = new ClassPath(context, dexNameFilter, new DexFileLoader(), EXECUTOR);
// ClassLoaderHelper.setParent(loader, new ClassInjector(loader, classPath));
// }
//
// private static DexNameFilter createDexNameFilter(Class<?> rootClass) {
// String className = rootClass.getName();
// int lastDotPos = className.lastIndexOf('.');
// String packageName = lastDotPos == -1 ? null : className.substring(0, lastDotPos);
// if (isSupportedPackage(packageName)) {
// Logger logger = Loggers.get();
// if (logger.isLoggable(Level.FINEST)) {
// logger.finest("The final classes under " + packageName + " will be opened");
// }
// return new DexNameFilter(packageName, rootClass);
// }
// throw new UnsupportedOperationException(
// "Install to an Instrumentation instance the package of which is " + packageName);
// }
//
// private static boolean isSupportedPackage(String packageName) {
// if (packageName == null || packageName.indexOf('.') == -1) {
// return false;
// }
// for (String pkg : REFUSED_PACKAGES) {
// if (packageName.startsWith(pkg)) {
// return false;
// }
// }
// return true;
// }
//
// }
| import android.app.Application;
import android.content.Context;
import android.support.test.runner.AndroidJUnitRunner;
import com.github.tmurakami.dexopener.DexOpener; | /*
* Copyright 2016 Tsuyoshi Murakami
*
* 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.
*/
// Specify your root package as `package` statement.
package com.example.dexopener.atsl;
public class MyAndroidJUnitRunner extends AndroidJUnitRunner {
@Override
public Application newApplication(ClassLoader cl, String className, Context context)
throws ClassNotFoundException, IllegalAccessException, InstantiationException { | // Path: dexopener/src/main/java/com/github/tmurakami/dexopener/DexOpener.java
// public final class DexOpener {
//
// private static final String[] REFUSED_PACKAGES = {
// MY_PACKAGE_PREFIX,
// // Android
// "android.",
// "androidx.",
// "com.android.",
// "com.google.android.",
// "com.sun.",
// "dalvik.",
// "java.",
// "javax.",
// "libcore.",
// "org.apache.commons.logging.",
// "org.apache.harmony.",
// "org.apache.http.",
// "org.ccil.cowan.tagsoup.",
// "org.json.",
// "org.kxml2.io.",
// "org.w3c.dom.",
// "org.xml.sax.",
// "org.xmlpull.v1.",
// "sun.",
// // JUnit 4
// "junit.",
// "org.hamcrest.",
// "org.junit.",
// };
//
// private static final Executor EXECUTOR;
//
// static {
// final AtomicInteger count = new AtomicInteger();
// int availableProcessors = Runtime.getRuntime().availableProcessors();
// int nThreads = Math.max(1, Math.min(availableProcessors, 4)); // 1 to 4
// EXECUTOR = Executors.newFixedThreadPool(
// nThreads, r -> new Thread(r, "DexOpener #" + count.incrementAndGet()));
// }
//
// private DexOpener() {
// throw new AssertionError("Do not instantiate");
// }
//
// /**
// * Provides the ability to mock your final classes.
// *
// * @param instrumentation the {@link Instrumentation} instance of your AndroidJUnitRunner
// * subclass
// * @throws IllegalStateException if this method is called twice or is called in an
// * inappropriate location
// * @throws UnsupportedOperationException if the given {@link Instrumentation} instance belongs
// * to a special package such as 'android'
// * @apiNote This method must be called first on the
// * {@link Instrumentation#newApplication(ClassLoader, String, Context)
// * newApplication(ClassLoader, String, Context)} method overridden in your AndroidJUnitRunner
// * subclass.
// */
// public static void install(@NonNull Instrumentation instrumentation) {
// Context context = instrumentation.getTargetContext();
// if (context == null) {
// String instrumentationName = instrumentation.getClass().getSimpleName();
// throw new IllegalStateException(
// "The " + instrumentationName + " instance has not yet been initialized");
// }
// Context app = context.getApplicationContext();
// if (app != null) {
// throw new IllegalStateException(
// "The " + app.getClass().getSimpleName() + " instance has already been created");
// }
// ClassLoader loader = context.getClassLoader();
// for (ClassLoader l = loader; l != null; l = l.getParent()) {
// if (l instanceof ClassInjector) {
// throw new IllegalStateException("Already installed");
// }
// }
// DexNameFilter dexNameFilter = createDexNameFilter(instrumentation.getClass());
// ClassPath classPath = new ClassPath(context, dexNameFilter, new DexFileLoader(), EXECUTOR);
// ClassLoaderHelper.setParent(loader, new ClassInjector(loader, classPath));
// }
//
// private static DexNameFilter createDexNameFilter(Class<?> rootClass) {
// String className = rootClass.getName();
// int lastDotPos = className.lastIndexOf('.');
// String packageName = lastDotPos == -1 ? null : className.substring(0, lastDotPos);
// if (isSupportedPackage(packageName)) {
// Logger logger = Loggers.get();
// if (logger.isLoggable(Level.FINEST)) {
// logger.finest("The final classes under " + packageName + " will be opened");
// }
// return new DexNameFilter(packageName, rootClass);
// }
// throw new UnsupportedOperationException(
// "Install to an Instrumentation instance the package of which is " + packageName);
// }
//
// private static boolean isSupportedPackage(String packageName) {
// if (packageName == null || packageName.indexOf('.') == -1) {
// return false;
// }
// for (String pkg : REFUSED_PACKAGES) {
// if (packageName.startsWith(pkg)) {
// return false;
// }
// }
// return true;
// }
//
// }
// Path: examples/atsl/src/androidTest/java/com/example/dexopener/atsl/MyAndroidJUnitRunner.java
import android.app.Application;
import android.content.Context;
import android.support.test.runner.AndroidJUnitRunner;
import com.github.tmurakami.dexopener.DexOpener;
/*
* Copyright 2016 Tsuyoshi Murakami
*
* 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.
*/
// Specify your root package as `package` statement.
package com.example.dexopener.atsl;
public class MyAndroidJUnitRunner extends AndroidJUnitRunner {
@Override
public Application newApplication(ClassLoader cl, String className, Context context)
throws ClassNotFoundException, IllegalAccessException, InstantiationException { | DexOpener.install(this); // Call me first! |
tmurakami/dexopener | examples/simple/src/androidTest/java/com/example/dexopener/simple/MyAndroidJUnitRunner.java | // Path: dexopener/src/main/java/com/github/tmurakami/dexopener/DexOpener.java
// public final class DexOpener {
//
// private static final String[] REFUSED_PACKAGES = {
// MY_PACKAGE_PREFIX,
// // Android
// "android.",
// "androidx.",
// "com.android.",
// "com.google.android.",
// "com.sun.",
// "dalvik.",
// "java.",
// "javax.",
// "libcore.",
// "org.apache.commons.logging.",
// "org.apache.harmony.",
// "org.apache.http.",
// "org.ccil.cowan.tagsoup.",
// "org.json.",
// "org.kxml2.io.",
// "org.w3c.dom.",
// "org.xml.sax.",
// "org.xmlpull.v1.",
// "sun.",
// // JUnit 4
// "junit.",
// "org.hamcrest.",
// "org.junit.",
// };
//
// private static final Executor EXECUTOR;
//
// static {
// final AtomicInteger count = new AtomicInteger();
// int availableProcessors = Runtime.getRuntime().availableProcessors();
// int nThreads = Math.max(1, Math.min(availableProcessors, 4)); // 1 to 4
// EXECUTOR = Executors.newFixedThreadPool(
// nThreads, r -> new Thread(r, "DexOpener #" + count.incrementAndGet()));
// }
//
// private DexOpener() {
// throw new AssertionError("Do not instantiate");
// }
//
// /**
// * Provides the ability to mock your final classes.
// *
// * @param instrumentation the {@link Instrumentation} instance of your AndroidJUnitRunner
// * subclass
// * @throws IllegalStateException if this method is called twice or is called in an
// * inappropriate location
// * @throws UnsupportedOperationException if the given {@link Instrumentation} instance belongs
// * to a special package such as 'android'
// * @apiNote This method must be called first on the
// * {@link Instrumentation#newApplication(ClassLoader, String, Context)
// * newApplication(ClassLoader, String, Context)} method overridden in your AndroidJUnitRunner
// * subclass.
// */
// public static void install(@NonNull Instrumentation instrumentation) {
// Context context = instrumentation.getTargetContext();
// if (context == null) {
// String instrumentationName = instrumentation.getClass().getSimpleName();
// throw new IllegalStateException(
// "The " + instrumentationName + " instance has not yet been initialized");
// }
// Context app = context.getApplicationContext();
// if (app != null) {
// throw new IllegalStateException(
// "The " + app.getClass().getSimpleName() + " instance has already been created");
// }
// ClassLoader loader = context.getClassLoader();
// for (ClassLoader l = loader; l != null; l = l.getParent()) {
// if (l instanceof ClassInjector) {
// throw new IllegalStateException("Already installed");
// }
// }
// DexNameFilter dexNameFilter = createDexNameFilter(instrumentation.getClass());
// ClassPath classPath = new ClassPath(context, dexNameFilter, new DexFileLoader(), EXECUTOR);
// ClassLoaderHelper.setParent(loader, new ClassInjector(loader, classPath));
// }
//
// private static DexNameFilter createDexNameFilter(Class<?> rootClass) {
// String className = rootClass.getName();
// int lastDotPos = className.lastIndexOf('.');
// String packageName = lastDotPos == -1 ? null : className.substring(0, lastDotPos);
// if (isSupportedPackage(packageName)) {
// Logger logger = Loggers.get();
// if (logger.isLoggable(Level.FINEST)) {
// logger.finest("The final classes under " + packageName + " will be opened");
// }
// return new DexNameFilter(packageName, rootClass);
// }
// throw new UnsupportedOperationException(
// "Install to an Instrumentation instance the package of which is " + packageName);
// }
//
// private static boolean isSupportedPackage(String packageName) {
// if (packageName == null || packageName.indexOf('.') == -1) {
// return false;
// }
// for (String pkg : REFUSED_PACKAGES) {
// if (packageName.startsWith(pkg)) {
// return false;
// }
// }
// return true;
// }
//
// }
| import com.github.tmurakami.dexopener.DexOpener;
import android.app.Application;
import android.content.Context;
import androidx.test.runner.AndroidJUnitRunner; | /*
* Copyright 2016 Tsuyoshi Murakami
*
* 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.
*/
// Specify your root package as `package` statement.
package com.example.dexopener.simple;
public class MyAndroidJUnitRunner extends AndroidJUnitRunner {
@Override
public Application newApplication(ClassLoader cl, String className, Context context)
throws ClassNotFoundException, IllegalAccessException, InstantiationException { | // Path: dexopener/src/main/java/com/github/tmurakami/dexopener/DexOpener.java
// public final class DexOpener {
//
// private static final String[] REFUSED_PACKAGES = {
// MY_PACKAGE_PREFIX,
// // Android
// "android.",
// "androidx.",
// "com.android.",
// "com.google.android.",
// "com.sun.",
// "dalvik.",
// "java.",
// "javax.",
// "libcore.",
// "org.apache.commons.logging.",
// "org.apache.harmony.",
// "org.apache.http.",
// "org.ccil.cowan.tagsoup.",
// "org.json.",
// "org.kxml2.io.",
// "org.w3c.dom.",
// "org.xml.sax.",
// "org.xmlpull.v1.",
// "sun.",
// // JUnit 4
// "junit.",
// "org.hamcrest.",
// "org.junit.",
// };
//
// private static final Executor EXECUTOR;
//
// static {
// final AtomicInteger count = new AtomicInteger();
// int availableProcessors = Runtime.getRuntime().availableProcessors();
// int nThreads = Math.max(1, Math.min(availableProcessors, 4)); // 1 to 4
// EXECUTOR = Executors.newFixedThreadPool(
// nThreads, r -> new Thread(r, "DexOpener #" + count.incrementAndGet()));
// }
//
// private DexOpener() {
// throw new AssertionError("Do not instantiate");
// }
//
// /**
// * Provides the ability to mock your final classes.
// *
// * @param instrumentation the {@link Instrumentation} instance of your AndroidJUnitRunner
// * subclass
// * @throws IllegalStateException if this method is called twice or is called in an
// * inappropriate location
// * @throws UnsupportedOperationException if the given {@link Instrumentation} instance belongs
// * to a special package such as 'android'
// * @apiNote This method must be called first on the
// * {@link Instrumentation#newApplication(ClassLoader, String, Context)
// * newApplication(ClassLoader, String, Context)} method overridden in your AndroidJUnitRunner
// * subclass.
// */
// public static void install(@NonNull Instrumentation instrumentation) {
// Context context = instrumentation.getTargetContext();
// if (context == null) {
// String instrumentationName = instrumentation.getClass().getSimpleName();
// throw new IllegalStateException(
// "The " + instrumentationName + " instance has not yet been initialized");
// }
// Context app = context.getApplicationContext();
// if (app != null) {
// throw new IllegalStateException(
// "The " + app.getClass().getSimpleName() + " instance has already been created");
// }
// ClassLoader loader = context.getClassLoader();
// for (ClassLoader l = loader; l != null; l = l.getParent()) {
// if (l instanceof ClassInjector) {
// throw new IllegalStateException("Already installed");
// }
// }
// DexNameFilter dexNameFilter = createDexNameFilter(instrumentation.getClass());
// ClassPath classPath = new ClassPath(context, dexNameFilter, new DexFileLoader(), EXECUTOR);
// ClassLoaderHelper.setParent(loader, new ClassInjector(loader, classPath));
// }
//
// private static DexNameFilter createDexNameFilter(Class<?> rootClass) {
// String className = rootClass.getName();
// int lastDotPos = className.lastIndexOf('.');
// String packageName = lastDotPos == -1 ? null : className.substring(0, lastDotPos);
// if (isSupportedPackage(packageName)) {
// Logger logger = Loggers.get();
// if (logger.isLoggable(Level.FINEST)) {
// logger.finest("The final classes under " + packageName + " will be opened");
// }
// return new DexNameFilter(packageName, rootClass);
// }
// throw new UnsupportedOperationException(
// "Install to an Instrumentation instance the package of which is " + packageName);
// }
//
// private static boolean isSupportedPackage(String packageName) {
// if (packageName == null || packageName.indexOf('.') == -1) {
// return false;
// }
// for (String pkg : REFUSED_PACKAGES) {
// if (packageName.startsWith(pkg)) {
// return false;
// }
// }
// return true;
// }
//
// }
// Path: examples/simple/src/androidTest/java/com/example/dexopener/simple/MyAndroidJUnitRunner.java
import com.github.tmurakami.dexopener.DexOpener;
import android.app.Application;
import android.content.Context;
import androidx.test.runner.AndroidJUnitRunner;
/*
* Copyright 2016 Tsuyoshi Murakami
*
* 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.
*/
// Specify your root package as `package` statement.
package com.example.dexopener.simple;
public class MyAndroidJUnitRunner extends AndroidJUnitRunner {
@Override
public Application newApplication(ClassLoader cl, String className, Context context)
throws ClassNotFoundException, IllegalAccessException, InstantiationException { | DexOpener.install(this); // Call me first! |
tmurakami/dexopener | examples/replaceapp/src/androidTest/java/com/example/dexopener/replaceapp/MyAndroidJUnitRunner.java | // Path: dexopener/src/main/java/com/github/tmurakami/dexopener/DexOpener.java
// public final class DexOpener {
//
// private static final String[] REFUSED_PACKAGES = {
// MY_PACKAGE_PREFIX,
// // Android
// "android.",
// "androidx.",
// "com.android.",
// "com.google.android.",
// "com.sun.",
// "dalvik.",
// "java.",
// "javax.",
// "libcore.",
// "org.apache.commons.logging.",
// "org.apache.harmony.",
// "org.apache.http.",
// "org.ccil.cowan.tagsoup.",
// "org.json.",
// "org.kxml2.io.",
// "org.w3c.dom.",
// "org.xml.sax.",
// "org.xmlpull.v1.",
// "sun.",
// // JUnit 4
// "junit.",
// "org.hamcrest.",
// "org.junit.",
// };
//
// private static final Executor EXECUTOR;
//
// static {
// final AtomicInteger count = new AtomicInteger();
// int availableProcessors = Runtime.getRuntime().availableProcessors();
// int nThreads = Math.max(1, Math.min(availableProcessors, 4)); // 1 to 4
// EXECUTOR = Executors.newFixedThreadPool(
// nThreads, r -> new Thread(r, "DexOpener #" + count.incrementAndGet()));
// }
//
// private DexOpener() {
// throw new AssertionError("Do not instantiate");
// }
//
// /**
// * Provides the ability to mock your final classes.
// *
// * @param instrumentation the {@link Instrumentation} instance of your AndroidJUnitRunner
// * subclass
// * @throws IllegalStateException if this method is called twice or is called in an
// * inappropriate location
// * @throws UnsupportedOperationException if the given {@link Instrumentation} instance belongs
// * to a special package such as 'android'
// * @apiNote This method must be called first on the
// * {@link Instrumentation#newApplication(ClassLoader, String, Context)
// * newApplication(ClassLoader, String, Context)} method overridden in your AndroidJUnitRunner
// * subclass.
// */
// public static void install(@NonNull Instrumentation instrumentation) {
// Context context = instrumentation.getTargetContext();
// if (context == null) {
// String instrumentationName = instrumentation.getClass().getSimpleName();
// throw new IllegalStateException(
// "The " + instrumentationName + " instance has not yet been initialized");
// }
// Context app = context.getApplicationContext();
// if (app != null) {
// throw new IllegalStateException(
// "The " + app.getClass().getSimpleName() + " instance has already been created");
// }
// ClassLoader loader = context.getClassLoader();
// for (ClassLoader l = loader; l != null; l = l.getParent()) {
// if (l instanceof ClassInjector) {
// throw new IllegalStateException("Already installed");
// }
// }
// DexNameFilter dexNameFilter = createDexNameFilter(instrumentation.getClass());
// ClassPath classPath = new ClassPath(context, dexNameFilter, new DexFileLoader(), EXECUTOR);
// ClassLoaderHelper.setParent(loader, new ClassInjector(loader, classPath));
// }
//
// private static DexNameFilter createDexNameFilter(Class<?> rootClass) {
// String className = rootClass.getName();
// int lastDotPos = className.lastIndexOf('.');
// String packageName = lastDotPos == -1 ? null : className.substring(0, lastDotPos);
// if (isSupportedPackage(packageName)) {
// Logger logger = Loggers.get();
// if (logger.isLoggable(Level.FINEST)) {
// logger.finest("The final classes under " + packageName + " will be opened");
// }
// return new DexNameFilter(packageName, rootClass);
// }
// throw new UnsupportedOperationException(
// "Install to an Instrumentation instance the package of which is " + packageName);
// }
//
// private static boolean isSupportedPackage(String packageName) {
// if (packageName == null || packageName.indexOf('.') == -1) {
// return false;
// }
// for (String pkg : REFUSED_PACKAGES) {
// if (packageName.startsWith(pkg)) {
// return false;
// }
// }
// return true;
// }
//
// }
| import com.github.tmurakami.dexopener.DexOpener;
import android.app.Application;
import android.content.Context;
import androidx.test.runner.AndroidJUnitRunner; | /*
* Copyright 2016 Tsuyoshi Murakami
*
* 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.
*/
// Specify your root package as `package` statement.
package com.example.dexopener.replaceapp;
public class MyAndroidJUnitRunner extends AndroidJUnitRunner {
@Override
public Application newApplication(ClassLoader cl, String className, Context context)
throws ClassNotFoundException, IllegalAccessException, InstantiationException { | // Path: dexopener/src/main/java/com/github/tmurakami/dexopener/DexOpener.java
// public final class DexOpener {
//
// private static final String[] REFUSED_PACKAGES = {
// MY_PACKAGE_PREFIX,
// // Android
// "android.",
// "androidx.",
// "com.android.",
// "com.google.android.",
// "com.sun.",
// "dalvik.",
// "java.",
// "javax.",
// "libcore.",
// "org.apache.commons.logging.",
// "org.apache.harmony.",
// "org.apache.http.",
// "org.ccil.cowan.tagsoup.",
// "org.json.",
// "org.kxml2.io.",
// "org.w3c.dom.",
// "org.xml.sax.",
// "org.xmlpull.v1.",
// "sun.",
// // JUnit 4
// "junit.",
// "org.hamcrest.",
// "org.junit.",
// };
//
// private static final Executor EXECUTOR;
//
// static {
// final AtomicInteger count = new AtomicInteger();
// int availableProcessors = Runtime.getRuntime().availableProcessors();
// int nThreads = Math.max(1, Math.min(availableProcessors, 4)); // 1 to 4
// EXECUTOR = Executors.newFixedThreadPool(
// nThreads, r -> new Thread(r, "DexOpener #" + count.incrementAndGet()));
// }
//
// private DexOpener() {
// throw new AssertionError("Do not instantiate");
// }
//
// /**
// * Provides the ability to mock your final classes.
// *
// * @param instrumentation the {@link Instrumentation} instance of your AndroidJUnitRunner
// * subclass
// * @throws IllegalStateException if this method is called twice or is called in an
// * inappropriate location
// * @throws UnsupportedOperationException if the given {@link Instrumentation} instance belongs
// * to a special package such as 'android'
// * @apiNote This method must be called first on the
// * {@link Instrumentation#newApplication(ClassLoader, String, Context)
// * newApplication(ClassLoader, String, Context)} method overridden in your AndroidJUnitRunner
// * subclass.
// */
// public static void install(@NonNull Instrumentation instrumentation) {
// Context context = instrumentation.getTargetContext();
// if (context == null) {
// String instrumentationName = instrumentation.getClass().getSimpleName();
// throw new IllegalStateException(
// "The " + instrumentationName + " instance has not yet been initialized");
// }
// Context app = context.getApplicationContext();
// if (app != null) {
// throw new IllegalStateException(
// "The " + app.getClass().getSimpleName() + " instance has already been created");
// }
// ClassLoader loader = context.getClassLoader();
// for (ClassLoader l = loader; l != null; l = l.getParent()) {
// if (l instanceof ClassInjector) {
// throw new IllegalStateException("Already installed");
// }
// }
// DexNameFilter dexNameFilter = createDexNameFilter(instrumentation.getClass());
// ClassPath classPath = new ClassPath(context, dexNameFilter, new DexFileLoader(), EXECUTOR);
// ClassLoaderHelper.setParent(loader, new ClassInjector(loader, classPath));
// }
//
// private static DexNameFilter createDexNameFilter(Class<?> rootClass) {
// String className = rootClass.getName();
// int lastDotPos = className.lastIndexOf('.');
// String packageName = lastDotPos == -1 ? null : className.substring(0, lastDotPos);
// if (isSupportedPackage(packageName)) {
// Logger logger = Loggers.get();
// if (logger.isLoggable(Level.FINEST)) {
// logger.finest("The final classes under " + packageName + " will be opened");
// }
// return new DexNameFilter(packageName, rootClass);
// }
// throw new UnsupportedOperationException(
// "Install to an Instrumentation instance the package of which is " + packageName);
// }
//
// private static boolean isSupportedPackage(String packageName) {
// if (packageName == null || packageName.indexOf('.') == -1) {
// return false;
// }
// for (String pkg : REFUSED_PACKAGES) {
// if (packageName.startsWith(pkg)) {
// return false;
// }
// }
// return true;
// }
//
// }
// Path: examples/replaceapp/src/androidTest/java/com/example/dexopener/replaceapp/MyAndroidJUnitRunner.java
import com.github.tmurakami.dexopener.DexOpener;
import android.app.Application;
import android.content.Context;
import androidx.test.runner.AndroidJUnitRunner;
/*
* Copyright 2016 Tsuyoshi Murakami
*
* 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.
*/
// Specify your root package as `package` statement.
package com.example.dexopener.replaceapp;
public class MyAndroidJUnitRunner extends AndroidJUnitRunner {
@Override
public Application newApplication(ClassLoader cl, String className, Context context)
throws ClassNotFoundException, IllegalAccessException, InstantiationException { | DexOpener.install(this); // Call me first! |
tmurakami/dexopener | examples/multiproject/app/src/androidTest/java/com/example/dexopener/multiproject/app/MainActivityTest.java | // Path: examples/multiproject/lib/src/main/java/com/example/dexopener/multiproject/lib/MyService.java
// public final class MyService {
//
// @VisibleForTesting
// MyServiceDelegate delegate = new MyServiceDelegate();
//
// public void doIt() {
// delegate.doIt();
// }
//
// }
| import org.junit.runner.RunWith;
import org.mockito.junit.MockitoJUnit;
import org.mockito.junit.MockitoRule;
import org.mockito.quality.Strictness;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import android.app.Activity;
import androidx.test.core.app.ActivityScenario;
import androidx.test.ext.junit.runners.AndroidJUnit4;
import androidx.test.runner.lifecycle.ActivityLifecycleCallback;
import androidx.test.runner.lifecycle.ActivityLifecycleMonitorRegistry;
import androidx.test.runner.lifecycle.Stage;
import com.example.dexopener.multiproject.lib.MyService;
import org.junit.After;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test; | /*
* Copyright 2016 Tsuyoshi Murakami
*
* 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.example.dexopener.multiproject.app;
@RunWith(AndroidJUnit4.class)
public class MainActivityTest implements ActivityLifecycleCallback {
@Rule
public final MockitoRule mockitoRule = MockitoJUnit.rule().strictness(Strictness.STRICT_STUBS);
@Before
public void setUp() {
ActivityLifecycleMonitorRegistry.getInstance().addLifecycleCallback(this);
}
@After
public void tearDown() {
ActivityLifecycleMonitorRegistry.getInstance().removeLifecycleCallback(this);
}
@Override
public void onActivityLifecycleChanged(Activity activity, Stage stage) {
if (stage == Stage.PRE_ON_CREATE) { | // Path: examples/multiproject/lib/src/main/java/com/example/dexopener/multiproject/lib/MyService.java
// public final class MyService {
//
// @VisibleForTesting
// MyServiceDelegate delegate = new MyServiceDelegate();
//
// public void doIt() {
// delegate.doIt();
// }
//
// }
// Path: examples/multiproject/app/src/androidTest/java/com/example/dexopener/multiproject/app/MainActivityTest.java
import org.junit.runner.RunWith;
import org.mockito.junit.MockitoJUnit;
import org.mockito.junit.MockitoRule;
import org.mockito.quality.Strictness;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import android.app.Activity;
import androidx.test.core.app.ActivityScenario;
import androidx.test.ext.junit.runners.AndroidJUnit4;
import androidx.test.runner.lifecycle.ActivityLifecycleCallback;
import androidx.test.runner.lifecycle.ActivityLifecycleMonitorRegistry;
import androidx.test.runner.lifecycle.Stage;
import com.example.dexopener.multiproject.lib.MyService;
import org.junit.After;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
/*
* Copyright 2016 Tsuyoshi Murakami
*
* 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.example.dexopener.multiproject.app;
@RunWith(AndroidJUnit4.class)
public class MainActivityTest implements ActivityLifecycleCallback {
@Rule
public final MockitoRule mockitoRule = MockitoJUnit.rule().strictness(Strictness.STRICT_STUBS);
@Before
public void setUp() {
ActivityLifecycleMonitorRegistry.getInstance().addLifecycleCallback(this);
}
@After
public void tearDown() {
ActivityLifecycleMonitorRegistry.getInstance().removeLifecycleCallback(this);
}
@Override
public void onActivityLifecycleChanged(Activity activity, Stage stage) {
if (stage == Stage.PRE_ON_CREATE) { | ((MainActivity) activity).myService = mock(MyService.class); |
tmurakami/dexopener | dexopener/src/main/java/com/github/tmurakami/dexopener/DexOpener.java | // Path: dexopener/src/main/java/com/github/tmurakami/dexopener/Constants.java
// static final String MY_PACKAGE_PREFIX = MY_PACKAGE + '.';
| import android.app.Instrumentation;
import android.content.Context;
import androidx.annotation.NonNull;
import java.util.concurrent.Executor;
import java.util.concurrent.Executors;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.logging.Level;
import java.util.logging.Logger;
import static com.github.tmurakami.dexopener.Constants.MY_PACKAGE_PREFIX; | /*
* Copyright 2016 Tsuyoshi Murakami
*
* 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.github.tmurakami.dexopener;
/**
* This is a utility that provides the ability to mock your final classes. To use this, first add an
* AndroidJUnitRunner subclass into your app's <strong>androidTest</strong> directory.
*
* <pre><code>
* // Specify your root package as `package` statement.
* // The final classes you can mock are only in the package and its subpackages.
* package your.root.pkg;
*
* public class YourAndroidJUnitRunner extends AndroidJUnitRunner {
* @Override
* public Application newApplication(ClassLoader cl, String className, Context context)
* throws ClassNotFoundException, IllegalAccessException, InstantiationException {
* DexOpener.install(this); // Call me first!
* return super.newApplication(cl, className, context);
* }
* }
* </code></pre>
* <p>
* Then specify your AndroidJUnitRunner as the default test instrumentation runner in your app's
* build.gradle.
*
* <pre><code>
* android {
* defaultConfig {
* minSdkVersion 16 // 16 or higher
* testInstrumentationRunner 'your.root.pkg.YourAndroidJUnitRunner'
* }
* }
* </code></pre>
*/
public final class DexOpener {
private static final String[] REFUSED_PACKAGES = { | // Path: dexopener/src/main/java/com/github/tmurakami/dexopener/Constants.java
// static final String MY_PACKAGE_PREFIX = MY_PACKAGE + '.';
// Path: dexopener/src/main/java/com/github/tmurakami/dexopener/DexOpener.java
import android.app.Instrumentation;
import android.content.Context;
import androidx.annotation.NonNull;
import java.util.concurrent.Executor;
import java.util.concurrent.Executors;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.logging.Level;
import java.util.logging.Logger;
import static com.github.tmurakami.dexopener.Constants.MY_PACKAGE_PREFIX;
/*
* Copyright 2016 Tsuyoshi Murakami
*
* 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.github.tmurakami.dexopener;
/**
* This is a utility that provides the ability to mock your final classes. To use this, first add an
* AndroidJUnitRunner subclass into your app's <strong>androidTest</strong> directory.
*
* <pre><code>
* // Specify your root package as `package` statement.
* // The final classes you can mock are only in the package and its subpackages.
* package your.root.pkg;
*
* public class YourAndroidJUnitRunner extends AndroidJUnitRunner {
* @Override
* public Application newApplication(ClassLoader cl, String className, Context context)
* throws ClassNotFoundException, IllegalAccessException, InstantiationException {
* DexOpener.install(this); // Call me first!
* return super.newApplication(cl, className, context);
* }
* }
* </code></pre>
* <p>
* Then specify your AndroidJUnitRunner as the default test instrumentation runner in your app's
* build.gradle.
*
* <pre><code>
* android {
* defaultConfig {
* minSdkVersion 16 // 16 or higher
* testInstrumentationRunner 'your.root.pkg.YourAndroidJUnitRunner'
* }
* }
* </code></pre>
*/
public final class DexOpener {
private static final String[] REFUSED_PACKAGES = { | MY_PACKAGE_PREFIX, |
tmurakami/dexopener | dexopener/src/test/java/com/github/tmurakami/dexopener/ClassInjectorTest.java | // Path: dexopener/src/test/java/test/MyClass.java
// public class MyClass {
// }
| import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.junit.MockitoJUnitRunner;
import test.MyClass;
import static org.junit.Assert.assertSame;
import static org.mockito.BDDMockito.given;
import static org.mockito.BDDMockito.then; | /*
* Copyright 2016 Tsuyoshi Murakami
*
* 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.github.tmurakami.dexopener;
@RunWith(MockitoJUnitRunner.StrictStubs.class)
public class ClassInjectorTest {
@Mock
private ClassPath classPath;
@Test
public void should_get_the_Class_with_the_given_name() throws ClassNotFoundException {
ClassLoader loader = new ClassLoader() {
}; | // Path: dexopener/src/test/java/test/MyClass.java
// public class MyClass {
// }
// Path: dexopener/src/test/java/com/github/tmurakami/dexopener/ClassInjectorTest.java
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.junit.MockitoJUnitRunner;
import test.MyClass;
import static org.junit.Assert.assertSame;
import static org.mockito.BDDMockito.given;
import static org.mockito.BDDMockito.then;
/*
* Copyright 2016 Tsuyoshi Murakami
*
* 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.github.tmurakami.dexopener;
@RunWith(MockitoJUnitRunner.StrictStubs.class)
public class ClassInjectorTest {
@Mock
private ClassPath classPath;
@Test
public void should_get_the_Class_with_the_given_name() throws ClassNotFoundException {
ClassLoader loader = new ClassLoader() {
}; | given(classPath.loadClass("foo.Bar", loader)).willReturn(MyClass.class); |
tmurakami/dexopener | examples/multiproject/app/src/main/java/com/example/dexopener/multiproject/app/MainActivity.java | // Path: examples/multiproject/lib/src/main/java/com/example/dexopener/multiproject/lib/MyService.java
// public final class MyService {
//
// @VisibleForTesting
// MyServiceDelegate delegate = new MyServiceDelegate();
//
// public void doIt() {
// delegate.doIt();
// }
//
// }
| import android.app.Activity;
import android.os.Bundle;
import androidx.annotation.VisibleForTesting;
import com.example.dexopener.multiproject.lib.MyService; | /*
* Copyright 2016 Tsuyoshi Murakami
*
* 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.example.dexopener.multiproject.app;
public final class MainActivity extends Activity {
@VisibleForTesting | // Path: examples/multiproject/lib/src/main/java/com/example/dexopener/multiproject/lib/MyService.java
// public final class MyService {
//
// @VisibleForTesting
// MyServiceDelegate delegate = new MyServiceDelegate();
//
// public void doIt() {
// delegate.doIt();
// }
//
// }
// Path: examples/multiproject/app/src/main/java/com/example/dexopener/multiproject/app/MainActivity.java
import android.app.Activity;
import android.os.Bundle;
import androidx.annotation.VisibleForTesting;
import com.example.dexopener.multiproject.lib.MyService;
/*
* Copyright 2016 Tsuyoshi Murakami
*
* 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.example.dexopener.multiproject.app;
public final class MainActivity extends Activity {
@VisibleForTesting | MyService myService = new MyService(); |
tmurakami/dexopener | examples/dexmaker/src/androidTestMinApi16/java/com/example/dexopener/dexmaker/MyAndroidJUnitRunner.java | // Path: dexopener/src/main/java/com/github/tmurakami/dexopener/DexOpener.java
// public final class DexOpener {
//
// private static final String[] REFUSED_PACKAGES = {
// MY_PACKAGE_PREFIX,
// // Android
// "android.",
// "androidx.",
// "com.android.",
// "com.google.android.",
// "com.sun.",
// "dalvik.",
// "java.",
// "javax.",
// "libcore.",
// "org.apache.commons.logging.",
// "org.apache.harmony.",
// "org.apache.http.",
// "org.ccil.cowan.tagsoup.",
// "org.json.",
// "org.kxml2.io.",
// "org.w3c.dom.",
// "org.xml.sax.",
// "org.xmlpull.v1.",
// "sun.",
// // JUnit 4
// "junit.",
// "org.hamcrest.",
// "org.junit.",
// };
//
// private static final Executor EXECUTOR;
//
// static {
// final AtomicInteger count = new AtomicInteger();
// int availableProcessors = Runtime.getRuntime().availableProcessors();
// int nThreads = Math.max(1, Math.min(availableProcessors, 4)); // 1 to 4
// EXECUTOR = Executors.newFixedThreadPool(
// nThreads, r -> new Thread(r, "DexOpener #" + count.incrementAndGet()));
// }
//
// private DexOpener() {
// throw new AssertionError("Do not instantiate");
// }
//
// /**
// * Provides the ability to mock your final classes.
// *
// * @param instrumentation the {@link Instrumentation} instance of your AndroidJUnitRunner
// * subclass
// * @throws IllegalStateException if this method is called twice or is called in an
// * inappropriate location
// * @throws UnsupportedOperationException if the given {@link Instrumentation} instance belongs
// * to a special package such as 'android'
// * @apiNote This method must be called first on the
// * {@link Instrumentation#newApplication(ClassLoader, String, Context)
// * newApplication(ClassLoader, String, Context)} method overridden in your AndroidJUnitRunner
// * subclass.
// */
// public static void install(@NonNull Instrumentation instrumentation) {
// Context context = instrumentation.getTargetContext();
// if (context == null) {
// String instrumentationName = instrumentation.getClass().getSimpleName();
// throw new IllegalStateException(
// "The " + instrumentationName + " instance has not yet been initialized");
// }
// Context app = context.getApplicationContext();
// if (app != null) {
// throw new IllegalStateException(
// "The " + app.getClass().getSimpleName() + " instance has already been created");
// }
// ClassLoader loader = context.getClassLoader();
// for (ClassLoader l = loader; l != null; l = l.getParent()) {
// if (l instanceof ClassInjector) {
// throw new IllegalStateException("Already installed");
// }
// }
// DexNameFilter dexNameFilter = createDexNameFilter(instrumentation.getClass());
// ClassPath classPath = new ClassPath(context, dexNameFilter, new DexFileLoader(), EXECUTOR);
// ClassLoaderHelper.setParent(loader, new ClassInjector(loader, classPath));
// }
//
// private static DexNameFilter createDexNameFilter(Class<?> rootClass) {
// String className = rootClass.getName();
// int lastDotPos = className.lastIndexOf('.');
// String packageName = lastDotPos == -1 ? null : className.substring(0, lastDotPos);
// if (isSupportedPackage(packageName)) {
// Logger logger = Loggers.get();
// if (logger.isLoggable(Level.FINEST)) {
// logger.finest("The final classes under " + packageName + " will be opened");
// }
// return new DexNameFilter(packageName, rootClass);
// }
// throw new UnsupportedOperationException(
// "Install to an Instrumentation instance the package of which is " + packageName);
// }
//
// private static boolean isSupportedPackage(String packageName) {
// if (packageName == null || packageName.indexOf('.') == -1) {
// return false;
// }
// for (String pkg : REFUSED_PACKAGES) {
// if (packageName.startsWith(pkg)) {
// return false;
// }
// }
// return true;
// }
//
// }
| import com.github.tmurakami.dexopener.DexOpener;
import android.app.Application;
import android.content.Context;
import androidx.test.runner.AndroidJUnitRunner; | /*
* Copyright 2016 Tsuyoshi Murakami
*
* 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.
*/
// Specify your root package as `package` statement.
package com.example.dexopener.dexmaker;
public class MyAndroidJUnitRunner extends AndroidJUnitRunner {
@Override
public Application newApplication(ClassLoader cl, String className, Context context)
throws ClassNotFoundException, IllegalAccessException, InstantiationException { | // Path: dexopener/src/main/java/com/github/tmurakami/dexopener/DexOpener.java
// public final class DexOpener {
//
// private static final String[] REFUSED_PACKAGES = {
// MY_PACKAGE_PREFIX,
// // Android
// "android.",
// "androidx.",
// "com.android.",
// "com.google.android.",
// "com.sun.",
// "dalvik.",
// "java.",
// "javax.",
// "libcore.",
// "org.apache.commons.logging.",
// "org.apache.harmony.",
// "org.apache.http.",
// "org.ccil.cowan.tagsoup.",
// "org.json.",
// "org.kxml2.io.",
// "org.w3c.dom.",
// "org.xml.sax.",
// "org.xmlpull.v1.",
// "sun.",
// // JUnit 4
// "junit.",
// "org.hamcrest.",
// "org.junit.",
// };
//
// private static final Executor EXECUTOR;
//
// static {
// final AtomicInteger count = new AtomicInteger();
// int availableProcessors = Runtime.getRuntime().availableProcessors();
// int nThreads = Math.max(1, Math.min(availableProcessors, 4)); // 1 to 4
// EXECUTOR = Executors.newFixedThreadPool(
// nThreads, r -> new Thread(r, "DexOpener #" + count.incrementAndGet()));
// }
//
// private DexOpener() {
// throw new AssertionError("Do not instantiate");
// }
//
// /**
// * Provides the ability to mock your final classes.
// *
// * @param instrumentation the {@link Instrumentation} instance of your AndroidJUnitRunner
// * subclass
// * @throws IllegalStateException if this method is called twice or is called in an
// * inappropriate location
// * @throws UnsupportedOperationException if the given {@link Instrumentation} instance belongs
// * to a special package such as 'android'
// * @apiNote This method must be called first on the
// * {@link Instrumentation#newApplication(ClassLoader, String, Context)
// * newApplication(ClassLoader, String, Context)} method overridden in your AndroidJUnitRunner
// * subclass.
// */
// public static void install(@NonNull Instrumentation instrumentation) {
// Context context = instrumentation.getTargetContext();
// if (context == null) {
// String instrumentationName = instrumentation.getClass().getSimpleName();
// throw new IllegalStateException(
// "The " + instrumentationName + " instance has not yet been initialized");
// }
// Context app = context.getApplicationContext();
// if (app != null) {
// throw new IllegalStateException(
// "The " + app.getClass().getSimpleName() + " instance has already been created");
// }
// ClassLoader loader = context.getClassLoader();
// for (ClassLoader l = loader; l != null; l = l.getParent()) {
// if (l instanceof ClassInjector) {
// throw new IllegalStateException("Already installed");
// }
// }
// DexNameFilter dexNameFilter = createDexNameFilter(instrumentation.getClass());
// ClassPath classPath = new ClassPath(context, dexNameFilter, new DexFileLoader(), EXECUTOR);
// ClassLoaderHelper.setParent(loader, new ClassInjector(loader, classPath));
// }
//
// private static DexNameFilter createDexNameFilter(Class<?> rootClass) {
// String className = rootClass.getName();
// int lastDotPos = className.lastIndexOf('.');
// String packageName = lastDotPos == -1 ? null : className.substring(0, lastDotPos);
// if (isSupportedPackage(packageName)) {
// Logger logger = Loggers.get();
// if (logger.isLoggable(Level.FINEST)) {
// logger.finest("The final classes under " + packageName + " will be opened");
// }
// return new DexNameFilter(packageName, rootClass);
// }
// throw new UnsupportedOperationException(
// "Install to an Instrumentation instance the package of which is " + packageName);
// }
//
// private static boolean isSupportedPackage(String packageName) {
// if (packageName == null || packageName.indexOf('.') == -1) {
// return false;
// }
// for (String pkg : REFUSED_PACKAGES) {
// if (packageName.startsWith(pkg)) {
// return false;
// }
// }
// return true;
// }
//
// }
// Path: examples/dexmaker/src/androidTestMinApi16/java/com/example/dexopener/dexmaker/MyAndroidJUnitRunner.java
import com.github.tmurakami.dexopener.DexOpener;
import android.app.Application;
import android.content.Context;
import androidx.test.runner.AndroidJUnitRunner;
/*
* Copyright 2016 Tsuyoshi Murakami
*
* 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.
*/
// Specify your root package as `package` statement.
package com.example.dexopener.dexmaker;
public class MyAndroidJUnitRunner extends AndroidJUnitRunner {
@Override
public Application newApplication(ClassLoader cl, String className, Context context)
throws ClassNotFoundException, IllegalAccessException, InstantiationException { | DexOpener.install(this); // Call me first! |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.