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 |
|---|---|---|---|---|---|---|
deshi-basara/susurrus-android-app | Susurrus/app/src/main/java/rocks/susurrus/susurrus/views/adapters/IntroPageAdapter.java | // Path: Susurrus/app/src/main/java/rocks/susurrus/susurrus/fragments/IntroPageFourFragment.java
// public class IntroPageFourFragment extends Fragment {
//
// /**
// * Views
// */
// private EditText passwordInputOne;
// private EditText passwordInputTwo;
//
// @Override
// public View onCreateView(LayoutInflater inflater, ViewGroup container,
// Bundle savedInstanceState) {
// // Inflate the layout for this fragment
// View view = inflater.inflate(R.layout.fragment_intro_page_four, container, false);
//
// setView(view);
//
// return view;
// }
//
// /**
// * Sets the view.
// * @param _view Fragment view.
// */
// private void setView(View _view) {
// this.passwordInputOne = (EditText) _view.findViewById(R.id.intro_four_passwort_one);
// this.passwordInputTwo = (EditText) _view.findViewById(R.id.intro_four_passwort_two);
// }
//
// }
//
// Path: Susurrus/app/src/main/java/rocks/susurrus/susurrus/fragments/IntroPageOneFragment.java
// public class IntroPageOneFragment extends Fragment {
//
// private final String logIndictaor = "IntroPageOneFragment";
//
// private View rootView;
// private ViewGroup upperContainer;
// private ImageView logo;
//
// @Override
// public View onCreateView(LayoutInflater inflater, ViewGroup container,
// Bundle savedInstanceState) {
// // Inflate the layout for this fragment
// rootView = inflater.inflate(R.layout.fragment_intro_page_one, container, false);
//
// return rootView;
// }
//
// @Override
// public void onViewCreated(View view, Bundle savedInstanceState) {
// super.onViewCreated(view, savedInstanceState);
//
// setLayout(view);
// //startAnimation();
// }
//
//
// private void setLayout(View view) {
// //upperContainer = (ViewGroup) view.findViewById(R.id.upper_container);
// //logo = (ImageView) view.findViewById(R.id.logo);
// }
//
// private void startAnimation() {
// logo.setVisibility(View.INVISIBLE);
// }
//
// }
//
// Path: Susurrus/app/src/main/java/rocks/susurrus/susurrus/fragments/IntroPageThreeFragment.java
// public class IntroPageThreeFragment extends Fragment {
//
// /**
// * Views
// */
// EditText inputName;
// ImageButton buttonRandomName;
//
//
// public IntroPageThreeFragment() {
// // Required empty public constructor
// }
//
// @Override
// public View onCreateView(LayoutInflater inflater, ViewGroup container,
// Bundle savedInstanceState) {
// // Inflate the layout for this fragment
// View view = inflater.inflate(R.layout.fragment_intro_page_three, container, false);
//
// setView(view);
// insertRandomName();
//
// return view;
// }
//
// /**
// * Set all view elements.
// * @param _view Fragment view.
// */
// private void setView(View _view) {
// // get views
// this.inputName = (EditText) _view.findViewById(R.id.username_input_name);
// this.buttonRandomName = (ImageButton) _view.findViewById(R.id.username_refresh_button);
//
// // set listeners
// this.buttonRandomName.setOnClickListener(this.randomListener);
// }
//
// /**
// * Helper method for inserting a random name into username input-field.
// */
// private void insertRandomName() {
// // get a random name & set it
// RandomName randName = new RandomName(getActivity());
// inputName.setText(randName.generate());
// }
//
// /**
// * OnClickListener: buttonRandomName.
// * Refreshes the random name.
// */
// private View.OnClickListener randomListener = new View.OnClickListener() {
// @Override
// public void onClick(View v) {
// insertRandomName();
// }
// };
//
// }
//
// Path: Susurrus/app/src/main/java/rocks/susurrus/susurrus/fragments/IntroPageTwoFragment.java
// public class IntroPageTwoFragment extends Fragment {
//
// @Override
// public View onCreateView(LayoutInflater inflater, ViewGroup container,
// Bundle savedInstanceState) {
// // Inflate the layout for this fragment
// return inflater.inflate(R.layout.fragment_intro_page_two, container, false);
// }
//
// private void checkWifiDirect() {
//
// }
//
// private void checkHotspot() {
//
// }
//
// }
| import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentStatePagerAdapter;
import java.util.ArrayList;
import rocks.susurrus.susurrus.fragments.IntroPageFourFragment;
import rocks.susurrus.susurrus.fragments.IntroPageOneFragment;
import rocks.susurrus.susurrus.fragments.IntroPageThreeFragment;
import rocks.susurrus.susurrus.fragments.IntroPageTwoFragment; | package rocks.susurrus.susurrus.views.adapters;
/**
* Created by simon on 01.05.15.
*/
public class IntroPageAdapter extends FragmentStatePagerAdapter {
/**
* Intro page count
*/
final static int NUM_PAGES = 4;
/**
* Constructor
* @param fm
*/
public IntroPageAdapter(FragmentManager fm) {
super(fm);
}
@Override
public Fragment getItem(int position) {
// for each different position, return another fragment with different layout
switch(position) {
case 0:
Fragment fragmentOne = new IntroPageOneFragment();
return fragmentOne;
case 1: | // Path: Susurrus/app/src/main/java/rocks/susurrus/susurrus/fragments/IntroPageFourFragment.java
// public class IntroPageFourFragment extends Fragment {
//
// /**
// * Views
// */
// private EditText passwordInputOne;
// private EditText passwordInputTwo;
//
// @Override
// public View onCreateView(LayoutInflater inflater, ViewGroup container,
// Bundle savedInstanceState) {
// // Inflate the layout for this fragment
// View view = inflater.inflate(R.layout.fragment_intro_page_four, container, false);
//
// setView(view);
//
// return view;
// }
//
// /**
// * Sets the view.
// * @param _view Fragment view.
// */
// private void setView(View _view) {
// this.passwordInputOne = (EditText) _view.findViewById(R.id.intro_four_passwort_one);
// this.passwordInputTwo = (EditText) _view.findViewById(R.id.intro_four_passwort_two);
// }
//
// }
//
// Path: Susurrus/app/src/main/java/rocks/susurrus/susurrus/fragments/IntroPageOneFragment.java
// public class IntroPageOneFragment extends Fragment {
//
// private final String logIndictaor = "IntroPageOneFragment";
//
// private View rootView;
// private ViewGroup upperContainer;
// private ImageView logo;
//
// @Override
// public View onCreateView(LayoutInflater inflater, ViewGroup container,
// Bundle savedInstanceState) {
// // Inflate the layout for this fragment
// rootView = inflater.inflate(R.layout.fragment_intro_page_one, container, false);
//
// return rootView;
// }
//
// @Override
// public void onViewCreated(View view, Bundle savedInstanceState) {
// super.onViewCreated(view, savedInstanceState);
//
// setLayout(view);
// //startAnimation();
// }
//
//
// private void setLayout(View view) {
// //upperContainer = (ViewGroup) view.findViewById(R.id.upper_container);
// //logo = (ImageView) view.findViewById(R.id.logo);
// }
//
// private void startAnimation() {
// logo.setVisibility(View.INVISIBLE);
// }
//
// }
//
// Path: Susurrus/app/src/main/java/rocks/susurrus/susurrus/fragments/IntroPageThreeFragment.java
// public class IntroPageThreeFragment extends Fragment {
//
// /**
// * Views
// */
// EditText inputName;
// ImageButton buttonRandomName;
//
//
// public IntroPageThreeFragment() {
// // Required empty public constructor
// }
//
// @Override
// public View onCreateView(LayoutInflater inflater, ViewGroup container,
// Bundle savedInstanceState) {
// // Inflate the layout for this fragment
// View view = inflater.inflate(R.layout.fragment_intro_page_three, container, false);
//
// setView(view);
// insertRandomName();
//
// return view;
// }
//
// /**
// * Set all view elements.
// * @param _view Fragment view.
// */
// private void setView(View _view) {
// // get views
// this.inputName = (EditText) _view.findViewById(R.id.username_input_name);
// this.buttonRandomName = (ImageButton) _view.findViewById(R.id.username_refresh_button);
//
// // set listeners
// this.buttonRandomName.setOnClickListener(this.randomListener);
// }
//
// /**
// * Helper method for inserting a random name into username input-field.
// */
// private void insertRandomName() {
// // get a random name & set it
// RandomName randName = new RandomName(getActivity());
// inputName.setText(randName.generate());
// }
//
// /**
// * OnClickListener: buttonRandomName.
// * Refreshes the random name.
// */
// private View.OnClickListener randomListener = new View.OnClickListener() {
// @Override
// public void onClick(View v) {
// insertRandomName();
// }
// };
//
// }
//
// Path: Susurrus/app/src/main/java/rocks/susurrus/susurrus/fragments/IntroPageTwoFragment.java
// public class IntroPageTwoFragment extends Fragment {
//
// @Override
// public View onCreateView(LayoutInflater inflater, ViewGroup container,
// Bundle savedInstanceState) {
// // Inflate the layout for this fragment
// return inflater.inflate(R.layout.fragment_intro_page_two, container, false);
// }
//
// private void checkWifiDirect() {
//
// }
//
// private void checkHotspot() {
//
// }
//
// }
// Path: Susurrus/app/src/main/java/rocks/susurrus/susurrus/views/adapters/IntroPageAdapter.java
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentStatePagerAdapter;
import java.util.ArrayList;
import rocks.susurrus.susurrus.fragments.IntroPageFourFragment;
import rocks.susurrus.susurrus.fragments.IntroPageOneFragment;
import rocks.susurrus.susurrus.fragments.IntroPageThreeFragment;
import rocks.susurrus.susurrus.fragments.IntroPageTwoFragment;
package rocks.susurrus.susurrus.views.adapters;
/**
* Created by simon on 01.05.15.
*/
public class IntroPageAdapter extends FragmentStatePagerAdapter {
/**
* Intro page count
*/
final static int NUM_PAGES = 4;
/**
* Constructor
* @param fm
*/
public IntroPageAdapter(FragmentManager fm) {
super(fm);
}
@Override
public Fragment getItem(int position) {
// for each different position, return another fragment with different layout
switch(position) {
case 0:
Fragment fragmentOne = new IntroPageOneFragment();
return fragmentOne;
case 1: | Fragment fragmentTwo = new IntroPageTwoFragment(); |
deshi-basara/susurrus-android-app | Susurrus/app/src/main/java/rocks/susurrus/susurrus/views/adapters/IntroPageAdapter.java | // Path: Susurrus/app/src/main/java/rocks/susurrus/susurrus/fragments/IntroPageFourFragment.java
// public class IntroPageFourFragment extends Fragment {
//
// /**
// * Views
// */
// private EditText passwordInputOne;
// private EditText passwordInputTwo;
//
// @Override
// public View onCreateView(LayoutInflater inflater, ViewGroup container,
// Bundle savedInstanceState) {
// // Inflate the layout for this fragment
// View view = inflater.inflate(R.layout.fragment_intro_page_four, container, false);
//
// setView(view);
//
// return view;
// }
//
// /**
// * Sets the view.
// * @param _view Fragment view.
// */
// private void setView(View _view) {
// this.passwordInputOne = (EditText) _view.findViewById(R.id.intro_four_passwort_one);
// this.passwordInputTwo = (EditText) _view.findViewById(R.id.intro_four_passwort_two);
// }
//
// }
//
// Path: Susurrus/app/src/main/java/rocks/susurrus/susurrus/fragments/IntroPageOneFragment.java
// public class IntroPageOneFragment extends Fragment {
//
// private final String logIndictaor = "IntroPageOneFragment";
//
// private View rootView;
// private ViewGroup upperContainer;
// private ImageView logo;
//
// @Override
// public View onCreateView(LayoutInflater inflater, ViewGroup container,
// Bundle savedInstanceState) {
// // Inflate the layout for this fragment
// rootView = inflater.inflate(R.layout.fragment_intro_page_one, container, false);
//
// return rootView;
// }
//
// @Override
// public void onViewCreated(View view, Bundle savedInstanceState) {
// super.onViewCreated(view, savedInstanceState);
//
// setLayout(view);
// //startAnimation();
// }
//
//
// private void setLayout(View view) {
// //upperContainer = (ViewGroup) view.findViewById(R.id.upper_container);
// //logo = (ImageView) view.findViewById(R.id.logo);
// }
//
// private void startAnimation() {
// logo.setVisibility(View.INVISIBLE);
// }
//
// }
//
// Path: Susurrus/app/src/main/java/rocks/susurrus/susurrus/fragments/IntroPageThreeFragment.java
// public class IntroPageThreeFragment extends Fragment {
//
// /**
// * Views
// */
// EditText inputName;
// ImageButton buttonRandomName;
//
//
// public IntroPageThreeFragment() {
// // Required empty public constructor
// }
//
// @Override
// public View onCreateView(LayoutInflater inflater, ViewGroup container,
// Bundle savedInstanceState) {
// // Inflate the layout for this fragment
// View view = inflater.inflate(R.layout.fragment_intro_page_three, container, false);
//
// setView(view);
// insertRandomName();
//
// return view;
// }
//
// /**
// * Set all view elements.
// * @param _view Fragment view.
// */
// private void setView(View _view) {
// // get views
// this.inputName = (EditText) _view.findViewById(R.id.username_input_name);
// this.buttonRandomName = (ImageButton) _view.findViewById(R.id.username_refresh_button);
//
// // set listeners
// this.buttonRandomName.setOnClickListener(this.randomListener);
// }
//
// /**
// * Helper method for inserting a random name into username input-field.
// */
// private void insertRandomName() {
// // get a random name & set it
// RandomName randName = new RandomName(getActivity());
// inputName.setText(randName.generate());
// }
//
// /**
// * OnClickListener: buttonRandomName.
// * Refreshes the random name.
// */
// private View.OnClickListener randomListener = new View.OnClickListener() {
// @Override
// public void onClick(View v) {
// insertRandomName();
// }
// };
//
// }
//
// Path: Susurrus/app/src/main/java/rocks/susurrus/susurrus/fragments/IntroPageTwoFragment.java
// public class IntroPageTwoFragment extends Fragment {
//
// @Override
// public View onCreateView(LayoutInflater inflater, ViewGroup container,
// Bundle savedInstanceState) {
// // Inflate the layout for this fragment
// return inflater.inflate(R.layout.fragment_intro_page_two, container, false);
// }
//
// private void checkWifiDirect() {
//
// }
//
// private void checkHotspot() {
//
// }
//
// }
| import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentStatePagerAdapter;
import java.util.ArrayList;
import rocks.susurrus.susurrus.fragments.IntroPageFourFragment;
import rocks.susurrus.susurrus.fragments.IntroPageOneFragment;
import rocks.susurrus.susurrus.fragments.IntroPageThreeFragment;
import rocks.susurrus.susurrus.fragments.IntroPageTwoFragment; | package rocks.susurrus.susurrus.views.adapters;
/**
* Created by simon on 01.05.15.
*/
public class IntroPageAdapter extends FragmentStatePagerAdapter {
/**
* Intro page count
*/
final static int NUM_PAGES = 4;
/**
* Constructor
* @param fm
*/
public IntroPageAdapter(FragmentManager fm) {
super(fm);
}
@Override
public Fragment getItem(int position) {
// for each different position, return another fragment with different layout
switch(position) {
case 0:
Fragment fragmentOne = new IntroPageOneFragment();
return fragmentOne;
case 1:
Fragment fragmentTwo = new IntroPageTwoFragment();
return fragmentTwo;
case 2: | // Path: Susurrus/app/src/main/java/rocks/susurrus/susurrus/fragments/IntroPageFourFragment.java
// public class IntroPageFourFragment extends Fragment {
//
// /**
// * Views
// */
// private EditText passwordInputOne;
// private EditText passwordInputTwo;
//
// @Override
// public View onCreateView(LayoutInflater inflater, ViewGroup container,
// Bundle savedInstanceState) {
// // Inflate the layout for this fragment
// View view = inflater.inflate(R.layout.fragment_intro_page_four, container, false);
//
// setView(view);
//
// return view;
// }
//
// /**
// * Sets the view.
// * @param _view Fragment view.
// */
// private void setView(View _view) {
// this.passwordInputOne = (EditText) _view.findViewById(R.id.intro_four_passwort_one);
// this.passwordInputTwo = (EditText) _view.findViewById(R.id.intro_four_passwort_two);
// }
//
// }
//
// Path: Susurrus/app/src/main/java/rocks/susurrus/susurrus/fragments/IntroPageOneFragment.java
// public class IntroPageOneFragment extends Fragment {
//
// private final String logIndictaor = "IntroPageOneFragment";
//
// private View rootView;
// private ViewGroup upperContainer;
// private ImageView logo;
//
// @Override
// public View onCreateView(LayoutInflater inflater, ViewGroup container,
// Bundle savedInstanceState) {
// // Inflate the layout for this fragment
// rootView = inflater.inflate(R.layout.fragment_intro_page_one, container, false);
//
// return rootView;
// }
//
// @Override
// public void onViewCreated(View view, Bundle savedInstanceState) {
// super.onViewCreated(view, savedInstanceState);
//
// setLayout(view);
// //startAnimation();
// }
//
//
// private void setLayout(View view) {
// //upperContainer = (ViewGroup) view.findViewById(R.id.upper_container);
// //logo = (ImageView) view.findViewById(R.id.logo);
// }
//
// private void startAnimation() {
// logo.setVisibility(View.INVISIBLE);
// }
//
// }
//
// Path: Susurrus/app/src/main/java/rocks/susurrus/susurrus/fragments/IntroPageThreeFragment.java
// public class IntroPageThreeFragment extends Fragment {
//
// /**
// * Views
// */
// EditText inputName;
// ImageButton buttonRandomName;
//
//
// public IntroPageThreeFragment() {
// // Required empty public constructor
// }
//
// @Override
// public View onCreateView(LayoutInflater inflater, ViewGroup container,
// Bundle savedInstanceState) {
// // Inflate the layout for this fragment
// View view = inflater.inflate(R.layout.fragment_intro_page_three, container, false);
//
// setView(view);
// insertRandomName();
//
// return view;
// }
//
// /**
// * Set all view elements.
// * @param _view Fragment view.
// */
// private void setView(View _view) {
// // get views
// this.inputName = (EditText) _view.findViewById(R.id.username_input_name);
// this.buttonRandomName = (ImageButton) _view.findViewById(R.id.username_refresh_button);
//
// // set listeners
// this.buttonRandomName.setOnClickListener(this.randomListener);
// }
//
// /**
// * Helper method for inserting a random name into username input-field.
// */
// private void insertRandomName() {
// // get a random name & set it
// RandomName randName = new RandomName(getActivity());
// inputName.setText(randName.generate());
// }
//
// /**
// * OnClickListener: buttonRandomName.
// * Refreshes the random name.
// */
// private View.OnClickListener randomListener = new View.OnClickListener() {
// @Override
// public void onClick(View v) {
// insertRandomName();
// }
// };
//
// }
//
// Path: Susurrus/app/src/main/java/rocks/susurrus/susurrus/fragments/IntroPageTwoFragment.java
// public class IntroPageTwoFragment extends Fragment {
//
// @Override
// public View onCreateView(LayoutInflater inflater, ViewGroup container,
// Bundle savedInstanceState) {
// // Inflate the layout for this fragment
// return inflater.inflate(R.layout.fragment_intro_page_two, container, false);
// }
//
// private void checkWifiDirect() {
//
// }
//
// private void checkHotspot() {
//
// }
//
// }
// Path: Susurrus/app/src/main/java/rocks/susurrus/susurrus/views/adapters/IntroPageAdapter.java
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentStatePagerAdapter;
import java.util.ArrayList;
import rocks.susurrus.susurrus.fragments.IntroPageFourFragment;
import rocks.susurrus.susurrus.fragments.IntroPageOneFragment;
import rocks.susurrus.susurrus.fragments.IntroPageThreeFragment;
import rocks.susurrus.susurrus.fragments.IntroPageTwoFragment;
package rocks.susurrus.susurrus.views.adapters;
/**
* Created by simon on 01.05.15.
*/
public class IntroPageAdapter extends FragmentStatePagerAdapter {
/**
* Intro page count
*/
final static int NUM_PAGES = 4;
/**
* Constructor
* @param fm
*/
public IntroPageAdapter(FragmentManager fm) {
super(fm);
}
@Override
public Fragment getItem(int position) {
// for each different position, return another fragment with different layout
switch(position) {
case 0:
Fragment fragmentOne = new IntroPageOneFragment();
return fragmentOne;
case 1:
Fragment fragmentTwo = new IntroPageTwoFragment();
return fragmentTwo;
case 2: | Fragment fragmentThree = new IntroPageThreeFragment(); |
deshi-basara/susurrus-android-app | Susurrus/app/src/main/java/rocks/susurrus/susurrus/views/adapters/IntroPageAdapter.java | // Path: Susurrus/app/src/main/java/rocks/susurrus/susurrus/fragments/IntroPageFourFragment.java
// public class IntroPageFourFragment extends Fragment {
//
// /**
// * Views
// */
// private EditText passwordInputOne;
// private EditText passwordInputTwo;
//
// @Override
// public View onCreateView(LayoutInflater inflater, ViewGroup container,
// Bundle savedInstanceState) {
// // Inflate the layout for this fragment
// View view = inflater.inflate(R.layout.fragment_intro_page_four, container, false);
//
// setView(view);
//
// return view;
// }
//
// /**
// * Sets the view.
// * @param _view Fragment view.
// */
// private void setView(View _view) {
// this.passwordInputOne = (EditText) _view.findViewById(R.id.intro_four_passwort_one);
// this.passwordInputTwo = (EditText) _view.findViewById(R.id.intro_four_passwort_two);
// }
//
// }
//
// Path: Susurrus/app/src/main/java/rocks/susurrus/susurrus/fragments/IntroPageOneFragment.java
// public class IntroPageOneFragment extends Fragment {
//
// private final String logIndictaor = "IntroPageOneFragment";
//
// private View rootView;
// private ViewGroup upperContainer;
// private ImageView logo;
//
// @Override
// public View onCreateView(LayoutInflater inflater, ViewGroup container,
// Bundle savedInstanceState) {
// // Inflate the layout for this fragment
// rootView = inflater.inflate(R.layout.fragment_intro_page_one, container, false);
//
// return rootView;
// }
//
// @Override
// public void onViewCreated(View view, Bundle savedInstanceState) {
// super.onViewCreated(view, savedInstanceState);
//
// setLayout(view);
// //startAnimation();
// }
//
//
// private void setLayout(View view) {
// //upperContainer = (ViewGroup) view.findViewById(R.id.upper_container);
// //logo = (ImageView) view.findViewById(R.id.logo);
// }
//
// private void startAnimation() {
// logo.setVisibility(View.INVISIBLE);
// }
//
// }
//
// Path: Susurrus/app/src/main/java/rocks/susurrus/susurrus/fragments/IntroPageThreeFragment.java
// public class IntroPageThreeFragment extends Fragment {
//
// /**
// * Views
// */
// EditText inputName;
// ImageButton buttonRandomName;
//
//
// public IntroPageThreeFragment() {
// // Required empty public constructor
// }
//
// @Override
// public View onCreateView(LayoutInflater inflater, ViewGroup container,
// Bundle savedInstanceState) {
// // Inflate the layout for this fragment
// View view = inflater.inflate(R.layout.fragment_intro_page_three, container, false);
//
// setView(view);
// insertRandomName();
//
// return view;
// }
//
// /**
// * Set all view elements.
// * @param _view Fragment view.
// */
// private void setView(View _view) {
// // get views
// this.inputName = (EditText) _view.findViewById(R.id.username_input_name);
// this.buttonRandomName = (ImageButton) _view.findViewById(R.id.username_refresh_button);
//
// // set listeners
// this.buttonRandomName.setOnClickListener(this.randomListener);
// }
//
// /**
// * Helper method for inserting a random name into username input-field.
// */
// private void insertRandomName() {
// // get a random name & set it
// RandomName randName = new RandomName(getActivity());
// inputName.setText(randName.generate());
// }
//
// /**
// * OnClickListener: buttonRandomName.
// * Refreshes the random name.
// */
// private View.OnClickListener randomListener = new View.OnClickListener() {
// @Override
// public void onClick(View v) {
// insertRandomName();
// }
// };
//
// }
//
// Path: Susurrus/app/src/main/java/rocks/susurrus/susurrus/fragments/IntroPageTwoFragment.java
// public class IntroPageTwoFragment extends Fragment {
//
// @Override
// public View onCreateView(LayoutInflater inflater, ViewGroup container,
// Bundle savedInstanceState) {
// // Inflate the layout for this fragment
// return inflater.inflate(R.layout.fragment_intro_page_two, container, false);
// }
//
// private void checkWifiDirect() {
//
// }
//
// private void checkHotspot() {
//
// }
//
// }
| import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentStatePagerAdapter;
import java.util.ArrayList;
import rocks.susurrus.susurrus.fragments.IntroPageFourFragment;
import rocks.susurrus.susurrus.fragments.IntroPageOneFragment;
import rocks.susurrus.susurrus.fragments.IntroPageThreeFragment;
import rocks.susurrus.susurrus.fragments.IntroPageTwoFragment; | package rocks.susurrus.susurrus.views.adapters;
/**
* Created by simon on 01.05.15.
*/
public class IntroPageAdapter extends FragmentStatePagerAdapter {
/**
* Intro page count
*/
final static int NUM_PAGES = 4;
/**
* Constructor
* @param fm
*/
public IntroPageAdapter(FragmentManager fm) {
super(fm);
}
@Override
public Fragment getItem(int position) {
// for each different position, return another fragment with different layout
switch(position) {
case 0:
Fragment fragmentOne = new IntroPageOneFragment();
return fragmentOne;
case 1:
Fragment fragmentTwo = new IntroPageTwoFragment();
return fragmentTwo;
case 2:
Fragment fragmentThree = new IntroPageThreeFragment();
return fragmentThree;
case 3: | // Path: Susurrus/app/src/main/java/rocks/susurrus/susurrus/fragments/IntroPageFourFragment.java
// public class IntroPageFourFragment extends Fragment {
//
// /**
// * Views
// */
// private EditText passwordInputOne;
// private EditText passwordInputTwo;
//
// @Override
// public View onCreateView(LayoutInflater inflater, ViewGroup container,
// Bundle savedInstanceState) {
// // Inflate the layout for this fragment
// View view = inflater.inflate(R.layout.fragment_intro_page_four, container, false);
//
// setView(view);
//
// return view;
// }
//
// /**
// * Sets the view.
// * @param _view Fragment view.
// */
// private void setView(View _view) {
// this.passwordInputOne = (EditText) _view.findViewById(R.id.intro_four_passwort_one);
// this.passwordInputTwo = (EditText) _view.findViewById(R.id.intro_four_passwort_two);
// }
//
// }
//
// Path: Susurrus/app/src/main/java/rocks/susurrus/susurrus/fragments/IntroPageOneFragment.java
// public class IntroPageOneFragment extends Fragment {
//
// private final String logIndictaor = "IntroPageOneFragment";
//
// private View rootView;
// private ViewGroup upperContainer;
// private ImageView logo;
//
// @Override
// public View onCreateView(LayoutInflater inflater, ViewGroup container,
// Bundle savedInstanceState) {
// // Inflate the layout for this fragment
// rootView = inflater.inflate(R.layout.fragment_intro_page_one, container, false);
//
// return rootView;
// }
//
// @Override
// public void onViewCreated(View view, Bundle savedInstanceState) {
// super.onViewCreated(view, savedInstanceState);
//
// setLayout(view);
// //startAnimation();
// }
//
//
// private void setLayout(View view) {
// //upperContainer = (ViewGroup) view.findViewById(R.id.upper_container);
// //logo = (ImageView) view.findViewById(R.id.logo);
// }
//
// private void startAnimation() {
// logo.setVisibility(View.INVISIBLE);
// }
//
// }
//
// Path: Susurrus/app/src/main/java/rocks/susurrus/susurrus/fragments/IntroPageThreeFragment.java
// public class IntroPageThreeFragment extends Fragment {
//
// /**
// * Views
// */
// EditText inputName;
// ImageButton buttonRandomName;
//
//
// public IntroPageThreeFragment() {
// // Required empty public constructor
// }
//
// @Override
// public View onCreateView(LayoutInflater inflater, ViewGroup container,
// Bundle savedInstanceState) {
// // Inflate the layout for this fragment
// View view = inflater.inflate(R.layout.fragment_intro_page_three, container, false);
//
// setView(view);
// insertRandomName();
//
// return view;
// }
//
// /**
// * Set all view elements.
// * @param _view Fragment view.
// */
// private void setView(View _view) {
// // get views
// this.inputName = (EditText) _view.findViewById(R.id.username_input_name);
// this.buttonRandomName = (ImageButton) _view.findViewById(R.id.username_refresh_button);
//
// // set listeners
// this.buttonRandomName.setOnClickListener(this.randomListener);
// }
//
// /**
// * Helper method for inserting a random name into username input-field.
// */
// private void insertRandomName() {
// // get a random name & set it
// RandomName randName = new RandomName(getActivity());
// inputName.setText(randName.generate());
// }
//
// /**
// * OnClickListener: buttonRandomName.
// * Refreshes the random name.
// */
// private View.OnClickListener randomListener = new View.OnClickListener() {
// @Override
// public void onClick(View v) {
// insertRandomName();
// }
// };
//
// }
//
// Path: Susurrus/app/src/main/java/rocks/susurrus/susurrus/fragments/IntroPageTwoFragment.java
// public class IntroPageTwoFragment extends Fragment {
//
// @Override
// public View onCreateView(LayoutInflater inflater, ViewGroup container,
// Bundle savedInstanceState) {
// // Inflate the layout for this fragment
// return inflater.inflate(R.layout.fragment_intro_page_two, container, false);
// }
//
// private void checkWifiDirect() {
//
// }
//
// private void checkHotspot() {
//
// }
//
// }
// Path: Susurrus/app/src/main/java/rocks/susurrus/susurrus/views/adapters/IntroPageAdapter.java
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentStatePagerAdapter;
import java.util.ArrayList;
import rocks.susurrus.susurrus.fragments.IntroPageFourFragment;
import rocks.susurrus.susurrus.fragments.IntroPageOneFragment;
import rocks.susurrus.susurrus.fragments.IntroPageThreeFragment;
import rocks.susurrus.susurrus.fragments.IntroPageTwoFragment;
package rocks.susurrus.susurrus.views.adapters;
/**
* Created by simon on 01.05.15.
*/
public class IntroPageAdapter extends FragmentStatePagerAdapter {
/**
* Intro page count
*/
final static int NUM_PAGES = 4;
/**
* Constructor
* @param fm
*/
public IntroPageAdapter(FragmentManager fm) {
super(fm);
}
@Override
public Fragment getItem(int position) {
// for each different position, return another fragment with different layout
switch(position) {
case 0:
Fragment fragmentOne = new IntroPageOneFragment();
return fragmentOne;
case 1:
Fragment fragmentTwo = new IntroPageTwoFragment();
return fragmentTwo;
case 2:
Fragment fragmentThree = new IntroPageThreeFragment();
return fragmentThree;
case 3: | Fragment fragmentFour = new IntroPageFourFragment(); |
deshi-basara/susurrus-android-app | Susurrus/app/src/main/java/rocks/susurrus/susurrus/utils/Crypto.java | // Path: Susurrus/app/src/main/java/rocks/susurrus/susurrus/models/EncryptionModel.java
// public class EncryptionModel implements Serializable {
//
// /**
// * Data
// */
// private SealedObject sealedObject;
// private byte[] wrappedKey;
//
// public EncryptionModel(SealedObject _sealedObject, byte[] _wrappedKey) {
// this.sealedObject = _sealedObject;
// this.wrappedKey = _wrappedKey;
// }
//
// public SealedObject getSealedObject() {
// return this.sealedObject;
// }
// public byte[] getWrappedKey() {
// return this.wrappedKey;
// }
//
// }
| import android.util.Base64;
import java.io.IOException;
import java.io.Serializable;
import java.lang.reflect.Array;
import java.security.InvalidKeyException;
import java.security.Key;
import java.security.KeyFactory;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.NoSuchAlgorithmException;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.SecureRandom;
import java.security.spec.InvalidKeySpecException;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.KeyGenerator;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.SealedObject;
import javax.crypto.SecretKey;
import rocks.susurrus.susurrus.models.EncryptionModel; | public static PrivateKey privateStringToKey(String keyString) {
// convert back to bytes and construct an PKCS8EncodedKeySpec from it
byte[] keyBytes = Base64.decode(keyString, Base64.DEFAULT);
PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(keyBytes);
// obtain the publicKey
PrivateKey privateKey = null;
try {
KeyFactory generator = KeyFactory.getInstance(CRYPTO_ALGO);
privateKey = generator.generatePrivate(keySpec);
} catch(NoSuchAlgorithmException e) {
e.printStackTrace();
} catch(InvalidKeySpecException e) {
e.printStackTrace();
}
return privateKey;
}
/**
* Encrypts an unencrypted serializable Object with AES.
*
* At first an AES-Session-Key is generated for encrypting the handed SealedObject. The AES-
* Session-Key is wrapped with the user's publicKey. The wrapped-key can be used to decrypt
* the SealedObject later.
*
* @param _unencryptedObj Serializable object.
* @param _publicKey The user's publicKey.
* @return An EncryptionModel with SealedObject and wrapped-Key.
*/ | // Path: Susurrus/app/src/main/java/rocks/susurrus/susurrus/models/EncryptionModel.java
// public class EncryptionModel implements Serializable {
//
// /**
// * Data
// */
// private SealedObject sealedObject;
// private byte[] wrappedKey;
//
// public EncryptionModel(SealedObject _sealedObject, byte[] _wrappedKey) {
// this.sealedObject = _sealedObject;
// this.wrappedKey = _wrappedKey;
// }
//
// public SealedObject getSealedObject() {
// return this.sealedObject;
// }
// public byte[] getWrappedKey() {
// return this.wrappedKey;
// }
//
// }
// Path: Susurrus/app/src/main/java/rocks/susurrus/susurrus/utils/Crypto.java
import android.util.Base64;
import java.io.IOException;
import java.io.Serializable;
import java.lang.reflect.Array;
import java.security.InvalidKeyException;
import java.security.Key;
import java.security.KeyFactory;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.NoSuchAlgorithmException;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.SecureRandom;
import java.security.spec.InvalidKeySpecException;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.KeyGenerator;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.SealedObject;
import javax.crypto.SecretKey;
import rocks.susurrus.susurrus.models.EncryptionModel;
public static PrivateKey privateStringToKey(String keyString) {
// convert back to bytes and construct an PKCS8EncodedKeySpec from it
byte[] keyBytes = Base64.decode(keyString, Base64.DEFAULT);
PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(keyBytes);
// obtain the publicKey
PrivateKey privateKey = null;
try {
KeyFactory generator = KeyFactory.getInstance(CRYPTO_ALGO);
privateKey = generator.generatePrivate(keySpec);
} catch(NoSuchAlgorithmException e) {
e.printStackTrace();
} catch(InvalidKeySpecException e) {
e.printStackTrace();
}
return privateKey;
}
/**
* Encrypts an unencrypted serializable Object with AES.
*
* At first an AES-Session-Key is generated for encrypting the handed SealedObject. The AES-
* Session-Key is wrapped with the user's publicKey. The wrapped-key can be used to decrypt
* the SealedObject later.
*
* @param _unencryptedObj Serializable object.
* @param _publicKey The user's publicKey.
* @return An EncryptionModel with SealedObject and wrapped-Key.
*/ | public static EncryptionModel encryptBytes(Serializable _unencryptedObj, |
rundeck-plugins/salt-step | src/test/java/org/rundeck/plugin/salt/SaltApiNodeStepPlugin_SubmitSaltJobTest.java | // Path: src/main/java/org/rundeck/plugin/salt/output/SaltApiResponseOutput.java
// public class SaltApiResponseOutput {
// protected String jid;
// protected List<String> minions;
//
// public String getJid() {
// return jid;
// }
//
// public List<String> getMinions() {
// return minions == null ? Collections.<String>emptyList() : Collections.unmodifiableList(minions);
// }
// }
| import org.apache.http.HttpStatus;
import org.apache.http.NameValuePair;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.mockito.ArgumentCaptor;
import org.mockito.Mockito;
import org.rundeck.plugin.salt.output.SaltApiResponseOutput;
import org.rundeck.plugin.salt.version.SaltInteractionHandler;
import com.google.common.base.Predicate;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableSet;
import java.util.List;
import java.util.Set;
import org.apache.http.HttpException; | setupResponseCode(post, HttpStatus.SC_ACCEPTED);
String arg1 = "sdf%33&";
String arg2 = "adsf asdf";
plugin.function = String.format("%s \"%s\" \"%s\"", PARAM_FUNCTION, arg1, arg2);
Assert.assertEquals("Expected mocked jid after submitting job", OUTPUT_JID,
plugin.submitJob(latestCapability, client, AUTH_TOKEN, PARAM_MINION_NAME, ImmutableSet.<String> of()));
assertThatSubmitSaltJobAttemptedSuccessfully("fun=%s&tgt=%s&arg=%s&arg=%s", PARAM_FUNCTION, PARAM_MINION_NAME,
arg1, arg2);
}
@Test
public void testSubmitJobResponseCodeError() throws Exception {
setupResponseCode(post, HttpStatus.SC_TEMPORARY_REDIRECT);
try {
plugin.submitJob(latestCapability, client, AUTH_TOKEN, PARAM_MINION_NAME, ImmutableSet.<String> of());
Assert.fail("Expected http exception due to bad response code.");
}
catch (HttpException e) {
// expected
}
assertThatSubmitSaltJobAttemptedSuccessfully();
}
@Test
public void testSubmitJobNoMinionsMatched() throws Exception { | // Path: src/main/java/org/rundeck/plugin/salt/output/SaltApiResponseOutput.java
// public class SaltApiResponseOutput {
// protected String jid;
// protected List<String> minions;
//
// public String getJid() {
// return jid;
// }
//
// public List<String> getMinions() {
// return minions == null ? Collections.<String>emptyList() : Collections.unmodifiableList(minions);
// }
// }
// Path: src/test/java/org/rundeck/plugin/salt/SaltApiNodeStepPlugin_SubmitSaltJobTest.java
import org.apache.http.HttpStatus;
import org.apache.http.NameValuePair;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.mockito.ArgumentCaptor;
import org.mockito.Mockito;
import org.rundeck.plugin.salt.output.SaltApiResponseOutput;
import org.rundeck.plugin.salt.version.SaltInteractionHandler;
import com.google.common.base.Predicate;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableSet;
import java.util.List;
import java.util.Set;
import org.apache.http.HttpException;
setupResponseCode(post, HttpStatus.SC_ACCEPTED);
String arg1 = "sdf%33&";
String arg2 = "adsf asdf";
plugin.function = String.format("%s \"%s\" \"%s\"", PARAM_FUNCTION, arg1, arg2);
Assert.assertEquals("Expected mocked jid after submitting job", OUTPUT_JID,
plugin.submitJob(latestCapability, client, AUTH_TOKEN, PARAM_MINION_NAME, ImmutableSet.<String> of()));
assertThatSubmitSaltJobAttemptedSuccessfully("fun=%s&tgt=%s&arg=%s&arg=%s", PARAM_FUNCTION, PARAM_MINION_NAME,
arg1, arg2);
}
@Test
public void testSubmitJobResponseCodeError() throws Exception {
setupResponseCode(post, HttpStatus.SC_TEMPORARY_REDIRECT);
try {
plugin.submitJob(latestCapability, client, AUTH_TOKEN, PARAM_MINION_NAME, ImmutableSet.<String> of());
Assert.fail("Expected http exception due to bad response code.");
}
catch (HttpException e) {
// expected
}
assertThatSubmitSaltJobAttemptedSuccessfully();
}
@Test
public void testSubmitJobNoMinionsMatched() throws Exception { | SaltApiResponseOutput response = new SaltApiResponseOutput(); |
rundeck-plugins/salt-step | src/test/java/org/rundeck/plugin/salt/output/DefaultSaltReturnHandlerTest.java | // Path: src/main/java/org/rundeck/plugin/salt/output/DefaultSaltReturnHandler.java
// @Component
// public class DefaultSaltReturnHandler implements SaltReturnHandler {
//
// protected Integer exitCode;
//
// public DefaultSaltReturnHandler() {
// this(0);
// }
//
// @Autowired
// public DefaultSaltReturnHandler(@Value("${defaultSaltReturner.exitCode}") Integer exitCode) {
// setExitCode(exitCode);
// }
//
// public void setExitCode(Integer exitCode) {
// this.exitCode = exitCode;
// }
//
// @Override
// public SaltReturnResponse extractResponse(String rawResponse) throws SaltReturnResponseParseException {
// SaltReturnResponse response = new SaltReturnResponse();
// response.setExitCode(exitCode);
// if (rawResponse != null) {
// response.addOutput(rawResponse);
// }
// return response;
// }
// }
//
// Path: src/main/java/org/rundeck/plugin/salt/output/SaltReturnHandler.java
// public interface SaltReturnHandler {
// /**
// * Deserializes a {@link SaltReturnResponse} from a salt minion response.
// *
// * @param rawResponse
// * a minion's response.
// *
// * @throws SaltReturnResponseParseException
// * if there was an error interpreting the response
// */
// SaltReturnResponse extractResponse(String rawResponse) throws SaltReturnResponseParseException;
// }
| import org.rundeck.plugin.salt.output.SaltReturnResponse;
import org.junit.Assert;
import org.junit.Test;
import org.rundeck.plugin.salt.output.DefaultSaltReturnHandler;
import org.rundeck.plugin.salt.output.SaltReturnHandler; | /**
* Copyright (c) 2013, salesforce.com, inc.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification, are permitted provided
* that the following conditions are met:
*
* Redistributions of source code must retain the above copyright notice, this list of conditions and the
* following disclaimer.
*
* Redistributions in binary form must reproduce the above copyright notice, this list of conditions and
* the following disclaimer in the documentation and/or other materials provided with the distribution.
*
* Neither the name of salesforce.com, inc. nor the names of its contributors may be used to endorse or
* promote products derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
* PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED
* TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
package org.rundeck.plugin.salt.output;
public class DefaultSaltReturnHandlerTest {
@Test
public void testConstructor() { | // Path: src/main/java/org/rundeck/plugin/salt/output/DefaultSaltReturnHandler.java
// @Component
// public class DefaultSaltReturnHandler implements SaltReturnHandler {
//
// protected Integer exitCode;
//
// public DefaultSaltReturnHandler() {
// this(0);
// }
//
// @Autowired
// public DefaultSaltReturnHandler(@Value("${defaultSaltReturner.exitCode}") Integer exitCode) {
// setExitCode(exitCode);
// }
//
// public void setExitCode(Integer exitCode) {
// this.exitCode = exitCode;
// }
//
// @Override
// public SaltReturnResponse extractResponse(String rawResponse) throws SaltReturnResponseParseException {
// SaltReturnResponse response = new SaltReturnResponse();
// response.setExitCode(exitCode);
// if (rawResponse != null) {
// response.addOutput(rawResponse);
// }
// return response;
// }
// }
//
// Path: src/main/java/org/rundeck/plugin/salt/output/SaltReturnHandler.java
// public interface SaltReturnHandler {
// /**
// * Deserializes a {@link SaltReturnResponse} from a salt minion response.
// *
// * @param rawResponse
// * a minion's response.
// *
// * @throws SaltReturnResponseParseException
// * if there was an error interpreting the response
// */
// SaltReturnResponse extractResponse(String rawResponse) throws SaltReturnResponseParseException;
// }
// Path: src/test/java/org/rundeck/plugin/salt/output/DefaultSaltReturnHandlerTest.java
import org.rundeck.plugin.salt.output.SaltReturnResponse;
import org.junit.Assert;
import org.junit.Test;
import org.rundeck.plugin.salt.output.DefaultSaltReturnHandler;
import org.rundeck.plugin.salt.output.SaltReturnHandler;
/**
* Copyright (c) 2013, salesforce.com, inc.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification, are permitted provided
* that the following conditions are met:
*
* Redistributions of source code must retain the above copyright notice, this list of conditions and the
* following disclaimer.
*
* Redistributions in binary form must reproduce the above copyright notice, this list of conditions and
* the following disclaimer in the documentation and/or other materials provided with the distribution.
*
* Neither the name of salesforce.com, inc. nor the names of its contributors may be used to endorse or
* promote products derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
* PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED
* TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
package org.rundeck.plugin.salt.output;
public class DefaultSaltReturnHandlerTest {
@Test
public void testConstructor() { | DefaultSaltReturnHandler handler = new DefaultSaltReturnHandler(); |
rundeck-plugins/salt-step | src/test/java/org/rundeck/plugin/salt/output/DefaultSaltReturnHandlerTest.java | // Path: src/main/java/org/rundeck/plugin/salt/output/DefaultSaltReturnHandler.java
// @Component
// public class DefaultSaltReturnHandler implements SaltReturnHandler {
//
// protected Integer exitCode;
//
// public DefaultSaltReturnHandler() {
// this(0);
// }
//
// @Autowired
// public DefaultSaltReturnHandler(@Value("${defaultSaltReturner.exitCode}") Integer exitCode) {
// setExitCode(exitCode);
// }
//
// public void setExitCode(Integer exitCode) {
// this.exitCode = exitCode;
// }
//
// @Override
// public SaltReturnResponse extractResponse(String rawResponse) throws SaltReturnResponseParseException {
// SaltReturnResponse response = new SaltReturnResponse();
// response.setExitCode(exitCode);
// if (rawResponse != null) {
// response.addOutput(rawResponse);
// }
// return response;
// }
// }
//
// Path: src/main/java/org/rundeck/plugin/salt/output/SaltReturnHandler.java
// public interface SaltReturnHandler {
// /**
// * Deserializes a {@link SaltReturnResponse} from a salt minion response.
// *
// * @param rawResponse
// * a minion's response.
// *
// * @throws SaltReturnResponseParseException
// * if there was an error interpreting the response
// */
// SaltReturnResponse extractResponse(String rawResponse) throws SaltReturnResponseParseException;
// }
| import org.rundeck.plugin.salt.output.SaltReturnResponse;
import org.junit.Assert;
import org.junit.Test;
import org.rundeck.plugin.salt.output.DefaultSaltReturnHandler;
import org.rundeck.plugin.salt.output.SaltReturnHandler; | /**
* Copyright (c) 2013, salesforce.com, inc.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification, are permitted provided
* that the following conditions are met:
*
* Redistributions of source code must retain the above copyright notice, this list of conditions and the
* following disclaimer.
*
* Redistributions in binary form must reproduce the above copyright notice, this list of conditions and
* the following disclaimer in the documentation and/or other materials provided with the distribution.
*
* Neither the name of salesforce.com, inc. nor the names of its contributors may be used to endorse or
* promote products derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
* PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED
* TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
package org.rundeck.plugin.salt.output;
public class DefaultSaltReturnHandlerTest {
@Test
public void testConstructor() {
DefaultSaltReturnHandler handler = new DefaultSaltReturnHandler();
Assert.assertEquals("Didn't get default response code", 0, handler.exitCode.intValue());
}
@Test
public void testConstructorExitCode() {
Integer exitCode = 127;
DefaultSaltReturnHandler handler = new DefaultSaltReturnHandler(exitCode);
Assert.assertEquals("Didn't get passed in response code", exitCode, handler.exitCode);
}
@Test
public void testSetExitCode() {
Integer exitCode = 127;
DefaultSaltReturnHandler handler = new DefaultSaltReturnHandler();
handler.setExitCode(exitCode);
Assert.assertEquals("Didn't get explicity set response code", exitCode, handler.exitCode);
}
@Test
public void testExtractResponse() { | // Path: src/main/java/org/rundeck/plugin/salt/output/DefaultSaltReturnHandler.java
// @Component
// public class DefaultSaltReturnHandler implements SaltReturnHandler {
//
// protected Integer exitCode;
//
// public DefaultSaltReturnHandler() {
// this(0);
// }
//
// @Autowired
// public DefaultSaltReturnHandler(@Value("${defaultSaltReturner.exitCode}") Integer exitCode) {
// setExitCode(exitCode);
// }
//
// public void setExitCode(Integer exitCode) {
// this.exitCode = exitCode;
// }
//
// @Override
// public SaltReturnResponse extractResponse(String rawResponse) throws SaltReturnResponseParseException {
// SaltReturnResponse response = new SaltReturnResponse();
// response.setExitCode(exitCode);
// if (rawResponse != null) {
// response.addOutput(rawResponse);
// }
// return response;
// }
// }
//
// Path: src/main/java/org/rundeck/plugin/salt/output/SaltReturnHandler.java
// public interface SaltReturnHandler {
// /**
// * Deserializes a {@link SaltReturnResponse} from a salt minion response.
// *
// * @param rawResponse
// * a minion's response.
// *
// * @throws SaltReturnResponseParseException
// * if there was an error interpreting the response
// */
// SaltReturnResponse extractResponse(String rawResponse) throws SaltReturnResponseParseException;
// }
// Path: src/test/java/org/rundeck/plugin/salt/output/DefaultSaltReturnHandlerTest.java
import org.rundeck.plugin.salt.output.SaltReturnResponse;
import org.junit.Assert;
import org.junit.Test;
import org.rundeck.plugin.salt.output.DefaultSaltReturnHandler;
import org.rundeck.plugin.salt.output.SaltReturnHandler;
/**
* Copyright (c) 2013, salesforce.com, inc.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification, are permitted provided
* that the following conditions are met:
*
* Redistributions of source code must retain the above copyright notice, this list of conditions and the
* following disclaimer.
*
* Redistributions in binary form must reproduce the above copyright notice, this list of conditions and
* the following disclaimer in the documentation and/or other materials provided with the distribution.
*
* Neither the name of salesforce.com, inc. nor the names of its contributors may be used to endorse or
* promote products derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
* PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED
* TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
package org.rundeck.plugin.salt.output;
public class DefaultSaltReturnHandlerTest {
@Test
public void testConstructor() {
DefaultSaltReturnHandler handler = new DefaultSaltReturnHandler();
Assert.assertEquals("Didn't get default response code", 0, handler.exitCode.intValue());
}
@Test
public void testConstructorExitCode() {
Integer exitCode = 127;
DefaultSaltReturnHandler handler = new DefaultSaltReturnHandler(exitCode);
Assert.assertEquals("Didn't get passed in response code", exitCode, handler.exitCode);
}
@Test
public void testSetExitCode() {
Integer exitCode = 127;
DefaultSaltReturnHandler handler = new DefaultSaltReturnHandler();
handler.setExitCode(exitCode);
Assert.assertEquals("Didn't get explicity set response code", exitCode, handler.exitCode);
}
@Test
public void testExtractResponse() { | SaltReturnHandler handler = new DefaultSaltReturnHandler(); |
rundeck-plugins/salt-step | src/test/java/org/rundeck/plugin/salt/version/Pre082SaltInteractionHandlerTest.java | // Path: src/main/java/org/rundeck/plugin/salt/output/SaltApiResponseOutput.java
// public class SaltApiResponseOutput {
// protected String jid;
// protected List<String> minions;
//
// public String getJid() {
// return jid;
// }
//
// public List<String> getMinions() {
// return minions == null ? Collections.<String>emptyList() : Collections.unmodifiableList(minions);
// }
// }
| import org.junit.Assert;
import org.junit.Test;
import org.rundeck.plugin.salt.SaltApiException;
import org.rundeck.plugin.salt.output.SaltApiResponseOutput; | package org.rundeck.plugin.salt.version;
public class Pre082SaltInteractionHandlerTest {
protected SaltInteractionHandler handler = new Pre082SaltInteractionHandler();
@Test
public void testExtractOutputForJobSubmissionResponse() throws Exception {
String jid = "20130903200912838566";
String host1 = "host1";
String host2 = "host2";
String template = "[{\"return\": {\"jid\": \"%s\", \"minions\": [\"%s\", \"%s\"]}}]";
String response = String.format(template, jid, host1, host2); | // Path: src/main/java/org/rundeck/plugin/salt/output/SaltApiResponseOutput.java
// public class SaltApiResponseOutput {
// protected String jid;
// protected List<String> minions;
//
// public String getJid() {
// return jid;
// }
//
// public List<String> getMinions() {
// return minions == null ? Collections.<String>emptyList() : Collections.unmodifiableList(minions);
// }
// }
// Path: src/test/java/org/rundeck/plugin/salt/version/Pre082SaltInteractionHandlerTest.java
import org.junit.Assert;
import org.junit.Test;
import org.rundeck.plugin.salt.SaltApiException;
import org.rundeck.plugin.salt.output.SaltApiResponseOutput;
package org.rundeck.plugin.salt.version;
public class Pre082SaltInteractionHandlerTest {
protected SaltInteractionHandler handler = new Pre082SaltInteractionHandler();
@Test
public void testExtractOutputForJobSubmissionResponse() throws Exception {
String jid = "20130903200912838566";
String host1 = "host1";
String host2 = "host2";
String template = "[{\"return\": {\"jid\": \"%s\", \"minions\": [\"%s\", \"%s\"]}}]";
String response = String.format(template, jid, host1, host2); | SaltApiResponseOutput output = handler.extractOutputForJobSubmissionResponse(response); |
rundeck-plugins/salt-step | src/test/java/org/rundeck/plugin/salt/validation/ValidatorsTest.java | // Path: src/main/java/org/rundeck/plugin/salt/SaltApiNodeStepPlugin.java
// public enum SaltApiNodeStepFailureReason implements FailureReason {
// EXIT_CODE, ARGUMENTS_MISSING, ARGUMENTS_INVALID, AUTHENTICATION_FAILURE, COMMUNICATION_FAILURE, SALT_API_FAILURE, SALT_TARGET_MISMATCH, INTERRUPTED;
// }
| import org.rundeck.plugin.salt.SaltApiNodeStepPlugin.SaltApiNodeStepFailureReason;
import com.dtolabs.rundeck.core.common.INodeEntry;
import com.dtolabs.rundeck.core.execution.workflow.steps.FailureReason;
import com.dtolabs.rundeck.core.execution.workflow.steps.node.NodeStepException;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.mockito.Mockito; | /**
* Copyright (c) 2013, salesforce.com, inc.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification, are permitted provided
* that the following conditions are met:
*
* Redistributions of source code must retain the above copyright notice, this list of conditions and the
* following disclaimer.
*
* Redistributions in binary form must reproduce the above copyright notice, this list of conditions and
* the following disclaimer in the documentation and/or other materials provided with the distribution.
*
* Neither the name of salesforce.com, inc. nor the names of its contributors may be used to endorse or
* promote products derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
* PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED
* TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
package org.rundeck.plugin.salt.validation;
public class ValidatorsTest {
protected String NODE_NAME = "node";
protected INodeEntry entry;
@Before
public void setup() {
entry = Mockito.mock(INodeEntry.class);
Mockito.when(entry.getNodename()).thenReturn(NODE_NAME);
}
@Test
public void testCheckNotEmptyWithNullString() { | // Path: src/main/java/org/rundeck/plugin/salt/SaltApiNodeStepPlugin.java
// public enum SaltApiNodeStepFailureReason implements FailureReason {
// EXIT_CODE, ARGUMENTS_MISSING, ARGUMENTS_INVALID, AUTHENTICATION_FAILURE, COMMUNICATION_FAILURE, SALT_API_FAILURE, SALT_TARGET_MISMATCH, INTERRUPTED;
// }
// Path: src/test/java/org/rundeck/plugin/salt/validation/ValidatorsTest.java
import org.rundeck.plugin.salt.SaltApiNodeStepPlugin.SaltApiNodeStepFailureReason;
import com.dtolabs.rundeck.core.common.INodeEntry;
import com.dtolabs.rundeck.core.execution.workflow.steps.FailureReason;
import com.dtolabs.rundeck.core.execution.workflow.steps.node.NodeStepException;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.mockito.Mockito;
/**
* Copyright (c) 2013, salesforce.com, inc.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification, are permitted provided
* that the following conditions are met:
*
* Redistributions of source code must retain the above copyright notice, this list of conditions and the
* following disclaimer.
*
* Redistributions in binary form must reproduce the above copyright notice, this list of conditions and
* the following disclaimer in the documentation and/or other materials provided with the distribution.
*
* Neither the name of salesforce.com, inc. nor the names of its contributors may be used to endorse or
* promote products derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
* PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED
* TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
package org.rundeck.plugin.salt.validation;
public class ValidatorsTest {
protected String NODE_NAME = "node";
protected INodeEntry entry;
@Before
public void setup() {
entry = Mockito.mock(INodeEntry.class);
Mockito.when(entry.getNodename()).thenReturn(NODE_NAME);
}
@Test
public void testCheckNotEmptyWithNullString() { | FailureReason reason = SaltApiNodeStepFailureReason.ARGUMENTS_MISSING; |
rundeck-plugins/salt-step | src/test/java/org/rundeck/plugin/salt/SaltApiNodeStepPlugin_ExecuteTest.java | // Path: src/main/java/org/rundeck/plugin/salt/SaltApiNodeStepPlugin.java
// public enum SaltApiNodeStepFailureReason implements FailureReason {
// EXIT_CODE, ARGUMENTS_MISSING, ARGUMENTS_INVALID, AUTHENTICATION_FAILURE, COMMUNICATION_FAILURE, SALT_API_FAILURE, SALT_TARGET_MISMATCH, INTERRUPTED;
// }
| import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.mockito.InOrder;
import org.mockito.Mockito;
import org.rundeck.plugin.salt.SaltApiNodeStepPlugin.SaltApiNodeStepFailureReason;
import org.rundeck.plugin.salt.output.SaltReturnResponse;
import org.rundeck.plugin.salt.output.SaltReturnResponseParseException;
import org.rundeck.plugin.salt.validation.SaltStepValidationException;
import java.util.Set;
import com.dtolabs.rundeck.core.execution.workflow.steps.node.NodeStepException;
import com.google.common.collect.ImmutableSet;
import org.apache.http.HttpException;
import org.apache.http.client.HttpClient; | /**
* Copyright (c) 2013, salesforce.com, inc.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification, are permitted provided
* that the following conditions are met:
*
* Redistributions of source code must retain the above copyright notice, this list of conditions and the
* following disclaimer.
*
* Redistributions in binary form must reproduce the above copyright notice, this list of conditions and
* the following disclaimer in the documentation and/or other materials provided with the distribution.
*
* Neither the name of salesforce.com, inc. nor the names of its contributors may be used to endorse or
* promote products derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
* PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED
* TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
package org.rundeck.plugin.salt;
public class SaltApiNodeStepPlugin_ExecuteTest extends AbstractSaltApiNodeStepPluginTest {
@Before
public void setup() throws Exception {
spyPlugin();
}
@Test
public void testExecuteWithAuthenticationFailure() {
setupAuthenticate(null);
setupDoReturnJidWhenSubmitJob();
setupDoReturnHostResponseWhenWaitForResponse();
setupDoReturnSaltResponseWhenExtractResponse(0, new String[0], new String[0]);
try {
plugin.executeNodeStep(pluginContext, configuration, node);
Assert.fail("Expected authentication failure");
} catch (NodeStepException e) { | // Path: src/main/java/org/rundeck/plugin/salt/SaltApiNodeStepPlugin.java
// public enum SaltApiNodeStepFailureReason implements FailureReason {
// EXIT_CODE, ARGUMENTS_MISSING, ARGUMENTS_INVALID, AUTHENTICATION_FAILURE, COMMUNICATION_FAILURE, SALT_API_FAILURE, SALT_TARGET_MISMATCH, INTERRUPTED;
// }
// Path: src/test/java/org/rundeck/plugin/salt/SaltApiNodeStepPlugin_ExecuteTest.java
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.mockito.InOrder;
import org.mockito.Mockito;
import org.rundeck.plugin.salt.SaltApiNodeStepPlugin.SaltApiNodeStepFailureReason;
import org.rundeck.plugin.salt.output.SaltReturnResponse;
import org.rundeck.plugin.salt.output.SaltReturnResponseParseException;
import org.rundeck.plugin.salt.validation.SaltStepValidationException;
import java.util.Set;
import com.dtolabs.rundeck.core.execution.workflow.steps.node.NodeStepException;
import com.google.common.collect.ImmutableSet;
import org.apache.http.HttpException;
import org.apache.http.client.HttpClient;
/**
* Copyright (c) 2013, salesforce.com, inc.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification, are permitted provided
* that the following conditions are met:
*
* Redistributions of source code must retain the above copyright notice, this list of conditions and the
* following disclaimer.
*
* Redistributions in binary form must reproduce the above copyright notice, this list of conditions and
* the following disclaimer in the documentation and/or other materials provided with the distribution.
*
* Neither the name of salesforce.com, inc. nor the names of its contributors may be used to endorse or
* promote products derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
* PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED
* TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
package org.rundeck.plugin.salt;
public class SaltApiNodeStepPlugin_ExecuteTest extends AbstractSaltApiNodeStepPluginTest {
@Before
public void setup() throws Exception {
spyPlugin();
}
@Test
public void testExecuteWithAuthenticationFailure() {
setupAuthenticate(null);
setupDoReturnJidWhenSubmitJob();
setupDoReturnHostResponseWhenWaitForResponse();
setupDoReturnSaltResponseWhenExtractResponse(0, new String[0], new String[0]);
try {
plugin.executeNodeStep(pluginContext, configuration, node);
Assert.fail("Expected authentication failure");
} catch (NodeStepException e) { | Assert.assertEquals(SaltApiNodeStepFailureReason.AUTHENTICATION_FAILURE, e.getFailureReason()); |
rundeck-plugins/salt-step | src/main/java/org/rundeck/plugin/salt/version/Pre082SaltInteractionHandler.java | // Path: src/main/java/org/rundeck/plugin/salt/output/SaltApiResponseOutput.java
// public class SaltApiResponseOutput {
// protected String jid;
// protected List<String> minions;
//
// public String getJid() {
// return jid;
// }
//
// public List<String> getMinions() {
// return minions == null ? Collections.<String>emptyList() : Collections.unmodifiableList(minions);
// }
// }
| import java.lang.reflect.Type;
import java.util.List;
import java.util.Map;
import org.rundeck.plugin.salt.SaltApiException;
import org.rundeck.plugin.salt.output.SaltApiResponseOutput;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken; | package org.rundeck.plugin.salt.version;
/**
* The interaction handler responsible for dealing with salt-api responses pre
* 0.8.2
*
* Backwards incompatible end points: - POST to /minions
*/
public class Pre082SaltInteractionHandler implements SaltInteractionHandler {
protected static final String SALT_OUTPUT_RETURN_KEY = "return";
protected static final Type MINION_RESPONSE_TYPE = new TypeToken<List<Map<String, Object>>>() {}.getType();
@Override | // Path: src/main/java/org/rundeck/plugin/salt/output/SaltApiResponseOutput.java
// public class SaltApiResponseOutput {
// protected String jid;
// protected List<String> minions;
//
// public String getJid() {
// return jid;
// }
//
// public List<String> getMinions() {
// return minions == null ? Collections.<String>emptyList() : Collections.unmodifiableList(minions);
// }
// }
// Path: src/main/java/org/rundeck/plugin/salt/version/Pre082SaltInteractionHandler.java
import java.lang.reflect.Type;
import java.util.List;
import java.util.Map;
import org.rundeck.plugin.salt.SaltApiException;
import org.rundeck.plugin.salt.output.SaltApiResponseOutput;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
package org.rundeck.plugin.salt.version;
/**
* The interaction handler responsible for dealing with salt-api responses pre
* 0.8.2
*
* Backwards incompatible end points: - POST to /minions
*/
public class Pre082SaltInteractionHandler implements SaltInteractionHandler {
protected static final String SALT_OUTPUT_RETURN_KEY = "return";
protected static final Type MINION_RESPONSE_TYPE = new TypeToken<List<Map<String, Object>>>() {}.getType();
@Override | public SaltApiResponseOutput extractOutputForJobSubmissionResponse(String json) throws SaltApiException { |
rundeck-plugins/salt-step | src/test/java/org/rundeck/plugin/salt/SaltApiNodeStepPlugin_ValidationTest.java | // Path: src/main/java/org/rundeck/plugin/salt/SaltApiNodeStepPlugin.java
// public enum SaltApiNodeStepFailureReason implements FailureReason {
// EXIT_CODE, ARGUMENTS_MISSING, ARGUMENTS_INVALID, AUTHENTICATION_FAILURE, COMMUNICATION_FAILURE, SALT_API_FAILURE, SALT_TARGET_MISMATCH, INTERRUPTED;
// }
//
// Path: src/main/java/org/rundeck/plugin/salt/validation/Validators.java
// public class Validators {
//
// /**
// * Checks that the given propertyValue is not empty or null.
// *
// * @param propertyName The name of the property that is being checked
// * @param propertyValue The value of the property that is being checked.
// * @param reason A {@link com.dtolabs.rundeck.core.execution.workflow.steps.node.NodeStepFailure} for this this validation failure.
// * @param nodeName The node this node step is executing against.
// */
// public static void checkNotEmpty(String propertyName, String propertyValue, FailureReason reason, INodeEntry entry)
// throws SaltStepValidationException {
// if (StringUtils.isEmpty(propertyValue)) {
// throw new SaltStepValidationException(propertyName, String.format("%s is a required property.",
// propertyName), reason, entry.getNodename());
// }
// }
// }
| import org.powermock.api.mockito.PowerMockito;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.PowerMockRunner;
import org.rundeck.plugin.salt.SaltApiNodeStepPlugin.SaltApiNodeStepFailureReason;
import org.rundeck.plugin.salt.validation.SaltStepValidationException;
import org.rundeck.plugin.salt.validation.Validators;
import com.dtolabs.rundeck.core.execution.workflow.steps.node.NodeStepException;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mockito; | /**
* Copyright (c) 2013, salesforce.com, inc.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification, are permitted provided
* that the following conditions are met:
*
* Redistributions of source code must retain the above copyright notice, this list of conditions and the
* following disclaimer.
*
* Redistributions in binary form must reproduce the above copyright notice, this list of conditions and
* the following disclaimer in the documentation and/or other materials provided with the distribution.
*
* Neither the name of salesforce.com, inc. nor the names of its contributors may be used to endorse or
* promote products derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
* PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED
* TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
package org.rundeck.plugin.salt;
@RunWith(PowerMockRunner.class)
@PrepareForTest(Validators.class)
public class SaltApiNodeStepPlugin_ValidationTest extends AbstractSaltApiNodeStepPluginTest {
@Test
public void testValidateAllArguments() throws SaltStepValidationException {
PowerMockito.mockStatic(Validators.class);
PowerMockito.doNothing().when(Validators.class);
Validators.checkNotEmpty(Mockito.anyString(), Mockito.anyString(), | // Path: src/main/java/org/rundeck/plugin/salt/SaltApiNodeStepPlugin.java
// public enum SaltApiNodeStepFailureReason implements FailureReason {
// EXIT_CODE, ARGUMENTS_MISSING, ARGUMENTS_INVALID, AUTHENTICATION_FAILURE, COMMUNICATION_FAILURE, SALT_API_FAILURE, SALT_TARGET_MISMATCH, INTERRUPTED;
// }
//
// Path: src/main/java/org/rundeck/plugin/salt/validation/Validators.java
// public class Validators {
//
// /**
// * Checks that the given propertyValue is not empty or null.
// *
// * @param propertyName The name of the property that is being checked
// * @param propertyValue The value of the property that is being checked.
// * @param reason A {@link com.dtolabs.rundeck.core.execution.workflow.steps.node.NodeStepFailure} for this this validation failure.
// * @param nodeName The node this node step is executing against.
// */
// public static void checkNotEmpty(String propertyName, String propertyValue, FailureReason reason, INodeEntry entry)
// throws SaltStepValidationException {
// if (StringUtils.isEmpty(propertyValue)) {
// throw new SaltStepValidationException(propertyName, String.format("%s is a required property.",
// propertyName), reason, entry.getNodename());
// }
// }
// }
// Path: src/test/java/org/rundeck/plugin/salt/SaltApiNodeStepPlugin_ValidationTest.java
import org.powermock.api.mockito.PowerMockito;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.PowerMockRunner;
import org.rundeck.plugin.salt.SaltApiNodeStepPlugin.SaltApiNodeStepFailureReason;
import org.rundeck.plugin.salt.validation.SaltStepValidationException;
import org.rundeck.plugin.salt.validation.Validators;
import com.dtolabs.rundeck.core.execution.workflow.steps.node.NodeStepException;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mockito;
/**
* Copyright (c) 2013, salesforce.com, inc.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification, are permitted provided
* that the following conditions are met:
*
* Redistributions of source code must retain the above copyright notice, this list of conditions and the
* following disclaimer.
*
* Redistributions in binary form must reproduce the above copyright notice, this list of conditions and
* the following disclaimer in the documentation and/or other materials provided with the distribution.
*
* Neither the name of salesforce.com, inc. nor the names of its contributors may be used to endorse or
* promote products derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
* PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED
* TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
package org.rundeck.plugin.salt;
@RunWith(PowerMockRunner.class)
@PrepareForTest(Validators.class)
public class SaltApiNodeStepPlugin_ValidationTest extends AbstractSaltApiNodeStepPluginTest {
@Test
public void testValidateAllArguments() throws SaltStepValidationException {
PowerMockito.mockStatic(Validators.class);
PowerMockito.doNothing().when(Validators.class);
Validators.checkNotEmpty(Mockito.anyString(), Mockito.anyString(), | Mockito.any(SaltApiNodeStepFailureReason.class), Mockito.same(node)); |
rundeck-plugins/salt-step | src/main/java/org/rundeck/plugin/salt/version/SaltApiVersionCapabilityRegistry.java | // Path: src/main/java/org/rundeck/plugin/salt/version/SaltApiCapability.java
// public static class Builder {
// SaltApiCapability origin = new SaltApiCapability();
//
// public static Builder from(SaltApiCapability capability) {
// Builder builder = new Builder();
// try {
// builder.origin = (SaltApiCapability) capability.clone();
// } catch (CloneNotSupportedException e) {
// throw new RuntimeException(e);
// }
// return builder;
// }
//
// public Builder withId(String id) {
// origin.id = id;
// return this;
// }
//
// public Builder withLoginFailureResponseCode(int newLoginFailureResponseCode) {
// origin.loginFailureResponseCode = newLoginFailureResponseCode;
// return this;
// }
//
// public Builder withLoginSuccessResponseCode(int newLoginSuccessResponseCode) {
// origin.loginSuccessResponseCode = newLoginSuccessResponseCode;
// return this;
// }
//
// public Builder supportsLogout() {
// origin.supportsLogout = true;
// return this;
// }
//
// public Builder withSaltInteractionHandler(SaltInteractionHandler interactionHandler) {
// origin.interactionHandler = interactionHandler;
// return this;
// }
//
// public SaltApiCapability build() {
// return origin;
// }
// }
| import org.rundeck.plugin.salt.version.SaltApiCapability.Builder;
import org.springframework.stereotype.Component;
import com.google.common.collect.Maps;
import java.util.Comparator;
import java.util.SortedMap;
import org.apache.http.HttpStatus; | /**
* Copyright (c) 2013, salesforce.com, inc.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification, are permitted provided
* that the following conditions are met:
*
* Redistributions of source code must retain the above copyright notice, this list of conditions and the
* following disclaimer.
*
* Redistributions in binary form must reproduce the above copyright notice, this list of conditions and
* the following disclaimer in the documentation and/or other materials provided with the distribution.
*
* Neither the name of salesforce.com, inc. nor the names of its contributors may be used to endorse or
* promote products derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
* PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED
* TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
package org.rundeck.plugin.salt.version;
/**
* Central management for different versions of salt-api
*/
@Component
public class SaltApiVersionCapabilityRegistry { | // Path: src/main/java/org/rundeck/plugin/salt/version/SaltApiCapability.java
// public static class Builder {
// SaltApiCapability origin = new SaltApiCapability();
//
// public static Builder from(SaltApiCapability capability) {
// Builder builder = new Builder();
// try {
// builder.origin = (SaltApiCapability) capability.clone();
// } catch (CloneNotSupportedException e) {
// throw new RuntimeException(e);
// }
// return builder;
// }
//
// public Builder withId(String id) {
// origin.id = id;
// return this;
// }
//
// public Builder withLoginFailureResponseCode(int newLoginFailureResponseCode) {
// origin.loginFailureResponseCode = newLoginFailureResponseCode;
// return this;
// }
//
// public Builder withLoginSuccessResponseCode(int newLoginSuccessResponseCode) {
// origin.loginSuccessResponseCode = newLoginSuccessResponseCode;
// return this;
// }
//
// public Builder supportsLogout() {
// origin.supportsLogout = true;
// return this;
// }
//
// public Builder withSaltInteractionHandler(SaltInteractionHandler interactionHandler) {
// origin.interactionHandler = interactionHandler;
// return this;
// }
//
// public SaltApiCapability build() {
// return origin;
// }
// }
// Path: src/main/java/org/rundeck/plugin/salt/version/SaltApiVersionCapabilityRegistry.java
import org.rundeck.plugin.salt.version.SaltApiCapability.Builder;
import org.springframework.stereotype.Component;
import com.google.common.collect.Maps;
import java.util.Comparator;
import java.util.SortedMap;
import org.apache.http.HttpStatus;
/**
* Copyright (c) 2013, salesforce.com, inc.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification, are permitted provided
* that the following conditions are met:
*
* Redistributions of source code must retain the above copyright notice, this list of conditions and the
* following disclaimer.
*
* Redistributions in binary form must reproduce the above copyright notice, this list of conditions and
* the following disclaimer in the documentation and/or other materials provided with the distribution.
*
* Neither the name of salesforce.com, inc. nor the names of its contributors may be used to endorse or
* promote products derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
* PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED
* TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
package org.rundeck.plugin.salt.version;
/**
* Central management for different versions of salt-api
*/
@Component
public class SaltApiVersionCapabilityRegistry { | public static final SaltApiCapability VERSION_0_7_5 = new SaltApiCapability.Builder() |
rundeck-plugins/salt-step | src/main/java/org/rundeck/plugin/salt/version/LatestSaltInteractionHandler.java | // Path: src/main/java/org/rundeck/plugin/salt/output/SaltApiResponseOutput.java
// public class SaltApiResponseOutput {
// protected String jid;
// protected List<String> minions;
//
// public String getJid() {
// return jid;
// }
//
// public List<String> getMinions() {
// return minions == null ? Collections.<String>emptyList() : Collections.unmodifiableList(minions);
// }
// }
| import java.lang.reflect.Type;
import java.util.List;
import java.util.Map;
import org.rundeck.plugin.salt.SaltApiException;
import org.rundeck.plugin.salt.output.SaltApiResponseOutput;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken; | package org.rundeck.plugin.salt.version;
/**
* The latest incarnation of the interaction handler.
*/
public class LatestSaltInteractionHandler implements SaltInteractionHandler {
protected static final String SALT_OUTPUT_RETURN_KEY = "return";
protected static final Type MINION_RESPONSE_TYPE = new TypeToken<Map<String, Object>>() {}.getType(); | // Path: src/main/java/org/rundeck/plugin/salt/output/SaltApiResponseOutput.java
// public class SaltApiResponseOutput {
// protected String jid;
// protected List<String> minions;
//
// public String getJid() {
// return jid;
// }
//
// public List<String> getMinions() {
// return minions == null ? Collections.<String>emptyList() : Collections.unmodifiableList(minions);
// }
// }
// Path: src/main/java/org/rundeck/plugin/salt/version/LatestSaltInteractionHandler.java
import java.lang.reflect.Type;
import java.util.List;
import java.util.Map;
import org.rundeck.plugin.salt.SaltApiException;
import org.rundeck.plugin.salt.output.SaltApiResponseOutput;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
package org.rundeck.plugin.salt.version;
/**
* The latest incarnation of the interaction handler.
*/
public class LatestSaltInteractionHandler implements SaltInteractionHandler {
protected static final String SALT_OUTPUT_RETURN_KEY = "return";
protected static final Type MINION_RESPONSE_TYPE = new TypeToken<Map<String, Object>>() {}.getType(); | protected static final Type LIST_OF_SALT_API_RESPONSE_TYPE = new TypeToken<List<SaltApiResponseOutput>>() {}.getType(); |
funcatron/funcatron | starter/src/main/resources/archetype-resources/src/main/java/RedisProvider.java | // Path: intf/src/main/java/funcatron/intf/Accumulator.java
// public interface Accumulator {
// /**
// * Accumulate vendors that need "finishing"
// * @param item the item that was vended
// * @param vendor the thing doing the vending
// * @param <T> the type of thing
// */
// <T> void accumulate(T item, ServiceVendor<T> vendor);
//
// /**
// * For all the vended things, finish them either successfully onsuccessfully.
// *
// * @param success was the operation a success (e.g., commit) or not (e.g., rollback)
// */
// void finished(boolean success);
// }
//
// Path: intf/src/main/java/funcatron/intf/ServiceVendor.java
// public interface ServiceVendor<T> {
//
// /**
// * The name of the service
// * @return the name of the service
// */
// String name();
//
// /**
// * The type of the service vended
// *
// * @return the class object of the type of service vended
// */
// Class<T> type();
//
//
// /**
// * Is the class of a given type? For example `ofType(java.sql.Connection.class)`
// * to test for JDBC
// * @param clz the class to test the instance against
// * @return boolean
// */
// default boolean ofType(Class<?> clz) {
// return type().isAssignableFrom(clz);
// }
//
// /**
// * Vends an instance of the thing (like a JDBC connection)
// *
// * @param acc the accumulator
// * @return an instance of the thing
// * @throws Exception failure to create the instance
// */
// T vend(Accumulator acc) throws Exception;
//
// /**
// * Close down any resources the vendor has (e.g., close all the JDBC connections)
// */
// void endLife();
//
// /**
// * Release the resource at the end of a Func execution. Depending on `success`,
// * the resource may be released in different ways (e.g., database commit vs. database rollback)
// * @param item the item to release
// * @param success true if the function executed successfully and the transaction should be committed. false on an exception
// * @throws Exception if the release operation throws an exception
// */
// void release(T item, boolean success) throws Exception;
// }
//
// Path: intf/src/main/java/funcatron/intf/ServiceVendorProvider.java
// public interface ServiceVendorProvider {
// /**
// * The string type that this Builder will build a vendor for.
// * Example "database"
// * @return the name of the type this builder will build for
// */
// String forType();
//
//
// /**
// * If the 'type' field in the properties matches
// * @param name the name of the ServiceVendor
// * @param properties properties for the service vendor... for example the JDBC connection information
// * @param logger log anything to the logger
// * @return If we can successfull build the service vendor, build it
// */
// Optional<ServiceVendor<?>> buildVendor(String name, Map<String, Object> properties, Logger logger);
// }
| import funcatron.intf.Accumulator;
import funcatron.intf.ServiceVendor;
import funcatron.intf.ServiceVendorProvider;
import redis.clients.jedis.Jedis;
import java.util.Map;
import java.util.Optional;
import java.util.logging.Logger; | package $package;
/**
* An example of a provider so the Context can vend instances of
* things like DB drivers, cache drivers, etc.
*/
public class RedisProvider implements ServiceVendorProvider {
/**
* What's the name of this driver?
* @return the unique name
*/
@Override
public String forType() {
return "redis";
}
/**
* Some fancy null testing
* @param o an object
* @param clz a class to test
* @param <T> the type of the class
* @return null if o is not an instance of the class or null
*/
private <T> T ofType(Object o, Class<T> clz) {
if (null != o &&
clz.isInstance(o)) return (T) o;
return null;
}
/**
* Build something that will vend the named service based on the property map
* @param name the name of the item
* @param properties the properties
* @param logger if something needs logging
* @return If the properties are valid, return a ServiceVendor that will do the right thing
*/
@Override | // Path: intf/src/main/java/funcatron/intf/Accumulator.java
// public interface Accumulator {
// /**
// * Accumulate vendors that need "finishing"
// * @param item the item that was vended
// * @param vendor the thing doing the vending
// * @param <T> the type of thing
// */
// <T> void accumulate(T item, ServiceVendor<T> vendor);
//
// /**
// * For all the vended things, finish them either successfully onsuccessfully.
// *
// * @param success was the operation a success (e.g., commit) or not (e.g., rollback)
// */
// void finished(boolean success);
// }
//
// Path: intf/src/main/java/funcatron/intf/ServiceVendor.java
// public interface ServiceVendor<T> {
//
// /**
// * The name of the service
// * @return the name of the service
// */
// String name();
//
// /**
// * The type of the service vended
// *
// * @return the class object of the type of service vended
// */
// Class<T> type();
//
//
// /**
// * Is the class of a given type? For example `ofType(java.sql.Connection.class)`
// * to test for JDBC
// * @param clz the class to test the instance against
// * @return boolean
// */
// default boolean ofType(Class<?> clz) {
// return type().isAssignableFrom(clz);
// }
//
// /**
// * Vends an instance of the thing (like a JDBC connection)
// *
// * @param acc the accumulator
// * @return an instance of the thing
// * @throws Exception failure to create the instance
// */
// T vend(Accumulator acc) throws Exception;
//
// /**
// * Close down any resources the vendor has (e.g., close all the JDBC connections)
// */
// void endLife();
//
// /**
// * Release the resource at the end of a Func execution. Depending on `success`,
// * the resource may be released in different ways (e.g., database commit vs. database rollback)
// * @param item the item to release
// * @param success true if the function executed successfully and the transaction should be committed. false on an exception
// * @throws Exception if the release operation throws an exception
// */
// void release(T item, boolean success) throws Exception;
// }
//
// Path: intf/src/main/java/funcatron/intf/ServiceVendorProvider.java
// public interface ServiceVendorProvider {
// /**
// * The string type that this Builder will build a vendor for.
// * Example "database"
// * @return the name of the type this builder will build for
// */
// String forType();
//
//
// /**
// * If the 'type' field in the properties matches
// * @param name the name of the ServiceVendor
// * @param properties properties for the service vendor... for example the JDBC connection information
// * @param logger log anything to the logger
// * @return If we can successfull build the service vendor, build it
// */
// Optional<ServiceVendor<?>> buildVendor(String name, Map<String, Object> properties, Logger logger);
// }
// Path: starter/src/main/resources/archetype-resources/src/main/java/RedisProvider.java
import funcatron.intf.Accumulator;
import funcatron.intf.ServiceVendor;
import funcatron.intf.ServiceVendorProvider;
import redis.clients.jedis.Jedis;
import java.util.Map;
import java.util.Optional;
import java.util.logging.Logger;
package $package;
/**
* An example of a provider so the Context can vend instances of
* things like DB drivers, cache drivers, etc.
*/
public class RedisProvider implements ServiceVendorProvider {
/**
* What's the name of this driver?
* @return the unique name
*/
@Override
public String forType() {
return "redis";
}
/**
* Some fancy null testing
* @param o an object
* @param clz a class to test
* @param <T> the type of the class
* @return null if o is not an instance of the class or null
*/
private <T> T ofType(Object o, Class<T> clz) {
if (null != o &&
clz.isInstance(o)) return (T) o;
return null;
}
/**
* Build something that will vend the named service based on the property map
* @param name the name of the item
* @param properties the properties
* @param logger if something needs logging
* @return If the properties are valid, return a ServiceVendor that will do the right thing
*/
@Override | public Optional<ServiceVendor<?>> buildVendor(String name, Map<String, Object> properties, Logger logger) { |
funcatron/funcatron | starter/src/main/resources/archetype-resources/src/main/java/RedisProvider.java | // Path: intf/src/main/java/funcatron/intf/Accumulator.java
// public interface Accumulator {
// /**
// * Accumulate vendors that need "finishing"
// * @param item the item that was vended
// * @param vendor the thing doing the vending
// * @param <T> the type of thing
// */
// <T> void accumulate(T item, ServiceVendor<T> vendor);
//
// /**
// * For all the vended things, finish them either successfully onsuccessfully.
// *
// * @param success was the operation a success (e.g., commit) or not (e.g., rollback)
// */
// void finished(boolean success);
// }
//
// Path: intf/src/main/java/funcatron/intf/ServiceVendor.java
// public interface ServiceVendor<T> {
//
// /**
// * The name of the service
// * @return the name of the service
// */
// String name();
//
// /**
// * The type of the service vended
// *
// * @return the class object of the type of service vended
// */
// Class<T> type();
//
//
// /**
// * Is the class of a given type? For example `ofType(java.sql.Connection.class)`
// * to test for JDBC
// * @param clz the class to test the instance against
// * @return boolean
// */
// default boolean ofType(Class<?> clz) {
// return type().isAssignableFrom(clz);
// }
//
// /**
// * Vends an instance of the thing (like a JDBC connection)
// *
// * @param acc the accumulator
// * @return an instance of the thing
// * @throws Exception failure to create the instance
// */
// T vend(Accumulator acc) throws Exception;
//
// /**
// * Close down any resources the vendor has (e.g., close all the JDBC connections)
// */
// void endLife();
//
// /**
// * Release the resource at the end of a Func execution. Depending on `success`,
// * the resource may be released in different ways (e.g., database commit vs. database rollback)
// * @param item the item to release
// * @param success true if the function executed successfully and the transaction should be committed. false on an exception
// * @throws Exception if the release operation throws an exception
// */
// void release(T item, boolean success) throws Exception;
// }
//
// Path: intf/src/main/java/funcatron/intf/ServiceVendorProvider.java
// public interface ServiceVendorProvider {
// /**
// * The string type that this Builder will build a vendor for.
// * Example "database"
// * @return the name of the type this builder will build for
// */
// String forType();
//
//
// /**
// * If the 'type' field in the properties matches
// * @param name the name of the ServiceVendor
// * @param properties properties for the service vendor... for example the JDBC connection information
// * @param logger log anything to the logger
// * @return If we can successfull build the service vendor, build it
// */
// Optional<ServiceVendor<?>> buildVendor(String name, Map<String, Object> properties, Logger logger);
// }
| import funcatron.intf.Accumulator;
import funcatron.intf.ServiceVendor;
import funcatron.intf.ServiceVendorProvider;
import redis.clients.jedis.Jedis;
import java.util.Map;
import java.util.Optional;
import java.util.logging.Logger; | package $package;
/**
* An example of a provider so the Context can vend instances of
* things like DB drivers, cache drivers, etc.
*/
public class RedisProvider implements ServiceVendorProvider {
/**
* What's the name of this driver?
* @return the unique name
*/
@Override
public String forType() {
return "redis";
}
/**
* Some fancy null testing
* @param o an object
* @param clz a class to test
* @param <T> the type of the class
* @return null if o is not an instance of the class or null
*/
private <T> T ofType(Object o, Class<T> clz) {
if (null != o &&
clz.isInstance(o)) return (T) o;
return null;
}
/**
* Build something that will vend the named service based on the property map
* @param name the name of the item
* @param properties the properties
* @param logger if something needs logging
* @return If the properties are valid, return a ServiceVendor that will do the right thing
*/
@Override
public Optional<ServiceVendor<?>> buildVendor(String name, Map<String, Object> properties, Logger logger) {
final String host = ofType(properties.get("host"), String.class);
if (null == host) return Optional.empty();
return Optional.of(new ServiceVendor<Jedis>() {
@Override
public String name() {
return name;
}
@Override
public Class<Jedis> type() {
return Jedis.class;
}
@Override | // Path: intf/src/main/java/funcatron/intf/Accumulator.java
// public interface Accumulator {
// /**
// * Accumulate vendors that need "finishing"
// * @param item the item that was vended
// * @param vendor the thing doing the vending
// * @param <T> the type of thing
// */
// <T> void accumulate(T item, ServiceVendor<T> vendor);
//
// /**
// * For all the vended things, finish them either successfully onsuccessfully.
// *
// * @param success was the operation a success (e.g., commit) or not (e.g., rollback)
// */
// void finished(boolean success);
// }
//
// Path: intf/src/main/java/funcatron/intf/ServiceVendor.java
// public interface ServiceVendor<T> {
//
// /**
// * The name of the service
// * @return the name of the service
// */
// String name();
//
// /**
// * The type of the service vended
// *
// * @return the class object of the type of service vended
// */
// Class<T> type();
//
//
// /**
// * Is the class of a given type? For example `ofType(java.sql.Connection.class)`
// * to test for JDBC
// * @param clz the class to test the instance against
// * @return boolean
// */
// default boolean ofType(Class<?> clz) {
// return type().isAssignableFrom(clz);
// }
//
// /**
// * Vends an instance of the thing (like a JDBC connection)
// *
// * @param acc the accumulator
// * @return an instance of the thing
// * @throws Exception failure to create the instance
// */
// T vend(Accumulator acc) throws Exception;
//
// /**
// * Close down any resources the vendor has (e.g., close all the JDBC connections)
// */
// void endLife();
//
// /**
// * Release the resource at the end of a Func execution. Depending on `success`,
// * the resource may be released in different ways (e.g., database commit vs. database rollback)
// * @param item the item to release
// * @param success true if the function executed successfully and the transaction should be committed. false on an exception
// * @throws Exception if the release operation throws an exception
// */
// void release(T item, boolean success) throws Exception;
// }
//
// Path: intf/src/main/java/funcatron/intf/ServiceVendorProvider.java
// public interface ServiceVendorProvider {
// /**
// * The string type that this Builder will build a vendor for.
// * Example "database"
// * @return the name of the type this builder will build for
// */
// String forType();
//
//
// /**
// * If the 'type' field in the properties matches
// * @param name the name of the ServiceVendor
// * @param properties properties for the service vendor... for example the JDBC connection information
// * @param logger log anything to the logger
// * @return If we can successfull build the service vendor, build it
// */
// Optional<ServiceVendor<?>> buildVendor(String name, Map<String, Object> properties, Logger logger);
// }
// Path: starter/src/main/resources/archetype-resources/src/main/java/RedisProvider.java
import funcatron.intf.Accumulator;
import funcatron.intf.ServiceVendor;
import funcatron.intf.ServiceVendorProvider;
import redis.clients.jedis.Jedis;
import java.util.Map;
import java.util.Optional;
import java.util.logging.Logger;
package $package;
/**
* An example of a provider so the Context can vend instances of
* things like DB drivers, cache drivers, etc.
*/
public class RedisProvider implements ServiceVendorProvider {
/**
* What's the name of this driver?
* @return the unique name
*/
@Override
public String forType() {
return "redis";
}
/**
* Some fancy null testing
* @param o an object
* @param clz a class to test
* @param <T> the type of the class
* @return null if o is not an instance of the class or null
*/
private <T> T ofType(Object o, Class<T> clz) {
if (null != o &&
clz.isInstance(o)) return (T) o;
return null;
}
/**
* Build something that will vend the named service based on the property map
* @param name the name of the item
* @param properties the properties
* @param logger if something needs logging
* @return If the properties are valid, return a ServiceVendor that will do the right thing
*/
@Override
public Optional<ServiceVendor<?>> buildVendor(String name, Map<String, Object> properties, Logger logger) {
final String host = ofType(properties.get("host"), String.class);
if (null == host) return Optional.empty();
return Optional.of(new ServiceVendor<Jedis>() {
@Override
public String name() {
return name;
}
@Override
public Class<Jedis> type() {
return Jedis.class;
}
@Override | public Jedis vend(Accumulator acc) throws Exception { |
funcatron/funcatron | tron/src/java/funcatron/abstractions/MessageBroker.java | // Path: tron/src/java/funcatron/helpers/Tuple2.java
// public class Tuple2<A, B> {
//
// private final A a;
// private final B b;
//
// public Tuple2(A a, B b) {
// this.a = a;
// this.b = b;
// }
//
// public A _1() {return a;}
// public B _2() {return b;}
// public A a() {return a;}
// public B b() {return b;}
//
// /**
// * Convert the Tuple into a List
// * @return a List containing the elements of the Tuple
// */
// public List toList() {
// return (List) Clojure.var("clojure/core", "list").invoke(a, b);
// }
// }
| import funcatron.helpers.Tuple2;
import java.io.Closeable;
import java.io.IOException;
import java.util.List;
import java.util.Map;
import java.util.function.Function; | package funcatron.abstractions;
/**
* An abstraction for message brokers. What does a message broker need to
* do?
*/
public interface MessageBroker extends Closeable {
/**
* Is the instance connected to the message broker?
*
* @return true if there's a connection to the message broker
*/
boolean isConnected();
interface ReceivedMessage {
/**
* Metadata associated with the message including headers, etc.
* @return the metadata associated with the message
*/
Map<String, Object> metadata();
/**
* The content type of the message
* @return the content type
*/
String contentType();
/**
* The body of the message. It will likely be decoded into
* a type associated with the content type: JSON -> Map,
* XML -> Node, or maybe a byte[] or String.
*
* @return the Body of the message
*/
Object body();
/**
* Return the raw bytes that make up the message body
* @return the raw bytes that make up the message body
*/
byte[] rawBody();
/**
* Acknowledge the message
*
* @throws IOException if there's a communication error
*/
void ackMessage() throws IOException;
/**
* Nacks the message.
*
* @param reQueue should the message be re-queued
*
* @throws IOException
*/
void nackMessage(boolean reQueue) throws IOException;
/**
* Returns the message broker associated with this message
* @return the message broker
*/
MessageBroker messageBroker();
}
/**
* Listen to the named queue for messages or other events
*
* @param queueName the name of the queue
* @param handler a Function that consumes the message
* @return a Runnable that, when the `.run()` method is invoked, will stop listening the the queue
*
* @throws IOException if something goes pear-shaped
*/
Runnable listenToQueue(String queueName, Function<ReceivedMessage, Void> handler) throws IOException;
/**
* Send a message to the named queue
*
* @param queueName the name of the queue to send messages to
* @param metadata key/value pairs of metadata (e.g., headers)
* @param message the message which will be appropriately serialized given its type
* @throws IOException if something goes pear-shaped
*/
void sendMessage(String queueName, Map<String, Object> metadata, Object message) throws IOException;
/**
* Get a list of all the listeners. It's a Pair of the queue name and the Runnable to cancel the listening
* @return a list of all the listeners
*/ | // Path: tron/src/java/funcatron/helpers/Tuple2.java
// public class Tuple2<A, B> {
//
// private final A a;
// private final B b;
//
// public Tuple2(A a, B b) {
// this.a = a;
// this.b = b;
// }
//
// public A _1() {return a;}
// public B _2() {return b;}
// public A a() {return a;}
// public B b() {return b;}
//
// /**
// * Convert the Tuple into a List
// * @return a List containing the elements of the Tuple
// */
// public List toList() {
// return (List) Clojure.var("clojure/core", "list").invoke(a, b);
// }
// }
// Path: tron/src/java/funcatron/abstractions/MessageBroker.java
import funcatron.helpers.Tuple2;
import java.io.Closeable;
import java.io.IOException;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
package funcatron.abstractions;
/**
* An abstraction for message brokers. What does a message broker need to
* do?
*/
public interface MessageBroker extends Closeable {
/**
* Is the instance connected to the message broker?
*
* @return true if there's a connection to the message broker
*/
boolean isConnected();
interface ReceivedMessage {
/**
* Metadata associated with the message including headers, etc.
* @return the metadata associated with the message
*/
Map<String, Object> metadata();
/**
* The content type of the message
* @return the content type
*/
String contentType();
/**
* The body of the message. It will likely be decoded into
* a type associated with the content type: JSON -> Map,
* XML -> Node, or maybe a byte[] or String.
*
* @return the Body of the message
*/
Object body();
/**
* Return the raw bytes that make up the message body
* @return the raw bytes that make up the message body
*/
byte[] rawBody();
/**
* Acknowledge the message
*
* @throws IOException if there's a communication error
*/
void ackMessage() throws IOException;
/**
* Nacks the message.
*
* @param reQueue should the message be re-queued
*
* @throws IOException
*/
void nackMessage(boolean reQueue) throws IOException;
/**
* Returns the message broker associated with this message
* @return the message broker
*/
MessageBroker messageBroker();
}
/**
* Listen to the named queue for messages or other events
*
* @param queueName the name of the queue
* @param handler a Function that consumes the message
* @return a Runnable that, when the `.run()` method is invoked, will stop listening the the queue
*
* @throws IOException if something goes pear-shaped
*/
Runnable listenToQueue(String queueName, Function<ReceivedMessage, Void> handler) throws IOException;
/**
* Send a message to the named queue
*
* @param queueName the name of the queue to send messages to
* @param metadata key/value pairs of metadata (e.g., headers)
* @param message the message which will be appropriately serialized given its type
* @throws IOException if something goes pear-shaped
*/
void sendMessage(String queueName, Map<String, Object> metadata, Object message) throws IOException;
/**
* Get a list of all the listeners. It's a Pair of the queue name and the Runnable to cancel the listening
* @return a list of all the listeners
*/ | List<Tuple2<String, Runnable>> listeners(); |
funcatron/funcatron | tron/src/java/funcatron/abstractions/ContainerSubstrate.java | // Path: tron/src/java/funcatron/helpers/Tuple2.java
// public class Tuple2<A, B> {
//
// private final A a;
// private final B b;
//
// public Tuple2(A a, B b) {
// this.a = a;
// this.b = b;
// }
//
// public A _1() {return a;}
// public B _2() {return b;}
// public A a() {return a;}
// public B b() {return b;}
//
// /**
// * Convert the Tuple into a List
// * @return a List containing the elements of the Tuple
// */
// public List toList() {
// return (List) Clojure.var("clojure/core", "list").invoke(a, b);
// }
// }
//
// Path: tron/src/java/funcatron/helpers/Tuple3.java
// public class Tuple3<A, B, C> extends Tuple2<A,B> {
//
// private final C c;
//
// public Tuple3(A a, B b,C c) {
// super(a,b);
// this.c = c;
// }
//
// public C _3() {return c;}
// public C c() {return c;}
//
// /**
// * Convert the Tuple into a List
// * @return a List containing the elements of the Tuple
// */
// @Override
// public List toList() {
// return (List) Clojure.var("clojure/core", "list").invoke(_1(), _2(), c);
// }
// }
| import funcatron.helpers.Tuple2;
import funcatron.helpers.Tuple3;
import java.io.IOException;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.function.Function; | package funcatron.abstractions;
/**
* How the Tron talks to the Container substrate (Mesos, Kubernetes, Docker Swarm)
* to start, stop, and monitor
*/
public interface ContainerSubstrate {
class ServiceType {
public final String dockerImage;
public final double cpu;
public final double memory; | // Path: tron/src/java/funcatron/helpers/Tuple2.java
// public class Tuple2<A, B> {
//
// private final A a;
// private final B b;
//
// public Tuple2(A a, B b) {
// this.a = a;
// this.b = b;
// }
//
// public A _1() {return a;}
// public B _2() {return b;}
// public A a() {return a;}
// public B b() {return b;}
//
// /**
// * Convert the Tuple into a List
// * @return a List containing the elements of the Tuple
// */
// public List toList() {
// return (List) Clojure.var("clojure/core", "list").invoke(a, b);
// }
// }
//
// Path: tron/src/java/funcatron/helpers/Tuple3.java
// public class Tuple3<A, B, C> extends Tuple2<A,B> {
//
// private final C c;
//
// public Tuple3(A a, B b,C c) {
// super(a,b);
// this.c = c;
// }
//
// public C _3() {return c;}
// public C c() {return c;}
//
// /**
// * Convert the Tuple into a List
// * @return a List containing the elements of the Tuple
// */
// @Override
// public List toList() {
// return (List) Clojure.var("clojure/core", "list").invoke(_1(), _2(), c);
// }
// }
// Path: tron/src/java/funcatron/abstractions/ContainerSubstrate.java
import funcatron.helpers.Tuple2;
import funcatron.helpers.Tuple3;
import java.io.IOException;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.function.Function;
package funcatron.abstractions;
/**
* How the Tron talks to the Container substrate (Mesos, Kubernetes, Docker Swarm)
* to start, stop, and monitor
*/
public interface ContainerSubstrate {
class ServiceType {
public final String dockerImage;
public final double cpu;
public final double memory; | public final List<Tuple2<String, String>> env; |
funcatron/funcatron | tron/src/java/funcatron/abstractions/ContainerSubstrate.java | // Path: tron/src/java/funcatron/helpers/Tuple2.java
// public class Tuple2<A, B> {
//
// private final A a;
// private final B b;
//
// public Tuple2(A a, B b) {
// this.a = a;
// this.b = b;
// }
//
// public A _1() {return a;}
// public B _2() {return b;}
// public A a() {return a;}
// public B b() {return b;}
//
// /**
// * Convert the Tuple into a List
// * @return a List containing the elements of the Tuple
// */
// public List toList() {
// return (List) Clojure.var("clojure/core", "list").invoke(a, b);
// }
// }
//
// Path: tron/src/java/funcatron/helpers/Tuple3.java
// public class Tuple3<A, B, C> extends Tuple2<A,B> {
//
// private final C c;
//
// public Tuple3(A a, B b,C c) {
// super(a,b);
// this.c = c;
// }
//
// public C _3() {return c;}
// public C c() {return c;}
//
// /**
// * Convert the Tuple into a List
// * @return a List containing the elements of the Tuple
// */
// @Override
// public List toList() {
// return (List) Clojure.var("clojure/core", "list").invoke(_1(), _2(), c);
// }
// }
| import funcatron.helpers.Tuple2;
import funcatron.helpers.Tuple3;
import java.io.IOException;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.function.Function; | package funcatron.abstractions;
/**
* How the Tron talks to the Container substrate (Mesos, Kubernetes, Docker Swarm)
* to start, stop, and monitor
*/
public interface ContainerSubstrate {
class ServiceType {
public final String dockerImage;
public final double cpu;
public final double memory;
public final List<Tuple2<String, String>> env;
public ServiceType(String dockerImage,
double cpu,
double memory,
List<Tuple2<String, String>> env) {
this.dockerImage = dockerImage;
this.env = env;
this.cpu = cpu;
this.memory = memory;
}
}
/**
* Get all the internal information for the substrate... the results depend on
* the implementation. This is mostly for debugging purposes
* @return
*/
Map<Object, Object> allInfo();
/**
* Start a service
*
* @param type the type of service to start
* @param monitor an optional function that will be called with updates about this service
*
* @return the UUID for the function
*
* @throws IOException if there's a problem talking to the substrate
*/
UUID startService(ServiceType type, | // Path: tron/src/java/funcatron/helpers/Tuple2.java
// public class Tuple2<A, B> {
//
// private final A a;
// private final B b;
//
// public Tuple2(A a, B b) {
// this.a = a;
// this.b = b;
// }
//
// public A _1() {return a;}
// public B _2() {return b;}
// public A a() {return a;}
// public B b() {return b;}
//
// /**
// * Convert the Tuple into a List
// * @return a List containing the elements of the Tuple
// */
// public List toList() {
// return (List) Clojure.var("clojure/core", "list").invoke(a, b);
// }
// }
//
// Path: tron/src/java/funcatron/helpers/Tuple3.java
// public class Tuple3<A, B, C> extends Tuple2<A,B> {
//
// private final C c;
//
// public Tuple3(A a, B b,C c) {
// super(a,b);
// this.c = c;
// }
//
// public C _3() {return c;}
// public C c() {return c;}
//
// /**
// * Convert the Tuple into a List
// * @return a List containing the elements of the Tuple
// */
// @Override
// public List toList() {
// return (List) Clojure.var("clojure/core", "list").invoke(_1(), _2(), c);
// }
// }
// Path: tron/src/java/funcatron/abstractions/ContainerSubstrate.java
import funcatron.helpers.Tuple2;
import funcatron.helpers.Tuple3;
import java.io.IOException;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.function.Function;
package funcatron.abstractions;
/**
* How the Tron talks to the Container substrate (Mesos, Kubernetes, Docker Swarm)
* to start, stop, and monitor
*/
public interface ContainerSubstrate {
class ServiceType {
public final String dockerImage;
public final double cpu;
public final double memory;
public final List<Tuple2<String, String>> env;
public ServiceType(String dockerImage,
double cpu,
double memory,
List<Tuple2<String, String>> env) {
this.dockerImage = dockerImage;
this.env = env;
this.cpu = cpu;
this.memory = memory;
}
}
/**
* Get all the internal information for the substrate... the results depend on
* the implementation. This is mostly for debugging purposes
* @return
*/
Map<Object, Object> allInfo();
/**
* Start a service
*
* @param type the type of service to start
* @param monitor an optional function that will be called with updates about this service
*
* @return the UUID for the function
*
* @throws IOException if there's a problem talking to the substrate
*/
UUID startService(ServiceType type, | Function<Tuple3<UUID, TaskState, Map<String, Object>>, Void> monitor) |
funcatron/funcatron | intf/src/main/java/funcatron/intf/impl/JDBCServiceVendorBuilder.java | // Path: intf/src/main/java/funcatron/intf/Accumulator.java
// public interface Accumulator {
// /**
// * Accumulate vendors that need "finishing"
// * @param item the item that was vended
// * @param vendor the thing doing the vending
// * @param <T> the type of thing
// */
// <T> void accumulate(T item, ServiceVendor<T> vendor);
//
// /**
// * For all the vended things, finish them either successfully onsuccessfully.
// *
// * @param success was the operation a success (e.g., commit) or not (e.g., rollback)
// */
// void finished(boolean success);
// }
//
// Path: intf/src/main/java/funcatron/intf/ServiceVendor.java
// public interface ServiceVendor<T> {
//
// /**
// * The name of the service
// * @return the name of the service
// */
// String name();
//
// /**
// * The type of the service vended
// *
// * @return the class object of the type of service vended
// */
// Class<T> type();
//
//
// /**
// * Is the class of a given type? For example `ofType(java.sql.Connection.class)`
// * to test for JDBC
// * @param clz the class to test the instance against
// * @return boolean
// */
// default boolean ofType(Class<?> clz) {
// return type().isAssignableFrom(clz);
// }
//
// /**
// * Vends an instance of the thing (like a JDBC connection)
// *
// * @param acc the accumulator
// * @return an instance of the thing
// * @throws Exception failure to create the instance
// */
// T vend(Accumulator acc) throws Exception;
//
// /**
// * Close down any resources the vendor has (e.g., close all the JDBC connections)
// */
// void endLife();
//
// /**
// * Release the resource at the end of a Func execution. Depending on `success`,
// * the resource may be released in different ways (e.g., database commit vs. database rollback)
// * @param item the item to release
// * @param success true if the function executed successfully and the transaction should be committed. false on an exception
// * @throws Exception if the release operation throws an exception
// */
// void release(T item, boolean success) throws Exception;
// }
//
// Path: intf/src/main/java/funcatron/intf/ServiceVendorProvider.java
// public interface ServiceVendorProvider {
// /**
// * The string type that this Builder will build a vendor for.
// * Example "database"
// * @return the name of the type this builder will build for
// */
// String forType();
//
//
// /**
// * If the 'type' field in the properties matches
// * @param name the name of the ServiceVendor
// * @param properties properties for the service vendor... for example the JDBC connection information
// * @param logger log anything to the logger
// * @return If we can successfull build the service vendor, build it
// */
// Optional<ServiceVendor<?>> buildVendor(String name, Map<String, Object> properties, Logger logger);
// }
| import com.zaxxer.hikari.HikariConfig;
import com.zaxxer.hikari.HikariDataSource;
import funcatron.intf.Accumulator;
import funcatron.intf.ServiceVendor;
import funcatron.intf.ServiceVendorProvider;
import java.sql.Connection;
import java.sql.Driver;
import java.sql.DriverManager;
import java.util.*;
import java.util.logging.Level;
import java.util.logging.Logger; | package funcatron.intf.impl;
/**
* The built in JDBC vendor
*/
public class JDBCServiceVendorBuilder implements ServiceVendorProvider {
/**
* The string type that this Builder will build a vendor for.
* Example "database"
*
* @return the name of the type this builder will build for
*/
@Override
public String forType() {
return "database";
}
private static String mapToString(Map map) {
StringBuilder sb = new StringBuilder();
Iterator<Map.Entry> iter = map.entrySet().iterator();
while (iter.hasNext()) {
Map.Entry entry = iter.next();
sb.append(entry.getKey());
sb.append('=').append('"');
sb.append(entry.getValue());
sb.append('"');
if (iter.hasNext()) {
sb.append(',').append(' ');
}
}
return sb.toString();
}
/**
* If the 'type' field in the properties matches
*
* @param name the name of the ServiceVendor
* @param properties properties for the service vendor... for example the JDBC connection information
* @param logger log anything to the logger
* @return If we can successfull build the service vendor, build it
*/
@Override | // Path: intf/src/main/java/funcatron/intf/Accumulator.java
// public interface Accumulator {
// /**
// * Accumulate vendors that need "finishing"
// * @param item the item that was vended
// * @param vendor the thing doing the vending
// * @param <T> the type of thing
// */
// <T> void accumulate(T item, ServiceVendor<T> vendor);
//
// /**
// * For all the vended things, finish them either successfully onsuccessfully.
// *
// * @param success was the operation a success (e.g., commit) or not (e.g., rollback)
// */
// void finished(boolean success);
// }
//
// Path: intf/src/main/java/funcatron/intf/ServiceVendor.java
// public interface ServiceVendor<T> {
//
// /**
// * The name of the service
// * @return the name of the service
// */
// String name();
//
// /**
// * The type of the service vended
// *
// * @return the class object of the type of service vended
// */
// Class<T> type();
//
//
// /**
// * Is the class of a given type? For example `ofType(java.sql.Connection.class)`
// * to test for JDBC
// * @param clz the class to test the instance against
// * @return boolean
// */
// default boolean ofType(Class<?> clz) {
// return type().isAssignableFrom(clz);
// }
//
// /**
// * Vends an instance of the thing (like a JDBC connection)
// *
// * @param acc the accumulator
// * @return an instance of the thing
// * @throws Exception failure to create the instance
// */
// T vend(Accumulator acc) throws Exception;
//
// /**
// * Close down any resources the vendor has (e.g., close all the JDBC connections)
// */
// void endLife();
//
// /**
// * Release the resource at the end of a Func execution. Depending on `success`,
// * the resource may be released in different ways (e.g., database commit vs. database rollback)
// * @param item the item to release
// * @param success true if the function executed successfully and the transaction should be committed. false on an exception
// * @throws Exception if the release operation throws an exception
// */
// void release(T item, boolean success) throws Exception;
// }
//
// Path: intf/src/main/java/funcatron/intf/ServiceVendorProvider.java
// public interface ServiceVendorProvider {
// /**
// * The string type that this Builder will build a vendor for.
// * Example "database"
// * @return the name of the type this builder will build for
// */
// String forType();
//
//
// /**
// * If the 'type' field in the properties matches
// * @param name the name of the ServiceVendor
// * @param properties properties for the service vendor... for example the JDBC connection information
// * @param logger log anything to the logger
// * @return If we can successfull build the service vendor, build it
// */
// Optional<ServiceVendor<?>> buildVendor(String name, Map<String, Object> properties, Logger logger);
// }
// Path: intf/src/main/java/funcatron/intf/impl/JDBCServiceVendorBuilder.java
import com.zaxxer.hikari.HikariConfig;
import com.zaxxer.hikari.HikariDataSource;
import funcatron.intf.Accumulator;
import funcatron.intf.ServiceVendor;
import funcatron.intf.ServiceVendorProvider;
import java.sql.Connection;
import java.sql.Driver;
import java.sql.DriverManager;
import java.util.*;
import java.util.logging.Level;
import java.util.logging.Logger;
package funcatron.intf.impl;
/**
* The built in JDBC vendor
*/
public class JDBCServiceVendorBuilder implements ServiceVendorProvider {
/**
* The string type that this Builder will build a vendor for.
* Example "database"
*
* @return the name of the type this builder will build for
*/
@Override
public String forType() {
return "database";
}
private static String mapToString(Map map) {
StringBuilder sb = new StringBuilder();
Iterator<Map.Entry> iter = map.entrySet().iterator();
while (iter.hasNext()) {
Map.Entry entry = iter.next();
sb.append(entry.getKey());
sb.append('=').append('"');
sb.append(entry.getValue());
sb.append('"');
if (iter.hasNext()) {
sb.append(',').append(' ');
}
}
return sb.toString();
}
/**
* If the 'type' field in the properties matches
*
* @param name the name of the ServiceVendor
* @param properties properties for the service vendor... for example the JDBC connection information
* @param logger log anything to the logger
* @return If we can successfull build the service vendor, build it
*/
@Override | public Optional<ServiceVendor<?>> buildVendor(String name, Map<String, Object> properties, Logger logger) { |
funcatron/funcatron | intf/src/main/java/funcatron/intf/impl/JDBCServiceVendorBuilder.java | // Path: intf/src/main/java/funcatron/intf/Accumulator.java
// public interface Accumulator {
// /**
// * Accumulate vendors that need "finishing"
// * @param item the item that was vended
// * @param vendor the thing doing the vending
// * @param <T> the type of thing
// */
// <T> void accumulate(T item, ServiceVendor<T> vendor);
//
// /**
// * For all the vended things, finish them either successfully onsuccessfully.
// *
// * @param success was the operation a success (e.g., commit) or not (e.g., rollback)
// */
// void finished(boolean success);
// }
//
// Path: intf/src/main/java/funcatron/intf/ServiceVendor.java
// public interface ServiceVendor<T> {
//
// /**
// * The name of the service
// * @return the name of the service
// */
// String name();
//
// /**
// * The type of the service vended
// *
// * @return the class object of the type of service vended
// */
// Class<T> type();
//
//
// /**
// * Is the class of a given type? For example `ofType(java.sql.Connection.class)`
// * to test for JDBC
// * @param clz the class to test the instance against
// * @return boolean
// */
// default boolean ofType(Class<?> clz) {
// return type().isAssignableFrom(clz);
// }
//
// /**
// * Vends an instance of the thing (like a JDBC connection)
// *
// * @param acc the accumulator
// * @return an instance of the thing
// * @throws Exception failure to create the instance
// */
// T vend(Accumulator acc) throws Exception;
//
// /**
// * Close down any resources the vendor has (e.g., close all the JDBC connections)
// */
// void endLife();
//
// /**
// * Release the resource at the end of a Func execution. Depending on `success`,
// * the resource may be released in different ways (e.g., database commit vs. database rollback)
// * @param item the item to release
// * @param success true if the function executed successfully and the transaction should be committed. false on an exception
// * @throws Exception if the release operation throws an exception
// */
// void release(T item, boolean success) throws Exception;
// }
//
// Path: intf/src/main/java/funcatron/intf/ServiceVendorProvider.java
// public interface ServiceVendorProvider {
// /**
// * The string type that this Builder will build a vendor for.
// * Example "database"
// * @return the name of the type this builder will build for
// */
// String forType();
//
//
// /**
// * If the 'type' field in the properties matches
// * @param name the name of the ServiceVendor
// * @param properties properties for the service vendor... for example the JDBC connection information
// * @param logger log anything to the logger
// * @return If we can successfull build the service vendor, build it
// */
// Optional<ServiceVendor<?>> buildVendor(String name, Map<String, Object> properties, Logger logger);
// }
| import com.zaxxer.hikari.HikariConfig;
import com.zaxxer.hikari.HikariDataSource;
import funcatron.intf.Accumulator;
import funcatron.intf.ServiceVendor;
import funcatron.intf.ServiceVendorProvider;
import java.sql.Connection;
import java.sql.Driver;
import java.sql.DriverManager;
import java.util.*;
import java.util.logging.Level;
import java.util.logging.Logger; | return Optional.of(
new ServiceVendor<Connection>() {
/**
* The name of the service
*
* @return the name of the service
*/
@Override
public String name() {
return name;
}
/**
* The type of the service vended
*
* @return the class object of the type of service vended
*/
@Override
public Class<Connection> type() {
return Connection.class;
}
/**
* Vends an instance of the thing (like a JDBC connection)
*
* @param acc the accumulator
* @return an instance of the thing
* @throws Exception failure to create the instance
*/
@Override | // Path: intf/src/main/java/funcatron/intf/Accumulator.java
// public interface Accumulator {
// /**
// * Accumulate vendors that need "finishing"
// * @param item the item that was vended
// * @param vendor the thing doing the vending
// * @param <T> the type of thing
// */
// <T> void accumulate(T item, ServiceVendor<T> vendor);
//
// /**
// * For all the vended things, finish them either successfully onsuccessfully.
// *
// * @param success was the operation a success (e.g., commit) or not (e.g., rollback)
// */
// void finished(boolean success);
// }
//
// Path: intf/src/main/java/funcatron/intf/ServiceVendor.java
// public interface ServiceVendor<T> {
//
// /**
// * The name of the service
// * @return the name of the service
// */
// String name();
//
// /**
// * The type of the service vended
// *
// * @return the class object of the type of service vended
// */
// Class<T> type();
//
//
// /**
// * Is the class of a given type? For example `ofType(java.sql.Connection.class)`
// * to test for JDBC
// * @param clz the class to test the instance against
// * @return boolean
// */
// default boolean ofType(Class<?> clz) {
// return type().isAssignableFrom(clz);
// }
//
// /**
// * Vends an instance of the thing (like a JDBC connection)
// *
// * @param acc the accumulator
// * @return an instance of the thing
// * @throws Exception failure to create the instance
// */
// T vend(Accumulator acc) throws Exception;
//
// /**
// * Close down any resources the vendor has (e.g., close all the JDBC connections)
// */
// void endLife();
//
// /**
// * Release the resource at the end of a Func execution. Depending on `success`,
// * the resource may be released in different ways (e.g., database commit vs. database rollback)
// * @param item the item to release
// * @param success true if the function executed successfully and the transaction should be committed. false on an exception
// * @throws Exception if the release operation throws an exception
// */
// void release(T item, boolean success) throws Exception;
// }
//
// Path: intf/src/main/java/funcatron/intf/ServiceVendorProvider.java
// public interface ServiceVendorProvider {
// /**
// * The string type that this Builder will build a vendor for.
// * Example "database"
// * @return the name of the type this builder will build for
// */
// String forType();
//
//
// /**
// * If the 'type' field in the properties matches
// * @param name the name of the ServiceVendor
// * @param properties properties for the service vendor... for example the JDBC connection information
// * @param logger log anything to the logger
// * @return If we can successfull build the service vendor, build it
// */
// Optional<ServiceVendor<?>> buildVendor(String name, Map<String, Object> properties, Logger logger);
// }
// Path: intf/src/main/java/funcatron/intf/impl/JDBCServiceVendorBuilder.java
import com.zaxxer.hikari.HikariConfig;
import com.zaxxer.hikari.HikariDataSource;
import funcatron.intf.Accumulator;
import funcatron.intf.ServiceVendor;
import funcatron.intf.ServiceVendorProvider;
import java.sql.Connection;
import java.sql.Driver;
import java.sql.DriverManager;
import java.util.*;
import java.util.logging.Level;
import java.util.logging.Logger;
return Optional.of(
new ServiceVendor<Connection>() {
/**
* The name of the service
*
* @return the name of the service
*/
@Override
public String name() {
return name;
}
/**
* The type of the service vended
*
* @return the class object of the type of service vended
*/
@Override
public Class<Connection> type() {
return Connection.class;
}
/**
* Vends an instance of the thing (like a JDBC connection)
*
* @param acc the accumulator
* @return an instance of the thing
* @throws Exception failure to create the instance
*/
@Override | public Connection vend(Accumulator acc) throws Exception { |
CorwinJV/MobTotems | src/main/java/com/corwinjv/mobtotems/blocks/tiles/IncenseKindlingBoxTileEntity.java | // Path: src/main/java/com/corwinjv/mobtotems/blocks/tiles/base/ModTileEntity.java
// public class ModTileEntity extends TileEntity {
// public ModTileEntity() {
// super();
// }
//
// @Override
// public NBTTagCompound writeToNBT(NBTTagCompound tagCompound) {
// return super.writeToNBT(tagCompound);
// }
//
// @Override
// public void readFromNBT(NBTTagCompound tagCompound) {
// super.readFromNBT(tagCompound);
// }
//
// @Nonnull
// @Override
// public final NBTTagCompound getUpdateTag() {
// return writeToNBT(super.getUpdateTag());
// }
//
// @Override
// public SPacketUpdateTileEntity getUpdatePacket() {
// return new SPacketUpdateTileEntity(pos, 0, getUpdateTag());
// }
//
// @Override
// public void onDataPacket(NetworkManager networkManager, SPacketUpdateTileEntity packet) {
// super.onDataPacket(networkManager, packet);
// readFromNBT(packet.getNbtCompound());
//
// final IBlockState state = getWorld().getBlockState(getPos());
// getWorld().notifyBlockUpdate(getPos(), state, state, 3);
// }
//
// @Override
// public boolean shouldRefresh(World world, BlockPos pos, @Nonnull IBlockState oldState, @Nonnull IBlockState newState) {
// return (oldState.getBlock() != newState.getBlock());
// }
//
// @Override
// public void markDirty() {
// super.markDirty();
// if (world != null) {
// world.notifyBlockUpdate(pos, world.getBlockState(pos), world.getBlockState(pos), 3);
// }
// }
// }
//
// Path: src/main/java/com/corwinjv/mobtotems/interfaces/IChargeable.java
// public interface IChargeable {
// int getChargeLevel(ItemStack stack);
//
// void setChargeLevel(ItemStack stack, int chargeLevel);
//
// void decrementChargeLevel(ItemStack stack, int amount);
//
// void incrementChargeLevel(ItemStack stack, int amount);
//
// int getMaxChargeLevel();
// }
| import baubles.api.BaublesApi;
import baubles.api.cap.IBaublesItemHandler;
import com.corwinjv.mobtotems.blocks.tiles.base.ModTileEntity;
import com.corwinjv.mobtotems.interfaces.IChargeable;
import net.minecraft.block.Block;
import net.minecraft.block.BlockAir;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.item.ItemStack;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.util.EnumFacing;
import net.minecraft.util.EnumParticleTypes;
import net.minecraft.util.ITickable;
import net.minecraft.util.math.BlockPos;
import javax.annotation.Nonnull;
import java.util.List;
import java.util.Random;
import java.util.function.Predicate; | long worldTime = getWorld().getWorldTime();
if (worldTime % UPDATE_TICKS == 0) {
performChargeAura();
}
} else {
long worldTime = getWorld().getWorldTime();
if (worldTime % PARTICLE_UPDATE_TICKS == 0) {
spawnParticleEffects();
}
}
}
private void performTTLUpdate() {
timeLived++;
if (timeLived > TTL) {
getWorld().destroyBlock(pos, false);
}
}
private void performChargeAura() {
final BlockPos targetPos = getPos();
Predicate<EntityPlayer> playerWithinRangePredicate = input -> input != null
&& input.getPosition().getDistance(targetPos.getX(), targetPos.getY(), targetPos.getZ()) < TMP_MANA_GAIN_DIST;
List<EntityPlayer> playersWithinRange = getWorld().getEntities(EntityPlayer.class, playerWithinRangePredicate::test);
for (EntityPlayer player : playersWithinRange) {
IBaublesItemHandler baublesItemHandler = BaublesApi.getBaublesHandler(player);
for (int i = 0; i < baublesItemHandler.getSlots(); i++) {
final ItemStack baubleStack = baublesItemHandler.getStackInSlot(i);
if (baubleStack != ItemStack.EMPTY | // Path: src/main/java/com/corwinjv/mobtotems/blocks/tiles/base/ModTileEntity.java
// public class ModTileEntity extends TileEntity {
// public ModTileEntity() {
// super();
// }
//
// @Override
// public NBTTagCompound writeToNBT(NBTTagCompound tagCompound) {
// return super.writeToNBT(tagCompound);
// }
//
// @Override
// public void readFromNBT(NBTTagCompound tagCompound) {
// super.readFromNBT(tagCompound);
// }
//
// @Nonnull
// @Override
// public final NBTTagCompound getUpdateTag() {
// return writeToNBT(super.getUpdateTag());
// }
//
// @Override
// public SPacketUpdateTileEntity getUpdatePacket() {
// return new SPacketUpdateTileEntity(pos, 0, getUpdateTag());
// }
//
// @Override
// public void onDataPacket(NetworkManager networkManager, SPacketUpdateTileEntity packet) {
// super.onDataPacket(networkManager, packet);
// readFromNBT(packet.getNbtCompound());
//
// final IBlockState state = getWorld().getBlockState(getPos());
// getWorld().notifyBlockUpdate(getPos(), state, state, 3);
// }
//
// @Override
// public boolean shouldRefresh(World world, BlockPos pos, @Nonnull IBlockState oldState, @Nonnull IBlockState newState) {
// return (oldState.getBlock() != newState.getBlock());
// }
//
// @Override
// public void markDirty() {
// super.markDirty();
// if (world != null) {
// world.notifyBlockUpdate(pos, world.getBlockState(pos), world.getBlockState(pos), 3);
// }
// }
// }
//
// Path: src/main/java/com/corwinjv/mobtotems/interfaces/IChargeable.java
// public interface IChargeable {
// int getChargeLevel(ItemStack stack);
//
// void setChargeLevel(ItemStack stack, int chargeLevel);
//
// void decrementChargeLevel(ItemStack stack, int amount);
//
// void incrementChargeLevel(ItemStack stack, int amount);
//
// int getMaxChargeLevel();
// }
// Path: src/main/java/com/corwinjv/mobtotems/blocks/tiles/IncenseKindlingBoxTileEntity.java
import baubles.api.BaublesApi;
import baubles.api.cap.IBaublesItemHandler;
import com.corwinjv.mobtotems.blocks.tiles.base.ModTileEntity;
import com.corwinjv.mobtotems.interfaces.IChargeable;
import net.minecraft.block.Block;
import net.minecraft.block.BlockAir;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.item.ItemStack;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.util.EnumFacing;
import net.minecraft.util.EnumParticleTypes;
import net.minecraft.util.ITickable;
import net.minecraft.util.math.BlockPos;
import javax.annotation.Nonnull;
import java.util.List;
import java.util.Random;
import java.util.function.Predicate;
long worldTime = getWorld().getWorldTime();
if (worldTime % UPDATE_TICKS == 0) {
performChargeAura();
}
} else {
long worldTime = getWorld().getWorldTime();
if (worldTime % PARTICLE_UPDATE_TICKS == 0) {
spawnParticleEffects();
}
}
}
private void performTTLUpdate() {
timeLived++;
if (timeLived > TTL) {
getWorld().destroyBlock(pos, false);
}
}
private void performChargeAura() {
final BlockPos targetPos = getPos();
Predicate<EntityPlayer> playerWithinRangePredicate = input -> input != null
&& input.getPosition().getDistance(targetPos.getX(), targetPos.getY(), targetPos.getZ()) < TMP_MANA_GAIN_DIST;
List<EntityPlayer> playersWithinRange = getWorld().getEntities(EntityPlayer.class, playerWithinRangePredicate::test);
for (EntityPlayer player : playersWithinRange) {
IBaublesItemHandler baublesItemHandler = BaublesApi.getBaublesHandler(player);
for (int i = 0; i < baublesItemHandler.getSlots(); i++) {
final ItemStack baubleStack = baublesItemHandler.getStackInSlot(i);
if (baubleStack != ItemStack.EMPTY | && baubleStack.getItem() instanceof IChargeable) { |
CorwinJV/MobTotems | src/main/java/com/corwinjv/mobtotems/entities/EntitySpiritWolf.java | // Path: src/main/java/com/corwinjv/mobtotems/MobTotems.java
// @Mod(modid = Reference.MOD_ID, name = Reference.MOD_NAME, version = Reference.MOD_VERSION, guiFactory = Reference.GUI_FACTORY_CLASS,
// dependencies = "before:guideapi")
// public class MobTotems {
// @Mod.Instance
// public static MobTotems instance;
//
// @SidedProxy(clientSide = Reference.CLIENT_SIDE_PROXY_CLASS, serverSide = Reference.SERVER_SIDE_PROXY_CLASS)
// public static CommonProxy proxy;
//
// private static MobTotemsComponent mobTotemsComponent;
//
// @Mod.EventHandler
// public void preInit(FMLPreInitializationEvent event) {
// // //Dagger 2 implementation
// // mobTotemsComponent = proxy.initializeDagger(instance);
//
// // Network & Messages
// Network.init();
// NetworkRegistry.INSTANCE.registerGuiHandler(instance, new OfferingBoxGuiHandler());
//
// // Config
// ConfigurationHandler.Init(event.getSuggestedConfigurationFile());
// MinecraftForge.EVENT_BUS.register(new ConfigurationHandler());
//
// // Helper stuff
// TotemHelper.init();
// MinecraftForge.EVENT_BUS.register(new CreeperLogic.CreeperTotemEntityJoinWorldEvent());
// MinecraftForge.EVENT_BUS.register(new CowLogic.CowTotemEntityJoinWorldEvent());
// MinecraftForge.EVENT_BUS.register(new EnderLogic.EnderTotemEnderTeleportEvent());
//
// // Blocks
// ModBlocks.init();
//
// // Items
// ModItems.init();
//
// // Entities
// ModEntities.init();
// ModEntities.registerEntities(instance);
// proxy.registerEntityRenders();
//
// // Keybinds
// proxy.registerKeys();
// }
//
// public static MobTotemsComponent component() {
// return mobTotemsComponent;
// }
//
// @Mod.EventHandler
// public void init(FMLInitializationEvent event) {
// proxy.registerRenders();
// }
//
// @Mod.EventHandler
// public void postInit(FMLPostInitializationEvent event) {
// proxy.registerGui();
// proxy.registerParticleRenderer();
// }
// }
//
// Path: src/main/java/com/corwinjv/mobtotems/particles/ModParticles.java
// public class ModParticles {
// public static final int WOLF_IDLE_SMOKE = 0;
// public static final int WOLF_ENTRANCE_SMOKE = 1;
// public static final int WOLF_EXIT_SMOKE = 2;
//
// @SideOnly(Side.CLIENT)
// public static class Factory implements IParticleFactory {
// @Nullable
// public Particle createParticle(int particleID, @Nonnull World worldIn, double xCoordIn, double yCoordIn, double zCoordIn, double xSpeedIn, double ySpeedIn, double zSpeedIn, int... p_178902_15_) {
// Particle ret = null;
//
// switch (particleID) {
// case WOLF_IDLE_SMOKE: {
// ret = new WolfIdleParticle(worldIn, xCoordIn, yCoordIn, zCoordIn, xSpeedIn, ySpeedIn, zSpeedIn);
// break;
// }
// default: {
// FMLLog.log(Level.ERROR, "Unknown particleId: " + particleID);
// break;
// }
// }
//
// return ret;
// }
// }
// }
| import com.corwinjv.mobtotems.MobTotems;
import com.corwinjv.mobtotems.particles.ModParticles;
import net.minecraft.client.Minecraft;
import net.minecraft.client.particle.IParticleFactory;
import net.minecraft.client.particle.Particle;
import net.minecraft.entity.SharedMonsterAttributes;
import net.minecraft.entity.ai.*;
import net.minecraft.entity.monster.EntityMob;
import net.minecraft.entity.passive.EntityWolf;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.util.math.Vec3d;
import net.minecraft.world.World;
import net.minecraftforge.fml.relauncher.Side;
import net.minecraftforge.fml.relauncher.SideOnly; | }
if (getEntityWorld().isRemote) {
spawnParticles();
}
}
@SuppressWarnings("unchecked")
@Override
protected void initEntityAI() {
this.aiSit = new EntityAISit(this);
this.tasks.addTask(1, new EntityAISwimming(this));
this.tasks.addTask(3, new EntityAILeapAtTarget(this, 0.4F));
this.tasks.addTask(4, new EntityAIAttackMelee(this, 1.0D, true));
this.tasks.addTask(5, new EntityAIFollowOwner(this, 1.0D, 10.0F, 2.0F));
this.tasks.addTask(7, new EntityAIWander(this, 1.0D));
this.targetTasks.addTask(1, new EntityAIOwnerHurtByTarget(this));
this.targetTasks.addTask(2, new EntityAIOwnerHurtTarget(this));
this.targetTasks.addTask(3, new EntityAIHurtByTarget(this, true));
this.targetTasks.addTask(5, new EntityAINearestAttackableTarget(this, EntityMob.class, false));
}
@Override
protected void applyEntityAttributes() {
super.applyEntityAttributes();
this.getEntityAttribute(SharedMonsterAttributes.ATTACK_DAMAGE).setBaseValue(4.0D);
}
@SideOnly(Side.CLIENT)
private void spawnParticles() { | // Path: src/main/java/com/corwinjv/mobtotems/MobTotems.java
// @Mod(modid = Reference.MOD_ID, name = Reference.MOD_NAME, version = Reference.MOD_VERSION, guiFactory = Reference.GUI_FACTORY_CLASS,
// dependencies = "before:guideapi")
// public class MobTotems {
// @Mod.Instance
// public static MobTotems instance;
//
// @SidedProxy(clientSide = Reference.CLIENT_SIDE_PROXY_CLASS, serverSide = Reference.SERVER_SIDE_PROXY_CLASS)
// public static CommonProxy proxy;
//
// private static MobTotemsComponent mobTotemsComponent;
//
// @Mod.EventHandler
// public void preInit(FMLPreInitializationEvent event) {
// // //Dagger 2 implementation
// // mobTotemsComponent = proxy.initializeDagger(instance);
//
// // Network & Messages
// Network.init();
// NetworkRegistry.INSTANCE.registerGuiHandler(instance, new OfferingBoxGuiHandler());
//
// // Config
// ConfigurationHandler.Init(event.getSuggestedConfigurationFile());
// MinecraftForge.EVENT_BUS.register(new ConfigurationHandler());
//
// // Helper stuff
// TotemHelper.init();
// MinecraftForge.EVENT_BUS.register(new CreeperLogic.CreeperTotemEntityJoinWorldEvent());
// MinecraftForge.EVENT_BUS.register(new CowLogic.CowTotemEntityJoinWorldEvent());
// MinecraftForge.EVENT_BUS.register(new EnderLogic.EnderTotemEnderTeleportEvent());
//
// // Blocks
// ModBlocks.init();
//
// // Items
// ModItems.init();
//
// // Entities
// ModEntities.init();
// ModEntities.registerEntities(instance);
// proxy.registerEntityRenders();
//
// // Keybinds
// proxy.registerKeys();
// }
//
// public static MobTotemsComponent component() {
// return mobTotemsComponent;
// }
//
// @Mod.EventHandler
// public void init(FMLInitializationEvent event) {
// proxy.registerRenders();
// }
//
// @Mod.EventHandler
// public void postInit(FMLPostInitializationEvent event) {
// proxy.registerGui();
// proxy.registerParticleRenderer();
// }
// }
//
// Path: src/main/java/com/corwinjv/mobtotems/particles/ModParticles.java
// public class ModParticles {
// public static final int WOLF_IDLE_SMOKE = 0;
// public static final int WOLF_ENTRANCE_SMOKE = 1;
// public static final int WOLF_EXIT_SMOKE = 2;
//
// @SideOnly(Side.CLIENT)
// public static class Factory implements IParticleFactory {
// @Nullable
// public Particle createParticle(int particleID, @Nonnull World worldIn, double xCoordIn, double yCoordIn, double zCoordIn, double xSpeedIn, double ySpeedIn, double zSpeedIn, int... p_178902_15_) {
// Particle ret = null;
//
// switch (particleID) {
// case WOLF_IDLE_SMOKE: {
// ret = new WolfIdleParticle(worldIn, xCoordIn, yCoordIn, zCoordIn, xSpeedIn, ySpeedIn, zSpeedIn);
// break;
// }
// default: {
// FMLLog.log(Level.ERROR, "Unknown particleId: " + particleID);
// break;
// }
// }
//
// return ret;
// }
// }
// }
// Path: src/main/java/com/corwinjv/mobtotems/entities/EntitySpiritWolf.java
import com.corwinjv.mobtotems.MobTotems;
import com.corwinjv.mobtotems.particles.ModParticles;
import net.minecraft.client.Minecraft;
import net.minecraft.client.particle.IParticleFactory;
import net.minecraft.client.particle.Particle;
import net.minecraft.entity.SharedMonsterAttributes;
import net.minecraft.entity.ai.*;
import net.minecraft.entity.monster.EntityMob;
import net.minecraft.entity.passive.EntityWolf;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.util.math.Vec3d;
import net.minecraft.world.World;
import net.minecraftforge.fml.relauncher.Side;
import net.minecraftforge.fml.relauncher.SideOnly;
}
if (getEntityWorld().isRemote) {
spawnParticles();
}
}
@SuppressWarnings("unchecked")
@Override
protected void initEntityAI() {
this.aiSit = new EntityAISit(this);
this.tasks.addTask(1, new EntityAISwimming(this));
this.tasks.addTask(3, new EntityAILeapAtTarget(this, 0.4F));
this.tasks.addTask(4, new EntityAIAttackMelee(this, 1.0D, true));
this.tasks.addTask(5, new EntityAIFollowOwner(this, 1.0D, 10.0F, 2.0F));
this.tasks.addTask(7, new EntityAIWander(this, 1.0D));
this.targetTasks.addTask(1, new EntityAIOwnerHurtByTarget(this));
this.targetTasks.addTask(2, new EntityAIOwnerHurtTarget(this));
this.targetTasks.addTask(3, new EntityAIHurtByTarget(this, true));
this.targetTasks.addTask(5, new EntityAINearestAttackableTarget(this, EntityMob.class, false));
}
@Override
protected void applyEntityAttributes() {
super.applyEntityAttributes();
this.getEntityAttribute(SharedMonsterAttributes.ATTACK_DAMAGE).setBaseValue(4.0D);
}
@SideOnly(Side.CLIENT)
private void spawnParticles() { | IParticleFactory particleFactory = new ModParticles.Factory(); |
CorwinJV/MobTotems | src/main/java/baubles/api/cap/BaublesCapabilities.java | // Path: src/main/java/baubles/api/IBauble.java
// public interface IBauble {
//
// /**
// * This method return the type of bauble this is.
// * Type is used to determine the slots it can go into.
// */
// public BaubleType getBaubleType(ItemStack itemstack);
//
// /**
// * This method is called once per tick if the bauble is being worn by a player
// */
// public default void onWornTick(ItemStack itemstack, EntityLivingBase player) {
// }
//
// /**
// * This method is called when the bauble is equipped by a player
// */
// public default void onEquipped(ItemStack itemstack, EntityLivingBase player) {
// }
//
// /**
// * This method is called when the bauble is unequipped by a player
// */
// public default void onUnequipped(ItemStack itemstack, EntityLivingBase player) {
// }
//
// /**
// * can this bauble be placed in a bauble slot
// */
// public default boolean canEquip(ItemStack itemstack, EntityLivingBase player) {
// return true;
// }
//
// /**
// * Can this bauble be removed from a bauble slot
// */
// public default boolean canUnequip(ItemStack itemstack, EntityLivingBase player) {
// return true;
// }
//
// /**
// * Will bauble automatically sync to client if a change is detected in its NBT or damage values?
// * Default is off, so override and set to true if you want to auto sync.
// * This sync is not instant, but occurs every 10 ticks (.5 seconds).
// */
// public default boolean willAutoSync(ItemStack itemstack, EntityLivingBase player) {
// return false;
// }
// }
| import baubles.api.IBauble;
import net.minecraft.nbt.NBTBase;
import net.minecraft.util.EnumFacing;
import net.minecraftforge.common.capabilities.Capability;
import net.minecraftforge.common.capabilities.Capability.IStorage;
import net.minecraftforge.common.capabilities.CapabilityInject; | package baubles.api.cap;
public class BaublesCapabilities {
/**
* Access to the baubles capability.
*/
@CapabilityInject(IBaublesItemHandler.class)
public static final Capability<IBaublesItemHandler> CAPABILITY_BAUBLES = null;
| // Path: src/main/java/baubles/api/IBauble.java
// public interface IBauble {
//
// /**
// * This method return the type of bauble this is.
// * Type is used to determine the slots it can go into.
// */
// public BaubleType getBaubleType(ItemStack itemstack);
//
// /**
// * This method is called once per tick if the bauble is being worn by a player
// */
// public default void onWornTick(ItemStack itemstack, EntityLivingBase player) {
// }
//
// /**
// * This method is called when the bauble is equipped by a player
// */
// public default void onEquipped(ItemStack itemstack, EntityLivingBase player) {
// }
//
// /**
// * This method is called when the bauble is unequipped by a player
// */
// public default void onUnequipped(ItemStack itemstack, EntityLivingBase player) {
// }
//
// /**
// * can this bauble be placed in a bauble slot
// */
// public default boolean canEquip(ItemStack itemstack, EntityLivingBase player) {
// return true;
// }
//
// /**
// * Can this bauble be removed from a bauble slot
// */
// public default boolean canUnequip(ItemStack itemstack, EntityLivingBase player) {
// return true;
// }
//
// /**
// * Will bauble automatically sync to client if a change is detected in its NBT or damage values?
// * Default is off, so override and set to true if you want to auto sync.
// * This sync is not instant, but occurs every 10 ticks (.5 seconds).
// */
// public default boolean willAutoSync(ItemStack itemstack, EntityLivingBase player) {
// return false;
// }
// }
// Path: src/main/java/baubles/api/cap/BaublesCapabilities.java
import baubles.api.IBauble;
import net.minecraft.nbt.NBTBase;
import net.minecraft.util.EnumFacing;
import net.minecraftforge.common.capabilities.Capability;
import net.minecraftforge.common.capabilities.Capability.IStorage;
import net.minecraftforge.common.capabilities.CapabilityInject;
package baubles.api.cap;
public class BaublesCapabilities {
/**
* Access to the baubles capability.
*/
@CapabilityInject(IBaublesItemHandler.class)
public static final Capability<IBaublesItemHandler> CAPABILITY_BAUBLES = null;
| @CapabilityInject(IBauble.class) |
CorwinJV/MobTotems | src/main/java/baubles/api/cap/BaublesContainer.java | // Path: src/main/java/baubles/api/IBauble.java
// public interface IBauble {
//
// /**
// * This method return the type of bauble this is.
// * Type is used to determine the slots it can go into.
// */
// public BaubleType getBaubleType(ItemStack itemstack);
//
// /**
// * This method is called once per tick if the bauble is being worn by a player
// */
// public default void onWornTick(ItemStack itemstack, EntityLivingBase player) {
// }
//
// /**
// * This method is called when the bauble is equipped by a player
// */
// public default void onEquipped(ItemStack itemstack, EntityLivingBase player) {
// }
//
// /**
// * This method is called when the bauble is unequipped by a player
// */
// public default void onUnequipped(ItemStack itemstack, EntityLivingBase player) {
// }
//
// /**
// * can this bauble be placed in a bauble slot
// */
// public default boolean canEquip(ItemStack itemstack, EntityLivingBase player) {
// return true;
// }
//
// /**
// * Can this bauble be removed from a bauble slot
// */
// public default boolean canUnequip(ItemStack itemstack, EntityLivingBase player) {
// return true;
// }
//
// /**
// * Will bauble automatically sync to client if a change is detected in its NBT or damage values?
// * Default is off, so override and set to true if you want to auto sync.
// * This sync is not instant, but occurs every 10 ticks (.5 seconds).
// */
// public default boolean willAutoSync(ItemStack itemstack, EntityLivingBase player) {
// return false;
// }
// }
| import baubles.api.IBauble;
import net.minecraft.entity.EntityLivingBase;
import net.minecraft.item.ItemStack;
import net.minecraftforge.items.ItemStackHandler; | package baubles.api.cap;
public class BaublesContainer extends ItemStackHandler implements IBaublesItemHandler {
private final static int BAUBLE_SLOTS = 7;
private boolean[] changed = new boolean[BAUBLE_SLOTS];
private boolean blockEvents=false;
private EntityLivingBase player;
public BaublesContainer()
{
super(BAUBLE_SLOTS);
}
@Override
public void setSize(int size)
{
if (size<BAUBLE_SLOTS) size = BAUBLE_SLOTS;
super.setSize(size);
boolean[] old = changed;
changed = new boolean[size];
for(int i = 0;i<old.length && i<changed.length;i++)
{
changed[i] = old[i];
}
}
/**
* Returns true if automation is allowed to insert the given stack (ignoring
* stack size) into the given slot.
*/
@Override
public boolean isItemValidForSlot(int slot, ItemStack stack, EntityLivingBase player) {
if (stack==null || stack.isEmpty() || !stack.hasCapability(BaublesCapabilities.CAPABILITY_ITEM_BAUBLE, null))
return false; | // Path: src/main/java/baubles/api/IBauble.java
// public interface IBauble {
//
// /**
// * This method return the type of bauble this is.
// * Type is used to determine the slots it can go into.
// */
// public BaubleType getBaubleType(ItemStack itemstack);
//
// /**
// * This method is called once per tick if the bauble is being worn by a player
// */
// public default void onWornTick(ItemStack itemstack, EntityLivingBase player) {
// }
//
// /**
// * This method is called when the bauble is equipped by a player
// */
// public default void onEquipped(ItemStack itemstack, EntityLivingBase player) {
// }
//
// /**
// * This method is called when the bauble is unequipped by a player
// */
// public default void onUnequipped(ItemStack itemstack, EntityLivingBase player) {
// }
//
// /**
// * can this bauble be placed in a bauble slot
// */
// public default boolean canEquip(ItemStack itemstack, EntityLivingBase player) {
// return true;
// }
//
// /**
// * Can this bauble be removed from a bauble slot
// */
// public default boolean canUnequip(ItemStack itemstack, EntityLivingBase player) {
// return true;
// }
//
// /**
// * Will bauble automatically sync to client if a change is detected in its NBT or damage values?
// * Default is off, so override and set to true if you want to auto sync.
// * This sync is not instant, but occurs every 10 ticks (.5 seconds).
// */
// public default boolean willAutoSync(ItemStack itemstack, EntityLivingBase player) {
// return false;
// }
// }
// Path: src/main/java/baubles/api/cap/BaublesContainer.java
import baubles.api.IBauble;
import net.minecraft.entity.EntityLivingBase;
import net.minecraft.item.ItemStack;
import net.minecraftforge.items.ItemStackHandler;
package baubles.api.cap;
public class BaublesContainer extends ItemStackHandler implements IBaublesItemHandler {
private final static int BAUBLE_SLOTS = 7;
private boolean[] changed = new boolean[BAUBLE_SLOTS];
private boolean blockEvents=false;
private EntityLivingBase player;
public BaublesContainer()
{
super(BAUBLE_SLOTS);
}
@Override
public void setSize(int size)
{
if (size<BAUBLE_SLOTS) size = BAUBLE_SLOTS;
super.setSize(size);
boolean[] old = changed;
changed = new boolean[size];
for(int i = 0;i<old.length && i<changed.length;i++)
{
changed[i] = old[i];
}
}
/**
* Returns true if automation is allowed to insert the given stack (ignoring
* stack size) into the given slot.
*/
@Override
public boolean isItemValidForSlot(int slot, ItemStack stack, EntityLivingBase player) {
if (stack==null || stack.isEmpty() || !stack.hasCapability(BaublesCapabilities.CAPABILITY_ITEM_BAUBLE, null))
return false; | IBauble bauble = stack.getCapability(BaublesCapabilities.CAPABILITY_ITEM_BAUBLE, null); |
CorwinJV/MobTotems | src/main/java/com/corwinjv/mobtotems/blocks/ModBlock.java | // Path: src/main/java/com/corwinjv/mobtotems/Reference.java
// public class Reference {
// public static final String MOD_ID = "mobtotems";
// public static final String MOD_NAME = "Mob Totems";
// public static final String MOD_VERSION = "1.12.1-0.3.0";
// public static final String RESOURCE_PREFIX = MOD_ID + ":";
//
// public static final String GUI_FACTORY_CLASS = "com.corwinjv.mobtotems.gui.GuiFactoryMT";
// public static final String CLIENT_SIDE_PROXY_CLASS = "com.corwinjv.mobtotems.proxy.ClientProxy";
// public static final String SERVER_SIDE_PROXY_CLASS = "com.corwinjv.mobtotems.proxy.CommonProxy";
//
// public static final int CHARGE_COLOR = 0xFF00FF00;
//
// public enum GUI_ID {
// OFFERING_BOX
// }
//
// ;
//
// public static void PrintEntityList() {
// Iterator entityNameItr = EntityList.getEntityNameList().iterator();
// FMLLog.log(Reference.MOD_NAME, Level.INFO, "-Printing Registered Entity Classes-");
// while (entityNameItr.hasNext()) {
// String key = (String) entityNameItr.next();
// FMLLog.log(Reference.MOD_NAME, Level.INFO, String.format(" %s", key));
// }
// }
// }
//
// Path: src/main/java/com/corwinjv/mobtotems/creativetab/CreativeTabMT.java
// public class CreativeTabMT {
// public static final CreativeTabs MT_TAB = new CreativeTabs(Reference.MOD_ID) {
// @Override
// public ItemStack getTabIconItem() {
// return new ItemStack(ModItems.TOTEMIC_FOCUS);
// }
// };
// }
| import com.corwinjv.mobtotems.Reference;
import com.corwinjv.mobtotems.creativetab.CreativeTabMT;
import net.minecraft.block.Block;
import net.minecraft.block.material.Material; | package com.corwinjv.mobtotems.blocks;
/**
* Created by CorwinJV on 9/1/14.
*/
public class ModBlock extends Block {
public ModBlock(Material aMaterial) {
super(aMaterial);
this.init();
}
public ModBlock() {
super(Material.WOOD);
this.init();
}
public void init() { | // Path: src/main/java/com/corwinjv/mobtotems/Reference.java
// public class Reference {
// public static final String MOD_ID = "mobtotems";
// public static final String MOD_NAME = "Mob Totems";
// public static final String MOD_VERSION = "1.12.1-0.3.0";
// public static final String RESOURCE_PREFIX = MOD_ID + ":";
//
// public static final String GUI_FACTORY_CLASS = "com.corwinjv.mobtotems.gui.GuiFactoryMT";
// public static final String CLIENT_SIDE_PROXY_CLASS = "com.corwinjv.mobtotems.proxy.ClientProxy";
// public static final String SERVER_SIDE_PROXY_CLASS = "com.corwinjv.mobtotems.proxy.CommonProxy";
//
// public static final int CHARGE_COLOR = 0xFF00FF00;
//
// public enum GUI_ID {
// OFFERING_BOX
// }
//
// ;
//
// public static void PrintEntityList() {
// Iterator entityNameItr = EntityList.getEntityNameList().iterator();
// FMLLog.log(Reference.MOD_NAME, Level.INFO, "-Printing Registered Entity Classes-");
// while (entityNameItr.hasNext()) {
// String key = (String) entityNameItr.next();
// FMLLog.log(Reference.MOD_NAME, Level.INFO, String.format(" %s", key));
// }
// }
// }
//
// Path: src/main/java/com/corwinjv/mobtotems/creativetab/CreativeTabMT.java
// public class CreativeTabMT {
// public static final CreativeTabs MT_TAB = new CreativeTabs(Reference.MOD_ID) {
// @Override
// public ItemStack getTabIconItem() {
// return new ItemStack(ModItems.TOTEMIC_FOCUS);
// }
// };
// }
// Path: src/main/java/com/corwinjv/mobtotems/blocks/ModBlock.java
import com.corwinjv.mobtotems.Reference;
import com.corwinjv.mobtotems.creativetab.CreativeTabMT;
import net.minecraft.block.Block;
import net.minecraft.block.material.Material;
package com.corwinjv.mobtotems.blocks;
/**
* Created by CorwinJV on 9/1/14.
*/
public class ModBlock extends Block {
public ModBlock(Material aMaterial) {
super(aMaterial);
this.init();
}
public ModBlock() {
super(Material.WOOD);
this.init();
}
public void init() { | this.setCreativeTab(CreativeTabMT.MT_TAB); |
CorwinJV/MobTotems | src/main/java/com/corwinjv/mobtotems/blocks/ModBlock.java | // Path: src/main/java/com/corwinjv/mobtotems/Reference.java
// public class Reference {
// public static final String MOD_ID = "mobtotems";
// public static final String MOD_NAME = "Mob Totems";
// public static final String MOD_VERSION = "1.12.1-0.3.0";
// public static final String RESOURCE_PREFIX = MOD_ID + ":";
//
// public static final String GUI_FACTORY_CLASS = "com.corwinjv.mobtotems.gui.GuiFactoryMT";
// public static final String CLIENT_SIDE_PROXY_CLASS = "com.corwinjv.mobtotems.proxy.ClientProxy";
// public static final String SERVER_SIDE_PROXY_CLASS = "com.corwinjv.mobtotems.proxy.CommonProxy";
//
// public static final int CHARGE_COLOR = 0xFF00FF00;
//
// public enum GUI_ID {
// OFFERING_BOX
// }
//
// ;
//
// public static void PrintEntityList() {
// Iterator entityNameItr = EntityList.getEntityNameList().iterator();
// FMLLog.log(Reference.MOD_NAME, Level.INFO, "-Printing Registered Entity Classes-");
// while (entityNameItr.hasNext()) {
// String key = (String) entityNameItr.next();
// FMLLog.log(Reference.MOD_NAME, Level.INFO, String.format(" %s", key));
// }
// }
// }
//
// Path: src/main/java/com/corwinjv/mobtotems/creativetab/CreativeTabMT.java
// public class CreativeTabMT {
// public static final CreativeTabs MT_TAB = new CreativeTabs(Reference.MOD_ID) {
// @Override
// public ItemStack getTabIconItem() {
// return new ItemStack(ModItems.TOTEMIC_FOCUS);
// }
// };
// }
| import com.corwinjv.mobtotems.Reference;
import com.corwinjv.mobtotems.creativetab.CreativeTabMT;
import net.minecraft.block.Block;
import net.minecraft.block.material.Material; | package com.corwinjv.mobtotems.blocks;
/**
* Created by CorwinJV on 9/1/14.
*/
public class ModBlock extends Block {
public ModBlock(Material aMaterial) {
super(aMaterial);
this.init();
}
public ModBlock() {
super(Material.WOOD);
this.init();
}
public void init() {
this.setCreativeTab(CreativeTabMT.MT_TAB);
}
@Override
public String getUnlocalizedName() { | // Path: src/main/java/com/corwinjv/mobtotems/Reference.java
// public class Reference {
// public static final String MOD_ID = "mobtotems";
// public static final String MOD_NAME = "Mob Totems";
// public static final String MOD_VERSION = "1.12.1-0.3.0";
// public static final String RESOURCE_PREFIX = MOD_ID + ":";
//
// public static final String GUI_FACTORY_CLASS = "com.corwinjv.mobtotems.gui.GuiFactoryMT";
// public static final String CLIENT_SIDE_PROXY_CLASS = "com.corwinjv.mobtotems.proxy.ClientProxy";
// public static final String SERVER_SIDE_PROXY_CLASS = "com.corwinjv.mobtotems.proxy.CommonProxy";
//
// public static final int CHARGE_COLOR = 0xFF00FF00;
//
// public enum GUI_ID {
// OFFERING_BOX
// }
//
// ;
//
// public static void PrintEntityList() {
// Iterator entityNameItr = EntityList.getEntityNameList().iterator();
// FMLLog.log(Reference.MOD_NAME, Level.INFO, "-Printing Registered Entity Classes-");
// while (entityNameItr.hasNext()) {
// String key = (String) entityNameItr.next();
// FMLLog.log(Reference.MOD_NAME, Level.INFO, String.format(" %s", key));
// }
// }
// }
//
// Path: src/main/java/com/corwinjv/mobtotems/creativetab/CreativeTabMT.java
// public class CreativeTabMT {
// public static final CreativeTabs MT_TAB = new CreativeTabs(Reference.MOD_ID) {
// @Override
// public ItemStack getTabIconItem() {
// return new ItemStack(ModItems.TOTEMIC_FOCUS);
// }
// };
// }
// Path: src/main/java/com/corwinjv/mobtotems/blocks/ModBlock.java
import com.corwinjv.mobtotems.Reference;
import com.corwinjv.mobtotems.creativetab.CreativeTabMT;
import net.minecraft.block.Block;
import net.minecraft.block.material.Material;
package com.corwinjv.mobtotems.blocks;
/**
* Created by CorwinJV on 9/1/14.
*/
public class ModBlock extends Block {
public ModBlock(Material aMaterial) {
super(aMaterial);
this.init();
}
public ModBlock() {
super(Material.WOOD);
this.init();
}
public void init() {
this.setCreativeTab(CreativeTabMT.MT_TAB);
}
@Override
public String getUnlocalizedName() { | return String.format("tiles.%s%s", Reference.RESOURCE_PREFIX, getUnwrappedUnlocalizedName(super.getUnlocalizedName())); |
CorwinJV/MobTotems | src/main/java/com/corwinjv/mobtotems/items/TotemicFocus.java | // Path: src/main/java/com/corwinjv/mobtotems/blocks/ModBlocks.java
// @Mod.EventBusSubscriber(modid = Reference.MOD_ID)
// public class ModBlocks {
// public static final HashSet<ItemBlock> ITEM_BLOCKS = new HashSet<>();
//
// public static final String TOTEM_WOOD_NAME = "totem_wood";
// public static final String SACRED_LIGHT_NAME = "sacred_light";
// public static final String INCENSE_KINDLING_BOX_NAME = "incense_kindling_box";
// public static final String OFFERING_BOX_NAME = "offering_box";
//
// public static final Block TOTEM_WOOD = new TotemWoodBlock().setUnlocalizedName(TOTEM_WOOD_NAME).setRegistryName(Reference.MOD_ID, TOTEM_WOOD_NAME);
// public static final Block SACRED_LIGHT = new SacredLightBlock().setUnlocalizedName(SACRED_LIGHT_NAME).setRegistryName(Reference.MOD_ID, SACRED_LIGHT_NAME);
// public static final Block INCENSE_KINDLING_BOX = new IncenseKindlingBox().setUnlocalizedName(INCENSE_KINDLING_BOX_NAME).setRegistryName(Reference.MOD_ID, INCENSE_KINDLING_BOX_NAME);
// public static final Block OFFERING_BOX = new OfferingBox().setUnlocalizedName(OFFERING_BOX_NAME).setRegistryName(Reference.MOD_ID, OFFERING_BOX_NAME);
//
// public static void init() {
// }
//
// @SubscribeEvent
// public static void registerBlocks(RegistryEvent.Register<Block> e) {
// final IForgeRegistry<Block> registry = e.getRegistry();
// final Block[] blocks = {
// TOTEM_WOOD,
// SACRED_LIGHT,
// INCENSE_KINDLING_BOX,
// OFFERING_BOX
// };
//
// registry.registerAll(blocks);
// }
//
// @SubscribeEvent
// public static void registerItemBlocks(RegistryEvent.Register<Item> e) {
// final IForgeRegistry<Item> registry = e.getRegistry();
//
// final ItemBlock[] items = {
// new TotemWoodItemBlock(TOTEM_WOOD),
// new ItemBlock(SACRED_LIGHT),
// new ItemBlock(INCENSE_KINDLING_BOX),
// new ItemBlock(OFFERING_BOX),
// };
//
// for(final ItemBlock item : items)
// {
// final Block block = item.getBlock();
// final ResourceLocation registryName = Preconditions.checkNotNull(block.getRegistryName(), "Block %s has null registry name", block);
// registry.register(item.setRegistryName(registryName));
// ITEM_BLOCKS.add(item);
// }
//
// registerTileEntities();
// }
//
// private static void registerTileEntities()
// {
// GameRegistry.registerTileEntity(TotemTileEntity.class, Reference.RESOURCE_PREFIX + TOTEM_WOOD_NAME);
// GameRegistry.registerTileEntity(SacredLightTileEntity.class, Reference.RESOURCE_PREFIX + SACRED_LIGHT_NAME);
// GameRegistry.registerTileEntity(IncenseKindlingBoxTileEntity.class, Reference.RESOURCE_PREFIX + INCENSE_KINDLING_BOX_NAME);
// GameRegistry.registerTileEntity(OfferingBoxTileEntity.class, Reference.RESOURCE_PREFIX + OFFERING_BOX_NAME);
// }
//
// @SubscribeEvent
// public static void registerRenders(ModelRegistryEvent e) {
// for (int i = 0; i < TotemType.values().length; i++) {
// Item item = Item.getItemFromBlock(TOTEM_WOOD);
// ModelResourceLocation modelResourceLocation = new ModelResourceLocation(Reference.RESOURCE_PREFIX + TOTEM_WOOD_NAME, "totem_type=" + TotemType.fromMeta(i).getName());
// ModelLoader.setCustomModelResourceLocation(item, i, modelResourceLocation);
// }
//
// registerRender(SACRED_LIGHT, SACRED_LIGHT_NAME);
// registerRender(INCENSE_KINDLING_BOX, INCENSE_KINDLING_BOX_NAME);
// registerRender(OFFERING_BOX, OFFERING_BOX_NAME);
// }
//
// private static void registerRender(Block block, String key) {
// Item item = Item.getItemFromBlock(block);
// ModelLoader.setCustomModelResourceLocation(item, 0, new ModelResourceLocation(Reference.RESOURCE_PREFIX + key, "inventory"));
// }
// }
//
// Path: src/main/java/com/corwinjv/mobtotems/utils/BlockUtils.java
// public class BlockUtils {
// // Returns an instance of the block at the given position in the given world
// public static Block getBlock(World world, BlockPos pos) {
// Block targetBlock = null;
// if (pos != null) {
// targetBlock = world.getBlockState(pos).getBlock();
// }
// return targetBlock;
// }
//
// public static boolean isAreaSolid(EntityPlayer player, BlockPos centerPos) {
// for (double x = centerPos.getX() - 1; x <= centerPos.getX() + 1; x++) {
// for (double z = centerPos.getZ() - 1; z <= centerPos.getZ() + 1; z++) {
// IBlockState blockState = player.world.getBlockState(new BlockPos(x, player.posY, z));
// if (blockState.getMaterial().isSolid()) {
// return true;
// }
// }
// }
// return false;
// }
// }
| import com.corwinjv.mobtotems.blocks.ModBlocks;
import com.corwinjv.mobtotems.utils.BlockUtils;
import net.minecraft.block.Block;
import net.minecraft.block.BlockLog;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.item.EnumAction;
import net.minecraft.item.ItemStack;
import net.minecraft.util.EnumActionResult;
import net.minecraft.util.EnumFacing;
import net.minecraft.util.EnumHand;
import net.minecraft.util.math.BlockPos;
import net.minecraft.world.World;
import javax.annotation.Nonnull; | package com.corwinjv.mobtotems.items;
/**
* Created by CorwinJV on 2/17/2016.
*/
public class TotemicFocus extends ModItem {
@Nonnull
@Override
public EnumActionResult onItemUse(EntityPlayer player, World world, BlockPos pos, EnumHand enumHand, EnumFacing side, float hitX, float hitY, float hitZ) {
if (!world.isRemote) { | // Path: src/main/java/com/corwinjv/mobtotems/blocks/ModBlocks.java
// @Mod.EventBusSubscriber(modid = Reference.MOD_ID)
// public class ModBlocks {
// public static final HashSet<ItemBlock> ITEM_BLOCKS = new HashSet<>();
//
// public static final String TOTEM_WOOD_NAME = "totem_wood";
// public static final String SACRED_LIGHT_NAME = "sacred_light";
// public static final String INCENSE_KINDLING_BOX_NAME = "incense_kindling_box";
// public static final String OFFERING_BOX_NAME = "offering_box";
//
// public static final Block TOTEM_WOOD = new TotemWoodBlock().setUnlocalizedName(TOTEM_WOOD_NAME).setRegistryName(Reference.MOD_ID, TOTEM_WOOD_NAME);
// public static final Block SACRED_LIGHT = new SacredLightBlock().setUnlocalizedName(SACRED_LIGHT_NAME).setRegistryName(Reference.MOD_ID, SACRED_LIGHT_NAME);
// public static final Block INCENSE_KINDLING_BOX = new IncenseKindlingBox().setUnlocalizedName(INCENSE_KINDLING_BOX_NAME).setRegistryName(Reference.MOD_ID, INCENSE_KINDLING_BOX_NAME);
// public static final Block OFFERING_BOX = new OfferingBox().setUnlocalizedName(OFFERING_BOX_NAME).setRegistryName(Reference.MOD_ID, OFFERING_BOX_NAME);
//
// public static void init() {
// }
//
// @SubscribeEvent
// public static void registerBlocks(RegistryEvent.Register<Block> e) {
// final IForgeRegistry<Block> registry = e.getRegistry();
// final Block[] blocks = {
// TOTEM_WOOD,
// SACRED_LIGHT,
// INCENSE_KINDLING_BOX,
// OFFERING_BOX
// };
//
// registry.registerAll(blocks);
// }
//
// @SubscribeEvent
// public static void registerItemBlocks(RegistryEvent.Register<Item> e) {
// final IForgeRegistry<Item> registry = e.getRegistry();
//
// final ItemBlock[] items = {
// new TotemWoodItemBlock(TOTEM_WOOD),
// new ItemBlock(SACRED_LIGHT),
// new ItemBlock(INCENSE_KINDLING_BOX),
// new ItemBlock(OFFERING_BOX),
// };
//
// for(final ItemBlock item : items)
// {
// final Block block = item.getBlock();
// final ResourceLocation registryName = Preconditions.checkNotNull(block.getRegistryName(), "Block %s has null registry name", block);
// registry.register(item.setRegistryName(registryName));
// ITEM_BLOCKS.add(item);
// }
//
// registerTileEntities();
// }
//
// private static void registerTileEntities()
// {
// GameRegistry.registerTileEntity(TotemTileEntity.class, Reference.RESOURCE_PREFIX + TOTEM_WOOD_NAME);
// GameRegistry.registerTileEntity(SacredLightTileEntity.class, Reference.RESOURCE_PREFIX + SACRED_LIGHT_NAME);
// GameRegistry.registerTileEntity(IncenseKindlingBoxTileEntity.class, Reference.RESOURCE_PREFIX + INCENSE_KINDLING_BOX_NAME);
// GameRegistry.registerTileEntity(OfferingBoxTileEntity.class, Reference.RESOURCE_PREFIX + OFFERING_BOX_NAME);
// }
//
// @SubscribeEvent
// public static void registerRenders(ModelRegistryEvent e) {
// for (int i = 0; i < TotemType.values().length; i++) {
// Item item = Item.getItemFromBlock(TOTEM_WOOD);
// ModelResourceLocation modelResourceLocation = new ModelResourceLocation(Reference.RESOURCE_PREFIX + TOTEM_WOOD_NAME, "totem_type=" + TotemType.fromMeta(i).getName());
// ModelLoader.setCustomModelResourceLocation(item, i, modelResourceLocation);
// }
//
// registerRender(SACRED_LIGHT, SACRED_LIGHT_NAME);
// registerRender(INCENSE_KINDLING_BOX, INCENSE_KINDLING_BOX_NAME);
// registerRender(OFFERING_BOX, OFFERING_BOX_NAME);
// }
//
// private static void registerRender(Block block, String key) {
// Item item = Item.getItemFromBlock(block);
// ModelLoader.setCustomModelResourceLocation(item, 0, new ModelResourceLocation(Reference.RESOURCE_PREFIX + key, "inventory"));
// }
// }
//
// Path: src/main/java/com/corwinjv/mobtotems/utils/BlockUtils.java
// public class BlockUtils {
// // Returns an instance of the block at the given position in the given world
// public static Block getBlock(World world, BlockPos pos) {
// Block targetBlock = null;
// if (pos != null) {
// targetBlock = world.getBlockState(pos).getBlock();
// }
// return targetBlock;
// }
//
// public static boolean isAreaSolid(EntityPlayer player, BlockPos centerPos) {
// for (double x = centerPos.getX() - 1; x <= centerPos.getX() + 1; x++) {
// for (double z = centerPos.getZ() - 1; z <= centerPos.getZ() + 1; z++) {
// IBlockState blockState = player.world.getBlockState(new BlockPos(x, player.posY, z));
// if (blockState.getMaterial().isSolid()) {
// return true;
// }
// }
// }
// return false;
// }
// }
// Path: src/main/java/com/corwinjv/mobtotems/items/TotemicFocus.java
import com.corwinjv.mobtotems.blocks.ModBlocks;
import com.corwinjv.mobtotems.utils.BlockUtils;
import net.minecraft.block.Block;
import net.minecraft.block.BlockLog;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.item.EnumAction;
import net.minecraft.item.ItemStack;
import net.minecraft.util.EnumActionResult;
import net.minecraft.util.EnumFacing;
import net.minecraft.util.EnumHand;
import net.minecraft.util.math.BlockPos;
import net.minecraft.world.World;
import javax.annotation.Nonnull;
package com.corwinjv.mobtotems.items;
/**
* Created by CorwinJV on 2/17/2016.
*/
public class TotemicFocus extends ModItem {
@Nonnull
@Override
public EnumActionResult onItemUse(EntityPlayer player, World world, BlockPos pos, EnumHand enumHand, EnumFacing side, float hitX, float hitY, float hitZ) {
if (!world.isRemote) { | Block targetBlock = BlockUtils.getBlock(world, pos); |
CorwinJV/MobTotems | src/main/java/com/corwinjv/mobtotems/items/TotemicFocus.java | // Path: src/main/java/com/corwinjv/mobtotems/blocks/ModBlocks.java
// @Mod.EventBusSubscriber(modid = Reference.MOD_ID)
// public class ModBlocks {
// public static final HashSet<ItemBlock> ITEM_BLOCKS = new HashSet<>();
//
// public static final String TOTEM_WOOD_NAME = "totem_wood";
// public static final String SACRED_LIGHT_NAME = "sacred_light";
// public static final String INCENSE_KINDLING_BOX_NAME = "incense_kindling_box";
// public static final String OFFERING_BOX_NAME = "offering_box";
//
// public static final Block TOTEM_WOOD = new TotemWoodBlock().setUnlocalizedName(TOTEM_WOOD_NAME).setRegistryName(Reference.MOD_ID, TOTEM_WOOD_NAME);
// public static final Block SACRED_LIGHT = new SacredLightBlock().setUnlocalizedName(SACRED_LIGHT_NAME).setRegistryName(Reference.MOD_ID, SACRED_LIGHT_NAME);
// public static final Block INCENSE_KINDLING_BOX = new IncenseKindlingBox().setUnlocalizedName(INCENSE_KINDLING_BOX_NAME).setRegistryName(Reference.MOD_ID, INCENSE_KINDLING_BOX_NAME);
// public static final Block OFFERING_BOX = new OfferingBox().setUnlocalizedName(OFFERING_BOX_NAME).setRegistryName(Reference.MOD_ID, OFFERING_BOX_NAME);
//
// public static void init() {
// }
//
// @SubscribeEvent
// public static void registerBlocks(RegistryEvent.Register<Block> e) {
// final IForgeRegistry<Block> registry = e.getRegistry();
// final Block[] blocks = {
// TOTEM_WOOD,
// SACRED_LIGHT,
// INCENSE_KINDLING_BOX,
// OFFERING_BOX
// };
//
// registry.registerAll(blocks);
// }
//
// @SubscribeEvent
// public static void registerItemBlocks(RegistryEvent.Register<Item> e) {
// final IForgeRegistry<Item> registry = e.getRegistry();
//
// final ItemBlock[] items = {
// new TotemWoodItemBlock(TOTEM_WOOD),
// new ItemBlock(SACRED_LIGHT),
// new ItemBlock(INCENSE_KINDLING_BOX),
// new ItemBlock(OFFERING_BOX),
// };
//
// for(final ItemBlock item : items)
// {
// final Block block = item.getBlock();
// final ResourceLocation registryName = Preconditions.checkNotNull(block.getRegistryName(), "Block %s has null registry name", block);
// registry.register(item.setRegistryName(registryName));
// ITEM_BLOCKS.add(item);
// }
//
// registerTileEntities();
// }
//
// private static void registerTileEntities()
// {
// GameRegistry.registerTileEntity(TotemTileEntity.class, Reference.RESOURCE_PREFIX + TOTEM_WOOD_NAME);
// GameRegistry.registerTileEntity(SacredLightTileEntity.class, Reference.RESOURCE_PREFIX + SACRED_LIGHT_NAME);
// GameRegistry.registerTileEntity(IncenseKindlingBoxTileEntity.class, Reference.RESOURCE_PREFIX + INCENSE_KINDLING_BOX_NAME);
// GameRegistry.registerTileEntity(OfferingBoxTileEntity.class, Reference.RESOURCE_PREFIX + OFFERING_BOX_NAME);
// }
//
// @SubscribeEvent
// public static void registerRenders(ModelRegistryEvent e) {
// for (int i = 0; i < TotemType.values().length; i++) {
// Item item = Item.getItemFromBlock(TOTEM_WOOD);
// ModelResourceLocation modelResourceLocation = new ModelResourceLocation(Reference.RESOURCE_PREFIX + TOTEM_WOOD_NAME, "totem_type=" + TotemType.fromMeta(i).getName());
// ModelLoader.setCustomModelResourceLocation(item, i, modelResourceLocation);
// }
//
// registerRender(SACRED_LIGHT, SACRED_LIGHT_NAME);
// registerRender(INCENSE_KINDLING_BOX, INCENSE_KINDLING_BOX_NAME);
// registerRender(OFFERING_BOX, OFFERING_BOX_NAME);
// }
//
// private static void registerRender(Block block, String key) {
// Item item = Item.getItemFromBlock(block);
// ModelLoader.setCustomModelResourceLocation(item, 0, new ModelResourceLocation(Reference.RESOURCE_PREFIX + key, "inventory"));
// }
// }
//
// Path: src/main/java/com/corwinjv/mobtotems/utils/BlockUtils.java
// public class BlockUtils {
// // Returns an instance of the block at the given position in the given world
// public static Block getBlock(World world, BlockPos pos) {
// Block targetBlock = null;
// if (pos != null) {
// targetBlock = world.getBlockState(pos).getBlock();
// }
// return targetBlock;
// }
//
// public static boolean isAreaSolid(EntityPlayer player, BlockPos centerPos) {
// for (double x = centerPos.getX() - 1; x <= centerPos.getX() + 1; x++) {
// for (double z = centerPos.getZ() - 1; z <= centerPos.getZ() + 1; z++) {
// IBlockState blockState = player.world.getBlockState(new BlockPos(x, player.posY, z));
// if (blockState.getMaterial().isSolid()) {
// return true;
// }
// }
// }
// return false;
// }
// }
| import com.corwinjv.mobtotems.blocks.ModBlocks;
import com.corwinjv.mobtotems.utils.BlockUtils;
import net.minecraft.block.Block;
import net.minecraft.block.BlockLog;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.item.EnumAction;
import net.minecraft.item.ItemStack;
import net.minecraft.util.EnumActionResult;
import net.minecraft.util.EnumFacing;
import net.minecraft.util.EnumHand;
import net.minecraft.util.math.BlockPos;
import net.minecraft.world.World;
import javax.annotation.Nonnull; | package com.corwinjv.mobtotems.items;
/**
* Created by CorwinJV on 2/17/2016.
*/
public class TotemicFocus extends ModItem {
@Nonnull
@Override
public EnumActionResult onItemUse(EntityPlayer player, World world, BlockPos pos, EnumHand enumHand, EnumFacing side, float hitX, float hitY, float hitZ) {
if (!world.isRemote) {
Block targetBlock = BlockUtils.getBlock(world, pos);
if (targetBlock != null
&& targetBlock instanceof BlockLog) {
world.destroyBlock(pos, false); | // Path: src/main/java/com/corwinjv/mobtotems/blocks/ModBlocks.java
// @Mod.EventBusSubscriber(modid = Reference.MOD_ID)
// public class ModBlocks {
// public static final HashSet<ItemBlock> ITEM_BLOCKS = new HashSet<>();
//
// public static final String TOTEM_WOOD_NAME = "totem_wood";
// public static final String SACRED_LIGHT_NAME = "sacred_light";
// public static final String INCENSE_KINDLING_BOX_NAME = "incense_kindling_box";
// public static final String OFFERING_BOX_NAME = "offering_box";
//
// public static final Block TOTEM_WOOD = new TotemWoodBlock().setUnlocalizedName(TOTEM_WOOD_NAME).setRegistryName(Reference.MOD_ID, TOTEM_WOOD_NAME);
// public static final Block SACRED_LIGHT = new SacredLightBlock().setUnlocalizedName(SACRED_LIGHT_NAME).setRegistryName(Reference.MOD_ID, SACRED_LIGHT_NAME);
// public static final Block INCENSE_KINDLING_BOX = new IncenseKindlingBox().setUnlocalizedName(INCENSE_KINDLING_BOX_NAME).setRegistryName(Reference.MOD_ID, INCENSE_KINDLING_BOX_NAME);
// public static final Block OFFERING_BOX = new OfferingBox().setUnlocalizedName(OFFERING_BOX_NAME).setRegistryName(Reference.MOD_ID, OFFERING_BOX_NAME);
//
// public static void init() {
// }
//
// @SubscribeEvent
// public static void registerBlocks(RegistryEvent.Register<Block> e) {
// final IForgeRegistry<Block> registry = e.getRegistry();
// final Block[] blocks = {
// TOTEM_WOOD,
// SACRED_LIGHT,
// INCENSE_KINDLING_BOX,
// OFFERING_BOX
// };
//
// registry.registerAll(blocks);
// }
//
// @SubscribeEvent
// public static void registerItemBlocks(RegistryEvent.Register<Item> e) {
// final IForgeRegistry<Item> registry = e.getRegistry();
//
// final ItemBlock[] items = {
// new TotemWoodItemBlock(TOTEM_WOOD),
// new ItemBlock(SACRED_LIGHT),
// new ItemBlock(INCENSE_KINDLING_BOX),
// new ItemBlock(OFFERING_BOX),
// };
//
// for(final ItemBlock item : items)
// {
// final Block block = item.getBlock();
// final ResourceLocation registryName = Preconditions.checkNotNull(block.getRegistryName(), "Block %s has null registry name", block);
// registry.register(item.setRegistryName(registryName));
// ITEM_BLOCKS.add(item);
// }
//
// registerTileEntities();
// }
//
// private static void registerTileEntities()
// {
// GameRegistry.registerTileEntity(TotemTileEntity.class, Reference.RESOURCE_PREFIX + TOTEM_WOOD_NAME);
// GameRegistry.registerTileEntity(SacredLightTileEntity.class, Reference.RESOURCE_PREFIX + SACRED_LIGHT_NAME);
// GameRegistry.registerTileEntity(IncenseKindlingBoxTileEntity.class, Reference.RESOURCE_PREFIX + INCENSE_KINDLING_BOX_NAME);
// GameRegistry.registerTileEntity(OfferingBoxTileEntity.class, Reference.RESOURCE_PREFIX + OFFERING_BOX_NAME);
// }
//
// @SubscribeEvent
// public static void registerRenders(ModelRegistryEvent e) {
// for (int i = 0; i < TotemType.values().length; i++) {
// Item item = Item.getItemFromBlock(TOTEM_WOOD);
// ModelResourceLocation modelResourceLocation = new ModelResourceLocation(Reference.RESOURCE_PREFIX + TOTEM_WOOD_NAME, "totem_type=" + TotemType.fromMeta(i).getName());
// ModelLoader.setCustomModelResourceLocation(item, i, modelResourceLocation);
// }
//
// registerRender(SACRED_LIGHT, SACRED_LIGHT_NAME);
// registerRender(INCENSE_KINDLING_BOX, INCENSE_KINDLING_BOX_NAME);
// registerRender(OFFERING_BOX, OFFERING_BOX_NAME);
// }
//
// private static void registerRender(Block block, String key) {
// Item item = Item.getItemFromBlock(block);
// ModelLoader.setCustomModelResourceLocation(item, 0, new ModelResourceLocation(Reference.RESOURCE_PREFIX + key, "inventory"));
// }
// }
//
// Path: src/main/java/com/corwinjv/mobtotems/utils/BlockUtils.java
// public class BlockUtils {
// // Returns an instance of the block at the given position in the given world
// public static Block getBlock(World world, BlockPos pos) {
// Block targetBlock = null;
// if (pos != null) {
// targetBlock = world.getBlockState(pos).getBlock();
// }
// return targetBlock;
// }
//
// public static boolean isAreaSolid(EntityPlayer player, BlockPos centerPos) {
// for (double x = centerPos.getX() - 1; x <= centerPos.getX() + 1; x++) {
// for (double z = centerPos.getZ() - 1; z <= centerPos.getZ() + 1; z++) {
// IBlockState blockState = player.world.getBlockState(new BlockPos(x, player.posY, z));
// if (blockState.getMaterial().isSolid()) {
// return true;
// }
// }
// }
// return false;
// }
// }
// Path: src/main/java/com/corwinjv/mobtotems/items/TotemicFocus.java
import com.corwinjv.mobtotems.blocks.ModBlocks;
import com.corwinjv.mobtotems.utils.BlockUtils;
import net.minecraft.block.Block;
import net.minecraft.block.BlockLog;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.item.EnumAction;
import net.minecraft.item.ItemStack;
import net.minecraft.util.EnumActionResult;
import net.minecraft.util.EnumFacing;
import net.minecraft.util.EnumHand;
import net.minecraft.util.math.BlockPos;
import net.minecraft.world.World;
import javax.annotation.Nonnull;
package com.corwinjv.mobtotems.items;
/**
* Created by CorwinJV on 2/17/2016.
*/
public class TotemicFocus extends ModItem {
@Nonnull
@Override
public EnumActionResult onItemUse(EntityPlayer player, World world, BlockPos pos, EnumHand enumHand, EnumFacing side, float hitX, float hitY, float hitZ) {
if (!world.isRemote) {
Block targetBlock = BlockUtils.getBlock(world, pos);
if (targetBlock != null
&& targetBlock instanceof BlockLog) {
world.destroyBlock(pos, false); | Block blockToPlace = ModBlocks.TOTEM_WOOD; |
CorwinJV/MobTotems | src/main/java/com/corwinjv/mobtotems/network/Network.java | // Path: src/main/java/com/corwinjv/mobtotems/Reference.java
// public class Reference {
// public static final String MOD_ID = "mobtotems";
// public static final String MOD_NAME = "Mob Totems";
// public static final String MOD_VERSION = "1.12.1-0.3.0";
// public static final String RESOURCE_PREFIX = MOD_ID + ":";
//
// public static final String GUI_FACTORY_CLASS = "com.corwinjv.mobtotems.gui.GuiFactoryMT";
// public static final String CLIENT_SIDE_PROXY_CLASS = "com.corwinjv.mobtotems.proxy.ClientProxy";
// public static final String SERVER_SIDE_PROXY_CLASS = "com.corwinjv.mobtotems.proxy.CommonProxy";
//
// public static final int CHARGE_COLOR = 0xFF00FF00;
//
// public enum GUI_ID {
// OFFERING_BOX
// }
//
// ;
//
// public static void PrintEntityList() {
// Iterator entityNameItr = EntityList.getEntityNameList().iterator();
// FMLLog.log(Reference.MOD_NAME, Level.INFO, "-Printing Registered Entity Classes-");
// while (entityNameItr.hasNext()) {
// String key = (String) entityNameItr.next();
// FMLLog.log(Reference.MOD_NAME, Level.INFO, String.format(" %s", key));
// }
// }
// }
| import com.corwinjv.mobtotems.Reference;
import net.minecraft.entity.player.EntityPlayerMP;
import net.minecraftforge.fml.common.network.NetworkRegistry;
import net.minecraftforge.fml.common.network.simpleimpl.SimpleNetworkWrapper;
import net.minecraftforge.fml.relauncher.Side; | package com.corwinjv.mobtotems.network;
/**
* Created by CorwinJV on 2/1/2016.
*/
public class Network {
private static SimpleNetworkWrapper instance = null;
private static int DISCRIMINATOR_ID = 0;
public static void init() { | // Path: src/main/java/com/corwinjv/mobtotems/Reference.java
// public class Reference {
// public static final String MOD_ID = "mobtotems";
// public static final String MOD_NAME = "Mob Totems";
// public static final String MOD_VERSION = "1.12.1-0.3.0";
// public static final String RESOURCE_PREFIX = MOD_ID + ":";
//
// public static final String GUI_FACTORY_CLASS = "com.corwinjv.mobtotems.gui.GuiFactoryMT";
// public static final String CLIENT_SIDE_PROXY_CLASS = "com.corwinjv.mobtotems.proxy.ClientProxy";
// public static final String SERVER_SIDE_PROXY_CLASS = "com.corwinjv.mobtotems.proxy.CommonProxy";
//
// public static final int CHARGE_COLOR = 0xFF00FF00;
//
// public enum GUI_ID {
// OFFERING_BOX
// }
//
// ;
//
// public static void PrintEntityList() {
// Iterator entityNameItr = EntityList.getEntityNameList().iterator();
// FMLLog.log(Reference.MOD_NAME, Level.INFO, "-Printing Registered Entity Classes-");
// while (entityNameItr.hasNext()) {
// String key = (String) entityNameItr.next();
// FMLLog.log(Reference.MOD_NAME, Level.INFO, String.format(" %s", key));
// }
// }
// }
// Path: src/main/java/com/corwinjv/mobtotems/network/Network.java
import com.corwinjv.mobtotems.Reference;
import net.minecraft.entity.player.EntityPlayerMP;
import net.minecraftforge.fml.common.network.NetworkRegistry;
import net.minecraftforge.fml.common.network.simpleimpl.SimpleNetworkWrapper;
import net.minecraftforge.fml.relauncher.Side;
package com.corwinjv.mobtotems.network;
/**
* Created by CorwinJV on 2/1/2016.
*/
public class Network {
private static SimpleNetworkWrapper instance = null;
private static int DISCRIMINATOR_ID = 0;
public static void init() { | instance = NetworkRegistry.INSTANCE.newSimpleChannel(Reference.MOD_ID); |
CorwinJV/MobTotems | src/main/java/com/corwinjv/mobtotems/items/ModItem.java | // Path: src/main/java/com/corwinjv/mobtotems/Reference.java
// public class Reference {
// public static final String MOD_ID = "mobtotems";
// public static final String MOD_NAME = "Mob Totems";
// public static final String MOD_VERSION = "1.12.1-0.3.0";
// public static final String RESOURCE_PREFIX = MOD_ID + ":";
//
// public static final String GUI_FACTORY_CLASS = "com.corwinjv.mobtotems.gui.GuiFactoryMT";
// public static final String CLIENT_SIDE_PROXY_CLASS = "com.corwinjv.mobtotems.proxy.ClientProxy";
// public static final String SERVER_SIDE_PROXY_CLASS = "com.corwinjv.mobtotems.proxy.CommonProxy";
//
// public static final int CHARGE_COLOR = 0xFF00FF00;
//
// public enum GUI_ID {
// OFFERING_BOX
// }
//
// ;
//
// public static void PrintEntityList() {
// Iterator entityNameItr = EntityList.getEntityNameList().iterator();
// FMLLog.log(Reference.MOD_NAME, Level.INFO, "-Printing Registered Entity Classes-");
// while (entityNameItr.hasNext()) {
// String key = (String) entityNameItr.next();
// FMLLog.log(Reference.MOD_NAME, Level.INFO, String.format(" %s", key));
// }
// }
// }
//
// Path: src/main/java/com/corwinjv/mobtotems/creativetab/CreativeTabMT.java
// public class CreativeTabMT {
// public static final CreativeTabs MT_TAB = new CreativeTabs(Reference.MOD_ID) {
// @Override
// public ItemStack getTabIconItem() {
// return new ItemStack(ModItems.TOTEMIC_FOCUS);
// }
// };
// }
| import com.corwinjv.mobtotems.Reference;
import com.corwinjv.mobtotems.creativetab.CreativeTabMT;
import net.minecraft.item.Item; | package com.corwinjv.mobtotems.items;
/**
* Created by CorwinJV on 1/31/2016.
*/
public class ModItem extends Item {
public ModItem() {
super();
this.init();
}
public void init() { | // Path: src/main/java/com/corwinjv/mobtotems/Reference.java
// public class Reference {
// public static final String MOD_ID = "mobtotems";
// public static final String MOD_NAME = "Mob Totems";
// public static final String MOD_VERSION = "1.12.1-0.3.0";
// public static final String RESOURCE_PREFIX = MOD_ID + ":";
//
// public static final String GUI_FACTORY_CLASS = "com.corwinjv.mobtotems.gui.GuiFactoryMT";
// public static final String CLIENT_SIDE_PROXY_CLASS = "com.corwinjv.mobtotems.proxy.ClientProxy";
// public static final String SERVER_SIDE_PROXY_CLASS = "com.corwinjv.mobtotems.proxy.CommonProxy";
//
// public static final int CHARGE_COLOR = 0xFF00FF00;
//
// public enum GUI_ID {
// OFFERING_BOX
// }
//
// ;
//
// public static void PrintEntityList() {
// Iterator entityNameItr = EntityList.getEntityNameList().iterator();
// FMLLog.log(Reference.MOD_NAME, Level.INFO, "-Printing Registered Entity Classes-");
// while (entityNameItr.hasNext()) {
// String key = (String) entityNameItr.next();
// FMLLog.log(Reference.MOD_NAME, Level.INFO, String.format(" %s", key));
// }
// }
// }
//
// Path: src/main/java/com/corwinjv/mobtotems/creativetab/CreativeTabMT.java
// public class CreativeTabMT {
// public static final CreativeTabs MT_TAB = new CreativeTabs(Reference.MOD_ID) {
// @Override
// public ItemStack getTabIconItem() {
// return new ItemStack(ModItems.TOTEMIC_FOCUS);
// }
// };
// }
// Path: src/main/java/com/corwinjv/mobtotems/items/ModItem.java
import com.corwinjv.mobtotems.Reference;
import com.corwinjv.mobtotems.creativetab.CreativeTabMT;
import net.minecraft.item.Item;
package com.corwinjv.mobtotems.items;
/**
* Created by CorwinJV on 1/31/2016.
*/
public class ModItem extends Item {
public ModItem() {
super();
this.init();
}
public void init() { | this.setCreativeTab(CreativeTabMT.MT_TAB); |
CorwinJV/MobTotems | src/main/java/com/corwinjv/mobtotems/items/ModItem.java | // Path: src/main/java/com/corwinjv/mobtotems/Reference.java
// public class Reference {
// public static final String MOD_ID = "mobtotems";
// public static final String MOD_NAME = "Mob Totems";
// public static final String MOD_VERSION = "1.12.1-0.3.0";
// public static final String RESOURCE_PREFIX = MOD_ID + ":";
//
// public static final String GUI_FACTORY_CLASS = "com.corwinjv.mobtotems.gui.GuiFactoryMT";
// public static final String CLIENT_SIDE_PROXY_CLASS = "com.corwinjv.mobtotems.proxy.ClientProxy";
// public static final String SERVER_SIDE_PROXY_CLASS = "com.corwinjv.mobtotems.proxy.CommonProxy";
//
// public static final int CHARGE_COLOR = 0xFF00FF00;
//
// public enum GUI_ID {
// OFFERING_BOX
// }
//
// ;
//
// public static void PrintEntityList() {
// Iterator entityNameItr = EntityList.getEntityNameList().iterator();
// FMLLog.log(Reference.MOD_NAME, Level.INFO, "-Printing Registered Entity Classes-");
// while (entityNameItr.hasNext()) {
// String key = (String) entityNameItr.next();
// FMLLog.log(Reference.MOD_NAME, Level.INFO, String.format(" %s", key));
// }
// }
// }
//
// Path: src/main/java/com/corwinjv/mobtotems/creativetab/CreativeTabMT.java
// public class CreativeTabMT {
// public static final CreativeTabs MT_TAB = new CreativeTabs(Reference.MOD_ID) {
// @Override
// public ItemStack getTabIconItem() {
// return new ItemStack(ModItems.TOTEMIC_FOCUS);
// }
// };
// }
| import com.corwinjv.mobtotems.Reference;
import com.corwinjv.mobtotems.creativetab.CreativeTabMT;
import net.minecraft.item.Item; | package com.corwinjv.mobtotems.items;
/**
* Created by CorwinJV on 1/31/2016.
*/
public class ModItem extends Item {
public ModItem() {
super();
this.init();
}
public void init() {
this.setCreativeTab(CreativeTabMT.MT_TAB);
}
@Override
public String getUnlocalizedName() { | // Path: src/main/java/com/corwinjv/mobtotems/Reference.java
// public class Reference {
// public static final String MOD_ID = "mobtotems";
// public static final String MOD_NAME = "Mob Totems";
// public static final String MOD_VERSION = "1.12.1-0.3.0";
// public static final String RESOURCE_PREFIX = MOD_ID + ":";
//
// public static final String GUI_FACTORY_CLASS = "com.corwinjv.mobtotems.gui.GuiFactoryMT";
// public static final String CLIENT_SIDE_PROXY_CLASS = "com.corwinjv.mobtotems.proxy.ClientProxy";
// public static final String SERVER_SIDE_PROXY_CLASS = "com.corwinjv.mobtotems.proxy.CommonProxy";
//
// public static final int CHARGE_COLOR = 0xFF00FF00;
//
// public enum GUI_ID {
// OFFERING_BOX
// }
//
// ;
//
// public static void PrintEntityList() {
// Iterator entityNameItr = EntityList.getEntityNameList().iterator();
// FMLLog.log(Reference.MOD_NAME, Level.INFO, "-Printing Registered Entity Classes-");
// while (entityNameItr.hasNext()) {
// String key = (String) entityNameItr.next();
// FMLLog.log(Reference.MOD_NAME, Level.INFO, String.format(" %s", key));
// }
// }
// }
//
// Path: src/main/java/com/corwinjv/mobtotems/creativetab/CreativeTabMT.java
// public class CreativeTabMT {
// public static final CreativeTabs MT_TAB = new CreativeTabs(Reference.MOD_ID) {
// @Override
// public ItemStack getTabIconItem() {
// return new ItemStack(ModItems.TOTEMIC_FOCUS);
// }
// };
// }
// Path: src/main/java/com/corwinjv/mobtotems/items/ModItem.java
import com.corwinjv.mobtotems.Reference;
import com.corwinjv.mobtotems.creativetab.CreativeTabMT;
import net.minecraft.item.Item;
package com.corwinjv.mobtotems.items;
/**
* Created by CorwinJV on 1/31/2016.
*/
public class ModItem extends Item {
public ModItem() {
super();
this.init();
}
public void init() {
this.setCreativeTab(CreativeTabMT.MT_TAB);
}
@Override
public String getUnlocalizedName() { | return String.format("item.%s%s", Reference.RESOURCE_PREFIX, getUnwrappedUnlocalizedName(super.getUnlocalizedName())); |
CorwinJV/MobTotems | src/main/java/com/corwinjv/mobtotems/network/ActivateBaubleMessage.java | // Path: src/main/java/com/corwinjv/mobtotems/items/baubles/BaubleItem.java
// @Optional.Interface(modid = "baubles", iface = "baubles.api.IBauble")
// public class BaubleItem extends ModItem implements IBauble, IChargeable {
// protected static final String CHARGE_LEVEL = "CHARGE_LEVEL";
//
// public BaubleItem() {
// super();
// }
//
// @Override
// public void onCreated(ItemStack stack, World worldIn, EntityPlayer playerIn) {
// initNbtData(stack);
// }
//
// protected NBTTagCompound initNbtData(ItemStack stack) {
// NBTTagCompound nbtTagCompound = stack.getTagCompound();
// if (nbtTagCompound == null) {
// nbtTagCompound = new NBTTagCompound();
// }
// nbtTagCompound.setInteger(CHARGE_LEVEL, 0);
//
// stack.setTagCompound(nbtTagCompound);
// return nbtTagCompound;
// }
//
// @SuppressWarnings("all")
// @Override
// public int getChargeLevel(ItemStack stack) {
// NBTTagCompound tagCompound = stack.getTagCompound();
// if (tagCompound == null) {
// tagCompound = initNbtData(stack);
// }
// return tagCompound.getInteger(CHARGE_LEVEL);
// }
//
// @Override
// public void setChargeLevel(ItemStack stack, int chargeLevel) {
// NBTTagCompound tagCompound = stack.getTagCompound();
// if (tagCompound == null) {
// tagCompound = initNbtData(stack);
// }
// tagCompound.setInteger(CHARGE_LEVEL, chargeLevel);
// }
//
// @Override
// public void decrementChargeLevel(ItemStack stack, int amount) {
// int chargeLevel = getChargeLevel(stack);
// chargeLevel -= amount;
// if (chargeLevel < 0) {
// chargeLevel = 0;
// }
//
// setChargeLevel(stack, chargeLevel);
// }
//
// @Override
// public void incrementChargeLevel(ItemStack stack, int amount) {
// int chargeLevel = getChargeLevel(stack);
// chargeLevel += amount;
// if (chargeLevel > getMaxChargeLevel()) {
// chargeLevel = getMaxChargeLevel();
// }
// setChargeLevel(stack, chargeLevel);
// }
//
// @Override
// public int getMaxChargeLevel() {
// return 16;
// }
//
// public void onBaubleActivated(ItemStack stack, EntityPlayer player) {
// }
//
// @Override
// @SideOnly(Side.CLIENT)
// public void addInformation(ItemStack stack, @Nullable World worldIn, List<String> tooltip, ITooltipFlag flagIn) {
// super.addInformation(stack, worldIn, tooltip, flagIn);
// }
//
// @Override
// public BaubleType getBaubleType(ItemStack itemstack) {
// return BaubleType.TRINKET;
// }
//
// @Override
// public boolean canEquip(ItemStack itemstack, EntityLivingBase player) {
// return true;
// }
//
// @Override
// public boolean canUnequip(ItemStack itemstack, EntityLivingBase player) {
// return true;
// }
//
// @Override
// public boolean willAutoSync(ItemStack itemstack, EntityLivingBase player) {
// return true;
// }
// }
| import baubles.api.BaublesApi;
import baubles.api.cap.IBaublesItemHandler;
import com.corwinjv.mobtotems.items.baubles.BaubleItem;
import net.minecraft.entity.player.EntityPlayerMP;
import net.minecraft.item.ItemStack; | package com.corwinjv.mobtotems.network;
/**
* Created by CorwinJV on 2/1/2016.
*/
public class ActivateBaubleMessage extends Message<ActivateBaubleMessage> {
@Override
protected void handleServer(ActivateBaubleMessage message, EntityPlayerMP player) {
final IBaublesItemHandler baublesItemHandler = BaublesApi.getBaublesHandler(player);
if (baublesItemHandler == null) {
return;
}
for (int i = 0; i < baublesItemHandler.getSlots(); i++) {
final ItemStack baubleStack = baublesItemHandler.getStackInSlot(i);
if (baubleStack != ItemStack.EMPTY | // Path: src/main/java/com/corwinjv/mobtotems/items/baubles/BaubleItem.java
// @Optional.Interface(modid = "baubles", iface = "baubles.api.IBauble")
// public class BaubleItem extends ModItem implements IBauble, IChargeable {
// protected static final String CHARGE_LEVEL = "CHARGE_LEVEL";
//
// public BaubleItem() {
// super();
// }
//
// @Override
// public void onCreated(ItemStack stack, World worldIn, EntityPlayer playerIn) {
// initNbtData(stack);
// }
//
// protected NBTTagCompound initNbtData(ItemStack stack) {
// NBTTagCompound nbtTagCompound = stack.getTagCompound();
// if (nbtTagCompound == null) {
// nbtTagCompound = new NBTTagCompound();
// }
// nbtTagCompound.setInteger(CHARGE_LEVEL, 0);
//
// stack.setTagCompound(nbtTagCompound);
// return nbtTagCompound;
// }
//
// @SuppressWarnings("all")
// @Override
// public int getChargeLevel(ItemStack stack) {
// NBTTagCompound tagCompound = stack.getTagCompound();
// if (tagCompound == null) {
// tagCompound = initNbtData(stack);
// }
// return tagCompound.getInteger(CHARGE_LEVEL);
// }
//
// @Override
// public void setChargeLevel(ItemStack stack, int chargeLevel) {
// NBTTagCompound tagCompound = stack.getTagCompound();
// if (tagCompound == null) {
// tagCompound = initNbtData(stack);
// }
// tagCompound.setInteger(CHARGE_LEVEL, chargeLevel);
// }
//
// @Override
// public void decrementChargeLevel(ItemStack stack, int amount) {
// int chargeLevel = getChargeLevel(stack);
// chargeLevel -= amount;
// if (chargeLevel < 0) {
// chargeLevel = 0;
// }
//
// setChargeLevel(stack, chargeLevel);
// }
//
// @Override
// public void incrementChargeLevel(ItemStack stack, int amount) {
// int chargeLevel = getChargeLevel(stack);
// chargeLevel += amount;
// if (chargeLevel > getMaxChargeLevel()) {
// chargeLevel = getMaxChargeLevel();
// }
// setChargeLevel(stack, chargeLevel);
// }
//
// @Override
// public int getMaxChargeLevel() {
// return 16;
// }
//
// public void onBaubleActivated(ItemStack stack, EntityPlayer player) {
// }
//
// @Override
// @SideOnly(Side.CLIENT)
// public void addInformation(ItemStack stack, @Nullable World worldIn, List<String> tooltip, ITooltipFlag flagIn) {
// super.addInformation(stack, worldIn, tooltip, flagIn);
// }
//
// @Override
// public BaubleType getBaubleType(ItemStack itemstack) {
// return BaubleType.TRINKET;
// }
//
// @Override
// public boolean canEquip(ItemStack itemstack, EntityLivingBase player) {
// return true;
// }
//
// @Override
// public boolean canUnequip(ItemStack itemstack, EntityLivingBase player) {
// return true;
// }
//
// @Override
// public boolean willAutoSync(ItemStack itemstack, EntityLivingBase player) {
// return true;
// }
// }
// Path: src/main/java/com/corwinjv/mobtotems/network/ActivateBaubleMessage.java
import baubles.api.BaublesApi;
import baubles.api.cap.IBaublesItemHandler;
import com.corwinjv.mobtotems.items.baubles.BaubleItem;
import net.minecraft.entity.player.EntityPlayerMP;
import net.minecraft.item.ItemStack;
package com.corwinjv.mobtotems.network;
/**
* Created by CorwinJV on 2/1/2016.
*/
public class ActivateBaubleMessage extends Message<ActivateBaubleMessage> {
@Override
protected void handleServer(ActivateBaubleMessage message, EntityPlayerMP player) {
final IBaublesItemHandler baublesItemHandler = BaublesApi.getBaublesHandler(player);
if (baublesItemHandler == null) {
return;
}
for (int i = 0; i < baublesItemHandler.getSlots(); i++) {
final ItemStack baubleStack = baublesItemHandler.getStackInSlot(i);
if (baubleStack != ItemStack.EMPTY | && baubleStack.getItem() instanceof BaubleItem) { |
CorwinJV/MobTotems | src/main/java/com/corwinjv/mobtotems/gui/ConfigGuiMT.java | // Path: src/main/java/com/corwinjv/mobtotems/Reference.java
// public class Reference {
// public static final String MOD_ID = "mobtotems";
// public static final String MOD_NAME = "Mob Totems";
// public static final String MOD_VERSION = "1.12.1-0.3.0";
// public static final String RESOURCE_PREFIX = MOD_ID + ":";
//
// public static final String GUI_FACTORY_CLASS = "com.corwinjv.mobtotems.gui.GuiFactoryMT";
// public static final String CLIENT_SIDE_PROXY_CLASS = "com.corwinjv.mobtotems.proxy.ClientProxy";
// public static final String SERVER_SIDE_PROXY_CLASS = "com.corwinjv.mobtotems.proxy.CommonProxy";
//
// public static final int CHARGE_COLOR = 0xFF00FF00;
//
// public enum GUI_ID {
// OFFERING_BOX
// }
//
// ;
//
// public static void PrintEntityList() {
// Iterator entityNameItr = EntityList.getEntityNameList().iterator();
// FMLLog.log(Reference.MOD_NAME, Level.INFO, "-Printing Registered Entity Classes-");
// while (entityNameItr.hasNext()) {
// String key = (String) entityNameItr.next();
// FMLLog.log(Reference.MOD_NAME, Level.INFO, String.format(" %s", key));
// }
// }
// }
//
// Path: src/main/java/com/corwinjv/mobtotems/config/ConfigurationHandler.java
// public class ConfigurationHandler {
// public static Configuration configuration;
//
// /**
// * Config Properties
// **/
//
//
// public static void Init(File aConfigFile) {
// if (configuration == null) {
// configuration = new Configuration(aConfigFile);
// loadConfiguration();
// }
// }
//
// @SubscribeEvent
// public void onConfigurationChangedEvent(ConfigChangedEvent.OnConfigChangedEvent event) {
// if (Reference.MOD_ID.equalsIgnoreCase(event.getModID())) {
// loadConfiguration();
// }
// }
//
// private static void loadConfiguration() {
//
// if (configuration.hasChanged()) {
// configuration.save();
// }
// }
// }
| import com.corwinjv.mobtotems.Reference;
import com.corwinjv.mobtotems.config.ConfigurationHandler;
import net.minecraft.client.gui.GuiScreen;
import net.minecraftforge.common.config.ConfigElement;
import net.minecraftforge.common.config.Configuration;
import net.minecraftforge.fml.client.config.GuiConfig; | package com.corwinjv.mobtotems.gui;
/**
* Created by CorwinJV on 9/1/14.
*/
public class ConfigGuiMT extends GuiConfig {
public ConfigGuiMT(GuiScreen guiScreen) {
super(guiScreen, | // Path: src/main/java/com/corwinjv/mobtotems/Reference.java
// public class Reference {
// public static final String MOD_ID = "mobtotems";
// public static final String MOD_NAME = "Mob Totems";
// public static final String MOD_VERSION = "1.12.1-0.3.0";
// public static final String RESOURCE_PREFIX = MOD_ID + ":";
//
// public static final String GUI_FACTORY_CLASS = "com.corwinjv.mobtotems.gui.GuiFactoryMT";
// public static final String CLIENT_SIDE_PROXY_CLASS = "com.corwinjv.mobtotems.proxy.ClientProxy";
// public static final String SERVER_SIDE_PROXY_CLASS = "com.corwinjv.mobtotems.proxy.CommonProxy";
//
// public static final int CHARGE_COLOR = 0xFF00FF00;
//
// public enum GUI_ID {
// OFFERING_BOX
// }
//
// ;
//
// public static void PrintEntityList() {
// Iterator entityNameItr = EntityList.getEntityNameList().iterator();
// FMLLog.log(Reference.MOD_NAME, Level.INFO, "-Printing Registered Entity Classes-");
// while (entityNameItr.hasNext()) {
// String key = (String) entityNameItr.next();
// FMLLog.log(Reference.MOD_NAME, Level.INFO, String.format(" %s", key));
// }
// }
// }
//
// Path: src/main/java/com/corwinjv/mobtotems/config/ConfigurationHandler.java
// public class ConfigurationHandler {
// public static Configuration configuration;
//
// /**
// * Config Properties
// **/
//
//
// public static void Init(File aConfigFile) {
// if (configuration == null) {
// configuration = new Configuration(aConfigFile);
// loadConfiguration();
// }
// }
//
// @SubscribeEvent
// public void onConfigurationChangedEvent(ConfigChangedEvent.OnConfigChangedEvent event) {
// if (Reference.MOD_ID.equalsIgnoreCase(event.getModID())) {
// loadConfiguration();
// }
// }
//
// private static void loadConfiguration() {
//
// if (configuration.hasChanged()) {
// configuration.save();
// }
// }
// }
// Path: src/main/java/com/corwinjv/mobtotems/gui/ConfigGuiMT.java
import com.corwinjv.mobtotems.Reference;
import com.corwinjv.mobtotems.config.ConfigurationHandler;
import net.minecraft.client.gui.GuiScreen;
import net.minecraftforge.common.config.ConfigElement;
import net.minecraftforge.common.config.Configuration;
import net.minecraftforge.fml.client.config.GuiConfig;
package com.corwinjv.mobtotems.gui;
/**
* Created by CorwinJV on 9/1/14.
*/
public class ConfigGuiMT extends GuiConfig {
public ConfigGuiMT(GuiScreen guiScreen) {
super(guiScreen, | new ConfigElement(ConfigurationHandler.configuration.getCategory(Configuration.CATEGORY_GENERAL)).getChildElements(), |
CorwinJV/MobTotems | src/main/java/com/corwinjv/mobtotems/gui/ConfigGuiMT.java | // Path: src/main/java/com/corwinjv/mobtotems/Reference.java
// public class Reference {
// public static final String MOD_ID = "mobtotems";
// public static final String MOD_NAME = "Mob Totems";
// public static final String MOD_VERSION = "1.12.1-0.3.0";
// public static final String RESOURCE_PREFIX = MOD_ID + ":";
//
// public static final String GUI_FACTORY_CLASS = "com.corwinjv.mobtotems.gui.GuiFactoryMT";
// public static final String CLIENT_SIDE_PROXY_CLASS = "com.corwinjv.mobtotems.proxy.ClientProxy";
// public static final String SERVER_SIDE_PROXY_CLASS = "com.corwinjv.mobtotems.proxy.CommonProxy";
//
// public static final int CHARGE_COLOR = 0xFF00FF00;
//
// public enum GUI_ID {
// OFFERING_BOX
// }
//
// ;
//
// public static void PrintEntityList() {
// Iterator entityNameItr = EntityList.getEntityNameList().iterator();
// FMLLog.log(Reference.MOD_NAME, Level.INFO, "-Printing Registered Entity Classes-");
// while (entityNameItr.hasNext()) {
// String key = (String) entityNameItr.next();
// FMLLog.log(Reference.MOD_NAME, Level.INFO, String.format(" %s", key));
// }
// }
// }
//
// Path: src/main/java/com/corwinjv/mobtotems/config/ConfigurationHandler.java
// public class ConfigurationHandler {
// public static Configuration configuration;
//
// /**
// * Config Properties
// **/
//
//
// public static void Init(File aConfigFile) {
// if (configuration == null) {
// configuration = new Configuration(aConfigFile);
// loadConfiguration();
// }
// }
//
// @SubscribeEvent
// public void onConfigurationChangedEvent(ConfigChangedEvent.OnConfigChangedEvent event) {
// if (Reference.MOD_ID.equalsIgnoreCase(event.getModID())) {
// loadConfiguration();
// }
// }
//
// private static void loadConfiguration() {
//
// if (configuration.hasChanged()) {
// configuration.save();
// }
// }
// }
| import com.corwinjv.mobtotems.Reference;
import com.corwinjv.mobtotems.config.ConfigurationHandler;
import net.minecraft.client.gui.GuiScreen;
import net.minecraftforge.common.config.ConfigElement;
import net.minecraftforge.common.config.Configuration;
import net.minecraftforge.fml.client.config.GuiConfig; | package com.corwinjv.mobtotems.gui;
/**
* Created by CorwinJV on 9/1/14.
*/
public class ConfigGuiMT extends GuiConfig {
public ConfigGuiMT(GuiScreen guiScreen) {
super(guiScreen,
new ConfigElement(ConfigurationHandler.configuration.getCategory(Configuration.CATEGORY_GENERAL)).getChildElements(), | // Path: src/main/java/com/corwinjv/mobtotems/Reference.java
// public class Reference {
// public static final String MOD_ID = "mobtotems";
// public static final String MOD_NAME = "Mob Totems";
// public static final String MOD_VERSION = "1.12.1-0.3.0";
// public static final String RESOURCE_PREFIX = MOD_ID + ":";
//
// public static final String GUI_FACTORY_CLASS = "com.corwinjv.mobtotems.gui.GuiFactoryMT";
// public static final String CLIENT_SIDE_PROXY_CLASS = "com.corwinjv.mobtotems.proxy.ClientProxy";
// public static final String SERVER_SIDE_PROXY_CLASS = "com.corwinjv.mobtotems.proxy.CommonProxy";
//
// public static final int CHARGE_COLOR = 0xFF00FF00;
//
// public enum GUI_ID {
// OFFERING_BOX
// }
//
// ;
//
// public static void PrintEntityList() {
// Iterator entityNameItr = EntityList.getEntityNameList().iterator();
// FMLLog.log(Reference.MOD_NAME, Level.INFO, "-Printing Registered Entity Classes-");
// while (entityNameItr.hasNext()) {
// String key = (String) entityNameItr.next();
// FMLLog.log(Reference.MOD_NAME, Level.INFO, String.format(" %s", key));
// }
// }
// }
//
// Path: src/main/java/com/corwinjv/mobtotems/config/ConfigurationHandler.java
// public class ConfigurationHandler {
// public static Configuration configuration;
//
// /**
// * Config Properties
// **/
//
//
// public static void Init(File aConfigFile) {
// if (configuration == null) {
// configuration = new Configuration(aConfigFile);
// loadConfiguration();
// }
// }
//
// @SubscribeEvent
// public void onConfigurationChangedEvent(ConfigChangedEvent.OnConfigChangedEvent event) {
// if (Reference.MOD_ID.equalsIgnoreCase(event.getModID())) {
// loadConfiguration();
// }
// }
//
// private static void loadConfiguration() {
//
// if (configuration.hasChanged()) {
// configuration.save();
// }
// }
// }
// Path: src/main/java/com/corwinjv/mobtotems/gui/ConfigGuiMT.java
import com.corwinjv.mobtotems.Reference;
import com.corwinjv.mobtotems.config.ConfigurationHandler;
import net.minecraft.client.gui.GuiScreen;
import net.minecraftforge.common.config.ConfigElement;
import net.minecraftforge.common.config.Configuration;
import net.minecraftforge.fml.client.config.GuiConfig;
package com.corwinjv.mobtotems.gui;
/**
* Created by CorwinJV on 9/1/14.
*/
public class ConfigGuiMT extends GuiConfig {
public ConfigGuiMT(GuiScreen guiScreen) {
super(guiScreen,
new ConfigElement(ConfigurationHandler.configuration.getCategory(Configuration.CATEGORY_GENERAL)).getChildElements(), | Reference.MOD_ID, |
CorwinJV/MobTotems | src/main/java/com/corwinjv/mobtotems/blocks/ModBlockContainer.java | // Path: src/main/java/com/corwinjv/mobtotems/Reference.java
// public class Reference {
// public static final String MOD_ID = "mobtotems";
// public static final String MOD_NAME = "Mob Totems";
// public static final String MOD_VERSION = "1.12.1-0.3.0";
// public static final String RESOURCE_PREFIX = MOD_ID + ":";
//
// public static final String GUI_FACTORY_CLASS = "com.corwinjv.mobtotems.gui.GuiFactoryMT";
// public static final String CLIENT_SIDE_PROXY_CLASS = "com.corwinjv.mobtotems.proxy.ClientProxy";
// public static final String SERVER_SIDE_PROXY_CLASS = "com.corwinjv.mobtotems.proxy.CommonProxy";
//
// public static final int CHARGE_COLOR = 0xFF00FF00;
//
// public enum GUI_ID {
// OFFERING_BOX
// }
//
// ;
//
// public static void PrintEntityList() {
// Iterator entityNameItr = EntityList.getEntityNameList().iterator();
// FMLLog.log(Reference.MOD_NAME, Level.INFO, "-Printing Registered Entity Classes-");
// while (entityNameItr.hasNext()) {
// String key = (String) entityNameItr.next();
// FMLLog.log(Reference.MOD_NAME, Level.INFO, String.format(" %s", key));
// }
// }
// }
//
// Path: src/main/java/com/corwinjv/mobtotems/creativetab/CreativeTabMT.java
// public class CreativeTabMT {
// public static final CreativeTabs MT_TAB = new CreativeTabs(Reference.MOD_ID) {
// @Override
// public ItemStack getTabIconItem() {
// return new ItemStack(ModItems.TOTEMIC_FOCUS);
// }
// };
// }
| import com.corwinjv.mobtotems.Reference;
import com.corwinjv.mobtotems.creativetab.CreativeTabMT;
import net.minecraft.block.BlockContainer;
import net.minecraft.block.material.Material;
import net.minecraft.tileentity.TileEntity;
import net.minecraft.world.World;
import javax.annotation.Nullable; | package com.corwinjv.mobtotems.blocks;
/**
* Created by CorwinJV on 9/1/14.
*/
public class ModBlockContainer extends BlockContainer {
public ModBlockContainer(Material aMaterial) {
super(aMaterial);
this.init();
}
public ModBlockContainer() {
super(Material.WOOD);
this.init();
}
public void init() { | // Path: src/main/java/com/corwinjv/mobtotems/Reference.java
// public class Reference {
// public static final String MOD_ID = "mobtotems";
// public static final String MOD_NAME = "Mob Totems";
// public static final String MOD_VERSION = "1.12.1-0.3.0";
// public static final String RESOURCE_PREFIX = MOD_ID + ":";
//
// public static final String GUI_FACTORY_CLASS = "com.corwinjv.mobtotems.gui.GuiFactoryMT";
// public static final String CLIENT_SIDE_PROXY_CLASS = "com.corwinjv.mobtotems.proxy.ClientProxy";
// public static final String SERVER_SIDE_PROXY_CLASS = "com.corwinjv.mobtotems.proxy.CommonProxy";
//
// public static final int CHARGE_COLOR = 0xFF00FF00;
//
// public enum GUI_ID {
// OFFERING_BOX
// }
//
// ;
//
// public static void PrintEntityList() {
// Iterator entityNameItr = EntityList.getEntityNameList().iterator();
// FMLLog.log(Reference.MOD_NAME, Level.INFO, "-Printing Registered Entity Classes-");
// while (entityNameItr.hasNext()) {
// String key = (String) entityNameItr.next();
// FMLLog.log(Reference.MOD_NAME, Level.INFO, String.format(" %s", key));
// }
// }
// }
//
// Path: src/main/java/com/corwinjv/mobtotems/creativetab/CreativeTabMT.java
// public class CreativeTabMT {
// public static final CreativeTabs MT_TAB = new CreativeTabs(Reference.MOD_ID) {
// @Override
// public ItemStack getTabIconItem() {
// return new ItemStack(ModItems.TOTEMIC_FOCUS);
// }
// };
// }
// Path: src/main/java/com/corwinjv/mobtotems/blocks/ModBlockContainer.java
import com.corwinjv.mobtotems.Reference;
import com.corwinjv.mobtotems.creativetab.CreativeTabMT;
import net.minecraft.block.BlockContainer;
import net.minecraft.block.material.Material;
import net.minecraft.tileentity.TileEntity;
import net.minecraft.world.World;
import javax.annotation.Nullable;
package com.corwinjv.mobtotems.blocks;
/**
* Created by CorwinJV on 9/1/14.
*/
public class ModBlockContainer extends BlockContainer {
public ModBlockContainer(Material aMaterial) {
super(aMaterial);
this.init();
}
public ModBlockContainer() {
super(Material.WOOD);
this.init();
}
public void init() { | this.setCreativeTab(CreativeTabMT.MT_TAB); |
CorwinJV/MobTotems | src/main/java/com/corwinjv/mobtotems/blocks/ModBlockContainer.java | // Path: src/main/java/com/corwinjv/mobtotems/Reference.java
// public class Reference {
// public static final String MOD_ID = "mobtotems";
// public static final String MOD_NAME = "Mob Totems";
// public static final String MOD_VERSION = "1.12.1-0.3.0";
// public static final String RESOURCE_PREFIX = MOD_ID + ":";
//
// public static final String GUI_FACTORY_CLASS = "com.corwinjv.mobtotems.gui.GuiFactoryMT";
// public static final String CLIENT_SIDE_PROXY_CLASS = "com.corwinjv.mobtotems.proxy.ClientProxy";
// public static final String SERVER_SIDE_PROXY_CLASS = "com.corwinjv.mobtotems.proxy.CommonProxy";
//
// public static final int CHARGE_COLOR = 0xFF00FF00;
//
// public enum GUI_ID {
// OFFERING_BOX
// }
//
// ;
//
// public static void PrintEntityList() {
// Iterator entityNameItr = EntityList.getEntityNameList().iterator();
// FMLLog.log(Reference.MOD_NAME, Level.INFO, "-Printing Registered Entity Classes-");
// while (entityNameItr.hasNext()) {
// String key = (String) entityNameItr.next();
// FMLLog.log(Reference.MOD_NAME, Level.INFO, String.format(" %s", key));
// }
// }
// }
//
// Path: src/main/java/com/corwinjv/mobtotems/creativetab/CreativeTabMT.java
// public class CreativeTabMT {
// public static final CreativeTabs MT_TAB = new CreativeTabs(Reference.MOD_ID) {
// @Override
// public ItemStack getTabIconItem() {
// return new ItemStack(ModItems.TOTEMIC_FOCUS);
// }
// };
// }
| import com.corwinjv.mobtotems.Reference;
import com.corwinjv.mobtotems.creativetab.CreativeTabMT;
import net.minecraft.block.BlockContainer;
import net.minecraft.block.material.Material;
import net.minecraft.tileentity.TileEntity;
import net.minecraft.world.World;
import javax.annotation.Nullable; | package com.corwinjv.mobtotems.blocks;
/**
* Created by CorwinJV on 9/1/14.
*/
public class ModBlockContainer extends BlockContainer {
public ModBlockContainer(Material aMaterial) {
super(aMaterial);
this.init();
}
public ModBlockContainer() {
super(Material.WOOD);
this.init();
}
public void init() {
this.setCreativeTab(CreativeTabMT.MT_TAB);
}
@Override
public String getUnlocalizedName() { | // Path: src/main/java/com/corwinjv/mobtotems/Reference.java
// public class Reference {
// public static final String MOD_ID = "mobtotems";
// public static final String MOD_NAME = "Mob Totems";
// public static final String MOD_VERSION = "1.12.1-0.3.0";
// public static final String RESOURCE_PREFIX = MOD_ID + ":";
//
// public static final String GUI_FACTORY_CLASS = "com.corwinjv.mobtotems.gui.GuiFactoryMT";
// public static final String CLIENT_SIDE_PROXY_CLASS = "com.corwinjv.mobtotems.proxy.ClientProxy";
// public static final String SERVER_SIDE_PROXY_CLASS = "com.corwinjv.mobtotems.proxy.CommonProxy";
//
// public static final int CHARGE_COLOR = 0xFF00FF00;
//
// public enum GUI_ID {
// OFFERING_BOX
// }
//
// ;
//
// public static void PrintEntityList() {
// Iterator entityNameItr = EntityList.getEntityNameList().iterator();
// FMLLog.log(Reference.MOD_NAME, Level.INFO, "-Printing Registered Entity Classes-");
// while (entityNameItr.hasNext()) {
// String key = (String) entityNameItr.next();
// FMLLog.log(Reference.MOD_NAME, Level.INFO, String.format(" %s", key));
// }
// }
// }
//
// Path: src/main/java/com/corwinjv/mobtotems/creativetab/CreativeTabMT.java
// public class CreativeTabMT {
// public static final CreativeTabs MT_TAB = new CreativeTabs(Reference.MOD_ID) {
// @Override
// public ItemStack getTabIconItem() {
// return new ItemStack(ModItems.TOTEMIC_FOCUS);
// }
// };
// }
// Path: src/main/java/com/corwinjv/mobtotems/blocks/ModBlockContainer.java
import com.corwinjv.mobtotems.Reference;
import com.corwinjv.mobtotems.creativetab.CreativeTabMT;
import net.minecraft.block.BlockContainer;
import net.minecraft.block.material.Material;
import net.minecraft.tileentity.TileEntity;
import net.minecraft.world.World;
import javax.annotation.Nullable;
package com.corwinjv.mobtotems.blocks;
/**
* Created by CorwinJV on 9/1/14.
*/
public class ModBlockContainer extends BlockContainer {
public ModBlockContainer(Material aMaterial) {
super(aMaterial);
this.init();
}
public ModBlockContainer() {
super(Material.WOOD);
this.init();
}
public void init() {
this.setCreativeTab(CreativeTabMT.MT_TAB);
}
@Override
public String getUnlocalizedName() { | return String.format("tiles.%s%s", Reference.RESOURCE_PREFIX, getUnwrappedUnlocalizedName(super.getUnlocalizedName())); |
CorwinJV/MobTotems | src/main/java/com/corwinjv/di/MobTotemsComponent.java | // Path: src/main/java/com/corwinjv/di/modules/MobTotemsModule.java
// @Module
// public class MobTotemsModule {
//
// private MobTotems mobTotems;
//
// public MobTotemsModule(MobTotems mobTotems) {
// this.mobTotems = mobTotems;
// }
//
// @Provides
// public MobTotems provideMobTotems() {
// return mobTotems;
// }
// }
//
// Path: src/main/java/com/corwinjv/mobtotems/MobTotems.java
// @Mod(modid = Reference.MOD_ID, name = Reference.MOD_NAME, version = Reference.MOD_VERSION, guiFactory = Reference.GUI_FACTORY_CLASS,
// dependencies = "before:guideapi")
// public class MobTotems {
// @Mod.Instance
// public static MobTotems instance;
//
// @SidedProxy(clientSide = Reference.CLIENT_SIDE_PROXY_CLASS, serverSide = Reference.SERVER_SIDE_PROXY_CLASS)
// public static CommonProxy proxy;
//
// private static MobTotemsComponent mobTotemsComponent;
//
// @Mod.EventHandler
// public void preInit(FMLPreInitializationEvent event) {
// // //Dagger 2 implementation
// // mobTotemsComponent = proxy.initializeDagger(instance);
//
// // Network & Messages
// Network.init();
// NetworkRegistry.INSTANCE.registerGuiHandler(instance, new OfferingBoxGuiHandler());
//
// // Config
// ConfigurationHandler.Init(event.getSuggestedConfigurationFile());
// MinecraftForge.EVENT_BUS.register(new ConfigurationHandler());
//
// // Helper stuff
// TotemHelper.init();
// MinecraftForge.EVENT_BUS.register(new CreeperLogic.CreeperTotemEntityJoinWorldEvent());
// MinecraftForge.EVENT_BUS.register(new CowLogic.CowTotemEntityJoinWorldEvent());
// MinecraftForge.EVENT_BUS.register(new EnderLogic.EnderTotemEnderTeleportEvent());
//
// // Blocks
// ModBlocks.init();
//
// // Items
// ModItems.init();
//
// // Entities
// ModEntities.init();
// ModEntities.registerEntities(instance);
// proxy.registerEntityRenders();
//
// // Keybinds
// proxy.registerKeys();
// }
//
// public static MobTotemsComponent component() {
// return mobTotemsComponent;
// }
//
// @Mod.EventHandler
// public void init(FMLInitializationEvent event) {
// proxy.registerRenders();
// }
//
// @Mod.EventHandler
// public void postInit(FMLPostInitializationEvent event) {
// proxy.registerGui();
// proxy.registerParticleRenderer();
// }
// }
| import com.corwinjv.di.modules.MobTotemsModule;
import com.corwinjv.mobtotems.MobTotems;
import dagger.Component; | package com.corwinjv.di;
@Component(modules = {
MobTotemsModule.class
}, dependencies = {
MinecraftComponent.class
})
public interface MobTotemsComponent extends MinecraftComponent {
| // Path: src/main/java/com/corwinjv/di/modules/MobTotemsModule.java
// @Module
// public class MobTotemsModule {
//
// private MobTotems mobTotems;
//
// public MobTotemsModule(MobTotems mobTotems) {
// this.mobTotems = mobTotems;
// }
//
// @Provides
// public MobTotems provideMobTotems() {
// return mobTotems;
// }
// }
//
// Path: src/main/java/com/corwinjv/mobtotems/MobTotems.java
// @Mod(modid = Reference.MOD_ID, name = Reference.MOD_NAME, version = Reference.MOD_VERSION, guiFactory = Reference.GUI_FACTORY_CLASS,
// dependencies = "before:guideapi")
// public class MobTotems {
// @Mod.Instance
// public static MobTotems instance;
//
// @SidedProxy(clientSide = Reference.CLIENT_SIDE_PROXY_CLASS, serverSide = Reference.SERVER_SIDE_PROXY_CLASS)
// public static CommonProxy proxy;
//
// private static MobTotemsComponent mobTotemsComponent;
//
// @Mod.EventHandler
// public void preInit(FMLPreInitializationEvent event) {
// // //Dagger 2 implementation
// // mobTotemsComponent = proxy.initializeDagger(instance);
//
// // Network & Messages
// Network.init();
// NetworkRegistry.INSTANCE.registerGuiHandler(instance, new OfferingBoxGuiHandler());
//
// // Config
// ConfigurationHandler.Init(event.getSuggestedConfigurationFile());
// MinecraftForge.EVENT_BUS.register(new ConfigurationHandler());
//
// // Helper stuff
// TotemHelper.init();
// MinecraftForge.EVENT_BUS.register(new CreeperLogic.CreeperTotemEntityJoinWorldEvent());
// MinecraftForge.EVENT_BUS.register(new CowLogic.CowTotemEntityJoinWorldEvent());
// MinecraftForge.EVENT_BUS.register(new EnderLogic.EnderTotemEnderTeleportEvent());
//
// // Blocks
// ModBlocks.init();
//
// // Items
// ModItems.init();
//
// // Entities
// ModEntities.init();
// ModEntities.registerEntities(instance);
// proxy.registerEntityRenders();
//
// // Keybinds
// proxy.registerKeys();
// }
//
// public static MobTotemsComponent component() {
// return mobTotemsComponent;
// }
//
// @Mod.EventHandler
// public void init(FMLInitializationEvent event) {
// proxy.registerRenders();
// }
//
// @Mod.EventHandler
// public void postInit(FMLPostInitializationEvent event) {
// proxy.registerGui();
// proxy.registerParticleRenderer();
// }
// }
// Path: src/main/java/com/corwinjv/di/MobTotemsComponent.java
import com.corwinjv.di.modules.MobTotemsModule;
import com.corwinjv.mobtotems.MobTotems;
import dagger.Component;
package com.corwinjv.di;
@Component(modules = {
MobTotemsModule.class
}, dependencies = {
MinecraftComponent.class
})
public interface MobTotemsComponent extends MinecraftComponent {
| MobTotems mobTotems(); |
CorwinJV/MobTotems | src/main/java/com/corwinjv/mobtotems/config/ConfigurationHandler.java | // Path: src/main/java/com/corwinjv/mobtotems/Reference.java
// public class Reference {
// public static final String MOD_ID = "mobtotems";
// public static final String MOD_NAME = "Mob Totems";
// public static final String MOD_VERSION = "1.12.1-0.3.0";
// public static final String RESOURCE_PREFIX = MOD_ID + ":";
//
// public static final String GUI_FACTORY_CLASS = "com.corwinjv.mobtotems.gui.GuiFactoryMT";
// public static final String CLIENT_SIDE_PROXY_CLASS = "com.corwinjv.mobtotems.proxy.ClientProxy";
// public static final String SERVER_SIDE_PROXY_CLASS = "com.corwinjv.mobtotems.proxy.CommonProxy";
//
// public static final int CHARGE_COLOR = 0xFF00FF00;
//
// public enum GUI_ID {
// OFFERING_BOX
// }
//
// ;
//
// public static void PrintEntityList() {
// Iterator entityNameItr = EntityList.getEntityNameList().iterator();
// FMLLog.log(Reference.MOD_NAME, Level.INFO, "-Printing Registered Entity Classes-");
// while (entityNameItr.hasNext()) {
// String key = (String) entityNameItr.next();
// FMLLog.log(Reference.MOD_NAME, Level.INFO, String.format(" %s", key));
// }
// }
// }
| import com.corwinjv.mobtotems.Reference;
import net.minecraftforge.common.config.Configuration;
import net.minecraftforge.fml.client.event.ConfigChangedEvent;
import net.minecraftforge.fml.common.eventhandler.SubscribeEvent;
import java.io.File; | package com.corwinjv.mobtotems.config;
/**
* Created by CorwinJV on 8/31/14.
*/
public class ConfigurationHandler {
public static Configuration configuration;
/**
* Config Properties
**/
public static void Init(File aConfigFile) {
if (configuration == null) {
configuration = new Configuration(aConfigFile);
loadConfiguration();
}
}
@SubscribeEvent
public void onConfigurationChangedEvent(ConfigChangedEvent.OnConfigChangedEvent event) { | // Path: src/main/java/com/corwinjv/mobtotems/Reference.java
// public class Reference {
// public static final String MOD_ID = "mobtotems";
// public static final String MOD_NAME = "Mob Totems";
// public static final String MOD_VERSION = "1.12.1-0.3.0";
// public static final String RESOURCE_PREFIX = MOD_ID + ":";
//
// public static final String GUI_FACTORY_CLASS = "com.corwinjv.mobtotems.gui.GuiFactoryMT";
// public static final String CLIENT_SIDE_PROXY_CLASS = "com.corwinjv.mobtotems.proxy.ClientProxy";
// public static final String SERVER_SIDE_PROXY_CLASS = "com.corwinjv.mobtotems.proxy.CommonProxy";
//
// public static final int CHARGE_COLOR = 0xFF00FF00;
//
// public enum GUI_ID {
// OFFERING_BOX
// }
//
// ;
//
// public static void PrintEntityList() {
// Iterator entityNameItr = EntityList.getEntityNameList().iterator();
// FMLLog.log(Reference.MOD_NAME, Level.INFO, "-Printing Registered Entity Classes-");
// while (entityNameItr.hasNext()) {
// String key = (String) entityNameItr.next();
// FMLLog.log(Reference.MOD_NAME, Level.INFO, String.format(" %s", key));
// }
// }
// }
// Path: src/main/java/com/corwinjv/mobtotems/config/ConfigurationHandler.java
import com.corwinjv.mobtotems.Reference;
import net.minecraftforge.common.config.Configuration;
import net.minecraftforge.fml.client.event.ConfigChangedEvent;
import net.minecraftforge.fml.common.eventhandler.SubscribeEvent;
import java.io.File;
package com.corwinjv.mobtotems.config;
/**
* Created by CorwinJV on 8/31/14.
*/
public class ConfigurationHandler {
public static Configuration configuration;
/**
* Config Properties
**/
public static void Init(File aConfigFile) {
if (configuration == null) {
configuration = new Configuration(aConfigFile);
loadConfiguration();
}
}
@SubscribeEvent
public void onConfigurationChangedEvent(ConfigChangedEvent.OnConfigChangedEvent event) { | if (Reference.MOD_ID.equalsIgnoreCase(event.getModID())) { |
CorwinJV/MobTotems | src/main/java/com/corwinjv/mobtotems/gui/BaublesChargeGui.java | // Path: src/main/java/com/corwinjv/mobtotems/Reference.java
// public class Reference {
// public static final String MOD_ID = "mobtotems";
// public static final String MOD_NAME = "Mob Totems";
// public static final String MOD_VERSION = "1.12.1-0.3.0";
// public static final String RESOURCE_PREFIX = MOD_ID + ":";
//
// public static final String GUI_FACTORY_CLASS = "com.corwinjv.mobtotems.gui.GuiFactoryMT";
// public static final String CLIENT_SIDE_PROXY_CLASS = "com.corwinjv.mobtotems.proxy.ClientProxy";
// public static final String SERVER_SIDE_PROXY_CLASS = "com.corwinjv.mobtotems.proxy.CommonProxy";
//
// public static final int CHARGE_COLOR = 0xFF00FF00;
//
// public enum GUI_ID {
// OFFERING_BOX
// }
//
// ;
//
// public static void PrintEntityList() {
// Iterator entityNameItr = EntityList.getEntityNameList().iterator();
// FMLLog.log(Reference.MOD_NAME, Level.INFO, "-Printing Registered Entity Classes-");
// while (entityNameItr.hasNext()) {
// String key = (String) entityNameItr.next();
// FMLLog.log(Reference.MOD_NAME, Level.INFO, String.format(" %s", key));
// }
// }
// }
//
// Path: src/main/java/com/corwinjv/mobtotems/items/baubles/BaubleItem.java
// @Optional.Interface(modid = "baubles", iface = "baubles.api.IBauble")
// public class BaubleItem extends ModItem implements IBauble, IChargeable {
// protected static final String CHARGE_LEVEL = "CHARGE_LEVEL";
//
// public BaubleItem() {
// super();
// }
//
// @Override
// public void onCreated(ItemStack stack, World worldIn, EntityPlayer playerIn) {
// initNbtData(stack);
// }
//
// protected NBTTagCompound initNbtData(ItemStack stack) {
// NBTTagCompound nbtTagCompound = stack.getTagCompound();
// if (nbtTagCompound == null) {
// nbtTagCompound = new NBTTagCompound();
// }
// nbtTagCompound.setInteger(CHARGE_LEVEL, 0);
//
// stack.setTagCompound(nbtTagCompound);
// return nbtTagCompound;
// }
//
// @SuppressWarnings("all")
// @Override
// public int getChargeLevel(ItemStack stack) {
// NBTTagCompound tagCompound = stack.getTagCompound();
// if (tagCompound == null) {
// tagCompound = initNbtData(stack);
// }
// return tagCompound.getInteger(CHARGE_LEVEL);
// }
//
// @Override
// public void setChargeLevel(ItemStack stack, int chargeLevel) {
// NBTTagCompound tagCompound = stack.getTagCompound();
// if (tagCompound == null) {
// tagCompound = initNbtData(stack);
// }
// tagCompound.setInteger(CHARGE_LEVEL, chargeLevel);
// }
//
// @Override
// public void decrementChargeLevel(ItemStack stack, int amount) {
// int chargeLevel = getChargeLevel(stack);
// chargeLevel -= amount;
// if (chargeLevel < 0) {
// chargeLevel = 0;
// }
//
// setChargeLevel(stack, chargeLevel);
// }
//
// @Override
// public void incrementChargeLevel(ItemStack stack, int amount) {
// int chargeLevel = getChargeLevel(stack);
// chargeLevel += amount;
// if (chargeLevel > getMaxChargeLevel()) {
// chargeLevel = getMaxChargeLevel();
// }
// setChargeLevel(stack, chargeLevel);
// }
//
// @Override
// public int getMaxChargeLevel() {
// return 16;
// }
//
// public void onBaubleActivated(ItemStack stack, EntityPlayer player) {
// }
//
// @Override
// @SideOnly(Side.CLIENT)
// public void addInformation(ItemStack stack, @Nullable World worldIn, List<String> tooltip, ITooltipFlag flagIn) {
// super.addInformation(stack, worldIn, tooltip, flagIn);
// }
//
// @Override
// public BaubleType getBaubleType(ItemStack itemstack) {
// return BaubleType.TRINKET;
// }
//
// @Override
// public boolean canEquip(ItemStack itemstack, EntityLivingBase player) {
// return true;
// }
//
// @Override
// public boolean canUnequip(ItemStack itemstack, EntityLivingBase player) {
// return true;
// }
//
// @Override
// public boolean willAutoSync(ItemStack itemstack, EntityLivingBase player) {
// return true;
// }
// }
| import baubles.api.BaublesApi;
import baubles.api.cap.IBaublesItemHandler;
import com.corwinjv.mobtotems.Reference;
import com.corwinjv.mobtotems.items.baubles.BaubleItem;
import net.minecraft.client.Minecraft;
import net.minecraft.client.gui.Gui;
import net.minecraft.item.ItemStack;
import net.minecraftforge.client.event.RenderGameOverlayEvent;
import net.minecraftforge.fml.common.Optional;
import net.minecraftforge.fml.common.eventhandler.SubscribeEvent;
import org.lwjgl.opengl.GL11; | package com.corwinjv.mobtotems.gui;
/**
* Created by CorwinJV on 7/27/2016.
*/
public class BaublesChargeGui extends Gui {
private static final int ICON_BORDER = 2;
private static final int ICON_WIDTH = 16;
private static final int ICON_HEIGHT = 16;
private static final int BG_BORDER = 1;
private static final int BG_WIDTH = 18;
private static final int BG_HEIGHT = 18;
private Minecraft minecraft = null;
public BaublesChargeGui(Minecraft mc) {
super();
minecraft = mc;
}
@Optional.Method(modid = "baubles")
@SubscribeEvent()
public void onRenderOverlay(RenderGameOverlayEvent e) {
if (e.isCancelable() || e.getType() != RenderGameOverlayEvent.ElementType.POTION_ICONS) {
return;
}
IBaublesItemHandler baublesItemHandler = BaublesApi.getBaublesHandler(minecraft.player);
for (int i = 0; i < baublesItemHandler.getSlots(); i++) {
final ItemStack baubleStack = baublesItemHandler.getStackInSlot(i);
if (baubleStack != ItemStack.EMPTY | // Path: src/main/java/com/corwinjv/mobtotems/Reference.java
// public class Reference {
// public static final String MOD_ID = "mobtotems";
// public static final String MOD_NAME = "Mob Totems";
// public static final String MOD_VERSION = "1.12.1-0.3.0";
// public static final String RESOURCE_PREFIX = MOD_ID + ":";
//
// public static final String GUI_FACTORY_CLASS = "com.corwinjv.mobtotems.gui.GuiFactoryMT";
// public static final String CLIENT_SIDE_PROXY_CLASS = "com.corwinjv.mobtotems.proxy.ClientProxy";
// public static final String SERVER_SIDE_PROXY_CLASS = "com.corwinjv.mobtotems.proxy.CommonProxy";
//
// public static final int CHARGE_COLOR = 0xFF00FF00;
//
// public enum GUI_ID {
// OFFERING_BOX
// }
//
// ;
//
// public static void PrintEntityList() {
// Iterator entityNameItr = EntityList.getEntityNameList().iterator();
// FMLLog.log(Reference.MOD_NAME, Level.INFO, "-Printing Registered Entity Classes-");
// while (entityNameItr.hasNext()) {
// String key = (String) entityNameItr.next();
// FMLLog.log(Reference.MOD_NAME, Level.INFO, String.format(" %s", key));
// }
// }
// }
//
// Path: src/main/java/com/corwinjv/mobtotems/items/baubles/BaubleItem.java
// @Optional.Interface(modid = "baubles", iface = "baubles.api.IBauble")
// public class BaubleItem extends ModItem implements IBauble, IChargeable {
// protected static final String CHARGE_LEVEL = "CHARGE_LEVEL";
//
// public BaubleItem() {
// super();
// }
//
// @Override
// public void onCreated(ItemStack stack, World worldIn, EntityPlayer playerIn) {
// initNbtData(stack);
// }
//
// protected NBTTagCompound initNbtData(ItemStack stack) {
// NBTTagCompound nbtTagCompound = stack.getTagCompound();
// if (nbtTagCompound == null) {
// nbtTagCompound = new NBTTagCompound();
// }
// nbtTagCompound.setInteger(CHARGE_LEVEL, 0);
//
// stack.setTagCompound(nbtTagCompound);
// return nbtTagCompound;
// }
//
// @SuppressWarnings("all")
// @Override
// public int getChargeLevel(ItemStack stack) {
// NBTTagCompound tagCompound = stack.getTagCompound();
// if (tagCompound == null) {
// tagCompound = initNbtData(stack);
// }
// return tagCompound.getInteger(CHARGE_LEVEL);
// }
//
// @Override
// public void setChargeLevel(ItemStack stack, int chargeLevel) {
// NBTTagCompound tagCompound = stack.getTagCompound();
// if (tagCompound == null) {
// tagCompound = initNbtData(stack);
// }
// tagCompound.setInteger(CHARGE_LEVEL, chargeLevel);
// }
//
// @Override
// public void decrementChargeLevel(ItemStack stack, int amount) {
// int chargeLevel = getChargeLevel(stack);
// chargeLevel -= amount;
// if (chargeLevel < 0) {
// chargeLevel = 0;
// }
//
// setChargeLevel(stack, chargeLevel);
// }
//
// @Override
// public void incrementChargeLevel(ItemStack stack, int amount) {
// int chargeLevel = getChargeLevel(stack);
// chargeLevel += amount;
// if (chargeLevel > getMaxChargeLevel()) {
// chargeLevel = getMaxChargeLevel();
// }
// setChargeLevel(stack, chargeLevel);
// }
//
// @Override
// public int getMaxChargeLevel() {
// return 16;
// }
//
// public void onBaubleActivated(ItemStack stack, EntityPlayer player) {
// }
//
// @Override
// @SideOnly(Side.CLIENT)
// public void addInformation(ItemStack stack, @Nullable World worldIn, List<String> tooltip, ITooltipFlag flagIn) {
// super.addInformation(stack, worldIn, tooltip, flagIn);
// }
//
// @Override
// public BaubleType getBaubleType(ItemStack itemstack) {
// return BaubleType.TRINKET;
// }
//
// @Override
// public boolean canEquip(ItemStack itemstack, EntityLivingBase player) {
// return true;
// }
//
// @Override
// public boolean canUnequip(ItemStack itemstack, EntityLivingBase player) {
// return true;
// }
//
// @Override
// public boolean willAutoSync(ItemStack itemstack, EntityLivingBase player) {
// return true;
// }
// }
// Path: src/main/java/com/corwinjv/mobtotems/gui/BaublesChargeGui.java
import baubles.api.BaublesApi;
import baubles.api.cap.IBaublesItemHandler;
import com.corwinjv.mobtotems.Reference;
import com.corwinjv.mobtotems.items.baubles.BaubleItem;
import net.minecraft.client.Minecraft;
import net.minecraft.client.gui.Gui;
import net.minecraft.item.ItemStack;
import net.minecraftforge.client.event.RenderGameOverlayEvent;
import net.minecraftforge.fml.common.Optional;
import net.minecraftforge.fml.common.eventhandler.SubscribeEvent;
import org.lwjgl.opengl.GL11;
package com.corwinjv.mobtotems.gui;
/**
* Created by CorwinJV on 7/27/2016.
*/
public class BaublesChargeGui extends Gui {
private static final int ICON_BORDER = 2;
private static final int ICON_WIDTH = 16;
private static final int ICON_HEIGHT = 16;
private static final int BG_BORDER = 1;
private static final int BG_WIDTH = 18;
private static final int BG_HEIGHT = 18;
private Minecraft minecraft = null;
public BaublesChargeGui(Minecraft mc) {
super();
minecraft = mc;
}
@Optional.Method(modid = "baubles")
@SubscribeEvent()
public void onRenderOverlay(RenderGameOverlayEvent e) {
if (e.isCancelable() || e.getType() != RenderGameOverlayEvent.ElementType.POTION_ICONS) {
return;
}
IBaublesItemHandler baublesItemHandler = BaublesApi.getBaublesHandler(minecraft.player);
for (int i = 0; i < baublesItemHandler.getSlots(); i++) {
final ItemStack baubleStack = baublesItemHandler.getStackInSlot(i);
if (baubleStack != ItemStack.EMPTY | && baubleStack.getItem() instanceof BaubleItem) { |
CorwinJV/MobTotems | src/main/java/com/corwinjv/di/modules/MobTotemsModule.java | // Path: src/main/java/com/corwinjv/mobtotems/MobTotems.java
// @Mod(modid = Reference.MOD_ID, name = Reference.MOD_NAME, version = Reference.MOD_VERSION, guiFactory = Reference.GUI_FACTORY_CLASS,
// dependencies = "before:guideapi")
// public class MobTotems {
// @Mod.Instance
// public static MobTotems instance;
//
// @SidedProxy(clientSide = Reference.CLIENT_SIDE_PROXY_CLASS, serverSide = Reference.SERVER_SIDE_PROXY_CLASS)
// public static CommonProxy proxy;
//
// private static MobTotemsComponent mobTotemsComponent;
//
// @Mod.EventHandler
// public void preInit(FMLPreInitializationEvent event) {
// // //Dagger 2 implementation
// // mobTotemsComponent = proxy.initializeDagger(instance);
//
// // Network & Messages
// Network.init();
// NetworkRegistry.INSTANCE.registerGuiHandler(instance, new OfferingBoxGuiHandler());
//
// // Config
// ConfigurationHandler.Init(event.getSuggestedConfigurationFile());
// MinecraftForge.EVENT_BUS.register(new ConfigurationHandler());
//
// // Helper stuff
// TotemHelper.init();
// MinecraftForge.EVENT_BUS.register(new CreeperLogic.CreeperTotemEntityJoinWorldEvent());
// MinecraftForge.EVENT_BUS.register(new CowLogic.CowTotemEntityJoinWorldEvent());
// MinecraftForge.EVENT_BUS.register(new EnderLogic.EnderTotemEnderTeleportEvent());
//
// // Blocks
// ModBlocks.init();
//
// // Items
// ModItems.init();
//
// // Entities
// ModEntities.init();
// ModEntities.registerEntities(instance);
// proxy.registerEntityRenders();
//
// // Keybinds
// proxy.registerKeys();
// }
//
// public static MobTotemsComponent component() {
// return mobTotemsComponent;
// }
//
// @Mod.EventHandler
// public void init(FMLInitializationEvent event) {
// proxy.registerRenders();
// }
//
// @Mod.EventHandler
// public void postInit(FMLPostInitializationEvent event) {
// proxy.registerGui();
// proxy.registerParticleRenderer();
// }
// }
| import com.corwinjv.mobtotems.MobTotems;
import dagger.Module;
import dagger.Provides; | package com.corwinjv.di.modules;
@Module
public class MobTotemsModule {
| // Path: src/main/java/com/corwinjv/mobtotems/MobTotems.java
// @Mod(modid = Reference.MOD_ID, name = Reference.MOD_NAME, version = Reference.MOD_VERSION, guiFactory = Reference.GUI_FACTORY_CLASS,
// dependencies = "before:guideapi")
// public class MobTotems {
// @Mod.Instance
// public static MobTotems instance;
//
// @SidedProxy(clientSide = Reference.CLIENT_SIDE_PROXY_CLASS, serverSide = Reference.SERVER_SIDE_PROXY_CLASS)
// public static CommonProxy proxy;
//
// private static MobTotemsComponent mobTotemsComponent;
//
// @Mod.EventHandler
// public void preInit(FMLPreInitializationEvent event) {
// // //Dagger 2 implementation
// // mobTotemsComponent = proxy.initializeDagger(instance);
//
// // Network & Messages
// Network.init();
// NetworkRegistry.INSTANCE.registerGuiHandler(instance, new OfferingBoxGuiHandler());
//
// // Config
// ConfigurationHandler.Init(event.getSuggestedConfigurationFile());
// MinecraftForge.EVENT_BUS.register(new ConfigurationHandler());
//
// // Helper stuff
// TotemHelper.init();
// MinecraftForge.EVENT_BUS.register(new CreeperLogic.CreeperTotemEntityJoinWorldEvent());
// MinecraftForge.EVENT_BUS.register(new CowLogic.CowTotemEntityJoinWorldEvent());
// MinecraftForge.EVENT_BUS.register(new EnderLogic.EnderTotemEnderTeleportEvent());
//
// // Blocks
// ModBlocks.init();
//
// // Items
// ModItems.init();
//
// // Entities
// ModEntities.init();
// ModEntities.registerEntities(instance);
// proxy.registerEntityRenders();
//
// // Keybinds
// proxy.registerKeys();
// }
//
// public static MobTotemsComponent component() {
// return mobTotemsComponent;
// }
//
// @Mod.EventHandler
// public void init(FMLInitializationEvent event) {
// proxy.registerRenders();
// }
//
// @Mod.EventHandler
// public void postInit(FMLPostInitializationEvent event) {
// proxy.registerGui();
// proxy.registerParticleRenderer();
// }
// }
// Path: src/main/java/com/corwinjv/di/modules/MobTotemsModule.java
import com.corwinjv.mobtotems.MobTotems;
import dagger.Module;
import dagger.Provides;
package com.corwinjv.di.modules;
@Module
public class MobTotemsModule {
| private MobTotems mobTotems; |
CorwinJV/MobTotems | src/main/java/com/corwinjv/mobtotems/blocks/tiles/TotemLogic/BlazeLogic.java | // Path: src/main/java/com/corwinjv/mobtotems/TotemHelper.java
// public static final int DEFAULT_RADIUS = 32;
//
// Path: src/main/java/com/corwinjv/mobtotems/TotemHelper.java
// public static final int RANGE_BOOST = 16;
| import net.minecraft.entity.Entity;
import net.minecraft.entity.monster.IMob;
import net.minecraft.init.Items;
import net.minecraft.item.ItemStack;
import net.minecraft.util.DamageSource;
import net.minecraft.util.math.AxisAlignedBB;
import net.minecraft.util.math.BlockPos;
import net.minecraft.world.World;
import javax.annotation.Nonnull;
import java.util.ArrayList;
import java.util.List;
import static com.corwinjv.mobtotems.TotemHelper.DEFAULT_RADIUS;
import static com.corwinjv.mobtotems.TotemHelper.RANGE_BOOST; | package com.corwinjv.mobtotems.blocks.tiles.TotemLogic;
/**
* Created by CorwinJV on 1/25/2017.
*/
public class BlazeLogic extends TotemLogic {
private static final int FIRE_DURATION = 1;
@Override
public List<ItemStack> getCost() {
List<ItemStack> cost = new ArrayList<>();
cost.add(new ItemStack(Items.COAL, 2, 0));
return cost;
}
@Nonnull
@Override
public EffectType getEffectType() {
return EffectType.EFFECT;
}
@Override
public void performEffect(World world, BlockPos pos, Modifiers modifiers) { | // Path: src/main/java/com/corwinjv/mobtotems/TotemHelper.java
// public static final int DEFAULT_RADIUS = 32;
//
// Path: src/main/java/com/corwinjv/mobtotems/TotemHelper.java
// public static final int RANGE_BOOST = 16;
// Path: src/main/java/com/corwinjv/mobtotems/blocks/tiles/TotemLogic/BlazeLogic.java
import net.minecraft.entity.Entity;
import net.minecraft.entity.monster.IMob;
import net.minecraft.init.Items;
import net.minecraft.item.ItemStack;
import net.minecraft.util.DamageSource;
import net.minecraft.util.math.AxisAlignedBB;
import net.minecraft.util.math.BlockPos;
import net.minecraft.world.World;
import javax.annotation.Nonnull;
import java.util.ArrayList;
import java.util.List;
import static com.corwinjv.mobtotems.TotemHelper.DEFAULT_RADIUS;
import static com.corwinjv.mobtotems.TotemHelper.RANGE_BOOST;
package com.corwinjv.mobtotems.blocks.tiles.TotemLogic;
/**
* Created by CorwinJV on 1/25/2017.
*/
public class BlazeLogic extends TotemLogic {
private static final int FIRE_DURATION = 1;
@Override
public List<ItemStack> getCost() {
List<ItemStack> cost = new ArrayList<>();
cost.add(new ItemStack(Items.COAL, 2, 0));
return cost;
}
@Nonnull
@Override
public EffectType getEffectType() {
return EffectType.EFFECT;
}
@Override
public void performEffect(World world, BlockPos pos, Modifiers modifiers) { | int radius = DEFAULT_RADIUS + (int) (RANGE_BOOST * modifiers.range); |
CorwinJV/MobTotems | src/main/java/com/corwinjv/mobtotems/blocks/tiles/TotemLogic/BlazeLogic.java | // Path: src/main/java/com/corwinjv/mobtotems/TotemHelper.java
// public static final int DEFAULT_RADIUS = 32;
//
// Path: src/main/java/com/corwinjv/mobtotems/TotemHelper.java
// public static final int RANGE_BOOST = 16;
| import net.minecraft.entity.Entity;
import net.minecraft.entity.monster.IMob;
import net.minecraft.init.Items;
import net.minecraft.item.ItemStack;
import net.minecraft.util.DamageSource;
import net.minecraft.util.math.AxisAlignedBB;
import net.minecraft.util.math.BlockPos;
import net.minecraft.world.World;
import javax.annotation.Nonnull;
import java.util.ArrayList;
import java.util.List;
import static com.corwinjv.mobtotems.TotemHelper.DEFAULT_RADIUS;
import static com.corwinjv.mobtotems.TotemHelper.RANGE_BOOST; | package com.corwinjv.mobtotems.blocks.tiles.TotemLogic;
/**
* Created by CorwinJV on 1/25/2017.
*/
public class BlazeLogic extends TotemLogic {
private static final int FIRE_DURATION = 1;
@Override
public List<ItemStack> getCost() {
List<ItemStack> cost = new ArrayList<>();
cost.add(new ItemStack(Items.COAL, 2, 0));
return cost;
}
@Nonnull
@Override
public EffectType getEffectType() {
return EffectType.EFFECT;
}
@Override
public void performEffect(World world, BlockPos pos, Modifiers modifiers) { | // Path: src/main/java/com/corwinjv/mobtotems/TotemHelper.java
// public static final int DEFAULT_RADIUS = 32;
//
// Path: src/main/java/com/corwinjv/mobtotems/TotemHelper.java
// public static final int RANGE_BOOST = 16;
// Path: src/main/java/com/corwinjv/mobtotems/blocks/tiles/TotemLogic/BlazeLogic.java
import net.minecraft.entity.Entity;
import net.minecraft.entity.monster.IMob;
import net.minecraft.init.Items;
import net.minecraft.item.ItemStack;
import net.minecraft.util.DamageSource;
import net.minecraft.util.math.AxisAlignedBB;
import net.minecraft.util.math.BlockPos;
import net.minecraft.world.World;
import javax.annotation.Nonnull;
import java.util.ArrayList;
import java.util.List;
import static com.corwinjv.mobtotems.TotemHelper.DEFAULT_RADIUS;
import static com.corwinjv.mobtotems.TotemHelper.RANGE_BOOST;
package com.corwinjv.mobtotems.blocks.tiles.TotemLogic;
/**
* Created by CorwinJV on 1/25/2017.
*/
public class BlazeLogic extends TotemLogic {
private static final int FIRE_DURATION = 1;
@Override
public List<ItemStack> getCost() {
List<ItemStack> cost = new ArrayList<>();
cost.add(new ItemStack(Items.COAL, 2, 0));
return cost;
}
@Nonnull
@Override
public EffectType getEffectType() {
return EffectType.EFFECT;
}
@Override
public void performEffect(World world, BlockPos pos, Modifiers modifiers) { | int radius = DEFAULT_RADIUS + (int) (RANGE_BOOST * modifiers.range); |
CorwinJV/MobTotems | src/main/java/com/corwinjv/mobtotems/KeyBindings.java | // Path: src/main/java/com/corwinjv/mobtotems/network/ActivateBaubleMessage.java
// public class ActivateBaubleMessage extends Message<ActivateBaubleMessage> {
// @Override
// protected void handleServer(ActivateBaubleMessage message, EntityPlayerMP player) {
// final IBaublesItemHandler baublesItemHandler = BaublesApi.getBaublesHandler(player);
//
// if (baublesItemHandler == null) {
// return;
// }
//
// for (int i = 0; i < baublesItemHandler.getSlots(); i++) {
// final ItemStack baubleStack = baublesItemHandler.getStackInSlot(i);
// if (baubleStack != ItemStack.EMPTY
// && baubleStack.getItem() instanceof BaubleItem) {
// ((BaubleItem) baubleStack.getItem()).onBaubleActivated(baubleStack, player);
// }
// }
// }
// }
//
// Path: src/main/java/com/corwinjv/mobtotems/network/Network.java
// public class Network {
// private static SimpleNetworkWrapper instance = null;
// private static int DISCRIMINATOR_ID = 0;
//
// public static void init() {
// instance = NetworkRegistry.INSTANCE.newSimpleChannel(Reference.MOD_ID);
//
// instance.registerMessage(ActivateBaubleMessage.class, ActivateBaubleMessage.class, getDiscriminatorId(), Side.SERVER);
// instance.registerMessage(ActivateKnifeMessage.class, ActivateKnifeMessage.class, getDiscriminatorId(), Side.SERVER);
// instance.registerMessage(SetKnifeMetaMessage.class, SetKnifeMetaMessage.class, getDiscriminatorId(), Side.SERVER);
//
// instance.registerMessage(OpenKnifeGuiMessage.class, OpenKnifeGuiMessage.class, getDiscriminatorId(), Side.CLIENT);
// }
//
// private static int getDiscriminatorId() {
// return DISCRIMINATOR_ID++;
// }
//
// public static void sendToServer(Message message) {
// instance.sendToServer(message);
// }
//
// public static void sendToAll(Message message) {
// instance.sendToAll(message);
// }
//
// public static void sendTo(Message message, EntityPlayerMP player) {
// instance.sendTo(message, player);
// }
// }
| import com.corwinjv.mobtotems.network.ActivateBaubleMessage;
import com.corwinjv.mobtotems.network.Network;
import net.minecraft.client.gui.GuiChat;
import net.minecraft.client.settings.KeyBinding;
import net.minecraftforge.fml.client.FMLClientHandler;
import net.minecraftforge.fml.client.registry.ClientRegistry;
import net.minecraftforge.fml.common.eventhandler.SubscribeEvent;
import net.minecraftforge.fml.common.gameevent.InputEvent;
import net.minecraftforge.fml.relauncher.Side;
import net.minecraftforge.fml.relauncher.SideOnly;
import org.lwjgl.input.Keyboard; | package com.corwinjv.mobtotems;
/**
* Created by CorwinJV on 1/31/2016.
*/
public class KeyBindings {
public static final int ACTIVATE_BAUBLE_KEY = 0;
public static final KeyBinding[] keys = new KeyBinding[1];
public static boolean ACTIVATE_BAUBLE_KEY_PRESSED = false;
public KeyBindings() {
keys[ACTIVATE_BAUBLE_KEY] = new KeyBinding("key.mobtotems.activateBaubleDescription", Keyboard.KEY_H, "key.mobtotems.category");
ClientRegistry.registerKeyBinding(keys[ACTIVATE_BAUBLE_KEY]);
}
@SubscribeEvent
@SideOnly(Side.CLIENT)
public void onKeyInput(InputEvent.KeyInputEvent event) {
if (!FMLClientHandler.instance().isGUIOpen(GuiChat.class)) {
if (keys[ACTIVATE_BAUBLE_KEY].isKeyDown() && !ACTIVATE_BAUBLE_KEY_PRESSED) { | // Path: src/main/java/com/corwinjv/mobtotems/network/ActivateBaubleMessage.java
// public class ActivateBaubleMessage extends Message<ActivateBaubleMessage> {
// @Override
// protected void handleServer(ActivateBaubleMessage message, EntityPlayerMP player) {
// final IBaublesItemHandler baublesItemHandler = BaublesApi.getBaublesHandler(player);
//
// if (baublesItemHandler == null) {
// return;
// }
//
// for (int i = 0; i < baublesItemHandler.getSlots(); i++) {
// final ItemStack baubleStack = baublesItemHandler.getStackInSlot(i);
// if (baubleStack != ItemStack.EMPTY
// && baubleStack.getItem() instanceof BaubleItem) {
// ((BaubleItem) baubleStack.getItem()).onBaubleActivated(baubleStack, player);
// }
// }
// }
// }
//
// Path: src/main/java/com/corwinjv/mobtotems/network/Network.java
// public class Network {
// private static SimpleNetworkWrapper instance = null;
// private static int DISCRIMINATOR_ID = 0;
//
// public static void init() {
// instance = NetworkRegistry.INSTANCE.newSimpleChannel(Reference.MOD_ID);
//
// instance.registerMessage(ActivateBaubleMessage.class, ActivateBaubleMessage.class, getDiscriminatorId(), Side.SERVER);
// instance.registerMessage(ActivateKnifeMessage.class, ActivateKnifeMessage.class, getDiscriminatorId(), Side.SERVER);
// instance.registerMessage(SetKnifeMetaMessage.class, SetKnifeMetaMessage.class, getDiscriminatorId(), Side.SERVER);
//
// instance.registerMessage(OpenKnifeGuiMessage.class, OpenKnifeGuiMessage.class, getDiscriminatorId(), Side.CLIENT);
// }
//
// private static int getDiscriminatorId() {
// return DISCRIMINATOR_ID++;
// }
//
// public static void sendToServer(Message message) {
// instance.sendToServer(message);
// }
//
// public static void sendToAll(Message message) {
// instance.sendToAll(message);
// }
//
// public static void sendTo(Message message, EntityPlayerMP player) {
// instance.sendTo(message, player);
// }
// }
// Path: src/main/java/com/corwinjv/mobtotems/KeyBindings.java
import com.corwinjv.mobtotems.network.ActivateBaubleMessage;
import com.corwinjv.mobtotems.network.Network;
import net.minecraft.client.gui.GuiChat;
import net.minecraft.client.settings.KeyBinding;
import net.minecraftforge.fml.client.FMLClientHandler;
import net.minecraftforge.fml.client.registry.ClientRegistry;
import net.minecraftforge.fml.common.eventhandler.SubscribeEvent;
import net.minecraftforge.fml.common.gameevent.InputEvent;
import net.minecraftforge.fml.relauncher.Side;
import net.minecraftforge.fml.relauncher.SideOnly;
import org.lwjgl.input.Keyboard;
package com.corwinjv.mobtotems;
/**
* Created by CorwinJV on 1/31/2016.
*/
public class KeyBindings {
public static final int ACTIVATE_BAUBLE_KEY = 0;
public static final KeyBinding[] keys = new KeyBinding[1];
public static boolean ACTIVATE_BAUBLE_KEY_PRESSED = false;
public KeyBindings() {
keys[ACTIVATE_BAUBLE_KEY] = new KeyBinding("key.mobtotems.activateBaubleDescription", Keyboard.KEY_H, "key.mobtotems.category");
ClientRegistry.registerKeyBinding(keys[ACTIVATE_BAUBLE_KEY]);
}
@SubscribeEvent
@SideOnly(Side.CLIENT)
public void onKeyInput(InputEvent.KeyInputEvent event) {
if (!FMLClientHandler.instance().isGUIOpen(GuiChat.class)) {
if (keys[ACTIVATE_BAUBLE_KEY].isKeyDown() && !ACTIVATE_BAUBLE_KEY_PRESSED) { | Network.sendToServer(new ActivateBaubleMessage()); |
CorwinJV/MobTotems | src/main/java/com/corwinjv/mobtotems/KeyBindings.java | // Path: src/main/java/com/corwinjv/mobtotems/network/ActivateBaubleMessage.java
// public class ActivateBaubleMessage extends Message<ActivateBaubleMessage> {
// @Override
// protected void handleServer(ActivateBaubleMessage message, EntityPlayerMP player) {
// final IBaublesItemHandler baublesItemHandler = BaublesApi.getBaublesHandler(player);
//
// if (baublesItemHandler == null) {
// return;
// }
//
// for (int i = 0; i < baublesItemHandler.getSlots(); i++) {
// final ItemStack baubleStack = baublesItemHandler.getStackInSlot(i);
// if (baubleStack != ItemStack.EMPTY
// && baubleStack.getItem() instanceof BaubleItem) {
// ((BaubleItem) baubleStack.getItem()).onBaubleActivated(baubleStack, player);
// }
// }
// }
// }
//
// Path: src/main/java/com/corwinjv/mobtotems/network/Network.java
// public class Network {
// private static SimpleNetworkWrapper instance = null;
// private static int DISCRIMINATOR_ID = 0;
//
// public static void init() {
// instance = NetworkRegistry.INSTANCE.newSimpleChannel(Reference.MOD_ID);
//
// instance.registerMessage(ActivateBaubleMessage.class, ActivateBaubleMessage.class, getDiscriminatorId(), Side.SERVER);
// instance.registerMessage(ActivateKnifeMessage.class, ActivateKnifeMessage.class, getDiscriminatorId(), Side.SERVER);
// instance.registerMessage(SetKnifeMetaMessage.class, SetKnifeMetaMessage.class, getDiscriminatorId(), Side.SERVER);
//
// instance.registerMessage(OpenKnifeGuiMessage.class, OpenKnifeGuiMessage.class, getDiscriminatorId(), Side.CLIENT);
// }
//
// private static int getDiscriminatorId() {
// return DISCRIMINATOR_ID++;
// }
//
// public static void sendToServer(Message message) {
// instance.sendToServer(message);
// }
//
// public static void sendToAll(Message message) {
// instance.sendToAll(message);
// }
//
// public static void sendTo(Message message, EntityPlayerMP player) {
// instance.sendTo(message, player);
// }
// }
| import com.corwinjv.mobtotems.network.ActivateBaubleMessage;
import com.corwinjv.mobtotems.network.Network;
import net.minecraft.client.gui.GuiChat;
import net.minecraft.client.settings.KeyBinding;
import net.minecraftforge.fml.client.FMLClientHandler;
import net.minecraftforge.fml.client.registry.ClientRegistry;
import net.minecraftforge.fml.common.eventhandler.SubscribeEvent;
import net.minecraftforge.fml.common.gameevent.InputEvent;
import net.minecraftforge.fml.relauncher.Side;
import net.minecraftforge.fml.relauncher.SideOnly;
import org.lwjgl.input.Keyboard; | package com.corwinjv.mobtotems;
/**
* Created by CorwinJV on 1/31/2016.
*/
public class KeyBindings {
public static final int ACTIVATE_BAUBLE_KEY = 0;
public static final KeyBinding[] keys = new KeyBinding[1];
public static boolean ACTIVATE_BAUBLE_KEY_PRESSED = false;
public KeyBindings() {
keys[ACTIVATE_BAUBLE_KEY] = new KeyBinding("key.mobtotems.activateBaubleDescription", Keyboard.KEY_H, "key.mobtotems.category");
ClientRegistry.registerKeyBinding(keys[ACTIVATE_BAUBLE_KEY]);
}
@SubscribeEvent
@SideOnly(Side.CLIENT)
public void onKeyInput(InputEvent.KeyInputEvent event) {
if (!FMLClientHandler.instance().isGUIOpen(GuiChat.class)) {
if (keys[ACTIVATE_BAUBLE_KEY].isKeyDown() && !ACTIVATE_BAUBLE_KEY_PRESSED) { | // Path: src/main/java/com/corwinjv/mobtotems/network/ActivateBaubleMessage.java
// public class ActivateBaubleMessage extends Message<ActivateBaubleMessage> {
// @Override
// protected void handleServer(ActivateBaubleMessage message, EntityPlayerMP player) {
// final IBaublesItemHandler baublesItemHandler = BaublesApi.getBaublesHandler(player);
//
// if (baublesItemHandler == null) {
// return;
// }
//
// for (int i = 0; i < baublesItemHandler.getSlots(); i++) {
// final ItemStack baubleStack = baublesItemHandler.getStackInSlot(i);
// if (baubleStack != ItemStack.EMPTY
// && baubleStack.getItem() instanceof BaubleItem) {
// ((BaubleItem) baubleStack.getItem()).onBaubleActivated(baubleStack, player);
// }
// }
// }
// }
//
// Path: src/main/java/com/corwinjv/mobtotems/network/Network.java
// public class Network {
// private static SimpleNetworkWrapper instance = null;
// private static int DISCRIMINATOR_ID = 0;
//
// public static void init() {
// instance = NetworkRegistry.INSTANCE.newSimpleChannel(Reference.MOD_ID);
//
// instance.registerMessage(ActivateBaubleMessage.class, ActivateBaubleMessage.class, getDiscriminatorId(), Side.SERVER);
// instance.registerMessage(ActivateKnifeMessage.class, ActivateKnifeMessage.class, getDiscriminatorId(), Side.SERVER);
// instance.registerMessage(SetKnifeMetaMessage.class, SetKnifeMetaMessage.class, getDiscriminatorId(), Side.SERVER);
//
// instance.registerMessage(OpenKnifeGuiMessage.class, OpenKnifeGuiMessage.class, getDiscriminatorId(), Side.CLIENT);
// }
//
// private static int getDiscriminatorId() {
// return DISCRIMINATOR_ID++;
// }
//
// public static void sendToServer(Message message) {
// instance.sendToServer(message);
// }
//
// public static void sendToAll(Message message) {
// instance.sendToAll(message);
// }
//
// public static void sendTo(Message message, EntityPlayerMP player) {
// instance.sendTo(message, player);
// }
// }
// Path: src/main/java/com/corwinjv/mobtotems/KeyBindings.java
import com.corwinjv.mobtotems.network.ActivateBaubleMessage;
import com.corwinjv.mobtotems.network.Network;
import net.minecraft.client.gui.GuiChat;
import net.minecraft.client.settings.KeyBinding;
import net.minecraftforge.fml.client.FMLClientHandler;
import net.minecraftforge.fml.client.registry.ClientRegistry;
import net.minecraftforge.fml.common.eventhandler.SubscribeEvent;
import net.minecraftforge.fml.common.gameevent.InputEvent;
import net.minecraftforge.fml.relauncher.Side;
import net.minecraftforge.fml.relauncher.SideOnly;
import org.lwjgl.input.Keyboard;
package com.corwinjv.mobtotems;
/**
* Created by CorwinJV on 1/31/2016.
*/
public class KeyBindings {
public static final int ACTIVATE_BAUBLE_KEY = 0;
public static final KeyBinding[] keys = new KeyBinding[1];
public static boolean ACTIVATE_BAUBLE_KEY_PRESSED = false;
public KeyBindings() {
keys[ACTIVATE_BAUBLE_KEY] = new KeyBinding("key.mobtotems.activateBaubleDescription", Keyboard.KEY_H, "key.mobtotems.category");
ClientRegistry.registerKeyBinding(keys[ACTIVATE_BAUBLE_KEY]);
}
@SubscribeEvent
@SideOnly(Side.CLIENT)
public void onKeyInput(InputEvent.KeyInputEvent event) {
if (!FMLClientHandler.instance().isGUIOpen(GuiChat.class)) {
if (keys[ACTIVATE_BAUBLE_KEY].isKeyDown() && !ACTIVATE_BAUBLE_KEY_PRESSED) { | Network.sendToServer(new ActivateBaubleMessage()); |
CorwinJV/MobTotems | src/main/java/com/corwinjv/mobtotems/creativetab/CreativeTabMT.java | // Path: src/main/java/com/corwinjv/mobtotems/Reference.java
// public class Reference {
// public static final String MOD_ID = "mobtotems";
// public static final String MOD_NAME = "Mob Totems";
// public static final String MOD_VERSION = "1.12.1-0.3.0";
// public static final String RESOURCE_PREFIX = MOD_ID + ":";
//
// public static final String GUI_FACTORY_CLASS = "com.corwinjv.mobtotems.gui.GuiFactoryMT";
// public static final String CLIENT_SIDE_PROXY_CLASS = "com.corwinjv.mobtotems.proxy.ClientProxy";
// public static final String SERVER_SIDE_PROXY_CLASS = "com.corwinjv.mobtotems.proxy.CommonProxy";
//
// public static final int CHARGE_COLOR = 0xFF00FF00;
//
// public enum GUI_ID {
// OFFERING_BOX
// }
//
// ;
//
// public static void PrintEntityList() {
// Iterator entityNameItr = EntityList.getEntityNameList().iterator();
// FMLLog.log(Reference.MOD_NAME, Level.INFO, "-Printing Registered Entity Classes-");
// while (entityNameItr.hasNext()) {
// String key = (String) entityNameItr.next();
// FMLLog.log(Reference.MOD_NAME, Level.INFO, String.format(" %s", key));
// }
// }
// }
//
// Path: src/main/java/com/corwinjv/mobtotems/items/ModItems.java
// @Mod.EventBusSubscriber(modid = Reference.MOD_ID)
// public class ModItems {
// public static final Map<String, Item> ITEMS = new HashMap<String, Item>();
//
// public static final String WOLF_TOTEM_BAUBLE_NAME = "wolf_totem_bauble";
// public static final String TOTEMIC_FOCUS_NAME = "totemic_focus";
// public static final String CARVING_KNIFE_NAME = "carving_knife";
//
// // We're going to use the TotemicFocus for the CreativeTab:
// public static final Item TOTEMIC_FOCUS = new TotemicFocus().setUnlocalizedName(TOTEMIC_FOCUS_NAME).setRegistryName(Reference.MOD_ID, TOTEMIC_FOCUS_NAME);
// public static final Item WOLF_TOTEM_BAUBLE = new WolfTotemBauble().setUnlocalizedName(WOLF_TOTEM_BAUBLE_NAME).setRegistryName(Reference.MOD_ID, WOLF_TOTEM_BAUBLE_NAME);
// ;
// public static final Item CARVING_KNIFE = new CarvingKnife().setUnlocalizedName(CARVING_KNIFE_NAME).setRegistryName(Reference.MOD_ID, CARVING_KNIFE_NAME);
// ;
//
// public static void init() {
// }
//
// @SubscribeEvent
// public static void registerItems(RegistryEvent.Register<Item> e) {
// final IForgeRegistry<Item> registry = e.getRegistry();
// final Item[] items = {
// TOTEMIC_FOCUS,
// WOLF_TOTEM_BAUBLE,
// CARVING_KNIFE
// };
//
// for (Item item : items) {
// registry.register(item);
// }
//
// ITEMS.put(TOTEMIC_FOCUS_NAME, TOTEMIC_FOCUS);
// ITEMS.put(WOLF_TOTEM_BAUBLE_NAME, WOLF_TOTEM_BAUBLE);
// ITEMS.put(CARVING_KNIFE_NAME, CARVING_KNIFE);
// }
//
// public static void registerRenders() {
// for (String key : ITEMS.keySet()) {
// Item item = ITEMS.get(key);
// if (item != null) {
// registerRender(item, 0, key);
// }
// }
// }
//
// private static void registerRender(Item item, int meta, String key) {
// Minecraft.getMinecraft().getRenderItem().getItemModelMesher().register(item,
// meta,
// new ModelResourceLocation(Reference.RESOURCE_PREFIX + key, "inventory"));
// }
// }
| import com.corwinjv.mobtotems.Reference;
import com.corwinjv.mobtotems.items.ModItems;
import net.minecraft.creativetab.CreativeTabs;
import net.minecraft.item.ItemStack; | package com.corwinjv.mobtotems.creativetab;
/**
* Created by CorwinJV on 9/1/14.
*/
public class CreativeTabMT {
public static final CreativeTabs MT_TAB = new CreativeTabs(Reference.MOD_ID) {
@Override
public ItemStack getTabIconItem() { | // Path: src/main/java/com/corwinjv/mobtotems/Reference.java
// public class Reference {
// public static final String MOD_ID = "mobtotems";
// public static final String MOD_NAME = "Mob Totems";
// public static final String MOD_VERSION = "1.12.1-0.3.0";
// public static final String RESOURCE_PREFIX = MOD_ID + ":";
//
// public static final String GUI_FACTORY_CLASS = "com.corwinjv.mobtotems.gui.GuiFactoryMT";
// public static final String CLIENT_SIDE_PROXY_CLASS = "com.corwinjv.mobtotems.proxy.ClientProxy";
// public static final String SERVER_SIDE_PROXY_CLASS = "com.corwinjv.mobtotems.proxy.CommonProxy";
//
// public static final int CHARGE_COLOR = 0xFF00FF00;
//
// public enum GUI_ID {
// OFFERING_BOX
// }
//
// ;
//
// public static void PrintEntityList() {
// Iterator entityNameItr = EntityList.getEntityNameList().iterator();
// FMLLog.log(Reference.MOD_NAME, Level.INFO, "-Printing Registered Entity Classes-");
// while (entityNameItr.hasNext()) {
// String key = (String) entityNameItr.next();
// FMLLog.log(Reference.MOD_NAME, Level.INFO, String.format(" %s", key));
// }
// }
// }
//
// Path: src/main/java/com/corwinjv/mobtotems/items/ModItems.java
// @Mod.EventBusSubscriber(modid = Reference.MOD_ID)
// public class ModItems {
// public static final Map<String, Item> ITEMS = new HashMap<String, Item>();
//
// public static final String WOLF_TOTEM_BAUBLE_NAME = "wolf_totem_bauble";
// public static final String TOTEMIC_FOCUS_NAME = "totemic_focus";
// public static final String CARVING_KNIFE_NAME = "carving_knife";
//
// // We're going to use the TotemicFocus for the CreativeTab:
// public static final Item TOTEMIC_FOCUS = new TotemicFocus().setUnlocalizedName(TOTEMIC_FOCUS_NAME).setRegistryName(Reference.MOD_ID, TOTEMIC_FOCUS_NAME);
// public static final Item WOLF_TOTEM_BAUBLE = new WolfTotemBauble().setUnlocalizedName(WOLF_TOTEM_BAUBLE_NAME).setRegistryName(Reference.MOD_ID, WOLF_TOTEM_BAUBLE_NAME);
// ;
// public static final Item CARVING_KNIFE = new CarvingKnife().setUnlocalizedName(CARVING_KNIFE_NAME).setRegistryName(Reference.MOD_ID, CARVING_KNIFE_NAME);
// ;
//
// public static void init() {
// }
//
// @SubscribeEvent
// public static void registerItems(RegistryEvent.Register<Item> e) {
// final IForgeRegistry<Item> registry = e.getRegistry();
// final Item[] items = {
// TOTEMIC_FOCUS,
// WOLF_TOTEM_BAUBLE,
// CARVING_KNIFE
// };
//
// for (Item item : items) {
// registry.register(item);
// }
//
// ITEMS.put(TOTEMIC_FOCUS_NAME, TOTEMIC_FOCUS);
// ITEMS.put(WOLF_TOTEM_BAUBLE_NAME, WOLF_TOTEM_BAUBLE);
// ITEMS.put(CARVING_KNIFE_NAME, CARVING_KNIFE);
// }
//
// public static void registerRenders() {
// for (String key : ITEMS.keySet()) {
// Item item = ITEMS.get(key);
// if (item != null) {
// registerRender(item, 0, key);
// }
// }
// }
//
// private static void registerRender(Item item, int meta, String key) {
// Minecraft.getMinecraft().getRenderItem().getItemModelMesher().register(item,
// meta,
// new ModelResourceLocation(Reference.RESOURCE_PREFIX + key, "inventory"));
// }
// }
// Path: src/main/java/com/corwinjv/mobtotems/creativetab/CreativeTabMT.java
import com.corwinjv.mobtotems.Reference;
import com.corwinjv.mobtotems.items.ModItems;
import net.minecraft.creativetab.CreativeTabs;
import net.minecraft.item.ItemStack;
package com.corwinjv.mobtotems.creativetab;
/**
* Created by CorwinJV on 9/1/14.
*/
public class CreativeTabMT {
public static final CreativeTabs MT_TAB = new CreativeTabs(Reference.MOD_ID) {
@Override
public ItemStack getTabIconItem() { | return new ItemStack(ModItems.TOTEMIC_FOCUS); |
CorwinJV/MobTotems | src/main/java/com/corwinjv/mobtotems/entities/ModEntities.java | // Path: src/main/java/com/corwinjv/mobtotems/Reference.java
// public class Reference {
// public static final String MOD_ID = "mobtotems";
// public static final String MOD_NAME = "Mob Totems";
// public static final String MOD_VERSION = "1.12.1-0.3.0";
// public static final String RESOURCE_PREFIX = MOD_ID + ":";
//
// public static final String GUI_FACTORY_CLASS = "com.corwinjv.mobtotems.gui.GuiFactoryMT";
// public static final String CLIENT_SIDE_PROXY_CLASS = "com.corwinjv.mobtotems.proxy.ClientProxy";
// public static final String SERVER_SIDE_PROXY_CLASS = "com.corwinjv.mobtotems.proxy.CommonProxy";
//
// public static final int CHARGE_COLOR = 0xFF00FF00;
//
// public enum GUI_ID {
// OFFERING_BOX
// }
//
// ;
//
// public static void PrintEntityList() {
// Iterator entityNameItr = EntityList.getEntityNameList().iterator();
// FMLLog.log(Reference.MOD_NAME, Level.INFO, "-Printing Registered Entity Classes-");
// while (entityNameItr.hasNext()) {
// String key = (String) entityNameItr.next();
// FMLLog.log(Reference.MOD_NAME, Level.INFO, String.format(" %s", key));
// }
// }
// }
//
// Path: src/main/java/com/corwinjv/mobtotems/entities/render/SpiritWolfRenderFactory.java
// public class SpiritWolfRenderFactory implements IRenderFactory<EntitySpiritWolf> {
// @Override
// public Render<? super EntitySpiritWolf> createRenderFor(RenderManager manager) {
// return new SpiritWolfRender(manager, new ModelWolf(), 0.5F);
// }
// }
| import com.corwinjv.mobtotems.Reference;
import com.corwinjv.mobtotems.entities.render.SpiritWolfRenderFactory;
import net.minecraft.entity.Entity;
import net.minecraft.util.ResourceLocation;
import net.minecraftforge.fml.client.registry.RenderingRegistry;
import net.minecraftforge.fml.common.registry.EntityRegistry;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map; | package com.corwinjv.mobtotems.entities;
/**
* Created by CorwinJV on 2/15/2016.
*/
public class ModEntities {
private static int ENTITY_ID = 0;
public static final String SPIRIT_WOLF = "spirit_wolf";
private static Map<String, Class<? extends Entity>> mEntities = Collections.emptyMap();
public static void init() {
mEntities = new HashMap<String, Class<? extends Entity>>();
mEntities.put(SPIRIT_WOLF, EntitySpiritWolf.class);
}
public static void registerEntities(Object modObject) {
for (String key : mEntities.keySet()) {
Class<? extends Entity> entityClass = mEntities.get(key);
if (entityClass != null) { | // Path: src/main/java/com/corwinjv/mobtotems/Reference.java
// public class Reference {
// public static final String MOD_ID = "mobtotems";
// public static final String MOD_NAME = "Mob Totems";
// public static final String MOD_VERSION = "1.12.1-0.3.0";
// public static final String RESOURCE_PREFIX = MOD_ID + ":";
//
// public static final String GUI_FACTORY_CLASS = "com.corwinjv.mobtotems.gui.GuiFactoryMT";
// public static final String CLIENT_SIDE_PROXY_CLASS = "com.corwinjv.mobtotems.proxy.ClientProxy";
// public static final String SERVER_SIDE_PROXY_CLASS = "com.corwinjv.mobtotems.proxy.CommonProxy";
//
// public static final int CHARGE_COLOR = 0xFF00FF00;
//
// public enum GUI_ID {
// OFFERING_BOX
// }
//
// ;
//
// public static void PrintEntityList() {
// Iterator entityNameItr = EntityList.getEntityNameList().iterator();
// FMLLog.log(Reference.MOD_NAME, Level.INFO, "-Printing Registered Entity Classes-");
// while (entityNameItr.hasNext()) {
// String key = (String) entityNameItr.next();
// FMLLog.log(Reference.MOD_NAME, Level.INFO, String.format(" %s", key));
// }
// }
// }
//
// Path: src/main/java/com/corwinjv/mobtotems/entities/render/SpiritWolfRenderFactory.java
// public class SpiritWolfRenderFactory implements IRenderFactory<EntitySpiritWolf> {
// @Override
// public Render<? super EntitySpiritWolf> createRenderFor(RenderManager manager) {
// return new SpiritWolfRender(manager, new ModelWolf(), 0.5F);
// }
// }
// Path: src/main/java/com/corwinjv/mobtotems/entities/ModEntities.java
import com.corwinjv.mobtotems.Reference;
import com.corwinjv.mobtotems.entities.render.SpiritWolfRenderFactory;
import net.minecraft.entity.Entity;
import net.minecraft.util.ResourceLocation;
import net.minecraftforge.fml.client.registry.RenderingRegistry;
import net.minecraftforge.fml.common.registry.EntityRegistry;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
package com.corwinjv.mobtotems.entities;
/**
* Created by CorwinJV on 2/15/2016.
*/
public class ModEntities {
private static int ENTITY_ID = 0;
public static final String SPIRIT_WOLF = "spirit_wolf";
private static Map<String, Class<? extends Entity>> mEntities = Collections.emptyMap();
public static void init() {
mEntities = new HashMap<String, Class<? extends Entity>>();
mEntities.put(SPIRIT_WOLF, EntitySpiritWolf.class);
}
public static void registerEntities(Object modObject) {
for (String key : mEntities.keySet()) {
Class<? extends Entity> entityClass = mEntities.get(key);
if (entityClass != null) { | EntityRegistry.registerModEntity(new ResourceLocation(Reference.RESOURCE_PREFIX + key), entityClass, Reference.RESOURCE_PREFIX + key, ENTITY_ID++, modObject, 80, 3, false); |
CorwinJV/MobTotems | src/main/java/com/corwinjv/mobtotems/entities/ModEntities.java | // Path: src/main/java/com/corwinjv/mobtotems/Reference.java
// public class Reference {
// public static final String MOD_ID = "mobtotems";
// public static final String MOD_NAME = "Mob Totems";
// public static final String MOD_VERSION = "1.12.1-0.3.0";
// public static final String RESOURCE_PREFIX = MOD_ID + ":";
//
// public static final String GUI_FACTORY_CLASS = "com.corwinjv.mobtotems.gui.GuiFactoryMT";
// public static final String CLIENT_SIDE_PROXY_CLASS = "com.corwinjv.mobtotems.proxy.ClientProxy";
// public static final String SERVER_SIDE_PROXY_CLASS = "com.corwinjv.mobtotems.proxy.CommonProxy";
//
// public static final int CHARGE_COLOR = 0xFF00FF00;
//
// public enum GUI_ID {
// OFFERING_BOX
// }
//
// ;
//
// public static void PrintEntityList() {
// Iterator entityNameItr = EntityList.getEntityNameList().iterator();
// FMLLog.log(Reference.MOD_NAME, Level.INFO, "-Printing Registered Entity Classes-");
// while (entityNameItr.hasNext()) {
// String key = (String) entityNameItr.next();
// FMLLog.log(Reference.MOD_NAME, Level.INFO, String.format(" %s", key));
// }
// }
// }
//
// Path: src/main/java/com/corwinjv/mobtotems/entities/render/SpiritWolfRenderFactory.java
// public class SpiritWolfRenderFactory implements IRenderFactory<EntitySpiritWolf> {
// @Override
// public Render<? super EntitySpiritWolf> createRenderFor(RenderManager manager) {
// return new SpiritWolfRender(manager, new ModelWolf(), 0.5F);
// }
// }
| import com.corwinjv.mobtotems.Reference;
import com.corwinjv.mobtotems.entities.render.SpiritWolfRenderFactory;
import net.minecraft.entity.Entity;
import net.minecraft.util.ResourceLocation;
import net.minecraftforge.fml.client.registry.RenderingRegistry;
import net.minecraftforge.fml.common.registry.EntityRegistry;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map; | package com.corwinjv.mobtotems.entities;
/**
* Created by CorwinJV on 2/15/2016.
*/
public class ModEntities {
private static int ENTITY_ID = 0;
public static final String SPIRIT_WOLF = "spirit_wolf";
private static Map<String, Class<? extends Entity>> mEntities = Collections.emptyMap();
public static void init() {
mEntities = new HashMap<String, Class<? extends Entity>>();
mEntities.put(SPIRIT_WOLF, EntitySpiritWolf.class);
}
public static void registerEntities(Object modObject) {
for (String key : mEntities.keySet()) {
Class<? extends Entity> entityClass = mEntities.get(key);
if (entityClass != null) {
EntityRegistry.registerModEntity(new ResourceLocation(Reference.RESOURCE_PREFIX + key), entityClass, Reference.RESOURCE_PREFIX + key, ENTITY_ID++, modObject, 80, 3, false);
EntityRegistry.registerEgg(new ResourceLocation(Reference.RESOURCE_PREFIX + key), 1, 2);
}
}
}
public static void registerEntityRenders() { | // Path: src/main/java/com/corwinjv/mobtotems/Reference.java
// public class Reference {
// public static final String MOD_ID = "mobtotems";
// public static final String MOD_NAME = "Mob Totems";
// public static final String MOD_VERSION = "1.12.1-0.3.0";
// public static final String RESOURCE_PREFIX = MOD_ID + ":";
//
// public static final String GUI_FACTORY_CLASS = "com.corwinjv.mobtotems.gui.GuiFactoryMT";
// public static final String CLIENT_SIDE_PROXY_CLASS = "com.corwinjv.mobtotems.proxy.ClientProxy";
// public static final String SERVER_SIDE_PROXY_CLASS = "com.corwinjv.mobtotems.proxy.CommonProxy";
//
// public static final int CHARGE_COLOR = 0xFF00FF00;
//
// public enum GUI_ID {
// OFFERING_BOX
// }
//
// ;
//
// public static void PrintEntityList() {
// Iterator entityNameItr = EntityList.getEntityNameList().iterator();
// FMLLog.log(Reference.MOD_NAME, Level.INFO, "-Printing Registered Entity Classes-");
// while (entityNameItr.hasNext()) {
// String key = (String) entityNameItr.next();
// FMLLog.log(Reference.MOD_NAME, Level.INFO, String.format(" %s", key));
// }
// }
// }
//
// Path: src/main/java/com/corwinjv/mobtotems/entities/render/SpiritWolfRenderFactory.java
// public class SpiritWolfRenderFactory implements IRenderFactory<EntitySpiritWolf> {
// @Override
// public Render<? super EntitySpiritWolf> createRenderFor(RenderManager manager) {
// return new SpiritWolfRender(manager, new ModelWolf(), 0.5F);
// }
// }
// Path: src/main/java/com/corwinjv/mobtotems/entities/ModEntities.java
import com.corwinjv.mobtotems.Reference;
import com.corwinjv.mobtotems.entities.render.SpiritWolfRenderFactory;
import net.minecraft.entity.Entity;
import net.minecraft.util.ResourceLocation;
import net.minecraftforge.fml.client.registry.RenderingRegistry;
import net.minecraftforge.fml.common.registry.EntityRegistry;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
package com.corwinjv.mobtotems.entities;
/**
* Created by CorwinJV on 2/15/2016.
*/
public class ModEntities {
private static int ENTITY_ID = 0;
public static final String SPIRIT_WOLF = "spirit_wolf";
private static Map<String, Class<? extends Entity>> mEntities = Collections.emptyMap();
public static void init() {
mEntities = new HashMap<String, Class<? extends Entity>>();
mEntities.put(SPIRIT_WOLF, EntitySpiritWolf.class);
}
public static void registerEntities(Object modObject) {
for (String key : mEntities.keySet()) {
Class<? extends Entity> entityClass = mEntities.get(key);
if (entityClass != null) {
EntityRegistry.registerModEntity(new ResourceLocation(Reference.RESOURCE_PREFIX + key), entityClass, Reference.RESOURCE_PREFIX + key, ENTITY_ID++, modObject, 80, 3, false);
EntityRegistry.registerEgg(new ResourceLocation(Reference.RESOURCE_PREFIX + key), 1, 2);
}
}
}
public static void registerEntityRenders() { | RenderingRegistry.registerEntityRenderingHandler(EntitySpiritWolf.class, new SpiritWolfRenderFactory()); |
CorwinJV/MobTotems | src/main/java/com/corwinjv/mobtotems/blocks/tiles/TotemLogic/SpiderLogic.java | // Path: src/main/java/com/corwinjv/mobtotems/TotemHelper.java
// public static final int DEFAULT_RADIUS = 32;
//
// Path: src/main/java/com/corwinjv/mobtotems/TotemHelper.java
// public static final int RANGE_BOOST = 16;
| import net.minecraft.entity.EntityLivingBase;
import net.minecraft.entity.monster.IMob;
import net.minecraft.init.Items;
import net.minecraft.init.MobEffects;
import net.minecraft.item.ItemStack;
import net.minecraft.potion.PotionEffect;
import net.minecraft.util.DamageSource;
import net.minecraft.util.math.AxisAlignedBB;
import net.minecraft.util.math.BlockPos;
import net.minecraft.world.World;
import javax.annotation.Nonnull;
import java.util.ArrayList;
import java.util.List;
import static com.corwinjv.mobtotems.TotemHelper.DEFAULT_RADIUS;
import static com.corwinjv.mobtotems.TotemHelper.RANGE_BOOST; | package com.corwinjv.mobtotems.blocks.tiles.TotemLogic;
/**
* Created by CorwinJV on 1/25/2017.
*/
public class SpiderLogic extends TotemLogic {
public static final int POISON_DURATION = 300;
public static final int POTION_AMPLIFIER = 1;
@Override
public List<ItemStack> getCost() {
List<ItemStack> cost = new ArrayList<>();
cost.add(new ItemStack(Items.STRING, 2));
return cost;
}
@Nonnull
@Override
public EffectType getEffectType() {
return EffectType.EFFECT;
}
@Override
public void performEffect(World world, BlockPos pos, Modifiers modifiers) { | // Path: src/main/java/com/corwinjv/mobtotems/TotemHelper.java
// public static final int DEFAULT_RADIUS = 32;
//
// Path: src/main/java/com/corwinjv/mobtotems/TotemHelper.java
// public static final int RANGE_BOOST = 16;
// Path: src/main/java/com/corwinjv/mobtotems/blocks/tiles/TotemLogic/SpiderLogic.java
import net.minecraft.entity.EntityLivingBase;
import net.minecraft.entity.monster.IMob;
import net.minecraft.init.Items;
import net.minecraft.init.MobEffects;
import net.minecraft.item.ItemStack;
import net.minecraft.potion.PotionEffect;
import net.minecraft.util.DamageSource;
import net.minecraft.util.math.AxisAlignedBB;
import net.minecraft.util.math.BlockPos;
import net.minecraft.world.World;
import javax.annotation.Nonnull;
import java.util.ArrayList;
import java.util.List;
import static com.corwinjv.mobtotems.TotemHelper.DEFAULT_RADIUS;
import static com.corwinjv.mobtotems.TotemHelper.RANGE_BOOST;
package com.corwinjv.mobtotems.blocks.tiles.TotemLogic;
/**
* Created by CorwinJV on 1/25/2017.
*/
public class SpiderLogic extends TotemLogic {
public static final int POISON_DURATION = 300;
public static final int POTION_AMPLIFIER = 1;
@Override
public List<ItemStack> getCost() {
List<ItemStack> cost = new ArrayList<>();
cost.add(new ItemStack(Items.STRING, 2));
return cost;
}
@Nonnull
@Override
public EffectType getEffectType() {
return EffectType.EFFECT;
}
@Override
public void performEffect(World world, BlockPos pos, Modifiers modifiers) { | int radius = DEFAULT_RADIUS + (int) (RANGE_BOOST * modifiers.range); |
CorwinJV/MobTotems | src/main/java/com/corwinjv/mobtotems/blocks/tiles/TotemLogic/SpiderLogic.java | // Path: src/main/java/com/corwinjv/mobtotems/TotemHelper.java
// public static final int DEFAULT_RADIUS = 32;
//
// Path: src/main/java/com/corwinjv/mobtotems/TotemHelper.java
// public static final int RANGE_BOOST = 16;
| import net.minecraft.entity.EntityLivingBase;
import net.minecraft.entity.monster.IMob;
import net.minecraft.init.Items;
import net.minecraft.init.MobEffects;
import net.minecraft.item.ItemStack;
import net.minecraft.potion.PotionEffect;
import net.minecraft.util.DamageSource;
import net.minecraft.util.math.AxisAlignedBB;
import net.minecraft.util.math.BlockPos;
import net.minecraft.world.World;
import javax.annotation.Nonnull;
import java.util.ArrayList;
import java.util.List;
import static com.corwinjv.mobtotems.TotemHelper.DEFAULT_RADIUS;
import static com.corwinjv.mobtotems.TotemHelper.RANGE_BOOST; | package com.corwinjv.mobtotems.blocks.tiles.TotemLogic;
/**
* Created by CorwinJV on 1/25/2017.
*/
public class SpiderLogic extends TotemLogic {
public static final int POISON_DURATION = 300;
public static final int POTION_AMPLIFIER = 1;
@Override
public List<ItemStack> getCost() {
List<ItemStack> cost = new ArrayList<>();
cost.add(new ItemStack(Items.STRING, 2));
return cost;
}
@Nonnull
@Override
public EffectType getEffectType() {
return EffectType.EFFECT;
}
@Override
public void performEffect(World world, BlockPos pos, Modifiers modifiers) { | // Path: src/main/java/com/corwinjv/mobtotems/TotemHelper.java
// public static final int DEFAULT_RADIUS = 32;
//
// Path: src/main/java/com/corwinjv/mobtotems/TotemHelper.java
// public static final int RANGE_BOOST = 16;
// Path: src/main/java/com/corwinjv/mobtotems/blocks/tiles/TotemLogic/SpiderLogic.java
import net.minecraft.entity.EntityLivingBase;
import net.minecraft.entity.monster.IMob;
import net.minecraft.init.Items;
import net.minecraft.init.MobEffects;
import net.minecraft.item.ItemStack;
import net.minecraft.potion.PotionEffect;
import net.minecraft.util.DamageSource;
import net.minecraft.util.math.AxisAlignedBB;
import net.minecraft.util.math.BlockPos;
import net.minecraft.world.World;
import javax.annotation.Nonnull;
import java.util.ArrayList;
import java.util.List;
import static com.corwinjv.mobtotems.TotemHelper.DEFAULT_RADIUS;
import static com.corwinjv.mobtotems.TotemHelper.RANGE_BOOST;
package com.corwinjv.mobtotems.blocks.tiles.TotemLogic;
/**
* Created by CorwinJV on 1/25/2017.
*/
public class SpiderLogic extends TotemLogic {
public static final int POISON_DURATION = 300;
public static final int POTION_AMPLIFIER = 1;
@Override
public List<ItemStack> getCost() {
List<ItemStack> cost = new ArrayList<>();
cost.add(new ItemStack(Items.STRING, 2));
return cost;
}
@Nonnull
@Override
public EffectType getEffectType() {
return EffectType.EFFECT;
}
@Override
public void performEffect(World world, BlockPos pos, Modifiers modifiers) { | int radius = DEFAULT_RADIUS + (int) (RANGE_BOOST * modifiers.range); |
CorwinJV/MobTotems | src/main/java/com/corwinjv/mobtotems/blocks/items/TotemWoodItemBlock.java | // Path: src/main/java/com/corwinjv/mobtotems/blocks/TotemType.java
// public enum TotemType implements IStringSerializable {
// NONE(0, "none"),
// CREEPER(1, "creeper"),
// ENDER(2, "ender"),
// BLAZE(3, "blaze"),
// SPIDER(4, "spider"),
// COW(5, "cow"),
// WOLF(6, "wolf"),
// OCELOT(7, "ocelot"),
// WITHER(8, "wither"),
// LLAMA(9, "llama"),
// RABBIT(10, "rabbit");
//
// private final int meta;
// private final String name;
//
// private TotemType(int meta, String name) {
// this.meta = meta;
// this.name = name;
// }
//
// public int getMeta() {
// return this.meta;
// }
//
// @Override
// public String getName() {
// return this.name;
// }
//
// public static TotemType fromMeta(int meta) {
// TotemType retType = TotemType.NONE;
// for (TotemType type : values()) {
// if (type.getMeta() == meta) {
// retType = type;
// break;
// }
// }
// return retType;
// }
// }
| import com.corwinjv.mobtotems.blocks.TotemType;
import net.minecraft.block.Block;
import net.minecraft.item.ItemBlock;
import net.minecraft.item.ItemStack; | package com.corwinjv.mobtotems.blocks.items;
/**
* Created by CorwinJV on 1/18/2017.
*/
public class TotemWoodItemBlock extends ItemBlock {
public TotemWoodItemBlock(Block block) {
super(block);
this.setMaxDamage(0);
this.setHasSubtypes(true);
}
@Override
public int getMetadata(int metadata) {
return metadata;
}
// create a unique unlocalised name for each colour, so that we can give each one a unique name
@Override
public String getUnlocalizedName(ItemStack stack) { | // Path: src/main/java/com/corwinjv/mobtotems/blocks/TotemType.java
// public enum TotemType implements IStringSerializable {
// NONE(0, "none"),
// CREEPER(1, "creeper"),
// ENDER(2, "ender"),
// BLAZE(3, "blaze"),
// SPIDER(4, "spider"),
// COW(5, "cow"),
// WOLF(6, "wolf"),
// OCELOT(7, "ocelot"),
// WITHER(8, "wither"),
// LLAMA(9, "llama"),
// RABBIT(10, "rabbit");
//
// private final int meta;
// private final String name;
//
// private TotemType(int meta, String name) {
// this.meta = meta;
// this.name = name;
// }
//
// public int getMeta() {
// return this.meta;
// }
//
// @Override
// public String getName() {
// return this.name;
// }
//
// public static TotemType fromMeta(int meta) {
// TotemType retType = TotemType.NONE;
// for (TotemType type : values()) {
// if (type.getMeta() == meta) {
// retType = type;
// break;
// }
// }
// return retType;
// }
// }
// Path: src/main/java/com/corwinjv/mobtotems/blocks/items/TotemWoodItemBlock.java
import com.corwinjv.mobtotems.blocks.TotemType;
import net.minecraft.block.Block;
import net.minecraft.item.ItemBlock;
import net.minecraft.item.ItemStack;
package com.corwinjv.mobtotems.blocks.items;
/**
* Created by CorwinJV on 1/18/2017.
*/
public class TotemWoodItemBlock extends ItemBlock {
public TotemWoodItemBlock(Block block) {
super(block);
this.setMaxDamage(0);
this.setHasSubtypes(true);
}
@Override
public int getMetadata(int metadata) {
return metadata;
}
// create a unique unlocalised name for each colour, so that we can give each one a unique name
@Override
public String getUnlocalizedName(ItemStack stack) { | TotemType totemType = TotemType.fromMeta(stack.getMetadata()); |
CorwinJV/MobTotems | src/main/java/com/corwinjv/mobtotems/gui/util.java | // Path: src/main/java/com/corwinjv/mobtotems/Reference.java
// public class Reference {
// public static final String MOD_ID = "mobtotems";
// public static final String MOD_NAME = "Mob Totems";
// public static final String MOD_VERSION = "1.12.1-0.3.0";
// public static final String RESOURCE_PREFIX = MOD_ID + ":";
//
// public static final String GUI_FACTORY_CLASS = "com.corwinjv.mobtotems.gui.GuiFactoryMT";
// public static final String CLIENT_SIDE_PROXY_CLASS = "com.corwinjv.mobtotems.proxy.ClientProxy";
// public static final String SERVER_SIDE_PROXY_CLASS = "com.corwinjv.mobtotems.proxy.CommonProxy";
//
// public static final int CHARGE_COLOR = 0xFF00FF00;
//
// public enum GUI_ID {
// OFFERING_BOX
// }
//
// ;
//
// public static void PrintEntityList() {
// Iterator entityNameItr = EntityList.getEntityNameList().iterator();
// FMLLog.log(Reference.MOD_NAME, Level.INFO, "-Printing Registered Entity Classes-");
// while (entityNameItr.hasNext()) {
// String key = (String) entityNameItr.next();
// FMLLog.log(Reference.MOD_NAME, Level.INFO, String.format(" %s", key));
// }
// }
// }
//
// Path: src/main/java/com/corwinjv/mobtotems/items/baubles/BaubleItem.java
// @Optional.Interface(modid = "baubles", iface = "baubles.api.IBauble")
// public class BaubleItem extends ModItem implements IBauble, IChargeable {
// protected static final String CHARGE_LEVEL = "CHARGE_LEVEL";
//
// public BaubleItem() {
// super();
// }
//
// @Override
// public void onCreated(ItemStack stack, World worldIn, EntityPlayer playerIn) {
// initNbtData(stack);
// }
//
// protected NBTTagCompound initNbtData(ItemStack stack) {
// NBTTagCompound nbtTagCompound = stack.getTagCompound();
// if (nbtTagCompound == null) {
// nbtTagCompound = new NBTTagCompound();
// }
// nbtTagCompound.setInteger(CHARGE_LEVEL, 0);
//
// stack.setTagCompound(nbtTagCompound);
// return nbtTagCompound;
// }
//
// @SuppressWarnings("all")
// @Override
// public int getChargeLevel(ItemStack stack) {
// NBTTagCompound tagCompound = stack.getTagCompound();
// if (tagCompound == null) {
// tagCompound = initNbtData(stack);
// }
// return tagCompound.getInteger(CHARGE_LEVEL);
// }
//
// @Override
// public void setChargeLevel(ItemStack stack, int chargeLevel) {
// NBTTagCompound tagCompound = stack.getTagCompound();
// if (tagCompound == null) {
// tagCompound = initNbtData(stack);
// }
// tagCompound.setInteger(CHARGE_LEVEL, chargeLevel);
// }
//
// @Override
// public void decrementChargeLevel(ItemStack stack, int amount) {
// int chargeLevel = getChargeLevel(stack);
// chargeLevel -= amount;
// if (chargeLevel < 0) {
// chargeLevel = 0;
// }
//
// setChargeLevel(stack, chargeLevel);
// }
//
// @Override
// public void incrementChargeLevel(ItemStack stack, int amount) {
// int chargeLevel = getChargeLevel(stack);
// chargeLevel += amount;
// if (chargeLevel > getMaxChargeLevel()) {
// chargeLevel = getMaxChargeLevel();
// }
// setChargeLevel(stack, chargeLevel);
// }
//
// @Override
// public int getMaxChargeLevel() {
// return 16;
// }
//
// public void onBaubleActivated(ItemStack stack, EntityPlayer player) {
// }
//
// @Override
// @SideOnly(Side.CLIENT)
// public void addInformation(ItemStack stack, @Nullable World worldIn, List<String> tooltip, ITooltipFlag flagIn) {
// super.addInformation(stack, worldIn, tooltip, flagIn);
// }
//
// @Override
// public BaubleType getBaubleType(ItemStack itemstack) {
// return BaubleType.TRINKET;
// }
//
// @Override
// public boolean canEquip(ItemStack itemstack, EntityLivingBase player) {
// return true;
// }
//
// @Override
// public boolean canUnequip(ItemStack itemstack, EntityLivingBase player) {
// return true;
// }
//
// @Override
// public boolean willAutoSync(ItemStack itemstack, EntityLivingBase player) {
// return true;
// }
// }
| import com.corwinjv.mobtotems.Reference;
import com.corwinjv.mobtotems.items.baubles.BaubleItem;
import net.minecraft.util.ResourceLocation;
import net.minecraft.util.text.translation.I18n;
import javax.annotation.Nonnull; | package com.corwinjv.mobtotems.gui;
/**
* Created by CorwinJV on 1/19/2017.
*/
public class util {
public static ResourceLocation getGuiResourceLocation(@Nonnull BaubleItem baubleItem) { | // Path: src/main/java/com/corwinjv/mobtotems/Reference.java
// public class Reference {
// public static final String MOD_ID = "mobtotems";
// public static final String MOD_NAME = "Mob Totems";
// public static final String MOD_VERSION = "1.12.1-0.3.0";
// public static final String RESOURCE_PREFIX = MOD_ID + ":";
//
// public static final String GUI_FACTORY_CLASS = "com.corwinjv.mobtotems.gui.GuiFactoryMT";
// public static final String CLIENT_SIDE_PROXY_CLASS = "com.corwinjv.mobtotems.proxy.ClientProxy";
// public static final String SERVER_SIDE_PROXY_CLASS = "com.corwinjv.mobtotems.proxy.CommonProxy";
//
// public static final int CHARGE_COLOR = 0xFF00FF00;
//
// public enum GUI_ID {
// OFFERING_BOX
// }
//
// ;
//
// public static void PrintEntityList() {
// Iterator entityNameItr = EntityList.getEntityNameList().iterator();
// FMLLog.log(Reference.MOD_NAME, Level.INFO, "-Printing Registered Entity Classes-");
// while (entityNameItr.hasNext()) {
// String key = (String) entityNameItr.next();
// FMLLog.log(Reference.MOD_NAME, Level.INFO, String.format(" %s", key));
// }
// }
// }
//
// Path: src/main/java/com/corwinjv/mobtotems/items/baubles/BaubleItem.java
// @Optional.Interface(modid = "baubles", iface = "baubles.api.IBauble")
// public class BaubleItem extends ModItem implements IBauble, IChargeable {
// protected static final String CHARGE_LEVEL = "CHARGE_LEVEL";
//
// public BaubleItem() {
// super();
// }
//
// @Override
// public void onCreated(ItemStack stack, World worldIn, EntityPlayer playerIn) {
// initNbtData(stack);
// }
//
// protected NBTTagCompound initNbtData(ItemStack stack) {
// NBTTagCompound nbtTagCompound = stack.getTagCompound();
// if (nbtTagCompound == null) {
// nbtTagCompound = new NBTTagCompound();
// }
// nbtTagCompound.setInteger(CHARGE_LEVEL, 0);
//
// stack.setTagCompound(nbtTagCompound);
// return nbtTagCompound;
// }
//
// @SuppressWarnings("all")
// @Override
// public int getChargeLevel(ItemStack stack) {
// NBTTagCompound tagCompound = stack.getTagCompound();
// if (tagCompound == null) {
// tagCompound = initNbtData(stack);
// }
// return tagCompound.getInteger(CHARGE_LEVEL);
// }
//
// @Override
// public void setChargeLevel(ItemStack stack, int chargeLevel) {
// NBTTagCompound tagCompound = stack.getTagCompound();
// if (tagCompound == null) {
// tagCompound = initNbtData(stack);
// }
// tagCompound.setInteger(CHARGE_LEVEL, chargeLevel);
// }
//
// @Override
// public void decrementChargeLevel(ItemStack stack, int amount) {
// int chargeLevel = getChargeLevel(stack);
// chargeLevel -= amount;
// if (chargeLevel < 0) {
// chargeLevel = 0;
// }
//
// setChargeLevel(stack, chargeLevel);
// }
//
// @Override
// public void incrementChargeLevel(ItemStack stack, int amount) {
// int chargeLevel = getChargeLevel(stack);
// chargeLevel += amount;
// if (chargeLevel > getMaxChargeLevel()) {
// chargeLevel = getMaxChargeLevel();
// }
// setChargeLevel(stack, chargeLevel);
// }
//
// @Override
// public int getMaxChargeLevel() {
// return 16;
// }
//
// public void onBaubleActivated(ItemStack stack, EntityPlayer player) {
// }
//
// @Override
// @SideOnly(Side.CLIENT)
// public void addInformation(ItemStack stack, @Nullable World worldIn, List<String> tooltip, ITooltipFlag flagIn) {
// super.addInformation(stack, worldIn, tooltip, flagIn);
// }
//
// @Override
// public BaubleType getBaubleType(ItemStack itemstack) {
// return BaubleType.TRINKET;
// }
//
// @Override
// public boolean canEquip(ItemStack itemstack, EntityLivingBase player) {
// return true;
// }
//
// @Override
// public boolean canUnequip(ItemStack itemstack, EntityLivingBase player) {
// return true;
// }
//
// @Override
// public boolean willAutoSync(ItemStack itemstack, EntityLivingBase player) {
// return true;
// }
// }
// Path: src/main/java/com/corwinjv/mobtotems/gui/util.java
import com.corwinjv.mobtotems.Reference;
import com.corwinjv.mobtotems.items.baubles.BaubleItem;
import net.minecraft.util.ResourceLocation;
import net.minecraft.util.text.translation.I18n;
import javax.annotation.Nonnull;
package com.corwinjv.mobtotems.gui;
/**
* Created by CorwinJV on 1/19/2017.
*/
public class util {
public static ResourceLocation getGuiResourceLocation(@Nonnull BaubleItem baubleItem) { | String resourceName = baubleItem.getRegistryName().toString().substring(Reference.RESOURCE_PREFIX.length()); |
CorwinJV/MobTotems | src/main/java/com/corwinjv/mobtotems/blocks/tiles/base/ModMultiblockInventoryTileEntity.java | // Path: src/main/java/com/corwinjv/mobtotems/blocks/tiles/TotemTileEntity.java
// public class TotemTileEntity extends ModMultiblockTileEntity<TotemType> {
// private static final String TOTEM_TYPE = "totem_type";
// private TotemType type = TotemType.NONE;
//
// public TotemTileEntity() {
// super();
// this.setType(TotemType.NONE);
// }
//
// public TotemTileEntity(TotemType type) {
// super();
// this.setType(type);
// }
//
// @Override
// public NBTTagCompound writeToNBT(NBTTagCompound tagCompound) {
// tagCompound = super.writeToNBT(tagCompound);
// tagCompound.setInteger(TOTEM_TYPE, type.getMeta());
// return tagCompound;
// }
//
// @Override
// public void readFromNBT(NBTTagCompound tagCompound) {
// super.readFromNBT(tagCompound);
// type = TotemType.fromMeta(tagCompound.getInteger(TOTEM_TYPE));
// }
//
// @Override
// public boolean shouldRefresh(World world, BlockPos pos, @Nonnull IBlockState oldState, @Nonnull IBlockState newState) {
// if (newState.getProperties().containsKey(TotemWoodBlock.TOTEM_TYPE)) {
// return !newState.getValue(TotemWoodBlock.TOTEM_TYPE).equals(oldState.getValue(TotemWoodBlock.TOTEM_TYPE));
// }
// return (oldState.getBlock() != newState.getBlock());
// }
//
// @Override
// public boolean getIsMaster() {
// return false;
// }
//
// @Override
// public void verifyMultiblock() {
// return;
// }
//
// @Override
// public void invalidateSlaves() {
// }
//
// @Override
// public List<BlockPos> getSlaves() {
// return null;
// }
//
// @Override
// public List<TotemType> getSlaveTypes() {
// return null;
// }
//
// @Override
// public TotemType getType() {
// return type;
// }
//
// @Override
// public void setType(TotemType type) {
// this.type = type;
// markDirty();
// }
// }
//
// Path: src/main/java/com/corwinjv/mobtotems/interfaces/IMultiblock.java
// public interface IMultiblock<T> {
// String IS_MASTER = "isMaster";
// String SLAVES = "slaves";
// String MASTER_POS = "masterPos";
//
// boolean getIsMaster();
//
// void setIsMaster(boolean isMaster);
//
// void verifyMultiblock();
//
// void setSlaves(List<BlockPos> slaves);
//
// void invalidateSlaves();
//
// List<BlockPos> getSlaves();
//
// List<T> getSlaveTypes();
//
// T getType();
//
// void setType(T type);
//
// void setMaster(IMultiblock<T> master);
//
// IMultiblock<T> getMaster();
// }
| import com.corwinjv.mobtotems.blocks.tiles.TotemTileEntity;
import com.corwinjv.mobtotems.interfaces.IMultiblock;
import net.minecraft.nbt.NBTBase;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.nbt.NBTTagList;
import net.minecraft.nbt.NBTTagLong;
import net.minecraft.tileentity.TileEntity;
import net.minecraft.util.math.BlockPos;
import net.minecraftforge.common.util.Constants;
import java.util.ArrayList;
import java.util.List; | NBTTagList tagList = tagCompound.getTagList(SLAVES, Constants.NBT.TAG_LONG);
for (int i = 0; i < tagList.tagCount(); i++) {
NBTBase tag = tagList.get(i);
if (tag instanceof NBTTagLong) {
BlockPos blockPos = BlockPos.fromLong(((NBTTagLong) tag).getLong());
slaves.add(blockPos);
}
}
}
@Override
public boolean getIsMaster() {
return isMaster;
}
@Override
public void setIsMaster(boolean isMaster) {
this.isMaster = isMaster;
markDirty();
}
public void setSlaves(List<BlockPos> slaves) {
this.slaves = slaves;
markDirty();
}
public void invalidateSlaves() {
for (BlockPos slavePos : getSlaves()) {
TileEntity te = world.getTileEntity(slavePos);
if (te != null | // Path: src/main/java/com/corwinjv/mobtotems/blocks/tiles/TotemTileEntity.java
// public class TotemTileEntity extends ModMultiblockTileEntity<TotemType> {
// private static final String TOTEM_TYPE = "totem_type";
// private TotemType type = TotemType.NONE;
//
// public TotemTileEntity() {
// super();
// this.setType(TotemType.NONE);
// }
//
// public TotemTileEntity(TotemType type) {
// super();
// this.setType(type);
// }
//
// @Override
// public NBTTagCompound writeToNBT(NBTTagCompound tagCompound) {
// tagCompound = super.writeToNBT(tagCompound);
// tagCompound.setInteger(TOTEM_TYPE, type.getMeta());
// return tagCompound;
// }
//
// @Override
// public void readFromNBT(NBTTagCompound tagCompound) {
// super.readFromNBT(tagCompound);
// type = TotemType.fromMeta(tagCompound.getInteger(TOTEM_TYPE));
// }
//
// @Override
// public boolean shouldRefresh(World world, BlockPos pos, @Nonnull IBlockState oldState, @Nonnull IBlockState newState) {
// if (newState.getProperties().containsKey(TotemWoodBlock.TOTEM_TYPE)) {
// return !newState.getValue(TotemWoodBlock.TOTEM_TYPE).equals(oldState.getValue(TotemWoodBlock.TOTEM_TYPE));
// }
// return (oldState.getBlock() != newState.getBlock());
// }
//
// @Override
// public boolean getIsMaster() {
// return false;
// }
//
// @Override
// public void verifyMultiblock() {
// return;
// }
//
// @Override
// public void invalidateSlaves() {
// }
//
// @Override
// public List<BlockPos> getSlaves() {
// return null;
// }
//
// @Override
// public List<TotemType> getSlaveTypes() {
// return null;
// }
//
// @Override
// public TotemType getType() {
// return type;
// }
//
// @Override
// public void setType(TotemType type) {
// this.type = type;
// markDirty();
// }
// }
//
// Path: src/main/java/com/corwinjv/mobtotems/interfaces/IMultiblock.java
// public interface IMultiblock<T> {
// String IS_MASTER = "isMaster";
// String SLAVES = "slaves";
// String MASTER_POS = "masterPos";
//
// boolean getIsMaster();
//
// void setIsMaster(boolean isMaster);
//
// void verifyMultiblock();
//
// void setSlaves(List<BlockPos> slaves);
//
// void invalidateSlaves();
//
// List<BlockPos> getSlaves();
//
// List<T> getSlaveTypes();
//
// T getType();
//
// void setType(T type);
//
// void setMaster(IMultiblock<T> master);
//
// IMultiblock<T> getMaster();
// }
// Path: src/main/java/com/corwinjv/mobtotems/blocks/tiles/base/ModMultiblockInventoryTileEntity.java
import com.corwinjv.mobtotems.blocks.tiles.TotemTileEntity;
import com.corwinjv.mobtotems.interfaces.IMultiblock;
import net.minecraft.nbt.NBTBase;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.nbt.NBTTagList;
import net.minecraft.nbt.NBTTagLong;
import net.minecraft.tileentity.TileEntity;
import net.minecraft.util.math.BlockPos;
import net.minecraftforge.common.util.Constants;
import java.util.ArrayList;
import java.util.List;
NBTTagList tagList = tagCompound.getTagList(SLAVES, Constants.NBT.TAG_LONG);
for (int i = 0; i < tagList.tagCount(); i++) {
NBTBase tag = tagList.get(i);
if (tag instanceof NBTTagLong) {
BlockPos blockPos = BlockPos.fromLong(((NBTTagLong) tag).getLong());
slaves.add(blockPos);
}
}
}
@Override
public boolean getIsMaster() {
return isMaster;
}
@Override
public void setIsMaster(boolean isMaster) {
this.isMaster = isMaster;
markDirty();
}
public void setSlaves(List<BlockPos> slaves) {
this.slaves = slaves;
markDirty();
}
public void invalidateSlaves() {
for (BlockPos slavePos : getSlaves()) {
TileEntity te = world.getTileEntity(slavePos);
if (te != null | && te instanceof TotemTileEntity) { |
JanWiemer/jacis | src/test/java/org/jacis/persistence/microstream/microstreamframework/BasicMicrostreamTest.java | // Path: src/test/java/org/jacis/testhelper/FileUtils.java
// public abstract class FileUtils {
//
// public static boolean deleteDirectory(File directoryToBeDeleted) {
// File[] allContents = directoryToBeDeleted.listFiles();
// if (allContents != null) {
// for (File file : allContents) {
// deleteDirectory(file);
// }
// }
// return directoryToBeDeleted.delete();
// }
//
// }
| import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import org.jacis.testhelper.FileUtils;
import org.junit.AfterClass;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import one.microstream.storage.configuration.Configuration;
import one.microstream.storage.embedded.types.EmbeddedStorage;
import one.microstream.storage.embedded.types.EmbeddedStorageManager;
| /*
* Copyright (c) 2020. Jan Wiemer
*/
package org.jacis.persistence.microstream.microstreamframework;
public class BasicMicrostreamTest {
private static final Logger log = LoggerFactory.getLogger(BasicMicrostreamTest.class);
protected static Path getStorageDir(String suffix) {
Path path = suffix == null ? Paths.get("var", BasicMicrostreamTest.class.getName()) : Paths.get("var", BasicMicrostreamTest.class.getName(), suffix);
log.info("use storage path: {}", path.toString());
return path;
}
@AfterClass
public static void cleanup() {
| // Path: src/test/java/org/jacis/testhelper/FileUtils.java
// public abstract class FileUtils {
//
// public static boolean deleteDirectory(File directoryToBeDeleted) {
// File[] allContents = directoryToBeDeleted.listFiles();
// if (allContents != null) {
// for (File file : allContents) {
// deleteDirectory(file);
// }
// }
// return directoryToBeDeleted.delete();
// }
//
// }
// Path: src/test/java/org/jacis/persistence/microstream/microstreamframework/BasicMicrostreamTest.java
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import org.jacis.testhelper.FileUtils;
import org.junit.AfterClass;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import one.microstream.storage.configuration.Configuration;
import one.microstream.storage.embedded.types.EmbeddedStorage;
import one.microstream.storage.embedded.types.EmbeddedStorageManager;
/*
* Copyright (c) 2020. Jan Wiemer
*/
package org.jacis.persistence.microstream.microstreamframework;
public class BasicMicrostreamTest {
private static final Logger log = LoggerFactory.getLogger(BasicMicrostreamTest.class);
protected static Path getStorageDir(String suffix) {
Path path = suffix == null ? Paths.get("var", BasicMicrostreamTest.class.getName()) : Paths.get("var", BasicMicrostreamTest.class.getName(), suffix);
log.info("use storage path: {}", path.toString());
return path;
}
@AfterClass
public static void cleanup() {
| FileUtils.deleteDirectory(Paths.get("var", BasicMicrostreamTest.class.getName()).toFile());
|
JanWiemer/jacis | src/main/java/org/jacis/plugin/dirtycheck/object/AbstractReadOnlyModeAndDirtyCheckSupportingObject.java | // Path: src/main/java/org/jacis/exception/ReadOnlyException.java
// @JacisApi
// public class ReadOnlyException extends IllegalStateException {
//
// private static final long serialVersionUID = 1L;
//
// public ReadOnlyException(String s) {
// super(s);
// }
// }
//
// Path: src/main/java/org/jacis/plugin/readonly/object/AbstractReadOnlyModeSupportingObject.java
// @JacisApi
// public abstract class AbstractReadOnlyModeSupportingObject implements JacisReadonlyModeSupport {
//
// public static final boolean WRITE_ACCESS_MODE_SINGLE_THREAD = true;
//
// /** The thread currently permitted to modify the object (if any) */
// private transient Thread threadWithWriteAccess = null;
//
// protected AbstractReadOnlyModeSupportingObject() {
// threadWithWriteAccess = Thread.currentThread(); // when creating the object its writable
// }
//
// @Override
// protected Object clone() {
// try {
// return super.clone();
// } catch (CloneNotSupportedException e) {
// throw new InternalError("Could not clone " + this.getClass().getName());
// }
// }
//
// @Override
// public void switchToReadOnlyMode() {
// threadWithWriteAccess = null;
// }
//
// @Override
// public void switchToReadWriteMode() {
// threadWithWriteAccess = Thread.currentThread();
// }
//
// @Override
// public boolean isReadOnly() {
// return threadWithWriteAccess == null;
// }
//
// @Override
// public boolean isWritable() {
// if (isSingleThreadedWriteAccessRequirred()) {
// return Thread.currentThread().equals(threadWithWriteAccess);
// } else {
// return threadWithWriteAccess != null;
// }
// }
//
// /**
// * This method should be called prior to all modifying accesses to the object (e.g. in al setter-methods).
// * The method will check if the current thread has write access to the object and will throw a {@link ReadOnlyException} otherwise.
// *
// * @throws ReadOnlyException thrown if the current thread has no write access to the object.
// */
// protected void checkWritable() throws ReadOnlyException {
// if (threadWithWriteAccess == null) {
// throw new ReadOnlyException("Object currently in read only mode! Accessing Thread: " + Thread.currentThread() + ". Object: " + this);
// } else if (isSingleThreadedWriteAccessRequirred() && !threadWithWriteAccess.equals(Thread.currentThread())) {
// throw new ReadOnlyException("Object currently only writable for thread " + threadWithWriteAccess + "! Accessing Thread: " + Thread.currentThread() + ". Object: " + this);
// }
// }
//
// /**
// * Overwrite this method and return false if write access should not be restricted to a single thread.
// *
// * @return if single threaded write access is required (default: true)
// */
// protected boolean isSingleThreadedWriteAccessRequirred() {
// return WRITE_ACCESS_MODE_SINGLE_THREAD;
// }
//
// }
| import org.jacis.plugin.readonly.object.AbstractReadOnlyModeSupportingObject;
import org.jacis.JacisApi;
import org.jacis.exception.ReadOnlyException; | /*
* Copyright (c) 2016. Jan Wiemer
*/
package org.jacis.plugin.dirtycheck.object;
/**
* Abstract base class for objects supporting switching them between the usual read-write mode and a read-only mode
* (see {@link AbstractReadOnlyModeSupportingObject})
* and tracking if the object is dirty by tracking if the {@link #checkWritable()} method has been called.
*
* @author Jan Wiemer
*/
@JacisApi
public abstract class AbstractReadOnlyModeAndDirtyCheckSupportingObject extends AbstractReadOnlyModeSupportingObject implements JacisDirtyTrackingObject {
private boolean dirty = false;
/** @return if the object is dirty */
@Override
public boolean isDirty() {
return dirty;
}
@Override | // Path: src/main/java/org/jacis/exception/ReadOnlyException.java
// @JacisApi
// public class ReadOnlyException extends IllegalStateException {
//
// private static final long serialVersionUID = 1L;
//
// public ReadOnlyException(String s) {
// super(s);
// }
// }
//
// Path: src/main/java/org/jacis/plugin/readonly/object/AbstractReadOnlyModeSupportingObject.java
// @JacisApi
// public abstract class AbstractReadOnlyModeSupportingObject implements JacisReadonlyModeSupport {
//
// public static final boolean WRITE_ACCESS_MODE_SINGLE_THREAD = true;
//
// /** The thread currently permitted to modify the object (if any) */
// private transient Thread threadWithWriteAccess = null;
//
// protected AbstractReadOnlyModeSupportingObject() {
// threadWithWriteAccess = Thread.currentThread(); // when creating the object its writable
// }
//
// @Override
// protected Object clone() {
// try {
// return super.clone();
// } catch (CloneNotSupportedException e) {
// throw new InternalError("Could not clone " + this.getClass().getName());
// }
// }
//
// @Override
// public void switchToReadOnlyMode() {
// threadWithWriteAccess = null;
// }
//
// @Override
// public void switchToReadWriteMode() {
// threadWithWriteAccess = Thread.currentThread();
// }
//
// @Override
// public boolean isReadOnly() {
// return threadWithWriteAccess == null;
// }
//
// @Override
// public boolean isWritable() {
// if (isSingleThreadedWriteAccessRequirred()) {
// return Thread.currentThread().equals(threadWithWriteAccess);
// } else {
// return threadWithWriteAccess != null;
// }
// }
//
// /**
// * This method should be called prior to all modifying accesses to the object (e.g. in al setter-methods).
// * The method will check if the current thread has write access to the object and will throw a {@link ReadOnlyException} otherwise.
// *
// * @throws ReadOnlyException thrown if the current thread has no write access to the object.
// */
// protected void checkWritable() throws ReadOnlyException {
// if (threadWithWriteAccess == null) {
// throw new ReadOnlyException("Object currently in read only mode! Accessing Thread: " + Thread.currentThread() + ". Object: " + this);
// } else if (isSingleThreadedWriteAccessRequirred() && !threadWithWriteAccess.equals(Thread.currentThread())) {
// throw new ReadOnlyException("Object currently only writable for thread " + threadWithWriteAccess + "! Accessing Thread: " + Thread.currentThread() + ". Object: " + this);
// }
// }
//
// /**
// * Overwrite this method and return false if write access should not be restricted to a single thread.
// *
// * @return if single threaded write access is required (default: true)
// */
// protected boolean isSingleThreadedWriteAccessRequirred() {
// return WRITE_ACCESS_MODE_SINGLE_THREAD;
// }
//
// }
// Path: src/main/java/org/jacis/plugin/dirtycheck/object/AbstractReadOnlyModeAndDirtyCheckSupportingObject.java
import org.jacis.plugin.readonly.object.AbstractReadOnlyModeSupportingObject;
import org.jacis.JacisApi;
import org.jacis.exception.ReadOnlyException;
/*
* Copyright (c) 2016. Jan Wiemer
*/
package org.jacis.plugin.dirtycheck.object;
/**
* Abstract base class for objects supporting switching them between the usual read-write mode and a read-only mode
* (see {@link AbstractReadOnlyModeSupportingObject})
* and tracking if the object is dirty by tracking if the {@link #checkWritable()} method has been called.
*
* @author Jan Wiemer
*/
@JacisApi
public abstract class AbstractReadOnlyModeAndDirtyCheckSupportingObject extends AbstractReadOnlyModeSupportingObject implements JacisDirtyTrackingObject {
private boolean dirty = false;
/** @return if the object is dirty */
@Override
public boolean isDirty() {
return dirty;
}
@Override | protected void checkWritable() throws ReadOnlyException { |
JanWiemer/jacis | src/main/java/org/jacis/plugin/objectadapter/cloning/AbstractJacisCloningObjectAdapter.java | // Path: src/main/java/org/jacis/exception/ReadOnlyModeNotSupportedException.java
// @JacisApi
// public class ReadOnlyModeNotSupportedException extends IllegalStateException {
//
// private static final long serialVersionUID = 1L;
//
// public ReadOnlyModeNotSupportedException(String s) {
// super(s);
// }
// }
//
// Path: src/main/java/org/jacis/plugin/objectadapter/JacisObjectAdapter.java
// @JacisApi
// public interface JacisObjectAdapter<TV, CV> {
//
// /**
// * Clone a committed version of the object into the transactional view.
// * Note that modifications ib the returned transactional view must not influence the committed version of the object.
// *
// * @param value Committed version of the object.
// * @return A transactional view for the passed object.
// */
// TV cloneCommitted2WritableTxView(CV value);
//
// /**
// * Clone back a transactional view of the object into the committed version of the object.
// * The returned committed version will replace the previous one in the store of the committed values.
// *
// * @param value A transactional view for the passed object.
// * @return Committed version of the object.
// */
// CV cloneTxView2Committed(TV value);
//
// /**
// * Clone a committed version of the object into a read only transactional view.
// * Modifications of the read only view must not be possible (lead to an exception).
// * As an optimization it is allowed to skip a real cloning here since the returned object is guaranteed to be read only.
// * Note that a difference using read only views where cloning is skipped is that a repeated read of the same object
// * may return different versions of the object if another transaction committed a newer version between both reads.
// *
// * @param value Committed version of the object.
// * @return A read only transactional view for the passed object.
// */
// TV cloneCommitted2ReadOnlyTxView(CV value);
//
// /**
// * Convert a transactional view of an object into a read only representation of this object.
// * Modifications of the read only view must not be possible (lead to an exception).
// *
// * @param value A transactional view for the passed object.
// * @return A read only transactional view for the passed object.
// */
// TV cloneTxView2ReadOnlyTxView(TV value);
//
// }
//
// Path: src/main/java/org/jacis/plugin/readonly/DefaultJacisStoreEntryReadOnlyModeAdapter.java
// public class DefaultJacisStoreEntryReadOnlyModeAdapter<V> implements JacisStoreEntryReadOnlyModeAdapter<V> {
//
// @Override
// public boolean isApplicableTo(V value) {
// return value instanceof JacisReadonlyModeSupport;
// }
//
// @Override
// public boolean isReadOnly(V value) {
// return ((JacisReadonlyModeSupport) value).isReadOnly();
// }
//
// @Override
// public V switchToReadOnlyMode(V value) {
// ((JacisReadonlyModeSupport) value).switchToReadOnlyMode();
// return value;
// }
//
// @Override
// public V switchToReadWriteMode(V value) {
// ((JacisReadonlyModeSupport) value).switchToReadWriteMode();
// return value;
// }
//
// @Override
// public String toString() {
// return getClass().getSimpleName();
// }
// }
//
// Path: src/main/java/org/jacis/plugin/readonly/JacisStoreEntryReadOnlyModeAdapter.java
// @JacisApi
// public interface JacisStoreEntryReadOnlyModeAdapter<V> {
//
// /**
// * Returns if this adapter can switch the read / write mode for the passed object
// *
// * @param value The object to check.
// * @return if this adapter can switch the read / write mode for the passed object
// */
// boolean isApplicableTo(V value);
//
// /**
// * Returns if the passed object is in read-only mode
// *
// * @param value The object to check.
// * @return if the passed object is in read-only mode
// */
// boolean isReadOnly(V value);
//
// /**
// * Switch the read / write mode for the passed object to read-only mode
// * Note that the calling methods will work with the returned value.
// * Therefore the implementation of the method may return another instance than the passed (e.g. a proxy).
// *
// * @param value The object to switch to read-only mode
// * @return the object with the switched mode.
// */
// V switchToReadOnlyMode(V value);
//
// /**
// * Switch the read / write mode for the passed object to read-write mode
// * Note that the calling methods will work with the returned value.
// * Therefore the implementation of the method may return another instance than the passed (e.g. a proxy).
// *
// * @param value The object to switch to read-write mode
// * @return the object with the switched mode.
// */
// V switchToReadWriteMode(V value);
//
// }
| import org.jacis.JacisApi;
import org.jacis.exception.ReadOnlyModeNotSupportedException;
import org.jacis.plugin.objectadapter.JacisObjectAdapter;
import org.jacis.plugin.readonly.DefaultJacisStoreEntryReadOnlyModeAdapter;
import org.jacis.plugin.readonly.JacisStoreEntryReadOnlyModeAdapter;
| public V cloneCommitted2ReadOnlyTxView(V value) {
if (value == null) {
return null;
}
checkReadOnlyModeSupported(value);
V clone;
if (readOnlyModeAdapter == null || !readOnlyModeAdapter.isApplicableTo(value)) {
clone = cloneValue(value);
} else {
clone = value; // for read only objects we do not clone the returned object. -> skip call of: cloneValue(value);
}
return clone;
}
@Override
public V cloneTxView2ReadOnlyTxView(V value) {
if (value == null) {
return null;
}
if (readOnlyModeAdapter != null && readOnlyModeAdapter.isApplicableTo(value)) {
if (readOnlyModeAdapter.isReadOnly(value)) {
return value;
} else {
return readOnlyModeAdapter.switchToReadOnlyMode(cloneValue(value));
}
} else {
return cloneValue(value);
}
}
| // Path: src/main/java/org/jacis/exception/ReadOnlyModeNotSupportedException.java
// @JacisApi
// public class ReadOnlyModeNotSupportedException extends IllegalStateException {
//
// private static final long serialVersionUID = 1L;
//
// public ReadOnlyModeNotSupportedException(String s) {
// super(s);
// }
// }
//
// Path: src/main/java/org/jacis/plugin/objectadapter/JacisObjectAdapter.java
// @JacisApi
// public interface JacisObjectAdapter<TV, CV> {
//
// /**
// * Clone a committed version of the object into the transactional view.
// * Note that modifications ib the returned transactional view must not influence the committed version of the object.
// *
// * @param value Committed version of the object.
// * @return A transactional view for the passed object.
// */
// TV cloneCommitted2WritableTxView(CV value);
//
// /**
// * Clone back a transactional view of the object into the committed version of the object.
// * The returned committed version will replace the previous one in the store of the committed values.
// *
// * @param value A transactional view for the passed object.
// * @return Committed version of the object.
// */
// CV cloneTxView2Committed(TV value);
//
// /**
// * Clone a committed version of the object into a read only transactional view.
// * Modifications of the read only view must not be possible (lead to an exception).
// * As an optimization it is allowed to skip a real cloning here since the returned object is guaranteed to be read only.
// * Note that a difference using read only views where cloning is skipped is that a repeated read of the same object
// * may return different versions of the object if another transaction committed a newer version between both reads.
// *
// * @param value Committed version of the object.
// * @return A read only transactional view for the passed object.
// */
// TV cloneCommitted2ReadOnlyTxView(CV value);
//
// /**
// * Convert a transactional view of an object into a read only representation of this object.
// * Modifications of the read only view must not be possible (lead to an exception).
// *
// * @param value A transactional view for the passed object.
// * @return A read only transactional view for the passed object.
// */
// TV cloneTxView2ReadOnlyTxView(TV value);
//
// }
//
// Path: src/main/java/org/jacis/plugin/readonly/DefaultJacisStoreEntryReadOnlyModeAdapter.java
// public class DefaultJacisStoreEntryReadOnlyModeAdapter<V> implements JacisStoreEntryReadOnlyModeAdapter<V> {
//
// @Override
// public boolean isApplicableTo(V value) {
// return value instanceof JacisReadonlyModeSupport;
// }
//
// @Override
// public boolean isReadOnly(V value) {
// return ((JacisReadonlyModeSupport) value).isReadOnly();
// }
//
// @Override
// public V switchToReadOnlyMode(V value) {
// ((JacisReadonlyModeSupport) value).switchToReadOnlyMode();
// return value;
// }
//
// @Override
// public V switchToReadWriteMode(V value) {
// ((JacisReadonlyModeSupport) value).switchToReadWriteMode();
// return value;
// }
//
// @Override
// public String toString() {
// return getClass().getSimpleName();
// }
// }
//
// Path: src/main/java/org/jacis/plugin/readonly/JacisStoreEntryReadOnlyModeAdapter.java
// @JacisApi
// public interface JacisStoreEntryReadOnlyModeAdapter<V> {
//
// /**
// * Returns if this adapter can switch the read / write mode for the passed object
// *
// * @param value The object to check.
// * @return if this adapter can switch the read / write mode for the passed object
// */
// boolean isApplicableTo(V value);
//
// /**
// * Returns if the passed object is in read-only mode
// *
// * @param value The object to check.
// * @return if the passed object is in read-only mode
// */
// boolean isReadOnly(V value);
//
// /**
// * Switch the read / write mode for the passed object to read-only mode
// * Note that the calling methods will work with the returned value.
// * Therefore the implementation of the method may return another instance than the passed (e.g. a proxy).
// *
// * @param value The object to switch to read-only mode
// * @return the object with the switched mode.
// */
// V switchToReadOnlyMode(V value);
//
// /**
// * Switch the read / write mode for the passed object to read-write mode
// * Note that the calling methods will work with the returned value.
// * Therefore the implementation of the method may return another instance than the passed (e.g. a proxy).
// *
// * @param value The object to switch to read-write mode
// * @return the object with the switched mode.
// */
// V switchToReadWriteMode(V value);
//
// }
// Path: src/main/java/org/jacis/plugin/objectadapter/cloning/AbstractJacisCloningObjectAdapter.java
import org.jacis.JacisApi;
import org.jacis.exception.ReadOnlyModeNotSupportedException;
import org.jacis.plugin.objectadapter.JacisObjectAdapter;
import org.jacis.plugin.readonly.DefaultJacisStoreEntryReadOnlyModeAdapter;
import org.jacis.plugin.readonly.JacisStoreEntryReadOnlyModeAdapter;
public V cloneCommitted2ReadOnlyTxView(V value) {
if (value == null) {
return null;
}
checkReadOnlyModeSupported(value);
V clone;
if (readOnlyModeAdapter == null || !readOnlyModeAdapter.isApplicableTo(value)) {
clone = cloneValue(value);
} else {
clone = value; // for read only objects we do not clone the returned object. -> skip call of: cloneValue(value);
}
return clone;
}
@Override
public V cloneTxView2ReadOnlyTxView(V value) {
if (value == null) {
return null;
}
if (readOnlyModeAdapter != null && readOnlyModeAdapter.isApplicableTo(value)) {
if (readOnlyModeAdapter.isReadOnly(value)) {
return value;
} else {
return readOnlyModeAdapter.switchToReadOnlyMode(cloneValue(value));
}
} else {
return cloneValue(value);
}
}
| private void checkReadOnlyModeSupported(V value) throws ReadOnlyModeNotSupportedException {
|
JanWiemer/jacis | src/main/java/org/jacis/plugin/readonly/DefaultJacisStoreEntryReadOnlyModeAdapter.java | // Path: src/main/java/org/jacis/plugin/readonly/object/JacisReadonlyModeSupport.java
// @JacisApi
// public interface JacisReadonlyModeSupport {
//
// /**
// * Switches the object into the read-only mode
// */
// void switchToReadOnlyMode();
//
// /**
// * Switches the object into the read-write mode
// */
// void switchToReadWriteMode();
//
// /**
// * @return if the object is currently in the read-only mode
// */
// boolean isReadOnly();
//
// /**
// * @return if the object is writable for the current thread
// */
// boolean isWritable();
//
// /**
// * Switches the read / write mode depending on the passed parameter
// *
// * @param readOnlyMode if 'true' switch to read-only mode, if 'false' switch to read-write mode
// */
// default void switchToReadOnlyMode(boolean readOnlyMode) {
// if (readOnlyMode) {
// switchToReadOnlyMode();
// } else {
// switchToReadWriteMode();
// }
// }
//
// }
| import org.jacis.plugin.readonly.object.JacisReadonlyModeSupport; | /*
* Copyright (c) 2016. Jan Wiemer
*/
package org.jacis.plugin.readonly;
/**
* The default implementation of the interface {@link JacisStoreEntryReadOnlyModeAdapter}.
* This implementation is applicable for objects
* implementing the {@link org.jacis.plugin.readonly.object.JacisReadonlyModeSupport} interface
* and uses the methods declared in this interface for switching the mode.
*
* @param <V> The type of the values that should be switched between read-write and read-only mode.
* @author Jan Wiemer
*/
public class DefaultJacisStoreEntryReadOnlyModeAdapter<V> implements JacisStoreEntryReadOnlyModeAdapter<V> {
@Override
public boolean isApplicableTo(V value) { | // Path: src/main/java/org/jacis/plugin/readonly/object/JacisReadonlyModeSupport.java
// @JacisApi
// public interface JacisReadonlyModeSupport {
//
// /**
// * Switches the object into the read-only mode
// */
// void switchToReadOnlyMode();
//
// /**
// * Switches the object into the read-write mode
// */
// void switchToReadWriteMode();
//
// /**
// * @return if the object is currently in the read-only mode
// */
// boolean isReadOnly();
//
// /**
// * @return if the object is writable for the current thread
// */
// boolean isWritable();
//
// /**
// * Switches the read / write mode depending on the passed parameter
// *
// * @param readOnlyMode if 'true' switch to read-only mode, if 'false' switch to read-write mode
// */
// default void switchToReadOnlyMode(boolean readOnlyMode) {
// if (readOnlyMode) {
// switchToReadOnlyMode();
// } else {
// switchToReadWriteMode();
// }
// }
//
// }
// Path: src/main/java/org/jacis/plugin/readonly/DefaultJacisStoreEntryReadOnlyModeAdapter.java
import org.jacis.plugin.readonly.object.JacisReadonlyModeSupport;
/*
* Copyright (c) 2016. Jan Wiemer
*/
package org.jacis.plugin.readonly;
/**
* The default implementation of the interface {@link JacisStoreEntryReadOnlyModeAdapter}.
* This implementation is applicable for objects
* implementing the {@link org.jacis.plugin.readonly.object.JacisReadonlyModeSupport} interface
* and uses the methods declared in this interface for switching the mode.
*
* @param <V> The type of the values that should be switched between read-write and read-only mode.
* @author Jan Wiemer
*/
public class DefaultJacisStoreEntryReadOnlyModeAdapter<V> implements JacisStoreEntryReadOnlyModeAdapter<V> {
@Override
public boolean isApplicableTo(V value) { | return value instanceof JacisReadonlyModeSupport; |
JanWiemer/jacis | src/test/java/org/jacis/persistence/microstream/microstreamframework/BasicMicrostreamPerfTest.java | // Path: src/test/java/org/jacis/testhelper/FileUtils.java
// public abstract class FileUtils {
//
// public static boolean deleteDirectory(File directoryToBeDeleted) {
// File[] allContents = directoryToBeDeleted.listFiles();
// if (allContents != null) {
// for (File file : allContents) {
// deleteDirectory(file);
// }
// }
// return directoryToBeDeleted.delete();
// }
//
// }
| import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.ListIterator;
import java.util.Map;
import org.jacis.testhelper.FileUtils;
import org.junit.AfterClass;
import org.junit.Ignore;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import one.microstream.storage.configuration.Configuration;
import one.microstream.storage.embedded.types.EmbeddedStorageFoundation;
import one.microstream.storage.embedded.types.EmbeddedStorageManager;
| /*
* Copyright (c) 2020. Jan Wiemer
*/
package org.jacis.persistence.microstream.microstreamframework;
@Ignore
public class BasicMicrostreamPerfTest {
private static final int MAX_TEST_SIZE = 500;
// private static final int MAX_TEST_SIZE = Integer.MAX_VALUE;
private static final Logger log = LoggerFactory.getLogger(BasicMicrostreamPerfTest.class);
protected static Path getStorageDir(String suffix) {
Path path = suffix == null ? Paths.get("var", BasicMicrostreamPerfTest.class.getName()) : Paths.get("var", BasicMicrostreamPerfTest.class.getName(), suffix);
log.debug("use storage path: {}", path.toString());
return path;
}
@AfterClass
public static void cleanup() {
| // Path: src/test/java/org/jacis/testhelper/FileUtils.java
// public abstract class FileUtils {
//
// public static boolean deleteDirectory(File directoryToBeDeleted) {
// File[] allContents = directoryToBeDeleted.listFiles();
// if (allContents != null) {
// for (File file : allContents) {
// deleteDirectory(file);
// }
// }
// return directoryToBeDeleted.delete();
// }
//
// }
// Path: src/test/java/org/jacis/persistence/microstream/microstreamframework/BasicMicrostreamPerfTest.java
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.ListIterator;
import java.util.Map;
import org.jacis.testhelper.FileUtils;
import org.junit.AfterClass;
import org.junit.Ignore;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import one.microstream.storage.configuration.Configuration;
import one.microstream.storage.embedded.types.EmbeddedStorageFoundation;
import one.microstream.storage.embedded.types.EmbeddedStorageManager;
/*
* Copyright (c) 2020. Jan Wiemer
*/
package org.jacis.persistence.microstream.microstreamframework;
@Ignore
public class BasicMicrostreamPerfTest {
private static final int MAX_TEST_SIZE = 500;
// private static final int MAX_TEST_SIZE = Integer.MAX_VALUE;
private static final Logger log = LoggerFactory.getLogger(BasicMicrostreamPerfTest.class);
protected static Path getStorageDir(String suffix) {
Path path = suffix == null ? Paths.get("var", BasicMicrostreamPerfTest.class.getName()) : Paths.get("var", BasicMicrostreamPerfTest.class.getName(), suffix);
log.debug("use storage path: {}", path.toString());
return path;
}
@AfterClass
public static void cleanup() {
| FileUtils.deleteDirectory(Paths.get("var", BasicMicrostreamPerfTest.class.getName()).toFile());
|
JanWiemer/jacis | src/main/java/org/jacis/plugin/objectadapter/cloning/JacisCloningObjectAdapter.java | // Path: src/main/java/org/jacis/plugin/readonly/DefaultJacisStoreEntryReadOnlyModeAdapter.java
// public class DefaultJacisStoreEntryReadOnlyModeAdapter<V> implements JacisStoreEntryReadOnlyModeAdapter<V> {
//
// @Override
// public boolean isApplicableTo(V value) {
// return value instanceof JacisReadonlyModeSupport;
// }
//
// @Override
// public boolean isReadOnly(V value) {
// return ((JacisReadonlyModeSupport) value).isReadOnly();
// }
//
// @Override
// public V switchToReadOnlyMode(V value) {
// ((JacisReadonlyModeSupport) value).switchToReadOnlyMode();
// return value;
// }
//
// @Override
// public V switchToReadWriteMode(V value) {
// ((JacisReadonlyModeSupport) value).switchToReadWriteMode();
// return value;
// }
//
// @Override
// public String toString() {
// return getClass().getSimpleName();
// }
// }
//
// Path: src/main/java/org/jacis/plugin/readonly/JacisStoreEntryReadOnlyModeAdapter.java
// @JacisApi
// public interface JacisStoreEntryReadOnlyModeAdapter<V> {
//
// /**
// * Returns if this adapter can switch the read / write mode for the passed object
// *
// * @param value The object to check.
// * @return if this adapter can switch the read / write mode for the passed object
// */
// boolean isApplicableTo(V value);
//
// /**
// * Returns if the passed object is in read-only mode
// *
// * @param value The object to check.
// * @return if the passed object is in read-only mode
// */
// boolean isReadOnly(V value);
//
// /**
// * Switch the read / write mode for the passed object to read-only mode
// * Note that the calling methods will work with the returned value.
// * Therefore the implementation of the method may return another instance than the passed (e.g. a proxy).
// *
// * @param value The object to switch to read-only mode
// * @return the object with the switched mode.
// */
// V switchToReadOnlyMode(V value);
//
// /**
// * Switch the read / write mode for the passed object to read-write mode
// * Note that the calling methods will work with the returned value.
// * Therefore the implementation of the method may return another instance than the passed (e.g. a proxy).
// *
// * @param value The object to switch to read-write mode
// * @return the object with the switched mode.
// */
// V switchToReadWriteMode(V value);
//
// }
| import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import org.jacis.JacisApi;
import org.jacis.plugin.readonly.DefaultJacisStoreEntryReadOnlyModeAdapter;
import org.jacis.plugin.readonly.JacisStoreEntryReadOnlyModeAdapter;
| /*
* Copyright (c) 2016. Jan Wiemer
*/
package org.jacis.plugin.objectadapter.cloning;
/**
* Implementation of the {@link AbstractJacisCloningObjectAdapter} cloning the objects based on Java serialization.
* If the object is an instance of the {@link JacisCloneable} interface the {@link JacisCloneable#clone()} method
* declared in this interface is used to clone the object.
* Otherwise the object may be cloneable (overwrites the {@link Object#clone()} methods)
* but does not implement the {@link JacisCloneable} interface.
* In this case the {@link Object#clone()} method is called by reflection.
*
* @param <V> The object type (note that in this case the committed values and the values in the transactional view have the same type)
* @author Jan Wiemer
*/
@JacisApi
public class JacisCloningObjectAdapter<V> extends AbstractJacisCloningObjectAdapter<V> {
/**
* Create a cloning object adapter with the passed read only mode adapter.
*
* @param readOnlyModeAdapters Adapter to switch an object between read-only and read-write mode (if supported).
*/
| // Path: src/main/java/org/jacis/plugin/readonly/DefaultJacisStoreEntryReadOnlyModeAdapter.java
// public class DefaultJacisStoreEntryReadOnlyModeAdapter<V> implements JacisStoreEntryReadOnlyModeAdapter<V> {
//
// @Override
// public boolean isApplicableTo(V value) {
// return value instanceof JacisReadonlyModeSupport;
// }
//
// @Override
// public boolean isReadOnly(V value) {
// return ((JacisReadonlyModeSupport) value).isReadOnly();
// }
//
// @Override
// public V switchToReadOnlyMode(V value) {
// ((JacisReadonlyModeSupport) value).switchToReadOnlyMode();
// return value;
// }
//
// @Override
// public V switchToReadWriteMode(V value) {
// ((JacisReadonlyModeSupport) value).switchToReadWriteMode();
// return value;
// }
//
// @Override
// public String toString() {
// return getClass().getSimpleName();
// }
// }
//
// Path: src/main/java/org/jacis/plugin/readonly/JacisStoreEntryReadOnlyModeAdapter.java
// @JacisApi
// public interface JacisStoreEntryReadOnlyModeAdapter<V> {
//
// /**
// * Returns if this adapter can switch the read / write mode for the passed object
// *
// * @param value The object to check.
// * @return if this adapter can switch the read / write mode for the passed object
// */
// boolean isApplicableTo(V value);
//
// /**
// * Returns if the passed object is in read-only mode
// *
// * @param value The object to check.
// * @return if the passed object is in read-only mode
// */
// boolean isReadOnly(V value);
//
// /**
// * Switch the read / write mode for the passed object to read-only mode
// * Note that the calling methods will work with the returned value.
// * Therefore the implementation of the method may return another instance than the passed (e.g. a proxy).
// *
// * @param value The object to switch to read-only mode
// * @return the object with the switched mode.
// */
// V switchToReadOnlyMode(V value);
//
// /**
// * Switch the read / write mode for the passed object to read-write mode
// * Note that the calling methods will work with the returned value.
// * Therefore the implementation of the method may return another instance than the passed (e.g. a proxy).
// *
// * @param value The object to switch to read-write mode
// * @return the object with the switched mode.
// */
// V switchToReadWriteMode(V value);
//
// }
// Path: src/main/java/org/jacis/plugin/objectadapter/cloning/JacisCloningObjectAdapter.java
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import org.jacis.JacisApi;
import org.jacis.plugin.readonly.DefaultJacisStoreEntryReadOnlyModeAdapter;
import org.jacis.plugin.readonly.JacisStoreEntryReadOnlyModeAdapter;
/*
* Copyright (c) 2016. Jan Wiemer
*/
package org.jacis.plugin.objectadapter.cloning;
/**
* Implementation of the {@link AbstractJacisCloningObjectAdapter} cloning the objects based on Java serialization.
* If the object is an instance of the {@link JacisCloneable} interface the {@link JacisCloneable#clone()} method
* declared in this interface is used to clone the object.
* Otherwise the object may be cloneable (overwrites the {@link Object#clone()} methods)
* but does not implement the {@link JacisCloneable} interface.
* In this case the {@link Object#clone()} method is called by reflection.
*
* @param <V> The object type (note that in this case the committed values and the values in the transactional view have the same type)
* @author Jan Wiemer
*/
@JacisApi
public class JacisCloningObjectAdapter<V> extends AbstractJacisCloningObjectAdapter<V> {
/**
* Create a cloning object adapter with the passed read only mode adapter.
*
* @param readOnlyModeAdapters Adapter to switch an object between read-only and read-write mode (if supported).
*/
| public JacisCloningObjectAdapter(JacisStoreEntryReadOnlyModeAdapter<V> readOnlyModeAdapters) {
|
JanWiemer/jacis | src/main/java/org/jacis/plugin/readonly/object/AbstractReadOnlyModeSupportingObject.java | // Path: src/main/java/org/jacis/exception/ReadOnlyException.java
// @JacisApi
// public class ReadOnlyException extends IllegalStateException {
//
// private static final long serialVersionUID = 1L;
//
// public ReadOnlyException(String s) {
// super(s);
// }
// }
| import org.jacis.JacisApi;
import org.jacis.exception.ReadOnlyException; | /*
* Copyright (c) 2016. Jan Wiemer
*/
package org.jacis.plugin.readonly.object;
/**
* Abstract base class for objects supporting switching them between the usual read-write mode and a read-only mode.
* Therefore it implements the methods {@link #switchToReadOnlyMode()} and {@link #switchToReadWriteMode()} from
* the {@link JacisReadonlyModeSupport} interface. Note that all the time only one single thread is allowed to
* have write access to the object. When switching an object to read-write mode the current thread is stored
* as thread with write access (see {@link #threadWithWriteAccess}).
*
* For actual implementations the class provides the protected method {@link #checkWritable()}.
* This method should be called prior to all modifying accesses to the object (e.g. in all setter-methods).
* The method will throw a {@link ReadOnlyException} if the current thread has no write access to the object.
*
* @author Jan Wiemer
*/
@JacisApi
public abstract class AbstractReadOnlyModeSupportingObject implements JacisReadonlyModeSupport {
public static final boolean WRITE_ACCESS_MODE_SINGLE_THREAD = true;
/** The thread currently permitted to modify the object (if any) */
private transient Thread threadWithWriteAccess = null;
protected AbstractReadOnlyModeSupportingObject() {
threadWithWriteAccess = Thread.currentThread(); // when creating the object its writable
}
@Override
protected Object clone() {
try {
return super.clone();
} catch (CloneNotSupportedException e) {
throw new InternalError("Could not clone " + this.getClass().getName());
}
}
@Override
public void switchToReadOnlyMode() {
threadWithWriteAccess = null;
}
@Override
public void switchToReadWriteMode() {
threadWithWriteAccess = Thread.currentThread();
}
@Override
public boolean isReadOnly() {
return threadWithWriteAccess == null;
}
@Override
public boolean isWritable() {
if (isSingleThreadedWriteAccessRequirred()) {
return Thread.currentThread().equals(threadWithWriteAccess);
} else {
return threadWithWriteAccess != null;
}
}
/**
* This method should be called prior to all modifying accesses to the object (e.g. in al setter-methods).
* The method will check if the current thread has write access to the object and will throw a {@link ReadOnlyException} otherwise.
*
* @throws ReadOnlyException thrown if the current thread has no write access to the object.
*/ | // Path: src/main/java/org/jacis/exception/ReadOnlyException.java
// @JacisApi
// public class ReadOnlyException extends IllegalStateException {
//
// private static final long serialVersionUID = 1L;
//
// public ReadOnlyException(String s) {
// super(s);
// }
// }
// Path: src/main/java/org/jacis/plugin/readonly/object/AbstractReadOnlyModeSupportingObject.java
import org.jacis.JacisApi;
import org.jacis.exception.ReadOnlyException;
/*
* Copyright (c) 2016. Jan Wiemer
*/
package org.jacis.plugin.readonly.object;
/**
* Abstract base class for objects supporting switching them between the usual read-write mode and a read-only mode.
* Therefore it implements the methods {@link #switchToReadOnlyMode()} and {@link #switchToReadWriteMode()} from
* the {@link JacisReadonlyModeSupport} interface. Note that all the time only one single thread is allowed to
* have write access to the object. When switching an object to read-write mode the current thread is stored
* as thread with write access (see {@link #threadWithWriteAccess}).
*
* For actual implementations the class provides the protected method {@link #checkWritable()}.
* This method should be called prior to all modifying accesses to the object (e.g. in all setter-methods).
* The method will throw a {@link ReadOnlyException} if the current thread has no write access to the object.
*
* @author Jan Wiemer
*/
@JacisApi
public abstract class AbstractReadOnlyModeSupportingObject implements JacisReadonlyModeSupport {
public static final boolean WRITE_ACCESS_MODE_SINGLE_THREAD = true;
/** The thread currently permitted to modify the object (if any) */
private transient Thread threadWithWriteAccess = null;
protected AbstractReadOnlyModeSupportingObject() {
threadWithWriteAccess = Thread.currentThread(); // when creating the object its writable
}
@Override
protected Object clone() {
try {
return super.clone();
} catch (CloneNotSupportedException e) {
throw new InternalError("Could not clone " + this.getClass().getName());
}
}
@Override
public void switchToReadOnlyMode() {
threadWithWriteAccess = null;
}
@Override
public void switchToReadWriteMode() {
threadWithWriteAccess = Thread.currentThread();
}
@Override
public boolean isReadOnly() {
return threadWithWriteAccess == null;
}
@Override
public boolean isWritable() {
if (isSingleThreadedWriteAccessRequirred()) {
return Thread.currentThread().equals(threadWithWriteAccess);
} else {
return threadWithWriteAccess != null;
}
}
/**
* This method should be called prior to all modifying accesses to the object (e.g. in al setter-methods).
* The method will check if the current thread has write access to the object and will throw a {@link ReadOnlyException} otherwise.
*
* @throws ReadOnlyException thrown if the current thread has no write access to the object.
*/ | protected void checkWritable() throws ReadOnlyException { |
JanWiemer/jacis | src/main/java/org/jacis/plugin/objectadapter/cloning/JacisCloningObjectAdapterUnsafe.java | // Path: src/main/java/org/jacis/plugin/readonly/DefaultJacisStoreEntryReadOnlyModeAdapter.java
// public class DefaultJacisStoreEntryReadOnlyModeAdapter<V> implements JacisStoreEntryReadOnlyModeAdapter<V> {
//
// @Override
// public boolean isApplicableTo(V value) {
// return value instanceof JacisReadonlyModeSupport;
// }
//
// @Override
// public boolean isReadOnly(V value) {
// return ((JacisReadonlyModeSupport) value).isReadOnly();
// }
//
// @Override
// public V switchToReadOnlyMode(V value) {
// ((JacisReadonlyModeSupport) value).switchToReadOnlyMode();
// return value;
// }
//
// @Override
// public V switchToReadWriteMode(V value) {
// ((JacisReadonlyModeSupport) value).switchToReadWriteMode();
// return value;
// }
//
// @Override
// public String toString() {
// return getClass().getSimpleName();
// }
// }
//
// Path: src/main/java/org/jacis/plugin/readonly/JacisStoreEntryReadOnlyModeAdapter.java
// @JacisApi
// public interface JacisStoreEntryReadOnlyModeAdapter<V> {
//
// /**
// * Returns if this adapter can switch the read / write mode for the passed object
// *
// * @param value The object to check.
// * @return if this adapter can switch the read / write mode for the passed object
// */
// boolean isApplicableTo(V value);
//
// /**
// * Returns if the passed object is in read-only mode
// *
// * @param value The object to check.
// * @return if the passed object is in read-only mode
// */
// boolean isReadOnly(V value);
//
// /**
// * Switch the read / write mode for the passed object to read-only mode
// * Note that the calling methods will work with the returned value.
// * Therefore the implementation of the method may return another instance than the passed (e.g. a proxy).
// *
// * @param value The object to switch to read-only mode
// * @return the object with the switched mode.
// */
// V switchToReadOnlyMode(V value);
//
// /**
// * Switch the read / write mode for the passed object to read-write mode
// * Note that the calling methods will work with the returned value.
// * Therefore the implementation of the method may return another instance than the passed (e.g. a proxy).
// *
// * @param value The object to switch to read-write mode
// * @return the object with the switched mode.
// */
// V switchToReadWriteMode(V value);
//
// }
| import org.jacis.plugin.readonly.JacisStoreEntryReadOnlyModeAdapter;
import org.jacis.JacisApi;
import org.jacis.plugin.readonly.DefaultJacisStoreEntryReadOnlyModeAdapter;
| /*
* Copyright (c) 2016. Jan Wiemer
*/
package org.jacis.plugin.objectadapter.cloning;
/**
* Implementation of the {@link AbstractJacisCloningObjectAdapter} cloning the objects based on the Java clone method.
* The behavior is similar to the {@link JacisCloningObjectAdapter} but returning a read only version of the object does not first check if the object supports a read only mode.
*
* @param <V> The object type (note that in this case the committed values and the values in the transactional view have the same type)
* @author Jan Wiemer
*/
@JacisApi
public class JacisCloningObjectAdapterUnsafe<V> extends JacisCloningObjectAdapter<V> {
/**
* Create a cloning object adapter with the passed read only mode adapter.
*
* @param readOnlyModeAdapters Adapter to switch an object between read-only and read-write mode (if supported).
*/
| // Path: src/main/java/org/jacis/plugin/readonly/DefaultJacisStoreEntryReadOnlyModeAdapter.java
// public class DefaultJacisStoreEntryReadOnlyModeAdapter<V> implements JacisStoreEntryReadOnlyModeAdapter<V> {
//
// @Override
// public boolean isApplicableTo(V value) {
// return value instanceof JacisReadonlyModeSupport;
// }
//
// @Override
// public boolean isReadOnly(V value) {
// return ((JacisReadonlyModeSupport) value).isReadOnly();
// }
//
// @Override
// public V switchToReadOnlyMode(V value) {
// ((JacisReadonlyModeSupport) value).switchToReadOnlyMode();
// return value;
// }
//
// @Override
// public V switchToReadWriteMode(V value) {
// ((JacisReadonlyModeSupport) value).switchToReadWriteMode();
// return value;
// }
//
// @Override
// public String toString() {
// return getClass().getSimpleName();
// }
// }
//
// Path: src/main/java/org/jacis/plugin/readonly/JacisStoreEntryReadOnlyModeAdapter.java
// @JacisApi
// public interface JacisStoreEntryReadOnlyModeAdapter<V> {
//
// /**
// * Returns if this adapter can switch the read / write mode for the passed object
// *
// * @param value The object to check.
// * @return if this adapter can switch the read / write mode for the passed object
// */
// boolean isApplicableTo(V value);
//
// /**
// * Returns if the passed object is in read-only mode
// *
// * @param value The object to check.
// * @return if the passed object is in read-only mode
// */
// boolean isReadOnly(V value);
//
// /**
// * Switch the read / write mode for the passed object to read-only mode
// * Note that the calling methods will work with the returned value.
// * Therefore the implementation of the method may return another instance than the passed (e.g. a proxy).
// *
// * @param value The object to switch to read-only mode
// * @return the object with the switched mode.
// */
// V switchToReadOnlyMode(V value);
//
// /**
// * Switch the read / write mode for the passed object to read-write mode
// * Note that the calling methods will work with the returned value.
// * Therefore the implementation of the method may return another instance than the passed (e.g. a proxy).
// *
// * @param value The object to switch to read-write mode
// * @return the object with the switched mode.
// */
// V switchToReadWriteMode(V value);
//
// }
// Path: src/main/java/org/jacis/plugin/objectadapter/cloning/JacisCloningObjectAdapterUnsafe.java
import org.jacis.plugin.readonly.JacisStoreEntryReadOnlyModeAdapter;
import org.jacis.JacisApi;
import org.jacis.plugin.readonly.DefaultJacisStoreEntryReadOnlyModeAdapter;
/*
* Copyright (c) 2016. Jan Wiemer
*/
package org.jacis.plugin.objectadapter.cloning;
/**
* Implementation of the {@link AbstractJacisCloningObjectAdapter} cloning the objects based on the Java clone method.
* The behavior is similar to the {@link JacisCloningObjectAdapter} but returning a read only version of the object does not first check if the object supports a read only mode.
*
* @param <V> The object type (note that in this case the committed values and the values in the transactional view have the same type)
* @author Jan Wiemer
*/
@JacisApi
public class JacisCloningObjectAdapterUnsafe<V> extends JacisCloningObjectAdapter<V> {
/**
* Create a cloning object adapter with the passed read only mode adapter.
*
* @param readOnlyModeAdapters Adapter to switch an object between read-only and read-write mode (if supported).
*/
| public JacisCloningObjectAdapterUnsafe(JacisStoreEntryReadOnlyModeAdapter<V> readOnlyModeAdapters) {
|
ScreamingHawk/fate-sheets | app/src/main/java/link/standen/michael/fatesheets/fragment/CoreCharacterEditStuntsFragment.java | // Path: app/src/main/java/link/standen/michael/fatesheets/adapter/DeletableStringArrayAdapter.java
// public class DeletableStringArrayAdapter extends ArrayAdapter<String> {
//
// private static final String TAG = DeletableStringArrayAdapter.class.getName();
//
// private final Context context;
// private final int resourceId;
// private final List<String> items;
//
// public DeletableStringArrayAdapter(@NonNull Context context, @LayoutRes int resourceId, @NonNull List<String> items) {
// super(context, resourceId, items);
//
// this.context = context;
// this.resourceId = resourceId;
// this.items = items;
// }
//
// public String getItem(int index){
// return items.get(index);
// }
//
// @NonNull
// @Override
// public View getView(final int position, @Nullable View convertView, @NonNull ViewGroup parent) {
// View view = convertView;
// if (view == null){
// LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
// view = inflater.inflate(resourceId, null);
// }
//
// view.findViewById(R.id.delete).setOnClickListener(new View.OnClickListener() {
// @Override
// public void onClick(View v) {
// items.remove(position);
// DeletableStringArrayAdapter.this.notifyDataSetChanged();
// }
// });
//
// // Description
// TextView descriptionView = (TextView) view.findViewById(R.id.description);
// // Update description field on focus lost
// descriptionView.addTextChangedListener(new TextWatcher() {
// @Override
// public void beforeTextChanged(CharSequence s, int start, int count, int after) {}
//
// @Override
// public void onTextChanged(CharSequence s, int start, int before, int count) {}
//
// @Override
// public void afterTextChanged(Editable s) {
// items.set(position, s.toString());
// }
// });
// descriptionView.setText(getItem(position));
//
// return view;
// }
// }
//
// Path: app/src/main/java/link/standen/michael/fatesheets/view/AdapterLinearLayout.java
// public class AdapterLinearLayout extends LinearLayout {
//
// private static final String TAG = AdapterLinearLayout.class.getName();
//
// private Adapter adapter;
// private DataSetObserver dataSetObserver = new DataSetObserver() {
// @Override
// public void onChanged() {
// super.onChanged();
// reloadChildViews();
// }
// };
//
// @TargetApi(Build.VERSION_CODES.HONEYCOMB)
// public AdapterLinearLayout(Context context, AttributeSet attrs, int defStyle) {
// super(context, attrs, defStyle);
// }
//
// public AdapterLinearLayout(Context context, AttributeSet attrs) {
// super(context, attrs);
// }
//
// public AdapterLinearLayout(Context context) {
// super(context);
// }
//
// public void setAdapter(Adapter adapter) {
// if (this.adapter == adapter){
// return;
// }
// this.adapter = adapter;
// if (adapter != null){
// adapter.registerDataSetObserver(dataSetObserver);
// }
// reloadChildViews();
// }
//
// @Override
// protected void onDetachedFromWindow() {
// super.onDetachedFromWindow();
// if (adapter != null){
// try {
// adapter.unregisterDataSetObserver(dataSetObserver);
// } catch (IllegalStateException e){
// // Log error and ignore. I think it's fine.
// Log.e(TAG, "Observer was not registered.", e);
// }
// }
// }
//
// private void reloadChildViews() {
// removeAllViewsInLayout();
//
// if (adapter == null){
// return;
// }
//
// int count = adapter.getCount();
// for (int position = 0; position < count; position++) {
// View v = adapter.getView(position, null, this);
// if (v != null){
// addView(v);
// }
// }
//
// requestLayout();
// }
// }
| import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTransaction;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import link.standen.michael.fatesheets.R;
import link.standen.michael.fatesheets.adapter.DeletableStringArrayAdapter;
import link.standen.michael.fatesheets.view.AdapterLinearLayout; | package link.standen.michael.fatesheets.fragment;
/**
* A fragment for managing a characters stunts.
*/
public class CoreCharacterEditStuntsFragment extends CharacterEditAbstractFragment {
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
return inflater.inflate(R.layout.core_character_edit_stunts, container, false);
}
@Override
public void onViewCreated(View view, Bundle savedInstanceState) {
// Stunt
Fragment childFragment = new StuntFragment();
FragmentTransaction transaction = getChildFragmentManager().beginTransaction();
transaction.replace(R.id.stunt_container, childFragment).commit();
// Extra
childFragment = new ExtraFragment();
transaction = getChildFragmentManager().beginTransaction();
transaction.replace(R.id.extra_container, childFragment).commit();
}
/**
* Class for managing stunts.
*/
public static class StuntFragment extends CharacterEditAbstractFragment {
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.character_edit_stunts_stunt, container, false);
// Stunts | // Path: app/src/main/java/link/standen/michael/fatesheets/adapter/DeletableStringArrayAdapter.java
// public class DeletableStringArrayAdapter extends ArrayAdapter<String> {
//
// private static final String TAG = DeletableStringArrayAdapter.class.getName();
//
// private final Context context;
// private final int resourceId;
// private final List<String> items;
//
// public DeletableStringArrayAdapter(@NonNull Context context, @LayoutRes int resourceId, @NonNull List<String> items) {
// super(context, resourceId, items);
//
// this.context = context;
// this.resourceId = resourceId;
// this.items = items;
// }
//
// public String getItem(int index){
// return items.get(index);
// }
//
// @NonNull
// @Override
// public View getView(final int position, @Nullable View convertView, @NonNull ViewGroup parent) {
// View view = convertView;
// if (view == null){
// LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
// view = inflater.inflate(resourceId, null);
// }
//
// view.findViewById(R.id.delete).setOnClickListener(new View.OnClickListener() {
// @Override
// public void onClick(View v) {
// items.remove(position);
// DeletableStringArrayAdapter.this.notifyDataSetChanged();
// }
// });
//
// // Description
// TextView descriptionView = (TextView) view.findViewById(R.id.description);
// // Update description field on focus lost
// descriptionView.addTextChangedListener(new TextWatcher() {
// @Override
// public void beforeTextChanged(CharSequence s, int start, int count, int after) {}
//
// @Override
// public void onTextChanged(CharSequence s, int start, int before, int count) {}
//
// @Override
// public void afterTextChanged(Editable s) {
// items.set(position, s.toString());
// }
// });
// descriptionView.setText(getItem(position));
//
// return view;
// }
// }
//
// Path: app/src/main/java/link/standen/michael/fatesheets/view/AdapterLinearLayout.java
// public class AdapterLinearLayout extends LinearLayout {
//
// private static final String TAG = AdapterLinearLayout.class.getName();
//
// private Adapter adapter;
// private DataSetObserver dataSetObserver = new DataSetObserver() {
// @Override
// public void onChanged() {
// super.onChanged();
// reloadChildViews();
// }
// };
//
// @TargetApi(Build.VERSION_CODES.HONEYCOMB)
// public AdapterLinearLayout(Context context, AttributeSet attrs, int defStyle) {
// super(context, attrs, defStyle);
// }
//
// public AdapterLinearLayout(Context context, AttributeSet attrs) {
// super(context, attrs);
// }
//
// public AdapterLinearLayout(Context context) {
// super(context);
// }
//
// public void setAdapter(Adapter adapter) {
// if (this.adapter == adapter){
// return;
// }
// this.adapter = adapter;
// if (adapter != null){
// adapter.registerDataSetObserver(dataSetObserver);
// }
// reloadChildViews();
// }
//
// @Override
// protected void onDetachedFromWindow() {
// super.onDetachedFromWindow();
// if (adapter != null){
// try {
// adapter.unregisterDataSetObserver(dataSetObserver);
// } catch (IllegalStateException e){
// // Log error and ignore. I think it's fine.
// Log.e(TAG, "Observer was not registered.", e);
// }
// }
// }
//
// private void reloadChildViews() {
// removeAllViewsInLayout();
//
// if (adapter == null){
// return;
// }
//
// int count = adapter.getCount();
// for (int position = 0; position < count; position++) {
// View v = adapter.getView(position, null, this);
// if (v != null){
// addView(v);
// }
// }
//
// requestLayout();
// }
// }
// Path: app/src/main/java/link/standen/michael/fatesheets/fragment/CoreCharacterEditStuntsFragment.java
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTransaction;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import link.standen.michael.fatesheets.R;
import link.standen.michael.fatesheets.adapter.DeletableStringArrayAdapter;
import link.standen.michael.fatesheets.view.AdapterLinearLayout;
package link.standen.michael.fatesheets.fragment;
/**
* A fragment for managing a characters stunts.
*/
public class CoreCharacterEditStuntsFragment extends CharacterEditAbstractFragment {
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
return inflater.inflate(R.layout.core_character_edit_stunts, container, false);
}
@Override
public void onViewCreated(View view, Bundle savedInstanceState) {
// Stunt
Fragment childFragment = new StuntFragment();
FragmentTransaction transaction = getChildFragmentManager().beginTransaction();
transaction.replace(R.id.stunt_container, childFragment).commit();
// Extra
childFragment = new ExtraFragment();
transaction = getChildFragmentManager().beginTransaction();
transaction.replace(R.id.extra_container, childFragment).commit();
}
/**
* Class for managing stunts.
*/
public static class StuntFragment extends CharacterEditAbstractFragment {
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.character_edit_stunts_stunt, container, false);
// Stunts | final DeletableStringArrayAdapter stuntListAdapter = new DeletableStringArrayAdapter(getContext(), |
ScreamingHawk/fate-sheets | app/src/main/java/link/standen/michael/fatesheets/fragment/CoreCharacterEditStuntsFragment.java | // Path: app/src/main/java/link/standen/michael/fatesheets/adapter/DeletableStringArrayAdapter.java
// public class DeletableStringArrayAdapter extends ArrayAdapter<String> {
//
// private static final String TAG = DeletableStringArrayAdapter.class.getName();
//
// private final Context context;
// private final int resourceId;
// private final List<String> items;
//
// public DeletableStringArrayAdapter(@NonNull Context context, @LayoutRes int resourceId, @NonNull List<String> items) {
// super(context, resourceId, items);
//
// this.context = context;
// this.resourceId = resourceId;
// this.items = items;
// }
//
// public String getItem(int index){
// return items.get(index);
// }
//
// @NonNull
// @Override
// public View getView(final int position, @Nullable View convertView, @NonNull ViewGroup parent) {
// View view = convertView;
// if (view == null){
// LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
// view = inflater.inflate(resourceId, null);
// }
//
// view.findViewById(R.id.delete).setOnClickListener(new View.OnClickListener() {
// @Override
// public void onClick(View v) {
// items.remove(position);
// DeletableStringArrayAdapter.this.notifyDataSetChanged();
// }
// });
//
// // Description
// TextView descriptionView = (TextView) view.findViewById(R.id.description);
// // Update description field on focus lost
// descriptionView.addTextChangedListener(new TextWatcher() {
// @Override
// public void beforeTextChanged(CharSequence s, int start, int count, int after) {}
//
// @Override
// public void onTextChanged(CharSequence s, int start, int before, int count) {}
//
// @Override
// public void afterTextChanged(Editable s) {
// items.set(position, s.toString());
// }
// });
// descriptionView.setText(getItem(position));
//
// return view;
// }
// }
//
// Path: app/src/main/java/link/standen/michael/fatesheets/view/AdapterLinearLayout.java
// public class AdapterLinearLayout extends LinearLayout {
//
// private static final String TAG = AdapterLinearLayout.class.getName();
//
// private Adapter adapter;
// private DataSetObserver dataSetObserver = new DataSetObserver() {
// @Override
// public void onChanged() {
// super.onChanged();
// reloadChildViews();
// }
// };
//
// @TargetApi(Build.VERSION_CODES.HONEYCOMB)
// public AdapterLinearLayout(Context context, AttributeSet attrs, int defStyle) {
// super(context, attrs, defStyle);
// }
//
// public AdapterLinearLayout(Context context, AttributeSet attrs) {
// super(context, attrs);
// }
//
// public AdapterLinearLayout(Context context) {
// super(context);
// }
//
// public void setAdapter(Adapter adapter) {
// if (this.adapter == adapter){
// return;
// }
// this.adapter = adapter;
// if (adapter != null){
// adapter.registerDataSetObserver(dataSetObserver);
// }
// reloadChildViews();
// }
//
// @Override
// protected void onDetachedFromWindow() {
// super.onDetachedFromWindow();
// if (adapter != null){
// try {
// adapter.unregisterDataSetObserver(dataSetObserver);
// } catch (IllegalStateException e){
// // Log error and ignore. I think it's fine.
// Log.e(TAG, "Observer was not registered.", e);
// }
// }
// }
//
// private void reloadChildViews() {
// removeAllViewsInLayout();
//
// if (adapter == null){
// return;
// }
//
// int count = adapter.getCount();
// for (int position = 0; position < count; position++) {
// View v = adapter.getView(position, null, this);
// if (v != null){
// addView(v);
// }
// }
//
// requestLayout();
// }
// }
| import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTransaction;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import link.standen.michael.fatesheets.R;
import link.standen.michael.fatesheets.adapter.DeletableStringArrayAdapter;
import link.standen.michael.fatesheets.view.AdapterLinearLayout; | package link.standen.michael.fatesheets.fragment;
/**
* A fragment for managing a characters stunts.
*/
public class CoreCharacterEditStuntsFragment extends CharacterEditAbstractFragment {
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
return inflater.inflate(R.layout.core_character_edit_stunts, container, false);
}
@Override
public void onViewCreated(View view, Bundle savedInstanceState) {
// Stunt
Fragment childFragment = new StuntFragment();
FragmentTransaction transaction = getChildFragmentManager().beginTransaction();
transaction.replace(R.id.stunt_container, childFragment).commit();
// Extra
childFragment = new ExtraFragment();
transaction = getChildFragmentManager().beginTransaction();
transaction.replace(R.id.extra_container, childFragment).commit();
}
/**
* Class for managing stunts.
*/
public static class StuntFragment extends CharacterEditAbstractFragment {
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.character_edit_stunts_stunt, container, false);
// Stunts
final DeletableStringArrayAdapter stuntListAdapter = new DeletableStringArrayAdapter(getContext(),
R.layout.character_edit_stunts_list_item, getCharacter().getStunts()); | // Path: app/src/main/java/link/standen/michael/fatesheets/adapter/DeletableStringArrayAdapter.java
// public class DeletableStringArrayAdapter extends ArrayAdapter<String> {
//
// private static final String TAG = DeletableStringArrayAdapter.class.getName();
//
// private final Context context;
// private final int resourceId;
// private final List<String> items;
//
// public DeletableStringArrayAdapter(@NonNull Context context, @LayoutRes int resourceId, @NonNull List<String> items) {
// super(context, resourceId, items);
//
// this.context = context;
// this.resourceId = resourceId;
// this.items = items;
// }
//
// public String getItem(int index){
// return items.get(index);
// }
//
// @NonNull
// @Override
// public View getView(final int position, @Nullable View convertView, @NonNull ViewGroup parent) {
// View view = convertView;
// if (view == null){
// LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
// view = inflater.inflate(resourceId, null);
// }
//
// view.findViewById(R.id.delete).setOnClickListener(new View.OnClickListener() {
// @Override
// public void onClick(View v) {
// items.remove(position);
// DeletableStringArrayAdapter.this.notifyDataSetChanged();
// }
// });
//
// // Description
// TextView descriptionView = (TextView) view.findViewById(R.id.description);
// // Update description field on focus lost
// descriptionView.addTextChangedListener(new TextWatcher() {
// @Override
// public void beforeTextChanged(CharSequence s, int start, int count, int after) {}
//
// @Override
// public void onTextChanged(CharSequence s, int start, int before, int count) {}
//
// @Override
// public void afterTextChanged(Editable s) {
// items.set(position, s.toString());
// }
// });
// descriptionView.setText(getItem(position));
//
// return view;
// }
// }
//
// Path: app/src/main/java/link/standen/michael/fatesheets/view/AdapterLinearLayout.java
// public class AdapterLinearLayout extends LinearLayout {
//
// private static final String TAG = AdapterLinearLayout.class.getName();
//
// private Adapter adapter;
// private DataSetObserver dataSetObserver = new DataSetObserver() {
// @Override
// public void onChanged() {
// super.onChanged();
// reloadChildViews();
// }
// };
//
// @TargetApi(Build.VERSION_CODES.HONEYCOMB)
// public AdapterLinearLayout(Context context, AttributeSet attrs, int defStyle) {
// super(context, attrs, defStyle);
// }
//
// public AdapterLinearLayout(Context context, AttributeSet attrs) {
// super(context, attrs);
// }
//
// public AdapterLinearLayout(Context context) {
// super(context);
// }
//
// public void setAdapter(Adapter adapter) {
// if (this.adapter == adapter){
// return;
// }
// this.adapter = adapter;
// if (adapter != null){
// adapter.registerDataSetObserver(dataSetObserver);
// }
// reloadChildViews();
// }
//
// @Override
// protected void onDetachedFromWindow() {
// super.onDetachedFromWindow();
// if (adapter != null){
// try {
// adapter.unregisterDataSetObserver(dataSetObserver);
// } catch (IllegalStateException e){
// // Log error and ignore. I think it's fine.
// Log.e(TAG, "Observer was not registered.", e);
// }
// }
// }
//
// private void reloadChildViews() {
// removeAllViewsInLayout();
//
// if (adapter == null){
// return;
// }
//
// int count = adapter.getCount();
// for (int position = 0; position < count; position++) {
// View v = adapter.getView(position, null, this);
// if (v != null){
// addView(v);
// }
// }
//
// requestLayout();
// }
// }
// Path: app/src/main/java/link/standen/michael/fatesheets/fragment/CoreCharacterEditStuntsFragment.java
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTransaction;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import link.standen.michael.fatesheets.R;
import link.standen.michael.fatesheets.adapter.DeletableStringArrayAdapter;
import link.standen.michael.fatesheets.view.AdapterLinearLayout;
package link.standen.michael.fatesheets.fragment;
/**
* A fragment for managing a characters stunts.
*/
public class CoreCharacterEditStuntsFragment extends CharacterEditAbstractFragment {
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
return inflater.inflate(R.layout.core_character_edit_stunts, container, false);
}
@Override
public void onViewCreated(View view, Bundle savedInstanceState) {
// Stunt
Fragment childFragment = new StuntFragment();
FragmentTransaction transaction = getChildFragmentManager().beginTransaction();
transaction.replace(R.id.stunt_container, childFragment).commit();
// Extra
childFragment = new ExtraFragment();
transaction = getChildFragmentManager().beginTransaction();
transaction.replace(R.id.extra_container, childFragment).commit();
}
/**
* Class for managing stunts.
*/
public static class StuntFragment extends CharacterEditAbstractFragment {
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.character_edit_stunts_stunt, container, false);
// Stunts
final DeletableStringArrayAdapter stuntListAdapter = new DeletableStringArrayAdapter(getContext(),
R.layout.character_edit_stunts_list_item, getCharacter().getStunts()); | ((AdapterLinearLayout) rootView.findViewById(R.id.stunts_list)).setAdapter(stuntListAdapter); |
ScreamingHawk/fate-sheets | app/src/main/java/link/standen/michael/fatesheets/adapter/SkillArrayAdapter.java | // Path: app/src/main/java/link/standen/michael/fatesheets/model/Skill.java
// public class Skill implements Serializable, Comparable<Skill> {
//
// private Integer value;
// private String description;
//
// public Skill(Integer value){
// this(value, "");
// }
//
// public Skill(Integer value, String description){
// this.value = value;
// this.description = description;
// }
//
// public Integer getValue() {
// return value;
// }
//
// public void setValue(Integer value) {
// this.value = value;
// }
//
// public String getDescription() {
// return description;
// }
//
// public void setDescription(String description) {
// this.description = description;
// }
//
// @Override
// public int compareTo(@NonNull Skill other) {
// if (this.getValue().equals(other.getValue())){
// return this.getDescription().compareTo(other.getDescription());
// }
// return this.getValue().compareTo(other.getValue());
// }
// }
//
// Path: app/src/main/java/link/standen/michael/fatesheets/util/SkillsHelper.java
// public final class SkillsHelper extends JsonFileHelper {
//
// private static final String SKILLS_STORAGE = "SKILLS_LIST";
//
// private SkillsHelper(){}
//
// /**
// * Saves skills to local storage.
// * @return True if the write operation was successful, false otherwise.
// */
// public static boolean saveSkills(Context context, List<String> skills) {
// return saveJsonToFile(context, new Gson().toJson(skills), SKILLS_STORAGE);
// }
//
// /**
// * Gets the saved skills list.
// * If no skills list has been saved, gets the default skill list.
// */
// @SuppressWarnings("unchecked")
// @Nullable
// public static List<String> getSkills(Context context) {
// String json = getJsonFromFile(context, SKILLS_STORAGE);
//
// if (json == null) {
// return getDefaultSkills(context);
// }
//
// return new Gson().fromJson(json, List.class);
// }
//
// /**
// * Gets the default skill list.
// */
// public static List<String> getDefaultSkills(Context context){
// return Arrays.asList(context.getResources().getStringArray(R.array.core_skills));
// }
//
// }
| import android.content.Context;
import android.support.annotation.LayoutRes;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Spinner;
import android.widget.TextView;
import java.util.List;
import link.standen.michael.fatesheets.R;
import link.standen.michael.fatesheets.model.Skill;
import link.standen.michael.fatesheets.util.SkillsHelper; | package link.standen.michael.fatesheets.adapter;
/**
* Manages a list of character skills.
*/
public class SkillArrayAdapter extends ArrayAdapter<Skill> {
private static final String TAG = SkillArrayAdapter.class.getName();
private final Context context;
private final int resourceId;
private final List<Skill> items;
private static List<String> skills;
public SkillArrayAdapter(@NonNull Context context, @LayoutRes int resourceId, @NonNull List<Skill> items) {
super(context, resourceId, items);
this.context = context;
this.resourceId = resourceId;
this.items = items;
// Refresh skills list | // Path: app/src/main/java/link/standen/michael/fatesheets/model/Skill.java
// public class Skill implements Serializable, Comparable<Skill> {
//
// private Integer value;
// private String description;
//
// public Skill(Integer value){
// this(value, "");
// }
//
// public Skill(Integer value, String description){
// this.value = value;
// this.description = description;
// }
//
// public Integer getValue() {
// return value;
// }
//
// public void setValue(Integer value) {
// this.value = value;
// }
//
// public String getDescription() {
// return description;
// }
//
// public void setDescription(String description) {
// this.description = description;
// }
//
// @Override
// public int compareTo(@NonNull Skill other) {
// if (this.getValue().equals(other.getValue())){
// return this.getDescription().compareTo(other.getDescription());
// }
// return this.getValue().compareTo(other.getValue());
// }
// }
//
// Path: app/src/main/java/link/standen/michael/fatesheets/util/SkillsHelper.java
// public final class SkillsHelper extends JsonFileHelper {
//
// private static final String SKILLS_STORAGE = "SKILLS_LIST";
//
// private SkillsHelper(){}
//
// /**
// * Saves skills to local storage.
// * @return True if the write operation was successful, false otherwise.
// */
// public static boolean saveSkills(Context context, List<String> skills) {
// return saveJsonToFile(context, new Gson().toJson(skills), SKILLS_STORAGE);
// }
//
// /**
// * Gets the saved skills list.
// * If no skills list has been saved, gets the default skill list.
// */
// @SuppressWarnings("unchecked")
// @Nullable
// public static List<String> getSkills(Context context) {
// String json = getJsonFromFile(context, SKILLS_STORAGE);
//
// if (json == null) {
// return getDefaultSkills(context);
// }
//
// return new Gson().fromJson(json, List.class);
// }
//
// /**
// * Gets the default skill list.
// */
// public static List<String> getDefaultSkills(Context context){
// return Arrays.asList(context.getResources().getStringArray(R.array.core_skills));
// }
//
// }
// Path: app/src/main/java/link/standen/michael/fatesheets/adapter/SkillArrayAdapter.java
import android.content.Context;
import android.support.annotation.LayoutRes;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Spinner;
import android.widget.TextView;
import java.util.List;
import link.standen.michael.fatesheets.R;
import link.standen.michael.fatesheets.model.Skill;
import link.standen.michael.fatesheets.util.SkillsHelper;
package link.standen.michael.fatesheets.adapter;
/**
* Manages a list of character skills.
*/
public class SkillArrayAdapter extends ArrayAdapter<Skill> {
private static final String TAG = SkillArrayAdapter.class.getName();
private final Context context;
private final int resourceId;
private final List<Skill> items;
private static List<String> skills;
public SkillArrayAdapter(@NonNull Context context, @LayoutRes int resourceId, @NonNull List<Skill> items) {
super(context, resourceId, items);
this.context = context;
this.resourceId = resourceId;
this.items = items;
// Refresh skills list | skills = SkillsHelper.getSkills(context); |
ScreamingHawk/fate-sheets | app/src/main/java/link/standen/michael/fatesheets/fragment/FAECharacterEditStuntsFragment.java | // Path: app/src/main/java/link/standen/michael/fatesheets/adapter/DeletableStringArrayAdapter.java
// public class DeletableStringArrayAdapter extends ArrayAdapter<String> {
//
// private static final String TAG = DeletableStringArrayAdapter.class.getName();
//
// private final Context context;
// private final int resourceId;
// private final List<String> items;
//
// public DeletableStringArrayAdapter(@NonNull Context context, @LayoutRes int resourceId, @NonNull List<String> items) {
// super(context, resourceId, items);
//
// this.context = context;
// this.resourceId = resourceId;
// this.items = items;
// }
//
// public String getItem(int index){
// return items.get(index);
// }
//
// @NonNull
// @Override
// public View getView(final int position, @Nullable View convertView, @NonNull ViewGroup parent) {
// View view = convertView;
// if (view == null){
// LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
// view = inflater.inflate(resourceId, null);
// }
//
// view.findViewById(R.id.delete).setOnClickListener(new View.OnClickListener() {
// @Override
// public void onClick(View v) {
// items.remove(position);
// DeletableStringArrayAdapter.this.notifyDataSetChanged();
// }
// });
//
// // Description
// TextView descriptionView = (TextView) view.findViewById(R.id.description);
// // Update description field on focus lost
// descriptionView.addTextChangedListener(new TextWatcher() {
// @Override
// public void beforeTextChanged(CharSequence s, int start, int count, int after) {}
//
// @Override
// public void onTextChanged(CharSequence s, int start, int before, int count) {}
//
// @Override
// public void afterTextChanged(Editable s) {
// items.set(position, s.toString());
// }
// });
// descriptionView.setText(getItem(position));
//
// return view;
// }
// }
//
// Path: app/src/main/java/link/standen/michael/fatesheets/view/AdapterLinearLayout.java
// public class AdapterLinearLayout extends LinearLayout {
//
// private static final String TAG = AdapterLinearLayout.class.getName();
//
// private Adapter adapter;
// private DataSetObserver dataSetObserver = new DataSetObserver() {
// @Override
// public void onChanged() {
// super.onChanged();
// reloadChildViews();
// }
// };
//
// @TargetApi(Build.VERSION_CODES.HONEYCOMB)
// public AdapterLinearLayout(Context context, AttributeSet attrs, int defStyle) {
// super(context, attrs, defStyle);
// }
//
// public AdapterLinearLayout(Context context, AttributeSet attrs) {
// super(context, attrs);
// }
//
// public AdapterLinearLayout(Context context) {
// super(context);
// }
//
// public void setAdapter(Adapter adapter) {
// if (this.adapter == adapter){
// return;
// }
// this.adapter = adapter;
// if (adapter != null){
// adapter.registerDataSetObserver(dataSetObserver);
// }
// reloadChildViews();
// }
//
// @Override
// protected void onDetachedFromWindow() {
// super.onDetachedFromWindow();
// if (adapter != null){
// try {
// adapter.unregisterDataSetObserver(dataSetObserver);
// } catch (IllegalStateException e){
// // Log error and ignore. I think it's fine.
// Log.e(TAG, "Observer was not registered.", e);
// }
// }
// }
//
// private void reloadChildViews() {
// removeAllViewsInLayout();
//
// if (adapter == null){
// return;
// }
//
// int count = adapter.getCount();
// for (int position = 0; position < count; position++) {
// View v = adapter.getView(position, null, this);
// if (v != null){
// addView(v);
// }
// }
//
// requestLayout();
// }
// }
| import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTransaction;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import link.standen.michael.fatesheets.R;
import link.standen.michael.fatesheets.adapter.DeletableStringArrayAdapter;
import link.standen.michael.fatesheets.view.AdapterLinearLayout; | package link.standen.michael.fatesheets.fragment;
/**
* A fragment for managing a characters stunts.
*/
public class FAECharacterEditStuntsFragment extends CharacterEditAbstractFragment {
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
return inflater.inflate(R.layout.fae_character_edit_stunts, container, false);
}
@Override
public void onViewCreated(View view, Bundle savedInstanceState) {
// Stunt
Fragment childFragment = new StuntFragment();
FragmentTransaction transaction = getChildFragmentManager().beginTransaction();
transaction.replace(R.id.stunt_container, childFragment).commit();
}
/**
* Class for managing stunts.
*/
public static class StuntFragment extends CharacterEditAbstractFragment {
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.character_edit_stunts_stunt, container, false);
// Stunts | // Path: app/src/main/java/link/standen/michael/fatesheets/adapter/DeletableStringArrayAdapter.java
// public class DeletableStringArrayAdapter extends ArrayAdapter<String> {
//
// private static final String TAG = DeletableStringArrayAdapter.class.getName();
//
// private final Context context;
// private final int resourceId;
// private final List<String> items;
//
// public DeletableStringArrayAdapter(@NonNull Context context, @LayoutRes int resourceId, @NonNull List<String> items) {
// super(context, resourceId, items);
//
// this.context = context;
// this.resourceId = resourceId;
// this.items = items;
// }
//
// public String getItem(int index){
// return items.get(index);
// }
//
// @NonNull
// @Override
// public View getView(final int position, @Nullable View convertView, @NonNull ViewGroup parent) {
// View view = convertView;
// if (view == null){
// LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
// view = inflater.inflate(resourceId, null);
// }
//
// view.findViewById(R.id.delete).setOnClickListener(new View.OnClickListener() {
// @Override
// public void onClick(View v) {
// items.remove(position);
// DeletableStringArrayAdapter.this.notifyDataSetChanged();
// }
// });
//
// // Description
// TextView descriptionView = (TextView) view.findViewById(R.id.description);
// // Update description field on focus lost
// descriptionView.addTextChangedListener(new TextWatcher() {
// @Override
// public void beforeTextChanged(CharSequence s, int start, int count, int after) {}
//
// @Override
// public void onTextChanged(CharSequence s, int start, int before, int count) {}
//
// @Override
// public void afterTextChanged(Editable s) {
// items.set(position, s.toString());
// }
// });
// descriptionView.setText(getItem(position));
//
// return view;
// }
// }
//
// Path: app/src/main/java/link/standen/michael/fatesheets/view/AdapterLinearLayout.java
// public class AdapterLinearLayout extends LinearLayout {
//
// private static final String TAG = AdapterLinearLayout.class.getName();
//
// private Adapter adapter;
// private DataSetObserver dataSetObserver = new DataSetObserver() {
// @Override
// public void onChanged() {
// super.onChanged();
// reloadChildViews();
// }
// };
//
// @TargetApi(Build.VERSION_CODES.HONEYCOMB)
// public AdapterLinearLayout(Context context, AttributeSet attrs, int defStyle) {
// super(context, attrs, defStyle);
// }
//
// public AdapterLinearLayout(Context context, AttributeSet attrs) {
// super(context, attrs);
// }
//
// public AdapterLinearLayout(Context context) {
// super(context);
// }
//
// public void setAdapter(Adapter adapter) {
// if (this.adapter == adapter){
// return;
// }
// this.adapter = adapter;
// if (adapter != null){
// adapter.registerDataSetObserver(dataSetObserver);
// }
// reloadChildViews();
// }
//
// @Override
// protected void onDetachedFromWindow() {
// super.onDetachedFromWindow();
// if (adapter != null){
// try {
// adapter.unregisterDataSetObserver(dataSetObserver);
// } catch (IllegalStateException e){
// // Log error and ignore. I think it's fine.
// Log.e(TAG, "Observer was not registered.", e);
// }
// }
// }
//
// private void reloadChildViews() {
// removeAllViewsInLayout();
//
// if (adapter == null){
// return;
// }
//
// int count = adapter.getCount();
// for (int position = 0; position < count; position++) {
// View v = adapter.getView(position, null, this);
// if (v != null){
// addView(v);
// }
// }
//
// requestLayout();
// }
// }
// Path: app/src/main/java/link/standen/michael/fatesheets/fragment/FAECharacterEditStuntsFragment.java
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTransaction;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import link.standen.michael.fatesheets.R;
import link.standen.michael.fatesheets.adapter.DeletableStringArrayAdapter;
import link.standen.michael.fatesheets.view.AdapterLinearLayout;
package link.standen.michael.fatesheets.fragment;
/**
* A fragment for managing a characters stunts.
*/
public class FAECharacterEditStuntsFragment extends CharacterEditAbstractFragment {
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
return inflater.inflate(R.layout.fae_character_edit_stunts, container, false);
}
@Override
public void onViewCreated(View view, Bundle savedInstanceState) {
// Stunt
Fragment childFragment = new StuntFragment();
FragmentTransaction transaction = getChildFragmentManager().beginTransaction();
transaction.replace(R.id.stunt_container, childFragment).commit();
}
/**
* Class for managing stunts.
*/
public static class StuntFragment extends CharacterEditAbstractFragment {
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.character_edit_stunts_stunt, container, false);
// Stunts | final DeletableStringArrayAdapter stuntListAdapter = new DeletableStringArrayAdapter(getContext(), |
ScreamingHawk/fate-sheets | app/src/main/java/link/standen/michael/fatesheets/fragment/FAECharacterEditStuntsFragment.java | // Path: app/src/main/java/link/standen/michael/fatesheets/adapter/DeletableStringArrayAdapter.java
// public class DeletableStringArrayAdapter extends ArrayAdapter<String> {
//
// private static final String TAG = DeletableStringArrayAdapter.class.getName();
//
// private final Context context;
// private final int resourceId;
// private final List<String> items;
//
// public DeletableStringArrayAdapter(@NonNull Context context, @LayoutRes int resourceId, @NonNull List<String> items) {
// super(context, resourceId, items);
//
// this.context = context;
// this.resourceId = resourceId;
// this.items = items;
// }
//
// public String getItem(int index){
// return items.get(index);
// }
//
// @NonNull
// @Override
// public View getView(final int position, @Nullable View convertView, @NonNull ViewGroup parent) {
// View view = convertView;
// if (view == null){
// LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
// view = inflater.inflate(resourceId, null);
// }
//
// view.findViewById(R.id.delete).setOnClickListener(new View.OnClickListener() {
// @Override
// public void onClick(View v) {
// items.remove(position);
// DeletableStringArrayAdapter.this.notifyDataSetChanged();
// }
// });
//
// // Description
// TextView descriptionView = (TextView) view.findViewById(R.id.description);
// // Update description field on focus lost
// descriptionView.addTextChangedListener(new TextWatcher() {
// @Override
// public void beforeTextChanged(CharSequence s, int start, int count, int after) {}
//
// @Override
// public void onTextChanged(CharSequence s, int start, int before, int count) {}
//
// @Override
// public void afterTextChanged(Editable s) {
// items.set(position, s.toString());
// }
// });
// descriptionView.setText(getItem(position));
//
// return view;
// }
// }
//
// Path: app/src/main/java/link/standen/michael/fatesheets/view/AdapterLinearLayout.java
// public class AdapterLinearLayout extends LinearLayout {
//
// private static final String TAG = AdapterLinearLayout.class.getName();
//
// private Adapter adapter;
// private DataSetObserver dataSetObserver = new DataSetObserver() {
// @Override
// public void onChanged() {
// super.onChanged();
// reloadChildViews();
// }
// };
//
// @TargetApi(Build.VERSION_CODES.HONEYCOMB)
// public AdapterLinearLayout(Context context, AttributeSet attrs, int defStyle) {
// super(context, attrs, defStyle);
// }
//
// public AdapterLinearLayout(Context context, AttributeSet attrs) {
// super(context, attrs);
// }
//
// public AdapterLinearLayout(Context context) {
// super(context);
// }
//
// public void setAdapter(Adapter adapter) {
// if (this.adapter == adapter){
// return;
// }
// this.adapter = adapter;
// if (adapter != null){
// adapter.registerDataSetObserver(dataSetObserver);
// }
// reloadChildViews();
// }
//
// @Override
// protected void onDetachedFromWindow() {
// super.onDetachedFromWindow();
// if (adapter != null){
// try {
// adapter.unregisterDataSetObserver(dataSetObserver);
// } catch (IllegalStateException e){
// // Log error and ignore. I think it's fine.
// Log.e(TAG, "Observer was not registered.", e);
// }
// }
// }
//
// private void reloadChildViews() {
// removeAllViewsInLayout();
//
// if (adapter == null){
// return;
// }
//
// int count = adapter.getCount();
// for (int position = 0; position < count; position++) {
// View v = adapter.getView(position, null, this);
// if (v != null){
// addView(v);
// }
// }
//
// requestLayout();
// }
// }
| import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTransaction;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import link.standen.michael.fatesheets.R;
import link.standen.michael.fatesheets.adapter.DeletableStringArrayAdapter;
import link.standen.michael.fatesheets.view.AdapterLinearLayout; | package link.standen.michael.fatesheets.fragment;
/**
* A fragment for managing a characters stunts.
*/
public class FAECharacterEditStuntsFragment extends CharacterEditAbstractFragment {
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
return inflater.inflate(R.layout.fae_character_edit_stunts, container, false);
}
@Override
public void onViewCreated(View view, Bundle savedInstanceState) {
// Stunt
Fragment childFragment = new StuntFragment();
FragmentTransaction transaction = getChildFragmentManager().beginTransaction();
transaction.replace(R.id.stunt_container, childFragment).commit();
}
/**
* Class for managing stunts.
*/
public static class StuntFragment extends CharacterEditAbstractFragment {
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.character_edit_stunts_stunt, container, false);
// Stunts
final DeletableStringArrayAdapter stuntListAdapter = new DeletableStringArrayAdapter(getContext(),
R.layout.character_edit_stunts_list_item, getCharacter().getStunts()); | // Path: app/src/main/java/link/standen/michael/fatesheets/adapter/DeletableStringArrayAdapter.java
// public class DeletableStringArrayAdapter extends ArrayAdapter<String> {
//
// private static final String TAG = DeletableStringArrayAdapter.class.getName();
//
// private final Context context;
// private final int resourceId;
// private final List<String> items;
//
// public DeletableStringArrayAdapter(@NonNull Context context, @LayoutRes int resourceId, @NonNull List<String> items) {
// super(context, resourceId, items);
//
// this.context = context;
// this.resourceId = resourceId;
// this.items = items;
// }
//
// public String getItem(int index){
// return items.get(index);
// }
//
// @NonNull
// @Override
// public View getView(final int position, @Nullable View convertView, @NonNull ViewGroup parent) {
// View view = convertView;
// if (view == null){
// LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
// view = inflater.inflate(resourceId, null);
// }
//
// view.findViewById(R.id.delete).setOnClickListener(new View.OnClickListener() {
// @Override
// public void onClick(View v) {
// items.remove(position);
// DeletableStringArrayAdapter.this.notifyDataSetChanged();
// }
// });
//
// // Description
// TextView descriptionView = (TextView) view.findViewById(R.id.description);
// // Update description field on focus lost
// descriptionView.addTextChangedListener(new TextWatcher() {
// @Override
// public void beforeTextChanged(CharSequence s, int start, int count, int after) {}
//
// @Override
// public void onTextChanged(CharSequence s, int start, int before, int count) {}
//
// @Override
// public void afterTextChanged(Editable s) {
// items.set(position, s.toString());
// }
// });
// descriptionView.setText(getItem(position));
//
// return view;
// }
// }
//
// Path: app/src/main/java/link/standen/michael/fatesheets/view/AdapterLinearLayout.java
// public class AdapterLinearLayout extends LinearLayout {
//
// private static final String TAG = AdapterLinearLayout.class.getName();
//
// private Adapter adapter;
// private DataSetObserver dataSetObserver = new DataSetObserver() {
// @Override
// public void onChanged() {
// super.onChanged();
// reloadChildViews();
// }
// };
//
// @TargetApi(Build.VERSION_CODES.HONEYCOMB)
// public AdapterLinearLayout(Context context, AttributeSet attrs, int defStyle) {
// super(context, attrs, defStyle);
// }
//
// public AdapterLinearLayout(Context context, AttributeSet attrs) {
// super(context, attrs);
// }
//
// public AdapterLinearLayout(Context context) {
// super(context);
// }
//
// public void setAdapter(Adapter adapter) {
// if (this.adapter == adapter){
// return;
// }
// this.adapter = adapter;
// if (adapter != null){
// adapter.registerDataSetObserver(dataSetObserver);
// }
// reloadChildViews();
// }
//
// @Override
// protected void onDetachedFromWindow() {
// super.onDetachedFromWindow();
// if (adapter != null){
// try {
// adapter.unregisterDataSetObserver(dataSetObserver);
// } catch (IllegalStateException e){
// // Log error and ignore. I think it's fine.
// Log.e(TAG, "Observer was not registered.", e);
// }
// }
// }
//
// private void reloadChildViews() {
// removeAllViewsInLayout();
//
// if (adapter == null){
// return;
// }
//
// int count = adapter.getCount();
// for (int position = 0; position < count; position++) {
// View v = adapter.getView(position, null, this);
// if (v != null){
// addView(v);
// }
// }
//
// requestLayout();
// }
// }
// Path: app/src/main/java/link/standen/michael/fatesheets/fragment/FAECharacterEditStuntsFragment.java
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTransaction;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import link.standen.michael.fatesheets.R;
import link.standen.michael.fatesheets.adapter.DeletableStringArrayAdapter;
import link.standen.michael.fatesheets.view.AdapterLinearLayout;
package link.standen.michael.fatesheets.fragment;
/**
* A fragment for managing a characters stunts.
*/
public class FAECharacterEditStuntsFragment extends CharacterEditAbstractFragment {
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
return inflater.inflate(R.layout.fae_character_edit_stunts, container, false);
}
@Override
public void onViewCreated(View view, Bundle savedInstanceState) {
// Stunt
Fragment childFragment = new StuntFragment();
FragmentTransaction transaction = getChildFragmentManager().beginTransaction();
transaction.replace(R.id.stunt_container, childFragment).commit();
}
/**
* Class for managing stunts.
*/
public static class StuntFragment extends CharacterEditAbstractFragment {
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.character_edit_stunts_stunt, container, false);
// Stunts
final DeletableStringArrayAdapter stuntListAdapter = new DeletableStringArrayAdapter(getContext(),
R.layout.character_edit_stunts_list_item, getCharacter().getStunts()); | ((AdapterLinearLayout) rootView.findViewById(R.id.stunts_list)).setAdapter(stuntListAdapter); |
ScreamingHawk/fate-sheets | app/src/main/java/link/standen/michael/fatesheets/activity/SharedMenuActivity.java | // Path: app/src/main/java/link/standen/michael/fatesheets/util/DiceClickListener.java
// public final class DiceClickListener implements View.OnClickListener {
//
// private final Resources resources;
// private final Random random;
//
// /**
// * A shared list of rolls for persistence.
// */
// private static List<int[]> rolls = new ArrayList<>();
//
// public DiceClickListener(Resources resources){
// this.resources = resources;
// this.random = new Random();
// }
//
// @Override
// public void onClick(View view) {
// // Roll dice
// int[] roll = new int[4];
// int total = 0;
// StringBuilder bob = new StringBuilder("[");
// for (int i = 0; i < roll.length; i++) {
// roll[i] = random.nextInt(3) - 1;
// total += roll[i];
// // Display string
// if (i > 0){
// bob.append(" ");
// }
// bob.append(formatRoll(roll[i]));
// }
// bob.append("]");
// rolls.add(roll);
//
// Snackbar.make(view, resources.getString(R.string.toast_rolled, formatRoll(total),
// ladderResult(total), bob.toString()), Snackbar.LENGTH_INDEFINITE)
// .setAction("Action", null).show();
// }
//
// /**
// * Convert the integer to a string for display purposes.
// */
// private String formatRoll(int roll){
// if (roll > 0){
// return "+"+roll;
// }
// return ""+roll;
// }
//
// private String[] ladder;
//
// /**
// * Get the ladder string result from the roll.
// */
// private String ladderResult(int roll){
// // Init ladder
// if (ladder == null){
// ladder = resources.getStringArray(R.array.roll_ladder);
// }
// // Convert roll to array index location
// roll += 2;
// if (roll < 0){
// // Lowest result
// roll = 0;
// } else if (roll >= ladder.length){
// // Highest result
// roll = ladder.length - 1;
// }
// return ladder[roll];
// }
// }
| import android.content.Intent;
import android.net.Uri;
import android.os.Handler;
import android.support.design.widget.FloatingActionButton;
import android.support.v7.app.AppCompatActivity;
import android.view.Menu;
import android.view.MenuItem;
import link.standen.michael.fatesheets.R;
import link.standen.michael.fatesheets.util.DiceClickListener; | package link.standen.michael.fatesheets.activity;
/**
* An abstract class that handles the menu items shared across activities.
*/
public abstract class SharedMenuActivity extends AppCompatActivity {
private static final long FOCUS_PAUSE = 500;
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_shared_activity, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_credits) {
startActivity(new Intent(this, CreditsActivity.class));
return true;
} else if (id == R.id.action_docs) {
startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("https://fate-srd.com/")));
return true;
} else if (id == R.id.action_edit_skills) {
startActivity(new Intent(this, EditSkillsActivity.class));
return true;
}
return super.onOptionsItemSelected(item);
}
protected void setupDiceFAB() {
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.dice_fab); | // Path: app/src/main/java/link/standen/michael/fatesheets/util/DiceClickListener.java
// public final class DiceClickListener implements View.OnClickListener {
//
// private final Resources resources;
// private final Random random;
//
// /**
// * A shared list of rolls for persistence.
// */
// private static List<int[]> rolls = new ArrayList<>();
//
// public DiceClickListener(Resources resources){
// this.resources = resources;
// this.random = new Random();
// }
//
// @Override
// public void onClick(View view) {
// // Roll dice
// int[] roll = new int[4];
// int total = 0;
// StringBuilder bob = new StringBuilder("[");
// for (int i = 0; i < roll.length; i++) {
// roll[i] = random.nextInt(3) - 1;
// total += roll[i];
// // Display string
// if (i > 0){
// bob.append(" ");
// }
// bob.append(formatRoll(roll[i]));
// }
// bob.append("]");
// rolls.add(roll);
//
// Snackbar.make(view, resources.getString(R.string.toast_rolled, formatRoll(total),
// ladderResult(total), bob.toString()), Snackbar.LENGTH_INDEFINITE)
// .setAction("Action", null).show();
// }
//
// /**
// * Convert the integer to a string for display purposes.
// */
// private String formatRoll(int roll){
// if (roll > 0){
// return "+"+roll;
// }
// return ""+roll;
// }
//
// private String[] ladder;
//
// /**
// * Get the ladder string result from the roll.
// */
// private String ladderResult(int roll){
// // Init ladder
// if (ladder == null){
// ladder = resources.getStringArray(R.array.roll_ladder);
// }
// // Convert roll to array index location
// roll += 2;
// if (roll < 0){
// // Lowest result
// roll = 0;
// } else if (roll >= ladder.length){
// // Highest result
// roll = ladder.length - 1;
// }
// return ladder[roll];
// }
// }
// Path: app/src/main/java/link/standen/michael/fatesheets/activity/SharedMenuActivity.java
import android.content.Intent;
import android.net.Uri;
import android.os.Handler;
import android.support.design.widget.FloatingActionButton;
import android.support.v7.app.AppCompatActivity;
import android.view.Menu;
import android.view.MenuItem;
import link.standen.michael.fatesheets.R;
import link.standen.michael.fatesheets.util.DiceClickListener;
package link.standen.michael.fatesheets.activity;
/**
* An abstract class that handles the menu items shared across activities.
*/
public abstract class SharedMenuActivity extends AppCompatActivity {
private static final long FOCUS_PAUSE = 500;
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_shared_activity, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_credits) {
startActivity(new Intent(this, CreditsActivity.class));
return true;
} else if (id == R.id.action_docs) {
startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("https://fate-srd.com/")));
return true;
} else if (id == R.id.action_edit_skills) {
startActivity(new Intent(this, EditSkillsActivity.class));
return true;
}
return super.onOptionsItemSelected(item);
}
protected void setupDiceFAB() {
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.dice_fab); | fab.setOnClickListener(new DiceClickListener(getResources())); |
ScreamingHawk/fate-sheets | app/src/main/java/link/standen/michael/fatesheets/fragment/CharacterEditDescriptionFragment.java | // Path: app/src/main/java/link/standen/michael/fatesheets/model/Character.java
// public abstract class Character implements Serializable {
//
// public static final String INTENT_EXTRA_NAME = "Character";
//
// private String sheetType;
// private String name;
// private String description;
// private Integer fatePoints;
// private String highConcept;
// private String trouble;
// private List<String> aspects;
// private List<String> stunts;
// private List<Consequence> consequences;
//
// public Character(String name){
// this.name = name;
// fatePoints = 3;
// aspects = new ArrayList<>();
// stunts = new ArrayList<>();
// consequences = new ArrayList<>();
// consequences.add(new Consequence(2));
// consequences.add(new Consequence(4));
// consequences.add(new Consequence(6));
// }
//
// public String getName() {
// return name;
// }
//
// public void setName(String name) {
// this.name = name;
// }
//
// public String getDescription() {
// return description;
// }
//
// public void setDescription(String description) {
// this.description = description;
// }
//
// public String getHighConcept() {
// return highConcept;
// }
//
// public void setHighConcept(String highConcept) {
// this.highConcept = highConcept;
// }
//
// public String getTrouble() {
// return trouble;
// }
//
// public void setTrouble(String trouble) {
// this.trouble = trouble;
// }
//
// public List<String> getAspects() {
// return aspects;
// }
//
// public void setAspects(List<String> aspects) {
// this.aspects = aspects;
// }
//
// public List<String> getStunts() {
// return stunts;
// }
//
// public void setStunts(List<String> stunts) {
// this.stunts = stunts;
// }
//
// public List<Consequence> getConsequences() {
// return consequences;
// }
//
// public void setConsequences(List<Consequence> consequences) {
// this.consequences = consequences;
// }
//
// public Integer getFatePoints() {
// return fatePoints;
// }
//
// public void setFatePoints(Integer fatePoints) {
// this.fatePoints = fatePoints;
// }
//
// public void incrementFatePoints() {
// fatePoints++;
// }
// public void decrementFatePoints() {
// fatePoints--;
// }
//
// public abstract String getSheetType();
//
// public void setSheetType(String sheetType) {
// this.sheetType = sheetType;
// }
// }
| import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import link.standen.michael.fatesheets.R;
import link.standen.michael.fatesheets.model.Character; | package link.standen.michael.fatesheets.fragment;
/**
* A fragment for managing a characters description.
*/
public class CharacterEditDescriptionFragment extends CharacterEditAbstractFragment {
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.character_edit_description, container, false);
| // Path: app/src/main/java/link/standen/michael/fatesheets/model/Character.java
// public abstract class Character implements Serializable {
//
// public static final String INTENT_EXTRA_NAME = "Character";
//
// private String sheetType;
// private String name;
// private String description;
// private Integer fatePoints;
// private String highConcept;
// private String trouble;
// private List<String> aspects;
// private List<String> stunts;
// private List<Consequence> consequences;
//
// public Character(String name){
// this.name = name;
// fatePoints = 3;
// aspects = new ArrayList<>();
// stunts = new ArrayList<>();
// consequences = new ArrayList<>();
// consequences.add(new Consequence(2));
// consequences.add(new Consequence(4));
// consequences.add(new Consequence(6));
// }
//
// public String getName() {
// return name;
// }
//
// public void setName(String name) {
// this.name = name;
// }
//
// public String getDescription() {
// return description;
// }
//
// public void setDescription(String description) {
// this.description = description;
// }
//
// public String getHighConcept() {
// return highConcept;
// }
//
// public void setHighConcept(String highConcept) {
// this.highConcept = highConcept;
// }
//
// public String getTrouble() {
// return trouble;
// }
//
// public void setTrouble(String trouble) {
// this.trouble = trouble;
// }
//
// public List<String> getAspects() {
// return aspects;
// }
//
// public void setAspects(List<String> aspects) {
// this.aspects = aspects;
// }
//
// public List<String> getStunts() {
// return stunts;
// }
//
// public void setStunts(List<String> stunts) {
// this.stunts = stunts;
// }
//
// public List<Consequence> getConsequences() {
// return consequences;
// }
//
// public void setConsequences(List<Consequence> consequences) {
// this.consequences = consequences;
// }
//
// public Integer getFatePoints() {
// return fatePoints;
// }
//
// public void setFatePoints(Integer fatePoints) {
// this.fatePoints = fatePoints;
// }
//
// public void incrementFatePoints() {
// fatePoints++;
// }
// public void decrementFatePoints() {
// fatePoints--;
// }
//
// public abstract String getSheetType();
//
// public void setSheetType(String sheetType) {
// this.sheetType = sheetType;
// }
// }
// Path: app/src/main/java/link/standen/michael/fatesheets/fragment/CharacterEditDescriptionFragment.java
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import link.standen.michael.fatesheets.R;
import link.standen.michael.fatesheets.model.Character;
package link.standen.michael.fatesheets.fragment;
/**
* A fragment for managing a characters description.
*/
public class CharacterEditDescriptionFragment extends CharacterEditAbstractFragment {
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.character_edit_description, container, false);
| Character character = getCharacter(); |
ScreamingHawk/fate-sheets | app/src/main/java/link/standen/michael/fatesheets/util/CharacterHelper.java | // Path: app/src/main/java/link/standen/michael/fatesheets/model/CoreCharacter.java
// public class CoreCharacter extends Character {
//
// @Override
// public String getSheetType() {
// return "CORE";
// }
//
// private List<Skill> skills;
// private List<String> extras;
// private List<Stress> physicalStress;
// private List<Stress> mentalStress;
//
// public CoreCharacter(String name) {
// super(name);
// skills = new ArrayList<>();
// // Init skills (1 at 5, 2 at 4...)
// for (int i = 5; i > 0; i--){
// for (int j = 5; j >= i; j--){
// skills.add(new Skill(i));
// }
// }
// extras = new ArrayList<>();
// // Init stresses
// physicalStress = new ArrayList<>();
// physicalStress.add(new Stress(1));
// physicalStress.add(new Stress(2));
// mentalStress = new ArrayList<>();
// mentalStress.add(new Stress(1));
// mentalStress.add(new Stress(2));
// }
//
// public List<Skill> getSkills() {
// return skills;
// }
//
// public void setSkills(List<Skill> skills) {
// this.skills = skills;
// }
//
// public List<String> getExtras() {
// return extras;
// }
//
// public void setExtras(List<String> extras) {
// this.extras = extras;
// }
//
// public List<Stress> getPhysicalStress() {
// return physicalStress;
// }
//
// public void setPhysicalStress(List<Stress> physicalStress) {
// this.physicalStress = physicalStress;
// }
//
// public List<Stress> getMentalStress() {
// return mentalStress;
// }
//
// public void setMentalStress(List<Stress> mentalStress) {
// this.mentalStress = mentalStress;
// }
// }
//
// Path: app/src/main/java/link/standen/michael/fatesheets/model/FAECharacter.java
// public class FAECharacter extends Character {
//
// @Override
// public String getSheetType() {
// return "FAE";
// }
//
// private List<Approach> approaches;
// private List<Stress> stress;
//
// public FAECharacter(String name, Context context) {
// super(name);
// approaches = new ArrayList<>();
// // Init each approach
// if (context != null) {
// for (String approach : context.getResources().getStringArray(R.array.fae_approaches)) {
// if (!approach.isEmpty()) {
// approaches.add(new Approach(approach));
// }
// }
// }
// // Init stress
// stress = new ArrayList<>();
// stress.add(new Stress(1));
// stress.add(new Stress(2));
// stress.add(new Stress(3));
// }
//
// public List<Approach> getApproaches() {
// return approaches;
// }
//
// public void setApproaches(List<Approach> approaches) {
// this.approaches = approaches;
// }
//
// public List<Stress> getStress() {
// return stress;
// }
//
// public void setStress(List<Stress> stress) {
// this.stress = stress;
// }
// }
| import android.content.Context;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.util.Log;
import com.google.gson.Gson;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import link.standen.michael.fatesheets.R;
import link.standen.michael.fatesheets.model.CoreCharacter;
import link.standen.michael.fatesheets.model.FAECharacter; | package link.standen.michael.fatesheets.util;
/**
* A helper class for managing characters
*/
public final class CharacterHelper extends JsonFileHelper {
private static final String TAG = CharacterHelper.class.getName();
private static final String CORE_PREFIX = "Core_";
private static final String FAE_PREFIX = "FAE_";
private CharacterHelper(){}
/**
* Returns the default name for a character.
*/
@NonNull
public static String getCharacterDefaultName(Context context){
return context.getResources().getString(R.string.character_name_default);
}
/**
* Saves the Core character to local storage.
* @return True if the write operation was successful, false otherwise.
*/ | // Path: app/src/main/java/link/standen/michael/fatesheets/model/CoreCharacter.java
// public class CoreCharacter extends Character {
//
// @Override
// public String getSheetType() {
// return "CORE";
// }
//
// private List<Skill> skills;
// private List<String> extras;
// private List<Stress> physicalStress;
// private List<Stress> mentalStress;
//
// public CoreCharacter(String name) {
// super(name);
// skills = new ArrayList<>();
// // Init skills (1 at 5, 2 at 4...)
// for (int i = 5; i > 0; i--){
// for (int j = 5; j >= i; j--){
// skills.add(new Skill(i));
// }
// }
// extras = new ArrayList<>();
// // Init stresses
// physicalStress = new ArrayList<>();
// physicalStress.add(new Stress(1));
// physicalStress.add(new Stress(2));
// mentalStress = new ArrayList<>();
// mentalStress.add(new Stress(1));
// mentalStress.add(new Stress(2));
// }
//
// public List<Skill> getSkills() {
// return skills;
// }
//
// public void setSkills(List<Skill> skills) {
// this.skills = skills;
// }
//
// public List<String> getExtras() {
// return extras;
// }
//
// public void setExtras(List<String> extras) {
// this.extras = extras;
// }
//
// public List<Stress> getPhysicalStress() {
// return physicalStress;
// }
//
// public void setPhysicalStress(List<Stress> physicalStress) {
// this.physicalStress = physicalStress;
// }
//
// public List<Stress> getMentalStress() {
// return mentalStress;
// }
//
// public void setMentalStress(List<Stress> mentalStress) {
// this.mentalStress = mentalStress;
// }
// }
//
// Path: app/src/main/java/link/standen/michael/fatesheets/model/FAECharacter.java
// public class FAECharacter extends Character {
//
// @Override
// public String getSheetType() {
// return "FAE";
// }
//
// private List<Approach> approaches;
// private List<Stress> stress;
//
// public FAECharacter(String name, Context context) {
// super(name);
// approaches = new ArrayList<>();
// // Init each approach
// if (context != null) {
// for (String approach : context.getResources().getStringArray(R.array.fae_approaches)) {
// if (!approach.isEmpty()) {
// approaches.add(new Approach(approach));
// }
// }
// }
// // Init stress
// stress = new ArrayList<>();
// stress.add(new Stress(1));
// stress.add(new Stress(2));
// stress.add(new Stress(3));
// }
//
// public List<Approach> getApproaches() {
// return approaches;
// }
//
// public void setApproaches(List<Approach> approaches) {
// this.approaches = approaches;
// }
//
// public List<Stress> getStress() {
// return stress;
// }
//
// public void setStress(List<Stress> stress) {
// this.stress = stress;
// }
// }
// Path: app/src/main/java/link/standen/michael/fatesheets/util/CharacterHelper.java
import android.content.Context;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.util.Log;
import com.google.gson.Gson;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import link.standen.michael.fatesheets.R;
import link.standen.michael.fatesheets.model.CoreCharacter;
import link.standen.michael.fatesheets.model.FAECharacter;
package link.standen.michael.fatesheets.util;
/**
* A helper class for managing characters
*/
public final class CharacterHelper extends JsonFileHelper {
private static final String TAG = CharacterHelper.class.getName();
private static final String CORE_PREFIX = "Core_";
private static final String FAE_PREFIX = "FAE_";
private CharacterHelper(){}
/**
* Returns the default name for a character.
*/
@NonNull
public static String getCharacterDefaultName(Context context){
return context.getResources().getString(R.string.character_name_default);
}
/**
* Saves the Core character to local storage.
* @return True if the write operation was successful, false otherwise.
*/ | public static boolean saveCoreCharacter(Context context, CoreCharacter character) { |
ScreamingHawk/fate-sheets | app/src/main/java/link/standen/michael/fatesheets/util/CharacterHelper.java | // Path: app/src/main/java/link/standen/michael/fatesheets/model/CoreCharacter.java
// public class CoreCharacter extends Character {
//
// @Override
// public String getSheetType() {
// return "CORE";
// }
//
// private List<Skill> skills;
// private List<String> extras;
// private List<Stress> physicalStress;
// private List<Stress> mentalStress;
//
// public CoreCharacter(String name) {
// super(name);
// skills = new ArrayList<>();
// // Init skills (1 at 5, 2 at 4...)
// for (int i = 5; i > 0; i--){
// for (int j = 5; j >= i; j--){
// skills.add(new Skill(i));
// }
// }
// extras = new ArrayList<>();
// // Init stresses
// physicalStress = new ArrayList<>();
// physicalStress.add(new Stress(1));
// physicalStress.add(new Stress(2));
// mentalStress = new ArrayList<>();
// mentalStress.add(new Stress(1));
// mentalStress.add(new Stress(2));
// }
//
// public List<Skill> getSkills() {
// return skills;
// }
//
// public void setSkills(List<Skill> skills) {
// this.skills = skills;
// }
//
// public List<String> getExtras() {
// return extras;
// }
//
// public void setExtras(List<String> extras) {
// this.extras = extras;
// }
//
// public List<Stress> getPhysicalStress() {
// return physicalStress;
// }
//
// public void setPhysicalStress(List<Stress> physicalStress) {
// this.physicalStress = physicalStress;
// }
//
// public List<Stress> getMentalStress() {
// return mentalStress;
// }
//
// public void setMentalStress(List<Stress> mentalStress) {
// this.mentalStress = mentalStress;
// }
// }
//
// Path: app/src/main/java/link/standen/michael/fatesheets/model/FAECharacter.java
// public class FAECharacter extends Character {
//
// @Override
// public String getSheetType() {
// return "FAE";
// }
//
// private List<Approach> approaches;
// private List<Stress> stress;
//
// public FAECharacter(String name, Context context) {
// super(name);
// approaches = new ArrayList<>();
// // Init each approach
// if (context != null) {
// for (String approach : context.getResources().getStringArray(R.array.fae_approaches)) {
// if (!approach.isEmpty()) {
// approaches.add(new Approach(approach));
// }
// }
// }
// // Init stress
// stress = new ArrayList<>();
// stress.add(new Stress(1));
// stress.add(new Stress(2));
// stress.add(new Stress(3));
// }
//
// public List<Approach> getApproaches() {
// return approaches;
// }
//
// public void setApproaches(List<Approach> approaches) {
// this.approaches = approaches;
// }
//
// public List<Stress> getStress() {
// return stress;
// }
//
// public void setStress(List<Stress> stress) {
// this.stress = stress;
// }
// }
| import android.content.Context;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.util.Log;
import com.google.gson.Gson;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import link.standen.michael.fatesheets.R;
import link.standen.michael.fatesheets.model.CoreCharacter;
import link.standen.michael.fatesheets.model.FAECharacter; | package link.standen.michael.fatesheets.util;
/**
* A helper class for managing characters
*/
public final class CharacterHelper extends JsonFileHelper {
private static final String TAG = CharacterHelper.class.getName();
private static final String CORE_PREFIX = "Core_";
private static final String FAE_PREFIX = "FAE_";
private CharacterHelper(){}
/**
* Returns the default name for a character.
*/
@NonNull
public static String getCharacterDefaultName(Context context){
return context.getResources().getString(R.string.character_name_default);
}
/**
* Saves the Core character to local storage.
* @return True if the write operation was successful, false otherwise.
*/
public static boolean saveCoreCharacter(Context context, CoreCharacter character) {
return saveJsonToFile(context, new Gson().toJson(character), CORE_PREFIX + character.getName());
}
/**
* Saves the FAE character to local storage.
* @return True if the write operation was successful, false otherwise.
*/ | // Path: app/src/main/java/link/standen/michael/fatesheets/model/CoreCharacter.java
// public class CoreCharacter extends Character {
//
// @Override
// public String getSheetType() {
// return "CORE";
// }
//
// private List<Skill> skills;
// private List<String> extras;
// private List<Stress> physicalStress;
// private List<Stress> mentalStress;
//
// public CoreCharacter(String name) {
// super(name);
// skills = new ArrayList<>();
// // Init skills (1 at 5, 2 at 4...)
// for (int i = 5; i > 0; i--){
// for (int j = 5; j >= i; j--){
// skills.add(new Skill(i));
// }
// }
// extras = new ArrayList<>();
// // Init stresses
// physicalStress = new ArrayList<>();
// physicalStress.add(new Stress(1));
// physicalStress.add(new Stress(2));
// mentalStress = new ArrayList<>();
// mentalStress.add(new Stress(1));
// mentalStress.add(new Stress(2));
// }
//
// public List<Skill> getSkills() {
// return skills;
// }
//
// public void setSkills(List<Skill> skills) {
// this.skills = skills;
// }
//
// public List<String> getExtras() {
// return extras;
// }
//
// public void setExtras(List<String> extras) {
// this.extras = extras;
// }
//
// public List<Stress> getPhysicalStress() {
// return physicalStress;
// }
//
// public void setPhysicalStress(List<Stress> physicalStress) {
// this.physicalStress = physicalStress;
// }
//
// public List<Stress> getMentalStress() {
// return mentalStress;
// }
//
// public void setMentalStress(List<Stress> mentalStress) {
// this.mentalStress = mentalStress;
// }
// }
//
// Path: app/src/main/java/link/standen/michael/fatesheets/model/FAECharacter.java
// public class FAECharacter extends Character {
//
// @Override
// public String getSheetType() {
// return "FAE";
// }
//
// private List<Approach> approaches;
// private List<Stress> stress;
//
// public FAECharacter(String name, Context context) {
// super(name);
// approaches = new ArrayList<>();
// // Init each approach
// if (context != null) {
// for (String approach : context.getResources().getStringArray(R.array.fae_approaches)) {
// if (!approach.isEmpty()) {
// approaches.add(new Approach(approach));
// }
// }
// }
// // Init stress
// stress = new ArrayList<>();
// stress.add(new Stress(1));
// stress.add(new Stress(2));
// stress.add(new Stress(3));
// }
//
// public List<Approach> getApproaches() {
// return approaches;
// }
//
// public void setApproaches(List<Approach> approaches) {
// this.approaches = approaches;
// }
//
// public List<Stress> getStress() {
// return stress;
// }
//
// public void setStress(List<Stress> stress) {
// this.stress = stress;
// }
// }
// Path: app/src/main/java/link/standen/michael/fatesheets/util/CharacterHelper.java
import android.content.Context;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.util.Log;
import com.google.gson.Gson;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import link.standen.michael.fatesheets.R;
import link.standen.michael.fatesheets.model.CoreCharacter;
import link.standen.michael.fatesheets.model.FAECharacter;
package link.standen.michael.fatesheets.util;
/**
* A helper class for managing characters
*/
public final class CharacterHelper extends JsonFileHelper {
private static final String TAG = CharacterHelper.class.getName();
private static final String CORE_PREFIX = "Core_";
private static final String FAE_PREFIX = "FAE_";
private CharacterHelper(){}
/**
* Returns the default name for a character.
*/
@NonNull
public static String getCharacterDefaultName(Context context){
return context.getResources().getString(R.string.character_name_default);
}
/**
* Saves the Core character to local storage.
* @return True if the write operation was successful, false otherwise.
*/
public static boolean saveCoreCharacter(Context context, CoreCharacter character) {
return saveJsonToFile(context, new Gson().toJson(character), CORE_PREFIX + character.getName());
}
/**
* Saves the FAE character to local storage.
* @return True if the write operation was successful, false otherwise.
*/ | public static boolean saveFAECharacter(Context context, FAECharacter character) { |
aisrael/junit-rules | src/test/java/junit/rules/jpa/hibernate/DerbyHibernateTestCaseTest.java | // Path: src/test/java/com/example/ejb3/beans/WidgetBean.java
// public class WidgetBean {
//
// @PersistenceContext
// private EntityManager em;
//
// private WidgetDao widgetDao;
//
// /**
// * We create the {@link JpaWidgetDao}
// */
// @PostConstruct
// @SuppressWarnings("unused")
// private void initialize() {
// widgetDao = new JpaWidgetDao(em);
// }
//
// /**
// * @return list of all widgets
// */
// public final List<Widget> listAll() {
// return widgetDao.listAll();
// }
//
// /**
// * @param id
// * the Widget id
// * @return the found Widget
// */
// public final Widget findById(final int id) {
// return widgetDao.findById(id);
// }
// }
//
// Path: src/test/java/com/example/model/Widget.java
// @Entity
// @NamedQueries({
// @NamedQuery(name = Widget.LIST_ALL, query = "SELECT w FROM Widget w"),
// @NamedQuery(name = Widget.FIND_BY_ID, query = "SELECT w FROM Widget w WHERE w.id = :id"),
// @NamedQuery(name = Widget.FIND_BY_NAME, query = "SELECT w FROM Widget w WHERE w.name = :name")
// })
// public class Widget implements Serializable {
//
// /**
// *
// */
// private static final long serialVersionUID = -1689099836716604893L;
//
// /**
// * {@value #LIST_ALL}
// */
// public static final String LIST_ALL = "Widget.listAll";
//
// /**
// * {@value #FIND_BY_ID}
// */
// public static final String FIND_BY_ID = "Widget.findById";
//
// /**
// * {@value #FIND_BY_NAME}
// */
// public static final String FIND_BY_NAME = "Widget.findByName";
//
// @Id
// private Integer id;
//
// @Column
// private String name;
//
// /**
// * @return the id
// */
// public final Integer getId() {
// return id;
// }
//
// /**
// * @param id
// * the id to set
// */
// public final void setId(final Integer id) {
// this.id = id;
// }
//
// /**
// * @return the name
// */
// public final String getName() {
// return name;
// }
//
// /**
// * @param name
// * the name to set
// */
// public final void setName(final String name) {
// this.name = name;
// }
//
// }
| import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import java.util.List;
import junit.rules.dbunit.Fixtures;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.JUnitCore;
import org.junit.runner.Result;
import com.example.ejb3.beans.WidgetBean;
import com.example.model.Widget; | /**
* junit-rules: JUnit Rules Library
*
* Copyright (c) 2009-2011 by Alistair A. Israel.
* This software is made available under the terms of the MIT License.
*
* Created Oct 15, 2009
*/
package junit.rules.jpa.hibernate;
/**
* @author Alistair A. Israel
* @since 0.3
*/
public final class DerbyHibernateTestCaseTest {
/**
* @author Alistair A. Israel
*/
@Fixtures("fixtures.xml")
public static final class FirstTest extends DerbyHibernateTestCase {
| // Path: src/test/java/com/example/ejb3/beans/WidgetBean.java
// public class WidgetBean {
//
// @PersistenceContext
// private EntityManager em;
//
// private WidgetDao widgetDao;
//
// /**
// * We create the {@link JpaWidgetDao}
// */
// @PostConstruct
// @SuppressWarnings("unused")
// private void initialize() {
// widgetDao = new JpaWidgetDao(em);
// }
//
// /**
// * @return list of all widgets
// */
// public final List<Widget> listAll() {
// return widgetDao.listAll();
// }
//
// /**
// * @param id
// * the Widget id
// * @return the found Widget
// */
// public final Widget findById(final int id) {
// return widgetDao.findById(id);
// }
// }
//
// Path: src/test/java/com/example/model/Widget.java
// @Entity
// @NamedQueries({
// @NamedQuery(name = Widget.LIST_ALL, query = "SELECT w FROM Widget w"),
// @NamedQuery(name = Widget.FIND_BY_ID, query = "SELECT w FROM Widget w WHERE w.id = :id"),
// @NamedQuery(name = Widget.FIND_BY_NAME, query = "SELECT w FROM Widget w WHERE w.name = :name")
// })
// public class Widget implements Serializable {
//
// /**
// *
// */
// private static final long serialVersionUID = -1689099836716604893L;
//
// /**
// * {@value #LIST_ALL}
// */
// public static final String LIST_ALL = "Widget.listAll";
//
// /**
// * {@value #FIND_BY_ID}
// */
// public static final String FIND_BY_ID = "Widget.findById";
//
// /**
// * {@value #FIND_BY_NAME}
// */
// public static final String FIND_BY_NAME = "Widget.findByName";
//
// @Id
// private Integer id;
//
// @Column
// private String name;
//
// /**
// * @return the id
// */
// public final Integer getId() {
// return id;
// }
//
// /**
// * @param id
// * the id to set
// */
// public final void setId(final Integer id) {
// this.id = id;
// }
//
// /**
// * @return the name
// */
// public final String getName() {
// return name;
// }
//
// /**
// * @param name
// * the name to set
// */
// public final void setName(final String name) {
// this.name = name;
// }
//
// }
// Path: src/test/java/junit/rules/jpa/hibernate/DerbyHibernateTestCaseTest.java
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import java.util.List;
import junit.rules.dbunit.Fixtures;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.JUnitCore;
import org.junit.runner.Result;
import com.example.ejb3.beans.WidgetBean;
import com.example.model.Widget;
/**
* junit-rules: JUnit Rules Library
*
* Copyright (c) 2009-2011 by Alistair A. Israel.
* This software is made available under the terms of the MIT License.
*
* Created Oct 15, 2009
*/
package junit.rules.jpa.hibernate;
/**
* @author Alistair A. Israel
* @since 0.3
*/
public final class DerbyHibernateTestCaseTest {
/**
* @author Alistair A. Israel
*/
@Fixtures("fixtures.xml")
public static final class FirstTest extends DerbyHibernateTestCase {
| private WidgetBean widgetBean = new WidgetBean(); |
aisrael/junit-rules | src/test/java/junit/rules/jpa/hibernate/DerbyHibernateTestCaseTest.java | // Path: src/test/java/com/example/ejb3/beans/WidgetBean.java
// public class WidgetBean {
//
// @PersistenceContext
// private EntityManager em;
//
// private WidgetDao widgetDao;
//
// /**
// * We create the {@link JpaWidgetDao}
// */
// @PostConstruct
// @SuppressWarnings("unused")
// private void initialize() {
// widgetDao = new JpaWidgetDao(em);
// }
//
// /**
// * @return list of all widgets
// */
// public final List<Widget> listAll() {
// return widgetDao.listAll();
// }
//
// /**
// * @param id
// * the Widget id
// * @return the found Widget
// */
// public final Widget findById(final int id) {
// return widgetDao.findById(id);
// }
// }
//
// Path: src/test/java/com/example/model/Widget.java
// @Entity
// @NamedQueries({
// @NamedQuery(name = Widget.LIST_ALL, query = "SELECT w FROM Widget w"),
// @NamedQuery(name = Widget.FIND_BY_ID, query = "SELECT w FROM Widget w WHERE w.id = :id"),
// @NamedQuery(name = Widget.FIND_BY_NAME, query = "SELECT w FROM Widget w WHERE w.name = :name")
// })
// public class Widget implements Serializable {
//
// /**
// *
// */
// private static final long serialVersionUID = -1689099836716604893L;
//
// /**
// * {@value #LIST_ALL}
// */
// public static final String LIST_ALL = "Widget.listAll";
//
// /**
// * {@value #FIND_BY_ID}
// */
// public static final String FIND_BY_ID = "Widget.findById";
//
// /**
// * {@value #FIND_BY_NAME}
// */
// public static final String FIND_BY_NAME = "Widget.findByName";
//
// @Id
// private Integer id;
//
// @Column
// private String name;
//
// /**
// * @return the id
// */
// public final Integer getId() {
// return id;
// }
//
// /**
// * @param id
// * the id to set
// */
// public final void setId(final Integer id) {
// this.id = id;
// }
//
// /**
// * @return the name
// */
// public final String getName() {
// return name;
// }
//
// /**
// * @param name
// * the name to set
// */
// public final void setName(final String name) {
// this.name = name;
// }
//
// }
| import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import java.util.List;
import junit.rules.dbunit.Fixtures;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.JUnitCore;
import org.junit.runner.Result;
import com.example.ejb3.beans.WidgetBean;
import com.example.model.Widget; | /**
* junit-rules: JUnit Rules Library
*
* Copyright (c) 2009-2011 by Alistair A. Israel.
* This software is made available under the terms of the MIT License.
*
* Created Oct 15, 2009
*/
package junit.rules.jpa.hibernate;
/**
* @author Alistair A. Israel
* @since 0.3
*/
public final class DerbyHibernateTestCaseTest {
/**
* @author Alistair A. Israel
*/
@Fixtures("fixtures.xml")
public static final class FirstTest extends DerbyHibernateTestCase {
private WidgetBean widgetBean = new WidgetBean();
/**
*
*/
@Before
public void setUp() {
injectAndPostConstruct(widgetBean);
}
/**
* @throws Exception
* on exception
*/
@Test
public void testListAll() throws Exception { | // Path: src/test/java/com/example/ejb3/beans/WidgetBean.java
// public class WidgetBean {
//
// @PersistenceContext
// private EntityManager em;
//
// private WidgetDao widgetDao;
//
// /**
// * We create the {@link JpaWidgetDao}
// */
// @PostConstruct
// @SuppressWarnings("unused")
// private void initialize() {
// widgetDao = new JpaWidgetDao(em);
// }
//
// /**
// * @return list of all widgets
// */
// public final List<Widget> listAll() {
// return widgetDao.listAll();
// }
//
// /**
// * @param id
// * the Widget id
// * @return the found Widget
// */
// public final Widget findById(final int id) {
// return widgetDao.findById(id);
// }
// }
//
// Path: src/test/java/com/example/model/Widget.java
// @Entity
// @NamedQueries({
// @NamedQuery(name = Widget.LIST_ALL, query = "SELECT w FROM Widget w"),
// @NamedQuery(name = Widget.FIND_BY_ID, query = "SELECT w FROM Widget w WHERE w.id = :id"),
// @NamedQuery(name = Widget.FIND_BY_NAME, query = "SELECT w FROM Widget w WHERE w.name = :name")
// })
// public class Widget implements Serializable {
//
// /**
// *
// */
// private static final long serialVersionUID = -1689099836716604893L;
//
// /**
// * {@value #LIST_ALL}
// */
// public static final String LIST_ALL = "Widget.listAll";
//
// /**
// * {@value #FIND_BY_ID}
// */
// public static final String FIND_BY_ID = "Widget.findById";
//
// /**
// * {@value #FIND_BY_NAME}
// */
// public static final String FIND_BY_NAME = "Widget.findByName";
//
// @Id
// private Integer id;
//
// @Column
// private String name;
//
// /**
// * @return the id
// */
// public final Integer getId() {
// return id;
// }
//
// /**
// * @param id
// * the id to set
// */
// public final void setId(final Integer id) {
// this.id = id;
// }
//
// /**
// * @return the name
// */
// public final String getName() {
// return name;
// }
//
// /**
// * @param name
// * the name to set
// */
// public final void setName(final String name) {
// this.name = name;
// }
//
// }
// Path: src/test/java/junit/rules/jpa/hibernate/DerbyHibernateTestCaseTest.java
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import java.util.List;
import junit.rules.dbunit.Fixtures;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.JUnitCore;
import org.junit.runner.Result;
import com.example.ejb3.beans.WidgetBean;
import com.example.model.Widget;
/**
* junit-rules: JUnit Rules Library
*
* Copyright (c) 2009-2011 by Alistair A. Israel.
* This software is made available under the terms of the MIT License.
*
* Created Oct 15, 2009
*/
package junit.rules.jpa.hibernate;
/**
* @author Alistair A. Israel
* @since 0.3
*/
public final class DerbyHibernateTestCaseTest {
/**
* @author Alistair A. Israel
*/
@Fixtures("fixtures.xml")
public static final class FirstTest extends DerbyHibernateTestCase {
private WidgetBean widgetBean = new WidgetBean();
/**
*
*/
@Before
public void setUp() {
injectAndPostConstruct(widgetBean);
}
/**
* @throws Exception
* on exception
*/
@Test
public void testListAll() throws Exception { | final List<Widget> widgets = widgetBean.listAll(); |
aisrael/junit-rules | src/test/java/junit/rules/jetty/JettyServerRuleTest.java | // Path: src/test/java/junit/rules/util/SimpleReference.java
// public class SimpleReference<T> {
//
// private T value;
//
// /**
// * @return the object referenced
// */
// public final T get() {
// return value;
// }
//
// /**
// * @param obj
// * the new object to reference
// */
// public final void set(final T obj) {
// this.value = obj;
// }
//
// /**
// * @param <T>
// * a type
// * @param obj
// * the object we want to reference
// * @return a SimpleReference to the object
// */
// public static <T> SimpleReference<T> to(final T obj) {
// return new SimpleReference<T>();
// }
// }
| import static java.lang.Boolean.FALSE;
import static java.lang.Boolean.TRUE;
import static java.net.HttpURLConnection.HTTP_OK;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.HttpURLConnection;
import junit.rules.util.SimpleReference;
import org.junit.Rule;
import org.junit.Test; | * @throws Exception
* should never happen
*/
@Test
public void testJettyServerRulePutMethod() throws Exception {
jettyServer.setHandler(new SimpleJettyHandler() {
@Override
protected void onPut() throws IOException {
final BufferedReader reader = new BufferedReader(new InputStreamReader(request().getInputStream()));
final PrintWriter out = getResponseWriter();
out.println(reader.readLine());
}
});
final HttpURLConnection connection = jettyServer.put("/");
final BufferedWriter out = new BufferedWriter(new OutputStreamWriter(connection.getOutputStream()));
out.write("Hello Again");
out.flush();
final BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
assertEquals("Hello Again", in.readLine());
assertEquals(HTTP_OK, connection.getResponseCode());
}
/**
* Test HTTP DELETE
*
* @throws Exception
* should never happen
*/
@Test
public void testJettyServerRuleDeleteMethod() throws Exception { | // Path: src/test/java/junit/rules/util/SimpleReference.java
// public class SimpleReference<T> {
//
// private T value;
//
// /**
// * @return the object referenced
// */
// public final T get() {
// return value;
// }
//
// /**
// * @param obj
// * the new object to reference
// */
// public final void set(final T obj) {
// this.value = obj;
// }
//
// /**
// * @param <T>
// * a type
// * @param obj
// * the object we want to reference
// * @return a SimpleReference to the object
// */
// public static <T> SimpleReference<T> to(final T obj) {
// return new SimpleReference<T>();
// }
// }
// Path: src/test/java/junit/rules/jetty/JettyServerRuleTest.java
import static java.lang.Boolean.FALSE;
import static java.lang.Boolean.TRUE;
import static java.net.HttpURLConnection.HTTP_OK;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.HttpURLConnection;
import junit.rules.util.SimpleReference;
import org.junit.Rule;
import org.junit.Test;
* @throws Exception
* should never happen
*/
@Test
public void testJettyServerRulePutMethod() throws Exception {
jettyServer.setHandler(new SimpleJettyHandler() {
@Override
protected void onPut() throws IOException {
final BufferedReader reader = new BufferedReader(new InputStreamReader(request().getInputStream()));
final PrintWriter out = getResponseWriter();
out.println(reader.readLine());
}
});
final HttpURLConnection connection = jettyServer.put("/");
final BufferedWriter out = new BufferedWriter(new OutputStreamWriter(connection.getOutputStream()));
out.write("Hello Again");
out.flush();
final BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
assertEquals("Hello Again", in.readLine());
assertEquals(HTTP_OK, connection.getResponseCode());
}
/**
* Test HTTP DELETE
*
* @throws Exception
* should never happen
*/
@Test
public void testJettyServerRuleDeleteMethod() throws Exception { | final SimpleReference<Boolean> deleteIssued = SimpleReference.to(FALSE); |
aisrael/junit-rules | src/test/java/junit/rules/jpa/hibernate/HibernatePersistenceContextTest.java | // Path: src/test/java/com/example/ejb3/beans/WidgetBean.java
// public class WidgetBean {
//
// @PersistenceContext
// private EntityManager em;
//
// private WidgetDao widgetDao;
//
// /**
// * We create the {@link JpaWidgetDao}
// */
// @PostConstruct
// @SuppressWarnings("unused")
// private void initialize() {
// widgetDao = new JpaWidgetDao(em);
// }
//
// /**
// * @return list of all widgets
// */
// public final List<Widget> listAll() {
// return widgetDao.listAll();
// }
//
// /**
// * @param id
// * the Widget id
// * @return the found Widget
// */
// public final Widget findById(final int id) {
// return widgetDao.findById(id);
// }
// }
//
// Path: src/test/java/com/example/model/Widget.java
// @Entity
// @NamedQueries({
// @NamedQuery(name = Widget.LIST_ALL, query = "SELECT w FROM Widget w"),
// @NamedQuery(name = Widget.FIND_BY_ID, query = "SELECT w FROM Widget w WHERE w.id = :id"),
// @NamedQuery(name = Widget.FIND_BY_NAME, query = "SELECT w FROM Widget w WHERE w.name = :name")
// })
// public class Widget implements Serializable {
//
// /**
// *
// */
// private static final long serialVersionUID = -1689099836716604893L;
//
// /**
// * {@value #LIST_ALL}
// */
// public static final String LIST_ALL = "Widget.listAll";
//
// /**
// * {@value #FIND_BY_ID}
// */
// public static final String FIND_BY_ID = "Widget.findById";
//
// /**
// * {@value #FIND_BY_NAME}
// */
// public static final String FIND_BY_NAME = "Widget.findByName";
//
// @Id
// private Integer id;
//
// @Column
// private String name;
//
// /**
// * @return the id
// */
// public final Integer getId() {
// return id;
// }
//
// /**
// * @param id
// * the id to set
// */
// public final void setId(final Integer id) {
// this.id = id;
// }
//
// /**
// * @return the name
// */
// public final String getName() {
// return name;
// }
//
// /**
// * @param name
// * the name to set
// */
// public final void setName(final String name) {
// this.name = name;
// }
//
// }
| import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import java.util.List;
import junit.rules.dbunit.Fixtures;
import org.junit.Rule;
import org.junit.Test;
import com.example.ejb3.beans.WidgetBean;
import com.example.model.Widget; | /**
* junit-rules: JUnit Rules Library
*
* Copyright (c) 2009-2011 by Alistair A. Israel.
* This software is made available under the terms of the MIT License.
*
* Created Oct 15, 2009
*/
package junit.rules.jpa.hibernate;
/**
* @author Alistair A. Israel
* @since 0.3
*/
@Fixtures("fixtures.xml")
public final class HibernatePersistenceContextTest {
// CHECKSTYLE:OFF
@Rule
public HibernatePersistenceContext persistenceContext = new HibernatePersistenceContext();
// CHECKSTYLE:ON
| // Path: src/test/java/com/example/ejb3/beans/WidgetBean.java
// public class WidgetBean {
//
// @PersistenceContext
// private EntityManager em;
//
// private WidgetDao widgetDao;
//
// /**
// * We create the {@link JpaWidgetDao}
// */
// @PostConstruct
// @SuppressWarnings("unused")
// private void initialize() {
// widgetDao = new JpaWidgetDao(em);
// }
//
// /**
// * @return list of all widgets
// */
// public final List<Widget> listAll() {
// return widgetDao.listAll();
// }
//
// /**
// * @param id
// * the Widget id
// * @return the found Widget
// */
// public final Widget findById(final int id) {
// return widgetDao.findById(id);
// }
// }
//
// Path: src/test/java/com/example/model/Widget.java
// @Entity
// @NamedQueries({
// @NamedQuery(name = Widget.LIST_ALL, query = "SELECT w FROM Widget w"),
// @NamedQuery(name = Widget.FIND_BY_ID, query = "SELECT w FROM Widget w WHERE w.id = :id"),
// @NamedQuery(name = Widget.FIND_BY_NAME, query = "SELECT w FROM Widget w WHERE w.name = :name")
// })
// public class Widget implements Serializable {
//
// /**
// *
// */
// private static final long serialVersionUID = -1689099836716604893L;
//
// /**
// * {@value #LIST_ALL}
// */
// public static final String LIST_ALL = "Widget.listAll";
//
// /**
// * {@value #FIND_BY_ID}
// */
// public static final String FIND_BY_ID = "Widget.findById";
//
// /**
// * {@value #FIND_BY_NAME}
// */
// public static final String FIND_BY_NAME = "Widget.findByName";
//
// @Id
// private Integer id;
//
// @Column
// private String name;
//
// /**
// * @return the id
// */
// public final Integer getId() {
// return id;
// }
//
// /**
// * @param id
// * the id to set
// */
// public final void setId(final Integer id) {
// this.id = id;
// }
//
// /**
// * @return the name
// */
// public final String getName() {
// return name;
// }
//
// /**
// * @param name
// * the name to set
// */
// public final void setName(final String name) {
// this.name = name;
// }
//
// }
// Path: src/test/java/junit/rules/jpa/hibernate/HibernatePersistenceContextTest.java
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import java.util.List;
import junit.rules.dbunit.Fixtures;
import org.junit.Rule;
import org.junit.Test;
import com.example.ejb3.beans.WidgetBean;
import com.example.model.Widget;
/**
* junit-rules: JUnit Rules Library
*
* Copyright (c) 2009-2011 by Alistair A. Israel.
* This software is made available under the terms of the MIT License.
*
* Created Oct 15, 2009
*/
package junit.rules.jpa.hibernate;
/**
* @author Alistair A. Israel
* @since 0.3
*/
@Fixtures("fixtures.xml")
public final class HibernatePersistenceContextTest {
// CHECKSTYLE:OFF
@Rule
public HibernatePersistenceContext persistenceContext = new HibernatePersistenceContext();
// CHECKSTYLE:ON
| private WidgetBean widgetBean = new WidgetBean(); |
aisrael/junit-rules | src/test/java/junit/rules/jpa/hibernate/HibernatePersistenceContextTest.java | // Path: src/test/java/com/example/ejb3/beans/WidgetBean.java
// public class WidgetBean {
//
// @PersistenceContext
// private EntityManager em;
//
// private WidgetDao widgetDao;
//
// /**
// * We create the {@link JpaWidgetDao}
// */
// @PostConstruct
// @SuppressWarnings("unused")
// private void initialize() {
// widgetDao = new JpaWidgetDao(em);
// }
//
// /**
// * @return list of all widgets
// */
// public final List<Widget> listAll() {
// return widgetDao.listAll();
// }
//
// /**
// * @param id
// * the Widget id
// * @return the found Widget
// */
// public final Widget findById(final int id) {
// return widgetDao.findById(id);
// }
// }
//
// Path: src/test/java/com/example/model/Widget.java
// @Entity
// @NamedQueries({
// @NamedQuery(name = Widget.LIST_ALL, query = "SELECT w FROM Widget w"),
// @NamedQuery(name = Widget.FIND_BY_ID, query = "SELECT w FROM Widget w WHERE w.id = :id"),
// @NamedQuery(name = Widget.FIND_BY_NAME, query = "SELECT w FROM Widget w WHERE w.name = :name")
// })
// public class Widget implements Serializable {
//
// /**
// *
// */
// private static final long serialVersionUID = -1689099836716604893L;
//
// /**
// * {@value #LIST_ALL}
// */
// public static final String LIST_ALL = "Widget.listAll";
//
// /**
// * {@value #FIND_BY_ID}
// */
// public static final String FIND_BY_ID = "Widget.findById";
//
// /**
// * {@value #FIND_BY_NAME}
// */
// public static final String FIND_BY_NAME = "Widget.findByName";
//
// @Id
// private Integer id;
//
// @Column
// private String name;
//
// /**
// * @return the id
// */
// public final Integer getId() {
// return id;
// }
//
// /**
// * @param id
// * the id to set
// */
// public final void setId(final Integer id) {
// this.id = id;
// }
//
// /**
// * @return the name
// */
// public final String getName() {
// return name;
// }
//
// /**
// * @param name
// * the name to set
// */
// public final void setName(final String name) {
// this.name = name;
// }
//
// }
| import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import java.util.List;
import junit.rules.dbunit.Fixtures;
import org.junit.Rule;
import org.junit.Test;
import com.example.ejb3.beans.WidgetBean;
import com.example.model.Widget; | /**
* junit-rules: JUnit Rules Library
*
* Copyright (c) 2009-2011 by Alistair A. Israel.
* This software is made available under the terms of the MIT License.
*
* Created Oct 15, 2009
*/
package junit.rules.jpa.hibernate;
/**
* @author Alistair A. Israel
* @since 0.3
*/
@Fixtures("fixtures.xml")
public final class HibernatePersistenceContextTest {
// CHECKSTYLE:OFF
@Rule
public HibernatePersistenceContext persistenceContext = new HibernatePersistenceContext();
// CHECKSTYLE:ON
private WidgetBean widgetBean = new WidgetBean();
/**
* @throws Exception
* on exception
*/
@Test
public void testListAll() throws Exception {
persistenceContext.injectAndPostConstruct(widgetBean);
| // Path: src/test/java/com/example/ejb3/beans/WidgetBean.java
// public class WidgetBean {
//
// @PersistenceContext
// private EntityManager em;
//
// private WidgetDao widgetDao;
//
// /**
// * We create the {@link JpaWidgetDao}
// */
// @PostConstruct
// @SuppressWarnings("unused")
// private void initialize() {
// widgetDao = new JpaWidgetDao(em);
// }
//
// /**
// * @return list of all widgets
// */
// public final List<Widget> listAll() {
// return widgetDao.listAll();
// }
//
// /**
// * @param id
// * the Widget id
// * @return the found Widget
// */
// public final Widget findById(final int id) {
// return widgetDao.findById(id);
// }
// }
//
// Path: src/test/java/com/example/model/Widget.java
// @Entity
// @NamedQueries({
// @NamedQuery(name = Widget.LIST_ALL, query = "SELECT w FROM Widget w"),
// @NamedQuery(name = Widget.FIND_BY_ID, query = "SELECT w FROM Widget w WHERE w.id = :id"),
// @NamedQuery(name = Widget.FIND_BY_NAME, query = "SELECT w FROM Widget w WHERE w.name = :name")
// })
// public class Widget implements Serializable {
//
// /**
// *
// */
// private static final long serialVersionUID = -1689099836716604893L;
//
// /**
// * {@value #LIST_ALL}
// */
// public static final String LIST_ALL = "Widget.listAll";
//
// /**
// * {@value #FIND_BY_ID}
// */
// public static final String FIND_BY_ID = "Widget.findById";
//
// /**
// * {@value #FIND_BY_NAME}
// */
// public static final String FIND_BY_NAME = "Widget.findByName";
//
// @Id
// private Integer id;
//
// @Column
// private String name;
//
// /**
// * @return the id
// */
// public final Integer getId() {
// return id;
// }
//
// /**
// * @param id
// * the id to set
// */
// public final void setId(final Integer id) {
// this.id = id;
// }
//
// /**
// * @return the name
// */
// public final String getName() {
// return name;
// }
//
// /**
// * @param name
// * the name to set
// */
// public final void setName(final String name) {
// this.name = name;
// }
//
// }
// Path: src/test/java/junit/rules/jpa/hibernate/HibernatePersistenceContextTest.java
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import java.util.List;
import junit.rules.dbunit.Fixtures;
import org.junit.Rule;
import org.junit.Test;
import com.example.ejb3.beans.WidgetBean;
import com.example.model.Widget;
/**
* junit-rules: JUnit Rules Library
*
* Copyright (c) 2009-2011 by Alistair A. Israel.
* This software is made available under the terms of the MIT License.
*
* Created Oct 15, 2009
*/
package junit.rules.jpa.hibernate;
/**
* @author Alistair A. Israel
* @since 0.3
*/
@Fixtures("fixtures.xml")
public final class HibernatePersistenceContextTest {
// CHECKSTYLE:OFF
@Rule
public HibernatePersistenceContext persistenceContext = new HibernatePersistenceContext();
// CHECKSTYLE:ON
private WidgetBean widgetBean = new WidgetBean();
/**
* @throws Exception
* on exception
*/
@Test
public void testListAll() throws Exception {
persistenceContext.injectAndPostConstruct(widgetBean);
| final List<Widget> widgets = widgetBean.listAll(); |
aisrael/junit-rules | src/main/java/junit/rules/jdbc/support/DriverManagerDataSource.java | // Path: src/main/java/junit/rules/util/ObjectUtils.java
// public static <T> boolean nullSafeEquals(final T a, final T b) {
// if (a == b) {
// return true;
// }
// if (a == null || b == null) {
// return false;
// }
// return a.equals(b);
// }
//
// Path: src/main/java/junit/rules/util/StringUtils.java
// public static boolean hasLength(final String s) {
// return s != null && s.length() > 0;
// }
| import static junit.rules.util.ObjectUtils.nullSafeEquals;
import static junit.rules.util.StringUtils.hasLength;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.Driver;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.Enumeration;
import javax.sql.DataSource; | /**
* junit-rules: JUnit Rules Library
*
* Copyright (c) 2009-2011 by Alistair A. Israel.
* This software is made available under the terms of the MIT License.
*
* Created May 5, 2011
*/
package junit.rules.jdbc.support;
/**
* Poor man's implementation of Spring's DriverManager-backed {@link DataSource}.
*
* @author Alistair.Israel
*/
public class DriverManagerDataSource implements DataSource {
private boolean needToRegisterDriver;
private String jdbcDriver;
private String jdbcUrl;
private String jdbcUser;
private String jdbcPassword;
/**
* @return the jdbcDriver
*/
public final String getJdbcDriver() {
return jdbcDriver;
}
/**
* @param jdbcDriver
* the jdbcDriver to set
*/
public final void setJdbcDriver(final String jdbcDriver) { | // Path: src/main/java/junit/rules/util/ObjectUtils.java
// public static <T> boolean nullSafeEquals(final T a, final T b) {
// if (a == b) {
// return true;
// }
// if (a == null || b == null) {
// return false;
// }
// return a.equals(b);
// }
//
// Path: src/main/java/junit/rules/util/StringUtils.java
// public static boolean hasLength(final String s) {
// return s != null && s.length() > 0;
// }
// Path: src/main/java/junit/rules/jdbc/support/DriverManagerDataSource.java
import static junit.rules.util.ObjectUtils.nullSafeEquals;
import static junit.rules.util.StringUtils.hasLength;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.Driver;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.Enumeration;
import javax.sql.DataSource;
/**
* junit-rules: JUnit Rules Library
*
* Copyright (c) 2009-2011 by Alistair A. Israel.
* This software is made available under the terms of the MIT License.
*
* Created May 5, 2011
*/
package junit.rules.jdbc.support;
/**
* Poor man's implementation of Spring's DriverManager-backed {@link DataSource}.
*
* @author Alistair.Israel
*/
public class DriverManagerDataSource implements DataSource {
private boolean needToRegisterDriver;
private String jdbcDriver;
private String jdbcUrl;
private String jdbcUser;
private String jdbcPassword;
/**
* @return the jdbcDriver
*/
public final String getJdbcDriver() {
return jdbcDriver;
}
/**
* @param jdbcDriver
* the jdbcDriver to set
*/
public final void setJdbcDriver(final String jdbcDriver) { | if (!nullSafeEquals(this.jdbcDriver, jdbcDriver)) { |
aisrael/junit-rules | src/main/java/junit/rules/jdbc/support/DriverManagerDataSource.java | // Path: src/main/java/junit/rules/util/ObjectUtils.java
// public static <T> boolean nullSafeEquals(final T a, final T b) {
// if (a == b) {
// return true;
// }
// if (a == null || b == null) {
// return false;
// }
// return a.equals(b);
// }
//
// Path: src/main/java/junit/rules/util/StringUtils.java
// public static boolean hasLength(final String s) {
// return s != null && s.length() > 0;
// }
| import static junit.rules.util.ObjectUtils.nullSafeEquals;
import static junit.rules.util.StringUtils.hasLength;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.Driver;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.Enumeration;
import javax.sql.DataSource; | @Override
public final boolean isWrapperFor(final Class<?> iface) throws SQLException {
return DataSource.class.equals(iface);
}
/**
* {@inheritDoc}
*
* @see java.sql.Wrapper#unwrap(java.lang.Class)
*/
@SuppressWarnings("unchecked")
@Override
public final <T> T unwrap(final Class<T> iface) throws SQLException {
if (isWrapperFor(iface)) {
return (T) this;
}
throw new SQLException("DriverManagerDataSource can only be unwrapped as javax.sql.DataSource, not as "
+ iface.getCanonicalName());
}
/**
* {@inheritDoc}
*
* @see javax.sql.DataSource#getConnection()
*/
@Override
public final Connection getConnection() throws SQLException {
if (needToRegisterDriver) {
registerDriver();
} | // Path: src/main/java/junit/rules/util/ObjectUtils.java
// public static <T> boolean nullSafeEquals(final T a, final T b) {
// if (a == b) {
// return true;
// }
// if (a == null || b == null) {
// return false;
// }
// return a.equals(b);
// }
//
// Path: src/main/java/junit/rules/util/StringUtils.java
// public static boolean hasLength(final String s) {
// return s != null && s.length() > 0;
// }
// Path: src/main/java/junit/rules/jdbc/support/DriverManagerDataSource.java
import static junit.rules.util.ObjectUtils.nullSafeEquals;
import static junit.rules.util.StringUtils.hasLength;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.Driver;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.Enumeration;
import javax.sql.DataSource;
@Override
public final boolean isWrapperFor(final Class<?> iface) throws SQLException {
return DataSource.class.equals(iface);
}
/**
* {@inheritDoc}
*
* @see java.sql.Wrapper#unwrap(java.lang.Class)
*/
@SuppressWarnings("unchecked")
@Override
public final <T> T unwrap(final Class<T> iface) throws SQLException {
if (isWrapperFor(iface)) {
return (T) this;
}
throw new SQLException("DriverManagerDataSource can only be unwrapped as javax.sql.DataSource, not as "
+ iface.getCanonicalName());
}
/**
* {@inheritDoc}
*
* @see javax.sql.DataSource#getConnection()
*/
@Override
public final Connection getConnection() throws SQLException {
if (needToRegisterDriver) {
registerDriver();
} | if (hasLength(jdbcUser) || jdbcPassword != null) { |
aisrael/junit-rules | src/test/java/com/example/ejb3/beans/WidgetBean.java | // Path: src/test/java/com/example/dao/WidgetDao.java
// public interface WidgetDao {
//
// /**
// * @return {@link List}<{@link Widget}>
// */
// List<Widget> listAll();
//
// /**
// * @param id
// * the widget id
// * @return {@link Widget}
// */
// Widget findById(int id);
//
// /**
// * @param name
// * the widget name
// * @return {@link Widget}
// */
// Widget findByName(String name);
//
// }
//
// Path: src/test/java/com/example/dao/jpa/JpaWidgetDao.java
// public class JpaWidgetDao implements WidgetDao {
//
// private final EntityManager entityManager;
//
// /**
// * @param entityManager
// * the {@link EntityManager}
// */
// public JpaWidgetDao(final EntityManager entityManager) {
// this.entityManager = entityManager;
// }
//
// /**
// * {@inheritDoc}
// *
// * @see com.example.dao.WidgetDao#findById(int)
// */
// @Override
// public final Widget findById(final int id) {
// return entityManager.find(Widget.class, id);
// }
//
// /**
// * {@inheritDoc}
// *
// * @see com.example.dao.WidgetDao#findByName(java.lang.String)
// */
// @Override
// @SuppressWarnings("unchecked")
// public final Widget findByName(final String name) {
// final List<Widget> list = entityManager.createNamedQuery(Widget.FIND_BY_NAME).setParameter("name", name)
// .getResultList();
// if (list.isEmpty()) {
// return null;
// }
// return list.get(0);
// }
//
// /**
// * {@inheritDoc}
// *
// * @see com.example.dao.WidgetDao#listAll()
// */
// @Override
// @SuppressWarnings("unchecked")
// public final List<Widget> listAll() {
// return entityManager.createNamedQuery(Widget.LIST_ALL).getResultList();
// }
//
// }
//
// Path: src/test/java/com/example/model/Widget.java
// @Entity
// @NamedQueries({
// @NamedQuery(name = Widget.LIST_ALL, query = "SELECT w FROM Widget w"),
// @NamedQuery(name = Widget.FIND_BY_ID, query = "SELECT w FROM Widget w WHERE w.id = :id"),
// @NamedQuery(name = Widget.FIND_BY_NAME, query = "SELECT w FROM Widget w WHERE w.name = :name")
// })
// public class Widget implements Serializable {
//
// /**
// *
// */
// private static final long serialVersionUID = -1689099836716604893L;
//
// /**
// * {@value #LIST_ALL}
// */
// public static final String LIST_ALL = "Widget.listAll";
//
// /**
// * {@value #FIND_BY_ID}
// */
// public static final String FIND_BY_ID = "Widget.findById";
//
// /**
// * {@value #FIND_BY_NAME}
// */
// public static final String FIND_BY_NAME = "Widget.findByName";
//
// @Id
// private Integer id;
//
// @Column
// private String name;
//
// /**
// * @return the id
// */
// public final Integer getId() {
// return id;
// }
//
// /**
// * @param id
// * the id to set
// */
// public final void setId(final Integer id) {
// this.id = id;
// }
//
// /**
// * @return the name
// */
// public final String getName() {
// return name;
// }
//
// /**
// * @param name
// * the name to set
// */
// public final void setName(final String name) {
// this.name = name;
// }
//
// }
| import java.util.List;
import javax.annotation.PostConstruct;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import com.example.dao.WidgetDao;
import com.example.dao.jpa.JpaWidgetDao;
import com.example.model.Widget; | /**
* junit-rules: JUnit Rules Library
*
* Copyright (c) 2009-2011 by Alistair A. Israel.
* This software is made available under the terms of the MIT License.
*
* Created Oct 16, 2009
*/
package com.example.ejb3.beans;
/**
* @author Alistair A. Israel
*/
public class WidgetBean {
@PersistenceContext
private EntityManager em;
| // Path: src/test/java/com/example/dao/WidgetDao.java
// public interface WidgetDao {
//
// /**
// * @return {@link List}<{@link Widget}>
// */
// List<Widget> listAll();
//
// /**
// * @param id
// * the widget id
// * @return {@link Widget}
// */
// Widget findById(int id);
//
// /**
// * @param name
// * the widget name
// * @return {@link Widget}
// */
// Widget findByName(String name);
//
// }
//
// Path: src/test/java/com/example/dao/jpa/JpaWidgetDao.java
// public class JpaWidgetDao implements WidgetDao {
//
// private final EntityManager entityManager;
//
// /**
// * @param entityManager
// * the {@link EntityManager}
// */
// public JpaWidgetDao(final EntityManager entityManager) {
// this.entityManager = entityManager;
// }
//
// /**
// * {@inheritDoc}
// *
// * @see com.example.dao.WidgetDao#findById(int)
// */
// @Override
// public final Widget findById(final int id) {
// return entityManager.find(Widget.class, id);
// }
//
// /**
// * {@inheritDoc}
// *
// * @see com.example.dao.WidgetDao#findByName(java.lang.String)
// */
// @Override
// @SuppressWarnings("unchecked")
// public final Widget findByName(final String name) {
// final List<Widget> list = entityManager.createNamedQuery(Widget.FIND_BY_NAME).setParameter("name", name)
// .getResultList();
// if (list.isEmpty()) {
// return null;
// }
// return list.get(0);
// }
//
// /**
// * {@inheritDoc}
// *
// * @see com.example.dao.WidgetDao#listAll()
// */
// @Override
// @SuppressWarnings("unchecked")
// public final List<Widget> listAll() {
// return entityManager.createNamedQuery(Widget.LIST_ALL).getResultList();
// }
//
// }
//
// Path: src/test/java/com/example/model/Widget.java
// @Entity
// @NamedQueries({
// @NamedQuery(name = Widget.LIST_ALL, query = "SELECT w FROM Widget w"),
// @NamedQuery(name = Widget.FIND_BY_ID, query = "SELECT w FROM Widget w WHERE w.id = :id"),
// @NamedQuery(name = Widget.FIND_BY_NAME, query = "SELECT w FROM Widget w WHERE w.name = :name")
// })
// public class Widget implements Serializable {
//
// /**
// *
// */
// private static final long serialVersionUID = -1689099836716604893L;
//
// /**
// * {@value #LIST_ALL}
// */
// public static final String LIST_ALL = "Widget.listAll";
//
// /**
// * {@value #FIND_BY_ID}
// */
// public static final String FIND_BY_ID = "Widget.findById";
//
// /**
// * {@value #FIND_BY_NAME}
// */
// public static final String FIND_BY_NAME = "Widget.findByName";
//
// @Id
// private Integer id;
//
// @Column
// private String name;
//
// /**
// * @return the id
// */
// public final Integer getId() {
// return id;
// }
//
// /**
// * @param id
// * the id to set
// */
// public final void setId(final Integer id) {
// this.id = id;
// }
//
// /**
// * @return the name
// */
// public final String getName() {
// return name;
// }
//
// /**
// * @param name
// * the name to set
// */
// public final void setName(final String name) {
// this.name = name;
// }
//
// }
// Path: src/test/java/com/example/ejb3/beans/WidgetBean.java
import java.util.List;
import javax.annotation.PostConstruct;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import com.example.dao.WidgetDao;
import com.example.dao.jpa.JpaWidgetDao;
import com.example.model.Widget;
/**
* junit-rules: JUnit Rules Library
*
* Copyright (c) 2009-2011 by Alistair A. Israel.
* This software is made available under the terms of the MIT License.
*
* Created Oct 16, 2009
*/
package com.example.ejb3.beans;
/**
* @author Alistair A. Israel
*/
public class WidgetBean {
@PersistenceContext
private EntityManager em;
| private WidgetDao widgetDao; |
aisrael/junit-rules | src/test/java/com/example/ejb3/beans/WidgetBean.java | // Path: src/test/java/com/example/dao/WidgetDao.java
// public interface WidgetDao {
//
// /**
// * @return {@link List}<{@link Widget}>
// */
// List<Widget> listAll();
//
// /**
// * @param id
// * the widget id
// * @return {@link Widget}
// */
// Widget findById(int id);
//
// /**
// * @param name
// * the widget name
// * @return {@link Widget}
// */
// Widget findByName(String name);
//
// }
//
// Path: src/test/java/com/example/dao/jpa/JpaWidgetDao.java
// public class JpaWidgetDao implements WidgetDao {
//
// private final EntityManager entityManager;
//
// /**
// * @param entityManager
// * the {@link EntityManager}
// */
// public JpaWidgetDao(final EntityManager entityManager) {
// this.entityManager = entityManager;
// }
//
// /**
// * {@inheritDoc}
// *
// * @see com.example.dao.WidgetDao#findById(int)
// */
// @Override
// public final Widget findById(final int id) {
// return entityManager.find(Widget.class, id);
// }
//
// /**
// * {@inheritDoc}
// *
// * @see com.example.dao.WidgetDao#findByName(java.lang.String)
// */
// @Override
// @SuppressWarnings("unchecked")
// public final Widget findByName(final String name) {
// final List<Widget> list = entityManager.createNamedQuery(Widget.FIND_BY_NAME).setParameter("name", name)
// .getResultList();
// if (list.isEmpty()) {
// return null;
// }
// return list.get(0);
// }
//
// /**
// * {@inheritDoc}
// *
// * @see com.example.dao.WidgetDao#listAll()
// */
// @Override
// @SuppressWarnings("unchecked")
// public final List<Widget> listAll() {
// return entityManager.createNamedQuery(Widget.LIST_ALL).getResultList();
// }
//
// }
//
// Path: src/test/java/com/example/model/Widget.java
// @Entity
// @NamedQueries({
// @NamedQuery(name = Widget.LIST_ALL, query = "SELECT w FROM Widget w"),
// @NamedQuery(name = Widget.FIND_BY_ID, query = "SELECT w FROM Widget w WHERE w.id = :id"),
// @NamedQuery(name = Widget.FIND_BY_NAME, query = "SELECT w FROM Widget w WHERE w.name = :name")
// })
// public class Widget implements Serializable {
//
// /**
// *
// */
// private static final long serialVersionUID = -1689099836716604893L;
//
// /**
// * {@value #LIST_ALL}
// */
// public static final String LIST_ALL = "Widget.listAll";
//
// /**
// * {@value #FIND_BY_ID}
// */
// public static final String FIND_BY_ID = "Widget.findById";
//
// /**
// * {@value #FIND_BY_NAME}
// */
// public static final String FIND_BY_NAME = "Widget.findByName";
//
// @Id
// private Integer id;
//
// @Column
// private String name;
//
// /**
// * @return the id
// */
// public final Integer getId() {
// return id;
// }
//
// /**
// * @param id
// * the id to set
// */
// public final void setId(final Integer id) {
// this.id = id;
// }
//
// /**
// * @return the name
// */
// public final String getName() {
// return name;
// }
//
// /**
// * @param name
// * the name to set
// */
// public final void setName(final String name) {
// this.name = name;
// }
//
// }
| import java.util.List;
import javax.annotation.PostConstruct;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import com.example.dao.WidgetDao;
import com.example.dao.jpa.JpaWidgetDao;
import com.example.model.Widget; | /**
* junit-rules: JUnit Rules Library
*
* Copyright (c) 2009-2011 by Alistair A. Israel.
* This software is made available under the terms of the MIT License.
*
* Created Oct 16, 2009
*/
package com.example.ejb3.beans;
/**
* @author Alistair A. Israel
*/
public class WidgetBean {
@PersistenceContext
private EntityManager em;
private WidgetDao widgetDao;
/**
* We create the {@link JpaWidgetDao}
*/
@PostConstruct
@SuppressWarnings("unused")
private void initialize() { | // Path: src/test/java/com/example/dao/WidgetDao.java
// public interface WidgetDao {
//
// /**
// * @return {@link List}<{@link Widget}>
// */
// List<Widget> listAll();
//
// /**
// * @param id
// * the widget id
// * @return {@link Widget}
// */
// Widget findById(int id);
//
// /**
// * @param name
// * the widget name
// * @return {@link Widget}
// */
// Widget findByName(String name);
//
// }
//
// Path: src/test/java/com/example/dao/jpa/JpaWidgetDao.java
// public class JpaWidgetDao implements WidgetDao {
//
// private final EntityManager entityManager;
//
// /**
// * @param entityManager
// * the {@link EntityManager}
// */
// public JpaWidgetDao(final EntityManager entityManager) {
// this.entityManager = entityManager;
// }
//
// /**
// * {@inheritDoc}
// *
// * @see com.example.dao.WidgetDao#findById(int)
// */
// @Override
// public final Widget findById(final int id) {
// return entityManager.find(Widget.class, id);
// }
//
// /**
// * {@inheritDoc}
// *
// * @see com.example.dao.WidgetDao#findByName(java.lang.String)
// */
// @Override
// @SuppressWarnings("unchecked")
// public final Widget findByName(final String name) {
// final List<Widget> list = entityManager.createNamedQuery(Widget.FIND_BY_NAME).setParameter("name", name)
// .getResultList();
// if (list.isEmpty()) {
// return null;
// }
// return list.get(0);
// }
//
// /**
// * {@inheritDoc}
// *
// * @see com.example.dao.WidgetDao#listAll()
// */
// @Override
// @SuppressWarnings("unchecked")
// public final List<Widget> listAll() {
// return entityManager.createNamedQuery(Widget.LIST_ALL).getResultList();
// }
//
// }
//
// Path: src/test/java/com/example/model/Widget.java
// @Entity
// @NamedQueries({
// @NamedQuery(name = Widget.LIST_ALL, query = "SELECT w FROM Widget w"),
// @NamedQuery(name = Widget.FIND_BY_ID, query = "SELECT w FROM Widget w WHERE w.id = :id"),
// @NamedQuery(name = Widget.FIND_BY_NAME, query = "SELECT w FROM Widget w WHERE w.name = :name")
// })
// public class Widget implements Serializable {
//
// /**
// *
// */
// private static final long serialVersionUID = -1689099836716604893L;
//
// /**
// * {@value #LIST_ALL}
// */
// public static final String LIST_ALL = "Widget.listAll";
//
// /**
// * {@value #FIND_BY_ID}
// */
// public static final String FIND_BY_ID = "Widget.findById";
//
// /**
// * {@value #FIND_BY_NAME}
// */
// public static final String FIND_BY_NAME = "Widget.findByName";
//
// @Id
// private Integer id;
//
// @Column
// private String name;
//
// /**
// * @return the id
// */
// public final Integer getId() {
// return id;
// }
//
// /**
// * @param id
// * the id to set
// */
// public final void setId(final Integer id) {
// this.id = id;
// }
//
// /**
// * @return the name
// */
// public final String getName() {
// return name;
// }
//
// /**
// * @param name
// * the name to set
// */
// public final void setName(final String name) {
// this.name = name;
// }
//
// }
// Path: src/test/java/com/example/ejb3/beans/WidgetBean.java
import java.util.List;
import javax.annotation.PostConstruct;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import com.example.dao.WidgetDao;
import com.example.dao.jpa.JpaWidgetDao;
import com.example.model.Widget;
/**
* junit-rules: JUnit Rules Library
*
* Copyright (c) 2009-2011 by Alistair A. Israel.
* This software is made available under the terms of the MIT License.
*
* Created Oct 16, 2009
*/
package com.example.ejb3.beans;
/**
* @author Alistair A. Israel
*/
public class WidgetBean {
@PersistenceContext
private EntityManager em;
private WidgetDao widgetDao;
/**
* We create the {@link JpaWidgetDao}
*/
@PostConstruct
@SuppressWarnings("unused")
private void initialize() { | widgetDao = new JpaWidgetDao(em); |
aisrael/junit-rules | src/test/java/com/example/ejb3/beans/WidgetBean.java | // Path: src/test/java/com/example/dao/WidgetDao.java
// public interface WidgetDao {
//
// /**
// * @return {@link List}<{@link Widget}>
// */
// List<Widget> listAll();
//
// /**
// * @param id
// * the widget id
// * @return {@link Widget}
// */
// Widget findById(int id);
//
// /**
// * @param name
// * the widget name
// * @return {@link Widget}
// */
// Widget findByName(String name);
//
// }
//
// Path: src/test/java/com/example/dao/jpa/JpaWidgetDao.java
// public class JpaWidgetDao implements WidgetDao {
//
// private final EntityManager entityManager;
//
// /**
// * @param entityManager
// * the {@link EntityManager}
// */
// public JpaWidgetDao(final EntityManager entityManager) {
// this.entityManager = entityManager;
// }
//
// /**
// * {@inheritDoc}
// *
// * @see com.example.dao.WidgetDao#findById(int)
// */
// @Override
// public final Widget findById(final int id) {
// return entityManager.find(Widget.class, id);
// }
//
// /**
// * {@inheritDoc}
// *
// * @see com.example.dao.WidgetDao#findByName(java.lang.String)
// */
// @Override
// @SuppressWarnings("unchecked")
// public final Widget findByName(final String name) {
// final List<Widget> list = entityManager.createNamedQuery(Widget.FIND_BY_NAME).setParameter("name", name)
// .getResultList();
// if (list.isEmpty()) {
// return null;
// }
// return list.get(0);
// }
//
// /**
// * {@inheritDoc}
// *
// * @see com.example.dao.WidgetDao#listAll()
// */
// @Override
// @SuppressWarnings("unchecked")
// public final List<Widget> listAll() {
// return entityManager.createNamedQuery(Widget.LIST_ALL).getResultList();
// }
//
// }
//
// Path: src/test/java/com/example/model/Widget.java
// @Entity
// @NamedQueries({
// @NamedQuery(name = Widget.LIST_ALL, query = "SELECT w FROM Widget w"),
// @NamedQuery(name = Widget.FIND_BY_ID, query = "SELECT w FROM Widget w WHERE w.id = :id"),
// @NamedQuery(name = Widget.FIND_BY_NAME, query = "SELECT w FROM Widget w WHERE w.name = :name")
// })
// public class Widget implements Serializable {
//
// /**
// *
// */
// private static final long serialVersionUID = -1689099836716604893L;
//
// /**
// * {@value #LIST_ALL}
// */
// public static final String LIST_ALL = "Widget.listAll";
//
// /**
// * {@value #FIND_BY_ID}
// */
// public static final String FIND_BY_ID = "Widget.findById";
//
// /**
// * {@value #FIND_BY_NAME}
// */
// public static final String FIND_BY_NAME = "Widget.findByName";
//
// @Id
// private Integer id;
//
// @Column
// private String name;
//
// /**
// * @return the id
// */
// public final Integer getId() {
// return id;
// }
//
// /**
// * @param id
// * the id to set
// */
// public final void setId(final Integer id) {
// this.id = id;
// }
//
// /**
// * @return the name
// */
// public final String getName() {
// return name;
// }
//
// /**
// * @param name
// * the name to set
// */
// public final void setName(final String name) {
// this.name = name;
// }
//
// }
| import java.util.List;
import javax.annotation.PostConstruct;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import com.example.dao.WidgetDao;
import com.example.dao.jpa.JpaWidgetDao;
import com.example.model.Widget; | /**
* junit-rules: JUnit Rules Library
*
* Copyright (c) 2009-2011 by Alistair A. Israel.
* This software is made available under the terms of the MIT License.
*
* Created Oct 16, 2009
*/
package com.example.ejb3.beans;
/**
* @author Alistair A. Israel
*/
public class WidgetBean {
@PersistenceContext
private EntityManager em;
private WidgetDao widgetDao;
/**
* We create the {@link JpaWidgetDao}
*/
@PostConstruct
@SuppressWarnings("unused")
private void initialize() {
widgetDao = new JpaWidgetDao(em);
}
/**
* @return list of all widgets
*/ | // Path: src/test/java/com/example/dao/WidgetDao.java
// public interface WidgetDao {
//
// /**
// * @return {@link List}<{@link Widget}>
// */
// List<Widget> listAll();
//
// /**
// * @param id
// * the widget id
// * @return {@link Widget}
// */
// Widget findById(int id);
//
// /**
// * @param name
// * the widget name
// * @return {@link Widget}
// */
// Widget findByName(String name);
//
// }
//
// Path: src/test/java/com/example/dao/jpa/JpaWidgetDao.java
// public class JpaWidgetDao implements WidgetDao {
//
// private final EntityManager entityManager;
//
// /**
// * @param entityManager
// * the {@link EntityManager}
// */
// public JpaWidgetDao(final EntityManager entityManager) {
// this.entityManager = entityManager;
// }
//
// /**
// * {@inheritDoc}
// *
// * @see com.example.dao.WidgetDao#findById(int)
// */
// @Override
// public final Widget findById(final int id) {
// return entityManager.find(Widget.class, id);
// }
//
// /**
// * {@inheritDoc}
// *
// * @see com.example.dao.WidgetDao#findByName(java.lang.String)
// */
// @Override
// @SuppressWarnings("unchecked")
// public final Widget findByName(final String name) {
// final List<Widget> list = entityManager.createNamedQuery(Widget.FIND_BY_NAME).setParameter("name", name)
// .getResultList();
// if (list.isEmpty()) {
// return null;
// }
// return list.get(0);
// }
//
// /**
// * {@inheritDoc}
// *
// * @see com.example.dao.WidgetDao#listAll()
// */
// @Override
// @SuppressWarnings("unchecked")
// public final List<Widget> listAll() {
// return entityManager.createNamedQuery(Widget.LIST_ALL).getResultList();
// }
//
// }
//
// Path: src/test/java/com/example/model/Widget.java
// @Entity
// @NamedQueries({
// @NamedQuery(name = Widget.LIST_ALL, query = "SELECT w FROM Widget w"),
// @NamedQuery(name = Widget.FIND_BY_ID, query = "SELECT w FROM Widget w WHERE w.id = :id"),
// @NamedQuery(name = Widget.FIND_BY_NAME, query = "SELECT w FROM Widget w WHERE w.name = :name")
// })
// public class Widget implements Serializable {
//
// /**
// *
// */
// private static final long serialVersionUID = -1689099836716604893L;
//
// /**
// * {@value #LIST_ALL}
// */
// public static final String LIST_ALL = "Widget.listAll";
//
// /**
// * {@value #FIND_BY_ID}
// */
// public static final String FIND_BY_ID = "Widget.findById";
//
// /**
// * {@value #FIND_BY_NAME}
// */
// public static final String FIND_BY_NAME = "Widget.findByName";
//
// @Id
// private Integer id;
//
// @Column
// private String name;
//
// /**
// * @return the id
// */
// public final Integer getId() {
// return id;
// }
//
// /**
// * @param id
// * the id to set
// */
// public final void setId(final Integer id) {
// this.id = id;
// }
//
// /**
// * @return the name
// */
// public final String getName() {
// return name;
// }
//
// /**
// * @param name
// * the name to set
// */
// public final void setName(final String name) {
// this.name = name;
// }
//
// }
// Path: src/test/java/com/example/ejb3/beans/WidgetBean.java
import java.util.List;
import javax.annotation.PostConstruct;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import com.example.dao.WidgetDao;
import com.example.dao.jpa.JpaWidgetDao;
import com.example.model.Widget;
/**
* junit-rules: JUnit Rules Library
*
* Copyright (c) 2009-2011 by Alistair A. Israel.
* This software is made available under the terms of the MIT License.
*
* Created Oct 16, 2009
*/
package com.example.ejb3.beans;
/**
* @author Alistair A. Israel
*/
public class WidgetBean {
@PersistenceContext
private EntityManager em;
private WidgetDao widgetDao;
/**
* We create the {@link JpaWidgetDao}
*/
@PostConstruct
@SuppressWarnings("unused")
private void initialize() {
widgetDao = new JpaWidgetDao(em);
}
/**
* @return list of all widgets
*/ | public final List<Widget> listAll() { |
aisrael/junit-rules | src/main/java/junit/rules/jpa/hibernate/DerbyHibernateTestCase.java | // Path: src/main/java/junit/rules/jpa/hibernate/DerbyHibernateUtil.java
// public static final String JDBC_DERBY_URL = "jdbc:derby:test";
//
// Path: src/main/java/junit/rules/util/Reflection.java
// public static MethodInvoker invoke(final Method method) {
// return new MethodInvoker(method);
// }
//
// Path: src/main/java/junit/rules/util/Reflection.java
// public static FieldWrapper set(final Field field) {
// return new FieldWrapper(field);
// }
//
// Path: src/main/java/junit/rules/dbunit/DbUnitUtil.java
// public final class DbUnitUtil {
//
// private static final Logger LOGGER = LoggerFactory.getLogger(DbUnitUtil.class);
//
// /**
// * Utility classes should not have a public or default constructor.
// */
// private DbUnitUtil() {
// // noop
// }
//
// /**
// * @param fixtureNames
// * the fixture names
// * @return IDataSet[]
// */
// public static IDataSet[] loadDataSets(final List<String> fixtureNames) {
// final List<IDataSet> dataSets = new ArrayList<IDataSet>();
//
// for (final String fixtureName : fixtureNames) {
// LOGGER.trace("Attempting to load database fixture \"" + fixtureName + "\"");
// final IDataSet dataSet = attemptToLoadFixture(fixtureName);
// if (dataSet != null) {
// dataSets.add(dataSet);
// }
// }
//
// return dataSets.toArray(new IDataSet[dataSets.size()]);
// }
//
// /**
// * @param fixtureName
// * the fixture name
// * @return {@link IDataSet}
// */
// private static IDataSet attemptToLoadFixture(final String fixtureName) {
// IDataSet dataSet = null;
//
// try {
// final InputStream in = new FileInputStream(getFile(fixtureName));
// try {
// if (in != null) {
// if (fixtureName.endsWith(".xml")) {
// dataSet = new XmlDataSet(in);
// }
// }
// } finally {
// in.close();
// }
// } catch (final Exception e) {
// throw new Error(e.getMessage(), e);
// }
// return dataSet;
// }
//
// /**
// * @param fixtureName
// * the fixture (file) name
// * @return the {@link File} with the prefix
// */
// public static File getFile(final String fixtureName) {
// return new File("src/test/db/fixtures", fixtureName);
// }
//
// }
//
// Path: src/main/java/junit/rules/dbunit/FixturesUtil.java
// public final class FixturesUtil {
//
// /**
// * Utility classes should not have a public or default constructor.
// */
// private FixturesUtil() {
// // noop
// }
//
// /**
// * @param elements
// * the Class(es) or Method(s) to inspect for the {@link Fixtures} annotation
// * @return the list of fixture names
// */
// public static List<String> getFixtureNames(final AnnotatedElement... elements) {
// final List<String> fixtureNames = new ArrayList<String>();
// for (final AnnotatedElement element : elements) {
// if (element.isAnnotationPresent(Fixtures.class)) {
// for (final String fixtureName : element.getAnnotation(Fixtures.class).value()) {
// fixtureNames.add(fixtureName);
// }
// }
// }
// return fixtureNames;
// }
//
// }
| import static junit.rules.jpa.hibernate.DerbyHibernateUtil.JDBC_DERBY_URL;
import static junit.rules.util.Reflection.invoke;
import static junit.rules.util.Reflection.set;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.List;
import javax.annotation.PostConstruct;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.PersistenceContext;
import junit.rules.dbunit.DbUnitUtil;
import junit.rules.dbunit.FixturesUtil;
import org.apache.derby.jdbc.EmbeddedDriver;
import org.dbunit.JdbcDatabaseTester;
import org.dbunit.dataset.CompositeDataSet;
import org.dbunit.dataset.DataSetException;
import org.dbunit.dataset.IDataSet;
import org.hibernate.ejb.Ejb3Configuration;
import org.junit.After;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory; | /**
* junit-rules: JUnit Rules Library
*
* Copyright (c) 2009-2011 by Alistair A. Israel.
* This software is made available under the terms of the MIT License.
*
* Created Oct 22, 2009
*/
package junit.rules.jpa.hibernate;
/**
* @author Alistair A. Israel
*/
public class DerbyHibernateTestCase {
private static final Logger logger = LoggerFactory.getLogger(HibernatePersistenceContext.class);
private static final ThreadLocal<EntityManagerFactory> ENTITY_MANAGER_FACTORY = new ThreadLocal<EntityManagerFactory>();
private EntityManager entityManager;
private JdbcDatabaseTester jdbcDatabaseTester;
/**
*
*/
@BeforeClass
public static void initializeDerbyHibernate() {
final Ejb3Configuration configuration = DerbyHibernateUtil.configureDerbyHibernateJpa(); | // Path: src/main/java/junit/rules/jpa/hibernate/DerbyHibernateUtil.java
// public static final String JDBC_DERBY_URL = "jdbc:derby:test";
//
// Path: src/main/java/junit/rules/util/Reflection.java
// public static MethodInvoker invoke(final Method method) {
// return new MethodInvoker(method);
// }
//
// Path: src/main/java/junit/rules/util/Reflection.java
// public static FieldWrapper set(final Field field) {
// return new FieldWrapper(field);
// }
//
// Path: src/main/java/junit/rules/dbunit/DbUnitUtil.java
// public final class DbUnitUtil {
//
// private static final Logger LOGGER = LoggerFactory.getLogger(DbUnitUtil.class);
//
// /**
// * Utility classes should not have a public or default constructor.
// */
// private DbUnitUtil() {
// // noop
// }
//
// /**
// * @param fixtureNames
// * the fixture names
// * @return IDataSet[]
// */
// public static IDataSet[] loadDataSets(final List<String> fixtureNames) {
// final List<IDataSet> dataSets = new ArrayList<IDataSet>();
//
// for (final String fixtureName : fixtureNames) {
// LOGGER.trace("Attempting to load database fixture \"" + fixtureName + "\"");
// final IDataSet dataSet = attemptToLoadFixture(fixtureName);
// if (dataSet != null) {
// dataSets.add(dataSet);
// }
// }
//
// return dataSets.toArray(new IDataSet[dataSets.size()]);
// }
//
// /**
// * @param fixtureName
// * the fixture name
// * @return {@link IDataSet}
// */
// private static IDataSet attemptToLoadFixture(final String fixtureName) {
// IDataSet dataSet = null;
//
// try {
// final InputStream in = new FileInputStream(getFile(fixtureName));
// try {
// if (in != null) {
// if (fixtureName.endsWith(".xml")) {
// dataSet = new XmlDataSet(in);
// }
// }
// } finally {
// in.close();
// }
// } catch (final Exception e) {
// throw new Error(e.getMessage(), e);
// }
// return dataSet;
// }
//
// /**
// * @param fixtureName
// * the fixture (file) name
// * @return the {@link File} with the prefix
// */
// public static File getFile(final String fixtureName) {
// return new File("src/test/db/fixtures", fixtureName);
// }
//
// }
//
// Path: src/main/java/junit/rules/dbunit/FixturesUtil.java
// public final class FixturesUtil {
//
// /**
// * Utility classes should not have a public or default constructor.
// */
// private FixturesUtil() {
// // noop
// }
//
// /**
// * @param elements
// * the Class(es) or Method(s) to inspect for the {@link Fixtures} annotation
// * @return the list of fixture names
// */
// public static List<String> getFixtureNames(final AnnotatedElement... elements) {
// final List<String> fixtureNames = new ArrayList<String>();
// for (final AnnotatedElement element : elements) {
// if (element.isAnnotationPresent(Fixtures.class)) {
// for (final String fixtureName : element.getAnnotation(Fixtures.class).value()) {
// fixtureNames.add(fixtureName);
// }
// }
// }
// return fixtureNames;
// }
//
// }
// Path: src/main/java/junit/rules/jpa/hibernate/DerbyHibernateTestCase.java
import static junit.rules.jpa.hibernate.DerbyHibernateUtil.JDBC_DERBY_URL;
import static junit.rules.util.Reflection.invoke;
import static junit.rules.util.Reflection.set;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.List;
import javax.annotation.PostConstruct;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.PersistenceContext;
import junit.rules.dbunit.DbUnitUtil;
import junit.rules.dbunit.FixturesUtil;
import org.apache.derby.jdbc.EmbeddedDriver;
import org.dbunit.JdbcDatabaseTester;
import org.dbunit.dataset.CompositeDataSet;
import org.dbunit.dataset.DataSetException;
import org.dbunit.dataset.IDataSet;
import org.hibernate.ejb.Ejb3Configuration;
import org.junit.After;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* junit-rules: JUnit Rules Library
*
* Copyright (c) 2009-2011 by Alistair A. Israel.
* This software is made available under the terms of the MIT License.
*
* Created Oct 22, 2009
*/
package junit.rules.jpa.hibernate;
/**
* @author Alistair A. Israel
*/
public class DerbyHibernateTestCase {
private static final Logger logger = LoggerFactory.getLogger(HibernatePersistenceContext.class);
private static final ThreadLocal<EntityManagerFactory> ENTITY_MANAGER_FACTORY = new ThreadLocal<EntityManagerFactory>();
private EntityManager entityManager;
private JdbcDatabaseTester jdbcDatabaseTester;
/**
*
*/
@BeforeClass
public static void initializeDerbyHibernate() {
final Ejb3Configuration configuration = DerbyHibernateUtil.configureDerbyHibernateJpa(); | ENTITY_MANAGER_FACTORY.set(configuration.buildEntityManagerFactory()); |
aisrael/junit-rules | src/main/java/junit/rules/jpa/hibernate/DerbyHibernateTestCase.java | // Path: src/main/java/junit/rules/jpa/hibernate/DerbyHibernateUtil.java
// public static final String JDBC_DERBY_URL = "jdbc:derby:test";
//
// Path: src/main/java/junit/rules/util/Reflection.java
// public static MethodInvoker invoke(final Method method) {
// return new MethodInvoker(method);
// }
//
// Path: src/main/java/junit/rules/util/Reflection.java
// public static FieldWrapper set(final Field field) {
// return new FieldWrapper(field);
// }
//
// Path: src/main/java/junit/rules/dbunit/DbUnitUtil.java
// public final class DbUnitUtil {
//
// private static final Logger LOGGER = LoggerFactory.getLogger(DbUnitUtil.class);
//
// /**
// * Utility classes should not have a public or default constructor.
// */
// private DbUnitUtil() {
// // noop
// }
//
// /**
// * @param fixtureNames
// * the fixture names
// * @return IDataSet[]
// */
// public static IDataSet[] loadDataSets(final List<String> fixtureNames) {
// final List<IDataSet> dataSets = new ArrayList<IDataSet>();
//
// for (final String fixtureName : fixtureNames) {
// LOGGER.trace("Attempting to load database fixture \"" + fixtureName + "\"");
// final IDataSet dataSet = attemptToLoadFixture(fixtureName);
// if (dataSet != null) {
// dataSets.add(dataSet);
// }
// }
//
// return dataSets.toArray(new IDataSet[dataSets.size()]);
// }
//
// /**
// * @param fixtureName
// * the fixture name
// * @return {@link IDataSet}
// */
// private static IDataSet attemptToLoadFixture(final String fixtureName) {
// IDataSet dataSet = null;
//
// try {
// final InputStream in = new FileInputStream(getFile(fixtureName));
// try {
// if (in != null) {
// if (fixtureName.endsWith(".xml")) {
// dataSet = new XmlDataSet(in);
// }
// }
// } finally {
// in.close();
// }
// } catch (final Exception e) {
// throw new Error(e.getMessage(), e);
// }
// return dataSet;
// }
//
// /**
// * @param fixtureName
// * the fixture (file) name
// * @return the {@link File} with the prefix
// */
// public static File getFile(final String fixtureName) {
// return new File("src/test/db/fixtures", fixtureName);
// }
//
// }
//
// Path: src/main/java/junit/rules/dbunit/FixturesUtil.java
// public final class FixturesUtil {
//
// /**
// * Utility classes should not have a public or default constructor.
// */
// private FixturesUtil() {
// // noop
// }
//
// /**
// * @param elements
// * the Class(es) or Method(s) to inspect for the {@link Fixtures} annotation
// * @return the list of fixture names
// */
// public static List<String> getFixtureNames(final AnnotatedElement... elements) {
// final List<String> fixtureNames = new ArrayList<String>();
// for (final AnnotatedElement element : elements) {
// if (element.isAnnotationPresent(Fixtures.class)) {
// for (final String fixtureName : element.getAnnotation(Fixtures.class).value()) {
// fixtureNames.add(fixtureName);
// }
// }
// }
// return fixtureNames;
// }
//
// }
| import static junit.rules.jpa.hibernate.DerbyHibernateUtil.JDBC_DERBY_URL;
import static junit.rules.util.Reflection.invoke;
import static junit.rules.util.Reflection.set;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.List;
import javax.annotation.PostConstruct;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.PersistenceContext;
import junit.rules.dbunit.DbUnitUtil;
import junit.rules.dbunit.FixturesUtil;
import org.apache.derby.jdbc.EmbeddedDriver;
import org.dbunit.JdbcDatabaseTester;
import org.dbunit.dataset.CompositeDataSet;
import org.dbunit.dataset.DataSetException;
import org.dbunit.dataset.IDataSet;
import org.hibernate.ejb.Ejb3Configuration;
import org.junit.After;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory; | /**
* junit-rules: JUnit Rules Library
*
* Copyright (c) 2009-2011 by Alistair A. Israel.
* This software is made available under the terms of the MIT License.
*
* Created Oct 22, 2009
*/
package junit.rules.jpa.hibernate;
/**
* @author Alistair A. Israel
*/
public class DerbyHibernateTestCase {
private static final Logger logger = LoggerFactory.getLogger(HibernatePersistenceContext.class);
private static final ThreadLocal<EntityManagerFactory> ENTITY_MANAGER_FACTORY = new ThreadLocal<EntityManagerFactory>();
private EntityManager entityManager;
private JdbcDatabaseTester jdbcDatabaseTester;
/**
*
*/
@BeforeClass
public static void initializeDerbyHibernate() {
final Ejb3Configuration configuration = DerbyHibernateUtil.configureDerbyHibernateJpa();
ENTITY_MANAGER_FACTORY.set(configuration.buildEntityManagerFactory());
}
/**
*
*/
@AfterClass
public static void closeHibernateDerby() {
ENTITY_MANAGER_FACTORY.get().close();
try { | // Path: src/main/java/junit/rules/jpa/hibernate/DerbyHibernateUtil.java
// public static final String JDBC_DERBY_URL = "jdbc:derby:test";
//
// Path: src/main/java/junit/rules/util/Reflection.java
// public static MethodInvoker invoke(final Method method) {
// return new MethodInvoker(method);
// }
//
// Path: src/main/java/junit/rules/util/Reflection.java
// public static FieldWrapper set(final Field field) {
// return new FieldWrapper(field);
// }
//
// Path: src/main/java/junit/rules/dbunit/DbUnitUtil.java
// public final class DbUnitUtil {
//
// private static final Logger LOGGER = LoggerFactory.getLogger(DbUnitUtil.class);
//
// /**
// * Utility classes should not have a public or default constructor.
// */
// private DbUnitUtil() {
// // noop
// }
//
// /**
// * @param fixtureNames
// * the fixture names
// * @return IDataSet[]
// */
// public static IDataSet[] loadDataSets(final List<String> fixtureNames) {
// final List<IDataSet> dataSets = new ArrayList<IDataSet>();
//
// for (final String fixtureName : fixtureNames) {
// LOGGER.trace("Attempting to load database fixture \"" + fixtureName + "\"");
// final IDataSet dataSet = attemptToLoadFixture(fixtureName);
// if (dataSet != null) {
// dataSets.add(dataSet);
// }
// }
//
// return dataSets.toArray(new IDataSet[dataSets.size()]);
// }
//
// /**
// * @param fixtureName
// * the fixture name
// * @return {@link IDataSet}
// */
// private static IDataSet attemptToLoadFixture(final String fixtureName) {
// IDataSet dataSet = null;
//
// try {
// final InputStream in = new FileInputStream(getFile(fixtureName));
// try {
// if (in != null) {
// if (fixtureName.endsWith(".xml")) {
// dataSet = new XmlDataSet(in);
// }
// }
// } finally {
// in.close();
// }
// } catch (final Exception e) {
// throw new Error(e.getMessage(), e);
// }
// return dataSet;
// }
//
// /**
// * @param fixtureName
// * the fixture (file) name
// * @return the {@link File} with the prefix
// */
// public static File getFile(final String fixtureName) {
// return new File("src/test/db/fixtures", fixtureName);
// }
//
// }
//
// Path: src/main/java/junit/rules/dbunit/FixturesUtil.java
// public final class FixturesUtil {
//
// /**
// * Utility classes should not have a public or default constructor.
// */
// private FixturesUtil() {
// // noop
// }
//
// /**
// * @param elements
// * the Class(es) or Method(s) to inspect for the {@link Fixtures} annotation
// * @return the list of fixture names
// */
// public static List<String> getFixtureNames(final AnnotatedElement... elements) {
// final List<String> fixtureNames = new ArrayList<String>();
// for (final AnnotatedElement element : elements) {
// if (element.isAnnotationPresent(Fixtures.class)) {
// for (final String fixtureName : element.getAnnotation(Fixtures.class).value()) {
// fixtureNames.add(fixtureName);
// }
// }
// }
// return fixtureNames;
// }
//
// }
// Path: src/main/java/junit/rules/jpa/hibernate/DerbyHibernateTestCase.java
import static junit.rules.jpa.hibernate.DerbyHibernateUtil.JDBC_DERBY_URL;
import static junit.rules.util.Reflection.invoke;
import static junit.rules.util.Reflection.set;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.List;
import javax.annotation.PostConstruct;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.PersistenceContext;
import junit.rules.dbunit.DbUnitUtil;
import junit.rules.dbunit.FixturesUtil;
import org.apache.derby.jdbc.EmbeddedDriver;
import org.dbunit.JdbcDatabaseTester;
import org.dbunit.dataset.CompositeDataSet;
import org.dbunit.dataset.DataSetException;
import org.dbunit.dataset.IDataSet;
import org.hibernate.ejb.Ejb3Configuration;
import org.junit.After;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* junit-rules: JUnit Rules Library
*
* Copyright (c) 2009-2011 by Alistair A. Israel.
* This software is made available under the terms of the MIT License.
*
* Created Oct 22, 2009
*/
package junit.rules.jpa.hibernate;
/**
* @author Alistair A. Israel
*/
public class DerbyHibernateTestCase {
private static final Logger logger = LoggerFactory.getLogger(HibernatePersistenceContext.class);
private static final ThreadLocal<EntityManagerFactory> ENTITY_MANAGER_FACTORY = new ThreadLocal<EntityManagerFactory>();
private EntityManager entityManager;
private JdbcDatabaseTester jdbcDatabaseTester;
/**
*
*/
@BeforeClass
public static void initializeDerbyHibernate() {
final Ejb3Configuration configuration = DerbyHibernateUtil.configureDerbyHibernateJpa();
ENTITY_MANAGER_FACTORY.set(configuration.buildEntityManagerFactory());
}
/**
*
*/
@AfterClass
public static void closeHibernateDerby() {
ENTITY_MANAGER_FACTORY.get().close();
try { | DriverManager.getConnection(JDBC_DERBY_URL + ";shutdown=true"); |
aisrael/junit-rules | src/main/java/junit/rules/jpa/hibernate/DerbyHibernateTestCase.java | // Path: src/main/java/junit/rules/jpa/hibernate/DerbyHibernateUtil.java
// public static final String JDBC_DERBY_URL = "jdbc:derby:test";
//
// Path: src/main/java/junit/rules/util/Reflection.java
// public static MethodInvoker invoke(final Method method) {
// return new MethodInvoker(method);
// }
//
// Path: src/main/java/junit/rules/util/Reflection.java
// public static FieldWrapper set(final Field field) {
// return new FieldWrapper(field);
// }
//
// Path: src/main/java/junit/rules/dbunit/DbUnitUtil.java
// public final class DbUnitUtil {
//
// private static final Logger LOGGER = LoggerFactory.getLogger(DbUnitUtil.class);
//
// /**
// * Utility classes should not have a public or default constructor.
// */
// private DbUnitUtil() {
// // noop
// }
//
// /**
// * @param fixtureNames
// * the fixture names
// * @return IDataSet[]
// */
// public static IDataSet[] loadDataSets(final List<String> fixtureNames) {
// final List<IDataSet> dataSets = new ArrayList<IDataSet>();
//
// for (final String fixtureName : fixtureNames) {
// LOGGER.trace("Attempting to load database fixture \"" + fixtureName + "\"");
// final IDataSet dataSet = attemptToLoadFixture(fixtureName);
// if (dataSet != null) {
// dataSets.add(dataSet);
// }
// }
//
// return dataSets.toArray(new IDataSet[dataSets.size()]);
// }
//
// /**
// * @param fixtureName
// * the fixture name
// * @return {@link IDataSet}
// */
// private static IDataSet attemptToLoadFixture(final String fixtureName) {
// IDataSet dataSet = null;
//
// try {
// final InputStream in = new FileInputStream(getFile(fixtureName));
// try {
// if (in != null) {
// if (fixtureName.endsWith(".xml")) {
// dataSet = new XmlDataSet(in);
// }
// }
// } finally {
// in.close();
// }
// } catch (final Exception e) {
// throw new Error(e.getMessage(), e);
// }
// return dataSet;
// }
//
// /**
// * @param fixtureName
// * the fixture (file) name
// * @return the {@link File} with the prefix
// */
// public static File getFile(final String fixtureName) {
// return new File("src/test/db/fixtures", fixtureName);
// }
//
// }
//
// Path: src/main/java/junit/rules/dbunit/FixturesUtil.java
// public final class FixturesUtil {
//
// /**
// * Utility classes should not have a public or default constructor.
// */
// private FixturesUtil() {
// // noop
// }
//
// /**
// * @param elements
// * the Class(es) or Method(s) to inspect for the {@link Fixtures} annotation
// * @return the list of fixture names
// */
// public static List<String> getFixtureNames(final AnnotatedElement... elements) {
// final List<String> fixtureNames = new ArrayList<String>();
// for (final AnnotatedElement element : elements) {
// if (element.isAnnotationPresent(Fixtures.class)) {
// for (final String fixtureName : element.getAnnotation(Fixtures.class).value()) {
// fixtureNames.add(fixtureName);
// }
// }
// }
// return fixtureNames;
// }
//
// }
| import static junit.rules.jpa.hibernate.DerbyHibernateUtil.JDBC_DERBY_URL;
import static junit.rules.util.Reflection.invoke;
import static junit.rules.util.Reflection.set;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.List;
import javax.annotation.PostConstruct;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.PersistenceContext;
import junit.rules.dbunit.DbUnitUtil;
import junit.rules.dbunit.FixturesUtil;
import org.apache.derby.jdbc.EmbeddedDriver;
import org.dbunit.JdbcDatabaseTester;
import org.dbunit.dataset.CompositeDataSet;
import org.dbunit.dataset.DataSetException;
import org.dbunit.dataset.IDataSet;
import org.hibernate.ejb.Ejb3Configuration;
import org.junit.After;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory; | } else {
// if the error code or SQLState is different, we have
// an unexpected exception (shutdown failed)
throw new RuntimeException(e.getMessage(), e);
}
}
}
/**
* @param object
* an object to which we will apply EJB 3.0 style @PersistenceContext and @PostConstruct handling
*/
public final void injectAndPostConstruct(final Object object) {
final Class<? extends Object> clazz = object.getClass();
for (final Field field : clazz.getDeclaredFields()) {
if (field.isAnnotationPresent(PersistenceContext.class)) {
final Class<?> type = field.getType();
if (type.equals(EntityManager.class)) {
set(field).of(object).to(entityManager);
} else {
logger.warn("Found field \"{}\" annotated with @PersistenceContext " + "but is of type {}", field
.getName(), type.getName());
}
}
}
for (final Method method : clazz.getDeclaredMethods()) {
if (method.isAnnotationPresent(PostConstruct.class)) {
final int nParameters = method.getParameterTypes().length;
if (nParameters == 0) { | // Path: src/main/java/junit/rules/jpa/hibernate/DerbyHibernateUtil.java
// public static final String JDBC_DERBY_URL = "jdbc:derby:test";
//
// Path: src/main/java/junit/rules/util/Reflection.java
// public static MethodInvoker invoke(final Method method) {
// return new MethodInvoker(method);
// }
//
// Path: src/main/java/junit/rules/util/Reflection.java
// public static FieldWrapper set(final Field field) {
// return new FieldWrapper(field);
// }
//
// Path: src/main/java/junit/rules/dbunit/DbUnitUtil.java
// public final class DbUnitUtil {
//
// private static final Logger LOGGER = LoggerFactory.getLogger(DbUnitUtil.class);
//
// /**
// * Utility classes should not have a public or default constructor.
// */
// private DbUnitUtil() {
// // noop
// }
//
// /**
// * @param fixtureNames
// * the fixture names
// * @return IDataSet[]
// */
// public static IDataSet[] loadDataSets(final List<String> fixtureNames) {
// final List<IDataSet> dataSets = new ArrayList<IDataSet>();
//
// for (final String fixtureName : fixtureNames) {
// LOGGER.trace("Attempting to load database fixture \"" + fixtureName + "\"");
// final IDataSet dataSet = attemptToLoadFixture(fixtureName);
// if (dataSet != null) {
// dataSets.add(dataSet);
// }
// }
//
// return dataSets.toArray(new IDataSet[dataSets.size()]);
// }
//
// /**
// * @param fixtureName
// * the fixture name
// * @return {@link IDataSet}
// */
// private static IDataSet attemptToLoadFixture(final String fixtureName) {
// IDataSet dataSet = null;
//
// try {
// final InputStream in = new FileInputStream(getFile(fixtureName));
// try {
// if (in != null) {
// if (fixtureName.endsWith(".xml")) {
// dataSet = new XmlDataSet(in);
// }
// }
// } finally {
// in.close();
// }
// } catch (final Exception e) {
// throw new Error(e.getMessage(), e);
// }
// return dataSet;
// }
//
// /**
// * @param fixtureName
// * the fixture (file) name
// * @return the {@link File} with the prefix
// */
// public static File getFile(final String fixtureName) {
// return new File("src/test/db/fixtures", fixtureName);
// }
//
// }
//
// Path: src/main/java/junit/rules/dbunit/FixturesUtil.java
// public final class FixturesUtil {
//
// /**
// * Utility classes should not have a public or default constructor.
// */
// private FixturesUtil() {
// // noop
// }
//
// /**
// * @param elements
// * the Class(es) or Method(s) to inspect for the {@link Fixtures} annotation
// * @return the list of fixture names
// */
// public static List<String> getFixtureNames(final AnnotatedElement... elements) {
// final List<String> fixtureNames = new ArrayList<String>();
// for (final AnnotatedElement element : elements) {
// if (element.isAnnotationPresent(Fixtures.class)) {
// for (final String fixtureName : element.getAnnotation(Fixtures.class).value()) {
// fixtureNames.add(fixtureName);
// }
// }
// }
// return fixtureNames;
// }
//
// }
// Path: src/main/java/junit/rules/jpa/hibernate/DerbyHibernateTestCase.java
import static junit.rules.jpa.hibernate.DerbyHibernateUtil.JDBC_DERBY_URL;
import static junit.rules.util.Reflection.invoke;
import static junit.rules.util.Reflection.set;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.List;
import javax.annotation.PostConstruct;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.PersistenceContext;
import junit.rules.dbunit.DbUnitUtil;
import junit.rules.dbunit.FixturesUtil;
import org.apache.derby.jdbc.EmbeddedDriver;
import org.dbunit.JdbcDatabaseTester;
import org.dbunit.dataset.CompositeDataSet;
import org.dbunit.dataset.DataSetException;
import org.dbunit.dataset.IDataSet;
import org.hibernate.ejb.Ejb3Configuration;
import org.junit.After;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
} else {
// if the error code or SQLState is different, we have
// an unexpected exception (shutdown failed)
throw new RuntimeException(e.getMessage(), e);
}
}
}
/**
* @param object
* an object to which we will apply EJB 3.0 style @PersistenceContext and @PostConstruct handling
*/
public final void injectAndPostConstruct(final Object object) {
final Class<? extends Object> clazz = object.getClass();
for (final Field field : clazz.getDeclaredFields()) {
if (field.isAnnotationPresent(PersistenceContext.class)) {
final Class<?> type = field.getType();
if (type.equals(EntityManager.class)) {
set(field).of(object).to(entityManager);
} else {
logger.warn("Found field \"{}\" annotated with @PersistenceContext " + "but is of type {}", field
.getName(), type.getName());
}
}
}
for (final Method method : clazz.getDeclaredMethods()) {
if (method.isAnnotationPresent(PostConstruct.class)) {
final int nParameters = method.getParameterTypes().length;
if (nParameters == 0) { | invoke(method).on(object); |
aisrael/junit-rules | src/main/java/junit/rules/jpa/hibernate/DerbyHibernateTestCase.java | // Path: src/main/java/junit/rules/jpa/hibernate/DerbyHibernateUtil.java
// public static final String JDBC_DERBY_URL = "jdbc:derby:test";
//
// Path: src/main/java/junit/rules/util/Reflection.java
// public static MethodInvoker invoke(final Method method) {
// return new MethodInvoker(method);
// }
//
// Path: src/main/java/junit/rules/util/Reflection.java
// public static FieldWrapper set(final Field field) {
// return new FieldWrapper(field);
// }
//
// Path: src/main/java/junit/rules/dbunit/DbUnitUtil.java
// public final class DbUnitUtil {
//
// private static final Logger LOGGER = LoggerFactory.getLogger(DbUnitUtil.class);
//
// /**
// * Utility classes should not have a public or default constructor.
// */
// private DbUnitUtil() {
// // noop
// }
//
// /**
// * @param fixtureNames
// * the fixture names
// * @return IDataSet[]
// */
// public static IDataSet[] loadDataSets(final List<String> fixtureNames) {
// final List<IDataSet> dataSets = new ArrayList<IDataSet>();
//
// for (final String fixtureName : fixtureNames) {
// LOGGER.trace("Attempting to load database fixture \"" + fixtureName + "\"");
// final IDataSet dataSet = attemptToLoadFixture(fixtureName);
// if (dataSet != null) {
// dataSets.add(dataSet);
// }
// }
//
// return dataSets.toArray(new IDataSet[dataSets.size()]);
// }
//
// /**
// * @param fixtureName
// * the fixture name
// * @return {@link IDataSet}
// */
// private static IDataSet attemptToLoadFixture(final String fixtureName) {
// IDataSet dataSet = null;
//
// try {
// final InputStream in = new FileInputStream(getFile(fixtureName));
// try {
// if (in != null) {
// if (fixtureName.endsWith(".xml")) {
// dataSet = new XmlDataSet(in);
// }
// }
// } finally {
// in.close();
// }
// } catch (final Exception e) {
// throw new Error(e.getMessage(), e);
// }
// return dataSet;
// }
//
// /**
// * @param fixtureName
// * the fixture (file) name
// * @return the {@link File} with the prefix
// */
// public static File getFile(final String fixtureName) {
// return new File("src/test/db/fixtures", fixtureName);
// }
//
// }
//
// Path: src/main/java/junit/rules/dbunit/FixturesUtil.java
// public final class FixturesUtil {
//
// /**
// * Utility classes should not have a public or default constructor.
// */
// private FixturesUtil() {
// // noop
// }
//
// /**
// * @param elements
// * the Class(es) or Method(s) to inspect for the {@link Fixtures} annotation
// * @return the list of fixture names
// */
// public static List<String> getFixtureNames(final AnnotatedElement... elements) {
// final List<String> fixtureNames = new ArrayList<String>();
// for (final AnnotatedElement element : elements) {
// if (element.isAnnotationPresent(Fixtures.class)) {
// for (final String fixtureName : element.getAnnotation(Fixtures.class).value()) {
// fixtureNames.add(fixtureName);
// }
// }
// }
// return fixtureNames;
// }
//
// }
| import static junit.rules.jpa.hibernate.DerbyHibernateUtil.JDBC_DERBY_URL;
import static junit.rules.util.Reflection.invoke;
import static junit.rules.util.Reflection.set;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.List;
import javax.annotation.PostConstruct;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.PersistenceContext;
import junit.rules.dbunit.DbUnitUtil;
import junit.rules.dbunit.FixturesUtil;
import org.apache.derby.jdbc.EmbeddedDriver;
import org.dbunit.JdbcDatabaseTester;
import org.dbunit.dataset.CompositeDataSet;
import org.dbunit.dataset.DataSetException;
import org.dbunit.dataset.IDataSet;
import org.hibernate.ejb.Ejb3Configuration;
import org.junit.After;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory; | set(field).of(object).to(entityManager);
} else {
logger.warn("Found field \"{}\" annotated with @PersistenceContext " + "but is of type {}", field
.getName(), type.getName());
}
}
}
for (final Method method : clazz.getDeclaredMethods()) {
if (method.isAnnotationPresent(PostConstruct.class)) {
final int nParameters = method.getParameterTypes().length;
if (nParameters == 0) {
invoke(method).on(object);
} else {
logger.warn("Found method \"{}\" annotated @PostConstruct "
+ "but don't know how to invoke with {} parameters", method.getName(), nParameters);
}
}
}
}
/**
* @throws Throwable
* on any throwable
*/
@Before
public final void initializeDbUnit() throws Throwable {
entityManager = ENTITY_MANAGER_FACTORY.get().createEntityManager();
jdbcDatabaseTester = new JdbcDatabaseTester(EmbeddedDriver.class.getName(), JDBC_DERBY_URL); | // Path: src/main/java/junit/rules/jpa/hibernate/DerbyHibernateUtil.java
// public static final String JDBC_DERBY_URL = "jdbc:derby:test";
//
// Path: src/main/java/junit/rules/util/Reflection.java
// public static MethodInvoker invoke(final Method method) {
// return new MethodInvoker(method);
// }
//
// Path: src/main/java/junit/rules/util/Reflection.java
// public static FieldWrapper set(final Field field) {
// return new FieldWrapper(field);
// }
//
// Path: src/main/java/junit/rules/dbunit/DbUnitUtil.java
// public final class DbUnitUtil {
//
// private static final Logger LOGGER = LoggerFactory.getLogger(DbUnitUtil.class);
//
// /**
// * Utility classes should not have a public or default constructor.
// */
// private DbUnitUtil() {
// // noop
// }
//
// /**
// * @param fixtureNames
// * the fixture names
// * @return IDataSet[]
// */
// public static IDataSet[] loadDataSets(final List<String> fixtureNames) {
// final List<IDataSet> dataSets = new ArrayList<IDataSet>();
//
// for (final String fixtureName : fixtureNames) {
// LOGGER.trace("Attempting to load database fixture \"" + fixtureName + "\"");
// final IDataSet dataSet = attemptToLoadFixture(fixtureName);
// if (dataSet != null) {
// dataSets.add(dataSet);
// }
// }
//
// return dataSets.toArray(new IDataSet[dataSets.size()]);
// }
//
// /**
// * @param fixtureName
// * the fixture name
// * @return {@link IDataSet}
// */
// private static IDataSet attemptToLoadFixture(final String fixtureName) {
// IDataSet dataSet = null;
//
// try {
// final InputStream in = new FileInputStream(getFile(fixtureName));
// try {
// if (in != null) {
// if (fixtureName.endsWith(".xml")) {
// dataSet = new XmlDataSet(in);
// }
// }
// } finally {
// in.close();
// }
// } catch (final Exception e) {
// throw new Error(e.getMessage(), e);
// }
// return dataSet;
// }
//
// /**
// * @param fixtureName
// * the fixture (file) name
// * @return the {@link File} with the prefix
// */
// public static File getFile(final String fixtureName) {
// return new File("src/test/db/fixtures", fixtureName);
// }
//
// }
//
// Path: src/main/java/junit/rules/dbunit/FixturesUtil.java
// public final class FixturesUtil {
//
// /**
// * Utility classes should not have a public or default constructor.
// */
// private FixturesUtil() {
// // noop
// }
//
// /**
// * @param elements
// * the Class(es) or Method(s) to inspect for the {@link Fixtures} annotation
// * @return the list of fixture names
// */
// public static List<String> getFixtureNames(final AnnotatedElement... elements) {
// final List<String> fixtureNames = new ArrayList<String>();
// for (final AnnotatedElement element : elements) {
// if (element.isAnnotationPresent(Fixtures.class)) {
// for (final String fixtureName : element.getAnnotation(Fixtures.class).value()) {
// fixtureNames.add(fixtureName);
// }
// }
// }
// return fixtureNames;
// }
//
// }
// Path: src/main/java/junit/rules/jpa/hibernate/DerbyHibernateTestCase.java
import static junit.rules.jpa.hibernate.DerbyHibernateUtil.JDBC_DERBY_URL;
import static junit.rules.util.Reflection.invoke;
import static junit.rules.util.Reflection.set;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.List;
import javax.annotation.PostConstruct;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.PersistenceContext;
import junit.rules.dbunit.DbUnitUtil;
import junit.rules.dbunit.FixturesUtil;
import org.apache.derby.jdbc.EmbeddedDriver;
import org.dbunit.JdbcDatabaseTester;
import org.dbunit.dataset.CompositeDataSet;
import org.dbunit.dataset.DataSetException;
import org.dbunit.dataset.IDataSet;
import org.hibernate.ejb.Ejb3Configuration;
import org.junit.After;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
set(field).of(object).to(entityManager);
} else {
logger.warn("Found field \"{}\" annotated with @PersistenceContext " + "but is of type {}", field
.getName(), type.getName());
}
}
}
for (final Method method : clazz.getDeclaredMethods()) {
if (method.isAnnotationPresent(PostConstruct.class)) {
final int nParameters = method.getParameterTypes().length;
if (nParameters == 0) {
invoke(method).on(object);
} else {
logger.warn("Found method \"{}\" annotated @PostConstruct "
+ "but don't know how to invoke with {} parameters", method.getName(), nParameters);
}
}
}
}
/**
* @throws Throwable
* on any throwable
*/
@Before
public final void initializeDbUnit() throws Throwable {
entityManager = ENTITY_MANAGER_FACTORY.get().createEntityManager();
jdbcDatabaseTester = new JdbcDatabaseTester(EmbeddedDriver.class.getName(), JDBC_DERBY_URL); | final List<String> fixtureNames = FixturesUtil.getFixtureNames(getClass()); |
aisrael/junit-rules | src/main/java/junit/rules/jpa/hibernate/DerbyHibernateTestCase.java | // Path: src/main/java/junit/rules/jpa/hibernate/DerbyHibernateUtil.java
// public static final String JDBC_DERBY_URL = "jdbc:derby:test";
//
// Path: src/main/java/junit/rules/util/Reflection.java
// public static MethodInvoker invoke(final Method method) {
// return new MethodInvoker(method);
// }
//
// Path: src/main/java/junit/rules/util/Reflection.java
// public static FieldWrapper set(final Field field) {
// return new FieldWrapper(field);
// }
//
// Path: src/main/java/junit/rules/dbunit/DbUnitUtil.java
// public final class DbUnitUtil {
//
// private static final Logger LOGGER = LoggerFactory.getLogger(DbUnitUtil.class);
//
// /**
// * Utility classes should not have a public or default constructor.
// */
// private DbUnitUtil() {
// // noop
// }
//
// /**
// * @param fixtureNames
// * the fixture names
// * @return IDataSet[]
// */
// public static IDataSet[] loadDataSets(final List<String> fixtureNames) {
// final List<IDataSet> dataSets = new ArrayList<IDataSet>();
//
// for (final String fixtureName : fixtureNames) {
// LOGGER.trace("Attempting to load database fixture \"" + fixtureName + "\"");
// final IDataSet dataSet = attemptToLoadFixture(fixtureName);
// if (dataSet != null) {
// dataSets.add(dataSet);
// }
// }
//
// return dataSets.toArray(new IDataSet[dataSets.size()]);
// }
//
// /**
// * @param fixtureName
// * the fixture name
// * @return {@link IDataSet}
// */
// private static IDataSet attemptToLoadFixture(final String fixtureName) {
// IDataSet dataSet = null;
//
// try {
// final InputStream in = new FileInputStream(getFile(fixtureName));
// try {
// if (in != null) {
// if (fixtureName.endsWith(".xml")) {
// dataSet = new XmlDataSet(in);
// }
// }
// } finally {
// in.close();
// }
// } catch (final Exception e) {
// throw new Error(e.getMessage(), e);
// }
// return dataSet;
// }
//
// /**
// * @param fixtureName
// * the fixture (file) name
// * @return the {@link File} with the prefix
// */
// public static File getFile(final String fixtureName) {
// return new File("src/test/db/fixtures", fixtureName);
// }
//
// }
//
// Path: src/main/java/junit/rules/dbunit/FixturesUtil.java
// public final class FixturesUtil {
//
// /**
// * Utility classes should not have a public or default constructor.
// */
// private FixturesUtil() {
// // noop
// }
//
// /**
// * @param elements
// * the Class(es) or Method(s) to inspect for the {@link Fixtures} annotation
// * @return the list of fixture names
// */
// public static List<String> getFixtureNames(final AnnotatedElement... elements) {
// final List<String> fixtureNames = new ArrayList<String>();
// for (final AnnotatedElement element : elements) {
// if (element.isAnnotationPresent(Fixtures.class)) {
// for (final String fixtureName : element.getAnnotation(Fixtures.class).value()) {
// fixtureNames.add(fixtureName);
// }
// }
// }
// return fixtureNames;
// }
//
// }
| import static junit.rules.jpa.hibernate.DerbyHibernateUtil.JDBC_DERBY_URL;
import static junit.rules.util.Reflection.invoke;
import static junit.rules.util.Reflection.set;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.List;
import javax.annotation.PostConstruct;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.PersistenceContext;
import junit.rules.dbunit.DbUnitUtil;
import junit.rules.dbunit.FixturesUtil;
import org.apache.derby.jdbc.EmbeddedDriver;
import org.dbunit.JdbcDatabaseTester;
import org.dbunit.dataset.CompositeDataSet;
import org.dbunit.dataset.DataSetException;
import org.dbunit.dataset.IDataSet;
import org.hibernate.ejb.Ejb3Configuration;
import org.junit.After;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory; | }
}
}
/**
* @throws Throwable
* on any throwable
*/
@Before
public final void initializeDbUnit() throws Throwable {
entityManager = ENTITY_MANAGER_FACTORY.get().createEntityManager();
jdbcDatabaseTester = new JdbcDatabaseTester(EmbeddedDriver.class.getName(), JDBC_DERBY_URL);
final List<String> fixtureNames = FixturesUtil.getFixtureNames(getClass());
if (fixtureNames.isEmpty()) {
logger.warn("No fixtures to load! Specify fixtures using @Fixtures.");
} else {
loadFixtures(fixtureNames);
}
jdbcDatabaseTester.onSetup();
}
/**
* @param fixtureNames
* the fixture names
* @throws DataSetException
* on any exception
*/
private void loadFixtures(final List<String> fixtureNames) throws DataSetException { | // Path: src/main/java/junit/rules/jpa/hibernate/DerbyHibernateUtil.java
// public static final String JDBC_DERBY_URL = "jdbc:derby:test";
//
// Path: src/main/java/junit/rules/util/Reflection.java
// public static MethodInvoker invoke(final Method method) {
// return new MethodInvoker(method);
// }
//
// Path: src/main/java/junit/rules/util/Reflection.java
// public static FieldWrapper set(final Field field) {
// return new FieldWrapper(field);
// }
//
// Path: src/main/java/junit/rules/dbunit/DbUnitUtil.java
// public final class DbUnitUtil {
//
// private static final Logger LOGGER = LoggerFactory.getLogger(DbUnitUtil.class);
//
// /**
// * Utility classes should not have a public or default constructor.
// */
// private DbUnitUtil() {
// // noop
// }
//
// /**
// * @param fixtureNames
// * the fixture names
// * @return IDataSet[]
// */
// public static IDataSet[] loadDataSets(final List<String> fixtureNames) {
// final List<IDataSet> dataSets = new ArrayList<IDataSet>();
//
// for (final String fixtureName : fixtureNames) {
// LOGGER.trace("Attempting to load database fixture \"" + fixtureName + "\"");
// final IDataSet dataSet = attemptToLoadFixture(fixtureName);
// if (dataSet != null) {
// dataSets.add(dataSet);
// }
// }
//
// return dataSets.toArray(new IDataSet[dataSets.size()]);
// }
//
// /**
// * @param fixtureName
// * the fixture name
// * @return {@link IDataSet}
// */
// private static IDataSet attemptToLoadFixture(final String fixtureName) {
// IDataSet dataSet = null;
//
// try {
// final InputStream in = new FileInputStream(getFile(fixtureName));
// try {
// if (in != null) {
// if (fixtureName.endsWith(".xml")) {
// dataSet = new XmlDataSet(in);
// }
// }
// } finally {
// in.close();
// }
// } catch (final Exception e) {
// throw new Error(e.getMessage(), e);
// }
// return dataSet;
// }
//
// /**
// * @param fixtureName
// * the fixture (file) name
// * @return the {@link File} with the prefix
// */
// public static File getFile(final String fixtureName) {
// return new File("src/test/db/fixtures", fixtureName);
// }
//
// }
//
// Path: src/main/java/junit/rules/dbunit/FixturesUtil.java
// public final class FixturesUtil {
//
// /**
// * Utility classes should not have a public or default constructor.
// */
// private FixturesUtil() {
// // noop
// }
//
// /**
// * @param elements
// * the Class(es) or Method(s) to inspect for the {@link Fixtures} annotation
// * @return the list of fixture names
// */
// public static List<String> getFixtureNames(final AnnotatedElement... elements) {
// final List<String> fixtureNames = new ArrayList<String>();
// for (final AnnotatedElement element : elements) {
// if (element.isAnnotationPresent(Fixtures.class)) {
// for (final String fixtureName : element.getAnnotation(Fixtures.class).value()) {
// fixtureNames.add(fixtureName);
// }
// }
// }
// return fixtureNames;
// }
//
// }
// Path: src/main/java/junit/rules/jpa/hibernate/DerbyHibernateTestCase.java
import static junit.rules.jpa.hibernate.DerbyHibernateUtil.JDBC_DERBY_URL;
import static junit.rules.util.Reflection.invoke;
import static junit.rules.util.Reflection.set;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.List;
import javax.annotation.PostConstruct;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.PersistenceContext;
import junit.rules.dbunit.DbUnitUtil;
import junit.rules.dbunit.FixturesUtil;
import org.apache.derby.jdbc.EmbeddedDriver;
import org.dbunit.JdbcDatabaseTester;
import org.dbunit.dataset.CompositeDataSet;
import org.dbunit.dataset.DataSetException;
import org.dbunit.dataset.IDataSet;
import org.hibernate.ejb.Ejb3Configuration;
import org.junit.After;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
}
}
}
/**
* @throws Throwable
* on any throwable
*/
@Before
public final void initializeDbUnit() throws Throwable {
entityManager = ENTITY_MANAGER_FACTORY.get().createEntityManager();
jdbcDatabaseTester = new JdbcDatabaseTester(EmbeddedDriver.class.getName(), JDBC_DERBY_URL);
final List<String> fixtureNames = FixturesUtil.getFixtureNames(getClass());
if (fixtureNames.isEmpty()) {
logger.warn("No fixtures to load! Specify fixtures using @Fixtures.");
} else {
loadFixtures(fixtureNames);
}
jdbcDatabaseTester.onSetup();
}
/**
* @param fixtureNames
* the fixture names
* @throws DataSetException
* on any exception
*/
private void loadFixtures(final List<String> fixtureNames) throws DataSetException { | final IDataSet[] dataSets = DbUnitUtil.loadDataSets(fixtureNames); |
aisrael/junit-rules | src/test/java/com/example/dao/jpa/JpaWidgetDao.java | // Path: src/test/java/com/example/dao/WidgetDao.java
// public interface WidgetDao {
//
// /**
// * @return {@link List}<{@link Widget}>
// */
// List<Widget> listAll();
//
// /**
// * @param id
// * the widget id
// * @return {@link Widget}
// */
// Widget findById(int id);
//
// /**
// * @param name
// * the widget name
// * @return {@link Widget}
// */
// Widget findByName(String name);
//
// }
//
// Path: src/test/java/com/example/model/Widget.java
// @Entity
// @NamedQueries({
// @NamedQuery(name = Widget.LIST_ALL, query = "SELECT w FROM Widget w"),
// @NamedQuery(name = Widget.FIND_BY_ID, query = "SELECT w FROM Widget w WHERE w.id = :id"),
// @NamedQuery(name = Widget.FIND_BY_NAME, query = "SELECT w FROM Widget w WHERE w.name = :name")
// })
// public class Widget implements Serializable {
//
// /**
// *
// */
// private static final long serialVersionUID = -1689099836716604893L;
//
// /**
// * {@value #LIST_ALL}
// */
// public static final String LIST_ALL = "Widget.listAll";
//
// /**
// * {@value #FIND_BY_ID}
// */
// public static final String FIND_BY_ID = "Widget.findById";
//
// /**
// * {@value #FIND_BY_NAME}
// */
// public static final String FIND_BY_NAME = "Widget.findByName";
//
// @Id
// private Integer id;
//
// @Column
// private String name;
//
// /**
// * @return the id
// */
// public final Integer getId() {
// return id;
// }
//
// /**
// * @param id
// * the id to set
// */
// public final void setId(final Integer id) {
// this.id = id;
// }
//
// /**
// * @return the name
// */
// public final String getName() {
// return name;
// }
//
// /**
// * @param name
// * the name to set
// */
// public final void setName(final String name) {
// this.name = name;
// }
//
// }
| import java.util.List;
import javax.persistence.EntityManager;
import com.example.dao.WidgetDao;
import com.example.model.Widget; | /**
* junit-rules: JUnit Rules Library
*
* Copyright (c) 2009-2011 by Alistair A. Israel.
* This software is made available under the terms of the MIT License.
*
* Created Oct 22, 2009
*/
package com.example.dao.jpa;
/**
* @author Alistair A. Israel
*/
public class JpaWidgetDao implements WidgetDao {
private final EntityManager entityManager;
/**
* @param entityManager
* the {@link EntityManager}
*/
public JpaWidgetDao(final EntityManager entityManager) {
this.entityManager = entityManager;
}
/**
* {@inheritDoc}
*
* @see com.example.dao.WidgetDao#findById(int)
*/
@Override | // Path: src/test/java/com/example/dao/WidgetDao.java
// public interface WidgetDao {
//
// /**
// * @return {@link List}<{@link Widget}>
// */
// List<Widget> listAll();
//
// /**
// * @param id
// * the widget id
// * @return {@link Widget}
// */
// Widget findById(int id);
//
// /**
// * @param name
// * the widget name
// * @return {@link Widget}
// */
// Widget findByName(String name);
//
// }
//
// Path: src/test/java/com/example/model/Widget.java
// @Entity
// @NamedQueries({
// @NamedQuery(name = Widget.LIST_ALL, query = "SELECT w FROM Widget w"),
// @NamedQuery(name = Widget.FIND_BY_ID, query = "SELECT w FROM Widget w WHERE w.id = :id"),
// @NamedQuery(name = Widget.FIND_BY_NAME, query = "SELECT w FROM Widget w WHERE w.name = :name")
// })
// public class Widget implements Serializable {
//
// /**
// *
// */
// private static final long serialVersionUID = -1689099836716604893L;
//
// /**
// * {@value #LIST_ALL}
// */
// public static final String LIST_ALL = "Widget.listAll";
//
// /**
// * {@value #FIND_BY_ID}
// */
// public static final String FIND_BY_ID = "Widget.findById";
//
// /**
// * {@value #FIND_BY_NAME}
// */
// public static final String FIND_BY_NAME = "Widget.findByName";
//
// @Id
// private Integer id;
//
// @Column
// private String name;
//
// /**
// * @return the id
// */
// public final Integer getId() {
// return id;
// }
//
// /**
// * @param id
// * the id to set
// */
// public final void setId(final Integer id) {
// this.id = id;
// }
//
// /**
// * @return the name
// */
// public final String getName() {
// return name;
// }
//
// /**
// * @param name
// * the name to set
// */
// public final void setName(final String name) {
// this.name = name;
// }
//
// }
// Path: src/test/java/com/example/dao/jpa/JpaWidgetDao.java
import java.util.List;
import javax.persistence.EntityManager;
import com.example.dao.WidgetDao;
import com.example.model.Widget;
/**
* junit-rules: JUnit Rules Library
*
* Copyright (c) 2009-2011 by Alistair A. Israel.
* This software is made available under the terms of the MIT License.
*
* Created Oct 22, 2009
*/
package com.example.dao.jpa;
/**
* @author Alistair A. Israel
*/
public class JpaWidgetDao implements WidgetDao {
private final EntityManager entityManager;
/**
* @param entityManager
* the {@link EntityManager}
*/
public JpaWidgetDao(final EntityManager entityManager) {
this.entityManager = entityManager;
}
/**
* {@inheritDoc}
*
* @see com.example.dao.WidgetDao#findById(int)
*/
@Override | public final Widget findById(final int id) { |
aisrael/junit-rules | src/test/java/junit/rules/httpserver/HttpServerRuleTest.java | // Path: src/test/java/junit/rules/util/SimpleReference.java
// public class SimpleReference<T> {
//
// private T value;
//
// /**
// * @return the object referenced
// */
// public final T get() {
// return value;
// }
//
// /**
// * @param obj
// * the new object to reference
// */
// public final void set(final T obj) {
// this.value = obj;
// }
//
// /**
// * @param <T>
// * a type
// * @param obj
// * the object we want to reference
// * @return a SimpleReference to the object
// */
// public static <T> SimpleReference<T> to(final T obj) {
// return new SimpleReference<T>();
// }
// }
| import static java.lang.Boolean.FALSE;
import static java.lang.Boolean.TRUE;
import static java.net.HttpURLConnection.HTTP_OK;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.HttpURLConnection;
import junit.rules.util.SimpleReference;
import org.junit.Rule;
import org.junit.Test; | * @throws Exception
* should never happen
*/
@Test
public void testHttpServerRulePutMethod() throws Exception {
httpServer.addHandler("/", new SimpleHttpHandler() {
@Override
protected void onPut() throws IOException {
final BufferedReader reader = new BufferedReader(new InputStreamReader(getRequestBody()));
getResponseWriter().write("Hello " + reader.readLine());
sendResponse(HTTP_OK);
}
});
final HttpURLConnection connection = httpServer.put("/");
final BufferedWriter out = new BufferedWriter(new OutputStreamWriter(connection.getOutputStream()));
out.write("Again");
out.flush();
final BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
assertEquals("Hello Again", in.readLine());
assertEquals(HTTP_OK, connection.getResponseCode());
}
/**
* Test HTTP DELETE
*
* @throws Exception
* should never happen
*/
@Test
public void testHttpServerRuleDeleteMethod() throws Exception { | // Path: src/test/java/junit/rules/util/SimpleReference.java
// public class SimpleReference<T> {
//
// private T value;
//
// /**
// * @return the object referenced
// */
// public final T get() {
// return value;
// }
//
// /**
// * @param obj
// * the new object to reference
// */
// public final void set(final T obj) {
// this.value = obj;
// }
//
// /**
// * @param <T>
// * a type
// * @param obj
// * the object we want to reference
// * @return a SimpleReference to the object
// */
// public static <T> SimpleReference<T> to(final T obj) {
// return new SimpleReference<T>();
// }
// }
// Path: src/test/java/junit/rules/httpserver/HttpServerRuleTest.java
import static java.lang.Boolean.FALSE;
import static java.lang.Boolean.TRUE;
import static java.net.HttpURLConnection.HTTP_OK;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.HttpURLConnection;
import junit.rules.util.SimpleReference;
import org.junit.Rule;
import org.junit.Test;
* @throws Exception
* should never happen
*/
@Test
public void testHttpServerRulePutMethod() throws Exception {
httpServer.addHandler("/", new SimpleHttpHandler() {
@Override
protected void onPut() throws IOException {
final BufferedReader reader = new BufferedReader(new InputStreamReader(getRequestBody()));
getResponseWriter().write("Hello " + reader.readLine());
sendResponse(HTTP_OK);
}
});
final HttpURLConnection connection = httpServer.put("/");
final BufferedWriter out = new BufferedWriter(new OutputStreamWriter(connection.getOutputStream()));
out.write("Again");
out.flush();
final BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
assertEquals("Hello Again", in.readLine());
assertEquals(HTTP_OK, connection.getResponseCode());
}
/**
* Test HTTP DELETE
*
* @throws Exception
* should never happen
*/
@Test
public void testHttpServerRuleDeleteMethod() throws Exception { | final SimpleReference<Boolean> deleteIssued = SimpleReference.to(FALSE); |
walmartlabs/mupd8 | src/main/java/com/walmartlabs/mupd8/compression/GZIPCompression.java | // Path: src/main/java/com/walmartlabs/mupd8/Constants.java
// public class Constants {
//
// public final static int SLATE_CAPACITY = 1048576; // 1M
// public final static int COMPRESSED_CAPACITY = 205824; // 200K
//
// }
| import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.util.zip.GZIPInputStream;
import java.util.zip.GZIPOutputStream;
import com.walmartlabs.mupd8.Constants; | /**
* Copyright 2011-2012 @WalmartLabs, a division of Wal-Mart Stores, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.walmartlabs.mupd8.compression;
public class GZIPCompression implements CompressionService {
@Override
public byte[] compress(byte[] uncompressed) throws Exception { | // Path: src/main/java/com/walmartlabs/mupd8/Constants.java
// public class Constants {
//
// public final static int SLATE_CAPACITY = 1048576; // 1M
// public final static int COMPRESSED_CAPACITY = 205824; // 200K
//
// }
// Path: src/main/java/com/walmartlabs/mupd8/compression/GZIPCompression.java
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.util.zip.GZIPInputStream;
import java.util.zip.GZIPOutputStream;
import com.walmartlabs.mupd8.Constants;
/**
* Copyright 2011-2012 @WalmartLabs, a division of Wal-Mart Stores, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.walmartlabs.mupd8.compression;
public class GZIPCompression implements CompressionService {
@Override
public byte[] compress(byte[] uncompressed) throws Exception { | ByteArrayOutputStream bos = new ByteArrayOutputStream(Constants.SLATE_CAPACITY); |
walmartlabs/mupd8 | src/test/java/com/walmartlabs/mupd8/KafkaSourceTest.java | // Path: src/main/java/com/walmartlabs/mupd8/application/Mupd8DataPair.java
// public class Mupd8DataPair {
// public String _key;
// public byte _value[];
// }
| import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;
import junit.framework.TestCase;
import kafka.javaapi.producer.Producer;
import kafka.producer.KeyedMessage;
import kafka.producer.ProducerConfig;
import kafka.server.KafkaConfig;
import kafka.server.KafkaServerStartable;
import org.apache.curator.test.TestingServer;
import com.google.common.io.Files;
import com.walmartlabs.mupd8.application.Mupd8DataPair; | private File logDir;
private String topic = "mupd8-test-topic";
private String key = "Kf1";
private String val = "data1";
private String mesg = "{ \"" + key + "\" : \"" + val + "\" }";
@Override
public void setUp() throws Exception {
zkServer = new TestingServer();
logDir = Files.createTempDir();
kafkaServer = startKafkaServer(zkServer.getConnectString(), logDir.getAbsolutePath());
produceJsonMessage();
kafkaSource = getKafkaSource();
}
@Override
public void tearDown() throws Exception {
kafkaSource.closeSource();
kafkaServer.shutdown();
zkServer.stop();
logDir.delete();
}
public void testHasNext() {
assertTrue("HasNext should return true when data", kafkaSource.hasNext());
assertTrue("HasNext should not consume data",kafkaSource.hasNext());
}
public void testNext() {
assertTrue("HasNext should return true when data", kafkaSource.hasNext()); | // Path: src/main/java/com/walmartlabs/mupd8/application/Mupd8DataPair.java
// public class Mupd8DataPair {
// public String _key;
// public byte _value[];
// }
// Path: src/test/java/com/walmartlabs/mupd8/KafkaSourceTest.java
import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;
import junit.framework.TestCase;
import kafka.javaapi.producer.Producer;
import kafka.producer.KeyedMessage;
import kafka.producer.ProducerConfig;
import kafka.server.KafkaConfig;
import kafka.server.KafkaServerStartable;
import org.apache.curator.test.TestingServer;
import com.google.common.io.Files;
import com.walmartlabs.mupd8.application.Mupd8DataPair;
private File logDir;
private String topic = "mupd8-test-topic";
private String key = "Kf1";
private String val = "data1";
private String mesg = "{ \"" + key + "\" : \"" + val + "\" }";
@Override
public void setUp() throws Exception {
zkServer = new TestingServer();
logDir = Files.createTempDir();
kafkaServer = startKafkaServer(zkServer.getConnectString(), logDir.getAbsolutePath());
produceJsonMessage();
kafkaSource = getKafkaSource();
}
@Override
public void tearDown() throws Exception {
kafkaSource.closeSource();
kafkaServer.shutdown();
zkServer.stop();
logDir.delete();
}
public void testHasNext() {
assertTrue("HasNext should return true when data", kafkaSource.hasNext());
assertTrue("HasNext should not consume data",kafkaSource.hasNext());
}
public void testNext() {
assertTrue("HasNext should return true when data", kafkaSource.hasNext()); | Mupd8DataPair mupd8DataPair = kafkaSource.getNextDataPair(); |
walmartlabs/mupd8 | src/main/java/com/walmartlabs/mupd8/application/binary/PerformerUtilities.java | // Path: src/main/java/com/walmartlabs/mupd8/application/SlateSizeException.java
// public class SlateSizeException extends Exception {
// private static final long serialVersionUID = -4088317439305528023L;
//
// /** The actual size of the disallowed slate, in bytes. */
// public int actualLength;
// public int allowedLength;
//
// public SlateSizeException(int length, int max) {
// actualLength = length;
// allowedLength = max;
// }
//
// @Override
// public String toString() {
// return this.getClass().getSimpleName()+": Actual length "+actualLength+" exceeds permitted length "+allowedLength+")";
// }
//
// @Override
// public String getMessage() {
// return toString();
// }
// }
| import com.walmartlabs.mupd8.application.SlateSizeException; | /**
* Copyright 2011-2012 @WalmartLabs, a division of Wal-Mart Stores, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.walmartlabs.mupd8.application.binary;
/** A Performer gets an object of type PerformerUtilities to receive and publish outgoing events.
*
* This class is so named to allow Mupd8 implementations to provide additional services
* accessible to a Performer.
*
* A Performer should use EventPublisher.publish (only) to post a new event.
*/
public interface PerformerUtilities {
/** Direct version of publish (recommended for new code).
*
* @param stream - name of stream to which to publish event
* @param key - event key
* @param event - event data
* @throws Exception - reserved (may be used to indicate null values or disallowed stream)
*
* @todo TODO Throw more specific exceptions (indicating an invalid value).
*/
public void publish(String stream, byte[] key, byte[] event) throws Exception;
/** Replace a given slate (updaters only).
*
* @param slate - new slate to replace existing slate (if updater; if mapper, ignored)
*/ | // Path: src/main/java/com/walmartlabs/mupd8/application/SlateSizeException.java
// public class SlateSizeException extends Exception {
// private static final long serialVersionUID = -4088317439305528023L;
//
// /** The actual size of the disallowed slate, in bytes. */
// public int actualLength;
// public int allowedLength;
//
// public SlateSizeException(int length, int max) {
// actualLength = length;
// allowedLength = max;
// }
//
// @Override
// public String toString() {
// return this.getClass().getSimpleName()+": Actual length "+actualLength+" exceeds permitted length "+allowedLength+")";
// }
//
// @Override
// public String getMessage() {
// return toString();
// }
// }
// Path: src/main/java/com/walmartlabs/mupd8/application/binary/PerformerUtilities.java
import com.walmartlabs.mupd8.application.SlateSizeException;
/**
* Copyright 2011-2012 @WalmartLabs, a division of Wal-Mart Stores, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.walmartlabs.mupd8.application.binary;
/** A Performer gets an object of type PerformerUtilities to receive and publish outgoing events.
*
* This class is so named to allow Mupd8 implementations to provide additional services
* accessible to a Performer.
*
* A Performer should use EventPublisher.publish (only) to post a new event.
*/
public interface PerformerUtilities {
/** Direct version of publish (recommended for new code).
*
* @param stream - name of stream to which to publish event
* @param key - event key
* @param event - event data
* @throws Exception - reserved (may be used to indicate null values or disallowed stream)
*
* @todo TODO Throw more specific exceptions (indicating an invalid value).
*/
public void publish(String stream, byte[] key, byte[] event) throws Exception;
/** Replace a given slate (updaters only).
*
* @param slate - new slate to replace existing slate (if updater; if mapper, ignored)
*/ | public void replaceSlate(Object slate) throws SlateSizeException; |
walmartlabs/mupd8 | src/main/java/com/walmartlabs/mupd8/compression/SnappyCompression.java | // Path: src/main/java/com/walmartlabs/mupd8/Constants.java
// public class Constants {
//
// public final static int SLATE_CAPACITY = 1048576; // 1M
// public final static int COMPRESSED_CAPACITY = 205824; // 200K
//
// }
| import org.xerial.snappy.Snappy;
import com.walmartlabs.mupd8.Constants; | /**
* Copyright 2011-2012 @WalmartLabs, a division of Wal-Mart Stores, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.walmartlabs.mupd8.compression;
public class SnappyCompression implements CompressionService {
@Override
public byte[] compress(byte[] uncompressed) throws Exception { | // Path: src/main/java/com/walmartlabs/mupd8/Constants.java
// public class Constants {
//
// public final static int SLATE_CAPACITY = 1048576; // 1M
// public final static int COMPRESSED_CAPACITY = 205824; // 200K
//
// }
// Path: src/main/java/com/walmartlabs/mupd8/compression/SnappyCompression.java
import org.xerial.snappy.Snappy;
import com.walmartlabs.mupd8.Constants;
/**
* Copyright 2011-2012 @WalmartLabs, a division of Wal-Mart Stores, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.walmartlabs.mupd8.compression;
public class SnappyCompression implements CompressionService {
@Override
public byte[] compress(byte[] uncompressed) throws Exception { | assert(uncompressed.length < Constants.SLATE_CAPACITY); |
walmartlabs/mupd8 | src/main/java/com/walmartlabs/mupd8/compression/NoCompression.java | // Path: src/main/java/com/walmartlabs/mupd8/Constants.java
// public class Constants {
//
// public final static int SLATE_CAPACITY = 1048576; // 1M
// public final static int COMPRESSED_CAPACITY = 205824; // 200K
//
// }
| import com.walmartlabs.mupd8.Constants; | /**
* Copyright 2011-2012 @WalmartLabs, a division of Wal-Mart Stores, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.walmartlabs.mupd8.compression;
public class NoCompression implements CompressionService {
@Override
public byte[] compress(byte[] uncompressed) throws Exception { | // Path: src/main/java/com/walmartlabs/mupd8/Constants.java
// public class Constants {
//
// public final static int SLATE_CAPACITY = 1048576; // 1M
// public final static int COMPRESSED_CAPACITY = 205824; // 200K
//
// }
// Path: src/main/java/com/walmartlabs/mupd8/compression/NoCompression.java
import com.walmartlabs.mupd8.Constants;
/**
* Copyright 2011-2012 @WalmartLabs, a division of Wal-Mart Stores, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.walmartlabs.mupd8.compression;
public class NoCompression implements CompressionService {
@Override
public byte[] compress(byte[] uncompressed) throws Exception { | assert(uncompressed.length < Constants.SLATE_CAPACITY); |
walmartlabs/mupd8 | src/main/java/com/walmartlabs/mupd8/KafkaSource.java | // Path: src/main/java/com/walmartlabs/mupd8/application/Mupd8DataPair.java
// public class Mupd8DataPair {
// public String _key;
// public byte _value[];
// }
//
// Path: src/main/java/com/walmartlabs/mupd8/application/Mupd8Source.java
// public interface Mupd8Source {
// /**
// * Returns true if there is a next item ready to be read by getNextDataPair().
// * @return true if there is a next item ready to be read by getNextDataPair(), false otherwise
// */
// boolean hasNext();
//
// /**
// * Returns a Mupd8DataPair parsed from the next item
// * @return a Mupd8DataPair parsed from the next item
// * @throws NoSuchElementException if there is no next item to read from
// */
// Mupd8DataPair getNextDataPair();
// }
| import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import kafka.consumer.Consumer;
import kafka.consumer.ConsumerConfig;
import kafka.consumer.ConsumerIterator;
import kafka.consumer.KafkaStream;
import kafka.javaapi.consumer.ConsumerConnector;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.walmartlabs.mupd8.application.Mupd8DataPair;
import com.walmartlabs.mupd8.application.Mupd8Source; | key = args.get(3);
}
initialize();
objMapper=new ObjectMapper();
}
@Override
public boolean hasNext() {
boolean done = false;
boolean ret = false;
int retry = 0;
while(!done){
if(retry>MAX_RETRY){
initialize();
retry = 0;
}
try {
ret = consumerIterator.hasNext();
done = true;
} catch (Exception e) {
String mesg = "Consumer iterator hasNext throws exception";
LOG.error(mesg, e);
threadSleep(retry++,mesg);
done = false;
}
}
return ret;
}
@Override | // Path: src/main/java/com/walmartlabs/mupd8/application/Mupd8DataPair.java
// public class Mupd8DataPair {
// public String _key;
// public byte _value[];
// }
//
// Path: src/main/java/com/walmartlabs/mupd8/application/Mupd8Source.java
// public interface Mupd8Source {
// /**
// * Returns true if there is a next item ready to be read by getNextDataPair().
// * @return true if there is a next item ready to be read by getNextDataPair(), false otherwise
// */
// boolean hasNext();
//
// /**
// * Returns a Mupd8DataPair parsed from the next item
// * @return a Mupd8DataPair parsed from the next item
// * @throws NoSuchElementException if there is no next item to read from
// */
// Mupd8DataPair getNextDataPair();
// }
// Path: src/main/java/com/walmartlabs/mupd8/KafkaSource.java
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import kafka.consumer.Consumer;
import kafka.consumer.ConsumerConfig;
import kafka.consumer.ConsumerIterator;
import kafka.consumer.KafkaStream;
import kafka.javaapi.consumer.ConsumerConnector;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.walmartlabs.mupd8.application.Mupd8DataPair;
import com.walmartlabs.mupd8.application.Mupd8Source;
key = args.get(3);
}
initialize();
objMapper=new ObjectMapper();
}
@Override
public boolean hasNext() {
boolean done = false;
boolean ret = false;
int retry = 0;
while(!done){
if(retry>MAX_RETRY){
initialize();
retry = 0;
}
try {
ret = consumerIterator.hasNext();
done = true;
} catch (Exception e) {
String mesg = "Consumer iterator hasNext throws exception";
LOG.error(mesg, e);
threadSleep(retry++,mesg);
done = false;
}
}
return ret;
}
@Override | public Mupd8DataPair getNextDataPair() { |
giancosta86/EasyPmd | src/main/java/info/gianlucacosta/easypmd/ide/annotations/DefaultAnnotationService.java | // Path: src/main/java/info/gianlucacosta/easypmd/ide/options/Options.java
// public interface Options {
//
// static OptionsChanges computeChanges(Options oldOptions, Options newOptions) {
// if (oldOptions == null) {
// return OptionsChanges.ENGINE;
// }
//
// boolean noEngineChanges
// = Objects.equals(oldOptions.getTargetJavaVersion(), newOptions.getTargetJavaVersion())
// && Objects.equals(oldOptions.getSourceFileEncoding(), newOptions.getSourceFileEncoding())
// && Objects.equals(oldOptions.getSuppressMarker(), newOptions.getSuppressMarker())
// && CollectionItems.equals(oldOptions.getAdditionalClassPathUrls(), newOptions.getAdditionalClassPathUrls())
// && CollectionItems.equals(oldOptions.getRuleSets(), newOptions.getRuleSets())
// && (oldOptions.isShowAllMessagesInGuardedSections() == newOptions.isShowAllMessagesInGuardedSections())
// && Objects.equals(oldOptions.getPathFilteringOptions(), newOptions.getPathFilteringOptions())
// && (oldOptions.getMinimumPriority() == newOptions.getMinimumPriority())
// && Objects.equals(oldOptions.getAuxiliaryClassPath(), newOptions.getAuxiliaryClassPath())
// && (oldOptions.isUseScanMessagesCache() == newOptions.isUseScanMessagesCache());
//
// if (noEngineChanges) {
// boolean noChanges
// = (oldOptions.isShowRulePriorityInTasks() == newOptions.isShowRulePriorityInTasks())
// && (oldOptions.isShowDescriptionInTasks() == newOptions.isShowDescriptionInTasks())
// && (oldOptions.isShowRuleInTasks() == newOptions.isShowRuleInTasks())
// && (oldOptions.isShowRuleSetInTasks() == newOptions.isShowRuleSetInTasks())
// && (oldOptions.isShowAnnotationsInEditor() == newOptions.isShowAnnotationsInEditor());
//
// if (noChanges) {
// return OptionsChanges.NONE;
// } else {
// return OptionsChanges.VIEW_ONLY;
// }
// } else {
// return OptionsChanges.ENGINE;
// }
// }
//
// String getTargetJavaVersion();
//
// String getSourceFileEncoding();
//
// String getSuppressMarker();
//
// Collection<URL> getAdditionalClassPathUrls();
//
// Collection<String> getRuleSets();
//
// boolean isUseScanMessagesCache();
//
// boolean isShowRulePriorityInTasks();
//
// boolean isShowDescriptionInTasks();
//
// boolean isShowRuleInTasks();
//
// boolean isShowRuleSetInTasks();
//
// boolean isShowAnnotationsInEditor();
//
// boolean isShowAllMessagesInGuardedSections();
//
// PathFilteringOptions getPathFilteringOptions();
//
// RulePriority getMinimumPriority();
//
// String getAuxiliaryClassPath();
//
// Options clone();
// }
//
// Path: src/main/java/info/gianlucacosta/easypmd/pmdscanner/ScanMessage.java
// public interface ScanMessage extends Serializable {
//
// boolean isShowableInGuardedSections();
//
// int getLineNumber();
//
// Task createTask(Options options, FileObject fileObject);
//
// Annotation createAnnotation(Options options);
// }
| import org.openide.text.Line;
import org.openide.util.lookup.ServiceProvider;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;
import info.gianlucacosta.easypmd.ide.options.Options;
import info.gianlucacosta.easypmd.pmdscanner.ScanMessage;
import org.openide.cookies.LineCookie;
import org.openide.filesystems.FileChangeAdapter;
import org.openide.filesystems.FileChangeListener;
import org.openide.filesystems.FileEvent;
import org.openide.filesystems.FileObject;
import org.openide.loaders.DataObject;
import org.openide.text.Annotation; | /*
* ==========================================================================%%#
* EasyPmd
* ===========================================================================%%
* Copyright (C) 2009 - 2017 Gianluca Costa
* ===========================================================================%%
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public
* License along with this program. If not, see
* <http://www.gnu.org/licenses/gpl-3.0.html>.
* ==========================================================================%##
*/
package info.gianlucacosta.easypmd.ide.annotations;
/**
* Default implementation of AnnotationService
*/
@ServiceProvider(service = AnnotationService.class)
public class DefaultAnnotationService implements AnnotationService {
private final Map<FileObject, Set<Annotation>> attachedAnnotations = new HashMap<>();
private final Map<FileObject, FileChangeListener> registeredFileChangeListeners = new HashMap<>();
@Override | // Path: src/main/java/info/gianlucacosta/easypmd/ide/options/Options.java
// public interface Options {
//
// static OptionsChanges computeChanges(Options oldOptions, Options newOptions) {
// if (oldOptions == null) {
// return OptionsChanges.ENGINE;
// }
//
// boolean noEngineChanges
// = Objects.equals(oldOptions.getTargetJavaVersion(), newOptions.getTargetJavaVersion())
// && Objects.equals(oldOptions.getSourceFileEncoding(), newOptions.getSourceFileEncoding())
// && Objects.equals(oldOptions.getSuppressMarker(), newOptions.getSuppressMarker())
// && CollectionItems.equals(oldOptions.getAdditionalClassPathUrls(), newOptions.getAdditionalClassPathUrls())
// && CollectionItems.equals(oldOptions.getRuleSets(), newOptions.getRuleSets())
// && (oldOptions.isShowAllMessagesInGuardedSections() == newOptions.isShowAllMessagesInGuardedSections())
// && Objects.equals(oldOptions.getPathFilteringOptions(), newOptions.getPathFilteringOptions())
// && (oldOptions.getMinimumPriority() == newOptions.getMinimumPriority())
// && Objects.equals(oldOptions.getAuxiliaryClassPath(), newOptions.getAuxiliaryClassPath())
// && (oldOptions.isUseScanMessagesCache() == newOptions.isUseScanMessagesCache());
//
// if (noEngineChanges) {
// boolean noChanges
// = (oldOptions.isShowRulePriorityInTasks() == newOptions.isShowRulePriorityInTasks())
// && (oldOptions.isShowDescriptionInTasks() == newOptions.isShowDescriptionInTasks())
// && (oldOptions.isShowRuleInTasks() == newOptions.isShowRuleInTasks())
// && (oldOptions.isShowRuleSetInTasks() == newOptions.isShowRuleSetInTasks())
// && (oldOptions.isShowAnnotationsInEditor() == newOptions.isShowAnnotationsInEditor());
//
// if (noChanges) {
// return OptionsChanges.NONE;
// } else {
// return OptionsChanges.VIEW_ONLY;
// }
// } else {
// return OptionsChanges.ENGINE;
// }
// }
//
// String getTargetJavaVersion();
//
// String getSourceFileEncoding();
//
// String getSuppressMarker();
//
// Collection<URL> getAdditionalClassPathUrls();
//
// Collection<String> getRuleSets();
//
// boolean isUseScanMessagesCache();
//
// boolean isShowRulePriorityInTasks();
//
// boolean isShowDescriptionInTasks();
//
// boolean isShowRuleInTasks();
//
// boolean isShowRuleSetInTasks();
//
// boolean isShowAnnotationsInEditor();
//
// boolean isShowAllMessagesInGuardedSections();
//
// PathFilteringOptions getPathFilteringOptions();
//
// RulePriority getMinimumPriority();
//
// String getAuxiliaryClassPath();
//
// Options clone();
// }
//
// Path: src/main/java/info/gianlucacosta/easypmd/pmdscanner/ScanMessage.java
// public interface ScanMessage extends Serializable {
//
// boolean isShowableInGuardedSections();
//
// int getLineNumber();
//
// Task createTask(Options options, FileObject fileObject);
//
// Annotation createAnnotation(Options options);
// }
// Path: src/main/java/info/gianlucacosta/easypmd/ide/annotations/DefaultAnnotationService.java
import org.openide.text.Line;
import org.openide.util.lookup.ServiceProvider;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;
import info.gianlucacosta.easypmd.ide.options.Options;
import info.gianlucacosta.easypmd.pmdscanner.ScanMessage;
import org.openide.cookies.LineCookie;
import org.openide.filesystems.FileChangeAdapter;
import org.openide.filesystems.FileChangeListener;
import org.openide.filesystems.FileEvent;
import org.openide.filesystems.FileObject;
import org.openide.loaders.DataObject;
import org.openide.text.Annotation;
/*
* ==========================================================================%%#
* EasyPmd
* ===========================================================================%%
* Copyright (C) 2009 - 2017 Gianluca Costa
* ===========================================================================%%
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public
* License along with this program. If not, see
* <http://www.gnu.org/licenses/gpl-3.0.html>.
* ==========================================================================%##
*/
package info.gianlucacosta.easypmd.ide.annotations;
/**
* Default implementation of AnnotationService
*/
@ServiceProvider(service = AnnotationService.class)
public class DefaultAnnotationService implements AnnotationService {
private final Map<FileObject, Set<Annotation>> attachedAnnotations = new HashMap<>();
private final Map<FileObject, FileChangeListener> registeredFileChangeListeners = new HashMap<>();
@Override | public void attachAnnotationsTo(Options options, DataObject dataObject, Set<ScanMessage> scanMessages) { |
giancosta86/EasyPmd | src/main/java/info/gianlucacosta/easypmd/ide/annotations/DefaultAnnotationService.java | // Path: src/main/java/info/gianlucacosta/easypmd/ide/options/Options.java
// public interface Options {
//
// static OptionsChanges computeChanges(Options oldOptions, Options newOptions) {
// if (oldOptions == null) {
// return OptionsChanges.ENGINE;
// }
//
// boolean noEngineChanges
// = Objects.equals(oldOptions.getTargetJavaVersion(), newOptions.getTargetJavaVersion())
// && Objects.equals(oldOptions.getSourceFileEncoding(), newOptions.getSourceFileEncoding())
// && Objects.equals(oldOptions.getSuppressMarker(), newOptions.getSuppressMarker())
// && CollectionItems.equals(oldOptions.getAdditionalClassPathUrls(), newOptions.getAdditionalClassPathUrls())
// && CollectionItems.equals(oldOptions.getRuleSets(), newOptions.getRuleSets())
// && (oldOptions.isShowAllMessagesInGuardedSections() == newOptions.isShowAllMessagesInGuardedSections())
// && Objects.equals(oldOptions.getPathFilteringOptions(), newOptions.getPathFilteringOptions())
// && (oldOptions.getMinimumPriority() == newOptions.getMinimumPriority())
// && Objects.equals(oldOptions.getAuxiliaryClassPath(), newOptions.getAuxiliaryClassPath())
// && (oldOptions.isUseScanMessagesCache() == newOptions.isUseScanMessagesCache());
//
// if (noEngineChanges) {
// boolean noChanges
// = (oldOptions.isShowRulePriorityInTasks() == newOptions.isShowRulePriorityInTasks())
// && (oldOptions.isShowDescriptionInTasks() == newOptions.isShowDescriptionInTasks())
// && (oldOptions.isShowRuleInTasks() == newOptions.isShowRuleInTasks())
// && (oldOptions.isShowRuleSetInTasks() == newOptions.isShowRuleSetInTasks())
// && (oldOptions.isShowAnnotationsInEditor() == newOptions.isShowAnnotationsInEditor());
//
// if (noChanges) {
// return OptionsChanges.NONE;
// } else {
// return OptionsChanges.VIEW_ONLY;
// }
// } else {
// return OptionsChanges.ENGINE;
// }
// }
//
// String getTargetJavaVersion();
//
// String getSourceFileEncoding();
//
// String getSuppressMarker();
//
// Collection<URL> getAdditionalClassPathUrls();
//
// Collection<String> getRuleSets();
//
// boolean isUseScanMessagesCache();
//
// boolean isShowRulePriorityInTasks();
//
// boolean isShowDescriptionInTasks();
//
// boolean isShowRuleInTasks();
//
// boolean isShowRuleSetInTasks();
//
// boolean isShowAnnotationsInEditor();
//
// boolean isShowAllMessagesInGuardedSections();
//
// PathFilteringOptions getPathFilteringOptions();
//
// RulePriority getMinimumPriority();
//
// String getAuxiliaryClassPath();
//
// Options clone();
// }
//
// Path: src/main/java/info/gianlucacosta/easypmd/pmdscanner/ScanMessage.java
// public interface ScanMessage extends Serializable {
//
// boolean isShowableInGuardedSections();
//
// int getLineNumber();
//
// Task createTask(Options options, FileObject fileObject);
//
// Annotation createAnnotation(Options options);
// }
| import org.openide.text.Line;
import org.openide.util.lookup.ServiceProvider;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;
import info.gianlucacosta.easypmd.ide.options.Options;
import info.gianlucacosta.easypmd.pmdscanner.ScanMessage;
import org.openide.cookies.LineCookie;
import org.openide.filesystems.FileChangeAdapter;
import org.openide.filesystems.FileChangeListener;
import org.openide.filesystems.FileEvent;
import org.openide.filesystems.FileObject;
import org.openide.loaders.DataObject;
import org.openide.text.Annotation; | /*
* ==========================================================================%%#
* EasyPmd
* ===========================================================================%%
* Copyright (C) 2009 - 2017 Gianluca Costa
* ===========================================================================%%
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public
* License along with this program. If not, see
* <http://www.gnu.org/licenses/gpl-3.0.html>.
* ==========================================================================%##
*/
package info.gianlucacosta.easypmd.ide.annotations;
/**
* Default implementation of AnnotationService
*/
@ServiceProvider(service = AnnotationService.class)
public class DefaultAnnotationService implements AnnotationService {
private final Map<FileObject, Set<Annotation>> attachedAnnotations = new HashMap<>();
private final Map<FileObject, FileChangeListener> registeredFileChangeListeners = new HashMap<>();
@Override | // Path: src/main/java/info/gianlucacosta/easypmd/ide/options/Options.java
// public interface Options {
//
// static OptionsChanges computeChanges(Options oldOptions, Options newOptions) {
// if (oldOptions == null) {
// return OptionsChanges.ENGINE;
// }
//
// boolean noEngineChanges
// = Objects.equals(oldOptions.getTargetJavaVersion(), newOptions.getTargetJavaVersion())
// && Objects.equals(oldOptions.getSourceFileEncoding(), newOptions.getSourceFileEncoding())
// && Objects.equals(oldOptions.getSuppressMarker(), newOptions.getSuppressMarker())
// && CollectionItems.equals(oldOptions.getAdditionalClassPathUrls(), newOptions.getAdditionalClassPathUrls())
// && CollectionItems.equals(oldOptions.getRuleSets(), newOptions.getRuleSets())
// && (oldOptions.isShowAllMessagesInGuardedSections() == newOptions.isShowAllMessagesInGuardedSections())
// && Objects.equals(oldOptions.getPathFilteringOptions(), newOptions.getPathFilteringOptions())
// && (oldOptions.getMinimumPriority() == newOptions.getMinimumPriority())
// && Objects.equals(oldOptions.getAuxiliaryClassPath(), newOptions.getAuxiliaryClassPath())
// && (oldOptions.isUseScanMessagesCache() == newOptions.isUseScanMessagesCache());
//
// if (noEngineChanges) {
// boolean noChanges
// = (oldOptions.isShowRulePriorityInTasks() == newOptions.isShowRulePriorityInTasks())
// && (oldOptions.isShowDescriptionInTasks() == newOptions.isShowDescriptionInTasks())
// && (oldOptions.isShowRuleInTasks() == newOptions.isShowRuleInTasks())
// && (oldOptions.isShowRuleSetInTasks() == newOptions.isShowRuleSetInTasks())
// && (oldOptions.isShowAnnotationsInEditor() == newOptions.isShowAnnotationsInEditor());
//
// if (noChanges) {
// return OptionsChanges.NONE;
// } else {
// return OptionsChanges.VIEW_ONLY;
// }
// } else {
// return OptionsChanges.ENGINE;
// }
// }
//
// String getTargetJavaVersion();
//
// String getSourceFileEncoding();
//
// String getSuppressMarker();
//
// Collection<URL> getAdditionalClassPathUrls();
//
// Collection<String> getRuleSets();
//
// boolean isUseScanMessagesCache();
//
// boolean isShowRulePriorityInTasks();
//
// boolean isShowDescriptionInTasks();
//
// boolean isShowRuleInTasks();
//
// boolean isShowRuleSetInTasks();
//
// boolean isShowAnnotationsInEditor();
//
// boolean isShowAllMessagesInGuardedSections();
//
// PathFilteringOptions getPathFilteringOptions();
//
// RulePriority getMinimumPriority();
//
// String getAuxiliaryClassPath();
//
// Options clone();
// }
//
// Path: src/main/java/info/gianlucacosta/easypmd/pmdscanner/ScanMessage.java
// public interface ScanMessage extends Serializable {
//
// boolean isShowableInGuardedSections();
//
// int getLineNumber();
//
// Task createTask(Options options, FileObject fileObject);
//
// Annotation createAnnotation(Options options);
// }
// Path: src/main/java/info/gianlucacosta/easypmd/ide/annotations/DefaultAnnotationService.java
import org.openide.text.Line;
import org.openide.util.lookup.ServiceProvider;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;
import info.gianlucacosta.easypmd.ide.options.Options;
import info.gianlucacosta.easypmd.pmdscanner.ScanMessage;
import org.openide.cookies.LineCookie;
import org.openide.filesystems.FileChangeAdapter;
import org.openide.filesystems.FileChangeListener;
import org.openide.filesystems.FileEvent;
import org.openide.filesystems.FileObject;
import org.openide.loaders.DataObject;
import org.openide.text.Annotation;
/*
* ==========================================================================%%#
* EasyPmd
* ===========================================================================%%
* Copyright (C) 2009 - 2017 Gianluca Costa
* ===========================================================================%%
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public
* License along with this program. If not, see
* <http://www.gnu.org/licenses/gpl-3.0.html>.
* ==========================================================================%##
*/
package info.gianlucacosta.easypmd.ide.annotations;
/**
* Default implementation of AnnotationService
*/
@ServiceProvider(service = AnnotationService.class)
public class DefaultAnnotationService implements AnnotationService {
private final Map<FileObject, Set<Annotation>> attachedAnnotations = new HashMap<>();
private final Map<FileObject, FileChangeListener> registeredFileChangeListeners = new HashMap<>();
@Override | public void attachAnnotationsTo(Options options, DataObject dataObject, Set<ScanMessage> scanMessages) { |
giancosta86/EasyPmd | src/main/java/info/gianlucacosta/easypmd/ide/options/EasyPmdOptionsPanelController.java | // Path: src/main/java/info/gianlucacosta/easypmd/ide/Injector.java
// public class Injector {
//
// @ServiceProvider(service = TestService.class)
// public static class TestService {
// }
//
// private static final Lookup lookup = Lookup.getDefault();
//
// private static Lookup getLookup() {
// return lookup;
// }
//
// public static <T> T lookup(Class<T> serviceClass) {
// T result = getLookup().lookup(serviceClass);
//
// validateLookupResult(serviceClass, result);
//
// return result;
// }
//
// public static <T> Collection<? extends T> lookupAll(Class<T> serviceClass) {
// Collection<? extends T> result = getLookup().lookupAll(serviceClass);
//
// validateLookupResult(serviceClass, result);
//
// return result;
// }
//
// private static void validateLookupResult(Class<?> serviceClass, Object lookupResult) {
// if (lookupResult == null) {
// if (shouldThrowLookupExceptions(serviceClass)) {
// throw new IllegalArgumentException(String.format("Service '%s' not registered!", serviceClass.getSimpleName()));
// }
// }
// }
//
// //This code prevents exceptions in the visual form editors within NetBeans
// private static boolean shouldThrowLookupExceptions(Class<?> serviceClass) {
// if (serviceClass != TestService.class) {
// TestService testService = lookup.lookup(TestService.class);
// if (testService == null) {
// return false;
// }
// }
//
// return true;
// }
//
// private Injector() {
// }
// }
//
// Path: src/main/java/info/gianlucacosta/easypmd/pmdscanner/PmdScanner.java
// public class PmdScanner {
//
// private static final Logger logger = Logger.getLogger(PmdScanner.class.getName());
//
// private final PmdScannerStrategy strategy;
//
// public PmdScanner(Options options) {
// if (options.getRuleSets().isEmpty()) {
// logger.info(() -> "Setting a NOP scanning strategy");
// strategy = new NoOpPmdScannerStrategy();
// return;
// }
//
// if (options.isUseScanMessagesCache()) {
// logger.info(() -> "Setting a cached scanning strategy");
// strategy = new CacheBasedLinkedPmdScanningStrategy(options);
// } else {
// logger.info(() -> "Setting a non-cached scanning strategy");
// strategy = new LinkedPmdScanningStrategy(options);
// }
// }
//
// public Set<ScanMessage> scan(Path path) {
// try {
// return strategy.scan(path);
// } catch (Exception ex) {
// ScanError scanError = new ScanError(ex);
//
// return Collections.singleton(
// scanError
// );
// }
// }
// }
//
// Path: src/main/java/info/gianlucacosta/easypmd/ide/options/profiles/ProfileContext.java
// public interface ProfileContext {
//
// ProfileMap getProfiles();
//
// String getActiveProfileName();
//
// Options getActiveOptions();
// }
//
// Path: src/main/java/info/gianlucacosta/easypmd/ide/options/profiles/ProfileContextRepository.java
// public interface ProfileContextRepository {
//
// ProfileContext getProfileContext();
//
// void saveProfileContext(ProfileContext profileContext);
// }
| import info.gianlucacosta.easypmd.ide.options.profiles.ProfileContext;
import info.gianlucacosta.easypmd.ide.options.profiles.ProfileContextRepository;
import java.util.logging.Logger;
import info.gianlucacosta.easypmd.ide.Injector;
import info.gianlucacosta.easypmd.pmdscanner.PmdScanner;
import org.netbeans.spi.options.OptionsPanelController;
import org.openide.util.HelpCtx;
import org.openide.util.Lookup;
import javax.swing.*;
import java.beans.PropertyChangeListener;
import java.beans.PropertyChangeSupport; | /*
* ==========================================================================%%#
* EasyPmd
* ===========================================================================%%
* Copyright (C) 2009 - 2017 Gianluca Costa
* ===========================================================================%%
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public
* License along with this program. If not, see
* <http://www.gnu.org/licenses/gpl-3.0.html>.
* ==========================================================================%##
*/
package info.gianlucacosta.easypmd.ide.options;
/**
* Controller underlying the plugin's options panel
*/
@OptionsPanelController.TopLevelRegistration(
id = "info.gianlucacosta.easypmd.ide.options.EasyPmdOptionsPanelController",
categoryName = "#Option_DisplayName_EasyPmd",
keywords = "#Option_Keywords_EasyPmd",
keywordsCategory = "#Option_KeywordsCategory_EasyPmd",
iconBase = "info/gianlucacosta/easypmd/mainIcon32.png"
)
public class EasyPmdOptionsPanelController extends OptionsPanelController {
private static final Logger logger = Logger.getLogger(EasyPmdOptionsPanelController.class.getName());
private static final String EASY_PMD_OPTIONS_NAME_IN_EVENT = "EASYPMD_OPTIONS";
private final EasyPmdPanel easyPmdPanel = new EasyPmdPanel();
private final PropertyChangeSupport pcs = new PropertyChangeSupport(this); | // Path: src/main/java/info/gianlucacosta/easypmd/ide/Injector.java
// public class Injector {
//
// @ServiceProvider(service = TestService.class)
// public static class TestService {
// }
//
// private static final Lookup lookup = Lookup.getDefault();
//
// private static Lookup getLookup() {
// return lookup;
// }
//
// public static <T> T lookup(Class<T> serviceClass) {
// T result = getLookup().lookup(serviceClass);
//
// validateLookupResult(serviceClass, result);
//
// return result;
// }
//
// public static <T> Collection<? extends T> lookupAll(Class<T> serviceClass) {
// Collection<? extends T> result = getLookup().lookupAll(serviceClass);
//
// validateLookupResult(serviceClass, result);
//
// return result;
// }
//
// private static void validateLookupResult(Class<?> serviceClass, Object lookupResult) {
// if (lookupResult == null) {
// if (shouldThrowLookupExceptions(serviceClass)) {
// throw new IllegalArgumentException(String.format("Service '%s' not registered!", serviceClass.getSimpleName()));
// }
// }
// }
//
// //This code prevents exceptions in the visual form editors within NetBeans
// private static boolean shouldThrowLookupExceptions(Class<?> serviceClass) {
// if (serviceClass != TestService.class) {
// TestService testService = lookup.lookup(TestService.class);
// if (testService == null) {
// return false;
// }
// }
//
// return true;
// }
//
// private Injector() {
// }
// }
//
// Path: src/main/java/info/gianlucacosta/easypmd/pmdscanner/PmdScanner.java
// public class PmdScanner {
//
// private static final Logger logger = Logger.getLogger(PmdScanner.class.getName());
//
// private final PmdScannerStrategy strategy;
//
// public PmdScanner(Options options) {
// if (options.getRuleSets().isEmpty()) {
// logger.info(() -> "Setting a NOP scanning strategy");
// strategy = new NoOpPmdScannerStrategy();
// return;
// }
//
// if (options.isUseScanMessagesCache()) {
// logger.info(() -> "Setting a cached scanning strategy");
// strategy = new CacheBasedLinkedPmdScanningStrategy(options);
// } else {
// logger.info(() -> "Setting a non-cached scanning strategy");
// strategy = new LinkedPmdScanningStrategy(options);
// }
// }
//
// public Set<ScanMessage> scan(Path path) {
// try {
// return strategy.scan(path);
// } catch (Exception ex) {
// ScanError scanError = new ScanError(ex);
//
// return Collections.singleton(
// scanError
// );
// }
// }
// }
//
// Path: src/main/java/info/gianlucacosta/easypmd/ide/options/profiles/ProfileContext.java
// public interface ProfileContext {
//
// ProfileMap getProfiles();
//
// String getActiveProfileName();
//
// Options getActiveOptions();
// }
//
// Path: src/main/java/info/gianlucacosta/easypmd/ide/options/profiles/ProfileContextRepository.java
// public interface ProfileContextRepository {
//
// ProfileContext getProfileContext();
//
// void saveProfileContext(ProfileContext profileContext);
// }
// Path: src/main/java/info/gianlucacosta/easypmd/ide/options/EasyPmdOptionsPanelController.java
import info.gianlucacosta.easypmd.ide.options.profiles.ProfileContext;
import info.gianlucacosta.easypmd.ide.options.profiles.ProfileContextRepository;
import java.util.logging.Logger;
import info.gianlucacosta.easypmd.ide.Injector;
import info.gianlucacosta.easypmd.pmdscanner.PmdScanner;
import org.netbeans.spi.options.OptionsPanelController;
import org.openide.util.HelpCtx;
import org.openide.util.Lookup;
import javax.swing.*;
import java.beans.PropertyChangeListener;
import java.beans.PropertyChangeSupport;
/*
* ==========================================================================%%#
* EasyPmd
* ===========================================================================%%
* Copyright (C) 2009 - 2017 Gianluca Costa
* ===========================================================================%%
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public
* License along with this program. If not, see
* <http://www.gnu.org/licenses/gpl-3.0.html>.
* ==========================================================================%##
*/
package info.gianlucacosta.easypmd.ide.options;
/**
* Controller underlying the plugin's options panel
*/
@OptionsPanelController.TopLevelRegistration(
id = "info.gianlucacosta.easypmd.ide.options.EasyPmdOptionsPanelController",
categoryName = "#Option_DisplayName_EasyPmd",
keywords = "#Option_Keywords_EasyPmd",
keywordsCategory = "#Option_KeywordsCategory_EasyPmd",
iconBase = "info/gianlucacosta/easypmd/mainIcon32.png"
)
public class EasyPmdOptionsPanelController extends OptionsPanelController {
private static final Logger logger = Logger.getLogger(EasyPmdOptionsPanelController.class.getName());
private static final String EASY_PMD_OPTIONS_NAME_IN_EVENT = "EASYPMD_OPTIONS";
private final EasyPmdPanel easyPmdPanel = new EasyPmdPanel();
private final PropertyChangeSupport pcs = new PropertyChangeSupport(this); | private final ProfileContextRepository profileContextRepository; |
giancosta86/EasyPmd | src/main/java/info/gianlucacosta/easypmd/ide/options/EasyPmdOptionsPanelController.java | // Path: src/main/java/info/gianlucacosta/easypmd/ide/Injector.java
// public class Injector {
//
// @ServiceProvider(service = TestService.class)
// public static class TestService {
// }
//
// private static final Lookup lookup = Lookup.getDefault();
//
// private static Lookup getLookup() {
// return lookup;
// }
//
// public static <T> T lookup(Class<T> serviceClass) {
// T result = getLookup().lookup(serviceClass);
//
// validateLookupResult(serviceClass, result);
//
// return result;
// }
//
// public static <T> Collection<? extends T> lookupAll(Class<T> serviceClass) {
// Collection<? extends T> result = getLookup().lookupAll(serviceClass);
//
// validateLookupResult(serviceClass, result);
//
// return result;
// }
//
// private static void validateLookupResult(Class<?> serviceClass, Object lookupResult) {
// if (lookupResult == null) {
// if (shouldThrowLookupExceptions(serviceClass)) {
// throw new IllegalArgumentException(String.format("Service '%s' not registered!", serviceClass.getSimpleName()));
// }
// }
// }
//
// //This code prevents exceptions in the visual form editors within NetBeans
// private static boolean shouldThrowLookupExceptions(Class<?> serviceClass) {
// if (serviceClass != TestService.class) {
// TestService testService = lookup.lookup(TestService.class);
// if (testService == null) {
// return false;
// }
// }
//
// return true;
// }
//
// private Injector() {
// }
// }
//
// Path: src/main/java/info/gianlucacosta/easypmd/pmdscanner/PmdScanner.java
// public class PmdScanner {
//
// private static final Logger logger = Logger.getLogger(PmdScanner.class.getName());
//
// private final PmdScannerStrategy strategy;
//
// public PmdScanner(Options options) {
// if (options.getRuleSets().isEmpty()) {
// logger.info(() -> "Setting a NOP scanning strategy");
// strategy = new NoOpPmdScannerStrategy();
// return;
// }
//
// if (options.isUseScanMessagesCache()) {
// logger.info(() -> "Setting a cached scanning strategy");
// strategy = new CacheBasedLinkedPmdScanningStrategy(options);
// } else {
// logger.info(() -> "Setting a non-cached scanning strategy");
// strategy = new LinkedPmdScanningStrategy(options);
// }
// }
//
// public Set<ScanMessage> scan(Path path) {
// try {
// return strategy.scan(path);
// } catch (Exception ex) {
// ScanError scanError = new ScanError(ex);
//
// return Collections.singleton(
// scanError
// );
// }
// }
// }
//
// Path: src/main/java/info/gianlucacosta/easypmd/ide/options/profiles/ProfileContext.java
// public interface ProfileContext {
//
// ProfileMap getProfiles();
//
// String getActiveProfileName();
//
// Options getActiveOptions();
// }
//
// Path: src/main/java/info/gianlucacosta/easypmd/ide/options/profiles/ProfileContextRepository.java
// public interface ProfileContextRepository {
//
// ProfileContext getProfileContext();
//
// void saveProfileContext(ProfileContext profileContext);
// }
| import info.gianlucacosta.easypmd.ide.options.profiles.ProfileContext;
import info.gianlucacosta.easypmd.ide.options.profiles.ProfileContextRepository;
import java.util.logging.Logger;
import info.gianlucacosta.easypmd.ide.Injector;
import info.gianlucacosta.easypmd.pmdscanner.PmdScanner;
import org.netbeans.spi.options.OptionsPanelController;
import org.openide.util.HelpCtx;
import org.openide.util.Lookup;
import javax.swing.*;
import java.beans.PropertyChangeListener;
import java.beans.PropertyChangeSupport; | /*
* ==========================================================================%%#
* EasyPmd
* ===========================================================================%%
* Copyright (C) 2009 - 2017 Gianluca Costa
* ===========================================================================%%
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public
* License along with this program. If not, see
* <http://www.gnu.org/licenses/gpl-3.0.html>.
* ==========================================================================%##
*/
package info.gianlucacosta.easypmd.ide.options;
/**
* Controller underlying the plugin's options panel
*/
@OptionsPanelController.TopLevelRegistration(
id = "info.gianlucacosta.easypmd.ide.options.EasyPmdOptionsPanelController",
categoryName = "#Option_DisplayName_EasyPmd",
keywords = "#Option_Keywords_EasyPmd",
keywordsCategory = "#Option_KeywordsCategory_EasyPmd",
iconBase = "info/gianlucacosta/easypmd/mainIcon32.png"
)
public class EasyPmdOptionsPanelController extends OptionsPanelController {
private static final Logger logger = Logger.getLogger(EasyPmdOptionsPanelController.class.getName());
private static final String EASY_PMD_OPTIONS_NAME_IN_EVENT = "EASYPMD_OPTIONS";
private final EasyPmdPanel easyPmdPanel = new EasyPmdPanel();
private final PropertyChangeSupport pcs = new PropertyChangeSupport(this);
private final ProfileContextRepository profileContextRepository;
private final OptionsService optionsService;
private boolean optionsChanged;
private boolean valid;
public EasyPmdOptionsPanelController() { | // Path: src/main/java/info/gianlucacosta/easypmd/ide/Injector.java
// public class Injector {
//
// @ServiceProvider(service = TestService.class)
// public static class TestService {
// }
//
// private static final Lookup lookup = Lookup.getDefault();
//
// private static Lookup getLookup() {
// return lookup;
// }
//
// public static <T> T lookup(Class<T> serviceClass) {
// T result = getLookup().lookup(serviceClass);
//
// validateLookupResult(serviceClass, result);
//
// return result;
// }
//
// public static <T> Collection<? extends T> lookupAll(Class<T> serviceClass) {
// Collection<? extends T> result = getLookup().lookupAll(serviceClass);
//
// validateLookupResult(serviceClass, result);
//
// return result;
// }
//
// private static void validateLookupResult(Class<?> serviceClass, Object lookupResult) {
// if (lookupResult == null) {
// if (shouldThrowLookupExceptions(serviceClass)) {
// throw new IllegalArgumentException(String.format("Service '%s' not registered!", serviceClass.getSimpleName()));
// }
// }
// }
//
// //This code prevents exceptions in the visual form editors within NetBeans
// private static boolean shouldThrowLookupExceptions(Class<?> serviceClass) {
// if (serviceClass != TestService.class) {
// TestService testService = lookup.lookup(TestService.class);
// if (testService == null) {
// return false;
// }
// }
//
// return true;
// }
//
// private Injector() {
// }
// }
//
// Path: src/main/java/info/gianlucacosta/easypmd/pmdscanner/PmdScanner.java
// public class PmdScanner {
//
// private static final Logger logger = Logger.getLogger(PmdScanner.class.getName());
//
// private final PmdScannerStrategy strategy;
//
// public PmdScanner(Options options) {
// if (options.getRuleSets().isEmpty()) {
// logger.info(() -> "Setting a NOP scanning strategy");
// strategy = new NoOpPmdScannerStrategy();
// return;
// }
//
// if (options.isUseScanMessagesCache()) {
// logger.info(() -> "Setting a cached scanning strategy");
// strategy = new CacheBasedLinkedPmdScanningStrategy(options);
// } else {
// logger.info(() -> "Setting a non-cached scanning strategy");
// strategy = new LinkedPmdScanningStrategy(options);
// }
// }
//
// public Set<ScanMessage> scan(Path path) {
// try {
// return strategy.scan(path);
// } catch (Exception ex) {
// ScanError scanError = new ScanError(ex);
//
// return Collections.singleton(
// scanError
// );
// }
// }
// }
//
// Path: src/main/java/info/gianlucacosta/easypmd/ide/options/profiles/ProfileContext.java
// public interface ProfileContext {
//
// ProfileMap getProfiles();
//
// String getActiveProfileName();
//
// Options getActiveOptions();
// }
//
// Path: src/main/java/info/gianlucacosta/easypmd/ide/options/profiles/ProfileContextRepository.java
// public interface ProfileContextRepository {
//
// ProfileContext getProfileContext();
//
// void saveProfileContext(ProfileContext profileContext);
// }
// Path: src/main/java/info/gianlucacosta/easypmd/ide/options/EasyPmdOptionsPanelController.java
import info.gianlucacosta.easypmd.ide.options.profiles.ProfileContext;
import info.gianlucacosta.easypmd.ide.options.profiles.ProfileContextRepository;
import java.util.logging.Logger;
import info.gianlucacosta.easypmd.ide.Injector;
import info.gianlucacosta.easypmd.pmdscanner.PmdScanner;
import org.netbeans.spi.options.OptionsPanelController;
import org.openide.util.HelpCtx;
import org.openide.util.Lookup;
import javax.swing.*;
import java.beans.PropertyChangeListener;
import java.beans.PropertyChangeSupport;
/*
* ==========================================================================%%#
* EasyPmd
* ===========================================================================%%
* Copyright (C) 2009 - 2017 Gianluca Costa
* ===========================================================================%%
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public
* License along with this program. If not, see
* <http://www.gnu.org/licenses/gpl-3.0.html>.
* ==========================================================================%##
*/
package info.gianlucacosta.easypmd.ide.options;
/**
* Controller underlying the plugin's options panel
*/
@OptionsPanelController.TopLevelRegistration(
id = "info.gianlucacosta.easypmd.ide.options.EasyPmdOptionsPanelController",
categoryName = "#Option_DisplayName_EasyPmd",
keywords = "#Option_Keywords_EasyPmd",
keywordsCategory = "#Option_KeywordsCategory_EasyPmd",
iconBase = "info/gianlucacosta/easypmd/mainIcon32.png"
)
public class EasyPmdOptionsPanelController extends OptionsPanelController {
private static final Logger logger = Logger.getLogger(EasyPmdOptionsPanelController.class.getName());
private static final String EASY_PMD_OPTIONS_NAME_IN_EVENT = "EASYPMD_OPTIONS";
private final EasyPmdPanel easyPmdPanel = new EasyPmdPanel();
private final PropertyChangeSupport pcs = new PropertyChangeSupport(this);
private final ProfileContextRepository profileContextRepository;
private final OptionsService optionsService;
private boolean optionsChanged;
private boolean valid;
public EasyPmdOptionsPanelController() { | profileContextRepository = Injector.lookup(ProfileContextRepository.class); |
giancosta86/EasyPmd | src/main/java/info/gianlucacosta/easypmd/ide/options/EasyPmdOptionsPanelController.java | // Path: src/main/java/info/gianlucacosta/easypmd/ide/Injector.java
// public class Injector {
//
// @ServiceProvider(service = TestService.class)
// public static class TestService {
// }
//
// private static final Lookup lookup = Lookup.getDefault();
//
// private static Lookup getLookup() {
// return lookup;
// }
//
// public static <T> T lookup(Class<T> serviceClass) {
// T result = getLookup().lookup(serviceClass);
//
// validateLookupResult(serviceClass, result);
//
// return result;
// }
//
// public static <T> Collection<? extends T> lookupAll(Class<T> serviceClass) {
// Collection<? extends T> result = getLookup().lookupAll(serviceClass);
//
// validateLookupResult(serviceClass, result);
//
// return result;
// }
//
// private static void validateLookupResult(Class<?> serviceClass, Object lookupResult) {
// if (lookupResult == null) {
// if (shouldThrowLookupExceptions(serviceClass)) {
// throw new IllegalArgumentException(String.format("Service '%s' not registered!", serviceClass.getSimpleName()));
// }
// }
// }
//
// //This code prevents exceptions in the visual form editors within NetBeans
// private static boolean shouldThrowLookupExceptions(Class<?> serviceClass) {
// if (serviceClass != TestService.class) {
// TestService testService = lookup.lookup(TestService.class);
// if (testService == null) {
// return false;
// }
// }
//
// return true;
// }
//
// private Injector() {
// }
// }
//
// Path: src/main/java/info/gianlucacosta/easypmd/pmdscanner/PmdScanner.java
// public class PmdScanner {
//
// private static final Logger logger = Logger.getLogger(PmdScanner.class.getName());
//
// private final PmdScannerStrategy strategy;
//
// public PmdScanner(Options options) {
// if (options.getRuleSets().isEmpty()) {
// logger.info(() -> "Setting a NOP scanning strategy");
// strategy = new NoOpPmdScannerStrategy();
// return;
// }
//
// if (options.isUseScanMessagesCache()) {
// logger.info(() -> "Setting a cached scanning strategy");
// strategy = new CacheBasedLinkedPmdScanningStrategy(options);
// } else {
// logger.info(() -> "Setting a non-cached scanning strategy");
// strategy = new LinkedPmdScanningStrategy(options);
// }
// }
//
// public Set<ScanMessage> scan(Path path) {
// try {
// return strategy.scan(path);
// } catch (Exception ex) {
// ScanError scanError = new ScanError(ex);
//
// return Collections.singleton(
// scanError
// );
// }
// }
// }
//
// Path: src/main/java/info/gianlucacosta/easypmd/ide/options/profiles/ProfileContext.java
// public interface ProfileContext {
//
// ProfileMap getProfiles();
//
// String getActiveProfileName();
//
// Options getActiveOptions();
// }
//
// Path: src/main/java/info/gianlucacosta/easypmd/ide/options/profiles/ProfileContextRepository.java
// public interface ProfileContextRepository {
//
// ProfileContext getProfileContext();
//
// void saveProfileContext(ProfileContext profileContext);
// }
| import info.gianlucacosta.easypmd.ide.options.profiles.ProfileContext;
import info.gianlucacosta.easypmd.ide.options.profiles.ProfileContextRepository;
import java.util.logging.Logger;
import info.gianlucacosta.easypmd.ide.Injector;
import info.gianlucacosta.easypmd.pmdscanner.PmdScanner;
import org.netbeans.spi.options.OptionsPanelController;
import org.openide.util.HelpCtx;
import org.openide.util.Lookup;
import javax.swing.*;
import java.beans.PropertyChangeListener;
import java.beans.PropertyChangeSupport; | private boolean valid;
public EasyPmdOptionsPanelController() {
profileContextRepository = Injector.lookup(ProfileContextRepository.class);
optionsService = Injector.lookup(OptionsService.class);
optionsService.addOptionsSetListener((options, optionsChanges) -> {
optionsChanged = (optionsChanges != OptionsChanges.NONE);
if (optionsChanged) {
pcs.firePropertyChange(EASY_PMD_OPTIONS_NAME_IN_EVENT, null, options);
}
});
}
private void internalValidate() {
logger.info(() -> "Internally validating the options, for the options controller...");
try {
Options activeOptions = easyPmdPanel.getProfileContextDTO().getProfileContext().getActiveOptions();
optionsService.validateOptions(activeOptions);
valid = true;
logger.info("Options valid");
} catch (InvalidOptionsException ex) {
valid = false;
logger.info("Options NOT valid");
}
}
@Override
public void update() { | // Path: src/main/java/info/gianlucacosta/easypmd/ide/Injector.java
// public class Injector {
//
// @ServiceProvider(service = TestService.class)
// public static class TestService {
// }
//
// private static final Lookup lookup = Lookup.getDefault();
//
// private static Lookup getLookup() {
// return lookup;
// }
//
// public static <T> T lookup(Class<T> serviceClass) {
// T result = getLookup().lookup(serviceClass);
//
// validateLookupResult(serviceClass, result);
//
// return result;
// }
//
// public static <T> Collection<? extends T> lookupAll(Class<T> serviceClass) {
// Collection<? extends T> result = getLookup().lookupAll(serviceClass);
//
// validateLookupResult(serviceClass, result);
//
// return result;
// }
//
// private static void validateLookupResult(Class<?> serviceClass, Object lookupResult) {
// if (lookupResult == null) {
// if (shouldThrowLookupExceptions(serviceClass)) {
// throw new IllegalArgumentException(String.format("Service '%s' not registered!", serviceClass.getSimpleName()));
// }
// }
// }
//
// //This code prevents exceptions in the visual form editors within NetBeans
// private static boolean shouldThrowLookupExceptions(Class<?> serviceClass) {
// if (serviceClass != TestService.class) {
// TestService testService = lookup.lookup(TestService.class);
// if (testService == null) {
// return false;
// }
// }
//
// return true;
// }
//
// private Injector() {
// }
// }
//
// Path: src/main/java/info/gianlucacosta/easypmd/pmdscanner/PmdScanner.java
// public class PmdScanner {
//
// private static final Logger logger = Logger.getLogger(PmdScanner.class.getName());
//
// private final PmdScannerStrategy strategy;
//
// public PmdScanner(Options options) {
// if (options.getRuleSets().isEmpty()) {
// logger.info(() -> "Setting a NOP scanning strategy");
// strategy = new NoOpPmdScannerStrategy();
// return;
// }
//
// if (options.isUseScanMessagesCache()) {
// logger.info(() -> "Setting a cached scanning strategy");
// strategy = new CacheBasedLinkedPmdScanningStrategy(options);
// } else {
// logger.info(() -> "Setting a non-cached scanning strategy");
// strategy = new LinkedPmdScanningStrategy(options);
// }
// }
//
// public Set<ScanMessage> scan(Path path) {
// try {
// return strategy.scan(path);
// } catch (Exception ex) {
// ScanError scanError = new ScanError(ex);
//
// return Collections.singleton(
// scanError
// );
// }
// }
// }
//
// Path: src/main/java/info/gianlucacosta/easypmd/ide/options/profiles/ProfileContext.java
// public interface ProfileContext {
//
// ProfileMap getProfiles();
//
// String getActiveProfileName();
//
// Options getActiveOptions();
// }
//
// Path: src/main/java/info/gianlucacosta/easypmd/ide/options/profiles/ProfileContextRepository.java
// public interface ProfileContextRepository {
//
// ProfileContext getProfileContext();
//
// void saveProfileContext(ProfileContext profileContext);
// }
// Path: src/main/java/info/gianlucacosta/easypmd/ide/options/EasyPmdOptionsPanelController.java
import info.gianlucacosta.easypmd.ide.options.profiles.ProfileContext;
import info.gianlucacosta.easypmd.ide.options.profiles.ProfileContextRepository;
import java.util.logging.Logger;
import info.gianlucacosta.easypmd.ide.Injector;
import info.gianlucacosta.easypmd.pmdscanner.PmdScanner;
import org.netbeans.spi.options.OptionsPanelController;
import org.openide.util.HelpCtx;
import org.openide.util.Lookup;
import javax.swing.*;
import java.beans.PropertyChangeListener;
import java.beans.PropertyChangeSupport;
private boolean valid;
public EasyPmdOptionsPanelController() {
profileContextRepository = Injector.lookup(ProfileContextRepository.class);
optionsService = Injector.lookup(OptionsService.class);
optionsService.addOptionsSetListener((options, optionsChanges) -> {
optionsChanged = (optionsChanges != OptionsChanges.NONE);
if (optionsChanged) {
pcs.firePropertyChange(EASY_PMD_OPTIONS_NAME_IN_EVENT, null, options);
}
});
}
private void internalValidate() {
logger.info(() -> "Internally validating the options, for the options controller...");
try {
Options activeOptions = easyPmdPanel.getProfileContextDTO().getProfileContext().getActiveOptions();
optionsService.validateOptions(activeOptions);
valid = true;
logger.info("Options valid");
} catch (InvalidOptionsException ex) {
valid = false;
logger.info("Options NOT valid");
}
}
@Override
public void update() { | ProfileContext profileContext = profileContextRepository.getProfileContext(); |
giancosta86/EasyPmd | src/main/java/info/gianlucacosta/easypmd/ide/options/DefaultOptionsFactory.java | // Path: src/main/java/info/gianlucacosta/easypmd/system/SystemPropertiesService.java
// public interface SystemPropertiesService {
//
// String getJavaVersion();
//
// Path getUserHomeDirectory();
// }
//
// Path: src/main/java/info/gianlucacosta/easypmd/ide/Injector.java
// public class Injector {
//
// @ServiceProvider(service = TestService.class)
// public static class TestService {
// }
//
// private static final Lookup lookup = Lookup.getDefault();
//
// private static Lookup getLookup() {
// return lookup;
// }
//
// public static <T> T lookup(Class<T> serviceClass) {
// T result = getLookup().lookup(serviceClass);
//
// validateLookupResult(serviceClass, result);
//
// return result;
// }
//
// public static <T> Collection<? extends T> lookupAll(Class<T> serviceClass) {
// Collection<? extends T> result = getLookup().lookupAll(serviceClass);
//
// validateLookupResult(serviceClass, result);
//
// return result;
// }
//
// private static void validateLookupResult(Class<?> serviceClass, Object lookupResult) {
// if (lookupResult == null) {
// if (shouldThrowLookupExceptions(serviceClass)) {
// throw new IllegalArgumentException(String.format("Service '%s' not registered!", serviceClass.getSimpleName()));
// }
// }
// }
//
// //This code prevents exceptions in the visual form editors within NetBeans
// private static boolean shouldThrowLookupExceptions(Class<?> serviceClass) {
// if (serviceClass != TestService.class) {
// TestService testService = lookup.lookup(TestService.class);
// if (testService == null) {
// return false;
// }
// }
//
// return true;
// }
//
// private Injector() {
// }
// }
//
// Path: src/main/java/info/gianlucacosta/easypmd/pmdscanner/pmdcatalogs/LanguageVersionParser.java
// public interface LanguageVersionParser {
//
// LanguageVersion parse(String versionString);
// }
//
// Path: src/main/java/info/gianlucacosta/easypmd/pmdscanner/pmdcatalogs/StandardRuleSetsCatalog.java
// public interface StandardRuleSetsCatalog {
//
// boolean containsFileName(String ruleSetFileName);
//
// Collection<RuleSetWrapper> getRuleSetWrappers();
// }
| import java.util.Arrays;
import java.util.List;
import java.util.logging.Logger;
import info.gianlucacosta.easypmd.system.SystemPropertiesService;
import info.gianlucacosta.easypmd.ide.Injector;
import info.gianlucacosta.easypmd.pmdscanner.pmdcatalogs.LanguageVersionParser;
import info.gianlucacosta.easypmd.pmdscanner.pmdcatalogs.StandardRuleSetsCatalog;
import info.gianlucacosta.helios.regex.OsSpecificPathCompositeRegex;
import net.sourceforge.pmd.RulePriority;
import org.openide.util.lookup.ServiceProvider;
import java.util.ArrayList; | /*
* ==========================================================================%%#
* EasyPmd
* ===========================================================================%%
* Copyright (C) 2009 - 2017 Gianluca Costa
* ===========================================================================%%
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public
* License along with this program. If not, see
* <http://www.gnu.org/licenses/gpl-3.0.html>.
* ==========================================================================%##
*/
package info.gianlucacosta.easypmd.ide.options;
/**
* Default implementation of OptionsFactory
*/
@ServiceProvider(service = OptionsFactory.class)
public class DefaultOptionsFactory implements OptionsFactory {
private static final Logger logger = Logger.getLogger(DefaultOptionsFactory.class.getName());
private static final String fallbackJavaLanguageVersion = "1.8";
| // Path: src/main/java/info/gianlucacosta/easypmd/system/SystemPropertiesService.java
// public interface SystemPropertiesService {
//
// String getJavaVersion();
//
// Path getUserHomeDirectory();
// }
//
// Path: src/main/java/info/gianlucacosta/easypmd/ide/Injector.java
// public class Injector {
//
// @ServiceProvider(service = TestService.class)
// public static class TestService {
// }
//
// private static final Lookup lookup = Lookup.getDefault();
//
// private static Lookup getLookup() {
// return lookup;
// }
//
// public static <T> T lookup(Class<T> serviceClass) {
// T result = getLookup().lookup(serviceClass);
//
// validateLookupResult(serviceClass, result);
//
// return result;
// }
//
// public static <T> Collection<? extends T> lookupAll(Class<T> serviceClass) {
// Collection<? extends T> result = getLookup().lookupAll(serviceClass);
//
// validateLookupResult(serviceClass, result);
//
// return result;
// }
//
// private static void validateLookupResult(Class<?> serviceClass, Object lookupResult) {
// if (lookupResult == null) {
// if (shouldThrowLookupExceptions(serviceClass)) {
// throw new IllegalArgumentException(String.format("Service '%s' not registered!", serviceClass.getSimpleName()));
// }
// }
// }
//
// //This code prevents exceptions in the visual form editors within NetBeans
// private static boolean shouldThrowLookupExceptions(Class<?> serviceClass) {
// if (serviceClass != TestService.class) {
// TestService testService = lookup.lookup(TestService.class);
// if (testService == null) {
// return false;
// }
// }
//
// return true;
// }
//
// private Injector() {
// }
// }
//
// Path: src/main/java/info/gianlucacosta/easypmd/pmdscanner/pmdcatalogs/LanguageVersionParser.java
// public interface LanguageVersionParser {
//
// LanguageVersion parse(String versionString);
// }
//
// Path: src/main/java/info/gianlucacosta/easypmd/pmdscanner/pmdcatalogs/StandardRuleSetsCatalog.java
// public interface StandardRuleSetsCatalog {
//
// boolean containsFileName(String ruleSetFileName);
//
// Collection<RuleSetWrapper> getRuleSetWrappers();
// }
// Path: src/main/java/info/gianlucacosta/easypmd/ide/options/DefaultOptionsFactory.java
import java.util.Arrays;
import java.util.List;
import java.util.logging.Logger;
import info.gianlucacosta.easypmd.system.SystemPropertiesService;
import info.gianlucacosta.easypmd.ide.Injector;
import info.gianlucacosta.easypmd.pmdscanner.pmdcatalogs.LanguageVersionParser;
import info.gianlucacosta.easypmd.pmdscanner.pmdcatalogs.StandardRuleSetsCatalog;
import info.gianlucacosta.helios.regex.OsSpecificPathCompositeRegex;
import net.sourceforge.pmd.RulePriority;
import org.openide.util.lookup.ServiceProvider;
import java.util.ArrayList;
/*
* ==========================================================================%%#
* EasyPmd
* ===========================================================================%%
* Copyright (C) 2009 - 2017 Gianluca Costa
* ===========================================================================%%
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public
* License along with this program. If not, see
* <http://www.gnu.org/licenses/gpl-3.0.html>.
* ==========================================================================%##
*/
package info.gianlucacosta.easypmd.ide.options;
/**
* Default implementation of OptionsFactory
*/
@ServiceProvider(service = OptionsFactory.class)
public class DefaultOptionsFactory implements OptionsFactory {
private static final Logger logger = Logger.getLogger(DefaultOptionsFactory.class.getName());
private static final String fallbackJavaLanguageVersion = "1.8";
| private final StandardRuleSetsCatalog standardRulesetsCatalog; |
giancosta86/EasyPmd | src/main/java/info/gianlucacosta/easypmd/ide/options/DefaultOptionsFactory.java | // Path: src/main/java/info/gianlucacosta/easypmd/system/SystemPropertiesService.java
// public interface SystemPropertiesService {
//
// String getJavaVersion();
//
// Path getUserHomeDirectory();
// }
//
// Path: src/main/java/info/gianlucacosta/easypmd/ide/Injector.java
// public class Injector {
//
// @ServiceProvider(service = TestService.class)
// public static class TestService {
// }
//
// private static final Lookup lookup = Lookup.getDefault();
//
// private static Lookup getLookup() {
// return lookup;
// }
//
// public static <T> T lookup(Class<T> serviceClass) {
// T result = getLookup().lookup(serviceClass);
//
// validateLookupResult(serviceClass, result);
//
// return result;
// }
//
// public static <T> Collection<? extends T> lookupAll(Class<T> serviceClass) {
// Collection<? extends T> result = getLookup().lookupAll(serviceClass);
//
// validateLookupResult(serviceClass, result);
//
// return result;
// }
//
// private static void validateLookupResult(Class<?> serviceClass, Object lookupResult) {
// if (lookupResult == null) {
// if (shouldThrowLookupExceptions(serviceClass)) {
// throw new IllegalArgumentException(String.format("Service '%s' not registered!", serviceClass.getSimpleName()));
// }
// }
// }
//
// //This code prevents exceptions in the visual form editors within NetBeans
// private static boolean shouldThrowLookupExceptions(Class<?> serviceClass) {
// if (serviceClass != TestService.class) {
// TestService testService = lookup.lookup(TestService.class);
// if (testService == null) {
// return false;
// }
// }
//
// return true;
// }
//
// private Injector() {
// }
// }
//
// Path: src/main/java/info/gianlucacosta/easypmd/pmdscanner/pmdcatalogs/LanguageVersionParser.java
// public interface LanguageVersionParser {
//
// LanguageVersion parse(String versionString);
// }
//
// Path: src/main/java/info/gianlucacosta/easypmd/pmdscanner/pmdcatalogs/StandardRuleSetsCatalog.java
// public interface StandardRuleSetsCatalog {
//
// boolean containsFileName(String ruleSetFileName);
//
// Collection<RuleSetWrapper> getRuleSetWrappers();
// }
| import java.util.Arrays;
import java.util.List;
import java.util.logging.Logger;
import info.gianlucacosta.easypmd.system.SystemPropertiesService;
import info.gianlucacosta.easypmd.ide.Injector;
import info.gianlucacosta.easypmd.pmdscanner.pmdcatalogs.LanguageVersionParser;
import info.gianlucacosta.easypmd.pmdscanner.pmdcatalogs.StandardRuleSetsCatalog;
import info.gianlucacosta.helios.regex.OsSpecificPathCompositeRegex;
import net.sourceforge.pmd.RulePriority;
import org.openide.util.lookup.ServiceProvider;
import java.util.ArrayList; | /*
* ==========================================================================%%#
* EasyPmd
* ===========================================================================%%
* Copyright (C) 2009 - 2017 Gianluca Costa
* ===========================================================================%%
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public
* License along with this program. If not, see
* <http://www.gnu.org/licenses/gpl-3.0.html>.
* ==========================================================================%##
*/
package info.gianlucacosta.easypmd.ide.options;
/**
* Default implementation of OptionsFactory
*/
@ServiceProvider(service = OptionsFactory.class)
public class DefaultOptionsFactory implements OptionsFactory {
private static final Logger logger = Logger.getLogger(DefaultOptionsFactory.class.getName());
private static final String fallbackJavaLanguageVersion = "1.8";
private final StandardRuleSetsCatalog standardRulesetsCatalog; | // Path: src/main/java/info/gianlucacosta/easypmd/system/SystemPropertiesService.java
// public interface SystemPropertiesService {
//
// String getJavaVersion();
//
// Path getUserHomeDirectory();
// }
//
// Path: src/main/java/info/gianlucacosta/easypmd/ide/Injector.java
// public class Injector {
//
// @ServiceProvider(service = TestService.class)
// public static class TestService {
// }
//
// private static final Lookup lookup = Lookup.getDefault();
//
// private static Lookup getLookup() {
// return lookup;
// }
//
// public static <T> T lookup(Class<T> serviceClass) {
// T result = getLookup().lookup(serviceClass);
//
// validateLookupResult(serviceClass, result);
//
// return result;
// }
//
// public static <T> Collection<? extends T> lookupAll(Class<T> serviceClass) {
// Collection<? extends T> result = getLookup().lookupAll(serviceClass);
//
// validateLookupResult(serviceClass, result);
//
// return result;
// }
//
// private static void validateLookupResult(Class<?> serviceClass, Object lookupResult) {
// if (lookupResult == null) {
// if (shouldThrowLookupExceptions(serviceClass)) {
// throw new IllegalArgumentException(String.format("Service '%s' not registered!", serviceClass.getSimpleName()));
// }
// }
// }
//
// //This code prevents exceptions in the visual form editors within NetBeans
// private static boolean shouldThrowLookupExceptions(Class<?> serviceClass) {
// if (serviceClass != TestService.class) {
// TestService testService = lookup.lookup(TestService.class);
// if (testService == null) {
// return false;
// }
// }
//
// return true;
// }
//
// private Injector() {
// }
// }
//
// Path: src/main/java/info/gianlucacosta/easypmd/pmdscanner/pmdcatalogs/LanguageVersionParser.java
// public interface LanguageVersionParser {
//
// LanguageVersion parse(String versionString);
// }
//
// Path: src/main/java/info/gianlucacosta/easypmd/pmdscanner/pmdcatalogs/StandardRuleSetsCatalog.java
// public interface StandardRuleSetsCatalog {
//
// boolean containsFileName(String ruleSetFileName);
//
// Collection<RuleSetWrapper> getRuleSetWrappers();
// }
// Path: src/main/java/info/gianlucacosta/easypmd/ide/options/DefaultOptionsFactory.java
import java.util.Arrays;
import java.util.List;
import java.util.logging.Logger;
import info.gianlucacosta.easypmd.system.SystemPropertiesService;
import info.gianlucacosta.easypmd.ide.Injector;
import info.gianlucacosta.easypmd.pmdscanner.pmdcatalogs.LanguageVersionParser;
import info.gianlucacosta.easypmd.pmdscanner.pmdcatalogs.StandardRuleSetsCatalog;
import info.gianlucacosta.helios.regex.OsSpecificPathCompositeRegex;
import net.sourceforge.pmd.RulePriority;
import org.openide.util.lookup.ServiceProvider;
import java.util.ArrayList;
/*
* ==========================================================================%%#
* EasyPmd
* ===========================================================================%%
* Copyright (C) 2009 - 2017 Gianluca Costa
* ===========================================================================%%
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public
* License along with this program. If not, see
* <http://www.gnu.org/licenses/gpl-3.0.html>.
* ==========================================================================%##
*/
package info.gianlucacosta.easypmd.ide.options;
/**
* Default implementation of OptionsFactory
*/
@ServiceProvider(service = OptionsFactory.class)
public class DefaultOptionsFactory implements OptionsFactory {
private static final Logger logger = Logger.getLogger(DefaultOptionsFactory.class.getName());
private static final String fallbackJavaLanguageVersion = "1.8";
private final StandardRuleSetsCatalog standardRulesetsCatalog; | private final SystemPropertiesService systemPropertiesService; |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.