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
sahildave/Gazetti_Newspaper_Reader
app/src/main/java/in/sahildave/gazetti/widget/jazzyviewpager/OutlineContainer.java
// Path: app/src/main/java/in/sahildave/gazetti/util/Util.java // public class Util { // // public static int dpToPx(Resources res, int dp) { // return (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dp, res.getDisplayMetrics()); // } // // }
import android.content.Context; import android.graphics.Canvas; import android.graphics.Paint; import android.graphics.Paint.Style; import android.graphics.Rect; import android.graphics.drawable.Animatable; import android.util.AttributeSet; import android.view.animation.AnimationUtils; import android.view.animation.Interpolator; import android.widget.FrameLayout; import in.sahildave.gazetti.R; import in.sahildave.gazetti.util.Util;
package in.sahildave.gazetti.widget.jazzyviewpager; public class OutlineContainer extends FrameLayout implements Animatable { private Paint mOutlinePaint; private boolean mIsRunning = false; private long mStartTime; private float mAlpha = 1.0f; private static final long ANIMATION_DURATION = 500; private static final long FRAME_DURATION = 1000 / 60; private final Interpolator mInterpolator = new Interpolator() { public float getInterpolation(float t) { t -= 1.0f; return t * t * t + 1.0f; } }; public OutlineContainer(Context context) { super(context); init(); } public OutlineContainer(Context context, AttributeSet attrs) { super(context, attrs); init(); } public OutlineContainer(Context context, AttributeSet attrs, int defStyle) { super(context, attrs, defStyle); init(); } private void init() { mOutlinePaint = new Paint(); mOutlinePaint.setAntiAlias(true);
// Path: app/src/main/java/in/sahildave/gazetti/util/Util.java // public class Util { // // public static int dpToPx(Resources res, int dp) { // return (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dp, res.getDisplayMetrics()); // } // // } // Path: app/src/main/java/in/sahildave/gazetti/widget/jazzyviewpager/OutlineContainer.java import android.content.Context; import android.graphics.Canvas; import android.graphics.Paint; import android.graphics.Paint.Style; import android.graphics.Rect; import android.graphics.drawable.Animatable; import android.util.AttributeSet; import android.view.animation.AnimationUtils; import android.view.animation.Interpolator; import android.widget.FrameLayout; import in.sahildave.gazetti.R; import in.sahildave.gazetti.util.Util; package in.sahildave.gazetti.widget.jazzyviewpager; public class OutlineContainer extends FrameLayout implements Animatable { private Paint mOutlinePaint; private boolean mIsRunning = false; private long mStartTime; private float mAlpha = 1.0f; private static final long ANIMATION_DURATION = 500; private static final long FRAME_DURATION = 1000 / 60; private final Interpolator mInterpolator = new Interpolator() { public float getInterpolation(float t) { t -= 1.0f; return t * t * t + 1.0f; } }; public OutlineContainer(Context context) { super(context); init(); } public OutlineContainer(Context context, AttributeSet attrs) { super(context, attrs); init(); } public OutlineContainer(Context context, AttributeSet attrs, int defStyle) { super(context, attrs, defStyle); init(); } private void init() { mOutlinePaint = new Paint(); mOutlinePaint.setAntiAlias(true);
mOutlinePaint.setStrokeWidth(Util.dpToPx(getResources(), 2));
sahildave/Gazetti_Newspaper_Reader
app/src/main/java/in/sahildave/gazetti/welcomescreen/WelcomeScreenFragmentExpList.java
// Path: app/src/main/java/in/sahildave/gazetti/welcomescreen/WelcomeScreenExpListAdapter.java // public interface CheckBoxInterface { // void checkBoxClicked(boolean isChecked); // }
import android.app.Activity; import android.os.Bundle; import android.support.v4.app.Fragment; import android.view.LayoutInflater; import android.view.View; import android.view.View.OnClickListener; import android.view.ViewGroup; import android.widget.Button; import android.widget.ExpandableListView; import android.widget.ExpandableListView.OnGroupClickListener; import android.widget.LinearLayout; import android.widget.LinearLayout.LayoutParams; import in.sahildave.gazetti.R; import in.sahildave.gazetti.welcomescreen.WelcomeScreenExpListAdapter.CheckBoxInterface; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map;
}); prepareListData(); expListAdapter = new WelcomeScreenExpListAdapter(getActivity(), listDataHeader, listDataChild, checkBoxInterface); expListAdapter.setExpList(expListView); expListView.setAdapter(expListAdapter); expListView.setOnGroupClickListener(new OnGroupClickListener() { @Override public boolean onGroupClick(ExpandableListView parent, View v, int groupPosition, long id) { // Log.d(LOG_TAG, "Top Layer Hidden ? " + topLayerHidden); if (topLayer.getVisibility()==View.VISIBLE) { LayoutParams originalParams = (LayoutParams) bottomLayer.getLayoutParams(); originalBottomMargin = originalParams.bottomMargin; LayoutParams params = new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT); params.setMargins(0, 0, 0, 0); bottomLayer.setLayoutParams(params); topLayer.setVisibility(View.GONE); topLayerHidden = true; } return false; } }); return rootView; }
// Path: app/src/main/java/in/sahildave/gazetti/welcomescreen/WelcomeScreenExpListAdapter.java // public interface CheckBoxInterface { // void checkBoxClicked(boolean isChecked); // } // Path: app/src/main/java/in/sahildave/gazetti/welcomescreen/WelcomeScreenFragmentExpList.java import android.app.Activity; import android.os.Bundle; import android.support.v4.app.Fragment; import android.view.LayoutInflater; import android.view.View; import android.view.View.OnClickListener; import android.view.ViewGroup; import android.widget.Button; import android.widget.ExpandableListView; import android.widget.ExpandableListView.OnGroupClickListener; import android.widget.LinearLayout; import android.widget.LinearLayout.LayoutParams; import in.sahildave.gazetti.R; import in.sahildave.gazetti.welcomescreen.WelcomeScreenExpListAdapter.CheckBoxInterface; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; }); prepareListData(); expListAdapter = new WelcomeScreenExpListAdapter(getActivity(), listDataHeader, listDataChild, checkBoxInterface); expListAdapter.setExpList(expListView); expListView.setAdapter(expListAdapter); expListView.setOnGroupClickListener(new OnGroupClickListener() { @Override public boolean onGroupClick(ExpandableListView parent, View v, int groupPosition, long id) { // Log.d(LOG_TAG, "Top Layer Hidden ? " + topLayerHidden); if (topLayer.getVisibility()==View.VISIBLE) { LayoutParams originalParams = (LayoutParams) bottomLayer.getLayoutParams(); originalBottomMargin = originalParams.bottomMargin; LayoutParams params = new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT); params.setMargins(0, 0, 0, 0); bottomLayer.setLayoutParams(params); topLayer.setVisibility(View.GONE); topLayerHidden = true; } return false; } }); return rootView; }
CheckBoxInterface checkBoxInterface = new CheckBoxInterface() {
sahildave/Gazetti_Newspaper_Reader
app/src/main/java/in/sahildave/gazetti/homescreen/adapter/NewsCatModel.java
// Path: app/src/main/java/in/sahildave/gazetti/util/GazettiEnums.java // public enum Category { // NATIONAL ("National", "1"), // INTERNATIONAL ("International", "2"), // SPORTS ("Sports", "3"), // SCIENCE ("Science", "4"), // BUSINESS ("Business", "6"), // OPINION_BLOG_EDITORIAL("Blogs and Editorials", "7"), // ENTERTAINMENT ("Entertainment", "5"), // ADD_NEW("Add New", "-1"); // // private final String categoryTitle; // private final String categoryId; // // Category(String categoryTitle, String catId) { // this.categoryTitle = categoryTitle; // this.categoryId = catId; // } // // public String getTitle() { // return categoryTitle; // } // // public String getCategoryId() { // return categoryId; // } // } // // Path: app/src/main/java/in/sahildave/gazetti/util/GazettiEnums.java // public enum Newspapers { // THE_HINDU ("The Hindu", "th", "0", "hindu_data"), // TOI ("The Times of India", "toi", "1", "toi_data"), // FIRST_POST ("First Post", "fp", "2", "fp_data"), // INDIAN_EXP ("The Indian Express", "tie", "3", "tie_data"), // ADD_NEW ("Add New", "add_new", "-1", "null"); // // private final String newspaperTitle; // private final String newspaperImage; // private final String newspaperId; // private final String dbToSearch; // // Newspapers(String newspaperTitle, String newspaperImage, String npId, String dbToSearch) { // this.newspaperTitle = newspaperTitle; // this.newspaperImage = newspaperImage; // this.newspaperId = npId; // this.dbToSearch = dbToSearch; // } // // public String getTitle() { // return newspaperTitle; // } // // public String getNewspaperImage() { // return newspaperImage; // } // // public String getNewspaperId() { // return newspaperId; // } // }
import in.sahildave.gazetti.util.GazettiEnums.Category; import in.sahildave.gazetti.util.GazettiEnums.Newspapers;
package in.sahildave.gazetti.homescreen.adapter; public class NewsCatModel { String newspaperId; String newspaperTitle; String categoryId; String categoryTitle; String newspaperImage;
// Path: app/src/main/java/in/sahildave/gazetti/util/GazettiEnums.java // public enum Category { // NATIONAL ("National", "1"), // INTERNATIONAL ("International", "2"), // SPORTS ("Sports", "3"), // SCIENCE ("Science", "4"), // BUSINESS ("Business", "6"), // OPINION_BLOG_EDITORIAL("Blogs and Editorials", "7"), // ENTERTAINMENT ("Entertainment", "5"), // ADD_NEW("Add New", "-1"); // // private final String categoryTitle; // private final String categoryId; // // Category(String categoryTitle, String catId) { // this.categoryTitle = categoryTitle; // this.categoryId = catId; // } // // public String getTitle() { // return categoryTitle; // } // // public String getCategoryId() { // return categoryId; // } // } // // Path: app/src/main/java/in/sahildave/gazetti/util/GazettiEnums.java // public enum Newspapers { // THE_HINDU ("The Hindu", "th", "0", "hindu_data"), // TOI ("The Times of India", "toi", "1", "toi_data"), // FIRST_POST ("First Post", "fp", "2", "fp_data"), // INDIAN_EXP ("The Indian Express", "tie", "3", "tie_data"), // ADD_NEW ("Add New", "add_new", "-1", "null"); // // private final String newspaperTitle; // private final String newspaperImage; // private final String newspaperId; // private final String dbToSearch; // // Newspapers(String newspaperTitle, String newspaperImage, String npId, String dbToSearch) { // this.newspaperTitle = newspaperTitle; // this.newspaperImage = newspaperImage; // this.newspaperId = npId; // this.dbToSearch = dbToSearch; // } // // public String getTitle() { // return newspaperTitle; // } // // public String getNewspaperImage() { // return newspaperImage; // } // // public String getNewspaperId() { // return newspaperId; // } // } // Path: app/src/main/java/in/sahildave/gazetti/homescreen/adapter/NewsCatModel.java import in.sahildave.gazetti.util.GazettiEnums.Category; import in.sahildave.gazetti.util.GazettiEnums.Newspapers; package in.sahildave.gazetti.homescreen.adapter; public class NewsCatModel { String newspaperId; String newspaperTitle; String categoryId; String categoryTitle; String newspaperImage;
public NewsCatModel(Newspapers newspaper, Category category){
sahildave/Gazetti_Newspaper_Reader
app/src/main/java/in/sahildave/gazetti/homescreen/adapter/NewsCatModel.java
// Path: app/src/main/java/in/sahildave/gazetti/util/GazettiEnums.java // public enum Category { // NATIONAL ("National", "1"), // INTERNATIONAL ("International", "2"), // SPORTS ("Sports", "3"), // SCIENCE ("Science", "4"), // BUSINESS ("Business", "6"), // OPINION_BLOG_EDITORIAL("Blogs and Editorials", "7"), // ENTERTAINMENT ("Entertainment", "5"), // ADD_NEW("Add New", "-1"); // // private final String categoryTitle; // private final String categoryId; // // Category(String categoryTitle, String catId) { // this.categoryTitle = categoryTitle; // this.categoryId = catId; // } // // public String getTitle() { // return categoryTitle; // } // // public String getCategoryId() { // return categoryId; // } // } // // Path: app/src/main/java/in/sahildave/gazetti/util/GazettiEnums.java // public enum Newspapers { // THE_HINDU ("The Hindu", "th", "0", "hindu_data"), // TOI ("The Times of India", "toi", "1", "toi_data"), // FIRST_POST ("First Post", "fp", "2", "fp_data"), // INDIAN_EXP ("The Indian Express", "tie", "3", "tie_data"), // ADD_NEW ("Add New", "add_new", "-1", "null"); // // private final String newspaperTitle; // private final String newspaperImage; // private final String newspaperId; // private final String dbToSearch; // // Newspapers(String newspaperTitle, String newspaperImage, String npId, String dbToSearch) { // this.newspaperTitle = newspaperTitle; // this.newspaperImage = newspaperImage; // this.newspaperId = npId; // this.dbToSearch = dbToSearch; // } // // public String getTitle() { // return newspaperTitle; // } // // public String getNewspaperImage() { // return newspaperImage; // } // // public String getNewspaperId() { // return newspaperId; // } // }
import in.sahildave.gazetti.util.GazettiEnums.Category; import in.sahildave.gazetti.util.GazettiEnums.Newspapers;
package in.sahildave.gazetti.homescreen.adapter; public class NewsCatModel { String newspaperId; String newspaperTitle; String categoryId; String categoryTitle; String newspaperImage;
// Path: app/src/main/java/in/sahildave/gazetti/util/GazettiEnums.java // public enum Category { // NATIONAL ("National", "1"), // INTERNATIONAL ("International", "2"), // SPORTS ("Sports", "3"), // SCIENCE ("Science", "4"), // BUSINESS ("Business", "6"), // OPINION_BLOG_EDITORIAL("Blogs and Editorials", "7"), // ENTERTAINMENT ("Entertainment", "5"), // ADD_NEW("Add New", "-1"); // // private final String categoryTitle; // private final String categoryId; // // Category(String categoryTitle, String catId) { // this.categoryTitle = categoryTitle; // this.categoryId = catId; // } // // public String getTitle() { // return categoryTitle; // } // // public String getCategoryId() { // return categoryId; // } // } // // Path: app/src/main/java/in/sahildave/gazetti/util/GazettiEnums.java // public enum Newspapers { // THE_HINDU ("The Hindu", "th", "0", "hindu_data"), // TOI ("The Times of India", "toi", "1", "toi_data"), // FIRST_POST ("First Post", "fp", "2", "fp_data"), // INDIAN_EXP ("The Indian Express", "tie", "3", "tie_data"), // ADD_NEW ("Add New", "add_new", "-1", "null"); // // private final String newspaperTitle; // private final String newspaperImage; // private final String newspaperId; // private final String dbToSearch; // // Newspapers(String newspaperTitle, String newspaperImage, String npId, String dbToSearch) { // this.newspaperTitle = newspaperTitle; // this.newspaperImage = newspaperImage; // this.newspaperId = npId; // this.dbToSearch = dbToSearch; // } // // public String getTitle() { // return newspaperTitle; // } // // public String getNewspaperImage() { // return newspaperImage; // } // // public String getNewspaperId() { // return newspaperId; // } // } // Path: app/src/main/java/in/sahildave/gazetti/homescreen/adapter/NewsCatModel.java import in.sahildave.gazetti.util.GazettiEnums.Category; import in.sahildave.gazetti.util.GazettiEnums.Newspapers; package in.sahildave.gazetti.homescreen.adapter; public class NewsCatModel { String newspaperId; String newspaperTitle; String categoryId; String categoryTitle; String newspaperImage;
public NewsCatModel(Newspapers newspaper, Category category){
sahildave/Gazetti_Newspaper_Reader
app/src/main/java/in/sahildave/gazetti/util/UserPrefUtil.java
// Path: app/src/main/java/in/sahildave/gazetti/homescreen/adapter/CellModel.java // public class CellModel { // // private String newspaperImage; // private String newspaperTitle; // private String newspaperId; // private String categoryTitle; // private String categoryId; // // public CellModel(Newspapers newspapers, Category category) { // setNewspaperImage(newspapers.getNewspaperImage()); // setNewspaperTitle(newspapers.getTitle()); // setNewspaperId(newspapers.getNewspaperId()); // // setCategoryTitle(category.getTitle()); // setCategoryId(category.getCategoryId()); // } // // public CellModel (NewsCatModel newsCatModel) { // setNewspaperImage(newsCatModel.getNewspaperImage()); // setNewspaperTitle(newsCatModel.getNewspaperTitle()); // setNewspaperId(newsCatModel.getNewspaperId()); // // setCategoryTitle(newsCatModel.getCategoryTitle()); // setCategoryId(newsCatModel.getCategoryId()); // } // // public String getNewspaperImage() { // return newspaperImage; // } // // public void setNewspaperImage(String newspaperImage) { // this.newspaperImage = newspaperImage; // } // // public String getCategoryTitle() { // return categoryTitle; // } // // public void setCategoryTitle(String categoryTitle) { // this.categoryTitle = categoryTitle; // } // // public String getNewspaperTitle() { // return newspaperTitle; // } // // public void setNewspaperTitle(String newspaperTitle) { // this.newspaperTitle = newspaperTitle; // } // // public String getNewspaperId() { // return newspaperId; // } // // public void setNewspaperId(String newspaperId) { // this.newspaperId = newspaperId; // } // // public String getCategoryId() { // return categoryId; // } // // public void setCategoryId(String categoryId) { // this.categoryId = categoryId; // } // // @Override // public String toString() { // return getNewspaperId()+"-"+getNewspaperTitle()+", "+getCategoryId()+"-"+getCategoryTitle(); // } // // } // // Path: app/src/main/java/in/sahildave/gazetti/util/GazettiEnums.java // public enum Category { // NATIONAL ("National", "1"), // INTERNATIONAL ("International", "2"), // SPORTS ("Sports", "3"), // SCIENCE ("Science", "4"), // BUSINESS ("Business", "6"), // OPINION_BLOG_EDITORIAL("Blogs and Editorials", "7"), // ENTERTAINMENT ("Entertainment", "5"), // ADD_NEW("Add New", "-1"); // // private final String categoryTitle; // private final String categoryId; // // Category(String categoryTitle, String catId) { // this.categoryTitle = categoryTitle; // this.categoryId = catId; // } // // public String getTitle() { // return categoryTitle; // } // // public String getCategoryId() { // return categoryId; // } // } // // Path: app/src/main/java/in/sahildave/gazetti/util/GazettiEnums.java // public enum Newspapers { // THE_HINDU ("The Hindu", "th", "0", "hindu_data"), // TOI ("The Times of India", "toi", "1", "toi_data"), // FIRST_POST ("First Post", "fp", "2", "fp_data"), // INDIAN_EXP ("The Indian Express", "tie", "3", "tie_data"), // ADD_NEW ("Add New", "add_new", "-1", "null"); // // private final String newspaperTitle; // private final String newspaperImage; // private final String newspaperId; // private final String dbToSearch; // // Newspapers(String newspaperTitle, String newspaperImage, String npId, String dbToSearch) { // this.newspaperTitle = newspaperTitle; // this.newspaperImage = newspaperImage; // this.newspaperId = npId; // this.dbToSearch = dbToSearch; // } // // public String getTitle() { // return newspaperTitle; // } // // public String getNewspaperImage() { // return newspaperImage; // } // // public String getNewspaperId() { // return newspaperId; // } // }
import android.content.Context; import in.sahildave.gazetti.homescreen.adapter.CellModel; import in.sahildave.gazetti.util.GazettiEnums.Category; import in.sahildave.gazetti.util.GazettiEnums.Newspapers; import java.util.ArrayList; import java.util.List; import java.util.Map;
package in.sahildave.gazetti.util; /** * Created by sahil on 9/11/14. */ public class UserPrefUtil { private static final String LOG_TAG = UserPrefUtil.class.getName(); private static UserPrefUtil _instance = null; private Context context; public static synchronized UserPrefUtil getInstance(Context context){ if (_instance == null) { _instance = new UserPrefUtil(context.getApplicationContext()); } return _instance; } private UserPrefUtil(Context parentContext) { context = parentContext; }
// Path: app/src/main/java/in/sahildave/gazetti/homescreen/adapter/CellModel.java // public class CellModel { // // private String newspaperImage; // private String newspaperTitle; // private String newspaperId; // private String categoryTitle; // private String categoryId; // // public CellModel(Newspapers newspapers, Category category) { // setNewspaperImage(newspapers.getNewspaperImage()); // setNewspaperTitle(newspapers.getTitle()); // setNewspaperId(newspapers.getNewspaperId()); // // setCategoryTitle(category.getTitle()); // setCategoryId(category.getCategoryId()); // } // // public CellModel (NewsCatModel newsCatModel) { // setNewspaperImage(newsCatModel.getNewspaperImage()); // setNewspaperTitle(newsCatModel.getNewspaperTitle()); // setNewspaperId(newsCatModel.getNewspaperId()); // // setCategoryTitle(newsCatModel.getCategoryTitle()); // setCategoryId(newsCatModel.getCategoryId()); // } // // public String getNewspaperImage() { // return newspaperImage; // } // // public void setNewspaperImage(String newspaperImage) { // this.newspaperImage = newspaperImage; // } // // public String getCategoryTitle() { // return categoryTitle; // } // // public void setCategoryTitle(String categoryTitle) { // this.categoryTitle = categoryTitle; // } // // public String getNewspaperTitle() { // return newspaperTitle; // } // // public void setNewspaperTitle(String newspaperTitle) { // this.newspaperTitle = newspaperTitle; // } // // public String getNewspaperId() { // return newspaperId; // } // // public void setNewspaperId(String newspaperId) { // this.newspaperId = newspaperId; // } // // public String getCategoryId() { // return categoryId; // } // // public void setCategoryId(String categoryId) { // this.categoryId = categoryId; // } // // @Override // public String toString() { // return getNewspaperId()+"-"+getNewspaperTitle()+", "+getCategoryId()+"-"+getCategoryTitle(); // } // // } // // Path: app/src/main/java/in/sahildave/gazetti/util/GazettiEnums.java // public enum Category { // NATIONAL ("National", "1"), // INTERNATIONAL ("International", "2"), // SPORTS ("Sports", "3"), // SCIENCE ("Science", "4"), // BUSINESS ("Business", "6"), // OPINION_BLOG_EDITORIAL("Blogs and Editorials", "7"), // ENTERTAINMENT ("Entertainment", "5"), // ADD_NEW("Add New", "-1"); // // private final String categoryTitle; // private final String categoryId; // // Category(String categoryTitle, String catId) { // this.categoryTitle = categoryTitle; // this.categoryId = catId; // } // // public String getTitle() { // return categoryTitle; // } // // public String getCategoryId() { // return categoryId; // } // } // // Path: app/src/main/java/in/sahildave/gazetti/util/GazettiEnums.java // public enum Newspapers { // THE_HINDU ("The Hindu", "th", "0", "hindu_data"), // TOI ("The Times of India", "toi", "1", "toi_data"), // FIRST_POST ("First Post", "fp", "2", "fp_data"), // INDIAN_EXP ("The Indian Express", "tie", "3", "tie_data"), // ADD_NEW ("Add New", "add_new", "-1", "null"); // // private final String newspaperTitle; // private final String newspaperImage; // private final String newspaperId; // private final String dbToSearch; // // Newspapers(String newspaperTitle, String newspaperImage, String npId, String dbToSearch) { // this.newspaperTitle = newspaperTitle; // this.newspaperImage = newspaperImage; // this.newspaperId = npId; // this.dbToSearch = dbToSearch; // } // // public String getTitle() { // return newspaperTitle; // } // // public String getNewspaperImage() { // return newspaperImage; // } // // public String getNewspaperId() { // return newspaperId; // } // } // Path: app/src/main/java/in/sahildave/gazetti/util/UserPrefUtil.java import android.content.Context; import in.sahildave.gazetti.homescreen.adapter.CellModel; import in.sahildave.gazetti.util.GazettiEnums.Category; import in.sahildave.gazetti.util.GazettiEnums.Newspapers; import java.util.ArrayList; import java.util.List; import java.util.Map; package in.sahildave.gazetti.util; /** * Created by sahil on 9/11/14. */ public class UserPrefUtil { private static final String LOG_TAG = UserPrefUtil.class.getName(); private static UserPrefUtil _instance = null; private Context context; public static synchronized UserPrefUtil getInstance(Context context){ if (_instance == null) { _instance = new UserPrefUtil(context.getApplicationContext()); } return _instance; } private UserPrefUtil(Context parentContext) { context = parentContext; }
public List<CellModel> getUserPrefCellList(){
sahildave/Gazetti_Newspaper_Reader
app/src/main/java/in/sahildave/gazetti/util/UserPrefUtil.java
// Path: app/src/main/java/in/sahildave/gazetti/homescreen/adapter/CellModel.java // public class CellModel { // // private String newspaperImage; // private String newspaperTitle; // private String newspaperId; // private String categoryTitle; // private String categoryId; // // public CellModel(Newspapers newspapers, Category category) { // setNewspaperImage(newspapers.getNewspaperImage()); // setNewspaperTitle(newspapers.getTitle()); // setNewspaperId(newspapers.getNewspaperId()); // // setCategoryTitle(category.getTitle()); // setCategoryId(category.getCategoryId()); // } // // public CellModel (NewsCatModel newsCatModel) { // setNewspaperImage(newsCatModel.getNewspaperImage()); // setNewspaperTitle(newsCatModel.getNewspaperTitle()); // setNewspaperId(newsCatModel.getNewspaperId()); // // setCategoryTitle(newsCatModel.getCategoryTitle()); // setCategoryId(newsCatModel.getCategoryId()); // } // // public String getNewspaperImage() { // return newspaperImage; // } // // public void setNewspaperImage(String newspaperImage) { // this.newspaperImage = newspaperImage; // } // // public String getCategoryTitle() { // return categoryTitle; // } // // public void setCategoryTitle(String categoryTitle) { // this.categoryTitle = categoryTitle; // } // // public String getNewspaperTitle() { // return newspaperTitle; // } // // public void setNewspaperTitle(String newspaperTitle) { // this.newspaperTitle = newspaperTitle; // } // // public String getNewspaperId() { // return newspaperId; // } // // public void setNewspaperId(String newspaperId) { // this.newspaperId = newspaperId; // } // // public String getCategoryId() { // return categoryId; // } // // public void setCategoryId(String categoryId) { // this.categoryId = categoryId; // } // // @Override // public String toString() { // return getNewspaperId()+"-"+getNewspaperTitle()+", "+getCategoryId()+"-"+getCategoryTitle(); // } // // } // // Path: app/src/main/java/in/sahildave/gazetti/util/GazettiEnums.java // public enum Category { // NATIONAL ("National", "1"), // INTERNATIONAL ("International", "2"), // SPORTS ("Sports", "3"), // SCIENCE ("Science", "4"), // BUSINESS ("Business", "6"), // OPINION_BLOG_EDITORIAL("Blogs and Editorials", "7"), // ENTERTAINMENT ("Entertainment", "5"), // ADD_NEW("Add New", "-1"); // // private final String categoryTitle; // private final String categoryId; // // Category(String categoryTitle, String catId) { // this.categoryTitle = categoryTitle; // this.categoryId = catId; // } // // public String getTitle() { // return categoryTitle; // } // // public String getCategoryId() { // return categoryId; // } // } // // Path: app/src/main/java/in/sahildave/gazetti/util/GazettiEnums.java // public enum Newspapers { // THE_HINDU ("The Hindu", "th", "0", "hindu_data"), // TOI ("The Times of India", "toi", "1", "toi_data"), // FIRST_POST ("First Post", "fp", "2", "fp_data"), // INDIAN_EXP ("The Indian Express", "tie", "3", "tie_data"), // ADD_NEW ("Add New", "add_new", "-1", "null"); // // private final String newspaperTitle; // private final String newspaperImage; // private final String newspaperId; // private final String dbToSearch; // // Newspapers(String newspaperTitle, String newspaperImage, String npId, String dbToSearch) { // this.newspaperTitle = newspaperTitle; // this.newspaperImage = newspaperImage; // this.newspaperId = npId; // this.dbToSearch = dbToSearch; // } // // public String getTitle() { // return newspaperTitle; // } // // public String getNewspaperImage() { // return newspaperImage; // } // // public String getNewspaperId() { // return newspaperId; // } // }
import android.content.Context; import in.sahildave.gazetti.homescreen.adapter.CellModel; import in.sahildave.gazetti.util.GazettiEnums.Category; import in.sahildave.gazetti.util.GazettiEnums.Newspapers; import java.util.ArrayList; import java.util.List; import java.util.Map;
package in.sahildave.gazetti.util; /** * Created by sahil on 9/11/14. */ public class UserPrefUtil { private static final String LOG_TAG = UserPrefUtil.class.getName(); private static UserPrefUtil _instance = null; private Context context; public static synchronized UserPrefUtil getInstance(Context context){ if (_instance == null) { _instance = new UserPrefUtil(context.getApplicationContext()); } return _instance; } private UserPrefUtil(Context parentContext) { context = parentContext; } public List<CellModel> getUserPrefCellList(){ List<CellModel> returnList = new ArrayList<CellModel>(); Map<String, List<String>> userPrefMap = NewsCatFileUtil.getInstance(context).getUserSelectionMap(); GazettiEnums gazettiEnums = new GazettiEnums(); for (String newspaper : userPrefMap.keySet()) { List<String> categoriesSelected = userPrefMap.get(newspaper);
// Path: app/src/main/java/in/sahildave/gazetti/homescreen/adapter/CellModel.java // public class CellModel { // // private String newspaperImage; // private String newspaperTitle; // private String newspaperId; // private String categoryTitle; // private String categoryId; // // public CellModel(Newspapers newspapers, Category category) { // setNewspaperImage(newspapers.getNewspaperImage()); // setNewspaperTitle(newspapers.getTitle()); // setNewspaperId(newspapers.getNewspaperId()); // // setCategoryTitle(category.getTitle()); // setCategoryId(category.getCategoryId()); // } // // public CellModel (NewsCatModel newsCatModel) { // setNewspaperImage(newsCatModel.getNewspaperImage()); // setNewspaperTitle(newsCatModel.getNewspaperTitle()); // setNewspaperId(newsCatModel.getNewspaperId()); // // setCategoryTitle(newsCatModel.getCategoryTitle()); // setCategoryId(newsCatModel.getCategoryId()); // } // // public String getNewspaperImage() { // return newspaperImage; // } // // public void setNewspaperImage(String newspaperImage) { // this.newspaperImage = newspaperImage; // } // // public String getCategoryTitle() { // return categoryTitle; // } // // public void setCategoryTitle(String categoryTitle) { // this.categoryTitle = categoryTitle; // } // // public String getNewspaperTitle() { // return newspaperTitle; // } // // public void setNewspaperTitle(String newspaperTitle) { // this.newspaperTitle = newspaperTitle; // } // // public String getNewspaperId() { // return newspaperId; // } // // public void setNewspaperId(String newspaperId) { // this.newspaperId = newspaperId; // } // // public String getCategoryId() { // return categoryId; // } // // public void setCategoryId(String categoryId) { // this.categoryId = categoryId; // } // // @Override // public String toString() { // return getNewspaperId()+"-"+getNewspaperTitle()+", "+getCategoryId()+"-"+getCategoryTitle(); // } // // } // // Path: app/src/main/java/in/sahildave/gazetti/util/GazettiEnums.java // public enum Category { // NATIONAL ("National", "1"), // INTERNATIONAL ("International", "2"), // SPORTS ("Sports", "3"), // SCIENCE ("Science", "4"), // BUSINESS ("Business", "6"), // OPINION_BLOG_EDITORIAL("Blogs and Editorials", "7"), // ENTERTAINMENT ("Entertainment", "5"), // ADD_NEW("Add New", "-1"); // // private final String categoryTitle; // private final String categoryId; // // Category(String categoryTitle, String catId) { // this.categoryTitle = categoryTitle; // this.categoryId = catId; // } // // public String getTitle() { // return categoryTitle; // } // // public String getCategoryId() { // return categoryId; // } // } // // Path: app/src/main/java/in/sahildave/gazetti/util/GazettiEnums.java // public enum Newspapers { // THE_HINDU ("The Hindu", "th", "0", "hindu_data"), // TOI ("The Times of India", "toi", "1", "toi_data"), // FIRST_POST ("First Post", "fp", "2", "fp_data"), // INDIAN_EXP ("The Indian Express", "tie", "3", "tie_data"), // ADD_NEW ("Add New", "add_new", "-1", "null"); // // private final String newspaperTitle; // private final String newspaperImage; // private final String newspaperId; // private final String dbToSearch; // // Newspapers(String newspaperTitle, String newspaperImage, String npId, String dbToSearch) { // this.newspaperTitle = newspaperTitle; // this.newspaperImage = newspaperImage; // this.newspaperId = npId; // this.dbToSearch = dbToSearch; // } // // public String getTitle() { // return newspaperTitle; // } // // public String getNewspaperImage() { // return newspaperImage; // } // // public String getNewspaperId() { // return newspaperId; // } // } // Path: app/src/main/java/in/sahildave/gazetti/util/UserPrefUtil.java import android.content.Context; import in.sahildave.gazetti.homescreen.adapter.CellModel; import in.sahildave.gazetti.util.GazettiEnums.Category; import in.sahildave.gazetti.util.GazettiEnums.Newspapers; import java.util.ArrayList; import java.util.List; import java.util.Map; package in.sahildave.gazetti.util; /** * Created by sahil on 9/11/14. */ public class UserPrefUtil { private static final String LOG_TAG = UserPrefUtil.class.getName(); private static UserPrefUtil _instance = null; private Context context; public static synchronized UserPrefUtil getInstance(Context context){ if (_instance == null) { _instance = new UserPrefUtil(context.getApplicationContext()); } return _instance; } private UserPrefUtil(Context parentContext) { context = parentContext; } public List<CellModel> getUserPrefCellList(){ List<CellModel> returnList = new ArrayList<CellModel>(); Map<String, List<String>> userPrefMap = NewsCatFileUtil.getInstance(context).getUserSelectionMap(); GazettiEnums gazettiEnums = new GazettiEnums(); for (String newspaper : userPrefMap.keySet()) { List<String> categoriesSelected = userPrefMap.get(newspaper);
Newspapers npEnum = gazettiEnums.getNewspaperFromName(newspaper);
sahildave/Gazetti_Newspaper_Reader
app/src/main/java/in/sahildave/gazetti/util/UserPrefUtil.java
// Path: app/src/main/java/in/sahildave/gazetti/homescreen/adapter/CellModel.java // public class CellModel { // // private String newspaperImage; // private String newspaperTitle; // private String newspaperId; // private String categoryTitle; // private String categoryId; // // public CellModel(Newspapers newspapers, Category category) { // setNewspaperImage(newspapers.getNewspaperImage()); // setNewspaperTitle(newspapers.getTitle()); // setNewspaperId(newspapers.getNewspaperId()); // // setCategoryTitle(category.getTitle()); // setCategoryId(category.getCategoryId()); // } // // public CellModel (NewsCatModel newsCatModel) { // setNewspaperImage(newsCatModel.getNewspaperImage()); // setNewspaperTitle(newsCatModel.getNewspaperTitle()); // setNewspaperId(newsCatModel.getNewspaperId()); // // setCategoryTitle(newsCatModel.getCategoryTitle()); // setCategoryId(newsCatModel.getCategoryId()); // } // // public String getNewspaperImage() { // return newspaperImage; // } // // public void setNewspaperImage(String newspaperImage) { // this.newspaperImage = newspaperImage; // } // // public String getCategoryTitle() { // return categoryTitle; // } // // public void setCategoryTitle(String categoryTitle) { // this.categoryTitle = categoryTitle; // } // // public String getNewspaperTitle() { // return newspaperTitle; // } // // public void setNewspaperTitle(String newspaperTitle) { // this.newspaperTitle = newspaperTitle; // } // // public String getNewspaperId() { // return newspaperId; // } // // public void setNewspaperId(String newspaperId) { // this.newspaperId = newspaperId; // } // // public String getCategoryId() { // return categoryId; // } // // public void setCategoryId(String categoryId) { // this.categoryId = categoryId; // } // // @Override // public String toString() { // return getNewspaperId()+"-"+getNewspaperTitle()+", "+getCategoryId()+"-"+getCategoryTitle(); // } // // } // // Path: app/src/main/java/in/sahildave/gazetti/util/GazettiEnums.java // public enum Category { // NATIONAL ("National", "1"), // INTERNATIONAL ("International", "2"), // SPORTS ("Sports", "3"), // SCIENCE ("Science", "4"), // BUSINESS ("Business", "6"), // OPINION_BLOG_EDITORIAL("Blogs and Editorials", "7"), // ENTERTAINMENT ("Entertainment", "5"), // ADD_NEW("Add New", "-1"); // // private final String categoryTitle; // private final String categoryId; // // Category(String categoryTitle, String catId) { // this.categoryTitle = categoryTitle; // this.categoryId = catId; // } // // public String getTitle() { // return categoryTitle; // } // // public String getCategoryId() { // return categoryId; // } // } // // Path: app/src/main/java/in/sahildave/gazetti/util/GazettiEnums.java // public enum Newspapers { // THE_HINDU ("The Hindu", "th", "0", "hindu_data"), // TOI ("The Times of India", "toi", "1", "toi_data"), // FIRST_POST ("First Post", "fp", "2", "fp_data"), // INDIAN_EXP ("The Indian Express", "tie", "3", "tie_data"), // ADD_NEW ("Add New", "add_new", "-1", "null"); // // private final String newspaperTitle; // private final String newspaperImage; // private final String newspaperId; // private final String dbToSearch; // // Newspapers(String newspaperTitle, String newspaperImage, String npId, String dbToSearch) { // this.newspaperTitle = newspaperTitle; // this.newspaperImage = newspaperImage; // this.newspaperId = npId; // this.dbToSearch = dbToSearch; // } // // public String getTitle() { // return newspaperTitle; // } // // public String getNewspaperImage() { // return newspaperImage; // } // // public String getNewspaperId() { // return newspaperId; // } // }
import android.content.Context; import in.sahildave.gazetti.homescreen.adapter.CellModel; import in.sahildave.gazetti.util.GazettiEnums.Category; import in.sahildave.gazetti.util.GazettiEnums.Newspapers; import java.util.ArrayList; import java.util.List; import java.util.Map;
package in.sahildave.gazetti.util; /** * Created by sahil on 9/11/14. */ public class UserPrefUtil { private static final String LOG_TAG = UserPrefUtil.class.getName(); private static UserPrefUtil _instance = null; private Context context; public static synchronized UserPrefUtil getInstance(Context context){ if (_instance == null) { _instance = new UserPrefUtil(context.getApplicationContext()); } return _instance; } private UserPrefUtil(Context parentContext) { context = parentContext; } public List<CellModel> getUserPrefCellList(){ List<CellModel> returnList = new ArrayList<CellModel>(); Map<String, List<String>> userPrefMap = NewsCatFileUtil.getInstance(context).getUserSelectionMap(); GazettiEnums gazettiEnums = new GazettiEnums(); for (String newspaper : userPrefMap.keySet()) { List<String> categoriesSelected = userPrefMap.get(newspaper); Newspapers npEnum = gazettiEnums.getNewspaperFromName(newspaper); for (String category : categoriesSelected) {
// Path: app/src/main/java/in/sahildave/gazetti/homescreen/adapter/CellModel.java // public class CellModel { // // private String newspaperImage; // private String newspaperTitle; // private String newspaperId; // private String categoryTitle; // private String categoryId; // // public CellModel(Newspapers newspapers, Category category) { // setNewspaperImage(newspapers.getNewspaperImage()); // setNewspaperTitle(newspapers.getTitle()); // setNewspaperId(newspapers.getNewspaperId()); // // setCategoryTitle(category.getTitle()); // setCategoryId(category.getCategoryId()); // } // // public CellModel (NewsCatModel newsCatModel) { // setNewspaperImage(newsCatModel.getNewspaperImage()); // setNewspaperTitle(newsCatModel.getNewspaperTitle()); // setNewspaperId(newsCatModel.getNewspaperId()); // // setCategoryTitle(newsCatModel.getCategoryTitle()); // setCategoryId(newsCatModel.getCategoryId()); // } // // public String getNewspaperImage() { // return newspaperImage; // } // // public void setNewspaperImage(String newspaperImage) { // this.newspaperImage = newspaperImage; // } // // public String getCategoryTitle() { // return categoryTitle; // } // // public void setCategoryTitle(String categoryTitle) { // this.categoryTitle = categoryTitle; // } // // public String getNewspaperTitle() { // return newspaperTitle; // } // // public void setNewspaperTitle(String newspaperTitle) { // this.newspaperTitle = newspaperTitle; // } // // public String getNewspaperId() { // return newspaperId; // } // // public void setNewspaperId(String newspaperId) { // this.newspaperId = newspaperId; // } // // public String getCategoryId() { // return categoryId; // } // // public void setCategoryId(String categoryId) { // this.categoryId = categoryId; // } // // @Override // public String toString() { // return getNewspaperId()+"-"+getNewspaperTitle()+", "+getCategoryId()+"-"+getCategoryTitle(); // } // // } // // Path: app/src/main/java/in/sahildave/gazetti/util/GazettiEnums.java // public enum Category { // NATIONAL ("National", "1"), // INTERNATIONAL ("International", "2"), // SPORTS ("Sports", "3"), // SCIENCE ("Science", "4"), // BUSINESS ("Business", "6"), // OPINION_BLOG_EDITORIAL("Blogs and Editorials", "7"), // ENTERTAINMENT ("Entertainment", "5"), // ADD_NEW("Add New", "-1"); // // private final String categoryTitle; // private final String categoryId; // // Category(String categoryTitle, String catId) { // this.categoryTitle = categoryTitle; // this.categoryId = catId; // } // // public String getTitle() { // return categoryTitle; // } // // public String getCategoryId() { // return categoryId; // } // } // // Path: app/src/main/java/in/sahildave/gazetti/util/GazettiEnums.java // public enum Newspapers { // THE_HINDU ("The Hindu", "th", "0", "hindu_data"), // TOI ("The Times of India", "toi", "1", "toi_data"), // FIRST_POST ("First Post", "fp", "2", "fp_data"), // INDIAN_EXP ("The Indian Express", "tie", "3", "tie_data"), // ADD_NEW ("Add New", "add_new", "-1", "null"); // // private final String newspaperTitle; // private final String newspaperImage; // private final String newspaperId; // private final String dbToSearch; // // Newspapers(String newspaperTitle, String newspaperImage, String npId, String dbToSearch) { // this.newspaperTitle = newspaperTitle; // this.newspaperImage = newspaperImage; // this.newspaperId = npId; // this.dbToSearch = dbToSearch; // } // // public String getTitle() { // return newspaperTitle; // } // // public String getNewspaperImage() { // return newspaperImage; // } // // public String getNewspaperId() { // return newspaperId; // } // } // Path: app/src/main/java/in/sahildave/gazetti/util/UserPrefUtil.java import android.content.Context; import in.sahildave.gazetti.homescreen.adapter.CellModel; import in.sahildave.gazetti.util.GazettiEnums.Category; import in.sahildave.gazetti.util.GazettiEnums.Newspapers; import java.util.ArrayList; import java.util.List; import java.util.Map; package in.sahildave.gazetti.util; /** * Created by sahil on 9/11/14. */ public class UserPrefUtil { private static final String LOG_TAG = UserPrefUtil.class.getName(); private static UserPrefUtil _instance = null; private Context context; public static synchronized UserPrefUtil getInstance(Context context){ if (_instance == null) { _instance = new UserPrefUtil(context.getApplicationContext()); } return _instance; } private UserPrefUtil(Context parentContext) { context = parentContext; } public List<CellModel> getUserPrefCellList(){ List<CellModel> returnList = new ArrayList<CellModel>(); Map<String, List<String>> userPrefMap = NewsCatFileUtil.getInstance(context).getUserSelectionMap(); GazettiEnums gazettiEnums = new GazettiEnums(); for (String newspaper : userPrefMap.keySet()) { List<String> categoriesSelected = userPrefMap.get(newspaper); Newspapers npEnum = gazettiEnums.getNewspaperFromName(newspaper); for (String category : categoriesSelected) {
Category catEnum = gazettiEnums.getCategoryFromName(category);
sahildave/Gazetti_Newspaper_Reader
app/src/main/java/in/sahildave/gazetti/news_activities/WebsiteListFragment.java
// Path: app/src/main/java/in/sahildave/gazetti/news_activities/adapter/NewsAdapter.java // public class NewsAdapter extends ArrayAdapter<ParseObject> { // // private static final String TAG = "MasterDetail"; // private static final int SECOND_MILLIS = 1000; // private static final int MINUTE_MILLIS = 60 * SECOND_MILLIS; // private static final int HOUR_MILLIS = 60 * MINUTE_MILLIS; // private static final int DAY_MILLIS = 24 * HOUR_MILLIS; // // private Activity ctx; // // public static HashMap<String, String> linkMap = new HashMap<String, String>(); // public static HashMap<String, String> pubDateMap = new HashMap<String, String>(); // // private List<ParseObject> articleObjectList; // // public NewsAdapter(Activity context, List<ParseObject> articleObjectList) { // super(context, R.layout.headline_list_row, articleObjectList); // ctx = context; // this.articleObjectList = articleObjectList; // // } // // static class ViewHolder { // TextView textViewItem; // } // // @Override // public View getView(int position, View convertView, ViewGroup parent) { // ViewHolder holder; // if (convertView == null) { // LayoutInflater inflater = ctx.getLayoutInflater(); // convertView = inflater.inflate(R.layout.headline_list_row, parent, false); // // holder = new ViewHolder(); // holder.textViewItem = (TextView) convertView.findViewById(R.id.headline); // convertView.setTag(holder); // // } else { // holder = (ViewHolder) convertView.getTag(); // } // // ParseObject object = articleObjectList.get(position); // // Add the title view // holder.textViewItem.setText(object.getString("title")); // // // get PubDate // Date createdAtDate = object.getCreatedAt(); // long createdAtDateInMillis = createdAtDate.getTime(); // //Log.d(TAG, "createdAtDateInMillis " + createdAtDateInMillis); // // String diff = getTimeAgo(createdAtDateInMillis); // //Log.d(TAG, "diff " + diff); // // // Add title, link to Map // linkMap.put(object.getString("title"), object.getString("link")); // pubDateMap.put(object.getString("title"), diff); // //Log.d(TAG, "Added " + pubDateMap.get(object.getString("title"))); // // // PubDate // // return convertView; // // } // // public static String getTimeAgo(long time) { // if (time < 1000000000000L) { // // if timestamp given in seconds, convert to millis // time *= 1000; // } // // long now = System.currentTimeMillis(); // if (time > now || time <= 0) { // return "Just Now"; // } // // // TODO: localize // final long diff = now - time; // if (diff < MINUTE_MILLIS) { // return "Just Now"; // } else if (diff < 2 * MINUTE_MILLIS) { // return "A Minute Ago"; // } else if (diff < 50 * MINUTE_MILLIS) { // return diff / MINUTE_MILLIS + " Minutes Ago"; // } else if (diff < 120 * MINUTE_MILLIS) { // return "An Hour Ago"; // } else if (diff < 24 * HOUR_MILLIS) { // return diff / HOUR_MILLIS + " Hours Ago"; // } else if (diff < 48 * HOUR_MILLIS) { // return "Yesterday"; // } else { // return diff / DAY_MILLIS + " Days Ago"; // } // } // // }
import android.app.Activity; import android.content.Context; import android.net.ConnectivityManager; import android.net.NetworkInfo; import android.os.Bundle; import android.support.v4.app.ListFragment; import android.support.v4.widget.SwipeRefreshLayout; import android.text.format.DateUtils; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.AbsListView; import android.widget.ListView; import android.widget.TextView; import com.crashlytics.android.Crashlytics; import com.nhaarman.listviewanimations.appearance.simple.ScaleInAnimationAdapter; import com.nhaarman.listviewanimations.appearance.simple.SwingBottomInAnimationAdapter; import com.parse.FindCallback; import com.parse.ParseException; import com.parse.ParseObject; import com.parse.ParseQuery; import in.sahildave.gazetti.R; import in.sahildave.gazetti.news_activities.adapter.NewsAdapter; import java.util.ArrayList; import java.util.Date; import java.util.List;
package in.sahildave.gazetti.news_activities; public class WebsiteListFragment extends ListFragment implements SwipeRefreshLayout.OnRefreshListener, ListView.OnScrollListener { // Tags private static final String TAG = "MasterDetail"; private ItemSelectedCallback mItemSelectedCallback = sDummyItemSelectedCallback; private static final String PREFS_NAME = "QueryPrefs"; private static final String STATE_ACTIVATED_POSITION = "activated_position"; // Retained objects private static int mActivatedPosition = 1; // For HeadlinesList public String dbToSearch; private SwipeRefreshLayout mListViewContainer;
// Path: app/src/main/java/in/sahildave/gazetti/news_activities/adapter/NewsAdapter.java // public class NewsAdapter extends ArrayAdapter<ParseObject> { // // private static final String TAG = "MasterDetail"; // private static final int SECOND_MILLIS = 1000; // private static final int MINUTE_MILLIS = 60 * SECOND_MILLIS; // private static final int HOUR_MILLIS = 60 * MINUTE_MILLIS; // private static final int DAY_MILLIS = 24 * HOUR_MILLIS; // // private Activity ctx; // // public static HashMap<String, String> linkMap = new HashMap<String, String>(); // public static HashMap<String, String> pubDateMap = new HashMap<String, String>(); // // private List<ParseObject> articleObjectList; // // public NewsAdapter(Activity context, List<ParseObject> articleObjectList) { // super(context, R.layout.headline_list_row, articleObjectList); // ctx = context; // this.articleObjectList = articleObjectList; // // } // // static class ViewHolder { // TextView textViewItem; // } // // @Override // public View getView(int position, View convertView, ViewGroup parent) { // ViewHolder holder; // if (convertView == null) { // LayoutInflater inflater = ctx.getLayoutInflater(); // convertView = inflater.inflate(R.layout.headline_list_row, parent, false); // // holder = new ViewHolder(); // holder.textViewItem = (TextView) convertView.findViewById(R.id.headline); // convertView.setTag(holder); // // } else { // holder = (ViewHolder) convertView.getTag(); // } // // ParseObject object = articleObjectList.get(position); // // Add the title view // holder.textViewItem.setText(object.getString("title")); // // // get PubDate // Date createdAtDate = object.getCreatedAt(); // long createdAtDateInMillis = createdAtDate.getTime(); // //Log.d(TAG, "createdAtDateInMillis " + createdAtDateInMillis); // // String diff = getTimeAgo(createdAtDateInMillis); // //Log.d(TAG, "diff " + diff); // // // Add title, link to Map // linkMap.put(object.getString("title"), object.getString("link")); // pubDateMap.put(object.getString("title"), diff); // //Log.d(TAG, "Added " + pubDateMap.get(object.getString("title"))); // // // PubDate // // return convertView; // // } // // public static String getTimeAgo(long time) { // if (time < 1000000000000L) { // // if timestamp given in seconds, convert to millis // time *= 1000; // } // // long now = System.currentTimeMillis(); // if (time > now || time <= 0) { // return "Just Now"; // } // // // TODO: localize // final long diff = now - time; // if (diff < MINUTE_MILLIS) { // return "Just Now"; // } else if (diff < 2 * MINUTE_MILLIS) { // return "A Minute Ago"; // } else if (diff < 50 * MINUTE_MILLIS) { // return diff / MINUTE_MILLIS + " Minutes Ago"; // } else if (diff < 120 * MINUTE_MILLIS) { // return "An Hour Ago"; // } else if (diff < 24 * HOUR_MILLIS) { // return diff / HOUR_MILLIS + " Hours Ago"; // } else if (diff < 48 * HOUR_MILLIS) { // return "Yesterday"; // } else { // return diff / DAY_MILLIS + " Days Ago"; // } // } // // } // Path: app/src/main/java/in/sahildave/gazetti/news_activities/WebsiteListFragment.java import android.app.Activity; import android.content.Context; import android.net.ConnectivityManager; import android.net.NetworkInfo; import android.os.Bundle; import android.support.v4.app.ListFragment; import android.support.v4.widget.SwipeRefreshLayout; import android.text.format.DateUtils; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.AbsListView; import android.widget.ListView; import android.widget.TextView; import com.crashlytics.android.Crashlytics; import com.nhaarman.listviewanimations.appearance.simple.ScaleInAnimationAdapter; import com.nhaarman.listviewanimations.appearance.simple.SwingBottomInAnimationAdapter; import com.parse.FindCallback; import com.parse.ParseException; import com.parse.ParseObject; import com.parse.ParseQuery; import in.sahildave.gazetti.R; import in.sahildave.gazetti.news_activities.adapter.NewsAdapter; import java.util.ArrayList; import java.util.Date; import java.util.List; package in.sahildave.gazetti.news_activities; public class WebsiteListFragment extends ListFragment implements SwipeRefreshLayout.OnRefreshListener, ListView.OnScrollListener { // Tags private static final String TAG = "MasterDetail"; private ItemSelectedCallback mItemSelectedCallback = sDummyItemSelectedCallback; private static final String PREFS_NAME = "QueryPrefs"; private static final String STATE_ACTIVATED_POSITION = "activated_position"; // Retained objects private static int mActivatedPosition = 1; // For HeadlinesList public String dbToSearch; private SwipeRefreshLayout mListViewContainer;
private NewsAdapter newsAdapter;
tim-group/karg
src/test/java/com/timgroup/karg/keywords/KeywordArgumentTest.java
// Path: src/main/java/com/timgroup/karg/keywords/Keyword.java // public interface Keyword<T> extends KeywordArgumentsLens<T> { // // KeywordArguments metadata(); // KeywordArgument of(T value); // T from(KeywordArguments keywordArguments); // T from(KeywordArguments keywordArguments, T defaultValue); // // } // // Path: src/main/java/com/timgroup/karg/keywords/KeywordArgument.java // public class KeywordArgument { // // private final Keyword<?> keyword; // private final Object value; // // public static <T> KeywordArgument value(Keyword<? super T> keyword, T value) { // return new KeywordArgument(keyword, value); // } // // private <T> KeywordArgument(Keyword<? super T> name, T value) { // this.keyword = name; // this.value = value; // } // // public Keyword<?> keyword() { // return keyword; // } // // public Object value() { // return value; // } // // @Override // public int hashCode() { // final int prime = 31; // int result = 1; // result = prime * result + ((keyword == null) ? 0 : keyword.hashCode()); // result = prime * result + ((value == null) ? 0 : value.hashCode()); // return result; // } // // @Override // public boolean equals(Object obj) { // if (this == obj) { // return true; // } // if (obj == null) { // return false; // } // if (getClass() != obj.getClass()) { // return false; // } // KeywordArgument other = (KeywordArgument) obj; // if (!keyword.equals(other.keyword)) { // return false; // } // if (value == null) { // if (other.value != null) { // return false; // } // } else if (!value.equals(other.value)) { // return false; // } // return true; // } // // }
import org.junit.Test; import com.timgroup.karg.keywords.Keyword; import com.timgroup.karg.keywords.KeywordArgument; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.is;
package com.timgroup.karg.keywords; public class KeywordArgumentTest { @SuppressWarnings("unchecked") @Test public void bindsAKeywordToAValue() {
// Path: src/main/java/com/timgroup/karg/keywords/Keyword.java // public interface Keyword<T> extends KeywordArgumentsLens<T> { // // KeywordArguments metadata(); // KeywordArgument of(T value); // T from(KeywordArguments keywordArguments); // T from(KeywordArguments keywordArguments, T defaultValue); // // } // // Path: src/main/java/com/timgroup/karg/keywords/KeywordArgument.java // public class KeywordArgument { // // private final Keyword<?> keyword; // private final Object value; // // public static <T> KeywordArgument value(Keyword<? super T> keyword, T value) { // return new KeywordArgument(keyword, value); // } // // private <T> KeywordArgument(Keyword<? super T> name, T value) { // this.keyword = name; // this.value = value; // } // // public Keyword<?> keyword() { // return keyword; // } // // public Object value() { // return value; // } // // @Override // public int hashCode() { // final int prime = 31; // int result = 1; // result = prime * result + ((keyword == null) ? 0 : keyword.hashCode()); // result = prime * result + ((value == null) ? 0 : value.hashCode()); // return result; // } // // @Override // public boolean equals(Object obj) { // if (this == obj) { // return true; // } // if (obj == null) { // return false; // } // if (getClass() != obj.getClass()) { // return false; // } // KeywordArgument other = (KeywordArgument) obj; // if (!keyword.equals(other.keyword)) { // return false; // } // if (value == null) { // if (other.value != null) { // return false; // } // } else if (!value.equals(other.value)) { // return false; // } // return true; // } // // } // Path: src/test/java/com/timgroup/karg/keywords/KeywordArgumentTest.java import org.junit.Test; import com.timgroup.karg.keywords.Keyword; import com.timgroup.karg.keywords.KeywordArgument; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.is; package com.timgroup.karg.keywords; public class KeywordArgumentTest { @SuppressWarnings("unchecked") @Test public void bindsAKeywordToAValue() {
Keyword<String> name = Keywords.newKeyword();
tim-group/karg
src/test/java/com/timgroup/karg/keywords/KeywordArgumentTest.java
// Path: src/main/java/com/timgroup/karg/keywords/Keyword.java // public interface Keyword<T> extends KeywordArgumentsLens<T> { // // KeywordArguments metadata(); // KeywordArgument of(T value); // T from(KeywordArguments keywordArguments); // T from(KeywordArguments keywordArguments, T defaultValue); // // } // // Path: src/main/java/com/timgroup/karg/keywords/KeywordArgument.java // public class KeywordArgument { // // private final Keyword<?> keyword; // private final Object value; // // public static <T> KeywordArgument value(Keyword<? super T> keyword, T value) { // return new KeywordArgument(keyword, value); // } // // private <T> KeywordArgument(Keyword<? super T> name, T value) { // this.keyword = name; // this.value = value; // } // // public Keyword<?> keyword() { // return keyword; // } // // public Object value() { // return value; // } // // @Override // public int hashCode() { // final int prime = 31; // int result = 1; // result = prime * result + ((keyword == null) ? 0 : keyword.hashCode()); // result = prime * result + ((value == null) ? 0 : value.hashCode()); // return result; // } // // @Override // public boolean equals(Object obj) { // if (this == obj) { // return true; // } // if (obj == null) { // return false; // } // if (getClass() != obj.getClass()) { // return false; // } // KeywordArgument other = (KeywordArgument) obj; // if (!keyword.equals(other.keyword)) { // return false; // } // if (value == null) { // if (other.value != null) { // return false; // } // } else if (!value.equals(other.value)) { // return false; // } // return true; // } // // }
import org.junit.Test; import com.timgroup.karg.keywords.Keyword; import com.timgroup.karg.keywords.KeywordArgument; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.is;
package com.timgroup.karg.keywords; public class KeywordArgumentTest { @SuppressWarnings("unchecked") @Test public void bindsAKeywordToAValue() { Keyword<String> name = Keywords.newKeyword();
// Path: src/main/java/com/timgroup/karg/keywords/Keyword.java // public interface Keyword<T> extends KeywordArgumentsLens<T> { // // KeywordArguments metadata(); // KeywordArgument of(T value); // T from(KeywordArguments keywordArguments); // T from(KeywordArguments keywordArguments, T defaultValue); // // } // // Path: src/main/java/com/timgroup/karg/keywords/KeywordArgument.java // public class KeywordArgument { // // private final Keyword<?> keyword; // private final Object value; // // public static <T> KeywordArgument value(Keyword<? super T> keyword, T value) { // return new KeywordArgument(keyword, value); // } // // private <T> KeywordArgument(Keyword<? super T> name, T value) { // this.keyword = name; // this.value = value; // } // // public Keyword<?> keyword() { // return keyword; // } // // public Object value() { // return value; // } // // @Override // public int hashCode() { // final int prime = 31; // int result = 1; // result = prime * result + ((keyword == null) ? 0 : keyword.hashCode()); // result = prime * result + ((value == null) ? 0 : value.hashCode()); // return result; // } // // @Override // public boolean equals(Object obj) { // if (this == obj) { // return true; // } // if (obj == null) { // return false; // } // if (getClass() != obj.getClass()) { // return false; // } // KeywordArgument other = (KeywordArgument) obj; // if (!keyword.equals(other.keyword)) { // return false; // } // if (value == null) { // if (other.value != null) { // return false; // } // } else if (!value.equals(other.value)) { // return false; // } // return true; // } // // } // Path: src/test/java/com/timgroup/karg/keywords/KeywordArgumentTest.java import org.junit.Test; import com.timgroup.karg.keywords.Keyword; import com.timgroup.karg.keywords.KeywordArgument; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.is; package com.timgroup.karg.keywords; public class KeywordArgumentTest { @SuppressWarnings("unchecked") @Test public void bindsAKeywordToAValue() { Keyword<String> name = Keywords.newKeyword();
KeywordArgument bound = KeywordArgument.value(name, "Hello");
tim-group/karg
src/main/java/com/timgroup/karg/naming/TargetNameParser.java
// Path: src/main/java/com/timgroup/karg/naming/StringFunctions.java // public static final Function<String, String> LOWERCASE_TRIM = Functions.compose(LOWERCASE, TRIM); // // Path: src/main/java/com/timgroup/karg/naming/StringFunctions.java // public static final Predicate<String> NOT_EMPTY = Predicates.not(EMPTY);
import java.util.Iterator; import java.util.List; import com.google.common.collect.Lists; import static com.google.common.collect.Iterators.filter; import static com.google.common.collect.Iterators.transform; import static com.google.common.collect.Lists.newArrayList; import static com.google.common.collect.Lists.newLinkedList; import static com.timgroup.karg.naming.StringFunctions.LOWERCASE_TRIM; import static com.timgroup.karg.naming.StringFunctions.NOT_EMPTY;
package com.timgroup.karg.naming; public interface TargetNameParser { static TargetNameParser CAMEL_CASE = new CamelCaseParser(); static TargetNameParser UNDERSCORE_SEPARATED = new UnderscoreParser(); TargetName parse(String input); static final class UnderscoreParser implements TargetNameParser { @Override public TargetName parse(String input) {
// Path: src/main/java/com/timgroup/karg/naming/StringFunctions.java // public static final Function<String, String> LOWERCASE_TRIM = Functions.compose(LOWERCASE, TRIM); // // Path: src/main/java/com/timgroup/karg/naming/StringFunctions.java // public static final Predicate<String> NOT_EMPTY = Predicates.not(EMPTY); // Path: src/main/java/com/timgroup/karg/naming/TargetNameParser.java import java.util.Iterator; import java.util.List; import com.google.common.collect.Lists; import static com.google.common.collect.Iterators.filter; import static com.google.common.collect.Iterators.transform; import static com.google.common.collect.Lists.newArrayList; import static com.google.common.collect.Lists.newLinkedList; import static com.timgroup.karg.naming.StringFunctions.LOWERCASE_TRIM; import static com.timgroup.karg.naming.StringFunctions.NOT_EMPTY; package com.timgroup.karg.naming; public interface TargetNameParser { static TargetNameParser CAMEL_CASE = new CamelCaseParser(); static TargetNameParser UNDERSCORE_SEPARATED = new UnderscoreParser(); TargetName parse(String input); static final class UnderscoreParser implements TargetNameParser { @Override public TargetName parse(String input) {
Iterator<String> words = transform(filter(newArrayList(input.split("_")).iterator(), NOT_EMPTY), LOWERCASE_TRIM);
tim-group/karg
src/main/java/com/timgroup/karg/naming/TargetNameParser.java
// Path: src/main/java/com/timgroup/karg/naming/StringFunctions.java // public static final Function<String, String> LOWERCASE_TRIM = Functions.compose(LOWERCASE, TRIM); // // Path: src/main/java/com/timgroup/karg/naming/StringFunctions.java // public static final Predicate<String> NOT_EMPTY = Predicates.not(EMPTY);
import java.util.Iterator; import java.util.List; import com.google.common.collect.Lists; import static com.google.common.collect.Iterators.filter; import static com.google.common.collect.Iterators.transform; import static com.google.common.collect.Lists.newArrayList; import static com.google.common.collect.Lists.newLinkedList; import static com.timgroup.karg.naming.StringFunctions.LOWERCASE_TRIM; import static com.timgroup.karg.naming.StringFunctions.NOT_EMPTY;
package com.timgroup.karg.naming; public interface TargetNameParser { static TargetNameParser CAMEL_CASE = new CamelCaseParser(); static TargetNameParser UNDERSCORE_SEPARATED = new UnderscoreParser(); TargetName parse(String input); static final class UnderscoreParser implements TargetNameParser { @Override public TargetName parse(String input) {
// Path: src/main/java/com/timgroup/karg/naming/StringFunctions.java // public static final Function<String, String> LOWERCASE_TRIM = Functions.compose(LOWERCASE, TRIM); // // Path: src/main/java/com/timgroup/karg/naming/StringFunctions.java // public static final Predicate<String> NOT_EMPTY = Predicates.not(EMPTY); // Path: src/main/java/com/timgroup/karg/naming/TargetNameParser.java import java.util.Iterator; import java.util.List; import com.google.common.collect.Lists; import static com.google.common.collect.Iterators.filter; import static com.google.common.collect.Iterators.transform; import static com.google.common.collect.Lists.newArrayList; import static com.google.common.collect.Lists.newLinkedList; import static com.timgroup.karg.naming.StringFunctions.LOWERCASE_TRIM; import static com.timgroup.karg.naming.StringFunctions.NOT_EMPTY; package com.timgroup.karg.naming; public interface TargetNameParser { static TargetNameParser CAMEL_CASE = new CamelCaseParser(); static TargetNameParser UNDERSCORE_SEPARATED = new UnderscoreParser(); TargetName parse(String input); static final class UnderscoreParser implements TargetNameParser { @Override public TargetName parse(String input) {
Iterator<String> words = transform(filter(newArrayList(input.split("_")).iterator(), NOT_EMPTY), LOWERCASE_TRIM);
tim-group/karg
src/test/java/com/timgroup/karg/reflection/AccessorCatalogueTest.java
// Path: src/main/java/com/timgroup/karg/reference/Getter.java // public interface Getter<O, T> { // T get(O object); // } // // Path: src/main/java/com/timgroup/karg/reference/Lens.java // public interface Lens<O, T> extends Getter<O, T>, Setter<O, T> { }
import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.hasItems; import static org.hamcrest.Matchers.is; import static org.hamcrest.Matchers.not; import org.junit.Test; import com.timgroup.karg.reference.Getter; import com.timgroup.karg.reference.Lens;
encapsulatedField = value; } } @Test public void exposes_all_attributes_of_a_class_as_getters() { AccessorCatalogue<TestClass> catalogue = AccessorCatalogue.forClass(TestClass.class); assertThat(catalogue.readOnlyAttributes().keySet(), hasItems("readOnlyField", "readOnlyProperty", "writableField", "encapsulatedField", "hashCode", "class", "toString")); } @Test public void exposes_all_writable_attributes_of_a_class_as_lenses() { AccessorCatalogue<TestClass> catalogue = AccessorCatalogue.forClass(TestClass.class); assertThat(catalogue.allAttributes().keySet(), hasItems("writableField", "encapsulatedField")); } @Test public void does_not_expose_read_only_attributes_of_a_class_as_lenses() { AccessorCatalogue<TestClass> catalogue = AccessorCatalogue.forClass(TestClass.class); assertThat(catalogue.allAttributes().keySet(), not(hasItems("readOnlyField", "readOnlyProperty", "hashCode", "class", "toString"))); } @Test public void has_a_type_inferencing_getReadOnlyAttribute_method() { AccessorCatalogue<TestClass> catalogue = AccessorCatalogue.forClass(TestClass.class);
// Path: src/main/java/com/timgroup/karg/reference/Getter.java // public interface Getter<O, T> { // T get(O object); // } // // Path: src/main/java/com/timgroup/karg/reference/Lens.java // public interface Lens<O, T> extends Getter<O, T>, Setter<O, T> { } // Path: src/test/java/com/timgroup/karg/reflection/AccessorCatalogueTest.java import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.hasItems; import static org.hamcrest.Matchers.is; import static org.hamcrest.Matchers.not; import org.junit.Test; import com.timgroup.karg.reference.Getter; import com.timgroup.karg.reference.Lens; encapsulatedField = value; } } @Test public void exposes_all_attributes_of_a_class_as_getters() { AccessorCatalogue<TestClass> catalogue = AccessorCatalogue.forClass(TestClass.class); assertThat(catalogue.readOnlyAttributes().keySet(), hasItems("readOnlyField", "readOnlyProperty", "writableField", "encapsulatedField", "hashCode", "class", "toString")); } @Test public void exposes_all_writable_attributes_of_a_class_as_lenses() { AccessorCatalogue<TestClass> catalogue = AccessorCatalogue.forClass(TestClass.class); assertThat(catalogue.allAttributes().keySet(), hasItems("writableField", "encapsulatedField")); } @Test public void does_not_expose_read_only_attributes_of_a_class_as_lenses() { AccessorCatalogue<TestClass> catalogue = AccessorCatalogue.forClass(TestClass.class); assertThat(catalogue.allAttributes().keySet(), not(hasItems("readOnlyField", "readOnlyProperty", "hashCode", "class", "toString"))); } @Test public void has_a_type_inferencing_getReadOnlyAttribute_method() { AccessorCatalogue<TestClass> catalogue = AccessorCatalogue.forClass(TestClass.class);
Getter<TestClass, String> getter = catalogue.getReadOnlyAttribute("encapsulatedField");
tim-group/karg
src/test/java/com/timgroup/karg/reflection/AccessorCatalogueTest.java
// Path: src/main/java/com/timgroup/karg/reference/Getter.java // public interface Getter<O, T> { // T get(O object); // } // // Path: src/main/java/com/timgroup/karg/reference/Lens.java // public interface Lens<O, T> extends Getter<O, T>, Setter<O, T> { }
import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.hasItems; import static org.hamcrest.Matchers.is; import static org.hamcrest.Matchers.not; import org.junit.Test; import com.timgroup.karg.reference.Getter; import com.timgroup.karg.reference.Lens;
hasItems("readOnlyField", "readOnlyProperty", "writableField", "encapsulatedField", "hashCode", "class", "toString")); } @Test public void exposes_all_writable_attributes_of_a_class_as_lenses() { AccessorCatalogue<TestClass> catalogue = AccessorCatalogue.forClass(TestClass.class); assertThat(catalogue.allAttributes().keySet(), hasItems("writableField", "encapsulatedField")); } @Test public void does_not_expose_read_only_attributes_of_a_class_as_lenses() { AccessorCatalogue<TestClass> catalogue = AccessorCatalogue.forClass(TestClass.class); assertThat(catalogue.allAttributes().keySet(), not(hasItems("readOnlyField", "readOnlyProperty", "hashCode", "class", "toString"))); } @Test public void has_a_type_inferencing_getReadOnlyAttribute_method() { AccessorCatalogue<TestClass> catalogue = AccessorCatalogue.forClass(TestClass.class); Getter<TestClass, String> getter = catalogue.getReadOnlyAttribute("encapsulatedField"); TestClass testInstance = new TestClass(); assertThat(getter.get(testInstance), is("writable value 2")); } @Test public void has_a_type_inferencing_getAttribute_method() { AccessorCatalogue<TestClass> catalogue = AccessorCatalogue.forClass(TestClass.class);
// Path: src/main/java/com/timgroup/karg/reference/Getter.java // public interface Getter<O, T> { // T get(O object); // } // // Path: src/main/java/com/timgroup/karg/reference/Lens.java // public interface Lens<O, T> extends Getter<O, T>, Setter<O, T> { } // Path: src/test/java/com/timgroup/karg/reflection/AccessorCatalogueTest.java import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.hasItems; import static org.hamcrest.Matchers.is; import static org.hamcrest.Matchers.not; import org.junit.Test; import com.timgroup.karg.reference.Getter; import com.timgroup.karg.reference.Lens; hasItems("readOnlyField", "readOnlyProperty", "writableField", "encapsulatedField", "hashCode", "class", "toString")); } @Test public void exposes_all_writable_attributes_of_a_class_as_lenses() { AccessorCatalogue<TestClass> catalogue = AccessorCatalogue.forClass(TestClass.class); assertThat(catalogue.allAttributes().keySet(), hasItems("writableField", "encapsulatedField")); } @Test public void does_not_expose_read_only_attributes_of_a_class_as_lenses() { AccessorCatalogue<TestClass> catalogue = AccessorCatalogue.forClass(TestClass.class); assertThat(catalogue.allAttributes().keySet(), not(hasItems("readOnlyField", "readOnlyProperty", "hashCode", "class", "toString"))); } @Test public void has_a_type_inferencing_getReadOnlyAttribute_method() { AccessorCatalogue<TestClass> catalogue = AccessorCatalogue.forClass(TestClass.class); Getter<TestClass, String> getter = catalogue.getReadOnlyAttribute("encapsulatedField"); TestClass testInstance = new TestClass(); assertThat(getter.get(testInstance), is("writable value 2")); } @Test public void has_a_type_inferencing_getAttribute_method() { AccessorCatalogue<TestClass> catalogue = AccessorCatalogue.forClass(TestClass.class);
Lens<TestClass, String> lens = catalogue.getAttribute("encapsulatedField");
tim-group/karg
src/main/java/com/timgroup/karg/typeconversion/TypeConverters.java
// Path: src/main/java/com/timgroup/karg/reference/Gettable.java // public interface Gettable<T> extends Supplier<T> { // } // // Path: src/main/java/com/timgroup/karg/reference/Getter.java // public interface Getter<O, T> { // T get(O object); // } // // Path: src/main/java/com/timgroup/karg/reference/Lens.java // public interface Lens<O, T> extends Getter<O, T>, Setter<O, T> { } // // Path: src/main/java/com/timgroup/karg/reference/Ref.java // public interface Ref<T> extends Gettable<T>, Settable<T> { } // // Path: src/main/java/com/timgroup/karg/reference/Settable.java // public interface Settable<T> { // T set(T newValue); // } // // Path: src/main/java/com/timgroup/karg/reference/Setter.java // public interface Setter<O, T> { // T set(O object, T newValue); // }
import com.timgroup.karg.reference.Gettable; import com.timgroup.karg.reference.Getter; import com.timgroup.karg.reference.Lens; import com.timgroup.karg.reference.Ref; import com.timgroup.karg.reference.Settable; import com.timgroup.karg.reference.Setter;
package com.timgroup.karg.typeconversion; public final class TypeConverters { public static <O, INNER, OUTER> Lens<O, OUTER> convert(final Lens<O, INNER> lens, final TypeConverter<INNER, OUTER> converter) { return new Lens<O, OUTER>() { @Override public OUTER get(O object) { return converter.pullOut(lens.get(object)); } @Override public OUTER set(O object, OUTER newValue) { return converter.pullOut(lens.set(object, converter.pushIn(newValue))); } }; }
// Path: src/main/java/com/timgroup/karg/reference/Gettable.java // public interface Gettable<T> extends Supplier<T> { // } // // Path: src/main/java/com/timgroup/karg/reference/Getter.java // public interface Getter<O, T> { // T get(O object); // } // // Path: src/main/java/com/timgroup/karg/reference/Lens.java // public interface Lens<O, T> extends Getter<O, T>, Setter<O, T> { } // // Path: src/main/java/com/timgroup/karg/reference/Ref.java // public interface Ref<T> extends Gettable<T>, Settable<T> { } // // Path: src/main/java/com/timgroup/karg/reference/Settable.java // public interface Settable<T> { // T set(T newValue); // } // // Path: src/main/java/com/timgroup/karg/reference/Setter.java // public interface Setter<O, T> { // T set(O object, T newValue); // } // Path: src/main/java/com/timgroup/karg/typeconversion/TypeConverters.java import com.timgroup.karg.reference.Gettable; import com.timgroup.karg.reference.Getter; import com.timgroup.karg.reference.Lens; import com.timgroup.karg.reference.Ref; import com.timgroup.karg.reference.Settable; import com.timgroup.karg.reference.Setter; package com.timgroup.karg.typeconversion; public final class TypeConverters { public static <O, INNER, OUTER> Lens<O, OUTER> convert(final Lens<O, INNER> lens, final TypeConverter<INNER, OUTER> converter) { return new Lens<O, OUTER>() { @Override public OUTER get(O object) { return converter.pullOut(lens.get(object)); } @Override public OUTER set(O object, OUTER newValue) { return converter.pullOut(lens.set(object, converter.pushIn(newValue))); } }; }
public static <O, INNER, OUTER> Getter<O, OUTER> convert(final Getter<O, INNER> lens, final TypeConverter<INNER, OUTER> converter) {
tim-group/karg
src/main/java/com/timgroup/karg/typeconversion/TypeConverters.java
// Path: src/main/java/com/timgroup/karg/reference/Gettable.java // public interface Gettable<T> extends Supplier<T> { // } // // Path: src/main/java/com/timgroup/karg/reference/Getter.java // public interface Getter<O, T> { // T get(O object); // } // // Path: src/main/java/com/timgroup/karg/reference/Lens.java // public interface Lens<O, T> extends Getter<O, T>, Setter<O, T> { } // // Path: src/main/java/com/timgroup/karg/reference/Ref.java // public interface Ref<T> extends Gettable<T>, Settable<T> { } // // Path: src/main/java/com/timgroup/karg/reference/Settable.java // public interface Settable<T> { // T set(T newValue); // } // // Path: src/main/java/com/timgroup/karg/reference/Setter.java // public interface Setter<O, T> { // T set(O object, T newValue); // }
import com.timgroup.karg.reference.Gettable; import com.timgroup.karg.reference.Getter; import com.timgroup.karg.reference.Lens; import com.timgroup.karg.reference.Ref; import com.timgroup.karg.reference.Settable; import com.timgroup.karg.reference.Setter;
package com.timgroup.karg.typeconversion; public final class TypeConverters { public static <O, INNER, OUTER> Lens<O, OUTER> convert(final Lens<O, INNER> lens, final TypeConverter<INNER, OUTER> converter) { return new Lens<O, OUTER>() { @Override public OUTER get(O object) { return converter.pullOut(lens.get(object)); } @Override public OUTER set(O object, OUTER newValue) { return converter.pullOut(lens.set(object, converter.pushIn(newValue))); } }; } public static <O, INNER, OUTER> Getter<O, OUTER> convert(final Getter<O, INNER> lens, final TypeConverter<INNER, OUTER> converter) { return new Getter<O, OUTER>() { @Override public OUTER get(O object) { return converter.pullOut(lens.get(object)); } }; }
// Path: src/main/java/com/timgroup/karg/reference/Gettable.java // public interface Gettable<T> extends Supplier<T> { // } // // Path: src/main/java/com/timgroup/karg/reference/Getter.java // public interface Getter<O, T> { // T get(O object); // } // // Path: src/main/java/com/timgroup/karg/reference/Lens.java // public interface Lens<O, T> extends Getter<O, T>, Setter<O, T> { } // // Path: src/main/java/com/timgroup/karg/reference/Ref.java // public interface Ref<T> extends Gettable<T>, Settable<T> { } // // Path: src/main/java/com/timgroup/karg/reference/Settable.java // public interface Settable<T> { // T set(T newValue); // } // // Path: src/main/java/com/timgroup/karg/reference/Setter.java // public interface Setter<O, T> { // T set(O object, T newValue); // } // Path: src/main/java/com/timgroup/karg/typeconversion/TypeConverters.java import com.timgroup.karg.reference.Gettable; import com.timgroup.karg.reference.Getter; import com.timgroup.karg.reference.Lens; import com.timgroup.karg.reference.Ref; import com.timgroup.karg.reference.Settable; import com.timgroup.karg.reference.Setter; package com.timgroup.karg.typeconversion; public final class TypeConverters { public static <O, INNER, OUTER> Lens<O, OUTER> convert(final Lens<O, INNER> lens, final TypeConverter<INNER, OUTER> converter) { return new Lens<O, OUTER>() { @Override public OUTER get(O object) { return converter.pullOut(lens.get(object)); } @Override public OUTER set(O object, OUTER newValue) { return converter.pullOut(lens.set(object, converter.pushIn(newValue))); } }; } public static <O, INNER, OUTER> Getter<O, OUTER> convert(final Getter<O, INNER> lens, final TypeConverter<INNER, OUTER> converter) { return new Getter<O, OUTER>() { @Override public OUTER get(O object) { return converter.pullOut(lens.get(object)); } }; }
public static <O, INNER, OUTER> Setter<O, OUTER> convert(final Setter<O, INNER> lens, final TypeConverter<INNER, OUTER> converter) {
tim-group/karg
src/main/java/com/timgroup/karg/typeconversion/TypeConverters.java
// Path: src/main/java/com/timgroup/karg/reference/Gettable.java // public interface Gettable<T> extends Supplier<T> { // } // // Path: src/main/java/com/timgroup/karg/reference/Getter.java // public interface Getter<O, T> { // T get(O object); // } // // Path: src/main/java/com/timgroup/karg/reference/Lens.java // public interface Lens<O, T> extends Getter<O, T>, Setter<O, T> { } // // Path: src/main/java/com/timgroup/karg/reference/Ref.java // public interface Ref<T> extends Gettable<T>, Settable<T> { } // // Path: src/main/java/com/timgroup/karg/reference/Settable.java // public interface Settable<T> { // T set(T newValue); // } // // Path: src/main/java/com/timgroup/karg/reference/Setter.java // public interface Setter<O, T> { // T set(O object, T newValue); // }
import com.timgroup.karg.reference.Gettable; import com.timgroup.karg.reference.Getter; import com.timgroup.karg.reference.Lens; import com.timgroup.karg.reference.Ref; import com.timgroup.karg.reference.Settable; import com.timgroup.karg.reference.Setter;
package com.timgroup.karg.typeconversion; public final class TypeConverters { public static <O, INNER, OUTER> Lens<O, OUTER> convert(final Lens<O, INNER> lens, final TypeConverter<INNER, OUTER> converter) { return new Lens<O, OUTER>() { @Override public OUTER get(O object) { return converter.pullOut(lens.get(object)); } @Override public OUTER set(O object, OUTER newValue) { return converter.pullOut(lens.set(object, converter.pushIn(newValue))); } }; } public static <O, INNER, OUTER> Getter<O, OUTER> convert(final Getter<O, INNER> lens, final TypeConverter<INNER, OUTER> converter) { return new Getter<O, OUTER>() { @Override public OUTER get(O object) { return converter.pullOut(lens.get(object)); } }; } public static <O, INNER, OUTER> Setter<O, OUTER> convert(final Setter<O, INNER> lens, final TypeConverter<INNER, OUTER> converter) { return new Setter<O, OUTER>() { @Override public OUTER set(O object, OUTER newValue) { return converter.pullOut(lens.set(object, converter.pushIn(newValue))); } }; }
// Path: src/main/java/com/timgroup/karg/reference/Gettable.java // public interface Gettable<T> extends Supplier<T> { // } // // Path: src/main/java/com/timgroup/karg/reference/Getter.java // public interface Getter<O, T> { // T get(O object); // } // // Path: src/main/java/com/timgroup/karg/reference/Lens.java // public interface Lens<O, T> extends Getter<O, T>, Setter<O, T> { } // // Path: src/main/java/com/timgroup/karg/reference/Ref.java // public interface Ref<T> extends Gettable<T>, Settable<T> { } // // Path: src/main/java/com/timgroup/karg/reference/Settable.java // public interface Settable<T> { // T set(T newValue); // } // // Path: src/main/java/com/timgroup/karg/reference/Setter.java // public interface Setter<O, T> { // T set(O object, T newValue); // } // Path: src/main/java/com/timgroup/karg/typeconversion/TypeConverters.java import com.timgroup.karg.reference.Gettable; import com.timgroup.karg.reference.Getter; import com.timgroup.karg.reference.Lens; import com.timgroup.karg.reference.Ref; import com.timgroup.karg.reference.Settable; import com.timgroup.karg.reference.Setter; package com.timgroup.karg.typeconversion; public final class TypeConverters { public static <O, INNER, OUTER> Lens<O, OUTER> convert(final Lens<O, INNER> lens, final TypeConverter<INNER, OUTER> converter) { return new Lens<O, OUTER>() { @Override public OUTER get(O object) { return converter.pullOut(lens.get(object)); } @Override public OUTER set(O object, OUTER newValue) { return converter.pullOut(lens.set(object, converter.pushIn(newValue))); } }; } public static <O, INNER, OUTER> Getter<O, OUTER> convert(final Getter<O, INNER> lens, final TypeConverter<INNER, OUTER> converter) { return new Getter<O, OUTER>() { @Override public OUTER get(O object) { return converter.pullOut(lens.get(object)); } }; } public static <O, INNER, OUTER> Setter<O, OUTER> convert(final Setter<O, INNER> lens, final TypeConverter<INNER, OUTER> converter) { return new Setter<O, OUTER>() { @Override public OUTER set(O object, OUTER newValue) { return converter.pullOut(lens.set(object, converter.pushIn(newValue))); } }; }
public static <INNER, OUTER> Ref<OUTER> convert(final Ref<INNER> ref, final TypeConverter<INNER, OUTER> converter) {
tim-group/karg
src/main/java/com/timgroup/karg/typeconversion/TypeConverters.java
// Path: src/main/java/com/timgroup/karg/reference/Gettable.java // public interface Gettable<T> extends Supplier<T> { // } // // Path: src/main/java/com/timgroup/karg/reference/Getter.java // public interface Getter<O, T> { // T get(O object); // } // // Path: src/main/java/com/timgroup/karg/reference/Lens.java // public interface Lens<O, T> extends Getter<O, T>, Setter<O, T> { } // // Path: src/main/java/com/timgroup/karg/reference/Ref.java // public interface Ref<T> extends Gettable<T>, Settable<T> { } // // Path: src/main/java/com/timgroup/karg/reference/Settable.java // public interface Settable<T> { // T set(T newValue); // } // // Path: src/main/java/com/timgroup/karg/reference/Setter.java // public interface Setter<O, T> { // T set(O object, T newValue); // }
import com.timgroup.karg.reference.Gettable; import com.timgroup.karg.reference.Getter; import com.timgroup.karg.reference.Lens; import com.timgroup.karg.reference.Ref; import com.timgroup.karg.reference.Settable; import com.timgroup.karg.reference.Setter;
} public static <O, INNER, OUTER> Getter<O, OUTER> convert(final Getter<O, INNER> lens, final TypeConverter<INNER, OUTER> converter) { return new Getter<O, OUTER>() { @Override public OUTER get(O object) { return converter.pullOut(lens.get(object)); } }; } public static <O, INNER, OUTER> Setter<O, OUTER> convert(final Setter<O, INNER> lens, final TypeConverter<INNER, OUTER> converter) { return new Setter<O, OUTER>() { @Override public OUTER set(O object, OUTER newValue) { return converter.pullOut(lens.set(object, converter.pushIn(newValue))); } }; } public static <INNER, OUTER> Ref<OUTER> convert(final Ref<INNER> ref, final TypeConverter<INNER, OUTER> converter) { return new Ref<OUTER>() { @Override public OUTER get() { return converter.pullOut(ref.get()); } @Override public OUTER set(OUTER newValue) { return converter.pullOut(ref.set(converter.pushIn(newValue))); } }; }
// Path: src/main/java/com/timgroup/karg/reference/Gettable.java // public interface Gettable<T> extends Supplier<T> { // } // // Path: src/main/java/com/timgroup/karg/reference/Getter.java // public interface Getter<O, T> { // T get(O object); // } // // Path: src/main/java/com/timgroup/karg/reference/Lens.java // public interface Lens<O, T> extends Getter<O, T>, Setter<O, T> { } // // Path: src/main/java/com/timgroup/karg/reference/Ref.java // public interface Ref<T> extends Gettable<T>, Settable<T> { } // // Path: src/main/java/com/timgroup/karg/reference/Settable.java // public interface Settable<T> { // T set(T newValue); // } // // Path: src/main/java/com/timgroup/karg/reference/Setter.java // public interface Setter<O, T> { // T set(O object, T newValue); // } // Path: src/main/java/com/timgroup/karg/typeconversion/TypeConverters.java import com.timgroup.karg.reference.Gettable; import com.timgroup.karg.reference.Getter; import com.timgroup.karg.reference.Lens; import com.timgroup.karg.reference.Ref; import com.timgroup.karg.reference.Settable; import com.timgroup.karg.reference.Setter; } public static <O, INNER, OUTER> Getter<O, OUTER> convert(final Getter<O, INNER> lens, final TypeConverter<INNER, OUTER> converter) { return new Getter<O, OUTER>() { @Override public OUTER get(O object) { return converter.pullOut(lens.get(object)); } }; } public static <O, INNER, OUTER> Setter<O, OUTER> convert(final Setter<O, INNER> lens, final TypeConverter<INNER, OUTER> converter) { return new Setter<O, OUTER>() { @Override public OUTER set(O object, OUTER newValue) { return converter.pullOut(lens.set(object, converter.pushIn(newValue))); } }; } public static <INNER, OUTER> Ref<OUTER> convert(final Ref<INNER> ref, final TypeConverter<INNER, OUTER> converter) { return new Ref<OUTER>() { @Override public OUTER get() { return converter.pullOut(ref.get()); } @Override public OUTER set(OUTER newValue) { return converter.pullOut(ref.set(converter.pushIn(newValue))); } }; }
public static <INNER, OUTER> Gettable<OUTER> convert(final Gettable<INNER> ref, final TypeConverter<INNER, OUTER> converter) {
tim-group/karg
src/main/java/com/timgroup/karg/typeconversion/TypeConverters.java
// Path: src/main/java/com/timgroup/karg/reference/Gettable.java // public interface Gettable<T> extends Supplier<T> { // } // // Path: src/main/java/com/timgroup/karg/reference/Getter.java // public interface Getter<O, T> { // T get(O object); // } // // Path: src/main/java/com/timgroup/karg/reference/Lens.java // public interface Lens<O, T> extends Getter<O, T>, Setter<O, T> { } // // Path: src/main/java/com/timgroup/karg/reference/Ref.java // public interface Ref<T> extends Gettable<T>, Settable<T> { } // // Path: src/main/java/com/timgroup/karg/reference/Settable.java // public interface Settable<T> { // T set(T newValue); // } // // Path: src/main/java/com/timgroup/karg/reference/Setter.java // public interface Setter<O, T> { // T set(O object, T newValue); // }
import com.timgroup.karg.reference.Gettable; import com.timgroup.karg.reference.Getter; import com.timgroup.karg.reference.Lens; import com.timgroup.karg.reference.Ref; import com.timgroup.karg.reference.Settable; import com.timgroup.karg.reference.Setter;
} public static <O, INNER, OUTER> Setter<O, OUTER> convert(final Setter<O, INNER> lens, final TypeConverter<INNER, OUTER> converter) { return new Setter<O, OUTER>() { @Override public OUTER set(O object, OUTER newValue) { return converter.pullOut(lens.set(object, converter.pushIn(newValue))); } }; } public static <INNER, OUTER> Ref<OUTER> convert(final Ref<INNER> ref, final TypeConverter<INNER, OUTER> converter) { return new Ref<OUTER>() { @Override public OUTER get() { return converter.pullOut(ref.get()); } @Override public OUTER set(OUTER newValue) { return converter.pullOut(ref.set(converter.pushIn(newValue))); } }; } public static <INNER, OUTER> Gettable<OUTER> convert(final Gettable<INNER> ref, final TypeConverter<INNER, OUTER> converter) { return new Gettable<OUTER>() { @Override public OUTER get() { return converter.pullOut(ref.get()); } }; }
// Path: src/main/java/com/timgroup/karg/reference/Gettable.java // public interface Gettable<T> extends Supplier<T> { // } // // Path: src/main/java/com/timgroup/karg/reference/Getter.java // public interface Getter<O, T> { // T get(O object); // } // // Path: src/main/java/com/timgroup/karg/reference/Lens.java // public interface Lens<O, T> extends Getter<O, T>, Setter<O, T> { } // // Path: src/main/java/com/timgroup/karg/reference/Ref.java // public interface Ref<T> extends Gettable<T>, Settable<T> { } // // Path: src/main/java/com/timgroup/karg/reference/Settable.java // public interface Settable<T> { // T set(T newValue); // } // // Path: src/main/java/com/timgroup/karg/reference/Setter.java // public interface Setter<O, T> { // T set(O object, T newValue); // } // Path: src/main/java/com/timgroup/karg/typeconversion/TypeConverters.java import com.timgroup.karg.reference.Gettable; import com.timgroup.karg.reference.Getter; import com.timgroup.karg.reference.Lens; import com.timgroup.karg.reference.Ref; import com.timgroup.karg.reference.Settable; import com.timgroup.karg.reference.Setter; } public static <O, INNER, OUTER> Setter<O, OUTER> convert(final Setter<O, INNER> lens, final TypeConverter<INNER, OUTER> converter) { return new Setter<O, OUTER>() { @Override public OUTER set(O object, OUTER newValue) { return converter.pullOut(lens.set(object, converter.pushIn(newValue))); } }; } public static <INNER, OUTER> Ref<OUTER> convert(final Ref<INNER> ref, final TypeConverter<INNER, OUTER> converter) { return new Ref<OUTER>() { @Override public OUTER get() { return converter.pullOut(ref.get()); } @Override public OUTER set(OUTER newValue) { return converter.pullOut(ref.set(converter.pushIn(newValue))); } }; } public static <INNER, OUTER> Gettable<OUTER> convert(final Gettable<INNER> ref, final TypeConverter<INNER, OUTER> converter) { return new Gettable<OUTER>() { @Override public OUTER get() { return converter.pullOut(ref.get()); } }; }
public static <INNER, OUTER> Settable<OUTER> convert(final Settable<INNER> ref, final TypeConverter<INNER, OUTER> converter) {
tim-group/karg
src/test/java/com/timgroup/karg/multipledispatch/CandidateFunctionTest.java
// Path: src/main/java/com/timgroup/karg/keywords/KeywordArguments.java // public class KeywordArguments implements Map<Keyword<?>, KeywordArgument> { // // private final Map<Keyword<?>, KeywordArgument> keywordArguments = newHashMap(); // // public static KeywordArguments of(KeywordArgument...keywordArgumentArgs) { // return of(newArrayList(keywordArgumentArgs)); // } // // public static KeywordArguments empty() { // return of(); // } // // public static KeywordArguments of(List<KeywordArgument> keywordArgumentList) { // return new KeywordArguments(keywordArgumentList); // } // // private KeywordArguments(List<KeywordArgument> keywordArgumentList) { // for (KeywordArgument keywordArgument : keywordArgumentList) { // keywordArguments.put(keywordArgument.keyword(), keywordArgument); // } // } // // public boolean matchesKeywords(Set<Keyword<?>> keywords) { // return keywordArguments.keySet().equals(keywords); // } // // public <T> T valueOf(Keyword<T> keyword) { // return valueOf(keyword, null); // } // // @SuppressWarnings("unchecked") // public <T> T valueOf(Keyword<T> keyword, T defaultValue) { // KeywordArgument argument = keywordArguments.get(keyword); // return argument == null ? defaultValue : (T) argument.value(); // } // // public KeywordArguments with(KeywordArgument...additionalArguments) { // return with(newArrayList(additionalArguments)); // } // // public KeywordArguments with(List<KeywordArgument> additionalArguments) { // List<KeywordArgument> argumentList = newLinkedList(keywordArguments.values()); // argumentList.addAll(additionalArguments); // return new KeywordArguments(argumentList); // } // // public KeywordArguments with(KeywordArguments additionalArguments) { // List<KeywordArgument> argumentList = newLinkedList(keywordArguments.values()); // argumentList.addAll(additionalArguments.keywordArguments.values()); // return new KeywordArguments(argumentList); // } // // public static Predicate<KeywordArguments> containing(Keyword<?>...keywords) { // final Set<Keyword<?>> keywordSet = Sets.newHashSet(keywords); // return new Predicate<KeywordArguments>() { // @Override // public boolean apply(KeywordArguments input) { // return input.matchesKeywords(keywordSet); // } // }; // } // // @Override // public int hashCode() { // return keywordArguments.hashCode(); // } // // @Override // public boolean equals(Object obj) { // if (this == obj) { // return true; // } // // if (obj == null || !(obj instanceof KeywordArguments)) { // return false; // } // // KeywordArguments other = (KeywordArguments) obj; // return keywordArguments.equals(other.keywordArguments); // } // // @Override // public int size() { // return keywordArguments.size(); // } // // @Override // public boolean isEmpty() { // return keywordArguments.isEmpty(); // } // // @Override // public boolean containsKey(Object key) { // return keywordArguments.containsKey(key); // } // // @Override // public boolean containsValue(Object value) { // return keywordArguments.containsValue(value); // } // // @Override // public KeywordArgument get(Object key) { // return keywordArguments.get(key); // } // // @Override // public void putAll(Map<? extends Keyword<?>, ? extends KeywordArgument> m) { // keywordArguments.putAll(m); // } // // @Override // public void clear() { // keywordArguments.clear(); // } // // @Override // public Set<Keyword<?>> keySet() { // return Sets.newHashSet(keywordArguments.keySet()); // } // // @Override // public Collection<KeywordArgument> values() { // return Lists.newArrayList(keywordArguments.values()); // } // // @Override // public Set<java.util.Map.Entry<Keyword<?>, KeywordArgument>> entrySet() { // return Sets.newHashSet(keywordArguments.entrySet()); // } // // @Override // public KeywordArgument put(Keyword<?> key, KeywordArgument value) { // return keywordArguments.put(key, value); // } // // @Override // public KeywordArgument remove(Object key) { // return keywordArguments.remove(key); // } // } // // Path: src/main/java/com/timgroup/karg/multipledispatch/CandidateFunction.java // public class CandidateFunction<T> implements KeywordFunction<T> { // // private final Predicate<KeywordArguments> predicate; // private final Function<KeywordArguments, T> function; // // public CandidateFunction(Predicate<KeywordArguments> predicate, Function<KeywordArguments, T> function) { // this.predicate = predicate; // this.function = function; // } // // public boolean matches(KeywordArguments arguments) { // return predicate.apply(arguments); // } // // @Override // public T apply(KeywordArguments arguments) { // return function.apply(arguments); // } // }
import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.is; import org.jmock.Expectations; import org.jmock.Mockery; import org.junit.Test; import com.google.common.base.Function; import com.google.common.base.Predicate; import com.timgroup.karg.keywords.KeywordArguments; import com.timgroup.karg.multipledispatch.CandidateFunction;
package com.timgroup.karg.multipledispatch; public class CandidateFunctionTest { private final Mockery context = new Mockery(); @SuppressWarnings("unchecked")
// Path: src/main/java/com/timgroup/karg/keywords/KeywordArguments.java // public class KeywordArguments implements Map<Keyword<?>, KeywordArgument> { // // private final Map<Keyword<?>, KeywordArgument> keywordArguments = newHashMap(); // // public static KeywordArguments of(KeywordArgument...keywordArgumentArgs) { // return of(newArrayList(keywordArgumentArgs)); // } // // public static KeywordArguments empty() { // return of(); // } // // public static KeywordArguments of(List<KeywordArgument> keywordArgumentList) { // return new KeywordArguments(keywordArgumentList); // } // // private KeywordArguments(List<KeywordArgument> keywordArgumentList) { // for (KeywordArgument keywordArgument : keywordArgumentList) { // keywordArguments.put(keywordArgument.keyword(), keywordArgument); // } // } // // public boolean matchesKeywords(Set<Keyword<?>> keywords) { // return keywordArguments.keySet().equals(keywords); // } // // public <T> T valueOf(Keyword<T> keyword) { // return valueOf(keyword, null); // } // // @SuppressWarnings("unchecked") // public <T> T valueOf(Keyword<T> keyword, T defaultValue) { // KeywordArgument argument = keywordArguments.get(keyword); // return argument == null ? defaultValue : (T) argument.value(); // } // // public KeywordArguments with(KeywordArgument...additionalArguments) { // return with(newArrayList(additionalArguments)); // } // // public KeywordArguments with(List<KeywordArgument> additionalArguments) { // List<KeywordArgument> argumentList = newLinkedList(keywordArguments.values()); // argumentList.addAll(additionalArguments); // return new KeywordArguments(argumentList); // } // // public KeywordArguments with(KeywordArguments additionalArguments) { // List<KeywordArgument> argumentList = newLinkedList(keywordArguments.values()); // argumentList.addAll(additionalArguments.keywordArguments.values()); // return new KeywordArguments(argumentList); // } // // public static Predicate<KeywordArguments> containing(Keyword<?>...keywords) { // final Set<Keyword<?>> keywordSet = Sets.newHashSet(keywords); // return new Predicate<KeywordArguments>() { // @Override // public boolean apply(KeywordArguments input) { // return input.matchesKeywords(keywordSet); // } // }; // } // // @Override // public int hashCode() { // return keywordArguments.hashCode(); // } // // @Override // public boolean equals(Object obj) { // if (this == obj) { // return true; // } // // if (obj == null || !(obj instanceof KeywordArguments)) { // return false; // } // // KeywordArguments other = (KeywordArguments) obj; // return keywordArguments.equals(other.keywordArguments); // } // // @Override // public int size() { // return keywordArguments.size(); // } // // @Override // public boolean isEmpty() { // return keywordArguments.isEmpty(); // } // // @Override // public boolean containsKey(Object key) { // return keywordArguments.containsKey(key); // } // // @Override // public boolean containsValue(Object value) { // return keywordArguments.containsValue(value); // } // // @Override // public KeywordArgument get(Object key) { // return keywordArguments.get(key); // } // // @Override // public void putAll(Map<? extends Keyword<?>, ? extends KeywordArgument> m) { // keywordArguments.putAll(m); // } // // @Override // public void clear() { // keywordArguments.clear(); // } // // @Override // public Set<Keyword<?>> keySet() { // return Sets.newHashSet(keywordArguments.keySet()); // } // // @Override // public Collection<KeywordArgument> values() { // return Lists.newArrayList(keywordArguments.values()); // } // // @Override // public Set<java.util.Map.Entry<Keyword<?>, KeywordArgument>> entrySet() { // return Sets.newHashSet(keywordArguments.entrySet()); // } // // @Override // public KeywordArgument put(Keyword<?> key, KeywordArgument value) { // return keywordArguments.put(key, value); // } // // @Override // public KeywordArgument remove(Object key) { // return keywordArguments.remove(key); // } // } // // Path: src/main/java/com/timgroup/karg/multipledispatch/CandidateFunction.java // public class CandidateFunction<T> implements KeywordFunction<T> { // // private final Predicate<KeywordArguments> predicate; // private final Function<KeywordArguments, T> function; // // public CandidateFunction(Predicate<KeywordArguments> predicate, Function<KeywordArguments, T> function) { // this.predicate = predicate; // this.function = function; // } // // public boolean matches(KeywordArguments arguments) { // return predicate.apply(arguments); // } // // @Override // public T apply(KeywordArguments arguments) { // return function.apply(arguments); // } // } // Path: src/test/java/com/timgroup/karg/multipledispatch/CandidateFunctionTest.java import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.is; import org.jmock.Expectations; import org.jmock.Mockery; import org.junit.Test; import com.google.common.base.Function; import com.google.common.base.Predicate; import com.timgroup.karg.keywords.KeywordArguments; import com.timgroup.karg.multipledispatch.CandidateFunction; package com.timgroup.karg.multipledispatch; public class CandidateFunctionTest { private final Mockery context = new Mockery(); @SuppressWarnings("unchecked")
private final Predicate<KeywordArguments> predicate = context.mock(Predicate.class);
tim-group/karg
src/test/java/com/timgroup/karg/multipledispatch/CandidateFunctionTest.java
// Path: src/main/java/com/timgroup/karg/keywords/KeywordArguments.java // public class KeywordArguments implements Map<Keyword<?>, KeywordArgument> { // // private final Map<Keyword<?>, KeywordArgument> keywordArguments = newHashMap(); // // public static KeywordArguments of(KeywordArgument...keywordArgumentArgs) { // return of(newArrayList(keywordArgumentArgs)); // } // // public static KeywordArguments empty() { // return of(); // } // // public static KeywordArguments of(List<KeywordArgument> keywordArgumentList) { // return new KeywordArguments(keywordArgumentList); // } // // private KeywordArguments(List<KeywordArgument> keywordArgumentList) { // for (KeywordArgument keywordArgument : keywordArgumentList) { // keywordArguments.put(keywordArgument.keyword(), keywordArgument); // } // } // // public boolean matchesKeywords(Set<Keyword<?>> keywords) { // return keywordArguments.keySet().equals(keywords); // } // // public <T> T valueOf(Keyword<T> keyword) { // return valueOf(keyword, null); // } // // @SuppressWarnings("unchecked") // public <T> T valueOf(Keyword<T> keyword, T defaultValue) { // KeywordArgument argument = keywordArguments.get(keyword); // return argument == null ? defaultValue : (T) argument.value(); // } // // public KeywordArguments with(KeywordArgument...additionalArguments) { // return with(newArrayList(additionalArguments)); // } // // public KeywordArguments with(List<KeywordArgument> additionalArguments) { // List<KeywordArgument> argumentList = newLinkedList(keywordArguments.values()); // argumentList.addAll(additionalArguments); // return new KeywordArguments(argumentList); // } // // public KeywordArguments with(KeywordArguments additionalArguments) { // List<KeywordArgument> argumentList = newLinkedList(keywordArguments.values()); // argumentList.addAll(additionalArguments.keywordArguments.values()); // return new KeywordArguments(argumentList); // } // // public static Predicate<KeywordArguments> containing(Keyword<?>...keywords) { // final Set<Keyword<?>> keywordSet = Sets.newHashSet(keywords); // return new Predicate<KeywordArguments>() { // @Override // public boolean apply(KeywordArguments input) { // return input.matchesKeywords(keywordSet); // } // }; // } // // @Override // public int hashCode() { // return keywordArguments.hashCode(); // } // // @Override // public boolean equals(Object obj) { // if (this == obj) { // return true; // } // // if (obj == null || !(obj instanceof KeywordArguments)) { // return false; // } // // KeywordArguments other = (KeywordArguments) obj; // return keywordArguments.equals(other.keywordArguments); // } // // @Override // public int size() { // return keywordArguments.size(); // } // // @Override // public boolean isEmpty() { // return keywordArguments.isEmpty(); // } // // @Override // public boolean containsKey(Object key) { // return keywordArguments.containsKey(key); // } // // @Override // public boolean containsValue(Object value) { // return keywordArguments.containsValue(value); // } // // @Override // public KeywordArgument get(Object key) { // return keywordArguments.get(key); // } // // @Override // public void putAll(Map<? extends Keyword<?>, ? extends KeywordArgument> m) { // keywordArguments.putAll(m); // } // // @Override // public void clear() { // keywordArguments.clear(); // } // // @Override // public Set<Keyword<?>> keySet() { // return Sets.newHashSet(keywordArguments.keySet()); // } // // @Override // public Collection<KeywordArgument> values() { // return Lists.newArrayList(keywordArguments.values()); // } // // @Override // public Set<java.util.Map.Entry<Keyword<?>, KeywordArgument>> entrySet() { // return Sets.newHashSet(keywordArguments.entrySet()); // } // // @Override // public KeywordArgument put(Keyword<?> key, KeywordArgument value) { // return keywordArguments.put(key, value); // } // // @Override // public KeywordArgument remove(Object key) { // return keywordArguments.remove(key); // } // } // // Path: src/main/java/com/timgroup/karg/multipledispatch/CandidateFunction.java // public class CandidateFunction<T> implements KeywordFunction<T> { // // private final Predicate<KeywordArguments> predicate; // private final Function<KeywordArguments, T> function; // // public CandidateFunction(Predicate<KeywordArguments> predicate, Function<KeywordArguments, T> function) { // this.predicate = predicate; // this.function = function; // } // // public boolean matches(KeywordArguments arguments) { // return predicate.apply(arguments); // } // // @Override // public T apply(KeywordArguments arguments) { // return function.apply(arguments); // } // }
import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.is; import org.jmock.Expectations; import org.jmock.Mockery; import org.junit.Test; import com.google.common.base.Function; import com.google.common.base.Predicate; import com.timgroup.karg.keywords.KeywordArguments; import com.timgroup.karg.multipledispatch.CandidateFunction;
package com.timgroup.karg.multipledispatch; public class CandidateFunctionTest { private final Mockery context = new Mockery(); @SuppressWarnings("unchecked") private final Predicate<KeywordArguments> predicate = context.mock(Predicate.class); @SuppressWarnings("unchecked") private final Function<KeywordArguments, String> function = context.mock(Function.class); @Test public void matchesUsingTheSuppliedPredicate() {
// Path: src/main/java/com/timgroup/karg/keywords/KeywordArguments.java // public class KeywordArguments implements Map<Keyword<?>, KeywordArgument> { // // private final Map<Keyword<?>, KeywordArgument> keywordArguments = newHashMap(); // // public static KeywordArguments of(KeywordArgument...keywordArgumentArgs) { // return of(newArrayList(keywordArgumentArgs)); // } // // public static KeywordArguments empty() { // return of(); // } // // public static KeywordArguments of(List<KeywordArgument> keywordArgumentList) { // return new KeywordArguments(keywordArgumentList); // } // // private KeywordArguments(List<KeywordArgument> keywordArgumentList) { // for (KeywordArgument keywordArgument : keywordArgumentList) { // keywordArguments.put(keywordArgument.keyword(), keywordArgument); // } // } // // public boolean matchesKeywords(Set<Keyword<?>> keywords) { // return keywordArguments.keySet().equals(keywords); // } // // public <T> T valueOf(Keyword<T> keyword) { // return valueOf(keyword, null); // } // // @SuppressWarnings("unchecked") // public <T> T valueOf(Keyword<T> keyword, T defaultValue) { // KeywordArgument argument = keywordArguments.get(keyword); // return argument == null ? defaultValue : (T) argument.value(); // } // // public KeywordArguments with(KeywordArgument...additionalArguments) { // return with(newArrayList(additionalArguments)); // } // // public KeywordArguments with(List<KeywordArgument> additionalArguments) { // List<KeywordArgument> argumentList = newLinkedList(keywordArguments.values()); // argumentList.addAll(additionalArguments); // return new KeywordArguments(argumentList); // } // // public KeywordArguments with(KeywordArguments additionalArguments) { // List<KeywordArgument> argumentList = newLinkedList(keywordArguments.values()); // argumentList.addAll(additionalArguments.keywordArguments.values()); // return new KeywordArguments(argumentList); // } // // public static Predicate<KeywordArguments> containing(Keyword<?>...keywords) { // final Set<Keyword<?>> keywordSet = Sets.newHashSet(keywords); // return new Predicate<KeywordArguments>() { // @Override // public boolean apply(KeywordArguments input) { // return input.matchesKeywords(keywordSet); // } // }; // } // // @Override // public int hashCode() { // return keywordArguments.hashCode(); // } // // @Override // public boolean equals(Object obj) { // if (this == obj) { // return true; // } // // if (obj == null || !(obj instanceof KeywordArguments)) { // return false; // } // // KeywordArguments other = (KeywordArguments) obj; // return keywordArguments.equals(other.keywordArguments); // } // // @Override // public int size() { // return keywordArguments.size(); // } // // @Override // public boolean isEmpty() { // return keywordArguments.isEmpty(); // } // // @Override // public boolean containsKey(Object key) { // return keywordArguments.containsKey(key); // } // // @Override // public boolean containsValue(Object value) { // return keywordArguments.containsValue(value); // } // // @Override // public KeywordArgument get(Object key) { // return keywordArguments.get(key); // } // // @Override // public void putAll(Map<? extends Keyword<?>, ? extends KeywordArgument> m) { // keywordArguments.putAll(m); // } // // @Override // public void clear() { // keywordArguments.clear(); // } // // @Override // public Set<Keyword<?>> keySet() { // return Sets.newHashSet(keywordArguments.keySet()); // } // // @Override // public Collection<KeywordArgument> values() { // return Lists.newArrayList(keywordArguments.values()); // } // // @Override // public Set<java.util.Map.Entry<Keyword<?>, KeywordArgument>> entrySet() { // return Sets.newHashSet(keywordArguments.entrySet()); // } // // @Override // public KeywordArgument put(Keyword<?> key, KeywordArgument value) { // return keywordArguments.put(key, value); // } // // @Override // public KeywordArgument remove(Object key) { // return keywordArguments.remove(key); // } // } // // Path: src/main/java/com/timgroup/karg/multipledispatch/CandidateFunction.java // public class CandidateFunction<T> implements KeywordFunction<T> { // // private final Predicate<KeywordArguments> predicate; // private final Function<KeywordArguments, T> function; // // public CandidateFunction(Predicate<KeywordArguments> predicate, Function<KeywordArguments, T> function) { // this.predicate = predicate; // this.function = function; // } // // public boolean matches(KeywordArguments arguments) { // return predicate.apply(arguments); // } // // @Override // public T apply(KeywordArguments arguments) { // return function.apply(arguments); // } // } // Path: src/test/java/com/timgroup/karg/multipledispatch/CandidateFunctionTest.java import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.is; import org.jmock.Expectations; import org.jmock.Mockery; import org.junit.Test; import com.google.common.base.Function; import com.google.common.base.Predicate; import com.timgroup.karg.keywords.KeywordArguments; import com.timgroup.karg.multipledispatch.CandidateFunction; package com.timgroup.karg.multipledispatch; public class CandidateFunctionTest { private final Mockery context = new Mockery(); @SuppressWarnings("unchecked") private final Predicate<KeywordArguments> predicate = context.mock(Predicate.class); @SuppressWarnings("unchecked") private final Function<KeywordArguments, String> function = context.mock(Function.class); @Test public void matchesUsingTheSuppliedPredicate() {
CandidateFunction<String> candidate = new CandidateFunction<String>(predicate, null);
tim-group/karg
src/test/java/com/timgroup/karg/reference/RefsTest.java
// Path: src/main/java/com/timgroup/karg/reference/Cell.java // public final class Cell<T> implements Ref<T> { // // public static <T> Updatable<T> of(final T value) { // return ConcurrentRef.to(new Cell<T>(value)); // } // // private T value; // // private Cell(T value) { // this.value = value; // } // // @Override // public T get() { // return value; // } // // @Override // public T set(T newValue) { // value = newValue; // return newValue; // } // } // // Path: src/main/java/com/timgroup/karg/reference/Ref.java // public interface Ref<T> extends Gettable<T>, Settable<T> { } // // Path: src/main/java/com/timgroup/karg/reference/Refs.java // public final class Refs { // // public static <T> Iterable<T> toIterable(final Ref<T> ref) { // return new Iterable<T>() { // @Override public Iterator<T> iterator() { // return new Iterator<T>() { // private boolean consumed = ref.get() == null; // @Override public boolean hasNext() { // return !consumed; // } // // @Override public T next() { // if (consumed) { // return null; // } // consumed = true; // return ref.get(); // } // // @Override public void remove() { // ref.set(null); // } // }; // } // }; // } // // public static <T> Function<Ref<T>, Iterable<T>> toIterable() { // return new Function<Ref<T>, Iterable<T>>() { // @Override public Iterable<T> apply(Ref<T> arg0) { // return toIterable(arg0); // } // }; // } // // public static <T> Iterable<T> toIterable(Iterable<? extends Ref<T>> refs) { // Function<Ref<T>, Iterable<T>> toIterable = toIterable(); // return Iterables.concat(Iterables.transform(refs, toIterable)); // } // // private Refs() { } // // }
import org.junit.Test; import com.google.common.collect.Lists; import com.timgroup.karg.reference.Cell; import com.timgroup.karg.reference.Ref; import com.timgroup.karg.reference.Refs; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.contains; import static org.hamcrest.Matchers.is;
package com.timgroup.karg.reference; public class RefsTest { @Test public void anyRefCanBeAnIterable() {
// Path: src/main/java/com/timgroup/karg/reference/Cell.java // public final class Cell<T> implements Ref<T> { // // public static <T> Updatable<T> of(final T value) { // return ConcurrentRef.to(new Cell<T>(value)); // } // // private T value; // // private Cell(T value) { // this.value = value; // } // // @Override // public T get() { // return value; // } // // @Override // public T set(T newValue) { // value = newValue; // return newValue; // } // } // // Path: src/main/java/com/timgroup/karg/reference/Ref.java // public interface Ref<T> extends Gettable<T>, Settable<T> { } // // Path: src/main/java/com/timgroup/karg/reference/Refs.java // public final class Refs { // // public static <T> Iterable<T> toIterable(final Ref<T> ref) { // return new Iterable<T>() { // @Override public Iterator<T> iterator() { // return new Iterator<T>() { // private boolean consumed = ref.get() == null; // @Override public boolean hasNext() { // return !consumed; // } // // @Override public T next() { // if (consumed) { // return null; // } // consumed = true; // return ref.get(); // } // // @Override public void remove() { // ref.set(null); // } // }; // } // }; // } // // public static <T> Function<Ref<T>, Iterable<T>> toIterable() { // return new Function<Ref<T>, Iterable<T>>() { // @Override public Iterable<T> apply(Ref<T> arg0) { // return toIterable(arg0); // } // }; // } // // public static <T> Iterable<T> toIterable(Iterable<? extends Ref<T>> refs) { // Function<Ref<T>, Iterable<T>> toIterable = toIterable(); // return Iterables.concat(Iterables.transform(refs, toIterable)); // } // // private Refs() { } // // } // Path: src/test/java/com/timgroup/karg/reference/RefsTest.java import org.junit.Test; import com.google.common.collect.Lists; import com.timgroup.karg.reference.Cell; import com.timgroup.karg.reference.Ref; import com.timgroup.karg.reference.Refs; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.contains; import static org.hamcrest.Matchers.is; package com.timgroup.karg.reference; public class RefsTest { @Test public void anyRefCanBeAnIterable() {
Iterable<String> iterable = Refs.toIterable(Cell.of("Hello"));
tim-group/karg
src/test/java/com/timgroup/karg/reference/RefsTest.java
// Path: src/main/java/com/timgroup/karg/reference/Cell.java // public final class Cell<T> implements Ref<T> { // // public static <T> Updatable<T> of(final T value) { // return ConcurrentRef.to(new Cell<T>(value)); // } // // private T value; // // private Cell(T value) { // this.value = value; // } // // @Override // public T get() { // return value; // } // // @Override // public T set(T newValue) { // value = newValue; // return newValue; // } // } // // Path: src/main/java/com/timgroup/karg/reference/Ref.java // public interface Ref<T> extends Gettable<T>, Settable<T> { } // // Path: src/main/java/com/timgroup/karg/reference/Refs.java // public final class Refs { // // public static <T> Iterable<T> toIterable(final Ref<T> ref) { // return new Iterable<T>() { // @Override public Iterator<T> iterator() { // return new Iterator<T>() { // private boolean consumed = ref.get() == null; // @Override public boolean hasNext() { // return !consumed; // } // // @Override public T next() { // if (consumed) { // return null; // } // consumed = true; // return ref.get(); // } // // @Override public void remove() { // ref.set(null); // } // }; // } // }; // } // // public static <T> Function<Ref<T>, Iterable<T>> toIterable() { // return new Function<Ref<T>, Iterable<T>>() { // @Override public Iterable<T> apply(Ref<T> arg0) { // return toIterable(arg0); // } // }; // } // // public static <T> Iterable<T> toIterable(Iterable<? extends Ref<T>> refs) { // Function<Ref<T>, Iterable<T>> toIterable = toIterable(); // return Iterables.concat(Iterables.transform(refs, toIterable)); // } // // private Refs() { } // // }
import org.junit.Test; import com.google.common.collect.Lists; import com.timgroup.karg.reference.Cell; import com.timgroup.karg.reference.Ref; import com.timgroup.karg.reference.Refs; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.contains; import static org.hamcrest.Matchers.is;
package com.timgroup.karg.reference; public class RefsTest { @Test public void anyRefCanBeAnIterable() {
// Path: src/main/java/com/timgroup/karg/reference/Cell.java // public final class Cell<T> implements Ref<T> { // // public static <T> Updatable<T> of(final T value) { // return ConcurrentRef.to(new Cell<T>(value)); // } // // private T value; // // private Cell(T value) { // this.value = value; // } // // @Override // public T get() { // return value; // } // // @Override // public T set(T newValue) { // value = newValue; // return newValue; // } // } // // Path: src/main/java/com/timgroup/karg/reference/Ref.java // public interface Ref<T> extends Gettable<T>, Settable<T> { } // // Path: src/main/java/com/timgroup/karg/reference/Refs.java // public final class Refs { // // public static <T> Iterable<T> toIterable(final Ref<T> ref) { // return new Iterable<T>() { // @Override public Iterator<T> iterator() { // return new Iterator<T>() { // private boolean consumed = ref.get() == null; // @Override public boolean hasNext() { // return !consumed; // } // // @Override public T next() { // if (consumed) { // return null; // } // consumed = true; // return ref.get(); // } // // @Override public void remove() { // ref.set(null); // } // }; // } // }; // } // // public static <T> Function<Ref<T>, Iterable<T>> toIterable() { // return new Function<Ref<T>, Iterable<T>>() { // @Override public Iterable<T> apply(Ref<T> arg0) { // return toIterable(arg0); // } // }; // } // // public static <T> Iterable<T> toIterable(Iterable<? extends Ref<T>> refs) { // Function<Ref<T>, Iterable<T>> toIterable = toIterable(); // return Iterables.concat(Iterables.transform(refs, toIterable)); // } // // private Refs() { } // // } // Path: src/test/java/com/timgroup/karg/reference/RefsTest.java import org.junit.Test; import com.google.common.collect.Lists; import com.timgroup.karg.reference.Cell; import com.timgroup.karg.reference.Ref; import com.timgroup.karg.reference.Refs; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.contains; import static org.hamcrest.Matchers.is; package com.timgroup.karg.reference; public class RefsTest { @Test public void anyRefCanBeAnIterable() {
Iterable<String> iterable = Refs.toIterable(Cell.of("Hello"));
tim-group/karg
src/test/java/com/timgroup/karg/reference/RefsTest.java
// Path: src/main/java/com/timgroup/karg/reference/Cell.java // public final class Cell<T> implements Ref<T> { // // public static <T> Updatable<T> of(final T value) { // return ConcurrentRef.to(new Cell<T>(value)); // } // // private T value; // // private Cell(T value) { // this.value = value; // } // // @Override // public T get() { // return value; // } // // @Override // public T set(T newValue) { // value = newValue; // return newValue; // } // } // // Path: src/main/java/com/timgroup/karg/reference/Ref.java // public interface Ref<T> extends Gettable<T>, Settable<T> { } // // Path: src/main/java/com/timgroup/karg/reference/Refs.java // public final class Refs { // // public static <T> Iterable<T> toIterable(final Ref<T> ref) { // return new Iterable<T>() { // @Override public Iterator<T> iterator() { // return new Iterator<T>() { // private boolean consumed = ref.get() == null; // @Override public boolean hasNext() { // return !consumed; // } // // @Override public T next() { // if (consumed) { // return null; // } // consumed = true; // return ref.get(); // } // // @Override public void remove() { // ref.set(null); // } // }; // } // }; // } // // public static <T> Function<Ref<T>, Iterable<T>> toIterable() { // return new Function<Ref<T>, Iterable<T>>() { // @Override public Iterable<T> apply(Ref<T> arg0) { // return toIterable(arg0); // } // }; // } // // public static <T> Iterable<T> toIterable(Iterable<? extends Ref<T>> refs) { // Function<Ref<T>, Iterable<T>> toIterable = toIterable(); // return Iterables.concat(Iterables.transform(refs, toIterable)); // } // // private Refs() { } // // }
import org.junit.Test; import com.google.common.collect.Lists; import com.timgroup.karg.reference.Cell; import com.timgroup.karg.reference.Ref; import com.timgroup.karg.reference.Refs; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.contains; import static org.hamcrest.Matchers.is;
package com.timgroup.karg.reference; public class RefsTest { @Test public void anyRefCanBeAnIterable() { Iterable<String> iterable = Refs.toIterable(Cell.of("Hello")); assertThat(iterable.iterator().hasNext(), is(true)); assertThat(iterable.iterator().next(), is("Hello")); } @Test public void anEmptyRefIsAnEmptyIterable() {
// Path: src/main/java/com/timgroup/karg/reference/Cell.java // public final class Cell<T> implements Ref<T> { // // public static <T> Updatable<T> of(final T value) { // return ConcurrentRef.to(new Cell<T>(value)); // } // // private T value; // // private Cell(T value) { // this.value = value; // } // // @Override // public T get() { // return value; // } // // @Override // public T set(T newValue) { // value = newValue; // return newValue; // } // } // // Path: src/main/java/com/timgroup/karg/reference/Ref.java // public interface Ref<T> extends Gettable<T>, Settable<T> { } // // Path: src/main/java/com/timgroup/karg/reference/Refs.java // public final class Refs { // // public static <T> Iterable<T> toIterable(final Ref<T> ref) { // return new Iterable<T>() { // @Override public Iterator<T> iterator() { // return new Iterator<T>() { // private boolean consumed = ref.get() == null; // @Override public boolean hasNext() { // return !consumed; // } // // @Override public T next() { // if (consumed) { // return null; // } // consumed = true; // return ref.get(); // } // // @Override public void remove() { // ref.set(null); // } // }; // } // }; // } // // public static <T> Function<Ref<T>, Iterable<T>> toIterable() { // return new Function<Ref<T>, Iterable<T>>() { // @Override public Iterable<T> apply(Ref<T> arg0) { // return toIterable(arg0); // } // }; // } // // public static <T> Iterable<T> toIterable(Iterable<? extends Ref<T>> refs) { // Function<Ref<T>, Iterable<T>> toIterable = toIterable(); // return Iterables.concat(Iterables.transform(refs, toIterable)); // } // // private Refs() { } // // } // Path: src/test/java/com/timgroup/karg/reference/RefsTest.java import org.junit.Test; import com.google.common.collect.Lists; import com.timgroup.karg.reference.Cell; import com.timgroup.karg.reference.Ref; import com.timgroup.karg.reference.Refs; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.contains; import static org.hamcrest.Matchers.is; package com.timgroup.karg.reference; public class RefsTest { @Test public void anyRefCanBeAnIterable() { Iterable<String> iterable = Refs.toIterable(Cell.of("Hello")); assertThat(iterable.iterator().hasNext(), is(true)); assertThat(iterable.iterator().next(), is("Hello")); } @Test public void anEmptyRefIsAnEmptyIterable() {
Ref<String> ref = Cell.of(null);
tim-group/karg
src/main/java/com/timgroup/karg/reflection/PropertyAccessor.java
// Path: src/main/java/com/timgroup/karg/reference/Setter.java // public interface Setter<O, T> { // T set(O object, T newValue); // }
import com.google.common.base.Optional; import com.google.common.base.Preconditions; import com.timgroup.karg.reference.Setter;
public static <C, V> PropertyAccessor<C, V> forProperty(String propertyName, GetterMethod<C, V> getter, SetterMethod<C, V> setter) { return new PropertyAccessor<C, V>(propertyName, getter, setter); } private final String propertyName; private final GetterMethod<C, V> getter; private final Optional<SetterMethod<C, V>> setter; private PropertyAccessor(String propertyName, GetterMethod<C, V> getter) { this.propertyName = propertyName; this.getter = getter; this.setter = Optional.absent(); } private PropertyAccessor(String propertyName, GetterMethod<C, V> getter, SetterMethod<C, V> setter) { this.propertyName = propertyName; this.getter = getter; this.setter = Optional.of(setter); } @Override public V get(C object) { return getter.get(object); } @Override public V set(C object, V newValue) {
// Path: src/main/java/com/timgroup/karg/reference/Setter.java // public interface Setter<O, T> { // T set(O object, T newValue); // } // Path: src/main/java/com/timgroup/karg/reflection/PropertyAccessor.java import com.google.common.base.Optional; import com.google.common.base.Preconditions; import com.timgroup.karg.reference.Setter; public static <C, V> PropertyAccessor<C, V> forProperty(String propertyName, GetterMethod<C, V> getter, SetterMethod<C, V> setter) { return new PropertyAccessor<C, V>(propertyName, getter, setter); } private final String propertyName; private final GetterMethod<C, V> getter; private final Optional<SetterMethod<C, V>> setter; private PropertyAccessor(String propertyName, GetterMethod<C, V> getter) { this.propertyName = propertyName; this.getter = getter; this.setter = Optional.absent(); } private PropertyAccessor(String propertyName, GetterMethod<C, V> getter, SetterMethod<C, V> setter) { this.propertyName = propertyName; this.getter = getter; this.setter = Optional.of(setter); } @Override public V get(C object) { return getter.get(object); } @Override public V set(C object, V newValue) {
Setter<C, V> notNullSetter = setter.get();
tim-group/karg
src/main/java/com/timgroup/karg/multipledispatch/CandidateFunctionRegistry.java
// Path: src/main/java/com/timgroup/karg/keywords/KeywordArguments.java // public class KeywordArguments implements Map<Keyword<?>, KeywordArgument> { // // private final Map<Keyword<?>, KeywordArgument> keywordArguments = newHashMap(); // // public static KeywordArguments of(KeywordArgument...keywordArgumentArgs) { // return of(newArrayList(keywordArgumentArgs)); // } // // public static KeywordArguments empty() { // return of(); // } // // public static KeywordArguments of(List<KeywordArgument> keywordArgumentList) { // return new KeywordArguments(keywordArgumentList); // } // // private KeywordArguments(List<KeywordArgument> keywordArgumentList) { // for (KeywordArgument keywordArgument : keywordArgumentList) { // keywordArguments.put(keywordArgument.keyword(), keywordArgument); // } // } // // public boolean matchesKeywords(Set<Keyword<?>> keywords) { // return keywordArguments.keySet().equals(keywords); // } // // public <T> T valueOf(Keyword<T> keyword) { // return valueOf(keyword, null); // } // // @SuppressWarnings("unchecked") // public <T> T valueOf(Keyword<T> keyword, T defaultValue) { // KeywordArgument argument = keywordArguments.get(keyword); // return argument == null ? defaultValue : (T) argument.value(); // } // // public KeywordArguments with(KeywordArgument...additionalArguments) { // return with(newArrayList(additionalArguments)); // } // // public KeywordArguments with(List<KeywordArgument> additionalArguments) { // List<KeywordArgument> argumentList = newLinkedList(keywordArguments.values()); // argumentList.addAll(additionalArguments); // return new KeywordArguments(argumentList); // } // // public KeywordArguments with(KeywordArguments additionalArguments) { // List<KeywordArgument> argumentList = newLinkedList(keywordArguments.values()); // argumentList.addAll(additionalArguments.keywordArguments.values()); // return new KeywordArguments(argumentList); // } // // public static Predicate<KeywordArguments> containing(Keyword<?>...keywords) { // final Set<Keyword<?>> keywordSet = Sets.newHashSet(keywords); // return new Predicate<KeywordArguments>() { // @Override // public boolean apply(KeywordArguments input) { // return input.matchesKeywords(keywordSet); // } // }; // } // // @Override // public int hashCode() { // return keywordArguments.hashCode(); // } // // @Override // public boolean equals(Object obj) { // if (this == obj) { // return true; // } // // if (obj == null || !(obj instanceof KeywordArguments)) { // return false; // } // // KeywordArguments other = (KeywordArguments) obj; // return keywordArguments.equals(other.keywordArguments); // } // // @Override // public int size() { // return keywordArguments.size(); // } // // @Override // public boolean isEmpty() { // return keywordArguments.isEmpty(); // } // // @Override // public boolean containsKey(Object key) { // return keywordArguments.containsKey(key); // } // // @Override // public boolean containsValue(Object value) { // return keywordArguments.containsValue(value); // } // // @Override // public KeywordArgument get(Object key) { // return keywordArguments.get(key); // } // // @Override // public void putAll(Map<? extends Keyword<?>, ? extends KeywordArgument> m) { // keywordArguments.putAll(m); // } // // @Override // public void clear() { // keywordArguments.clear(); // } // // @Override // public Set<Keyword<?>> keySet() { // return Sets.newHashSet(keywordArguments.keySet()); // } // // @Override // public Collection<KeywordArgument> values() { // return Lists.newArrayList(keywordArguments.values()); // } // // @Override // public Set<java.util.Map.Entry<Keyword<?>, KeywordArgument>> entrySet() { // return Sets.newHashSet(keywordArguments.entrySet()); // } // // @Override // public KeywordArgument put(Keyword<?> key, KeywordArgument value) { // return keywordArguments.put(key, value); // } // // @Override // public KeywordArgument remove(Object key) { // return keywordArguments.remove(key); // } // }
import java.util.List; import java.util.NoSuchElementException; import com.google.common.base.Function; import com.google.common.base.Predicate; import com.google.common.collect.Iterables; import com.timgroup.karg.keywords.KeywordArguments; import static com.google.common.collect.Lists.newArrayList;
package com.timgroup.karg.multipledispatch; public class CandidateFunctionRegistry<T> { private final List<CandidateFunction<T>> candidates = newArrayList(); public static interface MatchBuilder<T> {
// Path: src/main/java/com/timgroup/karg/keywords/KeywordArguments.java // public class KeywordArguments implements Map<Keyword<?>, KeywordArgument> { // // private final Map<Keyword<?>, KeywordArgument> keywordArguments = newHashMap(); // // public static KeywordArguments of(KeywordArgument...keywordArgumentArgs) { // return of(newArrayList(keywordArgumentArgs)); // } // // public static KeywordArguments empty() { // return of(); // } // // public static KeywordArguments of(List<KeywordArgument> keywordArgumentList) { // return new KeywordArguments(keywordArgumentList); // } // // private KeywordArguments(List<KeywordArgument> keywordArgumentList) { // for (KeywordArgument keywordArgument : keywordArgumentList) { // keywordArguments.put(keywordArgument.keyword(), keywordArgument); // } // } // // public boolean matchesKeywords(Set<Keyword<?>> keywords) { // return keywordArguments.keySet().equals(keywords); // } // // public <T> T valueOf(Keyword<T> keyword) { // return valueOf(keyword, null); // } // // @SuppressWarnings("unchecked") // public <T> T valueOf(Keyword<T> keyword, T defaultValue) { // KeywordArgument argument = keywordArguments.get(keyword); // return argument == null ? defaultValue : (T) argument.value(); // } // // public KeywordArguments with(KeywordArgument...additionalArguments) { // return with(newArrayList(additionalArguments)); // } // // public KeywordArguments with(List<KeywordArgument> additionalArguments) { // List<KeywordArgument> argumentList = newLinkedList(keywordArguments.values()); // argumentList.addAll(additionalArguments); // return new KeywordArguments(argumentList); // } // // public KeywordArguments with(KeywordArguments additionalArguments) { // List<KeywordArgument> argumentList = newLinkedList(keywordArguments.values()); // argumentList.addAll(additionalArguments.keywordArguments.values()); // return new KeywordArguments(argumentList); // } // // public static Predicate<KeywordArguments> containing(Keyword<?>...keywords) { // final Set<Keyword<?>> keywordSet = Sets.newHashSet(keywords); // return new Predicate<KeywordArguments>() { // @Override // public boolean apply(KeywordArguments input) { // return input.matchesKeywords(keywordSet); // } // }; // } // // @Override // public int hashCode() { // return keywordArguments.hashCode(); // } // // @Override // public boolean equals(Object obj) { // if (this == obj) { // return true; // } // // if (obj == null || !(obj instanceof KeywordArguments)) { // return false; // } // // KeywordArguments other = (KeywordArguments) obj; // return keywordArguments.equals(other.keywordArguments); // } // // @Override // public int size() { // return keywordArguments.size(); // } // // @Override // public boolean isEmpty() { // return keywordArguments.isEmpty(); // } // // @Override // public boolean containsKey(Object key) { // return keywordArguments.containsKey(key); // } // // @Override // public boolean containsValue(Object value) { // return keywordArguments.containsValue(value); // } // // @Override // public KeywordArgument get(Object key) { // return keywordArguments.get(key); // } // // @Override // public void putAll(Map<? extends Keyword<?>, ? extends KeywordArgument> m) { // keywordArguments.putAll(m); // } // // @Override // public void clear() { // keywordArguments.clear(); // } // // @Override // public Set<Keyword<?>> keySet() { // return Sets.newHashSet(keywordArguments.keySet()); // } // // @Override // public Collection<KeywordArgument> values() { // return Lists.newArrayList(keywordArguments.values()); // } // // @Override // public Set<java.util.Map.Entry<Keyword<?>, KeywordArgument>> entrySet() { // return Sets.newHashSet(keywordArguments.entrySet()); // } // // @Override // public KeywordArgument put(Keyword<?> key, KeywordArgument value) { // return keywordArguments.put(key, value); // } // // @Override // public KeywordArgument remove(Object key) { // return keywordArguments.remove(key); // } // } // Path: src/main/java/com/timgroup/karg/multipledispatch/CandidateFunctionRegistry.java import java.util.List; import java.util.NoSuchElementException; import com.google.common.base.Function; import com.google.common.base.Predicate; import com.google.common.collect.Iterables; import com.timgroup.karg.keywords.KeywordArguments; import static com.google.common.collect.Lists.newArrayList; package com.timgroup.karg.multipledispatch; public class CandidateFunctionRegistry<T> { private final List<CandidateFunction<T>> candidates = newArrayList(); public static interface MatchBuilder<T> {
void with(Function<KeywordArguments, T> function);
tim-group/karg
src/main/java/com/timgroup/karg/reflection/GetterMethod.java
// Path: src/main/java/com/timgroup/karg/naming/TargetName.java // public class TargetName { // // public static TargetName fromMethodName(String methodName) { // if (methodName.contains("_")) { // return TargetNameParser.UNDERSCORE_SEPARATED.parse(methodName); // } // return TargetNameParser.CAMEL_CASE.parse(methodName); // } // // private final Iterable<String> words; // // public TargetName(Iterable<String> words) { // this.words = words; // } // // public TargetName prefixedWith(String prefix) { // return new TargetName(Iterables.concat(Lists.newArrayList(prefix), words)); // } // // public TargetName withSuffix(String suffix) { // return new TargetName(Iterables.concat(words, Lists.newArrayList(suffix))); // } // // public boolean hasPrefix(String prefix) { // return prefix.equals(Iterables.getFirst(words, null)); // } // // public TargetName withoutPrefix() { // return new TargetName(Iterables.skip(words, 1)); // } // // public String formatWith(TargetNameFormatter formatter) { // return formatter.format(words); // } // } // // Path: src/main/java/com/timgroup/karg/naming/TargetNameFormatter.java // public interface TargetNameFormatter { // // static final TargetNameFormatter LOWER_CAMEL_CASE = new LowerCamelCaseFormatter(); // static final TargetNameFormatter UPPER_CAMEL_CASE = new UpperCamelCaseFormatter(); // static final TargetNameFormatter UNDERSCORE_SEPARATED = new UnderscoreSeparatedFormatter(); // // static final class LowerCamelCaseFormatter implements TargetNameFormatter { // // @Override // public String format(Iterable<String> words) { // Iterator<String> lowercased = transform(words.iterator(), LOWERCASE_TRIM); // if (!lowercased.hasNext()) { // return ""; // } // Iterator<String> lowerCamelCased = concat(singletonIterator(lowercased.next()), // transform(lowercased, CAPITALISE)); // return Joiner.on("").join(Lists.newArrayList(lowerCamelCased)); // } // } // // static final class UpperCamelCaseFormatter implements TargetNameFormatter { // @Override // public String format(Iterable<String> words) { // Iterator<String> upperCamelCased = transform(words.iterator(), // compose(CAPITALISE, LOWERCASE_TRIM)); // return Joiner.on("").join(Lists.newArrayList(upperCamelCased)); // } // } // // static final class UnderscoreSeparatedFormatter implements TargetNameFormatter { // @Override // public String format(Iterable<String> words) { // Iterator<String> upperCamelCased = transform(words.iterator(), LOWERCASE_TRIM); // return Joiner.on("_").join(newArrayList(upperCamelCased)); // } // } // // public abstract String format(Iterable<String> words); // // } // // Path: src/main/java/com/timgroup/karg/reference/Getter.java // public interface Getter<O, T> { // T get(O object); // }
import static java.lang.String.format; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import com.google.common.base.Preconditions; import com.timgroup.karg.naming.TargetName; import com.timgroup.karg.naming.TargetNameFormatter; import com.timgroup.karg.reference.Getter;
/** * */ package com.timgroup.karg.reflection; public class GetterMethod<C, V> implements Getter<C, V>, PropertyMethod { private final Method method; private final String propertyName; public static interface PropertyNameBinder { <C, V> GetterMethod<C, V> ofClass(Class<C> owningClass); } public static PropertyNameBinder forProperty(final String propertyName) { return new PropertyNameBinder() { @Override public <C, V> GetterMethod<C, V> ofClass(Class<C> owningClass) { Method method = ClassInspector.forClass(owningClass).findGetterMethod(propertyName); Preconditions.checkNotNull(method, format("No getter method exists for the property %s", propertyName)); return forMethod(propertyName, method); } }; } public static <C, V> GetterMethod<C, V> forMethod(String propertyName, Method method) { return new GetterMethod<C, V>(propertyName, method); } public static <C, V> GetterMethod<C, V> forMethod(Method method) { return forMethod(getPropertyName(method.getName()), method); } private static String getPropertyName(String methodName) {
// Path: src/main/java/com/timgroup/karg/naming/TargetName.java // public class TargetName { // // public static TargetName fromMethodName(String methodName) { // if (methodName.contains("_")) { // return TargetNameParser.UNDERSCORE_SEPARATED.parse(methodName); // } // return TargetNameParser.CAMEL_CASE.parse(methodName); // } // // private final Iterable<String> words; // // public TargetName(Iterable<String> words) { // this.words = words; // } // // public TargetName prefixedWith(String prefix) { // return new TargetName(Iterables.concat(Lists.newArrayList(prefix), words)); // } // // public TargetName withSuffix(String suffix) { // return new TargetName(Iterables.concat(words, Lists.newArrayList(suffix))); // } // // public boolean hasPrefix(String prefix) { // return prefix.equals(Iterables.getFirst(words, null)); // } // // public TargetName withoutPrefix() { // return new TargetName(Iterables.skip(words, 1)); // } // // public String formatWith(TargetNameFormatter formatter) { // return formatter.format(words); // } // } // // Path: src/main/java/com/timgroup/karg/naming/TargetNameFormatter.java // public interface TargetNameFormatter { // // static final TargetNameFormatter LOWER_CAMEL_CASE = new LowerCamelCaseFormatter(); // static final TargetNameFormatter UPPER_CAMEL_CASE = new UpperCamelCaseFormatter(); // static final TargetNameFormatter UNDERSCORE_SEPARATED = new UnderscoreSeparatedFormatter(); // // static final class LowerCamelCaseFormatter implements TargetNameFormatter { // // @Override // public String format(Iterable<String> words) { // Iterator<String> lowercased = transform(words.iterator(), LOWERCASE_TRIM); // if (!lowercased.hasNext()) { // return ""; // } // Iterator<String> lowerCamelCased = concat(singletonIterator(lowercased.next()), // transform(lowercased, CAPITALISE)); // return Joiner.on("").join(Lists.newArrayList(lowerCamelCased)); // } // } // // static final class UpperCamelCaseFormatter implements TargetNameFormatter { // @Override // public String format(Iterable<String> words) { // Iterator<String> upperCamelCased = transform(words.iterator(), // compose(CAPITALISE, LOWERCASE_TRIM)); // return Joiner.on("").join(Lists.newArrayList(upperCamelCased)); // } // } // // static final class UnderscoreSeparatedFormatter implements TargetNameFormatter { // @Override // public String format(Iterable<String> words) { // Iterator<String> upperCamelCased = transform(words.iterator(), LOWERCASE_TRIM); // return Joiner.on("_").join(newArrayList(upperCamelCased)); // } // } // // public abstract String format(Iterable<String> words); // // } // // Path: src/main/java/com/timgroup/karg/reference/Getter.java // public interface Getter<O, T> { // T get(O object); // } // Path: src/main/java/com/timgroup/karg/reflection/GetterMethod.java import static java.lang.String.format; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import com.google.common.base.Preconditions; import com.timgroup.karg.naming.TargetName; import com.timgroup.karg.naming.TargetNameFormatter; import com.timgroup.karg.reference.Getter; /** * */ package com.timgroup.karg.reflection; public class GetterMethod<C, V> implements Getter<C, V>, PropertyMethod { private final Method method; private final String propertyName; public static interface PropertyNameBinder { <C, V> GetterMethod<C, V> ofClass(Class<C> owningClass); } public static PropertyNameBinder forProperty(final String propertyName) { return new PropertyNameBinder() { @Override public <C, V> GetterMethod<C, V> ofClass(Class<C> owningClass) { Method method = ClassInspector.forClass(owningClass).findGetterMethod(propertyName); Preconditions.checkNotNull(method, format("No getter method exists for the property %s", propertyName)); return forMethod(propertyName, method); } }; } public static <C, V> GetterMethod<C, V> forMethod(String propertyName, Method method) { return new GetterMethod<C, V>(propertyName, method); } public static <C, V> GetterMethod<C, V> forMethod(Method method) { return forMethod(getPropertyName(method.getName()), method); } private static String getPropertyName(String methodName) {
return targetNameWithoutPrefix(methodName).formatWith(TargetNameFormatter.LOWER_CAMEL_CASE);
tim-group/karg
src/main/java/com/timgroup/karg/reflection/GetterMethod.java
// Path: src/main/java/com/timgroup/karg/naming/TargetName.java // public class TargetName { // // public static TargetName fromMethodName(String methodName) { // if (methodName.contains("_")) { // return TargetNameParser.UNDERSCORE_SEPARATED.parse(methodName); // } // return TargetNameParser.CAMEL_CASE.parse(methodName); // } // // private final Iterable<String> words; // // public TargetName(Iterable<String> words) { // this.words = words; // } // // public TargetName prefixedWith(String prefix) { // return new TargetName(Iterables.concat(Lists.newArrayList(prefix), words)); // } // // public TargetName withSuffix(String suffix) { // return new TargetName(Iterables.concat(words, Lists.newArrayList(suffix))); // } // // public boolean hasPrefix(String prefix) { // return prefix.equals(Iterables.getFirst(words, null)); // } // // public TargetName withoutPrefix() { // return new TargetName(Iterables.skip(words, 1)); // } // // public String formatWith(TargetNameFormatter formatter) { // return formatter.format(words); // } // } // // Path: src/main/java/com/timgroup/karg/naming/TargetNameFormatter.java // public interface TargetNameFormatter { // // static final TargetNameFormatter LOWER_CAMEL_CASE = new LowerCamelCaseFormatter(); // static final TargetNameFormatter UPPER_CAMEL_CASE = new UpperCamelCaseFormatter(); // static final TargetNameFormatter UNDERSCORE_SEPARATED = new UnderscoreSeparatedFormatter(); // // static final class LowerCamelCaseFormatter implements TargetNameFormatter { // // @Override // public String format(Iterable<String> words) { // Iterator<String> lowercased = transform(words.iterator(), LOWERCASE_TRIM); // if (!lowercased.hasNext()) { // return ""; // } // Iterator<String> lowerCamelCased = concat(singletonIterator(lowercased.next()), // transform(lowercased, CAPITALISE)); // return Joiner.on("").join(Lists.newArrayList(lowerCamelCased)); // } // } // // static final class UpperCamelCaseFormatter implements TargetNameFormatter { // @Override // public String format(Iterable<String> words) { // Iterator<String> upperCamelCased = transform(words.iterator(), // compose(CAPITALISE, LOWERCASE_TRIM)); // return Joiner.on("").join(Lists.newArrayList(upperCamelCased)); // } // } // // static final class UnderscoreSeparatedFormatter implements TargetNameFormatter { // @Override // public String format(Iterable<String> words) { // Iterator<String> upperCamelCased = transform(words.iterator(), LOWERCASE_TRIM); // return Joiner.on("_").join(newArrayList(upperCamelCased)); // } // } // // public abstract String format(Iterable<String> words); // // } // // Path: src/main/java/com/timgroup/karg/reference/Getter.java // public interface Getter<O, T> { // T get(O object); // }
import static java.lang.String.format; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import com.google.common.base.Preconditions; import com.timgroup.karg.naming.TargetName; import com.timgroup.karg.naming.TargetNameFormatter; import com.timgroup.karg.reference.Getter;
/** * */ package com.timgroup.karg.reflection; public class GetterMethod<C, V> implements Getter<C, V>, PropertyMethod { private final Method method; private final String propertyName; public static interface PropertyNameBinder { <C, V> GetterMethod<C, V> ofClass(Class<C> owningClass); } public static PropertyNameBinder forProperty(final String propertyName) { return new PropertyNameBinder() { @Override public <C, V> GetterMethod<C, V> ofClass(Class<C> owningClass) { Method method = ClassInspector.forClass(owningClass).findGetterMethod(propertyName); Preconditions.checkNotNull(method, format("No getter method exists for the property %s", propertyName)); return forMethod(propertyName, method); } }; } public static <C, V> GetterMethod<C, V> forMethod(String propertyName, Method method) { return new GetterMethod<C, V>(propertyName, method); } public static <C, V> GetterMethod<C, V> forMethod(Method method) { return forMethod(getPropertyName(method.getName()), method); } private static String getPropertyName(String methodName) { return targetNameWithoutPrefix(methodName).formatWith(TargetNameFormatter.LOWER_CAMEL_CASE); }
// Path: src/main/java/com/timgroup/karg/naming/TargetName.java // public class TargetName { // // public static TargetName fromMethodName(String methodName) { // if (methodName.contains("_")) { // return TargetNameParser.UNDERSCORE_SEPARATED.parse(methodName); // } // return TargetNameParser.CAMEL_CASE.parse(methodName); // } // // private final Iterable<String> words; // // public TargetName(Iterable<String> words) { // this.words = words; // } // // public TargetName prefixedWith(String prefix) { // return new TargetName(Iterables.concat(Lists.newArrayList(prefix), words)); // } // // public TargetName withSuffix(String suffix) { // return new TargetName(Iterables.concat(words, Lists.newArrayList(suffix))); // } // // public boolean hasPrefix(String prefix) { // return prefix.equals(Iterables.getFirst(words, null)); // } // // public TargetName withoutPrefix() { // return new TargetName(Iterables.skip(words, 1)); // } // // public String formatWith(TargetNameFormatter formatter) { // return formatter.format(words); // } // } // // Path: src/main/java/com/timgroup/karg/naming/TargetNameFormatter.java // public interface TargetNameFormatter { // // static final TargetNameFormatter LOWER_CAMEL_CASE = new LowerCamelCaseFormatter(); // static final TargetNameFormatter UPPER_CAMEL_CASE = new UpperCamelCaseFormatter(); // static final TargetNameFormatter UNDERSCORE_SEPARATED = new UnderscoreSeparatedFormatter(); // // static final class LowerCamelCaseFormatter implements TargetNameFormatter { // // @Override // public String format(Iterable<String> words) { // Iterator<String> lowercased = transform(words.iterator(), LOWERCASE_TRIM); // if (!lowercased.hasNext()) { // return ""; // } // Iterator<String> lowerCamelCased = concat(singletonIterator(lowercased.next()), // transform(lowercased, CAPITALISE)); // return Joiner.on("").join(Lists.newArrayList(lowerCamelCased)); // } // } // // static final class UpperCamelCaseFormatter implements TargetNameFormatter { // @Override // public String format(Iterable<String> words) { // Iterator<String> upperCamelCased = transform(words.iterator(), // compose(CAPITALISE, LOWERCASE_TRIM)); // return Joiner.on("").join(Lists.newArrayList(upperCamelCased)); // } // } // // static final class UnderscoreSeparatedFormatter implements TargetNameFormatter { // @Override // public String format(Iterable<String> words) { // Iterator<String> upperCamelCased = transform(words.iterator(), LOWERCASE_TRIM); // return Joiner.on("_").join(newArrayList(upperCamelCased)); // } // } // // public abstract String format(Iterable<String> words); // // } // // Path: src/main/java/com/timgroup/karg/reference/Getter.java // public interface Getter<O, T> { // T get(O object); // } // Path: src/main/java/com/timgroup/karg/reflection/GetterMethod.java import static java.lang.String.format; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import com.google.common.base.Preconditions; import com.timgroup.karg.naming.TargetName; import com.timgroup.karg.naming.TargetNameFormatter; import com.timgroup.karg.reference.Getter; /** * */ package com.timgroup.karg.reflection; public class GetterMethod<C, V> implements Getter<C, V>, PropertyMethod { private final Method method; private final String propertyName; public static interface PropertyNameBinder { <C, V> GetterMethod<C, V> ofClass(Class<C> owningClass); } public static PropertyNameBinder forProperty(final String propertyName) { return new PropertyNameBinder() { @Override public <C, V> GetterMethod<C, V> ofClass(Class<C> owningClass) { Method method = ClassInspector.forClass(owningClass).findGetterMethod(propertyName); Preconditions.checkNotNull(method, format("No getter method exists for the property %s", propertyName)); return forMethod(propertyName, method); } }; } public static <C, V> GetterMethod<C, V> forMethod(String propertyName, Method method) { return new GetterMethod<C, V>(propertyName, method); } public static <C, V> GetterMethod<C, V> forMethod(Method method) { return forMethod(getPropertyName(method.getName()), method); } private static String getPropertyName(String methodName) { return targetNameWithoutPrefix(methodName).formatWith(TargetNameFormatter.LOWER_CAMEL_CASE); }
private static TargetName targetNameWithoutPrefix(String methodName) {
tim-group/karg
src/test/java/com/timgroup/karg/keywords/CandidateFunctionRegistryTest.java
// Path: src/main/java/com/timgroup/karg/functions/KeywordFunction.java // public interface KeywordFunction<T> extends Function<KeywordArguments, T> { } // // Path: src/main/java/com/timgroup/karg/multipledispatch/CandidateFunctionRegistry.java // public class CandidateFunctionRegistry<T> { // // private final List<CandidateFunction<T>> candidates = newArrayList(); // // public static interface MatchBuilder<T> { // void with(Function<KeywordArguments, T> function); // } // // public MatchBuilder<T> match(final Predicate<KeywordArguments> predicate) { // return new MatchBuilder<T>() { // @Override // public void with(Function<KeywordArguments, T> function) { // candidates.add(new CandidateFunction<T>(predicate, function)); // } // }; // } // // public CandidateFunction<T> findCandidateMatching(KeywordArguments parameters) { // try { // return Iterables.find(candidates, matchesParameters(parameters)); // } catch (NoSuchElementException e) { // throw new UnsupportedOperationException("No candidate function was found matching the supplied parameters."); // } // } // // private Predicate<CandidateFunction<T>> matchesParameters(final KeywordArguments parameters) { // return new Predicate<CandidateFunction<T>>() { // @Override public boolean apply(CandidateFunction<T> candidate) { // return candidate.matches(parameters); // } // }; // } // }
import org.jmock.Expectations; import org.jmock.Mockery; import org.junit.Test; import com.google.common.base.Predicate; import com.timgroup.karg.functions.KeywordFunction; import com.timgroup.karg.multipledispatch.CandidateFunctionRegistry;
package com.timgroup.karg.keywords; public class CandidateFunctionRegistryTest { private final Mockery context = new Mockery(); @SuppressWarnings("unchecked")
// Path: src/main/java/com/timgroup/karg/functions/KeywordFunction.java // public interface KeywordFunction<T> extends Function<KeywordArguments, T> { } // // Path: src/main/java/com/timgroup/karg/multipledispatch/CandidateFunctionRegistry.java // public class CandidateFunctionRegistry<T> { // // private final List<CandidateFunction<T>> candidates = newArrayList(); // // public static interface MatchBuilder<T> { // void with(Function<KeywordArguments, T> function); // } // // public MatchBuilder<T> match(final Predicate<KeywordArguments> predicate) { // return new MatchBuilder<T>() { // @Override // public void with(Function<KeywordArguments, T> function) { // candidates.add(new CandidateFunction<T>(predicate, function)); // } // }; // } // // public CandidateFunction<T> findCandidateMatching(KeywordArguments parameters) { // try { // return Iterables.find(candidates, matchesParameters(parameters)); // } catch (NoSuchElementException e) { // throw new UnsupportedOperationException("No candidate function was found matching the supplied parameters."); // } // } // // private Predicate<CandidateFunction<T>> matchesParameters(final KeywordArguments parameters) { // return new Predicate<CandidateFunction<T>>() { // @Override public boolean apply(CandidateFunction<T> candidate) { // return candidate.matches(parameters); // } // }; // } // } // Path: src/test/java/com/timgroup/karg/keywords/CandidateFunctionRegistryTest.java import org.jmock.Expectations; import org.jmock.Mockery; import org.junit.Test; import com.google.common.base.Predicate; import com.timgroup.karg.functions.KeywordFunction; import com.timgroup.karg.multipledispatch.CandidateFunctionRegistry; package com.timgroup.karg.keywords; public class CandidateFunctionRegistryTest { private final Mockery context = new Mockery(); @SuppressWarnings("unchecked")
private final KeywordFunction<String> function = context.mock(KeywordFunction.class);
tim-group/karg
src/test/java/com/timgroup/karg/keywords/CandidateFunctionRegistryTest.java
// Path: src/main/java/com/timgroup/karg/functions/KeywordFunction.java // public interface KeywordFunction<T> extends Function<KeywordArguments, T> { } // // Path: src/main/java/com/timgroup/karg/multipledispatch/CandidateFunctionRegistry.java // public class CandidateFunctionRegistry<T> { // // private final List<CandidateFunction<T>> candidates = newArrayList(); // // public static interface MatchBuilder<T> { // void with(Function<KeywordArguments, T> function); // } // // public MatchBuilder<T> match(final Predicate<KeywordArguments> predicate) { // return new MatchBuilder<T>() { // @Override // public void with(Function<KeywordArguments, T> function) { // candidates.add(new CandidateFunction<T>(predicate, function)); // } // }; // } // // public CandidateFunction<T> findCandidateMatching(KeywordArguments parameters) { // try { // return Iterables.find(candidates, matchesParameters(parameters)); // } catch (NoSuchElementException e) { // throw new UnsupportedOperationException("No candidate function was found matching the supplied parameters."); // } // } // // private Predicate<CandidateFunction<T>> matchesParameters(final KeywordArguments parameters) { // return new Predicate<CandidateFunction<T>>() { // @Override public boolean apply(CandidateFunction<T> candidate) { // return candidate.matches(parameters); // } // }; // } // }
import org.jmock.Expectations; import org.jmock.Mockery; import org.junit.Test; import com.google.common.base.Predicate; import com.timgroup.karg.functions.KeywordFunction; import com.timgroup.karg.multipledispatch.CandidateFunctionRegistry;
package com.timgroup.karg.keywords; public class CandidateFunctionRegistryTest { private final Mockery context = new Mockery(); @SuppressWarnings("unchecked") private final KeywordFunction<String> function = context.mock(KeywordFunction.class); @SuppressWarnings("unchecked") private final Predicate<KeywordArguments> predicate = context.mock(Predicate.class); @Test public void registers_a_function_bound_to_a_predicate() { final KeywordArguments arguments = KeywordArguments.empty();
// Path: src/main/java/com/timgroup/karg/functions/KeywordFunction.java // public interface KeywordFunction<T> extends Function<KeywordArguments, T> { } // // Path: src/main/java/com/timgroup/karg/multipledispatch/CandidateFunctionRegistry.java // public class CandidateFunctionRegistry<T> { // // private final List<CandidateFunction<T>> candidates = newArrayList(); // // public static interface MatchBuilder<T> { // void with(Function<KeywordArguments, T> function); // } // // public MatchBuilder<T> match(final Predicate<KeywordArguments> predicate) { // return new MatchBuilder<T>() { // @Override // public void with(Function<KeywordArguments, T> function) { // candidates.add(new CandidateFunction<T>(predicate, function)); // } // }; // } // // public CandidateFunction<T> findCandidateMatching(KeywordArguments parameters) { // try { // return Iterables.find(candidates, matchesParameters(parameters)); // } catch (NoSuchElementException e) { // throw new UnsupportedOperationException("No candidate function was found matching the supplied parameters."); // } // } // // private Predicate<CandidateFunction<T>> matchesParameters(final KeywordArguments parameters) { // return new Predicate<CandidateFunction<T>>() { // @Override public boolean apply(CandidateFunction<T> candidate) { // return candidate.matches(parameters); // } // }; // } // } // Path: src/test/java/com/timgroup/karg/keywords/CandidateFunctionRegistryTest.java import org.jmock.Expectations; import org.jmock.Mockery; import org.junit.Test; import com.google.common.base.Predicate; import com.timgroup.karg.functions.KeywordFunction; import com.timgroup.karg.multipledispatch.CandidateFunctionRegistry; package com.timgroup.karg.keywords; public class CandidateFunctionRegistryTest { private final Mockery context = new Mockery(); @SuppressWarnings("unchecked") private final KeywordFunction<String> function = context.mock(KeywordFunction.class); @SuppressWarnings("unchecked") private final Predicate<KeywordArguments> predicate = context.mock(Predicate.class); @Test public void registers_a_function_bound_to_a_predicate() { final KeywordArguments arguments = KeywordArguments.empty();
CandidateFunctionRegistry<String> registry = new CandidateFunctionRegistry<String>();
tim-group/karg
src/test/java/com/timgroup/karg/reflection/ReflectiveAccessorFactoryTest.java
// Path: src/main/java/com/timgroup/karg/reference/Getter.java // public interface Getter<O, T> { // T get(O object); // } // // Path: src/main/java/com/timgroup/karg/reference/Setter.java // public interface Setter<O, T> { // T set(O object, T newValue); // }
import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.is; import org.junit.Test; import com.timgroup.karg.reference.Getter; import com.timgroup.karg.reference.Setter;
package com.timgroup.karg.reflection; public class ReflectiveAccessorFactoryTest { public static class TestClass { public final String bar = "bar-value"; private String encapsulated = ""; public String getBaz() { return encapsulated; } public void setBaz(String newValue) { encapsulated = newValue; } } private final TestClass testInstance = new TestClass(); @Test(expected=Exception.class) public void throws_an_exception_if_asked_for_a_getter_that_does_not_exist() { ReflectiveAccessorFactory<TestClass> fac = ReflectiveAccessorFactory.forClass(TestClass.class); fac.getGetter("foo"); } @Test public void returns_a_getter_for_a_readable_field() { ReflectiveAccessorFactory<TestClass> fac = ReflectiveAccessorFactory.forClass(TestClass.class);
// Path: src/main/java/com/timgroup/karg/reference/Getter.java // public interface Getter<O, T> { // T get(O object); // } // // Path: src/main/java/com/timgroup/karg/reference/Setter.java // public interface Setter<O, T> { // T set(O object, T newValue); // } // Path: src/test/java/com/timgroup/karg/reflection/ReflectiveAccessorFactoryTest.java import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.is; import org.junit.Test; import com.timgroup.karg.reference.Getter; import com.timgroup.karg.reference.Setter; package com.timgroup.karg.reflection; public class ReflectiveAccessorFactoryTest { public static class TestClass { public final String bar = "bar-value"; private String encapsulated = ""; public String getBaz() { return encapsulated; } public void setBaz(String newValue) { encapsulated = newValue; } } private final TestClass testInstance = new TestClass(); @Test(expected=Exception.class) public void throws_an_exception_if_asked_for_a_getter_that_does_not_exist() { ReflectiveAccessorFactory<TestClass> fac = ReflectiveAccessorFactory.forClass(TestClass.class); fac.getGetter("foo"); } @Test public void returns_a_getter_for_a_readable_field() { ReflectiveAccessorFactory<TestClass> fac = ReflectiveAccessorFactory.forClass(TestClass.class);
Getter<TestClass, String> getter = fac.getGetter("bar");
tim-group/karg
src/test/java/com/timgroup/karg/reflection/ReflectiveAccessorFactoryTest.java
// Path: src/main/java/com/timgroup/karg/reference/Getter.java // public interface Getter<O, T> { // T get(O object); // } // // Path: src/main/java/com/timgroup/karg/reference/Setter.java // public interface Setter<O, T> { // T set(O object, T newValue); // }
import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.is; import org.junit.Test; import com.timgroup.karg.reference.Getter; import com.timgroup.karg.reference.Setter;
} public void setBaz(String newValue) { encapsulated = newValue; } } private final TestClass testInstance = new TestClass(); @Test(expected=Exception.class) public void throws_an_exception_if_asked_for_a_getter_that_does_not_exist() { ReflectiveAccessorFactory<TestClass> fac = ReflectiveAccessorFactory.forClass(TestClass.class); fac.getGetter("foo"); } @Test public void returns_a_getter_for_a_readable_field() { ReflectiveAccessorFactory<TestClass> fac = ReflectiveAccessorFactory.forClass(TestClass.class); Getter<TestClass, String> getter = fac.getGetter("bar"); assertThat(getter.get(testInstance), is("bar-value")); } @Test(expected=Exception.class) public void throws_an_exception_if_asked_for_a_setter_that_does_not_exist() { ReflectiveAccessorFactory<TestClass> fac = ReflectiveAccessorFactory.forClass(TestClass.class); fac.getSetter("bar"); } @Test public void returns_a_setter_for_a_writable_field() { ReflectiveAccessorFactory<TestClass> fac = ReflectiveAccessorFactory.forClass(TestClass.class);
// Path: src/main/java/com/timgroup/karg/reference/Getter.java // public interface Getter<O, T> { // T get(O object); // } // // Path: src/main/java/com/timgroup/karg/reference/Setter.java // public interface Setter<O, T> { // T set(O object, T newValue); // } // Path: src/test/java/com/timgroup/karg/reflection/ReflectiveAccessorFactoryTest.java import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.is; import org.junit.Test; import com.timgroup.karg.reference.Getter; import com.timgroup.karg.reference.Setter; } public void setBaz(String newValue) { encapsulated = newValue; } } private final TestClass testInstance = new TestClass(); @Test(expected=Exception.class) public void throws_an_exception_if_asked_for_a_getter_that_does_not_exist() { ReflectiveAccessorFactory<TestClass> fac = ReflectiveAccessorFactory.forClass(TestClass.class); fac.getGetter("foo"); } @Test public void returns_a_getter_for_a_readable_field() { ReflectiveAccessorFactory<TestClass> fac = ReflectiveAccessorFactory.forClass(TestClass.class); Getter<TestClass, String> getter = fac.getGetter("bar"); assertThat(getter.get(testInstance), is("bar-value")); } @Test(expected=Exception.class) public void throws_an_exception_if_asked_for_a_setter_that_does_not_exist() { ReflectiveAccessorFactory<TestClass> fac = ReflectiveAccessorFactory.forClass(TestClass.class); fac.getSetter("bar"); } @Test public void returns_a_setter_for_a_writable_field() { ReflectiveAccessorFactory<TestClass> fac = ReflectiveAccessorFactory.forClass(TestClass.class);
Setter<TestClass, String> setter = fac.getSetter("baz");
tim-group/karg
src/main/java/com/timgroup/karg/reflection/ReflectiveAccessorFactory.java
// Path: src/main/java/com/timgroup/karg/reference/Getter.java // public interface Getter<O, T> { // T get(O object); // } // // Path: src/main/java/com/timgroup/karg/reference/Lens.java // public interface Lens<O, T> extends Getter<O, T>, Setter<O, T> { } // // Path: src/main/java/com/timgroup/karg/reference/Setter.java // public interface Setter<O, T> { // T set(O object, T newValue); // }
import com.google.common.base.Preconditions; import com.timgroup.karg.reference.Getter; import com.timgroup.karg.reference.Lens; import com.timgroup.karg.reference.Setter;
package com.timgroup.karg.reflection; public class ReflectiveAccessorFactory<O> { private final AccessorCatalogue<O> catalogue; public static <O> ReflectiveAccessorFactory<O> forClass(Class<O> targetClass) { return new ReflectiveAccessorFactory<O>(targetClass); } private ReflectiveAccessorFactory(Class<O> targetClass) { catalogue = AccessorCatalogue.forClass(targetClass); }
// Path: src/main/java/com/timgroup/karg/reference/Getter.java // public interface Getter<O, T> { // T get(O object); // } // // Path: src/main/java/com/timgroup/karg/reference/Lens.java // public interface Lens<O, T> extends Getter<O, T>, Setter<O, T> { } // // Path: src/main/java/com/timgroup/karg/reference/Setter.java // public interface Setter<O, T> { // T set(O object, T newValue); // } // Path: src/main/java/com/timgroup/karg/reflection/ReflectiveAccessorFactory.java import com.google.common.base.Preconditions; import com.timgroup.karg.reference.Getter; import com.timgroup.karg.reference.Lens; import com.timgroup.karg.reference.Setter; package com.timgroup.karg.reflection; public class ReflectiveAccessorFactory<O> { private final AccessorCatalogue<O> catalogue; public static <O> ReflectiveAccessorFactory<O> forClass(Class<O> targetClass) { return new ReflectiveAccessorFactory<O>(targetClass); } private ReflectiveAccessorFactory(Class<O> targetClass) { catalogue = AccessorCatalogue.forClass(targetClass); }
public <T> Lens<O, T> getLens(final String propertyName) {
tim-group/karg
src/main/java/com/timgroup/karg/reflection/ReflectiveAccessorFactory.java
// Path: src/main/java/com/timgroup/karg/reference/Getter.java // public interface Getter<O, T> { // T get(O object); // } // // Path: src/main/java/com/timgroup/karg/reference/Lens.java // public interface Lens<O, T> extends Getter<O, T>, Setter<O, T> { } // // Path: src/main/java/com/timgroup/karg/reference/Setter.java // public interface Setter<O, T> { // T set(O object, T newValue); // }
import com.google.common.base.Preconditions; import com.timgroup.karg.reference.Getter; import com.timgroup.karg.reference.Lens; import com.timgroup.karg.reference.Setter;
package com.timgroup.karg.reflection; public class ReflectiveAccessorFactory<O> { private final AccessorCatalogue<O> catalogue; public static <O> ReflectiveAccessorFactory<O> forClass(Class<O> targetClass) { return new ReflectiveAccessorFactory<O>(targetClass); } private ReflectiveAccessorFactory(Class<O> targetClass) { catalogue = AccessorCatalogue.forClass(targetClass); } public <T> Lens<O, T> getLens(final String propertyName) { Lens<O, T> lens = catalogue.getAttribute(propertyName); Preconditions.checkNotNull(lens, "No writable property or field \"%s\"", propertyName); return lens; }
// Path: src/main/java/com/timgroup/karg/reference/Getter.java // public interface Getter<O, T> { // T get(O object); // } // // Path: src/main/java/com/timgroup/karg/reference/Lens.java // public interface Lens<O, T> extends Getter<O, T>, Setter<O, T> { } // // Path: src/main/java/com/timgroup/karg/reference/Setter.java // public interface Setter<O, T> { // T set(O object, T newValue); // } // Path: src/main/java/com/timgroup/karg/reflection/ReflectiveAccessorFactory.java import com.google.common.base.Preconditions; import com.timgroup.karg.reference.Getter; import com.timgroup.karg.reference.Lens; import com.timgroup.karg.reference.Setter; package com.timgroup.karg.reflection; public class ReflectiveAccessorFactory<O> { private final AccessorCatalogue<O> catalogue; public static <O> ReflectiveAccessorFactory<O> forClass(Class<O> targetClass) { return new ReflectiveAccessorFactory<O>(targetClass); } private ReflectiveAccessorFactory(Class<O> targetClass) { catalogue = AccessorCatalogue.forClass(targetClass); } public <T> Lens<O, T> getLens(final String propertyName) { Lens<O, T> lens = catalogue.getAttribute(propertyName); Preconditions.checkNotNull(lens, "No writable property or field \"%s\"", propertyName); return lens; }
public <T> Getter<O, T> getGetter(String propertyName) {
tim-group/karg
src/main/java/com/timgroup/karg/reflection/ReflectiveAccessorFactory.java
// Path: src/main/java/com/timgroup/karg/reference/Getter.java // public interface Getter<O, T> { // T get(O object); // } // // Path: src/main/java/com/timgroup/karg/reference/Lens.java // public interface Lens<O, T> extends Getter<O, T>, Setter<O, T> { } // // Path: src/main/java/com/timgroup/karg/reference/Setter.java // public interface Setter<O, T> { // T set(O object, T newValue); // }
import com.google.common.base.Preconditions; import com.timgroup.karg.reference.Getter; import com.timgroup.karg.reference.Lens; import com.timgroup.karg.reference.Setter;
package com.timgroup.karg.reflection; public class ReflectiveAccessorFactory<O> { private final AccessorCatalogue<O> catalogue; public static <O> ReflectiveAccessorFactory<O> forClass(Class<O> targetClass) { return new ReflectiveAccessorFactory<O>(targetClass); } private ReflectiveAccessorFactory(Class<O> targetClass) { catalogue = AccessorCatalogue.forClass(targetClass); } public <T> Lens<O, T> getLens(final String propertyName) { Lens<O, T> lens = catalogue.getAttribute(propertyName); Preconditions.checkNotNull(lens, "No writable property or field \"%s\"", propertyName); return lens; } public <T> Getter<O, T> getGetter(String propertyName) { Getter<O, T> getter = catalogue.getReadOnlyAttribute(propertyName); Preconditions.checkNotNull(getter, "No readable property or field \"%s\"", propertyName); return getter; } @SuppressWarnings("unchecked")
// Path: src/main/java/com/timgroup/karg/reference/Getter.java // public interface Getter<O, T> { // T get(O object); // } // // Path: src/main/java/com/timgroup/karg/reference/Lens.java // public interface Lens<O, T> extends Getter<O, T>, Setter<O, T> { } // // Path: src/main/java/com/timgroup/karg/reference/Setter.java // public interface Setter<O, T> { // T set(O object, T newValue); // } // Path: src/main/java/com/timgroup/karg/reflection/ReflectiveAccessorFactory.java import com.google.common.base.Preconditions; import com.timgroup.karg.reference.Getter; import com.timgroup.karg.reference.Lens; import com.timgroup.karg.reference.Setter; package com.timgroup.karg.reflection; public class ReflectiveAccessorFactory<O> { private final AccessorCatalogue<O> catalogue; public static <O> ReflectiveAccessorFactory<O> forClass(Class<O> targetClass) { return new ReflectiveAccessorFactory<O>(targetClass); } private ReflectiveAccessorFactory(Class<O> targetClass) { catalogue = AccessorCatalogue.forClass(targetClass); } public <T> Lens<O, T> getLens(final String propertyName) { Lens<O, T> lens = catalogue.getAttribute(propertyName); Preconditions.checkNotNull(lens, "No writable property or field \"%s\"", propertyName); return lens; } public <T> Getter<O, T> getGetter(String propertyName) { Getter<O, T> getter = catalogue.getReadOnlyAttribute(propertyName); Preconditions.checkNotNull(getter, "No readable property or field \"%s\"", propertyName); return getter; } @SuppressWarnings("unchecked")
public <T> Setter<O, T> getSetter(String propertyName) {
tim-group/karg
src/main/java/com/timgroup/karg/reflection/AccessorCatalogue.java
// Path: src/main/java/com/timgroup/karg/reference/Getter.java // public interface Getter<O, T> { // T get(O object); // } // // Path: src/main/java/com/timgroup/karg/reference/Lens.java // public interface Lens<O, T> extends Getter<O, T>, Setter<O, T> { }
import java.util.Map; import java.util.Set; import com.google.common.base.Predicate; import com.google.common.base.Predicates; import com.google.common.collect.ImmutableMap; import com.google.common.collect.Maps; import com.google.common.collect.Sets; import com.timgroup.karg.reference.Getter; import com.timgroup.karg.reference.Lens;
package com.timgroup.karg.reflection; public class AccessorCatalogue<O> { private static final Predicate<Accessor<?, ?>> isMutable = new Predicate<Accessor<?, ?>>() { @Override public boolean apply(Accessor<?, ?> accessor) { return accessor.isMutable(); } }; public static <O> AccessorCatalogue<O> forClass(Class<O> targetClass) { Map<String, Accessor<O, ?>> fieldAccessors = FieldAccessorFinder.forClass(targetClass).find(); Map<String, Accessor<O, ?>> propertyAccessors = PropertyAccessorFinder.forClass(targetClass).find(); Set<String> fieldOnlyAccessorNames = Sets.difference(fieldAccessors.keySet(), propertyAccessors.keySet()); ImmutableMap<String, Accessor<O, ?>> mergedAccessors = ImmutableMap.<String, Accessor<O, ?>>builder() .putAll(propertyAccessors) .putAll(Maps.filterKeys(fieldAccessors, Predicates.in(fieldOnlyAccessorNames))) .build(); return new AccessorCatalogue<O>(mergedAccessors); } private ImmutableMap<String, Accessor<O, ?>> getters; private ImmutableMap<String, Accessor<O, ?>> lenses; private AccessorCatalogue(Map<String, Accessor<O, ?>> accessors) { lenses = ImmutableMap.<String, Accessor<O, ?>>builder().putAll(Maps.filterValues(accessors, isMutable)).build(); getters = ImmutableMap.<String, Accessor<O, ?>>builder().putAll(accessors).build(); } public ImmutableMap<String, Accessor<O, ?>> readOnlyAttributes() { return getters; } public ImmutableMap<String, Accessor<O, ?>> allAttributes() { return lenses; } @SuppressWarnings("unchecked")
// Path: src/main/java/com/timgroup/karg/reference/Getter.java // public interface Getter<O, T> { // T get(O object); // } // // Path: src/main/java/com/timgroup/karg/reference/Lens.java // public interface Lens<O, T> extends Getter<O, T>, Setter<O, T> { } // Path: src/main/java/com/timgroup/karg/reflection/AccessorCatalogue.java import java.util.Map; import java.util.Set; import com.google.common.base.Predicate; import com.google.common.base.Predicates; import com.google.common.collect.ImmutableMap; import com.google.common.collect.Maps; import com.google.common.collect.Sets; import com.timgroup.karg.reference.Getter; import com.timgroup.karg.reference.Lens; package com.timgroup.karg.reflection; public class AccessorCatalogue<O> { private static final Predicate<Accessor<?, ?>> isMutable = new Predicate<Accessor<?, ?>>() { @Override public boolean apply(Accessor<?, ?> accessor) { return accessor.isMutable(); } }; public static <O> AccessorCatalogue<O> forClass(Class<O> targetClass) { Map<String, Accessor<O, ?>> fieldAccessors = FieldAccessorFinder.forClass(targetClass).find(); Map<String, Accessor<O, ?>> propertyAccessors = PropertyAccessorFinder.forClass(targetClass).find(); Set<String> fieldOnlyAccessorNames = Sets.difference(fieldAccessors.keySet(), propertyAccessors.keySet()); ImmutableMap<String, Accessor<O, ?>> mergedAccessors = ImmutableMap.<String, Accessor<O, ?>>builder() .putAll(propertyAccessors) .putAll(Maps.filterKeys(fieldAccessors, Predicates.in(fieldOnlyAccessorNames))) .build(); return new AccessorCatalogue<O>(mergedAccessors); } private ImmutableMap<String, Accessor<O, ?>> getters; private ImmutableMap<String, Accessor<O, ?>> lenses; private AccessorCatalogue(Map<String, Accessor<O, ?>> accessors) { lenses = ImmutableMap.<String, Accessor<O, ?>>builder().putAll(Maps.filterValues(accessors, isMutable)).build(); getters = ImmutableMap.<String, Accessor<O, ?>>builder().putAll(accessors).build(); } public ImmutableMap<String, Accessor<O, ?>> readOnlyAttributes() { return getters; } public ImmutableMap<String, Accessor<O, ?>> allAttributes() { return lenses; } @SuppressWarnings("unchecked")
public <T> Lens<O, T> getAttribute(String name) {
tim-group/karg
src/main/java/com/timgroup/karg/reflection/AccessorCatalogue.java
// Path: src/main/java/com/timgroup/karg/reference/Getter.java // public interface Getter<O, T> { // T get(O object); // } // // Path: src/main/java/com/timgroup/karg/reference/Lens.java // public interface Lens<O, T> extends Getter<O, T>, Setter<O, T> { }
import java.util.Map; import java.util.Set; import com.google.common.base.Predicate; import com.google.common.base.Predicates; import com.google.common.collect.ImmutableMap; import com.google.common.collect.Maps; import com.google.common.collect.Sets; import com.timgroup.karg.reference.Getter; import com.timgroup.karg.reference.Lens;
ImmutableMap<String, Accessor<O, ?>> mergedAccessors = ImmutableMap.<String, Accessor<O, ?>>builder() .putAll(propertyAccessors) .putAll(Maps.filterKeys(fieldAccessors, Predicates.in(fieldOnlyAccessorNames))) .build(); return new AccessorCatalogue<O>(mergedAccessors); } private ImmutableMap<String, Accessor<O, ?>> getters; private ImmutableMap<String, Accessor<O, ?>> lenses; private AccessorCatalogue(Map<String, Accessor<O, ?>> accessors) { lenses = ImmutableMap.<String, Accessor<O, ?>>builder().putAll(Maps.filterValues(accessors, isMutable)).build(); getters = ImmutableMap.<String, Accessor<O, ?>>builder().putAll(accessors).build(); } public ImmutableMap<String, Accessor<O, ?>> readOnlyAttributes() { return getters; } public ImmutableMap<String, Accessor<O, ?>> allAttributes() { return lenses; } @SuppressWarnings("unchecked") public <T> Lens<O, T> getAttribute(String name) { return (Lens<O, T>) lenses.get(name); } @SuppressWarnings("unchecked")
// Path: src/main/java/com/timgroup/karg/reference/Getter.java // public interface Getter<O, T> { // T get(O object); // } // // Path: src/main/java/com/timgroup/karg/reference/Lens.java // public interface Lens<O, T> extends Getter<O, T>, Setter<O, T> { } // Path: src/main/java/com/timgroup/karg/reflection/AccessorCatalogue.java import java.util.Map; import java.util.Set; import com.google.common.base.Predicate; import com.google.common.base.Predicates; import com.google.common.collect.ImmutableMap; import com.google.common.collect.Maps; import com.google.common.collect.Sets; import com.timgroup.karg.reference.Getter; import com.timgroup.karg.reference.Lens; ImmutableMap<String, Accessor<O, ?>> mergedAccessors = ImmutableMap.<String, Accessor<O, ?>>builder() .putAll(propertyAccessors) .putAll(Maps.filterKeys(fieldAccessors, Predicates.in(fieldOnlyAccessorNames))) .build(); return new AccessorCatalogue<O>(mergedAccessors); } private ImmutableMap<String, Accessor<O, ?>> getters; private ImmutableMap<String, Accessor<O, ?>> lenses; private AccessorCatalogue(Map<String, Accessor<O, ?>> accessors) { lenses = ImmutableMap.<String, Accessor<O, ?>>builder().putAll(Maps.filterValues(accessors, isMutable)).build(); getters = ImmutableMap.<String, Accessor<O, ?>>builder().putAll(accessors).build(); } public ImmutableMap<String, Accessor<O, ?>> readOnlyAttributes() { return getters; } public ImmutableMap<String, Accessor<O, ?>> allAttributes() { return lenses; } @SuppressWarnings("unchecked") public <T> Lens<O, T> getAttribute(String name) { return (Lens<O, T>) lenses.get(name); } @SuppressWarnings("unchecked")
public <T> Getter<O, T> getReadOnlyAttribute(String name) {
tim-group/karg
src/main/java/com/timgroup/karg/naming/TargetNameFormatter.java
// Path: src/main/java/com/timgroup/karg/naming/StringFunctions.java // public static final Function<String, String> CAPITALISE = new Function<String, String>() { // @Override // public String apply(String arg0) { // switch(arg0.length()) { // case 0: return ""; // case 1: return arg0.toUpperCase(); // default: return arg0.substring(0, 1).toUpperCase() + arg0.substring(1); // } // } // }; // // Path: src/main/java/com/timgroup/karg/naming/StringFunctions.java // public static final Function<String, String> LOWERCASE_TRIM = Functions.compose(LOWERCASE, TRIM);
import java.util.Iterator; import com.google.common.base.Joiner; import com.google.common.collect.Lists; import static com.google.common.base.Functions.compose; import static com.google.common.collect.Iterators.concat; import static com.google.common.collect.Iterators.singletonIterator; import static com.google.common.collect.Iterators.transform; import static com.google.common.collect.Lists.newArrayList; import static com.timgroup.karg.naming.StringFunctions.CAPITALISE; import static com.timgroup.karg.naming.StringFunctions.LOWERCASE_TRIM;
package com.timgroup.karg.naming; public interface TargetNameFormatter { static final TargetNameFormatter LOWER_CAMEL_CASE = new LowerCamelCaseFormatter(); static final TargetNameFormatter UPPER_CAMEL_CASE = new UpperCamelCaseFormatter(); static final TargetNameFormatter UNDERSCORE_SEPARATED = new UnderscoreSeparatedFormatter(); static final class LowerCamelCaseFormatter implements TargetNameFormatter { @Override public String format(Iterable<String> words) {
// Path: src/main/java/com/timgroup/karg/naming/StringFunctions.java // public static final Function<String, String> CAPITALISE = new Function<String, String>() { // @Override // public String apply(String arg0) { // switch(arg0.length()) { // case 0: return ""; // case 1: return arg0.toUpperCase(); // default: return arg0.substring(0, 1).toUpperCase() + arg0.substring(1); // } // } // }; // // Path: src/main/java/com/timgroup/karg/naming/StringFunctions.java // public static final Function<String, String> LOWERCASE_TRIM = Functions.compose(LOWERCASE, TRIM); // Path: src/main/java/com/timgroup/karg/naming/TargetNameFormatter.java import java.util.Iterator; import com.google.common.base.Joiner; import com.google.common.collect.Lists; import static com.google.common.base.Functions.compose; import static com.google.common.collect.Iterators.concat; import static com.google.common.collect.Iterators.singletonIterator; import static com.google.common.collect.Iterators.transform; import static com.google.common.collect.Lists.newArrayList; import static com.timgroup.karg.naming.StringFunctions.CAPITALISE; import static com.timgroup.karg.naming.StringFunctions.LOWERCASE_TRIM; package com.timgroup.karg.naming; public interface TargetNameFormatter { static final TargetNameFormatter LOWER_CAMEL_CASE = new LowerCamelCaseFormatter(); static final TargetNameFormatter UPPER_CAMEL_CASE = new UpperCamelCaseFormatter(); static final TargetNameFormatter UNDERSCORE_SEPARATED = new UnderscoreSeparatedFormatter(); static final class LowerCamelCaseFormatter implements TargetNameFormatter { @Override public String format(Iterable<String> words) {
Iterator<String> lowercased = transform(words.iterator(), LOWERCASE_TRIM);
tim-group/karg
src/main/java/com/timgroup/karg/naming/TargetNameFormatter.java
// Path: src/main/java/com/timgroup/karg/naming/StringFunctions.java // public static final Function<String, String> CAPITALISE = new Function<String, String>() { // @Override // public String apply(String arg0) { // switch(arg0.length()) { // case 0: return ""; // case 1: return arg0.toUpperCase(); // default: return arg0.substring(0, 1).toUpperCase() + arg0.substring(1); // } // } // }; // // Path: src/main/java/com/timgroup/karg/naming/StringFunctions.java // public static final Function<String, String> LOWERCASE_TRIM = Functions.compose(LOWERCASE, TRIM);
import java.util.Iterator; import com.google.common.base.Joiner; import com.google.common.collect.Lists; import static com.google.common.base.Functions.compose; import static com.google.common.collect.Iterators.concat; import static com.google.common.collect.Iterators.singletonIterator; import static com.google.common.collect.Iterators.transform; import static com.google.common.collect.Lists.newArrayList; import static com.timgroup.karg.naming.StringFunctions.CAPITALISE; import static com.timgroup.karg.naming.StringFunctions.LOWERCASE_TRIM;
package com.timgroup.karg.naming; public interface TargetNameFormatter { static final TargetNameFormatter LOWER_CAMEL_CASE = new LowerCamelCaseFormatter(); static final TargetNameFormatter UPPER_CAMEL_CASE = new UpperCamelCaseFormatter(); static final TargetNameFormatter UNDERSCORE_SEPARATED = new UnderscoreSeparatedFormatter(); static final class LowerCamelCaseFormatter implements TargetNameFormatter { @Override public String format(Iterable<String> words) { Iterator<String> lowercased = transform(words.iterator(), LOWERCASE_TRIM); if (!lowercased.hasNext()) { return ""; } Iterator<String> lowerCamelCased = concat(singletonIterator(lowercased.next()),
// Path: src/main/java/com/timgroup/karg/naming/StringFunctions.java // public static final Function<String, String> CAPITALISE = new Function<String, String>() { // @Override // public String apply(String arg0) { // switch(arg0.length()) { // case 0: return ""; // case 1: return arg0.toUpperCase(); // default: return arg0.substring(0, 1).toUpperCase() + arg0.substring(1); // } // } // }; // // Path: src/main/java/com/timgroup/karg/naming/StringFunctions.java // public static final Function<String, String> LOWERCASE_TRIM = Functions.compose(LOWERCASE, TRIM); // Path: src/main/java/com/timgroup/karg/naming/TargetNameFormatter.java import java.util.Iterator; import com.google.common.base.Joiner; import com.google.common.collect.Lists; import static com.google.common.base.Functions.compose; import static com.google.common.collect.Iterators.concat; import static com.google.common.collect.Iterators.singletonIterator; import static com.google.common.collect.Iterators.transform; import static com.google.common.collect.Lists.newArrayList; import static com.timgroup.karg.naming.StringFunctions.CAPITALISE; import static com.timgroup.karg.naming.StringFunctions.LOWERCASE_TRIM; package com.timgroup.karg.naming; public interface TargetNameFormatter { static final TargetNameFormatter LOWER_CAMEL_CASE = new LowerCamelCaseFormatter(); static final TargetNameFormatter UPPER_CAMEL_CASE = new UpperCamelCaseFormatter(); static final TargetNameFormatter UNDERSCORE_SEPARATED = new UnderscoreSeparatedFormatter(); static final class LowerCamelCaseFormatter implements TargetNameFormatter { @Override public String format(Iterable<String> words) { Iterator<String> lowercased = transform(words.iterator(), LOWERCASE_TRIM); if (!lowercased.hasNext()) { return ""; } Iterator<String> lowerCamelCased = concat(singletonIterator(lowercased.next()),
transform(lowercased, CAPITALISE));
tim-group/karg
src/main/java/com/timgroup/karg/reflection/ClassInspector.java
// Path: src/main/java/com/timgroup/karg/naming/StringFunctions.java // public final class StringFunctions { // // private StringFunctions() { } // // public static final Function<String, String> TRIM = new Function<String, String>() { // @Override // public String apply(String arg0) { // return arg0.trim(); // } // }; // // public static final Function<String, String> LOWERCASE = new Function<String, String>() { // @Override // public String apply(String arg0) { // return arg0.toLowerCase(); // } // }; // // public static final Function<String, String> LOWERCASE_TRIM = Functions.compose(LOWERCASE, TRIM); // // public static final Function<String, String> CAPITALISE = new Function<String, String>() { // @Override // public String apply(String arg0) { // switch(arg0.length()) { // case 0: return ""; // case 1: return arg0.toUpperCase(); // default: return arg0.substring(0, 1).toUpperCase() + arg0.substring(1); // } // } // }; // // public static final Function<String, String> UNCAPITALISE = new Function<String, String>() { // @Override // public String apply(String arg0) { // switch(arg0.length()) { // case 0: return ""; // case 1: return arg0.toLowerCase(); // default: return arg0.substring(0, 1).toLowerCase() + arg0.substring(1); // } // } // }; // // public static final Predicate<String> EMPTY = new Predicate<String>() { // @Override public boolean apply(String arg0) { // return arg0.isEmpty(); // } // }; // // public static final Predicate<String> NOT_EMPTY = Predicates.not(EMPTY); // }
import java.lang.reflect.Field; import java.lang.reflect.Member; import java.lang.reflect.Method; import java.lang.reflect.Modifier; import java.util.regex.Pattern; import com.google.common.base.Predicate; import com.google.common.base.Predicates; import com.google.common.collect.Iterators; import com.timgroup.karg.naming.StringFunctions; import static java.lang.String.format;
public Field findReadableField(String propertyName) { return Iterators.find(Iterators.forArray(fields), Predicates.and(isPublic(), fieldNameMatches(propertyName)), null); } public Field findWritableField(String propertyName) { return Iterators.find(Iterators.forArray(fields), Predicates.and(isModifiableField(), fieldNameMatches(propertyName)), null); } private Predicate<Member> isPublic() { return new Predicate<Member>() { @Override public boolean apply(Member member) { return Modifier.isPublic(member.getModifiers()); } }; } private Predicate<Field> isModifiableField() { return new Predicate<Field>() { @Override public boolean apply(Field field) { return Modifier.isPublic(field.getModifiers()) && !Modifier.isFinal(field.getModifiers()); } }; } private Predicate<Method> getterMethodNameMatches(String propertyName) {
// Path: src/main/java/com/timgroup/karg/naming/StringFunctions.java // public final class StringFunctions { // // private StringFunctions() { } // // public static final Function<String, String> TRIM = new Function<String, String>() { // @Override // public String apply(String arg0) { // return arg0.trim(); // } // }; // // public static final Function<String, String> LOWERCASE = new Function<String, String>() { // @Override // public String apply(String arg0) { // return arg0.toLowerCase(); // } // }; // // public static final Function<String, String> LOWERCASE_TRIM = Functions.compose(LOWERCASE, TRIM); // // public static final Function<String, String> CAPITALISE = new Function<String, String>() { // @Override // public String apply(String arg0) { // switch(arg0.length()) { // case 0: return ""; // case 1: return arg0.toUpperCase(); // default: return arg0.substring(0, 1).toUpperCase() + arg0.substring(1); // } // } // }; // // public static final Function<String, String> UNCAPITALISE = new Function<String, String>() { // @Override // public String apply(String arg0) { // switch(arg0.length()) { // case 0: return ""; // case 1: return arg0.toLowerCase(); // default: return arg0.substring(0, 1).toLowerCase() + arg0.substring(1); // } // } // }; // // public static final Predicate<String> EMPTY = new Predicate<String>() { // @Override public boolean apply(String arg0) { // return arg0.isEmpty(); // } // }; // // public static final Predicate<String> NOT_EMPTY = Predicates.not(EMPTY); // } // Path: src/main/java/com/timgroup/karg/reflection/ClassInspector.java import java.lang.reflect.Field; import java.lang.reflect.Member; import java.lang.reflect.Method; import java.lang.reflect.Modifier; import java.util.regex.Pattern; import com.google.common.base.Predicate; import com.google.common.base.Predicates; import com.google.common.collect.Iterators; import com.timgroup.karg.naming.StringFunctions; import static java.lang.String.format; public Field findReadableField(String propertyName) { return Iterators.find(Iterators.forArray(fields), Predicates.and(isPublic(), fieldNameMatches(propertyName)), null); } public Field findWritableField(String propertyName) { return Iterators.find(Iterators.forArray(fields), Predicates.and(isModifiableField(), fieldNameMatches(propertyName)), null); } private Predicate<Member> isPublic() { return new Predicate<Member>() { @Override public boolean apply(Member member) { return Modifier.isPublic(member.getModifiers()); } }; } private Predicate<Field> isModifiableField() { return new Predicate<Field>() { @Override public boolean apply(Field field) { return Modifier.isPublic(field.getModifiers()) && !Modifier.isFinal(field.getModifiers()); } }; } private Predicate<Method> getterMethodNameMatches(String propertyName) {
String capitalisedPropertyName = StringFunctions.CAPITALISE.apply(propertyName);
tim-group/karg
src/main/java/com/timgroup/karg/reflection/SetterMethod.java
// Path: src/main/java/com/timgroup/karg/naming/TargetName.java // public class TargetName { // // public static TargetName fromMethodName(String methodName) { // if (methodName.contains("_")) { // return TargetNameParser.UNDERSCORE_SEPARATED.parse(methodName); // } // return TargetNameParser.CAMEL_CASE.parse(methodName); // } // // private final Iterable<String> words; // // public TargetName(Iterable<String> words) { // this.words = words; // } // // public TargetName prefixedWith(String prefix) { // return new TargetName(Iterables.concat(Lists.newArrayList(prefix), words)); // } // // public TargetName withSuffix(String suffix) { // return new TargetName(Iterables.concat(words, Lists.newArrayList(suffix))); // } // // public boolean hasPrefix(String prefix) { // return prefix.equals(Iterables.getFirst(words, null)); // } // // public TargetName withoutPrefix() { // return new TargetName(Iterables.skip(words, 1)); // } // // public String formatWith(TargetNameFormatter formatter) { // return formatter.format(words); // } // } // // Path: src/main/java/com/timgroup/karg/naming/TargetNameFormatter.java // public interface TargetNameFormatter { // // static final TargetNameFormatter LOWER_CAMEL_CASE = new LowerCamelCaseFormatter(); // static final TargetNameFormatter UPPER_CAMEL_CASE = new UpperCamelCaseFormatter(); // static final TargetNameFormatter UNDERSCORE_SEPARATED = new UnderscoreSeparatedFormatter(); // // static final class LowerCamelCaseFormatter implements TargetNameFormatter { // // @Override // public String format(Iterable<String> words) { // Iterator<String> lowercased = transform(words.iterator(), LOWERCASE_TRIM); // if (!lowercased.hasNext()) { // return ""; // } // Iterator<String> lowerCamelCased = concat(singletonIterator(lowercased.next()), // transform(lowercased, CAPITALISE)); // return Joiner.on("").join(Lists.newArrayList(lowerCamelCased)); // } // } // // static final class UpperCamelCaseFormatter implements TargetNameFormatter { // @Override // public String format(Iterable<String> words) { // Iterator<String> upperCamelCased = transform(words.iterator(), // compose(CAPITALISE, LOWERCASE_TRIM)); // return Joiner.on("").join(Lists.newArrayList(upperCamelCased)); // } // } // // static final class UnderscoreSeparatedFormatter implements TargetNameFormatter { // @Override // public String format(Iterable<String> words) { // Iterator<String> upperCamelCased = transform(words.iterator(), LOWERCASE_TRIM); // return Joiner.on("_").join(newArrayList(upperCamelCased)); // } // } // // public abstract String format(Iterable<String> words); // // } // // Path: src/main/java/com/timgroup/karg/reference/Setter.java // public interface Setter<O, T> { // T set(O object, T newValue); // }
import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import com.google.common.base.Preconditions; import com.timgroup.karg.naming.TargetName; import com.timgroup.karg.naming.TargetNameFormatter; import com.timgroup.karg.reference.Setter;
package com.timgroup.karg.reflection; public class SetterMethod<C, V> implements Setter<C, V>, PropertyMethod { private final String propertyName; private final Method method; public static interface PropertyNameBinder { <C, V> SetterMethod<C, V> ofClass(Class<C> owningClass); } public static PropertyNameBinder forProperty(final String propertyName) { return new PropertyNameBinder() { @Override public <C, V> SetterMethod<C, V> ofClass(Class<C> owningClass) { Method setterMethod = ClassInspector.forClass(owningClass).findSetterMethod(propertyName); Preconditions.checkNotNull(setterMethod, "No setter method found for property %s", propertyName); return forMethod(propertyName, setterMethod); } }; } public static <C, V> SetterMethod<C, V> forMethod(String propertyName, Method method) { return new SetterMethod<C, V>(propertyName, method); } public static <C, V> SetterMethod<C, V> forMethod(Method method) { return new SetterMethod<C, V>(getPropertyName(method), method); } private static String getPropertyName(Method method) {
// Path: src/main/java/com/timgroup/karg/naming/TargetName.java // public class TargetName { // // public static TargetName fromMethodName(String methodName) { // if (methodName.contains("_")) { // return TargetNameParser.UNDERSCORE_SEPARATED.parse(methodName); // } // return TargetNameParser.CAMEL_CASE.parse(methodName); // } // // private final Iterable<String> words; // // public TargetName(Iterable<String> words) { // this.words = words; // } // // public TargetName prefixedWith(String prefix) { // return new TargetName(Iterables.concat(Lists.newArrayList(prefix), words)); // } // // public TargetName withSuffix(String suffix) { // return new TargetName(Iterables.concat(words, Lists.newArrayList(suffix))); // } // // public boolean hasPrefix(String prefix) { // return prefix.equals(Iterables.getFirst(words, null)); // } // // public TargetName withoutPrefix() { // return new TargetName(Iterables.skip(words, 1)); // } // // public String formatWith(TargetNameFormatter formatter) { // return formatter.format(words); // } // } // // Path: src/main/java/com/timgroup/karg/naming/TargetNameFormatter.java // public interface TargetNameFormatter { // // static final TargetNameFormatter LOWER_CAMEL_CASE = new LowerCamelCaseFormatter(); // static final TargetNameFormatter UPPER_CAMEL_CASE = new UpperCamelCaseFormatter(); // static final TargetNameFormatter UNDERSCORE_SEPARATED = new UnderscoreSeparatedFormatter(); // // static final class LowerCamelCaseFormatter implements TargetNameFormatter { // // @Override // public String format(Iterable<String> words) { // Iterator<String> lowercased = transform(words.iterator(), LOWERCASE_TRIM); // if (!lowercased.hasNext()) { // return ""; // } // Iterator<String> lowerCamelCased = concat(singletonIterator(lowercased.next()), // transform(lowercased, CAPITALISE)); // return Joiner.on("").join(Lists.newArrayList(lowerCamelCased)); // } // } // // static final class UpperCamelCaseFormatter implements TargetNameFormatter { // @Override // public String format(Iterable<String> words) { // Iterator<String> upperCamelCased = transform(words.iterator(), // compose(CAPITALISE, LOWERCASE_TRIM)); // return Joiner.on("").join(Lists.newArrayList(upperCamelCased)); // } // } // // static final class UnderscoreSeparatedFormatter implements TargetNameFormatter { // @Override // public String format(Iterable<String> words) { // Iterator<String> upperCamelCased = transform(words.iterator(), LOWERCASE_TRIM); // return Joiner.on("_").join(newArrayList(upperCamelCased)); // } // } // // public abstract String format(Iterable<String> words); // // } // // Path: src/main/java/com/timgroup/karg/reference/Setter.java // public interface Setter<O, T> { // T set(O object, T newValue); // } // Path: src/main/java/com/timgroup/karg/reflection/SetterMethod.java import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import com.google.common.base.Preconditions; import com.timgroup.karg.naming.TargetName; import com.timgroup.karg.naming.TargetNameFormatter; import com.timgroup.karg.reference.Setter; package com.timgroup.karg.reflection; public class SetterMethod<C, V> implements Setter<C, V>, PropertyMethod { private final String propertyName; private final Method method; public static interface PropertyNameBinder { <C, V> SetterMethod<C, V> ofClass(Class<C> owningClass); } public static PropertyNameBinder forProperty(final String propertyName) { return new PropertyNameBinder() { @Override public <C, V> SetterMethod<C, V> ofClass(Class<C> owningClass) { Method setterMethod = ClassInspector.forClass(owningClass).findSetterMethod(propertyName); Preconditions.checkNotNull(setterMethod, "No setter method found for property %s", propertyName); return forMethod(propertyName, setterMethod); } }; } public static <C, V> SetterMethod<C, V> forMethod(String propertyName, Method method) { return new SetterMethod<C, V>(propertyName, method); } public static <C, V> SetterMethod<C, V> forMethod(Method method) { return new SetterMethod<C, V>(getPropertyName(method), method); } private static String getPropertyName(Method method) {
return TargetName.fromMethodName(method.getName())
tim-group/karg
src/main/java/com/timgroup/karg/reflection/SetterMethod.java
// Path: src/main/java/com/timgroup/karg/naming/TargetName.java // public class TargetName { // // public static TargetName fromMethodName(String methodName) { // if (methodName.contains("_")) { // return TargetNameParser.UNDERSCORE_SEPARATED.parse(methodName); // } // return TargetNameParser.CAMEL_CASE.parse(methodName); // } // // private final Iterable<String> words; // // public TargetName(Iterable<String> words) { // this.words = words; // } // // public TargetName prefixedWith(String prefix) { // return new TargetName(Iterables.concat(Lists.newArrayList(prefix), words)); // } // // public TargetName withSuffix(String suffix) { // return new TargetName(Iterables.concat(words, Lists.newArrayList(suffix))); // } // // public boolean hasPrefix(String prefix) { // return prefix.equals(Iterables.getFirst(words, null)); // } // // public TargetName withoutPrefix() { // return new TargetName(Iterables.skip(words, 1)); // } // // public String formatWith(TargetNameFormatter formatter) { // return formatter.format(words); // } // } // // Path: src/main/java/com/timgroup/karg/naming/TargetNameFormatter.java // public interface TargetNameFormatter { // // static final TargetNameFormatter LOWER_CAMEL_CASE = new LowerCamelCaseFormatter(); // static final TargetNameFormatter UPPER_CAMEL_CASE = new UpperCamelCaseFormatter(); // static final TargetNameFormatter UNDERSCORE_SEPARATED = new UnderscoreSeparatedFormatter(); // // static final class LowerCamelCaseFormatter implements TargetNameFormatter { // // @Override // public String format(Iterable<String> words) { // Iterator<String> lowercased = transform(words.iterator(), LOWERCASE_TRIM); // if (!lowercased.hasNext()) { // return ""; // } // Iterator<String> lowerCamelCased = concat(singletonIterator(lowercased.next()), // transform(lowercased, CAPITALISE)); // return Joiner.on("").join(Lists.newArrayList(lowerCamelCased)); // } // } // // static final class UpperCamelCaseFormatter implements TargetNameFormatter { // @Override // public String format(Iterable<String> words) { // Iterator<String> upperCamelCased = transform(words.iterator(), // compose(CAPITALISE, LOWERCASE_TRIM)); // return Joiner.on("").join(Lists.newArrayList(upperCamelCased)); // } // } // // static final class UnderscoreSeparatedFormatter implements TargetNameFormatter { // @Override // public String format(Iterable<String> words) { // Iterator<String> upperCamelCased = transform(words.iterator(), LOWERCASE_TRIM); // return Joiner.on("_").join(newArrayList(upperCamelCased)); // } // } // // public abstract String format(Iterable<String> words); // // } // // Path: src/main/java/com/timgroup/karg/reference/Setter.java // public interface Setter<O, T> { // T set(O object, T newValue); // }
import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import com.google.common.base.Preconditions; import com.timgroup.karg.naming.TargetName; import com.timgroup.karg.naming.TargetNameFormatter; import com.timgroup.karg.reference.Setter;
package com.timgroup.karg.reflection; public class SetterMethod<C, V> implements Setter<C, V>, PropertyMethod { private final String propertyName; private final Method method; public static interface PropertyNameBinder { <C, V> SetterMethod<C, V> ofClass(Class<C> owningClass); } public static PropertyNameBinder forProperty(final String propertyName) { return new PropertyNameBinder() { @Override public <C, V> SetterMethod<C, V> ofClass(Class<C> owningClass) { Method setterMethod = ClassInspector.forClass(owningClass).findSetterMethod(propertyName); Preconditions.checkNotNull(setterMethod, "No setter method found for property %s", propertyName); return forMethod(propertyName, setterMethod); } }; } public static <C, V> SetterMethod<C, V> forMethod(String propertyName, Method method) { return new SetterMethod<C, V>(propertyName, method); } public static <C, V> SetterMethod<C, V> forMethod(Method method) { return new SetterMethod<C, V>(getPropertyName(method), method); } private static String getPropertyName(Method method) { return TargetName.fromMethodName(method.getName()) .withoutPrefix()
// Path: src/main/java/com/timgroup/karg/naming/TargetName.java // public class TargetName { // // public static TargetName fromMethodName(String methodName) { // if (methodName.contains("_")) { // return TargetNameParser.UNDERSCORE_SEPARATED.parse(methodName); // } // return TargetNameParser.CAMEL_CASE.parse(methodName); // } // // private final Iterable<String> words; // // public TargetName(Iterable<String> words) { // this.words = words; // } // // public TargetName prefixedWith(String prefix) { // return new TargetName(Iterables.concat(Lists.newArrayList(prefix), words)); // } // // public TargetName withSuffix(String suffix) { // return new TargetName(Iterables.concat(words, Lists.newArrayList(suffix))); // } // // public boolean hasPrefix(String prefix) { // return prefix.equals(Iterables.getFirst(words, null)); // } // // public TargetName withoutPrefix() { // return new TargetName(Iterables.skip(words, 1)); // } // // public String formatWith(TargetNameFormatter formatter) { // return formatter.format(words); // } // } // // Path: src/main/java/com/timgroup/karg/naming/TargetNameFormatter.java // public interface TargetNameFormatter { // // static final TargetNameFormatter LOWER_CAMEL_CASE = new LowerCamelCaseFormatter(); // static final TargetNameFormatter UPPER_CAMEL_CASE = new UpperCamelCaseFormatter(); // static final TargetNameFormatter UNDERSCORE_SEPARATED = new UnderscoreSeparatedFormatter(); // // static final class LowerCamelCaseFormatter implements TargetNameFormatter { // // @Override // public String format(Iterable<String> words) { // Iterator<String> lowercased = transform(words.iterator(), LOWERCASE_TRIM); // if (!lowercased.hasNext()) { // return ""; // } // Iterator<String> lowerCamelCased = concat(singletonIterator(lowercased.next()), // transform(lowercased, CAPITALISE)); // return Joiner.on("").join(Lists.newArrayList(lowerCamelCased)); // } // } // // static final class UpperCamelCaseFormatter implements TargetNameFormatter { // @Override // public String format(Iterable<String> words) { // Iterator<String> upperCamelCased = transform(words.iterator(), // compose(CAPITALISE, LOWERCASE_TRIM)); // return Joiner.on("").join(Lists.newArrayList(upperCamelCased)); // } // } // // static final class UnderscoreSeparatedFormatter implements TargetNameFormatter { // @Override // public String format(Iterable<String> words) { // Iterator<String> upperCamelCased = transform(words.iterator(), LOWERCASE_TRIM); // return Joiner.on("_").join(newArrayList(upperCamelCased)); // } // } // // public abstract String format(Iterable<String> words); // // } // // Path: src/main/java/com/timgroup/karg/reference/Setter.java // public interface Setter<O, T> { // T set(O object, T newValue); // } // Path: src/main/java/com/timgroup/karg/reflection/SetterMethod.java import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import com.google.common.base.Preconditions; import com.timgroup.karg.naming.TargetName; import com.timgroup.karg.naming.TargetNameFormatter; import com.timgroup.karg.reference.Setter; package com.timgroup.karg.reflection; public class SetterMethod<C, V> implements Setter<C, V>, PropertyMethod { private final String propertyName; private final Method method; public static interface PropertyNameBinder { <C, V> SetterMethod<C, V> ofClass(Class<C> owningClass); } public static PropertyNameBinder forProperty(final String propertyName) { return new PropertyNameBinder() { @Override public <C, V> SetterMethod<C, V> ofClass(Class<C> owningClass) { Method setterMethod = ClassInspector.forClass(owningClass).findSetterMethod(propertyName); Preconditions.checkNotNull(setterMethod, "No setter method found for property %s", propertyName); return forMethod(propertyName, setterMethod); } }; } public static <C, V> SetterMethod<C, V> forMethod(String propertyName, Method method) { return new SetterMethod<C, V>(propertyName, method); } public static <C, V> SetterMethod<C, V> forMethod(Method method) { return new SetterMethod<C, V>(getPropertyName(method), method); } private static String getPropertyName(Method method) { return TargetName.fromMethodName(method.getName()) .withoutPrefix()
.formatWith(TargetNameFormatter.LOWER_CAMEL_CASE);
ustwo/bdd-crossplatform-apps
android/app/src/main/java/com/ustwo/sample/CommitDetailActivity.java
// Path: android/app/src/main/java/com/ustwo/sample/data/Commit.java // public class Commit { // public String message; // public Author author; // // public class Author { // public String name; // public String email; // public String date; // } // } // // Path: android/app/src/main/java/com/ustwo/sample/data/CommitSummary.java // public class CommitSummary { // public String sha; // public Commit commit; // // public class Commit { // public Author author; // public String message; // } // // public class Author { // public String date; // } // } // // Path: android/app/src/main/java/com/ustwo/sample/data/GitHub.java // public interface GitHub { // @GET("/repos/{username}/{repo}") // void repository(@Path("username") String username, // @Path("repo") String repo, // Callback<RepositoryInfo> commit); // // @GET("/repos/{username}/{repo}/commits") // void commitList(@Path("username") String username, // @Path("repo") String repo, // Callback<List<CommitSummary>> commit); // // @GET("/repos/{username}/{repo}/git/commits/{commit}") // void commit(@Path("username") String username, // @Path("repo") String repo, // @Path("commit") String commit, // Callback<Commit> user); // }
import android.widget.TextView; import com.ustwo.sample.data.Commit; import com.ustwo.sample.data.CommitSummary; import com.ustwo.sample.data.GitHub; import retrofit.Callback; import retrofit.RestAdapter; import retrofit.RetrofitError; import retrofit.client.Response; import android.app.ProgressDialog; import android.content.Context; import android.content.Intent; import android.os.Bundle; import android.support.v7.app.ActionBarActivity; import android.util.Log;
/** * The MIT License (MIT) * * Copyright (c) 2015 ustwo™ * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. * */ package com.ustwo.sample; /** * Created by emma on 1/8/15. */ public class CommitDetailActivity extends ActionBarActivity { private static final String TAG = CommitDetailActivity.class.getSimpleName(); private static final String EXTRA_KEY_COMMIT_SHA = "key_commit_sha"; private ProgressDialog mProgressDialog; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_commit_detail); mProgressDialog = ProgressDialog.show(this, "", getString(R.string.shared_loading), true, false); retrieveCommitInfo(getIntent().getStringExtra(EXTRA_KEY_COMMIT_SHA)); } @Override protected void onPause() { super.onPause(); dismissProgressDialog(); } private void dismissProgressDialog() { if (mProgressDialog != null) { mProgressDialog.dismiss(); mProgressDialog = null; } } private void retrieveCommitInfo(String commit) { RestAdapter restAdapter = new RestAdapter.Builder() .setEndpoint(getString(R.string.app_endpoint_url)) .build();
// Path: android/app/src/main/java/com/ustwo/sample/data/Commit.java // public class Commit { // public String message; // public Author author; // // public class Author { // public String name; // public String email; // public String date; // } // } // // Path: android/app/src/main/java/com/ustwo/sample/data/CommitSummary.java // public class CommitSummary { // public String sha; // public Commit commit; // // public class Commit { // public Author author; // public String message; // } // // public class Author { // public String date; // } // } // // Path: android/app/src/main/java/com/ustwo/sample/data/GitHub.java // public interface GitHub { // @GET("/repos/{username}/{repo}") // void repository(@Path("username") String username, // @Path("repo") String repo, // Callback<RepositoryInfo> commit); // // @GET("/repos/{username}/{repo}/commits") // void commitList(@Path("username") String username, // @Path("repo") String repo, // Callback<List<CommitSummary>> commit); // // @GET("/repos/{username}/{repo}/git/commits/{commit}") // void commit(@Path("username") String username, // @Path("repo") String repo, // @Path("commit") String commit, // Callback<Commit> user); // } // Path: android/app/src/main/java/com/ustwo/sample/CommitDetailActivity.java import android.widget.TextView; import com.ustwo.sample.data.Commit; import com.ustwo.sample.data.CommitSummary; import com.ustwo.sample.data.GitHub; import retrofit.Callback; import retrofit.RestAdapter; import retrofit.RetrofitError; import retrofit.client.Response; import android.app.ProgressDialog; import android.content.Context; import android.content.Intent; import android.os.Bundle; import android.support.v7.app.ActionBarActivity; import android.util.Log; /** * The MIT License (MIT) * * Copyright (c) 2015 ustwo™ * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. * */ package com.ustwo.sample; /** * Created by emma on 1/8/15. */ public class CommitDetailActivity extends ActionBarActivity { private static final String TAG = CommitDetailActivity.class.getSimpleName(); private static final String EXTRA_KEY_COMMIT_SHA = "key_commit_sha"; private ProgressDialog mProgressDialog; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_commit_detail); mProgressDialog = ProgressDialog.show(this, "", getString(R.string.shared_loading), true, false); retrieveCommitInfo(getIntent().getStringExtra(EXTRA_KEY_COMMIT_SHA)); } @Override protected void onPause() { super.onPause(); dismissProgressDialog(); } private void dismissProgressDialog() { if (mProgressDialog != null) { mProgressDialog.dismiss(); mProgressDialog = null; } } private void retrieveCommitInfo(String commit) { RestAdapter restAdapter = new RestAdapter.Builder() .setEndpoint(getString(R.string.app_endpoint_url)) .build();
GitHub service = restAdapter.create(GitHub.class);
ustwo/bdd-crossplatform-apps
android/app/src/main/java/com/ustwo/sample/CommitDetailActivity.java
// Path: android/app/src/main/java/com/ustwo/sample/data/Commit.java // public class Commit { // public String message; // public Author author; // // public class Author { // public String name; // public String email; // public String date; // } // } // // Path: android/app/src/main/java/com/ustwo/sample/data/CommitSummary.java // public class CommitSummary { // public String sha; // public Commit commit; // // public class Commit { // public Author author; // public String message; // } // // public class Author { // public String date; // } // } // // Path: android/app/src/main/java/com/ustwo/sample/data/GitHub.java // public interface GitHub { // @GET("/repos/{username}/{repo}") // void repository(@Path("username") String username, // @Path("repo") String repo, // Callback<RepositoryInfo> commit); // // @GET("/repos/{username}/{repo}/commits") // void commitList(@Path("username") String username, // @Path("repo") String repo, // Callback<List<CommitSummary>> commit); // // @GET("/repos/{username}/{repo}/git/commits/{commit}") // void commit(@Path("username") String username, // @Path("repo") String repo, // @Path("commit") String commit, // Callback<Commit> user); // }
import android.widget.TextView; import com.ustwo.sample.data.Commit; import com.ustwo.sample.data.CommitSummary; import com.ustwo.sample.data.GitHub; import retrofit.Callback; import retrofit.RestAdapter; import retrofit.RetrofitError; import retrofit.client.Response; import android.app.ProgressDialog; import android.content.Context; import android.content.Intent; import android.os.Bundle; import android.support.v7.app.ActionBarActivity; import android.util.Log;
/** * The MIT License (MIT) * * Copyright (c) 2015 ustwo™ * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. * */ package com.ustwo.sample; /** * Created by emma on 1/8/15. */ public class CommitDetailActivity extends ActionBarActivity { private static final String TAG = CommitDetailActivity.class.getSimpleName(); private static final String EXTRA_KEY_COMMIT_SHA = "key_commit_sha"; private ProgressDialog mProgressDialog; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_commit_detail); mProgressDialog = ProgressDialog.show(this, "", getString(R.string.shared_loading), true, false); retrieveCommitInfo(getIntent().getStringExtra(EXTRA_KEY_COMMIT_SHA)); } @Override protected void onPause() { super.onPause(); dismissProgressDialog(); } private void dismissProgressDialog() { if (mProgressDialog != null) { mProgressDialog.dismiss(); mProgressDialog = null; } } private void retrieveCommitInfo(String commit) { RestAdapter restAdapter = new RestAdapter.Builder() .setEndpoint(getString(R.string.app_endpoint_url)) .build(); GitHub service = restAdapter.create(GitHub.class);
// Path: android/app/src/main/java/com/ustwo/sample/data/Commit.java // public class Commit { // public String message; // public Author author; // // public class Author { // public String name; // public String email; // public String date; // } // } // // Path: android/app/src/main/java/com/ustwo/sample/data/CommitSummary.java // public class CommitSummary { // public String sha; // public Commit commit; // // public class Commit { // public Author author; // public String message; // } // // public class Author { // public String date; // } // } // // Path: android/app/src/main/java/com/ustwo/sample/data/GitHub.java // public interface GitHub { // @GET("/repos/{username}/{repo}") // void repository(@Path("username") String username, // @Path("repo") String repo, // Callback<RepositoryInfo> commit); // // @GET("/repos/{username}/{repo}/commits") // void commitList(@Path("username") String username, // @Path("repo") String repo, // Callback<List<CommitSummary>> commit); // // @GET("/repos/{username}/{repo}/git/commits/{commit}") // void commit(@Path("username") String username, // @Path("repo") String repo, // @Path("commit") String commit, // Callback<Commit> user); // } // Path: android/app/src/main/java/com/ustwo/sample/CommitDetailActivity.java import android.widget.TextView; import com.ustwo.sample.data.Commit; import com.ustwo.sample.data.CommitSummary; import com.ustwo.sample.data.GitHub; import retrofit.Callback; import retrofit.RestAdapter; import retrofit.RetrofitError; import retrofit.client.Response; import android.app.ProgressDialog; import android.content.Context; import android.content.Intent; import android.os.Bundle; import android.support.v7.app.ActionBarActivity; import android.util.Log; /** * The MIT License (MIT) * * Copyright (c) 2015 ustwo™ * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. * */ package com.ustwo.sample; /** * Created by emma on 1/8/15. */ public class CommitDetailActivity extends ActionBarActivity { private static final String TAG = CommitDetailActivity.class.getSimpleName(); private static final String EXTRA_KEY_COMMIT_SHA = "key_commit_sha"; private ProgressDialog mProgressDialog; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_commit_detail); mProgressDialog = ProgressDialog.show(this, "", getString(R.string.shared_loading), true, false); retrieveCommitInfo(getIntent().getStringExtra(EXTRA_KEY_COMMIT_SHA)); } @Override protected void onPause() { super.onPause(); dismissProgressDialog(); } private void dismissProgressDialog() { if (mProgressDialog != null) { mProgressDialog.dismiss(); mProgressDialog = null; } } private void retrieveCommitInfo(String commit) { RestAdapter restAdapter = new RestAdapter.Builder() .setEndpoint(getString(R.string.app_endpoint_url)) .build(); GitHub service = restAdapter.create(GitHub.class);
service.commit(getString(R.string.default_repository_user), getString(R.string.default_repository_name), commit, new Callback<Commit>() {
ustwo/bdd-crossplatform-apps
android/app/src/main/java/com/ustwo/sample/CommitDetailActivity.java
// Path: android/app/src/main/java/com/ustwo/sample/data/Commit.java // public class Commit { // public String message; // public Author author; // // public class Author { // public String name; // public String email; // public String date; // } // } // // Path: android/app/src/main/java/com/ustwo/sample/data/CommitSummary.java // public class CommitSummary { // public String sha; // public Commit commit; // // public class Commit { // public Author author; // public String message; // } // // public class Author { // public String date; // } // } // // Path: android/app/src/main/java/com/ustwo/sample/data/GitHub.java // public interface GitHub { // @GET("/repos/{username}/{repo}") // void repository(@Path("username") String username, // @Path("repo") String repo, // Callback<RepositoryInfo> commit); // // @GET("/repos/{username}/{repo}/commits") // void commitList(@Path("username") String username, // @Path("repo") String repo, // Callback<List<CommitSummary>> commit); // // @GET("/repos/{username}/{repo}/git/commits/{commit}") // void commit(@Path("username") String username, // @Path("repo") String repo, // @Path("commit") String commit, // Callback<Commit> user); // }
import android.widget.TextView; import com.ustwo.sample.data.Commit; import com.ustwo.sample.data.CommitSummary; import com.ustwo.sample.data.GitHub; import retrofit.Callback; import retrofit.RestAdapter; import retrofit.RetrofitError; import retrofit.client.Response; import android.app.ProgressDialog; import android.content.Context; import android.content.Intent; import android.os.Bundle; import android.support.v7.app.ActionBarActivity; import android.util.Log;
} private void retrieveCommitInfo(String commit) { RestAdapter restAdapter = new RestAdapter.Builder() .setEndpoint(getString(R.string.app_endpoint_url)) .build(); GitHub service = restAdapter.create(GitHub.class); service.commit(getString(R.string.default_repository_user), getString(R.string.default_repository_name), commit, new Callback<Commit>() { @Override public void success(Commit commit, Response response) { mProgressDialog.cancel(); updateUI(commit); } @Override public void failure(RetrofitError error) { mProgressDialog.cancel(); Log.e(TAG, "Failed to get full commit information", error); } }); } private void updateUI(Commit commit) { ((TextView) findViewById(R.id.commit_detail_textview_name)).setText(commit.author.name); ((TextView) findViewById(R.id.commit_detail_textview_email)).setText(commit.author.email); ((TextView) findViewById(R.id.commit_detail_textview_date)).setText(commit.author.date); ((TextView) findViewById(R.id.commit_detail_textview_message)).setText(commit.message); }
// Path: android/app/src/main/java/com/ustwo/sample/data/Commit.java // public class Commit { // public String message; // public Author author; // // public class Author { // public String name; // public String email; // public String date; // } // } // // Path: android/app/src/main/java/com/ustwo/sample/data/CommitSummary.java // public class CommitSummary { // public String sha; // public Commit commit; // // public class Commit { // public Author author; // public String message; // } // // public class Author { // public String date; // } // } // // Path: android/app/src/main/java/com/ustwo/sample/data/GitHub.java // public interface GitHub { // @GET("/repos/{username}/{repo}") // void repository(@Path("username") String username, // @Path("repo") String repo, // Callback<RepositoryInfo> commit); // // @GET("/repos/{username}/{repo}/commits") // void commitList(@Path("username") String username, // @Path("repo") String repo, // Callback<List<CommitSummary>> commit); // // @GET("/repos/{username}/{repo}/git/commits/{commit}") // void commit(@Path("username") String username, // @Path("repo") String repo, // @Path("commit") String commit, // Callback<Commit> user); // } // Path: android/app/src/main/java/com/ustwo/sample/CommitDetailActivity.java import android.widget.TextView; import com.ustwo.sample.data.Commit; import com.ustwo.sample.data.CommitSummary; import com.ustwo.sample.data.GitHub; import retrofit.Callback; import retrofit.RestAdapter; import retrofit.RetrofitError; import retrofit.client.Response; import android.app.ProgressDialog; import android.content.Context; import android.content.Intent; import android.os.Bundle; import android.support.v7.app.ActionBarActivity; import android.util.Log; } private void retrieveCommitInfo(String commit) { RestAdapter restAdapter = new RestAdapter.Builder() .setEndpoint(getString(R.string.app_endpoint_url)) .build(); GitHub service = restAdapter.create(GitHub.class); service.commit(getString(R.string.default_repository_user), getString(R.string.default_repository_name), commit, new Callback<Commit>() { @Override public void success(Commit commit, Response response) { mProgressDialog.cancel(); updateUI(commit); } @Override public void failure(RetrofitError error) { mProgressDialog.cancel(); Log.e(TAG, "Failed to get full commit information", error); } }); } private void updateUI(Commit commit) { ((TextView) findViewById(R.id.commit_detail_textview_name)).setText(commit.author.name); ((TextView) findViewById(R.id.commit_detail_textview_email)).setText(commit.author.email); ((TextView) findViewById(R.id.commit_detail_textview_date)).setText(commit.author.date); ((TextView) findViewById(R.id.commit_detail_textview_message)).setText(commit.message); }
public static Intent getIntent(Context context, CommitSummary commit) {
ustwo/bdd-crossplatform-apps
android/app/src/main/java/com/ustwo/sample/CommitListActivity.java
// Path: android/app/src/main/java/com/ustwo/sample/data/CommitSummary.java // public class CommitSummary { // public String sha; // public Commit commit; // // public class Commit { // public Author author; // public String message; // } // // public class Author { // public String date; // } // } // // Path: android/app/src/main/java/com/ustwo/sample/data/GitHub.java // public interface GitHub { // @GET("/repos/{username}/{repo}") // void repository(@Path("username") String username, // @Path("repo") String repo, // Callback<RepositoryInfo> commit); // // @GET("/repos/{username}/{repo}/commits") // void commitList(@Path("username") String username, // @Path("repo") String repo, // Callback<List<CommitSummary>> commit); // // @GET("/repos/{username}/{repo}/git/commits/{commit}") // void commit(@Path("username") String username, // @Path("repo") String repo, // @Path("commit") String commit, // Callback<Commit> user); // } // // Path: android/app/src/main/java/com/ustwo/sample/data/RepositoryInfo.java // public class RepositoryInfo { // public String name; // public String description; // // @SerializedName("private") // public boolean isPrivate; // }
import android.app.ProgressDialog; import android.os.Bundle; import android.support.v7.app.ActionBarActivity; import android.util.Log; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.widget.AdapterView; import android.widget.ImageView; import android.widget.ListView; import android.widget.TextView; import com.ustwo.sample.data.CommitSummary; import com.ustwo.sample.data.GitHub; import com.ustwo.sample.data.RepositoryInfo; import java.util.List; import retrofit.Callback; import retrofit.RestAdapter; import retrofit.RetrofitError; import retrofit.client.Response;
/** * The MIT License (MIT) * * Copyright (c) 2015 ustwo™ * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. * */ package com.ustwo.sample; /** * Created by emma@ustwo.com on 1/8/15. */ public class CommitListActivity extends ActionBarActivity implements AdapterView.OnItemClickListener { private static final String TAG = CommitListActivity.class.getSimpleName(); private RestAdapter mRestAdapter;
// Path: android/app/src/main/java/com/ustwo/sample/data/CommitSummary.java // public class CommitSummary { // public String sha; // public Commit commit; // // public class Commit { // public Author author; // public String message; // } // // public class Author { // public String date; // } // } // // Path: android/app/src/main/java/com/ustwo/sample/data/GitHub.java // public interface GitHub { // @GET("/repos/{username}/{repo}") // void repository(@Path("username") String username, // @Path("repo") String repo, // Callback<RepositoryInfo> commit); // // @GET("/repos/{username}/{repo}/commits") // void commitList(@Path("username") String username, // @Path("repo") String repo, // Callback<List<CommitSummary>> commit); // // @GET("/repos/{username}/{repo}/git/commits/{commit}") // void commit(@Path("username") String username, // @Path("repo") String repo, // @Path("commit") String commit, // Callback<Commit> user); // } // // Path: android/app/src/main/java/com/ustwo/sample/data/RepositoryInfo.java // public class RepositoryInfo { // public String name; // public String description; // // @SerializedName("private") // public boolean isPrivate; // } // Path: android/app/src/main/java/com/ustwo/sample/CommitListActivity.java import android.app.ProgressDialog; import android.os.Bundle; import android.support.v7.app.ActionBarActivity; import android.util.Log; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.widget.AdapterView; import android.widget.ImageView; import android.widget.ListView; import android.widget.TextView; import com.ustwo.sample.data.CommitSummary; import com.ustwo.sample.data.GitHub; import com.ustwo.sample.data.RepositoryInfo; import java.util.List; import retrofit.Callback; import retrofit.RestAdapter; import retrofit.RetrofitError; import retrofit.client.Response; /** * The MIT License (MIT) * * Copyright (c) 2015 ustwo™ * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. * */ package com.ustwo.sample; /** * Created by emma@ustwo.com on 1/8/15. */ public class CommitListActivity extends ActionBarActivity implements AdapterView.OnItemClickListener { private static final String TAG = CommitListActivity.class.getSimpleName(); private RestAdapter mRestAdapter;
private GitHub mGitHubService;
ustwo/bdd-crossplatform-apps
android/app/src/main/java/com/ustwo/sample/CommitListActivity.java
// Path: android/app/src/main/java/com/ustwo/sample/data/CommitSummary.java // public class CommitSummary { // public String sha; // public Commit commit; // // public class Commit { // public Author author; // public String message; // } // // public class Author { // public String date; // } // } // // Path: android/app/src/main/java/com/ustwo/sample/data/GitHub.java // public interface GitHub { // @GET("/repos/{username}/{repo}") // void repository(@Path("username") String username, // @Path("repo") String repo, // Callback<RepositoryInfo> commit); // // @GET("/repos/{username}/{repo}/commits") // void commitList(@Path("username") String username, // @Path("repo") String repo, // Callback<List<CommitSummary>> commit); // // @GET("/repos/{username}/{repo}/git/commits/{commit}") // void commit(@Path("username") String username, // @Path("repo") String repo, // @Path("commit") String commit, // Callback<Commit> user); // } // // Path: android/app/src/main/java/com/ustwo/sample/data/RepositoryInfo.java // public class RepositoryInfo { // public String name; // public String description; // // @SerializedName("private") // public boolean isPrivate; // }
import android.app.ProgressDialog; import android.os.Bundle; import android.support.v7.app.ActionBarActivity; import android.util.Log; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.widget.AdapterView; import android.widget.ImageView; import android.widget.ListView; import android.widget.TextView; import com.ustwo.sample.data.CommitSummary; import com.ustwo.sample.data.GitHub; import com.ustwo.sample.data.RepositoryInfo; import java.util.List; import retrofit.Callback; import retrofit.RestAdapter; import retrofit.RetrofitError; import retrofit.client.Response;
public boolean onOptionsItemSelected(MenuItem item) { int id = item.getItemId(); if (id == R.id.commit_list_button_refresh) { refresh(); return true; } return super.onOptionsItemSelected(item); } private void refresh() { mProgressDialog = ProgressDialog.show(this, "", getString(R.string.shared_loading), true, false); retrieveRepositoryInfo(); } @Override protected void onPause() { super.onPause(); dismissProgressDialog(); } private void dismissProgressDialog() { if (mProgressDialog != null) { mProgressDialog.dismiss(); mProgressDialog = null; } } private void retrieveRepositoryInfo() {
// Path: android/app/src/main/java/com/ustwo/sample/data/CommitSummary.java // public class CommitSummary { // public String sha; // public Commit commit; // // public class Commit { // public Author author; // public String message; // } // // public class Author { // public String date; // } // } // // Path: android/app/src/main/java/com/ustwo/sample/data/GitHub.java // public interface GitHub { // @GET("/repos/{username}/{repo}") // void repository(@Path("username") String username, // @Path("repo") String repo, // Callback<RepositoryInfo> commit); // // @GET("/repos/{username}/{repo}/commits") // void commitList(@Path("username") String username, // @Path("repo") String repo, // Callback<List<CommitSummary>> commit); // // @GET("/repos/{username}/{repo}/git/commits/{commit}") // void commit(@Path("username") String username, // @Path("repo") String repo, // @Path("commit") String commit, // Callback<Commit> user); // } // // Path: android/app/src/main/java/com/ustwo/sample/data/RepositoryInfo.java // public class RepositoryInfo { // public String name; // public String description; // // @SerializedName("private") // public boolean isPrivate; // } // Path: android/app/src/main/java/com/ustwo/sample/CommitListActivity.java import android.app.ProgressDialog; import android.os.Bundle; import android.support.v7.app.ActionBarActivity; import android.util.Log; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.widget.AdapterView; import android.widget.ImageView; import android.widget.ListView; import android.widget.TextView; import com.ustwo.sample.data.CommitSummary; import com.ustwo.sample.data.GitHub; import com.ustwo.sample.data.RepositoryInfo; import java.util.List; import retrofit.Callback; import retrofit.RestAdapter; import retrofit.RetrofitError; import retrofit.client.Response; public boolean onOptionsItemSelected(MenuItem item) { int id = item.getItemId(); if (id == R.id.commit_list_button_refresh) { refresh(); return true; } return super.onOptionsItemSelected(item); } private void refresh() { mProgressDialog = ProgressDialog.show(this, "", getString(R.string.shared_loading), true, false); retrieveRepositoryInfo(); } @Override protected void onPause() { super.onPause(); dismissProgressDialog(); } private void dismissProgressDialog() { if (mProgressDialog != null) { mProgressDialog.dismiss(); mProgressDialog = null; } } private void retrieveRepositoryInfo() {
mGitHubService.repository(getString(R.string.default_repository_user), getString(R.string.default_repository_name), new Callback<RepositoryInfo>() {
ustwo/bdd-crossplatform-apps
android/app/src/main/java/com/ustwo/sample/CommitListActivity.java
// Path: android/app/src/main/java/com/ustwo/sample/data/CommitSummary.java // public class CommitSummary { // public String sha; // public Commit commit; // // public class Commit { // public Author author; // public String message; // } // // public class Author { // public String date; // } // } // // Path: android/app/src/main/java/com/ustwo/sample/data/GitHub.java // public interface GitHub { // @GET("/repos/{username}/{repo}") // void repository(@Path("username") String username, // @Path("repo") String repo, // Callback<RepositoryInfo> commit); // // @GET("/repos/{username}/{repo}/commits") // void commitList(@Path("username") String username, // @Path("repo") String repo, // Callback<List<CommitSummary>> commit); // // @GET("/repos/{username}/{repo}/git/commits/{commit}") // void commit(@Path("username") String username, // @Path("repo") String repo, // @Path("commit") String commit, // Callback<Commit> user); // } // // Path: android/app/src/main/java/com/ustwo/sample/data/RepositoryInfo.java // public class RepositoryInfo { // public String name; // public String description; // // @SerializedName("private") // public boolean isPrivate; // }
import android.app.ProgressDialog; import android.os.Bundle; import android.support.v7.app.ActionBarActivity; import android.util.Log; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.widget.AdapterView; import android.widget.ImageView; import android.widget.ListView; import android.widget.TextView; import com.ustwo.sample.data.CommitSummary; import com.ustwo.sample.data.GitHub; import com.ustwo.sample.data.RepositoryInfo; import java.util.List; import retrofit.Callback; import retrofit.RestAdapter; import retrofit.RetrofitError; import retrofit.client.Response;
@Override public void failure(RetrofitError error) { showErrorMessage(); dismissProgressDialog(); Log.e(TAG, "Failed to get repository information", error); } }); } private void updateRepositoryInfo(RepositoryInfo repositoryInfo) { ((TextView) findViewById(R.id.commit_list_textview_title)).setText(repositoryInfo.description); ImageView privacyStateView = (ImageView) findViewById(R.id.commit_list_imageview_privacy_state); privacyStateView.setImageResource(repositoryInfo.isPrivate ? R.drawable.ic_private : R.drawable.ic_public); privacyStateView.setContentDescription( getString(repositoryInfo.isPrivate ? R.string.commit_list_repo_private : R.string.commit_list_repo_public)); getSupportActionBar().setTitle(repositoryInfo.name); } private void showErrorMessage() { getListView().setVisibility(View.GONE); getStatusInformationTextView().setVisibility(View.VISIBLE); getStatusInformationTextView().setText(R.string.commit_list_error); } private void retrieveCommitList() {
// Path: android/app/src/main/java/com/ustwo/sample/data/CommitSummary.java // public class CommitSummary { // public String sha; // public Commit commit; // // public class Commit { // public Author author; // public String message; // } // // public class Author { // public String date; // } // } // // Path: android/app/src/main/java/com/ustwo/sample/data/GitHub.java // public interface GitHub { // @GET("/repos/{username}/{repo}") // void repository(@Path("username") String username, // @Path("repo") String repo, // Callback<RepositoryInfo> commit); // // @GET("/repos/{username}/{repo}/commits") // void commitList(@Path("username") String username, // @Path("repo") String repo, // Callback<List<CommitSummary>> commit); // // @GET("/repos/{username}/{repo}/git/commits/{commit}") // void commit(@Path("username") String username, // @Path("repo") String repo, // @Path("commit") String commit, // Callback<Commit> user); // } // // Path: android/app/src/main/java/com/ustwo/sample/data/RepositoryInfo.java // public class RepositoryInfo { // public String name; // public String description; // // @SerializedName("private") // public boolean isPrivate; // } // Path: android/app/src/main/java/com/ustwo/sample/CommitListActivity.java import android.app.ProgressDialog; import android.os.Bundle; import android.support.v7.app.ActionBarActivity; import android.util.Log; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.widget.AdapterView; import android.widget.ImageView; import android.widget.ListView; import android.widget.TextView; import com.ustwo.sample.data.CommitSummary; import com.ustwo.sample.data.GitHub; import com.ustwo.sample.data.RepositoryInfo; import java.util.List; import retrofit.Callback; import retrofit.RestAdapter; import retrofit.RetrofitError; import retrofit.client.Response; @Override public void failure(RetrofitError error) { showErrorMessage(); dismissProgressDialog(); Log.e(TAG, "Failed to get repository information", error); } }); } private void updateRepositoryInfo(RepositoryInfo repositoryInfo) { ((TextView) findViewById(R.id.commit_list_textview_title)).setText(repositoryInfo.description); ImageView privacyStateView = (ImageView) findViewById(R.id.commit_list_imageview_privacy_state); privacyStateView.setImageResource(repositoryInfo.isPrivate ? R.drawable.ic_private : R.drawable.ic_public); privacyStateView.setContentDescription( getString(repositoryInfo.isPrivate ? R.string.commit_list_repo_private : R.string.commit_list_repo_public)); getSupportActionBar().setTitle(repositoryInfo.name); } private void showErrorMessage() { getListView().setVisibility(View.GONE); getStatusInformationTextView().setVisibility(View.VISIBLE); getStatusInformationTextView().setText(R.string.commit_list_error); } private void retrieveCommitList() {
mGitHubService.commitList(getString(R.string.default_repository_user), getString(R.string.default_repository_name), new Callback<List<CommitSummary>>() {
ustwo/bdd-crossplatform-apps
android/app/src/main/java/com/ustwo/sample/CommitsAdapter.java
// Path: android/app/src/main/java/com/ustwo/sample/data/CommitSummary.java // public class CommitSummary { // public String sha; // public Commit commit; // // public class Commit { // public Author author; // public String message; // } // // public class Author { // public String date; // } // }
import com.ustwo.sample.data.CommitSummary; import java.util.List; import android.content.Context; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.BaseAdapter; import android.widget.TextView;
/** * The MIT License (MIT) * * Copyright (c) 2015 ustwo™ * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. * */ package com.ustwo.sample; /** * Created by emma@ustwo.com on 1/8/15. */ public class CommitsAdapter extends BaseAdapter { private final LayoutInflater mLayoutInflater;
// Path: android/app/src/main/java/com/ustwo/sample/data/CommitSummary.java // public class CommitSummary { // public String sha; // public Commit commit; // // public class Commit { // public Author author; // public String message; // } // // public class Author { // public String date; // } // } // Path: android/app/src/main/java/com/ustwo/sample/CommitsAdapter.java import com.ustwo.sample.data.CommitSummary; import java.util.List; import android.content.Context; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.BaseAdapter; import android.widget.TextView; /** * The MIT License (MIT) * * Copyright (c) 2015 ustwo™ * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. * */ package com.ustwo.sample; /** * Created by emma@ustwo.com on 1/8/15. */ public class CommitsAdapter extends BaseAdapter { private final LayoutInflater mLayoutInflater;
private final List<CommitSummary> mCommits;
kciray8/IronBrain
IBServer/src/main/java/org/ironbrain/APIController.java
// Path: IBServer/src/main/java/org/ironbrain/dao/AllDao.java // public class AllDao { // @Autowired // protected SectionDao sectionDao; // // @Autowired // protected FieldDao fieldDao; // // @Autowired // protected TicketDao ticketDao; // // @Autowired // protected UserDao userDao; // // @Autowired // protected RemindDao remindDao; // // @Autowired // protected ExamDao examDao; // // @Autowired // protected TryDao tryDao; // // @Autowired // protected DirectionDao directionDao; // // @Autowired // protected SectionToFieldDao secToFDao; // // @Autowired // protected DirectionToFieldDao dirToFDao; // } // // Path: IBServer/src/main/java/org/ironbrain/utils/DateUtils.java // public class DateUtils{ // // public static String getNiceDate(long ms){ // Date date = new Date(ms); // return new SimpleDateFormat("dd.MM.yyyy HH:mm:ss").format(date); // } // // public static String getUniqueFileName(){ // return new SimpleDateFormat("yyyy_MM_dd__HH_mm_ss_SSS").format(new Date(System.currentTimeMillis())); // } // }
import com.google.common.base.Joiner; import org.apache.commons.io.FileUtils; import org.apache.commons.io.FilenameUtils; import org.apache.commons.lang3.mutable.Mutable; import org.apache.commons.lang3.mutable.MutableObject; import org.apache.commons.lang3.tuple.Pair; import org.ironbrain.core.*; import org.ironbrain.dao.AllDao; import org.ironbrain.utils.DateUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.*; import org.springframework.web.multipart.MultipartFile; import java.io.File; import java.io.IOException; import java.nio.file.Path; import java.time.LocalDate; import java.util.ArrayList; import java.util.List; import java.util.stream.Collectors;
} @RequestMapping(method = RequestMethod.GET, value = "/paste_section") @ResponseBody public Result pastSection(@RequestParam Integer parent) { Section section = sectionDao.getSection(data.getBufferSectionId()); List<Section> parentPath = sectionDao.getPath(parent); if (parentPath.contains(section)) { return Result.getError("Рекурсивное добавление!"); } section.setParent(parent); sectionDao.update(section); data.setBufferSectionId(null); return Result.getOk(); } @RequestMapping(method = RequestMethod.POST, value = "/upload_file") @ResponseBody public Result uploadFileHandler(@RequestParam MultipartFile file) { String extension = FilenameUtils.getExtension(file.getOriginalFilename()); try { File userHomeDir = data.getHomeDir(); File userFilesDir = new File(userHomeDir, User.FILES_DIR); File userCommonsFir = new File(userFilesDir, User.COMMONS_DIR);
// Path: IBServer/src/main/java/org/ironbrain/dao/AllDao.java // public class AllDao { // @Autowired // protected SectionDao sectionDao; // // @Autowired // protected FieldDao fieldDao; // // @Autowired // protected TicketDao ticketDao; // // @Autowired // protected UserDao userDao; // // @Autowired // protected RemindDao remindDao; // // @Autowired // protected ExamDao examDao; // // @Autowired // protected TryDao tryDao; // // @Autowired // protected DirectionDao directionDao; // // @Autowired // protected SectionToFieldDao secToFDao; // // @Autowired // protected DirectionToFieldDao dirToFDao; // } // // Path: IBServer/src/main/java/org/ironbrain/utils/DateUtils.java // public class DateUtils{ // // public static String getNiceDate(long ms){ // Date date = new Date(ms); // return new SimpleDateFormat("dd.MM.yyyy HH:mm:ss").format(date); // } // // public static String getUniqueFileName(){ // return new SimpleDateFormat("yyyy_MM_dd__HH_mm_ss_SSS").format(new Date(System.currentTimeMillis())); // } // } // Path: IBServer/src/main/java/org/ironbrain/APIController.java import com.google.common.base.Joiner; import org.apache.commons.io.FileUtils; import org.apache.commons.io.FilenameUtils; import org.apache.commons.lang3.mutable.Mutable; import org.apache.commons.lang3.mutable.MutableObject; import org.apache.commons.lang3.tuple.Pair; import org.ironbrain.core.*; import org.ironbrain.dao.AllDao; import org.ironbrain.utils.DateUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.*; import org.springframework.web.multipart.MultipartFile; import java.io.File; import java.io.IOException; import java.nio.file.Path; import java.time.LocalDate; import java.util.ArrayList; import java.util.List; import java.util.stream.Collectors; } @RequestMapping(method = RequestMethod.GET, value = "/paste_section") @ResponseBody public Result pastSection(@RequestParam Integer parent) { Section section = sectionDao.getSection(data.getBufferSectionId()); List<Section> parentPath = sectionDao.getPath(parent); if (parentPath.contains(section)) { return Result.getError("Рекурсивное добавление!"); } section.setParent(parent); sectionDao.update(section); data.setBufferSectionId(null); return Result.getOk(); } @RequestMapping(method = RequestMethod.POST, value = "/upload_file") @ResponseBody public Result uploadFileHandler(@RequestParam MultipartFile file) { String extension = FilenameUtils.getExtension(file.getOriginalFilename()); try { File userHomeDir = data.getHomeDir(); File userFilesDir = new File(userHomeDir, User.FILES_DIR); File userCommonsFir = new File(userFilesDir, User.COMMONS_DIR);
File thisFile = new File(userCommonsFir, DateUtils.getUniqueFileName() + "." + extension);
kciray8/IronBrain
IBServer/src/main/java/org/ironbrain/SessionData.java
// Path: IBServer/src/main/java/org/ironbrain/core/User.java // @Table(name = "Users") // @Entity // public class User { // public static final String FILES_DIR = "files"; // public static final String COMMONS_DIR = "commons"; // // @Id // @GeneratedValue // private Integer id; // // private String login; // // private String password; // // private Integer root; // // public Boolean getExtended() { // return extended; // } // // public void setExtended(Boolean extended) { // this.extended = extended; // } // // private Boolean extended; // // public User(){ // // } // public User(Integer id){ // this.id = id; // } // // public String getEmail() { // return email; // } // // public void setEmail(String email) { // this.email = email; // } // // private String email; // // public Integer getId() { // return id; // } // // public void setId(Integer id) { // this.id = id; // } // // public String getLogin() { // return login; // } // // public void setLogin(String login) { // this.login = login; // } // // @JsonIgnore // public String getPassword() { // return password; // } // // public void setPassword(String password) { // this.password = password; // } // // public Integer getRoot() { // return root; // } // // public void setRoot(Integer root) { // this.root = root; // } // // public String getPort() { // return port; // } // // public void setPort(String port) { // this.port = port; // } // // private String port = "9993"; // // public Boolean getAdmin() { // return admin; // } // // public void setAdmin(Boolean admin) { // this.admin = admin; // } // // private Boolean admin = false; // // public long getRegisterDate() { // return registerDate; // } // // public void setRegisterDate(long registerDate) { // this.registerDate = registerDate; // } // // private long registerDate = System.currentTimeMillis(); // // @Transient // public String getRegisterDateStr(){ // return DateUtils.getNiceDate(registerDate); // } // }
import org.ironbrain.core.User; import java.io.File;
package org.ironbrain; public class SessionData { public SessionData() { }
// Path: IBServer/src/main/java/org/ironbrain/core/User.java // @Table(name = "Users") // @Entity // public class User { // public static final String FILES_DIR = "files"; // public static final String COMMONS_DIR = "commons"; // // @Id // @GeneratedValue // private Integer id; // // private String login; // // private String password; // // private Integer root; // // public Boolean getExtended() { // return extended; // } // // public void setExtended(Boolean extended) { // this.extended = extended; // } // // private Boolean extended; // // public User(){ // // } // public User(Integer id){ // this.id = id; // } // // public String getEmail() { // return email; // } // // public void setEmail(String email) { // this.email = email; // } // // private String email; // // public Integer getId() { // return id; // } // // public void setId(Integer id) { // this.id = id; // } // // public String getLogin() { // return login; // } // // public void setLogin(String login) { // this.login = login; // } // // @JsonIgnore // public String getPassword() { // return password; // } // // public void setPassword(String password) { // this.password = password; // } // // public Integer getRoot() { // return root; // } // // public void setRoot(Integer root) { // this.root = root; // } // // public String getPort() { // return port; // } // // public void setPort(String port) { // this.port = port; // } // // private String port = "9993"; // // public Boolean getAdmin() { // return admin; // } // // public void setAdmin(Boolean admin) { // this.admin = admin; // } // // private Boolean admin = false; // // public long getRegisterDate() { // return registerDate; // } // // public void setRegisterDate(long registerDate) { // this.registerDate = registerDate; // } // // private long registerDate = System.currentTimeMillis(); // // @Transient // public String getRegisterDateStr(){ // return DateUtils.getNiceDate(registerDate); // } // } // Path: IBServer/src/main/java/org/ironbrain/SessionData.java import org.ironbrain.core.User; import java.io.File; package org.ironbrain; public class SessionData { public SessionData() { }
public User getUser() {
kciray8/IronBrain
IBServer/src/main/java/org/ironbrain/dao/SectionToFieldDao.java
// Path: IBServer/src/main/java/org/ironbrain/Result.java // public class Result<T> { // public State getRes() { // return res; // } // // public void setRes(State res) { // this.res = res; // } // // public String getMessage() { // return message; // } // // public void setMessage(String message) { // this.message = message; // } // // @JsonIgnore // public boolean isOk() { // return res == State.OK; // } // // public T getData() { // return data; // } // // public void setData(T data) { // this.data = data; // } // // public enum State {OK, ERROR} // // private State res = State.OK; // private String message; // private T data; // // public String getSubRes() { // return subRes; // } // // public void setSubRes(String subRes) { // this.subRes = subRes; // } // // private String subRes; // // public static Result getError(String message) { // Result result = new Result(); // result.setRes(State.ERROR); // result.setMessage(message); // return result; // } // // public static Result getOk() { // return new Result(); // } // // public static <DataType> Result getOk(DataType data) { // Result<DataType> result = Result.getOk(); // result.setData(data); // return result; // } // } // // Path: IBServer/src/main/java/org/ironbrain/core/SectionToField.java // @Entity // public class SectionToField implements Serializable, IFieldMapper { // @Id // @GeneratedValue // private Integer id; // // //private Integer sectionId; // // private Boolean inverse = false; // // public void setField(Field field) { // this.field = field; // } // // @ManyToOne(fetch = FetchType.LAZY) // @JoinColumn(name = "fieldId") // public Field field; // // public Section getSection() { // return section; // } // // public Field getField() { // return field; // } // // public void setSection(Section section) { // this.section = section; // } // // @ManyToOne(fetch = FetchType.LAZY) // @JoinColumn(name = "sectionId") // public Section section; // // /* // public Integer getSectionId() { // return sectionId; // } // // public void setSectionId(Integer ticketId) { // this.sectionId = ticketId; // }*/ // // public Integer getId() { // return id; // } // // public void setId(Integer id) { // this.id = id; // } // // public Boolean getInverse() { // return inverse; // } // // public void setInverse(Boolean inverse) { // this.inverse = inverse; // } // }
import org.ironbrain.Result; import org.ironbrain.core.SectionToField; import org.springframework.stereotype.Repository;
package org.ironbrain.dao; @Repository @SuppressWarnings("unchecked") public class SectionToFieldDao extends BaseDao {
// Path: IBServer/src/main/java/org/ironbrain/Result.java // public class Result<T> { // public State getRes() { // return res; // } // // public void setRes(State res) { // this.res = res; // } // // public String getMessage() { // return message; // } // // public void setMessage(String message) { // this.message = message; // } // // @JsonIgnore // public boolean isOk() { // return res == State.OK; // } // // public T getData() { // return data; // } // // public void setData(T data) { // this.data = data; // } // // public enum State {OK, ERROR} // // private State res = State.OK; // private String message; // private T data; // // public String getSubRes() { // return subRes; // } // // public void setSubRes(String subRes) { // this.subRes = subRes; // } // // private String subRes; // // public static Result getError(String message) { // Result result = new Result(); // result.setRes(State.ERROR); // result.setMessage(message); // return result; // } // // public static Result getOk() { // return new Result(); // } // // public static <DataType> Result getOk(DataType data) { // Result<DataType> result = Result.getOk(); // result.setData(data); // return result; // } // } // // Path: IBServer/src/main/java/org/ironbrain/core/SectionToField.java // @Entity // public class SectionToField implements Serializable, IFieldMapper { // @Id // @GeneratedValue // private Integer id; // // //private Integer sectionId; // // private Boolean inverse = false; // // public void setField(Field field) { // this.field = field; // } // // @ManyToOne(fetch = FetchType.LAZY) // @JoinColumn(name = "fieldId") // public Field field; // // public Section getSection() { // return section; // } // // public Field getField() { // return field; // } // // public void setSection(Section section) { // this.section = section; // } // // @ManyToOne(fetch = FetchType.LAZY) // @JoinColumn(name = "sectionId") // public Section section; // // /* // public Integer getSectionId() { // return sectionId; // } // // public void setSectionId(Integer ticketId) { // this.sectionId = ticketId; // }*/ // // public Integer getId() { // return id; // } // // public void setId(Integer id) { // this.id = id; // } // // public Boolean getInverse() { // return inverse; // } // // public void setInverse(Boolean inverse) { // this.inverse = inverse; // } // } // Path: IBServer/src/main/java/org/ironbrain/dao/SectionToFieldDao.java import org.ironbrain.Result; import org.ironbrain.core.SectionToField; import org.springframework.stereotype.Repository; package org.ironbrain.dao; @Repository @SuppressWarnings("unchecked") public class SectionToFieldDao extends BaseDao {
public Result invertField(Integer fieldToSecId) {
kciray8/IronBrain
IBServer/src/main/java/org/ironbrain/dao/SectionToFieldDao.java
// Path: IBServer/src/main/java/org/ironbrain/Result.java // public class Result<T> { // public State getRes() { // return res; // } // // public void setRes(State res) { // this.res = res; // } // // public String getMessage() { // return message; // } // // public void setMessage(String message) { // this.message = message; // } // // @JsonIgnore // public boolean isOk() { // return res == State.OK; // } // // public T getData() { // return data; // } // // public void setData(T data) { // this.data = data; // } // // public enum State {OK, ERROR} // // private State res = State.OK; // private String message; // private T data; // // public String getSubRes() { // return subRes; // } // // public void setSubRes(String subRes) { // this.subRes = subRes; // } // // private String subRes; // // public static Result getError(String message) { // Result result = new Result(); // result.setRes(State.ERROR); // result.setMessage(message); // return result; // } // // public static Result getOk() { // return new Result(); // } // // public static <DataType> Result getOk(DataType data) { // Result<DataType> result = Result.getOk(); // result.setData(data); // return result; // } // } // // Path: IBServer/src/main/java/org/ironbrain/core/SectionToField.java // @Entity // public class SectionToField implements Serializable, IFieldMapper { // @Id // @GeneratedValue // private Integer id; // // //private Integer sectionId; // // private Boolean inverse = false; // // public void setField(Field field) { // this.field = field; // } // // @ManyToOne(fetch = FetchType.LAZY) // @JoinColumn(name = "fieldId") // public Field field; // // public Section getSection() { // return section; // } // // public Field getField() { // return field; // } // // public void setSection(Section section) { // this.section = section; // } // // @ManyToOne(fetch = FetchType.LAZY) // @JoinColumn(name = "sectionId") // public Section section; // // /* // public Integer getSectionId() { // return sectionId; // } // // public void setSectionId(Integer ticketId) { // this.sectionId = ticketId; // }*/ // // public Integer getId() { // return id; // } // // public void setId(Integer id) { // this.id = id; // } // // public Boolean getInverse() { // return inverse; // } // // public void setInverse(Boolean inverse) { // this.inverse = inverse; // } // }
import org.ironbrain.Result; import org.ironbrain.core.SectionToField; import org.springframework.stereotype.Repository;
package org.ironbrain.dao; @Repository @SuppressWarnings("unchecked") public class SectionToFieldDao extends BaseDao { public Result invertField(Integer fieldToSecId) {
// Path: IBServer/src/main/java/org/ironbrain/Result.java // public class Result<T> { // public State getRes() { // return res; // } // // public void setRes(State res) { // this.res = res; // } // // public String getMessage() { // return message; // } // // public void setMessage(String message) { // this.message = message; // } // // @JsonIgnore // public boolean isOk() { // return res == State.OK; // } // // public T getData() { // return data; // } // // public void setData(T data) { // this.data = data; // } // // public enum State {OK, ERROR} // // private State res = State.OK; // private String message; // private T data; // // public String getSubRes() { // return subRes; // } // // public void setSubRes(String subRes) { // this.subRes = subRes; // } // // private String subRes; // // public static Result getError(String message) { // Result result = new Result(); // result.setRes(State.ERROR); // result.setMessage(message); // return result; // } // // public static Result getOk() { // return new Result(); // } // // public static <DataType> Result getOk(DataType data) { // Result<DataType> result = Result.getOk(); // result.setData(data); // return result; // } // } // // Path: IBServer/src/main/java/org/ironbrain/core/SectionToField.java // @Entity // public class SectionToField implements Serializable, IFieldMapper { // @Id // @GeneratedValue // private Integer id; // // //private Integer sectionId; // // private Boolean inverse = false; // // public void setField(Field field) { // this.field = field; // } // // @ManyToOne(fetch = FetchType.LAZY) // @JoinColumn(name = "fieldId") // public Field field; // // public Section getSection() { // return section; // } // // public Field getField() { // return field; // } // // public void setSection(Section section) { // this.section = section; // } // // @ManyToOne(fetch = FetchType.LAZY) // @JoinColumn(name = "sectionId") // public Section section; // // /* // public Integer getSectionId() { // return sectionId; // } // // public void setSectionId(Integer ticketId) { // this.sectionId = ticketId; // }*/ // // public Integer getId() { // return id; // } // // public void setId(Integer id) { // this.id = id; // } // // public Boolean getInverse() { // return inverse; // } // // public void setInverse(Boolean inverse) { // this.inverse = inverse; // } // } // Path: IBServer/src/main/java/org/ironbrain/dao/SectionToFieldDao.java import org.ironbrain.Result; import org.ironbrain.core.SectionToField; import org.springframework.stereotype.Repository; package org.ironbrain.dao; @Repository @SuppressWarnings("unchecked") public class SectionToFieldDao extends BaseDao { public Result invertField(Integer fieldToSecId) {
SectionToField sectionToField = (SectionToField) getSess().get(SectionToField.class, fieldToSecId);
kciray8/IronBrain
IBServer/src/main/java/org/ironbrain/core/Ticket.java
// Path: IBServer/src/main/java/org/ironbrain/IB.java // @Component // public class IB { // @Autowired // private ServletContext context; // // //For testing purpose // private static long msOffset = 0; // // public static Random rand() { // return random; // } // // public static void setRandom(Random random) { // IB.random = random; // } // // private static Random random = new Random(); // // public static void setMsOffset(long msOffset) { // IB.msOffset = msOffset; // } // // public static long getNowMs() { // return System.currentTimeMillis() + msOffset; // } // // public static Calendar getNowCalendar() { // Calendar calendar = Calendar.getInstance(); // calendar.setTimeInMillis(getNowMs()); // // return calendar; // } // // public String getVersionStr() { // String version = getClass().getPackage().getImplementationVersion(); // if (version == null) {//Tomcat bug fix // Properties prop = new Properties(); // try { // prop.load(context.getResourceAsStream("/META-INF/MANIFEST.MF")); // version = prop.getProperty("Implementation-Version"); // } catch (IOException e) { // e.printStackTrace(); // } // } // // return version; // } // // public boolean isPublicVersion() { // return publicVersion; // } // // public static void out(Object object){ // System.out.println(object); // } // // public void setPublicVersion(boolean publicVersion) { // this.publicVersion = publicVersion; // } // // private boolean publicVersion; // }
import org.ironbrain.IB; import javax.persistence.*; import java.util.Calendar;
return customInfo; } public void setCustomInfo(String customInfo) { this.customInfo = customInfo; } private String customInfo = ""; private Integer owner; public Integer getOwner() { return owner; } public void setOwner(Integer owner) { this.owner = owner; } public String getPath() { return path; } public void setPath(String path) { this.path = path; } private String path = ""; public static long getMsFromState(String state) {
// Path: IBServer/src/main/java/org/ironbrain/IB.java // @Component // public class IB { // @Autowired // private ServletContext context; // // //For testing purpose // private static long msOffset = 0; // // public static Random rand() { // return random; // } // // public static void setRandom(Random random) { // IB.random = random; // } // // private static Random random = new Random(); // // public static void setMsOffset(long msOffset) { // IB.msOffset = msOffset; // } // // public static long getNowMs() { // return System.currentTimeMillis() + msOffset; // } // // public static Calendar getNowCalendar() { // Calendar calendar = Calendar.getInstance(); // calendar.setTimeInMillis(getNowMs()); // // return calendar; // } // // public String getVersionStr() { // String version = getClass().getPackage().getImplementationVersion(); // if (version == null) {//Tomcat bug fix // Properties prop = new Properties(); // try { // prop.load(context.getResourceAsStream("/META-INF/MANIFEST.MF")); // version = prop.getProperty("Implementation-Version"); // } catch (IOException e) { // e.printStackTrace(); // } // } // // return version; // } // // public boolean isPublicVersion() { // return publicVersion; // } // // public static void out(Object object){ // System.out.println(object); // } // // public void setPublicVersion(boolean publicVersion) { // this.publicVersion = publicVersion; // } // // private boolean publicVersion; // } // Path: IBServer/src/main/java/org/ironbrain/core/Ticket.java import org.ironbrain.IB; import javax.persistence.*; import java.util.Calendar; return customInfo; } public void setCustomInfo(String customInfo) { this.customInfo = customInfo; } private String customInfo = ""; private Integer owner; public Integer getOwner() { return owner; } public void setOwner(Integer owner) { this.owner = owner; } public String getPath() { return path; } public void setPath(String path) { this.path = path; } private String path = ""; public static long getMsFromState(String state) {
Calendar calendar = IB.getNowCalendar();
kciray8/IronBrain
IBServer/src/main/java/org/ironbrain/dao/ExamDao.java
// Path: IBServer/src/main/java/org/ironbrain/IB.java // @Component // public class IB { // @Autowired // private ServletContext context; // // //For testing purpose // private static long msOffset = 0; // // public static Random rand() { // return random; // } // // public static void setRandom(Random random) { // IB.random = random; // } // // private static Random random = new Random(); // // public static void setMsOffset(long msOffset) { // IB.msOffset = msOffset; // } // // public static long getNowMs() { // return System.currentTimeMillis() + msOffset; // } // // public static Calendar getNowCalendar() { // Calendar calendar = Calendar.getInstance(); // calendar.setTimeInMillis(getNowMs()); // // return calendar; // } // // public String getVersionStr() { // String version = getClass().getPackage().getImplementationVersion(); // if (version == null) {//Tomcat bug fix // Properties prop = new Properties(); // try { // prop.load(context.getResourceAsStream("/META-INF/MANIFEST.MF")); // version = prop.getProperty("Implementation-Version"); // } catch (IOException e) { // e.printStackTrace(); // } // } // // return version; // } // // public boolean isPublicVersion() { // return publicVersion; // } // // public static void out(Object object){ // System.out.println(object); // } // // public void setPublicVersion(boolean publicVersion) { // this.publicVersion = publicVersion; // } // // private boolean publicVersion; // } // // Path: IBServer/src/main/java/org/ironbrain/SessionData.java // public class SessionData { // public SessionData() { // } // // public User getUser() { // return user; // } // // public void setUser(User user) { // this.user = user; // } // // private User user; // // public Integer getUserId() { // return getUser().getId(); // } // // public boolean testOwner(int owner) { // return getUserId() == owner; // } // // public Integer getBufferSectionId() { // return bufferSectionId; // } // // public void setBufferSectionId(Integer bufferSectionId) { // this.bufferSectionId = bufferSectionId; // } // // private Integer bufferSectionId; // // public File getFilesDir() { // String rootPath = System.getProperty("catalina.home"); // return new File(rootPath, "files"); // } // // public File getHomeDir() { // File userHomeDir = new File(getFilesDir(), user.getLogin()); // // if (!userHomeDir.exists()) { // userHomeDir.mkdirs(); // } // return userHomeDir; // } // } // // Path: IBServer/src/main/java/org/ironbrain/core/Exam.java // @Table(name = "Exam") // @Entity // public class Exam { // @Id // @GeneratedValue // private Integer id; // // private Boolean done = false; // // private Integer user; // // public Boolean getDone() { // return done; // } // // public void setDone(Boolean done) { // this.done = done; // } // // public Integer getCount() { // return count; // } // // public void setCount(Integer count) { // this.count = count; // } // // private Integer count; // // private Long startMs; // // public Integer getId() { // return id; // } // // public void setId(Integer id) { // this.id = id; // } // // public Boolean isDone() { // return done; // } // // public void setDone(boolean done) { // this.done = done; // } // // public Integer getUser() { // return user; // } // // public void setUser(Integer user) { // this.user = user; // } // // public Long getStartMs() { // return startMs; // } // // public void setStartMs(Long startMs) { // this.startMs = startMs; // } // // public Long getEndMs() { // return endMs; // } // // public void setEndMs(Long endMs) { // this.endMs = endMs; // } // // private Long endMs; // // @Transient // public long getDurationMin() { // // return (endMs - startMs) / (1000 * 60); // } // // @Transient // public String getName() { // return DateUtils.getNiceDate(startMs); // } // // @Transient // public String getStrStart() { // return DateUtils.getNiceDate(this.getStartMs()); // } // }
import org.hibernate.criterion.Restrictions; import org.ironbrain.IB; import org.ironbrain.SessionData; import org.ironbrain.core.Exam; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Repository; import org.springframework.transaction.annotation.Transactional; import java.util.List;
package org.ironbrain.dao; @Repository @SuppressWarnings("unchecked") @Transactional public class ExamDao extends BaseDao { @Autowired
// Path: IBServer/src/main/java/org/ironbrain/IB.java // @Component // public class IB { // @Autowired // private ServletContext context; // // //For testing purpose // private static long msOffset = 0; // // public static Random rand() { // return random; // } // // public static void setRandom(Random random) { // IB.random = random; // } // // private static Random random = new Random(); // // public static void setMsOffset(long msOffset) { // IB.msOffset = msOffset; // } // // public static long getNowMs() { // return System.currentTimeMillis() + msOffset; // } // // public static Calendar getNowCalendar() { // Calendar calendar = Calendar.getInstance(); // calendar.setTimeInMillis(getNowMs()); // // return calendar; // } // // public String getVersionStr() { // String version = getClass().getPackage().getImplementationVersion(); // if (version == null) {//Tomcat bug fix // Properties prop = new Properties(); // try { // prop.load(context.getResourceAsStream("/META-INF/MANIFEST.MF")); // version = prop.getProperty("Implementation-Version"); // } catch (IOException e) { // e.printStackTrace(); // } // } // // return version; // } // // public boolean isPublicVersion() { // return publicVersion; // } // // public static void out(Object object){ // System.out.println(object); // } // // public void setPublicVersion(boolean publicVersion) { // this.publicVersion = publicVersion; // } // // private boolean publicVersion; // } // // Path: IBServer/src/main/java/org/ironbrain/SessionData.java // public class SessionData { // public SessionData() { // } // // public User getUser() { // return user; // } // // public void setUser(User user) { // this.user = user; // } // // private User user; // // public Integer getUserId() { // return getUser().getId(); // } // // public boolean testOwner(int owner) { // return getUserId() == owner; // } // // public Integer getBufferSectionId() { // return bufferSectionId; // } // // public void setBufferSectionId(Integer bufferSectionId) { // this.bufferSectionId = bufferSectionId; // } // // private Integer bufferSectionId; // // public File getFilesDir() { // String rootPath = System.getProperty("catalina.home"); // return new File(rootPath, "files"); // } // // public File getHomeDir() { // File userHomeDir = new File(getFilesDir(), user.getLogin()); // // if (!userHomeDir.exists()) { // userHomeDir.mkdirs(); // } // return userHomeDir; // } // } // // Path: IBServer/src/main/java/org/ironbrain/core/Exam.java // @Table(name = "Exam") // @Entity // public class Exam { // @Id // @GeneratedValue // private Integer id; // // private Boolean done = false; // // private Integer user; // // public Boolean getDone() { // return done; // } // // public void setDone(Boolean done) { // this.done = done; // } // // public Integer getCount() { // return count; // } // // public void setCount(Integer count) { // this.count = count; // } // // private Integer count; // // private Long startMs; // // public Integer getId() { // return id; // } // // public void setId(Integer id) { // this.id = id; // } // // public Boolean isDone() { // return done; // } // // public void setDone(boolean done) { // this.done = done; // } // // public Integer getUser() { // return user; // } // // public void setUser(Integer user) { // this.user = user; // } // // public Long getStartMs() { // return startMs; // } // // public void setStartMs(Long startMs) { // this.startMs = startMs; // } // // public Long getEndMs() { // return endMs; // } // // public void setEndMs(Long endMs) { // this.endMs = endMs; // } // // private Long endMs; // // @Transient // public long getDurationMin() { // // return (endMs - startMs) / (1000 * 60); // } // // @Transient // public String getName() { // return DateUtils.getNiceDate(startMs); // } // // @Transient // public String getStrStart() { // return DateUtils.getNiceDate(this.getStartMs()); // } // } // Path: IBServer/src/main/java/org/ironbrain/dao/ExamDao.java import org.hibernate.criterion.Restrictions; import org.ironbrain.IB; import org.ironbrain.SessionData; import org.ironbrain.core.Exam; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Repository; import org.springframework.transaction.annotation.Transactional; import java.util.List; package org.ironbrain.dao; @Repository @SuppressWarnings("unchecked") @Transactional public class ExamDao extends BaseDao { @Autowired
protected SessionData data;
kciray8/IronBrain
IBServer/src/main/java/org/ironbrain/dao/ExamDao.java
// Path: IBServer/src/main/java/org/ironbrain/IB.java // @Component // public class IB { // @Autowired // private ServletContext context; // // //For testing purpose // private static long msOffset = 0; // // public static Random rand() { // return random; // } // // public static void setRandom(Random random) { // IB.random = random; // } // // private static Random random = new Random(); // // public static void setMsOffset(long msOffset) { // IB.msOffset = msOffset; // } // // public static long getNowMs() { // return System.currentTimeMillis() + msOffset; // } // // public static Calendar getNowCalendar() { // Calendar calendar = Calendar.getInstance(); // calendar.setTimeInMillis(getNowMs()); // // return calendar; // } // // public String getVersionStr() { // String version = getClass().getPackage().getImplementationVersion(); // if (version == null) {//Tomcat bug fix // Properties prop = new Properties(); // try { // prop.load(context.getResourceAsStream("/META-INF/MANIFEST.MF")); // version = prop.getProperty("Implementation-Version"); // } catch (IOException e) { // e.printStackTrace(); // } // } // // return version; // } // // public boolean isPublicVersion() { // return publicVersion; // } // // public static void out(Object object){ // System.out.println(object); // } // // public void setPublicVersion(boolean publicVersion) { // this.publicVersion = publicVersion; // } // // private boolean publicVersion; // } // // Path: IBServer/src/main/java/org/ironbrain/SessionData.java // public class SessionData { // public SessionData() { // } // // public User getUser() { // return user; // } // // public void setUser(User user) { // this.user = user; // } // // private User user; // // public Integer getUserId() { // return getUser().getId(); // } // // public boolean testOwner(int owner) { // return getUserId() == owner; // } // // public Integer getBufferSectionId() { // return bufferSectionId; // } // // public void setBufferSectionId(Integer bufferSectionId) { // this.bufferSectionId = bufferSectionId; // } // // private Integer bufferSectionId; // // public File getFilesDir() { // String rootPath = System.getProperty("catalina.home"); // return new File(rootPath, "files"); // } // // public File getHomeDir() { // File userHomeDir = new File(getFilesDir(), user.getLogin()); // // if (!userHomeDir.exists()) { // userHomeDir.mkdirs(); // } // return userHomeDir; // } // } // // Path: IBServer/src/main/java/org/ironbrain/core/Exam.java // @Table(name = "Exam") // @Entity // public class Exam { // @Id // @GeneratedValue // private Integer id; // // private Boolean done = false; // // private Integer user; // // public Boolean getDone() { // return done; // } // // public void setDone(Boolean done) { // this.done = done; // } // // public Integer getCount() { // return count; // } // // public void setCount(Integer count) { // this.count = count; // } // // private Integer count; // // private Long startMs; // // public Integer getId() { // return id; // } // // public void setId(Integer id) { // this.id = id; // } // // public Boolean isDone() { // return done; // } // // public void setDone(boolean done) { // this.done = done; // } // // public Integer getUser() { // return user; // } // // public void setUser(Integer user) { // this.user = user; // } // // public Long getStartMs() { // return startMs; // } // // public void setStartMs(Long startMs) { // this.startMs = startMs; // } // // public Long getEndMs() { // return endMs; // } // // public void setEndMs(Long endMs) { // this.endMs = endMs; // } // // private Long endMs; // // @Transient // public long getDurationMin() { // // return (endMs - startMs) / (1000 * 60); // } // // @Transient // public String getName() { // return DateUtils.getNiceDate(startMs); // } // // @Transient // public String getStrStart() { // return DateUtils.getNiceDate(this.getStartMs()); // } // }
import org.hibernate.criterion.Restrictions; import org.ironbrain.IB; import org.ironbrain.SessionData; import org.ironbrain.core.Exam; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Repository; import org.springframework.transaction.annotation.Transactional; import java.util.List;
package org.ironbrain.dao; @Repository @SuppressWarnings("unchecked") @Transactional public class ExamDao extends BaseDao { @Autowired protected SessionData data;
// Path: IBServer/src/main/java/org/ironbrain/IB.java // @Component // public class IB { // @Autowired // private ServletContext context; // // //For testing purpose // private static long msOffset = 0; // // public static Random rand() { // return random; // } // // public static void setRandom(Random random) { // IB.random = random; // } // // private static Random random = new Random(); // // public static void setMsOffset(long msOffset) { // IB.msOffset = msOffset; // } // // public static long getNowMs() { // return System.currentTimeMillis() + msOffset; // } // // public static Calendar getNowCalendar() { // Calendar calendar = Calendar.getInstance(); // calendar.setTimeInMillis(getNowMs()); // // return calendar; // } // // public String getVersionStr() { // String version = getClass().getPackage().getImplementationVersion(); // if (version == null) {//Tomcat bug fix // Properties prop = new Properties(); // try { // prop.load(context.getResourceAsStream("/META-INF/MANIFEST.MF")); // version = prop.getProperty("Implementation-Version"); // } catch (IOException e) { // e.printStackTrace(); // } // } // // return version; // } // // public boolean isPublicVersion() { // return publicVersion; // } // // public static void out(Object object){ // System.out.println(object); // } // // public void setPublicVersion(boolean publicVersion) { // this.publicVersion = publicVersion; // } // // private boolean publicVersion; // } // // Path: IBServer/src/main/java/org/ironbrain/SessionData.java // public class SessionData { // public SessionData() { // } // // public User getUser() { // return user; // } // // public void setUser(User user) { // this.user = user; // } // // private User user; // // public Integer getUserId() { // return getUser().getId(); // } // // public boolean testOwner(int owner) { // return getUserId() == owner; // } // // public Integer getBufferSectionId() { // return bufferSectionId; // } // // public void setBufferSectionId(Integer bufferSectionId) { // this.bufferSectionId = bufferSectionId; // } // // private Integer bufferSectionId; // // public File getFilesDir() { // String rootPath = System.getProperty("catalina.home"); // return new File(rootPath, "files"); // } // // public File getHomeDir() { // File userHomeDir = new File(getFilesDir(), user.getLogin()); // // if (!userHomeDir.exists()) { // userHomeDir.mkdirs(); // } // return userHomeDir; // } // } // // Path: IBServer/src/main/java/org/ironbrain/core/Exam.java // @Table(name = "Exam") // @Entity // public class Exam { // @Id // @GeneratedValue // private Integer id; // // private Boolean done = false; // // private Integer user; // // public Boolean getDone() { // return done; // } // // public void setDone(Boolean done) { // this.done = done; // } // // public Integer getCount() { // return count; // } // // public void setCount(Integer count) { // this.count = count; // } // // private Integer count; // // private Long startMs; // // public Integer getId() { // return id; // } // // public void setId(Integer id) { // this.id = id; // } // // public Boolean isDone() { // return done; // } // // public void setDone(boolean done) { // this.done = done; // } // // public Integer getUser() { // return user; // } // // public void setUser(Integer user) { // this.user = user; // } // // public Long getStartMs() { // return startMs; // } // // public void setStartMs(Long startMs) { // this.startMs = startMs; // } // // public Long getEndMs() { // return endMs; // } // // public void setEndMs(Long endMs) { // this.endMs = endMs; // } // // private Long endMs; // // @Transient // public long getDurationMin() { // // return (endMs - startMs) / (1000 * 60); // } // // @Transient // public String getName() { // return DateUtils.getNiceDate(startMs); // } // // @Transient // public String getStrStart() { // return DateUtils.getNiceDate(this.getStartMs()); // } // } // Path: IBServer/src/main/java/org/ironbrain/dao/ExamDao.java import org.hibernate.criterion.Restrictions; import org.ironbrain.IB; import org.ironbrain.SessionData; import org.ironbrain.core.Exam; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Repository; import org.springframework.transaction.annotation.Transactional; import java.util.List; package org.ironbrain.dao; @Repository @SuppressWarnings("unchecked") @Transactional public class ExamDao extends BaseDao { @Autowired protected SessionData data;
public Exam create(int count) {
kciray8/IronBrain
IBServer/src/main/java/org/ironbrain/dao/ExamDao.java
// Path: IBServer/src/main/java/org/ironbrain/IB.java // @Component // public class IB { // @Autowired // private ServletContext context; // // //For testing purpose // private static long msOffset = 0; // // public static Random rand() { // return random; // } // // public static void setRandom(Random random) { // IB.random = random; // } // // private static Random random = new Random(); // // public static void setMsOffset(long msOffset) { // IB.msOffset = msOffset; // } // // public static long getNowMs() { // return System.currentTimeMillis() + msOffset; // } // // public static Calendar getNowCalendar() { // Calendar calendar = Calendar.getInstance(); // calendar.setTimeInMillis(getNowMs()); // // return calendar; // } // // public String getVersionStr() { // String version = getClass().getPackage().getImplementationVersion(); // if (version == null) {//Tomcat bug fix // Properties prop = new Properties(); // try { // prop.load(context.getResourceAsStream("/META-INF/MANIFEST.MF")); // version = prop.getProperty("Implementation-Version"); // } catch (IOException e) { // e.printStackTrace(); // } // } // // return version; // } // // public boolean isPublicVersion() { // return publicVersion; // } // // public static void out(Object object){ // System.out.println(object); // } // // public void setPublicVersion(boolean publicVersion) { // this.publicVersion = publicVersion; // } // // private boolean publicVersion; // } // // Path: IBServer/src/main/java/org/ironbrain/SessionData.java // public class SessionData { // public SessionData() { // } // // public User getUser() { // return user; // } // // public void setUser(User user) { // this.user = user; // } // // private User user; // // public Integer getUserId() { // return getUser().getId(); // } // // public boolean testOwner(int owner) { // return getUserId() == owner; // } // // public Integer getBufferSectionId() { // return bufferSectionId; // } // // public void setBufferSectionId(Integer bufferSectionId) { // this.bufferSectionId = bufferSectionId; // } // // private Integer bufferSectionId; // // public File getFilesDir() { // String rootPath = System.getProperty("catalina.home"); // return new File(rootPath, "files"); // } // // public File getHomeDir() { // File userHomeDir = new File(getFilesDir(), user.getLogin()); // // if (!userHomeDir.exists()) { // userHomeDir.mkdirs(); // } // return userHomeDir; // } // } // // Path: IBServer/src/main/java/org/ironbrain/core/Exam.java // @Table(name = "Exam") // @Entity // public class Exam { // @Id // @GeneratedValue // private Integer id; // // private Boolean done = false; // // private Integer user; // // public Boolean getDone() { // return done; // } // // public void setDone(Boolean done) { // this.done = done; // } // // public Integer getCount() { // return count; // } // // public void setCount(Integer count) { // this.count = count; // } // // private Integer count; // // private Long startMs; // // public Integer getId() { // return id; // } // // public void setId(Integer id) { // this.id = id; // } // // public Boolean isDone() { // return done; // } // // public void setDone(boolean done) { // this.done = done; // } // // public Integer getUser() { // return user; // } // // public void setUser(Integer user) { // this.user = user; // } // // public Long getStartMs() { // return startMs; // } // // public void setStartMs(Long startMs) { // this.startMs = startMs; // } // // public Long getEndMs() { // return endMs; // } // // public void setEndMs(Long endMs) { // this.endMs = endMs; // } // // private Long endMs; // // @Transient // public long getDurationMin() { // // return (endMs - startMs) / (1000 * 60); // } // // @Transient // public String getName() { // return DateUtils.getNiceDate(startMs); // } // // @Transient // public String getStrStart() { // return DateUtils.getNiceDate(this.getStartMs()); // } // }
import org.hibernate.criterion.Restrictions; import org.ironbrain.IB; import org.ironbrain.SessionData; import org.ironbrain.core.Exam; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Repository; import org.springframework.transaction.annotation.Transactional; import java.util.List;
package org.ironbrain.dao; @Repository @SuppressWarnings("unchecked") @Transactional public class ExamDao extends BaseDao { @Autowired protected SessionData data; public Exam create(int count) { Exam exam = new Exam();
// Path: IBServer/src/main/java/org/ironbrain/IB.java // @Component // public class IB { // @Autowired // private ServletContext context; // // //For testing purpose // private static long msOffset = 0; // // public static Random rand() { // return random; // } // // public static void setRandom(Random random) { // IB.random = random; // } // // private static Random random = new Random(); // // public static void setMsOffset(long msOffset) { // IB.msOffset = msOffset; // } // // public static long getNowMs() { // return System.currentTimeMillis() + msOffset; // } // // public static Calendar getNowCalendar() { // Calendar calendar = Calendar.getInstance(); // calendar.setTimeInMillis(getNowMs()); // // return calendar; // } // // public String getVersionStr() { // String version = getClass().getPackage().getImplementationVersion(); // if (version == null) {//Tomcat bug fix // Properties prop = new Properties(); // try { // prop.load(context.getResourceAsStream("/META-INF/MANIFEST.MF")); // version = prop.getProperty("Implementation-Version"); // } catch (IOException e) { // e.printStackTrace(); // } // } // // return version; // } // // public boolean isPublicVersion() { // return publicVersion; // } // // public static void out(Object object){ // System.out.println(object); // } // // public void setPublicVersion(boolean publicVersion) { // this.publicVersion = publicVersion; // } // // private boolean publicVersion; // } // // Path: IBServer/src/main/java/org/ironbrain/SessionData.java // public class SessionData { // public SessionData() { // } // // public User getUser() { // return user; // } // // public void setUser(User user) { // this.user = user; // } // // private User user; // // public Integer getUserId() { // return getUser().getId(); // } // // public boolean testOwner(int owner) { // return getUserId() == owner; // } // // public Integer getBufferSectionId() { // return bufferSectionId; // } // // public void setBufferSectionId(Integer bufferSectionId) { // this.bufferSectionId = bufferSectionId; // } // // private Integer bufferSectionId; // // public File getFilesDir() { // String rootPath = System.getProperty("catalina.home"); // return new File(rootPath, "files"); // } // // public File getHomeDir() { // File userHomeDir = new File(getFilesDir(), user.getLogin()); // // if (!userHomeDir.exists()) { // userHomeDir.mkdirs(); // } // return userHomeDir; // } // } // // Path: IBServer/src/main/java/org/ironbrain/core/Exam.java // @Table(name = "Exam") // @Entity // public class Exam { // @Id // @GeneratedValue // private Integer id; // // private Boolean done = false; // // private Integer user; // // public Boolean getDone() { // return done; // } // // public void setDone(Boolean done) { // this.done = done; // } // // public Integer getCount() { // return count; // } // // public void setCount(Integer count) { // this.count = count; // } // // private Integer count; // // private Long startMs; // // public Integer getId() { // return id; // } // // public void setId(Integer id) { // this.id = id; // } // // public Boolean isDone() { // return done; // } // // public void setDone(boolean done) { // this.done = done; // } // // public Integer getUser() { // return user; // } // // public void setUser(Integer user) { // this.user = user; // } // // public Long getStartMs() { // return startMs; // } // // public void setStartMs(Long startMs) { // this.startMs = startMs; // } // // public Long getEndMs() { // return endMs; // } // // public void setEndMs(Long endMs) { // this.endMs = endMs; // } // // private Long endMs; // // @Transient // public long getDurationMin() { // // return (endMs - startMs) / (1000 * 60); // } // // @Transient // public String getName() { // return DateUtils.getNiceDate(startMs); // } // // @Transient // public String getStrStart() { // return DateUtils.getNiceDate(this.getStartMs()); // } // } // Path: IBServer/src/main/java/org/ironbrain/dao/ExamDao.java import org.hibernate.criterion.Restrictions; import org.ironbrain.IB; import org.ironbrain.SessionData; import org.ironbrain.core.Exam; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Repository; import org.springframework.transaction.annotation.Transactional; import java.util.List; package org.ironbrain.dao; @Repository @SuppressWarnings("unchecked") @Transactional public class ExamDao extends BaseDao { @Autowired protected SessionData data; public Exam create(int count) { Exam exam = new Exam();
exam.setStartMs(IB.getNowMs());
kciray8/IronBrain
IBServer/src/main/java/org/ironbrain/core/Section.java
// Path: IBServer/src/main/java/org/ironbrain/utils/DateUtils.java // public class DateUtils{ // // public static String getNiceDate(long ms){ // Date date = new Date(ms); // return new SimpleDateFormat("dd.MM.yyyy HH:mm:ss").format(date); // } // // public static String getUniqueFileName(){ // return new SimpleDateFormat("yyyy_MM_dd__HH_mm_ss_SSS").format(new Date(System.currentTimeMillis())); // } // }
import com.fasterxml.jackson.annotation.JsonIgnore; import org.ironbrain.utils.DateUtils; import javax.persistence.*; import java.util.LinkedList; import java.util.List;
Section section = (Section) o; if (!id.equals(section.id)) return false; return true; } @Override public int hashCode() { return id.hashCode(); } @Override public int compareTo(Section o) { return this.getId() - o.getId(); } public Long getRemind() { return remind; } public void setRemind(Long remind) { this.remind = remind; } private Long remind = 0L; @Transient public String getRemindDateStr() { if ((remind != null) && (remind != 0)) {
// Path: IBServer/src/main/java/org/ironbrain/utils/DateUtils.java // public class DateUtils{ // // public static String getNiceDate(long ms){ // Date date = new Date(ms); // return new SimpleDateFormat("dd.MM.yyyy HH:mm:ss").format(date); // } // // public static String getUniqueFileName(){ // return new SimpleDateFormat("yyyy_MM_dd__HH_mm_ss_SSS").format(new Date(System.currentTimeMillis())); // } // } // Path: IBServer/src/main/java/org/ironbrain/core/Section.java import com.fasterxml.jackson.annotation.JsonIgnore; import org.ironbrain.utils.DateUtils; import javax.persistence.*; import java.util.LinkedList; import java.util.List; Section section = (Section) o; if (!id.equals(section.id)) return false; return true; } @Override public int hashCode() { return id.hashCode(); } @Override public int compareTo(Section o) { return this.getId() - o.getId(); } public Long getRemind() { return remind; } public void setRemind(Long remind) { this.remind = remind; } private Long remind = 0L; @Transient public String getRemindDateStr() { if ((remind != null) && (remind != 0)) {
return DateUtils.getNiceDate(remind);
kciray8/IronBrain
IBServer/src/main/java/org/ironbrain/core/User.java
// Path: IBServer/src/main/java/org/ironbrain/utils/DateUtils.java // public class DateUtils{ // // public static String getNiceDate(long ms){ // Date date = new Date(ms); // return new SimpleDateFormat("dd.MM.yyyy HH:mm:ss").format(date); // } // // public static String getUniqueFileName(){ // return new SimpleDateFormat("yyyy_MM_dd__HH_mm_ss_SSS").format(new Date(System.currentTimeMillis())); // } // }
import com.fasterxml.jackson.annotation.JsonIgnore; import org.ironbrain.utils.DateUtils; import javax.persistence.*;
} public void setPort(String port) { this.port = port; } private String port = "9993"; public Boolean getAdmin() { return admin; } public void setAdmin(Boolean admin) { this.admin = admin; } private Boolean admin = false; public long getRegisterDate() { return registerDate; } public void setRegisterDate(long registerDate) { this.registerDate = registerDate; } private long registerDate = System.currentTimeMillis(); @Transient public String getRegisterDateStr(){
// Path: IBServer/src/main/java/org/ironbrain/utils/DateUtils.java // public class DateUtils{ // // public static String getNiceDate(long ms){ // Date date = new Date(ms); // return new SimpleDateFormat("dd.MM.yyyy HH:mm:ss").format(date); // } // // public static String getUniqueFileName(){ // return new SimpleDateFormat("yyyy_MM_dd__HH_mm_ss_SSS").format(new Date(System.currentTimeMillis())); // } // } // Path: IBServer/src/main/java/org/ironbrain/core/User.java import com.fasterxml.jackson.annotation.JsonIgnore; import org.ironbrain.utils.DateUtils; import javax.persistence.*; } public void setPort(String port) { this.port = port; } private String port = "9993"; public Boolean getAdmin() { return admin; } public void setAdmin(Boolean admin) { this.admin = admin; } private Boolean admin = false; public long getRegisterDate() { return registerDate; } public void setRegisterDate(long registerDate) { this.registerDate = registerDate; } private long registerDate = System.currentTimeMillis(); @Transient public String getRegisterDateStr(){
return DateUtils.getNiceDate(registerDate);
kciray8/IronBrain
IBServer/src/main/java/org/ironbrain/core/Try.java
// Path: IBServer/src/main/java/org/ironbrain/utils/DateUtils.java // public class DateUtils{ // // public static String getNiceDate(long ms){ // Date date = new Date(ms); // return new SimpleDateFormat("dd.MM.yyyy HH:mm:ss").format(date); // } // // public static String getUniqueFileName(){ // return new SimpleDateFormat("yyyy_MM_dd__HH_mm_ss_SSS").format(new Date(System.currentTimeMillis())); // } // }
import org.ironbrain.utils.DateUtils; import javax.persistence.*;
} } public Long getRemindTo() { return remindTo; } public void setRemindTo(Long remindTo) { this.remindTo = remindTo; } private Long remindTo; public String getRemindState() { return remindState; } public void setRemindState(String remindState) { this.remindState = remindState; } @Transient public String getResult() { if (remindState.equals(Ticket.REMIND_NOW)) { return "Повтор"; } if (remindState.equals(Ticket.REMIND_LATER)) { return "Вспомнить потом"; }
// Path: IBServer/src/main/java/org/ironbrain/utils/DateUtils.java // public class DateUtils{ // // public static String getNiceDate(long ms){ // Date date = new Date(ms); // return new SimpleDateFormat("dd.MM.yyyy HH:mm:ss").format(date); // } // // public static String getUniqueFileName(){ // return new SimpleDateFormat("yyyy_MM_dd__HH_mm_ss_SSS").format(new Date(System.currentTimeMillis())); // } // } // Path: IBServer/src/main/java/org/ironbrain/core/Try.java import org.ironbrain.utils.DateUtils; import javax.persistence.*; } } public Long getRemindTo() { return remindTo; } public void setRemindTo(Long remindTo) { this.remindTo = remindTo; } private Long remindTo; public String getRemindState() { return remindState; } public void setRemindState(String remindState) { this.remindState = remindState; } @Transient public String getResult() { if (remindState.equals(Ticket.REMIND_NOW)) { return "Повтор"; } if (remindState.equals(Ticket.REMIND_LATER)) { return "Вспомнить потом"; }
return "Вспомнить " + DateUtils.getNiceDate(remindTo);
kciray8/IronBrain
IBServer/src/main/java/org/ironbrain/core/Exam.java
// Path: IBServer/src/main/java/org/ironbrain/utils/DateUtils.java // public class DateUtils{ // // public static String getNiceDate(long ms){ // Date date = new Date(ms); // return new SimpleDateFormat("dd.MM.yyyy HH:mm:ss").format(date); // } // // public static String getUniqueFileName(){ // return new SimpleDateFormat("yyyy_MM_dd__HH_mm_ss_SSS").format(new Date(System.currentTimeMillis())); // } // }
import org.ironbrain.utils.DateUtils; import javax.persistence.*;
public void setUser(Integer user) { this.user = user; } public Long getStartMs() { return startMs; } public void setStartMs(Long startMs) { this.startMs = startMs; } public Long getEndMs() { return endMs; } public void setEndMs(Long endMs) { this.endMs = endMs; } private Long endMs; @Transient public long getDurationMin() { return (endMs - startMs) / (1000 * 60); } @Transient public String getName() {
// Path: IBServer/src/main/java/org/ironbrain/utils/DateUtils.java // public class DateUtils{ // // public static String getNiceDate(long ms){ // Date date = new Date(ms); // return new SimpleDateFormat("dd.MM.yyyy HH:mm:ss").format(date); // } // // public static String getUniqueFileName(){ // return new SimpleDateFormat("yyyy_MM_dd__HH_mm_ss_SSS").format(new Date(System.currentTimeMillis())); // } // } // Path: IBServer/src/main/java/org/ironbrain/core/Exam.java import org.ironbrain.utils.DateUtils; import javax.persistence.*; public void setUser(Integer user) { this.user = user; } public Long getStartMs() { return startMs; } public void setStartMs(Long startMs) { this.startMs = startMs; } public Long getEndMs() { return endMs; } public void setEndMs(Long endMs) { this.endMs = endMs; } private Long endMs; @Transient public long getDurationMin() { return (endMs - startMs) / (1000 * 60); } @Transient public String getName() {
return DateUtils.getNiceDate(startMs);
kciray8/IronBrain
IBServer/src/main/java/org/ironbrain/dao/BaseDao.java
// Path: IBServer/src/main/java/org/ironbrain/SessionData.java // public class SessionData { // public SessionData() { // } // // public User getUser() { // return user; // } // // public void setUser(User user) { // this.user = user; // } // // private User user; // // public Integer getUserId() { // return getUser().getId(); // } // // public boolean testOwner(int owner) { // return getUserId() == owner; // } // // public Integer getBufferSectionId() { // return bufferSectionId; // } // // public void setBufferSectionId(Integer bufferSectionId) { // this.bufferSectionId = bufferSectionId; // } // // private Integer bufferSectionId; // // public File getFilesDir() { // String rootPath = System.getProperty("catalina.home"); // return new File(rootPath, "files"); // } // // public File getHomeDir() { // File userHomeDir = new File(getFilesDir(), user.getLogin()); // // if (!userHomeDir.exists()) { // userHomeDir.mkdirs(); // } // return userHomeDir; // } // }
import org.hibernate.Session; import org.hibernate.SessionFactory; import org.ironbrain.SessionData; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.transaction.annotation.Transactional;
package org.ironbrain.dao; @Transactional public class BaseDao { @Autowired
// Path: IBServer/src/main/java/org/ironbrain/SessionData.java // public class SessionData { // public SessionData() { // } // // public User getUser() { // return user; // } // // public void setUser(User user) { // this.user = user; // } // // private User user; // // public Integer getUserId() { // return getUser().getId(); // } // // public boolean testOwner(int owner) { // return getUserId() == owner; // } // // public Integer getBufferSectionId() { // return bufferSectionId; // } // // public void setBufferSectionId(Integer bufferSectionId) { // this.bufferSectionId = bufferSectionId; // } // // private Integer bufferSectionId; // // public File getFilesDir() { // String rootPath = System.getProperty("catalina.home"); // return new File(rootPath, "files"); // } // // public File getHomeDir() { // File userHomeDir = new File(getFilesDir(), user.getLogin()); // // if (!userHomeDir.exists()) { // userHomeDir.mkdirs(); // } // return userHomeDir; // } // } // Path: IBServer/src/main/java/org/ironbrain/dao/BaseDao.java import org.hibernate.Session; import org.hibernate.SessionFactory; import org.ironbrain.SessionData; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.transaction.annotation.Transactional; package org.ironbrain.dao; @Transactional public class BaseDao { @Autowired
protected SessionData data;
kciray8/IronBrain
IBServer/src/main/java/org/ironbrain/dao/DirectionToFieldDao.java
// Path: IBServer/src/main/java/org/ironbrain/Result.java // public class Result<T> { // public State getRes() { // return res; // } // // public void setRes(State res) { // this.res = res; // } // // public String getMessage() { // return message; // } // // public void setMessage(String message) { // this.message = message; // } // // @JsonIgnore // public boolean isOk() { // return res == State.OK; // } // // public T getData() { // return data; // } // // public void setData(T data) { // this.data = data; // } // // public enum State {OK, ERROR} // // private State res = State.OK; // private String message; // private T data; // // public String getSubRes() { // return subRes; // } // // public void setSubRes(String subRes) { // this.subRes = subRes; // } // // private String subRes; // // public static Result getError(String message) { // Result result = new Result(); // result.setRes(State.ERROR); // result.setMessage(message); // return result; // } // // public static Result getOk() { // return new Result(); // } // // public static <DataType> Result getOk(DataType data) { // Result<DataType> result = Result.getOk(); // result.setData(data); // return result; // } // } // // Path: IBServer/src/main/java/org/ironbrain/core/DirectionToField.java // @Entity // public class DirectionToField implements Serializable, IFieldMapper { // @Id // @GeneratedValue // private Integer id; // // public Integer getDirection_id() { // return direction_id; // } // // public void setDirection_id(Integer direction_id) { // this.direction_id = direction_id; // } // // private Integer direction_id; // // @Override // public Field getField() { // return field; // } // // public void setField(Field field) { // this.field = field; // } // // @ManyToOne // @JoinColumn // private Field field; // // public Integer getId() { // return id; // } // // public void setId(Integer id) { // this.id = id; // } // // private Boolean inverse = false; // // public Boolean getInverse() { // return inverse; // } // // public void setInverse(Boolean inverse) { // this.inverse = inverse; // } // }
import org.ironbrain.Result; import org.ironbrain.core.DirectionToField; import org.springframework.stereotype.Repository;
package org.ironbrain.dao; @Repository @SuppressWarnings("unchecked") public class DirectionToFieldDao extends BaseDao {
// Path: IBServer/src/main/java/org/ironbrain/Result.java // public class Result<T> { // public State getRes() { // return res; // } // // public void setRes(State res) { // this.res = res; // } // // public String getMessage() { // return message; // } // // public void setMessage(String message) { // this.message = message; // } // // @JsonIgnore // public boolean isOk() { // return res == State.OK; // } // // public T getData() { // return data; // } // // public void setData(T data) { // this.data = data; // } // // public enum State {OK, ERROR} // // private State res = State.OK; // private String message; // private T data; // // public String getSubRes() { // return subRes; // } // // public void setSubRes(String subRes) { // this.subRes = subRes; // } // // private String subRes; // // public static Result getError(String message) { // Result result = new Result(); // result.setRes(State.ERROR); // result.setMessage(message); // return result; // } // // public static Result getOk() { // return new Result(); // } // // public static <DataType> Result getOk(DataType data) { // Result<DataType> result = Result.getOk(); // result.setData(data); // return result; // } // } // // Path: IBServer/src/main/java/org/ironbrain/core/DirectionToField.java // @Entity // public class DirectionToField implements Serializable, IFieldMapper { // @Id // @GeneratedValue // private Integer id; // // public Integer getDirection_id() { // return direction_id; // } // // public void setDirection_id(Integer direction_id) { // this.direction_id = direction_id; // } // // private Integer direction_id; // // @Override // public Field getField() { // return field; // } // // public void setField(Field field) { // this.field = field; // } // // @ManyToOne // @JoinColumn // private Field field; // // public Integer getId() { // return id; // } // // public void setId(Integer id) { // this.id = id; // } // // private Boolean inverse = false; // // public Boolean getInverse() { // return inverse; // } // // public void setInverse(Boolean inverse) { // this.inverse = inverse; // } // } // Path: IBServer/src/main/java/org/ironbrain/dao/DirectionToFieldDao.java import org.ironbrain.Result; import org.ironbrain.core.DirectionToField; import org.springframework.stereotype.Repository; package org.ironbrain.dao; @Repository @SuppressWarnings("unchecked") public class DirectionToFieldDao extends BaseDao {
public Result invertField(Integer dirToFieldId) {
kciray8/IronBrain
IBServer/src/main/java/org/ironbrain/dao/DirectionToFieldDao.java
// Path: IBServer/src/main/java/org/ironbrain/Result.java // public class Result<T> { // public State getRes() { // return res; // } // // public void setRes(State res) { // this.res = res; // } // // public String getMessage() { // return message; // } // // public void setMessage(String message) { // this.message = message; // } // // @JsonIgnore // public boolean isOk() { // return res == State.OK; // } // // public T getData() { // return data; // } // // public void setData(T data) { // this.data = data; // } // // public enum State {OK, ERROR} // // private State res = State.OK; // private String message; // private T data; // // public String getSubRes() { // return subRes; // } // // public void setSubRes(String subRes) { // this.subRes = subRes; // } // // private String subRes; // // public static Result getError(String message) { // Result result = new Result(); // result.setRes(State.ERROR); // result.setMessage(message); // return result; // } // // public static Result getOk() { // return new Result(); // } // // public static <DataType> Result getOk(DataType data) { // Result<DataType> result = Result.getOk(); // result.setData(data); // return result; // } // } // // Path: IBServer/src/main/java/org/ironbrain/core/DirectionToField.java // @Entity // public class DirectionToField implements Serializable, IFieldMapper { // @Id // @GeneratedValue // private Integer id; // // public Integer getDirection_id() { // return direction_id; // } // // public void setDirection_id(Integer direction_id) { // this.direction_id = direction_id; // } // // private Integer direction_id; // // @Override // public Field getField() { // return field; // } // // public void setField(Field field) { // this.field = field; // } // // @ManyToOne // @JoinColumn // private Field field; // // public Integer getId() { // return id; // } // // public void setId(Integer id) { // this.id = id; // } // // private Boolean inverse = false; // // public Boolean getInverse() { // return inverse; // } // // public void setInverse(Boolean inverse) { // this.inverse = inverse; // } // }
import org.ironbrain.Result; import org.ironbrain.core.DirectionToField; import org.springframework.stereotype.Repository;
package org.ironbrain.dao; @Repository @SuppressWarnings("unchecked") public class DirectionToFieldDao extends BaseDao { public Result invertField(Integer dirToFieldId) {
// Path: IBServer/src/main/java/org/ironbrain/Result.java // public class Result<T> { // public State getRes() { // return res; // } // // public void setRes(State res) { // this.res = res; // } // // public String getMessage() { // return message; // } // // public void setMessage(String message) { // this.message = message; // } // // @JsonIgnore // public boolean isOk() { // return res == State.OK; // } // // public T getData() { // return data; // } // // public void setData(T data) { // this.data = data; // } // // public enum State {OK, ERROR} // // private State res = State.OK; // private String message; // private T data; // // public String getSubRes() { // return subRes; // } // // public void setSubRes(String subRes) { // this.subRes = subRes; // } // // private String subRes; // // public static Result getError(String message) { // Result result = new Result(); // result.setRes(State.ERROR); // result.setMessage(message); // return result; // } // // public static Result getOk() { // return new Result(); // } // // public static <DataType> Result getOk(DataType data) { // Result<DataType> result = Result.getOk(); // result.setData(data); // return result; // } // } // // Path: IBServer/src/main/java/org/ironbrain/core/DirectionToField.java // @Entity // public class DirectionToField implements Serializable, IFieldMapper { // @Id // @GeneratedValue // private Integer id; // // public Integer getDirection_id() { // return direction_id; // } // // public void setDirection_id(Integer direction_id) { // this.direction_id = direction_id; // } // // private Integer direction_id; // // @Override // public Field getField() { // return field; // } // // public void setField(Field field) { // this.field = field; // } // // @ManyToOne // @JoinColumn // private Field field; // // public Integer getId() { // return id; // } // // public void setId(Integer id) { // this.id = id; // } // // private Boolean inverse = false; // // public Boolean getInverse() { // return inverse; // } // // public void setInverse(Boolean inverse) { // this.inverse = inverse; // } // } // Path: IBServer/src/main/java/org/ironbrain/dao/DirectionToFieldDao.java import org.ironbrain.Result; import org.ironbrain.core.DirectionToField; import org.springframework.stereotype.Repository; package org.ironbrain.dao; @Repository @SuppressWarnings("unchecked") public class DirectionToFieldDao extends BaseDao { public Result invertField(Integer dirToFieldId) {
DirectionToField directionToField = (DirectionToField) getSess().get(DirectionToField.class, dirToFieldId);
InfinityStudio/TrigonometryLauncher
src/main/java/net/teamtf/launcher/util/DownloadUtils.java
// Path: src/main/java/net/teamtf/launcher/core/Engine.java // public class Engine { // // private static Engine instance; // // public static void initEngine() throws Exception { // if (instance == null) { // instance = new Engine(); // } else { // throw new IllegalAccessException("Engine has already initialized"); // } // } // // public static Engine getEngine() { // return instance; // } // // private final File gameDir; // private final File launcherDir; // private final Log logger; // private final TLFileSystem fileSystem; // private UIController uiController; // private Launcher launcher; // private I18n i18n; // private final AddonLoader addonLoader; // private final IConfig launcherConfiguration, gameConfiguration; // private AuthClient authClient; // private LibraryProvider libraryProvider; // private AssestsProvider assestsProvider; // private NativeProvider nativeProvider; // private VersionProvider versionProvider; // // private Engine() throws Exception { // this.launcherDir = new File(new File(URLDecoder.decode(Engine.class.getProtectionDomain().getCodeSource().getLocation().getPath(), // "UTF-8")).getParentFile().getCanonicalPath()); // // this.logger = LogFactory.getLog("MainLogger"); // this.fileSystem = new TLFileSystem(); // // this.launcherConfiguration = new Configuration(this.fileSystem.getLauncherConfigFile(), "launcherconfig"); // this.launcherConfiguration.setConfig("launcher.dir", this.launcherDir.getAbsolutePath()); // this.gameConfiguration = new Configuration(this.fileSystem.getGameConfigFile(), "gameconfig"); // // this.gameDir = FileUtils.getFile(this.launcherConfiguration.getString("game.dir")); // this.i18n = new DefaultI18n(); // this.logger.info(this.i18n.getTranslation("lang.welcome")); // // this.uiController = new DefaultUIControler(); // this.launcher = new DefaultLauncher(); // // this.addonLoader = new AddonLoader(this.launcherConfiguration.getString("addon.dir")); // } // // /** // * Engine start working. 1.load add addons. // * // * @throws Exception // */ // public void start() throws Exception { // //TODO:Still under develop // //I just put everything here as possible. // this.addonLoader.loadFilesFromFolder(); // this.addonLoader.perLoadAllAddons(); // this.getUiController().getMainWindow(); // this.addonLoader.loadAllAddons(); // this.getUiController().getMainWindow().setVisible(true); // this.addonLoader.postLoadAllAddons(); // // } // // public Log getLogger() { // return this.logger; // } // // public TLFileSystem getFileSystem() { // return this.fileSystem; // } // // public UIController getUIController() { // return this.getUiController(); // } // // /** // * Receive current launcher of // * // * @return launcher which current using // */ // public Launcher getLauncher() { // return launcher; // } // // public void setLauncher(Launcher launcher) { // this.launcher = launcher; // } // // public AddonLoader getAddonLoader() { // return addonLoader; // } // // /** // * @return the launcher configuration // */ // public IConfig getLauncherConfig() { // return this.launcherConfiguration; // } // // public void stop() { // this.getUiController().closeAllWindow(); // } // // /** // * @param uiController the uiController to set // */ // public void setUiController(UIController uiController) { // this.uiController = uiController; // } // // /** // * @return the i18n // */ // public I18n getI18n() { // return i18n; // } // // /** // * @param i18n the i18n to set // */ // public void setI18n(I18n i18n) { // this.i18n = i18n; // } // // /** // * @return the gameDir // */ // public File getGameDir() { // return gameDir; // } // // public UIController getUiController() { // return uiController; // } // // public AuthClient getAuthClient() { // return authClient; // } // // public void setAuthClient(AuthClient authClient) { // this.authClient = authClient; // } // // public LibraryProvider getLibraryProvider() { // return libraryProvider; // } // // public void setLibraryProvider(LibraryProvider libraryProvider) { // this.libraryProvider = libraryProvider; // } // }
import java.io.File; import java.io.IOException; import java.net.URL; import net.teamtf.launcher.core.Engine; import org.apache.commons.io.FileUtils;
package net.teamtf.launcher.util; /** * @author Epix, Darkyoooooo * @since 2015/1/5 */ public class DownloadUtils { public static void downloadToFile(String url, File file) throws IOException {
// Path: src/main/java/net/teamtf/launcher/core/Engine.java // public class Engine { // // private static Engine instance; // // public static void initEngine() throws Exception { // if (instance == null) { // instance = new Engine(); // } else { // throw new IllegalAccessException("Engine has already initialized"); // } // } // // public static Engine getEngine() { // return instance; // } // // private final File gameDir; // private final File launcherDir; // private final Log logger; // private final TLFileSystem fileSystem; // private UIController uiController; // private Launcher launcher; // private I18n i18n; // private final AddonLoader addonLoader; // private final IConfig launcherConfiguration, gameConfiguration; // private AuthClient authClient; // private LibraryProvider libraryProvider; // private AssestsProvider assestsProvider; // private NativeProvider nativeProvider; // private VersionProvider versionProvider; // // private Engine() throws Exception { // this.launcherDir = new File(new File(URLDecoder.decode(Engine.class.getProtectionDomain().getCodeSource().getLocation().getPath(), // "UTF-8")).getParentFile().getCanonicalPath()); // // this.logger = LogFactory.getLog("MainLogger"); // this.fileSystem = new TLFileSystem(); // // this.launcherConfiguration = new Configuration(this.fileSystem.getLauncherConfigFile(), "launcherconfig"); // this.launcherConfiguration.setConfig("launcher.dir", this.launcherDir.getAbsolutePath()); // this.gameConfiguration = new Configuration(this.fileSystem.getGameConfigFile(), "gameconfig"); // // this.gameDir = FileUtils.getFile(this.launcherConfiguration.getString("game.dir")); // this.i18n = new DefaultI18n(); // this.logger.info(this.i18n.getTranslation("lang.welcome")); // // this.uiController = new DefaultUIControler(); // this.launcher = new DefaultLauncher(); // // this.addonLoader = new AddonLoader(this.launcherConfiguration.getString("addon.dir")); // } // // /** // * Engine start working. 1.load add addons. // * // * @throws Exception // */ // public void start() throws Exception { // //TODO:Still under develop // //I just put everything here as possible. // this.addonLoader.loadFilesFromFolder(); // this.addonLoader.perLoadAllAddons(); // this.getUiController().getMainWindow(); // this.addonLoader.loadAllAddons(); // this.getUiController().getMainWindow().setVisible(true); // this.addonLoader.postLoadAllAddons(); // // } // // public Log getLogger() { // return this.logger; // } // // public TLFileSystem getFileSystem() { // return this.fileSystem; // } // // public UIController getUIController() { // return this.getUiController(); // } // // /** // * Receive current launcher of // * // * @return launcher which current using // */ // public Launcher getLauncher() { // return launcher; // } // // public void setLauncher(Launcher launcher) { // this.launcher = launcher; // } // // public AddonLoader getAddonLoader() { // return addonLoader; // } // // /** // * @return the launcher configuration // */ // public IConfig getLauncherConfig() { // return this.launcherConfiguration; // } // // public void stop() { // this.getUiController().closeAllWindow(); // } // // /** // * @param uiController the uiController to set // */ // public void setUiController(UIController uiController) { // this.uiController = uiController; // } // // /** // * @return the i18n // */ // public I18n getI18n() { // return i18n; // } // // /** // * @param i18n the i18n to set // */ // public void setI18n(I18n i18n) { // this.i18n = i18n; // } // // /** // * @return the gameDir // */ // public File getGameDir() { // return gameDir; // } // // public UIController getUiController() { // return uiController; // } // // public AuthClient getAuthClient() { // return authClient; // } // // public void setAuthClient(AuthClient authClient) { // this.authClient = authClient; // } // // public LibraryProvider getLibraryProvider() { // return libraryProvider; // } // // public void setLibraryProvider(LibraryProvider libraryProvider) { // this.libraryProvider = libraryProvider; // } // } // Path: src/main/java/net/teamtf/launcher/util/DownloadUtils.java import java.io.File; import java.io.IOException; import java.net.URL; import net.teamtf.launcher.core.Engine; import org.apache.commons.io.FileUtils; package net.teamtf.launcher.util; /** * @author Epix, Darkyoooooo * @since 2015/1/5 */ public class DownloadUtils { public static void downloadToFile(String url, File file) throws IOException {
File tempDir = Engine.getEngine().getFileSystem().createNewTempDir();
InfinityStudio/TrigonometryLauncher
src/main/java/net/teamtf/launcher/core/TLFileSystem.java
// Path: src/main/java/net/teamtf/launcher/content/FileContent.java // public class FileContent { // public static final int TEMPFILE_NAME_MAX_LENGTH = 18; // public static final String[] CRASHREPORTS_ANNOTATION = { // "萌萌萌" // }; // public static final String[] CRASHREPORTS_TEMPLET = { // "--- Trigonometry Launcher - Crash Report ---", // "// ${ANNOTATION}", // "", // "Time: ${TIME}", // "Description: ${DESCRIPTION}", // "", // "${EXCEPTION_TITLE}", // "${EXCEPTION_TEXT}", // "", // "-----------------------------------------------------------------------------", // "${MESSAGE}" // }; // } // // Path: src/main/java/net/teamtf/launcher/util/OSType.java // public enum OSType { // WINDOWS, // LINUX, // MACOSX, // OTHER // } // // Path: src/main/java/net/teamtf/launcher/util/OSUtils.java // public class OSUtils { // /** // * Get current OS Type // * // * @return the current OS type // */ // public static OSType getCurrentOSType() { // String osname = System.getProperty("os.name").toLowerCase(Locale.ENGLISH); // if(osname.contains("win")) { // return OSType.WINDOWS; // } else if (osname.contains("linux")) { // return OSType.LINUX; // } else if (osname.contains("mac")) { // return OSType.MACOSX; // } else { // return OSType.OTHER; // } // } // // // } // // Path: src/main/java/net/teamtf/launcher/util/RandomUtils.java // public class RandomUtils { // public static String nextString(int length) { // return RandomStringUtils.randomAlphanumeric(length).toLowerCase(); // } // // public static int nextInteger(int max) { // return new Random().nextInt(max); // } // } // // Path: src/main/java/net/teamtf/launcher/util/Utils.java // public class Utils { // /** // * Get current time (fully) // * // * @return current time: yyyy-MM-dd HH:mm:ss // */ // public static String getCurrentFullyTime() { // return new SimpleDateFormat("yyyy-MM-dd_HH:mm:ss").format(new Date()); // } // }
import java.io.File; import net.teamtf.launcher.content.FileContent; import net.teamtf.launcher.util.OSType; import net.teamtf.launcher.util.OSUtils; import net.teamtf.launcher.util.RandomUtils; import net.teamtf.launcher.util.Utils;
package net.teamtf.launcher.core; /** * @author Darkyoooooo */ public class TLFileSystem { private File parent, client, user, temp, crashreport, log; public boolean isFirstLaunch; public TLFileSystem() { String userHomeDir = System.getProperty("user.home", "."); String filename = ".tflauncher";
// Path: src/main/java/net/teamtf/launcher/content/FileContent.java // public class FileContent { // public static final int TEMPFILE_NAME_MAX_LENGTH = 18; // public static final String[] CRASHREPORTS_ANNOTATION = { // "萌萌萌" // }; // public static final String[] CRASHREPORTS_TEMPLET = { // "--- Trigonometry Launcher - Crash Report ---", // "// ${ANNOTATION}", // "", // "Time: ${TIME}", // "Description: ${DESCRIPTION}", // "", // "${EXCEPTION_TITLE}", // "${EXCEPTION_TEXT}", // "", // "-----------------------------------------------------------------------------", // "${MESSAGE}" // }; // } // // Path: src/main/java/net/teamtf/launcher/util/OSType.java // public enum OSType { // WINDOWS, // LINUX, // MACOSX, // OTHER // } // // Path: src/main/java/net/teamtf/launcher/util/OSUtils.java // public class OSUtils { // /** // * Get current OS Type // * // * @return the current OS type // */ // public static OSType getCurrentOSType() { // String osname = System.getProperty("os.name").toLowerCase(Locale.ENGLISH); // if(osname.contains("win")) { // return OSType.WINDOWS; // } else if (osname.contains("linux")) { // return OSType.LINUX; // } else if (osname.contains("mac")) { // return OSType.MACOSX; // } else { // return OSType.OTHER; // } // } // // // } // // Path: src/main/java/net/teamtf/launcher/util/RandomUtils.java // public class RandomUtils { // public static String nextString(int length) { // return RandomStringUtils.randomAlphanumeric(length).toLowerCase(); // } // // public static int nextInteger(int max) { // return new Random().nextInt(max); // } // } // // Path: src/main/java/net/teamtf/launcher/util/Utils.java // public class Utils { // /** // * Get current time (fully) // * // * @return current time: yyyy-MM-dd HH:mm:ss // */ // public static String getCurrentFullyTime() { // return new SimpleDateFormat("yyyy-MM-dd_HH:mm:ss").format(new Date()); // } // } // Path: src/main/java/net/teamtf/launcher/core/TLFileSystem.java import java.io.File; import net.teamtf.launcher.content.FileContent; import net.teamtf.launcher.util.OSType; import net.teamtf.launcher.util.OSUtils; import net.teamtf.launcher.util.RandomUtils; import net.teamtf.launcher.util.Utils; package net.teamtf.launcher.core; /** * @author Darkyoooooo */ public class TLFileSystem { private File parent, client, user, temp, crashreport, log; public boolean isFirstLaunch; public TLFileSystem() { String userHomeDir = System.getProperty("user.home", "."); String filename = ".tflauncher";
OSType type = OSUtils.getCurrentOSType();
InfinityStudio/TrigonometryLauncher
src/main/java/net/teamtf/launcher/core/TLFileSystem.java
// Path: src/main/java/net/teamtf/launcher/content/FileContent.java // public class FileContent { // public static final int TEMPFILE_NAME_MAX_LENGTH = 18; // public static final String[] CRASHREPORTS_ANNOTATION = { // "萌萌萌" // }; // public static final String[] CRASHREPORTS_TEMPLET = { // "--- Trigonometry Launcher - Crash Report ---", // "// ${ANNOTATION}", // "", // "Time: ${TIME}", // "Description: ${DESCRIPTION}", // "", // "${EXCEPTION_TITLE}", // "${EXCEPTION_TEXT}", // "", // "-----------------------------------------------------------------------------", // "${MESSAGE}" // }; // } // // Path: src/main/java/net/teamtf/launcher/util/OSType.java // public enum OSType { // WINDOWS, // LINUX, // MACOSX, // OTHER // } // // Path: src/main/java/net/teamtf/launcher/util/OSUtils.java // public class OSUtils { // /** // * Get current OS Type // * // * @return the current OS type // */ // public static OSType getCurrentOSType() { // String osname = System.getProperty("os.name").toLowerCase(Locale.ENGLISH); // if(osname.contains("win")) { // return OSType.WINDOWS; // } else if (osname.contains("linux")) { // return OSType.LINUX; // } else if (osname.contains("mac")) { // return OSType.MACOSX; // } else { // return OSType.OTHER; // } // } // // // } // // Path: src/main/java/net/teamtf/launcher/util/RandomUtils.java // public class RandomUtils { // public static String nextString(int length) { // return RandomStringUtils.randomAlphanumeric(length).toLowerCase(); // } // // public static int nextInteger(int max) { // return new Random().nextInt(max); // } // } // // Path: src/main/java/net/teamtf/launcher/util/Utils.java // public class Utils { // /** // * Get current time (fully) // * // * @return current time: yyyy-MM-dd HH:mm:ss // */ // public static String getCurrentFullyTime() { // return new SimpleDateFormat("yyyy-MM-dd_HH:mm:ss").format(new Date()); // } // }
import java.io.File; import net.teamtf.launcher.content.FileContent; import net.teamtf.launcher.util.OSType; import net.teamtf.launcher.util.OSUtils; import net.teamtf.launcher.util.RandomUtils; import net.teamtf.launcher.util.Utils;
package net.teamtf.launcher.core; /** * @author Darkyoooooo */ public class TLFileSystem { private File parent, client, user, temp, crashreport, log; public boolean isFirstLaunch; public TLFileSystem() { String userHomeDir = System.getProperty("user.home", "."); String filename = ".tflauncher";
// Path: src/main/java/net/teamtf/launcher/content/FileContent.java // public class FileContent { // public static final int TEMPFILE_NAME_MAX_LENGTH = 18; // public static final String[] CRASHREPORTS_ANNOTATION = { // "萌萌萌" // }; // public static final String[] CRASHREPORTS_TEMPLET = { // "--- Trigonometry Launcher - Crash Report ---", // "// ${ANNOTATION}", // "", // "Time: ${TIME}", // "Description: ${DESCRIPTION}", // "", // "${EXCEPTION_TITLE}", // "${EXCEPTION_TEXT}", // "", // "-----------------------------------------------------------------------------", // "${MESSAGE}" // }; // } // // Path: src/main/java/net/teamtf/launcher/util/OSType.java // public enum OSType { // WINDOWS, // LINUX, // MACOSX, // OTHER // } // // Path: src/main/java/net/teamtf/launcher/util/OSUtils.java // public class OSUtils { // /** // * Get current OS Type // * // * @return the current OS type // */ // public static OSType getCurrentOSType() { // String osname = System.getProperty("os.name").toLowerCase(Locale.ENGLISH); // if(osname.contains("win")) { // return OSType.WINDOWS; // } else if (osname.contains("linux")) { // return OSType.LINUX; // } else if (osname.contains("mac")) { // return OSType.MACOSX; // } else { // return OSType.OTHER; // } // } // // // } // // Path: src/main/java/net/teamtf/launcher/util/RandomUtils.java // public class RandomUtils { // public static String nextString(int length) { // return RandomStringUtils.randomAlphanumeric(length).toLowerCase(); // } // // public static int nextInteger(int max) { // return new Random().nextInt(max); // } // } // // Path: src/main/java/net/teamtf/launcher/util/Utils.java // public class Utils { // /** // * Get current time (fully) // * // * @return current time: yyyy-MM-dd HH:mm:ss // */ // public static String getCurrentFullyTime() { // return new SimpleDateFormat("yyyy-MM-dd_HH:mm:ss").format(new Date()); // } // } // Path: src/main/java/net/teamtf/launcher/core/TLFileSystem.java import java.io.File; import net.teamtf.launcher.content.FileContent; import net.teamtf.launcher.util.OSType; import net.teamtf.launcher.util.OSUtils; import net.teamtf.launcher.util.RandomUtils; import net.teamtf.launcher.util.Utils; package net.teamtf.launcher.core; /** * @author Darkyoooooo */ public class TLFileSystem { private File parent, client, user, temp, crashreport, log; public boolean isFirstLaunch; public TLFileSystem() { String userHomeDir = System.getProperty("user.home", "."); String filename = ".tflauncher";
OSType type = OSUtils.getCurrentOSType();
InfinityStudio/TrigonometryLauncher
src/main/java/net/teamtf/launcher/core/TLFileSystem.java
// Path: src/main/java/net/teamtf/launcher/content/FileContent.java // public class FileContent { // public static final int TEMPFILE_NAME_MAX_LENGTH = 18; // public static final String[] CRASHREPORTS_ANNOTATION = { // "萌萌萌" // }; // public static final String[] CRASHREPORTS_TEMPLET = { // "--- Trigonometry Launcher - Crash Report ---", // "// ${ANNOTATION}", // "", // "Time: ${TIME}", // "Description: ${DESCRIPTION}", // "", // "${EXCEPTION_TITLE}", // "${EXCEPTION_TEXT}", // "", // "-----------------------------------------------------------------------------", // "${MESSAGE}" // }; // } // // Path: src/main/java/net/teamtf/launcher/util/OSType.java // public enum OSType { // WINDOWS, // LINUX, // MACOSX, // OTHER // } // // Path: src/main/java/net/teamtf/launcher/util/OSUtils.java // public class OSUtils { // /** // * Get current OS Type // * // * @return the current OS type // */ // public static OSType getCurrentOSType() { // String osname = System.getProperty("os.name").toLowerCase(Locale.ENGLISH); // if(osname.contains("win")) { // return OSType.WINDOWS; // } else if (osname.contains("linux")) { // return OSType.LINUX; // } else if (osname.contains("mac")) { // return OSType.MACOSX; // } else { // return OSType.OTHER; // } // } // // // } // // Path: src/main/java/net/teamtf/launcher/util/RandomUtils.java // public class RandomUtils { // public static String nextString(int length) { // return RandomStringUtils.randomAlphanumeric(length).toLowerCase(); // } // // public static int nextInteger(int max) { // return new Random().nextInt(max); // } // } // // Path: src/main/java/net/teamtf/launcher/util/Utils.java // public class Utils { // /** // * Get current time (fully) // * // * @return current time: yyyy-MM-dd HH:mm:ss // */ // public static String getCurrentFullyTime() { // return new SimpleDateFormat("yyyy-MM-dd_HH:mm:ss").format(new Date()); // } // }
import java.io.File; import net.teamtf.launcher.content.FileContent; import net.teamtf.launcher.util.OSType; import net.teamtf.launcher.util.OSUtils; import net.teamtf.launcher.util.RandomUtils; import net.teamtf.launcher.util.Utils;
} else { parent = new File(userHomeDir, filename); } client = new File(parent, "client"); user = new File(parent, "user"); temp = new File(parent, "temp"); crashreport = new File(parent, "crash-report"); log = new File(parent, "log"); if(parent.exists()) { isFirstLaunch = false; } else { isFirstLaunch = true; } parent.mkdir(); client.mkdir(); user.mkdir(); temp.mkdir(); crashreport.mkdir(); log.mkdir(); } public File getGameConfigFile() { return new File(user, ".gconfig"); } public File getLauncherConfigFile() { return new File(user, ".lconfig"); } public File createNewCrashReportFile() {
// Path: src/main/java/net/teamtf/launcher/content/FileContent.java // public class FileContent { // public static final int TEMPFILE_NAME_MAX_LENGTH = 18; // public static final String[] CRASHREPORTS_ANNOTATION = { // "萌萌萌" // }; // public static final String[] CRASHREPORTS_TEMPLET = { // "--- Trigonometry Launcher - Crash Report ---", // "// ${ANNOTATION}", // "", // "Time: ${TIME}", // "Description: ${DESCRIPTION}", // "", // "${EXCEPTION_TITLE}", // "${EXCEPTION_TEXT}", // "", // "-----------------------------------------------------------------------------", // "${MESSAGE}" // }; // } // // Path: src/main/java/net/teamtf/launcher/util/OSType.java // public enum OSType { // WINDOWS, // LINUX, // MACOSX, // OTHER // } // // Path: src/main/java/net/teamtf/launcher/util/OSUtils.java // public class OSUtils { // /** // * Get current OS Type // * // * @return the current OS type // */ // public static OSType getCurrentOSType() { // String osname = System.getProperty("os.name").toLowerCase(Locale.ENGLISH); // if(osname.contains("win")) { // return OSType.WINDOWS; // } else if (osname.contains("linux")) { // return OSType.LINUX; // } else if (osname.contains("mac")) { // return OSType.MACOSX; // } else { // return OSType.OTHER; // } // } // // // } // // Path: src/main/java/net/teamtf/launcher/util/RandomUtils.java // public class RandomUtils { // public static String nextString(int length) { // return RandomStringUtils.randomAlphanumeric(length).toLowerCase(); // } // // public static int nextInteger(int max) { // return new Random().nextInt(max); // } // } // // Path: src/main/java/net/teamtf/launcher/util/Utils.java // public class Utils { // /** // * Get current time (fully) // * // * @return current time: yyyy-MM-dd HH:mm:ss // */ // public static String getCurrentFullyTime() { // return new SimpleDateFormat("yyyy-MM-dd_HH:mm:ss").format(new Date()); // } // } // Path: src/main/java/net/teamtf/launcher/core/TLFileSystem.java import java.io.File; import net.teamtf.launcher.content.FileContent; import net.teamtf.launcher.util.OSType; import net.teamtf.launcher.util.OSUtils; import net.teamtf.launcher.util.RandomUtils; import net.teamtf.launcher.util.Utils; } else { parent = new File(userHomeDir, filename); } client = new File(parent, "client"); user = new File(parent, "user"); temp = new File(parent, "temp"); crashreport = new File(parent, "crash-report"); log = new File(parent, "log"); if(parent.exists()) { isFirstLaunch = false; } else { isFirstLaunch = true; } parent.mkdir(); client.mkdir(); user.mkdir(); temp.mkdir(); crashreport.mkdir(); log.mkdir(); } public File getGameConfigFile() { return new File(user, ".gconfig"); } public File getLauncherConfigFile() { return new File(user, ".lconfig"); } public File createNewCrashReportFile() {
return new File(crashreport, Utils.getCurrentFullyTime() + ".txt");
InfinityStudio/TrigonometryLauncher
src/main/java/net/teamtf/launcher/core/TLFileSystem.java
// Path: src/main/java/net/teamtf/launcher/content/FileContent.java // public class FileContent { // public static final int TEMPFILE_NAME_MAX_LENGTH = 18; // public static final String[] CRASHREPORTS_ANNOTATION = { // "萌萌萌" // }; // public static final String[] CRASHREPORTS_TEMPLET = { // "--- Trigonometry Launcher - Crash Report ---", // "// ${ANNOTATION}", // "", // "Time: ${TIME}", // "Description: ${DESCRIPTION}", // "", // "${EXCEPTION_TITLE}", // "${EXCEPTION_TEXT}", // "", // "-----------------------------------------------------------------------------", // "${MESSAGE}" // }; // } // // Path: src/main/java/net/teamtf/launcher/util/OSType.java // public enum OSType { // WINDOWS, // LINUX, // MACOSX, // OTHER // } // // Path: src/main/java/net/teamtf/launcher/util/OSUtils.java // public class OSUtils { // /** // * Get current OS Type // * // * @return the current OS type // */ // public static OSType getCurrentOSType() { // String osname = System.getProperty("os.name").toLowerCase(Locale.ENGLISH); // if(osname.contains("win")) { // return OSType.WINDOWS; // } else if (osname.contains("linux")) { // return OSType.LINUX; // } else if (osname.contains("mac")) { // return OSType.MACOSX; // } else { // return OSType.OTHER; // } // } // // // } // // Path: src/main/java/net/teamtf/launcher/util/RandomUtils.java // public class RandomUtils { // public static String nextString(int length) { // return RandomStringUtils.randomAlphanumeric(length).toLowerCase(); // } // // public static int nextInteger(int max) { // return new Random().nextInt(max); // } // } // // Path: src/main/java/net/teamtf/launcher/util/Utils.java // public class Utils { // /** // * Get current time (fully) // * // * @return current time: yyyy-MM-dd HH:mm:ss // */ // public static String getCurrentFullyTime() { // return new SimpleDateFormat("yyyy-MM-dd_HH:mm:ss").format(new Date()); // } // }
import java.io.File; import net.teamtf.launcher.content.FileContent; import net.teamtf.launcher.util.OSType; import net.teamtf.launcher.util.OSUtils; import net.teamtf.launcher.util.RandomUtils; import net.teamtf.launcher.util.Utils;
user = new File(parent, "user"); temp = new File(parent, "temp"); crashreport = new File(parent, "crash-report"); log = new File(parent, "log"); if(parent.exists()) { isFirstLaunch = false; } else { isFirstLaunch = true; } parent.mkdir(); client.mkdir(); user.mkdir(); temp.mkdir(); crashreport.mkdir(); log.mkdir(); } public File getGameConfigFile() { return new File(user, ".gconfig"); } public File getLauncherConfigFile() { return new File(user, ".lconfig"); } public File createNewCrashReportFile() { return new File(crashreport, Utils.getCurrentFullyTime() + ".txt"); } public File createNewTempDir() {
// Path: src/main/java/net/teamtf/launcher/content/FileContent.java // public class FileContent { // public static final int TEMPFILE_NAME_MAX_LENGTH = 18; // public static final String[] CRASHREPORTS_ANNOTATION = { // "萌萌萌" // }; // public static final String[] CRASHREPORTS_TEMPLET = { // "--- Trigonometry Launcher - Crash Report ---", // "// ${ANNOTATION}", // "", // "Time: ${TIME}", // "Description: ${DESCRIPTION}", // "", // "${EXCEPTION_TITLE}", // "${EXCEPTION_TEXT}", // "", // "-----------------------------------------------------------------------------", // "${MESSAGE}" // }; // } // // Path: src/main/java/net/teamtf/launcher/util/OSType.java // public enum OSType { // WINDOWS, // LINUX, // MACOSX, // OTHER // } // // Path: src/main/java/net/teamtf/launcher/util/OSUtils.java // public class OSUtils { // /** // * Get current OS Type // * // * @return the current OS type // */ // public static OSType getCurrentOSType() { // String osname = System.getProperty("os.name").toLowerCase(Locale.ENGLISH); // if(osname.contains("win")) { // return OSType.WINDOWS; // } else if (osname.contains("linux")) { // return OSType.LINUX; // } else if (osname.contains("mac")) { // return OSType.MACOSX; // } else { // return OSType.OTHER; // } // } // // // } // // Path: src/main/java/net/teamtf/launcher/util/RandomUtils.java // public class RandomUtils { // public static String nextString(int length) { // return RandomStringUtils.randomAlphanumeric(length).toLowerCase(); // } // // public static int nextInteger(int max) { // return new Random().nextInt(max); // } // } // // Path: src/main/java/net/teamtf/launcher/util/Utils.java // public class Utils { // /** // * Get current time (fully) // * // * @return current time: yyyy-MM-dd HH:mm:ss // */ // public static String getCurrentFullyTime() { // return new SimpleDateFormat("yyyy-MM-dd_HH:mm:ss").format(new Date()); // } // } // Path: src/main/java/net/teamtf/launcher/core/TLFileSystem.java import java.io.File; import net.teamtf.launcher.content.FileContent; import net.teamtf.launcher.util.OSType; import net.teamtf.launcher.util.OSUtils; import net.teamtf.launcher.util.RandomUtils; import net.teamtf.launcher.util.Utils; user = new File(parent, "user"); temp = new File(parent, "temp"); crashreport = new File(parent, "crash-report"); log = new File(parent, "log"); if(parent.exists()) { isFirstLaunch = false; } else { isFirstLaunch = true; } parent.mkdir(); client.mkdir(); user.mkdir(); temp.mkdir(); crashreport.mkdir(); log.mkdir(); } public File getGameConfigFile() { return new File(user, ".gconfig"); } public File getLauncherConfigFile() { return new File(user, ".lconfig"); } public File createNewCrashReportFile() { return new File(crashreport, Utils.getCurrentFullyTime() + ".txt"); } public File createNewTempDir() {
return new File(temp, RandomUtils.nextString(24));
InfinityStudio/TrigonometryLauncher
src/main/java/net/teamtf/launcher/core/Launcher.java
// Path: src/main/java/net/teamtf/launcher/util/task/TaskManager.java // public class TaskManager { // // private final LinkedList<Task> tasks; // // public TaskManager() { // this.tasks = new LinkedList<>(); // } // // public Void executeTasks() { // // LinkedList<Task> reversedList = (LinkedList<Task>) this.tasks.clone(); // Collections.reverse(this.tasks); // // ExecutorService syncPool = Executors.newSingleThreadExecutor(); // ExecutorService asyncPool = Executors.newCachedThreadPool(); // // // for (Task task : reversedList) { // if (task.isSynchronized()) { // syncPool.execute(task); // if (task.getTaskExecuteException() != null) { // throw task.getTaskExecuteException(); // } // } else { // asyncPool.execute(task); // } // } // syncPool.shutdown(); // asyncPool.shutdown(); // return null; // } // // /** // * Insert task at the end of task list // * // * @param task the task which you want insert // */ // public void insertTask(Task task) { // this.tasks.add(task); // } // // /** // * Insert task at certain index of task list // * // * @param index the sequence you want your task execute // * @param task the task which you want insert // */ // public void insertTask(Integer index, Task task) { // this.tasks.add(index, task); // } // // /** // * Remove task which at the end of task list // * // * @param index the sequence of task // */ // public void removeTask(Integer index) { // this.tasks.remove(index.intValue()); // } // // /** // * Receive index of certain task through task. // * // * @param taskName of task // * @return first index of task which hold that name, -1 if not exists. // */ // public Integer getTaskSequenceByName(String taskName) { // for (int i = 0; i < this.tasks.size(); i++) { // if (this.tasks.get(i).getName().equals(taskName)) { // return i + 1; // } // } // return -1; // } // // }
import net.teamtf.launcher.util.task.TaskManager;
package net.teamtf.launcher.core; /** * Created by Decker on 2014/12/27. */ public interface Launcher { public void launch();
// Path: src/main/java/net/teamtf/launcher/util/task/TaskManager.java // public class TaskManager { // // private final LinkedList<Task> tasks; // // public TaskManager() { // this.tasks = new LinkedList<>(); // } // // public Void executeTasks() { // // LinkedList<Task> reversedList = (LinkedList<Task>) this.tasks.clone(); // Collections.reverse(this.tasks); // // ExecutorService syncPool = Executors.newSingleThreadExecutor(); // ExecutorService asyncPool = Executors.newCachedThreadPool(); // // // for (Task task : reversedList) { // if (task.isSynchronized()) { // syncPool.execute(task); // if (task.getTaskExecuteException() != null) { // throw task.getTaskExecuteException(); // } // } else { // asyncPool.execute(task); // } // } // syncPool.shutdown(); // asyncPool.shutdown(); // return null; // } // // /** // * Insert task at the end of task list // * // * @param task the task which you want insert // */ // public void insertTask(Task task) { // this.tasks.add(task); // } // // /** // * Insert task at certain index of task list // * // * @param index the sequence you want your task execute // * @param task the task which you want insert // */ // public void insertTask(Integer index, Task task) { // this.tasks.add(index, task); // } // // /** // * Remove task which at the end of task list // * // * @param index the sequence of task // */ // public void removeTask(Integer index) { // this.tasks.remove(index.intValue()); // } // // /** // * Receive index of certain task through task. // * // * @param taskName of task // * @return first index of task which hold that name, -1 if not exists. // */ // public Integer getTaskSequenceByName(String taskName) { // for (int i = 0; i < this.tasks.size(); i++) { // if (this.tasks.get(i).getName().equals(taskName)) { // return i + 1; // } // } // return -1; // } // // } // Path: src/main/java/net/teamtf/launcher/core/Launcher.java import net.teamtf.launcher.util.task.TaskManager; package net.teamtf.launcher.core; /** * Created by Decker on 2014/12/27. */ public interface Launcher { public void launch();
public TaskManager getLaunchTaskManager();
InfinityStudio/TrigonometryLauncher
src/main/java/net/teamtf/launcher/basis/DefaultLauncher.java
// Path: src/main/java/net/teamtf/launcher/core/Launcher.java // public interface Launcher { // public void launch(); // public TaskManager getLaunchTaskManager(); // } // // Path: src/main/java/net/teamtf/launcher/util/task/SynchronizedTask.java // public abstract class SynchronizedTask implements Task { // // private TaskExecuteException exceptionDuringExecuting; // // public SynchronizedTask() { // // } // // @Override // public abstract void run(); // // @Override // public Boolean isSynchronized() { // return true; // } // // @Override // public TaskExecuteException getTaskExecuteException() { // return this.exceptionDuringExecuting; // } // // // protected void setTaskExecuteException(Exception exception) { // this.exceptionDuringExecuting=new TaskExecuteException(this, exception); // } // } // // Path: src/main/java/net/teamtf/launcher/util/task/TaskManager.java // public class TaskManager { // // private final LinkedList<Task> tasks; // // public TaskManager() { // this.tasks = new LinkedList<>(); // } // // public Void executeTasks() { // // LinkedList<Task> reversedList = (LinkedList<Task>) this.tasks.clone(); // Collections.reverse(this.tasks); // // ExecutorService syncPool = Executors.newSingleThreadExecutor(); // ExecutorService asyncPool = Executors.newCachedThreadPool(); // // // for (Task task : reversedList) { // if (task.isSynchronized()) { // syncPool.execute(task); // if (task.getTaskExecuteException() != null) { // throw task.getTaskExecuteException(); // } // } else { // asyncPool.execute(task); // } // } // syncPool.shutdown(); // asyncPool.shutdown(); // return null; // } // // /** // * Insert task at the end of task list // * // * @param task the task which you want insert // */ // public void insertTask(Task task) { // this.tasks.add(task); // } // // /** // * Insert task at certain index of task list // * // * @param index the sequence you want your task execute // * @param task the task which you want insert // */ // public void insertTask(Integer index, Task task) { // this.tasks.add(index, task); // } // // /** // * Remove task which at the end of task list // * // * @param index the sequence of task // */ // public void removeTask(Integer index) { // this.tasks.remove(index.intValue()); // } // // /** // * Receive index of certain task through task. // * // * @param taskName of task // * @return first index of task which hold that name, -1 if not exists. // */ // public Integer getTaskSequenceByName(String taskName) { // for (int i = 0; i < this.tasks.size(); i++) { // if (this.tasks.get(i).getName().equals(taskName)) { // return i + 1; // } // } // return -1; // } // // }
import net.teamtf.launcher.core.Launcher; import net.teamtf.launcher.util.task.SynchronizedTask; import net.teamtf.launcher.util.task.TaskManager;
package net.teamtf.launcher.basis; /** * @Author Decker */ public class DefaultLauncher implements Launcher { private TaskManager launchTaskManager; public DefaultLauncher() { this.launchTaskManager = new TaskManager();
// Path: src/main/java/net/teamtf/launcher/core/Launcher.java // public interface Launcher { // public void launch(); // public TaskManager getLaunchTaskManager(); // } // // Path: src/main/java/net/teamtf/launcher/util/task/SynchronizedTask.java // public abstract class SynchronizedTask implements Task { // // private TaskExecuteException exceptionDuringExecuting; // // public SynchronizedTask() { // // } // // @Override // public abstract void run(); // // @Override // public Boolean isSynchronized() { // return true; // } // // @Override // public TaskExecuteException getTaskExecuteException() { // return this.exceptionDuringExecuting; // } // // // protected void setTaskExecuteException(Exception exception) { // this.exceptionDuringExecuting=new TaskExecuteException(this, exception); // } // } // // Path: src/main/java/net/teamtf/launcher/util/task/TaskManager.java // public class TaskManager { // // private final LinkedList<Task> tasks; // // public TaskManager() { // this.tasks = new LinkedList<>(); // } // // public Void executeTasks() { // // LinkedList<Task> reversedList = (LinkedList<Task>) this.tasks.clone(); // Collections.reverse(this.tasks); // // ExecutorService syncPool = Executors.newSingleThreadExecutor(); // ExecutorService asyncPool = Executors.newCachedThreadPool(); // // // for (Task task : reversedList) { // if (task.isSynchronized()) { // syncPool.execute(task); // if (task.getTaskExecuteException() != null) { // throw task.getTaskExecuteException(); // } // } else { // asyncPool.execute(task); // } // } // syncPool.shutdown(); // asyncPool.shutdown(); // return null; // } // // /** // * Insert task at the end of task list // * // * @param task the task which you want insert // */ // public void insertTask(Task task) { // this.tasks.add(task); // } // // /** // * Insert task at certain index of task list // * // * @param index the sequence you want your task execute // * @param task the task which you want insert // */ // public void insertTask(Integer index, Task task) { // this.tasks.add(index, task); // } // // /** // * Remove task which at the end of task list // * // * @param index the sequence of task // */ // public void removeTask(Integer index) { // this.tasks.remove(index.intValue()); // } // // /** // * Receive index of certain task through task. // * // * @param taskName of task // * @return first index of task which hold that name, -1 if not exists. // */ // public Integer getTaskSequenceByName(String taskName) { // for (int i = 0; i < this.tasks.size(); i++) { // if (this.tasks.get(i).getName().equals(taskName)) { // return i + 1; // } // } // return -1; // } // // } // Path: src/main/java/net/teamtf/launcher/basis/DefaultLauncher.java import net.teamtf.launcher.core.Launcher; import net.teamtf.launcher.util.task.SynchronizedTask; import net.teamtf.launcher.util.task.TaskManager; package net.teamtf.launcher.basis; /** * @Author Decker */ public class DefaultLauncher implements Launcher { private TaskManager launchTaskManager; public DefaultLauncher() { this.launchTaskManager = new TaskManager();
this.launchTaskManager.insertTask(new SynchronizedTask() {
InfinityStudio/TrigonometryLauncher
src/main/java/net/teamtf/launcher/basis/LaunchTaskManagerFactory.java
// Path: src/main/java/net/teamtf/launcher/util/task/SynchronizedTask.java // public abstract class SynchronizedTask implements Task { // // private TaskExecuteException exceptionDuringExecuting; // // public SynchronizedTask() { // // } // // @Override // public abstract void run(); // // @Override // public Boolean isSynchronized() { // return true; // } // // @Override // public TaskExecuteException getTaskExecuteException() { // return this.exceptionDuringExecuting; // } // // // protected void setTaskExecuteException(Exception exception) { // this.exceptionDuringExecuting=new TaskExecuteException(this, exception); // } // } // // Path: src/main/java/net/teamtf/launcher/util/task/TaskManager.java // public class TaskManager { // // private final LinkedList<Task> tasks; // // public TaskManager() { // this.tasks = new LinkedList<>(); // } // // public Void executeTasks() { // // LinkedList<Task> reversedList = (LinkedList<Task>) this.tasks.clone(); // Collections.reverse(this.tasks); // // ExecutorService syncPool = Executors.newSingleThreadExecutor(); // ExecutorService asyncPool = Executors.newCachedThreadPool(); // // // for (Task task : reversedList) { // if (task.isSynchronized()) { // syncPool.execute(task); // if (task.getTaskExecuteException() != null) { // throw task.getTaskExecuteException(); // } // } else { // asyncPool.execute(task); // } // } // syncPool.shutdown(); // asyncPool.shutdown(); // return null; // } // // /** // * Insert task at the end of task list // * // * @param task the task which you want insert // */ // public void insertTask(Task task) { // this.tasks.add(task); // } // // /** // * Insert task at certain index of task list // * // * @param index the sequence you want your task execute // * @param task the task which you want insert // */ // public void insertTask(Integer index, Task task) { // this.tasks.add(index, task); // } // // /** // * Remove task which at the end of task list // * // * @param index the sequence of task // */ // public void removeTask(Integer index) { // this.tasks.remove(index.intValue()); // } // // /** // * Receive index of certain task through task. // * // * @param taskName of task // * @return first index of task which hold that name, -1 if not exists. // */ // public Integer getTaskSequenceByName(String taskName) { // for (int i = 0; i < this.tasks.size(); i++) { // if (this.tasks.get(i).getName().equals(taskName)) { // return i + 1; // } // } // return -1; // } // // }
import java.io.File; import java.io.IOException; import net.teamtf.launcher.util.task.SynchronizedTask; import net.teamtf.launcher.util.task.TaskManager; import org.apache.commons.io.FileUtils;
package net.teamtf.launcher.basis; /** * @Author Decker */ public class LaunchTaskManagerFactory { private File launchFolder; private File nativeFolder; private File versionFolder; private File assetsFoler; public LaunchTaskManagerFactory() { super(); } public void setLaunchingFolder(File folder) { this.launchFolder = folder; }
// Path: src/main/java/net/teamtf/launcher/util/task/SynchronizedTask.java // public abstract class SynchronizedTask implements Task { // // private TaskExecuteException exceptionDuringExecuting; // // public SynchronizedTask() { // // } // // @Override // public abstract void run(); // // @Override // public Boolean isSynchronized() { // return true; // } // // @Override // public TaskExecuteException getTaskExecuteException() { // return this.exceptionDuringExecuting; // } // // // protected void setTaskExecuteException(Exception exception) { // this.exceptionDuringExecuting=new TaskExecuteException(this, exception); // } // } // // Path: src/main/java/net/teamtf/launcher/util/task/TaskManager.java // public class TaskManager { // // private final LinkedList<Task> tasks; // // public TaskManager() { // this.tasks = new LinkedList<>(); // } // // public Void executeTasks() { // // LinkedList<Task> reversedList = (LinkedList<Task>) this.tasks.clone(); // Collections.reverse(this.tasks); // // ExecutorService syncPool = Executors.newSingleThreadExecutor(); // ExecutorService asyncPool = Executors.newCachedThreadPool(); // // // for (Task task : reversedList) { // if (task.isSynchronized()) { // syncPool.execute(task); // if (task.getTaskExecuteException() != null) { // throw task.getTaskExecuteException(); // } // } else { // asyncPool.execute(task); // } // } // syncPool.shutdown(); // asyncPool.shutdown(); // return null; // } // // /** // * Insert task at the end of task list // * // * @param task the task which you want insert // */ // public void insertTask(Task task) { // this.tasks.add(task); // } // // /** // * Insert task at certain index of task list // * // * @param index the sequence you want your task execute // * @param task the task which you want insert // */ // public void insertTask(Integer index, Task task) { // this.tasks.add(index, task); // } // // /** // * Remove task which at the end of task list // * // * @param index the sequence of task // */ // public void removeTask(Integer index) { // this.tasks.remove(index.intValue()); // } // // /** // * Receive index of certain task through task. // * // * @param taskName of task // * @return first index of task which hold that name, -1 if not exists. // */ // public Integer getTaskSequenceByName(String taskName) { // for (int i = 0; i < this.tasks.size(); i++) { // if (this.tasks.get(i).getName().equals(taskName)) { // return i + 1; // } // } // return -1; // } // // } // Path: src/main/java/net/teamtf/launcher/basis/LaunchTaskManagerFactory.java import java.io.File; import java.io.IOException; import net.teamtf.launcher.util.task.SynchronizedTask; import net.teamtf.launcher.util.task.TaskManager; import org.apache.commons.io.FileUtils; package net.teamtf.launcher.basis; /** * @Author Decker */ public class LaunchTaskManagerFactory { private File launchFolder; private File nativeFolder; private File versionFolder; private File assetsFoler; public LaunchTaskManagerFactory() { super(); } public void setLaunchingFolder(File folder) { this.launchFolder = folder; }
public TaskManager buildTaskManager() {
InfinityStudio/TrigonometryLauncher
src/main/java/net/teamtf/launcher/basis/LaunchTaskManagerFactory.java
// Path: src/main/java/net/teamtf/launcher/util/task/SynchronizedTask.java // public abstract class SynchronizedTask implements Task { // // private TaskExecuteException exceptionDuringExecuting; // // public SynchronizedTask() { // // } // // @Override // public abstract void run(); // // @Override // public Boolean isSynchronized() { // return true; // } // // @Override // public TaskExecuteException getTaskExecuteException() { // return this.exceptionDuringExecuting; // } // // // protected void setTaskExecuteException(Exception exception) { // this.exceptionDuringExecuting=new TaskExecuteException(this, exception); // } // } // // Path: src/main/java/net/teamtf/launcher/util/task/TaskManager.java // public class TaskManager { // // private final LinkedList<Task> tasks; // // public TaskManager() { // this.tasks = new LinkedList<>(); // } // // public Void executeTasks() { // // LinkedList<Task> reversedList = (LinkedList<Task>) this.tasks.clone(); // Collections.reverse(this.tasks); // // ExecutorService syncPool = Executors.newSingleThreadExecutor(); // ExecutorService asyncPool = Executors.newCachedThreadPool(); // // // for (Task task : reversedList) { // if (task.isSynchronized()) { // syncPool.execute(task); // if (task.getTaskExecuteException() != null) { // throw task.getTaskExecuteException(); // } // } else { // asyncPool.execute(task); // } // } // syncPool.shutdown(); // asyncPool.shutdown(); // return null; // } // // /** // * Insert task at the end of task list // * // * @param task the task which you want insert // */ // public void insertTask(Task task) { // this.tasks.add(task); // } // // /** // * Insert task at certain index of task list // * // * @param index the sequence you want your task execute // * @param task the task which you want insert // */ // public void insertTask(Integer index, Task task) { // this.tasks.add(index, task); // } // // /** // * Remove task which at the end of task list // * // * @param index the sequence of task // */ // public void removeTask(Integer index) { // this.tasks.remove(index.intValue()); // } // // /** // * Receive index of certain task through task. // * // * @param taskName of task // * @return first index of task which hold that name, -1 if not exists. // */ // public Integer getTaskSequenceByName(String taskName) { // for (int i = 0; i < this.tasks.size(); i++) { // if (this.tasks.get(i).getName().equals(taskName)) { // return i + 1; // } // } // return -1; // } // // }
import java.io.File; import java.io.IOException; import net.teamtf.launcher.util.task.SynchronizedTask; import net.teamtf.launcher.util.task.TaskManager; import org.apache.commons.io.FileUtils;
package net.teamtf.launcher.basis; /** * @Author Decker */ public class LaunchTaskManagerFactory { private File launchFolder; private File nativeFolder; private File versionFolder; private File assetsFoler; public LaunchTaskManagerFactory() { super(); } public void setLaunchingFolder(File folder) { this.launchFolder = folder; } public TaskManager buildTaskManager() { TaskManager result = new TaskManager();
// Path: src/main/java/net/teamtf/launcher/util/task/SynchronizedTask.java // public abstract class SynchronizedTask implements Task { // // private TaskExecuteException exceptionDuringExecuting; // // public SynchronizedTask() { // // } // // @Override // public abstract void run(); // // @Override // public Boolean isSynchronized() { // return true; // } // // @Override // public TaskExecuteException getTaskExecuteException() { // return this.exceptionDuringExecuting; // } // // // protected void setTaskExecuteException(Exception exception) { // this.exceptionDuringExecuting=new TaskExecuteException(this, exception); // } // } // // Path: src/main/java/net/teamtf/launcher/util/task/TaskManager.java // public class TaskManager { // // private final LinkedList<Task> tasks; // // public TaskManager() { // this.tasks = new LinkedList<>(); // } // // public Void executeTasks() { // // LinkedList<Task> reversedList = (LinkedList<Task>) this.tasks.clone(); // Collections.reverse(this.tasks); // // ExecutorService syncPool = Executors.newSingleThreadExecutor(); // ExecutorService asyncPool = Executors.newCachedThreadPool(); // // // for (Task task : reversedList) { // if (task.isSynchronized()) { // syncPool.execute(task); // if (task.getTaskExecuteException() != null) { // throw task.getTaskExecuteException(); // } // } else { // asyncPool.execute(task); // } // } // syncPool.shutdown(); // asyncPool.shutdown(); // return null; // } // // /** // * Insert task at the end of task list // * // * @param task the task which you want insert // */ // public void insertTask(Task task) { // this.tasks.add(task); // } // // /** // * Insert task at certain index of task list // * // * @param index the sequence you want your task execute // * @param task the task which you want insert // */ // public void insertTask(Integer index, Task task) { // this.tasks.add(index, task); // } // // /** // * Remove task which at the end of task list // * // * @param index the sequence of task // */ // public void removeTask(Integer index) { // this.tasks.remove(index.intValue()); // } // // /** // * Receive index of certain task through task. // * // * @param taskName of task // * @return first index of task which hold that name, -1 if not exists. // */ // public Integer getTaskSequenceByName(String taskName) { // for (int i = 0; i < this.tasks.size(); i++) { // if (this.tasks.get(i).getName().equals(taskName)) { // return i + 1; // } // } // return -1; // } // // } // Path: src/main/java/net/teamtf/launcher/basis/LaunchTaskManagerFactory.java import java.io.File; import java.io.IOException; import net.teamtf.launcher.util.task.SynchronizedTask; import net.teamtf.launcher.util.task.TaskManager; import org.apache.commons.io.FileUtils; package net.teamtf.launcher.basis; /** * @Author Decker */ public class LaunchTaskManagerFactory { private File launchFolder; private File nativeFolder; private File versionFolder; private File assetsFoler; public LaunchTaskManagerFactory() { super(); } public void setLaunchingFolder(File folder) { this.launchFolder = folder; } public TaskManager buildTaskManager() { TaskManager result = new TaskManager();
result.insertTask(new SynchronizedTask() {
InfinityStudio/TrigonometryLauncher
src/main/java/net/teamtf/launcher/Start.java
// Path: src/main/java/net/teamtf/launcher/core/Engine.java // public class Engine { // // private static Engine instance; // // public static void initEngine() throws Exception { // if (instance == null) { // instance = new Engine(); // } else { // throw new IllegalAccessException("Engine has already initialized"); // } // } // // public static Engine getEngine() { // return instance; // } // // private final File gameDir; // private final File launcherDir; // private final Log logger; // private final TLFileSystem fileSystem; // private UIController uiController; // private Launcher launcher; // private I18n i18n; // private final AddonLoader addonLoader; // private final IConfig launcherConfiguration, gameConfiguration; // private AuthClient authClient; // private LibraryProvider libraryProvider; // private AssestsProvider assestsProvider; // private NativeProvider nativeProvider; // private VersionProvider versionProvider; // // private Engine() throws Exception { // this.launcherDir = new File(new File(URLDecoder.decode(Engine.class.getProtectionDomain().getCodeSource().getLocation().getPath(), // "UTF-8")).getParentFile().getCanonicalPath()); // // this.logger = LogFactory.getLog("MainLogger"); // this.fileSystem = new TLFileSystem(); // // this.launcherConfiguration = new Configuration(this.fileSystem.getLauncherConfigFile(), "launcherconfig"); // this.launcherConfiguration.setConfig("launcher.dir", this.launcherDir.getAbsolutePath()); // this.gameConfiguration = new Configuration(this.fileSystem.getGameConfigFile(), "gameconfig"); // // this.gameDir = FileUtils.getFile(this.launcherConfiguration.getString("game.dir")); // this.i18n = new DefaultI18n(); // this.logger.info(this.i18n.getTranslation("lang.welcome")); // // this.uiController = new DefaultUIControler(); // this.launcher = new DefaultLauncher(); // // this.addonLoader = new AddonLoader(this.launcherConfiguration.getString("addon.dir")); // } // // /** // * Engine start working. 1.load add addons. // * // * @throws Exception // */ // public void start() throws Exception { // //TODO:Still under develop // //I just put everything here as possible. // this.addonLoader.loadFilesFromFolder(); // this.addonLoader.perLoadAllAddons(); // this.getUiController().getMainWindow(); // this.addonLoader.loadAllAddons(); // this.getUiController().getMainWindow().setVisible(true); // this.addonLoader.postLoadAllAddons(); // // } // // public Log getLogger() { // return this.logger; // } // // public TLFileSystem getFileSystem() { // return this.fileSystem; // } // // public UIController getUIController() { // return this.getUiController(); // } // // /** // * Receive current launcher of // * // * @return launcher which current using // */ // public Launcher getLauncher() { // return launcher; // } // // public void setLauncher(Launcher launcher) { // this.launcher = launcher; // } // // public AddonLoader getAddonLoader() { // return addonLoader; // } // // /** // * @return the launcher configuration // */ // public IConfig getLauncherConfig() { // return this.launcherConfiguration; // } // // public void stop() { // this.getUiController().closeAllWindow(); // } // // /** // * @param uiController the uiController to set // */ // public void setUiController(UIController uiController) { // this.uiController = uiController; // } // // /** // * @return the i18n // */ // public I18n getI18n() { // return i18n; // } // // /** // * @param i18n the i18n to set // */ // public void setI18n(I18n i18n) { // this.i18n = i18n; // } // // /** // * @return the gameDir // */ // public File getGameDir() { // return gameDir; // } // // public UIController getUiController() { // return uiController; // } // // public AuthClient getAuthClient() { // return authClient; // } // // public void setAuthClient(AuthClient authClient) { // this.authClient = authClient; // } // // public LibraryProvider getLibraryProvider() { // return libraryProvider; // } // // public void setLibraryProvider(LibraryProvider libraryProvider) { // this.libraryProvider = libraryProvider; // } // } // // Path: src/main/java/net/teamtf/launcher/util/DownloadUtils.java // public class DownloadUtils { // public static void downloadToFile(String url, File file) throws IOException { // File tempDir = Engine.getEngine().getFileSystem().createNewTempDir(); // // File path = new File(tempDir.getAbsolutePath(), file.getName()); // FileUtils.copyURLToFile(new URL(url), path); // FileUtils.moveFile(path, file); // } // }
import net.teamtf.launcher.core.Engine; import net.teamtf.launcher.util.DownloadUtils;
package net.teamtf.launcher; /** * * @author Decker */ public class Start { public static void main(String[] args) throws Exception{
// Path: src/main/java/net/teamtf/launcher/core/Engine.java // public class Engine { // // private static Engine instance; // // public static void initEngine() throws Exception { // if (instance == null) { // instance = new Engine(); // } else { // throw new IllegalAccessException("Engine has already initialized"); // } // } // // public static Engine getEngine() { // return instance; // } // // private final File gameDir; // private final File launcherDir; // private final Log logger; // private final TLFileSystem fileSystem; // private UIController uiController; // private Launcher launcher; // private I18n i18n; // private final AddonLoader addonLoader; // private final IConfig launcherConfiguration, gameConfiguration; // private AuthClient authClient; // private LibraryProvider libraryProvider; // private AssestsProvider assestsProvider; // private NativeProvider nativeProvider; // private VersionProvider versionProvider; // // private Engine() throws Exception { // this.launcherDir = new File(new File(URLDecoder.decode(Engine.class.getProtectionDomain().getCodeSource().getLocation().getPath(), // "UTF-8")).getParentFile().getCanonicalPath()); // // this.logger = LogFactory.getLog("MainLogger"); // this.fileSystem = new TLFileSystem(); // // this.launcherConfiguration = new Configuration(this.fileSystem.getLauncherConfigFile(), "launcherconfig"); // this.launcherConfiguration.setConfig("launcher.dir", this.launcherDir.getAbsolutePath()); // this.gameConfiguration = new Configuration(this.fileSystem.getGameConfigFile(), "gameconfig"); // // this.gameDir = FileUtils.getFile(this.launcherConfiguration.getString("game.dir")); // this.i18n = new DefaultI18n(); // this.logger.info(this.i18n.getTranslation("lang.welcome")); // // this.uiController = new DefaultUIControler(); // this.launcher = new DefaultLauncher(); // // this.addonLoader = new AddonLoader(this.launcherConfiguration.getString("addon.dir")); // } // // /** // * Engine start working. 1.load add addons. // * // * @throws Exception // */ // public void start() throws Exception { // //TODO:Still under develop // //I just put everything here as possible. // this.addonLoader.loadFilesFromFolder(); // this.addonLoader.perLoadAllAddons(); // this.getUiController().getMainWindow(); // this.addonLoader.loadAllAddons(); // this.getUiController().getMainWindow().setVisible(true); // this.addonLoader.postLoadAllAddons(); // // } // // public Log getLogger() { // return this.logger; // } // // public TLFileSystem getFileSystem() { // return this.fileSystem; // } // // public UIController getUIController() { // return this.getUiController(); // } // // /** // * Receive current launcher of // * // * @return launcher which current using // */ // public Launcher getLauncher() { // return launcher; // } // // public void setLauncher(Launcher launcher) { // this.launcher = launcher; // } // // public AddonLoader getAddonLoader() { // return addonLoader; // } // // /** // * @return the launcher configuration // */ // public IConfig getLauncherConfig() { // return this.launcherConfiguration; // } // // public void stop() { // this.getUiController().closeAllWindow(); // } // // /** // * @param uiController the uiController to set // */ // public void setUiController(UIController uiController) { // this.uiController = uiController; // } // // /** // * @return the i18n // */ // public I18n getI18n() { // return i18n; // } // // /** // * @param i18n the i18n to set // */ // public void setI18n(I18n i18n) { // this.i18n = i18n; // } // // /** // * @return the gameDir // */ // public File getGameDir() { // return gameDir; // } // // public UIController getUiController() { // return uiController; // } // // public AuthClient getAuthClient() { // return authClient; // } // // public void setAuthClient(AuthClient authClient) { // this.authClient = authClient; // } // // public LibraryProvider getLibraryProvider() { // return libraryProvider; // } // // public void setLibraryProvider(LibraryProvider libraryProvider) { // this.libraryProvider = libraryProvider; // } // } // // Path: src/main/java/net/teamtf/launcher/util/DownloadUtils.java // public class DownloadUtils { // public static void downloadToFile(String url, File file) throws IOException { // File tempDir = Engine.getEngine().getFileSystem().createNewTempDir(); // // File path = new File(tempDir.getAbsolutePath(), file.getName()); // FileUtils.copyURLToFile(new URL(url), path); // FileUtils.moveFile(path, file); // } // } // Path: src/main/java/net/teamtf/launcher/Start.java import net.teamtf.launcher.core.Engine; import net.teamtf.launcher.util.DownloadUtils; package net.teamtf.launcher; /** * * @author Decker */ public class Start { public static void main(String[] args) throws Exception{
Engine.initEngine();
InfinityStudio/TrigonometryLauncher
src/main/java/net/teamtf/launcher/provider/library/LibraryProvider.java
// Path: src/main/java/net/teamtf/launcher/util/DownloadUtils.java // public class DownloadUtils { // public static void downloadToFile(String url, File file) throws IOException { // File tempDir = Engine.getEngine().getFileSystem().createNewTempDir(); // // File path = new File(tempDir.getAbsolutePath(), file.getName()); // FileUtils.copyURLToFile(new URL(url), path); // FileUtils.moveFile(path, file); // } // } // // Path: src/main/java/net/teamtf/launcher/util/LibraryUtils.java // public class LibraryUtils { // // public static Path resolveLibPath(File libFolder, String groupID, String artifactId, String version) { // File target=new File(libFolder.getPath()); // for (String element : StringUtils.split(groupID, '.')) { // target=FileUtils.getFile(target, element); // } // target=FileUtils.getFile(target, version); // target=FileUtils.getFile(target, artifactId); // return target.toPath(); // } // // }
import com.google.gson.Gson; import com.google.gson.JsonElement; import com.google.gson.JsonObject; import java.io.File; import java.io.IOException; import java.net.URL; import java.nio.file.Path; import java.util.HashMap; import net.teamtf.launcher.util.DownloadUtils; import net.teamtf.launcher.util.LibraryUtils; import org.apache.commons.io.FileUtils; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory;
package net.teamtf.launcher.provider.library; /** * * @author Decker */ public class LibraryProvider { private static Log logger; static { logger=LogFactory.getLog(LibraryProvider.class); } private HashMap<String, Library> libraryQuery; private File libraryFolder; private File repoFile; private URL repoUrl; private String repoContent; public LibraryProvider(File libraryFolder,File repoFile, URL repoUrl) throws IOException { this.libraryQuery = new HashMap<>(); this.libraryFolder = libraryFolder; this.repoUrl = repoUrl; this.repoFile=repoFile; //Try to download the latest version of librepo.json try { //Files.deleteIfExists(FileUtils.getFile(libraryFolder, "librepo.json").toPath());
// Path: src/main/java/net/teamtf/launcher/util/DownloadUtils.java // public class DownloadUtils { // public static void downloadToFile(String url, File file) throws IOException { // File tempDir = Engine.getEngine().getFileSystem().createNewTempDir(); // // File path = new File(tempDir.getAbsolutePath(), file.getName()); // FileUtils.copyURLToFile(new URL(url), path); // FileUtils.moveFile(path, file); // } // } // // Path: src/main/java/net/teamtf/launcher/util/LibraryUtils.java // public class LibraryUtils { // // public static Path resolveLibPath(File libFolder, String groupID, String artifactId, String version) { // File target=new File(libFolder.getPath()); // for (String element : StringUtils.split(groupID, '.')) { // target=FileUtils.getFile(target, element); // } // target=FileUtils.getFile(target, version); // target=FileUtils.getFile(target, artifactId); // return target.toPath(); // } // // } // Path: src/main/java/net/teamtf/launcher/provider/library/LibraryProvider.java import com.google.gson.Gson; import com.google.gson.JsonElement; import com.google.gson.JsonObject; import java.io.File; import java.io.IOException; import java.net.URL; import java.nio.file.Path; import java.util.HashMap; import net.teamtf.launcher.util.DownloadUtils; import net.teamtf.launcher.util.LibraryUtils; import org.apache.commons.io.FileUtils; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; package net.teamtf.launcher.provider.library; /** * * @author Decker */ public class LibraryProvider { private static Log logger; static { logger=LogFactory.getLog(LibraryProvider.class); } private HashMap<String, Library> libraryQuery; private File libraryFolder; private File repoFile; private URL repoUrl; private String repoContent; public LibraryProvider(File libraryFolder,File repoFile, URL repoUrl) throws IOException { this.libraryQuery = new HashMap<>(); this.libraryFolder = libraryFolder; this.repoUrl = repoUrl; this.repoFile=repoFile; //Try to download the latest version of librepo.json try { //Files.deleteIfExists(FileUtils.getFile(libraryFolder, "librepo.json").toPath());
DownloadUtils.downloadToFile(repoUrl.toString(), FileUtils.getFile(libraryFolder, "librepo.json"));
InfinityStudio/TrigonometryLauncher
src/main/java/net/teamtf/launcher/provider/library/LibraryProvider.java
// Path: src/main/java/net/teamtf/launcher/util/DownloadUtils.java // public class DownloadUtils { // public static void downloadToFile(String url, File file) throws IOException { // File tempDir = Engine.getEngine().getFileSystem().createNewTempDir(); // // File path = new File(tempDir.getAbsolutePath(), file.getName()); // FileUtils.copyURLToFile(new URL(url), path); // FileUtils.moveFile(path, file); // } // } // // Path: src/main/java/net/teamtf/launcher/util/LibraryUtils.java // public class LibraryUtils { // // public static Path resolveLibPath(File libFolder, String groupID, String artifactId, String version) { // File target=new File(libFolder.getPath()); // for (String element : StringUtils.split(groupID, '.')) { // target=FileUtils.getFile(target, element); // } // target=FileUtils.getFile(target, version); // target=FileUtils.getFile(target, artifactId); // return target.toPath(); // } // // }
import com.google.gson.Gson; import com.google.gson.JsonElement; import com.google.gson.JsonObject; import java.io.File; import java.io.IOException; import java.net.URL; import java.nio.file.Path; import java.util.HashMap; import net.teamtf.launcher.util.DownloadUtils; import net.teamtf.launcher.util.LibraryUtils; import org.apache.commons.io.FileUtils; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory;
private String repoContent; public LibraryProvider(File libraryFolder,File repoFile, URL repoUrl) throws IOException { this.libraryQuery = new HashMap<>(); this.libraryFolder = libraryFolder; this.repoUrl = repoUrl; this.repoFile=repoFile; //Try to download the latest version of librepo.json try { //Files.deleteIfExists(FileUtils.getFile(libraryFolder, "librepo.json").toPath()); DownloadUtils.downloadToFile(repoUrl.toString(), FileUtils.getFile(libraryFolder, "librepo.json")); } catch (Exception e) { logger.warn(String.format("LibProvider:Can not fetch repo.json form %s", repoUrl)); } File repoJsonFile = FileUtils.getFile(libraryFolder, "librepo.json"); if (!repoJsonFile.exists()) { logger.warn("LibProvider:repo.json not exists, you have to connect to internet at first time."); throw new IOException("librepo.json not found"); } JsonObject repoJsonObject = new Gson().fromJson(FileUtils.readFileToString(repoJsonFile), JsonObject.class); for (JsonElement lib : repoJsonObject.getAsJsonArray("libraries")) { String groupId = lib.getAsJsonObject().get("groupId").getAsString(); String artifactId = lib.getAsJsonObject().get("artifactId").getAsString(); String version = lib.getAsJsonObject().get("version").getAsString(); String url = lib.getAsJsonObject().get("url").getAsString();
// Path: src/main/java/net/teamtf/launcher/util/DownloadUtils.java // public class DownloadUtils { // public static void downloadToFile(String url, File file) throws IOException { // File tempDir = Engine.getEngine().getFileSystem().createNewTempDir(); // // File path = new File(tempDir.getAbsolutePath(), file.getName()); // FileUtils.copyURLToFile(new URL(url), path); // FileUtils.moveFile(path, file); // } // } // // Path: src/main/java/net/teamtf/launcher/util/LibraryUtils.java // public class LibraryUtils { // // public static Path resolveLibPath(File libFolder, String groupID, String artifactId, String version) { // File target=new File(libFolder.getPath()); // for (String element : StringUtils.split(groupID, '.')) { // target=FileUtils.getFile(target, element); // } // target=FileUtils.getFile(target, version); // target=FileUtils.getFile(target, artifactId); // return target.toPath(); // } // // } // Path: src/main/java/net/teamtf/launcher/provider/library/LibraryProvider.java import com.google.gson.Gson; import com.google.gson.JsonElement; import com.google.gson.JsonObject; import java.io.File; import java.io.IOException; import java.net.URL; import java.nio.file.Path; import java.util.HashMap; import net.teamtf.launcher.util.DownloadUtils; import net.teamtf.launcher.util.LibraryUtils; import org.apache.commons.io.FileUtils; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; private String repoContent; public LibraryProvider(File libraryFolder,File repoFile, URL repoUrl) throws IOException { this.libraryQuery = new HashMap<>(); this.libraryFolder = libraryFolder; this.repoUrl = repoUrl; this.repoFile=repoFile; //Try to download the latest version of librepo.json try { //Files.deleteIfExists(FileUtils.getFile(libraryFolder, "librepo.json").toPath()); DownloadUtils.downloadToFile(repoUrl.toString(), FileUtils.getFile(libraryFolder, "librepo.json")); } catch (Exception e) { logger.warn(String.format("LibProvider:Can not fetch repo.json form %s", repoUrl)); } File repoJsonFile = FileUtils.getFile(libraryFolder, "librepo.json"); if (!repoJsonFile.exists()) { logger.warn("LibProvider:repo.json not exists, you have to connect to internet at first time."); throw new IOException("librepo.json not found"); } JsonObject repoJsonObject = new Gson().fromJson(FileUtils.readFileToString(repoJsonFile), JsonObject.class); for (JsonElement lib : repoJsonObject.getAsJsonArray("libraries")) { String groupId = lib.getAsJsonObject().get("groupId").getAsString(); String artifactId = lib.getAsJsonObject().get("artifactId").getAsString(); String version = lib.getAsJsonObject().get("version").getAsString(); String url = lib.getAsJsonObject().get("url").getAsString();
Path inferPath = LibraryUtils.resolveLibPath(libraryFolder, groupId, artifactId, version);
InfinityStudio/TrigonometryLauncher
src/main/java/net/teamtf/launcher/basis/gui/DefaultUIControler.java
// Path: src/main/java/net/teamtf/launcher/core/UIController.java // public interface UIController { // // public Window getMainWindow(); // public Dialog getConfigDialog(); // public Dialog getAuthDialog(); // // public void closeAllWindow(); // } // // Path: src/main/java/net/teamtf/launcher/core/Engine.java // public class Engine { // // private static Engine instance; // // public static void initEngine() throws Exception { // if (instance == null) { // instance = new Engine(); // } else { // throw new IllegalAccessException("Engine has already initialized"); // } // } // // public static Engine getEngine() { // return instance; // } // // private final File gameDir; // private final File launcherDir; // private final Log logger; // private final TLFileSystem fileSystem; // private UIController uiController; // private Launcher launcher; // private I18n i18n; // private final AddonLoader addonLoader; // private final IConfig launcherConfiguration, gameConfiguration; // private AuthClient authClient; // private LibraryProvider libraryProvider; // private AssestsProvider assestsProvider; // private NativeProvider nativeProvider; // private VersionProvider versionProvider; // // private Engine() throws Exception { // this.launcherDir = new File(new File(URLDecoder.decode(Engine.class.getProtectionDomain().getCodeSource().getLocation().getPath(), // "UTF-8")).getParentFile().getCanonicalPath()); // // this.logger = LogFactory.getLog("MainLogger"); // this.fileSystem = new TLFileSystem(); // // this.launcherConfiguration = new Configuration(this.fileSystem.getLauncherConfigFile(), "launcherconfig"); // this.launcherConfiguration.setConfig("launcher.dir", this.launcherDir.getAbsolutePath()); // this.gameConfiguration = new Configuration(this.fileSystem.getGameConfigFile(), "gameconfig"); // // this.gameDir = FileUtils.getFile(this.launcherConfiguration.getString("game.dir")); // this.i18n = new DefaultI18n(); // this.logger.info(this.i18n.getTranslation("lang.welcome")); // // this.uiController = new DefaultUIControler(); // this.launcher = new DefaultLauncher(); // // this.addonLoader = new AddonLoader(this.launcherConfiguration.getString("addon.dir")); // } // // /** // * Engine start working. 1.load add addons. // * // * @throws Exception // */ // public void start() throws Exception { // //TODO:Still under develop // //I just put everything here as possible. // this.addonLoader.loadFilesFromFolder(); // this.addonLoader.perLoadAllAddons(); // this.getUiController().getMainWindow(); // this.addonLoader.loadAllAddons(); // this.getUiController().getMainWindow().setVisible(true); // this.addonLoader.postLoadAllAddons(); // // } // // public Log getLogger() { // return this.logger; // } // // public TLFileSystem getFileSystem() { // return this.fileSystem; // } // // public UIController getUIController() { // return this.getUiController(); // } // // /** // * Receive current launcher of // * // * @return launcher which current using // */ // public Launcher getLauncher() { // return launcher; // } // // public void setLauncher(Launcher launcher) { // this.launcher = launcher; // } // // public AddonLoader getAddonLoader() { // return addonLoader; // } // // /** // * @return the launcher configuration // */ // public IConfig getLauncherConfig() { // return this.launcherConfiguration; // } // // public void stop() { // this.getUiController().closeAllWindow(); // } // // /** // * @param uiController the uiController to set // */ // public void setUiController(UIController uiController) { // this.uiController = uiController; // } // // /** // * @return the i18n // */ // public I18n getI18n() { // return i18n; // } // // /** // * @param i18n the i18n to set // */ // public void setI18n(I18n i18n) { // this.i18n = i18n; // } // // /** // * @return the gameDir // */ // public File getGameDir() { // return gameDir; // } // // public UIController getUiController() { // return uiController; // } // // public AuthClient getAuthClient() { // return authClient; // } // // public void setAuthClient(AuthClient authClient) { // this.authClient = authClient; // } // // public LibraryProvider getLibraryProvider() { // return libraryProvider; // } // // public void setLibraryProvider(LibraryProvider libraryProvider) { // this.libraryProvider = libraryProvider; // } // }
import java.awt.EventQueue; import java.lang.reflect.InvocationTargetException; import java.util.logging.Level; import java.util.logging.Logger; import net.teamtf.launcher.core.UIController; import javax.swing.*; import net.teamtf.launcher.core.Engine;
package net.teamtf.launcher.basis.gui; /** * Created by Decker on 2014/12/27. */ public class DefaultUIControler implements UIController { MainFrame mainFrame; public DefaultUIControler() { try { EventQueue.invokeAndWait(new Runnable() { @Override public void run() { mainFrame = new MainFrame(); } }); } catch (InterruptedException | InvocationTargetException ex) {
// Path: src/main/java/net/teamtf/launcher/core/UIController.java // public interface UIController { // // public Window getMainWindow(); // public Dialog getConfigDialog(); // public Dialog getAuthDialog(); // // public void closeAllWindow(); // } // // Path: src/main/java/net/teamtf/launcher/core/Engine.java // public class Engine { // // private static Engine instance; // // public static void initEngine() throws Exception { // if (instance == null) { // instance = new Engine(); // } else { // throw new IllegalAccessException("Engine has already initialized"); // } // } // // public static Engine getEngine() { // return instance; // } // // private final File gameDir; // private final File launcherDir; // private final Log logger; // private final TLFileSystem fileSystem; // private UIController uiController; // private Launcher launcher; // private I18n i18n; // private final AddonLoader addonLoader; // private final IConfig launcherConfiguration, gameConfiguration; // private AuthClient authClient; // private LibraryProvider libraryProvider; // private AssestsProvider assestsProvider; // private NativeProvider nativeProvider; // private VersionProvider versionProvider; // // private Engine() throws Exception { // this.launcherDir = new File(new File(URLDecoder.decode(Engine.class.getProtectionDomain().getCodeSource().getLocation().getPath(), // "UTF-8")).getParentFile().getCanonicalPath()); // // this.logger = LogFactory.getLog("MainLogger"); // this.fileSystem = new TLFileSystem(); // // this.launcherConfiguration = new Configuration(this.fileSystem.getLauncherConfigFile(), "launcherconfig"); // this.launcherConfiguration.setConfig("launcher.dir", this.launcherDir.getAbsolutePath()); // this.gameConfiguration = new Configuration(this.fileSystem.getGameConfigFile(), "gameconfig"); // // this.gameDir = FileUtils.getFile(this.launcherConfiguration.getString("game.dir")); // this.i18n = new DefaultI18n(); // this.logger.info(this.i18n.getTranslation("lang.welcome")); // // this.uiController = new DefaultUIControler(); // this.launcher = new DefaultLauncher(); // // this.addonLoader = new AddonLoader(this.launcherConfiguration.getString("addon.dir")); // } // // /** // * Engine start working. 1.load add addons. // * // * @throws Exception // */ // public void start() throws Exception { // //TODO:Still under develop // //I just put everything here as possible. // this.addonLoader.loadFilesFromFolder(); // this.addonLoader.perLoadAllAddons(); // this.getUiController().getMainWindow(); // this.addonLoader.loadAllAddons(); // this.getUiController().getMainWindow().setVisible(true); // this.addonLoader.postLoadAllAddons(); // // } // // public Log getLogger() { // return this.logger; // } // // public TLFileSystem getFileSystem() { // return this.fileSystem; // } // // public UIController getUIController() { // return this.getUiController(); // } // // /** // * Receive current launcher of // * // * @return launcher which current using // */ // public Launcher getLauncher() { // return launcher; // } // // public void setLauncher(Launcher launcher) { // this.launcher = launcher; // } // // public AddonLoader getAddonLoader() { // return addonLoader; // } // // /** // * @return the launcher configuration // */ // public IConfig getLauncherConfig() { // return this.launcherConfiguration; // } // // public void stop() { // this.getUiController().closeAllWindow(); // } // // /** // * @param uiController the uiController to set // */ // public void setUiController(UIController uiController) { // this.uiController = uiController; // } // // /** // * @return the i18n // */ // public I18n getI18n() { // return i18n; // } // // /** // * @param i18n the i18n to set // */ // public void setI18n(I18n i18n) { // this.i18n = i18n; // } // // /** // * @return the gameDir // */ // public File getGameDir() { // return gameDir; // } // // public UIController getUiController() { // return uiController; // } // // public AuthClient getAuthClient() { // return authClient; // } // // public void setAuthClient(AuthClient authClient) { // this.authClient = authClient; // } // // public LibraryProvider getLibraryProvider() { // return libraryProvider; // } // // public void setLibraryProvider(LibraryProvider libraryProvider) { // this.libraryProvider = libraryProvider; // } // } // Path: src/main/java/net/teamtf/launcher/basis/gui/DefaultUIControler.java import java.awt.EventQueue; import java.lang.reflect.InvocationTargetException; import java.util.logging.Level; import java.util.logging.Logger; import net.teamtf.launcher.core.UIController; import javax.swing.*; import net.teamtf.launcher.core.Engine; package net.teamtf.launcher.basis.gui; /** * Created by Decker on 2014/12/27. */ public class DefaultUIControler implements UIController { MainFrame mainFrame; public DefaultUIControler() { try { EventQueue.invokeAndWait(new Runnable() { @Override public void run() { mainFrame = new MainFrame(); } }); } catch (InterruptedException | InvocationTargetException ex) {
Engine.getEngine().getLogger().fatal("Cant start up main window", ex);
Drazuam/RunicArcana
src/main/java/com/latenighters/runicarcana/common/items/trinkets/HearthstoneItem.java
// Path: src/main/java/com/latenighters/runicarcana/capabilities/BasicCurioProvider.java // public class BasicCurioProvider implements ICapabilityProvider { // // final LazyOptional<ICurio> capability; // // public BasicCurioProvider(ICurio curio) { // // this.capability = LazyOptional.of(() -> curio); // } // // @SuppressWarnings("ConstantConditions") // @Nonnull // @Override // public <T> LazyOptional<T> getCapability(@Nonnull Capability<T> cap, @Nullable Direction side) { // // return CuriosCapability.ITEM.orEmpty(cap, capability); // } // } // // Path: src/main/java/com/latenighters/runicarcana/common/items/IClickable.java // public interface IClickable { // // //do the action - this is performed server side // //returns true when behavior is as expected // boolean onClick(PlayerEntity player, ItemStack itemStack, Container container, int slot); // // } // // Path: src/main/java/com/latenighters/runicarcana/common/setup/ModSetup.java // public class ModSetup { // // public static final ItemGroup ITEM_GROUP = new ItemGroup(RunicArcana.MODID) { // @Override // public ItemStack createIcon() { // return new ItemStack(Registration.CHALK.get()); // } // }; // } // // Path: src/main/java/com/latenighters/runicarcana/util/Util.java // public class Util { // // public static ITextComponent loreStyle(ITextComponent textComponent){ // return textComponent.applyTextStyle(TextFormatting.DARK_PURPLE).applyTextStyle(TextFormatting.ITALIC); // } // // public static ITextComponent loreStyle(String key, Object...args){ // return loreStyle(new TranslationTextComponent(key, args)); // } // // public static ITextComponent tooltipStyle(ITextComponent textComponent){ // return textComponent.applyTextStyle(TextFormatting.GRAY); // } // // public static ITextComponent tooltipStyle(String key, Object... args){ // return tooltipStyle(new TranslationTextComponent(key, args)); // } // // public static void setPositionAndRotationAndUpdate(Entity entity, Double x, Double y, Double z, Float yaw, Float pitch) { // entity.setPositionAndUpdate(x, y, z); // entity.setPositionAndRotation(x, y, z, yaw, pitch); // } // // public static void setPositionAndRotationAndUpdate(Entity entity, Double x, Double y, Double z){ // setPositionAndRotationAndUpdate(entity, x, y, z, entity.rotationYaw, entity.rotationPitch); // } // // public static boolean checkHeadspace(World world, BlockPos pos){ // return world.isAirBlock(pos) && world.isAirBlock(pos.up()); // } // // public static void spawnParticleGroup(World world, BasicParticleType type, LivingEntity entity) { // final Random rand = new Random(); // if (world.isRemote) { // for (int i = 0; i < 30; ++i) { // double d0 = rand.nextGaussian() * 0.02D; // double d1 = rand.nextGaussian() * 0.02D; // double d2 = rand.nextGaussian() * 0.02D; // world.addParticle( // type, // entity.getPosX() + (double) (rand.nextFloat() * entity.getWidth() * 2.0F) - (double) entity.getWidth() - d0 * 10.0D, // entity.getPosY() + (double) (rand.nextFloat() * entity.getHeight()) - d1 * 10.0D, // entity.getPosZ() + (double) (rand.nextFloat() * entity.getWidth() * 2.0F) - (double) entity.getWidth() - d2 * 10.0D, d0, d1, d2 // ); // } // // } // } // // }
import com.latenighters.runicarcana.capabilities.BasicCurioProvider; import com.latenighters.runicarcana.common.items.IClickable; import com.latenighters.runicarcana.common.setup.ModSetup; import com.latenighters.runicarcana.util.Util; import net.minecraft.client.util.ITooltipFlag; import net.minecraft.entity.LivingEntity; import net.minecraft.entity.player.PlayerEntity; import net.minecraft.inventory.container.Container; import net.minecraft.item.Item; import net.minecraft.item.ItemStack; import net.minecraft.item.ItemUseContext; import net.minecraft.nbt.CompoundNBT; import net.minecraft.util.*; import net.minecraft.util.math.BlockPos; import net.minecraft.util.text.ITextComponent; import net.minecraft.util.text.TranslationTextComponent; import net.minecraft.world.World; import net.minecraft.world.dimension.DimensionType; import net.minecraftforge.common.capabilities.ICapabilityProvider; import top.theillusivec4.curios.api.capability.ICurio; import javax.annotation.Nonnull; import javax.annotation.Nullable; import java.util.List;
package com.latenighters.runicarcana.common.items.trinkets; public class HearthstoneItem extends Item implements IClickable { public HearthstoneItem() { super(new Properties() .maxStackSize(1)
// Path: src/main/java/com/latenighters/runicarcana/capabilities/BasicCurioProvider.java // public class BasicCurioProvider implements ICapabilityProvider { // // final LazyOptional<ICurio> capability; // // public BasicCurioProvider(ICurio curio) { // // this.capability = LazyOptional.of(() -> curio); // } // // @SuppressWarnings("ConstantConditions") // @Nonnull // @Override // public <T> LazyOptional<T> getCapability(@Nonnull Capability<T> cap, @Nullable Direction side) { // // return CuriosCapability.ITEM.orEmpty(cap, capability); // } // } // // Path: src/main/java/com/latenighters/runicarcana/common/items/IClickable.java // public interface IClickable { // // //do the action - this is performed server side // //returns true when behavior is as expected // boolean onClick(PlayerEntity player, ItemStack itemStack, Container container, int slot); // // } // // Path: src/main/java/com/latenighters/runicarcana/common/setup/ModSetup.java // public class ModSetup { // // public static final ItemGroup ITEM_GROUP = new ItemGroup(RunicArcana.MODID) { // @Override // public ItemStack createIcon() { // return new ItemStack(Registration.CHALK.get()); // } // }; // } // // Path: src/main/java/com/latenighters/runicarcana/util/Util.java // public class Util { // // public static ITextComponent loreStyle(ITextComponent textComponent){ // return textComponent.applyTextStyle(TextFormatting.DARK_PURPLE).applyTextStyle(TextFormatting.ITALIC); // } // // public static ITextComponent loreStyle(String key, Object...args){ // return loreStyle(new TranslationTextComponent(key, args)); // } // // public static ITextComponent tooltipStyle(ITextComponent textComponent){ // return textComponent.applyTextStyle(TextFormatting.GRAY); // } // // public static ITextComponent tooltipStyle(String key, Object... args){ // return tooltipStyle(new TranslationTextComponent(key, args)); // } // // public static void setPositionAndRotationAndUpdate(Entity entity, Double x, Double y, Double z, Float yaw, Float pitch) { // entity.setPositionAndUpdate(x, y, z); // entity.setPositionAndRotation(x, y, z, yaw, pitch); // } // // public static void setPositionAndRotationAndUpdate(Entity entity, Double x, Double y, Double z){ // setPositionAndRotationAndUpdate(entity, x, y, z, entity.rotationYaw, entity.rotationPitch); // } // // public static boolean checkHeadspace(World world, BlockPos pos){ // return world.isAirBlock(pos) && world.isAirBlock(pos.up()); // } // // public static void spawnParticleGroup(World world, BasicParticleType type, LivingEntity entity) { // final Random rand = new Random(); // if (world.isRemote) { // for (int i = 0; i < 30; ++i) { // double d0 = rand.nextGaussian() * 0.02D; // double d1 = rand.nextGaussian() * 0.02D; // double d2 = rand.nextGaussian() * 0.02D; // world.addParticle( // type, // entity.getPosX() + (double) (rand.nextFloat() * entity.getWidth() * 2.0F) - (double) entity.getWidth() - d0 * 10.0D, // entity.getPosY() + (double) (rand.nextFloat() * entity.getHeight()) - d1 * 10.0D, // entity.getPosZ() + (double) (rand.nextFloat() * entity.getWidth() * 2.0F) - (double) entity.getWidth() - d2 * 10.0D, d0, d1, d2 // ); // } // // } // } // // } // Path: src/main/java/com/latenighters/runicarcana/common/items/trinkets/HearthstoneItem.java import com.latenighters.runicarcana.capabilities.BasicCurioProvider; import com.latenighters.runicarcana.common.items.IClickable; import com.latenighters.runicarcana.common.setup.ModSetup; import com.latenighters.runicarcana.util.Util; import net.minecraft.client.util.ITooltipFlag; import net.minecraft.entity.LivingEntity; import net.minecraft.entity.player.PlayerEntity; import net.minecraft.inventory.container.Container; import net.minecraft.item.Item; import net.minecraft.item.ItemStack; import net.minecraft.item.ItemUseContext; import net.minecraft.nbt.CompoundNBT; import net.minecraft.util.*; import net.minecraft.util.math.BlockPos; import net.minecraft.util.text.ITextComponent; import net.minecraft.util.text.TranslationTextComponent; import net.minecraft.world.World; import net.minecraft.world.dimension.DimensionType; import net.minecraftforge.common.capabilities.ICapabilityProvider; import top.theillusivec4.curios.api.capability.ICurio; import javax.annotation.Nonnull; import javax.annotation.Nullable; import java.util.List; package com.latenighters.runicarcana.common.items.trinkets; public class HearthstoneItem extends Item implements IClickable { public HearthstoneItem() { super(new Properties() .maxStackSize(1)
.group(ModSetup.ITEM_GROUP)
Drazuam/RunicArcana
src/main/java/com/latenighters/runicarcana/common/items/trinkets/HearthstoneItem.java
// Path: src/main/java/com/latenighters/runicarcana/capabilities/BasicCurioProvider.java // public class BasicCurioProvider implements ICapabilityProvider { // // final LazyOptional<ICurio> capability; // // public BasicCurioProvider(ICurio curio) { // // this.capability = LazyOptional.of(() -> curio); // } // // @SuppressWarnings("ConstantConditions") // @Nonnull // @Override // public <T> LazyOptional<T> getCapability(@Nonnull Capability<T> cap, @Nullable Direction side) { // // return CuriosCapability.ITEM.orEmpty(cap, capability); // } // } // // Path: src/main/java/com/latenighters/runicarcana/common/items/IClickable.java // public interface IClickable { // // //do the action - this is performed server side // //returns true when behavior is as expected // boolean onClick(PlayerEntity player, ItemStack itemStack, Container container, int slot); // // } // // Path: src/main/java/com/latenighters/runicarcana/common/setup/ModSetup.java // public class ModSetup { // // public static final ItemGroup ITEM_GROUP = new ItemGroup(RunicArcana.MODID) { // @Override // public ItemStack createIcon() { // return new ItemStack(Registration.CHALK.get()); // } // }; // } // // Path: src/main/java/com/latenighters/runicarcana/util/Util.java // public class Util { // // public static ITextComponent loreStyle(ITextComponent textComponent){ // return textComponent.applyTextStyle(TextFormatting.DARK_PURPLE).applyTextStyle(TextFormatting.ITALIC); // } // // public static ITextComponent loreStyle(String key, Object...args){ // return loreStyle(new TranslationTextComponent(key, args)); // } // // public static ITextComponent tooltipStyle(ITextComponent textComponent){ // return textComponent.applyTextStyle(TextFormatting.GRAY); // } // // public static ITextComponent tooltipStyle(String key, Object... args){ // return tooltipStyle(new TranslationTextComponent(key, args)); // } // // public static void setPositionAndRotationAndUpdate(Entity entity, Double x, Double y, Double z, Float yaw, Float pitch) { // entity.setPositionAndUpdate(x, y, z); // entity.setPositionAndRotation(x, y, z, yaw, pitch); // } // // public static void setPositionAndRotationAndUpdate(Entity entity, Double x, Double y, Double z){ // setPositionAndRotationAndUpdate(entity, x, y, z, entity.rotationYaw, entity.rotationPitch); // } // // public static boolean checkHeadspace(World world, BlockPos pos){ // return world.isAirBlock(pos) && world.isAirBlock(pos.up()); // } // // public static void spawnParticleGroup(World world, BasicParticleType type, LivingEntity entity) { // final Random rand = new Random(); // if (world.isRemote) { // for (int i = 0; i < 30; ++i) { // double d0 = rand.nextGaussian() * 0.02D; // double d1 = rand.nextGaussian() * 0.02D; // double d2 = rand.nextGaussian() * 0.02D; // world.addParticle( // type, // entity.getPosX() + (double) (rand.nextFloat() * entity.getWidth() * 2.0F) - (double) entity.getWidth() - d0 * 10.0D, // entity.getPosY() + (double) (rand.nextFloat() * entity.getHeight()) - d1 * 10.0D, // entity.getPosZ() + (double) (rand.nextFloat() * entity.getWidth() * 2.0F) - (double) entity.getWidth() - d2 * 10.0D, d0, d1, d2 // ); // } // // } // } // // }
import com.latenighters.runicarcana.capabilities.BasicCurioProvider; import com.latenighters.runicarcana.common.items.IClickable; import com.latenighters.runicarcana.common.setup.ModSetup; import com.latenighters.runicarcana.util.Util; import net.minecraft.client.util.ITooltipFlag; import net.minecraft.entity.LivingEntity; import net.minecraft.entity.player.PlayerEntity; import net.minecraft.inventory.container.Container; import net.minecraft.item.Item; import net.minecraft.item.ItemStack; import net.minecraft.item.ItemUseContext; import net.minecraft.nbt.CompoundNBT; import net.minecraft.util.*; import net.minecraft.util.math.BlockPos; import net.minecraft.util.text.ITextComponent; import net.minecraft.util.text.TranslationTextComponent; import net.minecraft.world.World; import net.minecraft.world.dimension.DimensionType; import net.minecraftforge.common.capabilities.ICapabilityProvider; import top.theillusivec4.curios.api.capability.ICurio; import javax.annotation.Nonnull; import javax.annotation.Nullable; import java.util.List;
package com.latenighters.runicarcana.common.items.trinkets; public class HearthstoneItem extends Item implements IClickable { public HearthstoneItem() { super(new Properties() .maxStackSize(1) .group(ModSetup.ITEM_GROUP) ); } @Override public void addInformation(ItemStack stack, @Nullable World worldIn, List<ITextComponent> tooltip, ITooltipFlag flagIn) { BlockPos pos = getStoredPos(stack); DimensionType storedDim = getStoredDim(stack); if (pos.getY() > 0 && storedDim != null){ String dimString = DimensionType.getKey(storedDim).getPath();
// Path: src/main/java/com/latenighters/runicarcana/capabilities/BasicCurioProvider.java // public class BasicCurioProvider implements ICapabilityProvider { // // final LazyOptional<ICurio> capability; // // public BasicCurioProvider(ICurio curio) { // // this.capability = LazyOptional.of(() -> curio); // } // // @SuppressWarnings("ConstantConditions") // @Nonnull // @Override // public <T> LazyOptional<T> getCapability(@Nonnull Capability<T> cap, @Nullable Direction side) { // // return CuriosCapability.ITEM.orEmpty(cap, capability); // } // } // // Path: src/main/java/com/latenighters/runicarcana/common/items/IClickable.java // public interface IClickable { // // //do the action - this is performed server side // //returns true when behavior is as expected // boolean onClick(PlayerEntity player, ItemStack itemStack, Container container, int slot); // // } // // Path: src/main/java/com/latenighters/runicarcana/common/setup/ModSetup.java // public class ModSetup { // // public static final ItemGroup ITEM_GROUP = new ItemGroup(RunicArcana.MODID) { // @Override // public ItemStack createIcon() { // return new ItemStack(Registration.CHALK.get()); // } // }; // } // // Path: src/main/java/com/latenighters/runicarcana/util/Util.java // public class Util { // // public static ITextComponent loreStyle(ITextComponent textComponent){ // return textComponent.applyTextStyle(TextFormatting.DARK_PURPLE).applyTextStyle(TextFormatting.ITALIC); // } // // public static ITextComponent loreStyle(String key, Object...args){ // return loreStyle(new TranslationTextComponent(key, args)); // } // // public static ITextComponent tooltipStyle(ITextComponent textComponent){ // return textComponent.applyTextStyle(TextFormatting.GRAY); // } // // public static ITextComponent tooltipStyle(String key, Object... args){ // return tooltipStyle(new TranslationTextComponent(key, args)); // } // // public static void setPositionAndRotationAndUpdate(Entity entity, Double x, Double y, Double z, Float yaw, Float pitch) { // entity.setPositionAndUpdate(x, y, z); // entity.setPositionAndRotation(x, y, z, yaw, pitch); // } // // public static void setPositionAndRotationAndUpdate(Entity entity, Double x, Double y, Double z){ // setPositionAndRotationAndUpdate(entity, x, y, z, entity.rotationYaw, entity.rotationPitch); // } // // public static boolean checkHeadspace(World world, BlockPos pos){ // return world.isAirBlock(pos) && world.isAirBlock(pos.up()); // } // // public static void spawnParticleGroup(World world, BasicParticleType type, LivingEntity entity) { // final Random rand = new Random(); // if (world.isRemote) { // for (int i = 0; i < 30; ++i) { // double d0 = rand.nextGaussian() * 0.02D; // double d1 = rand.nextGaussian() * 0.02D; // double d2 = rand.nextGaussian() * 0.02D; // world.addParticle( // type, // entity.getPosX() + (double) (rand.nextFloat() * entity.getWidth() * 2.0F) - (double) entity.getWidth() - d0 * 10.0D, // entity.getPosY() + (double) (rand.nextFloat() * entity.getHeight()) - d1 * 10.0D, // entity.getPosZ() + (double) (rand.nextFloat() * entity.getWidth() * 2.0F) - (double) entity.getWidth() - d2 * 10.0D, d0, d1, d2 // ); // } // // } // } // // } // Path: src/main/java/com/latenighters/runicarcana/common/items/trinkets/HearthstoneItem.java import com.latenighters.runicarcana.capabilities.BasicCurioProvider; import com.latenighters.runicarcana.common.items.IClickable; import com.latenighters.runicarcana.common.setup.ModSetup; import com.latenighters.runicarcana.util.Util; import net.minecraft.client.util.ITooltipFlag; import net.minecraft.entity.LivingEntity; import net.minecraft.entity.player.PlayerEntity; import net.minecraft.inventory.container.Container; import net.minecraft.item.Item; import net.minecraft.item.ItemStack; import net.minecraft.item.ItemUseContext; import net.minecraft.nbt.CompoundNBT; import net.minecraft.util.*; import net.minecraft.util.math.BlockPos; import net.minecraft.util.text.ITextComponent; import net.minecraft.util.text.TranslationTextComponent; import net.minecraft.world.World; import net.minecraft.world.dimension.DimensionType; import net.minecraftforge.common.capabilities.ICapabilityProvider; import top.theillusivec4.curios.api.capability.ICurio; import javax.annotation.Nonnull; import javax.annotation.Nullable; import java.util.List; package com.latenighters.runicarcana.common.items.trinkets; public class HearthstoneItem extends Item implements IClickable { public HearthstoneItem() { super(new Properties() .maxStackSize(1) .group(ModSetup.ITEM_GROUP) ); } @Override public void addInformation(ItemStack stack, @Nullable World worldIn, List<ITextComponent> tooltip, ITooltipFlag flagIn) { BlockPos pos = getStoredPos(stack); DimensionType storedDim = getStoredDim(stack); if (pos.getY() > 0 && storedDim != null){ String dimString = DimensionType.getKey(storedDim).getPath();
tooltip.add(Util.tooltipStyle("tooltip.runicarcana.hearthstone.set_block_pos", pos.getX(), pos.getY(), pos.getZ(), dimString));
Drazuam/RunicArcana
src/main/java/com/latenighters/runicarcana/common/items/trinkets/HearthstoneItem.java
// Path: src/main/java/com/latenighters/runicarcana/capabilities/BasicCurioProvider.java // public class BasicCurioProvider implements ICapabilityProvider { // // final LazyOptional<ICurio> capability; // // public BasicCurioProvider(ICurio curio) { // // this.capability = LazyOptional.of(() -> curio); // } // // @SuppressWarnings("ConstantConditions") // @Nonnull // @Override // public <T> LazyOptional<T> getCapability(@Nonnull Capability<T> cap, @Nullable Direction side) { // // return CuriosCapability.ITEM.orEmpty(cap, capability); // } // } // // Path: src/main/java/com/latenighters/runicarcana/common/items/IClickable.java // public interface IClickable { // // //do the action - this is performed server side // //returns true when behavior is as expected // boolean onClick(PlayerEntity player, ItemStack itemStack, Container container, int slot); // // } // // Path: src/main/java/com/latenighters/runicarcana/common/setup/ModSetup.java // public class ModSetup { // // public static final ItemGroup ITEM_GROUP = new ItemGroup(RunicArcana.MODID) { // @Override // public ItemStack createIcon() { // return new ItemStack(Registration.CHALK.get()); // } // }; // } // // Path: src/main/java/com/latenighters/runicarcana/util/Util.java // public class Util { // // public static ITextComponent loreStyle(ITextComponent textComponent){ // return textComponent.applyTextStyle(TextFormatting.DARK_PURPLE).applyTextStyle(TextFormatting.ITALIC); // } // // public static ITextComponent loreStyle(String key, Object...args){ // return loreStyle(new TranslationTextComponent(key, args)); // } // // public static ITextComponent tooltipStyle(ITextComponent textComponent){ // return textComponent.applyTextStyle(TextFormatting.GRAY); // } // // public static ITextComponent tooltipStyle(String key, Object... args){ // return tooltipStyle(new TranslationTextComponent(key, args)); // } // // public static void setPositionAndRotationAndUpdate(Entity entity, Double x, Double y, Double z, Float yaw, Float pitch) { // entity.setPositionAndUpdate(x, y, z); // entity.setPositionAndRotation(x, y, z, yaw, pitch); // } // // public static void setPositionAndRotationAndUpdate(Entity entity, Double x, Double y, Double z){ // setPositionAndRotationAndUpdate(entity, x, y, z, entity.rotationYaw, entity.rotationPitch); // } // // public static boolean checkHeadspace(World world, BlockPos pos){ // return world.isAirBlock(pos) && world.isAirBlock(pos.up()); // } // // public static void spawnParticleGroup(World world, BasicParticleType type, LivingEntity entity) { // final Random rand = new Random(); // if (world.isRemote) { // for (int i = 0; i < 30; ++i) { // double d0 = rand.nextGaussian() * 0.02D; // double d1 = rand.nextGaussian() * 0.02D; // double d2 = rand.nextGaussian() * 0.02D; // world.addParticle( // type, // entity.getPosX() + (double) (rand.nextFloat() * entity.getWidth() * 2.0F) - (double) entity.getWidth() - d0 * 10.0D, // entity.getPosY() + (double) (rand.nextFloat() * entity.getHeight()) - d1 * 10.0D, // entity.getPosZ() + (double) (rand.nextFloat() * entity.getWidth() * 2.0F) - (double) entity.getWidth() - d2 * 10.0D, d0, d1, d2 // ); // } // // } // } // // }
import com.latenighters.runicarcana.capabilities.BasicCurioProvider; import com.latenighters.runicarcana.common.items.IClickable; import com.latenighters.runicarcana.common.setup.ModSetup; import com.latenighters.runicarcana.util.Util; import net.minecraft.client.util.ITooltipFlag; import net.minecraft.entity.LivingEntity; import net.minecraft.entity.player.PlayerEntity; import net.minecraft.inventory.container.Container; import net.minecraft.item.Item; import net.minecraft.item.ItemStack; import net.minecraft.item.ItemUseContext; import net.minecraft.nbt.CompoundNBT; import net.minecraft.util.*; import net.minecraft.util.math.BlockPos; import net.minecraft.util.text.ITextComponent; import net.minecraft.util.text.TranslationTextComponent; import net.minecraft.world.World; import net.minecraft.world.dimension.DimensionType; import net.minecraftforge.common.capabilities.ICapabilityProvider; import top.theillusivec4.curios.api.capability.ICurio; import javax.annotation.Nonnull; import javax.annotation.Nullable; import java.util.List;
package com.latenighters.runicarcana.common.items.trinkets; public class HearthstoneItem extends Item implements IClickable { public HearthstoneItem() { super(new Properties() .maxStackSize(1) .group(ModSetup.ITEM_GROUP) ); } @Override public void addInformation(ItemStack stack, @Nullable World worldIn, List<ITextComponent> tooltip, ITooltipFlag flagIn) { BlockPos pos = getStoredPos(stack); DimensionType storedDim = getStoredDim(stack); if (pos.getY() > 0 && storedDim != null){ String dimString = DimensionType.getKey(storedDim).getPath(); tooltip.add(Util.tooltipStyle("tooltip.runicarcana.hearthstone.set_block_pos", pos.getX(), pos.getY(), pos.getZ(), dimString)); } else { tooltip.add(Util.tooltipStyle("tooltip.runicarcana.hearthstone.no_set_block_pos")); } tooltip.add(Util.loreStyle("lore.runicarcana.hearthstone")); super.addInformation(stack, worldIn, tooltip, flagIn); } @Nullable @Override public ICapabilityProvider initCapabilities(ItemStack stack, @Nullable CompoundNBT nbt) {
// Path: src/main/java/com/latenighters/runicarcana/capabilities/BasicCurioProvider.java // public class BasicCurioProvider implements ICapabilityProvider { // // final LazyOptional<ICurio> capability; // // public BasicCurioProvider(ICurio curio) { // // this.capability = LazyOptional.of(() -> curio); // } // // @SuppressWarnings("ConstantConditions") // @Nonnull // @Override // public <T> LazyOptional<T> getCapability(@Nonnull Capability<T> cap, @Nullable Direction side) { // // return CuriosCapability.ITEM.orEmpty(cap, capability); // } // } // // Path: src/main/java/com/latenighters/runicarcana/common/items/IClickable.java // public interface IClickable { // // //do the action - this is performed server side // //returns true when behavior is as expected // boolean onClick(PlayerEntity player, ItemStack itemStack, Container container, int slot); // // } // // Path: src/main/java/com/latenighters/runicarcana/common/setup/ModSetup.java // public class ModSetup { // // public static final ItemGroup ITEM_GROUP = new ItemGroup(RunicArcana.MODID) { // @Override // public ItemStack createIcon() { // return new ItemStack(Registration.CHALK.get()); // } // }; // } // // Path: src/main/java/com/latenighters/runicarcana/util/Util.java // public class Util { // // public static ITextComponent loreStyle(ITextComponent textComponent){ // return textComponent.applyTextStyle(TextFormatting.DARK_PURPLE).applyTextStyle(TextFormatting.ITALIC); // } // // public static ITextComponent loreStyle(String key, Object...args){ // return loreStyle(new TranslationTextComponent(key, args)); // } // // public static ITextComponent tooltipStyle(ITextComponent textComponent){ // return textComponent.applyTextStyle(TextFormatting.GRAY); // } // // public static ITextComponent tooltipStyle(String key, Object... args){ // return tooltipStyle(new TranslationTextComponent(key, args)); // } // // public static void setPositionAndRotationAndUpdate(Entity entity, Double x, Double y, Double z, Float yaw, Float pitch) { // entity.setPositionAndUpdate(x, y, z); // entity.setPositionAndRotation(x, y, z, yaw, pitch); // } // // public static void setPositionAndRotationAndUpdate(Entity entity, Double x, Double y, Double z){ // setPositionAndRotationAndUpdate(entity, x, y, z, entity.rotationYaw, entity.rotationPitch); // } // // public static boolean checkHeadspace(World world, BlockPos pos){ // return world.isAirBlock(pos) && world.isAirBlock(pos.up()); // } // // public static void spawnParticleGroup(World world, BasicParticleType type, LivingEntity entity) { // final Random rand = new Random(); // if (world.isRemote) { // for (int i = 0; i < 30; ++i) { // double d0 = rand.nextGaussian() * 0.02D; // double d1 = rand.nextGaussian() * 0.02D; // double d2 = rand.nextGaussian() * 0.02D; // world.addParticle( // type, // entity.getPosX() + (double) (rand.nextFloat() * entity.getWidth() * 2.0F) - (double) entity.getWidth() - d0 * 10.0D, // entity.getPosY() + (double) (rand.nextFloat() * entity.getHeight()) - d1 * 10.0D, // entity.getPosZ() + (double) (rand.nextFloat() * entity.getWidth() * 2.0F) - (double) entity.getWidth() - d2 * 10.0D, d0, d1, d2 // ); // } // // } // } // // } // Path: src/main/java/com/latenighters/runicarcana/common/items/trinkets/HearthstoneItem.java import com.latenighters.runicarcana.capabilities.BasicCurioProvider; import com.latenighters.runicarcana.common.items.IClickable; import com.latenighters.runicarcana.common.setup.ModSetup; import com.latenighters.runicarcana.util.Util; import net.minecraft.client.util.ITooltipFlag; import net.minecraft.entity.LivingEntity; import net.minecraft.entity.player.PlayerEntity; import net.minecraft.inventory.container.Container; import net.minecraft.item.Item; import net.minecraft.item.ItemStack; import net.minecraft.item.ItemUseContext; import net.minecraft.nbt.CompoundNBT; import net.minecraft.util.*; import net.minecraft.util.math.BlockPos; import net.minecraft.util.text.ITextComponent; import net.minecraft.util.text.TranslationTextComponent; import net.minecraft.world.World; import net.minecraft.world.dimension.DimensionType; import net.minecraftforge.common.capabilities.ICapabilityProvider; import top.theillusivec4.curios.api.capability.ICurio; import javax.annotation.Nonnull; import javax.annotation.Nullable; import java.util.List; package com.latenighters.runicarcana.common.items.trinkets; public class HearthstoneItem extends Item implements IClickable { public HearthstoneItem() { super(new Properties() .maxStackSize(1) .group(ModSetup.ITEM_GROUP) ); } @Override public void addInformation(ItemStack stack, @Nullable World worldIn, List<ITextComponent> tooltip, ITooltipFlag flagIn) { BlockPos pos = getStoredPos(stack); DimensionType storedDim = getStoredDim(stack); if (pos.getY() > 0 && storedDim != null){ String dimString = DimensionType.getKey(storedDim).getPath(); tooltip.add(Util.tooltipStyle("tooltip.runicarcana.hearthstone.set_block_pos", pos.getX(), pos.getY(), pos.getZ(), dimString)); } else { tooltip.add(Util.tooltipStyle("tooltip.runicarcana.hearthstone.no_set_block_pos")); } tooltip.add(Util.loreStyle("lore.runicarcana.hearthstone")); super.addInformation(stack, worldIn, tooltip, flagIn); } @Nullable @Override public ICapabilityProvider initCapabilities(ItemStack stack, @Nullable CompoundNBT nbt) {
return new BasicCurioProvider(new ICurio() {
Drazuam/RunicArcana
src/main/java/com/latenighters/runicarcana/common/symbols/DetectSymbol.java
// Path: src/main/java/com/latenighters/runicarcana/common/symbols/categories/SymbolCategory.java // public class SymbolCategory { // // public static SymbolCategory DEFAULT = new SymbolCategory(Symbols.DEBUG, MODID+".symbol.category.default"); // // private Symbol displaySymbol; // private final String unlocalizedName; // // public static void generateCategories() // { // //TODO figure out why static initialization isn't working // DEFAULT.setDisplaySymbol(Symbols.EXPULSION); // } // // public SymbolCategory(Symbol displaySymbol, String unlocalizedName) { // this.displaySymbol = displaySymbol; // this.unlocalizedName = unlocalizedName; // } // // public Symbol getDisplaySymbol() { // return displaySymbol; // } // // public void setDisplaySymbol(Symbol displaySymbol) { // this.displaySymbol = displaySymbol; // } // // public String getUnlocalizedName() { // return unlocalizedName; // } // }
import com.latenighters.runicarcana.common.symbols.backend.*; import com.latenighters.runicarcana.common.symbols.categories.SymbolCategory; import net.minecraft.entity.LivingEntity; import net.minecraft.util.math.AxisAlignedBB; import net.minecraft.util.math.BlockPos; import net.minecraft.world.chunk.Chunk; import java.util.ArrayList; import java.util.List;
package com.latenighters.runicarcana.common.symbols; public class DetectSymbol extends Symbol { public DetectSymbol() {
// Path: src/main/java/com/latenighters/runicarcana/common/symbols/categories/SymbolCategory.java // public class SymbolCategory { // // public static SymbolCategory DEFAULT = new SymbolCategory(Symbols.DEBUG, MODID+".symbol.category.default"); // // private Symbol displaySymbol; // private final String unlocalizedName; // // public static void generateCategories() // { // //TODO figure out why static initialization isn't working // DEFAULT.setDisplaySymbol(Symbols.EXPULSION); // } // // public SymbolCategory(Symbol displaySymbol, String unlocalizedName) { // this.displaySymbol = displaySymbol; // this.unlocalizedName = unlocalizedName; // } // // public Symbol getDisplaySymbol() { // return displaySymbol; // } // // public void setDisplaySymbol(Symbol displaySymbol) { // this.displaySymbol = displaySymbol; // } // // public String getUnlocalizedName() { // return unlocalizedName; // } // } // Path: src/main/java/com/latenighters/runicarcana/common/symbols/DetectSymbol.java import com.latenighters.runicarcana.common.symbols.backend.*; import com.latenighters.runicarcana.common.symbols.categories.SymbolCategory; import net.minecraft.entity.LivingEntity; import net.minecraft.util.math.AxisAlignedBB; import net.minecraft.util.math.BlockPos; import net.minecraft.world.chunk.Chunk; import java.util.ArrayList; import java.util.List; package com.latenighters.runicarcana.common.symbols; public class DetectSymbol extends Symbol { public DetectSymbol() {
super("symbol_detect", SymbolTextures.DETECT, SymbolCategory.DEFAULT);
Drazuam/RunicArcana
src/main/java/com/latenighters/runicarcana/common/blocks/ArcanaPylon.java
// Path: src/main/java/com/latenighters/runicarcana/common/blocks/tile/TileArcanaPylon.java // public class TileArcanaPylon extends ArcanaMachine { // // public TileArcanaPylon() { // super(Registration.ARCANA_PYLON_TILE.get()); // //TODO maybe pull this out // // this.getCapability(RunicArcana.ARCANA_CAP).ifPresent(cap->{ // cap.getChambers().add(new ArcanaChamber(1000000,1)); // }); // } // // @Override // public void tick() { // super.tick(); // } // // @Override // public int getChamberSlotFromHitVec(Vec3d hitVec) { // return 0; // } // // @Override // public ArcanaChamber getChamberFromSlot(int slot) { // AtomicReference<ArcanaChamber> arcanaChamber = new AtomicReference<>(); // getCapability(RunicArcana.ARCANA_CAP).ifPresent(cap->{ // arcanaChamber.set(cap.getChambers().get(slot)); // }); // // return arcanaChamber.get(); // } // // @Override // public boolean canExport() { // return true; // } // // @Override // public boolean canImport() { // return true; // } // }
import com.latenighters.runicarcana.common.blocks.tile.TileArcanaPylon; import net.minecraft.block.Block; import net.minecraft.block.BlockState; import net.minecraft.tileentity.TileEntity; import net.minecraft.world.IBlockReader; import javax.annotation.Nullable;
package com.latenighters.runicarcana.common.blocks; public class ArcanaPylon extends Block { public ArcanaPylon(Properties properties) { super(properties); } @Override public boolean hasTileEntity(BlockState state) { return true; } @Nullable @Override public TileEntity createTileEntity(BlockState state, IBlockReader world) {
// Path: src/main/java/com/latenighters/runicarcana/common/blocks/tile/TileArcanaPylon.java // public class TileArcanaPylon extends ArcanaMachine { // // public TileArcanaPylon() { // super(Registration.ARCANA_PYLON_TILE.get()); // //TODO maybe pull this out // // this.getCapability(RunicArcana.ARCANA_CAP).ifPresent(cap->{ // cap.getChambers().add(new ArcanaChamber(1000000,1)); // }); // } // // @Override // public void tick() { // super.tick(); // } // // @Override // public int getChamberSlotFromHitVec(Vec3d hitVec) { // return 0; // } // // @Override // public ArcanaChamber getChamberFromSlot(int slot) { // AtomicReference<ArcanaChamber> arcanaChamber = new AtomicReference<>(); // getCapability(RunicArcana.ARCANA_CAP).ifPresent(cap->{ // arcanaChamber.set(cap.getChambers().get(slot)); // }); // // return arcanaChamber.get(); // } // // @Override // public boolean canExport() { // return true; // } // // @Override // public boolean canImport() { // return true; // } // } // Path: src/main/java/com/latenighters/runicarcana/common/blocks/ArcanaPylon.java import com.latenighters.runicarcana.common.blocks.tile.TileArcanaPylon; import net.minecraft.block.Block; import net.minecraft.block.BlockState; import net.minecraft.tileentity.TileEntity; import net.minecraft.world.IBlockReader; import javax.annotation.Nullable; package com.latenighters.runicarcana.common.blocks; public class ArcanaPylon extends Block { public ArcanaPylon(Properties properties) { super(properties); } @Override public boolean hasTileEntity(BlockState state) { return true; } @Nullable @Override public TileEntity createTileEntity(BlockState state, IBlockReader world) {
return new TileArcanaPylon();
Drazuam/RunicArcana
src/main/java/com/latenighters/runicarcana/common/items/tools/AbstractToolItem.java
// Path: src/main/java/com/latenighters/runicarcana/util/Util.java // public class Util { // // public static ITextComponent loreStyle(ITextComponent textComponent){ // return textComponent.applyTextStyle(TextFormatting.DARK_PURPLE).applyTextStyle(TextFormatting.ITALIC); // } // // public static ITextComponent loreStyle(String key, Object...args){ // return loreStyle(new TranslationTextComponent(key, args)); // } // // public static ITextComponent tooltipStyle(ITextComponent textComponent){ // return textComponent.applyTextStyle(TextFormatting.GRAY); // } // // public static ITextComponent tooltipStyle(String key, Object... args){ // return tooltipStyle(new TranslationTextComponent(key, args)); // } // // public static void setPositionAndRotationAndUpdate(Entity entity, Double x, Double y, Double z, Float yaw, Float pitch) { // entity.setPositionAndUpdate(x, y, z); // entity.setPositionAndRotation(x, y, z, yaw, pitch); // } // // public static void setPositionAndRotationAndUpdate(Entity entity, Double x, Double y, Double z){ // setPositionAndRotationAndUpdate(entity, x, y, z, entity.rotationYaw, entity.rotationPitch); // } // // public static boolean checkHeadspace(World world, BlockPos pos){ // return world.isAirBlock(pos) && world.isAirBlock(pos.up()); // } // // public static void spawnParticleGroup(World world, BasicParticleType type, LivingEntity entity) { // final Random rand = new Random(); // if (world.isRemote) { // for (int i = 0; i < 30; ++i) { // double d0 = rand.nextGaussian() * 0.02D; // double d1 = rand.nextGaussian() * 0.02D; // double d2 = rand.nextGaussian() * 0.02D; // world.addParticle( // type, // entity.getPosX() + (double) (rand.nextFloat() * entity.getWidth() * 2.0F) - (double) entity.getWidth() - d0 * 10.0D, // entity.getPosY() + (double) (rand.nextFloat() * entity.getHeight()) - d1 * 10.0D, // entity.getPosZ() + (double) (rand.nextFloat() * entity.getWidth() * 2.0F) - (double) entity.getWidth() - d2 * 10.0D, d0, d1, d2 // ); // } // // } // } // // }
import com.latenighters.runicarcana.util.Util; import net.minecraft.block.Block; import net.minecraft.block.BlockState; import net.minecraft.block.Blocks; import net.minecraft.block.material.Material; import net.minecraft.client.util.ITooltipFlag; import net.minecraft.enchantment.Enchantment; import net.minecraft.entity.player.PlayerEntity; import net.minecraft.item.ItemStack; import net.minecraft.item.ToolItem; import net.minecraft.nbt.CompoundNBT; import net.minecraft.util.ActionResult; import net.minecraft.util.Hand; import net.minecraft.util.text.ITextComponent; import net.minecraft.world.World; import net.minecraftforge.common.ToolType; import javax.annotation.Nullable; import java.util.ArrayList; import java.util.Collections; import java.util.List;
package com.latenighters.runicarcana.common.items.tools; abstract public class AbstractToolItem extends ToolItem { static private final ArcanaToolStats defaultStats = new ArcanaToolStats(1f, 1f, 10f, 0f); static private final int harvestLevel = 3; private List<ToolType> toolTypes = new ArrayList<>(); public AbstractToolItem(List<ToolType> toolTypes) { super(defaultStats.getAttackDamage(), defaultStats.getAttackSpeed(), ArcanaMaterial.instance, Collections.emptySet(), new Properties()); this.toolTypes = toolTypes; } public AbstractToolItem(ToolType toolType) { super(defaultStats.getAttackDamage(), defaultStats.getAttackSpeed(), ArcanaMaterial.instance, Collections.emptySet(), new Properties()); this.toolTypes.add(toolType); } @Override public void addInformation(ItemStack stack, @Nullable World worldIn, List<ITextComponent> tooltip, ITooltipFlag flagIn) { super.addInformation(stack, worldIn, tooltip, flagIn); ArcanaToolStats stats = getStats(stack);
// Path: src/main/java/com/latenighters/runicarcana/util/Util.java // public class Util { // // public static ITextComponent loreStyle(ITextComponent textComponent){ // return textComponent.applyTextStyle(TextFormatting.DARK_PURPLE).applyTextStyle(TextFormatting.ITALIC); // } // // public static ITextComponent loreStyle(String key, Object...args){ // return loreStyle(new TranslationTextComponent(key, args)); // } // // public static ITextComponent tooltipStyle(ITextComponent textComponent){ // return textComponent.applyTextStyle(TextFormatting.GRAY); // } // // public static ITextComponent tooltipStyle(String key, Object... args){ // return tooltipStyle(new TranslationTextComponent(key, args)); // } // // public static void setPositionAndRotationAndUpdate(Entity entity, Double x, Double y, Double z, Float yaw, Float pitch) { // entity.setPositionAndUpdate(x, y, z); // entity.setPositionAndRotation(x, y, z, yaw, pitch); // } // // public static void setPositionAndRotationAndUpdate(Entity entity, Double x, Double y, Double z){ // setPositionAndRotationAndUpdate(entity, x, y, z, entity.rotationYaw, entity.rotationPitch); // } // // public static boolean checkHeadspace(World world, BlockPos pos){ // return world.isAirBlock(pos) && world.isAirBlock(pos.up()); // } // // public static void spawnParticleGroup(World world, BasicParticleType type, LivingEntity entity) { // final Random rand = new Random(); // if (world.isRemote) { // for (int i = 0; i < 30; ++i) { // double d0 = rand.nextGaussian() * 0.02D; // double d1 = rand.nextGaussian() * 0.02D; // double d2 = rand.nextGaussian() * 0.02D; // world.addParticle( // type, // entity.getPosX() + (double) (rand.nextFloat() * entity.getWidth() * 2.0F) - (double) entity.getWidth() - d0 * 10.0D, // entity.getPosY() + (double) (rand.nextFloat() * entity.getHeight()) - d1 * 10.0D, // entity.getPosZ() + (double) (rand.nextFloat() * entity.getWidth() * 2.0F) - (double) entity.getWidth() - d2 * 10.0D, d0, d1, d2 // ); // } // // } // } // // } // Path: src/main/java/com/latenighters/runicarcana/common/items/tools/AbstractToolItem.java import com.latenighters.runicarcana.util.Util; import net.minecraft.block.Block; import net.minecraft.block.BlockState; import net.minecraft.block.Blocks; import net.minecraft.block.material.Material; import net.minecraft.client.util.ITooltipFlag; import net.minecraft.enchantment.Enchantment; import net.minecraft.entity.player.PlayerEntity; import net.minecraft.item.ItemStack; import net.minecraft.item.ToolItem; import net.minecraft.nbt.CompoundNBT; import net.minecraft.util.ActionResult; import net.minecraft.util.Hand; import net.minecraft.util.text.ITextComponent; import net.minecraft.world.World; import net.minecraftforge.common.ToolType; import javax.annotation.Nullable; import java.util.ArrayList; import java.util.Collections; import java.util.List; package com.latenighters.runicarcana.common.items.tools; abstract public class AbstractToolItem extends ToolItem { static private final ArcanaToolStats defaultStats = new ArcanaToolStats(1f, 1f, 10f, 0f); static private final int harvestLevel = 3; private List<ToolType> toolTypes = new ArrayList<>(); public AbstractToolItem(List<ToolType> toolTypes) { super(defaultStats.getAttackDamage(), defaultStats.getAttackSpeed(), ArcanaMaterial.instance, Collections.emptySet(), new Properties()); this.toolTypes = toolTypes; } public AbstractToolItem(ToolType toolType) { super(defaultStats.getAttackDamage(), defaultStats.getAttackSpeed(), ArcanaMaterial.instance, Collections.emptySet(), new Properties()); this.toolTypes.add(toolType); } @Override public void addInformation(ItemStack stack, @Nullable World worldIn, List<ITextComponent> tooltip, ITooltipFlag flagIn) { super.addInformation(stack, worldIn, tooltip, flagIn); ArcanaToolStats stats = getStats(stack);
tooltip.add(Util.tooltipStyle("tooltip.runicarcana.tool_items.attack_damage", stats.getAttackDamage()));
Drazuam/RunicArcana
src/main/java/com/latenighters/runicarcana/common/symbols/backend/SymbolUtil.java
// Path: src/main/java/com/latenighters/runicarcana/RunicArcana.java // @Mod("runicarcana") // public class RunicArcana // { // // Directly reference a log4j logger. // private static final Logger LOGGER = LogManager.getLogger(); // public static final String MODID = "runicarcana"; // // //Capability Registration // @CapabilityInject(ISymbolHandler.class) // public static Capability<ISymbolHandler> SYMBOL_CAP = null; // // @CapabilityInject(IArcanaHandler.class) // public static Capability<IArcanaHandler> ARCANA_CAP = null; // // public static IProxy proxy; // // public RunicArcana() { // // Register the setup method for modloading // FMLJavaModLoadingContext.get().getModEventBus().addListener(this::setup); // FMLJavaModLoadingContext.get().getModEventBus().addListener(this::onSetupComplete); // // Register the enqueueIMC method for modloading // FMLJavaModLoadingContext.get().getModEventBus().addListener(this::enqueueIMC); // // Register the processIMC method for modloading // FMLJavaModLoadingContext.get().getModEventBus().addListener(this::processIMC); // // Register the doClientStuff method for modloading // FMLJavaModLoadingContext.get().getModEventBus().addListener(this::doClientStuff); // FMLJavaModLoadingContext.get().getModEventBus().addListener(this::doServerStuff); // FMLJavaModLoadingContext.get().getModEventBus().addListener(SymbolRegistryHandler::onCreateRegistryEvent); // FMLJavaModLoadingContext.get().getModEventBus().addListener(SymbolRegistration::registerSymbols); // // // Register ourselves for server and other game events we are interested in // MinecraftForge.EVENT_BUS.register(this); // MinecraftForge.EVENT_BUS.register(new CommonEventHandler()); // MinecraftForge.EVENT_BUS.register(new SymbolSyncer()); // NetworkSync.registerPackets(); // ClickableHandler.registerPackets(); // Registration.init(); // //SymbolRegistration.init(); // // } // // private void setup(final FMLCommonSetupEvent event) // { // SymbolHandlerStorage storage = new SymbolHandlerStorage(); // SymbolHandler.SymbolHandlerFactory factory = new SymbolHandler.SymbolHandlerFactory(); // CapabilityManager.INSTANCE.register(ISymbolHandler.class, storage, factory); // // ArcanaHandlerStorage storage2 = new ArcanaHandlerStorage(); // ArcanaHandler.ArcanaHandlerFactory factory2 = new ArcanaHandler.ArcanaHandlerFactory(); // CapabilityManager.INSTANCE.register(IArcanaHandler.class, storage2, factory2); // // //TODO: register packets somewhere reasonable // registerPackets(); // } // // private void doClientStuff(final FMLClientSetupEvent event) { // proxy = new ClientProxy(); // KeyEventHandler.registerKeyBindings(); // } // // private void doServerStuff(final FMLDedicatedServerSetupEvent event) { // proxy = new ServerProxy(); // } // // private void enqueueIMC(final InterModEnqueueEvent event) // { // // some example code to dispatch IMC to another mod // // InterModComms.sendTo("examplemod", "helloworld", () -> { LOGGER.info("Hello world from the MDK"); return "Hello world";}); // InterModComms.sendTo("curios", CuriosAPI.IMC.REGISTER_TYPE, () -> new CurioIMCMessage("ring").setSize(2)); // InterModComms.sendTo("curios", CuriosAPI.IMC.REGISTER_TYPE, () -> new CurioIMCMessage("trinket").setSize(2)); // // } // // private void processIMC(final InterModProcessEvent event) // { // // some example code to receive and process InterModComms from other mods // // LOGGER.info("Got IMC {}", event.getIMCStream(). // // map(m->m.getMessageSupplier().get()). // // collect(Collectors.toList())); // } // // private void onSetupComplete(final FMLLoadCompleteEvent event) // { // PrincipicArmorEventHandler.onSetup(event); // SymbolCategory.generateCategories(); //TODO remove this when static initialization is working // } // // // You can use SubscribeEvent and let the Event Bus discover methods to call // @SubscribeEvent // public void onServerStarting(FMLServerStartingEvent event) { // // do something when the server starts // // LOGGER.info("HELLO from server starting"); // } // // // You can use EventBusSubscriber to automatically subscribe events on the contained class (this is subscribing to the MOD // // Event bus for receiving Registry Events) // @Mod.EventBusSubscriber(bus=Mod.EventBusSubscriber.Bus.MOD) // public static class RegistryEvents { // @SubscribeEvent // public static void onBlocksRegistry(final RegistryEvent.Register<Block> blockRegistryEvent) { // // register a new block here // // LOGGER.info("HELLO from Register Block"); // } // } // }
import com.latenighters.runicarcana.RunicArcana; import net.minecraft.client.Minecraft; import net.minecraft.entity.player.PlayerEntity; import net.minecraft.util.math.BlockRayTraceResult; import net.minecraft.util.math.RayTraceResult; import net.minecraft.world.chunk.Chunk; import net.minecraft.world.chunk.IChunk; import java.util.List; import java.util.Map; import java.util.concurrent.atomic.AtomicReference;
package com.latenighters.runicarcana.common.symbols.backend; public class SymbolUtil { //client-side only public static IFunctionalObject getLookedFunctionalObject(){
// Path: src/main/java/com/latenighters/runicarcana/RunicArcana.java // @Mod("runicarcana") // public class RunicArcana // { // // Directly reference a log4j logger. // private static final Logger LOGGER = LogManager.getLogger(); // public static final String MODID = "runicarcana"; // // //Capability Registration // @CapabilityInject(ISymbolHandler.class) // public static Capability<ISymbolHandler> SYMBOL_CAP = null; // // @CapabilityInject(IArcanaHandler.class) // public static Capability<IArcanaHandler> ARCANA_CAP = null; // // public static IProxy proxy; // // public RunicArcana() { // // Register the setup method for modloading // FMLJavaModLoadingContext.get().getModEventBus().addListener(this::setup); // FMLJavaModLoadingContext.get().getModEventBus().addListener(this::onSetupComplete); // // Register the enqueueIMC method for modloading // FMLJavaModLoadingContext.get().getModEventBus().addListener(this::enqueueIMC); // // Register the processIMC method for modloading // FMLJavaModLoadingContext.get().getModEventBus().addListener(this::processIMC); // // Register the doClientStuff method for modloading // FMLJavaModLoadingContext.get().getModEventBus().addListener(this::doClientStuff); // FMLJavaModLoadingContext.get().getModEventBus().addListener(this::doServerStuff); // FMLJavaModLoadingContext.get().getModEventBus().addListener(SymbolRegistryHandler::onCreateRegistryEvent); // FMLJavaModLoadingContext.get().getModEventBus().addListener(SymbolRegistration::registerSymbols); // // // Register ourselves for server and other game events we are interested in // MinecraftForge.EVENT_BUS.register(this); // MinecraftForge.EVENT_BUS.register(new CommonEventHandler()); // MinecraftForge.EVENT_BUS.register(new SymbolSyncer()); // NetworkSync.registerPackets(); // ClickableHandler.registerPackets(); // Registration.init(); // //SymbolRegistration.init(); // // } // // private void setup(final FMLCommonSetupEvent event) // { // SymbolHandlerStorage storage = new SymbolHandlerStorage(); // SymbolHandler.SymbolHandlerFactory factory = new SymbolHandler.SymbolHandlerFactory(); // CapabilityManager.INSTANCE.register(ISymbolHandler.class, storage, factory); // // ArcanaHandlerStorage storage2 = new ArcanaHandlerStorage(); // ArcanaHandler.ArcanaHandlerFactory factory2 = new ArcanaHandler.ArcanaHandlerFactory(); // CapabilityManager.INSTANCE.register(IArcanaHandler.class, storage2, factory2); // // //TODO: register packets somewhere reasonable // registerPackets(); // } // // private void doClientStuff(final FMLClientSetupEvent event) { // proxy = new ClientProxy(); // KeyEventHandler.registerKeyBindings(); // } // // private void doServerStuff(final FMLDedicatedServerSetupEvent event) { // proxy = new ServerProxy(); // } // // private void enqueueIMC(final InterModEnqueueEvent event) // { // // some example code to dispatch IMC to another mod // // InterModComms.sendTo("examplemod", "helloworld", () -> { LOGGER.info("Hello world from the MDK"); return "Hello world";}); // InterModComms.sendTo("curios", CuriosAPI.IMC.REGISTER_TYPE, () -> new CurioIMCMessage("ring").setSize(2)); // InterModComms.sendTo("curios", CuriosAPI.IMC.REGISTER_TYPE, () -> new CurioIMCMessage("trinket").setSize(2)); // // } // // private void processIMC(final InterModProcessEvent event) // { // // some example code to receive and process InterModComms from other mods // // LOGGER.info("Got IMC {}", event.getIMCStream(). // // map(m->m.getMessageSupplier().get()). // // collect(Collectors.toList())); // } // // private void onSetupComplete(final FMLLoadCompleteEvent event) // { // PrincipicArmorEventHandler.onSetup(event); // SymbolCategory.generateCategories(); //TODO remove this when static initialization is working // } // // // You can use SubscribeEvent and let the Event Bus discover methods to call // @SubscribeEvent // public void onServerStarting(FMLServerStartingEvent event) { // // do something when the server starts // // LOGGER.info("HELLO from server starting"); // } // // // You can use EventBusSubscriber to automatically subscribe events on the contained class (this is subscribing to the MOD // // Event bus for receiving Registry Events) // @Mod.EventBusSubscriber(bus=Mod.EventBusSubscriber.Bus.MOD) // public static class RegistryEvents { // @SubscribeEvent // public static void onBlocksRegistry(final RegistryEvent.Register<Block> blockRegistryEvent) { // // register a new block here // // LOGGER.info("HELLO from Register Block"); // } // } // } // Path: src/main/java/com/latenighters/runicarcana/common/symbols/backend/SymbolUtil.java import com.latenighters.runicarcana.RunicArcana; import net.minecraft.client.Minecraft; import net.minecraft.entity.player.PlayerEntity; import net.minecraft.util.math.BlockRayTraceResult; import net.minecraft.util.math.RayTraceResult; import net.minecraft.world.chunk.Chunk; import net.minecraft.world.chunk.IChunk; import java.util.List; import java.util.Map; import java.util.concurrent.atomic.AtomicReference; package com.latenighters.runicarcana.common.symbols.backend; public class SymbolUtil { //client-side only public static IFunctionalObject getLookedFunctionalObject(){
if(RunicArcana.proxy.getWorld()==null)return null;
Drazuam/RunicArcana
src/main/java/com/latenighters/runicarcana/common/symbols/BooleanLogicSymbol.java
// Path: src/main/java/com/latenighters/runicarcana/common/symbols/categories/SymbolCategory.java // public class SymbolCategory { // // public static SymbolCategory DEFAULT = new SymbolCategory(Symbols.DEBUG, MODID+".symbol.category.default"); // // private Symbol displaySymbol; // private final String unlocalizedName; // // public static void generateCategories() // { // //TODO figure out why static initialization isn't working // DEFAULT.setDisplaySymbol(Symbols.EXPULSION); // } // // public SymbolCategory(Symbol displaySymbol, String unlocalizedName) { // this.displaySymbol = displaySymbol; // this.unlocalizedName = unlocalizedName; // } // // public Symbol getDisplaySymbol() { // return displaySymbol; // } // // public void setDisplaySymbol(Symbol displaySymbol) { // this.displaySymbol = displaySymbol; // } // // public String getUnlocalizedName() { // return unlocalizedName; // } // }
import com.latenighters.runicarcana.common.symbols.backend.*; import com.latenighters.runicarcana.common.symbols.categories.SymbolCategory; import net.minecraft.world.chunk.Chunk; import java.util.ArrayList; import java.util.List;
package com.latenighters.runicarcana.common.symbols; public class BooleanLogicSymbol extends Symbol { public BooleanLogicSymbol() {
// Path: src/main/java/com/latenighters/runicarcana/common/symbols/categories/SymbolCategory.java // public class SymbolCategory { // // public static SymbolCategory DEFAULT = new SymbolCategory(Symbols.DEBUG, MODID+".symbol.category.default"); // // private Symbol displaySymbol; // private final String unlocalizedName; // // public static void generateCategories() // { // //TODO figure out why static initialization isn't working // DEFAULT.setDisplaySymbol(Symbols.EXPULSION); // } // // public SymbolCategory(Symbol displaySymbol, String unlocalizedName) { // this.displaySymbol = displaySymbol; // this.unlocalizedName = unlocalizedName; // } // // public Symbol getDisplaySymbol() { // return displaySymbol; // } // // public void setDisplaySymbol(Symbol displaySymbol) { // this.displaySymbol = displaySymbol; // } // // public String getUnlocalizedName() { // return unlocalizedName; // } // } // Path: src/main/java/com/latenighters/runicarcana/common/symbols/BooleanLogicSymbol.java import com.latenighters.runicarcana.common.symbols.backend.*; import com.latenighters.runicarcana.common.symbols.categories.SymbolCategory; import net.minecraft.world.chunk.Chunk; import java.util.ArrayList; import java.util.List; package com.latenighters.runicarcana.common.symbols; public class BooleanLogicSymbol extends Symbol { public BooleanLogicSymbol() {
super("symbol_boolean_logic", SymbolTextures.BOOLEAN_LOGIC, SymbolCategory.DEFAULT);
Drazuam/RunicArcana
src/main/java/com/latenighters/runicarcana/common/symbols/ExpulsionSymbol.java
// Path: src/main/java/com/latenighters/runicarcana/common/symbols/categories/SymbolCategory.java // public class SymbolCategory { // // public static SymbolCategory DEFAULT = new SymbolCategory(Symbols.DEBUG, MODID+".symbol.category.default"); // // private Symbol displaySymbol; // private final String unlocalizedName; // // public static void generateCategories() // { // //TODO figure out why static initialization isn't working // DEFAULT.setDisplaySymbol(Symbols.EXPULSION); // } // // public SymbolCategory(Symbol displaySymbol, String unlocalizedName) { // this.displaySymbol = displaySymbol; // this.unlocalizedName = unlocalizedName; // } // // public Symbol getDisplaySymbol() { // return displaySymbol; // } // // public void setDisplaySymbol(Symbol displaySymbol) { // this.displaySymbol = displaySymbol; // } // // public String getUnlocalizedName() { // return unlocalizedName; // } // }
import com.latenighters.runicarcana.common.symbols.backend.*; import com.latenighters.runicarcana.common.symbols.categories.SymbolCategory; import net.minecraft.dispenser.DefaultDispenseItemBehavior; import net.minecraft.dispenser.Position; import net.minecraft.entity.Entity; import net.minecraft.entity.player.PlayerEntity; import net.minecraft.inventory.IInventory; import net.minecraft.inventory.ISidedInventory; import net.minecraft.item.ItemStack; import net.minecraft.tileentity.HopperTileEntity; import net.minecraft.tileentity.TileEntity; import net.minecraft.util.Direction; import net.minecraft.util.math.BlockPos; import net.minecraft.world.World; import net.minecraft.world.chunk.Chunk; import net.minecraftforge.items.CapabilityItemHandler; import javax.annotation.Nullable; import java.util.ArrayList; import java.util.List;
package com.latenighters.runicarcana.common.symbols; public class ExpulsionSymbol extends Symbol { public ExpulsionSymbol() {
// Path: src/main/java/com/latenighters/runicarcana/common/symbols/categories/SymbolCategory.java // public class SymbolCategory { // // public static SymbolCategory DEFAULT = new SymbolCategory(Symbols.DEBUG, MODID+".symbol.category.default"); // // private Symbol displaySymbol; // private final String unlocalizedName; // // public static void generateCategories() // { // //TODO figure out why static initialization isn't working // DEFAULT.setDisplaySymbol(Symbols.EXPULSION); // } // // public SymbolCategory(Symbol displaySymbol, String unlocalizedName) { // this.displaySymbol = displaySymbol; // this.unlocalizedName = unlocalizedName; // } // // public Symbol getDisplaySymbol() { // return displaySymbol; // } // // public void setDisplaySymbol(Symbol displaySymbol) { // this.displaySymbol = displaySymbol; // } // // public String getUnlocalizedName() { // return unlocalizedName; // } // } // Path: src/main/java/com/latenighters/runicarcana/common/symbols/ExpulsionSymbol.java import com.latenighters.runicarcana.common.symbols.backend.*; import com.latenighters.runicarcana.common.symbols.categories.SymbolCategory; import net.minecraft.dispenser.DefaultDispenseItemBehavior; import net.minecraft.dispenser.Position; import net.minecraft.entity.Entity; import net.minecraft.entity.player.PlayerEntity; import net.minecraft.inventory.IInventory; import net.minecraft.inventory.ISidedInventory; import net.minecraft.item.ItemStack; import net.minecraft.tileentity.HopperTileEntity; import net.minecraft.tileentity.TileEntity; import net.minecraft.util.Direction; import net.minecraft.util.math.BlockPos; import net.minecraft.world.World; import net.minecraft.world.chunk.Chunk; import net.minecraftforge.items.CapabilityItemHandler; import javax.annotation.Nullable; import java.util.ArrayList; import java.util.List; package com.latenighters.runicarcana.common.symbols; public class ExpulsionSymbol extends Symbol { public ExpulsionSymbol() {
super("symbol_expulsion", SymbolTextures.EXPEL, SymbolCategory.DEFAULT);
Drazuam/RunicArcana
src/main/java/com/latenighters/runicarcana/common/items/armor/PrincipicChestplateItem.java
// Path: src/main/java/com/latenighters/runicarcana/common/items/IClickable.java // public interface IClickable { // // //do the action - this is performed server side // //returns true when behavior is as expected // boolean onClick(PlayerEntity player, ItemStack itemStack, Container container, int slot); // // } // // Path: src/main/java/com/latenighters/runicarcana/util/Util.java // public class Util { // // public static ITextComponent loreStyle(ITextComponent textComponent){ // return textComponent.applyTextStyle(TextFormatting.DARK_PURPLE).applyTextStyle(TextFormatting.ITALIC); // } // // public static ITextComponent loreStyle(String key, Object...args){ // return loreStyle(new TranslationTextComponent(key, args)); // } // // public static ITextComponent tooltipStyle(ITextComponent textComponent){ // return textComponent.applyTextStyle(TextFormatting.GRAY); // } // // public static ITextComponent tooltipStyle(String key, Object... args){ // return tooltipStyle(new TranslationTextComponent(key, args)); // } // // public static void setPositionAndRotationAndUpdate(Entity entity, Double x, Double y, Double z, Float yaw, Float pitch) { // entity.setPositionAndUpdate(x, y, z); // entity.setPositionAndRotation(x, y, z, yaw, pitch); // } // // public static void setPositionAndRotationAndUpdate(Entity entity, Double x, Double y, Double z){ // setPositionAndRotationAndUpdate(entity, x, y, z, entity.rotationYaw, entity.rotationPitch); // } // // public static boolean checkHeadspace(World world, BlockPos pos){ // return world.isAirBlock(pos) && world.isAirBlock(pos.up()); // } // // public static void spawnParticleGroup(World world, BasicParticleType type, LivingEntity entity) { // final Random rand = new Random(); // if (world.isRemote) { // for (int i = 0; i < 30; ++i) { // double d0 = rand.nextGaussian() * 0.02D; // double d1 = rand.nextGaussian() * 0.02D; // double d2 = rand.nextGaussian() * 0.02D; // world.addParticle( // type, // entity.getPosX() + (double) (rand.nextFloat() * entity.getWidth() * 2.0F) - (double) entity.getWidth() - d0 * 10.0D, // entity.getPosY() + (double) (rand.nextFloat() * entity.getHeight()) - d1 * 10.0D, // entity.getPosZ() + (double) (rand.nextFloat() * entity.getWidth() * 2.0F) - (double) entity.getWidth() - d2 * 10.0D, d0, d1, d2 // ); // } // // } // } // // }
import com.latenighters.runicarcana.common.items.IClickable; import com.latenighters.runicarcana.util.Util; import net.minecraft.client.util.ITooltipFlag; import net.minecraft.inventory.EquipmentSlotType; import net.minecraft.item.ItemStack; import net.minecraft.util.text.ITextComponent; import net.minecraft.world.World; import javax.annotation.Nullable; import java.util.List;
package com.latenighters.runicarcana.common.items.armor; public class PrincipicChestplateItem extends AbstractPrincipicArmor implements IClickable { public PrincipicChestplateItem() { super(EquipmentSlotType.CHEST); } @Override public void addInformation(ItemStack stack, @Nullable World worldIn, List<ITextComponent> tooltip, ITooltipFlag flagIn) { if(isEnabled(stack))
// Path: src/main/java/com/latenighters/runicarcana/common/items/IClickable.java // public interface IClickable { // // //do the action - this is performed server side // //returns true when behavior is as expected // boolean onClick(PlayerEntity player, ItemStack itemStack, Container container, int slot); // // } // // Path: src/main/java/com/latenighters/runicarcana/util/Util.java // public class Util { // // public static ITextComponent loreStyle(ITextComponent textComponent){ // return textComponent.applyTextStyle(TextFormatting.DARK_PURPLE).applyTextStyle(TextFormatting.ITALIC); // } // // public static ITextComponent loreStyle(String key, Object...args){ // return loreStyle(new TranslationTextComponent(key, args)); // } // // public static ITextComponent tooltipStyle(ITextComponent textComponent){ // return textComponent.applyTextStyle(TextFormatting.GRAY); // } // // public static ITextComponent tooltipStyle(String key, Object... args){ // return tooltipStyle(new TranslationTextComponent(key, args)); // } // // public static void setPositionAndRotationAndUpdate(Entity entity, Double x, Double y, Double z, Float yaw, Float pitch) { // entity.setPositionAndUpdate(x, y, z); // entity.setPositionAndRotation(x, y, z, yaw, pitch); // } // // public static void setPositionAndRotationAndUpdate(Entity entity, Double x, Double y, Double z){ // setPositionAndRotationAndUpdate(entity, x, y, z, entity.rotationYaw, entity.rotationPitch); // } // // public static boolean checkHeadspace(World world, BlockPos pos){ // return world.isAirBlock(pos) && world.isAirBlock(pos.up()); // } // // public static void spawnParticleGroup(World world, BasicParticleType type, LivingEntity entity) { // final Random rand = new Random(); // if (world.isRemote) { // for (int i = 0; i < 30; ++i) { // double d0 = rand.nextGaussian() * 0.02D; // double d1 = rand.nextGaussian() * 0.02D; // double d2 = rand.nextGaussian() * 0.02D; // world.addParticle( // type, // entity.getPosX() + (double) (rand.nextFloat() * entity.getWidth() * 2.0F) - (double) entity.getWidth() - d0 * 10.0D, // entity.getPosY() + (double) (rand.nextFloat() * entity.getHeight()) - d1 * 10.0D, // entity.getPosZ() + (double) (rand.nextFloat() * entity.getWidth() * 2.0F) - (double) entity.getWidth() - d2 * 10.0D, d0, d1, d2 // ); // } // // } // } // // } // Path: src/main/java/com/latenighters/runicarcana/common/items/armor/PrincipicChestplateItem.java import com.latenighters.runicarcana.common.items.IClickable; import com.latenighters.runicarcana.util.Util; import net.minecraft.client.util.ITooltipFlag; import net.minecraft.inventory.EquipmentSlotType; import net.minecraft.item.ItemStack; import net.minecraft.util.text.ITextComponent; import net.minecraft.world.World; import javax.annotation.Nullable; import java.util.List; package com.latenighters.runicarcana.common.items.armor; public class PrincipicChestplateItem extends AbstractPrincipicArmor implements IClickable { public PrincipicChestplateItem() { super(EquipmentSlotType.CHEST); } @Override public void addInformation(ItemStack stack, @Nullable World worldIn, List<ITextComponent> tooltip, ITooltipFlag flagIn) { if(isEnabled(stack))
tooltip.add(Util.tooltipStyle("tooltip.runicarcana.principic_chestplate.effect_enabled"));
Drazuam/RunicArcana
src/main/java/com/latenighters/runicarcana/network/NetworkSync.java
// Path: src/main/java/com/latenighters/runicarcana/common/items/armor/PrincipicBootsItem.java // public class PrincipicBootsItem extends AbstractPrincipicArmor { // // private static final ItemStack rocketStack = new ItemStack(Items.FIREWORK_ROCKET, 1); // private static final int boostCooldown = 30; // // // public PrincipicBootsItem() { // super(EquipmentSlotType.FEET); // } // // @Override // @OnlyIn(Dist.CLIENT) // public void addInformation(ItemStack stack, @Nullable World worldIn, List<ITextComponent> tooltip, ITooltipFlag flagIn) { // if(isEnabled(stack)) // tooltip.add(Util.tooltipStyle("tooltip.runicarcana.principic_boots.effect_enabled")); // else // tooltip.add(Util.tooltipStyle("tooltip.runicarcana.principic_boots.effect_disabled")); // tooltip.add(Util.tooltipStyle("tooltip.runicarcana.principic_boots")); // tooltip.add(Util.tooltipStyle("tooltip.runicarcana.principic_boots.boost")); // super.addInformation(stack, worldIn, tooltip, flagIn); // tooltip.add(Util.loreStyle("lore.runicarcana.principic_boots")); // } // // // // public static class StepSyncMessage // { // float stepHeight; // // public StepSyncMessage(float stepHeight) { // this.stepHeight = stepHeight; // } // // public static void encode(final StepSyncMessage msg, final PacketBuffer buf) // { // buf.writeFloat(msg.stepHeight); // } // // public static StepSyncMessage decode(final PacketBuffer buf) // { // return new StepSyncMessage(buf.readFloat()); // } // // public static void handle(final StepSyncMessage msg, final Supplier<NetworkEvent.Context> contextSupplier) { // final NetworkEvent.Context context = contextSupplier.get(); // if (context.getDirection().equals(NetworkDirection.PLAY_TO_CLIENT)) { // context.enqueueWork(() -> { // // RunicArcana.proxy.getPlayer().stepHeight = msg.stepHeight; // // context.setPacketHandled(true); // }); // } // } // } // // public static void checkTimerNBT(ItemStack stack) { // CompoundNBT nbt = stack.getTag(); // if(nbt==null) // nbt = new CompoundNBT(); // if(!nbt.contains("timer")) // nbt.putLong("timer", 0L); // stack.setTag(nbt); // } // // public static long getTimer(ItemStack stack){ // checkNBT(stack); // return stack.getTag().getLong("timer"); // } // // public static void setTimer(ItemStack stack, Long time){ // checkNBT(stack); // CompoundNBT nbt = stack.getTag(); // nbt.putLong("timer", time); // stack.setTag(nbt); // } // // @Override // public void onArmorTick(ItemStack stack, World world, PlayerEntity player) { // if (player.isSteppingCarefully() && getTimer(stack) < world.getGameTime() && player.isElytraFlying()) { // if (!world.isRemote){ // world.addEntity(new FireworkRocketEntity(world, rocketStack, player)); // } // setTimer(stack, world.getGameTime() + boostCooldown); // } // if (!player.isElytraFlying() && player.onGround && getTimer(stack) != 0) // setTimer(stack, 0L); // } // // }
import com.latenighters.runicarcana.common.items.armor.PrincipicBootsItem; import net.minecraft.util.ResourceLocation; import net.minecraftforge.fml.network.NetworkRegistry; import net.minecraftforge.fml.network.simple.SimpleChannel;
package com.latenighters.runicarcana.network; public class NetworkSync { private static final String PROTOCOL_VERSION = "1"; public static final SimpleChannel INSTANCE = NetworkRegistry.newSimpleChannel( new ResourceLocation("principium", "synchronization"), () -> PROTOCOL_VERSION, PROTOCOL_VERSION::equals, PROTOCOL_VERSION::equals ); public static void registerPackets() { int ind = 0;
// Path: src/main/java/com/latenighters/runicarcana/common/items/armor/PrincipicBootsItem.java // public class PrincipicBootsItem extends AbstractPrincipicArmor { // // private static final ItemStack rocketStack = new ItemStack(Items.FIREWORK_ROCKET, 1); // private static final int boostCooldown = 30; // // // public PrincipicBootsItem() { // super(EquipmentSlotType.FEET); // } // // @Override // @OnlyIn(Dist.CLIENT) // public void addInformation(ItemStack stack, @Nullable World worldIn, List<ITextComponent> tooltip, ITooltipFlag flagIn) { // if(isEnabled(stack)) // tooltip.add(Util.tooltipStyle("tooltip.runicarcana.principic_boots.effect_enabled")); // else // tooltip.add(Util.tooltipStyle("tooltip.runicarcana.principic_boots.effect_disabled")); // tooltip.add(Util.tooltipStyle("tooltip.runicarcana.principic_boots")); // tooltip.add(Util.tooltipStyle("tooltip.runicarcana.principic_boots.boost")); // super.addInformation(stack, worldIn, tooltip, flagIn); // tooltip.add(Util.loreStyle("lore.runicarcana.principic_boots")); // } // // // // public static class StepSyncMessage // { // float stepHeight; // // public StepSyncMessage(float stepHeight) { // this.stepHeight = stepHeight; // } // // public static void encode(final StepSyncMessage msg, final PacketBuffer buf) // { // buf.writeFloat(msg.stepHeight); // } // // public static StepSyncMessage decode(final PacketBuffer buf) // { // return new StepSyncMessage(buf.readFloat()); // } // // public static void handle(final StepSyncMessage msg, final Supplier<NetworkEvent.Context> contextSupplier) { // final NetworkEvent.Context context = contextSupplier.get(); // if (context.getDirection().equals(NetworkDirection.PLAY_TO_CLIENT)) { // context.enqueueWork(() -> { // // RunicArcana.proxy.getPlayer().stepHeight = msg.stepHeight; // // context.setPacketHandled(true); // }); // } // } // } // // public static void checkTimerNBT(ItemStack stack) { // CompoundNBT nbt = stack.getTag(); // if(nbt==null) // nbt = new CompoundNBT(); // if(!nbt.contains("timer")) // nbt.putLong("timer", 0L); // stack.setTag(nbt); // } // // public static long getTimer(ItemStack stack){ // checkNBT(stack); // return stack.getTag().getLong("timer"); // } // // public static void setTimer(ItemStack stack, Long time){ // checkNBT(stack); // CompoundNBT nbt = stack.getTag(); // nbt.putLong("timer", time); // stack.setTag(nbt); // } // // @Override // public void onArmorTick(ItemStack stack, World world, PlayerEntity player) { // if (player.isSteppingCarefully() && getTimer(stack) < world.getGameTime() && player.isElytraFlying()) { // if (!world.isRemote){ // world.addEntity(new FireworkRocketEntity(world, rocketStack, player)); // } // setTimer(stack, world.getGameTime() + boostCooldown); // } // if (!player.isElytraFlying() && player.onGround && getTimer(stack) != 0) // setTimer(stack, 0L); // } // // } // Path: src/main/java/com/latenighters/runicarcana/network/NetworkSync.java import com.latenighters.runicarcana.common.items.armor.PrincipicBootsItem; import net.minecraft.util.ResourceLocation; import net.minecraftforge.fml.network.NetworkRegistry; import net.minecraftforge.fml.network.simple.SimpleChannel; package com.latenighters.runicarcana.network; public class NetworkSync { private static final String PROTOCOL_VERSION = "1"; public static final SimpleChannel INSTANCE = NetworkRegistry.newSimpleChannel( new ResourceLocation("principium", "synchronization"), () -> PROTOCOL_VERSION, PROTOCOL_VERSION::equals, PROTOCOL_VERSION::equals ); public static void registerPackets() { int ind = 0;
INSTANCE.registerMessage(ind++, PrincipicBootsItem.StepSyncMessage.class,
Drazuam/RunicArcana
src/main/java/com/latenighters/runicarcana/common/symbols/RedstoneSymbol.java
// Path: src/main/java/com/latenighters/runicarcana/common/symbols/categories/SymbolCategory.java // public class SymbolCategory { // // public static SymbolCategory DEFAULT = new SymbolCategory(Symbols.DEBUG, MODID+".symbol.category.default"); // // private Symbol displaySymbol; // private final String unlocalizedName; // // public static void generateCategories() // { // //TODO figure out why static initialization isn't working // DEFAULT.setDisplaySymbol(Symbols.EXPULSION); // } // // public SymbolCategory(Symbol displaySymbol, String unlocalizedName) { // this.displaySymbol = displaySymbol; // this.unlocalizedName = unlocalizedName; // } // // public Symbol getDisplaySymbol() { // return displaySymbol; // } // // public void setDisplaySymbol(Symbol displaySymbol) { // this.displaySymbol = displaySymbol; // } // // public String getUnlocalizedName() { // return unlocalizedName; // } // }
import com.latenighters.runicarcana.common.symbols.backend.*; import com.latenighters.runicarcana.common.symbols.categories.SymbolCategory; import net.minecraft.state.BooleanProperty; import net.minecraft.state.properties.BlockStateProperties; import net.minecraft.world.chunk.Chunk; import java.util.ArrayList; import java.util.List;
package com.latenighters.runicarcana.common.symbols; public class RedstoneSymbol extends Symbol { public RedstoneSymbol() {
// Path: src/main/java/com/latenighters/runicarcana/common/symbols/categories/SymbolCategory.java // public class SymbolCategory { // // public static SymbolCategory DEFAULT = new SymbolCategory(Symbols.DEBUG, MODID+".symbol.category.default"); // // private Symbol displaySymbol; // private final String unlocalizedName; // // public static void generateCategories() // { // //TODO figure out why static initialization isn't working // DEFAULT.setDisplaySymbol(Symbols.EXPULSION); // } // // public SymbolCategory(Symbol displaySymbol, String unlocalizedName) { // this.displaySymbol = displaySymbol; // this.unlocalizedName = unlocalizedName; // } // // public Symbol getDisplaySymbol() { // return displaySymbol; // } // // public void setDisplaySymbol(Symbol displaySymbol) { // this.displaySymbol = displaySymbol; // } // // public String getUnlocalizedName() { // return unlocalizedName; // } // } // Path: src/main/java/com/latenighters/runicarcana/common/symbols/RedstoneSymbol.java import com.latenighters.runicarcana.common.symbols.backend.*; import com.latenighters.runicarcana.common.symbols.categories.SymbolCategory; import net.minecraft.state.BooleanProperty; import net.minecraft.state.properties.BlockStateProperties; import net.minecraft.world.chunk.Chunk; import java.util.ArrayList; import java.util.List; package com.latenighters.runicarcana.common.symbols; public class RedstoneSymbol extends Symbol { public RedstoneSymbol() {
super("symbol_redstone", SymbolTextures.REDSTONE, SymbolCategory.DEFAULT);
Drazuam/RunicArcana
src/main/java/com/latenighters/runicarcana/common/symbols/Symbols.java
// Path: src/main/java/com/latenighters/runicarcana/common/symbols/backend/Symbol.java // public abstract class Symbol extends net.minecraftforge.registries.ForgeRegistryEntry<Symbol> { // // protected String name; // protected ResourceLocation texture; // protected int id = -1; // protected final SymbolCategory category; // // protected List<IFunctional> functions = new ArrayList<IFunctional>(); // protected List<HashableTuple<String,DataType>> inputs = new ArrayList<HashableTuple<String,DataType>>(); // protected List<IFunctional> outputs = new ArrayList<IFunctional>(); // protected List<HashableTuple<HashableTuple<String, DataType>, IFunctional>> triggers = new ArrayList<HashableTuple<HashableTuple<String, DataType>, IFunctional>>(); // // public Symbol(String name, ResourceLocation texture, SymbolCategory category) { // this.name = name; // this.texture = texture; // this.category = category; // this.setRegistryName(new ResourceLocation(MODID, this.name)); // // this.registerFunctions(); // // //roll up the functions into the functional object fields // for (IFunctional function : functions) // { // //synchronize the inputs from all the functions // for(HashableTuple<String,DataType> input : inputs) { // //check to see if inputs already has the same DataType and String registered // if(function.getRequiredInputs()==null)return; // function.getRequiredInputs().removeIf(finput -> // { // if (function.getRequiredInputs().contains(finput)) return false; // if (input.getA().equals(finput.getA()) && input.getB().type.equals(finput.getB().type)) { // //if we do, remove the input from the function and replace it with the already registered input // function.getRequiredInputs().add(input); // return true; // } // return false; // }); // } // // //add each input into the object inputs // if(function.getRequiredInputs()!=null) // function.getRequiredInputs().forEach(finput->{ // if(!inputs.contains(finput)) // inputs.add(finput); // }); // } // // //repeat for outputs // for (IFunctional function : outputs) // { // //synchronize the inputs from all the functions // for(HashableTuple<String,DataType> input : inputs) { // //check to see if inputs already has the same DataType and String registered // if(function.getRequiredInputs()==null)return; // function.getRequiredInputs().removeIf(finput -> // { // if (function.getRequiredInputs().contains(finput)) return false; // if (input.getA().equals(finput.getA()) && input.getB().type.equals(finput.getB().type)) { // //if we do, remove the input from the function and replace it with the already registered input // function.getRequiredInputs().add(input); // return true; // } // return false; // }); // } // // //add each input into the object inputs // if(function.getRequiredInputs()!=null) // function.getRequiredInputs().forEach(finput->{ // if(!inputs.contains(finput)) // inputs.add(finput); // }); // } // } // // public Symbol(String name) // { // this(name, SymbolTextures.DEBUG, SymbolCategory.DEFAULT); // } // // public String getName() // { // return name; // } // // public ResourceLocation getTexture() { // return texture; // } // // //we really shouldn't be using this // public void onTick(DrawnSymbol symbol, World world, Chunk chunk, BlockPos drawnOn, Direction blockFace) { // // } // // protected abstract void registerFunctions(); // // public List<IFunctional> getFunctions() { // return functions; // } // // public List<HashableTuple<String,DataType>> getInputs(){ // return inputs; // } // // public List<IFunctional> getOutputs() { // return outputs; // } // // public List<HashableTuple<HashableTuple<String, DataType>, IFunctional>> getTriggers() // { // return triggers; // } // // public static class DummySymbol extends Symbol{ // public DummySymbol(String name) { // super(name); // } // // @Override // protected void registerFunctions() { // // } // } // // public SymbolCategory getCategory() // { // return category; // } // // public int getId() { // return id; // } // // //put DrawnSymbol data into contents of packet buffer // public void encode(final DrawnSymbol symbol, final PacketBuffer buf) // { // buf.writeInt(symbol.blockFace.getIndex()); // buf.writeInt(symbol.drawnOn.getX()); // buf.writeInt(symbol.drawnOn.getY()); // buf.writeInt(symbol.drawnOn.getZ()); // } // // //take contents of packet buffer and put into DrawnSymbol // public void decode(final DrawnSymbol symbol, final PacketBuffer buf) // { // symbol.blockFace = Direction.byIndex(buf.readInt()); // symbol.drawnOn = new BlockPos(buf.readInt(),buf.readInt(),buf.readInt()); // } // // // // }
import com.latenighters.runicarcana.common.symbols.backend.Symbol; import net.minecraftforge.registries.ObjectHolder;
package com.latenighters.runicarcana.common.symbols; public class Symbols { @ObjectHolder("runicarcana:symbol_debug")
// Path: src/main/java/com/latenighters/runicarcana/common/symbols/backend/Symbol.java // public abstract class Symbol extends net.minecraftforge.registries.ForgeRegistryEntry<Symbol> { // // protected String name; // protected ResourceLocation texture; // protected int id = -1; // protected final SymbolCategory category; // // protected List<IFunctional> functions = new ArrayList<IFunctional>(); // protected List<HashableTuple<String,DataType>> inputs = new ArrayList<HashableTuple<String,DataType>>(); // protected List<IFunctional> outputs = new ArrayList<IFunctional>(); // protected List<HashableTuple<HashableTuple<String, DataType>, IFunctional>> triggers = new ArrayList<HashableTuple<HashableTuple<String, DataType>, IFunctional>>(); // // public Symbol(String name, ResourceLocation texture, SymbolCategory category) { // this.name = name; // this.texture = texture; // this.category = category; // this.setRegistryName(new ResourceLocation(MODID, this.name)); // // this.registerFunctions(); // // //roll up the functions into the functional object fields // for (IFunctional function : functions) // { // //synchronize the inputs from all the functions // for(HashableTuple<String,DataType> input : inputs) { // //check to see if inputs already has the same DataType and String registered // if(function.getRequiredInputs()==null)return; // function.getRequiredInputs().removeIf(finput -> // { // if (function.getRequiredInputs().contains(finput)) return false; // if (input.getA().equals(finput.getA()) && input.getB().type.equals(finput.getB().type)) { // //if we do, remove the input from the function and replace it with the already registered input // function.getRequiredInputs().add(input); // return true; // } // return false; // }); // } // // //add each input into the object inputs // if(function.getRequiredInputs()!=null) // function.getRequiredInputs().forEach(finput->{ // if(!inputs.contains(finput)) // inputs.add(finput); // }); // } // // //repeat for outputs // for (IFunctional function : outputs) // { // //synchronize the inputs from all the functions // for(HashableTuple<String,DataType> input : inputs) { // //check to see if inputs already has the same DataType and String registered // if(function.getRequiredInputs()==null)return; // function.getRequiredInputs().removeIf(finput -> // { // if (function.getRequiredInputs().contains(finput)) return false; // if (input.getA().equals(finput.getA()) && input.getB().type.equals(finput.getB().type)) { // //if we do, remove the input from the function and replace it with the already registered input // function.getRequiredInputs().add(input); // return true; // } // return false; // }); // } // // //add each input into the object inputs // if(function.getRequiredInputs()!=null) // function.getRequiredInputs().forEach(finput->{ // if(!inputs.contains(finput)) // inputs.add(finput); // }); // } // } // // public Symbol(String name) // { // this(name, SymbolTextures.DEBUG, SymbolCategory.DEFAULT); // } // // public String getName() // { // return name; // } // // public ResourceLocation getTexture() { // return texture; // } // // //we really shouldn't be using this // public void onTick(DrawnSymbol symbol, World world, Chunk chunk, BlockPos drawnOn, Direction blockFace) { // // } // // protected abstract void registerFunctions(); // // public List<IFunctional> getFunctions() { // return functions; // } // // public List<HashableTuple<String,DataType>> getInputs(){ // return inputs; // } // // public List<IFunctional> getOutputs() { // return outputs; // } // // public List<HashableTuple<HashableTuple<String, DataType>, IFunctional>> getTriggers() // { // return triggers; // } // // public static class DummySymbol extends Symbol{ // public DummySymbol(String name) { // super(name); // } // // @Override // protected void registerFunctions() { // // } // } // // public SymbolCategory getCategory() // { // return category; // } // // public int getId() { // return id; // } // // //put DrawnSymbol data into contents of packet buffer // public void encode(final DrawnSymbol symbol, final PacketBuffer buf) // { // buf.writeInt(symbol.blockFace.getIndex()); // buf.writeInt(symbol.drawnOn.getX()); // buf.writeInt(symbol.drawnOn.getY()); // buf.writeInt(symbol.drawnOn.getZ()); // } // // //take contents of packet buffer and put into DrawnSymbol // public void decode(final DrawnSymbol symbol, final PacketBuffer buf) // { // symbol.blockFace = Direction.byIndex(buf.readInt()); // symbol.drawnOn = new BlockPos(buf.readInt(),buf.readInt(),buf.readInt()); // } // // // // } // Path: src/main/java/com/latenighters/runicarcana/common/symbols/Symbols.java import com.latenighters.runicarcana.common.symbols.backend.Symbol; import net.minecraftforge.registries.ObjectHolder; package com.latenighters.runicarcana.common.symbols; public class Symbols { @ObjectHolder("runicarcana:symbol_debug")
public static final Symbol DEBUG = null;
Drazuam/RunicArcana
src/main/java/com/latenighters/runicarcana/common/items/armor/PrincipicHelmetItem.java
// Path: src/main/java/com/latenighters/runicarcana/util/Util.java // public class Util { // // public static ITextComponent loreStyle(ITextComponent textComponent){ // return textComponent.applyTextStyle(TextFormatting.DARK_PURPLE).applyTextStyle(TextFormatting.ITALIC); // } // // public static ITextComponent loreStyle(String key, Object...args){ // return loreStyle(new TranslationTextComponent(key, args)); // } // // public static ITextComponent tooltipStyle(ITextComponent textComponent){ // return textComponent.applyTextStyle(TextFormatting.GRAY); // } // // public static ITextComponent tooltipStyle(String key, Object... args){ // return tooltipStyle(new TranslationTextComponent(key, args)); // } // // public static void setPositionAndRotationAndUpdate(Entity entity, Double x, Double y, Double z, Float yaw, Float pitch) { // entity.setPositionAndUpdate(x, y, z); // entity.setPositionAndRotation(x, y, z, yaw, pitch); // } // // public static void setPositionAndRotationAndUpdate(Entity entity, Double x, Double y, Double z){ // setPositionAndRotationAndUpdate(entity, x, y, z, entity.rotationYaw, entity.rotationPitch); // } // // public static boolean checkHeadspace(World world, BlockPos pos){ // return world.isAirBlock(pos) && world.isAirBlock(pos.up()); // } // // public static void spawnParticleGroup(World world, BasicParticleType type, LivingEntity entity) { // final Random rand = new Random(); // if (world.isRemote) { // for (int i = 0; i < 30; ++i) { // double d0 = rand.nextGaussian() * 0.02D; // double d1 = rand.nextGaussian() * 0.02D; // double d2 = rand.nextGaussian() * 0.02D; // world.addParticle( // type, // entity.getPosX() + (double) (rand.nextFloat() * entity.getWidth() * 2.0F) - (double) entity.getWidth() - d0 * 10.0D, // entity.getPosY() + (double) (rand.nextFloat() * entity.getHeight()) - d1 * 10.0D, // entity.getPosZ() + (double) (rand.nextFloat() * entity.getWidth() * 2.0F) - (double) entity.getWidth() - d2 * 10.0D, d0, d1, d2 // ); // } // // } // } // // }
import com.latenighters.runicarcana.util.Util; import net.minecraft.client.util.ITooltipFlag; import net.minecraft.entity.player.PlayerEntity; import net.minecraft.inventory.EquipmentSlotType; import net.minecraft.item.ItemStack; import net.minecraft.util.text.ITextComponent; import net.minecraft.world.World; import javax.annotation.Nullable; import java.util.List;
package com.latenighters.runicarcana.common.items.armor; public class PrincipicHelmetItem extends AbstractPrincipicArmor { public PrincipicHelmetItem() { super(EquipmentSlotType.HEAD); } @Override public void addInformation(ItemStack stack, @Nullable World worldIn, List<ITextComponent> tooltip, ITooltipFlag flagIn) { if(isEnabled(stack))
// Path: src/main/java/com/latenighters/runicarcana/util/Util.java // public class Util { // // public static ITextComponent loreStyle(ITextComponent textComponent){ // return textComponent.applyTextStyle(TextFormatting.DARK_PURPLE).applyTextStyle(TextFormatting.ITALIC); // } // // public static ITextComponent loreStyle(String key, Object...args){ // return loreStyle(new TranslationTextComponent(key, args)); // } // // public static ITextComponent tooltipStyle(ITextComponent textComponent){ // return textComponent.applyTextStyle(TextFormatting.GRAY); // } // // public static ITextComponent tooltipStyle(String key, Object... args){ // return tooltipStyle(new TranslationTextComponent(key, args)); // } // // public static void setPositionAndRotationAndUpdate(Entity entity, Double x, Double y, Double z, Float yaw, Float pitch) { // entity.setPositionAndUpdate(x, y, z); // entity.setPositionAndRotation(x, y, z, yaw, pitch); // } // // public static void setPositionAndRotationAndUpdate(Entity entity, Double x, Double y, Double z){ // setPositionAndRotationAndUpdate(entity, x, y, z, entity.rotationYaw, entity.rotationPitch); // } // // public static boolean checkHeadspace(World world, BlockPos pos){ // return world.isAirBlock(pos) && world.isAirBlock(pos.up()); // } // // public static void spawnParticleGroup(World world, BasicParticleType type, LivingEntity entity) { // final Random rand = new Random(); // if (world.isRemote) { // for (int i = 0; i < 30; ++i) { // double d0 = rand.nextGaussian() * 0.02D; // double d1 = rand.nextGaussian() * 0.02D; // double d2 = rand.nextGaussian() * 0.02D; // world.addParticle( // type, // entity.getPosX() + (double) (rand.nextFloat() * entity.getWidth() * 2.0F) - (double) entity.getWidth() - d0 * 10.0D, // entity.getPosY() + (double) (rand.nextFloat() * entity.getHeight()) - d1 * 10.0D, // entity.getPosZ() + (double) (rand.nextFloat() * entity.getWidth() * 2.0F) - (double) entity.getWidth() - d2 * 10.0D, d0, d1, d2 // ); // } // // } // } // // } // Path: src/main/java/com/latenighters/runicarcana/common/items/armor/PrincipicHelmetItem.java import com.latenighters.runicarcana.util.Util; import net.minecraft.client.util.ITooltipFlag; import net.minecraft.entity.player.PlayerEntity; import net.minecraft.inventory.EquipmentSlotType; import net.minecraft.item.ItemStack; import net.minecraft.util.text.ITextComponent; import net.minecraft.world.World; import javax.annotation.Nullable; import java.util.List; package com.latenighters.runicarcana.common.items.armor; public class PrincipicHelmetItem extends AbstractPrincipicArmor { public PrincipicHelmetItem() { super(EquipmentSlotType.HEAD); } @Override public void addInformation(ItemStack stack, @Nullable World worldIn, List<ITextComponent> tooltip, ITooltipFlag flagIn) { if(isEnabled(stack))
tooltip.add(Util.tooltipStyle("tooltip.runicarcana.principic_helmet.effect_enabled"));
Drazuam/RunicArcana
src/main/java/com/latenighters/runicarcana/common/symbols/backend/Symbol.java
// Path: src/main/java/com/latenighters/runicarcana/common/symbols/SymbolTextures.java // @Mod.EventBusSubscriber(modid = MODID, value = Dist.CLIENT, bus = Mod.EventBusSubscriber.Bus.MOD) // public class SymbolTextures { // // public static final ResourceLocation DEBUG = new ResourceLocation(MODID , "symbols/symbol_x"); // public static final ResourceLocation EXPEL = new ResourceLocation(MODID , "symbols/symbol_expel"); // public static final ResourceLocation INSERT = new ResourceLocation(MODID , "symbols/symbol_insert"); // public static final ResourceLocation REDSTONE = new ResourceLocation(MODID , "symbols/symbol_redstone"); // public static final ResourceLocation BOOLEAN_LOGIC = new ResourceLocation(MODID , "symbols/symbol_boolean_logic"); // public static final ResourceLocation DETECT= new ResourceLocation(MODID , "symbols/symbol_detect"); // // // // @SubscribeEvent // public static void onStitchEvent(TextureStitchEvent.Pre event) // { // ResourceLocation stitching = event.getMap().getTextureLocation(); // if(!stitching.equals(AtlasTexture.LOCATION_BLOCKS_TEXTURE)) // { // return; // } // for (ResourceLocation tex:textureList) // { // event.addSprite(tex); // } // } // // public static void consolidateTextures(final RegistryEvent.Register<Symbol> evt) // { // // for(Symbol symbol : evt.getRegistry().getValues()) // { // if(!textureList.contains(symbol.getTexture())) // { // textureList.add(symbol.getTexture()); // } // } // } // // private static ArrayList<ResourceLocation> textureList = new ArrayList<ResourceLocation>(); // // } // // Path: src/main/java/com/latenighters/runicarcana/common/symbols/categories/SymbolCategory.java // public class SymbolCategory { // // public static SymbolCategory DEFAULT = new SymbolCategory(Symbols.DEBUG, MODID+".symbol.category.default"); // // private Symbol displaySymbol; // private final String unlocalizedName; // // public static void generateCategories() // { // //TODO figure out why static initialization isn't working // DEFAULT.setDisplaySymbol(Symbols.EXPULSION); // } // // public SymbolCategory(Symbol displaySymbol, String unlocalizedName) { // this.displaySymbol = displaySymbol; // this.unlocalizedName = unlocalizedName; // } // // public Symbol getDisplaySymbol() { // return displaySymbol; // } // // public void setDisplaySymbol(Symbol displaySymbol) { // this.displaySymbol = displaySymbol; // } // // public String getUnlocalizedName() { // return unlocalizedName; // } // } // // Path: src/main/java/com/latenighters/runicarcana/RunicArcana.java // public static final String MODID = "runicarcana";
import com.latenighters.runicarcana.common.symbols.SymbolTextures; import com.latenighters.runicarcana.common.symbols.categories.SymbolCategory; import net.minecraft.network.PacketBuffer; import net.minecraft.util.Direction; import net.minecraft.util.ResourceLocation; import net.minecraft.util.math.BlockPos; import net.minecraft.world.World; import net.minecraft.world.chunk.Chunk; import java.util.ArrayList; import java.util.List; import static com.latenighters.runicarcana.RunicArcana.MODID;
package com.latenighters.runicarcana.common.symbols.backend; public abstract class Symbol extends net.minecraftforge.registries.ForgeRegistryEntry<Symbol> { protected String name; protected ResourceLocation texture; protected int id = -1;
// Path: src/main/java/com/latenighters/runicarcana/common/symbols/SymbolTextures.java // @Mod.EventBusSubscriber(modid = MODID, value = Dist.CLIENT, bus = Mod.EventBusSubscriber.Bus.MOD) // public class SymbolTextures { // // public static final ResourceLocation DEBUG = new ResourceLocation(MODID , "symbols/symbol_x"); // public static final ResourceLocation EXPEL = new ResourceLocation(MODID , "symbols/symbol_expel"); // public static final ResourceLocation INSERT = new ResourceLocation(MODID , "symbols/symbol_insert"); // public static final ResourceLocation REDSTONE = new ResourceLocation(MODID , "symbols/symbol_redstone"); // public static final ResourceLocation BOOLEAN_LOGIC = new ResourceLocation(MODID , "symbols/symbol_boolean_logic"); // public static final ResourceLocation DETECT= new ResourceLocation(MODID , "symbols/symbol_detect"); // // // // @SubscribeEvent // public static void onStitchEvent(TextureStitchEvent.Pre event) // { // ResourceLocation stitching = event.getMap().getTextureLocation(); // if(!stitching.equals(AtlasTexture.LOCATION_BLOCKS_TEXTURE)) // { // return; // } // for (ResourceLocation tex:textureList) // { // event.addSprite(tex); // } // } // // public static void consolidateTextures(final RegistryEvent.Register<Symbol> evt) // { // // for(Symbol symbol : evt.getRegistry().getValues()) // { // if(!textureList.contains(symbol.getTexture())) // { // textureList.add(symbol.getTexture()); // } // } // } // // private static ArrayList<ResourceLocation> textureList = new ArrayList<ResourceLocation>(); // // } // // Path: src/main/java/com/latenighters/runicarcana/common/symbols/categories/SymbolCategory.java // public class SymbolCategory { // // public static SymbolCategory DEFAULT = new SymbolCategory(Symbols.DEBUG, MODID+".symbol.category.default"); // // private Symbol displaySymbol; // private final String unlocalizedName; // // public static void generateCategories() // { // //TODO figure out why static initialization isn't working // DEFAULT.setDisplaySymbol(Symbols.EXPULSION); // } // // public SymbolCategory(Symbol displaySymbol, String unlocalizedName) { // this.displaySymbol = displaySymbol; // this.unlocalizedName = unlocalizedName; // } // // public Symbol getDisplaySymbol() { // return displaySymbol; // } // // public void setDisplaySymbol(Symbol displaySymbol) { // this.displaySymbol = displaySymbol; // } // // public String getUnlocalizedName() { // return unlocalizedName; // } // } // // Path: src/main/java/com/latenighters/runicarcana/RunicArcana.java // public static final String MODID = "runicarcana"; // Path: src/main/java/com/latenighters/runicarcana/common/symbols/backend/Symbol.java import com.latenighters.runicarcana.common.symbols.SymbolTextures; import com.latenighters.runicarcana.common.symbols.categories.SymbolCategory; import net.minecraft.network.PacketBuffer; import net.minecraft.util.Direction; import net.minecraft.util.ResourceLocation; import net.minecraft.util.math.BlockPos; import net.minecraft.world.World; import net.minecraft.world.chunk.Chunk; import java.util.ArrayList; import java.util.List; import static com.latenighters.runicarcana.RunicArcana.MODID; package com.latenighters.runicarcana.common.symbols.backend; public abstract class Symbol extends net.minecraftforge.registries.ForgeRegistryEntry<Symbol> { protected String name; protected ResourceLocation texture; protected int id = -1;
protected final SymbolCategory category;
Drazuam/RunicArcana
src/main/java/com/latenighters/runicarcana/common/symbols/backend/Symbol.java
// Path: src/main/java/com/latenighters/runicarcana/common/symbols/SymbolTextures.java // @Mod.EventBusSubscriber(modid = MODID, value = Dist.CLIENT, bus = Mod.EventBusSubscriber.Bus.MOD) // public class SymbolTextures { // // public static final ResourceLocation DEBUG = new ResourceLocation(MODID , "symbols/symbol_x"); // public static final ResourceLocation EXPEL = new ResourceLocation(MODID , "symbols/symbol_expel"); // public static final ResourceLocation INSERT = new ResourceLocation(MODID , "symbols/symbol_insert"); // public static final ResourceLocation REDSTONE = new ResourceLocation(MODID , "symbols/symbol_redstone"); // public static final ResourceLocation BOOLEAN_LOGIC = new ResourceLocation(MODID , "symbols/symbol_boolean_logic"); // public static final ResourceLocation DETECT= new ResourceLocation(MODID , "symbols/symbol_detect"); // // // // @SubscribeEvent // public static void onStitchEvent(TextureStitchEvent.Pre event) // { // ResourceLocation stitching = event.getMap().getTextureLocation(); // if(!stitching.equals(AtlasTexture.LOCATION_BLOCKS_TEXTURE)) // { // return; // } // for (ResourceLocation tex:textureList) // { // event.addSprite(tex); // } // } // // public static void consolidateTextures(final RegistryEvent.Register<Symbol> evt) // { // // for(Symbol symbol : evt.getRegistry().getValues()) // { // if(!textureList.contains(symbol.getTexture())) // { // textureList.add(symbol.getTexture()); // } // } // } // // private static ArrayList<ResourceLocation> textureList = new ArrayList<ResourceLocation>(); // // } // // Path: src/main/java/com/latenighters/runicarcana/common/symbols/categories/SymbolCategory.java // public class SymbolCategory { // // public static SymbolCategory DEFAULT = new SymbolCategory(Symbols.DEBUG, MODID+".symbol.category.default"); // // private Symbol displaySymbol; // private final String unlocalizedName; // // public static void generateCategories() // { // //TODO figure out why static initialization isn't working // DEFAULT.setDisplaySymbol(Symbols.EXPULSION); // } // // public SymbolCategory(Symbol displaySymbol, String unlocalizedName) { // this.displaySymbol = displaySymbol; // this.unlocalizedName = unlocalizedName; // } // // public Symbol getDisplaySymbol() { // return displaySymbol; // } // // public void setDisplaySymbol(Symbol displaySymbol) { // this.displaySymbol = displaySymbol; // } // // public String getUnlocalizedName() { // return unlocalizedName; // } // } // // Path: src/main/java/com/latenighters/runicarcana/RunicArcana.java // public static final String MODID = "runicarcana";
import com.latenighters.runicarcana.common.symbols.SymbolTextures; import com.latenighters.runicarcana.common.symbols.categories.SymbolCategory; import net.minecraft.network.PacketBuffer; import net.minecraft.util.Direction; import net.minecraft.util.ResourceLocation; import net.minecraft.util.math.BlockPos; import net.minecraft.world.World; import net.minecraft.world.chunk.Chunk; import java.util.ArrayList; import java.util.List; import static com.latenighters.runicarcana.RunicArcana.MODID;
package com.latenighters.runicarcana.common.symbols.backend; public abstract class Symbol extends net.minecraftforge.registries.ForgeRegistryEntry<Symbol> { protected String name; protected ResourceLocation texture; protected int id = -1; protected final SymbolCategory category; protected List<IFunctional> functions = new ArrayList<IFunctional>(); protected List<HashableTuple<String,DataType>> inputs = new ArrayList<HashableTuple<String,DataType>>(); protected List<IFunctional> outputs = new ArrayList<IFunctional>(); protected List<HashableTuple<HashableTuple<String, DataType>, IFunctional>> triggers = new ArrayList<HashableTuple<HashableTuple<String, DataType>, IFunctional>>(); public Symbol(String name, ResourceLocation texture, SymbolCategory category) { this.name = name; this.texture = texture; this.category = category;
// Path: src/main/java/com/latenighters/runicarcana/common/symbols/SymbolTextures.java // @Mod.EventBusSubscriber(modid = MODID, value = Dist.CLIENT, bus = Mod.EventBusSubscriber.Bus.MOD) // public class SymbolTextures { // // public static final ResourceLocation DEBUG = new ResourceLocation(MODID , "symbols/symbol_x"); // public static final ResourceLocation EXPEL = new ResourceLocation(MODID , "symbols/symbol_expel"); // public static final ResourceLocation INSERT = new ResourceLocation(MODID , "symbols/symbol_insert"); // public static final ResourceLocation REDSTONE = new ResourceLocation(MODID , "symbols/symbol_redstone"); // public static final ResourceLocation BOOLEAN_LOGIC = new ResourceLocation(MODID , "symbols/symbol_boolean_logic"); // public static final ResourceLocation DETECT= new ResourceLocation(MODID , "symbols/symbol_detect"); // // // // @SubscribeEvent // public static void onStitchEvent(TextureStitchEvent.Pre event) // { // ResourceLocation stitching = event.getMap().getTextureLocation(); // if(!stitching.equals(AtlasTexture.LOCATION_BLOCKS_TEXTURE)) // { // return; // } // for (ResourceLocation tex:textureList) // { // event.addSprite(tex); // } // } // // public static void consolidateTextures(final RegistryEvent.Register<Symbol> evt) // { // // for(Symbol symbol : evt.getRegistry().getValues()) // { // if(!textureList.contains(symbol.getTexture())) // { // textureList.add(symbol.getTexture()); // } // } // } // // private static ArrayList<ResourceLocation> textureList = new ArrayList<ResourceLocation>(); // // } // // Path: src/main/java/com/latenighters/runicarcana/common/symbols/categories/SymbolCategory.java // public class SymbolCategory { // // public static SymbolCategory DEFAULT = new SymbolCategory(Symbols.DEBUG, MODID+".symbol.category.default"); // // private Symbol displaySymbol; // private final String unlocalizedName; // // public static void generateCategories() // { // //TODO figure out why static initialization isn't working // DEFAULT.setDisplaySymbol(Symbols.EXPULSION); // } // // public SymbolCategory(Symbol displaySymbol, String unlocalizedName) { // this.displaySymbol = displaySymbol; // this.unlocalizedName = unlocalizedName; // } // // public Symbol getDisplaySymbol() { // return displaySymbol; // } // // public void setDisplaySymbol(Symbol displaySymbol) { // this.displaySymbol = displaySymbol; // } // // public String getUnlocalizedName() { // return unlocalizedName; // } // } // // Path: src/main/java/com/latenighters/runicarcana/RunicArcana.java // public static final String MODID = "runicarcana"; // Path: src/main/java/com/latenighters/runicarcana/common/symbols/backend/Symbol.java import com.latenighters.runicarcana.common.symbols.SymbolTextures; import com.latenighters.runicarcana.common.symbols.categories.SymbolCategory; import net.minecraft.network.PacketBuffer; import net.minecraft.util.Direction; import net.minecraft.util.ResourceLocation; import net.minecraft.util.math.BlockPos; import net.minecraft.world.World; import net.minecraft.world.chunk.Chunk; import java.util.ArrayList; import java.util.List; import static com.latenighters.runicarcana.RunicArcana.MODID; package com.latenighters.runicarcana.common.symbols.backend; public abstract class Symbol extends net.minecraftforge.registries.ForgeRegistryEntry<Symbol> { protected String name; protected ResourceLocation texture; protected int id = -1; protected final SymbolCategory category; protected List<IFunctional> functions = new ArrayList<IFunctional>(); protected List<HashableTuple<String,DataType>> inputs = new ArrayList<HashableTuple<String,DataType>>(); protected List<IFunctional> outputs = new ArrayList<IFunctional>(); protected List<HashableTuple<HashableTuple<String, DataType>, IFunctional>> triggers = new ArrayList<HashableTuple<HashableTuple<String, DataType>, IFunctional>>(); public Symbol(String name, ResourceLocation texture, SymbolCategory category) { this.name = name; this.texture = texture; this.category = category;
this.setRegistryName(new ResourceLocation(MODID, this.name));
Drazuam/RunicArcana
src/main/java/com/latenighters/runicarcana/common/symbols/backend/Symbol.java
// Path: src/main/java/com/latenighters/runicarcana/common/symbols/SymbolTextures.java // @Mod.EventBusSubscriber(modid = MODID, value = Dist.CLIENT, bus = Mod.EventBusSubscriber.Bus.MOD) // public class SymbolTextures { // // public static final ResourceLocation DEBUG = new ResourceLocation(MODID , "symbols/symbol_x"); // public static final ResourceLocation EXPEL = new ResourceLocation(MODID , "symbols/symbol_expel"); // public static final ResourceLocation INSERT = new ResourceLocation(MODID , "symbols/symbol_insert"); // public static final ResourceLocation REDSTONE = new ResourceLocation(MODID , "symbols/symbol_redstone"); // public static final ResourceLocation BOOLEAN_LOGIC = new ResourceLocation(MODID , "symbols/symbol_boolean_logic"); // public static final ResourceLocation DETECT= new ResourceLocation(MODID , "symbols/symbol_detect"); // // // // @SubscribeEvent // public static void onStitchEvent(TextureStitchEvent.Pre event) // { // ResourceLocation stitching = event.getMap().getTextureLocation(); // if(!stitching.equals(AtlasTexture.LOCATION_BLOCKS_TEXTURE)) // { // return; // } // for (ResourceLocation tex:textureList) // { // event.addSprite(tex); // } // } // // public static void consolidateTextures(final RegistryEvent.Register<Symbol> evt) // { // // for(Symbol symbol : evt.getRegistry().getValues()) // { // if(!textureList.contains(symbol.getTexture())) // { // textureList.add(symbol.getTexture()); // } // } // } // // private static ArrayList<ResourceLocation> textureList = new ArrayList<ResourceLocation>(); // // } // // Path: src/main/java/com/latenighters/runicarcana/common/symbols/categories/SymbolCategory.java // public class SymbolCategory { // // public static SymbolCategory DEFAULT = new SymbolCategory(Symbols.DEBUG, MODID+".symbol.category.default"); // // private Symbol displaySymbol; // private final String unlocalizedName; // // public static void generateCategories() // { // //TODO figure out why static initialization isn't working // DEFAULT.setDisplaySymbol(Symbols.EXPULSION); // } // // public SymbolCategory(Symbol displaySymbol, String unlocalizedName) { // this.displaySymbol = displaySymbol; // this.unlocalizedName = unlocalizedName; // } // // public Symbol getDisplaySymbol() { // return displaySymbol; // } // // public void setDisplaySymbol(Symbol displaySymbol) { // this.displaySymbol = displaySymbol; // } // // public String getUnlocalizedName() { // return unlocalizedName; // } // } // // Path: src/main/java/com/latenighters/runicarcana/RunicArcana.java // public static final String MODID = "runicarcana";
import com.latenighters.runicarcana.common.symbols.SymbolTextures; import com.latenighters.runicarcana.common.symbols.categories.SymbolCategory; import net.minecraft.network.PacketBuffer; import net.minecraft.util.Direction; import net.minecraft.util.ResourceLocation; import net.minecraft.util.math.BlockPos; import net.minecraft.world.World; import net.minecraft.world.chunk.Chunk; import java.util.ArrayList; import java.util.List; import static com.latenighters.runicarcana.RunicArcana.MODID;
//repeat for outputs for (IFunctional function : outputs) { //synchronize the inputs from all the functions for(HashableTuple<String,DataType> input : inputs) { //check to see if inputs already has the same DataType and String registered if(function.getRequiredInputs()==null)return; function.getRequiredInputs().removeIf(finput -> { if (function.getRequiredInputs().contains(finput)) return false; if (input.getA().equals(finput.getA()) && input.getB().type.equals(finput.getB().type)) { //if we do, remove the input from the function and replace it with the already registered input function.getRequiredInputs().add(input); return true; } return false; }); } //add each input into the object inputs if(function.getRequiredInputs()!=null) function.getRequiredInputs().forEach(finput->{ if(!inputs.contains(finput)) inputs.add(finput); }); } } public Symbol(String name) {
// Path: src/main/java/com/latenighters/runicarcana/common/symbols/SymbolTextures.java // @Mod.EventBusSubscriber(modid = MODID, value = Dist.CLIENT, bus = Mod.EventBusSubscriber.Bus.MOD) // public class SymbolTextures { // // public static final ResourceLocation DEBUG = new ResourceLocation(MODID , "symbols/symbol_x"); // public static final ResourceLocation EXPEL = new ResourceLocation(MODID , "symbols/symbol_expel"); // public static final ResourceLocation INSERT = new ResourceLocation(MODID , "symbols/symbol_insert"); // public static final ResourceLocation REDSTONE = new ResourceLocation(MODID , "symbols/symbol_redstone"); // public static final ResourceLocation BOOLEAN_LOGIC = new ResourceLocation(MODID , "symbols/symbol_boolean_logic"); // public static final ResourceLocation DETECT= new ResourceLocation(MODID , "symbols/symbol_detect"); // // // // @SubscribeEvent // public static void onStitchEvent(TextureStitchEvent.Pre event) // { // ResourceLocation stitching = event.getMap().getTextureLocation(); // if(!stitching.equals(AtlasTexture.LOCATION_BLOCKS_TEXTURE)) // { // return; // } // for (ResourceLocation tex:textureList) // { // event.addSprite(tex); // } // } // // public static void consolidateTextures(final RegistryEvent.Register<Symbol> evt) // { // // for(Symbol symbol : evt.getRegistry().getValues()) // { // if(!textureList.contains(symbol.getTexture())) // { // textureList.add(symbol.getTexture()); // } // } // } // // private static ArrayList<ResourceLocation> textureList = new ArrayList<ResourceLocation>(); // // } // // Path: src/main/java/com/latenighters/runicarcana/common/symbols/categories/SymbolCategory.java // public class SymbolCategory { // // public static SymbolCategory DEFAULT = new SymbolCategory(Symbols.DEBUG, MODID+".symbol.category.default"); // // private Symbol displaySymbol; // private final String unlocalizedName; // // public static void generateCategories() // { // //TODO figure out why static initialization isn't working // DEFAULT.setDisplaySymbol(Symbols.EXPULSION); // } // // public SymbolCategory(Symbol displaySymbol, String unlocalizedName) { // this.displaySymbol = displaySymbol; // this.unlocalizedName = unlocalizedName; // } // // public Symbol getDisplaySymbol() { // return displaySymbol; // } // // public void setDisplaySymbol(Symbol displaySymbol) { // this.displaySymbol = displaySymbol; // } // // public String getUnlocalizedName() { // return unlocalizedName; // } // } // // Path: src/main/java/com/latenighters/runicarcana/RunicArcana.java // public static final String MODID = "runicarcana"; // Path: src/main/java/com/latenighters/runicarcana/common/symbols/backend/Symbol.java import com.latenighters.runicarcana.common.symbols.SymbolTextures; import com.latenighters.runicarcana.common.symbols.categories.SymbolCategory; import net.minecraft.network.PacketBuffer; import net.minecraft.util.Direction; import net.minecraft.util.ResourceLocation; import net.minecraft.util.math.BlockPos; import net.minecraft.world.World; import net.minecraft.world.chunk.Chunk; import java.util.ArrayList; import java.util.List; import static com.latenighters.runicarcana.RunicArcana.MODID; //repeat for outputs for (IFunctional function : outputs) { //synchronize the inputs from all the functions for(HashableTuple<String,DataType> input : inputs) { //check to see if inputs already has the same DataType and String registered if(function.getRequiredInputs()==null)return; function.getRequiredInputs().removeIf(finput -> { if (function.getRequiredInputs().contains(finput)) return false; if (input.getA().equals(finput.getA()) && input.getB().type.equals(finput.getB().type)) { //if we do, remove the input from the function and replace it with the already registered input function.getRequiredInputs().add(input); return true; } return false; }); } //add each input into the object inputs if(function.getRequiredInputs()!=null) function.getRequiredInputs().forEach(finput->{ if(!inputs.contains(finput)) inputs.add(finput); }); } } public Symbol(String name) {
this(name, SymbolTextures.DEBUG, SymbolCategory.DEFAULT);
Drazuam/RunicArcana
src/main/java/com/latenighters/runicarcana/common/items/armor/AbstractPrincipicArmor.java
// Path: src/main/java/com/latenighters/runicarcana/common/items/IClickable.java // public interface IClickable { // // //do the action - this is performed server side // //returns true when behavior is as expected // boolean onClick(PlayerEntity player, ItemStack itemStack, Container container, int slot); // // } // // Path: src/main/java/com/latenighters/runicarcana/common/setup/ModSetup.java // public class ModSetup { // // public static final ItemGroup ITEM_GROUP = new ItemGroup(RunicArcana.MODID) { // @Override // public ItemStack createIcon() { // return new ItemStack(Registration.CHALK.get()); // } // }; // }
import com.latenighters.runicarcana.common.items.IClickable; import com.latenighters.runicarcana.common.setup.ModSetup; import net.minecraft.block.DispenserBlock; import net.minecraft.client.util.ITooltipFlag; import net.minecraft.entity.player.PlayerEntity; import net.minecraft.inventory.EquipmentSlotType; import net.minecraft.inventory.container.Container; import net.minecraft.item.ArmorItem; import net.minecraft.item.IArmorMaterial; import net.minecraft.item.ItemStack; import net.minecraft.item.Rarity; import net.minecraft.item.crafting.Ingredient; import net.minecraft.nbt.CompoundNBT; import net.minecraft.util.*; import net.minecraft.util.text.ITextComponent; import net.minecraft.util.text.TextFormatting; import net.minecraft.util.text.TranslationTextComponent; import net.minecraft.world.World; import javax.annotation.Nonnull; import javax.annotation.Nullable; import java.util.List;
@Nonnull public SoundEvent getSoundEvent() { return SoundEvents.ITEM_ARMOR_EQUIP_GOLD; } @Override @Nonnull public Ingredient getRepairMaterial() { return Ingredient.EMPTY; } @Override public String getName() { return "runicarcana:principic"; } @Override public float getToughness() { return 1; } }; public AbstractPrincipicArmor(EquipmentSlotType slot) { super( principic, slot, new Properties() .maxDamage(-1) .maxStackSize(1) .rarity(Rarity.EPIC)
// Path: src/main/java/com/latenighters/runicarcana/common/items/IClickable.java // public interface IClickable { // // //do the action - this is performed server side // //returns true when behavior is as expected // boolean onClick(PlayerEntity player, ItemStack itemStack, Container container, int slot); // // } // // Path: src/main/java/com/latenighters/runicarcana/common/setup/ModSetup.java // public class ModSetup { // // public static final ItemGroup ITEM_GROUP = new ItemGroup(RunicArcana.MODID) { // @Override // public ItemStack createIcon() { // return new ItemStack(Registration.CHALK.get()); // } // }; // } // Path: src/main/java/com/latenighters/runicarcana/common/items/armor/AbstractPrincipicArmor.java import com.latenighters.runicarcana.common.items.IClickable; import com.latenighters.runicarcana.common.setup.ModSetup; import net.minecraft.block.DispenserBlock; import net.minecraft.client.util.ITooltipFlag; import net.minecraft.entity.player.PlayerEntity; import net.minecraft.inventory.EquipmentSlotType; import net.minecraft.inventory.container.Container; import net.minecraft.item.ArmorItem; import net.minecraft.item.IArmorMaterial; import net.minecraft.item.ItemStack; import net.minecraft.item.Rarity; import net.minecraft.item.crafting.Ingredient; import net.minecraft.nbt.CompoundNBT; import net.minecraft.util.*; import net.minecraft.util.text.ITextComponent; import net.minecraft.util.text.TextFormatting; import net.minecraft.util.text.TranslationTextComponent; import net.minecraft.world.World; import javax.annotation.Nonnull; import javax.annotation.Nullable; import java.util.List; @Nonnull public SoundEvent getSoundEvent() { return SoundEvents.ITEM_ARMOR_EQUIP_GOLD; } @Override @Nonnull public Ingredient getRepairMaterial() { return Ingredient.EMPTY; } @Override public String getName() { return "runicarcana:principic"; } @Override public float getToughness() { return 1; } }; public AbstractPrincipicArmor(EquipmentSlotType slot) { super( principic, slot, new Properties() .maxDamage(-1) .maxStackSize(1) .rarity(Rarity.EPIC)
.group(ModSetup.ITEM_GROUP)
Drazuam/RunicArcana
src/main/java/com/latenighters/runicarcana/common/blocks/ArcanaCollector.java
// Path: src/main/java/com/latenighters/runicarcana/common/blocks/tile/TileArcanaCollector.java // public class TileArcanaCollector extends ArcanaMachine { // // public TileArcanaCollector() { // super(Registration.ARCANA_COLLECTOR_TILE.get()); // this.getCapability(RunicArcana.ARCANA_CAP).ifPresent(cap->{ // cap.getChambers().add(new ArcanaChamber(10000, 1)); // }); // // } // // @Override // public void tick() { // super.tick(); // this.getCapability(RunicArcana.ARCANA_CAP).ifPresent(cap-> { // cap.getChambers().get(0).addArcana(ArcanaMix.COMMON.mult(0.02f)); // }); // } // // @Override // public int getChamberSlotFromHitVec(Vec3d hitVec) { // return 0; // } // // @Override // public ArcanaChamber getChamberFromSlot(int slot) { // // AtomicReference<ArcanaChamber> arcanaChamber = new AtomicReference<>(); // getCapability(RunicArcana.ARCANA_CAP).ifPresent(cap->{ // arcanaChamber.set(cap.getChambers().get(slot)); // }); // // return arcanaChamber.get(); // } // // @Override // public int getExportRate() { // return 10000; // } // // @Override // public boolean canExport() { // return true; // } // // @Override // public boolean canImport() { // return false; // } // }
import com.latenighters.runicarcana.common.blocks.tile.TileArcanaCollector; import net.minecraft.block.Block; import net.minecraft.block.BlockState; import net.minecraft.tileentity.TileEntity; import net.minecraft.world.IBlockReader; import javax.annotation.Nullable;
package com.latenighters.runicarcana.common.blocks; public class ArcanaCollector extends Block { public ArcanaCollector(Properties properties) { super(properties); } @Override public boolean hasTileEntity(BlockState state) { return true; } @Nullable @Override public TileEntity createTileEntity(BlockState state, IBlockReader world) {
// Path: src/main/java/com/latenighters/runicarcana/common/blocks/tile/TileArcanaCollector.java // public class TileArcanaCollector extends ArcanaMachine { // // public TileArcanaCollector() { // super(Registration.ARCANA_COLLECTOR_TILE.get()); // this.getCapability(RunicArcana.ARCANA_CAP).ifPresent(cap->{ // cap.getChambers().add(new ArcanaChamber(10000, 1)); // }); // // } // // @Override // public void tick() { // super.tick(); // this.getCapability(RunicArcana.ARCANA_CAP).ifPresent(cap-> { // cap.getChambers().get(0).addArcana(ArcanaMix.COMMON.mult(0.02f)); // }); // } // // @Override // public int getChamberSlotFromHitVec(Vec3d hitVec) { // return 0; // } // // @Override // public ArcanaChamber getChamberFromSlot(int slot) { // // AtomicReference<ArcanaChamber> arcanaChamber = new AtomicReference<>(); // getCapability(RunicArcana.ARCANA_CAP).ifPresent(cap->{ // arcanaChamber.set(cap.getChambers().get(slot)); // }); // // return arcanaChamber.get(); // } // // @Override // public int getExportRate() { // return 10000; // } // // @Override // public boolean canExport() { // return true; // } // // @Override // public boolean canImport() { // return false; // } // } // Path: src/main/java/com/latenighters/runicarcana/common/blocks/ArcanaCollector.java import com.latenighters.runicarcana.common.blocks.tile.TileArcanaCollector; import net.minecraft.block.Block; import net.minecraft.block.BlockState; import net.minecraft.tileentity.TileEntity; import net.minecraft.world.IBlockReader; import javax.annotation.Nullable; package com.latenighters.runicarcana.common.blocks; public class ArcanaCollector extends Block { public ArcanaCollector(Properties properties) { super(properties); } @Override public boolean hasTileEntity(BlockState state) { return true; } @Nullable @Override public TileEntity createTileEntity(BlockState state, IBlockReader world) {
return new TileArcanaCollector();
Drazuam/RunicArcana
src/main/java/com/latenighters/runicarcana/common/symbols/backend/SymbolRegistration.java
// Path: src/main/java/com/latenighters/runicarcana/common/arcana/ArcanaType.java // public class ArcanaType { // // public static ArcanaType AIR = new ArcanaType("air"); // public static ArcanaType EARTH = new ArcanaType("earth"); // public static ArcanaType WATER = new ArcanaType("water"); // public static ArcanaType FIRE = new ArcanaType("fire"); // // private static HashMap<String, ArcanaType> arcanaTypes = new HashMap<>(); // // public final String name; // // public ArcanaType(String name) { // this.name = name; // } // // public static void registerType(ArcanaType arcanaType) // { // arcanaTypes.put(arcanaType.name, arcanaType); // } // // public static void registerArcanaTypes() // { // registerType(AIR); // registerType(EARTH); // registerType(WATER); // registerType(FIRE); // } // // public static ArcanaType getArcanaType(String name) // { // AtomicReference<ArcanaType> retval = new AtomicReference<>(); // retval.set(AIR); // arcanaTypes.forEach((tname,type)->{ // if(tname.equals(name)) // retval.set(arcanaTypes.get(tname)); // }); // // return retval.get(); // } // } // // Path: src/main/java/com/latenighters/runicarcana/common/symbols/backend/DataType.java // public static void registerDataTypes() // { // registerDataType(ENTITY); // registerDataType(BOOLEAN); // registerDataType(BLOCK_FACE); // } // // Path: src/main/java/com/latenighters/runicarcana/common/symbols/backend/FunctionalTypeRegister.java // public static void registerBaseProviders() // { // registerFunctionalObjectProvider("DrawnSymbol",DrawnSymbol::new); // }
import com.latenighters.runicarcana.common.arcana.ArcanaType; import com.latenighters.runicarcana.common.symbols.*; import net.minecraftforge.event.RegistryEvent; import static com.latenighters.runicarcana.common.symbols.backend.DataType.registerDataTypes; import static com.latenighters.runicarcana.common.symbols.backend.FunctionalTypeRegister.registerBaseProviders;
package com.latenighters.runicarcana.common.symbols.backend; public class SymbolRegistration { // private static final DeferredRegister<Symbol> SYMBOLS = new DeferredRegister<>(SymbolRegistryHandler.SYMBOLS, MODID); public static void registerSymbols(final RegistryEvent.Register<Symbol> evt) { if(!evt.getRegistry().getRegistrySuperType().equals(Symbol.class)) return; evt.getRegistry().register(new DebugSymbol()); evt.getRegistry().register(new ExpulsionSymbol()); evt.getRegistry().register(new InsertionSymbol()); evt.getRegistry().register(new RedstoneSymbol()); evt.getRegistry().register(new BooleanLogicSymbol()); evt.getRegistry().register(new DetectSymbol()); //TODO move this out of here... FunctionalObjects.putObject("DrawnSymbol",DrawnSymbol.class);
// Path: src/main/java/com/latenighters/runicarcana/common/arcana/ArcanaType.java // public class ArcanaType { // // public static ArcanaType AIR = new ArcanaType("air"); // public static ArcanaType EARTH = new ArcanaType("earth"); // public static ArcanaType WATER = new ArcanaType("water"); // public static ArcanaType FIRE = new ArcanaType("fire"); // // private static HashMap<String, ArcanaType> arcanaTypes = new HashMap<>(); // // public final String name; // // public ArcanaType(String name) { // this.name = name; // } // // public static void registerType(ArcanaType arcanaType) // { // arcanaTypes.put(arcanaType.name, arcanaType); // } // // public static void registerArcanaTypes() // { // registerType(AIR); // registerType(EARTH); // registerType(WATER); // registerType(FIRE); // } // // public static ArcanaType getArcanaType(String name) // { // AtomicReference<ArcanaType> retval = new AtomicReference<>(); // retval.set(AIR); // arcanaTypes.forEach((tname,type)->{ // if(tname.equals(name)) // retval.set(arcanaTypes.get(tname)); // }); // // return retval.get(); // } // } // // Path: src/main/java/com/latenighters/runicarcana/common/symbols/backend/DataType.java // public static void registerDataTypes() // { // registerDataType(ENTITY); // registerDataType(BOOLEAN); // registerDataType(BLOCK_FACE); // } // // Path: src/main/java/com/latenighters/runicarcana/common/symbols/backend/FunctionalTypeRegister.java // public static void registerBaseProviders() // { // registerFunctionalObjectProvider("DrawnSymbol",DrawnSymbol::new); // } // Path: src/main/java/com/latenighters/runicarcana/common/symbols/backend/SymbolRegistration.java import com.latenighters.runicarcana.common.arcana.ArcanaType; import com.latenighters.runicarcana.common.symbols.*; import net.minecraftforge.event.RegistryEvent; import static com.latenighters.runicarcana.common.symbols.backend.DataType.registerDataTypes; import static com.latenighters.runicarcana.common.symbols.backend.FunctionalTypeRegister.registerBaseProviders; package com.latenighters.runicarcana.common.symbols.backend; public class SymbolRegistration { // private static final DeferredRegister<Symbol> SYMBOLS = new DeferredRegister<>(SymbolRegistryHandler.SYMBOLS, MODID); public static void registerSymbols(final RegistryEvent.Register<Symbol> evt) { if(!evt.getRegistry().getRegistrySuperType().equals(Symbol.class)) return; evt.getRegistry().register(new DebugSymbol()); evt.getRegistry().register(new ExpulsionSymbol()); evt.getRegistry().register(new InsertionSymbol()); evt.getRegistry().register(new RedstoneSymbol()); evt.getRegistry().register(new BooleanLogicSymbol()); evt.getRegistry().register(new DetectSymbol()); //TODO move this out of here... FunctionalObjects.putObject("DrawnSymbol",DrawnSymbol.class);
registerDataTypes();
Drazuam/RunicArcana
src/main/java/com/latenighters/runicarcana/common/symbols/backend/SymbolRegistration.java
// Path: src/main/java/com/latenighters/runicarcana/common/arcana/ArcanaType.java // public class ArcanaType { // // public static ArcanaType AIR = new ArcanaType("air"); // public static ArcanaType EARTH = new ArcanaType("earth"); // public static ArcanaType WATER = new ArcanaType("water"); // public static ArcanaType FIRE = new ArcanaType("fire"); // // private static HashMap<String, ArcanaType> arcanaTypes = new HashMap<>(); // // public final String name; // // public ArcanaType(String name) { // this.name = name; // } // // public static void registerType(ArcanaType arcanaType) // { // arcanaTypes.put(arcanaType.name, arcanaType); // } // // public static void registerArcanaTypes() // { // registerType(AIR); // registerType(EARTH); // registerType(WATER); // registerType(FIRE); // } // // public static ArcanaType getArcanaType(String name) // { // AtomicReference<ArcanaType> retval = new AtomicReference<>(); // retval.set(AIR); // arcanaTypes.forEach((tname,type)->{ // if(tname.equals(name)) // retval.set(arcanaTypes.get(tname)); // }); // // return retval.get(); // } // } // // Path: src/main/java/com/latenighters/runicarcana/common/symbols/backend/DataType.java // public static void registerDataTypes() // { // registerDataType(ENTITY); // registerDataType(BOOLEAN); // registerDataType(BLOCK_FACE); // } // // Path: src/main/java/com/latenighters/runicarcana/common/symbols/backend/FunctionalTypeRegister.java // public static void registerBaseProviders() // { // registerFunctionalObjectProvider("DrawnSymbol",DrawnSymbol::new); // }
import com.latenighters.runicarcana.common.arcana.ArcanaType; import com.latenighters.runicarcana.common.symbols.*; import net.minecraftforge.event.RegistryEvent; import static com.latenighters.runicarcana.common.symbols.backend.DataType.registerDataTypes; import static com.latenighters.runicarcana.common.symbols.backend.FunctionalTypeRegister.registerBaseProviders;
package com.latenighters.runicarcana.common.symbols.backend; public class SymbolRegistration { // private static final DeferredRegister<Symbol> SYMBOLS = new DeferredRegister<>(SymbolRegistryHandler.SYMBOLS, MODID); public static void registerSymbols(final RegistryEvent.Register<Symbol> evt) { if(!evt.getRegistry().getRegistrySuperType().equals(Symbol.class)) return; evt.getRegistry().register(new DebugSymbol()); evt.getRegistry().register(new ExpulsionSymbol()); evt.getRegistry().register(new InsertionSymbol()); evt.getRegistry().register(new RedstoneSymbol()); evt.getRegistry().register(new BooleanLogicSymbol()); evt.getRegistry().register(new DetectSymbol()); //TODO move this out of here... FunctionalObjects.putObject("DrawnSymbol",DrawnSymbol.class); registerDataTypes();
// Path: src/main/java/com/latenighters/runicarcana/common/arcana/ArcanaType.java // public class ArcanaType { // // public static ArcanaType AIR = new ArcanaType("air"); // public static ArcanaType EARTH = new ArcanaType("earth"); // public static ArcanaType WATER = new ArcanaType("water"); // public static ArcanaType FIRE = new ArcanaType("fire"); // // private static HashMap<String, ArcanaType> arcanaTypes = new HashMap<>(); // // public final String name; // // public ArcanaType(String name) { // this.name = name; // } // // public static void registerType(ArcanaType arcanaType) // { // arcanaTypes.put(arcanaType.name, arcanaType); // } // // public static void registerArcanaTypes() // { // registerType(AIR); // registerType(EARTH); // registerType(WATER); // registerType(FIRE); // } // // public static ArcanaType getArcanaType(String name) // { // AtomicReference<ArcanaType> retval = new AtomicReference<>(); // retval.set(AIR); // arcanaTypes.forEach((tname,type)->{ // if(tname.equals(name)) // retval.set(arcanaTypes.get(tname)); // }); // // return retval.get(); // } // } // // Path: src/main/java/com/latenighters/runicarcana/common/symbols/backend/DataType.java // public static void registerDataTypes() // { // registerDataType(ENTITY); // registerDataType(BOOLEAN); // registerDataType(BLOCK_FACE); // } // // Path: src/main/java/com/latenighters/runicarcana/common/symbols/backend/FunctionalTypeRegister.java // public static void registerBaseProviders() // { // registerFunctionalObjectProvider("DrawnSymbol",DrawnSymbol::new); // } // Path: src/main/java/com/latenighters/runicarcana/common/symbols/backend/SymbolRegistration.java import com.latenighters.runicarcana.common.arcana.ArcanaType; import com.latenighters.runicarcana.common.symbols.*; import net.minecraftforge.event.RegistryEvent; import static com.latenighters.runicarcana.common.symbols.backend.DataType.registerDataTypes; import static com.latenighters.runicarcana.common.symbols.backend.FunctionalTypeRegister.registerBaseProviders; package com.latenighters.runicarcana.common.symbols.backend; public class SymbolRegistration { // private static final DeferredRegister<Symbol> SYMBOLS = new DeferredRegister<>(SymbolRegistryHandler.SYMBOLS, MODID); public static void registerSymbols(final RegistryEvent.Register<Symbol> evt) { if(!evt.getRegistry().getRegistrySuperType().equals(Symbol.class)) return; evt.getRegistry().register(new DebugSymbol()); evt.getRegistry().register(new ExpulsionSymbol()); evt.getRegistry().register(new InsertionSymbol()); evt.getRegistry().register(new RedstoneSymbol()); evt.getRegistry().register(new BooleanLogicSymbol()); evt.getRegistry().register(new DetectSymbol()); //TODO move this out of here... FunctionalObjects.putObject("DrawnSymbol",DrawnSymbol.class); registerDataTypes();
registerBaseProviders();
Drazuam/RunicArcana
src/main/java/com/latenighters/runicarcana/common/symbols/backend/SymbolRegistration.java
// Path: src/main/java/com/latenighters/runicarcana/common/arcana/ArcanaType.java // public class ArcanaType { // // public static ArcanaType AIR = new ArcanaType("air"); // public static ArcanaType EARTH = new ArcanaType("earth"); // public static ArcanaType WATER = new ArcanaType("water"); // public static ArcanaType FIRE = new ArcanaType("fire"); // // private static HashMap<String, ArcanaType> arcanaTypes = new HashMap<>(); // // public final String name; // // public ArcanaType(String name) { // this.name = name; // } // // public static void registerType(ArcanaType arcanaType) // { // arcanaTypes.put(arcanaType.name, arcanaType); // } // // public static void registerArcanaTypes() // { // registerType(AIR); // registerType(EARTH); // registerType(WATER); // registerType(FIRE); // } // // public static ArcanaType getArcanaType(String name) // { // AtomicReference<ArcanaType> retval = new AtomicReference<>(); // retval.set(AIR); // arcanaTypes.forEach((tname,type)->{ // if(tname.equals(name)) // retval.set(arcanaTypes.get(tname)); // }); // // return retval.get(); // } // } // // Path: src/main/java/com/latenighters/runicarcana/common/symbols/backend/DataType.java // public static void registerDataTypes() // { // registerDataType(ENTITY); // registerDataType(BOOLEAN); // registerDataType(BLOCK_FACE); // } // // Path: src/main/java/com/latenighters/runicarcana/common/symbols/backend/FunctionalTypeRegister.java // public static void registerBaseProviders() // { // registerFunctionalObjectProvider("DrawnSymbol",DrawnSymbol::new); // }
import com.latenighters.runicarcana.common.arcana.ArcanaType; import com.latenighters.runicarcana.common.symbols.*; import net.minecraftforge.event.RegistryEvent; import static com.latenighters.runicarcana.common.symbols.backend.DataType.registerDataTypes; import static com.latenighters.runicarcana.common.symbols.backend.FunctionalTypeRegister.registerBaseProviders;
package com.latenighters.runicarcana.common.symbols.backend; public class SymbolRegistration { // private static final DeferredRegister<Symbol> SYMBOLS = new DeferredRegister<>(SymbolRegistryHandler.SYMBOLS, MODID); public static void registerSymbols(final RegistryEvent.Register<Symbol> evt) { if(!evt.getRegistry().getRegistrySuperType().equals(Symbol.class)) return; evt.getRegistry().register(new DebugSymbol()); evt.getRegistry().register(new ExpulsionSymbol()); evt.getRegistry().register(new InsertionSymbol()); evt.getRegistry().register(new RedstoneSymbol()); evt.getRegistry().register(new BooleanLogicSymbol()); evt.getRegistry().register(new DetectSymbol()); //TODO move this out of here... FunctionalObjects.putObject("DrawnSymbol",DrawnSymbol.class); registerDataTypes(); registerBaseProviders();
// Path: src/main/java/com/latenighters/runicarcana/common/arcana/ArcanaType.java // public class ArcanaType { // // public static ArcanaType AIR = new ArcanaType("air"); // public static ArcanaType EARTH = new ArcanaType("earth"); // public static ArcanaType WATER = new ArcanaType("water"); // public static ArcanaType FIRE = new ArcanaType("fire"); // // private static HashMap<String, ArcanaType> arcanaTypes = new HashMap<>(); // // public final String name; // // public ArcanaType(String name) { // this.name = name; // } // // public static void registerType(ArcanaType arcanaType) // { // arcanaTypes.put(arcanaType.name, arcanaType); // } // // public static void registerArcanaTypes() // { // registerType(AIR); // registerType(EARTH); // registerType(WATER); // registerType(FIRE); // } // // public static ArcanaType getArcanaType(String name) // { // AtomicReference<ArcanaType> retval = new AtomicReference<>(); // retval.set(AIR); // arcanaTypes.forEach((tname,type)->{ // if(tname.equals(name)) // retval.set(arcanaTypes.get(tname)); // }); // // return retval.get(); // } // } // // Path: src/main/java/com/latenighters/runicarcana/common/symbols/backend/DataType.java // public static void registerDataTypes() // { // registerDataType(ENTITY); // registerDataType(BOOLEAN); // registerDataType(BLOCK_FACE); // } // // Path: src/main/java/com/latenighters/runicarcana/common/symbols/backend/FunctionalTypeRegister.java // public static void registerBaseProviders() // { // registerFunctionalObjectProvider("DrawnSymbol",DrawnSymbol::new); // } // Path: src/main/java/com/latenighters/runicarcana/common/symbols/backend/SymbolRegistration.java import com.latenighters.runicarcana.common.arcana.ArcanaType; import com.latenighters.runicarcana.common.symbols.*; import net.minecraftforge.event.RegistryEvent; import static com.latenighters.runicarcana.common.symbols.backend.DataType.registerDataTypes; import static com.latenighters.runicarcana.common.symbols.backend.FunctionalTypeRegister.registerBaseProviders; package com.latenighters.runicarcana.common.symbols.backend; public class SymbolRegistration { // private static final DeferredRegister<Symbol> SYMBOLS = new DeferredRegister<>(SymbolRegistryHandler.SYMBOLS, MODID); public static void registerSymbols(final RegistryEvent.Register<Symbol> evt) { if(!evt.getRegistry().getRegistrySuperType().equals(Symbol.class)) return; evt.getRegistry().register(new DebugSymbol()); evt.getRegistry().register(new ExpulsionSymbol()); evt.getRegistry().register(new InsertionSymbol()); evt.getRegistry().register(new RedstoneSymbol()); evt.getRegistry().register(new BooleanLogicSymbol()); evt.getRegistry().register(new DetectSymbol()); //TODO move this out of here... FunctionalObjects.putObject("DrawnSymbol",DrawnSymbol.class); registerDataTypes(); registerBaseProviders();
ArcanaType.registerArcanaTypes();
Drazuam/RunicArcana
src/main/java/com/latenighters/runicarcana/common/arcana/ArcanaMachine.java
// Path: src/main/java/com/latenighters/runicarcana/RunicArcana.java // @Mod("runicarcana") // public class RunicArcana // { // // Directly reference a log4j logger. // private static final Logger LOGGER = LogManager.getLogger(); // public static final String MODID = "runicarcana"; // // //Capability Registration // @CapabilityInject(ISymbolHandler.class) // public static Capability<ISymbolHandler> SYMBOL_CAP = null; // // @CapabilityInject(IArcanaHandler.class) // public static Capability<IArcanaHandler> ARCANA_CAP = null; // // public static IProxy proxy; // // public RunicArcana() { // // Register the setup method for modloading // FMLJavaModLoadingContext.get().getModEventBus().addListener(this::setup); // FMLJavaModLoadingContext.get().getModEventBus().addListener(this::onSetupComplete); // // Register the enqueueIMC method for modloading // FMLJavaModLoadingContext.get().getModEventBus().addListener(this::enqueueIMC); // // Register the processIMC method for modloading // FMLJavaModLoadingContext.get().getModEventBus().addListener(this::processIMC); // // Register the doClientStuff method for modloading // FMLJavaModLoadingContext.get().getModEventBus().addListener(this::doClientStuff); // FMLJavaModLoadingContext.get().getModEventBus().addListener(this::doServerStuff); // FMLJavaModLoadingContext.get().getModEventBus().addListener(SymbolRegistryHandler::onCreateRegistryEvent); // FMLJavaModLoadingContext.get().getModEventBus().addListener(SymbolRegistration::registerSymbols); // // // Register ourselves for server and other game events we are interested in // MinecraftForge.EVENT_BUS.register(this); // MinecraftForge.EVENT_BUS.register(new CommonEventHandler()); // MinecraftForge.EVENT_BUS.register(new SymbolSyncer()); // NetworkSync.registerPackets(); // ClickableHandler.registerPackets(); // Registration.init(); // //SymbolRegistration.init(); // // } // // private void setup(final FMLCommonSetupEvent event) // { // SymbolHandlerStorage storage = new SymbolHandlerStorage(); // SymbolHandler.SymbolHandlerFactory factory = new SymbolHandler.SymbolHandlerFactory(); // CapabilityManager.INSTANCE.register(ISymbolHandler.class, storage, factory); // // ArcanaHandlerStorage storage2 = new ArcanaHandlerStorage(); // ArcanaHandler.ArcanaHandlerFactory factory2 = new ArcanaHandler.ArcanaHandlerFactory(); // CapabilityManager.INSTANCE.register(IArcanaHandler.class, storage2, factory2); // // //TODO: register packets somewhere reasonable // registerPackets(); // } // // private void doClientStuff(final FMLClientSetupEvent event) { // proxy = new ClientProxy(); // KeyEventHandler.registerKeyBindings(); // } // // private void doServerStuff(final FMLDedicatedServerSetupEvent event) { // proxy = new ServerProxy(); // } // // private void enqueueIMC(final InterModEnqueueEvent event) // { // // some example code to dispatch IMC to another mod // // InterModComms.sendTo("examplemod", "helloworld", () -> { LOGGER.info("Hello world from the MDK"); return "Hello world";}); // InterModComms.sendTo("curios", CuriosAPI.IMC.REGISTER_TYPE, () -> new CurioIMCMessage("ring").setSize(2)); // InterModComms.sendTo("curios", CuriosAPI.IMC.REGISTER_TYPE, () -> new CurioIMCMessage("trinket").setSize(2)); // // } // // private void processIMC(final InterModProcessEvent event) // { // // some example code to receive and process InterModComms from other mods // // LOGGER.info("Got IMC {}", event.getIMCStream(). // // map(m->m.getMessageSupplier().get()). // // collect(Collectors.toList())); // } // // private void onSetupComplete(final FMLLoadCompleteEvent event) // { // PrincipicArmorEventHandler.onSetup(event); // SymbolCategory.generateCategories(); //TODO remove this when static initialization is working // } // // // You can use SubscribeEvent and let the Event Bus discover methods to call // @SubscribeEvent // public void onServerStarting(FMLServerStartingEvent event) { // // do something when the server starts // // LOGGER.info("HELLO from server starting"); // } // // // You can use EventBusSubscriber to automatically subscribe events on the contained class (this is subscribing to the MOD // // Event bus for receiving Registry Events) // @Mod.EventBusSubscriber(bus=Mod.EventBusSubscriber.Bus.MOD) // public static class RegistryEvents { // @SubscribeEvent // public static void onBlocksRegistry(final RegistryEvent.Register<Block> blockRegistryEvent) { // // register a new block here // // LOGGER.info("HELLO from Register Block"); // } // } // }
import com.latenighters.runicarcana.RunicArcana; import net.minecraft.nbt.CompoundNBT; import net.minecraft.tileentity.ITickableTileEntity; import net.minecraft.tileentity.TileEntity; import net.minecraft.tileentity.TileEntityType; import net.minecraft.util.Tuple; import net.minecraft.util.math.BlockPos; import net.minecraft.util.math.Vec3d; import net.minecraftforge.common.capabilities.Capability; import net.minecraftforge.common.util.LazyOptional; import javax.annotation.Nonnull; import java.util.HashSet; import java.util.Set;
public void tick() { if (this.canExport() && this.getExportRate() > 0) { upstreamLinks.forEach(link -> { TileEntity tileTo = this.world.getTileEntity(link.getB().getB()); if(tileTo instanceof ArcanaMachine) this.getChamberFromSlot(link.getA()).transferToArcanaChamber(((ArcanaMachine) tileTo) .getChamberFromSlot(link.getB().getA()),this.getExportRate()); else upstreamLinks.remove(link); }); } } public void clearLinks() { this.upstreamLinks.clear(); this.downstreamLinks.clear(); } public void addExportLink(int localSlot, BlockPos blockPos, int machineSlot){ this.upstreamLinks.add(new Tuple<>(localSlot, new Tuple<>(machineSlot, blockPos))); } public abstract int getChamberSlotFromHitVec(Vec3d hitVec); public abstract ArcanaChamber getChamberFromSlot(int slot); public ArcanaMix addMix(ArcanaChamber chamber, ArcanaMix mix) {
// Path: src/main/java/com/latenighters/runicarcana/RunicArcana.java // @Mod("runicarcana") // public class RunicArcana // { // // Directly reference a log4j logger. // private static final Logger LOGGER = LogManager.getLogger(); // public static final String MODID = "runicarcana"; // // //Capability Registration // @CapabilityInject(ISymbolHandler.class) // public static Capability<ISymbolHandler> SYMBOL_CAP = null; // // @CapabilityInject(IArcanaHandler.class) // public static Capability<IArcanaHandler> ARCANA_CAP = null; // // public static IProxy proxy; // // public RunicArcana() { // // Register the setup method for modloading // FMLJavaModLoadingContext.get().getModEventBus().addListener(this::setup); // FMLJavaModLoadingContext.get().getModEventBus().addListener(this::onSetupComplete); // // Register the enqueueIMC method for modloading // FMLJavaModLoadingContext.get().getModEventBus().addListener(this::enqueueIMC); // // Register the processIMC method for modloading // FMLJavaModLoadingContext.get().getModEventBus().addListener(this::processIMC); // // Register the doClientStuff method for modloading // FMLJavaModLoadingContext.get().getModEventBus().addListener(this::doClientStuff); // FMLJavaModLoadingContext.get().getModEventBus().addListener(this::doServerStuff); // FMLJavaModLoadingContext.get().getModEventBus().addListener(SymbolRegistryHandler::onCreateRegistryEvent); // FMLJavaModLoadingContext.get().getModEventBus().addListener(SymbolRegistration::registerSymbols); // // // Register ourselves for server and other game events we are interested in // MinecraftForge.EVENT_BUS.register(this); // MinecraftForge.EVENT_BUS.register(new CommonEventHandler()); // MinecraftForge.EVENT_BUS.register(new SymbolSyncer()); // NetworkSync.registerPackets(); // ClickableHandler.registerPackets(); // Registration.init(); // //SymbolRegistration.init(); // // } // // private void setup(final FMLCommonSetupEvent event) // { // SymbolHandlerStorage storage = new SymbolHandlerStorage(); // SymbolHandler.SymbolHandlerFactory factory = new SymbolHandler.SymbolHandlerFactory(); // CapabilityManager.INSTANCE.register(ISymbolHandler.class, storage, factory); // // ArcanaHandlerStorage storage2 = new ArcanaHandlerStorage(); // ArcanaHandler.ArcanaHandlerFactory factory2 = new ArcanaHandler.ArcanaHandlerFactory(); // CapabilityManager.INSTANCE.register(IArcanaHandler.class, storage2, factory2); // // //TODO: register packets somewhere reasonable // registerPackets(); // } // // private void doClientStuff(final FMLClientSetupEvent event) { // proxy = new ClientProxy(); // KeyEventHandler.registerKeyBindings(); // } // // private void doServerStuff(final FMLDedicatedServerSetupEvent event) { // proxy = new ServerProxy(); // } // // private void enqueueIMC(final InterModEnqueueEvent event) // { // // some example code to dispatch IMC to another mod // // InterModComms.sendTo("examplemod", "helloworld", () -> { LOGGER.info("Hello world from the MDK"); return "Hello world";}); // InterModComms.sendTo("curios", CuriosAPI.IMC.REGISTER_TYPE, () -> new CurioIMCMessage("ring").setSize(2)); // InterModComms.sendTo("curios", CuriosAPI.IMC.REGISTER_TYPE, () -> new CurioIMCMessage("trinket").setSize(2)); // // } // // private void processIMC(final InterModProcessEvent event) // { // // some example code to receive and process InterModComms from other mods // // LOGGER.info("Got IMC {}", event.getIMCStream(). // // map(m->m.getMessageSupplier().get()). // // collect(Collectors.toList())); // } // // private void onSetupComplete(final FMLLoadCompleteEvent event) // { // PrincipicArmorEventHandler.onSetup(event); // SymbolCategory.generateCategories(); //TODO remove this when static initialization is working // } // // // You can use SubscribeEvent and let the Event Bus discover methods to call // @SubscribeEvent // public void onServerStarting(FMLServerStartingEvent event) { // // do something when the server starts // // LOGGER.info("HELLO from server starting"); // } // // // You can use EventBusSubscriber to automatically subscribe events on the contained class (this is subscribing to the MOD // // Event bus for receiving Registry Events) // @Mod.EventBusSubscriber(bus=Mod.EventBusSubscriber.Bus.MOD) // public static class RegistryEvents { // @SubscribeEvent // public static void onBlocksRegistry(final RegistryEvent.Register<Block> blockRegistryEvent) { // // register a new block here // // LOGGER.info("HELLO from Register Block"); // } // } // } // Path: src/main/java/com/latenighters/runicarcana/common/arcana/ArcanaMachine.java import com.latenighters.runicarcana.RunicArcana; import net.minecraft.nbt.CompoundNBT; import net.minecraft.tileentity.ITickableTileEntity; import net.minecraft.tileentity.TileEntity; import net.minecraft.tileentity.TileEntityType; import net.minecraft.util.Tuple; import net.minecraft.util.math.BlockPos; import net.minecraft.util.math.Vec3d; import net.minecraftforge.common.capabilities.Capability; import net.minecraftforge.common.util.LazyOptional; import javax.annotation.Nonnull; import java.util.HashSet; import java.util.Set; public void tick() { if (this.canExport() && this.getExportRate() > 0) { upstreamLinks.forEach(link -> { TileEntity tileTo = this.world.getTileEntity(link.getB().getB()); if(tileTo instanceof ArcanaMachine) this.getChamberFromSlot(link.getA()).transferToArcanaChamber(((ArcanaMachine) tileTo) .getChamberFromSlot(link.getB().getA()),this.getExportRate()); else upstreamLinks.remove(link); }); } } public void clearLinks() { this.upstreamLinks.clear(); this.downstreamLinks.clear(); } public void addExportLink(int localSlot, BlockPos blockPos, int machineSlot){ this.upstreamLinks.add(new Tuple<>(localSlot, new Tuple<>(machineSlot, blockPos))); } public abstract int getChamberSlotFromHitVec(Vec3d hitVec); public abstract ArcanaChamber getChamberFromSlot(int slot); public ArcanaMix addMix(ArcanaChamber chamber, ArcanaMix mix) {
this.getCapability(RunicArcana.ARCANA_CAP).ifPresent(cap->{