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
XiaoMi/misound
src/com/xiaomi/mitv/soundbarapp/fragment/BaseFragment.java
// Path: src/com/xiaomi/mitv/soundbarapp/TypefaceManager.java // public class TypefaceManager { // private static Typeface mType; // // public static void updateTextFace(Context context, ViewGroup root){ // if(mType==null) init(context); // setFontStyle(root, mType); // } // // private static void init(Context context){ // // mType = Typeface.createFromAsset(context.getAssets(),"fonts/lanting.TTF"); // } // // private static void setFontStyle(ViewGroup root, Typeface type){ // // if(root == null) return; // // for(int i=0; i<root.getChildCount(); i++){ // // View v = root.getChildAt(i); // // if(v instanceof TextView){ // // ((TextView)v).setTypeface(type); // // }else if(v instanceof ViewGroup){ // // setFontStyle((ViewGroup)v, type); // // } // // } // } // }
import android.app.Activity; import android.graphics.Typeface; import android.os.Bundle; import android.support.v4.app.Fragment; import android.text.TextUtils; import android.view.View; import android.view.ViewGroup; import android.widget.TextView; import com.umeng.analytics.MobclickAgent; import com.xiaomi.mitv.soundbarapp.TypefaceManager; import com.xiaomi.mitv.utils.AsyncTaskRunner; import org.w3c.dom.Text;
package com.xiaomi.mitv.soundbarapp.fragment; /** * Created by chenxuetong on 8/26/14. */ public abstract class BaseFragment extends Fragment { protected View mRootView; protected boolean mIsDestroyed = false; @Override public void onViewCreated(View view, Bundle savedInstanceState) { super.onViewCreated(view, savedInstanceState); mRootView = view; } @Override public void onActivityCreated(Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); View root = getView(); if( root instanceof ViewGroup){
// Path: src/com/xiaomi/mitv/soundbarapp/TypefaceManager.java // public class TypefaceManager { // private static Typeface mType; // // public static void updateTextFace(Context context, ViewGroup root){ // if(mType==null) init(context); // setFontStyle(root, mType); // } // // private static void init(Context context){ // // mType = Typeface.createFromAsset(context.getAssets(),"fonts/lanting.TTF"); // } // // private static void setFontStyle(ViewGroup root, Typeface type){ // // if(root == null) return; // // for(int i=0; i<root.getChildCount(); i++){ // // View v = root.getChildAt(i); // // if(v instanceof TextView){ // // ((TextView)v).setTypeface(type); // // }else if(v instanceof ViewGroup){ // // setFontStyle((ViewGroup)v, type); // // } // // } // } // } // Path: src/com/xiaomi/mitv/soundbarapp/fragment/BaseFragment.java import android.app.Activity; import android.graphics.Typeface; import android.os.Bundle; import android.support.v4.app.Fragment; import android.text.TextUtils; import android.view.View; import android.view.ViewGroup; import android.widget.TextView; import com.umeng.analytics.MobclickAgent; import com.xiaomi.mitv.soundbarapp.TypefaceManager; import com.xiaomi.mitv.utils.AsyncTaskRunner; import org.w3c.dom.Text; package com.xiaomi.mitv.soundbarapp.fragment; /** * Created by chenxuetong on 8/26/14. */ public abstract class BaseFragment extends Fragment { protected View mRootView; protected boolean mIsDestroyed = false; @Override public void onViewCreated(View view, Bundle savedInstanceState) { super.onViewCreated(view, savedInstanceState); mRootView = view; } @Override public void onActivityCreated(Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); View root = getView(); if( root instanceof ViewGroup){
TypefaceManager.updateTextFace(getActivity(), (ViewGroup) root);
XiaoMi/misound
src/com/xiaomi/mitv/soundbarapp/diagnosis/Engine.java
// Path: src/com/xiaomi/mitv/soundbarapp/diagnosis/data/Entry.java // public class Entry implements Comparable<Entry>{ // private final Node mRoot; // private Node mCurrentView; // // public Entry(Node root){ // mRoot = root; // mCurrentView = mRoot; // } // // public Node getRoot(){ // return mRoot; // } // // public boolean isBegin(){ // return mCurrentView==mRoot; // } // // public boolean isEnd(){ // return (mCurrentView!=null)?mCurrentView.getChildren().size()==0:true; // } // // public Node pre(){ // if(isBegin()) return null; // return mCurrentView.getParent(); // } // // @Override // public int compareTo(Entry another) { // return mRoot.compareTo(another.getRoot()); // } // } // // Path: src/com/xiaomi/mitv/soundbarapp/diagnosis/data/Node.java // public class Node implements Comparable<Node>{ // private Node mParent; // private OrderedList<Node> mChildren = new OrderedList<Node>(); // private final QAElement mElement; // private final int mOrder; // // public Node(QAElement e, int order){ // mElement = e; // mOrder = order; // if(mElement==null) throw new IllegalArgumentException(); // } // // public Node getParent() { // return mParent; // } // // public void setParent(Node mPre) { // this.mParent = mPre; // } // // public int getOrder(){ return mOrder;} // // public List<Node> getChildren() { // return mChildren; // } // // public void addNext(Node node){ // node.setParent(this); // mChildren.add(node); // } // // public QAElement getElement() { // return mElement; // } // // @Override // public int compareTo(Node another) { // return mOrder -another.mOrder; // } // } // // Path: src/com/xiaomi/mitv/soundbarapp/diagnosis/data/QAElement.java // public abstract class QAElement{ // public static final String TYPE_CATEGORY = "category"; // public static final String TYPE_QUESTION = "question"; // public static final String TYPE_ANSWER = "answer"; // // protected String mType; // protected String mText; // protected String[] mImagePath; //relative // // public String getType() { return mType; } // public String getText() { return mText; } // public void setText(String text) { this.mText = trim(text); } // public String[] getImagePath() { return mImagePath; } // public void setImagePath(String[] mImagePath) { this.mImagePath = mImagePath; } // public boolean isCategory(){ return this instanceof Category; } // public boolean isQuestion(){ return this instanceof Question; } // public boolean isFix(){ return this instanceof Fix; } // // public static QAElement createCategory(String text) { // QAElement e = new Category(); // e.setText(text); // return e; // } // // public static QAElement createQuestion(String text) { // QAElement e = new Question(); // e.setText(text); // return e; // } // // public static QAElement createFix(String[] imgs) { // QAElement e = new Fix(); // e.setImagePath(imgs); // return e; // } // // @Override // public boolean equals(Object o) { // if(!(o instanceof QAElement)) return false; // QAElement q = (QAElement)o; // return mType.equals(q.mType) && mText.equals(q.mText); // } // // public static class Category extends QAElement{ // Category(){mType = TYPE_CATEGORY;} // } // public static class Question extends QAElement{ // Question(){mType= TYPE_QUESTION;} // } // public static class Fix extends QAElement{ // Fix(){mType= TYPE_ANSWER;} // } // // private String trim(String text){ // return text.trim() // .replaceFirst("\n", "").replaceFirst("\n", "") // .replaceFirst("\t", ""); // } // }
import android.content.Context; import android.content.res.AssetManager; import android.graphics.drawable.BitmapDrawable; import android.graphics.drawable.Drawable; import android.util.JsonWriter; import android.view.View; import android.widget.Toast; import com.xiaomi.mitv.soundbarapp.diagnosis.data.Entry; import com.xiaomi.mitv.soundbarapp.diagnosis.data.Node; import com.xiaomi.mitv.soundbarapp.diagnosis.data.QAElement; import com.xiaomi.mitv.utils.IOUtil; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.io.StringWriter; import java.util.*;
private String loadConfig() { AssetManager asm = mContext.getAssets(); InputStream in = null; try { in = asm.open(CONF_DIR + File.separator + CONF_FILE); return new String(IOUtil.readInputAsBytes(in), "utf-8"); } catch (IOException e) { e.printStackTrace(); } finally { if(in!=null)try {in.close();}catch (IOException e){} } return null; } private Drawable loadResource(String imageName){ if(imageName == null) return null; AssetManager asm = mContext.getAssets(); InputStream input = null; try { input = asm.open(CONF_DIR+File.separator+imageName); return new BitmapDrawable(mContext.getResources(), input); }catch (IOException e){ e.printStackTrace(); if(input!=null)try {input.close();}catch (IOException ei){} } return null; } //core function to switch the UI
// Path: src/com/xiaomi/mitv/soundbarapp/diagnosis/data/Entry.java // public class Entry implements Comparable<Entry>{ // private final Node mRoot; // private Node mCurrentView; // // public Entry(Node root){ // mRoot = root; // mCurrentView = mRoot; // } // // public Node getRoot(){ // return mRoot; // } // // public boolean isBegin(){ // return mCurrentView==mRoot; // } // // public boolean isEnd(){ // return (mCurrentView!=null)?mCurrentView.getChildren().size()==0:true; // } // // public Node pre(){ // if(isBegin()) return null; // return mCurrentView.getParent(); // } // // @Override // public int compareTo(Entry another) { // return mRoot.compareTo(another.getRoot()); // } // } // // Path: src/com/xiaomi/mitv/soundbarapp/diagnosis/data/Node.java // public class Node implements Comparable<Node>{ // private Node mParent; // private OrderedList<Node> mChildren = new OrderedList<Node>(); // private final QAElement mElement; // private final int mOrder; // // public Node(QAElement e, int order){ // mElement = e; // mOrder = order; // if(mElement==null) throw new IllegalArgumentException(); // } // // public Node getParent() { // return mParent; // } // // public void setParent(Node mPre) { // this.mParent = mPre; // } // // public int getOrder(){ return mOrder;} // // public List<Node> getChildren() { // return mChildren; // } // // public void addNext(Node node){ // node.setParent(this); // mChildren.add(node); // } // // public QAElement getElement() { // return mElement; // } // // @Override // public int compareTo(Node another) { // return mOrder -another.mOrder; // } // } // // Path: src/com/xiaomi/mitv/soundbarapp/diagnosis/data/QAElement.java // public abstract class QAElement{ // public static final String TYPE_CATEGORY = "category"; // public static final String TYPE_QUESTION = "question"; // public static final String TYPE_ANSWER = "answer"; // // protected String mType; // protected String mText; // protected String[] mImagePath; //relative // // public String getType() { return mType; } // public String getText() { return mText; } // public void setText(String text) { this.mText = trim(text); } // public String[] getImagePath() { return mImagePath; } // public void setImagePath(String[] mImagePath) { this.mImagePath = mImagePath; } // public boolean isCategory(){ return this instanceof Category; } // public boolean isQuestion(){ return this instanceof Question; } // public boolean isFix(){ return this instanceof Fix; } // // public static QAElement createCategory(String text) { // QAElement e = new Category(); // e.setText(text); // return e; // } // // public static QAElement createQuestion(String text) { // QAElement e = new Question(); // e.setText(text); // return e; // } // // public static QAElement createFix(String[] imgs) { // QAElement e = new Fix(); // e.setImagePath(imgs); // return e; // } // // @Override // public boolean equals(Object o) { // if(!(o instanceof QAElement)) return false; // QAElement q = (QAElement)o; // return mType.equals(q.mType) && mText.equals(q.mText); // } // // public static class Category extends QAElement{ // Category(){mType = TYPE_CATEGORY;} // } // public static class Question extends QAElement{ // Question(){mType= TYPE_QUESTION;} // } // public static class Fix extends QAElement{ // Fix(){mType= TYPE_ANSWER;} // } // // private String trim(String text){ // return text.trim() // .replaceFirst("\n", "").replaceFirst("\n", "") // .replaceFirst("\t", ""); // } // } // Path: src/com/xiaomi/mitv/soundbarapp/diagnosis/Engine.java import android.content.Context; import android.content.res.AssetManager; import android.graphics.drawable.BitmapDrawable; import android.graphics.drawable.Drawable; import android.util.JsonWriter; import android.view.View; import android.widget.Toast; import com.xiaomi.mitv.soundbarapp.diagnosis.data.Entry; import com.xiaomi.mitv.soundbarapp.diagnosis.data.Node; import com.xiaomi.mitv.soundbarapp.diagnosis.data.QAElement; import com.xiaomi.mitv.utils.IOUtil; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.io.StringWriter; import java.util.*; private String loadConfig() { AssetManager asm = mContext.getAssets(); InputStream in = null; try { in = asm.open(CONF_DIR + File.separator + CONF_FILE); return new String(IOUtil.readInputAsBytes(in), "utf-8"); } catch (IOException e) { e.printStackTrace(); } finally { if(in!=null)try {in.close();}catch (IOException e){} } return null; } private Drawable loadResource(String imageName){ if(imageName == null) return null; AssetManager asm = mContext.getAssets(); InputStream input = null; try { input = asm.open(CONF_DIR+File.separator+imageName); return new BitmapDrawable(mContext.getResources(), input); }catch (IOException e){ e.printStackTrace(); if(input!=null)try {input.close();}catch (IOException ei){} } return null; } //core function to switch the UI
private void go2(Node node, int viaAction){
XiaoMi/misound
src/com/xiaomi/mitv/soundbarapp/diagnosis/Engine.java
// Path: src/com/xiaomi/mitv/soundbarapp/diagnosis/data/Entry.java // public class Entry implements Comparable<Entry>{ // private final Node mRoot; // private Node mCurrentView; // // public Entry(Node root){ // mRoot = root; // mCurrentView = mRoot; // } // // public Node getRoot(){ // return mRoot; // } // // public boolean isBegin(){ // return mCurrentView==mRoot; // } // // public boolean isEnd(){ // return (mCurrentView!=null)?mCurrentView.getChildren().size()==0:true; // } // // public Node pre(){ // if(isBegin()) return null; // return mCurrentView.getParent(); // } // // @Override // public int compareTo(Entry another) { // return mRoot.compareTo(another.getRoot()); // } // } // // Path: src/com/xiaomi/mitv/soundbarapp/diagnosis/data/Node.java // public class Node implements Comparable<Node>{ // private Node mParent; // private OrderedList<Node> mChildren = new OrderedList<Node>(); // private final QAElement mElement; // private final int mOrder; // // public Node(QAElement e, int order){ // mElement = e; // mOrder = order; // if(mElement==null) throw new IllegalArgumentException(); // } // // public Node getParent() { // return mParent; // } // // public void setParent(Node mPre) { // this.mParent = mPre; // } // // public int getOrder(){ return mOrder;} // // public List<Node> getChildren() { // return mChildren; // } // // public void addNext(Node node){ // node.setParent(this); // mChildren.add(node); // } // // public QAElement getElement() { // return mElement; // } // // @Override // public int compareTo(Node another) { // return mOrder -another.mOrder; // } // } // // Path: src/com/xiaomi/mitv/soundbarapp/diagnosis/data/QAElement.java // public abstract class QAElement{ // public static final String TYPE_CATEGORY = "category"; // public static final String TYPE_QUESTION = "question"; // public static final String TYPE_ANSWER = "answer"; // // protected String mType; // protected String mText; // protected String[] mImagePath; //relative // // public String getType() { return mType; } // public String getText() { return mText; } // public void setText(String text) { this.mText = trim(text); } // public String[] getImagePath() { return mImagePath; } // public void setImagePath(String[] mImagePath) { this.mImagePath = mImagePath; } // public boolean isCategory(){ return this instanceof Category; } // public boolean isQuestion(){ return this instanceof Question; } // public boolean isFix(){ return this instanceof Fix; } // // public static QAElement createCategory(String text) { // QAElement e = new Category(); // e.setText(text); // return e; // } // // public static QAElement createQuestion(String text) { // QAElement e = new Question(); // e.setText(text); // return e; // } // // public static QAElement createFix(String[] imgs) { // QAElement e = new Fix(); // e.setImagePath(imgs); // return e; // } // // @Override // public boolean equals(Object o) { // if(!(o instanceof QAElement)) return false; // QAElement q = (QAElement)o; // return mType.equals(q.mType) && mText.equals(q.mText); // } // // public static class Category extends QAElement{ // Category(){mType = TYPE_CATEGORY;} // } // public static class Question extends QAElement{ // Question(){mType= TYPE_QUESTION;} // } // public static class Fix extends QAElement{ // Fix(){mType= TYPE_ANSWER;} // } // // private String trim(String text){ // return text.trim() // .replaceFirst("\n", "").replaceFirst("\n", "") // .replaceFirst("\t", ""); // } // }
import android.content.Context; import android.content.res.AssetManager; import android.graphics.drawable.BitmapDrawable; import android.graphics.drawable.Drawable; import android.util.JsonWriter; import android.view.View; import android.widget.Toast; import com.xiaomi.mitv.soundbarapp.diagnosis.data.Entry; import com.xiaomi.mitv.soundbarapp.diagnosis.data.Node; import com.xiaomi.mitv.soundbarapp.diagnosis.data.QAElement; import com.xiaomi.mitv.utils.IOUtil; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.io.StringWriter; import java.util.*;
} catch (IOException e) { e.printStackTrace(); } finally { if(in!=null)try {in.close();}catch (IOException e){} } return null; } private Drawable loadResource(String imageName){ if(imageName == null) return null; AssetManager asm = mContext.getAssets(); InputStream input = null; try { input = asm.open(CONF_DIR+File.separator+imageName); return new BitmapDrawable(mContext.getResources(), input); }catch (IOException e){ e.printStackTrace(); if(input!=null)try {input.close();}catch (IOException ei){} } return null; } //core function to switch the UI private void go2(Node node, int viaAction){ if(node == null) { //top bindCategoryListLayout(); return; }
// Path: src/com/xiaomi/mitv/soundbarapp/diagnosis/data/Entry.java // public class Entry implements Comparable<Entry>{ // private final Node mRoot; // private Node mCurrentView; // // public Entry(Node root){ // mRoot = root; // mCurrentView = mRoot; // } // // public Node getRoot(){ // return mRoot; // } // // public boolean isBegin(){ // return mCurrentView==mRoot; // } // // public boolean isEnd(){ // return (mCurrentView!=null)?mCurrentView.getChildren().size()==0:true; // } // // public Node pre(){ // if(isBegin()) return null; // return mCurrentView.getParent(); // } // // @Override // public int compareTo(Entry another) { // return mRoot.compareTo(another.getRoot()); // } // } // // Path: src/com/xiaomi/mitv/soundbarapp/diagnosis/data/Node.java // public class Node implements Comparable<Node>{ // private Node mParent; // private OrderedList<Node> mChildren = new OrderedList<Node>(); // private final QAElement mElement; // private final int mOrder; // // public Node(QAElement e, int order){ // mElement = e; // mOrder = order; // if(mElement==null) throw new IllegalArgumentException(); // } // // public Node getParent() { // return mParent; // } // // public void setParent(Node mPre) { // this.mParent = mPre; // } // // public int getOrder(){ return mOrder;} // // public List<Node> getChildren() { // return mChildren; // } // // public void addNext(Node node){ // node.setParent(this); // mChildren.add(node); // } // // public QAElement getElement() { // return mElement; // } // // @Override // public int compareTo(Node another) { // return mOrder -another.mOrder; // } // } // // Path: src/com/xiaomi/mitv/soundbarapp/diagnosis/data/QAElement.java // public abstract class QAElement{ // public static final String TYPE_CATEGORY = "category"; // public static final String TYPE_QUESTION = "question"; // public static final String TYPE_ANSWER = "answer"; // // protected String mType; // protected String mText; // protected String[] mImagePath; //relative // // public String getType() { return mType; } // public String getText() { return mText; } // public void setText(String text) { this.mText = trim(text); } // public String[] getImagePath() { return mImagePath; } // public void setImagePath(String[] mImagePath) { this.mImagePath = mImagePath; } // public boolean isCategory(){ return this instanceof Category; } // public boolean isQuestion(){ return this instanceof Question; } // public boolean isFix(){ return this instanceof Fix; } // // public static QAElement createCategory(String text) { // QAElement e = new Category(); // e.setText(text); // return e; // } // // public static QAElement createQuestion(String text) { // QAElement e = new Question(); // e.setText(text); // return e; // } // // public static QAElement createFix(String[] imgs) { // QAElement e = new Fix(); // e.setImagePath(imgs); // return e; // } // // @Override // public boolean equals(Object o) { // if(!(o instanceof QAElement)) return false; // QAElement q = (QAElement)o; // return mType.equals(q.mType) && mText.equals(q.mText); // } // // public static class Category extends QAElement{ // Category(){mType = TYPE_CATEGORY;} // } // public static class Question extends QAElement{ // Question(){mType= TYPE_QUESTION;} // } // public static class Fix extends QAElement{ // Fix(){mType= TYPE_ANSWER;} // } // // private String trim(String text){ // return text.trim() // .replaceFirst("\n", "").replaceFirst("\n", "") // .replaceFirst("\t", ""); // } // } // Path: src/com/xiaomi/mitv/soundbarapp/diagnosis/Engine.java import android.content.Context; import android.content.res.AssetManager; import android.graphics.drawable.BitmapDrawable; import android.graphics.drawable.Drawable; import android.util.JsonWriter; import android.view.View; import android.widget.Toast; import com.xiaomi.mitv.soundbarapp.diagnosis.data.Entry; import com.xiaomi.mitv.soundbarapp.diagnosis.data.Node; import com.xiaomi.mitv.soundbarapp.diagnosis.data.QAElement; import com.xiaomi.mitv.utils.IOUtil; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.io.StringWriter; import java.util.*; } catch (IOException e) { e.printStackTrace(); } finally { if(in!=null)try {in.close();}catch (IOException e){} } return null; } private Drawable loadResource(String imageName){ if(imageName == null) return null; AssetManager asm = mContext.getAssets(); InputStream input = null; try { input = asm.open(CONF_DIR+File.separator+imageName); return new BitmapDrawable(mContext.getResources(), input); }catch (IOException e){ e.printStackTrace(); if(input!=null)try {input.close();}catch (IOException ei){} } return null; } //core function to switch the UI private void go2(Node node, int viaAction){ if(node == null) { //top bindCategoryListLayout(); return; }
QAElement element = node.getElement();
XiaoMi/misound
src/com/xiaomi/mitv/soundbarapp/faq/FaqDataStore.java
// Path: src/com/xiaomi/mitv/soundbarapp/provider/DataProvider.java // public class DataProvider { // private GalaxyProvider mProvider = new GalaxyProvider(); // public List<FirmwareVersion> listVersion(){ // return mProvider.listVersion(); // } // // public FirmwareVersion queryNewVersion(int localVersion){ // return mProvider.queryNewVersion(localVersion); // } // // public FaqData queryFaqList(){ // return mProvider.queryFaqList(); // } // // // //check if the app run in dev mode via the config file on SDCARD // private boolean isInDevMode(){ // return mProvider.isInDevMode(); // } // }
import android.content.Context; import com.xiaomi.mitv.content.FaqData; import com.xiaomi.mitv.soundbarapp.provider.DataProvider; import com.xiaomi.mitv.utils.IOUtil; import java.io.*;
package com.xiaomi.mitv.soundbarapp.faq; /** * Created by chenxuetong on 7/3/14. * * [ * { * id:12111, * title:q1. * content:abcd * }, * { * id:22111, * title:q2. * content:abcd * } * ] * */ public class FaqDataStore { private static final String ASSETS_DEFAULT_DATA_FILE = "faq/faq_list"; private static final String QA_DATA_FILE_NAME = "faq_list"; private final Context mContext; public FaqDataStore(Context context) { mContext = context; } public FaqData load() { InputStream input = null; try { input = getDataInputStream(); return FaqData.loadString(new String(IOUtil.readInputAsBytes(input), "utf-8")); }catch (IOException e){ return null; } finally { if(input!=null)try {input.close();}catch (IOException e){} } } public FaqData loadRemote() {
// Path: src/com/xiaomi/mitv/soundbarapp/provider/DataProvider.java // public class DataProvider { // private GalaxyProvider mProvider = new GalaxyProvider(); // public List<FirmwareVersion> listVersion(){ // return mProvider.listVersion(); // } // // public FirmwareVersion queryNewVersion(int localVersion){ // return mProvider.queryNewVersion(localVersion); // } // // public FaqData queryFaqList(){ // return mProvider.queryFaqList(); // } // // // //check if the app run in dev mode via the config file on SDCARD // private boolean isInDevMode(){ // return mProvider.isInDevMode(); // } // } // Path: src/com/xiaomi/mitv/soundbarapp/faq/FaqDataStore.java import android.content.Context; import com.xiaomi.mitv.content.FaqData; import com.xiaomi.mitv.soundbarapp.provider.DataProvider; import com.xiaomi.mitv.utils.IOUtil; import java.io.*; package com.xiaomi.mitv.soundbarapp.faq; /** * Created by chenxuetong on 7/3/14. * * [ * { * id:12111, * title:q1. * content:abcd * }, * { * id:22111, * title:q2. * content:abcd * } * ] * */ public class FaqDataStore { private static final String ASSETS_DEFAULT_DATA_FILE = "faq/faq_list"; private static final String QA_DATA_FILE_NAME = "faq_list"; private final Context mContext; public FaqDataStore(Context context) { mContext = context; } public FaqData load() { InputStream input = null; try { input = getDataInputStream(); return FaqData.loadString(new String(IOUtil.readInputAsBytes(input), "utf-8")); }catch (IOException e){ return null; } finally { if(input!=null)try {input.close();}catch (IOException e){} } } public FaqData loadRemote() {
DataProvider provider = new DataProvider();
moronicgeek/SwaggerCloud
client/src/test/java/com/github/moronicgeek/swagger/cloud/client/ConfigurationTest.java
// Path: core/src/main/java/com/github/moronicgeek/swagger/cloud/model/SwaggerCloudClientProperties.java // @ConfigurationProperties("swagger.cloud.boot.client") // public class SwaggerCloudClientProperties { // private String adminServerUrl = ""; // private String swaggerUrl = ""; // private String name = ""; // private String groupId = ""; // //TODO We should probably derive this from the swagger json file and perhaps some other data. Think !!! // private String description =""; // // @Autowired // @JsonIgnore // private ServerProperties server; // // private Integer serverPort; // // // public String getGroupId() { // return groupId; // } // // public void setGroupId(String groupId) { // this.groupId = groupId; // } // // public String getSwaggerUrl() { // return swaggerUrl; // } // // public void setSwaggerUrl(String swaggerUrl) { // this.swaggerUrl = swaggerUrl; // } // // // public String getAdminServerUrl() { // return adminServerUrl; // } // // public void setAdminServerUrl(String adminServerUrl) { // this.adminServerUrl = adminServerUrl; // } // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // public ServerProperties getServer() { // return server; // } // // public void setServer(ServerProperties server) { // this.server = server; // } // // public Integer getServerPort() { // return serverPort; // } // // public void setServerPort(Integer serverPort) { // this.serverPort = serverPort; // } // // @Override // public String toString() { // return "SwaggerCloudClientProperties{" + // "adminServerUrl='" + adminServerUrl + '\'' + // ", swaggerUrl='" + swaggerUrl + '\'' + // ", name='" + name + '\'' + // ", groupId='" + groupId + '\'' + // ", description='" + description + '\'' + // ", server=" + server + // ", serverPort=" + serverPort + // '}'; // } // }
import org.junit.Assert; import org.springframework.boot.autoconfigure.PropertyPlaceholderAutoConfiguration; import org.springframework.boot.autoconfigure.web.ServerPropertiesAutoConfiguration; import org.springframework.boot.test.util.EnvironmentTestUtils; import org.springframework.web.context.support.AnnotationConfigWebApplicationContext; import com.github.moronicgeek.swagger.cloud.model.SwaggerCloudClientProperties; import static org.hamcrest.Matchers.is;
package com.github.moronicgeek.swagger.cloud.client; public class ConfigurationTest { private AnnotationConfigWebApplicationContext context; public void close() { if (this.context != null) { this.context.close(); } } public void testSwagerCloudAdminProperties(){ load("swagger.cloud.boot.client.name:IchiServerAPI"," swagger.cloud.boot.client.swagger-url:http://localhost:8081/swagger.json", "swagger.cloud.boot.client.groupId:za.co.moronicgeek.ichiserver");
// Path: core/src/main/java/com/github/moronicgeek/swagger/cloud/model/SwaggerCloudClientProperties.java // @ConfigurationProperties("swagger.cloud.boot.client") // public class SwaggerCloudClientProperties { // private String adminServerUrl = ""; // private String swaggerUrl = ""; // private String name = ""; // private String groupId = ""; // //TODO We should probably derive this from the swagger json file and perhaps some other data. Think !!! // private String description =""; // // @Autowired // @JsonIgnore // private ServerProperties server; // // private Integer serverPort; // // // public String getGroupId() { // return groupId; // } // // public void setGroupId(String groupId) { // this.groupId = groupId; // } // // public String getSwaggerUrl() { // return swaggerUrl; // } // // public void setSwaggerUrl(String swaggerUrl) { // this.swaggerUrl = swaggerUrl; // } // // // public String getAdminServerUrl() { // return adminServerUrl; // } // // public void setAdminServerUrl(String adminServerUrl) { // this.adminServerUrl = adminServerUrl; // } // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // public ServerProperties getServer() { // return server; // } // // public void setServer(ServerProperties server) { // this.server = server; // } // // public Integer getServerPort() { // return serverPort; // } // // public void setServerPort(Integer serverPort) { // this.serverPort = serverPort; // } // // @Override // public String toString() { // return "SwaggerCloudClientProperties{" + // "adminServerUrl='" + adminServerUrl + '\'' + // ", swaggerUrl='" + swaggerUrl + '\'' + // ", name='" + name + '\'' + // ", groupId='" + groupId + '\'' + // ", description='" + description + '\'' + // ", server=" + server + // ", serverPort=" + serverPort + // '}'; // } // } // Path: client/src/test/java/com/github/moronicgeek/swagger/cloud/client/ConfigurationTest.java import org.junit.Assert; import org.springframework.boot.autoconfigure.PropertyPlaceholderAutoConfiguration; import org.springframework.boot.autoconfigure.web.ServerPropertiesAutoConfiguration; import org.springframework.boot.test.util.EnvironmentTestUtils; import org.springframework.web.context.support.AnnotationConfigWebApplicationContext; import com.github.moronicgeek.swagger.cloud.model.SwaggerCloudClientProperties; import static org.hamcrest.Matchers.is; package com.github.moronicgeek.swagger.cloud.client; public class ConfigurationTest { private AnnotationConfigWebApplicationContext context; public void close() { if (this.context != null) { this.context.close(); } } public void testSwagerCloudAdminProperties(){ load("swagger.cloud.boot.client.name:IchiServerAPI"," swagger.cloud.boot.client.swagger-url:http://localhost:8081/swagger.json", "swagger.cloud.boot.client.groupId:za.co.moronicgeek.ichiserver");
SwaggerCloudClientProperties clientProperties = new SwaggerCloudClientProperties();
moronicgeek/SwaggerCloud
client/src/main/java/com/github/moronicgeek/swagger/cloud/client/listener/RegistrationApplicationListener.java
// Path: client/src/main/java/com/github/moronicgeek/swagger/cloud/client/ApplicationRegistrationService.java // public class ApplicationRegistrationService { // // private static HttpHeaders HTTP_HEADERS = createHttpHeaders(); // private SwaggerCloudAdminProperties adminProperties; // private SwaggerCloudClientProperties clientProperties; // private RestTemplate template; // // public ApplicationRegistrationService(SwaggerCloudClientProperties clientProperties, SwaggerCloudAdminProperties adminProperties, RestTemplate template) { // this.adminProperties = adminProperties; // this.clientProperties = clientProperties; // this.template = template; // } // // private static HttpHeaders createHttpHeaders() { // HttpHeaders headers = new HttpHeaders(); // headers.setContentType(MediaType.APPLICATION_JSON); // headers.setAccept(Collections.singletonList(MediaType.APPLICATION_JSON)); // return HttpHeaders.readOnlyHttpHeaders(headers); // } // // public static HttpHeaders getHttpHeaders() { // return HTTP_HEADERS; // } // // public static void setHttpHeaders(HttpHeaders httpHeaders) { // HTTP_HEADERS = httpHeaders; // } // // public boolean registerApplication() { // boolean registrationSuccessful = false; // ApplicationRegistrationMetadata self = createMetaDataApplication(); // // ResponseEntity<Boolean> response = template.postForEntity(adminProperties.getUrl() +AdminRoutes.CONTEXT.getPath()+ AdminRoutes.REGISTER.getPath(), // new HttpEntity<>(self, HTTP_HEADERS), Boolean.class); // if (response == null){ // return false; // } // // return registrationSuccessful; // } // // public boolean deregisterApplication() { // boolean deregistered = false; // ApplicationRegistrationMetadata self = createMetaDataApplication(); // //this will be used some day // ResponseEntity<Boolean> response = template.postForEntity(adminProperties.getUrl() +AdminRoutes.CONTEXT.getPath()+ AdminRoutes.DEREGISTER.getPath(), // new HttpEntity<>(self, HTTP_HEADERS), Boolean.class); // if (response == null){ // return false; // } // return deregistered; // } // // private ApplicationRegistrationMetadata createMetaDataApplication() { // return new ApplicationRegistrationMetadata(clientProperties.getName(),clientProperties.getSwaggerUrl(),clientProperties.getGroupId(),clientProperties.getServerPort(),clientProperties.getServer().getContextPath()); // } // // public SwaggerCloudAdminProperties getAdminProperties() { // return adminProperties; // } // // public void setAdminProperties(SwaggerCloudAdminProperties adminProperties) { // this.adminProperties = adminProperties; // } // // public SwaggerCloudClientProperties getClientProperties() { // return clientProperties; // } // // public void setClientProperties(SwaggerCloudClientProperties clientProperties) { // this.clientProperties = clientProperties; // } // // public RestTemplate getTemplate() { // return template; // } // // public void setTemplate(RestTemplate template) { // this.template = template; // } // }
import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.boot.context.event.ApplicationReadyEvent; import org.springframework.context.event.ContextClosedEvent; import org.springframework.context.event.ContextStoppedEvent; import org.springframework.context.event.EventListener; import org.springframework.core.Ordered; import org.springframework.core.annotation.Order; import org.springframework.scheduling.TaskScheduler; import org.springframework.scheduling.concurrent.ConcurrentTaskScheduler; import com.github.moronicgeek.swagger.cloud.client.ApplicationRegistrationService; import java.util.concurrent.Executors; import java.util.concurrent.ScheduledFuture;
package com.github.moronicgeek.swagger.cloud.client.listener; /** * Created by muhammedpatel on 2016/08/07. */ public class RegistrationApplicationListener { private static Logger LOGGER = LoggerFactory.getLogger(RegistrationApplicationListener.class);
// Path: client/src/main/java/com/github/moronicgeek/swagger/cloud/client/ApplicationRegistrationService.java // public class ApplicationRegistrationService { // // private static HttpHeaders HTTP_HEADERS = createHttpHeaders(); // private SwaggerCloudAdminProperties adminProperties; // private SwaggerCloudClientProperties clientProperties; // private RestTemplate template; // // public ApplicationRegistrationService(SwaggerCloudClientProperties clientProperties, SwaggerCloudAdminProperties adminProperties, RestTemplate template) { // this.adminProperties = adminProperties; // this.clientProperties = clientProperties; // this.template = template; // } // // private static HttpHeaders createHttpHeaders() { // HttpHeaders headers = new HttpHeaders(); // headers.setContentType(MediaType.APPLICATION_JSON); // headers.setAccept(Collections.singletonList(MediaType.APPLICATION_JSON)); // return HttpHeaders.readOnlyHttpHeaders(headers); // } // // public static HttpHeaders getHttpHeaders() { // return HTTP_HEADERS; // } // // public static void setHttpHeaders(HttpHeaders httpHeaders) { // HTTP_HEADERS = httpHeaders; // } // // public boolean registerApplication() { // boolean registrationSuccessful = false; // ApplicationRegistrationMetadata self = createMetaDataApplication(); // // ResponseEntity<Boolean> response = template.postForEntity(adminProperties.getUrl() +AdminRoutes.CONTEXT.getPath()+ AdminRoutes.REGISTER.getPath(), // new HttpEntity<>(self, HTTP_HEADERS), Boolean.class); // if (response == null){ // return false; // } // // return registrationSuccessful; // } // // public boolean deregisterApplication() { // boolean deregistered = false; // ApplicationRegistrationMetadata self = createMetaDataApplication(); // //this will be used some day // ResponseEntity<Boolean> response = template.postForEntity(adminProperties.getUrl() +AdminRoutes.CONTEXT.getPath()+ AdminRoutes.DEREGISTER.getPath(), // new HttpEntity<>(self, HTTP_HEADERS), Boolean.class); // if (response == null){ // return false; // } // return deregistered; // } // // private ApplicationRegistrationMetadata createMetaDataApplication() { // return new ApplicationRegistrationMetadata(clientProperties.getName(),clientProperties.getSwaggerUrl(),clientProperties.getGroupId(),clientProperties.getServerPort(),clientProperties.getServer().getContextPath()); // } // // public SwaggerCloudAdminProperties getAdminProperties() { // return adminProperties; // } // // public void setAdminProperties(SwaggerCloudAdminProperties adminProperties) { // this.adminProperties = adminProperties; // } // // public SwaggerCloudClientProperties getClientProperties() { // return clientProperties; // } // // public void setClientProperties(SwaggerCloudClientProperties clientProperties) { // this.clientProperties = clientProperties; // } // // public RestTemplate getTemplate() { // return template; // } // // public void setTemplate(RestTemplate template) { // this.template = template; // } // } // Path: client/src/main/java/com/github/moronicgeek/swagger/cloud/client/listener/RegistrationApplicationListener.java import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.boot.context.event.ApplicationReadyEvent; import org.springframework.context.event.ContextClosedEvent; import org.springframework.context.event.ContextStoppedEvent; import org.springframework.context.event.EventListener; import org.springframework.core.Ordered; import org.springframework.core.annotation.Order; import org.springframework.scheduling.TaskScheduler; import org.springframework.scheduling.concurrent.ConcurrentTaskScheduler; import com.github.moronicgeek.swagger.cloud.client.ApplicationRegistrationService; import java.util.concurrent.Executors; import java.util.concurrent.ScheduledFuture; package com.github.moronicgeek.swagger.cloud.client.listener; /** * Created by muhammedpatel on 2016/08/07. */ public class RegistrationApplicationListener { private static Logger LOGGER = LoggerFactory.getLogger(RegistrationApplicationListener.class);
private final ApplicationRegistrationService register;
moronicgeek/SwaggerCloud
server/src/main/java/com/github/moronicgeek/swagger/cloud/server/registry/Registry.java
// Path: core/src/main/java/com/github/moronicgeek/swagger/cloud/model/ApplicationRegistrationMetadata.java // public class ApplicationRegistrationMetadata { // // // private int id; // private String name; // private String swaggerUrl; // private String groupId; // private int port; // private String host; // // public ApplicationRegistrationMetadata(String name, String swaggerUrl, String groupId, int port, String host) { // this.name = name; // this.swaggerUrl = swaggerUrl; // this.groupId = groupId; // this.port = port; // this.host = host; // } // // public ApplicationRegistrationMetadata() { // // } // // // public int getId() { // return id; // } // // public void setId(int id) { // this.id = id; // } // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // public String getSwaggerUrl() { // return swaggerUrl; // } // // public void setSwaggerUrl(String swaggerUrl) { // this.swaggerUrl = swaggerUrl; // } // // public String getGroupId() { // return groupId; // } // // public void setGroupId(String groupId) { // this.groupId = groupId; // } // // public int getPort() { // return port; // } // // public void setPort(int port) { // this.port = port; // } // // public String getHost() { // return host; // } // // public void setHost(String host) { // this.host = host; // } // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (o == null || getClass() != o.getClass()) return false; // ApplicationRegistrationMetadata metadata = (ApplicationRegistrationMetadata) o; // return id == metadata.id && // Objects.equals(name, metadata.name) && // Objects.equals(swaggerUrl, metadata.swaggerUrl) && // Objects.equals(groupId, metadata.groupId); // } // // @Override // public int hashCode() { // return Objects.hash(id, name, swaggerUrl, groupId); // } // // @Override // public String toString() { // return "ApplicationRegistrationMetadata{" + // "id=" + id + // ", name='" + name + '\'' + // ", swaggerUrl='" + swaggerUrl + '\'' + // ", groupId='" + groupId + '\'' + // '}'; // } // // // } // // Path: server/src/main/java/com/github/moronicgeek/swagger/cloud/server/ApiDefinition.java // public class ApiDefinition { // // // private String name; // private String swaggerUrl; // private String groupId; // private String description; // private String host; // private int port; // // public ApiDefinition() { // } // // public ApiDefinition(String name, String swaggerUrl, String groupId, String description, String host, int port) { // this.name = name; // this.swaggerUrl = swaggerUrl; // this.groupId = groupId; // this.description = description; // this.host = host; // this.port = port; // } // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // public String getSwaggerUrl() { // return swaggerUrl; // } // // public void setSwaggerUrl(String swaggerUrl) { // this.swaggerUrl = swaggerUrl; // } // // public String getGroupId() { // return groupId; // } // // public void setGroupId(String groupId) { // this.groupId = groupId; // } // // public String getDescription() { // return description; // } // // public void setDescription(String description) { // this.description = description; // } // // public String getHost() { // return host; // } // // public void setHost(String host) { // this.host = host; // } // // public int getPort() { // return port; // } // // public void setPort(int port) { // this.port = port; // } // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (o == null || getClass() != o.getClass()) return false; // // ApiDefinition that = (ApiDefinition) o; // // if (port != that.port) return false; // if (groupId != null ? !groupId.equals(that.groupId) : that.groupId != null) return false; // return host != null ? host.equals(that.host) : that.host == null; // } // // @Override // public int hashCode() { // int result = groupId != null ? groupId.hashCode() : 0; // result = 31 * result + (host != null ? host.hashCode() : 0); // result = 31 * result + port; // return result; // } // }
import com.github.moronicgeek.swagger.cloud.model.ApplicationRegistrationMetadata; import com.github.moronicgeek.swagger.cloud.server.ApiDefinition; import io.swagger.models.Swagger; import io.swagger.parser.SwaggerParser; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.util.Assert; import org.springframework.web.client.HttpClientErrorException; import java.util.*; import java.util.concurrent.ConcurrentHashMap;
package com.github.moronicgeek.swagger.cloud.server.registry; /** * Created by muhammedpatel on 2016/08/06. */ //TODO probably a good idea to create an interface for other stores like hazel cast and the myriad other stores. One Day!!! public class Registry { private static Logger LOGGER = LoggerFactory.getLogger(Registry.class);
// Path: core/src/main/java/com/github/moronicgeek/swagger/cloud/model/ApplicationRegistrationMetadata.java // public class ApplicationRegistrationMetadata { // // // private int id; // private String name; // private String swaggerUrl; // private String groupId; // private int port; // private String host; // // public ApplicationRegistrationMetadata(String name, String swaggerUrl, String groupId, int port, String host) { // this.name = name; // this.swaggerUrl = swaggerUrl; // this.groupId = groupId; // this.port = port; // this.host = host; // } // // public ApplicationRegistrationMetadata() { // // } // // // public int getId() { // return id; // } // // public void setId(int id) { // this.id = id; // } // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // public String getSwaggerUrl() { // return swaggerUrl; // } // // public void setSwaggerUrl(String swaggerUrl) { // this.swaggerUrl = swaggerUrl; // } // // public String getGroupId() { // return groupId; // } // // public void setGroupId(String groupId) { // this.groupId = groupId; // } // // public int getPort() { // return port; // } // // public void setPort(int port) { // this.port = port; // } // // public String getHost() { // return host; // } // // public void setHost(String host) { // this.host = host; // } // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (o == null || getClass() != o.getClass()) return false; // ApplicationRegistrationMetadata metadata = (ApplicationRegistrationMetadata) o; // return id == metadata.id && // Objects.equals(name, metadata.name) && // Objects.equals(swaggerUrl, metadata.swaggerUrl) && // Objects.equals(groupId, metadata.groupId); // } // // @Override // public int hashCode() { // return Objects.hash(id, name, swaggerUrl, groupId); // } // // @Override // public String toString() { // return "ApplicationRegistrationMetadata{" + // "id=" + id + // ", name='" + name + '\'' + // ", swaggerUrl='" + swaggerUrl + '\'' + // ", groupId='" + groupId + '\'' + // '}'; // } // // // } // // Path: server/src/main/java/com/github/moronicgeek/swagger/cloud/server/ApiDefinition.java // public class ApiDefinition { // // // private String name; // private String swaggerUrl; // private String groupId; // private String description; // private String host; // private int port; // // public ApiDefinition() { // } // // public ApiDefinition(String name, String swaggerUrl, String groupId, String description, String host, int port) { // this.name = name; // this.swaggerUrl = swaggerUrl; // this.groupId = groupId; // this.description = description; // this.host = host; // this.port = port; // } // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // public String getSwaggerUrl() { // return swaggerUrl; // } // // public void setSwaggerUrl(String swaggerUrl) { // this.swaggerUrl = swaggerUrl; // } // // public String getGroupId() { // return groupId; // } // // public void setGroupId(String groupId) { // this.groupId = groupId; // } // // public String getDescription() { // return description; // } // // public void setDescription(String description) { // this.description = description; // } // // public String getHost() { // return host; // } // // public void setHost(String host) { // this.host = host; // } // // public int getPort() { // return port; // } // // public void setPort(int port) { // this.port = port; // } // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (o == null || getClass() != o.getClass()) return false; // // ApiDefinition that = (ApiDefinition) o; // // if (port != that.port) return false; // if (groupId != null ? !groupId.equals(that.groupId) : that.groupId != null) return false; // return host != null ? host.equals(that.host) : that.host == null; // } // // @Override // public int hashCode() { // int result = groupId != null ? groupId.hashCode() : 0; // result = 31 * result + (host != null ? host.hashCode() : 0); // result = 31 * result + port; // return result; // } // } // Path: server/src/main/java/com/github/moronicgeek/swagger/cloud/server/registry/Registry.java import com.github.moronicgeek.swagger.cloud.model.ApplicationRegistrationMetadata; import com.github.moronicgeek.swagger.cloud.server.ApiDefinition; import io.swagger.models.Swagger; import io.swagger.parser.SwaggerParser; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.util.Assert; import org.springframework.web.client.HttpClientErrorException; import java.util.*; import java.util.concurrent.ConcurrentHashMap; package com.github.moronicgeek.swagger.cloud.server.registry; /** * Created by muhammedpatel on 2016/08/06. */ //TODO probably a good idea to create an interface for other stores like hazel cast and the myriad other stores. One Day!!! public class Registry { private static Logger LOGGER = LoggerFactory.getLogger(Registry.class);
private ConcurrentHashMap<String, Set<ApiDefinition>> registry = new ConcurrentHashMap<>();
moronicgeek/SwaggerCloud
server/src/main/java/com/github/moronicgeek/swagger/cloud/server/registry/Registry.java
// Path: core/src/main/java/com/github/moronicgeek/swagger/cloud/model/ApplicationRegistrationMetadata.java // public class ApplicationRegistrationMetadata { // // // private int id; // private String name; // private String swaggerUrl; // private String groupId; // private int port; // private String host; // // public ApplicationRegistrationMetadata(String name, String swaggerUrl, String groupId, int port, String host) { // this.name = name; // this.swaggerUrl = swaggerUrl; // this.groupId = groupId; // this.port = port; // this.host = host; // } // // public ApplicationRegistrationMetadata() { // // } // // // public int getId() { // return id; // } // // public void setId(int id) { // this.id = id; // } // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // public String getSwaggerUrl() { // return swaggerUrl; // } // // public void setSwaggerUrl(String swaggerUrl) { // this.swaggerUrl = swaggerUrl; // } // // public String getGroupId() { // return groupId; // } // // public void setGroupId(String groupId) { // this.groupId = groupId; // } // // public int getPort() { // return port; // } // // public void setPort(int port) { // this.port = port; // } // // public String getHost() { // return host; // } // // public void setHost(String host) { // this.host = host; // } // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (o == null || getClass() != o.getClass()) return false; // ApplicationRegistrationMetadata metadata = (ApplicationRegistrationMetadata) o; // return id == metadata.id && // Objects.equals(name, metadata.name) && // Objects.equals(swaggerUrl, metadata.swaggerUrl) && // Objects.equals(groupId, metadata.groupId); // } // // @Override // public int hashCode() { // return Objects.hash(id, name, swaggerUrl, groupId); // } // // @Override // public String toString() { // return "ApplicationRegistrationMetadata{" + // "id=" + id + // ", name='" + name + '\'' + // ", swaggerUrl='" + swaggerUrl + '\'' + // ", groupId='" + groupId + '\'' + // '}'; // } // // // } // // Path: server/src/main/java/com/github/moronicgeek/swagger/cloud/server/ApiDefinition.java // public class ApiDefinition { // // // private String name; // private String swaggerUrl; // private String groupId; // private String description; // private String host; // private int port; // // public ApiDefinition() { // } // // public ApiDefinition(String name, String swaggerUrl, String groupId, String description, String host, int port) { // this.name = name; // this.swaggerUrl = swaggerUrl; // this.groupId = groupId; // this.description = description; // this.host = host; // this.port = port; // } // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // public String getSwaggerUrl() { // return swaggerUrl; // } // // public void setSwaggerUrl(String swaggerUrl) { // this.swaggerUrl = swaggerUrl; // } // // public String getGroupId() { // return groupId; // } // // public void setGroupId(String groupId) { // this.groupId = groupId; // } // // public String getDescription() { // return description; // } // // public void setDescription(String description) { // this.description = description; // } // // public String getHost() { // return host; // } // // public void setHost(String host) { // this.host = host; // } // // public int getPort() { // return port; // } // // public void setPort(int port) { // this.port = port; // } // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (o == null || getClass() != o.getClass()) return false; // // ApiDefinition that = (ApiDefinition) o; // // if (port != that.port) return false; // if (groupId != null ? !groupId.equals(that.groupId) : that.groupId != null) return false; // return host != null ? host.equals(that.host) : that.host == null; // } // // @Override // public int hashCode() { // int result = groupId != null ? groupId.hashCode() : 0; // result = 31 * result + (host != null ? host.hashCode() : 0); // result = 31 * result + port; // return result; // } // }
import com.github.moronicgeek.swagger.cloud.model.ApplicationRegistrationMetadata; import com.github.moronicgeek.swagger.cloud.server.ApiDefinition; import io.swagger.models.Swagger; import io.swagger.parser.SwaggerParser; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.util.Assert; import org.springframework.web.client.HttpClientErrorException; import java.util.*; import java.util.concurrent.ConcurrentHashMap;
package com.github.moronicgeek.swagger.cloud.server.registry; /** * Created by muhammedpatel on 2016/08/06. */ //TODO probably a good idea to create an interface for other stores like hazel cast and the myriad other stores. One Day!!! public class Registry { private static Logger LOGGER = LoggerFactory.getLogger(Registry.class); private ConcurrentHashMap<String, Set<ApiDefinition>> registry = new ConcurrentHashMap<>();
// Path: core/src/main/java/com/github/moronicgeek/swagger/cloud/model/ApplicationRegistrationMetadata.java // public class ApplicationRegistrationMetadata { // // // private int id; // private String name; // private String swaggerUrl; // private String groupId; // private int port; // private String host; // // public ApplicationRegistrationMetadata(String name, String swaggerUrl, String groupId, int port, String host) { // this.name = name; // this.swaggerUrl = swaggerUrl; // this.groupId = groupId; // this.port = port; // this.host = host; // } // // public ApplicationRegistrationMetadata() { // // } // // // public int getId() { // return id; // } // // public void setId(int id) { // this.id = id; // } // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // public String getSwaggerUrl() { // return swaggerUrl; // } // // public void setSwaggerUrl(String swaggerUrl) { // this.swaggerUrl = swaggerUrl; // } // // public String getGroupId() { // return groupId; // } // // public void setGroupId(String groupId) { // this.groupId = groupId; // } // // public int getPort() { // return port; // } // // public void setPort(int port) { // this.port = port; // } // // public String getHost() { // return host; // } // // public void setHost(String host) { // this.host = host; // } // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (o == null || getClass() != o.getClass()) return false; // ApplicationRegistrationMetadata metadata = (ApplicationRegistrationMetadata) o; // return id == metadata.id && // Objects.equals(name, metadata.name) && // Objects.equals(swaggerUrl, metadata.swaggerUrl) && // Objects.equals(groupId, metadata.groupId); // } // // @Override // public int hashCode() { // return Objects.hash(id, name, swaggerUrl, groupId); // } // // @Override // public String toString() { // return "ApplicationRegistrationMetadata{" + // "id=" + id + // ", name='" + name + '\'' + // ", swaggerUrl='" + swaggerUrl + '\'' + // ", groupId='" + groupId + '\'' + // '}'; // } // // // } // // Path: server/src/main/java/com/github/moronicgeek/swagger/cloud/server/ApiDefinition.java // public class ApiDefinition { // // // private String name; // private String swaggerUrl; // private String groupId; // private String description; // private String host; // private int port; // // public ApiDefinition() { // } // // public ApiDefinition(String name, String swaggerUrl, String groupId, String description, String host, int port) { // this.name = name; // this.swaggerUrl = swaggerUrl; // this.groupId = groupId; // this.description = description; // this.host = host; // this.port = port; // } // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // public String getSwaggerUrl() { // return swaggerUrl; // } // // public void setSwaggerUrl(String swaggerUrl) { // this.swaggerUrl = swaggerUrl; // } // // public String getGroupId() { // return groupId; // } // // public void setGroupId(String groupId) { // this.groupId = groupId; // } // // public String getDescription() { // return description; // } // // public void setDescription(String description) { // this.description = description; // } // // public String getHost() { // return host; // } // // public void setHost(String host) { // this.host = host; // } // // public int getPort() { // return port; // } // // public void setPort(int port) { // this.port = port; // } // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (o == null || getClass() != o.getClass()) return false; // // ApiDefinition that = (ApiDefinition) o; // // if (port != that.port) return false; // if (groupId != null ? !groupId.equals(that.groupId) : that.groupId != null) return false; // return host != null ? host.equals(that.host) : that.host == null; // } // // @Override // public int hashCode() { // int result = groupId != null ? groupId.hashCode() : 0; // result = 31 * result + (host != null ? host.hashCode() : 0); // result = 31 * result + port; // return result; // } // } // Path: server/src/main/java/com/github/moronicgeek/swagger/cloud/server/registry/Registry.java import com.github.moronicgeek.swagger.cloud.model.ApplicationRegistrationMetadata; import com.github.moronicgeek.swagger.cloud.server.ApiDefinition; import io.swagger.models.Swagger; import io.swagger.parser.SwaggerParser; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.util.Assert; import org.springframework.web.client.HttpClientErrorException; import java.util.*; import java.util.concurrent.ConcurrentHashMap; package com.github.moronicgeek.swagger.cloud.server.registry; /** * Created by muhammedpatel on 2016/08/06. */ //TODO probably a good idea to create an interface for other stores like hazel cast and the myriad other stores. One Day!!! public class Registry { private static Logger LOGGER = LoggerFactory.getLogger(Registry.class); private ConcurrentHashMap<String, Set<ApiDefinition>> registry = new ConcurrentHashMap<>();
public boolean addApi(ApplicationRegistrationMetadata metadata) {
moronicgeek/SwaggerCloud
client/src/test/java/com/github/moronicgeek/swagger/cloud/client/ApplicationRegistrationServiceTest.java
// Path: core/src/main/java/com/github/moronicgeek/swagger/cloud/model/SwaggerCloudAdminProperties.java // @ConfigurationProperties("swagger.cloud.boot.admin") // public class SwaggerCloudAdminProperties { // /** // * The admin server url to register at // */ // private String url; // // /** // * The admin rest-apis path. // */ // private String apiPath = "/swaggercloud/register/"; // // // public String getUrl() { // return url; // } // // public void setUrl(String url) { // this.url = url; // } // // public String getApiPath() { // return apiPath; // } // // public void setApiPath(String apiPath) { // this.apiPath = apiPath; // } // // // @Override // public String toString() { // return "SwaggerCloudAdminProperties{" + // "url='" + url + '\'' + // ", apiPath='" + apiPath + '\'' + // '}'; // } // } // // Path: core/src/main/java/com/github/moronicgeek/swagger/cloud/model/SwaggerCloudClientProperties.java // @ConfigurationProperties("swagger.cloud.boot.client") // public class SwaggerCloudClientProperties { // private String adminServerUrl = ""; // private String swaggerUrl = ""; // private String name = ""; // private String groupId = ""; // //TODO We should probably derive this from the swagger json file and perhaps some other data. Think !!! // private String description =""; // // @Autowired // @JsonIgnore // private ServerProperties server; // // private Integer serverPort; // // // public String getGroupId() { // return groupId; // } // // public void setGroupId(String groupId) { // this.groupId = groupId; // } // // public String getSwaggerUrl() { // return swaggerUrl; // } // // public void setSwaggerUrl(String swaggerUrl) { // this.swaggerUrl = swaggerUrl; // } // // // public String getAdminServerUrl() { // return adminServerUrl; // } // // public void setAdminServerUrl(String adminServerUrl) { // this.adminServerUrl = adminServerUrl; // } // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // public ServerProperties getServer() { // return server; // } // // public void setServer(ServerProperties server) { // this.server = server; // } // // public Integer getServerPort() { // return serverPort; // } // // public void setServerPort(Integer serverPort) { // this.serverPort = serverPort; // } // // @Override // public String toString() { // return "SwaggerCloudClientProperties{" + // "adminServerUrl='" + adminServerUrl + '\'' + // ", swaggerUrl='" + swaggerUrl + '\'' + // ", name='" + name + '\'' + // ", groupId='" + groupId + '\'' + // ", description='" + description + '\'' + // ", server=" + server + // ", serverPort=" + serverPort + // '}'; // } // }
import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.MockitoAnnotations; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import org.springframework.web.client.RestTemplate; import com.github.moronicgeek.swagger.cloud.model.SwaggerCloudAdminProperties; import com.github.moronicgeek.swagger.cloud.model.SwaggerCloudClientProperties;
package com.github.moronicgeek.swagger.cloud.client; /** * Created by muhammedpatel on 2016/08/14. */ @RunWith(SpringJUnit4ClassRunner.class) public class ApplicationRegistrationServiceTest { @InjectMocks ApplicationRegistrationService service; @Mock
// Path: core/src/main/java/com/github/moronicgeek/swagger/cloud/model/SwaggerCloudAdminProperties.java // @ConfigurationProperties("swagger.cloud.boot.admin") // public class SwaggerCloudAdminProperties { // /** // * The admin server url to register at // */ // private String url; // // /** // * The admin rest-apis path. // */ // private String apiPath = "/swaggercloud/register/"; // // // public String getUrl() { // return url; // } // // public void setUrl(String url) { // this.url = url; // } // // public String getApiPath() { // return apiPath; // } // // public void setApiPath(String apiPath) { // this.apiPath = apiPath; // } // // // @Override // public String toString() { // return "SwaggerCloudAdminProperties{" + // "url='" + url + '\'' + // ", apiPath='" + apiPath + '\'' + // '}'; // } // } // // Path: core/src/main/java/com/github/moronicgeek/swagger/cloud/model/SwaggerCloudClientProperties.java // @ConfigurationProperties("swagger.cloud.boot.client") // public class SwaggerCloudClientProperties { // private String adminServerUrl = ""; // private String swaggerUrl = ""; // private String name = ""; // private String groupId = ""; // //TODO We should probably derive this from the swagger json file and perhaps some other data. Think !!! // private String description =""; // // @Autowired // @JsonIgnore // private ServerProperties server; // // private Integer serverPort; // // // public String getGroupId() { // return groupId; // } // // public void setGroupId(String groupId) { // this.groupId = groupId; // } // // public String getSwaggerUrl() { // return swaggerUrl; // } // // public void setSwaggerUrl(String swaggerUrl) { // this.swaggerUrl = swaggerUrl; // } // // // public String getAdminServerUrl() { // return adminServerUrl; // } // // public void setAdminServerUrl(String adminServerUrl) { // this.adminServerUrl = adminServerUrl; // } // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // public ServerProperties getServer() { // return server; // } // // public void setServer(ServerProperties server) { // this.server = server; // } // // public Integer getServerPort() { // return serverPort; // } // // public void setServerPort(Integer serverPort) { // this.serverPort = serverPort; // } // // @Override // public String toString() { // return "SwaggerCloudClientProperties{" + // "adminServerUrl='" + adminServerUrl + '\'' + // ", swaggerUrl='" + swaggerUrl + '\'' + // ", name='" + name + '\'' + // ", groupId='" + groupId + '\'' + // ", description='" + description + '\'' + // ", server=" + server + // ", serverPort=" + serverPort + // '}'; // } // } // Path: client/src/test/java/com/github/moronicgeek/swagger/cloud/client/ApplicationRegistrationServiceTest.java import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.MockitoAnnotations; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import org.springframework.web.client.RestTemplate; import com.github.moronicgeek.swagger.cloud.model.SwaggerCloudAdminProperties; import com.github.moronicgeek.swagger.cloud.model.SwaggerCloudClientProperties; package com.github.moronicgeek.swagger.cloud.client; /** * Created by muhammedpatel on 2016/08/14. */ @RunWith(SpringJUnit4ClassRunner.class) public class ApplicationRegistrationServiceTest { @InjectMocks ApplicationRegistrationService service; @Mock
private SwaggerCloudAdminProperties adminProperties;
moronicgeek/SwaggerCloud
client/src/test/java/com/github/moronicgeek/swagger/cloud/client/ApplicationRegistrationServiceTest.java
// Path: core/src/main/java/com/github/moronicgeek/swagger/cloud/model/SwaggerCloudAdminProperties.java // @ConfigurationProperties("swagger.cloud.boot.admin") // public class SwaggerCloudAdminProperties { // /** // * The admin server url to register at // */ // private String url; // // /** // * The admin rest-apis path. // */ // private String apiPath = "/swaggercloud/register/"; // // // public String getUrl() { // return url; // } // // public void setUrl(String url) { // this.url = url; // } // // public String getApiPath() { // return apiPath; // } // // public void setApiPath(String apiPath) { // this.apiPath = apiPath; // } // // // @Override // public String toString() { // return "SwaggerCloudAdminProperties{" + // "url='" + url + '\'' + // ", apiPath='" + apiPath + '\'' + // '}'; // } // } // // Path: core/src/main/java/com/github/moronicgeek/swagger/cloud/model/SwaggerCloudClientProperties.java // @ConfigurationProperties("swagger.cloud.boot.client") // public class SwaggerCloudClientProperties { // private String adminServerUrl = ""; // private String swaggerUrl = ""; // private String name = ""; // private String groupId = ""; // //TODO We should probably derive this from the swagger json file and perhaps some other data. Think !!! // private String description =""; // // @Autowired // @JsonIgnore // private ServerProperties server; // // private Integer serverPort; // // // public String getGroupId() { // return groupId; // } // // public void setGroupId(String groupId) { // this.groupId = groupId; // } // // public String getSwaggerUrl() { // return swaggerUrl; // } // // public void setSwaggerUrl(String swaggerUrl) { // this.swaggerUrl = swaggerUrl; // } // // // public String getAdminServerUrl() { // return adminServerUrl; // } // // public void setAdminServerUrl(String adminServerUrl) { // this.adminServerUrl = adminServerUrl; // } // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // public ServerProperties getServer() { // return server; // } // // public void setServer(ServerProperties server) { // this.server = server; // } // // public Integer getServerPort() { // return serverPort; // } // // public void setServerPort(Integer serverPort) { // this.serverPort = serverPort; // } // // @Override // public String toString() { // return "SwaggerCloudClientProperties{" + // "adminServerUrl='" + adminServerUrl + '\'' + // ", swaggerUrl='" + swaggerUrl + '\'' + // ", name='" + name + '\'' + // ", groupId='" + groupId + '\'' + // ", description='" + description + '\'' + // ", server=" + server + // ", serverPort=" + serverPort + // '}'; // } // }
import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.MockitoAnnotations; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import org.springframework.web.client.RestTemplate; import com.github.moronicgeek.swagger.cloud.model.SwaggerCloudAdminProperties; import com.github.moronicgeek.swagger.cloud.model.SwaggerCloudClientProperties;
package com.github.moronicgeek.swagger.cloud.client; /** * Created by muhammedpatel on 2016/08/14. */ @RunWith(SpringJUnit4ClassRunner.class) public class ApplicationRegistrationServiceTest { @InjectMocks ApplicationRegistrationService service; @Mock private SwaggerCloudAdminProperties adminProperties; @Mock
// Path: core/src/main/java/com/github/moronicgeek/swagger/cloud/model/SwaggerCloudAdminProperties.java // @ConfigurationProperties("swagger.cloud.boot.admin") // public class SwaggerCloudAdminProperties { // /** // * The admin server url to register at // */ // private String url; // // /** // * The admin rest-apis path. // */ // private String apiPath = "/swaggercloud/register/"; // // // public String getUrl() { // return url; // } // // public void setUrl(String url) { // this.url = url; // } // // public String getApiPath() { // return apiPath; // } // // public void setApiPath(String apiPath) { // this.apiPath = apiPath; // } // // // @Override // public String toString() { // return "SwaggerCloudAdminProperties{" + // "url='" + url + '\'' + // ", apiPath='" + apiPath + '\'' + // '}'; // } // } // // Path: core/src/main/java/com/github/moronicgeek/swagger/cloud/model/SwaggerCloudClientProperties.java // @ConfigurationProperties("swagger.cloud.boot.client") // public class SwaggerCloudClientProperties { // private String adminServerUrl = ""; // private String swaggerUrl = ""; // private String name = ""; // private String groupId = ""; // //TODO We should probably derive this from the swagger json file and perhaps some other data. Think !!! // private String description =""; // // @Autowired // @JsonIgnore // private ServerProperties server; // // private Integer serverPort; // // // public String getGroupId() { // return groupId; // } // // public void setGroupId(String groupId) { // this.groupId = groupId; // } // // public String getSwaggerUrl() { // return swaggerUrl; // } // // public void setSwaggerUrl(String swaggerUrl) { // this.swaggerUrl = swaggerUrl; // } // // // public String getAdminServerUrl() { // return adminServerUrl; // } // // public void setAdminServerUrl(String adminServerUrl) { // this.adminServerUrl = adminServerUrl; // } // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // public ServerProperties getServer() { // return server; // } // // public void setServer(ServerProperties server) { // this.server = server; // } // // public Integer getServerPort() { // return serverPort; // } // // public void setServerPort(Integer serverPort) { // this.serverPort = serverPort; // } // // @Override // public String toString() { // return "SwaggerCloudClientProperties{" + // "adminServerUrl='" + adminServerUrl + '\'' + // ", swaggerUrl='" + swaggerUrl + '\'' + // ", name='" + name + '\'' + // ", groupId='" + groupId + '\'' + // ", description='" + description + '\'' + // ", server=" + server + // ", serverPort=" + serverPort + // '}'; // } // } // Path: client/src/test/java/com/github/moronicgeek/swagger/cloud/client/ApplicationRegistrationServiceTest.java import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.MockitoAnnotations; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import org.springframework.web.client.RestTemplate; import com.github.moronicgeek.swagger.cloud.model.SwaggerCloudAdminProperties; import com.github.moronicgeek.swagger.cloud.model.SwaggerCloudClientProperties; package com.github.moronicgeek.swagger.cloud.client; /** * Created by muhammedpatel on 2016/08/14. */ @RunWith(SpringJUnit4ClassRunner.class) public class ApplicationRegistrationServiceTest { @InjectMocks ApplicationRegistrationService service; @Mock private SwaggerCloudAdminProperties adminProperties; @Mock
private SwaggerCloudClientProperties clientProperties;
moronicgeek/SwaggerCloud
core/src/main/java/com/github/moronicgeek/swagger/cloud/rest/SwaggerCloudClientRestTemplate.java
// Path: core/src/main/java/com/github/moronicgeek/swagger/cloud/model/SwaggerCloudClientProperties.java // @ConfigurationProperties("swagger.cloud.boot.client") // public class SwaggerCloudClientProperties { // private String adminServerUrl = ""; // private String swaggerUrl = ""; // private String name = ""; // private String groupId = ""; // //TODO We should probably derive this from the swagger json file and perhaps some other data. Think !!! // private String description =""; // // @Autowired // @JsonIgnore // private ServerProperties server; // // private Integer serverPort; // // // public String getGroupId() { // return groupId; // } // // public void setGroupId(String groupId) { // this.groupId = groupId; // } // // public String getSwaggerUrl() { // return swaggerUrl; // } // // public void setSwaggerUrl(String swaggerUrl) { // this.swaggerUrl = swaggerUrl; // } // // // public String getAdminServerUrl() { // return adminServerUrl; // } // // public void setAdminServerUrl(String adminServerUrl) { // this.adminServerUrl = adminServerUrl; // } // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // public ServerProperties getServer() { // return server; // } // // public void setServer(ServerProperties server) { // this.server = server; // } // // public Integer getServerPort() { // return serverPort; // } // // public void setServerPort(Integer serverPort) { // this.serverPort = serverPort; // } // // @Override // public String toString() { // return "SwaggerCloudClientProperties{" + // "adminServerUrl='" + adminServerUrl + '\'' + // ", swaggerUrl='" + swaggerUrl + '\'' + // ", name='" + name + '\'' + // ", groupId='" + groupId + '\'' + // ", description='" + description + '\'' + // ", server=" + server + // ", serverPort=" + serverPort + // '}'; // } // }
import com.github.moronicgeek.swagger.cloud.model.SwaggerCloudClientProperties; import org.springframework.stereotype.Component; import org.springframework.web.client.RestTemplate;
package com.github.moronicgeek.swagger.cloud.rest; @Component public class SwaggerCloudClientRestTemplate { private RestTemplate restTemplate; private String resourceUrl; public SwaggerCloudClientRestTemplate(final RestTemplate restTemplate) { this.restTemplate = restTemplate; }
// Path: core/src/main/java/com/github/moronicgeek/swagger/cloud/model/SwaggerCloudClientProperties.java // @ConfigurationProperties("swagger.cloud.boot.client") // public class SwaggerCloudClientProperties { // private String adminServerUrl = ""; // private String swaggerUrl = ""; // private String name = ""; // private String groupId = ""; // //TODO We should probably derive this from the swagger json file and perhaps some other data. Think !!! // private String description =""; // // @Autowired // @JsonIgnore // private ServerProperties server; // // private Integer serverPort; // // // public String getGroupId() { // return groupId; // } // // public void setGroupId(String groupId) { // this.groupId = groupId; // } // // public String getSwaggerUrl() { // return swaggerUrl; // } // // public void setSwaggerUrl(String swaggerUrl) { // this.swaggerUrl = swaggerUrl; // } // // // public String getAdminServerUrl() { // return adminServerUrl; // } // // public void setAdminServerUrl(String adminServerUrl) { // this.adminServerUrl = adminServerUrl; // } // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // public ServerProperties getServer() { // return server; // } // // public void setServer(ServerProperties server) { // this.server = server; // } // // public Integer getServerPort() { // return serverPort; // } // // public void setServerPort(Integer serverPort) { // this.serverPort = serverPort; // } // // @Override // public String toString() { // return "SwaggerCloudClientProperties{" + // "adminServerUrl='" + adminServerUrl + '\'' + // ", swaggerUrl='" + swaggerUrl + '\'' + // ", name='" + name + '\'' + // ", groupId='" + groupId + '\'' + // ", description='" + description + '\'' + // ", server=" + server + // ", serverPort=" + serverPort + // '}'; // } // } // Path: core/src/main/java/com/github/moronicgeek/swagger/cloud/rest/SwaggerCloudClientRestTemplate.java import com.github.moronicgeek.swagger.cloud.model.SwaggerCloudClientProperties; import org.springframework.stereotype.Component; import org.springframework.web.client.RestTemplate; package com.github.moronicgeek.swagger.cloud.rest; @Component public class SwaggerCloudClientRestTemplate { private RestTemplate restTemplate; private String resourceUrl; public SwaggerCloudClientRestTemplate(final RestTemplate restTemplate) { this.restTemplate = restTemplate; }
public SwaggerCloudClientProperties getClientProperties(String resourceUrl) {
moronicgeek/SwaggerCloud
client/src/main/java/com/github/moronicgeek/swagger/cloud/client/resource/SwaggerCloudClientResource.java
// Path: core/src/main/java/com/github/moronicgeek/swagger/cloud/model/SwaggerCloudClientProperties.java // @ConfigurationProperties("swagger.cloud.boot.client") // public class SwaggerCloudClientProperties { // private String adminServerUrl = ""; // private String swaggerUrl = ""; // private String name = ""; // private String groupId = ""; // //TODO We should probably derive this from the swagger json file and perhaps some other data. Think !!! // private String description =""; // // @Autowired // @JsonIgnore // private ServerProperties server; // // private Integer serverPort; // // // public String getGroupId() { // return groupId; // } // // public void setGroupId(String groupId) { // this.groupId = groupId; // } // // public String getSwaggerUrl() { // return swaggerUrl; // } // // public void setSwaggerUrl(String swaggerUrl) { // this.swaggerUrl = swaggerUrl; // } // // // public String getAdminServerUrl() { // return adminServerUrl; // } // // public void setAdminServerUrl(String adminServerUrl) { // this.adminServerUrl = adminServerUrl; // } // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // public ServerProperties getServer() { // return server; // } // // public void setServer(ServerProperties server) { // this.server = server; // } // // public Integer getServerPort() { // return serverPort; // } // // public void setServerPort(Integer serverPort) { // this.serverPort = serverPort; // } // // @Override // public String toString() { // return "SwaggerCloudClientProperties{" + // "adminServerUrl='" + adminServerUrl + '\'' + // ", swaggerUrl='" + swaggerUrl + '\'' + // ", name='" + name + '\'' + // ", groupId='" + groupId + '\'' + // ", description='" + description + '\'' + // ", server=" + server + // ", serverPort=" + serverPort + // '}'; // } // }
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RestController; import com.github.moronicgeek.swagger.cloud.model.SwaggerCloudClientProperties;
package com.github.moronicgeek.swagger.cloud.client.resource; @RestController public class SwaggerCloudClientResource { @Autowired
// Path: core/src/main/java/com/github/moronicgeek/swagger/cloud/model/SwaggerCloudClientProperties.java // @ConfigurationProperties("swagger.cloud.boot.client") // public class SwaggerCloudClientProperties { // private String adminServerUrl = ""; // private String swaggerUrl = ""; // private String name = ""; // private String groupId = ""; // //TODO We should probably derive this from the swagger json file and perhaps some other data. Think !!! // private String description =""; // // @Autowired // @JsonIgnore // private ServerProperties server; // // private Integer serverPort; // // // public String getGroupId() { // return groupId; // } // // public void setGroupId(String groupId) { // this.groupId = groupId; // } // // public String getSwaggerUrl() { // return swaggerUrl; // } // // public void setSwaggerUrl(String swaggerUrl) { // this.swaggerUrl = swaggerUrl; // } // // // public String getAdminServerUrl() { // return adminServerUrl; // } // // public void setAdminServerUrl(String adminServerUrl) { // this.adminServerUrl = adminServerUrl; // } // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // public ServerProperties getServer() { // return server; // } // // public void setServer(ServerProperties server) { // this.server = server; // } // // public Integer getServerPort() { // return serverPort; // } // // public void setServerPort(Integer serverPort) { // this.serverPort = serverPort; // } // // @Override // public String toString() { // return "SwaggerCloudClientProperties{" + // "adminServerUrl='" + adminServerUrl + '\'' + // ", swaggerUrl='" + swaggerUrl + '\'' + // ", name='" + name + '\'' + // ", groupId='" + groupId + '\'' + // ", description='" + description + '\'' + // ", server=" + server + // ", serverPort=" + serverPort + // '}'; // } // } // Path: client/src/main/java/com/github/moronicgeek/swagger/cloud/client/resource/SwaggerCloudClientResource.java import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RestController; import com.github.moronicgeek.swagger.cloud.model.SwaggerCloudClientProperties; package com.github.moronicgeek.swagger.cloud.client.resource; @RestController public class SwaggerCloudClientResource { @Autowired
private SwaggerCloudClientProperties properties;
msdx/AndroidPNClient
androidpn/src/main/java/org/apache/harmony/javax/security/sasl/SaslServerFactory.java
// Path: androidpn/src/main/java/org/apache/harmony/javax/security/auth/callback/CallbackHandler.java // public interface CallbackHandler { // // /** // * Handles the actual {@link org.apache.harmony.javax.security.auth.callback.Callback}. A {@code CallbackHandler} needs to // * implement this method. In the method, it is free to select which {@code // * Callback}s it actually wants to handle and in which way. For example, a // * console-based {@code CallbackHandler} might choose to sequentially ask // * the user for login and password, if it implements these {@code Callback} // * s, whereas a GUI-based one might open a single dialog window for both // * values. If a {@code CallbackHandler} is not able to handle a specific // * {@code Callback}, it needs to throw an // * {@link UnsupportedCallbackException}. // * // * @param callbacks // * the array of {@code Callback}s that need handling // * @throws java.io.IOException // * if an I/O related error occurs // * @throws UnsupportedCallbackException // * if the {@code CallbackHandler} is not able to handle a // * specific {@code Callback} // */ // void handle(Callback[] callbacks) throws IOException, UnsupportedCallbackException; // // }
import java.util.Map; import org.apache.harmony.javax.security.auth.callback.CallbackHandler;
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.harmony.javax.security.sasl; public interface SaslServerFactory { SaslServer createSaslServer(String mechanisms, String protocol, String serverName,
// Path: androidpn/src/main/java/org/apache/harmony/javax/security/auth/callback/CallbackHandler.java // public interface CallbackHandler { // // /** // * Handles the actual {@link org.apache.harmony.javax.security.auth.callback.Callback}. A {@code CallbackHandler} needs to // * implement this method. In the method, it is free to select which {@code // * Callback}s it actually wants to handle and in which way. For example, a // * console-based {@code CallbackHandler} might choose to sequentially ask // * the user for login and password, if it implements these {@code Callback} // * s, whereas a GUI-based one might open a single dialog window for both // * values. If a {@code CallbackHandler} is not able to handle a specific // * {@code Callback}, it needs to throw an // * {@link UnsupportedCallbackException}. // * // * @param callbacks // * the array of {@code Callback}s that need handling // * @throws java.io.IOException // * if an I/O related error occurs // * @throws UnsupportedCallbackException // * if the {@code CallbackHandler} is not able to handle a // * specific {@code Callback} // */ // void handle(Callback[] callbacks) throws IOException, UnsupportedCallbackException; // // } // Path: androidpn/src/main/java/org/apache/harmony/javax/security/sasl/SaslServerFactory.java import java.util.Map; import org.apache.harmony.javax.security.auth.callback.CallbackHandler; /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.harmony.javax.security.sasl; public interface SaslServerFactory { SaslServer createSaslServer(String mechanisms, String protocol, String serverName,
Map<String, ?> props, CallbackHandler cbh) throws SaslException;
msdx/AndroidPNClient
androidpn/src/main/java/org/androidpn/client/NotificationReceiver.java
// Path: androidpn/src/main/java/com/githang/android/apnbb/Constants.java // public class Constants { // // // PROPERTY // public static final String PROP_FILE_NAME = "androidpn"; // // // PROPERTY KEYS // // public static final String PROP_API_KEY = "apiKey"; // public static final String PROP_XMPP_HOST = "xmppHost"; // public static final String PROP_XMPP_PORT = "xmppPort"; // public static final String PROP_PACKET_LISTENER = "packetListener"; // public static final String PROP_IQ = "iq"; // public static final String PROP_IQ_PROVIDER = "iqProvider"; // public static final String PROP_NOTIFY_ACTIVITY= "notifyActivity"; // // // PROPERTY DEFAULT VALUES // // public static final String DEFAULT_HOST = "127.0.0.1"; // public static final String DEFAULT_PORT = "5222"; // // // // PREFERENCE // public static final String SHARED_PREFERENCE_NAME = "client_preferences"; // // // PREFERENCE KEYS // // public static final String CALLBACK_ACTIVITY_PACKAGE_NAME = "CALLBACK_ACTIVITY_PACKAGE_NAME"; // // public static final String CALLBACK_ACTIVITY_CLASS_NAME = "CALLBACK_ACTIVITY_CLASS_NAME"; // // public static final String API_KEY = "API_KEY"; // // public static final String VERSION = "VERSION"; // // public static final String XMPP_HOST = "XMPP_HOST"; // // public static final String XMPP_PORT = "XMPP_PORT"; // // public static final String XMPP_USERNAME = "XMPP_USERNAME"; // // public static final String XMPP_PASSWORD = "XMPP_PASSWORD"; // // public static final String DEVICE_ID = "DEVICE_ID"; // // public static final String EMULATOR_DEVICE_ID = "EMULATOR_DEVICE_ID"; // // public static final String NOTIFICATION_ICON = "NOTIFICATION_ICON"; // // public static final String SETTINGS_NOTIFICATION_ENABLED = "SETTINGS_NOTIFICATION_ENABLED"; // // public static final String SETTINGS_SOUND_ENABLED = "SETTINGS_SOUND_ENABLED"; // // public static final String SETTINGS_VIBRATE_ENABLED = "SETTINGS_VIBRATE_ENABLED"; // // public static final String SETTINGS_TOAST_ENABLED = "SETTINGS_TOAST_ENABLED"; // // // NOTIFICATION FIELDS // // public static final String NOTIFICATION_ID = "NOTIFICATION_ID"; // // public static final String NOTIFICATION_API_KEY = "NOTIFICATION_API_KEY"; // // public static final String NOTIFICATION_TITLE = "NOTIFICATION_TITLE"; // // public static final String NOTIFICATION_MESSAGE = "NOTIFICATION_MESSAGE"; // // public static final String NOTIFICATION_URI = "NOTIFICATION_URI"; // // public static final String PACKET_ID = "PACKET_ID"; // // // // INTENT ACTIONS // // public static final String ACTION_SHOW_NOTIFICATION = "org.androidpn.client.SHOW_NOTIFICATION"; // // public static final String ACTION_NOTIFICATION_CLICKED = "org.androidpn.client.NOTIFICATION_CLICKED"; // // public static final String ACTION_NOTIFICATION_CLEARED = "org.androidpn.client.NOTIFICATION_CLEARED"; // // // INTENT_EXTRA // public static final String INTENT_EXTRA_IQ = "INTENT_IQ"; // // // NAMESPACE // public static final String DEFAULT_NAMESPACE = "androidpn:iq:notification"; // // ELEMENT_NAME // public static final String ELEMENT_NAME = "notification"; // // }
import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.util.Log; import com.githang.android.apnbb.Constants;
/* * Copyright (C) 2010 Moduad Co., Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.androidpn.client; /** * Broadcast receiver that handles push notification messages from the server. * This should be registered as receiver in AndroidManifest.xml. * * @author Sehwan Noh (devnoh@gmail.com) */ public final class NotificationReceiver extends BroadcastReceiver { private static final String LOGTAG = LogUtil .makeLogTag(NotificationReceiver.class); public NotificationReceiver() { } @Override public void onReceive(Context context, Intent intent) { Log.d(LOGTAG, "NotificationReceiver.onReceive()..."); String action = intent.getAction(); Log.d(LOGTAG, "action=" + action);
// Path: androidpn/src/main/java/com/githang/android/apnbb/Constants.java // public class Constants { // // // PROPERTY // public static final String PROP_FILE_NAME = "androidpn"; // // // PROPERTY KEYS // // public static final String PROP_API_KEY = "apiKey"; // public static final String PROP_XMPP_HOST = "xmppHost"; // public static final String PROP_XMPP_PORT = "xmppPort"; // public static final String PROP_PACKET_LISTENER = "packetListener"; // public static final String PROP_IQ = "iq"; // public static final String PROP_IQ_PROVIDER = "iqProvider"; // public static final String PROP_NOTIFY_ACTIVITY= "notifyActivity"; // // // PROPERTY DEFAULT VALUES // // public static final String DEFAULT_HOST = "127.0.0.1"; // public static final String DEFAULT_PORT = "5222"; // // // // PREFERENCE // public static final String SHARED_PREFERENCE_NAME = "client_preferences"; // // // PREFERENCE KEYS // // public static final String CALLBACK_ACTIVITY_PACKAGE_NAME = "CALLBACK_ACTIVITY_PACKAGE_NAME"; // // public static final String CALLBACK_ACTIVITY_CLASS_NAME = "CALLBACK_ACTIVITY_CLASS_NAME"; // // public static final String API_KEY = "API_KEY"; // // public static final String VERSION = "VERSION"; // // public static final String XMPP_HOST = "XMPP_HOST"; // // public static final String XMPP_PORT = "XMPP_PORT"; // // public static final String XMPP_USERNAME = "XMPP_USERNAME"; // // public static final String XMPP_PASSWORD = "XMPP_PASSWORD"; // // public static final String DEVICE_ID = "DEVICE_ID"; // // public static final String EMULATOR_DEVICE_ID = "EMULATOR_DEVICE_ID"; // // public static final String NOTIFICATION_ICON = "NOTIFICATION_ICON"; // // public static final String SETTINGS_NOTIFICATION_ENABLED = "SETTINGS_NOTIFICATION_ENABLED"; // // public static final String SETTINGS_SOUND_ENABLED = "SETTINGS_SOUND_ENABLED"; // // public static final String SETTINGS_VIBRATE_ENABLED = "SETTINGS_VIBRATE_ENABLED"; // // public static final String SETTINGS_TOAST_ENABLED = "SETTINGS_TOAST_ENABLED"; // // // NOTIFICATION FIELDS // // public static final String NOTIFICATION_ID = "NOTIFICATION_ID"; // // public static final String NOTIFICATION_API_KEY = "NOTIFICATION_API_KEY"; // // public static final String NOTIFICATION_TITLE = "NOTIFICATION_TITLE"; // // public static final String NOTIFICATION_MESSAGE = "NOTIFICATION_MESSAGE"; // // public static final String NOTIFICATION_URI = "NOTIFICATION_URI"; // // public static final String PACKET_ID = "PACKET_ID"; // // // // INTENT ACTIONS // // public static final String ACTION_SHOW_NOTIFICATION = "org.androidpn.client.SHOW_NOTIFICATION"; // // public static final String ACTION_NOTIFICATION_CLICKED = "org.androidpn.client.NOTIFICATION_CLICKED"; // // public static final String ACTION_NOTIFICATION_CLEARED = "org.androidpn.client.NOTIFICATION_CLEARED"; // // // INTENT_EXTRA // public static final String INTENT_EXTRA_IQ = "INTENT_IQ"; // // // NAMESPACE // public static final String DEFAULT_NAMESPACE = "androidpn:iq:notification"; // // ELEMENT_NAME // public static final String ELEMENT_NAME = "notification"; // // } // Path: androidpn/src/main/java/org/androidpn/client/NotificationReceiver.java import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.util.Log; import com.githang.android.apnbb.Constants; /* * Copyright (C) 2010 Moduad Co., Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.androidpn.client; /** * Broadcast receiver that handles push notification messages from the server. * This should be registered as receiver in AndroidManifest.xml. * * @author Sehwan Noh (devnoh@gmail.com) */ public final class NotificationReceiver extends BroadcastReceiver { private static final String LOGTAG = LogUtil .makeLogTag(NotificationReceiver.class); public NotificationReceiver() { } @Override public void onReceive(Context context, Intent intent) { Log.d(LOGTAG, "NotificationReceiver.onReceive()..."); String action = intent.getAction(); Log.d(LOGTAG, "action=" + action);
if (Constants.ACTION_SHOW_NOTIFICATION.equals(action)) {
msdx/AndroidPNClient
demo/src/main/java/com/githang/android/apnbb/demo/db/DBIQOperator.java
// Path: demo/src/main/java/com/githang/android/apnbb/demo/notify/NotifyIQ.java // public class NotifyIQ extends IQ implements Serializable{ // // private static final long serialVersionUID = 123123151L; // // private String id; // // private String apiKey; // // private String title; // // private String message; // // private String uri; // // private String time; // // // @Override // public String getChildElementXML() { // StringBuilder buf = new StringBuilder(); // buf.append("<").append("notification").append(" xmlns=\"").append( // Constants.DEFAULT_NAMESPACE).append("\">"); // if (id != null) { // buf.append("<id>").append(id).append("</id>"); // } // buf.append("</").append("notification").append("> "); // return buf.toString(); // } // // public String getId() { // return id; // } // // public void setId(String id) { // this.id = id; // } // // public String getApiKey() { // return apiKey; // } // // public void setApiKey(String apiKey) { // this.apiKey = apiKey; // } // // public String getTitle() { // return title; // } // // public void setTitle(String title) { // this.title = title; // } // // public String getMessage() { // return message; // } // // public void setMessage(String message) { // this.message = message; // } // // public String getUri() { // return uri; // } // // public void setUri(String uri) { // this.uri = uri; // } // // public String getTime() { // return time; // } // // public void setTime(String time) { // this.time = time; // } // // @Override // public String toString() { // return "NotifyIQ{" + // "time='" + time + '\'' + // ", uri='" + uri + '\'' + // ", message='" + message + '\'' + // ", title='" + title + '\'' + // ", apiKey='" + apiKey + '\'' + // ", id='" + id + '\'' + // '}'; // } // }
import android.content.ContentValues; import android.content.Context; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.util.Log; import org.androidpn.client.LogUtil; import java.util.ArrayList; import java.util.List; import com.githang.android.apnbb.demo.notify.NotifyIQ;
package com.githang.android.apnbb.demo.db; /** * User: Geek_Soledad(msdx.android@qq.com) * Date: 2014-03-26 * Time: 13:25 * 数据库操作类。 */ public class DBIQOperator { private static final String LOG_TAG = LogUtil.makeLogTag(DBIQOperator.class); private DBOpenHelper dbOpenHelper; private SQLiteDatabase dbReader; public DBIQOperator(Context context) { dbOpenHelper = new DBOpenHelper(context); }
// Path: demo/src/main/java/com/githang/android/apnbb/demo/notify/NotifyIQ.java // public class NotifyIQ extends IQ implements Serializable{ // // private static final long serialVersionUID = 123123151L; // // private String id; // // private String apiKey; // // private String title; // // private String message; // // private String uri; // // private String time; // // // @Override // public String getChildElementXML() { // StringBuilder buf = new StringBuilder(); // buf.append("<").append("notification").append(" xmlns=\"").append( // Constants.DEFAULT_NAMESPACE).append("\">"); // if (id != null) { // buf.append("<id>").append(id).append("</id>"); // } // buf.append("</").append("notification").append("> "); // return buf.toString(); // } // // public String getId() { // return id; // } // // public void setId(String id) { // this.id = id; // } // // public String getApiKey() { // return apiKey; // } // // public void setApiKey(String apiKey) { // this.apiKey = apiKey; // } // // public String getTitle() { // return title; // } // // public void setTitle(String title) { // this.title = title; // } // // public String getMessage() { // return message; // } // // public void setMessage(String message) { // this.message = message; // } // // public String getUri() { // return uri; // } // // public void setUri(String uri) { // this.uri = uri; // } // // public String getTime() { // return time; // } // // public void setTime(String time) { // this.time = time; // } // // @Override // public String toString() { // return "NotifyIQ{" + // "time='" + time + '\'' + // ", uri='" + uri + '\'' + // ", message='" + message + '\'' + // ", title='" + title + '\'' + // ", apiKey='" + apiKey + '\'' + // ", id='" + id + '\'' + // '}'; // } // } // Path: demo/src/main/java/com/githang/android/apnbb/demo/db/DBIQOperator.java import android.content.ContentValues; import android.content.Context; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.util.Log; import org.androidpn.client.LogUtil; import java.util.ArrayList; import java.util.List; import com.githang.android.apnbb.demo.notify.NotifyIQ; package com.githang.android.apnbb.demo.db; /** * User: Geek_Soledad(msdx.android@qq.com) * Date: 2014-03-26 * Time: 13:25 * 数据库操作类。 */ public class DBIQOperator { private static final String LOG_TAG = LogUtil.makeLogTag(DBIQOperator.class); private DBOpenHelper dbOpenHelper; private SQLiteDatabase dbReader; public DBIQOperator(Context context) { dbOpenHelper = new DBOpenHelper(context); }
public void saveIQ(NotifyIQ iq) {
msdx/AndroidPNClient
demo/src/main/java/com/githang/android/apnbb/demo/notify/NotifySettingsActivity.java
// Path: androidpn/src/main/java/com/githang/android/apnbb/Constants.java // public class Constants { // // // PROPERTY // public static final String PROP_FILE_NAME = "androidpn"; // // // PROPERTY KEYS // // public static final String PROP_API_KEY = "apiKey"; // public static final String PROP_XMPP_HOST = "xmppHost"; // public static final String PROP_XMPP_PORT = "xmppPort"; // public static final String PROP_PACKET_LISTENER = "packetListener"; // public static final String PROP_IQ = "iq"; // public static final String PROP_IQ_PROVIDER = "iqProvider"; // public static final String PROP_NOTIFY_ACTIVITY= "notifyActivity"; // // // PROPERTY DEFAULT VALUES // // public static final String DEFAULT_HOST = "127.0.0.1"; // public static final String DEFAULT_PORT = "5222"; // // // // PREFERENCE // public static final String SHARED_PREFERENCE_NAME = "client_preferences"; // // // PREFERENCE KEYS // // public static final String CALLBACK_ACTIVITY_PACKAGE_NAME = "CALLBACK_ACTIVITY_PACKAGE_NAME"; // // public static final String CALLBACK_ACTIVITY_CLASS_NAME = "CALLBACK_ACTIVITY_CLASS_NAME"; // // public static final String API_KEY = "API_KEY"; // // public static final String VERSION = "VERSION"; // // public static final String XMPP_HOST = "XMPP_HOST"; // // public static final String XMPP_PORT = "XMPP_PORT"; // // public static final String XMPP_USERNAME = "XMPP_USERNAME"; // // public static final String XMPP_PASSWORD = "XMPP_PASSWORD"; // // public static final String DEVICE_ID = "DEVICE_ID"; // // public static final String EMULATOR_DEVICE_ID = "EMULATOR_DEVICE_ID"; // // public static final String NOTIFICATION_ICON = "NOTIFICATION_ICON"; // // public static final String SETTINGS_NOTIFICATION_ENABLED = "SETTINGS_NOTIFICATION_ENABLED"; // // public static final String SETTINGS_SOUND_ENABLED = "SETTINGS_SOUND_ENABLED"; // // public static final String SETTINGS_VIBRATE_ENABLED = "SETTINGS_VIBRATE_ENABLED"; // // public static final String SETTINGS_TOAST_ENABLED = "SETTINGS_TOAST_ENABLED"; // // // NOTIFICATION FIELDS // // public static final String NOTIFICATION_ID = "NOTIFICATION_ID"; // // public static final String NOTIFICATION_API_KEY = "NOTIFICATION_API_KEY"; // // public static final String NOTIFICATION_TITLE = "NOTIFICATION_TITLE"; // // public static final String NOTIFICATION_MESSAGE = "NOTIFICATION_MESSAGE"; // // public static final String NOTIFICATION_URI = "NOTIFICATION_URI"; // // public static final String PACKET_ID = "PACKET_ID"; // // // // INTENT ACTIONS // // public static final String ACTION_SHOW_NOTIFICATION = "org.androidpn.client.SHOW_NOTIFICATION"; // // public static final String ACTION_NOTIFICATION_CLICKED = "org.androidpn.client.NOTIFICATION_CLICKED"; // // public static final String ACTION_NOTIFICATION_CLEARED = "org.androidpn.client.NOTIFICATION_CLEARED"; // // // INTENT_EXTRA // public static final String INTENT_EXTRA_IQ = "INTENT_IQ"; // // // NAMESPACE // public static final String DEFAULT_NAMESPACE = "androidpn:iq:notification"; // // ELEMENT_NAME // public static final String ELEMENT_NAME = "notification"; // // }
import android.content.Context; import android.os.Bundle; import android.preference.CheckBoxPreference; import android.preference.Preference; import android.preference.PreferenceActivity; import android.preference.PreferenceManager; import android.preference.PreferenceScreen; import android.util.Log; import com.githang.android.apnbb.Constants; import com.githang.android.apnbb.demo.R; import org.androidpn.client.LogUtil;
/* * Copyright 2010 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.githang.android.apnbb.demo.notify; /** * Activity for displaying the notification setting view. * * @author GeekSoledad (msdx.android@qq.com) */ public class NotifySettingsActivity extends PreferenceActivity { private static final String LOGTAG = LogUtil .makeLogTag(NotifySettingsActivity.class); public NotifySettingsActivity() { } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setPreferenceScreen(createPreferenceHierarchy()); setPreferenceDependencies(); CheckBoxPreference notifyPref = (CheckBoxPreference) getPreferenceManager()
// Path: androidpn/src/main/java/com/githang/android/apnbb/Constants.java // public class Constants { // // // PROPERTY // public static final String PROP_FILE_NAME = "androidpn"; // // // PROPERTY KEYS // // public static final String PROP_API_KEY = "apiKey"; // public static final String PROP_XMPP_HOST = "xmppHost"; // public static final String PROP_XMPP_PORT = "xmppPort"; // public static final String PROP_PACKET_LISTENER = "packetListener"; // public static final String PROP_IQ = "iq"; // public static final String PROP_IQ_PROVIDER = "iqProvider"; // public static final String PROP_NOTIFY_ACTIVITY= "notifyActivity"; // // // PROPERTY DEFAULT VALUES // // public static final String DEFAULT_HOST = "127.0.0.1"; // public static final String DEFAULT_PORT = "5222"; // // // // PREFERENCE // public static final String SHARED_PREFERENCE_NAME = "client_preferences"; // // // PREFERENCE KEYS // // public static final String CALLBACK_ACTIVITY_PACKAGE_NAME = "CALLBACK_ACTIVITY_PACKAGE_NAME"; // // public static final String CALLBACK_ACTIVITY_CLASS_NAME = "CALLBACK_ACTIVITY_CLASS_NAME"; // // public static final String API_KEY = "API_KEY"; // // public static final String VERSION = "VERSION"; // // public static final String XMPP_HOST = "XMPP_HOST"; // // public static final String XMPP_PORT = "XMPP_PORT"; // // public static final String XMPP_USERNAME = "XMPP_USERNAME"; // // public static final String XMPP_PASSWORD = "XMPP_PASSWORD"; // // public static final String DEVICE_ID = "DEVICE_ID"; // // public static final String EMULATOR_DEVICE_ID = "EMULATOR_DEVICE_ID"; // // public static final String NOTIFICATION_ICON = "NOTIFICATION_ICON"; // // public static final String SETTINGS_NOTIFICATION_ENABLED = "SETTINGS_NOTIFICATION_ENABLED"; // // public static final String SETTINGS_SOUND_ENABLED = "SETTINGS_SOUND_ENABLED"; // // public static final String SETTINGS_VIBRATE_ENABLED = "SETTINGS_VIBRATE_ENABLED"; // // public static final String SETTINGS_TOAST_ENABLED = "SETTINGS_TOAST_ENABLED"; // // // NOTIFICATION FIELDS // // public static final String NOTIFICATION_ID = "NOTIFICATION_ID"; // // public static final String NOTIFICATION_API_KEY = "NOTIFICATION_API_KEY"; // // public static final String NOTIFICATION_TITLE = "NOTIFICATION_TITLE"; // // public static final String NOTIFICATION_MESSAGE = "NOTIFICATION_MESSAGE"; // // public static final String NOTIFICATION_URI = "NOTIFICATION_URI"; // // public static final String PACKET_ID = "PACKET_ID"; // // // // INTENT ACTIONS // // public static final String ACTION_SHOW_NOTIFICATION = "org.androidpn.client.SHOW_NOTIFICATION"; // // public static final String ACTION_NOTIFICATION_CLICKED = "org.androidpn.client.NOTIFICATION_CLICKED"; // // public static final String ACTION_NOTIFICATION_CLEARED = "org.androidpn.client.NOTIFICATION_CLEARED"; // // // INTENT_EXTRA // public static final String INTENT_EXTRA_IQ = "INTENT_IQ"; // // // NAMESPACE // public static final String DEFAULT_NAMESPACE = "androidpn:iq:notification"; // // ELEMENT_NAME // public static final String ELEMENT_NAME = "notification"; // // } // Path: demo/src/main/java/com/githang/android/apnbb/demo/notify/NotifySettingsActivity.java import android.content.Context; import android.os.Bundle; import android.preference.CheckBoxPreference; import android.preference.Preference; import android.preference.PreferenceActivity; import android.preference.PreferenceManager; import android.preference.PreferenceScreen; import android.util.Log; import com.githang.android.apnbb.Constants; import com.githang.android.apnbb.demo.R; import org.androidpn.client.LogUtil; /* * Copyright 2010 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.githang.android.apnbb.demo.notify; /** * Activity for displaying the notification setting view. * * @author GeekSoledad (msdx.android@qq.com) */ public class NotifySettingsActivity extends PreferenceActivity { private static final String LOGTAG = LogUtil .makeLogTag(NotifySettingsActivity.class); public NotifySettingsActivity() { } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setPreferenceScreen(createPreferenceHierarchy()); setPreferenceDependencies(); CheckBoxPreference notifyPref = (CheckBoxPreference) getPreferenceManager()
.findPreference(Constants.SETTINGS_NOTIFICATION_ENABLED);
msdx/AndroidPNClient
androidpn/src/main/java/org/androidpn/client/NotificationSettingsActivity.java
// Path: androidpn/src/main/java/com/githang/android/apnbb/Constants.java // public class Constants { // // // PROPERTY // public static final String PROP_FILE_NAME = "androidpn"; // // // PROPERTY KEYS // // public static final String PROP_API_KEY = "apiKey"; // public static final String PROP_XMPP_HOST = "xmppHost"; // public static final String PROP_XMPP_PORT = "xmppPort"; // public static final String PROP_PACKET_LISTENER = "packetListener"; // public static final String PROP_IQ = "iq"; // public static final String PROP_IQ_PROVIDER = "iqProvider"; // public static final String PROP_NOTIFY_ACTIVITY= "notifyActivity"; // // // PROPERTY DEFAULT VALUES // // public static final String DEFAULT_HOST = "127.0.0.1"; // public static final String DEFAULT_PORT = "5222"; // // // // PREFERENCE // public static final String SHARED_PREFERENCE_NAME = "client_preferences"; // // // PREFERENCE KEYS // // public static final String CALLBACK_ACTIVITY_PACKAGE_NAME = "CALLBACK_ACTIVITY_PACKAGE_NAME"; // // public static final String CALLBACK_ACTIVITY_CLASS_NAME = "CALLBACK_ACTIVITY_CLASS_NAME"; // // public static final String API_KEY = "API_KEY"; // // public static final String VERSION = "VERSION"; // // public static final String XMPP_HOST = "XMPP_HOST"; // // public static final String XMPP_PORT = "XMPP_PORT"; // // public static final String XMPP_USERNAME = "XMPP_USERNAME"; // // public static final String XMPP_PASSWORD = "XMPP_PASSWORD"; // // public static final String DEVICE_ID = "DEVICE_ID"; // // public static final String EMULATOR_DEVICE_ID = "EMULATOR_DEVICE_ID"; // // public static final String NOTIFICATION_ICON = "NOTIFICATION_ICON"; // // public static final String SETTINGS_NOTIFICATION_ENABLED = "SETTINGS_NOTIFICATION_ENABLED"; // // public static final String SETTINGS_SOUND_ENABLED = "SETTINGS_SOUND_ENABLED"; // // public static final String SETTINGS_VIBRATE_ENABLED = "SETTINGS_VIBRATE_ENABLED"; // // public static final String SETTINGS_TOAST_ENABLED = "SETTINGS_TOAST_ENABLED"; // // // NOTIFICATION FIELDS // // public static final String NOTIFICATION_ID = "NOTIFICATION_ID"; // // public static final String NOTIFICATION_API_KEY = "NOTIFICATION_API_KEY"; // // public static final String NOTIFICATION_TITLE = "NOTIFICATION_TITLE"; // // public static final String NOTIFICATION_MESSAGE = "NOTIFICATION_MESSAGE"; // // public static final String NOTIFICATION_URI = "NOTIFICATION_URI"; // // public static final String PACKET_ID = "PACKET_ID"; // // // // INTENT ACTIONS // // public static final String ACTION_SHOW_NOTIFICATION = "org.androidpn.client.SHOW_NOTIFICATION"; // // public static final String ACTION_NOTIFICATION_CLICKED = "org.androidpn.client.NOTIFICATION_CLICKED"; // // public static final String ACTION_NOTIFICATION_CLEARED = "org.androidpn.client.NOTIFICATION_CLEARED"; // // // INTENT_EXTRA // public static final String INTENT_EXTRA_IQ = "INTENT_IQ"; // // // NAMESPACE // public static final String DEFAULT_NAMESPACE = "androidpn:iq:notification"; // // ELEMENT_NAME // public static final String ELEMENT_NAME = "notification"; // // }
import android.content.Context; import android.os.Bundle; import android.preference.CheckBoxPreference; import android.preference.Preference; import android.preference.PreferenceActivity; import android.preference.PreferenceManager; import android.preference.PreferenceScreen; import android.util.Log; import com.githang.android.apnbb.Constants;
/* * Copyright 2010 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.androidpn.client; /** * Activity for displaying the notification setting view. * * @author Sehwan Noh (devnoh@gmail.com) */ public class NotificationSettingsActivity extends PreferenceActivity { private static final String LOGTAG = LogUtil .makeLogTag(NotificationSettingsActivity.class); public NotificationSettingsActivity() { } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setPreferenceScreen(createPreferenceHierarchy()); setPreferenceDependencies(); CheckBoxPreference notifyPref = (CheckBoxPreference) getPreferenceManager()
// Path: androidpn/src/main/java/com/githang/android/apnbb/Constants.java // public class Constants { // // // PROPERTY // public static final String PROP_FILE_NAME = "androidpn"; // // // PROPERTY KEYS // // public static final String PROP_API_KEY = "apiKey"; // public static final String PROP_XMPP_HOST = "xmppHost"; // public static final String PROP_XMPP_PORT = "xmppPort"; // public static final String PROP_PACKET_LISTENER = "packetListener"; // public static final String PROP_IQ = "iq"; // public static final String PROP_IQ_PROVIDER = "iqProvider"; // public static final String PROP_NOTIFY_ACTIVITY= "notifyActivity"; // // // PROPERTY DEFAULT VALUES // // public static final String DEFAULT_HOST = "127.0.0.1"; // public static final String DEFAULT_PORT = "5222"; // // // // PREFERENCE // public static final String SHARED_PREFERENCE_NAME = "client_preferences"; // // // PREFERENCE KEYS // // public static final String CALLBACK_ACTIVITY_PACKAGE_NAME = "CALLBACK_ACTIVITY_PACKAGE_NAME"; // // public static final String CALLBACK_ACTIVITY_CLASS_NAME = "CALLBACK_ACTIVITY_CLASS_NAME"; // // public static final String API_KEY = "API_KEY"; // // public static final String VERSION = "VERSION"; // // public static final String XMPP_HOST = "XMPP_HOST"; // // public static final String XMPP_PORT = "XMPP_PORT"; // // public static final String XMPP_USERNAME = "XMPP_USERNAME"; // // public static final String XMPP_PASSWORD = "XMPP_PASSWORD"; // // public static final String DEVICE_ID = "DEVICE_ID"; // // public static final String EMULATOR_DEVICE_ID = "EMULATOR_DEVICE_ID"; // // public static final String NOTIFICATION_ICON = "NOTIFICATION_ICON"; // // public static final String SETTINGS_NOTIFICATION_ENABLED = "SETTINGS_NOTIFICATION_ENABLED"; // // public static final String SETTINGS_SOUND_ENABLED = "SETTINGS_SOUND_ENABLED"; // // public static final String SETTINGS_VIBRATE_ENABLED = "SETTINGS_VIBRATE_ENABLED"; // // public static final String SETTINGS_TOAST_ENABLED = "SETTINGS_TOAST_ENABLED"; // // // NOTIFICATION FIELDS // // public static final String NOTIFICATION_ID = "NOTIFICATION_ID"; // // public static final String NOTIFICATION_API_KEY = "NOTIFICATION_API_KEY"; // // public static final String NOTIFICATION_TITLE = "NOTIFICATION_TITLE"; // // public static final String NOTIFICATION_MESSAGE = "NOTIFICATION_MESSAGE"; // // public static final String NOTIFICATION_URI = "NOTIFICATION_URI"; // // public static final String PACKET_ID = "PACKET_ID"; // // // // INTENT ACTIONS // // public static final String ACTION_SHOW_NOTIFICATION = "org.androidpn.client.SHOW_NOTIFICATION"; // // public static final String ACTION_NOTIFICATION_CLICKED = "org.androidpn.client.NOTIFICATION_CLICKED"; // // public static final String ACTION_NOTIFICATION_CLEARED = "org.androidpn.client.NOTIFICATION_CLEARED"; // // // INTENT_EXTRA // public static final String INTENT_EXTRA_IQ = "INTENT_IQ"; // // // NAMESPACE // public static final String DEFAULT_NAMESPACE = "androidpn:iq:notification"; // // ELEMENT_NAME // public static final String ELEMENT_NAME = "notification"; // // } // Path: androidpn/src/main/java/org/androidpn/client/NotificationSettingsActivity.java import android.content.Context; import android.os.Bundle; import android.preference.CheckBoxPreference; import android.preference.Preference; import android.preference.PreferenceActivity; import android.preference.PreferenceManager; import android.preference.PreferenceScreen; import android.util.Log; import com.githang.android.apnbb.Constants; /* * Copyright 2010 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.androidpn.client; /** * Activity for displaying the notification setting view. * * @author Sehwan Noh (devnoh@gmail.com) */ public class NotificationSettingsActivity extends PreferenceActivity { private static final String LOGTAG = LogUtil .makeLogTag(NotificationSettingsActivity.class); public NotificationSettingsActivity() { } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setPreferenceScreen(createPreferenceHierarchy()); setPreferenceDependencies(); CheckBoxPreference notifyPref = (CheckBoxPreference) getPreferenceManager()
.findPreference(Constants.SETTINGS_NOTIFICATION_ENABLED);
msdx/AndroidPNClient
demo/src/main/java/com/githang/android/apnbb/demo/notify/NotifyDetailActivity.java
// Path: androidpn/src/main/java/com/githang/android/apnbb/Constants.java // public class Constants { // // // PROPERTY // public static final String PROP_FILE_NAME = "androidpn"; // // // PROPERTY KEYS // // public static final String PROP_API_KEY = "apiKey"; // public static final String PROP_XMPP_HOST = "xmppHost"; // public static final String PROP_XMPP_PORT = "xmppPort"; // public static final String PROP_PACKET_LISTENER = "packetListener"; // public static final String PROP_IQ = "iq"; // public static final String PROP_IQ_PROVIDER = "iqProvider"; // public static final String PROP_NOTIFY_ACTIVITY= "notifyActivity"; // // // PROPERTY DEFAULT VALUES // // public static final String DEFAULT_HOST = "127.0.0.1"; // public static final String DEFAULT_PORT = "5222"; // // // // PREFERENCE // public static final String SHARED_PREFERENCE_NAME = "client_preferences"; // // // PREFERENCE KEYS // // public static final String CALLBACK_ACTIVITY_PACKAGE_NAME = "CALLBACK_ACTIVITY_PACKAGE_NAME"; // // public static final String CALLBACK_ACTIVITY_CLASS_NAME = "CALLBACK_ACTIVITY_CLASS_NAME"; // // public static final String API_KEY = "API_KEY"; // // public static final String VERSION = "VERSION"; // // public static final String XMPP_HOST = "XMPP_HOST"; // // public static final String XMPP_PORT = "XMPP_PORT"; // // public static final String XMPP_USERNAME = "XMPP_USERNAME"; // // public static final String XMPP_PASSWORD = "XMPP_PASSWORD"; // // public static final String DEVICE_ID = "DEVICE_ID"; // // public static final String EMULATOR_DEVICE_ID = "EMULATOR_DEVICE_ID"; // // public static final String NOTIFICATION_ICON = "NOTIFICATION_ICON"; // // public static final String SETTINGS_NOTIFICATION_ENABLED = "SETTINGS_NOTIFICATION_ENABLED"; // // public static final String SETTINGS_SOUND_ENABLED = "SETTINGS_SOUND_ENABLED"; // // public static final String SETTINGS_VIBRATE_ENABLED = "SETTINGS_VIBRATE_ENABLED"; // // public static final String SETTINGS_TOAST_ENABLED = "SETTINGS_TOAST_ENABLED"; // // // NOTIFICATION FIELDS // // public static final String NOTIFICATION_ID = "NOTIFICATION_ID"; // // public static final String NOTIFICATION_API_KEY = "NOTIFICATION_API_KEY"; // // public static final String NOTIFICATION_TITLE = "NOTIFICATION_TITLE"; // // public static final String NOTIFICATION_MESSAGE = "NOTIFICATION_MESSAGE"; // // public static final String NOTIFICATION_URI = "NOTIFICATION_URI"; // // public static final String PACKET_ID = "PACKET_ID"; // // // // INTENT ACTIONS // // public static final String ACTION_SHOW_NOTIFICATION = "org.androidpn.client.SHOW_NOTIFICATION"; // // public static final String ACTION_NOTIFICATION_CLICKED = "org.androidpn.client.NOTIFICATION_CLICKED"; // // public static final String ACTION_NOTIFICATION_CLEARED = "org.androidpn.client.NOTIFICATION_CLEARED"; // // // INTENT_EXTRA // public static final String INTENT_EXTRA_IQ = "INTENT_IQ"; // // // NAMESPACE // public static final String DEFAULT_NAMESPACE = "androidpn:iq:notification"; // // ELEMENT_NAME // public static final String ELEMENT_NAME = "notification"; // // }
import android.content.Intent; import android.support.v7.app.ActionBarActivity; import android.os.Bundle; import android.util.Log; import android.widget.TextView; import com.githang.android.apnbb.Constants; import org.androidpn.client.LogUtil; import com.githang.android.apnbb.demo.R;
package com.githang.android.apnbb.demo.notify; public class NotifyDetailActivity extends ActionBarActivity { private static final String LOG_TAG = LogUtil.makeLogTag(NotifyDetailActivity.class); @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_notify_detail); Intent intent = getIntent();
// Path: androidpn/src/main/java/com/githang/android/apnbb/Constants.java // public class Constants { // // // PROPERTY // public static final String PROP_FILE_NAME = "androidpn"; // // // PROPERTY KEYS // // public static final String PROP_API_KEY = "apiKey"; // public static final String PROP_XMPP_HOST = "xmppHost"; // public static final String PROP_XMPP_PORT = "xmppPort"; // public static final String PROP_PACKET_LISTENER = "packetListener"; // public static final String PROP_IQ = "iq"; // public static final String PROP_IQ_PROVIDER = "iqProvider"; // public static final String PROP_NOTIFY_ACTIVITY= "notifyActivity"; // // // PROPERTY DEFAULT VALUES // // public static final String DEFAULT_HOST = "127.0.0.1"; // public static final String DEFAULT_PORT = "5222"; // // // // PREFERENCE // public static final String SHARED_PREFERENCE_NAME = "client_preferences"; // // // PREFERENCE KEYS // // public static final String CALLBACK_ACTIVITY_PACKAGE_NAME = "CALLBACK_ACTIVITY_PACKAGE_NAME"; // // public static final String CALLBACK_ACTIVITY_CLASS_NAME = "CALLBACK_ACTIVITY_CLASS_NAME"; // // public static final String API_KEY = "API_KEY"; // // public static final String VERSION = "VERSION"; // // public static final String XMPP_HOST = "XMPP_HOST"; // // public static final String XMPP_PORT = "XMPP_PORT"; // // public static final String XMPP_USERNAME = "XMPP_USERNAME"; // // public static final String XMPP_PASSWORD = "XMPP_PASSWORD"; // // public static final String DEVICE_ID = "DEVICE_ID"; // // public static final String EMULATOR_DEVICE_ID = "EMULATOR_DEVICE_ID"; // // public static final String NOTIFICATION_ICON = "NOTIFICATION_ICON"; // // public static final String SETTINGS_NOTIFICATION_ENABLED = "SETTINGS_NOTIFICATION_ENABLED"; // // public static final String SETTINGS_SOUND_ENABLED = "SETTINGS_SOUND_ENABLED"; // // public static final String SETTINGS_VIBRATE_ENABLED = "SETTINGS_VIBRATE_ENABLED"; // // public static final String SETTINGS_TOAST_ENABLED = "SETTINGS_TOAST_ENABLED"; // // // NOTIFICATION FIELDS // // public static final String NOTIFICATION_ID = "NOTIFICATION_ID"; // // public static final String NOTIFICATION_API_KEY = "NOTIFICATION_API_KEY"; // // public static final String NOTIFICATION_TITLE = "NOTIFICATION_TITLE"; // // public static final String NOTIFICATION_MESSAGE = "NOTIFICATION_MESSAGE"; // // public static final String NOTIFICATION_URI = "NOTIFICATION_URI"; // // public static final String PACKET_ID = "PACKET_ID"; // // // // INTENT ACTIONS // // public static final String ACTION_SHOW_NOTIFICATION = "org.androidpn.client.SHOW_NOTIFICATION"; // // public static final String ACTION_NOTIFICATION_CLICKED = "org.androidpn.client.NOTIFICATION_CLICKED"; // // public static final String ACTION_NOTIFICATION_CLEARED = "org.androidpn.client.NOTIFICATION_CLEARED"; // // // INTENT_EXTRA // public static final String INTENT_EXTRA_IQ = "INTENT_IQ"; // // // NAMESPACE // public static final String DEFAULT_NAMESPACE = "androidpn:iq:notification"; // // ELEMENT_NAME // public static final String ELEMENT_NAME = "notification"; // // } // Path: demo/src/main/java/com/githang/android/apnbb/demo/notify/NotifyDetailActivity.java import android.content.Intent; import android.support.v7.app.ActionBarActivity; import android.os.Bundle; import android.util.Log; import android.widget.TextView; import com.githang.android.apnbb.Constants; import org.androidpn.client.LogUtil; import com.githang.android.apnbb.demo.R; package com.githang.android.apnbb.demo.notify; public class NotifyDetailActivity extends ActionBarActivity { private static final String LOG_TAG = LogUtil.makeLogTag(NotifyDetailActivity.class); @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_notify_detail); Intent intent = getIntent();
Object o = intent.getSerializableExtra(Constants.INTENT_EXTRA_IQ);
msdx/AndroidPNClient
demo/src/main/java/com/githang/android/apnbb/demo/notify/AutoRunReceiver.java
// Path: androidpn/src/main/java/org/androidpn/client/ServiceManager.java // public final class ServiceManager { // // private static final String LOGTAG = LogUtil // .makeLogTag(ServiceManager.class); // // private Context context; // // private SharedPreferences sharedPrefs; // // private Properties props; // // private String version = "0.7.0"; // // private String apiKey; // // private String xmppHost; // // private String xmppPort; // // private String callbackActivityPackageName; // // private String callbackActivityClassName; // // public ServiceManager(Context context) { // this.context = context; // // if (context instanceof Activity) { // Log.i(LOGTAG, "Callback Activity..."); // Activity callbackActivity = (Activity) context; // callbackActivityPackageName = callbackActivity.getPackageName(); // callbackActivityClassName = callbackActivity.getClass().getName(); // } // // props = loadProperties(); // apiKey = props.getProperty(Constants.PROP_API_KEY, ""); // xmppHost = props.getProperty(Constants.PROP_XMPP_HOST, Constants.DEFAULT_HOST); // xmppPort = props.getProperty(Constants.PROP_XMPP_PORT, Constants.DEFAULT_PORT); // NotifierConfig.packetListener = props.getProperty(Constants.PROP_PACKET_LISTENER, null); // NotifierConfig.iq = props.getProperty(Constants.PROP_IQ, null); // NotifierConfig.iqProvider = props.getProperty(Constants.PROP_IQ_PROVIDER, null); // NotifierConfig.notifyActivity = props.getProperty(Constants.PROP_NOTIFY_ACTIVITY, null); // Log.i(LOGTAG, "apiKey=" + apiKey); // Log.i(LOGTAG, "xmppHost=" + xmppHost); // Log.i(LOGTAG, "xmppPort=" + xmppPort); // Log.i(LOGTAG, "packetListener=" + NotifierConfig.packetListener); // Log.i(LOGTAG, "iq=" + NotifierConfig.iq); // Log.i(LOGTAG, "iqProvider=" + NotifierConfig.iqProvider); // Log.i(LOGTAG, "notifyActivity" + NotifierConfig.notifyActivity); // // sharedPrefs = context.getSharedPreferences( // Constants.SHARED_PREFERENCE_NAME, Context.MODE_PRIVATE); // Editor editor = sharedPrefs.edit(); // editor.putString(Constants.API_KEY, apiKey); // editor.putString(Constants.VERSION, version); // editor.putString(Constants.XMPP_HOST, xmppHost); // editor.putInt(Constants.XMPP_PORT, Integer.parseInt(xmppPort)); // editor.putString(Constants.CALLBACK_ACTIVITY_PACKAGE_NAME, // callbackActivityPackageName); // editor.putString(Constants.CALLBACK_ACTIVITY_CLASS_NAME, // callbackActivityClassName); // editor.commit(); // SmackConfiguration.setKeepAliveInterval(60000); // } // // public void startService() { // Thread serviceThread = new Thread(new Runnable() { // @Override // public void run() { // Intent intent = NotificationService.getIntent(context); // context.startService(intent); // } // }); // // serviceThread.start(); // } // // public void stopService() { // Intent intent = NotificationService.getIntent(context); // context.stopService(intent); // } // // private Properties loadProperties() { // Properties props = new Properties(); // try { // int id = context.getResources().getIdentifier(Constants.PROP_FILE_NAME, "raw", // context.getPackageName()); // props.load(context.getResources().openRawResource(id)); // } catch (Exception e) { // Log.e(LOGTAG, "Could not find the properties file.", e); // } // return props; // } // // public void setNotificationIcon(int iconId) { // Editor editor = sharedPrefs.edit(); // editor.putInt(Constants.NOTIFICATION_ICON, iconId); // editor.commit(); // } // // public static void viewNotificationSettings(Context context) { // Intent intent = new Intent().setClass(context, // NotificationSettingsActivity.class); // context.startActivity(intent); // } // // }
import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.util.Log; import com.githang.android.apnbb.demo.R; import org.androidpn.client.LogUtil; import org.androidpn.client.ServiceManager;
package com.githang.android.apnbb.demo.notify; public class AutoRunReceiver extends BroadcastReceiver { private static final String LOG_TAG = LogUtil.makeLogTag(AutoRunReceiver.class); public AutoRunReceiver() { } @Override public void onReceive(Context context, Intent intent) { String action = intent.getAction(); if(Intent.ACTION_BOOT_COMPLETED.equals(action)) { Log.d(LOG_TAG, "action_boot_completed");
// Path: androidpn/src/main/java/org/androidpn/client/ServiceManager.java // public final class ServiceManager { // // private static final String LOGTAG = LogUtil // .makeLogTag(ServiceManager.class); // // private Context context; // // private SharedPreferences sharedPrefs; // // private Properties props; // // private String version = "0.7.0"; // // private String apiKey; // // private String xmppHost; // // private String xmppPort; // // private String callbackActivityPackageName; // // private String callbackActivityClassName; // // public ServiceManager(Context context) { // this.context = context; // // if (context instanceof Activity) { // Log.i(LOGTAG, "Callback Activity..."); // Activity callbackActivity = (Activity) context; // callbackActivityPackageName = callbackActivity.getPackageName(); // callbackActivityClassName = callbackActivity.getClass().getName(); // } // // props = loadProperties(); // apiKey = props.getProperty(Constants.PROP_API_KEY, ""); // xmppHost = props.getProperty(Constants.PROP_XMPP_HOST, Constants.DEFAULT_HOST); // xmppPort = props.getProperty(Constants.PROP_XMPP_PORT, Constants.DEFAULT_PORT); // NotifierConfig.packetListener = props.getProperty(Constants.PROP_PACKET_LISTENER, null); // NotifierConfig.iq = props.getProperty(Constants.PROP_IQ, null); // NotifierConfig.iqProvider = props.getProperty(Constants.PROP_IQ_PROVIDER, null); // NotifierConfig.notifyActivity = props.getProperty(Constants.PROP_NOTIFY_ACTIVITY, null); // Log.i(LOGTAG, "apiKey=" + apiKey); // Log.i(LOGTAG, "xmppHost=" + xmppHost); // Log.i(LOGTAG, "xmppPort=" + xmppPort); // Log.i(LOGTAG, "packetListener=" + NotifierConfig.packetListener); // Log.i(LOGTAG, "iq=" + NotifierConfig.iq); // Log.i(LOGTAG, "iqProvider=" + NotifierConfig.iqProvider); // Log.i(LOGTAG, "notifyActivity" + NotifierConfig.notifyActivity); // // sharedPrefs = context.getSharedPreferences( // Constants.SHARED_PREFERENCE_NAME, Context.MODE_PRIVATE); // Editor editor = sharedPrefs.edit(); // editor.putString(Constants.API_KEY, apiKey); // editor.putString(Constants.VERSION, version); // editor.putString(Constants.XMPP_HOST, xmppHost); // editor.putInt(Constants.XMPP_PORT, Integer.parseInt(xmppPort)); // editor.putString(Constants.CALLBACK_ACTIVITY_PACKAGE_NAME, // callbackActivityPackageName); // editor.putString(Constants.CALLBACK_ACTIVITY_CLASS_NAME, // callbackActivityClassName); // editor.commit(); // SmackConfiguration.setKeepAliveInterval(60000); // } // // public void startService() { // Thread serviceThread = new Thread(new Runnable() { // @Override // public void run() { // Intent intent = NotificationService.getIntent(context); // context.startService(intent); // } // }); // // serviceThread.start(); // } // // public void stopService() { // Intent intent = NotificationService.getIntent(context); // context.stopService(intent); // } // // private Properties loadProperties() { // Properties props = new Properties(); // try { // int id = context.getResources().getIdentifier(Constants.PROP_FILE_NAME, "raw", // context.getPackageName()); // props.load(context.getResources().openRawResource(id)); // } catch (Exception e) { // Log.e(LOGTAG, "Could not find the properties file.", e); // } // return props; // } // // public void setNotificationIcon(int iconId) { // Editor editor = sharedPrefs.edit(); // editor.putInt(Constants.NOTIFICATION_ICON, iconId); // editor.commit(); // } // // public static void viewNotificationSettings(Context context) { // Intent intent = new Intent().setClass(context, // NotificationSettingsActivity.class); // context.startActivity(intent); // } // // } // Path: demo/src/main/java/com/githang/android/apnbb/demo/notify/AutoRunReceiver.java import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.util.Log; import com.githang.android.apnbb.demo.R; import org.androidpn.client.LogUtil; import org.androidpn.client.ServiceManager; package com.githang.android.apnbb.demo.notify; public class AutoRunReceiver extends BroadcastReceiver { private static final String LOG_TAG = LogUtil.makeLogTag(AutoRunReceiver.class); public AutoRunReceiver() { } @Override public void onReceive(Context context, Intent intent) { String action = intent.getAction(); if(Intent.ACTION_BOOT_COMPLETED.equals(action)) { Log.d(LOG_TAG, "action_boot_completed");
final ServiceManager serviceManager = new ServiceManager(context);
msdx/AndroidPNClient
androidpn/src/main/java/org/jivesoftware/smack/ConnectionConfiguration.java
// Path: androidpn/src/main/java/org/apache/harmony/javax/security/auth/callback/CallbackHandler.java // public interface CallbackHandler { // // /** // * Handles the actual {@link org.apache.harmony.javax.security.auth.callback.Callback}. A {@code CallbackHandler} needs to // * implement this method. In the method, it is free to select which {@code // * Callback}s it actually wants to handle and in which way. For example, a // * console-based {@code CallbackHandler} might choose to sequentially ask // * the user for login and password, if it implements these {@code Callback} // * s, whereas a GUI-based one might open a single dialog window for both // * values. If a {@code CallbackHandler} is not able to handle a specific // * {@code Callback}, it needs to throw an // * {@link UnsupportedCallbackException}. // * // * @param callbacks // * the array of {@code Callback}s that need handling // * @throws java.io.IOException // * if an I/O related error occurs // * @throws UnsupportedCallbackException // * if the {@code CallbackHandler} is not able to handle a // * specific {@code Callback} // */ // void handle(Callback[] callbacks) throws IOException, UnsupportedCallbackException; // // }
import java.net.UnknownHostException; import javax.net.SocketFactory; import android.util.Log; import org.androidpn.client.LogUtil; import org.apache.harmony.javax.security.auth.callback.CallbackHandler; import org.apache.http.conn.util.InetAddressUtils; import org.jivesoftware.smack.proxy.ProxyInfo; import org.jivesoftware.smack.util.DNSUtil; import java.io.File; import java.net.InetAddress;
/** * $RCSfile$ * $Revision: 3306 $ * $Date: 2006-01-16 14:34:56 -0300 (Mon, 16 Jan 2006) $ * * Copyright 2003-2007 Jive Software. * * All rights reserved. Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.jivesoftware.smack; /** * Configuration to use while establishing the connection to the server. It is possible to * configure the path to the trustore file that keeps the trusted CA root certificates and * enable or disable all or some of the checkings done while verifying server certificates.<p> * * It is also possible to configure if TLS, SASL, and compression are used or not. * * @author Gaston Dombiak */ public class ConnectionConfiguration implements Cloneable { private String LOG_TAG = LogUtil.makeLogTag(ConnectionConfiguration.class); /** * Hostname of the XMPP server. Usually servers use the same service name as the name * of the server. However, there are some servers like google where host would be * talk.google.com and the serviceName would be gmail.com. */ private String serviceName; private String host; private int port; private String truststorePath; private String truststoreType; private String truststorePassword; private String keystorePath; private String keystoreType; private String pkcs11Library; private boolean verifyChainEnabled = false; private boolean verifyRootCAEnabled = false; private boolean selfSignedCertificateEnabled = false; private boolean expiredCertificatesCheckEnabled = false; private boolean notMatchingDomainCheckEnabled = false; private boolean isRosterVersioningAvailable = false; private String capsNode = null; private boolean compressionEnabled = false; private boolean saslAuthenticationEnabled = true; /** * Used to get information from the user */
// Path: androidpn/src/main/java/org/apache/harmony/javax/security/auth/callback/CallbackHandler.java // public interface CallbackHandler { // // /** // * Handles the actual {@link org.apache.harmony.javax.security.auth.callback.Callback}. A {@code CallbackHandler} needs to // * implement this method. In the method, it is free to select which {@code // * Callback}s it actually wants to handle and in which way. For example, a // * console-based {@code CallbackHandler} might choose to sequentially ask // * the user for login and password, if it implements these {@code Callback} // * s, whereas a GUI-based one might open a single dialog window for both // * values. If a {@code CallbackHandler} is not able to handle a specific // * {@code Callback}, it needs to throw an // * {@link UnsupportedCallbackException}. // * // * @param callbacks // * the array of {@code Callback}s that need handling // * @throws java.io.IOException // * if an I/O related error occurs // * @throws UnsupportedCallbackException // * if the {@code CallbackHandler} is not able to handle a // * specific {@code Callback} // */ // void handle(Callback[] callbacks) throws IOException, UnsupportedCallbackException; // // } // Path: androidpn/src/main/java/org/jivesoftware/smack/ConnectionConfiguration.java import java.net.UnknownHostException; import javax.net.SocketFactory; import android.util.Log; import org.androidpn.client.LogUtil; import org.apache.harmony.javax.security.auth.callback.CallbackHandler; import org.apache.http.conn.util.InetAddressUtils; import org.jivesoftware.smack.proxy.ProxyInfo; import org.jivesoftware.smack.util.DNSUtil; import java.io.File; import java.net.InetAddress; /** * $RCSfile$ * $Revision: 3306 $ * $Date: 2006-01-16 14:34:56 -0300 (Mon, 16 Jan 2006) $ * * Copyright 2003-2007 Jive Software. * * All rights reserved. Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.jivesoftware.smack; /** * Configuration to use while establishing the connection to the server. It is possible to * configure the path to the trustore file that keeps the trusted CA root certificates and * enable or disable all or some of the checkings done while verifying server certificates.<p> * * It is also possible to configure if TLS, SASL, and compression are used or not. * * @author Gaston Dombiak */ public class ConnectionConfiguration implements Cloneable { private String LOG_TAG = LogUtil.makeLogTag(ConnectionConfiguration.class); /** * Hostname of the XMPP server. Usually servers use the same service name as the name * of the server. However, there are some servers like google where host would be * talk.google.com and the serviceName would be gmail.com. */ private String serviceName; private String host; private int port; private String truststorePath; private String truststoreType; private String truststorePassword; private String keystorePath; private String keystoreType; private String pkcs11Library; private boolean verifyChainEnabled = false; private boolean verifyRootCAEnabled = false; private boolean selfSignedCertificateEnabled = false; private boolean expiredCertificatesCheckEnabled = false; private boolean notMatchingDomainCheckEnabled = false; private boolean isRosterVersioningAvailable = false; private String capsNode = null; private boolean compressionEnabled = false; private boolean saslAuthenticationEnabled = true; /** * Used to get information from the user */
private CallbackHandler callbackHandler;
msdx/AndroidPNClient
androidpn/src/main/java/org/androidpn/client/NotificationDetailsActivity.java
// Path: androidpn/src/main/java/com/githang/android/apnbb/Constants.java // public class Constants { // // // PROPERTY // public static final String PROP_FILE_NAME = "androidpn"; // // // PROPERTY KEYS // // public static final String PROP_API_KEY = "apiKey"; // public static final String PROP_XMPP_HOST = "xmppHost"; // public static final String PROP_XMPP_PORT = "xmppPort"; // public static final String PROP_PACKET_LISTENER = "packetListener"; // public static final String PROP_IQ = "iq"; // public static final String PROP_IQ_PROVIDER = "iqProvider"; // public static final String PROP_NOTIFY_ACTIVITY= "notifyActivity"; // // // PROPERTY DEFAULT VALUES // // public static final String DEFAULT_HOST = "127.0.0.1"; // public static final String DEFAULT_PORT = "5222"; // // // // PREFERENCE // public static final String SHARED_PREFERENCE_NAME = "client_preferences"; // // // PREFERENCE KEYS // // public static final String CALLBACK_ACTIVITY_PACKAGE_NAME = "CALLBACK_ACTIVITY_PACKAGE_NAME"; // // public static final String CALLBACK_ACTIVITY_CLASS_NAME = "CALLBACK_ACTIVITY_CLASS_NAME"; // // public static final String API_KEY = "API_KEY"; // // public static final String VERSION = "VERSION"; // // public static final String XMPP_HOST = "XMPP_HOST"; // // public static final String XMPP_PORT = "XMPP_PORT"; // // public static final String XMPP_USERNAME = "XMPP_USERNAME"; // // public static final String XMPP_PASSWORD = "XMPP_PASSWORD"; // // public static final String DEVICE_ID = "DEVICE_ID"; // // public static final String EMULATOR_DEVICE_ID = "EMULATOR_DEVICE_ID"; // // public static final String NOTIFICATION_ICON = "NOTIFICATION_ICON"; // // public static final String SETTINGS_NOTIFICATION_ENABLED = "SETTINGS_NOTIFICATION_ENABLED"; // // public static final String SETTINGS_SOUND_ENABLED = "SETTINGS_SOUND_ENABLED"; // // public static final String SETTINGS_VIBRATE_ENABLED = "SETTINGS_VIBRATE_ENABLED"; // // public static final String SETTINGS_TOAST_ENABLED = "SETTINGS_TOAST_ENABLED"; // // // NOTIFICATION FIELDS // // public static final String NOTIFICATION_ID = "NOTIFICATION_ID"; // // public static final String NOTIFICATION_API_KEY = "NOTIFICATION_API_KEY"; // // public static final String NOTIFICATION_TITLE = "NOTIFICATION_TITLE"; // // public static final String NOTIFICATION_MESSAGE = "NOTIFICATION_MESSAGE"; // // public static final String NOTIFICATION_URI = "NOTIFICATION_URI"; // // public static final String PACKET_ID = "PACKET_ID"; // // // // INTENT ACTIONS // // public static final String ACTION_SHOW_NOTIFICATION = "org.androidpn.client.SHOW_NOTIFICATION"; // // public static final String ACTION_NOTIFICATION_CLICKED = "org.androidpn.client.NOTIFICATION_CLICKED"; // // public static final String ACTION_NOTIFICATION_CLEARED = "org.androidpn.client.NOTIFICATION_CLEARED"; // // // INTENT_EXTRA // public static final String INTENT_EXTRA_IQ = "INTENT_IQ"; // // // NAMESPACE // public static final String DEFAULT_NAMESPACE = "androidpn:iq:notification"; // // ELEMENT_NAME // public static final String ELEMENT_NAME = "notification"; // // }
import android.app.Activity; import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; import android.graphics.Typeface; import android.net.Uri; import android.os.Bundle; import android.util.Log; import android.view.Gravity; import android.view.View; import android.widget.Button; import android.widget.LinearLayout; import android.widget.TextView; import com.githang.android.apnbb.Constants;
/* * Copyright (C) 2010 Moduad Co., Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.androidpn.client; /** * Activity for displaying the notification details view. * * @author Sehwan Noh (devnoh@gmail.com) */ public class NotificationDetailsActivity extends Activity { private static final String LOGTAG = LogUtil .makeLogTag(NotificationDetailsActivity.class); private String callbackActivityPackageName; private String callbackActivityClassName; public NotificationDetailsActivity() { } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); SharedPreferences sharedPrefs = this.getSharedPreferences(
// Path: androidpn/src/main/java/com/githang/android/apnbb/Constants.java // public class Constants { // // // PROPERTY // public static final String PROP_FILE_NAME = "androidpn"; // // // PROPERTY KEYS // // public static final String PROP_API_KEY = "apiKey"; // public static final String PROP_XMPP_HOST = "xmppHost"; // public static final String PROP_XMPP_PORT = "xmppPort"; // public static final String PROP_PACKET_LISTENER = "packetListener"; // public static final String PROP_IQ = "iq"; // public static final String PROP_IQ_PROVIDER = "iqProvider"; // public static final String PROP_NOTIFY_ACTIVITY= "notifyActivity"; // // // PROPERTY DEFAULT VALUES // // public static final String DEFAULT_HOST = "127.0.0.1"; // public static final String DEFAULT_PORT = "5222"; // // // // PREFERENCE // public static final String SHARED_PREFERENCE_NAME = "client_preferences"; // // // PREFERENCE KEYS // // public static final String CALLBACK_ACTIVITY_PACKAGE_NAME = "CALLBACK_ACTIVITY_PACKAGE_NAME"; // // public static final String CALLBACK_ACTIVITY_CLASS_NAME = "CALLBACK_ACTIVITY_CLASS_NAME"; // // public static final String API_KEY = "API_KEY"; // // public static final String VERSION = "VERSION"; // // public static final String XMPP_HOST = "XMPP_HOST"; // // public static final String XMPP_PORT = "XMPP_PORT"; // // public static final String XMPP_USERNAME = "XMPP_USERNAME"; // // public static final String XMPP_PASSWORD = "XMPP_PASSWORD"; // // public static final String DEVICE_ID = "DEVICE_ID"; // // public static final String EMULATOR_DEVICE_ID = "EMULATOR_DEVICE_ID"; // // public static final String NOTIFICATION_ICON = "NOTIFICATION_ICON"; // // public static final String SETTINGS_NOTIFICATION_ENABLED = "SETTINGS_NOTIFICATION_ENABLED"; // // public static final String SETTINGS_SOUND_ENABLED = "SETTINGS_SOUND_ENABLED"; // // public static final String SETTINGS_VIBRATE_ENABLED = "SETTINGS_VIBRATE_ENABLED"; // // public static final String SETTINGS_TOAST_ENABLED = "SETTINGS_TOAST_ENABLED"; // // // NOTIFICATION FIELDS // // public static final String NOTIFICATION_ID = "NOTIFICATION_ID"; // // public static final String NOTIFICATION_API_KEY = "NOTIFICATION_API_KEY"; // // public static final String NOTIFICATION_TITLE = "NOTIFICATION_TITLE"; // // public static final String NOTIFICATION_MESSAGE = "NOTIFICATION_MESSAGE"; // // public static final String NOTIFICATION_URI = "NOTIFICATION_URI"; // // public static final String PACKET_ID = "PACKET_ID"; // // // // INTENT ACTIONS // // public static final String ACTION_SHOW_NOTIFICATION = "org.androidpn.client.SHOW_NOTIFICATION"; // // public static final String ACTION_NOTIFICATION_CLICKED = "org.androidpn.client.NOTIFICATION_CLICKED"; // // public static final String ACTION_NOTIFICATION_CLEARED = "org.androidpn.client.NOTIFICATION_CLEARED"; // // // INTENT_EXTRA // public static final String INTENT_EXTRA_IQ = "INTENT_IQ"; // // // NAMESPACE // public static final String DEFAULT_NAMESPACE = "androidpn:iq:notification"; // // ELEMENT_NAME // public static final String ELEMENT_NAME = "notification"; // // } // Path: androidpn/src/main/java/org/androidpn/client/NotificationDetailsActivity.java import android.app.Activity; import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; import android.graphics.Typeface; import android.net.Uri; import android.os.Bundle; import android.util.Log; import android.view.Gravity; import android.view.View; import android.widget.Button; import android.widget.LinearLayout; import android.widget.TextView; import com.githang.android.apnbb.Constants; /* * Copyright (C) 2010 Moduad Co., Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.androidpn.client; /** * Activity for displaying the notification details view. * * @author Sehwan Noh (devnoh@gmail.com) */ public class NotificationDetailsActivity extends Activity { private static final String LOGTAG = LogUtil .makeLogTag(NotificationDetailsActivity.class); private String callbackActivityPackageName; private String callbackActivityClassName; public NotificationDetailsActivity() { } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); SharedPreferences sharedPrefs = this.getSharedPreferences(
Constants.SHARED_PREFERENCE_NAME, Context.MODE_PRIVATE);
msdx/AndroidPNClient
androidpn/src/main/java/org/androidpn/client/PhoneStateChangeListener.java
// Path: androidpn/src/main/java/com/githang/android/apnbb/BroadcastUtil.java // public class BroadcastUtil { // private static final String LOG_TAG = LogUtil.makeLogTag(BroadcastUtil.class); // // // BROADCAST FOR ANDROIDPN CONNECT STATUS // // // 连接中状态 // public static final String APN_STATUS_CONNECTING = "org.androidpn.client.ANDROIDPN_STATUS_CONNECTING"; // // 连接状态 // public static final String APN_STATUS_CONNECTED = "org.androidpn.client.ANDROIDPN_STATUS_CONNECTED"; // // 断开状态 // public static final String APN_STATUS_DISCONNECT = "org.androidpn.client.ANDROIDPN_STATUS_DISCONNECT"; // // 重连中状态 // public static final String APN_STATUS_RECONNECTING = "org.androidpn.client.ANDROIDPN_STATUS_RECONNECTING"; // // 重连成功状态 // public static final String APN_STATUS_RECONNECT_SUCCESS = "org.androidpn.client.ANDROIDPN_STATUS_RECONNECT_SUCCESS"; // // 连接失败状态 // public static final String APN_STATUS_CONNECT_FAILED = "org.androidpn.client.ANDROIDPN_STATUS_CONNECT_FAILED"; // // 已登录状态 // public static final String APN_STATUS_LOGINED = "org.androidpn.client.ANDROIDPN_STATUS_LOGINED"; // // 登录中状态 // public static final String APN_STATUS_LOGINING = "org.androdipn.client.ANDROIDPN_STATUS_LOGINING"; // // 登录成功 // public static final String APN_STATUS_LOGIN_SUCCESS = "org.androidpn.client.ANDROIDPN_STATUS_LOGIN_SUCCESS"; // // 登录失败 // public static final String APN_STATUS_LOGIN_FAIL = "org.androidpn.client.ANDROIDPN_STATUS_LOGIN_FAIL"; // // // BROADCAST FOR ANDROIDPN ACTION // // // 连接动作 // public static final String APN_ACTION_CONNECT = "org.androidpn.client.ANDROIDPN_ACTION_CONNECT"; // // 注册动作 // public static final String APN_ACTION_REGISTER = "org.androidpn.client.ANDROIDPN_ACTION_REGISTER"; // // 登录动作 // public static final String APN_ACTION_LOGIN = "org.androidpn.client.ANDROIDPN_ACTION_LOGIN"; // // 重连动作 // public static final String APN_ACTION_RECONNECT = "org.androidpn.client.ANDROIDPN_ACTION_RECONNECT"; // // 断开动作 // public static final String APN_ACTION_DISCONNECT = "org.androidpn.client.ANDORIDPN_ACTION_DISCONNECT"; // // 发送已接收状态 // public static final String APN_ACTION_RECEIPT = "org.androidpn.client.ANDROIDPN_ACTION_RECEIPT"; // // //查询连接状态 // public static final String APN_ACTION_REQUEST_STATUS = "org.androidpn.client.ANDROIDPN_ACTION_REQUEST_STATUS"; // // // 广播接收已准备好的消息 // public static final String ANDROIDPN_MSG_RECEIVER_READY = "org.androidpn.client.ANDROIDPN_MSG_RECEIVER_READY"; // // public static final void sendBroadcast(Context context, String action) { // LocalBroadcastManager lbm = LocalBroadcastManager.getInstance(context); // lbm.sendBroadcast(new Intent(action)); // } // // public static final void sendBroadcast(Context context, Intent intent) { // LocalBroadcastManager lbm = LocalBroadcastManager.getInstance(context); // lbm.sendBroadcast(intent); // } // // }
import android.telephony.PhoneStateListener; import android.telephony.TelephonyManager; import android.util.Log; import com.githang.android.apnbb.BroadcastUtil;
/* * Copyright (C) 2010 Moduad Co., Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.androidpn.client; /** * A listener class for monitoring changes in phone connection states. * * @author Sehwan Noh (devnoh@gmail.com) */ public class PhoneStateChangeListener extends PhoneStateListener { private static final String LOGTAG = LogUtil .makeLogTag(PhoneStateChangeListener.class); private final NotificationService notificationService; public PhoneStateChangeListener(NotificationService notificationService) { this.notificationService = notificationService; } @Override public void onDataConnectionStateChanged(int state) { super.onDataConnectionStateChanged(state); Log.d(LOGTAG, "onDataConnectionStateChanged()..."); Log.d(LOGTAG, "Data Connection State = " + getState(state)); if (state == TelephonyManager.DATA_CONNECTED) {
// Path: androidpn/src/main/java/com/githang/android/apnbb/BroadcastUtil.java // public class BroadcastUtil { // private static final String LOG_TAG = LogUtil.makeLogTag(BroadcastUtil.class); // // // BROADCAST FOR ANDROIDPN CONNECT STATUS // // // 连接中状态 // public static final String APN_STATUS_CONNECTING = "org.androidpn.client.ANDROIDPN_STATUS_CONNECTING"; // // 连接状态 // public static final String APN_STATUS_CONNECTED = "org.androidpn.client.ANDROIDPN_STATUS_CONNECTED"; // // 断开状态 // public static final String APN_STATUS_DISCONNECT = "org.androidpn.client.ANDROIDPN_STATUS_DISCONNECT"; // // 重连中状态 // public static final String APN_STATUS_RECONNECTING = "org.androidpn.client.ANDROIDPN_STATUS_RECONNECTING"; // // 重连成功状态 // public static final String APN_STATUS_RECONNECT_SUCCESS = "org.androidpn.client.ANDROIDPN_STATUS_RECONNECT_SUCCESS"; // // 连接失败状态 // public static final String APN_STATUS_CONNECT_FAILED = "org.androidpn.client.ANDROIDPN_STATUS_CONNECT_FAILED"; // // 已登录状态 // public static final String APN_STATUS_LOGINED = "org.androidpn.client.ANDROIDPN_STATUS_LOGINED"; // // 登录中状态 // public static final String APN_STATUS_LOGINING = "org.androdipn.client.ANDROIDPN_STATUS_LOGINING"; // // 登录成功 // public static final String APN_STATUS_LOGIN_SUCCESS = "org.androidpn.client.ANDROIDPN_STATUS_LOGIN_SUCCESS"; // // 登录失败 // public static final String APN_STATUS_LOGIN_FAIL = "org.androidpn.client.ANDROIDPN_STATUS_LOGIN_FAIL"; // // // BROADCAST FOR ANDROIDPN ACTION // // // 连接动作 // public static final String APN_ACTION_CONNECT = "org.androidpn.client.ANDROIDPN_ACTION_CONNECT"; // // 注册动作 // public static final String APN_ACTION_REGISTER = "org.androidpn.client.ANDROIDPN_ACTION_REGISTER"; // // 登录动作 // public static final String APN_ACTION_LOGIN = "org.androidpn.client.ANDROIDPN_ACTION_LOGIN"; // // 重连动作 // public static final String APN_ACTION_RECONNECT = "org.androidpn.client.ANDROIDPN_ACTION_RECONNECT"; // // 断开动作 // public static final String APN_ACTION_DISCONNECT = "org.androidpn.client.ANDORIDPN_ACTION_DISCONNECT"; // // 发送已接收状态 // public static final String APN_ACTION_RECEIPT = "org.androidpn.client.ANDROIDPN_ACTION_RECEIPT"; // // //查询连接状态 // public static final String APN_ACTION_REQUEST_STATUS = "org.androidpn.client.ANDROIDPN_ACTION_REQUEST_STATUS"; // // // 广播接收已准备好的消息 // public static final String ANDROIDPN_MSG_RECEIVER_READY = "org.androidpn.client.ANDROIDPN_MSG_RECEIVER_READY"; // // public static final void sendBroadcast(Context context, String action) { // LocalBroadcastManager lbm = LocalBroadcastManager.getInstance(context); // lbm.sendBroadcast(new Intent(action)); // } // // public static final void sendBroadcast(Context context, Intent intent) { // LocalBroadcastManager lbm = LocalBroadcastManager.getInstance(context); // lbm.sendBroadcast(intent); // } // // } // Path: androidpn/src/main/java/org/androidpn/client/PhoneStateChangeListener.java import android.telephony.PhoneStateListener; import android.telephony.TelephonyManager; import android.util.Log; import com.githang.android.apnbb.BroadcastUtil; /* * Copyright (C) 2010 Moduad Co., Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.androidpn.client; /** * A listener class for monitoring changes in phone connection states. * * @author Sehwan Noh (devnoh@gmail.com) */ public class PhoneStateChangeListener extends PhoneStateListener { private static final String LOGTAG = LogUtil .makeLogTag(PhoneStateChangeListener.class); private final NotificationService notificationService; public PhoneStateChangeListener(NotificationService notificationService) { this.notificationService = notificationService; } @Override public void onDataConnectionStateChanged(int state) { super.onDataConnectionStateChanged(state); Log.d(LOGTAG, "onDataConnectionStateChanged()..."); Log.d(LOGTAG, "Data Connection State = " + getState(state)); if (state == TelephonyManager.DATA_CONNECTED) {
BroadcastUtil.sendBroadcast(notificationService, BroadcastUtil.APN_ACTION_RECONNECT);
emina/kodkod
test/kodkod/test/AllTests.java
// Path: test/kodkod/test/unit/AllUnitTests.java // @RunWith(Suite.class) // @Suite.SuiteClasses({ // SparseSequenceTest.class, // BooleanCircuitTest.class, // BooleanMatrixTest.class, // TranslatorTest.class, // EvaluatorTest.class, // SymmetryBreakingTest.class, // SkolemizationTest.class, // EnumerationTest.class, // IntTest.class, // NativeSolverTest.class, // UCoreTest.class, // ReductionAndProofTest.class, // IncrementalSolverTest.class, // RegressionTests.class, // }) // // public class AllUnitTests {} // // Path: test/kodkod/test/sys/AllSysTests.java // @RunWith(Suite.class) // @SuiteClasses({ // ExamplesTestWithRegularSolver.class, // ExamplesTestWithIncrementalSolver.class}) // // public class AllSysTests {}
import org.junit.runner.RunWith; import org.junit.runners.Suite; import org.junit.runners.Suite.SuiteClasses; import kodkod.test.unit.AllUnitTests; import kodkod.test.sys.AllSysTests;
package kodkod.test; @RunWith(Suite.class) @SuiteClasses({
// Path: test/kodkod/test/unit/AllUnitTests.java // @RunWith(Suite.class) // @Suite.SuiteClasses({ // SparseSequenceTest.class, // BooleanCircuitTest.class, // BooleanMatrixTest.class, // TranslatorTest.class, // EvaluatorTest.class, // SymmetryBreakingTest.class, // SkolemizationTest.class, // EnumerationTest.class, // IntTest.class, // NativeSolverTest.class, // UCoreTest.class, // ReductionAndProofTest.class, // IncrementalSolverTest.class, // RegressionTests.class, // }) // // public class AllUnitTests {} // // Path: test/kodkod/test/sys/AllSysTests.java // @RunWith(Suite.class) // @SuiteClasses({ // ExamplesTestWithRegularSolver.class, // ExamplesTestWithIncrementalSolver.class}) // // public class AllSysTests {} // Path: test/kodkod/test/AllTests.java import org.junit.runner.RunWith; import org.junit.runners.Suite; import org.junit.runners.Suite.SuiteClasses; import kodkod.test.unit.AllUnitTests; import kodkod.test.sys.AllSysTests; package kodkod.test; @RunWith(Suite.class) @SuiteClasses({
AllUnitTests.class,
emina/kodkod
test/kodkod/test/AllTests.java
// Path: test/kodkod/test/unit/AllUnitTests.java // @RunWith(Suite.class) // @Suite.SuiteClasses({ // SparseSequenceTest.class, // BooleanCircuitTest.class, // BooleanMatrixTest.class, // TranslatorTest.class, // EvaluatorTest.class, // SymmetryBreakingTest.class, // SkolemizationTest.class, // EnumerationTest.class, // IntTest.class, // NativeSolverTest.class, // UCoreTest.class, // ReductionAndProofTest.class, // IncrementalSolverTest.class, // RegressionTests.class, // }) // // public class AllUnitTests {} // // Path: test/kodkod/test/sys/AllSysTests.java // @RunWith(Suite.class) // @SuiteClasses({ // ExamplesTestWithRegularSolver.class, // ExamplesTestWithIncrementalSolver.class}) // // public class AllSysTests {}
import org.junit.runner.RunWith; import org.junit.runners.Suite; import org.junit.runners.Suite.SuiteClasses; import kodkod.test.unit.AllUnitTests; import kodkod.test.sys.AllSysTests;
package kodkod.test; @RunWith(Suite.class) @SuiteClasses({ AllUnitTests.class,
// Path: test/kodkod/test/unit/AllUnitTests.java // @RunWith(Suite.class) // @Suite.SuiteClasses({ // SparseSequenceTest.class, // BooleanCircuitTest.class, // BooleanMatrixTest.class, // TranslatorTest.class, // EvaluatorTest.class, // SymmetryBreakingTest.class, // SkolemizationTest.class, // EnumerationTest.class, // IntTest.class, // NativeSolverTest.class, // UCoreTest.class, // ReductionAndProofTest.class, // IncrementalSolverTest.class, // RegressionTests.class, // }) // // public class AllUnitTests {} // // Path: test/kodkod/test/sys/AllSysTests.java // @RunWith(Suite.class) // @SuiteClasses({ // ExamplesTestWithRegularSolver.class, // ExamplesTestWithIncrementalSolver.class}) // // public class AllSysTests {} // Path: test/kodkod/test/AllTests.java import org.junit.runner.RunWith; import org.junit.runners.Suite; import org.junit.runners.Suite.SuiteClasses; import kodkod.test.unit.AllUnitTests; import kodkod.test.sys.AllSysTests; package kodkod.test; @RunWith(Suite.class) @SuiteClasses({ AllUnitTests.class,
AllSysTests.class
jmeter-maven-plugin/jmeter-maven-plugin
src/test/java/com/lazerycode/jmeter/configuration/JMeterArgumentsArrayTest.java
// Path: src/main/java/com/lazerycode/jmeter/utility/UtilityFunctions.java // public final class UtilityFunctions { // // /** // * Make constructor private as this is a non-instantiable helper classes // */ // UtilityFunctions() throws InstantiationError { // throw new InstantiationError("This class is non-instantiable."); // } // // /** // * Build a human readable command line from the arguments set by the plugin // * // * @param arguments Array of String // * @return String // */ // public static String humanReadableCommandLineOutput(List<String> arguments) { // //TODO investigate removing this, only used in tests // StringBuilder debugOutput = new StringBuilder(); // for (String argument : arguments) { // debugOutput.append(argument).append(" "); // } // return debugOutput.toString().trim(); // } // // /** // * Utility function to strip carriage returns out of a String // * // * @param value String // * @return String // */ // public static String stripCarriageReturns(String value) { // return value.replaceAll("[\n\r]", ""); // } // // /** // * Utility function to check if a Map is defined and not empty // * // * @param value Map // * @return boolean // */ // public static Boolean isNotSet(Map<?, ?> value) { // return null == value || value.isEmpty(); // } // // /** // * Utility function to check if a List is defined and not empty // * // * @param value List // * @return boolean // */ // public static Boolean isNotSet(List<?> value) { // return null == value || value.isEmpty(); // } // // /** // * Utility function to check if a String is defined and not empty // * // * @param value String // * @return boolean // */ // public static Boolean isNotSet(String value) { // return null == value || value.isEmpty() || value.trim().length() == 0; // } // // /** // * Utility function to check if a String is defined and not empty // * // * @param value String // * @return boolean // */ // public static Boolean isSet(String value) { // return !isNotSet(value); // } // // /** // * Utility function to check if File is defined and not empty // * // * @param value File // * @return boolean // */ // public static Boolean isNotSet(File value) { // return null == value || value.toString().isEmpty() || value.toString().trim().length() == 0; // } // }
import ch.qos.logback.classic.Logger; import ch.qos.logback.classic.spi.ILoggingEvent; import ch.qos.logback.core.read.ListAppender; import com.lazerycode.jmeter.utility.UtilityFunctions; import org.apache.maven.plugin.MojoExecutionException; import org.junit.Before; import org.junit.Test; import org.slf4j.LoggerFactory; import java.io.File; import java.net.URISyntaxException; import java.net.URL; import java.time.LocalDateTime; import java.time.format.DateTimeFormatter; import java.util.ArrayList; import java.util.List; import static org.assertj.core.api.Assertions.assertThat;
.buildArgumentsArray(); } @Test(expected = MojoExecutionException.class) public void jMeterHomeEmpty() throws Exception { new JMeterArgumentsArray(DISABLE_GUI, "") .setTestFile(testFile, testFileDirectory) .buildArgumentsArray(); } @Test(expected = MojoExecutionException.class) public void jMeterHomeNull() throws Exception { new JMeterArgumentsArray(DISABLE_GUI, null) .setTestFile(testFile, testFileDirectory) .buildArgumentsArray(); } @Test(expected = MojoExecutionException.class) public void nullTestFileIsNotAddedToArguments() throws Exception { new JMeterArgumentsArray(DISABLE_GUI, "target/jmeter/") .setTestFile(null, testFileDirectory) .buildArgumentsArray(); } @Test public void validateDefaultCommandLineOutputWithGUIDisabled() throws Exception { JMeterArgumentsArray testArgs = new JMeterArgumentsArray(DISABLE_GUI, "target/jmeter/") .setTestFile(testFile, testFileDirectory); assertThat(testArgs.getResultsLogFileName()).isNotEmpty();
// Path: src/main/java/com/lazerycode/jmeter/utility/UtilityFunctions.java // public final class UtilityFunctions { // // /** // * Make constructor private as this is a non-instantiable helper classes // */ // UtilityFunctions() throws InstantiationError { // throw new InstantiationError("This class is non-instantiable."); // } // // /** // * Build a human readable command line from the arguments set by the plugin // * // * @param arguments Array of String // * @return String // */ // public static String humanReadableCommandLineOutput(List<String> arguments) { // //TODO investigate removing this, only used in tests // StringBuilder debugOutput = new StringBuilder(); // for (String argument : arguments) { // debugOutput.append(argument).append(" "); // } // return debugOutput.toString().trim(); // } // // /** // * Utility function to strip carriage returns out of a String // * // * @param value String // * @return String // */ // public static String stripCarriageReturns(String value) { // return value.replaceAll("[\n\r]", ""); // } // // /** // * Utility function to check if a Map is defined and not empty // * // * @param value Map // * @return boolean // */ // public static Boolean isNotSet(Map<?, ?> value) { // return null == value || value.isEmpty(); // } // // /** // * Utility function to check if a List is defined and not empty // * // * @param value List // * @return boolean // */ // public static Boolean isNotSet(List<?> value) { // return null == value || value.isEmpty(); // } // // /** // * Utility function to check if a String is defined and not empty // * // * @param value String // * @return boolean // */ // public static Boolean isNotSet(String value) { // return null == value || value.isEmpty() || value.trim().length() == 0; // } // // /** // * Utility function to check if a String is defined and not empty // * // * @param value String // * @return boolean // */ // public static Boolean isSet(String value) { // return !isNotSet(value); // } // // /** // * Utility function to check if File is defined and not empty // * // * @param value File // * @return boolean // */ // public static Boolean isNotSet(File value) { // return null == value || value.toString().isEmpty() || value.toString().trim().length() == 0; // } // } // Path: src/test/java/com/lazerycode/jmeter/configuration/JMeterArgumentsArrayTest.java import ch.qos.logback.classic.Logger; import ch.qos.logback.classic.spi.ILoggingEvent; import ch.qos.logback.core.read.ListAppender; import com.lazerycode.jmeter.utility.UtilityFunctions; import org.apache.maven.plugin.MojoExecutionException; import org.junit.Before; import org.junit.Test; import org.slf4j.LoggerFactory; import java.io.File; import java.net.URISyntaxException; import java.net.URL; import java.time.LocalDateTime; import java.time.format.DateTimeFormatter; import java.util.ArrayList; import java.util.List; import static org.assertj.core.api.Assertions.assertThat; .buildArgumentsArray(); } @Test(expected = MojoExecutionException.class) public void jMeterHomeEmpty() throws Exception { new JMeterArgumentsArray(DISABLE_GUI, "") .setTestFile(testFile, testFileDirectory) .buildArgumentsArray(); } @Test(expected = MojoExecutionException.class) public void jMeterHomeNull() throws Exception { new JMeterArgumentsArray(DISABLE_GUI, null) .setTestFile(testFile, testFileDirectory) .buildArgumentsArray(); } @Test(expected = MojoExecutionException.class) public void nullTestFileIsNotAddedToArguments() throws Exception { new JMeterArgumentsArray(DISABLE_GUI, "target/jmeter/") .setTestFile(null, testFileDirectory) .buildArgumentsArray(); } @Test public void validateDefaultCommandLineOutputWithGUIDisabled() throws Exception { JMeterArgumentsArray testArgs = new JMeterArgumentsArray(DISABLE_GUI, "target/jmeter/") .setTestFile(testFile, testFileDirectory); assertThat(testArgs.getResultsLogFileName()).isNotEmpty();
assertThat(UtilityFunctions.humanReadableCommandLineOutput(testArgs.buildArgumentsArray()))
jmeter-maven-plugin/jmeter-maven-plugin
src/main/java/com/lazerycode/jmeter/configuration/JMeterArgumentsArray.java
// Path: src/main/java/com/lazerycode/jmeter/configuration/JMeterCommandLineArguments.java // public enum JMeterCommandLineArguments { // // PROXY_PASSWORD("a"), //DOCUMENTED // JMETER_HOME_OPT("d"), //ALWAYS_SET - The JMeter dir structure is created by the plugin. // REPORT_AT_END_OPT("e"), //DOCUMENTED // HELP_OPT("h"), //NOT_USED - Prints help information and exits. // REPORT_GENERATING_OPT("g"), //NOT_USED - We always generate reports in the verify phase. // SERVER_OPT("s"), //AUTOMATICALLY_SET - This is used hwne JMeter is started in server mode. // JMLOGFILE_OPT("j"), //ALWAYS_SET - Test name is used for logfile name (<testname>.log). // LOGFILE_OPT("l"), //ALWAYS_SET - Test name is used for logfile name (<testname>.jtl). // NONGUI_OPT("n"), //DOCUMENTED // REPORT_OUTPUT_FOLDER_OPT("o"), //DOCUMENTED // PROPFILE_OPT("p"), //NOT_USED - We place the jmeter.properties in the correct place on the filesystem. // PROPFILE2_OPT("q"), //DOCUMENTED // REMOTE_OPT("r"), //DOCUMENTED // TESTFILE_OPT("t"), //ALWAYS_SET - This is how we pass our test file list over to JMeter. // PROXY_USERNAME("u"), //DOCUMENTED // VERSION_OPT("v"), //NOT_USED - Prints version information and exits. // SYSTEM_PROPERTY("D"), //DOCUMENTED // JMETER_GLOBAL_PROP("G"), //DOCUMENTED // PROXY_HOST("H"), //DOCUMENTED // JMETER_PROPERTY("J"), //DOCUMENTED // LOGLEVEL("L"), //DOCUMENTED // NONPROXY_HOSTS("N"), //DOCUMENTED // PROXY_PORT("P"), //DOCUMENTED // REMOTE_OPT_PARAM("R"), //DOCUMENTED // SYSTEM_PROPFILE("S"), //NOT_USED - We place the system.properties in the correct place on the filesystem. // REMOTE_STOP("X"); //DOCUMENTED // // private final String commandLineArgument; // // JMeterCommandLineArguments(String commandLineArgument) { // this.commandLineArgument = commandLineArgument; // } // // public String getCommandLineArgument() { // return "-" + commandLineArgument; // } // // } // // Path: src/main/java/com/lazerycode/jmeter/utility/UtilityFunctions.java // public static Boolean isNotSet(Map<?, ?> value) { // return null == value || value.isEmpty(); // } // // Path: src/main/java/com/lazerycode/jmeter/utility/UtilityFunctions.java // public static Boolean isSet(String value) { // return !isNotSet(value); // }
import org.apache.commons.io.FilenameUtils; import org.apache.maven.plugin.MojoExecutionException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.File; import java.time.LocalDateTime; import java.time.format.DateTimeFormatter; import java.util.ArrayList; import java.util.List; import java.util.TreeSet; import static com.lazerycode.jmeter.configuration.JMeterCommandLineArguments.*; import static com.lazerycode.jmeter.utility.UtilityFunctions.isNotSet; import static com.lazerycode.jmeter.utility.UtilityFunctions.isSet;
package com.lazerycode.jmeter.configuration; /** * Creates an arguments array to pass to the JMeter object to run tests. * * @author Mark Collin */ public class JMeterArgumentsArray { private static final Logger LOGGER = LoggerFactory.getLogger(JMeterArgumentsArray.class); private final String jMeterHome; private boolean disableTests;
// Path: src/main/java/com/lazerycode/jmeter/configuration/JMeterCommandLineArguments.java // public enum JMeterCommandLineArguments { // // PROXY_PASSWORD("a"), //DOCUMENTED // JMETER_HOME_OPT("d"), //ALWAYS_SET - The JMeter dir structure is created by the plugin. // REPORT_AT_END_OPT("e"), //DOCUMENTED // HELP_OPT("h"), //NOT_USED - Prints help information and exits. // REPORT_GENERATING_OPT("g"), //NOT_USED - We always generate reports in the verify phase. // SERVER_OPT("s"), //AUTOMATICALLY_SET - This is used hwne JMeter is started in server mode. // JMLOGFILE_OPT("j"), //ALWAYS_SET - Test name is used for logfile name (<testname>.log). // LOGFILE_OPT("l"), //ALWAYS_SET - Test name is used for logfile name (<testname>.jtl). // NONGUI_OPT("n"), //DOCUMENTED // REPORT_OUTPUT_FOLDER_OPT("o"), //DOCUMENTED // PROPFILE_OPT("p"), //NOT_USED - We place the jmeter.properties in the correct place on the filesystem. // PROPFILE2_OPT("q"), //DOCUMENTED // REMOTE_OPT("r"), //DOCUMENTED // TESTFILE_OPT("t"), //ALWAYS_SET - This is how we pass our test file list over to JMeter. // PROXY_USERNAME("u"), //DOCUMENTED // VERSION_OPT("v"), //NOT_USED - Prints version information and exits. // SYSTEM_PROPERTY("D"), //DOCUMENTED // JMETER_GLOBAL_PROP("G"), //DOCUMENTED // PROXY_HOST("H"), //DOCUMENTED // JMETER_PROPERTY("J"), //DOCUMENTED // LOGLEVEL("L"), //DOCUMENTED // NONPROXY_HOSTS("N"), //DOCUMENTED // PROXY_PORT("P"), //DOCUMENTED // REMOTE_OPT_PARAM("R"), //DOCUMENTED // SYSTEM_PROPFILE("S"), //NOT_USED - We place the system.properties in the correct place on the filesystem. // REMOTE_STOP("X"); //DOCUMENTED // // private final String commandLineArgument; // // JMeterCommandLineArguments(String commandLineArgument) { // this.commandLineArgument = commandLineArgument; // } // // public String getCommandLineArgument() { // return "-" + commandLineArgument; // } // // } // // Path: src/main/java/com/lazerycode/jmeter/utility/UtilityFunctions.java // public static Boolean isNotSet(Map<?, ?> value) { // return null == value || value.isEmpty(); // } // // Path: src/main/java/com/lazerycode/jmeter/utility/UtilityFunctions.java // public static Boolean isSet(String value) { // return !isNotSet(value); // } // Path: src/main/java/com/lazerycode/jmeter/configuration/JMeterArgumentsArray.java import org.apache.commons.io.FilenameUtils; import org.apache.maven.plugin.MojoExecutionException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.File; import java.time.LocalDateTime; import java.time.format.DateTimeFormatter; import java.util.ArrayList; import java.util.List; import java.util.TreeSet; import static com.lazerycode.jmeter.configuration.JMeterCommandLineArguments.*; import static com.lazerycode.jmeter.utility.UtilityFunctions.isNotSet; import static com.lazerycode.jmeter.utility.UtilityFunctions.isSet; package com.lazerycode.jmeter.configuration; /** * Creates an arguments array to pass to the JMeter object to run tests. * * @author Mark Collin */ public class JMeterArgumentsArray { private static final Logger LOGGER = LoggerFactory.getLogger(JMeterArgumentsArray.class); private final String jMeterHome; private boolean disableTests;
private final TreeSet<JMeterCommandLineArguments> argumentList = new TreeSet<>();
jmeter-maven-plugin/jmeter-maven-plugin
src/main/java/com/lazerycode/jmeter/configuration/JMeterArgumentsArray.java
// Path: src/main/java/com/lazerycode/jmeter/configuration/JMeterCommandLineArguments.java // public enum JMeterCommandLineArguments { // // PROXY_PASSWORD("a"), //DOCUMENTED // JMETER_HOME_OPT("d"), //ALWAYS_SET - The JMeter dir structure is created by the plugin. // REPORT_AT_END_OPT("e"), //DOCUMENTED // HELP_OPT("h"), //NOT_USED - Prints help information and exits. // REPORT_GENERATING_OPT("g"), //NOT_USED - We always generate reports in the verify phase. // SERVER_OPT("s"), //AUTOMATICALLY_SET - This is used hwne JMeter is started in server mode. // JMLOGFILE_OPT("j"), //ALWAYS_SET - Test name is used for logfile name (<testname>.log). // LOGFILE_OPT("l"), //ALWAYS_SET - Test name is used for logfile name (<testname>.jtl). // NONGUI_OPT("n"), //DOCUMENTED // REPORT_OUTPUT_FOLDER_OPT("o"), //DOCUMENTED // PROPFILE_OPT("p"), //NOT_USED - We place the jmeter.properties in the correct place on the filesystem. // PROPFILE2_OPT("q"), //DOCUMENTED // REMOTE_OPT("r"), //DOCUMENTED // TESTFILE_OPT("t"), //ALWAYS_SET - This is how we pass our test file list over to JMeter. // PROXY_USERNAME("u"), //DOCUMENTED // VERSION_OPT("v"), //NOT_USED - Prints version information and exits. // SYSTEM_PROPERTY("D"), //DOCUMENTED // JMETER_GLOBAL_PROP("G"), //DOCUMENTED // PROXY_HOST("H"), //DOCUMENTED // JMETER_PROPERTY("J"), //DOCUMENTED // LOGLEVEL("L"), //DOCUMENTED // NONPROXY_HOSTS("N"), //DOCUMENTED // PROXY_PORT("P"), //DOCUMENTED // REMOTE_OPT_PARAM("R"), //DOCUMENTED // SYSTEM_PROPFILE("S"), //NOT_USED - We place the system.properties in the correct place on the filesystem. // REMOTE_STOP("X"); //DOCUMENTED // // private final String commandLineArgument; // // JMeterCommandLineArguments(String commandLineArgument) { // this.commandLineArgument = commandLineArgument; // } // // public String getCommandLineArgument() { // return "-" + commandLineArgument; // } // // } // // Path: src/main/java/com/lazerycode/jmeter/utility/UtilityFunctions.java // public static Boolean isNotSet(Map<?, ?> value) { // return null == value || value.isEmpty(); // } // // Path: src/main/java/com/lazerycode/jmeter/utility/UtilityFunctions.java // public static Boolean isSet(String value) { // return !isNotSet(value); // }
import org.apache.commons.io.FilenameUtils; import org.apache.maven.plugin.MojoExecutionException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.File; import java.time.LocalDateTime; import java.time.format.DateTimeFormatter; import java.util.ArrayList; import java.util.List; import java.util.TreeSet; import static com.lazerycode.jmeter.configuration.JMeterCommandLineArguments.*; import static com.lazerycode.jmeter.utility.UtilityFunctions.isNotSet; import static com.lazerycode.jmeter.utility.UtilityFunctions.isSet;
package com.lazerycode.jmeter.configuration; /** * Creates an arguments array to pass to the JMeter object to run tests. * * @author Mark Collin */ public class JMeterArgumentsArray { private static final Logger LOGGER = LoggerFactory.getLogger(JMeterArgumentsArray.class); private final String jMeterHome; private boolean disableTests; private final TreeSet<JMeterCommandLineArguments> argumentList = new TreeSet<>(); private DateTimeFormatter dateFormat = DateTimeFormatter.BASIC_ISO_DATE; private ProxyConfiguration proxyConfiguration; private boolean timestampResults = false; private boolean appendTimestamp = false; private String resultFileExtension = ".jtl"; private String remoteStartServerList; private List<String> customPropertiesFiles = new ArrayList<>(); private String testFile; private String resultsLogFileName; private String jmeterLogFileName; private String logsDirectory; private String resultsDirectory; private String reportDirectory; private LogLevel overrideRootLogLevel; /** * Create an instance of JMeterArgumentsArray * * @param disableGUI If GUI should be disabled or not * @param jMeterHomeDirectory The JMETER_HOME directory, what JMeter bases its classpath on * @throws MojoExecutionException Exception */ public JMeterArgumentsArray(boolean disableGUI, String jMeterHomeDirectory) throws MojoExecutionException {
// Path: src/main/java/com/lazerycode/jmeter/configuration/JMeterCommandLineArguments.java // public enum JMeterCommandLineArguments { // // PROXY_PASSWORD("a"), //DOCUMENTED // JMETER_HOME_OPT("d"), //ALWAYS_SET - The JMeter dir structure is created by the plugin. // REPORT_AT_END_OPT("e"), //DOCUMENTED // HELP_OPT("h"), //NOT_USED - Prints help information and exits. // REPORT_GENERATING_OPT("g"), //NOT_USED - We always generate reports in the verify phase. // SERVER_OPT("s"), //AUTOMATICALLY_SET - This is used hwne JMeter is started in server mode. // JMLOGFILE_OPT("j"), //ALWAYS_SET - Test name is used for logfile name (<testname>.log). // LOGFILE_OPT("l"), //ALWAYS_SET - Test name is used for logfile name (<testname>.jtl). // NONGUI_OPT("n"), //DOCUMENTED // REPORT_OUTPUT_FOLDER_OPT("o"), //DOCUMENTED // PROPFILE_OPT("p"), //NOT_USED - We place the jmeter.properties in the correct place on the filesystem. // PROPFILE2_OPT("q"), //DOCUMENTED // REMOTE_OPT("r"), //DOCUMENTED // TESTFILE_OPT("t"), //ALWAYS_SET - This is how we pass our test file list over to JMeter. // PROXY_USERNAME("u"), //DOCUMENTED // VERSION_OPT("v"), //NOT_USED - Prints version information and exits. // SYSTEM_PROPERTY("D"), //DOCUMENTED // JMETER_GLOBAL_PROP("G"), //DOCUMENTED // PROXY_HOST("H"), //DOCUMENTED // JMETER_PROPERTY("J"), //DOCUMENTED // LOGLEVEL("L"), //DOCUMENTED // NONPROXY_HOSTS("N"), //DOCUMENTED // PROXY_PORT("P"), //DOCUMENTED // REMOTE_OPT_PARAM("R"), //DOCUMENTED // SYSTEM_PROPFILE("S"), //NOT_USED - We place the system.properties in the correct place on the filesystem. // REMOTE_STOP("X"); //DOCUMENTED // // private final String commandLineArgument; // // JMeterCommandLineArguments(String commandLineArgument) { // this.commandLineArgument = commandLineArgument; // } // // public String getCommandLineArgument() { // return "-" + commandLineArgument; // } // // } // // Path: src/main/java/com/lazerycode/jmeter/utility/UtilityFunctions.java // public static Boolean isNotSet(Map<?, ?> value) { // return null == value || value.isEmpty(); // } // // Path: src/main/java/com/lazerycode/jmeter/utility/UtilityFunctions.java // public static Boolean isSet(String value) { // return !isNotSet(value); // } // Path: src/main/java/com/lazerycode/jmeter/configuration/JMeterArgumentsArray.java import org.apache.commons.io.FilenameUtils; import org.apache.maven.plugin.MojoExecutionException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.File; import java.time.LocalDateTime; import java.time.format.DateTimeFormatter; import java.util.ArrayList; import java.util.List; import java.util.TreeSet; import static com.lazerycode.jmeter.configuration.JMeterCommandLineArguments.*; import static com.lazerycode.jmeter.utility.UtilityFunctions.isNotSet; import static com.lazerycode.jmeter.utility.UtilityFunctions.isSet; package com.lazerycode.jmeter.configuration; /** * Creates an arguments array to pass to the JMeter object to run tests. * * @author Mark Collin */ public class JMeterArgumentsArray { private static final Logger LOGGER = LoggerFactory.getLogger(JMeterArgumentsArray.class); private final String jMeterHome; private boolean disableTests; private final TreeSet<JMeterCommandLineArguments> argumentList = new TreeSet<>(); private DateTimeFormatter dateFormat = DateTimeFormatter.BASIC_ISO_DATE; private ProxyConfiguration proxyConfiguration; private boolean timestampResults = false; private boolean appendTimestamp = false; private String resultFileExtension = ".jtl"; private String remoteStartServerList; private List<String> customPropertiesFiles = new ArrayList<>(); private String testFile; private String resultsLogFileName; private String jmeterLogFileName; private String logsDirectory; private String resultsDirectory; private String reportDirectory; private LogLevel overrideRootLogLevel; /** * Create an instance of JMeterArgumentsArray * * @param disableGUI If GUI should be disabled or not * @param jMeterHomeDirectory The JMETER_HOME directory, what JMeter bases its classpath on * @throws MojoExecutionException Exception */ public JMeterArgumentsArray(boolean disableGUI, String jMeterHomeDirectory) throws MojoExecutionException {
if (isNotSet(jMeterHomeDirectory)) {
jmeter-maven-plugin/jmeter-maven-plugin
src/main/java/com/lazerycode/jmeter/configuration/JMeterArgumentsArray.java
// Path: src/main/java/com/lazerycode/jmeter/configuration/JMeterCommandLineArguments.java // public enum JMeterCommandLineArguments { // // PROXY_PASSWORD("a"), //DOCUMENTED // JMETER_HOME_OPT("d"), //ALWAYS_SET - The JMeter dir structure is created by the plugin. // REPORT_AT_END_OPT("e"), //DOCUMENTED // HELP_OPT("h"), //NOT_USED - Prints help information and exits. // REPORT_GENERATING_OPT("g"), //NOT_USED - We always generate reports in the verify phase. // SERVER_OPT("s"), //AUTOMATICALLY_SET - This is used hwne JMeter is started in server mode. // JMLOGFILE_OPT("j"), //ALWAYS_SET - Test name is used for logfile name (<testname>.log). // LOGFILE_OPT("l"), //ALWAYS_SET - Test name is used for logfile name (<testname>.jtl). // NONGUI_OPT("n"), //DOCUMENTED // REPORT_OUTPUT_FOLDER_OPT("o"), //DOCUMENTED // PROPFILE_OPT("p"), //NOT_USED - We place the jmeter.properties in the correct place on the filesystem. // PROPFILE2_OPT("q"), //DOCUMENTED // REMOTE_OPT("r"), //DOCUMENTED // TESTFILE_OPT("t"), //ALWAYS_SET - This is how we pass our test file list over to JMeter. // PROXY_USERNAME("u"), //DOCUMENTED // VERSION_OPT("v"), //NOT_USED - Prints version information and exits. // SYSTEM_PROPERTY("D"), //DOCUMENTED // JMETER_GLOBAL_PROP("G"), //DOCUMENTED // PROXY_HOST("H"), //DOCUMENTED // JMETER_PROPERTY("J"), //DOCUMENTED // LOGLEVEL("L"), //DOCUMENTED // NONPROXY_HOSTS("N"), //DOCUMENTED // PROXY_PORT("P"), //DOCUMENTED // REMOTE_OPT_PARAM("R"), //DOCUMENTED // SYSTEM_PROPFILE("S"), //NOT_USED - We place the system.properties in the correct place on the filesystem. // REMOTE_STOP("X"); //DOCUMENTED // // private final String commandLineArgument; // // JMeterCommandLineArguments(String commandLineArgument) { // this.commandLineArgument = commandLineArgument; // } // // public String getCommandLineArgument() { // return "-" + commandLineArgument; // } // // } // // Path: src/main/java/com/lazerycode/jmeter/utility/UtilityFunctions.java // public static Boolean isNotSet(Map<?, ?> value) { // return null == value || value.isEmpty(); // } // // Path: src/main/java/com/lazerycode/jmeter/utility/UtilityFunctions.java // public static Boolean isSet(String value) { // return !isNotSet(value); // }
import org.apache.commons.io.FilenameUtils; import org.apache.maven.plugin.MojoExecutionException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.File; import java.time.LocalDateTime; import java.time.format.DateTimeFormatter; import java.util.ArrayList; import java.util.List; import java.util.TreeSet; import static com.lazerycode.jmeter.configuration.JMeterCommandLineArguments.*; import static com.lazerycode.jmeter.utility.UtilityFunctions.isNotSet; import static com.lazerycode.jmeter.utility.UtilityFunctions.isSet;
disableTests = false; } else { disableTests = true; } } public JMeterArgumentsArray setRemoteStop() { argumentList.add(REMOTE_STOP); return this; } public JMeterArgumentsArray setRemoteStart() { argumentList.add(REMOTE_OPT); return this; } public JMeterArgumentsArray setRemoteStartServerList(String serverList) { if (isNotSet(serverList)) return this; remoteStartServerList = serverList; argumentList.add(REMOTE_OPT_PARAM); return this; } public JMeterArgumentsArray setProxyConfig(ProxyConfiguration configuration) { if (configuration == null) return this; this.proxyConfiguration = configuration;
// Path: src/main/java/com/lazerycode/jmeter/configuration/JMeterCommandLineArguments.java // public enum JMeterCommandLineArguments { // // PROXY_PASSWORD("a"), //DOCUMENTED // JMETER_HOME_OPT("d"), //ALWAYS_SET - The JMeter dir structure is created by the plugin. // REPORT_AT_END_OPT("e"), //DOCUMENTED // HELP_OPT("h"), //NOT_USED - Prints help information and exits. // REPORT_GENERATING_OPT("g"), //NOT_USED - We always generate reports in the verify phase. // SERVER_OPT("s"), //AUTOMATICALLY_SET - This is used hwne JMeter is started in server mode. // JMLOGFILE_OPT("j"), //ALWAYS_SET - Test name is used for logfile name (<testname>.log). // LOGFILE_OPT("l"), //ALWAYS_SET - Test name is used for logfile name (<testname>.jtl). // NONGUI_OPT("n"), //DOCUMENTED // REPORT_OUTPUT_FOLDER_OPT("o"), //DOCUMENTED // PROPFILE_OPT("p"), //NOT_USED - We place the jmeter.properties in the correct place on the filesystem. // PROPFILE2_OPT("q"), //DOCUMENTED // REMOTE_OPT("r"), //DOCUMENTED // TESTFILE_OPT("t"), //ALWAYS_SET - This is how we pass our test file list over to JMeter. // PROXY_USERNAME("u"), //DOCUMENTED // VERSION_OPT("v"), //NOT_USED - Prints version information and exits. // SYSTEM_PROPERTY("D"), //DOCUMENTED // JMETER_GLOBAL_PROP("G"), //DOCUMENTED // PROXY_HOST("H"), //DOCUMENTED // JMETER_PROPERTY("J"), //DOCUMENTED // LOGLEVEL("L"), //DOCUMENTED // NONPROXY_HOSTS("N"), //DOCUMENTED // PROXY_PORT("P"), //DOCUMENTED // REMOTE_OPT_PARAM("R"), //DOCUMENTED // SYSTEM_PROPFILE("S"), //NOT_USED - We place the system.properties in the correct place on the filesystem. // REMOTE_STOP("X"); //DOCUMENTED // // private final String commandLineArgument; // // JMeterCommandLineArguments(String commandLineArgument) { // this.commandLineArgument = commandLineArgument; // } // // public String getCommandLineArgument() { // return "-" + commandLineArgument; // } // // } // // Path: src/main/java/com/lazerycode/jmeter/utility/UtilityFunctions.java // public static Boolean isNotSet(Map<?, ?> value) { // return null == value || value.isEmpty(); // } // // Path: src/main/java/com/lazerycode/jmeter/utility/UtilityFunctions.java // public static Boolean isSet(String value) { // return !isNotSet(value); // } // Path: src/main/java/com/lazerycode/jmeter/configuration/JMeterArgumentsArray.java import org.apache.commons.io.FilenameUtils; import org.apache.maven.plugin.MojoExecutionException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.File; import java.time.LocalDateTime; import java.time.format.DateTimeFormatter; import java.util.ArrayList; import java.util.List; import java.util.TreeSet; import static com.lazerycode.jmeter.configuration.JMeterCommandLineArguments.*; import static com.lazerycode.jmeter.utility.UtilityFunctions.isNotSet; import static com.lazerycode.jmeter.utility.UtilityFunctions.isSet; disableTests = false; } else { disableTests = true; } } public JMeterArgumentsArray setRemoteStop() { argumentList.add(REMOTE_STOP); return this; } public JMeterArgumentsArray setRemoteStart() { argumentList.add(REMOTE_OPT); return this; } public JMeterArgumentsArray setRemoteStartServerList(String serverList) { if (isNotSet(serverList)) return this; remoteStartServerList = serverList; argumentList.add(REMOTE_OPT_PARAM); return this; } public JMeterArgumentsArray setProxyConfig(ProxyConfiguration configuration) { if (configuration == null) return this; this.proxyConfiguration = configuration;
if (isSet(proxyConfiguration.getHost())) {
jmeter-maven-plugin/jmeter-maven-plugin
src/main/java/com/lazerycode/jmeter/configuration/RemoteConfiguration.java
// Path: src/main/java/com/lazerycode/jmeter/properties/ConfigurationFiles.java // public enum ConfigurationFiles { // // JMETER_PROPERTIES("jmeter.properties", true), // SAVE_SERVICE_PROPERTIES("saveservice.properties", true), // UPGRADE_PROPERTIES("upgrade.properties", true), // SYSTEM_PROPERTIES("system.properties", true), // USER_PROPERTIES("user.properties", true), // REPORT_GENERATOR_PROPERTIES("reportgenerator.properties", true), // GLOBAL_PROPERTIES("global.properties", false); // // private final String propertiesFilename; // private final boolean isRequired; // // ConfigurationFiles(String propertiesFilename, boolean isRequired) { // this.propertiesFilename = propertiesFilename; // this.isRequired = isRequired; // } // // public String getFilename() { // return propertiesFilename; // } // // public boolean createFileIfItDoesNotExist() { // return isRequired; // } // // } // // Path: src/main/java/com/lazerycode/jmeter/properties/PropertiesMapping.java // public class PropertiesMapping { // protected Map<String, String> additionalProperties; // private PropertiesFile propertiesFile; // // @JsonCreator // public PropertiesMapping(@JsonProperty("additionalProperties") Map<String, String> additionalProperties) { // this.additionalProperties = additionalProperties; // } // // public Map<String, String> getAdditionalProperties() { // return additionalProperties; // } // // public PropertiesFile getPropertiesFile() { // return propertiesFile; // } // // public void setPropertiesFile(PropertiesFile propertiesFile) { // this.propertiesFile = propertiesFile; // } // }
import com.lazerycode.jmeter.properties.ConfigurationFiles; import com.lazerycode.jmeter.properties.PropertiesMapping; import java.util.EnumMap; import java.util.Map;
package com.lazerycode.jmeter.configuration; /** * This is used by the TestManager to configure remote serverList and stopServersAfterTests settings for each test run. * <br> * Configuration in pom.xml: * <br> * <pre> * {@code * <remoteConfig> * <stopServersAfterTests></stopServersAfterTests> * <startServersBeforeTests></startServersBeforeTests> * <serverList></serverList> * <startAndStopServersForEachTest></startAndStopServersForEachTest> * </remoteConfig> * } * </pre> * * @author Arne Franken */ @SuppressWarnings({"UnusedDeclaration", "FieldCanBeLocal"}) public class RemoteConfiguration { private boolean startServersBeforeTests = false; private boolean stopServersAfterTests = false; private boolean startAndStopServersForEachTest = false; private String serverList = "";
// Path: src/main/java/com/lazerycode/jmeter/properties/ConfigurationFiles.java // public enum ConfigurationFiles { // // JMETER_PROPERTIES("jmeter.properties", true), // SAVE_SERVICE_PROPERTIES("saveservice.properties", true), // UPGRADE_PROPERTIES("upgrade.properties", true), // SYSTEM_PROPERTIES("system.properties", true), // USER_PROPERTIES("user.properties", true), // REPORT_GENERATOR_PROPERTIES("reportgenerator.properties", true), // GLOBAL_PROPERTIES("global.properties", false); // // private final String propertiesFilename; // private final boolean isRequired; // // ConfigurationFiles(String propertiesFilename, boolean isRequired) { // this.propertiesFilename = propertiesFilename; // this.isRequired = isRequired; // } // // public String getFilename() { // return propertiesFilename; // } // // public boolean createFileIfItDoesNotExist() { // return isRequired; // } // // } // // Path: src/main/java/com/lazerycode/jmeter/properties/PropertiesMapping.java // public class PropertiesMapping { // protected Map<String, String> additionalProperties; // private PropertiesFile propertiesFile; // // @JsonCreator // public PropertiesMapping(@JsonProperty("additionalProperties") Map<String, String> additionalProperties) { // this.additionalProperties = additionalProperties; // } // // public Map<String, String> getAdditionalProperties() { // return additionalProperties; // } // // public PropertiesFile getPropertiesFile() { // return propertiesFile; // } // // public void setPropertiesFile(PropertiesFile propertiesFile) { // this.propertiesFile = propertiesFile; // } // } // Path: src/main/java/com/lazerycode/jmeter/configuration/RemoteConfiguration.java import com.lazerycode.jmeter.properties.ConfigurationFiles; import com.lazerycode.jmeter.properties.PropertiesMapping; import java.util.EnumMap; import java.util.Map; package com.lazerycode.jmeter.configuration; /** * This is used by the TestManager to configure remote serverList and stopServersAfterTests settings for each test run. * <br> * Configuration in pom.xml: * <br> * <pre> * {@code * <remoteConfig> * <stopServersAfterTests></stopServersAfterTests> * <startServersBeforeTests></startServersBeforeTests> * <serverList></serverList> * <startAndStopServersForEachTest></startAndStopServersForEachTest> * </remoteConfig> * } * </pre> * * @author Arne Franken */ @SuppressWarnings({"UnusedDeclaration", "FieldCanBeLocal"}) public class RemoteConfiguration { private boolean startServersBeforeTests = false; private boolean stopServersAfterTests = false; private boolean startAndStopServersForEachTest = false; private String serverList = "";
private Map<ConfigurationFiles, PropertiesMapping> propertiesMap = new EnumMap<>(ConfigurationFiles.class);
jmeter-maven-plugin/jmeter-maven-plugin
src/main/java/com/lazerycode/jmeter/configuration/RemoteConfiguration.java
// Path: src/main/java/com/lazerycode/jmeter/properties/ConfigurationFiles.java // public enum ConfigurationFiles { // // JMETER_PROPERTIES("jmeter.properties", true), // SAVE_SERVICE_PROPERTIES("saveservice.properties", true), // UPGRADE_PROPERTIES("upgrade.properties", true), // SYSTEM_PROPERTIES("system.properties", true), // USER_PROPERTIES("user.properties", true), // REPORT_GENERATOR_PROPERTIES("reportgenerator.properties", true), // GLOBAL_PROPERTIES("global.properties", false); // // private final String propertiesFilename; // private final boolean isRequired; // // ConfigurationFiles(String propertiesFilename, boolean isRequired) { // this.propertiesFilename = propertiesFilename; // this.isRequired = isRequired; // } // // public String getFilename() { // return propertiesFilename; // } // // public boolean createFileIfItDoesNotExist() { // return isRequired; // } // // } // // Path: src/main/java/com/lazerycode/jmeter/properties/PropertiesMapping.java // public class PropertiesMapping { // protected Map<String, String> additionalProperties; // private PropertiesFile propertiesFile; // // @JsonCreator // public PropertiesMapping(@JsonProperty("additionalProperties") Map<String, String> additionalProperties) { // this.additionalProperties = additionalProperties; // } // // public Map<String, String> getAdditionalProperties() { // return additionalProperties; // } // // public PropertiesFile getPropertiesFile() { // return propertiesFile; // } // // public void setPropertiesFile(PropertiesFile propertiesFile) { // this.propertiesFile = propertiesFile; // } // }
import com.lazerycode.jmeter.properties.ConfigurationFiles; import com.lazerycode.jmeter.properties.PropertiesMapping; import java.util.EnumMap; import java.util.Map;
package com.lazerycode.jmeter.configuration; /** * This is used by the TestManager to configure remote serverList and stopServersAfterTests settings for each test run. * <br> * Configuration in pom.xml: * <br> * <pre> * {@code * <remoteConfig> * <stopServersAfterTests></stopServersAfterTests> * <startServersBeforeTests></startServersBeforeTests> * <serverList></serverList> * <startAndStopServersForEachTest></startAndStopServersForEachTest> * </remoteConfig> * } * </pre> * * @author Arne Franken */ @SuppressWarnings({"UnusedDeclaration", "FieldCanBeLocal"}) public class RemoteConfiguration { private boolean startServersBeforeTests = false; private boolean stopServersAfterTests = false; private boolean startAndStopServersForEachTest = false; private String serverList = "";
// Path: src/main/java/com/lazerycode/jmeter/properties/ConfigurationFiles.java // public enum ConfigurationFiles { // // JMETER_PROPERTIES("jmeter.properties", true), // SAVE_SERVICE_PROPERTIES("saveservice.properties", true), // UPGRADE_PROPERTIES("upgrade.properties", true), // SYSTEM_PROPERTIES("system.properties", true), // USER_PROPERTIES("user.properties", true), // REPORT_GENERATOR_PROPERTIES("reportgenerator.properties", true), // GLOBAL_PROPERTIES("global.properties", false); // // private final String propertiesFilename; // private final boolean isRequired; // // ConfigurationFiles(String propertiesFilename, boolean isRequired) { // this.propertiesFilename = propertiesFilename; // this.isRequired = isRequired; // } // // public String getFilename() { // return propertiesFilename; // } // // public boolean createFileIfItDoesNotExist() { // return isRequired; // } // // } // // Path: src/main/java/com/lazerycode/jmeter/properties/PropertiesMapping.java // public class PropertiesMapping { // protected Map<String, String> additionalProperties; // private PropertiesFile propertiesFile; // // @JsonCreator // public PropertiesMapping(@JsonProperty("additionalProperties") Map<String, String> additionalProperties) { // this.additionalProperties = additionalProperties; // } // // public Map<String, String> getAdditionalProperties() { // return additionalProperties; // } // // public PropertiesFile getPropertiesFile() { // return propertiesFile; // } // // public void setPropertiesFile(PropertiesFile propertiesFile) { // this.propertiesFile = propertiesFile; // } // } // Path: src/main/java/com/lazerycode/jmeter/configuration/RemoteConfiguration.java import com.lazerycode.jmeter.properties.ConfigurationFiles; import com.lazerycode.jmeter.properties.PropertiesMapping; import java.util.EnumMap; import java.util.Map; package com.lazerycode.jmeter.configuration; /** * This is used by the TestManager to configure remote serverList and stopServersAfterTests settings for each test run. * <br> * Configuration in pom.xml: * <br> * <pre> * {@code * <remoteConfig> * <stopServersAfterTests></stopServersAfterTests> * <startServersBeforeTests></startServersBeforeTests> * <serverList></serverList> * <startAndStopServersForEachTest></startAndStopServersForEachTest> * </remoteConfig> * } * </pre> * * @author Arne Franken */ @SuppressWarnings({"UnusedDeclaration", "FieldCanBeLocal"}) public class RemoteConfiguration { private boolean startServersBeforeTests = false; private boolean stopServersAfterTests = false; private boolean startAndStopServersForEachTest = false; private String serverList = "";
private Map<ConfigurationFiles, PropertiesMapping> propertiesMap = new EnumMap<>(ConfigurationFiles.class);
jmeter-maven-plugin/jmeter-maven-plugin
src/main/java/com/lazerycode/jmeter/configuration/RemoteArgumentsArrayBuilder.java
// Path: src/main/java/com/lazerycode/jmeter/properties/ConfigurationFiles.java // public enum ConfigurationFiles { // // JMETER_PROPERTIES("jmeter.properties", true), // SAVE_SERVICE_PROPERTIES("saveservice.properties", true), // UPGRADE_PROPERTIES("upgrade.properties", true), // SYSTEM_PROPERTIES("system.properties", true), // USER_PROPERTIES("user.properties", true), // REPORT_GENERATOR_PROPERTIES("reportgenerator.properties", true), // GLOBAL_PROPERTIES("global.properties", false); // // private final String propertiesFilename; // private final boolean isRequired; // // ConfigurationFiles(String propertiesFilename, boolean isRequired) { // this.propertiesFilename = propertiesFilename; // this.isRequired = isRequired; // } // // public String getFilename() { // return propertiesFilename; // } // // public boolean createFileIfItDoesNotExist() { // return isRequired; // } // // } // // Path: src/main/java/com/lazerycode/jmeter/properties/PropertiesMapping.java // public class PropertiesMapping { // protected Map<String, String> additionalProperties; // private PropertiesFile propertiesFile; // // @JsonCreator // public PropertiesMapping(@JsonProperty("additionalProperties") Map<String, String> additionalProperties) { // this.additionalProperties = additionalProperties; // } // // public Map<String, String> getAdditionalProperties() { // return additionalProperties; // } // // public PropertiesFile getPropertiesFile() { // return propertiesFile; // } // // public void setPropertiesFile(PropertiesFile propertiesFile) { // this.propertiesFile = propertiesFile; // } // }
import com.lazerycode.jmeter.properties.ConfigurationFiles; import com.lazerycode.jmeter.properties.PropertiesMapping; import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.Properties;
package com.lazerycode.jmeter.configuration; public class RemoteArgumentsArrayBuilder { /** * Make constructor private as this is a non-instantiable helper classes */ RemoteArgumentsArrayBuilder() throws InstantiationError { throw new InstantiationError("This class is non-instantiable."); }
// Path: src/main/java/com/lazerycode/jmeter/properties/ConfigurationFiles.java // public enum ConfigurationFiles { // // JMETER_PROPERTIES("jmeter.properties", true), // SAVE_SERVICE_PROPERTIES("saveservice.properties", true), // UPGRADE_PROPERTIES("upgrade.properties", true), // SYSTEM_PROPERTIES("system.properties", true), // USER_PROPERTIES("user.properties", true), // REPORT_GENERATOR_PROPERTIES("reportgenerator.properties", true), // GLOBAL_PROPERTIES("global.properties", false); // // private final String propertiesFilename; // private final boolean isRequired; // // ConfigurationFiles(String propertiesFilename, boolean isRequired) { // this.propertiesFilename = propertiesFilename; // this.isRequired = isRequired; // } // // public String getFilename() { // return propertiesFilename; // } // // public boolean createFileIfItDoesNotExist() { // return isRequired; // } // // } // // Path: src/main/java/com/lazerycode/jmeter/properties/PropertiesMapping.java // public class PropertiesMapping { // protected Map<String, String> additionalProperties; // private PropertiesFile propertiesFile; // // @JsonCreator // public PropertiesMapping(@JsonProperty("additionalProperties") Map<String, String> additionalProperties) { // this.additionalProperties = additionalProperties; // } // // public Map<String, String> getAdditionalProperties() { // return additionalProperties; // } // // public PropertiesFile getPropertiesFile() { // return propertiesFile; // } // // public void setPropertiesFile(PropertiesFile propertiesFile) { // this.propertiesFile = propertiesFile; // } // } // Path: src/main/java/com/lazerycode/jmeter/configuration/RemoteArgumentsArrayBuilder.java import com.lazerycode.jmeter.properties.ConfigurationFiles; import com.lazerycode.jmeter.properties.PropertiesMapping; import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.Properties; package com.lazerycode.jmeter.configuration; public class RemoteArgumentsArrayBuilder { /** * Make constructor private as this is a non-instantiable helper classes */ RemoteArgumentsArrayBuilder() throws InstantiationError { throw new InstantiationError("This class is non-instantiable."); }
public static List<String> buildRemoteArgumentsArray(Map<ConfigurationFiles, PropertiesMapping> propertiesMap) {
jmeter-maven-plugin/jmeter-maven-plugin
src/main/java/com/lazerycode/jmeter/configuration/RemoteArgumentsArrayBuilder.java
// Path: src/main/java/com/lazerycode/jmeter/properties/ConfigurationFiles.java // public enum ConfigurationFiles { // // JMETER_PROPERTIES("jmeter.properties", true), // SAVE_SERVICE_PROPERTIES("saveservice.properties", true), // UPGRADE_PROPERTIES("upgrade.properties", true), // SYSTEM_PROPERTIES("system.properties", true), // USER_PROPERTIES("user.properties", true), // REPORT_GENERATOR_PROPERTIES("reportgenerator.properties", true), // GLOBAL_PROPERTIES("global.properties", false); // // private final String propertiesFilename; // private final boolean isRequired; // // ConfigurationFiles(String propertiesFilename, boolean isRequired) { // this.propertiesFilename = propertiesFilename; // this.isRequired = isRequired; // } // // public String getFilename() { // return propertiesFilename; // } // // public boolean createFileIfItDoesNotExist() { // return isRequired; // } // // } // // Path: src/main/java/com/lazerycode/jmeter/properties/PropertiesMapping.java // public class PropertiesMapping { // protected Map<String, String> additionalProperties; // private PropertiesFile propertiesFile; // // @JsonCreator // public PropertiesMapping(@JsonProperty("additionalProperties") Map<String, String> additionalProperties) { // this.additionalProperties = additionalProperties; // } // // public Map<String, String> getAdditionalProperties() { // return additionalProperties; // } // // public PropertiesFile getPropertiesFile() { // return propertiesFile; // } // // public void setPropertiesFile(PropertiesFile propertiesFile) { // this.propertiesFile = propertiesFile; // } // }
import com.lazerycode.jmeter.properties.ConfigurationFiles; import com.lazerycode.jmeter.properties.PropertiesMapping; import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.Properties;
package com.lazerycode.jmeter.configuration; public class RemoteArgumentsArrayBuilder { /** * Make constructor private as this is a non-instantiable helper classes */ RemoteArgumentsArrayBuilder() throws InstantiationError { throw new InstantiationError("This class is non-instantiable."); }
// Path: src/main/java/com/lazerycode/jmeter/properties/ConfigurationFiles.java // public enum ConfigurationFiles { // // JMETER_PROPERTIES("jmeter.properties", true), // SAVE_SERVICE_PROPERTIES("saveservice.properties", true), // UPGRADE_PROPERTIES("upgrade.properties", true), // SYSTEM_PROPERTIES("system.properties", true), // USER_PROPERTIES("user.properties", true), // REPORT_GENERATOR_PROPERTIES("reportgenerator.properties", true), // GLOBAL_PROPERTIES("global.properties", false); // // private final String propertiesFilename; // private final boolean isRequired; // // ConfigurationFiles(String propertiesFilename, boolean isRequired) { // this.propertiesFilename = propertiesFilename; // this.isRequired = isRequired; // } // // public String getFilename() { // return propertiesFilename; // } // // public boolean createFileIfItDoesNotExist() { // return isRequired; // } // // } // // Path: src/main/java/com/lazerycode/jmeter/properties/PropertiesMapping.java // public class PropertiesMapping { // protected Map<String, String> additionalProperties; // private PropertiesFile propertiesFile; // // @JsonCreator // public PropertiesMapping(@JsonProperty("additionalProperties") Map<String, String> additionalProperties) { // this.additionalProperties = additionalProperties; // } // // public Map<String, String> getAdditionalProperties() { // return additionalProperties; // } // // public PropertiesFile getPropertiesFile() { // return propertiesFile; // } // // public void setPropertiesFile(PropertiesFile propertiesFile) { // this.propertiesFile = propertiesFile; // } // } // Path: src/main/java/com/lazerycode/jmeter/configuration/RemoteArgumentsArrayBuilder.java import com.lazerycode.jmeter.properties.ConfigurationFiles; import com.lazerycode.jmeter.properties.PropertiesMapping; import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.Properties; package com.lazerycode.jmeter.configuration; public class RemoteArgumentsArrayBuilder { /** * Make constructor private as this is a non-instantiable helper classes */ RemoteArgumentsArrayBuilder() throws InstantiationError { throw new InstantiationError("This class is non-instantiable."); }
public static List<String> buildRemoteArgumentsArray(Map<ConfigurationFiles, PropertiesMapping> propertiesMap) {
jmeter-maven-plugin/jmeter-maven-plugin
src/main/java/com/lazerycode/jmeter/testrunner/JMeterProcessBuilder.java
// Path: src/main/java/com/lazerycode/jmeter/configuration/JMeterProcessJVMSettings.java // @SuppressWarnings({"UnusedDeclaration", "FieldCanBeLocal"}) // public class JMeterProcessJVMSettings { // // private int xms = 512; // private int xmx = 512; // private String javaRuntime = "java"; // private List<String> arguments = new ArrayList<>(); // // private static final String RUN_HEADLESS = "-Djava.awt.headless=true"; // private static final String HEADLESS_SETTING = "-Djava.awt.headless="; // // public JMeterProcessJVMSettings() { // super(); // } // // public int getXms() { // return xms; // } // // public int getXmx() { // return xmx; // } // // public List<String> getArguments() { // return arguments; // } // // public JMeterProcessJVMSettings addArgument(String newArgument) { // if (arguments.stream().noneMatch(argument -> argument.equals(newArgument))) { // arguments.add(newArgument); // } // // return this; // } // // public JMeterProcessJVMSettings setHeadlessDefaultIfRequired() { // if (arguments.stream().noneMatch(argument -> argument.contains(HEADLESS_SETTING))) { // addArgument(RUN_HEADLESS); // } // // return this; // } // // public String getJavaRuntime() { // return this.javaRuntime; // } // }
import com.lazerycode.jmeter.configuration.JMeterProcessJVMSettings; import org.apache.maven.plugin.MojoExecutionException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.File; import java.io.IOException; import java.text.MessageFormat; import java.util.ArrayList; import java.util.List;
package com.lazerycode.jmeter.testrunner; public class JMeterProcessBuilder { private static final Logger LOGGER = LoggerFactory.getLogger(JMeterProcessBuilder.class); private final int initialHeapSizeInMegaBytes; private final int maximumHeapSizeInMegaBytes; private final String runtimeJarName; private final String javaRuntime; private final List<String> userSuppliedArguments; private List<String> mainClassArguments = new ArrayList<>(); private String workingDirectory;
// Path: src/main/java/com/lazerycode/jmeter/configuration/JMeterProcessJVMSettings.java // @SuppressWarnings({"UnusedDeclaration", "FieldCanBeLocal"}) // public class JMeterProcessJVMSettings { // // private int xms = 512; // private int xmx = 512; // private String javaRuntime = "java"; // private List<String> arguments = new ArrayList<>(); // // private static final String RUN_HEADLESS = "-Djava.awt.headless=true"; // private static final String HEADLESS_SETTING = "-Djava.awt.headless="; // // public JMeterProcessJVMSettings() { // super(); // } // // public int getXms() { // return xms; // } // // public int getXmx() { // return xmx; // } // // public List<String> getArguments() { // return arguments; // } // // public JMeterProcessJVMSettings addArgument(String newArgument) { // if (arguments.stream().noneMatch(argument -> argument.equals(newArgument))) { // arguments.add(newArgument); // } // // return this; // } // // public JMeterProcessJVMSettings setHeadlessDefaultIfRequired() { // if (arguments.stream().noneMatch(argument -> argument.contains(HEADLESS_SETTING))) { // addArgument(RUN_HEADLESS); // } // // return this; // } // // public String getJavaRuntime() { // return this.javaRuntime; // } // } // Path: src/main/java/com/lazerycode/jmeter/testrunner/JMeterProcessBuilder.java import com.lazerycode.jmeter.configuration.JMeterProcessJVMSettings; import org.apache.maven.plugin.MojoExecutionException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.File; import java.io.IOException; import java.text.MessageFormat; import java.util.ArrayList; import java.util.List; package com.lazerycode.jmeter.testrunner; public class JMeterProcessBuilder { private static final Logger LOGGER = LoggerFactory.getLogger(JMeterProcessBuilder.class); private final int initialHeapSizeInMegaBytes; private final int maximumHeapSizeInMegaBytes; private final String runtimeJarName; private final String javaRuntime; private final List<String> userSuppliedArguments; private List<String> mainClassArguments = new ArrayList<>(); private String workingDirectory;
public JMeterProcessBuilder(JMeterProcessJVMSettings settings, String runtimeJarName) {
jmeter-maven-plugin/jmeter-maven-plugin
src/main/java/com/lazerycode/jmeter/configuration/ProxyConfiguration.java
// Path: src/main/java/com/lazerycode/jmeter/utility/UtilityFunctions.java // public static Boolean isNotSet(Map<?, ?> value) { // return null == value || value.isEmpty(); // } // // Path: src/main/java/com/lazerycode/jmeter/utility/UtilityFunctions.java // public static Boolean isSet(String value) { // return !isNotSet(value); // }
import static com.lazerycode.jmeter.utility.UtilityFunctions.isNotSet; import static com.lazerycode.jmeter.utility.UtilityFunctions.isSet;
package com.lazerycode.jmeter.configuration; /** * Is used for configuration of all proxy related configuration. * <br> * Configuration in pom.xml: * <br> * <pre> * {@code * <proxyConfig> * <host></host> * <port></port> * <username></username> * <password></password> * <hostExclusions></hostExclusions> * </proxyConfig> * } * </pre> * * @author Arne Franken */ public class ProxyConfiguration { private String hostExclusions = null; private String host = null; private Integer port = 80; private String username = null; private String password = null; /** * @return HTTP proxy host name */ public String getHost() { return host; } /** * HTTP proxy host name * * @param host String */ public void setHost(String host) { this.host = host; } /** * @return HTTP proxy port as long as a host is set */ public String getPort() {
// Path: src/main/java/com/lazerycode/jmeter/utility/UtilityFunctions.java // public static Boolean isNotSet(Map<?, ?> value) { // return null == value || value.isEmpty(); // } // // Path: src/main/java/com/lazerycode/jmeter/utility/UtilityFunctions.java // public static Boolean isSet(String value) { // return !isNotSet(value); // } // Path: src/main/java/com/lazerycode/jmeter/configuration/ProxyConfiguration.java import static com.lazerycode.jmeter.utility.UtilityFunctions.isNotSet; import static com.lazerycode.jmeter.utility.UtilityFunctions.isSet; package com.lazerycode.jmeter.configuration; /** * Is used for configuration of all proxy related configuration. * <br> * Configuration in pom.xml: * <br> * <pre> * {@code * <proxyConfig> * <host></host> * <port></port> * <username></username> * <password></password> * <hostExclusions></hostExclusions> * </proxyConfig> * } * </pre> * * @author Arne Franken */ public class ProxyConfiguration { private String hostExclusions = null; private String host = null; private Integer port = 80; private String username = null; private String password = null; /** * @return HTTP proxy host name */ public String getHost() { return host; } /** * HTTP proxy host name * * @param host String */ public void setHost(String host) { this.host = host; } /** * @return HTTP proxy port as long as a host is set */ public String getPort() {
if (isNotSet(host)) return null;
jmeter-maven-plugin/jmeter-maven-plugin
src/main/java/com/lazerycode/jmeter/configuration/ProxyConfiguration.java
// Path: src/main/java/com/lazerycode/jmeter/utility/UtilityFunctions.java // public static Boolean isNotSet(Map<?, ?> value) { // return null == value || value.isEmpty(); // } // // Path: src/main/java/com/lazerycode/jmeter/utility/UtilityFunctions.java // public static Boolean isSet(String value) { // return !isNotSet(value); // }
import static com.lazerycode.jmeter.utility.UtilityFunctions.isNotSet; import static com.lazerycode.jmeter.utility.UtilityFunctions.isSet;
*/ public void setPassword(String password) { this.password = password; } /** * @return Regex of hosts that will not be proxied as long as a host is set */ public String getHostExclusions() { if (isNotSet(host)) return null; return hostExclusions; } /** * Regex of hosts that will not be proxied * * @param hostExclusions String */ public void setHostExclusions(String hostExclusions) { this.hostExclusions = hostExclusions; } /** * Proxy details formatted for command line output. * * @return String */ @Override public String toString() { String proxyDetails = "Proxy server is not being used.";
// Path: src/main/java/com/lazerycode/jmeter/utility/UtilityFunctions.java // public static Boolean isNotSet(Map<?, ?> value) { // return null == value || value.isEmpty(); // } // // Path: src/main/java/com/lazerycode/jmeter/utility/UtilityFunctions.java // public static Boolean isSet(String value) { // return !isNotSet(value); // } // Path: src/main/java/com/lazerycode/jmeter/configuration/ProxyConfiguration.java import static com.lazerycode.jmeter.utility.UtilityFunctions.isNotSet; import static com.lazerycode.jmeter.utility.UtilityFunctions.isSet; */ public void setPassword(String password) { this.password = password; } /** * @return Regex of hosts that will not be proxied as long as a host is set */ public String getHostExclusions() { if (isNotSet(host)) return null; return hostExclusions; } /** * Regex of hosts that will not be proxied * * @param hostExclusions String */ public void setHostExclusions(String hostExclusions) { this.hostExclusions = hostExclusions; } /** * Proxy details formatted for command line output. * * @return String */ @Override public String toString() { String proxyDetails = "Proxy server is not being used.";
if (isSet(host)) {
jmeter-maven-plugin/jmeter-maven-plugin
src/main/java/com/lazerycode/jmeter/json/TestConfiguration.java
// Path: src/main/java/com/lazerycode/jmeter/properties/ConfigurationFiles.java // public enum ConfigurationFiles { // // JMETER_PROPERTIES("jmeter.properties", true), // SAVE_SERVICE_PROPERTIES("saveservice.properties", true), // UPGRADE_PROPERTIES("upgrade.properties", true), // SYSTEM_PROPERTIES("system.properties", true), // USER_PROPERTIES("user.properties", true), // REPORT_GENERATOR_PROPERTIES("reportgenerator.properties", true), // GLOBAL_PROPERTIES("global.properties", false); // // private final String propertiesFilename; // private final boolean isRequired; // // ConfigurationFiles(String propertiesFilename, boolean isRequired) { // this.propertiesFilename = propertiesFilename; // this.isRequired = isRequired; // } // // public String getFilename() { // return propertiesFilename; // } // // public boolean createFileIfItDoesNotExist() { // return isRequired; // } // // } // // Path: src/main/java/com/lazerycode/jmeter/properties/PropertiesMapping.java // public class PropertiesMapping { // protected Map<String, String> additionalProperties; // private PropertiesFile propertiesFile; // // @JsonCreator // public PropertiesMapping(@JsonProperty("additionalProperties") Map<String, String> additionalProperties) { // this.additionalProperties = additionalProperties; // } // // public Map<String, String> getAdditionalProperties() { // return additionalProperties; // } // // public PropertiesFile getPropertiesFile() { // return propertiesFile; // } // // public void setPropertiesFile(PropertiesFile propertiesFile) { // this.propertiesFile = propertiesFile; // } // }
import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.lazerycode.jmeter.properties.ConfigurationFiles; import com.lazerycode.jmeter.properties.PropertiesMapping; import java.io.File; import java.nio.file.Paths; import java.util.Arrays; import java.util.List; import java.util.Map; import java.util.Objects;
package com.lazerycode.jmeter.json; @JsonIgnoreProperties(ignoreUnknown = true) public class TestConfiguration { private String executionID; private String jmeterDirectoryPath; private String runtimeJarName; private Boolean resultsOutputIsCSVFormat; private Boolean generateReports; private String[] resultFilesLocations = new String[0];
// Path: src/main/java/com/lazerycode/jmeter/properties/ConfigurationFiles.java // public enum ConfigurationFiles { // // JMETER_PROPERTIES("jmeter.properties", true), // SAVE_SERVICE_PROPERTIES("saveservice.properties", true), // UPGRADE_PROPERTIES("upgrade.properties", true), // SYSTEM_PROPERTIES("system.properties", true), // USER_PROPERTIES("user.properties", true), // REPORT_GENERATOR_PROPERTIES("reportgenerator.properties", true), // GLOBAL_PROPERTIES("global.properties", false); // // private final String propertiesFilename; // private final boolean isRequired; // // ConfigurationFiles(String propertiesFilename, boolean isRequired) { // this.propertiesFilename = propertiesFilename; // this.isRequired = isRequired; // } // // public String getFilename() { // return propertiesFilename; // } // // public boolean createFileIfItDoesNotExist() { // return isRequired; // } // // } // // Path: src/main/java/com/lazerycode/jmeter/properties/PropertiesMapping.java // public class PropertiesMapping { // protected Map<String, String> additionalProperties; // private PropertiesFile propertiesFile; // // @JsonCreator // public PropertiesMapping(@JsonProperty("additionalProperties") Map<String, String> additionalProperties) { // this.additionalProperties = additionalProperties; // } // // public Map<String, String> getAdditionalProperties() { // return additionalProperties; // } // // public PropertiesFile getPropertiesFile() { // return propertiesFile; // } // // public void setPropertiesFile(PropertiesFile propertiesFile) { // this.propertiesFile = propertiesFile; // } // } // Path: src/main/java/com/lazerycode/jmeter/json/TestConfiguration.java import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.lazerycode.jmeter.properties.ConfigurationFiles; import com.lazerycode.jmeter.properties.PropertiesMapping; import java.io.File; import java.nio.file.Paths; import java.util.Arrays; import java.util.List; import java.util.Map; import java.util.Objects; package com.lazerycode.jmeter.json; @JsonIgnoreProperties(ignoreUnknown = true) public class TestConfiguration { private String executionID; private String jmeterDirectoryPath; private String runtimeJarName; private Boolean resultsOutputIsCSVFormat; private Boolean generateReports; private String[] resultFilesLocations = new String[0];
private Map<ConfigurationFiles, PropertiesMapping> propertiesMap;
jmeter-maven-plugin/jmeter-maven-plugin
src/main/java/com/lazerycode/jmeter/json/TestConfiguration.java
// Path: src/main/java/com/lazerycode/jmeter/properties/ConfigurationFiles.java // public enum ConfigurationFiles { // // JMETER_PROPERTIES("jmeter.properties", true), // SAVE_SERVICE_PROPERTIES("saveservice.properties", true), // UPGRADE_PROPERTIES("upgrade.properties", true), // SYSTEM_PROPERTIES("system.properties", true), // USER_PROPERTIES("user.properties", true), // REPORT_GENERATOR_PROPERTIES("reportgenerator.properties", true), // GLOBAL_PROPERTIES("global.properties", false); // // private final String propertiesFilename; // private final boolean isRequired; // // ConfigurationFiles(String propertiesFilename, boolean isRequired) { // this.propertiesFilename = propertiesFilename; // this.isRequired = isRequired; // } // // public String getFilename() { // return propertiesFilename; // } // // public boolean createFileIfItDoesNotExist() { // return isRequired; // } // // } // // Path: src/main/java/com/lazerycode/jmeter/properties/PropertiesMapping.java // public class PropertiesMapping { // protected Map<String, String> additionalProperties; // private PropertiesFile propertiesFile; // // @JsonCreator // public PropertiesMapping(@JsonProperty("additionalProperties") Map<String, String> additionalProperties) { // this.additionalProperties = additionalProperties; // } // // public Map<String, String> getAdditionalProperties() { // return additionalProperties; // } // // public PropertiesFile getPropertiesFile() { // return propertiesFile; // } // // public void setPropertiesFile(PropertiesFile propertiesFile) { // this.propertiesFile = propertiesFile; // } // }
import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.lazerycode.jmeter.properties.ConfigurationFiles; import com.lazerycode.jmeter.properties.PropertiesMapping; import java.io.File; import java.nio.file.Paths; import java.util.Arrays; import java.util.List; import java.util.Map; import java.util.Objects;
package com.lazerycode.jmeter.json; @JsonIgnoreProperties(ignoreUnknown = true) public class TestConfiguration { private String executionID; private String jmeterDirectoryPath; private String runtimeJarName; private Boolean resultsOutputIsCSVFormat; private Boolean generateReports; private String[] resultFilesLocations = new String[0];
// Path: src/main/java/com/lazerycode/jmeter/properties/ConfigurationFiles.java // public enum ConfigurationFiles { // // JMETER_PROPERTIES("jmeter.properties", true), // SAVE_SERVICE_PROPERTIES("saveservice.properties", true), // UPGRADE_PROPERTIES("upgrade.properties", true), // SYSTEM_PROPERTIES("system.properties", true), // USER_PROPERTIES("user.properties", true), // REPORT_GENERATOR_PROPERTIES("reportgenerator.properties", true), // GLOBAL_PROPERTIES("global.properties", false); // // private final String propertiesFilename; // private final boolean isRequired; // // ConfigurationFiles(String propertiesFilename, boolean isRequired) { // this.propertiesFilename = propertiesFilename; // this.isRequired = isRequired; // } // // public String getFilename() { // return propertiesFilename; // } // // public boolean createFileIfItDoesNotExist() { // return isRequired; // } // // } // // Path: src/main/java/com/lazerycode/jmeter/properties/PropertiesMapping.java // public class PropertiesMapping { // protected Map<String, String> additionalProperties; // private PropertiesFile propertiesFile; // // @JsonCreator // public PropertiesMapping(@JsonProperty("additionalProperties") Map<String, String> additionalProperties) { // this.additionalProperties = additionalProperties; // } // // public Map<String, String> getAdditionalProperties() { // return additionalProperties; // } // // public PropertiesFile getPropertiesFile() { // return propertiesFile; // } // // public void setPropertiesFile(PropertiesFile propertiesFile) { // this.propertiesFile = propertiesFile; // } // } // Path: src/main/java/com/lazerycode/jmeter/json/TestConfiguration.java import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.lazerycode.jmeter.properties.ConfigurationFiles; import com.lazerycode.jmeter.properties.PropertiesMapping; import java.io.File; import java.nio.file.Paths; import java.util.Arrays; import java.util.List; import java.util.Map; import java.util.Objects; package com.lazerycode.jmeter.json; @JsonIgnoreProperties(ignoreUnknown = true) public class TestConfiguration { private String executionID; private String jmeterDirectoryPath; private String runtimeJarName; private Boolean resultsOutputIsCSVFormat; private Boolean generateReports; private String[] resultFilesLocations = new String[0];
private Map<ConfigurationFiles, PropertiesMapping> propertiesMap;
jmeter-maven-plugin/jmeter-maven-plugin
src/main/java/com/lazerycode/jmeter/results/ResultScanner.java
// Path: src/main/java/com/lazerycode/jmeter/results/XMLFileScanner.java // public static int scanXmlFileForPattern(File file, Pattern searchPattern) throws MojoExecutionException { // int patternMatchCount = 0; // try (Scanner resultFileScanner = new Scanner(file)) { // while (resultFileScanner.findWithinHorizon(searchPattern, 0) != null) { // patternMatchCount++; // } // } catch (IOException e) { // throw new MojoExecutionException("An unexpected error occurred while reading file " + file.getAbsolutePath(), e); // } // return patternMatchCount; // }
import org.apache.maven.plugin.MojoExecutionException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.File; import java.util.List; import java.util.Map; import java.util.regex.Pattern; import static com.lazerycode.jmeter.results.XMLFileScanner.scanXmlFileForPattern;
public ResultScanner(boolean countSuccesses, boolean countFailures, boolean isCsv, boolean onlyFailWhenMatchingFailureMessage, List<String> failureMessages) { this.csv = isCsv; this.countFailures = countFailures; this.countSuccesses = countSuccesses; this.onlyFailWhenMatchingFailureMessage = onlyFailWhenMatchingFailureMessage; this.failureMessages = failureMessages; } /** * Work out how to parse the file (if at all) * * @param file File to parse * @throws MojoExecutionException MojoExecutionException */ public void parseResultFile(File file) throws MojoExecutionException { if (!file.exists()) { throw new MojoExecutionException("Unable to find " + file.getAbsolutePath()); } LOGGER.info(" "); LOGGER.info("Parsing results file '{}' as type: {}", file, this.csv ? "CSV" : "XML"); if (csv) { CSVScanResult csvScanResult = CSVFileScanner.scanCsvForValues(file, failureMessages); successCount = csvScanResult.getSuccessCount(); failureCount = csvScanResult.getFailureCount(); for (Map.Entry<String, Integer> entry : csvScanResult.getSpecificFailureMessages().entrySet()) { customFailureCount = customFailureCount + entry.getValue(); LOGGER.info("Number of potential custom failures using '{}' in '{}': {}", entry.getKey(), file.getName(), customFailureCount); } } else { if (countSuccesses) {
// Path: src/main/java/com/lazerycode/jmeter/results/XMLFileScanner.java // public static int scanXmlFileForPattern(File file, Pattern searchPattern) throws MojoExecutionException { // int patternMatchCount = 0; // try (Scanner resultFileScanner = new Scanner(file)) { // while (resultFileScanner.findWithinHorizon(searchPattern, 0) != null) { // patternMatchCount++; // } // } catch (IOException e) { // throw new MojoExecutionException("An unexpected error occurred while reading file " + file.getAbsolutePath(), e); // } // return patternMatchCount; // } // Path: src/main/java/com/lazerycode/jmeter/results/ResultScanner.java import org.apache.maven.plugin.MojoExecutionException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.File; import java.util.List; import java.util.Map; import java.util.regex.Pattern; import static com.lazerycode.jmeter.results.XMLFileScanner.scanXmlFileForPattern; public ResultScanner(boolean countSuccesses, boolean countFailures, boolean isCsv, boolean onlyFailWhenMatchingFailureMessage, List<String> failureMessages) { this.csv = isCsv; this.countFailures = countFailures; this.countSuccesses = countSuccesses; this.onlyFailWhenMatchingFailureMessage = onlyFailWhenMatchingFailureMessage; this.failureMessages = failureMessages; } /** * Work out how to parse the file (if at all) * * @param file File to parse * @throws MojoExecutionException MojoExecutionException */ public void parseResultFile(File file) throws MojoExecutionException { if (!file.exists()) { throw new MojoExecutionException("Unable to find " + file.getAbsolutePath()); } LOGGER.info(" "); LOGGER.info("Parsing results file '{}' as type: {}", file, this.csv ? "CSV" : "XML"); if (csv) { CSVScanResult csvScanResult = CSVFileScanner.scanCsvForValues(file, failureMessages); successCount = csvScanResult.getSuccessCount(); failureCount = csvScanResult.getFailureCount(); for (Map.Entry<String, Integer> entry : csvScanResult.getSpecificFailureMessages().entrySet()) { customFailureCount = customFailureCount + entry.getValue(); LOGGER.info("Number of potential custom failures using '{}' in '{}': {}", entry.getKey(), file.getName(), customFailureCount); } } else { if (countSuccesses) {
successCount = scanXmlFileForPattern(file, Pattern.compile(XML_REQUEST_SUCCESS_PATTERN, Pattern.CASE_INSENSITIVE));
jmeter-maven-plugin/jmeter-maven-plugin
src/test/java/com/lazerycode/jmeter/testrunner/BenchmarkResultScannerTest.java
// Path: src/main/java/com/lazerycode/jmeter/results/ResultScanner.java // public class ResultScanner implements IResultScanner { // private static final Logger LOGGER = LoggerFactory.getLogger(ResultScanner.class); // private static final String XML_REQUEST_FAILURE_PATTERN = "s=\"false\""; // private static final String XML_REQUEST_SUCCESS_PATTERN = "s=\"true\""; // private final boolean countFailures; // private final boolean countSuccesses; // private final boolean onlyFailWhenMatchingFailureMessage; // private final boolean csv; // private final List<String> failureMessages; // private int successCount = 0; // private int failureCount = 0; // private int customFailureCount = 0; // // public ResultScanner(boolean countSuccesses, boolean countFailures, boolean isCsv, boolean onlyFailWhenMatchingFailureMessage, List<String> failureMessages) { // this.csv = isCsv; // this.countFailures = countFailures; // this.countSuccesses = countSuccesses; // this.onlyFailWhenMatchingFailureMessage = onlyFailWhenMatchingFailureMessage; // this.failureMessages = failureMessages; // } // // /** // * Work out how to parse the file (if at all) // * // * @param file File to parse // * @throws MojoExecutionException MojoExecutionException // */ // public void parseResultFile(File file) throws MojoExecutionException { // if (!file.exists()) { // throw new MojoExecutionException("Unable to find " + file.getAbsolutePath()); // } // LOGGER.info(" "); // LOGGER.info("Parsing results file '{}' as type: {}", file, this.csv ? "CSV" : "XML"); // if (csv) { // CSVScanResult csvScanResult = CSVFileScanner.scanCsvForValues(file, failureMessages); // successCount = csvScanResult.getSuccessCount(); // failureCount = csvScanResult.getFailureCount(); // for (Map.Entry<String, Integer> entry : csvScanResult.getSpecificFailureMessages().entrySet()) { // customFailureCount = customFailureCount + entry.getValue(); // LOGGER.info("Number of potential custom failures using '{}' in '{}': {}", entry.getKey(), file.getName(), customFailureCount); // } // } else { // if (countSuccesses) { // successCount = scanXmlFileForPattern(file, Pattern.compile(XML_REQUEST_SUCCESS_PATTERN, Pattern.CASE_INSENSITIVE)); // } // if (countFailures) { // failureCount = scanXmlFileForPattern(file, Pattern.compile(XML_REQUEST_FAILURE_PATTERN, Pattern.CASE_INSENSITIVE)); // } // } // } // // /** // * @return failureCount // */ // @Override // public int getFailureCount() { // if (countFailures) { // if (onlyFailWhenMatchingFailureMessage) { // return this.customFailureCount; // } else { // return this.failureCount; // } // } // return 0; // } // // /** // * @return failureCount // */ // @Override // public int getSuccessCount() { // if (countSuccesses) { // return this.successCount; // } // return 0; // } // // @Override // public int getTotalCount() { // return getSuccessCount() + getFailureCount(); // } // }
import com.lazerycode.jmeter.results.ResultScanner; import org.junit.Ignore; import org.junit.Test; import java.io.File; import java.time.Duration; import java.time.LocalDateTime; import java.util.ArrayList; import java.util.List;
package com.lazerycode.jmeter.testrunner; public class BenchmarkResultScannerTest { /* All ignored by default These are here so we can perform benchmarks against the scanner code whenever we want to check it against an alternative implementation To create the data file you can use an NPM module called datagen: npm install -g datagen datagen init # Now populate generated filed as noted below datagen gen -s 10000000 -w 1 --out-file data1.xml Header: <?xml version="1.0" encoding="UTF-8"?> <testResults version="1.2"> Footer: </testResults> Segment: <httpSample t="1187" lt="{segment_id}" ts="1133521593546" s="true" lb="/my_webapp/root/auth" rc="302" rm="Moved Temporarily" tn="Thread Group 1-1" dt="text"/> <httpSample t="16" lt="{segment_id}" ts="1133521593562" s="false" lb="/my_webapp/root/;jsessionid=xxx" rc="302" rm="Moved Temporarily" tn="Thread Group 1-1" dt="text"/> */ private static final boolean COUNT_FAILURES = true; private static final boolean DO_NOT_COUNT_FAILURES = false; private static final boolean COUNT_SUCCESSES = true; private static final boolean DO_NOT_COUNT_SUCCESSES = false; private static final boolean DEFAULT_IS_CSV = false; private static final boolean DEFAULT_ONLY_FAIL_WHEN_MATCHING_FAILURE_MESSAGES = false; private static final List<String> DEFAULT_FAILURE_LIST = new ArrayList<>(); private static final String TEST_XML_FILE_LOCATION = "/Programming/OpenSource/jmeter-maven-plugin/data1.xml"; @Ignore @Test public void countSuccessAndFailure() throws Exception { File resultsFile = new File(TEST_XML_FILE_LOCATION);
// Path: src/main/java/com/lazerycode/jmeter/results/ResultScanner.java // public class ResultScanner implements IResultScanner { // private static final Logger LOGGER = LoggerFactory.getLogger(ResultScanner.class); // private static final String XML_REQUEST_FAILURE_PATTERN = "s=\"false\""; // private static final String XML_REQUEST_SUCCESS_PATTERN = "s=\"true\""; // private final boolean countFailures; // private final boolean countSuccesses; // private final boolean onlyFailWhenMatchingFailureMessage; // private final boolean csv; // private final List<String> failureMessages; // private int successCount = 0; // private int failureCount = 0; // private int customFailureCount = 0; // // public ResultScanner(boolean countSuccesses, boolean countFailures, boolean isCsv, boolean onlyFailWhenMatchingFailureMessage, List<String> failureMessages) { // this.csv = isCsv; // this.countFailures = countFailures; // this.countSuccesses = countSuccesses; // this.onlyFailWhenMatchingFailureMessage = onlyFailWhenMatchingFailureMessage; // this.failureMessages = failureMessages; // } // // /** // * Work out how to parse the file (if at all) // * // * @param file File to parse // * @throws MojoExecutionException MojoExecutionException // */ // public void parseResultFile(File file) throws MojoExecutionException { // if (!file.exists()) { // throw new MojoExecutionException("Unable to find " + file.getAbsolutePath()); // } // LOGGER.info(" "); // LOGGER.info("Parsing results file '{}' as type: {}", file, this.csv ? "CSV" : "XML"); // if (csv) { // CSVScanResult csvScanResult = CSVFileScanner.scanCsvForValues(file, failureMessages); // successCount = csvScanResult.getSuccessCount(); // failureCount = csvScanResult.getFailureCount(); // for (Map.Entry<String, Integer> entry : csvScanResult.getSpecificFailureMessages().entrySet()) { // customFailureCount = customFailureCount + entry.getValue(); // LOGGER.info("Number of potential custom failures using '{}' in '{}': {}", entry.getKey(), file.getName(), customFailureCount); // } // } else { // if (countSuccesses) { // successCount = scanXmlFileForPattern(file, Pattern.compile(XML_REQUEST_SUCCESS_PATTERN, Pattern.CASE_INSENSITIVE)); // } // if (countFailures) { // failureCount = scanXmlFileForPattern(file, Pattern.compile(XML_REQUEST_FAILURE_PATTERN, Pattern.CASE_INSENSITIVE)); // } // } // } // // /** // * @return failureCount // */ // @Override // public int getFailureCount() { // if (countFailures) { // if (onlyFailWhenMatchingFailureMessage) { // return this.customFailureCount; // } else { // return this.failureCount; // } // } // return 0; // } // // /** // * @return failureCount // */ // @Override // public int getSuccessCount() { // if (countSuccesses) { // return this.successCount; // } // return 0; // } // // @Override // public int getTotalCount() { // return getSuccessCount() + getFailureCount(); // } // } // Path: src/test/java/com/lazerycode/jmeter/testrunner/BenchmarkResultScannerTest.java import com.lazerycode.jmeter.results.ResultScanner; import org.junit.Ignore; import org.junit.Test; import java.io.File; import java.time.Duration; import java.time.LocalDateTime; import java.util.ArrayList; import java.util.List; package com.lazerycode.jmeter.testrunner; public class BenchmarkResultScannerTest { /* All ignored by default These are here so we can perform benchmarks against the scanner code whenever we want to check it against an alternative implementation To create the data file you can use an NPM module called datagen: npm install -g datagen datagen init # Now populate generated filed as noted below datagen gen -s 10000000 -w 1 --out-file data1.xml Header: <?xml version="1.0" encoding="UTF-8"?> <testResults version="1.2"> Footer: </testResults> Segment: <httpSample t="1187" lt="{segment_id}" ts="1133521593546" s="true" lb="/my_webapp/root/auth" rc="302" rm="Moved Temporarily" tn="Thread Group 1-1" dt="text"/> <httpSample t="16" lt="{segment_id}" ts="1133521593562" s="false" lb="/my_webapp/root/;jsessionid=xxx" rc="302" rm="Moved Temporarily" tn="Thread Group 1-1" dt="text"/> */ private static final boolean COUNT_FAILURES = true; private static final boolean DO_NOT_COUNT_FAILURES = false; private static final boolean COUNT_SUCCESSES = true; private static final boolean DO_NOT_COUNT_SUCCESSES = false; private static final boolean DEFAULT_IS_CSV = false; private static final boolean DEFAULT_ONLY_FAIL_WHEN_MATCHING_FAILURE_MESSAGES = false; private static final List<String> DEFAULT_FAILURE_LIST = new ArrayList<>(); private static final String TEST_XML_FILE_LOCATION = "/Programming/OpenSource/jmeter-maven-plugin/data1.xml"; @Ignore @Test public void countSuccessAndFailure() throws Exception { File resultsFile = new File(TEST_XML_FILE_LOCATION);
ResultScanner fileScanner = new ResultScanner(COUNT_SUCCESSES, COUNT_FAILURES, DEFAULT_IS_CSV, DEFAULT_ONLY_FAIL_WHEN_MATCHING_FAILURE_MESSAGES, DEFAULT_FAILURE_LIST);
jmeter-maven-plugin/jmeter-maven-plugin
src/test/java/com/lazerycode/jmeter/configuration/RemoteConfigurationTest.java
// Path: src/main/java/com/lazerycode/jmeter/properties/ConfigurationFiles.java // public enum ConfigurationFiles { // // JMETER_PROPERTIES("jmeter.properties", true), // SAVE_SERVICE_PROPERTIES("saveservice.properties", true), // UPGRADE_PROPERTIES("upgrade.properties", true), // SYSTEM_PROPERTIES("system.properties", true), // USER_PROPERTIES("user.properties", true), // REPORT_GENERATOR_PROPERTIES("reportgenerator.properties", true), // GLOBAL_PROPERTIES("global.properties", false); // // private final String propertiesFilename; // private final boolean isRequired; // // ConfigurationFiles(String propertiesFilename, boolean isRequired) { // this.propertiesFilename = propertiesFilename; // this.isRequired = isRequired; // } // // public String getFilename() { // return propertiesFilename; // } // // public boolean createFileIfItDoesNotExist() { // return isRequired; // } // // } // // Path: src/main/java/com/lazerycode/jmeter/properties/PropertiesMapping.java // public class PropertiesMapping { // protected Map<String, String> additionalProperties; // private PropertiesFile propertiesFile; // // @JsonCreator // public PropertiesMapping(@JsonProperty("additionalProperties") Map<String, String> additionalProperties) { // this.additionalProperties = additionalProperties; // } // // public Map<String, String> getAdditionalProperties() { // return additionalProperties; // } // // public PropertiesFile getPropertiesFile() { // return propertiesFile; // } // // public void setPropertiesFile(PropertiesFile propertiesFile) { // this.propertiesFile = propertiesFile; // } // }
import com.lazerycode.jmeter.properties.ConfigurationFiles; import com.lazerycode.jmeter.properties.PropertiesMapping; import org.junit.Test; import java.util.EnumMap; import java.util.HashMap; import static org.assertj.core.api.Assertions.assertThat;
package com.lazerycode.jmeter.configuration; public class RemoteConfigurationTest { @Test public void defaultSettingsAreAsExpected() { RemoteConfiguration remoteConfiguration = new RemoteConfiguration(); assertThat(remoteConfiguration.isStopServersAfterTests()).isFalse(); assertThat(remoteConfiguration.isStartServersBeforeTests()).isFalse(); assertThat(remoteConfiguration.isStartAndStopServersForEachTest()).isFalse(); assertThat(remoteConfiguration.getServerList()).isEmpty(); assertThat(remoteConfiguration.getPropertiesMap().size()).isEqualTo(0); } @Test public void propertiesMapIsReplacedWhenSet() {
// Path: src/main/java/com/lazerycode/jmeter/properties/ConfigurationFiles.java // public enum ConfigurationFiles { // // JMETER_PROPERTIES("jmeter.properties", true), // SAVE_SERVICE_PROPERTIES("saveservice.properties", true), // UPGRADE_PROPERTIES("upgrade.properties", true), // SYSTEM_PROPERTIES("system.properties", true), // USER_PROPERTIES("user.properties", true), // REPORT_GENERATOR_PROPERTIES("reportgenerator.properties", true), // GLOBAL_PROPERTIES("global.properties", false); // // private final String propertiesFilename; // private final boolean isRequired; // // ConfigurationFiles(String propertiesFilename, boolean isRequired) { // this.propertiesFilename = propertiesFilename; // this.isRequired = isRequired; // } // // public String getFilename() { // return propertiesFilename; // } // // public boolean createFileIfItDoesNotExist() { // return isRequired; // } // // } // // Path: src/main/java/com/lazerycode/jmeter/properties/PropertiesMapping.java // public class PropertiesMapping { // protected Map<String, String> additionalProperties; // private PropertiesFile propertiesFile; // // @JsonCreator // public PropertiesMapping(@JsonProperty("additionalProperties") Map<String, String> additionalProperties) { // this.additionalProperties = additionalProperties; // } // // public Map<String, String> getAdditionalProperties() { // return additionalProperties; // } // // public PropertiesFile getPropertiesFile() { // return propertiesFile; // } // // public void setPropertiesFile(PropertiesFile propertiesFile) { // this.propertiesFile = propertiesFile; // } // } // Path: src/test/java/com/lazerycode/jmeter/configuration/RemoteConfigurationTest.java import com.lazerycode.jmeter.properties.ConfigurationFiles; import com.lazerycode.jmeter.properties.PropertiesMapping; import org.junit.Test; import java.util.EnumMap; import java.util.HashMap; import static org.assertj.core.api.Assertions.assertThat; package com.lazerycode.jmeter.configuration; public class RemoteConfigurationTest { @Test public void defaultSettingsAreAsExpected() { RemoteConfiguration remoteConfiguration = new RemoteConfiguration(); assertThat(remoteConfiguration.isStopServersAfterTests()).isFalse(); assertThat(remoteConfiguration.isStartServersBeforeTests()).isFalse(); assertThat(remoteConfiguration.isStartAndStopServersForEachTest()).isFalse(); assertThat(remoteConfiguration.getServerList()).isEmpty(); assertThat(remoteConfiguration.getPropertiesMap().size()).isEqualTo(0); } @Test public void propertiesMapIsReplacedWhenSet() {
EnumMap<ConfigurationFiles, PropertiesMapping> firstEnumMap = new EnumMap<>(ConfigurationFiles.class);
jmeter-maven-plugin/jmeter-maven-plugin
src/test/java/com/lazerycode/jmeter/configuration/RemoteConfigurationTest.java
// Path: src/main/java/com/lazerycode/jmeter/properties/ConfigurationFiles.java // public enum ConfigurationFiles { // // JMETER_PROPERTIES("jmeter.properties", true), // SAVE_SERVICE_PROPERTIES("saveservice.properties", true), // UPGRADE_PROPERTIES("upgrade.properties", true), // SYSTEM_PROPERTIES("system.properties", true), // USER_PROPERTIES("user.properties", true), // REPORT_GENERATOR_PROPERTIES("reportgenerator.properties", true), // GLOBAL_PROPERTIES("global.properties", false); // // private final String propertiesFilename; // private final boolean isRequired; // // ConfigurationFiles(String propertiesFilename, boolean isRequired) { // this.propertiesFilename = propertiesFilename; // this.isRequired = isRequired; // } // // public String getFilename() { // return propertiesFilename; // } // // public boolean createFileIfItDoesNotExist() { // return isRequired; // } // // } // // Path: src/main/java/com/lazerycode/jmeter/properties/PropertiesMapping.java // public class PropertiesMapping { // protected Map<String, String> additionalProperties; // private PropertiesFile propertiesFile; // // @JsonCreator // public PropertiesMapping(@JsonProperty("additionalProperties") Map<String, String> additionalProperties) { // this.additionalProperties = additionalProperties; // } // // public Map<String, String> getAdditionalProperties() { // return additionalProperties; // } // // public PropertiesFile getPropertiesFile() { // return propertiesFile; // } // // public void setPropertiesFile(PropertiesFile propertiesFile) { // this.propertiesFile = propertiesFile; // } // }
import com.lazerycode.jmeter.properties.ConfigurationFiles; import com.lazerycode.jmeter.properties.PropertiesMapping; import org.junit.Test; import java.util.EnumMap; import java.util.HashMap; import static org.assertj.core.api.Assertions.assertThat;
package com.lazerycode.jmeter.configuration; public class RemoteConfigurationTest { @Test public void defaultSettingsAreAsExpected() { RemoteConfiguration remoteConfiguration = new RemoteConfiguration(); assertThat(remoteConfiguration.isStopServersAfterTests()).isFalse(); assertThat(remoteConfiguration.isStartServersBeforeTests()).isFalse(); assertThat(remoteConfiguration.isStartAndStopServersForEachTest()).isFalse(); assertThat(remoteConfiguration.getServerList()).isEmpty(); assertThat(remoteConfiguration.getPropertiesMap().size()).isEqualTo(0); } @Test public void propertiesMapIsReplacedWhenSet() {
// Path: src/main/java/com/lazerycode/jmeter/properties/ConfigurationFiles.java // public enum ConfigurationFiles { // // JMETER_PROPERTIES("jmeter.properties", true), // SAVE_SERVICE_PROPERTIES("saveservice.properties", true), // UPGRADE_PROPERTIES("upgrade.properties", true), // SYSTEM_PROPERTIES("system.properties", true), // USER_PROPERTIES("user.properties", true), // REPORT_GENERATOR_PROPERTIES("reportgenerator.properties", true), // GLOBAL_PROPERTIES("global.properties", false); // // private final String propertiesFilename; // private final boolean isRequired; // // ConfigurationFiles(String propertiesFilename, boolean isRequired) { // this.propertiesFilename = propertiesFilename; // this.isRequired = isRequired; // } // // public String getFilename() { // return propertiesFilename; // } // // public boolean createFileIfItDoesNotExist() { // return isRequired; // } // // } // // Path: src/main/java/com/lazerycode/jmeter/properties/PropertiesMapping.java // public class PropertiesMapping { // protected Map<String, String> additionalProperties; // private PropertiesFile propertiesFile; // // @JsonCreator // public PropertiesMapping(@JsonProperty("additionalProperties") Map<String, String> additionalProperties) { // this.additionalProperties = additionalProperties; // } // // public Map<String, String> getAdditionalProperties() { // return additionalProperties; // } // // public PropertiesFile getPropertiesFile() { // return propertiesFile; // } // // public void setPropertiesFile(PropertiesFile propertiesFile) { // this.propertiesFile = propertiesFile; // } // } // Path: src/test/java/com/lazerycode/jmeter/configuration/RemoteConfigurationTest.java import com.lazerycode.jmeter.properties.ConfigurationFiles; import com.lazerycode.jmeter.properties.PropertiesMapping; import org.junit.Test; import java.util.EnumMap; import java.util.HashMap; import static org.assertj.core.api.Assertions.assertThat; package com.lazerycode.jmeter.configuration; public class RemoteConfigurationTest { @Test public void defaultSettingsAreAsExpected() { RemoteConfiguration remoteConfiguration = new RemoteConfiguration(); assertThat(remoteConfiguration.isStopServersAfterTests()).isFalse(); assertThat(remoteConfiguration.isStartServersBeforeTests()).isFalse(); assertThat(remoteConfiguration.isStartAndStopServersForEachTest()).isFalse(); assertThat(remoteConfiguration.getServerList()).isEmpty(); assertThat(remoteConfiguration.getPropertiesMap().size()).isEqualTo(0); } @Test public void propertiesMapIsReplacedWhenSet() {
EnumMap<ConfigurationFiles, PropertiesMapping> firstEnumMap = new EnumMap<>(ConfigurationFiles.class);
jmeter-maven-plugin/jmeter-maven-plugin
src/test/java/com/lazerycode/jmeter/testrunner/JMeterProcessBuilderTest.java
// Path: src/main/java/com/lazerycode/jmeter/configuration/JMeterProcessJVMSettings.java // @SuppressWarnings({"UnusedDeclaration", "FieldCanBeLocal"}) // public class JMeterProcessJVMSettings { // // private int xms = 512; // private int xmx = 512; // private String javaRuntime = "java"; // private List<String> arguments = new ArrayList<>(); // // private static final String RUN_HEADLESS = "-Djava.awt.headless=true"; // private static final String HEADLESS_SETTING = "-Djava.awt.headless="; // // public JMeterProcessJVMSettings() { // super(); // } // // public int getXms() { // return xms; // } // // public int getXmx() { // return xmx; // } // // public List<String> getArguments() { // return arguments; // } // // public JMeterProcessJVMSettings addArgument(String newArgument) { // if (arguments.stream().noneMatch(argument -> argument.equals(newArgument))) { // arguments.add(newArgument); // } // // return this; // } // // public JMeterProcessJVMSettings setHeadlessDefaultIfRequired() { // if (arguments.stream().noneMatch(argument -> argument.contains(HEADLESS_SETTING))) { // addArgument(RUN_HEADLESS); // } // // return this; // } // // public String getJavaRuntime() { // return this.javaRuntime; // } // }
import com.lazerycode.jmeter.configuration.JMeterProcessJVMSettings; import org.apache.maven.plugin.MojoExecutionException; import org.junit.Test; import java.io.File; import java.util.ArrayList; import static org.assertj.core.api.Assertions.assertThat;
package com.lazerycode.jmeter.testrunner; public class JMeterProcessBuilderTest { @Test public void defaultArgumentsListIsAsExpected() {
// Path: src/main/java/com/lazerycode/jmeter/configuration/JMeterProcessJVMSettings.java // @SuppressWarnings({"UnusedDeclaration", "FieldCanBeLocal"}) // public class JMeterProcessJVMSettings { // // private int xms = 512; // private int xmx = 512; // private String javaRuntime = "java"; // private List<String> arguments = new ArrayList<>(); // // private static final String RUN_HEADLESS = "-Djava.awt.headless=true"; // private static final String HEADLESS_SETTING = "-Djava.awt.headless="; // // public JMeterProcessJVMSettings() { // super(); // } // // public int getXms() { // return xms; // } // // public int getXmx() { // return xmx; // } // // public List<String> getArguments() { // return arguments; // } // // public JMeterProcessJVMSettings addArgument(String newArgument) { // if (arguments.stream().noneMatch(argument -> argument.equals(newArgument))) { // arguments.add(newArgument); // } // // return this; // } // // public JMeterProcessJVMSettings setHeadlessDefaultIfRequired() { // if (arguments.stream().noneMatch(argument -> argument.contains(HEADLESS_SETTING))) { // addArgument(RUN_HEADLESS); // } // // return this; // } // // public String getJavaRuntime() { // return this.javaRuntime; // } // } // Path: src/test/java/com/lazerycode/jmeter/testrunner/JMeterProcessBuilderTest.java import com.lazerycode.jmeter.configuration.JMeterProcessJVMSettings; import org.apache.maven.plugin.MojoExecutionException; import org.junit.Test; import java.io.File; import java.util.ArrayList; import static org.assertj.core.api.Assertions.assertThat; package com.lazerycode.jmeter.testrunner; public class JMeterProcessBuilderTest { @Test public void defaultArgumentsListIsAsExpected() {
JMeterProcessJVMSettings jMeterProcessJVMSettings = new JMeterProcessJVMSettings();
jmeter-maven-plugin/jmeter-maven-plugin
src/test/java/com/lazerycode/jmeter/testrunner/ResultScannerTest.java
// Path: src/main/java/com/lazerycode/jmeter/results/ResultScanner.java // public class ResultScanner implements IResultScanner { // private static final Logger LOGGER = LoggerFactory.getLogger(ResultScanner.class); // private static final String XML_REQUEST_FAILURE_PATTERN = "s=\"false\""; // private static final String XML_REQUEST_SUCCESS_PATTERN = "s=\"true\""; // private final boolean countFailures; // private final boolean countSuccesses; // private final boolean onlyFailWhenMatchingFailureMessage; // private final boolean csv; // private final List<String> failureMessages; // private int successCount = 0; // private int failureCount = 0; // private int customFailureCount = 0; // // public ResultScanner(boolean countSuccesses, boolean countFailures, boolean isCsv, boolean onlyFailWhenMatchingFailureMessage, List<String> failureMessages) { // this.csv = isCsv; // this.countFailures = countFailures; // this.countSuccesses = countSuccesses; // this.onlyFailWhenMatchingFailureMessage = onlyFailWhenMatchingFailureMessage; // this.failureMessages = failureMessages; // } // // /** // * Work out how to parse the file (if at all) // * // * @param file File to parse // * @throws MojoExecutionException MojoExecutionException // */ // public void parseResultFile(File file) throws MojoExecutionException { // if (!file.exists()) { // throw new MojoExecutionException("Unable to find " + file.getAbsolutePath()); // } // LOGGER.info(" "); // LOGGER.info("Parsing results file '{}' as type: {}", file, this.csv ? "CSV" : "XML"); // if (csv) { // CSVScanResult csvScanResult = CSVFileScanner.scanCsvForValues(file, failureMessages); // successCount = csvScanResult.getSuccessCount(); // failureCount = csvScanResult.getFailureCount(); // for (Map.Entry<String, Integer> entry : csvScanResult.getSpecificFailureMessages().entrySet()) { // customFailureCount = customFailureCount + entry.getValue(); // LOGGER.info("Number of potential custom failures using '{}' in '{}': {}", entry.getKey(), file.getName(), customFailureCount); // } // } else { // if (countSuccesses) { // successCount = scanXmlFileForPattern(file, Pattern.compile(XML_REQUEST_SUCCESS_PATTERN, Pattern.CASE_INSENSITIVE)); // } // if (countFailures) { // failureCount = scanXmlFileForPattern(file, Pattern.compile(XML_REQUEST_FAILURE_PATTERN, Pattern.CASE_INSENSITIVE)); // } // } // } // // /** // * @return failureCount // */ // @Override // public int getFailureCount() { // if (countFailures) { // if (onlyFailWhenMatchingFailureMessage) { // return this.customFailureCount; // } else { // return this.failureCount; // } // } // return 0; // } // // /** // * @return failureCount // */ // @Override // public int getSuccessCount() { // if (countSuccesses) { // return this.successCount; // } // return 0; // } // // @Override // public int getTotalCount() { // return getSuccessCount() + getFailureCount(); // } // }
import com.lazerycode.jmeter.results.ResultScanner; import org.apache.maven.plugin.MojoExecutionException; import org.junit.Test; import java.io.File; import java.net.URL; import java.util.ArrayList; import java.util.List; import static org.assertj.core.api.Assertions.assertThat;
package com.lazerycode.jmeter.testrunner; public class ResultScannerTest { private static final boolean COUNT_FAILURES = true; private static final boolean DO_NOT_COUNT_FAILURES = false; private static final boolean COUNT_SUCCESSES = true; private static final boolean DO_NOT_COUNT_SUCCESSES = false; private static final boolean DEFAULT_IS_CSV = false; private static final boolean DEFAULT_ONLY_FAIL_WHEN_MATCHING_FAILURE_MESSAGES = false; private static final List<String> DEFAULT_FAILURE_LIST = new ArrayList<>(); private final URL jtlFailingResultsFileURL = this.getClass().getResource("/jtl2-1-fail.jtl"); private final URL jtlPassingResultsFileURL = this.getClass().getResource("/jtl2-1-pass.jtl"); private final URL csvFailingResultsFileURL = this.getClass().getResource("/csv2-1-fail.csv"); private final URL csvPassingResultsFileURL = this.getClass().getResource("/csv2-1-pass.csv"); private final URL emptyCSVFileURL = this.getClass().getResource("/empty.csv"); private final URL csvMissingDelimiterFileURL = this.getClass().getResource("/csv-missing-delimiter.csv"); private final URL csvWithAlternateSeparatorPassingResultsFileURL = this.getClass().getResource("/csv3-1-pass.csv"); @Test public void jtlFileWithFailuresCountSuccessAndFailures() throws Exception { File resultsFile = new File(jtlFailingResultsFileURL.toURI());
// Path: src/main/java/com/lazerycode/jmeter/results/ResultScanner.java // public class ResultScanner implements IResultScanner { // private static final Logger LOGGER = LoggerFactory.getLogger(ResultScanner.class); // private static final String XML_REQUEST_FAILURE_PATTERN = "s=\"false\""; // private static final String XML_REQUEST_SUCCESS_PATTERN = "s=\"true\""; // private final boolean countFailures; // private final boolean countSuccesses; // private final boolean onlyFailWhenMatchingFailureMessage; // private final boolean csv; // private final List<String> failureMessages; // private int successCount = 0; // private int failureCount = 0; // private int customFailureCount = 0; // // public ResultScanner(boolean countSuccesses, boolean countFailures, boolean isCsv, boolean onlyFailWhenMatchingFailureMessage, List<String> failureMessages) { // this.csv = isCsv; // this.countFailures = countFailures; // this.countSuccesses = countSuccesses; // this.onlyFailWhenMatchingFailureMessage = onlyFailWhenMatchingFailureMessage; // this.failureMessages = failureMessages; // } // // /** // * Work out how to parse the file (if at all) // * // * @param file File to parse // * @throws MojoExecutionException MojoExecutionException // */ // public void parseResultFile(File file) throws MojoExecutionException { // if (!file.exists()) { // throw new MojoExecutionException("Unable to find " + file.getAbsolutePath()); // } // LOGGER.info(" "); // LOGGER.info("Parsing results file '{}' as type: {}", file, this.csv ? "CSV" : "XML"); // if (csv) { // CSVScanResult csvScanResult = CSVFileScanner.scanCsvForValues(file, failureMessages); // successCount = csvScanResult.getSuccessCount(); // failureCount = csvScanResult.getFailureCount(); // for (Map.Entry<String, Integer> entry : csvScanResult.getSpecificFailureMessages().entrySet()) { // customFailureCount = customFailureCount + entry.getValue(); // LOGGER.info("Number of potential custom failures using '{}' in '{}': {}", entry.getKey(), file.getName(), customFailureCount); // } // } else { // if (countSuccesses) { // successCount = scanXmlFileForPattern(file, Pattern.compile(XML_REQUEST_SUCCESS_PATTERN, Pattern.CASE_INSENSITIVE)); // } // if (countFailures) { // failureCount = scanXmlFileForPattern(file, Pattern.compile(XML_REQUEST_FAILURE_PATTERN, Pattern.CASE_INSENSITIVE)); // } // } // } // // /** // * @return failureCount // */ // @Override // public int getFailureCount() { // if (countFailures) { // if (onlyFailWhenMatchingFailureMessage) { // return this.customFailureCount; // } else { // return this.failureCount; // } // } // return 0; // } // // /** // * @return failureCount // */ // @Override // public int getSuccessCount() { // if (countSuccesses) { // return this.successCount; // } // return 0; // } // // @Override // public int getTotalCount() { // return getSuccessCount() + getFailureCount(); // } // } // Path: src/test/java/com/lazerycode/jmeter/testrunner/ResultScannerTest.java import com.lazerycode.jmeter.results.ResultScanner; import org.apache.maven.plugin.MojoExecutionException; import org.junit.Test; import java.io.File; import java.net.URL; import java.util.ArrayList; import java.util.List; import static org.assertj.core.api.Assertions.assertThat; package com.lazerycode.jmeter.testrunner; public class ResultScannerTest { private static final boolean COUNT_FAILURES = true; private static final boolean DO_NOT_COUNT_FAILURES = false; private static final boolean COUNT_SUCCESSES = true; private static final boolean DO_NOT_COUNT_SUCCESSES = false; private static final boolean DEFAULT_IS_CSV = false; private static final boolean DEFAULT_ONLY_FAIL_WHEN_MATCHING_FAILURE_MESSAGES = false; private static final List<String> DEFAULT_FAILURE_LIST = new ArrayList<>(); private final URL jtlFailingResultsFileURL = this.getClass().getResource("/jtl2-1-fail.jtl"); private final URL jtlPassingResultsFileURL = this.getClass().getResource("/jtl2-1-pass.jtl"); private final URL csvFailingResultsFileURL = this.getClass().getResource("/csv2-1-fail.csv"); private final URL csvPassingResultsFileURL = this.getClass().getResource("/csv2-1-pass.csv"); private final URL emptyCSVFileURL = this.getClass().getResource("/empty.csv"); private final URL csvMissingDelimiterFileURL = this.getClass().getResource("/csv-missing-delimiter.csv"); private final URL csvWithAlternateSeparatorPassingResultsFileURL = this.getClass().getResource("/csv3-1-pass.csv"); @Test public void jtlFileWithFailuresCountSuccessAndFailures() throws Exception { File resultsFile = new File(jtlFailingResultsFileURL.toURI());
ResultScanner fileScanner = new ResultScanner(COUNT_SUCCESSES, COUNT_FAILURES, DEFAULT_IS_CSV, DEFAULT_ONLY_FAIL_WHEN_MATCHING_FAILURE_MESSAGES, DEFAULT_FAILURE_LIST);
TEAMModding/KalStuff
src/main/java/com/team/kalstuff/item/ItemKalStuff.java
// Path: src/main/java/com/team/kalstuff/KalStuff.java // @Mod(modid = KalStuff.MODID, // name = KalStuff.NAME, // version = KalStuff.VERSION, // acceptedMinecraftVersions = "[1.12.2]", // useMetadata = true, // guiFactory = "com.team.kalstuff.config.KalStuffGuiFactory") // public class KalStuff // { // public static final String MODID = "kalstuff"; // public static final String NAME = "KalStuff"; // public static final String VERSION = "1.0.0"; // // @SidedProxy(clientSide = "com.team.kalstuff.proxy.ClientProxy", // serverSide = "com.team.kalstuff.proxy.ServerProxy") // public static CommonProxy proxy; // // // The instance of the mod that Forge uses. // @Mod.Instance // public static KalStuff instance; // // public static Logger logger; // // public static Configuration config; // // @EventHandler // public void preInit(FMLPreInitializationEvent e) // { // logger = e.getModLog(); // Config.initialize(e, e.getSuggestedConfigurationFile()); // config = Config.getConfig(); // proxy.preInit(e); // } // // @EventHandler // public void init(FMLInitializationEvent e) // { // proxy.init(e); // } // // @EventHandler // public void postInit(FMLPostInitializationEvent e) // { // if (config.hasChanged()) // { // config.save(); // } // proxy.postInit(e); // } // } // // Path: src/main/java/com/team/kalstuff/proxy/CommonProxy.java // @Mod.EventBusSubscriber // public class CommonProxy // { // public static final CreativeTabs KALSTUFFTAB = new KalStuffCreativeTab("kalstuffTab"); // // public void preInit(FMLPreInitializationEvent e) // { // MinecraftForge.EVENT_BUS.register(new CoreEventHandler()); // KalStuffTileEntities.register(); // KalStuffWorldGenerator.register(); // KalStuffEntities.setup(); // NetworkRegistry.INSTANCE.registerGuiHandler(KalStuff.instance, new KalStuffGuiHandler()); // } // // public void init(FMLInitializationEvent e) // { // KalStuffRecipes.add(); // KalStuffItems.configureItems(); // KalStuff.logger // .info("Hi there, nerdy geeks. You should just enjoy Minecraft and stop looking at the system output."); // } // // public void postInit(FMLPostInitializationEvent e) // { // KalStuff.logger.info("Wait a minute... Guys! IT WORKS!?! WE MADE A MOD!!!"); // } // }
import com.team.kalstuff.KalStuff; import com.team.kalstuff.proxy.CommonProxy; import net.minecraft.item.Item;
package com.team.kalstuff.item; public class ItemKalStuff extends Item { public ItemKalStuff(String name) { setupItem(this, name); } public static Item setupItem(Item item, String name) { item.setRegistryName(name);
// Path: src/main/java/com/team/kalstuff/KalStuff.java // @Mod(modid = KalStuff.MODID, // name = KalStuff.NAME, // version = KalStuff.VERSION, // acceptedMinecraftVersions = "[1.12.2]", // useMetadata = true, // guiFactory = "com.team.kalstuff.config.KalStuffGuiFactory") // public class KalStuff // { // public static final String MODID = "kalstuff"; // public static final String NAME = "KalStuff"; // public static final String VERSION = "1.0.0"; // // @SidedProxy(clientSide = "com.team.kalstuff.proxy.ClientProxy", // serverSide = "com.team.kalstuff.proxy.ServerProxy") // public static CommonProxy proxy; // // // The instance of the mod that Forge uses. // @Mod.Instance // public static KalStuff instance; // // public static Logger logger; // // public static Configuration config; // // @EventHandler // public void preInit(FMLPreInitializationEvent e) // { // logger = e.getModLog(); // Config.initialize(e, e.getSuggestedConfigurationFile()); // config = Config.getConfig(); // proxy.preInit(e); // } // // @EventHandler // public void init(FMLInitializationEvent e) // { // proxy.init(e); // } // // @EventHandler // public void postInit(FMLPostInitializationEvent e) // { // if (config.hasChanged()) // { // config.save(); // } // proxy.postInit(e); // } // } // // Path: src/main/java/com/team/kalstuff/proxy/CommonProxy.java // @Mod.EventBusSubscriber // public class CommonProxy // { // public static final CreativeTabs KALSTUFFTAB = new KalStuffCreativeTab("kalstuffTab"); // // public void preInit(FMLPreInitializationEvent e) // { // MinecraftForge.EVENT_BUS.register(new CoreEventHandler()); // KalStuffTileEntities.register(); // KalStuffWorldGenerator.register(); // KalStuffEntities.setup(); // NetworkRegistry.INSTANCE.registerGuiHandler(KalStuff.instance, new KalStuffGuiHandler()); // } // // public void init(FMLInitializationEvent e) // { // KalStuffRecipes.add(); // KalStuffItems.configureItems(); // KalStuff.logger // .info("Hi there, nerdy geeks. You should just enjoy Minecraft and stop looking at the system output."); // } // // public void postInit(FMLPostInitializationEvent e) // { // KalStuff.logger.info("Wait a minute... Guys! IT WORKS!?! WE MADE A MOD!!!"); // } // } // Path: src/main/java/com/team/kalstuff/item/ItemKalStuff.java import com.team.kalstuff.KalStuff; import com.team.kalstuff.proxy.CommonProxy; import net.minecraft.item.Item; package com.team.kalstuff.item; public class ItemKalStuff extends Item { public ItemKalStuff(String name) { setupItem(this, name); } public static Item setupItem(Item item, String name) { item.setRegistryName(name);
item.setUnlocalizedName(KalStuff.MODID + ":" + name);
TEAMModding/KalStuff
src/main/java/com/team/kalstuff/item/ItemKalStuff.java
// Path: src/main/java/com/team/kalstuff/KalStuff.java // @Mod(modid = KalStuff.MODID, // name = KalStuff.NAME, // version = KalStuff.VERSION, // acceptedMinecraftVersions = "[1.12.2]", // useMetadata = true, // guiFactory = "com.team.kalstuff.config.KalStuffGuiFactory") // public class KalStuff // { // public static final String MODID = "kalstuff"; // public static final String NAME = "KalStuff"; // public static final String VERSION = "1.0.0"; // // @SidedProxy(clientSide = "com.team.kalstuff.proxy.ClientProxy", // serverSide = "com.team.kalstuff.proxy.ServerProxy") // public static CommonProxy proxy; // // // The instance of the mod that Forge uses. // @Mod.Instance // public static KalStuff instance; // // public static Logger logger; // // public static Configuration config; // // @EventHandler // public void preInit(FMLPreInitializationEvent e) // { // logger = e.getModLog(); // Config.initialize(e, e.getSuggestedConfigurationFile()); // config = Config.getConfig(); // proxy.preInit(e); // } // // @EventHandler // public void init(FMLInitializationEvent e) // { // proxy.init(e); // } // // @EventHandler // public void postInit(FMLPostInitializationEvent e) // { // if (config.hasChanged()) // { // config.save(); // } // proxy.postInit(e); // } // } // // Path: src/main/java/com/team/kalstuff/proxy/CommonProxy.java // @Mod.EventBusSubscriber // public class CommonProxy // { // public static final CreativeTabs KALSTUFFTAB = new KalStuffCreativeTab("kalstuffTab"); // // public void preInit(FMLPreInitializationEvent e) // { // MinecraftForge.EVENT_BUS.register(new CoreEventHandler()); // KalStuffTileEntities.register(); // KalStuffWorldGenerator.register(); // KalStuffEntities.setup(); // NetworkRegistry.INSTANCE.registerGuiHandler(KalStuff.instance, new KalStuffGuiHandler()); // } // // public void init(FMLInitializationEvent e) // { // KalStuffRecipes.add(); // KalStuffItems.configureItems(); // KalStuff.logger // .info("Hi there, nerdy geeks. You should just enjoy Minecraft and stop looking at the system output."); // } // // public void postInit(FMLPostInitializationEvent e) // { // KalStuff.logger.info("Wait a minute... Guys! IT WORKS!?! WE MADE A MOD!!!"); // } // }
import com.team.kalstuff.KalStuff; import com.team.kalstuff.proxy.CommonProxy; import net.minecraft.item.Item;
package com.team.kalstuff.item; public class ItemKalStuff extends Item { public ItemKalStuff(String name) { setupItem(this, name); } public static Item setupItem(Item item, String name) { item.setRegistryName(name); item.setUnlocalizedName(KalStuff.MODID + ":" + name);
// Path: src/main/java/com/team/kalstuff/KalStuff.java // @Mod(modid = KalStuff.MODID, // name = KalStuff.NAME, // version = KalStuff.VERSION, // acceptedMinecraftVersions = "[1.12.2]", // useMetadata = true, // guiFactory = "com.team.kalstuff.config.KalStuffGuiFactory") // public class KalStuff // { // public static final String MODID = "kalstuff"; // public static final String NAME = "KalStuff"; // public static final String VERSION = "1.0.0"; // // @SidedProxy(clientSide = "com.team.kalstuff.proxy.ClientProxy", // serverSide = "com.team.kalstuff.proxy.ServerProxy") // public static CommonProxy proxy; // // // The instance of the mod that Forge uses. // @Mod.Instance // public static KalStuff instance; // // public static Logger logger; // // public static Configuration config; // // @EventHandler // public void preInit(FMLPreInitializationEvent e) // { // logger = e.getModLog(); // Config.initialize(e, e.getSuggestedConfigurationFile()); // config = Config.getConfig(); // proxy.preInit(e); // } // // @EventHandler // public void init(FMLInitializationEvent e) // { // proxy.init(e); // } // // @EventHandler // public void postInit(FMLPostInitializationEvent e) // { // if (config.hasChanged()) // { // config.save(); // } // proxy.postInit(e); // } // } // // Path: src/main/java/com/team/kalstuff/proxy/CommonProxy.java // @Mod.EventBusSubscriber // public class CommonProxy // { // public static final CreativeTabs KALSTUFFTAB = new KalStuffCreativeTab("kalstuffTab"); // // public void preInit(FMLPreInitializationEvent e) // { // MinecraftForge.EVENT_BUS.register(new CoreEventHandler()); // KalStuffTileEntities.register(); // KalStuffWorldGenerator.register(); // KalStuffEntities.setup(); // NetworkRegistry.INSTANCE.registerGuiHandler(KalStuff.instance, new KalStuffGuiHandler()); // } // // public void init(FMLInitializationEvent e) // { // KalStuffRecipes.add(); // KalStuffItems.configureItems(); // KalStuff.logger // .info("Hi there, nerdy geeks. You should just enjoy Minecraft and stop looking at the system output."); // } // // public void postInit(FMLPostInitializationEvent e) // { // KalStuff.logger.info("Wait a minute... Guys! IT WORKS!?! WE MADE A MOD!!!"); // } // } // Path: src/main/java/com/team/kalstuff/item/ItemKalStuff.java import com.team.kalstuff.KalStuff; import com.team.kalstuff.proxy.CommonProxy; import net.minecraft.item.Item; package com.team.kalstuff.item; public class ItemKalStuff extends Item { public ItemKalStuff(String name) { setupItem(this, name); } public static Item setupItem(Item item, String name) { item.setRegistryName(name); item.setUnlocalizedName(KalStuff.MODID + ":" + name);
item.setCreativeTab(CommonProxy.KALSTUFFTAB);
TEAMModding/KalStuff
src/main/java/com/team/kalstuff/item/ItemClosedSoda.java
// Path: src/main/java/com/team/kalstuff/KalStuffSoundEvents.java // @ObjectHolder(KalStuff.MODID) // public class KalStuffSoundEvents // { // @ObjectHolder("item.closed_soda.open") // public static final SoundEvent CAN_OPEN = null; // // @Mod.EventBusSubscriber(modid = KalStuff.MODID) // public static class RegistrationHandler // { // /** // * Register this mod's {@link SoundEvent}s. // * // * @param event // * The event // */ // @SubscribeEvent // public static void registerSoundEvents(final RegistryEvent.Register<SoundEvent> event) // { // final SoundEvent[] soundEvents = { createSoundEvent("item.closed_soda.open") }; // event.getRegistry().registerAll(soundEvents); // } // // /** // * Create a {@link SoundEvent}. // * // * @param soundName // * The SoundEvent's name without the testmod3 prefix // * @return The SoundEvent // */ // private static SoundEvent createSoundEvent(final String soundName) // { // final ResourceLocation soundID = new ResourceLocation(KalStuff.MODID, soundName); // return new SoundEvent(soundID).setRegistryName(soundID); // } // } // }
import java.util.List; import com.team.kalstuff.KalStuffSoundEvents; import net.minecraft.client.util.ITooltipFlag; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.item.Item; import net.minecraft.item.ItemStack; import net.minecraft.util.ActionResult; import net.minecraft.util.EnumActionResult; import net.minecraft.util.EnumHand; import net.minecraft.util.SoundCategory; import net.minecraft.world.World;
package com.team.kalstuff.item; public class ItemClosedSoda extends ItemKalStuff { private ItemStack returnStack = ItemStack.EMPTY; public ItemClosedSoda(String name) { super(name); this.setMaxStackSize(6); } @Override public ActionResult<ItemStack> onItemRightClick(World worldIn, EntityPlayer playerIn, EnumHand hand) { super.onItemRightClick(worldIn, playerIn, hand);
// Path: src/main/java/com/team/kalstuff/KalStuffSoundEvents.java // @ObjectHolder(KalStuff.MODID) // public class KalStuffSoundEvents // { // @ObjectHolder("item.closed_soda.open") // public static final SoundEvent CAN_OPEN = null; // // @Mod.EventBusSubscriber(modid = KalStuff.MODID) // public static class RegistrationHandler // { // /** // * Register this mod's {@link SoundEvent}s. // * // * @param event // * The event // */ // @SubscribeEvent // public static void registerSoundEvents(final RegistryEvent.Register<SoundEvent> event) // { // final SoundEvent[] soundEvents = { createSoundEvent("item.closed_soda.open") }; // event.getRegistry().registerAll(soundEvents); // } // // /** // * Create a {@link SoundEvent}. // * // * @param soundName // * The SoundEvent's name without the testmod3 prefix // * @return The SoundEvent // */ // private static SoundEvent createSoundEvent(final String soundName) // { // final ResourceLocation soundID = new ResourceLocation(KalStuff.MODID, soundName); // return new SoundEvent(soundID).setRegistryName(soundID); // } // } // } // Path: src/main/java/com/team/kalstuff/item/ItemClosedSoda.java import java.util.List; import com.team.kalstuff.KalStuffSoundEvents; import net.minecraft.client.util.ITooltipFlag; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.item.Item; import net.minecraft.item.ItemStack; import net.minecraft.util.ActionResult; import net.minecraft.util.EnumActionResult; import net.minecraft.util.EnumHand; import net.minecraft.util.SoundCategory; import net.minecraft.world.World; package com.team.kalstuff.item; public class ItemClosedSoda extends ItemKalStuff { private ItemStack returnStack = ItemStack.EMPTY; public ItemClosedSoda(String name) { super(name); this.setMaxStackSize(6); } @Override public ActionResult<ItemStack> onItemRightClick(World worldIn, EntityPlayer playerIn, EnumHand hand) { super.onItemRightClick(worldIn, playerIn, hand);
worldIn.playSound(playerIn, playerIn.posX, playerIn.posY, playerIn.posZ, KalStuffSoundEvents.CAN_OPEN,
TEAMModding/KalStuff
src/main/java/com/team/kalstuff/block/BlockKalStuff.java
// Path: src/main/java/com/team/kalstuff/KalStuff.java // @Mod(modid = KalStuff.MODID, // name = KalStuff.NAME, // version = KalStuff.VERSION, // acceptedMinecraftVersions = "[1.12.2]", // useMetadata = true, // guiFactory = "com.team.kalstuff.config.KalStuffGuiFactory") // public class KalStuff // { // public static final String MODID = "kalstuff"; // public static final String NAME = "KalStuff"; // public static final String VERSION = "1.0.0"; // // @SidedProxy(clientSide = "com.team.kalstuff.proxy.ClientProxy", // serverSide = "com.team.kalstuff.proxy.ServerProxy") // public static CommonProxy proxy; // // // The instance of the mod that Forge uses. // @Mod.Instance // public static KalStuff instance; // // public static Logger logger; // // public static Configuration config; // // @EventHandler // public void preInit(FMLPreInitializationEvent e) // { // logger = e.getModLog(); // Config.initialize(e, e.getSuggestedConfigurationFile()); // config = Config.getConfig(); // proxy.preInit(e); // } // // @EventHandler // public void init(FMLInitializationEvent e) // { // proxy.init(e); // } // // @EventHandler // public void postInit(FMLPostInitializationEvent e) // { // if (config.hasChanged()) // { // config.save(); // } // proxy.postInit(e); // } // } // // Path: src/main/java/com/team/kalstuff/proxy/CommonProxy.java // @Mod.EventBusSubscriber // public class CommonProxy // { // public static final CreativeTabs KALSTUFFTAB = new KalStuffCreativeTab("kalstuffTab"); // // public void preInit(FMLPreInitializationEvent e) // { // MinecraftForge.EVENT_BUS.register(new CoreEventHandler()); // KalStuffTileEntities.register(); // KalStuffWorldGenerator.register(); // KalStuffEntities.setup(); // NetworkRegistry.INSTANCE.registerGuiHandler(KalStuff.instance, new KalStuffGuiHandler()); // } // // public void init(FMLInitializationEvent e) // { // KalStuffRecipes.add(); // KalStuffItems.configureItems(); // KalStuff.logger // .info("Hi there, nerdy geeks. You should just enjoy Minecraft and stop looking at the system output."); // } // // public void postInit(FMLPostInitializationEvent e) // { // KalStuff.logger.info("Wait a minute... Guys! IT WORKS!?! WE MADE A MOD!!!"); // } // }
import com.team.kalstuff.KalStuff; import com.team.kalstuff.proxy.CommonProxy; import net.minecraft.block.Block; import net.minecraft.block.SoundType; import net.minecraft.block.material.Material;
package com.team.kalstuff.block; public class BlockKalStuff extends Block { public BlockKalStuff(Material material, String name) { super(material); setupBlock(this, name); } public BlockKalStuff(Material material, SoundType sound, String name) { super(material); this.setSoundType(sound); setupBlock(this, name); } public static Block setupBlock(Block block, String name) { block.setRegistryName(name);
// Path: src/main/java/com/team/kalstuff/KalStuff.java // @Mod(modid = KalStuff.MODID, // name = KalStuff.NAME, // version = KalStuff.VERSION, // acceptedMinecraftVersions = "[1.12.2]", // useMetadata = true, // guiFactory = "com.team.kalstuff.config.KalStuffGuiFactory") // public class KalStuff // { // public static final String MODID = "kalstuff"; // public static final String NAME = "KalStuff"; // public static final String VERSION = "1.0.0"; // // @SidedProxy(clientSide = "com.team.kalstuff.proxy.ClientProxy", // serverSide = "com.team.kalstuff.proxy.ServerProxy") // public static CommonProxy proxy; // // // The instance of the mod that Forge uses. // @Mod.Instance // public static KalStuff instance; // // public static Logger logger; // // public static Configuration config; // // @EventHandler // public void preInit(FMLPreInitializationEvent e) // { // logger = e.getModLog(); // Config.initialize(e, e.getSuggestedConfigurationFile()); // config = Config.getConfig(); // proxy.preInit(e); // } // // @EventHandler // public void init(FMLInitializationEvent e) // { // proxy.init(e); // } // // @EventHandler // public void postInit(FMLPostInitializationEvent e) // { // if (config.hasChanged()) // { // config.save(); // } // proxy.postInit(e); // } // } // // Path: src/main/java/com/team/kalstuff/proxy/CommonProxy.java // @Mod.EventBusSubscriber // public class CommonProxy // { // public static final CreativeTabs KALSTUFFTAB = new KalStuffCreativeTab("kalstuffTab"); // // public void preInit(FMLPreInitializationEvent e) // { // MinecraftForge.EVENT_BUS.register(new CoreEventHandler()); // KalStuffTileEntities.register(); // KalStuffWorldGenerator.register(); // KalStuffEntities.setup(); // NetworkRegistry.INSTANCE.registerGuiHandler(KalStuff.instance, new KalStuffGuiHandler()); // } // // public void init(FMLInitializationEvent e) // { // KalStuffRecipes.add(); // KalStuffItems.configureItems(); // KalStuff.logger // .info("Hi there, nerdy geeks. You should just enjoy Minecraft and stop looking at the system output."); // } // // public void postInit(FMLPostInitializationEvent e) // { // KalStuff.logger.info("Wait a minute... Guys! IT WORKS!?! WE MADE A MOD!!!"); // } // } // Path: src/main/java/com/team/kalstuff/block/BlockKalStuff.java import com.team.kalstuff.KalStuff; import com.team.kalstuff.proxy.CommonProxy; import net.minecraft.block.Block; import net.minecraft.block.SoundType; import net.minecraft.block.material.Material; package com.team.kalstuff.block; public class BlockKalStuff extends Block { public BlockKalStuff(Material material, String name) { super(material); setupBlock(this, name); } public BlockKalStuff(Material material, SoundType sound, String name) { super(material); this.setSoundType(sound); setupBlock(this, name); } public static Block setupBlock(Block block, String name) { block.setRegistryName(name);
block.setUnlocalizedName(KalStuff.MODID + ":" + name);
TEAMModding/KalStuff
src/main/java/com/team/kalstuff/block/BlockKalStuff.java
// Path: src/main/java/com/team/kalstuff/KalStuff.java // @Mod(modid = KalStuff.MODID, // name = KalStuff.NAME, // version = KalStuff.VERSION, // acceptedMinecraftVersions = "[1.12.2]", // useMetadata = true, // guiFactory = "com.team.kalstuff.config.KalStuffGuiFactory") // public class KalStuff // { // public static final String MODID = "kalstuff"; // public static final String NAME = "KalStuff"; // public static final String VERSION = "1.0.0"; // // @SidedProxy(clientSide = "com.team.kalstuff.proxy.ClientProxy", // serverSide = "com.team.kalstuff.proxy.ServerProxy") // public static CommonProxy proxy; // // // The instance of the mod that Forge uses. // @Mod.Instance // public static KalStuff instance; // // public static Logger logger; // // public static Configuration config; // // @EventHandler // public void preInit(FMLPreInitializationEvent e) // { // logger = e.getModLog(); // Config.initialize(e, e.getSuggestedConfigurationFile()); // config = Config.getConfig(); // proxy.preInit(e); // } // // @EventHandler // public void init(FMLInitializationEvent e) // { // proxy.init(e); // } // // @EventHandler // public void postInit(FMLPostInitializationEvent e) // { // if (config.hasChanged()) // { // config.save(); // } // proxy.postInit(e); // } // } // // Path: src/main/java/com/team/kalstuff/proxy/CommonProxy.java // @Mod.EventBusSubscriber // public class CommonProxy // { // public static final CreativeTabs KALSTUFFTAB = new KalStuffCreativeTab("kalstuffTab"); // // public void preInit(FMLPreInitializationEvent e) // { // MinecraftForge.EVENT_BUS.register(new CoreEventHandler()); // KalStuffTileEntities.register(); // KalStuffWorldGenerator.register(); // KalStuffEntities.setup(); // NetworkRegistry.INSTANCE.registerGuiHandler(KalStuff.instance, new KalStuffGuiHandler()); // } // // public void init(FMLInitializationEvent e) // { // KalStuffRecipes.add(); // KalStuffItems.configureItems(); // KalStuff.logger // .info("Hi there, nerdy geeks. You should just enjoy Minecraft and stop looking at the system output."); // } // // public void postInit(FMLPostInitializationEvent e) // { // KalStuff.logger.info("Wait a minute... Guys! IT WORKS!?! WE MADE A MOD!!!"); // } // }
import com.team.kalstuff.KalStuff; import com.team.kalstuff.proxy.CommonProxy; import net.minecraft.block.Block; import net.minecraft.block.SoundType; import net.minecraft.block.material.Material;
package com.team.kalstuff.block; public class BlockKalStuff extends Block { public BlockKalStuff(Material material, String name) { super(material); setupBlock(this, name); } public BlockKalStuff(Material material, SoundType sound, String name) { super(material); this.setSoundType(sound); setupBlock(this, name); } public static Block setupBlock(Block block, String name) { block.setRegistryName(name); block.setUnlocalizedName(KalStuff.MODID + ":" + name);
// Path: src/main/java/com/team/kalstuff/KalStuff.java // @Mod(modid = KalStuff.MODID, // name = KalStuff.NAME, // version = KalStuff.VERSION, // acceptedMinecraftVersions = "[1.12.2]", // useMetadata = true, // guiFactory = "com.team.kalstuff.config.KalStuffGuiFactory") // public class KalStuff // { // public static final String MODID = "kalstuff"; // public static final String NAME = "KalStuff"; // public static final String VERSION = "1.0.0"; // // @SidedProxy(clientSide = "com.team.kalstuff.proxy.ClientProxy", // serverSide = "com.team.kalstuff.proxy.ServerProxy") // public static CommonProxy proxy; // // // The instance of the mod that Forge uses. // @Mod.Instance // public static KalStuff instance; // // public static Logger logger; // // public static Configuration config; // // @EventHandler // public void preInit(FMLPreInitializationEvent e) // { // logger = e.getModLog(); // Config.initialize(e, e.getSuggestedConfigurationFile()); // config = Config.getConfig(); // proxy.preInit(e); // } // // @EventHandler // public void init(FMLInitializationEvent e) // { // proxy.init(e); // } // // @EventHandler // public void postInit(FMLPostInitializationEvent e) // { // if (config.hasChanged()) // { // config.save(); // } // proxy.postInit(e); // } // } // // Path: src/main/java/com/team/kalstuff/proxy/CommonProxy.java // @Mod.EventBusSubscriber // public class CommonProxy // { // public static final CreativeTabs KALSTUFFTAB = new KalStuffCreativeTab("kalstuffTab"); // // public void preInit(FMLPreInitializationEvent e) // { // MinecraftForge.EVENT_BUS.register(new CoreEventHandler()); // KalStuffTileEntities.register(); // KalStuffWorldGenerator.register(); // KalStuffEntities.setup(); // NetworkRegistry.INSTANCE.registerGuiHandler(KalStuff.instance, new KalStuffGuiHandler()); // } // // public void init(FMLInitializationEvent e) // { // KalStuffRecipes.add(); // KalStuffItems.configureItems(); // KalStuff.logger // .info("Hi there, nerdy geeks. You should just enjoy Minecraft and stop looking at the system output."); // } // // public void postInit(FMLPostInitializationEvent e) // { // KalStuff.logger.info("Wait a minute... Guys! IT WORKS!?! WE MADE A MOD!!!"); // } // } // Path: src/main/java/com/team/kalstuff/block/BlockKalStuff.java import com.team.kalstuff.KalStuff; import com.team.kalstuff.proxy.CommonProxy; import net.minecraft.block.Block; import net.minecraft.block.SoundType; import net.minecraft.block.material.Material; package com.team.kalstuff.block; public class BlockKalStuff extends Block { public BlockKalStuff(Material material, String name) { super(material); setupBlock(this, name); } public BlockKalStuff(Material material, SoundType sound, String name) { super(material); this.setSoundType(sound); setupBlock(this, name); } public static Block setupBlock(Block block, String name) { block.setRegistryName(name); block.setUnlocalizedName(KalStuff.MODID + ":" + name);
block.setCreativeTab(CommonProxy.KALSTUFFTAB);
TEAMModding/KalStuff
src/main/java/com/team/kalstuff/gui/GuiChickenNest.java
// Path: src/main/java/com/team/kalstuff/block/KalStuffBlocks.java // @GameRegistry.ObjectHolder("kalstuff") // @Mod.EventBusSubscriber(modid = "kalstuff") // public class KalStuffBlocks // { // // ---Please keep all blocks in alphabetical order!--- // // public static final Block APPLE_BLOCK = Blocks.AIR; // public static final Block BAKED_POTATO_BLOCK = Blocks.AIR; // public static final Block BLAZE_BLOCK = Blocks.AIR; // public static final Block BRIDGE = Blocks.AIR; // public static final Block CARROT_BLOCK = Blocks.AIR; // public static final Block CHICKEN_NEST = Blocks.AIR; // public static final Block ENDER_BLOCK = Blocks.AIR; // public static final Block GRAPE_VINE = Blocks.AIR; // public static final Block GREAT_GRAPE = Blocks.AIR; // public static final Block MOON_FLOWER = Blocks.AIR; // public static final Block MOON_FLOWER1 = Blocks.AIR; // public static final Block MOON_FLOWER2 = Blocks.AIR; // public static final Block MOON_FLOWER3 = Blocks.AIR; // public static final Block MOON_FLOWER4 = Blocks.AIR; // public static final Block MOON_FLOWER5 = Blocks.AIR; // public static final Block POTATO_BLOCK = Blocks.AIR; // public static final Block TRASH_CAN = Blocks.AIR; // public static final Block WILD_GRAPE_VINE = Blocks.AIR; // // /** // * Registers all blocks from the mod. // */ // @SubscribeEvent // public static void registerBlocks(Register<Block> event) // { // IForgeRegistry<Block> reg = event.getRegistry(); // // remember to register ItemBlocks in KalStuffItems, and // // please continue to keep all blocks in alphabetical order // // reg.register(new BlockFood(1.5F, 9, 2.4F, "apple_block")); // reg.register(new BlockBakedPotato(1.5F, 11, 6F, "baked_potato_block")); // reg.register(new BlockKalStuff(Material.IRON, SoundType.METAL, "blaze_block").setHardness(35.0F)); // reg.register(new BlockBridge("bridge")); // reg.register(new BlockFood(11.5F, 7, 4.8F, "carrot_block")); // reg.register(new BlockChickenNest("chicken_nest")); // reg.register(new BlockKalStuff(Material.IRON, SoundType.METAL, "ender_block").setHardness(5.0F)); // reg.register(new BlockGrapeVine("grape_vine")); // reg.register(new BlockKalStuff(Material.SPONGE, SoundType.CLOTH, "great_grape")); // // only the first BlockMoonFlower should appear in the Creative inventory // reg.register(new BlockMoonFlower(0, "moon_flower").setCreativeTab(CommonProxy.KALSTUFFTAB)); // reg.register(new BlockMoonFlower(1, "moon_flower1")); // reg.register(new BlockMoonFlower(2, "moon_flower2")); // reg.register(new BlockMoonFlower(3, "moon_flower3")); // reg.register(new BlockMoonFlower(4, "moon_flower4")); // reg.register(new BlockMoonFlower(5, "moon_flower5")); // reg.register(new BlockFood(1.5F, 3, 0.6F, "potato_block")); // reg.register(new BlockTrashCan("trash_can")); // reg.register(new BlockWildGrapeVine("wild_grape_vine")); // } // }
import com.team.kalstuff.block.KalStuffBlocks; import net.minecraft.client.Minecraft; import net.minecraft.client.gui.inventory.GuiContainer; import net.minecraft.client.renderer.GlStateManager; import net.minecraft.client.resources.I18n; import net.minecraft.entity.player.InventoryPlayer; import net.minecraft.inventory.Container; import net.minecraft.util.ResourceLocation; import net.minecraftforge.fml.relauncher.Side; import net.minecraftforge.fml.relauncher.SideOnly;
package com.team.kalstuff.gui; @SideOnly(Side.CLIENT) public class GuiChickenNest extends GuiContainer { // this is the resource location for the background image for the GUI private static final ResourceLocation texture = new ResourceLocation("kalstuff", "textures/gui/chicken_nest.png"); private InventoryPlayer playerInv; public GuiChickenNest(Container container, InventoryPlayer playerInv) { super(container); this.playerInv = playerInv; // set the width and height of the GUI. Should match the size of the texture! xSize = 176; ySize = 133; } @Override protected void drawGuiContainerBackgroundLayer(float partialTicks, int x, int y) { // bind the image texture of our custom container Minecraft.getMinecraft().getTextureManager().bindTexture(texture); // draw the image GlStateManager.color(1.0F, 1.0F, 1.0F, 1.0F); drawTexturedModalRect(guiLeft, guiTop, 0, 0, xSize, ySize); } @Override protected void drawGuiContainerForegroundLayer(int mouseX, int mouseY) {
// Path: src/main/java/com/team/kalstuff/block/KalStuffBlocks.java // @GameRegistry.ObjectHolder("kalstuff") // @Mod.EventBusSubscriber(modid = "kalstuff") // public class KalStuffBlocks // { // // ---Please keep all blocks in alphabetical order!--- // // public static final Block APPLE_BLOCK = Blocks.AIR; // public static final Block BAKED_POTATO_BLOCK = Blocks.AIR; // public static final Block BLAZE_BLOCK = Blocks.AIR; // public static final Block BRIDGE = Blocks.AIR; // public static final Block CARROT_BLOCK = Blocks.AIR; // public static final Block CHICKEN_NEST = Blocks.AIR; // public static final Block ENDER_BLOCK = Blocks.AIR; // public static final Block GRAPE_VINE = Blocks.AIR; // public static final Block GREAT_GRAPE = Blocks.AIR; // public static final Block MOON_FLOWER = Blocks.AIR; // public static final Block MOON_FLOWER1 = Blocks.AIR; // public static final Block MOON_FLOWER2 = Blocks.AIR; // public static final Block MOON_FLOWER3 = Blocks.AIR; // public static final Block MOON_FLOWER4 = Blocks.AIR; // public static final Block MOON_FLOWER5 = Blocks.AIR; // public static final Block POTATO_BLOCK = Blocks.AIR; // public static final Block TRASH_CAN = Blocks.AIR; // public static final Block WILD_GRAPE_VINE = Blocks.AIR; // // /** // * Registers all blocks from the mod. // */ // @SubscribeEvent // public static void registerBlocks(Register<Block> event) // { // IForgeRegistry<Block> reg = event.getRegistry(); // // remember to register ItemBlocks in KalStuffItems, and // // please continue to keep all blocks in alphabetical order // // reg.register(new BlockFood(1.5F, 9, 2.4F, "apple_block")); // reg.register(new BlockBakedPotato(1.5F, 11, 6F, "baked_potato_block")); // reg.register(new BlockKalStuff(Material.IRON, SoundType.METAL, "blaze_block").setHardness(35.0F)); // reg.register(new BlockBridge("bridge")); // reg.register(new BlockFood(11.5F, 7, 4.8F, "carrot_block")); // reg.register(new BlockChickenNest("chicken_nest")); // reg.register(new BlockKalStuff(Material.IRON, SoundType.METAL, "ender_block").setHardness(5.0F)); // reg.register(new BlockGrapeVine("grape_vine")); // reg.register(new BlockKalStuff(Material.SPONGE, SoundType.CLOTH, "great_grape")); // // only the first BlockMoonFlower should appear in the Creative inventory // reg.register(new BlockMoonFlower(0, "moon_flower").setCreativeTab(CommonProxy.KALSTUFFTAB)); // reg.register(new BlockMoonFlower(1, "moon_flower1")); // reg.register(new BlockMoonFlower(2, "moon_flower2")); // reg.register(new BlockMoonFlower(3, "moon_flower3")); // reg.register(new BlockMoonFlower(4, "moon_flower4")); // reg.register(new BlockMoonFlower(5, "moon_flower5")); // reg.register(new BlockFood(1.5F, 3, 0.6F, "potato_block")); // reg.register(new BlockTrashCan("trash_can")); // reg.register(new BlockWildGrapeVine("wild_grape_vine")); // } // } // Path: src/main/java/com/team/kalstuff/gui/GuiChickenNest.java import com.team.kalstuff.block.KalStuffBlocks; import net.minecraft.client.Minecraft; import net.minecraft.client.gui.inventory.GuiContainer; import net.minecraft.client.renderer.GlStateManager; import net.minecraft.client.resources.I18n; import net.minecraft.entity.player.InventoryPlayer; import net.minecraft.inventory.Container; import net.minecraft.util.ResourceLocation; import net.minecraftforge.fml.relauncher.Side; import net.minecraftforge.fml.relauncher.SideOnly; package com.team.kalstuff.gui; @SideOnly(Side.CLIENT) public class GuiChickenNest extends GuiContainer { // this is the resource location for the background image for the GUI private static final ResourceLocation texture = new ResourceLocation("kalstuff", "textures/gui/chicken_nest.png"); private InventoryPlayer playerInv; public GuiChickenNest(Container container, InventoryPlayer playerInv) { super(container); this.playerInv = playerInv; // set the width and height of the GUI. Should match the size of the texture! xSize = 176; ySize = 133; } @Override protected void drawGuiContainerBackgroundLayer(float partialTicks, int x, int y) { // bind the image texture of our custom container Minecraft.getMinecraft().getTextureManager().bindTexture(texture); // draw the image GlStateManager.color(1.0F, 1.0F, 1.0F, 1.0F); drawTexturedModalRect(guiLeft, guiTop, 0, 0, xSize, ySize); } @Override protected void drawGuiContainerForegroundLayer(int mouseX, int mouseY) {
String name = I18n.format(KalStuffBlocks.CHICKEN_NEST.getUnlocalizedName() + ".name");
TEAMModding/KalStuff
src/main/java/com/team/kalstuff/tileentity/KalStuffTileEntities.java
// Path: src/main/java/com/team/kalstuff/KalStuff.java // @Mod(modid = KalStuff.MODID, // name = KalStuff.NAME, // version = KalStuff.VERSION, // acceptedMinecraftVersions = "[1.12.2]", // useMetadata = true, // guiFactory = "com.team.kalstuff.config.KalStuffGuiFactory") // public class KalStuff // { // public static final String MODID = "kalstuff"; // public static final String NAME = "KalStuff"; // public static final String VERSION = "1.0.0"; // // @SidedProxy(clientSide = "com.team.kalstuff.proxy.ClientProxy", // serverSide = "com.team.kalstuff.proxy.ServerProxy") // public static CommonProxy proxy; // // // The instance of the mod that Forge uses. // @Mod.Instance // public static KalStuff instance; // // public static Logger logger; // // public static Configuration config; // // @EventHandler // public void preInit(FMLPreInitializationEvent e) // { // logger = e.getModLog(); // Config.initialize(e, e.getSuggestedConfigurationFile()); // config = Config.getConfig(); // proxy.preInit(e); // } // // @EventHandler // public void init(FMLInitializationEvent e) // { // proxy.init(e); // } // // @EventHandler // public void postInit(FMLPostInitializationEvent e) // { // if (config.hasChanged()) // { // config.save(); // } // proxy.postInit(e); // } // }
import com.team.kalstuff.KalStuff; import net.minecraftforge.fml.common.registry.GameRegistry;
package com.team.kalstuff.tileentity; public class KalStuffTileEntities { public static void register() {
// Path: src/main/java/com/team/kalstuff/KalStuff.java // @Mod(modid = KalStuff.MODID, // name = KalStuff.NAME, // version = KalStuff.VERSION, // acceptedMinecraftVersions = "[1.12.2]", // useMetadata = true, // guiFactory = "com.team.kalstuff.config.KalStuffGuiFactory") // public class KalStuff // { // public static final String MODID = "kalstuff"; // public static final String NAME = "KalStuff"; // public static final String VERSION = "1.0.0"; // // @SidedProxy(clientSide = "com.team.kalstuff.proxy.ClientProxy", // serverSide = "com.team.kalstuff.proxy.ServerProxy") // public static CommonProxy proxy; // // // The instance of the mod that Forge uses. // @Mod.Instance // public static KalStuff instance; // // public static Logger logger; // // public static Configuration config; // // @EventHandler // public void preInit(FMLPreInitializationEvent e) // { // logger = e.getModLog(); // Config.initialize(e, e.getSuggestedConfigurationFile()); // config = Config.getConfig(); // proxy.preInit(e); // } // // @EventHandler // public void init(FMLInitializationEvent e) // { // proxy.init(e); // } // // @EventHandler // public void postInit(FMLPostInitializationEvent e) // { // if (config.hasChanged()) // { // config.save(); // } // proxy.postInit(e); // } // } // Path: src/main/java/com/team/kalstuff/tileentity/KalStuffTileEntities.java import com.team.kalstuff.KalStuff; import net.minecraftforge.fml.common.registry.GameRegistry; package com.team.kalstuff.tileentity; public class KalStuffTileEntities { public static void register() {
GameRegistry.registerTileEntity(TileEntityChickenNest.class, KalStuff.MODID + ":chicken_nest");
TEAMModding/KalStuff
src/main/java/com/team/kalstuff/config/Config.java
// Path: src/main/java/com/team/kalstuff/KalStuff.java // @Mod(modid = KalStuff.MODID, // name = KalStuff.NAME, // version = KalStuff.VERSION, // acceptedMinecraftVersions = "[1.12.2]", // useMetadata = true, // guiFactory = "com.team.kalstuff.config.KalStuffGuiFactory") // public class KalStuff // { // public static final String MODID = "kalstuff"; // public static final String NAME = "KalStuff"; // public static final String VERSION = "1.0.0"; // // @SidedProxy(clientSide = "com.team.kalstuff.proxy.ClientProxy", // serverSide = "com.team.kalstuff.proxy.ServerProxy") // public static CommonProxy proxy; // // // The instance of the mod that Forge uses. // @Mod.Instance // public static KalStuff instance; // // public static Logger logger; // // public static Configuration config; // // @EventHandler // public void preInit(FMLPreInitializationEvent e) // { // logger = e.getModLog(); // Config.initialize(e, e.getSuggestedConfigurationFile()); // config = Config.getConfig(); // proxy.preInit(e); // } // // @EventHandler // public void init(FMLInitializationEvent e) // { // proxy.init(e); // } // // @EventHandler // public void postInit(FMLPostInitializationEvent e) // { // if (config.hasChanged()) // { // config.save(); // } // proxy.postInit(e); // } // }
import java.io.File; import java.util.List; import com.team.kalstuff.KalStuff; import net.minecraftforge.common.MinecraftForge; import net.minecraftforge.common.config.ConfigElement; import net.minecraftforge.common.config.Configuration; import net.minecraftforge.fml.client.config.IConfigElement; import net.minecraftforge.fml.client.event.ConfigChangedEvent; import net.minecraftforge.fml.common.event.FMLPreInitializationEvent; import net.minecraftforge.fml.common.eventhandler.SubscribeEvent;
package com.team.kalstuff.config; public class Config { public static File configurationFile; public static Configuration config; public static final String CATEGORY_GENERAL = "General"; public static int cottageRarity = 512; public static boolean bridgeTNT = false; public static final void initialize(FMLPreInitializationEvent e, File file) {
// Path: src/main/java/com/team/kalstuff/KalStuff.java // @Mod(modid = KalStuff.MODID, // name = KalStuff.NAME, // version = KalStuff.VERSION, // acceptedMinecraftVersions = "[1.12.2]", // useMetadata = true, // guiFactory = "com.team.kalstuff.config.KalStuffGuiFactory") // public class KalStuff // { // public static final String MODID = "kalstuff"; // public static final String NAME = "KalStuff"; // public static final String VERSION = "1.0.0"; // // @SidedProxy(clientSide = "com.team.kalstuff.proxy.ClientProxy", // serverSide = "com.team.kalstuff.proxy.ServerProxy") // public static CommonProxy proxy; // // // The instance of the mod that Forge uses. // @Mod.Instance // public static KalStuff instance; // // public static Logger logger; // // public static Configuration config; // // @EventHandler // public void preInit(FMLPreInitializationEvent e) // { // logger = e.getModLog(); // Config.initialize(e, e.getSuggestedConfigurationFile()); // config = Config.getConfig(); // proxy.preInit(e); // } // // @EventHandler // public void init(FMLInitializationEvent e) // { // proxy.init(e); // } // // @EventHandler // public void postInit(FMLPostInitializationEvent e) // { // if (config.hasChanged()) // { // config.save(); // } // proxy.postInit(e); // } // } // Path: src/main/java/com/team/kalstuff/config/Config.java import java.io.File; import java.util.List; import com.team.kalstuff.KalStuff; import net.minecraftforge.common.MinecraftForge; import net.minecraftforge.common.config.ConfigElement; import net.minecraftforge.common.config.Configuration; import net.minecraftforge.fml.client.config.IConfigElement; import net.minecraftforge.fml.client.event.ConfigChangedEvent; import net.minecraftforge.fml.common.event.FMLPreInitializationEvent; import net.minecraftforge.fml.common.eventhandler.SubscribeEvent; package com.team.kalstuff.config; public class Config { public static File configurationFile; public static Configuration config; public static final String CATEGORY_GENERAL = "General"; public static int cottageRarity = 512; public static boolean bridgeTNT = false; public static final void initialize(FMLPreInitializationEvent e, File file) {
config = new Configuration(file, KalStuff.VERSION, true);
TEAMModding/KalStuff
src/main/java/com/team/kalstuff/worldgen/WorldGenGrapeVine.java
// Path: src/main/java/com/team/kalstuff/block/KalStuffBlocks.java // @GameRegistry.ObjectHolder("kalstuff") // @Mod.EventBusSubscriber(modid = "kalstuff") // public class KalStuffBlocks // { // // ---Please keep all blocks in alphabetical order!--- // // public static final Block APPLE_BLOCK = Blocks.AIR; // public static final Block BAKED_POTATO_BLOCK = Blocks.AIR; // public static final Block BLAZE_BLOCK = Blocks.AIR; // public static final Block BRIDGE = Blocks.AIR; // public static final Block CARROT_BLOCK = Blocks.AIR; // public static final Block CHICKEN_NEST = Blocks.AIR; // public static final Block ENDER_BLOCK = Blocks.AIR; // public static final Block GRAPE_VINE = Blocks.AIR; // public static final Block GREAT_GRAPE = Blocks.AIR; // public static final Block MOON_FLOWER = Blocks.AIR; // public static final Block MOON_FLOWER1 = Blocks.AIR; // public static final Block MOON_FLOWER2 = Blocks.AIR; // public static final Block MOON_FLOWER3 = Blocks.AIR; // public static final Block MOON_FLOWER4 = Blocks.AIR; // public static final Block MOON_FLOWER5 = Blocks.AIR; // public static final Block POTATO_BLOCK = Blocks.AIR; // public static final Block TRASH_CAN = Blocks.AIR; // public static final Block WILD_GRAPE_VINE = Blocks.AIR; // // /** // * Registers all blocks from the mod. // */ // @SubscribeEvent // public static void registerBlocks(Register<Block> event) // { // IForgeRegistry<Block> reg = event.getRegistry(); // // remember to register ItemBlocks in KalStuffItems, and // // please continue to keep all blocks in alphabetical order // // reg.register(new BlockFood(1.5F, 9, 2.4F, "apple_block")); // reg.register(new BlockBakedPotato(1.5F, 11, 6F, "baked_potato_block")); // reg.register(new BlockKalStuff(Material.IRON, SoundType.METAL, "blaze_block").setHardness(35.0F)); // reg.register(new BlockBridge("bridge")); // reg.register(new BlockFood(11.5F, 7, 4.8F, "carrot_block")); // reg.register(new BlockChickenNest("chicken_nest")); // reg.register(new BlockKalStuff(Material.IRON, SoundType.METAL, "ender_block").setHardness(5.0F)); // reg.register(new BlockGrapeVine("grape_vine")); // reg.register(new BlockKalStuff(Material.SPONGE, SoundType.CLOTH, "great_grape")); // // only the first BlockMoonFlower should appear in the Creative inventory // reg.register(new BlockMoonFlower(0, "moon_flower").setCreativeTab(CommonProxy.KALSTUFFTAB)); // reg.register(new BlockMoonFlower(1, "moon_flower1")); // reg.register(new BlockMoonFlower(2, "moon_flower2")); // reg.register(new BlockMoonFlower(3, "moon_flower3")); // reg.register(new BlockMoonFlower(4, "moon_flower4")); // reg.register(new BlockMoonFlower(5, "moon_flower5")); // reg.register(new BlockFood(1.5F, 3, 0.6F, "potato_block")); // reg.register(new BlockTrashCan("trash_can")); // reg.register(new BlockWildGrapeVine("wild_grape_vine")); // } // }
import java.util.Random; import com.team.kalstuff.block.KalStuffBlocks; import net.minecraft.init.Blocks; import net.minecraft.util.ResourceLocation; import net.minecraft.util.math.BlockPos; import net.minecraft.world.World; import net.minecraft.world.biome.Biome; import net.minecraft.world.chunk.IChunkProvider; import net.minecraft.world.gen.IChunkGenerator; import net.minecraftforge.fml.common.IWorldGenerator;
package com.team.kalstuff.worldgen; public class WorldGenGrapeVine implements IWorldGenerator { public BlockPos getSurface(int x, int z, World world) { for (int y = 0; y < world.getHeight(); y++) { BlockPos aPos = new BlockPos(x, y, z); if (world.getBlockState(aPos) == Blocks.GRASS.getDefaultState() && world.isAirBlock(aPos.up())) return aPos; } return null; } @Override public void generate(Random random, int chunkX, int chunkZ, World world, IChunkGenerator chunkGenerator, IChunkProvider chunkProvider) { BlockPos aPos = this.getSurface(chunkX * 16 + random.nextInt(16), chunkZ * 16 + random.nextInt(16), world); if (random.nextInt(10) == 1) { if (aPos != null && world.getBiomeForCoordsBody(aPos) == Biome.REGISTRY .getObject(new ResourceLocation("roofed_forest"))) {
// Path: src/main/java/com/team/kalstuff/block/KalStuffBlocks.java // @GameRegistry.ObjectHolder("kalstuff") // @Mod.EventBusSubscriber(modid = "kalstuff") // public class KalStuffBlocks // { // // ---Please keep all blocks in alphabetical order!--- // // public static final Block APPLE_BLOCK = Blocks.AIR; // public static final Block BAKED_POTATO_BLOCK = Blocks.AIR; // public static final Block BLAZE_BLOCK = Blocks.AIR; // public static final Block BRIDGE = Blocks.AIR; // public static final Block CARROT_BLOCK = Blocks.AIR; // public static final Block CHICKEN_NEST = Blocks.AIR; // public static final Block ENDER_BLOCK = Blocks.AIR; // public static final Block GRAPE_VINE = Blocks.AIR; // public static final Block GREAT_GRAPE = Blocks.AIR; // public static final Block MOON_FLOWER = Blocks.AIR; // public static final Block MOON_FLOWER1 = Blocks.AIR; // public static final Block MOON_FLOWER2 = Blocks.AIR; // public static final Block MOON_FLOWER3 = Blocks.AIR; // public static final Block MOON_FLOWER4 = Blocks.AIR; // public static final Block MOON_FLOWER5 = Blocks.AIR; // public static final Block POTATO_BLOCK = Blocks.AIR; // public static final Block TRASH_CAN = Blocks.AIR; // public static final Block WILD_GRAPE_VINE = Blocks.AIR; // // /** // * Registers all blocks from the mod. // */ // @SubscribeEvent // public static void registerBlocks(Register<Block> event) // { // IForgeRegistry<Block> reg = event.getRegistry(); // // remember to register ItemBlocks in KalStuffItems, and // // please continue to keep all blocks in alphabetical order // // reg.register(new BlockFood(1.5F, 9, 2.4F, "apple_block")); // reg.register(new BlockBakedPotato(1.5F, 11, 6F, "baked_potato_block")); // reg.register(new BlockKalStuff(Material.IRON, SoundType.METAL, "blaze_block").setHardness(35.0F)); // reg.register(new BlockBridge("bridge")); // reg.register(new BlockFood(11.5F, 7, 4.8F, "carrot_block")); // reg.register(new BlockChickenNest("chicken_nest")); // reg.register(new BlockKalStuff(Material.IRON, SoundType.METAL, "ender_block").setHardness(5.0F)); // reg.register(new BlockGrapeVine("grape_vine")); // reg.register(new BlockKalStuff(Material.SPONGE, SoundType.CLOTH, "great_grape")); // // only the first BlockMoonFlower should appear in the Creative inventory // reg.register(new BlockMoonFlower(0, "moon_flower").setCreativeTab(CommonProxy.KALSTUFFTAB)); // reg.register(new BlockMoonFlower(1, "moon_flower1")); // reg.register(new BlockMoonFlower(2, "moon_flower2")); // reg.register(new BlockMoonFlower(3, "moon_flower3")); // reg.register(new BlockMoonFlower(4, "moon_flower4")); // reg.register(new BlockMoonFlower(5, "moon_flower5")); // reg.register(new BlockFood(1.5F, 3, 0.6F, "potato_block")); // reg.register(new BlockTrashCan("trash_can")); // reg.register(new BlockWildGrapeVine("wild_grape_vine")); // } // } // Path: src/main/java/com/team/kalstuff/worldgen/WorldGenGrapeVine.java import java.util.Random; import com.team.kalstuff.block.KalStuffBlocks; import net.minecraft.init.Blocks; import net.minecraft.util.ResourceLocation; import net.minecraft.util.math.BlockPos; import net.minecraft.world.World; import net.minecraft.world.biome.Biome; import net.minecraft.world.chunk.IChunkProvider; import net.minecraft.world.gen.IChunkGenerator; import net.minecraftforge.fml.common.IWorldGenerator; package com.team.kalstuff.worldgen; public class WorldGenGrapeVine implements IWorldGenerator { public BlockPos getSurface(int x, int z, World world) { for (int y = 0; y < world.getHeight(); y++) { BlockPos aPos = new BlockPos(x, y, z); if (world.getBlockState(aPos) == Blocks.GRASS.getDefaultState() && world.isAirBlock(aPos.up())) return aPos; } return null; } @Override public void generate(Random random, int chunkX, int chunkZ, World world, IChunkGenerator chunkGenerator, IChunkProvider chunkProvider) { BlockPos aPos = this.getSurface(chunkX * 16 + random.nextInt(16), chunkZ * 16 + random.nextInt(16), world); if (random.nextInt(10) == 1) { if (aPos != null && world.getBiomeForCoordsBody(aPos) == Biome.REGISTRY .getObject(new ResourceLocation("roofed_forest"))) {
world.setBlockState(aPos.up(), KalStuffBlocks.WILD_GRAPE_VINE.getDefaultState());
TEAMModding/KalStuff
src/main/java/com/team/kalstuff/config/KalStuffGuiFactory.java
// Path: src/main/java/com/team/kalstuff/KalStuff.java // @Mod(modid = KalStuff.MODID, // name = KalStuff.NAME, // version = KalStuff.VERSION, // acceptedMinecraftVersions = "[1.12.2]", // useMetadata = true, // guiFactory = "com.team.kalstuff.config.KalStuffGuiFactory") // public class KalStuff // { // public static final String MODID = "kalstuff"; // public static final String NAME = "KalStuff"; // public static final String VERSION = "1.0.0"; // // @SidedProxy(clientSide = "com.team.kalstuff.proxy.ClientProxy", // serverSide = "com.team.kalstuff.proxy.ServerProxy") // public static CommonProxy proxy; // // // The instance of the mod that Forge uses. // @Mod.Instance // public static KalStuff instance; // // public static Logger logger; // // public static Configuration config; // // @EventHandler // public void preInit(FMLPreInitializationEvent e) // { // logger = e.getModLog(); // Config.initialize(e, e.getSuggestedConfigurationFile()); // config = Config.getConfig(); // proxy.preInit(e); // } // // @EventHandler // public void init(FMLInitializationEvent e) // { // proxy.init(e); // } // // @EventHandler // public void postInit(FMLPostInitializationEvent e) // { // if (config.hasChanged()) // { // config.save(); // } // proxy.postInit(e); // } // }
import java.util.ArrayList; import java.util.List; import java.util.Set; import com.team.kalstuff.KalStuff; import net.minecraft.client.Minecraft; import net.minecraft.client.gui.GuiScreen; import net.minecraft.client.resources.I18n; import net.minecraftforge.fml.client.IModGuiFactory; import net.minecraftforge.fml.client.config.GuiConfig; import net.minecraftforge.fml.client.config.IConfigElement;
package com.team.kalstuff.config; public class KalStuffGuiFactory implements IModGuiFactory { @Override public void initialize(Minecraft minecraftInstance) {} @Override public boolean hasConfigGui() { return true; } @Override public GuiScreen createConfigGui(GuiScreen parentScreen) { return new ConfigGui(parentScreen); } @Override public Set<RuntimeOptionCategoryElement> runtimeGuiCategories() { return null; } public static class ConfigGui extends GuiConfig { public ConfigGui(GuiScreen parent) {
// Path: src/main/java/com/team/kalstuff/KalStuff.java // @Mod(modid = KalStuff.MODID, // name = KalStuff.NAME, // version = KalStuff.VERSION, // acceptedMinecraftVersions = "[1.12.2]", // useMetadata = true, // guiFactory = "com.team.kalstuff.config.KalStuffGuiFactory") // public class KalStuff // { // public static final String MODID = "kalstuff"; // public static final String NAME = "KalStuff"; // public static final String VERSION = "1.0.0"; // // @SidedProxy(clientSide = "com.team.kalstuff.proxy.ClientProxy", // serverSide = "com.team.kalstuff.proxy.ServerProxy") // public static CommonProxy proxy; // // // The instance of the mod that Forge uses. // @Mod.Instance // public static KalStuff instance; // // public static Logger logger; // // public static Configuration config; // // @EventHandler // public void preInit(FMLPreInitializationEvent e) // { // logger = e.getModLog(); // Config.initialize(e, e.getSuggestedConfigurationFile()); // config = Config.getConfig(); // proxy.preInit(e); // } // // @EventHandler // public void init(FMLInitializationEvent e) // { // proxy.init(e); // } // // @EventHandler // public void postInit(FMLPostInitializationEvent e) // { // if (config.hasChanged()) // { // config.save(); // } // proxy.postInit(e); // } // } // Path: src/main/java/com/team/kalstuff/config/KalStuffGuiFactory.java import java.util.ArrayList; import java.util.List; import java.util.Set; import com.team.kalstuff.KalStuff; import net.minecraft.client.Minecraft; import net.minecraft.client.gui.GuiScreen; import net.minecraft.client.resources.I18n; import net.minecraftforge.fml.client.IModGuiFactory; import net.minecraftforge.fml.client.config.GuiConfig; import net.minecraftforge.fml.client.config.IConfigElement; package com.team.kalstuff.config; public class KalStuffGuiFactory implements IModGuiFactory { @Override public void initialize(Minecraft minecraftInstance) {} @Override public boolean hasConfigGui() { return true; } @Override public GuiScreen createConfigGui(GuiScreen parentScreen) { return new ConfigGui(parentScreen); } @Override public Set<RuntimeOptionCategoryElement> runtimeGuiCategories() { return null; } public static class ConfigGui extends GuiConfig { public ConfigGui(GuiScreen parent) {
super(parent, getList(), KalStuff.MODID, false, false, getTitle());
TEAMModding/KalStuff
src/main/java/com/team/kalstuff/worldgen/WorldGenMoonFlower.java
// Path: src/main/java/com/team/kalstuff/block/KalStuffBlocks.java // @GameRegistry.ObjectHolder("kalstuff") // @Mod.EventBusSubscriber(modid = "kalstuff") // public class KalStuffBlocks // { // // ---Please keep all blocks in alphabetical order!--- // // public static final Block APPLE_BLOCK = Blocks.AIR; // public static final Block BAKED_POTATO_BLOCK = Blocks.AIR; // public static final Block BLAZE_BLOCK = Blocks.AIR; // public static final Block BRIDGE = Blocks.AIR; // public static final Block CARROT_BLOCK = Blocks.AIR; // public static final Block CHICKEN_NEST = Blocks.AIR; // public static final Block ENDER_BLOCK = Blocks.AIR; // public static final Block GRAPE_VINE = Blocks.AIR; // public static final Block GREAT_GRAPE = Blocks.AIR; // public static final Block MOON_FLOWER = Blocks.AIR; // public static final Block MOON_FLOWER1 = Blocks.AIR; // public static final Block MOON_FLOWER2 = Blocks.AIR; // public static final Block MOON_FLOWER3 = Blocks.AIR; // public static final Block MOON_FLOWER4 = Blocks.AIR; // public static final Block MOON_FLOWER5 = Blocks.AIR; // public static final Block POTATO_BLOCK = Blocks.AIR; // public static final Block TRASH_CAN = Blocks.AIR; // public static final Block WILD_GRAPE_VINE = Blocks.AIR; // // /** // * Registers all blocks from the mod. // */ // @SubscribeEvent // public static void registerBlocks(Register<Block> event) // { // IForgeRegistry<Block> reg = event.getRegistry(); // // remember to register ItemBlocks in KalStuffItems, and // // please continue to keep all blocks in alphabetical order // // reg.register(new BlockFood(1.5F, 9, 2.4F, "apple_block")); // reg.register(new BlockBakedPotato(1.5F, 11, 6F, "baked_potato_block")); // reg.register(new BlockKalStuff(Material.IRON, SoundType.METAL, "blaze_block").setHardness(35.0F)); // reg.register(new BlockBridge("bridge")); // reg.register(new BlockFood(11.5F, 7, 4.8F, "carrot_block")); // reg.register(new BlockChickenNest("chicken_nest")); // reg.register(new BlockKalStuff(Material.IRON, SoundType.METAL, "ender_block").setHardness(5.0F)); // reg.register(new BlockGrapeVine("grape_vine")); // reg.register(new BlockKalStuff(Material.SPONGE, SoundType.CLOTH, "great_grape")); // // only the first BlockMoonFlower should appear in the Creative inventory // reg.register(new BlockMoonFlower(0, "moon_flower").setCreativeTab(CommonProxy.KALSTUFFTAB)); // reg.register(new BlockMoonFlower(1, "moon_flower1")); // reg.register(new BlockMoonFlower(2, "moon_flower2")); // reg.register(new BlockMoonFlower(3, "moon_flower3")); // reg.register(new BlockMoonFlower(4, "moon_flower4")); // reg.register(new BlockMoonFlower(5, "moon_flower5")); // reg.register(new BlockFood(1.5F, 3, 0.6F, "potato_block")); // reg.register(new BlockTrashCan("trash_can")); // reg.register(new BlockWildGrapeVine("wild_grape_vine")); // } // }
import java.util.ArrayList; import java.util.Random; import com.team.kalstuff.block.KalStuffBlocks; import net.minecraft.init.Blocks; import net.minecraft.util.math.BlockPos; import net.minecraft.world.World; import net.minecraft.world.chunk.IChunkProvider; import net.minecraft.world.gen.IChunkGenerator; import net.minecraftforge.fml.common.IWorldGenerator;
package com.team.kalstuff.worldgen; public class WorldGenMoonFlower implements IWorldGenerator { @Override public void generate(Random random, int chunkX, int chunkZ, World world, IChunkGenerator chunkGenerator, IChunkProvider chunkProvider) { if (random.nextInt(200) == 1) { ArrayList<BlockPos> somePos = this.getValidLocationsInArea(random, chunkX * 16 + random.nextInt(16), chunkZ * 16 + random.nextInt(16), 8, world); if (somePos != null) { for (int i = 0; i < somePos.size(); i++) if (somePos.get(i) != null)
// Path: src/main/java/com/team/kalstuff/block/KalStuffBlocks.java // @GameRegistry.ObjectHolder("kalstuff") // @Mod.EventBusSubscriber(modid = "kalstuff") // public class KalStuffBlocks // { // // ---Please keep all blocks in alphabetical order!--- // // public static final Block APPLE_BLOCK = Blocks.AIR; // public static final Block BAKED_POTATO_BLOCK = Blocks.AIR; // public static final Block BLAZE_BLOCK = Blocks.AIR; // public static final Block BRIDGE = Blocks.AIR; // public static final Block CARROT_BLOCK = Blocks.AIR; // public static final Block CHICKEN_NEST = Blocks.AIR; // public static final Block ENDER_BLOCK = Blocks.AIR; // public static final Block GRAPE_VINE = Blocks.AIR; // public static final Block GREAT_GRAPE = Blocks.AIR; // public static final Block MOON_FLOWER = Blocks.AIR; // public static final Block MOON_FLOWER1 = Blocks.AIR; // public static final Block MOON_FLOWER2 = Blocks.AIR; // public static final Block MOON_FLOWER3 = Blocks.AIR; // public static final Block MOON_FLOWER4 = Blocks.AIR; // public static final Block MOON_FLOWER5 = Blocks.AIR; // public static final Block POTATO_BLOCK = Blocks.AIR; // public static final Block TRASH_CAN = Blocks.AIR; // public static final Block WILD_GRAPE_VINE = Blocks.AIR; // // /** // * Registers all blocks from the mod. // */ // @SubscribeEvent // public static void registerBlocks(Register<Block> event) // { // IForgeRegistry<Block> reg = event.getRegistry(); // // remember to register ItemBlocks in KalStuffItems, and // // please continue to keep all blocks in alphabetical order // // reg.register(new BlockFood(1.5F, 9, 2.4F, "apple_block")); // reg.register(new BlockBakedPotato(1.5F, 11, 6F, "baked_potato_block")); // reg.register(new BlockKalStuff(Material.IRON, SoundType.METAL, "blaze_block").setHardness(35.0F)); // reg.register(new BlockBridge("bridge")); // reg.register(new BlockFood(11.5F, 7, 4.8F, "carrot_block")); // reg.register(new BlockChickenNest("chicken_nest")); // reg.register(new BlockKalStuff(Material.IRON, SoundType.METAL, "ender_block").setHardness(5.0F)); // reg.register(new BlockGrapeVine("grape_vine")); // reg.register(new BlockKalStuff(Material.SPONGE, SoundType.CLOTH, "great_grape")); // // only the first BlockMoonFlower should appear in the Creative inventory // reg.register(new BlockMoonFlower(0, "moon_flower").setCreativeTab(CommonProxy.KALSTUFFTAB)); // reg.register(new BlockMoonFlower(1, "moon_flower1")); // reg.register(new BlockMoonFlower(2, "moon_flower2")); // reg.register(new BlockMoonFlower(3, "moon_flower3")); // reg.register(new BlockMoonFlower(4, "moon_flower4")); // reg.register(new BlockMoonFlower(5, "moon_flower5")); // reg.register(new BlockFood(1.5F, 3, 0.6F, "potato_block")); // reg.register(new BlockTrashCan("trash_can")); // reg.register(new BlockWildGrapeVine("wild_grape_vine")); // } // } // Path: src/main/java/com/team/kalstuff/worldgen/WorldGenMoonFlower.java import java.util.ArrayList; import java.util.Random; import com.team.kalstuff.block.KalStuffBlocks; import net.minecraft.init.Blocks; import net.minecraft.util.math.BlockPos; import net.minecraft.world.World; import net.minecraft.world.chunk.IChunkProvider; import net.minecraft.world.gen.IChunkGenerator; import net.minecraftforge.fml.common.IWorldGenerator; package com.team.kalstuff.worldgen; public class WorldGenMoonFlower implements IWorldGenerator { @Override public void generate(Random random, int chunkX, int chunkZ, World world, IChunkGenerator chunkGenerator, IChunkProvider chunkProvider) { if (random.nextInt(200) == 1) { ArrayList<BlockPos> somePos = this.getValidLocationsInArea(random, chunkX * 16 + random.nextInt(16), chunkZ * 16 + random.nextInt(16), 8, world); if (somePos != null) { for (int i = 0; i < somePos.size(); i++) if (somePos.get(i) != null)
world.setBlockState(somePos.get(i).up(), KalStuffBlocks.MOON_FLOWER.getDefaultState());
TEAMModding/KalStuff
src/main/java/com/team/kalstuff/block/KalStuffBlocks.java
// Path: src/main/java/com/team/kalstuff/proxy/CommonProxy.java // @Mod.EventBusSubscriber // public class CommonProxy // { // public static final CreativeTabs KALSTUFFTAB = new KalStuffCreativeTab("kalstuffTab"); // // public void preInit(FMLPreInitializationEvent e) // { // MinecraftForge.EVENT_BUS.register(new CoreEventHandler()); // KalStuffTileEntities.register(); // KalStuffWorldGenerator.register(); // KalStuffEntities.setup(); // NetworkRegistry.INSTANCE.registerGuiHandler(KalStuff.instance, new KalStuffGuiHandler()); // } // // public void init(FMLInitializationEvent e) // { // KalStuffRecipes.add(); // KalStuffItems.configureItems(); // KalStuff.logger // .info("Hi there, nerdy geeks. You should just enjoy Minecraft and stop looking at the system output."); // } // // public void postInit(FMLPostInitializationEvent e) // { // KalStuff.logger.info("Wait a minute... Guys! IT WORKS!?! WE MADE A MOD!!!"); // } // }
import com.team.kalstuff.proxy.CommonProxy; import net.minecraft.block.Block; import net.minecraft.block.SoundType; import net.minecraft.block.material.Material; import net.minecraft.init.Blocks; import net.minecraftforge.event.RegistryEvent.Register; import net.minecraftforge.fml.common.Mod; import net.minecraftforge.fml.common.eventhandler.SubscribeEvent; import net.minecraftforge.fml.common.registry.GameRegistry; import net.minecraftforge.registries.IForgeRegistry;
public static final Block MOON_FLOWER = Blocks.AIR; public static final Block MOON_FLOWER1 = Blocks.AIR; public static final Block MOON_FLOWER2 = Blocks.AIR; public static final Block MOON_FLOWER3 = Blocks.AIR; public static final Block MOON_FLOWER4 = Blocks.AIR; public static final Block MOON_FLOWER5 = Blocks.AIR; public static final Block POTATO_BLOCK = Blocks.AIR; public static final Block TRASH_CAN = Blocks.AIR; public static final Block WILD_GRAPE_VINE = Blocks.AIR; /** * Registers all blocks from the mod. */ @SubscribeEvent public static void registerBlocks(Register<Block> event) { IForgeRegistry<Block> reg = event.getRegistry(); // remember to register ItemBlocks in KalStuffItems, and // please continue to keep all blocks in alphabetical order reg.register(new BlockFood(1.5F, 9, 2.4F, "apple_block")); reg.register(new BlockBakedPotato(1.5F, 11, 6F, "baked_potato_block")); reg.register(new BlockKalStuff(Material.IRON, SoundType.METAL, "blaze_block").setHardness(35.0F)); reg.register(new BlockBridge("bridge")); reg.register(new BlockFood(11.5F, 7, 4.8F, "carrot_block")); reg.register(new BlockChickenNest("chicken_nest")); reg.register(new BlockKalStuff(Material.IRON, SoundType.METAL, "ender_block").setHardness(5.0F)); reg.register(new BlockGrapeVine("grape_vine")); reg.register(new BlockKalStuff(Material.SPONGE, SoundType.CLOTH, "great_grape")); // only the first BlockMoonFlower should appear in the Creative inventory
// Path: src/main/java/com/team/kalstuff/proxy/CommonProxy.java // @Mod.EventBusSubscriber // public class CommonProxy // { // public static final CreativeTabs KALSTUFFTAB = new KalStuffCreativeTab("kalstuffTab"); // // public void preInit(FMLPreInitializationEvent e) // { // MinecraftForge.EVENT_BUS.register(new CoreEventHandler()); // KalStuffTileEntities.register(); // KalStuffWorldGenerator.register(); // KalStuffEntities.setup(); // NetworkRegistry.INSTANCE.registerGuiHandler(KalStuff.instance, new KalStuffGuiHandler()); // } // // public void init(FMLInitializationEvent e) // { // KalStuffRecipes.add(); // KalStuffItems.configureItems(); // KalStuff.logger // .info("Hi there, nerdy geeks. You should just enjoy Minecraft and stop looking at the system output."); // } // // public void postInit(FMLPostInitializationEvent e) // { // KalStuff.logger.info("Wait a minute... Guys! IT WORKS!?! WE MADE A MOD!!!"); // } // } // Path: src/main/java/com/team/kalstuff/block/KalStuffBlocks.java import com.team.kalstuff.proxy.CommonProxy; import net.minecraft.block.Block; import net.minecraft.block.SoundType; import net.minecraft.block.material.Material; import net.minecraft.init.Blocks; import net.minecraftforge.event.RegistryEvent.Register; import net.minecraftforge.fml.common.Mod; import net.minecraftforge.fml.common.eventhandler.SubscribeEvent; import net.minecraftforge.fml.common.registry.GameRegistry; import net.minecraftforge.registries.IForgeRegistry; public static final Block MOON_FLOWER = Blocks.AIR; public static final Block MOON_FLOWER1 = Blocks.AIR; public static final Block MOON_FLOWER2 = Blocks.AIR; public static final Block MOON_FLOWER3 = Blocks.AIR; public static final Block MOON_FLOWER4 = Blocks.AIR; public static final Block MOON_FLOWER5 = Blocks.AIR; public static final Block POTATO_BLOCK = Blocks.AIR; public static final Block TRASH_CAN = Blocks.AIR; public static final Block WILD_GRAPE_VINE = Blocks.AIR; /** * Registers all blocks from the mod. */ @SubscribeEvent public static void registerBlocks(Register<Block> event) { IForgeRegistry<Block> reg = event.getRegistry(); // remember to register ItemBlocks in KalStuffItems, and // please continue to keep all blocks in alphabetical order reg.register(new BlockFood(1.5F, 9, 2.4F, "apple_block")); reg.register(new BlockBakedPotato(1.5F, 11, 6F, "baked_potato_block")); reg.register(new BlockKalStuff(Material.IRON, SoundType.METAL, "blaze_block").setHardness(35.0F)); reg.register(new BlockBridge("bridge")); reg.register(new BlockFood(11.5F, 7, 4.8F, "carrot_block")); reg.register(new BlockChickenNest("chicken_nest")); reg.register(new BlockKalStuff(Material.IRON, SoundType.METAL, "ender_block").setHardness(5.0F)); reg.register(new BlockGrapeVine("grape_vine")); reg.register(new BlockKalStuff(Material.SPONGE, SoundType.CLOTH, "great_grape")); // only the first BlockMoonFlower should appear in the Creative inventory
reg.register(new BlockMoonFlower(0, "moon_flower").setCreativeTab(CommonProxy.KALSTUFFTAB));
TEAMModding/KalStuff
src/main/java/com/team/kalstuff/KalStuff.java
// Path: src/main/java/com/team/kalstuff/config/Config.java // public class Config // { // public static File configurationFile; // public static Configuration config; // // public static final String CATEGORY_GENERAL = "General"; // // public static int cottageRarity = 512; // public static boolean bridgeTNT = false; // // public static final void initialize(FMLPreInitializationEvent e, File file) // { // config = new Configuration(file, KalStuff.VERSION, true); // MinecraftForge.EVENT_BUS.register(new EventHandler()); // config.load(); // config.setCategoryRequiresWorldRestart(CATEGORY_GENERAL, false); // config.setCategoryRequiresMcRestart(CATEGORY_GENERAL, false); // config.setCategoryComment(CATEGORY_GENERAL, "General configuration"); // refresh(); // config.save(); // } // // public static final Configuration getConfig() // { // return config; // } // // private static final void refresh() // { // cottageRarity = config.getInt("Cottage Rarity", CATEGORY_GENERAL, cottageRarity, 0, 16384, // "Rarity for cottage generation"); // bridgeTNT = config.getBoolean("Allow Bridge TNT", CATEGORY_GENERAL, bridgeTNT, // "Restricts bridge blocks from placing TNT"); // } // // public static void add(List<IConfigElement> list) // { // list.add(new ConfigElement(config.getCategory(CATEGORY_GENERAL))); // } // // public static class EventHandler // { // @SubscribeEvent // public void onConfigChanged(ConfigChangedEvent.OnConfigChangedEvent event) // { // if (event.getModID().equals(KalStuff.MODID)) // { // refresh(); // if (config.hasChanged()) // { // config.save(); // } // } // } // } // } // // Path: src/main/java/com/team/kalstuff/proxy/CommonProxy.java // @Mod.EventBusSubscriber // public class CommonProxy // { // public static final CreativeTabs KALSTUFFTAB = new KalStuffCreativeTab("kalstuffTab"); // // public void preInit(FMLPreInitializationEvent e) // { // MinecraftForge.EVENT_BUS.register(new CoreEventHandler()); // KalStuffTileEntities.register(); // KalStuffWorldGenerator.register(); // KalStuffEntities.setup(); // NetworkRegistry.INSTANCE.registerGuiHandler(KalStuff.instance, new KalStuffGuiHandler()); // } // // public void init(FMLInitializationEvent e) // { // KalStuffRecipes.add(); // KalStuffItems.configureItems(); // KalStuff.logger // .info("Hi there, nerdy geeks. You should just enjoy Minecraft and stop looking at the system output."); // } // // public void postInit(FMLPostInitializationEvent e) // { // KalStuff.logger.info("Wait a minute... Guys! IT WORKS!?! WE MADE A MOD!!!"); // } // }
import org.apache.logging.log4j.Logger; import com.team.kalstuff.config.Config; import com.team.kalstuff.proxy.CommonProxy; import net.minecraftforge.common.config.Configuration; import net.minecraftforge.fml.common.Mod; import net.minecraftforge.fml.common.Mod.EventHandler; import net.minecraftforge.fml.common.SidedProxy; import net.minecraftforge.fml.common.event.FMLInitializationEvent; import net.minecraftforge.fml.common.event.FMLPostInitializationEvent; import net.minecraftforge.fml.common.event.FMLPreInitializationEvent;
package com.team.kalstuff; @Mod(modid = KalStuff.MODID, name = KalStuff.NAME, version = KalStuff.VERSION, acceptedMinecraftVersions = "[1.12.2]", useMetadata = true, guiFactory = "com.team.kalstuff.config.KalStuffGuiFactory") public class KalStuff { public static final String MODID = "kalstuff"; public static final String NAME = "KalStuff"; public static final String VERSION = "1.0.0"; @SidedProxy(clientSide = "com.team.kalstuff.proxy.ClientProxy", serverSide = "com.team.kalstuff.proxy.ServerProxy")
// Path: src/main/java/com/team/kalstuff/config/Config.java // public class Config // { // public static File configurationFile; // public static Configuration config; // // public static final String CATEGORY_GENERAL = "General"; // // public static int cottageRarity = 512; // public static boolean bridgeTNT = false; // // public static final void initialize(FMLPreInitializationEvent e, File file) // { // config = new Configuration(file, KalStuff.VERSION, true); // MinecraftForge.EVENT_BUS.register(new EventHandler()); // config.load(); // config.setCategoryRequiresWorldRestart(CATEGORY_GENERAL, false); // config.setCategoryRequiresMcRestart(CATEGORY_GENERAL, false); // config.setCategoryComment(CATEGORY_GENERAL, "General configuration"); // refresh(); // config.save(); // } // // public static final Configuration getConfig() // { // return config; // } // // private static final void refresh() // { // cottageRarity = config.getInt("Cottage Rarity", CATEGORY_GENERAL, cottageRarity, 0, 16384, // "Rarity for cottage generation"); // bridgeTNT = config.getBoolean("Allow Bridge TNT", CATEGORY_GENERAL, bridgeTNT, // "Restricts bridge blocks from placing TNT"); // } // // public static void add(List<IConfigElement> list) // { // list.add(new ConfigElement(config.getCategory(CATEGORY_GENERAL))); // } // // public static class EventHandler // { // @SubscribeEvent // public void onConfigChanged(ConfigChangedEvent.OnConfigChangedEvent event) // { // if (event.getModID().equals(KalStuff.MODID)) // { // refresh(); // if (config.hasChanged()) // { // config.save(); // } // } // } // } // } // // Path: src/main/java/com/team/kalstuff/proxy/CommonProxy.java // @Mod.EventBusSubscriber // public class CommonProxy // { // public static final CreativeTabs KALSTUFFTAB = new KalStuffCreativeTab("kalstuffTab"); // // public void preInit(FMLPreInitializationEvent e) // { // MinecraftForge.EVENT_BUS.register(new CoreEventHandler()); // KalStuffTileEntities.register(); // KalStuffWorldGenerator.register(); // KalStuffEntities.setup(); // NetworkRegistry.INSTANCE.registerGuiHandler(KalStuff.instance, new KalStuffGuiHandler()); // } // // public void init(FMLInitializationEvent e) // { // KalStuffRecipes.add(); // KalStuffItems.configureItems(); // KalStuff.logger // .info("Hi there, nerdy geeks. You should just enjoy Minecraft and stop looking at the system output."); // } // // public void postInit(FMLPostInitializationEvent e) // { // KalStuff.logger.info("Wait a minute... Guys! IT WORKS!?! WE MADE A MOD!!!"); // } // } // Path: src/main/java/com/team/kalstuff/KalStuff.java import org.apache.logging.log4j.Logger; import com.team.kalstuff.config.Config; import com.team.kalstuff.proxy.CommonProxy; import net.minecraftforge.common.config.Configuration; import net.minecraftforge.fml.common.Mod; import net.minecraftforge.fml.common.Mod.EventHandler; import net.minecraftforge.fml.common.SidedProxy; import net.minecraftforge.fml.common.event.FMLInitializationEvent; import net.minecraftforge.fml.common.event.FMLPostInitializationEvent; import net.minecraftforge.fml.common.event.FMLPreInitializationEvent; package com.team.kalstuff; @Mod(modid = KalStuff.MODID, name = KalStuff.NAME, version = KalStuff.VERSION, acceptedMinecraftVersions = "[1.12.2]", useMetadata = true, guiFactory = "com.team.kalstuff.config.KalStuffGuiFactory") public class KalStuff { public static final String MODID = "kalstuff"; public static final String NAME = "KalStuff"; public static final String VERSION = "1.0.0"; @SidedProxy(clientSide = "com.team.kalstuff.proxy.ClientProxy", serverSide = "com.team.kalstuff.proxy.ServerProxy")
public static CommonProxy proxy;
TEAMModding/KalStuff
src/main/java/com/team/kalstuff/KalStuff.java
// Path: src/main/java/com/team/kalstuff/config/Config.java // public class Config // { // public static File configurationFile; // public static Configuration config; // // public static final String CATEGORY_GENERAL = "General"; // // public static int cottageRarity = 512; // public static boolean bridgeTNT = false; // // public static final void initialize(FMLPreInitializationEvent e, File file) // { // config = new Configuration(file, KalStuff.VERSION, true); // MinecraftForge.EVENT_BUS.register(new EventHandler()); // config.load(); // config.setCategoryRequiresWorldRestart(CATEGORY_GENERAL, false); // config.setCategoryRequiresMcRestart(CATEGORY_GENERAL, false); // config.setCategoryComment(CATEGORY_GENERAL, "General configuration"); // refresh(); // config.save(); // } // // public static final Configuration getConfig() // { // return config; // } // // private static final void refresh() // { // cottageRarity = config.getInt("Cottage Rarity", CATEGORY_GENERAL, cottageRarity, 0, 16384, // "Rarity for cottage generation"); // bridgeTNT = config.getBoolean("Allow Bridge TNT", CATEGORY_GENERAL, bridgeTNT, // "Restricts bridge blocks from placing TNT"); // } // // public static void add(List<IConfigElement> list) // { // list.add(new ConfigElement(config.getCategory(CATEGORY_GENERAL))); // } // // public static class EventHandler // { // @SubscribeEvent // public void onConfigChanged(ConfigChangedEvent.OnConfigChangedEvent event) // { // if (event.getModID().equals(KalStuff.MODID)) // { // refresh(); // if (config.hasChanged()) // { // config.save(); // } // } // } // } // } // // Path: src/main/java/com/team/kalstuff/proxy/CommonProxy.java // @Mod.EventBusSubscriber // public class CommonProxy // { // public static final CreativeTabs KALSTUFFTAB = new KalStuffCreativeTab("kalstuffTab"); // // public void preInit(FMLPreInitializationEvent e) // { // MinecraftForge.EVENT_BUS.register(new CoreEventHandler()); // KalStuffTileEntities.register(); // KalStuffWorldGenerator.register(); // KalStuffEntities.setup(); // NetworkRegistry.INSTANCE.registerGuiHandler(KalStuff.instance, new KalStuffGuiHandler()); // } // // public void init(FMLInitializationEvent e) // { // KalStuffRecipes.add(); // KalStuffItems.configureItems(); // KalStuff.logger // .info("Hi there, nerdy geeks. You should just enjoy Minecraft and stop looking at the system output."); // } // // public void postInit(FMLPostInitializationEvent e) // { // KalStuff.logger.info("Wait a minute... Guys! IT WORKS!?! WE MADE A MOD!!!"); // } // }
import org.apache.logging.log4j.Logger; import com.team.kalstuff.config.Config; import com.team.kalstuff.proxy.CommonProxy; import net.minecraftforge.common.config.Configuration; import net.minecraftforge.fml.common.Mod; import net.minecraftforge.fml.common.Mod.EventHandler; import net.minecraftforge.fml.common.SidedProxy; import net.minecraftforge.fml.common.event.FMLInitializationEvent; import net.minecraftforge.fml.common.event.FMLPostInitializationEvent; import net.minecraftforge.fml.common.event.FMLPreInitializationEvent;
package com.team.kalstuff; @Mod(modid = KalStuff.MODID, name = KalStuff.NAME, version = KalStuff.VERSION, acceptedMinecraftVersions = "[1.12.2]", useMetadata = true, guiFactory = "com.team.kalstuff.config.KalStuffGuiFactory") public class KalStuff { public static final String MODID = "kalstuff"; public static final String NAME = "KalStuff"; public static final String VERSION = "1.0.0"; @SidedProxy(clientSide = "com.team.kalstuff.proxy.ClientProxy", serverSide = "com.team.kalstuff.proxy.ServerProxy") public static CommonProxy proxy; // The instance of the mod that Forge uses. @Mod.Instance public static KalStuff instance; public static Logger logger; public static Configuration config; @EventHandler public void preInit(FMLPreInitializationEvent e) { logger = e.getModLog();
// Path: src/main/java/com/team/kalstuff/config/Config.java // public class Config // { // public static File configurationFile; // public static Configuration config; // // public static final String CATEGORY_GENERAL = "General"; // // public static int cottageRarity = 512; // public static boolean bridgeTNT = false; // // public static final void initialize(FMLPreInitializationEvent e, File file) // { // config = new Configuration(file, KalStuff.VERSION, true); // MinecraftForge.EVENT_BUS.register(new EventHandler()); // config.load(); // config.setCategoryRequiresWorldRestart(CATEGORY_GENERAL, false); // config.setCategoryRequiresMcRestart(CATEGORY_GENERAL, false); // config.setCategoryComment(CATEGORY_GENERAL, "General configuration"); // refresh(); // config.save(); // } // // public static final Configuration getConfig() // { // return config; // } // // private static final void refresh() // { // cottageRarity = config.getInt("Cottage Rarity", CATEGORY_GENERAL, cottageRarity, 0, 16384, // "Rarity for cottage generation"); // bridgeTNT = config.getBoolean("Allow Bridge TNT", CATEGORY_GENERAL, bridgeTNT, // "Restricts bridge blocks from placing TNT"); // } // // public static void add(List<IConfigElement> list) // { // list.add(new ConfigElement(config.getCategory(CATEGORY_GENERAL))); // } // // public static class EventHandler // { // @SubscribeEvent // public void onConfigChanged(ConfigChangedEvent.OnConfigChangedEvent event) // { // if (event.getModID().equals(KalStuff.MODID)) // { // refresh(); // if (config.hasChanged()) // { // config.save(); // } // } // } // } // } // // Path: src/main/java/com/team/kalstuff/proxy/CommonProxy.java // @Mod.EventBusSubscriber // public class CommonProxy // { // public static final CreativeTabs KALSTUFFTAB = new KalStuffCreativeTab("kalstuffTab"); // // public void preInit(FMLPreInitializationEvent e) // { // MinecraftForge.EVENT_BUS.register(new CoreEventHandler()); // KalStuffTileEntities.register(); // KalStuffWorldGenerator.register(); // KalStuffEntities.setup(); // NetworkRegistry.INSTANCE.registerGuiHandler(KalStuff.instance, new KalStuffGuiHandler()); // } // // public void init(FMLInitializationEvent e) // { // KalStuffRecipes.add(); // KalStuffItems.configureItems(); // KalStuff.logger // .info("Hi there, nerdy geeks. You should just enjoy Minecraft and stop looking at the system output."); // } // // public void postInit(FMLPostInitializationEvent e) // { // KalStuff.logger.info("Wait a minute... Guys! IT WORKS!?! WE MADE A MOD!!!"); // } // } // Path: src/main/java/com/team/kalstuff/KalStuff.java import org.apache.logging.log4j.Logger; import com.team.kalstuff.config.Config; import com.team.kalstuff.proxy.CommonProxy; import net.minecraftforge.common.config.Configuration; import net.minecraftforge.fml.common.Mod; import net.minecraftforge.fml.common.Mod.EventHandler; import net.minecraftforge.fml.common.SidedProxy; import net.minecraftforge.fml.common.event.FMLInitializationEvent; import net.minecraftforge.fml.common.event.FMLPostInitializationEvent; import net.minecraftforge.fml.common.event.FMLPreInitializationEvent; package com.team.kalstuff; @Mod(modid = KalStuff.MODID, name = KalStuff.NAME, version = KalStuff.VERSION, acceptedMinecraftVersions = "[1.12.2]", useMetadata = true, guiFactory = "com.team.kalstuff.config.KalStuffGuiFactory") public class KalStuff { public static final String MODID = "kalstuff"; public static final String NAME = "KalStuff"; public static final String VERSION = "1.0.0"; @SidedProxy(clientSide = "com.team.kalstuff.proxy.ClientProxy", serverSide = "com.team.kalstuff.proxy.ServerProxy") public static CommonProxy proxy; // The instance of the mod that Forge uses. @Mod.Instance public static KalStuff instance; public static Logger logger; public static Configuration config; @EventHandler public void preInit(FMLPreInitializationEvent e) { logger = e.getModLog();
Config.initialize(e, e.getSuggestedConfigurationFile());
TEAMModding/KalStuff
src/main/java/com/team/kalstuff/gui/GuiTrashCan.java
// Path: src/main/java/com/team/kalstuff/block/KalStuffBlocks.java // @GameRegistry.ObjectHolder("kalstuff") // @Mod.EventBusSubscriber(modid = "kalstuff") // public class KalStuffBlocks // { // // ---Please keep all blocks in alphabetical order!--- // // public static final Block APPLE_BLOCK = Blocks.AIR; // public static final Block BAKED_POTATO_BLOCK = Blocks.AIR; // public static final Block BLAZE_BLOCK = Blocks.AIR; // public static final Block BRIDGE = Blocks.AIR; // public static final Block CARROT_BLOCK = Blocks.AIR; // public static final Block CHICKEN_NEST = Blocks.AIR; // public static final Block ENDER_BLOCK = Blocks.AIR; // public static final Block GRAPE_VINE = Blocks.AIR; // public static final Block GREAT_GRAPE = Blocks.AIR; // public static final Block MOON_FLOWER = Blocks.AIR; // public static final Block MOON_FLOWER1 = Blocks.AIR; // public static final Block MOON_FLOWER2 = Blocks.AIR; // public static final Block MOON_FLOWER3 = Blocks.AIR; // public static final Block MOON_FLOWER4 = Blocks.AIR; // public static final Block MOON_FLOWER5 = Blocks.AIR; // public static final Block POTATO_BLOCK = Blocks.AIR; // public static final Block TRASH_CAN = Blocks.AIR; // public static final Block WILD_GRAPE_VINE = Blocks.AIR; // // /** // * Registers all blocks from the mod. // */ // @SubscribeEvent // public static void registerBlocks(Register<Block> event) // { // IForgeRegistry<Block> reg = event.getRegistry(); // // remember to register ItemBlocks in KalStuffItems, and // // please continue to keep all blocks in alphabetical order // // reg.register(new BlockFood(1.5F, 9, 2.4F, "apple_block")); // reg.register(new BlockBakedPotato(1.5F, 11, 6F, "baked_potato_block")); // reg.register(new BlockKalStuff(Material.IRON, SoundType.METAL, "blaze_block").setHardness(35.0F)); // reg.register(new BlockBridge("bridge")); // reg.register(new BlockFood(11.5F, 7, 4.8F, "carrot_block")); // reg.register(new BlockChickenNest("chicken_nest")); // reg.register(new BlockKalStuff(Material.IRON, SoundType.METAL, "ender_block").setHardness(5.0F)); // reg.register(new BlockGrapeVine("grape_vine")); // reg.register(new BlockKalStuff(Material.SPONGE, SoundType.CLOTH, "great_grape")); // // only the first BlockMoonFlower should appear in the Creative inventory // reg.register(new BlockMoonFlower(0, "moon_flower").setCreativeTab(CommonProxy.KALSTUFFTAB)); // reg.register(new BlockMoonFlower(1, "moon_flower1")); // reg.register(new BlockMoonFlower(2, "moon_flower2")); // reg.register(new BlockMoonFlower(3, "moon_flower3")); // reg.register(new BlockMoonFlower(4, "moon_flower4")); // reg.register(new BlockMoonFlower(5, "moon_flower5")); // reg.register(new BlockFood(1.5F, 3, 0.6F, "potato_block")); // reg.register(new BlockTrashCan("trash_can")); // reg.register(new BlockWildGrapeVine("wild_grape_vine")); // } // } // // Path: src/main/java/com/team/kalstuff/container/ContainerTrashCan.java // public class ContainerTrashCan extends Container // { // public ContainerTrashCan(InventoryPlayer player) // { // // this.addSlotToContainer(new Slot(tileEntity, 0, 80, 40)); // addPlayerSlots(player); // } // // public void addPlayerSlots(InventoryPlayer player) // { // for (int i = 0; i < 3; ++i) // { // for (int j = 0; j < 9; ++j) // { // this.addSlotToContainer(new Slot(player, j + i * 9 + 9, 8 + j * 18, 51 + i * 18)); // } // } // // for (int i = 0; i < 9; ++i) // this.addSlotToContainer(new Slot(player, i, 8 + i * 18, 109)); // // IInventory tableInventory = new InventoryBasic("Trash", false, 1) // { // public void setInventorySlotContents(int index, ItemStack stack) // { // // } // }; // this.addSlotToContainer(new Slot(tableInventory, 0, 80, 20)); // } // // public ItemStack transferStackInSlot(EntityPlayer player, int sourceSlotIndex) // { // Slot sourceSlot = (Slot) inventorySlots.get(sourceSlotIndex); // // an item stack cannot be null. `ItemStack.EMPTY` is a special "allowed" null // // stack // sourceSlot.putStack(ItemStack.EMPTY); // return ItemStack.EMPTY; // } // // @Override // public boolean canInteractWith(EntityPlayer playerIn) // { // return true; // } // }
import com.team.kalstuff.block.KalStuffBlocks; import com.team.kalstuff.container.ContainerTrashCan; import net.minecraft.client.Minecraft; import net.minecraft.client.gui.inventory.GuiContainer; import net.minecraft.client.renderer.GlStateManager; import net.minecraft.client.resources.I18n; import net.minecraft.entity.player.InventoryPlayer; import net.minecraft.util.ResourceLocation;
package com.team.kalstuff.gui; public class GuiTrashCan extends GuiContainer { private static final ResourceLocation texture = new ResourceLocation("kalstuff", "textures/gui/trash_can.png"); private InventoryPlayer playerInv; public GuiTrashCan(InventoryPlayer playerInv) {
// Path: src/main/java/com/team/kalstuff/block/KalStuffBlocks.java // @GameRegistry.ObjectHolder("kalstuff") // @Mod.EventBusSubscriber(modid = "kalstuff") // public class KalStuffBlocks // { // // ---Please keep all blocks in alphabetical order!--- // // public static final Block APPLE_BLOCK = Blocks.AIR; // public static final Block BAKED_POTATO_BLOCK = Blocks.AIR; // public static final Block BLAZE_BLOCK = Blocks.AIR; // public static final Block BRIDGE = Blocks.AIR; // public static final Block CARROT_BLOCK = Blocks.AIR; // public static final Block CHICKEN_NEST = Blocks.AIR; // public static final Block ENDER_BLOCK = Blocks.AIR; // public static final Block GRAPE_VINE = Blocks.AIR; // public static final Block GREAT_GRAPE = Blocks.AIR; // public static final Block MOON_FLOWER = Blocks.AIR; // public static final Block MOON_FLOWER1 = Blocks.AIR; // public static final Block MOON_FLOWER2 = Blocks.AIR; // public static final Block MOON_FLOWER3 = Blocks.AIR; // public static final Block MOON_FLOWER4 = Blocks.AIR; // public static final Block MOON_FLOWER5 = Blocks.AIR; // public static final Block POTATO_BLOCK = Blocks.AIR; // public static final Block TRASH_CAN = Blocks.AIR; // public static final Block WILD_GRAPE_VINE = Blocks.AIR; // // /** // * Registers all blocks from the mod. // */ // @SubscribeEvent // public static void registerBlocks(Register<Block> event) // { // IForgeRegistry<Block> reg = event.getRegistry(); // // remember to register ItemBlocks in KalStuffItems, and // // please continue to keep all blocks in alphabetical order // // reg.register(new BlockFood(1.5F, 9, 2.4F, "apple_block")); // reg.register(new BlockBakedPotato(1.5F, 11, 6F, "baked_potato_block")); // reg.register(new BlockKalStuff(Material.IRON, SoundType.METAL, "blaze_block").setHardness(35.0F)); // reg.register(new BlockBridge("bridge")); // reg.register(new BlockFood(11.5F, 7, 4.8F, "carrot_block")); // reg.register(new BlockChickenNest("chicken_nest")); // reg.register(new BlockKalStuff(Material.IRON, SoundType.METAL, "ender_block").setHardness(5.0F)); // reg.register(new BlockGrapeVine("grape_vine")); // reg.register(new BlockKalStuff(Material.SPONGE, SoundType.CLOTH, "great_grape")); // // only the first BlockMoonFlower should appear in the Creative inventory // reg.register(new BlockMoonFlower(0, "moon_flower").setCreativeTab(CommonProxy.KALSTUFFTAB)); // reg.register(new BlockMoonFlower(1, "moon_flower1")); // reg.register(new BlockMoonFlower(2, "moon_flower2")); // reg.register(new BlockMoonFlower(3, "moon_flower3")); // reg.register(new BlockMoonFlower(4, "moon_flower4")); // reg.register(new BlockMoonFlower(5, "moon_flower5")); // reg.register(new BlockFood(1.5F, 3, 0.6F, "potato_block")); // reg.register(new BlockTrashCan("trash_can")); // reg.register(new BlockWildGrapeVine("wild_grape_vine")); // } // } // // Path: src/main/java/com/team/kalstuff/container/ContainerTrashCan.java // public class ContainerTrashCan extends Container // { // public ContainerTrashCan(InventoryPlayer player) // { // // this.addSlotToContainer(new Slot(tileEntity, 0, 80, 40)); // addPlayerSlots(player); // } // // public void addPlayerSlots(InventoryPlayer player) // { // for (int i = 0; i < 3; ++i) // { // for (int j = 0; j < 9; ++j) // { // this.addSlotToContainer(new Slot(player, j + i * 9 + 9, 8 + j * 18, 51 + i * 18)); // } // } // // for (int i = 0; i < 9; ++i) // this.addSlotToContainer(new Slot(player, i, 8 + i * 18, 109)); // // IInventory tableInventory = new InventoryBasic("Trash", false, 1) // { // public void setInventorySlotContents(int index, ItemStack stack) // { // // } // }; // this.addSlotToContainer(new Slot(tableInventory, 0, 80, 20)); // } // // public ItemStack transferStackInSlot(EntityPlayer player, int sourceSlotIndex) // { // Slot sourceSlot = (Slot) inventorySlots.get(sourceSlotIndex); // // an item stack cannot be null. `ItemStack.EMPTY` is a special "allowed" null // // stack // sourceSlot.putStack(ItemStack.EMPTY); // return ItemStack.EMPTY; // } // // @Override // public boolean canInteractWith(EntityPlayer playerIn) // { // return true; // } // } // Path: src/main/java/com/team/kalstuff/gui/GuiTrashCan.java import com.team.kalstuff.block.KalStuffBlocks; import com.team.kalstuff.container.ContainerTrashCan; import net.minecraft.client.Minecraft; import net.minecraft.client.gui.inventory.GuiContainer; import net.minecraft.client.renderer.GlStateManager; import net.minecraft.client.resources.I18n; import net.minecraft.entity.player.InventoryPlayer; import net.minecraft.util.ResourceLocation; package com.team.kalstuff.gui; public class GuiTrashCan extends GuiContainer { private static final ResourceLocation texture = new ResourceLocation("kalstuff", "textures/gui/trash_can.png"); private InventoryPlayer playerInv; public GuiTrashCan(InventoryPlayer playerInv) {
super(new ContainerTrashCan(playerInv));
TEAMModding/KalStuff
src/main/java/com/team/kalstuff/block/BlockMoonFlower.java
// Path: src/main/java/com/team/kalstuff/tileentity/TileEntityMoonFlower.java // public class TileEntityMoonFlower extends TileEntity implements ITickable // { // @Override // public void update() // { // if (this.world != null && !this.world.isRemote && world.getWorldTime() >= 12800 || world.getWorldTime() < 23000) // { // this.blockType = this.getBlockType(); // // if (this.blockType instanceof BlockMoonFlower) // ((BlockMoonFlower) this.blockType).checkSky(this.world, this.pos); // } // } // }
import java.util.Random; import com.team.kalstuff.tileentity.TileEntityMoonFlower; import net.minecraft.block.BlockBush; import net.minecraft.block.ITileEntityProvider; import net.minecraft.block.SoundType; import net.minecraft.block.properties.IProperty; import net.minecraft.block.properties.PropertyInteger; import net.minecraft.block.state.BlockStateContainer; import net.minecraft.block.state.IBlockState; import net.minecraft.item.Item; import net.minecraft.tileentity.TileEntity; import net.minecraft.util.math.BlockPos; import net.minecraft.world.World; import net.minecraftforge.fml.relauncher.Side; import net.minecraftforge.fml.relauncher.SideOnly;
package com.team.kalstuff.block; public class BlockMoonFlower extends BlockBush implements ITileEntityProvider { public static final PropertyInteger NIGHT = PropertyInteger.create("night", 0, 1); public BlockMoonFlower(float light, String name) { BlockKalStuff.setupBlock(this, name); this.setDefaultState(this.blockState.getBaseState().withProperty(NIGHT, Integer.valueOf(0))); this.setLightLevel((light) / 16.0f); this.setSoundType(SoundType.PLANT); // we must set the creative tab to null here so all varieties will not show up // in the inventory this.setCreativeTab(null); } public void breakBlock(World worldIn, BlockPos pos, IBlockState state) { super.breakBlock(worldIn, pos, state); worldIn.removeTileEntity(pos); } public TileEntity createNewTileEntity(World worldIn, int meta) {
// Path: src/main/java/com/team/kalstuff/tileentity/TileEntityMoonFlower.java // public class TileEntityMoonFlower extends TileEntity implements ITickable // { // @Override // public void update() // { // if (this.world != null && !this.world.isRemote && world.getWorldTime() >= 12800 || world.getWorldTime() < 23000) // { // this.blockType = this.getBlockType(); // // if (this.blockType instanceof BlockMoonFlower) // ((BlockMoonFlower) this.blockType).checkSky(this.world, this.pos); // } // } // } // Path: src/main/java/com/team/kalstuff/block/BlockMoonFlower.java import java.util.Random; import com.team.kalstuff.tileentity.TileEntityMoonFlower; import net.minecraft.block.BlockBush; import net.minecraft.block.ITileEntityProvider; import net.minecraft.block.SoundType; import net.minecraft.block.properties.IProperty; import net.minecraft.block.properties.PropertyInteger; import net.minecraft.block.state.BlockStateContainer; import net.minecraft.block.state.IBlockState; import net.minecraft.item.Item; import net.minecraft.tileentity.TileEntity; import net.minecraft.util.math.BlockPos; import net.minecraft.world.World; import net.minecraftforge.fml.relauncher.Side; import net.minecraftforge.fml.relauncher.SideOnly; package com.team.kalstuff.block; public class BlockMoonFlower extends BlockBush implements ITileEntityProvider { public static final PropertyInteger NIGHT = PropertyInteger.create("night", 0, 1); public BlockMoonFlower(float light, String name) { BlockKalStuff.setupBlock(this, name); this.setDefaultState(this.blockState.getBaseState().withProperty(NIGHT, Integer.valueOf(0))); this.setLightLevel((light) / 16.0f); this.setSoundType(SoundType.PLANT); // we must set the creative tab to null here so all varieties will not show up // in the inventory this.setCreativeTab(null); } public void breakBlock(World worldIn, BlockPos pos, IBlockState state) { super.breakBlock(worldIn, pos, state); worldIn.removeTileEntity(pos); } public TileEntity createNewTileEntity(World worldIn, int meta) {
return new TileEntityMoonFlower();
TEAMModding/KalStuff
src/main/java/com/team/kalstuff/KalStuffRecipes.java
// Path: src/main/java/com/team/kalstuff/block/KalStuffBlocks.java // @GameRegistry.ObjectHolder("kalstuff") // @Mod.EventBusSubscriber(modid = "kalstuff") // public class KalStuffBlocks // { // // ---Please keep all blocks in alphabetical order!--- // // public static final Block APPLE_BLOCK = Blocks.AIR; // public static final Block BAKED_POTATO_BLOCK = Blocks.AIR; // public static final Block BLAZE_BLOCK = Blocks.AIR; // public static final Block BRIDGE = Blocks.AIR; // public static final Block CARROT_BLOCK = Blocks.AIR; // public static final Block CHICKEN_NEST = Blocks.AIR; // public static final Block ENDER_BLOCK = Blocks.AIR; // public static final Block GRAPE_VINE = Blocks.AIR; // public static final Block GREAT_GRAPE = Blocks.AIR; // public static final Block MOON_FLOWER = Blocks.AIR; // public static final Block MOON_FLOWER1 = Blocks.AIR; // public static final Block MOON_FLOWER2 = Blocks.AIR; // public static final Block MOON_FLOWER3 = Blocks.AIR; // public static final Block MOON_FLOWER4 = Blocks.AIR; // public static final Block MOON_FLOWER5 = Blocks.AIR; // public static final Block POTATO_BLOCK = Blocks.AIR; // public static final Block TRASH_CAN = Blocks.AIR; // public static final Block WILD_GRAPE_VINE = Blocks.AIR; // // /** // * Registers all blocks from the mod. // */ // @SubscribeEvent // public static void registerBlocks(Register<Block> event) // { // IForgeRegistry<Block> reg = event.getRegistry(); // // remember to register ItemBlocks in KalStuffItems, and // // please continue to keep all blocks in alphabetical order // // reg.register(new BlockFood(1.5F, 9, 2.4F, "apple_block")); // reg.register(new BlockBakedPotato(1.5F, 11, 6F, "baked_potato_block")); // reg.register(new BlockKalStuff(Material.IRON, SoundType.METAL, "blaze_block").setHardness(35.0F)); // reg.register(new BlockBridge("bridge")); // reg.register(new BlockFood(11.5F, 7, 4.8F, "carrot_block")); // reg.register(new BlockChickenNest("chicken_nest")); // reg.register(new BlockKalStuff(Material.IRON, SoundType.METAL, "ender_block").setHardness(5.0F)); // reg.register(new BlockGrapeVine("grape_vine")); // reg.register(new BlockKalStuff(Material.SPONGE, SoundType.CLOTH, "great_grape")); // // only the first BlockMoonFlower should appear in the Creative inventory // reg.register(new BlockMoonFlower(0, "moon_flower").setCreativeTab(CommonProxy.KALSTUFFTAB)); // reg.register(new BlockMoonFlower(1, "moon_flower1")); // reg.register(new BlockMoonFlower(2, "moon_flower2")); // reg.register(new BlockMoonFlower(3, "moon_flower3")); // reg.register(new BlockMoonFlower(4, "moon_flower4")); // reg.register(new BlockMoonFlower(5, "moon_flower5")); // reg.register(new BlockFood(1.5F, 3, 0.6F, "potato_block")); // reg.register(new BlockTrashCan("trash_can")); // reg.register(new BlockWildGrapeVine("wild_grape_vine")); // } // }
import com.team.kalstuff.block.KalStuffBlocks; import net.minecraft.item.ItemStack; import net.minecraftforge.fml.common.registry.GameRegistry;
package com.team.kalstuff; public class KalStuffRecipes { public static void add() { // a super big thank you to williewillus for writing a script // to convert recipes to JSON! // Link: https://gist.github.com/williewillus/a1a899ce5b0f0ba099078d46ae3dae6e addSmeltingRecipes(); } public static void addSmeltingRecipes() {
// Path: src/main/java/com/team/kalstuff/block/KalStuffBlocks.java // @GameRegistry.ObjectHolder("kalstuff") // @Mod.EventBusSubscriber(modid = "kalstuff") // public class KalStuffBlocks // { // // ---Please keep all blocks in alphabetical order!--- // // public static final Block APPLE_BLOCK = Blocks.AIR; // public static final Block BAKED_POTATO_BLOCK = Blocks.AIR; // public static final Block BLAZE_BLOCK = Blocks.AIR; // public static final Block BRIDGE = Blocks.AIR; // public static final Block CARROT_BLOCK = Blocks.AIR; // public static final Block CHICKEN_NEST = Blocks.AIR; // public static final Block ENDER_BLOCK = Blocks.AIR; // public static final Block GRAPE_VINE = Blocks.AIR; // public static final Block GREAT_GRAPE = Blocks.AIR; // public static final Block MOON_FLOWER = Blocks.AIR; // public static final Block MOON_FLOWER1 = Blocks.AIR; // public static final Block MOON_FLOWER2 = Blocks.AIR; // public static final Block MOON_FLOWER3 = Blocks.AIR; // public static final Block MOON_FLOWER4 = Blocks.AIR; // public static final Block MOON_FLOWER5 = Blocks.AIR; // public static final Block POTATO_BLOCK = Blocks.AIR; // public static final Block TRASH_CAN = Blocks.AIR; // public static final Block WILD_GRAPE_VINE = Blocks.AIR; // // /** // * Registers all blocks from the mod. // */ // @SubscribeEvent // public static void registerBlocks(Register<Block> event) // { // IForgeRegistry<Block> reg = event.getRegistry(); // // remember to register ItemBlocks in KalStuffItems, and // // please continue to keep all blocks in alphabetical order // // reg.register(new BlockFood(1.5F, 9, 2.4F, "apple_block")); // reg.register(new BlockBakedPotato(1.5F, 11, 6F, "baked_potato_block")); // reg.register(new BlockKalStuff(Material.IRON, SoundType.METAL, "blaze_block").setHardness(35.0F)); // reg.register(new BlockBridge("bridge")); // reg.register(new BlockFood(11.5F, 7, 4.8F, "carrot_block")); // reg.register(new BlockChickenNest("chicken_nest")); // reg.register(new BlockKalStuff(Material.IRON, SoundType.METAL, "ender_block").setHardness(5.0F)); // reg.register(new BlockGrapeVine("grape_vine")); // reg.register(new BlockKalStuff(Material.SPONGE, SoundType.CLOTH, "great_grape")); // // only the first BlockMoonFlower should appear in the Creative inventory // reg.register(new BlockMoonFlower(0, "moon_flower").setCreativeTab(CommonProxy.KALSTUFFTAB)); // reg.register(new BlockMoonFlower(1, "moon_flower1")); // reg.register(new BlockMoonFlower(2, "moon_flower2")); // reg.register(new BlockMoonFlower(3, "moon_flower3")); // reg.register(new BlockMoonFlower(4, "moon_flower4")); // reg.register(new BlockMoonFlower(5, "moon_flower5")); // reg.register(new BlockFood(1.5F, 3, 0.6F, "potato_block")); // reg.register(new BlockTrashCan("trash_can")); // reg.register(new BlockWildGrapeVine("wild_grape_vine")); // } // } // Path: src/main/java/com/team/kalstuff/KalStuffRecipes.java import com.team.kalstuff.block.KalStuffBlocks; import net.minecraft.item.ItemStack; import net.minecraftforge.fml.common.registry.GameRegistry; package com.team.kalstuff; public class KalStuffRecipes { public static void add() { // a super big thank you to williewillus for writing a script // to convert recipes to JSON! // Link: https://gist.github.com/williewillus/a1a899ce5b0f0ba099078d46ae3dae6e addSmeltingRecipes(); } public static void addSmeltingRecipes() {
GameRegistry.addSmelting(KalStuffBlocks.POTATO_BLOCK, new ItemStack(KalStuffBlocks.BAKED_POTATO_BLOCK), 2);
TEAMModding/KalStuff
src/main/java/com/team/kalstuff/item/ItemLute.java
// Path: src/main/java/com/team/kalstuff/proxy/CommonProxy.java // @Mod.EventBusSubscriber // public class CommonProxy // { // public static final CreativeTabs KALSTUFFTAB = new KalStuffCreativeTab("kalstuffTab"); // // public void preInit(FMLPreInitializationEvent e) // { // MinecraftForge.EVENT_BUS.register(new CoreEventHandler()); // KalStuffTileEntities.register(); // KalStuffWorldGenerator.register(); // KalStuffEntities.setup(); // NetworkRegistry.INSTANCE.registerGuiHandler(KalStuff.instance, new KalStuffGuiHandler()); // } // // public void init(FMLInitializationEvent e) // { // KalStuffRecipes.add(); // KalStuffItems.configureItems(); // KalStuff.logger // .info("Hi there, nerdy geeks. You should just enjoy Minecraft and stop looking at the system output."); // } // // public void postInit(FMLPostInitializationEvent e) // { // KalStuff.logger.info("Wait a minute... Guys! IT WORKS!?! WE MADE A MOD!!!"); // } // }
import com.team.kalstuff.proxy.CommonProxy; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.init.SoundEvents; import net.minecraft.item.ItemStack; import net.minecraft.util.ActionResult; import net.minecraft.util.EnumActionResult; import net.minecraft.util.EnumHand; import net.minecraft.util.EnumParticleTypes; import net.minecraft.util.SoundCategory; import net.minecraft.world.World;
package com.team.kalstuff.item; public class ItemLute extends ItemKalStuff { public ItemLute(String name) { super(name);
// Path: src/main/java/com/team/kalstuff/proxy/CommonProxy.java // @Mod.EventBusSubscriber // public class CommonProxy // { // public static final CreativeTabs KALSTUFFTAB = new KalStuffCreativeTab("kalstuffTab"); // // public void preInit(FMLPreInitializationEvent e) // { // MinecraftForge.EVENT_BUS.register(new CoreEventHandler()); // KalStuffTileEntities.register(); // KalStuffWorldGenerator.register(); // KalStuffEntities.setup(); // NetworkRegistry.INSTANCE.registerGuiHandler(KalStuff.instance, new KalStuffGuiHandler()); // } // // public void init(FMLInitializationEvent e) // { // KalStuffRecipes.add(); // KalStuffItems.configureItems(); // KalStuff.logger // .info("Hi there, nerdy geeks. You should just enjoy Minecraft and stop looking at the system output."); // } // // public void postInit(FMLPostInitializationEvent e) // { // KalStuff.logger.info("Wait a minute... Guys! IT WORKS!?! WE MADE A MOD!!!"); // } // } // Path: src/main/java/com/team/kalstuff/item/ItemLute.java import com.team.kalstuff.proxy.CommonProxy; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.init.SoundEvents; import net.minecraft.item.ItemStack; import net.minecraft.util.ActionResult; import net.minecraft.util.EnumActionResult; import net.minecraft.util.EnumHand; import net.minecraft.util.EnumParticleTypes; import net.minecraft.util.SoundCategory; import net.minecraft.world.World; package com.team.kalstuff.item; public class ItemLute extends ItemKalStuff { public ItemLute(String name) { super(name);
this.setCreativeTab(CommonProxy.KALSTUFFTAB);
TEAMModding/KalStuff
src/main/java/com/team/kalstuff/tileentity/TileEntityMoonFlower.java
// Path: src/main/java/com/team/kalstuff/block/BlockMoonFlower.java // public class BlockMoonFlower extends BlockBush implements ITileEntityProvider // { // public static final PropertyInteger NIGHT = PropertyInteger.create("night", 0, 1); // // public BlockMoonFlower(float light, String name) // { // BlockKalStuff.setupBlock(this, name); // this.setDefaultState(this.blockState.getBaseState().withProperty(NIGHT, Integer.valueOf(0))); // this.setLightLevel((light) / 16.0f); // this.setSoundType(SoundType.PLANT); // // we must set the creative tab to null here so all varieties will not show up // // in the inventory // this.setCreativeTab(null); // } // // public void breakBlock(World worldIn, BlockPos pos, IBlockState state) // { // super.breakBlock(worldIn, pos, state); // worldIn.removeTileEntity(pos); // } // // public TileEntity createNewTileEntity(World worldIn, int meta) // { // return new TileEntityMoonFlower(); // } // // @Override // public void updateTick(World worldIn, BlockPos pos, IBlockState state, Random rand) // { // super.updateTick(worldIn, pos, state, rand); // if ((worldIn.getWorldTime() >= 12800 && worldIn.getWorldTime() < 23000) // && ((Integer) state.getValue(NIGHT)).intValue() != 1) // { // worldIn.setBlockState(pos, state.withProperty(NIGHT, Integer.valueOf(1))); // } else if ((worldIn.getWorldTime() >= 23000 || worldIn.getWorldTime() < 12800) // && ((Integer) state.getValue(NIGHT)).intValue() != 0) // { // worldIn.setBlockState(pos, state.withProperty(NIGHT, Integer.valueOf(0))); // } // } // // public void checkSky(World worldIn, BlockPos pos) // { // IBlockState iblockstate = worldIn.getBlockState(pos); // if (worldIn.getBlockState(pos).getBlock().getClass() == BlockMoonFlower.class) // { // if (worldIn.canSeeSky(pos) && ((Integer) worldIn.getBlockState(pos).getValue(NIGHT)).intValue() == 1) // { // if (worldIn.getCurrentMoonPhaseFactor() == 0) // worldIn.setBlockState(pos, KalStuffBlocks.MOON_FLOWER1.getDefaultState().withProperty(NIGHT, // iblockstate.getValue(NIGHT))); // if (worldIn.getCurrentMoonPhaseFactor() == .25) // worldIn.setBlockState(pos, KalStuffBlocks.MOON_FLOWER2.getDefaultState().withProperty(NIGHT, // iblockstate.getValue(NIGHT))); // if (worldIn.getCurrentMoonPhaseFactor() == .50) // worldIn.setBlockState(pos, KalStuffBlocks.MOON_FLOWER3.getDefaultState().withProperty(NIGHT, // iblockstate.getValue(NIGHT))); // if (worldIn.getCurrentMoonPhaseFactor() == .75) // worldIn.setBlockState(pos, KalStuffBlocks.MOON_FLOWER4.getDefaultState().withProperty(NIGHT, // iblockstate.getValue(NIGHT))); // if (worldIn.getCurrentMoonPhaseFactor() == 1) // worldIn.setBlockState(pos, KalStuffBlocks.MOON_FLOWER5.getDefaultState().withProperty(NIGHT, // iblockstate.getValue(NIGHT))); // } else // { // worldIn.setBlockState(pos, // KalStuffBlocks.MOON_FLOWER.getDefaultState().withProperty(NIGHT, iblockstate.getValue(NIGHT)), // 3); // } // } // } // // protected BlockStateContainer createBlockState() // { // return new BlockStateContainer(this, new IProperty[] { NIGHT }); // } // // public Item getItemDropped(IBlockState state, Random rand, int fortune) // { // return Item.getItemFromBlock(KalStuffBlocks.MOON_FLOWER); // } // // @SideOnly(Side.CLIENT) // public Item getItem(World worldIn, BlockPos pos) // { // return Item.getItemFromBlock(KalStuffBlocks.MOON_FLOWER); // } // // /** // * Convert the given metadata into a BlockState for this Block // */ // public IBlockState getStateFromMeta(int meta) // { // return this.getDefaultState().withProperty(NIGHT, Integer.valueOf(meta)); // } // // /** // * Convert the BlockState into the correct metadata value // */ // public int getMetaFromState(IBlockState state) // { // return ((Integer) state.getValue(NIGHT)).intValue(); // } // }
import com.team.kalstuff.block.BlockMoonFlower; import net.minecraft.tileentity.TileEntity; import net.minecraft.util.ITickable;
package com.team.kalstuff.tileentity; public class TileEntityMoonFlower extends TileEntity implements ITickable { @Override public void update() { if (this.world != null && !this.world.isRemote && world.getWorldTime() >= 12800 || world.getWorldTime() < 23000) { this.blockType = this.getBlockType();
// Path: src/main/java/com/team/kalstuff/block/BlockMoonFlower.java // public class BlockMoonFlower extends BlockBush implements ITileEntityProvider // { // public static final PropertyInteger NIGHT = PropertyInteger.create("night", 0, 1); // // public BlockMoonFlower(float light, String name) // { // BlockKalStuff.setupBlock(this, name); // this.setDefaultState(this.blockState.getBaseState().withProperty(NIGHT, Integer.valueOf(0))); // this.setLightLevel((light) / 16.0f); // this.setSoundType(SoundType.PLANT); // // we must set the creative tab to null here so all varieties will not show up // // in the inventory // this.setCreativeTab(null); // } // // public void breakBlock(World worldIn, BlockPos pos, IBlockState state) // { // super.breakBlock(worldIn, pos, state); // worldIn.removeTileEntity(pos); // } // // public TileEntity createNewTileEntity(World worldIn, int meta) // { // return new TileEntityMoonFlower(); // } // // @Override // public void updateTick(World worldIn, BlockPos pos, IBlockState state, Random rand) // { // super.updateTick(worldIn, pos, state, rand); // if ((worldIn.getWorldTime() >= 12800 && worldIn.getWorldTime() < 23000) // && ((Integer) state.getValue(NIGHT)).intValue() != 1) // { // worldIn.setBlockState(pos, state.withProperty(NIGHT, Integer.valueOf(1))); // } else if ((worldIn.getWorldTime() >= 23000 || worldIn.getWorldTime() < 12800) // && ((Integer) state.getValue(NIGHT)).intValue() != 0) // { // worldIn.setBlockState(pos, state.withProperty(NIGHT, Integer.valueOf(0))); // } // } // // public void checkSky(World worldIn, BlockPos pos) // { // IBlockState iblockstate = worldIn.getBlockState(pos); // if (worldIn.getBlockState(pos).getBlock().getClass() == BlockMoonFlower.class) // { // if (worldIn.canSeeSky(pos) && ((Integer) worldIn.getBlockState(pos).getValue(NIGHT)).intValue() == 1) // { // if (worldIn.getCurrentMoonPhaseFactor() == 0) // worldIn.setBlockState(pos, KalStuffBlocks.MOON_FLOWER1.getDefaultState().withProperty(NIGHT, // iblockstate.getValue(NIGHT))); // if (worldIn.getCurrentMoonPhaseFactor() == .25) // worldIn.setBlockState(pos, KalStuffBlocks.MOON_FLOWER2.getDefaultState().withProperty(NIGHT, // iblockstate.getValue(NIGHT))); // if (worldIn.getCurrentMoonPhaseFactor() == .50) // worldIn.setBlockState(pos, KalStuffBlocks.MOON_FLOWER3.getDefaultState().withProperty(NIGHT, // iblockstate.getValue(NIGHT))); // if (worldIn.getCurrentMoonPhaseFactor() == .75) // worldIn.setBlockState(pos, KalStuffBlocks.MOON_FLOWER4.getDefaultState().withProperty(NIGHT, // iblockstate.getValue(NIGHT))); // if (worldIn.getCurrentMoonPhaseFactor() == 1) // worldIn.setBlockState(pos, KalStuffBlocks.MOON_FLOWER5.getDefaultState().withProperty(NIGHT, // iblockstate.getValue(NIGHT))); // } else // { // worldIn.setBlockState(pos, // KalStuffBlocks.MOON_FLOWER.getDefaultState().withProperty(NIGHT, iblockstate.getValue(NIGHT)), // 3); // } // } // } // // protected BlockStateContainer createBlockState() // { // return new BlockStateContainer(this, new IProperty[] { NIGHT }); // } // // public Item getItemDropped(IBlockState state, Random rand, int fortune) // { // return Item.getItemFromBlock(KalStuffBlocks.MOON_FLOWER); // } // // @SideOnly(Side.CLIENT) // public Item getItem(World worldIn, BlockPos pos) // { // return Item.getItemFromBlock(KalStuffBlocks.MOON_FLOWER); // } // // /** // * Convert the given metadata into a BlockState for this Block // */ // public IBlockState getStateFromMeta(int meta) // { // return this.getDefaultState().withProperty(NIGHT, Integer.valueOf(meta)); // } // // /** // * Convert the BlockState into the correct metadata value // */ // public int getMetaFromState(IBlockState state) // { // return ((Integer) state.getValue(NIGHT)).intValue(); // } // } // Path: src/main/java/com/team/kalstuff/tileentity/TileEntityMoonFlower.java import com.team.kalstuff.block.BlockMoonFlower; import net.minecraft.tileentity.TileEntity; import net.minecraft.util.ITickable; package com.team.kalstuff.tileentity; public class TileEntityMoonFlower extends TileEntity implements ITickable { @Override public void update() { if (this.world != null && !this.world.isRemote && world.getWorldTime() >= 12800 || world.getWorldTime() < 23000) { this.blockType = this.getBlockType();
if (this.blockType instanceof BlockMoonFlower)
TEAMModding/KalStuff
src/main/java/com/team/kalstuff/entity/KalStuffEntities.java
// Path: src/main/java/com/team/kalstuff/KalStuff.java // @Mod(modid = KalStuff.MODID, // name = KalStuff.NAME, // version = KalStuff.VERSION, // acceptedMinecraftVersions = "[1.12.2]", // useMetadata = true, // guiFactory = "com.team.kalstuff.config.KalStuffGuiFactory") // public class KalStuff // { // public static final String MODID = "kalstuff"; // public static final String NAME = "KalStuff"; // public static final String VERSION = "1.0.0"; // // @SidedProxy(clientSide = "com.team.kalstuff.proxy.ClientProxy", // serverSide = "com.team.kalstuff.proxy.ServerProxy") // public static CommonProxy proxy; // // // The instance of the mod that Forge uses. // @Mod.Instance // public static KalStuff instance; // // public static Logger logger; // // public static Configuration config; // // @EventHandler // public void preInit(FMLPreInitializationEvent e) // { // logger = e.getModLog(); // Config.initialize(e, e.getSuggestedConfigurationFile()); // config = Config.getConfig(); // proxy.preInit(e); // } // // @EventHandler // public void init(FMLInitializationEvent e) // { // proxy.init(e); // } // // @EventHandler // public void postInit(FMLPostInitializationEvent e) // { // if (config.hasChanged()) // { // config.save(); // } // proxy.postInit(e); // } // }
import com.team.kalstuff.KalStuff; import net.minecraft.entity.Entity; import net.minecraft.util.ResourceLocation; import net.minecraftforge.fml.common.registry.EntityRegistry;
package com.team.kalstuff.entity; public class KalStuffEntities { /** * Initializes and registers all entities from the mod. */ public static void setup() { registerEntities(); } public static void registerEntities() { registerEntity(EntityDuck.class, "duck", 80, 3, true, 0xFFFFFF, 0xE0C494); } // bits of this code were borrowed from Choonster because he wrote it very // neatly! // https://github.com/Choonster/TestMod3/blob/a6e5f7c223a18e4a53732af49aac6ac1bb52cc6f/src/main/java/choonster/testmod3/init/ModEntities.java private static int entityID = 0; /** * Register an entity with the specified tracking values. * * @param entityClass * The entity's class * @param entityName * The entity's unique name * @param trackingRange * The range at which MC will send tracking updates * @param updateFrequency * The frequency of tracking updates * @param sendsVelocityUpdates * Whether to send velocity information packets as well */ @SuppressWarnings("unused") private static void registerEntity(Class<? extends Entity> entityClass, String entityName, int trackingRange, int updateFrequency, boolean sendsVelocityUpdates) {
// Path: src/main/java/com/team/kalstuff/KalStuff.java // @Mod(modid = KalStuff.MODID, // name = KalStuff.NAME, // version = KalStuff.VERSION, // acceptedMinecraftVersions = "[1.12.2]", // useMetadata = true, // guiFactory = "com.team.kalstuff.config.KalStuffGuiFactory") // public class KalStuff // { // public static final String MODID = "kalstuff"; // public static final String NAME = "KalStuff"; // public static final String VERSION = "1.0.0"; // // @SidedProxy(clientSide = "com.team.kalstuff.proxy.ClientProxy", // serverSide = "com.team.kalstuff.proxy.ServerProxy") // public static CommonProxy proxy; // // // The instance of the mod that Forge uses. // @Mod.Instance // public static KalStuff instance; // // public static Logger logger; // // public static Configuration config; // // @EventHandler // public void preInit(FMLPreInitializationEvent e) // { // logger = e.getModLog(); // Config.initialize(e, e.getSuggestedConfigurationFile()); // config = Config.getConfig(); // proxy.preInit(e); // } // // @EventHandler // public void init(FMLInitializationEvent e) // { // proxy.init(e); // } // // @EventHandler // public void postInit(FMLPostInitializationEvent e) // { // if (config.hasChanged()) // { // config.save(); // } // proxy.postInit(e); // } // } // Path: src/main/java/com/team/kalstuff/entity/KalStuffEntities.java import com.team.kalstuff.KalStuff; import net.minecraft.entity.Entity; import net.minecraft.util.ResourceLocation; import net.minecraftforge.fml.common.registry.EntityRegistry; package com.team.kalstuff.entity; public class KalStuffEntities { /** * Initializes and registers all entities from the mod. */ public static void setup() { registerEntities(); } public static void registerEntities() { registerEntity(EntityDuck.class, "duck", 80, 3, true, 0xFFFFFF, 0xE0C494); } // bits of this code were borrowed from Choonster because he wrote it very // neatly! // https://github.com/Choonster/TestMod3/blob/a6e5f7c223a18e4a53732af49aac6ac1bb52cc6f/src/main/java/choonster/testmod3/init/ModEntities.java private static int entityID = 0; /** * Register an entity with the specified tracking values. * * @param entityClass * The entity's class * @param entityName * The entity's unique name * @param trackingRange * The range at which MC will send tracking updates * @param updateFrequency * The frequency of tracking updates * @param sendsVelocityUpdates * Whether to send velocity information packets as well */ @SuppressWarnings("unused") private static void registerEntity(Class<? extends Entity> entityClass, String entityName, int trackingRange, int updateFrequency, boolean sendsVelocityUpdates) {
final ResourceLocation registryName = new ResourceLocation(KalStuff.MODID, entityName);
TEAMModding/KalStuff
src/main/java/com/team/kalstuff/block/BlockBridge.java
// Path: src/main/java/com/team/kalstuff/KalStuff.java // @Mod(modid = KalStuff.MODID, // name = KalStuff.NAME, // version = KalStuff.VERSION, // acceptedMinecraftVersions = "[1.12.2]", // useMetadata = true, // guiFactory = "com.team.kalstuff.config.KalStuffGuiFactory") // public class KalStuff // { // public static final String MODID = "kalstuff"; // public static final String NAME = "KalStuff"; // public static final String VERSION = "1.0.0"; // // @SidedProxy(clientSide = "com.team.kalstuff.proxy.ClientProxy", // serverSide = "com.team.kalstuff.proxy.ServerProxy") // public static CommonProxy proxy; // // // The instance of the mod that Forge uses. // @Mod.Instance // public static KalStuff instance; // // public static Logger logger; // // public static Configuration config; // // @EventHandler // public void preInit(FMLPreInitializationEvent e) // { // logger = e.getModLog(); // Config.initialize(e, e.getSuggestedConfigurationFile()); // config = Config.getConfig(); // proxy.preInit(e); // } // // @EventHandler // public void init(FMLInitializationEvent e) // { // proxy.init(e); // } // // @EventHandler // public void postInit(FMLPostInitializationEvent e) // { // if (config.hasChanged()) // { // config.save(); // } // proxy.postInit(e); // } // } // // Path: src/main/java/com/team/kalstuff/config/Config.java // public class Config // { // public static File configurationFile; // public static Configuration config; // // public static final String CATEGORY_GENERAL = "General"; // // public static int cottageRarity = 512; // public static boolean bridgeTNT = false; // // public static final void initialize(FMLPreInitializationEvent e, File file) // { // config = new Configuration(file, KalStuff.VERSION, true); // MinecraftForge.EVENT_BUS.register(new EventHandler()); // config.load(); // config.setCategoryRequiresWorldRestart(CATEGORY_GENERAL, false); // config.setCategoryRequiresMcRestart(CATEGORY_GENERAL, false); // config.setCategoryComment(CATEGORY_GENERAL, "General configuration"); // refresh(); // config.save(); // } // // public static final Configuration getConfig() // { // return config; // } // // private static final void refresh() // { // cottageRarity = config.getInt("Cottage Rarity", CATEGORY_GENERAL, cottageRarity, 0, 16384, // "Rarity for cottage generation"); // bridgeTNT = config.getBoolean("Allow Bridge TNT", CATEGORY_GENERAL, bridgeTNT, // "Restricts bridge blocks from placing TNT"); // } // // public static void add(List<IConfigElement> list) // { // list.add(new ConfigElement(config.getCategory(CATEGORY_GENERAL))); // } // // public static class EventHandler // { // @SubscribeEvent // public void onConfigChanged(ConfigChangedEvent.OnConfigChangedEvent event) // { // if (event.getModID().equals(KalStuff.MODID)) // { // refresh(); // if (config.hasChanged()) // { // config.save(); // } // } // } // } // }
import java.util.Random; import com.team.kalstuff.KalStuff; import com.team.kalstuff.config.Config; import net.minecraft.block.Block; import net.minecraft.block.BlockDirectional; import net.minecraft.block.SoundType; import net.minecraft.block.material.Material; import net.minecraft.block.properties.IProperty; import net.minecraft.block.state.BlockStateContainer; import net.minecraft.block.state.IBlockState; import net.minecraft.entity.EntityLivingBase; import net.minecraft.entity.monster.EntityEnderman; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.init.Blocks; import net.minecraft.init.SoundEvents; import net.minecraft.item.ItemBlock; import net.minecraft.item.ItemStack; import net.minecraft.util.EnumFacing; import net.minecraft.util.EnumHand; import net.minecraft.util.EnumParticleTypes; import net.minecraft.util.SoundCategory; import net.minecraft.util.math.BlockPos; import net.minecraft.util.text.TextComponentTranslation; import net.minecraft.world.World; import net.minecraftforge.fml.relauncher.Side; import net.minecraftforge.fml.relauncher.SideOnly;
/** * Whenever the bridge block is right clicked or activated by another bridge, * this method is fired. It attempts to find where to place or chain the given * block */ @SuppressWarnings("deprecation") public boolean chain(World world, BlockPos pos, IBlockState state, EntityPlayer player, EnumHand hand, EnumFacing side, float hitX, float hitY, float hitZ, BlockPos origin) { if (world.isRemote) return true; ItemStack itemstack = player.getHeldItemMainhand(); Block block; // attempt to get a block from the held item without crashing the game try { block = Block.getBlockFromItem(itemstack.getItem()); } catch (Exception e) { return true; } if (block == null) return true; // if the block cannot be picked up by endermen, is not a bridge block, and in // the case of TNT is not allowed in the config, return with a chat message if ((!EntityEnderman.getCarriable(block) && block != KalStuffBlocks.BRIDGE)
// Path: src/main/java/com/team/kalstuff/KalStuff.java // @Mod(modid = KalStuff.MODID, // name = KalStuff.NAME, // version = KalStuff.VERSION, // acceptedMinecraftVersions = "[1.12.2]", // useMetadata = true, // guiFactory = "com.team.kalstuff.config.KalStuffGuiFactory") // public class KalStuff // { // public static final String MODID = "kalstuff"; // public static final String NAME = "KalStuff"; // public static final String VERSION = "1.0.0"; // // @SidedProxy(clientSide = "com.team.kalstuff.proxy.ClientProxy", // serverSide = "com.team.kalstuff.proxy.ServerProxy") // public static CommonProxy proxy; // // // The instance of the mod that Forge uses. // @Mod.Instance // public static KalStuff instance; // // public static Logger logger; // // public static Configuration config; // // @EventHandler // public void preInit(FMLPreInitializationEvent e) // { // logger = e.getModLog(); // Config.initialize(e, e.getSuggestedConfigurationFile()); // config = Config.getConfig(); // proxy.preInit(e); // } // // @EventHandler // public void init(FMLInitializationEvent e) // { // proxy.init(e); // } // // @EventHandler // public void postInit(FMLPostInitializationEvent e) // { // if (config.hasChanged()) // { // config.save(); // } // proxy.postInit(e); // } // } // // Path: src/main/java/com/team/kalstuff/config/Config.java // public class Config // { // public static File configurationFile; // public static Configuration config; // // public static final String CATEGORY_GENERAL = "General"; // // public static int cottageRarity = 512; // public static boolean bridgeTNT = false; // // public static final void initialize(FMLPreInitializationEvent e, File file) // { // config = new Configuration(file, KalStuff.VERSION, true); // MinecraftForge.EVENT_BUS.register(new EventHandler()); // config.load(); // config.setCategoryRequiresWorldRestart(CATEGORY_GENERAL, false); // config.setCategoryRequiresMcRestart(CATEGORY_GENERAL, false); // config.setCategoryComment(CATEGORY_GENERAL, "General configuration"); // refresh(); // config.save(); // } // // public static final Configuration getConfig() // { // return config; // } // // private static final void refresh() // { // cottageRarity = config.getInt("Cottage Rarity", CATEGORY_GENERAL, cottageRarity, 0, 16384, // "Rarity for cottage generation"); // bridgeTNT = config.getBoolean("Allow Bridge TNT", CATEGORY_GENERAL, bridgeTNT, // "Restricts bridge blocks from placing TNT"); // } // // public static void add(List<IConfigElement> list) // { // list.add(new ConfigElement(config.getCategory(CATEGORY_GENERAL))); // } // // public static class EventHandler // { // @SubscribeEvent // public void onConfigChanged(ConfigChangedEvent.OnConfigChangedEvent event) // { // if (event.getModID().equals(KalStuff.MODID)) // { // refresh(); // if (config.hasChanged()) // { // config.save(); // } // } // } // } // } // Path: src/main/java/com/team/kalstuff/block/BlockBridge.java import java.util.Random; import com.team.kalstuff.KalStuff; import com.team.kalstuff.config.Config; import net.minecraft.block.Block; import net.minecraft.block.BlockDirectional; import net.minecraft.block.SoundType; import net.minecraft.block.material.Material; import net.minecraft.block.properties.IProperty; import net.minecraft.block.state.BlockStateContainer; import net.minecraft.block.state.IBlockState; import net.minecraft.entity.EntityLivingBase; import net.minecraft.entity.monster.EntityEnderman; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.init.Blocks; import net.minecraft.init.SoundEvents; import net.minecraft.item.ItemBlock; import net.minecraft.item.ItemStack; import net.minecraft.util.EnumFacing; import net.minecraft.util.EnumHand; import net.minecraft.util.EnumParticleTypes; import net.minecraft.util.SoundCategory; import net.minecraft.util.math.BlockPos; import net.minecraft.util.text.TextComponentTranslation; import net.minecraft.world.World; import net.minecraftforge.fml.relauncher.Side; import net.minecraftforge.fml.relauncher.SideOnly; /** * Whenever the bridge block is right clicked or activated by another bridge, * this method is fired. It attempts to find where to place or chain the given * block */ @SuppressWarnings("deprecation") public boolean chain(World world, BlockPos pos, IBlockState state, EntityPlayer player, EnumHand hand, EnumFacing side, float hitX, float hitY, float hitZ, BlockPos origin) { if (world.isRemote) return true; ItemStack itemstack = player.getHeldItemMainhand(); Block block; // attempt to get a block from the held item without crashing the game try { block = Block.getBlockFromItem(itemstack.getItem()); } catch (Exception e) { return true; } if (block == null) return true; // if the block cannot be picked up by endermen, is not a bridge block, and in // the case of TNT is not allowed in the config, return with a chat message if ((!EntityEnderman.getCarriable(block) && block != KalStuffBlocks.BRIDGE)
|| (!Config.bridgeTNT && block == Blocks.TNT))
TEAMModding/KalStuff
src/main/java/com/team/kalstuff/block/BlockBridge.java
// Path: src/main/java/com/team/kalstuff/KalStuff.java // @Mod(modid = KalStuff.MODID, // name = KalStuff.NAME, // version = KalStuff.VERSION, // acceptedMinecraftVersions = "[1.12.2]", // useMetadata = true, // guiFactory = "com.team.kalstuff.config.KalStuffGuiFactory") // public class KalStuff // { // public static final String MODID = "kalstuff"; // public static final String NAME = "KalStuff"; // public static final String VERSION = "1.0.0"; // // @SidedProxy(clientSide = "com.team.kalstuff.proxy.ClientProxy", // serverSide = "com.team.kalstuff.proxy.ServerProxy") // public static CommonProxy proxy; // // // The instance of the mod that Forge uses. // @Mod.Instance // public static KalStuff instance; // // public static Logger logger; // // public static Configuration config; // // @EventHandler // public void preInit(FMLPreInitializationEvent e) // { // logger = e.getModLog(); // Config.initialize(e, e.getSuggestedConfigurationFile()); // config = Config.getConfig(); // proxy.preInit(e); // } // // @EventHandler // public void init(FMLInitializationEvent e) // { // proxy.init(e); // } // // @EventHandler // public void postInit(FMLPostInitializationEvent e) // { // if (config.hasChanged()) // { // config.save(); // } // proxy.postInit(e); // } // } // // Path: src/main/java/com/team/kalstuff/config/Config.java // public class Config // { // public static File configurationFile; // public static Configuration config; // // public static final String CATEGORY_GENERAL = "General"; // // public static int cottageRarity = 512; // public static boolean bridgeTNT = false; // // public static final void initialize(FMLPreInitializationEvent e, File file) // { // config = new Configuration(file, KalStuff.VERSION, true); // MinecraftForge.EVENT_BUS.register(new EventHandler()); // config.load(); // config.setCategoryRequiresWorldRestart(CATEGORY_GENERAL, false); // config.setCategoryRequiresMcRestart(CATEGORY_GENERAL, false); // config.setCategoryComment(CATEGORY_GENERAL, "General configuration"); // refresh(); // config.save(); // } // // public static final Configuration getConfig() // { // return config; // } // // private static final void refresh() // { // cottageRarity = config.getInt("Cottage Rarity", CATEGORY_GENERAL, cottageRarity, 0, 16384, // "Rarity for cottage generation"); // bridgeTNT = config.getBoolean("Allow Bridge TNT", CATEGORY_GENERAL, bridgeTNT, // "Restricts bridge blocks from placing TNT"); // } // // public static void add(List<IConfigElement> list) // { // list.add(new ConfigElement(config.getCategory(CATEGORY_GENERAL))); // } // // public static class EventHandler // { // @SubscribeEvent // public void onConfigChanged(ConfigChangedEvent.OnConfigChangedEvent event) // { // if (event.getModID().equals(KalStuff.MODID)) // { // refresh(); // if (config.hasChanged()) // { // config.save(); // } // } // } // } // }
import java.util.Random; import com.team.kalstuff.KalStuff; import com.team.kalstuff.config.Config; import net.minecraft.block.Block; import net.minecraft.block.BlockDirectional; import net.minecraft.block.SoundType; import net.minecraft.block.material.Material; import net.minecraft.block.properties.IProperty; import net.minecraft.block.state.BlockStateContainer; import net.minecraft.block.state.IBlockState; import net.minecraft.entity.EntityLivingBase; import net.minecraft.entity.monster.EntityEnderman; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.init.Blocks; import net.minecraft.init.SoundEvents; import net.minecraft.item.ItemBlock; import net.minecraft.item.ItemStack; import net.minecraft.util.EnumFacing; import net.minecraft.util.EnumHand; import net.minecraft.util.EnumParticleTypes; import net.minecraft.util.SoundCategory; import net.minecraft.util.math.BlockPos; import net.minecraft.util.text.TextComponentTranslation; import net.minecraft.world.World; import net.minecraftforge.fml.relauncher.Side; import net.minecraftforge.fml.relauncher.SideOnly;
} catch (Exception e) { return true; } if (block == null) return true; // if the block cannot be picked up by endermen, is not a bridge block, and in // the case of TNT is not allowed in the config, return with a chat message if ((!EntityEnderman.getCarriable(block) && block != KalStuffBlocks.BRIDGE) || (!Config.bridgeTNT && block == Blocks.TNT)) { player.sendMessage(new TextComponentTranslation("The bridge is unable to send this")); return true; } // get next position that the bridge block is pointing towards BlockPos aPos = this.getNextBlock(pos, state, world); int dist = (int) aPos.getDistance(pos.getX(), pos.getY(), pos.getZ()); // check for unbreakable or very hard blocks - should only catch unbreakable // blocks (e.g. bedrock), obsidian, and water by default (we explicitly allow // lava) if (world.getBlockState(aPos).getBlockHardness(world, aPos) == -1.0F || (world.getBlockState(aPos).getBlockHardness(world, aPos) >= 50.0F && world.getBlockState(aPos).getBlock() != Blocks.LAVA && world.getBlockState(aPos).getBlock() != Blocks.FLOWING_LAVA)) { player.sendMessage(new TextComponentTranslation("Something is blocking the bridge"));
// Path: src/main/java/com/team/kalstuff/KalStuff.java // @Mod(modid = KalStuff.MODID, // name = KalStuff.NAME, // version = KalStuff.VERSION, // acceptedMinecraftVersions = "[1.12.2]", // useMetadata = true, // guiFactory = "com.team.kalstuff.config.KalStuffGuiFactory") // public class KalStuff // { // public static final String MODID = "kalstuff"; // public static final String NAME = "KalStuff"; // public static final String VERSION = "1.0.0"; // // @SidedProxy(clientSide = "com.team.kalstuff.proxy.ClientProxy", // serverSide = "com.team.kalstuff.proxy.ServerProxy") // public static CommonProxy proxy; // // // The instance of the mod that Forge uses. // @Mod.Instance // public static KalStuff instance; // // public static Logger logger; // // public static Configuration config; // // @EventHandler // public void preInit(FMLPreInitializationEvent e) // { // logger = e.getModLog(); // Config.initialize(e, e.getSuggestedConfigurationFile()); // config = Config.getConfig(); // proxy.preInit(e); // } // // @EventHandler // public void init(FMLInitializationEvent e) // { // proxy.init(e); // } // // @EventHandler // public void postInit(FMLPostInitializationEvent e) // { // if (config.hasChanged()) // { // config.save(); // } // proxy.postInit(e); // } // } // // Path: src/main/java/com/team/kalstuff/config/Config.java // public class Config // { // public static File configurationFile; // public static Configuration config; // // public static final String CATEGORY_GENERAL = "General"; // // public static int cottageRarity = 512; // public static boolean bridgeTNT = false; // // public static final void initialize(FMLPreInitializationEvent e, File file) // { // config = new Configuration(file, KalStuff.VERSION, true); // MinecraftForge.EVENT_BUS.register(new EventHandler()); // config.load(); // config.setCategoryRequiresWorldRestart(CATEGORY_GENERAL, false); // config.setCategoryRequiresMcRestart(CATEGORY_GENERAL, false); // config.setCategoryComment(CATEGORY_GENERAL, "General configuration"); // refresh(); // config.save(); // } // // public static final Configuration getConfig() // { // return config; // } // // private static final void refresh() // { // cottageRarity = config.getInt("Cottage Rarity", CATEGORY_GENERAL, cottageRarity, 0, 16384, // "Rarity for cottage generation"); // bridgeTNT = config.getBoolean("Allow Bridge TNT", CATEGORY_GENERAL, bridgeTNT, // "Restricts bridge blocks from placing TNT"); // } // // public static void add(List<IConfigElement> list) // { // list.add(new ConfigElement(config.getCategory(CATEGORY_GENERAL))); // } // // public static class EventHandler // { // @SubscribeEvent // public void onConfigChanged(ConfigChangedEvent.OnConfigChangedEvent event) // { // if (event.getModID().equals(KalStuff.MODID)) // { // refresh(); // if (config.hasChanged()) // { // config.save(); // } // } // } // } // } // Path: src/main/java/com/team/kalstuff/block/BlockBridge.java import java.util.Random; import com.team.kalstuff.KalStuff; import com.team.kalstuff.config.Config; import net.minecraft.block.Block; import net.minecraft.block.BlockDirectional; import net.minecraft.block.SoundType; import net.minecraft.block.material.Material; import net.minecraft.block.properties.IProperty; import net.minecraft.block.state.BlockStateContainer; import net.minecraft.block.state.IBlockState; import net.minecraft.entity.EntityLivingBase; import net.minecraft.entity.monster.EntityEnderman; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.init.Blocks; import net.minecraft.init.SoundEvents; import net.minecraft.item.ItemBlock; import net.minecraft.item.ItemStack; import net.minecraft.util.EnumFacing; import net.minecraft.util.EnumHand; import net.minecraft.util.EnumParticleTypes; import net.minecraft.util.SoundCategory; import net.minecraft.util.math.BlockPos; import net.minecraft.util.text.TextComponentTranslation; import net.minecraft.world.World; import net.minecraftforge.fml.relauncher.Side; import net.minecraftforge.fml.relauncher.SideOnly; } catch (Exception e) { return true; } if (block == null) return true; // if the block cannot be picked up by endermen, is not a bridge block, and in // the case of TNT is not allowed in the config, return with a chat message if ((!EntityEnderman.getCarriable(block) && block != KalStuffBlocks.BRIDGE) || (!Config.bridgeTNT && block == Blocks.TNT)) { player.sendMessage(new TextComponentTranslation("The bridge is unable to send this")); return true; } // get next position that the bridge block is pointing towards BlockPos aPos = this.getNextBlock(pos, state, world); int dist = (int) aPos.getDistance(pos.getX(), pos.getY(), pos.getZ()); // check for unbreakable or very hard blocks - should only catch unbreakable // blocks (e.g. bedrock), obsidian, and water by default (we explicitly allow // lava) if (world.getBlockState(aPos).getBlockHardness(world, aPos) == -1.0F || (world.getBlockState(aPos).getBlockHardness(world, aPos) >= 50.0F && world.getBlockState(aPos).getBlock() != Blocks.LAVA && world.getBlockState(aPos).getBlock() != Blocks.FLOWING_LAVA)) { player.sendMessage(new TextComponentTranslation("Something is blocking the bridge"));
KalStuff.logger.info(world.getBlockState(aPos).getBlock());
TEAMModding/KalStuff
src/main/java/com/team/kalstuff/block/BlockTrashCan.java
// Path: src/main/java/com/team/kalstuff/KalStuff.java // @Mod(modid = KalStuff.MODID, // name = KalStuff.NAME, // version = KalStuff.VERSION, // acceptedMinecraftVersions = "[1.12.2]", // useMetadata = true, // guiFactory = "com.team.kalstuff.config.KalStuffGuiFactory") // public class KalStuff // { // public static final String MODID = "kalstuff"; // public static final String NAME = "KalStuff"; // public static final String VERSION = "1.0.0"; // // @SidedProxy(clientSide = "com.team.kalstuff.proxy.ClientProxy", // serverSide = "com.team.kalstuff.proxy.ServerProxy") // public static CommonProxy proxy; // // // The instance of the mod that Forge uses. // @Mod.Instance // public static KalStuff instance; // // public static Logger logger; // // public static Configuration config; // // @EventHandler // public void preInit(FMLPreInitializationEvent e) // { // logger = e.getModLog(); // Config.initialize(e, e.getSuggestedConfigurationFile()); // config = Config.getConfig(); // proxy.preInit(e); // } // // @EventHandler // public void init(FMLInitializationEvent e) // { // proxy.init(e); // } // // @EventHandler // public void postInit(FMLPostInitializationEvent e) // { // if (config.hasChanged()) // { // config.save(); // } // proxy.postInit(e); // } // } // // Path: src/main/java/com/team/kalstuff/proxy/CommonProxy.java // @Mod.EventBusSubscriber // public class CommonProxy // { // public static final CreativeTabs KALSTUFFTAB = new KalStuffCreativeTab("kalstuffTab"); // // public void preInit(FMLPreInitializationEvent e) // { // MinecraftForge.EVENT_BUS.register(new CoreEventHandler()); // KalStuffTileEntities.register(); // KalStuffWorldGenerator.register(); // KalStuffEntities.setup(); // NetworkRegistry.INSTANCE.registerGuiHandler(KalStuff.instance, new KalStuffGuiHandler()); // } // // public void init(FMLInitializationEvent e) // { // KalStuffRecipes.add(); // KalStuffItems.configureItems(); // KalStuff.logger // .info("Hi there, nerdy geeks. You should just enjoy Minecraft and stop looking at the system output."); // } // // public void postInit(FMLPostInitializationEvent e) // { // KalStuff.logger.info("Wait a minute... Guys! IT WORKS!?! WE MADE A MOD!!!"); // } // }
import com.team.kalstuff.KalStuff; import com.team.kalstuff.proxy.CommonProxy; import net.minecraft.block.SoundType; import net.minecraft.block.material.Material; import net.minecraft.block.state.IBlockState; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.util.EnumFacing; import net.minecraft.util.EnumHand; import net.minecraft.util.math.AxisAlignedBB; import net.minecraft.util.math.BlockPos; import net.minecraft.world.IBlockAccess; import net.minecraft.world.World;
package com.team.kalstuff.block; public class BlockTrashCan extends BlockKalStuff { public static final AxisAlignedBB AABB = new AxisAlignedBB(1d / 16d, 0d, 1d / 16d, 15d / 16d, 1d, 15d / 16d); public BlockTrashCan(String name) { super(Material.IRON, name);
// Path: src/main/java/com/team/kalstuff/KalStuff.java // @Mod(modid = KalStuff.MODID, // name = KalStuff.NAME, // version = KalStuff.VERSION, // acceptedMinecraftVersions = "[1.12.2]", // useMetadata = true, // guiFactory = "com.team.kalstuff.config.KalStuffGuiFactory") // public class KalStuff // { // public static final String MODID = "kalstuff"; // public static final String NAME = "KalStuff"; // public static final String VERSION = "1.0.0"; // // @SidedProxy(clientSide = "com.team.kalstuff.proxy.ClientProxy", // serverSide = "com.team.kalstuff.proxy.ServerProxy") // public static CommonProxy proxy; // // // The instance of the mod that Forge uses. // @Mod.Instance // public static KalStuff instance; // // public static Logger logger; // // public static Configuration config; // // @EventHandler // public void preInit(FMLPreInitializationEvent e) // { // logger = e.getModLog(); // Config.initialize(e, e.getSuggestedConfigurationFile()); // config = Config.getConfig(); // proxy.preInit(e); // } // // @EventHandler // public void init(FMLInitializationEvent e) // { // proxy.init(e); // } // // @EventHandler // public void postInit(FMLPostInitializationEvent e) // { // if (config.hasChanged()) // { // config.save(); // } // proxy.postInit(e); // } // } // // Path: src/main/java/com/team/kalstuff/proxy/CommonProxy.java // @Mod.EventBusSubscriber // public class CommonProxy // { // public static final CreativeTabs KALSTUFFTAB = new KalStuffCreativeTab("kalstuffTab"); // // public void preInit(FMLPreInitializationEvent e) // { // MinecraftForge.EVENT_BUS.register(new CoreEventHandler()); // KalStuffTileEntities.register(); // KalStuffWorldGenerator.register(); // KalStuffEntities.setup(); // NetworkRegistry.INSTANCE.registerGuiHandler(KalStuff.instance, new KalStuffGuiHandler()); // } // // public void init(FMLInitializationEvent e) // { // KalStuffRecipes.add(); // KalStuffItems.configureItems(); // KalStuff.logger // .info("Hi there, nerdy geeks. You should just enjoy Minecraft and stop looking at the system output."); // } // // public void postInit(FMLPostInitializationEvent e) // { // KalStuff.logger.info("Wait a minute... Guys! IT WORKS!?! WE MADE A MOD!!!"); // } // } // Path: src/main/java/com/team/kalstuff/block/BlockTrashCan.java import com.team.kalstuff.KalStuff; import com.team.kalstuff.proxy.CommonProxy; import net.minecraft.block.SoundType; import net.minecraft.block.material.Material; import net.minecraft.block.state.IBlockState; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.util.EnumFacing; import net.minecraft.util.EnumHand; import net.minecraft.util.math.AxisAlignedBB; import net.minecraft.util.math.BlockPos; import net.minecraft.world.IBlockAccess; import net.minecraft.world.World; package com.team.kalstuff.block; public class BlockTrashCan extends BlockKalStuff { public static final AxisAlignedBB AABB = new AxisAlignedBB(1d / 16d, 0d, 1d / 16d, 15d / 16d, 1d, 15d / 16d); public BlockTrashCan(String name) { super(Material.IRON, name);
this.setCreativeTab(CommonProxy.KALSTUFFTAB);
TEAMModding/KalStuff
src/main/java/com/team/kalstuff/block/BlockTrashCan.java
// Path: src/main/java/com/team/kalstuff/KalStuff.java // @Mod(modid = KalStuff.MODID, // name = KalStuff.NAME, // version = KalStuff.VERSION, // acceptedMinecraftVersions = "[1.12.2]", // useMetadata = true, // guiFactory = "com.team.kalstuff.config.KalStuffGuiFactory") // public class KalStuff // { // public static final String MODID = "kalstuff"; // public static final String NAME = "KalStuff"; // public static final String VERSION = "1.0.0"; // // @SidedProxy(clientSide = "com.team.kalstuff.proxy.ClientProxy", // serverSide = "com.team.kalstuff.proxy.ServerProxy") // public static CommonProxy proxy; // // // The instance of the mod that Forge uses. // @Mod.Instance // public static KalStuff instance; // // public static Logger logger; // // public static Configuration config; // // @EventHandler // public void preInit(FMLPreInitializationEvent e) // { // logger = e.getModLog(); // Config.initialize(e, e.getSuggestedConfigurationFile()); // config = Config.getConfig(); // proxy.preInit(e); // } // // @EventHandler // public void init(FMLInitializationEvent e) // { // proxy.init(e); // } // // @EventHandler // public void postInit(FMLPostInitializationEvent e) // { // if (config.hasChanged()) // { // config.save(); // } // proxy.postInit(e); // } // } // // Path: src/main/java/com/team/kalstuff/proxy/CommonProxy.java // @Mod.EventBusSubscriber // public class CommonProxy // { // public static final CreativeTabs KALSTUFFTAB = new KalStuffCreativeTab("kalstuffTab"); // // public void preInit(FMLPreInitializationEvent e) // { // MinecraftForge.EVENT_BUS.register(new CoreEventHandler()); // KalStuffTileEntities.register(); // KalStuffWorldGenerator.register(); // KalStuffEntities.setup(); // NetworkRegistry.INSTANCE.registerGuiHandler(KalStuff.instance, new KalStuffGuiHandler()); // } // // public void init(FMLInitializationEvent e) // { // KalStuffRecipes.add(); // KalStuffItems.configureItems(); // KalStuff.logger // .info("Hi there, nerdy geeks. You should just enjoy Minecraft and stop looking at the system output."); // } // // public void postInit(FMLPostInitializationEvent e) // { // KalStuff.logger.info("Wait a minute... Guys! IT WORKS!?! WE MADE A MOD!!!"); // } // }
import com.team.kalstuff.KalStuff; import com.team.kalstuff.proxy.CommonProxy; import net.minecraft.block.SoundType; import net.minecraft.block.material.Material; import net.minecraft.block.state.IBlockState; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.util.EnumFacing; import net.minecraft.util.EnumHand; import net.minecraft.util.math.AxisAlignedBB; import net.minecraft.util.math.BlockPos; import net.minecraft.world.IBlockAccess; import net.minecraft.world.World;
package com.team.kalstuff.block; public class BlockTrashCan extends BlockKalStuff { public static final AxisAlignedBB AABB = new AxisAlignedBB(1d / 16d, 0d, 1d / 16d, 15d / 16d, 1d, 15d / 16d); public BlockTrashCan(String name) { super(Material.IRON, name); this.setCreativeTab(CommonProxy.KALSTUFFTAB); this.setHardness(3.0F); this.setSoundType(SoundType.LADDER); } public AxisAlignedBB getBoundingBox(IBlockState state, IBlockAccess source, BlockPos pos) { return AABB; } public boolean onBlockActivated(World worldIn, BlockPos pos, IBlockState state, EntityPlayer playerIn, EnumHand hand, EnumFacing side, float hitX, float hitY, float hitZ) { if (!worldIn.isRemote) {
// Path: src/main/java/com/team/kalstuff/KalStuff.java // @Mod(modid = KalStuff.MODID, // name = KalStuff.NAME, // version = KalStuff.VERSION, // acceptedMinecraftVersions = "[1.12.2]", // useMetadata = true, // guiFactory = "com.team.kalstuff.config.KalStuffGuiFactory") // public class KalStuff // { // public static final String MODID = "kalstuff"; // public static final String NAME = "KalStuff"; // public static final String VERSION = "1.0.0"; // // @SidedProxy(clientSide = "com.team.kalstuff.proxy.ClientProxy", // serverSide = "com.team.kalstuff.proxy.ServerProxy") // public static CommonProxy proxy; // // // The instance of the mod that Forge uses. // @Mod.Instance // public static KalStuff instance; // // public static Logger logger; // // public static Configuration config; // // @EventHandler // public void preInit(FMLPreInitializationEvent e) // { // logger = e.getModLog(); // Config.initialize(e, e.getSuggestedConfigurationFile()); // config = Config.getConfig(); // proxy.preInit(e); // } // // @EventHandler // public void init(FMLInitializationEvent e) // { // proxy.init(e); // } // // @EventHandler // public void postInit(FMLPostInitializationEvent e) // { // if (config.hasChanged()) // { // config.save(); // } // proxy.postInit(e); // } // } // // Path: src/main/java/com/team/kalstuff/proxy/CommonProxy.java // @Mod.EventBusSubscriber // public class CommonProxy // { // public static final CreativeTabs KALSTUFFTAB = new KalStuffCreativeTab("kalstuffTab"); // // public void preInit(FMLPreInitializationEvent e) // { // MinecraftForge.EVENT_BUS.register(new CoreEventHandler()); // KalStuffTileEntities.register(); // KalStuffWorldGenerator.register(); // KalStuffEntities.setup(); // NetworkRegistry.INSTANCE.registerGuiHandler(KalStuff.instance, new KalStuffGuiHandler()); // } // // public void init(FMLInitializationEvent e) // { // KalStuffRecipes.add(); // KalStuffItems.configureItems(); // KalStuff.logger // .info("Hi there, nerdy geeks. You should just enjoy Minecraft and stop looking at the system output."); // } // // public void postInit(FMLPostInitializationEvent e) // { // KalStuff.logger.info("Wait a minute... Guys! IT WORKS!?! WE MADE A MOD!!!"); // } // } // Path: src/main/java/com/team/kalstuff/block/BlockTrashCan.java import com.team.kalstuff.KalStuff; import com.team.kalstuff.proxy.CommonProxy; import net.minecraft.block.SoundType; import net.minecraft.block.material.Material; import net.minecraft.block.state.IBlockState; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.util.EnumFacing; import net.minecraft.util.EnumHand; import net.minecraft.util.math.AxisAlignedBB; import net.minecraft.util.math.BlockPos; import net.minecraft.world.IBlockAccess; import net.minecraft.world.World; package com.team.kalstuff.block; public class BlockTrashCan extends BlockKalStuff { public static final AxisAlignedBB AABB = new AxisAlignedBB(1d / 16d, 0d, 1d / 16d, 15d / 16d, 1d, 15d / 16d); public BlockTrashCan(String name) { super(Material.IRON, name); this.setCreativeTab(CommonProxy.KALSTUFFTAB); this.setHardness(3.0F); this.setSoundType(SoundType.LADDER); } public AxisAlignedBB getBoundingBox(IBlockState state, IBlockAccess source, BlockPos pos) { return AABB; } public boolean onBlockActivated(World worldIn, BlockPos pos, IBlockState state, EntityPlayer playerIn, EnumHand hand, EnumFacing side, float hitX, float hitY, float hitZ) { if (!worldIn.isRemote) {
playerIn.openGui(KalStuff.instance, 1, worldIn, pos.getX(), pos.getY(), pos.getZ());
pdtyreus/conversation-kit
redux/src/main/java/com/conversationkit/redux/impl/SupplierMiddleware.java
// Path: redux/src/main/java/com/conversationkit/redux/Action.java // @FunctionalInterface // public interface Action { // public String getType(); // } // // Path: redux/src/main/java/com/conversationkit/redux/Middleware.java // @FunctionalInterface // /** // * A middleware is a higher-order function that composes a {@link Dispatcher} function to return a new dispatch function. It often turns async actions into actions. // * @see <a href="https://redux.js.org/glossary#middleware">https://redux.js.org/glossary#middleware</a> // */ // public interface Middleware<S> { // // void dispatch(Store<S> store, Object action, Middleware<S> next); // } // // Path: redux/src/main/java/com/conversationkit/redux/Store.java // public final class Store<S> implements Dispatcher { // // private static final Logger logger = Logger.getLogger(Store.class.getName()); // // private Map currentState; // // private final Reducer reducer; // private ActionDispatcher dispatcher; // private final Function<Map,S> typedStateBuilder; // private final Map<UUID, Consumer<Map<String, Object>>> consumers = new HashMap<>(); // // @FunctionalInterface // public interface ActionDispatcher { // // public void dispatch(Object action); // // } // // protected Store(Reducer reducer, Map initialState, Function<Map,S> stateBuilder, Middleware... middlewares) { // this.reducer = reducer; // this.currentState = initialState; // this.typedStateBuilder = stateBuilder; // // List<Middleware> allMiddlewares = new ArrayList(); // // for (Middleware mw : middlewares) { // allMiddlewares.add(mw); // } // //native middleware, last middleware in chain // allMiddlewares.add((store, action, next) -> { // Map nextState; // synchronized (Store.this) { // logger.fine(String.format("[REDUX] reducing action: %s", action.toString())); // if (!(action instanceof Action)) { // throw new RuntimeException("The action must be an instance of Action by the time it is received by the reducer. Action is " + action.getClass().getName()); // } // Action a = (Action) action; // nextState = store.reducer.reduce(a, currentState); // } // if (!nextState.equals(currentState)) { // logger.fine(String.format("[REDUX] state has changed after %s", action.toString())); // currentState = nextState; // consumers.values().parallelStream().forEach(e -> e.accept(currentState)); // } else { // logger.fine(String.format("[REDUX] state has not changed after %s", action.toString())); // } // }); // // logger.info(String.format("[REDUX] initializing redux store with %d middleware(s).", (allMiddlewares.size() - 1))); // // for (int i = allMiddlewares.size() - 1; i >= 0; i--) { // final Middleware mw = allMiddlewares.get(i); // logger.fine(String.format("[REDUX] chaining middleware (%d)", i)); // //this will be null for the native middleware only, which is last // final Middleware next = (i == allMiddlewares.size() - 1 ? null : allMiddlewares.get(i + 1)); // this.dispatcher = (action) -> { // mw.dispatch(Store.this, action, next); // }; // // } // } // // @Override // public S dispatch(Object action) { // logger.fine(String.format("[REDUX] dispatching action: %s", action.toString())); // // dispatcher.dispatch(action); // logger.finer(String.format("[REDUX] reduced state: %s", getState().toString())); // return getState(); // } // // public S getState() { // return typedStateBuilder.apply(currentState); // } // // public UUID subscribe(Consumer<Map<String, Object>> subscriber) { // UUID uuid = UUID.randomUUID(); // this.consumers.put(uuid, subscriber); // // return uuid; // } // // public void unsubscribe(UUID uuid) { // // this.consumers.remove(uuid); // } // }
import java.util.logging.Logger; import com.conversationkit.redux.Action; import com.conversationkit.redux.Middleware; import com.conversationkit.redux.Store; import java.util.concurrent.CompletableFuture; import java.util.concurrent.ExecutorService; import java.util.function.Supplier; import java.util.logging.Level;
/* * The MIT License * * Copyright 2019 Synclab Consulting LLC. * * 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.conversationkit.redux.impl; /** * Redux middleware that handles an async {@link Action} of type {@link Supplier} * @author pdtyreus */ public class SupplierMiddleware implements Middleware { private static final Logger logger = Logger.getLogger(SupplierMiddleware.class.getName()); private final ExecutorService executorService; public SupplierMiddleware(ExecutorService executorService) { this.executorService = executorService; } @Override
// Path: redux/src/main/java/com/conversationkit/redux/Action.java // @FunctionalInterface // public interface Action { // public String getType(); // } // // Path: redux/src/main/java/com/conversationkit/redux/Middleware.java // @FunctionalInterface // /** // * A middleware is a higher-order function that composes a {@link Dispatcher} function to return a new dispatch function. It often turns async actions into actions. // * @see <a href="https://redux.js.org/glossary#middleware">https://redux.js.org/glossary#middleware</a> // */ // public interface Middleware<S> { // // void dispatch(Store<S> store, Object action, Middleware<S> next); // } // // Path: redux/src/main/java/com/conversationkit/redux/Store.java // public final class Store<S> implements Dispatcher { // // private static final Logger logger = Logger.getLogger(Store.class.getName()); // // private Map currentState; // // private final Reducer reducer; // private ActionDispatcher dispatcher; // private final Function<Map,S> typedStateBuilder; // private final Map<UUID, Consumer<Map<String, Object>>> consumers = new HashMap<>(); // // @FunctionalInterface // public interface ActionDispatcher { // // public void dispatch(Object action); // // } // // protected Store(Reducer reducer, Map initialState, Function<Map,S> stateBuilder, Middleware... middlewares) { // this.reducer = reducer; // this.currentState = initialState; // this.typedStateBuilder = stateBuilder; // // List<Middleware> allMiddlewares = new ArrayList(); // // for (Middleware mw : middlewares) { // allMiddlewares.add(mw); // } // //native middleware, last middleware in chain // allMiddlewares.add((store, action, next) -> { // Map nextState; // synchronized (Store.this) { // logger.fine(String.format("[REDUX] reducing action: %s", action.toString())); // if (!(action instanceof Action)) { // throw new RuntimeException("The action must be an instance of Action by the time it is received by the reducer. Action is " + action.getClass().getName()); // } // Action a = (Action) action; // nextState = store.reducer.reduce(a, currentState); // } // if (!nextState.equals(currentState)) { // logger.fine(String.format("[REDUX] state has changed after %s", action.toString())); // currentState = nextState; // consumers.values().parallelStream().forEach(e -> e.accept(currentState)); // } else { // logger.fine(String.format("[REDUX] state has not changed after %s", action.toString())); // } // }); // // logger.info(String.format("[REDUX] initializing redux store with %d middleware(s).", (allMiddlewares.size() - 1))); // // for (int i = allMiddlewares.size() - 1; i >= 0; i--) { // final Middleware mw = allMiddlewares.get(i); // logger.fine(String.format("[REDUX] chaining middleware (%d)", i)); // //this will be null for the native middleware only, which is last // final Middleware next = (i == allMiddlewares.size() - 1 ? null : allMiddlewares.get(i + 1)); // this.dispatcher = (action) -> { // mw.dispatch(Store.this, action, next); // }; // // } // } // // @Override // public S dispatch(Object action) { // logger.fine(String.format("[REDUX] dispatching action: %s", action.toString())); // // dispatcher.dispatch(action); // logger.finer(String.format("[REDUX] reduced state: %s", getState().toString())); // return getState(); // } // // public S getState() { // return typedStateBuilder.apply(currentState); // } // // public UUID subscribe(Consumer<Map<String, Object>> subscriber) { // UUID uuid = UUID.randomUUID(); // this.consumers.put(uuid, subscriber); // // return uuid; // } // // public void unsubscribe(UUID uuid) { // // this.consumers.remove(uuid); // } // } // Path: redux/src/main/java/com/conversationkit/redux/impl/SupplierMiddleware.java import java.util.logging.Logger; import com.conversationkit.redux.Action; import com.conversationkit.redux.Middleware; import com.conversationkit.redux.Store; import java.util.concurrent.CompletableFuture; import java.util.concurrent.ExecutorService; import java.util.function.Supplier; import java.util.logging.Level; /* * The MIT License * * Copyright 2019 Synclab Consulting LLC. * * 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.conversationkit.redux.impl; /** * Redux middleware that handles an async {@link Action} of type {@link Supplier} * @author pdtyreus */ public class SupplierMiddleware implements Middleware { private static final Logger logger = Logger.getLogger(SupplierMiddleware.class.getName()); private final ExecutorService executorService; public SupplierMiddleware(ExecutorService executorService) { this.executorService = executorService; } @Override
public void dispatch(Store store, Object action, Middleware next) {
pdtyreus/conversation-kit
redux/src/main/java/com/conversationkit/redux/impl/ThunkMiddleware.java
// Path: redux/src/main/java/com/conversationkit/redux/Action.java // @FunctionalInterface // public interface Action { // public String getType(); // } // // Path: redux/src/main/java/com/conversationkit/redux/Middleware.java // @FunctionalInterface // /** // * A middleware is a higher-order function that composes a {@link Dispatcher} function to return a new dispatch function. It often turns async actions into actions. // * @see <a href="https://redux.js.org/glossary#middleware">https://redux.js.org/glossary#middleware</a> // */ // public interface Middleware<S> { // // void dispatch(Store<S> store, Object action, Middleware<S> next); // } // // Path: redux/src/main/java/com/conversationkit/redux/Store.java // public final class Store<S> implements Dispatcher { // // private static final Logger logger = Logger.getLogger(Store.class.getName()); // // private Map currentState; // // private final Reducer reducer; // private ActionDispatcher dispatcher; // private final Function<Map,S> typedStateBuilder; // private final Map<UUID, Consumer<Map<String, Object>>> consumers = new HashMap<>(); // // @FunctionalInterface // public interface ActionDispatcher { // // public void dispatch(Object action); // // } // // protected Store(Reducer reducer, Map initialState, Function<Map,S> stateBuilder, Middleware... middlewares) { // this.reducer = reducer; // this.currentState = initialState; // this.typedStateBuilder = stateBuilder; // // List<Middleware> allMiddlewares = new ArrayList(); // // for (Middleware mw : middlewares) { // allMiddlewares.add(mw); // } // //native middleware, last middleware in chain // allMiddlewares.add((store, action, next) -> { // Map nextState; // synchronized (Store.this) { // logger.fine(String.format("[REDUX] reducing action: %s", action.toString())); // if (!(action instanceof Action)) { // throw new RuntimeException("The action must be an instance of Action by the time it is received by the reducer. Action is " + action.getClass().getName()); // } // Action a = (Action) action; // nextState = store.reducer.reduce(a, currentState); // } // if (!nextState.equals(currentState)) { // logger.fine(String.format("[REDUX] state has changed after %s", action.toString())); // currentState = nextState; // consumers.values().parallelStream().forEach(e -> e.accept(currentState)); // } else { // logger.fine(String.format("[REDUX] state has not changed after %s", action.toString())); // } // }); // // logger.info(String.format("[REDUX] initializing redux store with %d middleware(s).", (allMiddlewares.size() - 1))); // // for (int i = allMiddlewares.size() - 1; i >= 0; i--) { // final Middleware mw = allMiddlewares.get(i); // logger.fine(String.format("[REDUX] chaining middleware (%d)", i)); // //this will be null for the native middleware only, which is last // final Middleware next = (i == allMiddlewares.size() - 1 ? null : allMiddlewares.get(i + 1)); // this.dispatcher = (action) -> { // mw.dispatch(Store.this, action, next); // }; // // } // } // // @Override // public S dispatch(Object action) { // logger.fine(String.format("[REDUX] dispatching action: %s", action.toString())); // // dispatcher.dispatch(action); // logger.finer(String.format("[REDUX] reduced state: %s", getState().toString())); // return getState(); // } // // public S getState() { // return typedStateBuilder.apply(currentState); // } // // public UUID subscribe(Consumer<Map<String, Object>> subscriber) { // UUID uuid = UUID.randomUUID(); // this.consumers.put(uuid, subscriber); // // return uuid; // } // // public void unsubscribe(UUID uuid) { // // this.consumers.remove(uuid); // } // }
import com.conversationkit.redux.Action; import com.conversationkit.redux.Middleware; import com.conversationkit.redux.Store; import java.util.function.Consumer;
/* * The MIT License * * Copyright 2019 Synclab Consulting LLC. * * 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.conversationkit.redux.impl; /** * Redux middleware that handles an async {@link Action} of type {@link Consumer} * @author pdtyreus */ public class ThunkMiddleware implements Middleware { @Override
// Path: redux/src/main/java/com/conversationkit/redux/Action.java // @FunctionalInterface // public interface Action { // public String getType(); // } // // Path: redux/src/main/java/com/conversationkit/redux/Middleware.java // @FunctionalInterface // /** // * A middleware is a higher-order function that composes a {@link Dispatcher} function to return a new dispatch function. It often turns async actions into actions. // * @see <a href="https://redux.js.org/glossary#middleware">https://redux.js.org/glossary#middleware</a> // */ // public interface Middleware<S> { // // void dispatch(Store<S> store, Object action, Middleware<S> next); // } // // Path: redux/src/main/java/com/conversationkit/redux/Store.java // public final class Store<S> implements Dispatcher { // // private static final Logger logger = Logger.getLogger(Store.class.getName()); // // private Map currentState; // // private final Reducer reducer; // private ActionDispatcher dispatcher; // private final Function<Map,S> typedStateBuilder; // private final Map<UUID, Consumer<Map<String, Object>>> consumers = new HashMap<>(); // // @FunctionalInterface // public interface ActionDispatcher { // // public void dispatch(Object action); // // } // // protected Store(Reducer reducer, Map initialState, Function<Map,S> stateBuilder, Middleware... middlewares) { // this.reducer = reducer; // this.currentState = initialState; // this.typedStateBuilder = stateBuilder; // // List<Middleware> allMiddlewares = new ArrayList(); // // for (Middleware mw : middlewares) { // allMiddlewares.add(mw); // } // //native middleware, last middleware in chain // allMiddlewares.add((store, action, next) -> { // Map nextState; // synchronized (Store.this) { // logger.fine(String.format("[REDUX] reducing action: %s", action.toString())); // if (!(action instanceof Action)) { // throw new RuntimeException("The action must be an instance of Action by the time it is received by the reducer. Action is " + action.getClass().getName()); // } // Action a = (Action) action; // nextState = store.reducer.reduce(a, currentState); // } // if (!nextState.equals(currentState)) { // logger.fine(String.format("[REDUX] state has changed after %s", action.toString())); // currentState = nextState; // consumers.values().parallelStream().forEach(e -> e.accept(currentState)); // } else { // logger.fine(String.format("[REDUX] state has not changed after %s", action.toString())); // } // }); // // logger.info(String.format("[REDUX] initializing redux store with %d middleware(s).", (allMiddlewares.size() - 1))); // // for (int i = allMiddlewares.size() - 1; i >= 0; i--) { // final Middleware mw = allMiddlewares.get(i); // logger.fine(String.format("[REDUX] chaining middleware (%d)", i)); // //this will be null for the native middleware only, which is last // final Middleware next = (i == allMiddlewares.size() - 1 ? null : allMiddlewares.get(i + 1)); // this.dispatcher = (action) -> { // mw.dispatch(Store.this, action, next); // }; // // } // } // // @Override // public S dispatch(Object action) { // logger.fine(String.format("[REDUX] dispatching action: %s", action.toString())); // // dispatcher.dispatch(action); // logger.finer(String.format("[REDUX] reduced state: %s", getState().toString())); // return getState(); // } // // public S getState() { // return typedStateBuilder.apply(currentState); // } // // public UUID subscribe(Consumer<Map<String, Object>> subscriber) { // UUID uuid = UUID.randomUUID(); // this.consumers.put(uuid, subscriber); // // return uuid; // } // // public void unsubscribe(UUID uuid) { // // this.consumers.remove(uuid); // } // } // Path: redux/src/main/java/com/conversationkit/redux/impl/ThunkMiddleware.java import com.conversationkit.redux.Action; import com.conversationkit.redux.Middleware; import com.conversationkit.redux.Store; import java.util.function.Consumer; /* * The MIT License * * Copyright 2019 Synclab Consulting LLC. * * 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.conversationkit.redux.impl; /** * Redux middleware that handles an async {@link Action} of type {@link Consumer} * @author pdtyreus */ public class ThunkMiddleware implements Middleware { @Override
public void dispatch(Store store, Object action, Middleware next) {
pdtyreus/conversation-kit
nlu-core/src/test/java/com/conversationkit/nlp/RegexIntentDetectorTest.java
// Path: nlu-core/src/main/java/com/conversationkit/model/IConversationIntent.java // public interface IConversationIntent { // /** // * @return unique ID for the intent. // */ // public String getIntentId(); // /** // * Slots are parameters collected from the user's input while detecting intent. As an example, a // * a slot might be a color. So in the user input, "Press the red button" the intent // * might be <code>PRESS_BUTTON</code> with a slot of <code>color</code> set to <code>red</code>. // * @return map of slot keys to slot values // */ // public Map<String,Object> getSlots(); // // public boolean getAllRequiredSlotsFilled(); // }
import com.conversationkit.model.IConversationIntent; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Optional; import org.junit.Test; import static org.junit.Assert.*;
package com.conversationkit.nlp; /** * * @author pdtyreus */ public class RegexIntentDetectorTest { @Test public void testDetectIntent() { System.out.println("detectIntent"); String sessionId = "0"; Map<String,String> intentMap = new HashMap(); intentMap.put("DUCK", "duck"); intentMap.put("GOOSE", "goose"); intentMap.put("YES", RegexIntentDetector.YES); intentMap.put("NO", RegexIntentDetector.NO); RegexIntentDetector instance = new RegexIntentDetector(intentMap);
// Path: nlu-core/src/main/java/com/conversationkit/model/IConversationIntent.java // public interface IConversationIntent { // /** // * @return unique ID for the intent. // */ // public String getIntentId(); // /** // * Slots are parameters collected from the user's input while detecting intent. As an example, a // * a slot might be a color. So in the user input, "Press the red button" the intent // * might be <code>PRESS_BUTTON</code> with a slot of <code>color</code> set to <code>red</code>. // * @return map of slot keys to slot values // */ // public Map<String,Object> getSlots(); // // public boolean getAllRequiredSlotsFilled(); // } // Path: nlu-core/src/test/java/com/conversationkit/nlp/RegexIntentDetectorTest.java import com.conversationkit.model.IConversationIntent; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Optional; import org.junit.Test; import static org.junit.Assert.*; package com.conversationkit.nlp; /** * * @author pdtyreus */ public class RegexIntentDetectorTest { @Test public void testDetectIntent() { System.out.println("detectIntent"); String sessionId = "0"; Map<String,String> intentMap = new HashMap(); intentMap.put("DUCK", "duck"); intentMap.put("GOOSE", "goose"); intentMap.put("YES", RegexIntentDetector.YES); intentMap.put("NO", RegexIntentDetector.NO); RegexIntentDetector instance = new RegexIntentDetector(intentMap);
Optional<IConversationIntent> result = instance.detectIntent("yes, please", "en_US", sessionId);
pdtyreus/conversation-kit
conversation-kit/src/main/java/com/conversationkit/impl/edge/DialogTreeEdge.java
// Path: conversation-kit/src/main/java/com/conversationkit/impl/node/DialogTreeNode.java // public class DialogTreeNode implements IConversationNode<DialogTreeEdge> { // // protected final List<String> messages; // protected final List<DialogTreeEdge> edges; // private final int id; // private final JsonObject metadata; // // /** // * Creates a node with the specified text. // * // * @param id the unique ID of the node from the underlying data store // * @param messages the text responses displayed to the user // */ // public DialogTreeNode(int id, List<String> messages) { // this.id = id; // this.edges = new ArrayList(); // this.metadata = new JsonObject(); // this.messages = messages; // } // // public List<String> getMessages() { // return messages; // } // // public List<String> getSuggestedResponses() { // List<String> suggestions = new ArrayList(); // for (DialogTreeEdge edge : edges) { // suggestions.add(edge.getPrompt()); // } // return suggestions; // } // // @Override // public Iterable<DialogTreeEdge> getEdges() { // return edges; // } // // @Override // public void addEdge(DialogTreeEdge edge) { // edges.add(edge); // } // // @Override // public int getId() { // return id; // } // // @Override // public JsonObject getMetadata() { // return metadata; // } // // // // } // // Path: nlu-core/src/main/java/com/conversationkit/model/IConversationIntent.java // public interface IConversationIntent { // /** // * @return unique ID for the intent. // */ // public String getIntentId(); // /** // * Slots are parameters collected from the user's input while detecting intent. As an example, a // * a slot might be a color. So in the user input, "Press the red button" the intent // * might be <code>PRESS_BUTTON</code> with a slot of <code>color</code> set to <code>red</code>. // * @return map of slot keys to slot values // */ // public Map<String,Object> getSlots(); // // public boolean getAllRequiredSlotsFilled(); // } // // Path: conversation-kit/src/main/java/com/conversationkit/model/IConversationState.java // public interface IConversationState <S extends IConversationState> extends Function<Map,S> { // /** // * @return the id of the node representing the last message sent to the user // */ // public Integer getCurrentNodeId(); // /** // * @return the number of consecutive times the engine has misunderstood the user's input. // */ // public Integer getMisunderstoodCount(); // /** // * @return a unique string representation of the current user // */ // public String getUserId(); // /** // * @return the current state as a Map // */ // public Map getStateAsMap(); // }
import com.conversationkit.impl.node.DialogTreeNode; import com.conversationkit.model.IConversationIntent; import com.conversationkit.model.IConversationState; import java.util.function.BiFunction;
/* * The MIT License * * Copyright 2016 Synclab Consulting LLC. * * 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.conversationkit.impl.edge; /** * A <code>DialogTreeEdge</code> is an implementation of * <code>IConversationEdge</code> that connects one * <code>IConversationNode</code> that is a question to the * <code>IConversationNode</code> matching the answer. * <p> * A Dialog Tree is a type of branching conversation often seen in adventure * video games. The user is given a choice of what to say and makes subsequent * choices until the conversation ends. The responses to the user are scripted * based on the choices made. Since the user can only answer questions using one * the supplied suggestions from the {@link DialogTreeNode}, this edge type does * a string match between the answer stored in the edge and the response * provided by the user. * * @author pdtyreus */ public class DialogTreeEdge extends ConversationEdge { private final String prompt; /** * Only an exact match for the answer stored in this node will cause the * conversion to advance to the endNode. * * @param prompt string value to match * @param intentId intent id * @param endNodeId next node id in the conversation */ public DialogTreeEdge(Integer endNodeId, String intentId, String prompt) { super(endNodeId, intentId); this.prompt = prompt; }
// Path: conversation-kit/src/main/java/com/conversationkit/impl/node/DialogTreeNode.java // public class DialogTreeNode implements IConversationNode<DialogTreeEdge> { // // protected final List<String> messages; // protected final List<DialogTreeEdge> edges; // private final int id; // private final JsonObject metadata; // // /** // * Creates a node with the specified text. // * // * @param id the unique ID of the node from the underlying data store // * @param messages the text responses displayed to the user // */ // public DialogTreeNode(int id, List<String> messages) { // this.id = id; // this.edges = new ArrayList(); // this.metadata = new JsonObject(); // this.messages = messages; // } // // public List<String> getMessages() { // return messages; // } // // public List<String> getSuggestedResponses() { // List<String> suggestions = new ArrayList(); // for (DialogTreeEdge edge : edges) { // suggestions.add(edge.getPrompt()); // } // return suggestions; // } // // @Override // public Iterable<DialogTreeEdge> getEdges() { // return edges; // } // // @Override // public void addEdge(DialogTreeEdge edge) { // edges.add(edge); // } // // @Override // public int getId() { // return id; // } // // @Override // public JsonObject getMetadata() { // return metadata; // } // // // // } // // Path: nlu-core/src/main/java/com/conversationkit/model/IConversationIntent.java // public interface IConversationIntent { // /** // * @return unique ID for the intent. // */ // public String getIntentId(); // /** // * Slots are parameters collected from the user's input while detecting intent. As an example, a // * a slot might be a color. So in the user input, "Press the red button" the intent // * might be <code>PRESS_BUTTON</code> with a slot of <code>color</code> set to <code>red</code>. // * @return map of slot keys to slot values // */ // public Map<String,Object> getSlots(); // // public boolean getAllRequiredSlotsFilled(); // } // // Path: conversation-kit/src/main/java/com/conversationkit/model/IConversationState.java // public interface IConversationState <S extends IConversationState> extends Function<Map,S> { // /** // * @return the id of the node representing the last message sent to the user // */ // public Integer getCurrentNodeId(); // /** // * @return the number of consecutive times the engine has misunderstood the user's input. // */ // public Integer getMisunderstoodCount(); // /** // * @return a unique string representation of the current user // */ // public String getUserId(); // /** // * @return the current state as a Map // */ // public Map getStateAsMap(); // } // Path: conversation-kit/src/main/java/com/conversationkit/impl/edge/DialogTreeEdge.java import com.conversationkit.impl.node.DialogTreeNode; import com.conversationkit.model.IConversationIntent; import com.conversationkit.model.IConversationState; import java.util.function.BiFunction; /* * The MIT License * * Copyright 2016 Synclab Consulting LLC. * * 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.conversationkit.impl.edge; /** * A <code>DialogTreeEdge</code> is an implementation of * <code>IConversationEdge</code> that connects one * <code>IConversationNode</code> that is a question to the * <code>IConversationNode</code> matching the answer. * <p> * A Dialog Tree is a type of branching conversation often seen in adventure * video games. The user is given a choice of what to say and makes subsequent * choices until the conversation ends. The responses to the user are scripted * based on the choices made. Since the user can only answer questions using one * the supplied suggestions from the {@link DialogTreeNode}, this edge type does * a string match between the answer stored in the edge and the response * provided by the user. * * @author pdtyreus */ public class DialogTreeEdge extends ConversationEdge { private final String prompt; /** * Only an exact match for the answer stored in this node will cause the * conversion to advance to the endNode. * * @param prompt string value to match * @param intentId intent id * @param endNodeId next node id in the conversation */ public DialogTreeEdge(Integer endNodeId, String intentId, String prompt) { super(endNodeId, intentId); this.prompt = prompt; }
public DialogTreeEdge(Integer endNodeId, String intentId, String prompt, BiFunction<IConversationIntent, IConversationState, Object>... sideEffects) {
pdtyreus/conversation-kit
conversation-kit/src/main/java/com/conversationkit/impl/edge/DialogTreeEdge.java
// Path: conversation-kit/src/main/java/com/conversationkit/impl/node/DialogTreeNode.java // public class DialogTreeNode implements IConversationNode<DialogTreeEdge> { // // protected final List<String> messages; // protected final List<DialogTreeEdge> edges; // private final int id; // private final JsonObject metadata; // // /** // * Creates a node with the specified text. // * // * @param id the unique ID of the node from the underlying data store // * @param messages the text responses displayed to the user // */ // public DialogTreeNode(int id, List<String> messages) { // this.id = id; // this.edges = new ArrayList(); // this.metadata = new JsonObject(); // this.messages = messages; // } // // public List<String> getMessages() { // return messages; // } // // public List<String> getSuggestedResponses() { // List<String> suggestions = new ArrayList(); // for (DialogTreeEdge edge : edges) { // suggestions.add(edge.getPrompt()); // } // return suggestions; // } // // @Override // public Iterable<DialogTreeEdge> getEdges() { // return edges; // } // // @Override // public void addEdge(DialogTreeEdge edge) { // edges.add(edge); // } // // @Override // public int getId() { // return id; // } // // @Override // public JsonObject getMetadata() { // return metadata; // } // // // // } // // Path: nlu-core/src/main/java/com/conversationkit/model/IConversationIntent.java // public interface IConversationIntent { // /** // * @return unique ID for the intent. // */ // public String getIntentId(); // /** // * Slots are parameters collected from the user's input while detecting intent. As an example, a // * a slot might be a color. So in the user input, "Press the red button" the intent // * might be <code>PRESS_BUTTON</code> with a slot of <code>color</code> set to <code>red</code>. // * @return map of slot keys to slot values // */ // public Map<String,Object> getSlots(); // // public boolean getAllRequiredSlotsFilled(); // } // // Path: conversation-kit/src/main/java/com/conversationkit/model/IConversationState.java // public interface IConversationState <S extends IConversationState> extends Function<Map,S> { // /** // * @return the id of the node representing the last message sent to the user // */ // public Integer getCurrentNodeId(); // /** // * @return the number of consecutive times the engine has misunderstood the user's input. // */ // public Integer getMisunderstoodCount(); // /** // * @return a unique string representation of the current user // */ // public String getUserId(); // /** // * @return the current state as a Map // */ // public Map getStateAsMap(); // }
import com.conversationkit.impl.node.DialogTreeNode; import com.conversationkit.model.IConversationIntent; import com.conversationkit.model.IConversationState; import java.util.function.BiFunction;
/* * The MIT License * * Copyright 2016 Synclab Consulting LLC. * * 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.conversationkit.impl.edge; /** * A <code>DialogTreeEdge</code> is an implementation of * <code>IConversationEdge</code> that connects one * <code>IConversationNode</code> that is a question to the * <code>IConversationNode</code> matching the answer. * <p> * A Dialog Tree is a type of branching conversation often seen in adventure * video games. The user is given a choice of what to say and makes subsequent * choices until the conversation ends. The responses to the user are scripted * based on the choices made. Since the user can only answer questions using one * the supplied suggestions from the {@link DialogTreeNode}, this edge type does * a string match between the answer stored in the edge and the response * provided by the user. * * @author pdtyreus */ public class DialogTreeEdge extends ConversationEdge { private final String prompt; /** * Only an exact match for the answer stored in this node will cause the * conversion to advance to the endNode. * * @param prompt string value to match * @param intentId intent id * @param endNodeId next node id in the conversation */ public DialogTreeEdge(Integer endNodeId, String intentId, String prompt) { super(endNodeId, intentId); this.prompt = prompt; }
// Path: conversation-kit/src/main/java/com/conversationkit/impl/node/DialogTreeNode.java // public class DialogTreeNode implements IConversationNode<DialogTreeEdge> { // // protected final List<String> messages; // protected final List<DialogTreeEdge> edges; // private final int id; // private final JsonObject metadata; // // /** // * Creates a node with the specified text. // * // * @param id the unique ID of the node from the underlying data store // * @param messages the text responses displayed to the user // */ // public DialogTreeNode(int id, List<String> messages) { // this.id = id; // this.edges = new ArrayList(); // this.metadata = new JsonObject(); // this.messages = messages; // } // // public List<String> getMessages() { // return messages; // } // // public List<String> getSuggestedResponses() { // List<String> suggestions = new ArrayList(); // for (DialogTreeEdge edge : edges) { // suggestions.add(edge.getPrompt()); // } // return suggestions; // } // // @Override // public Iterable<DialogTreeEdge> getEdges() { // return edges; // } // // @Override // public void addEdge(DialogTreeEdge edge) { // edges.add(edge); // } // // @Override // public int getId() { // return id; // } // // @Override // public JsonObject getMetadata() { // return metadata; // } // // // // } // // Path: nlu-core/src/main/java/com/conversationkit/model/IConversationIntent.java // public interface IConversationIntent { // /** // * @return unique ID for the intent. // */ // public String getIntentId(); // /** // * Slots are parameters collected from the user's input while detecting intent. As an example, a // * a slot might be a color. So in the user input, "Press the red button" the intent // * might be <code>PRESS_BUTTON</code> with a slot of <code>color</code> set to <code>red</code>. // * @return map of slot keys to slot values // */ // public Map<String,Object> getSlots(); // // public boolean getAllRequiredSlotsFilled(); // } // // Path: conversation-kit/src/main/java/com/conversationkit/model/IConversationState.java // public interface IConversationState <S extends IConversationState> extends Function<Map,S> { // /** // * @return the id of the node representing the last message sent to the user // */ // public Integer getCurrentNodeId(); // /** // * @return the number of consecutive times the engine has misunderstood the user's input. // */ // public Integer getMisunderstoodCount(); // /** // * @return a unique string representation of the current user // */ // public String getUserId(); // /** // * @return the current state as a Map // */ // public Map getStateAsMap(); // } // Path: conversation-kit/src/main/java/com/conversationkit/impl/edge/DialogTreeEdge.java import com.conversationkit.impl.node.DialogTreeNode; import com.conversationkit.model.IConversationIntent; import com.conversationkit.model.IConversationState; import java.util.function.BiFunction; /* * The MIT License * * Copyright 2016 Synclab Consulting LLC. * * 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.conversationkit.impl.edge; /** * A <code>DialogTreeEdge</code> is an implementation of * <code>IConversationEdge</code> that connects one * <code>IConversationNode</code> that is a question to the * <code>IConversationNode</code> matching the answer. * <p> * A Dialog Tree is a type of branching conversation often seen in adventure * video games. The user is given a choice of what to say and makes subsequent * choices until the conversation ends. The responses to the user are scripted * based on the choices made. Since the user can only answer questions using one * the supplied suggestions from the {@link DialogTreeNode}, this edge type does * a string match between the answer stored in the edge and the response * provided by the user. * * @author pdtyreus */ public class DialogTreeEdge extends ConversationEdge { private final String prompt; /** * Only an exact match for the answer stored in this node will cause the * conversion to advance to the endNode. * * @param prompt string value to match * @param intentId intent id * @param endNodeId next node id in the conversation */ public DialogTreeEdge(Integer endNodeId, String intentId, String prompt) { super(endNodeId, intentId); this.prompt = prompt; }
public DialogTreeEdge(Integer endNodeId, String intentId, String prompt, BiFunction<IConversationIntent, IConversationState, Object>... sideEffects) {
pdtyreus/conversation-kit
redux/src/main/java/com/conversationkit/redux/impl/CompletableFutureMiddleware.java
// Path: redux/src/main/java/com/conversationkit/redux/Action.java // @FunctionalInterface // public interface Action { // public String getType(); // } // // Path: redux/src/main/java/com/conversationkit/redux/Middleware.java // @FunctionalInterface // /** // * A middleware is a higher-order function that composes a {@link Dispatcher} function to return a new dispatch function. It often turns async actions into actions. // * @see <a href="https://redux.js.org/glossary#middleware">https://redux.js.org/glossary#middleware</a> // */ // public interface Middleware<S> { // // void dispatch(Store<S> store, Object action, Middleware<S> next); // } // // Path: redux/src/main/java/com/conversationkit/redux/Store.java // public final class Store<S> implements Dispatcher { // // private static final Logger logger = Logger.getLogger(Store.class.getName()); // // private Map currentState; // // private final Reducer reducer; // private ActionDispatcher dispatcher; // private final Function<Map,S> typedStateBuilder; // private final Map<UUID, Consumer<Map<String, Object>>> consumers = new HashMap<>(); // // @FunctionalInterface // public interface ActionDispatcher { // // public void dispatch(Object action); // // } // // protected Store(Reducer reducer, Map initialState, Function<Map,S> stateBuilder, Middleware... middlewares) { // this.reducer = reducer; // this.currentState = initialState; // this.typedStateBuilder = stateBuilder; // // List<Middleware> allMiddlewares = new ArrayList(); // // for (Middleware mw : middlewares) { // allMiddlewares.add(mw); // } // //native middleware, last middleware in chain // allMiddlewares.add((store, action, next) -> { // Map nextState; // synchronized (Store.this) { // logger.fine(String.format("[REDUX] reducing action: %s", action.toString())); // if (!(action instanceof Action)) { // throw new RuntimeException("The action must be an instance of Action by the time it is received by the reducer. Action is " + action.getClass().getName()); // } // Action a = (Action) action; // nextState = store.reducer.reduce(a, currentState); // } // if (!nextState.equals(currentState)) { // logger.fine(String.format("[REDUX] state has changed after %s", action.toString())); // currentState = nextState; // consumers.values().parallelStream().forEach(e -> e.accept(currentState)); // } else { // logger.fine(String.format("[REDUX] state has not changed after %s", action.toString())); // } // }); // // logger.info(String.format("[REDUX] initializing redux store with %d middleware(s).", (allMiddlewares.size() - 1))); // // for (int i = allMiddlewares.size() - 1; i >= 0; i--) { // final Middleware mw = allMiddlewares.get(i); // logger.fine(String.format("[REDUX] chaining middleware (%d)", i)); // //this will be null for the native middleware only, which is last // final Middleware next = (i == allMiddlewares.size() - 1 ? null : allMiddlewares.get(i + 1)); // this.dispatcher = (action) -> { // mw.dispatch(Store.this, action, next); // }; // // } // } // // @Override // public S dispatch(Object action) { // logger.fine(String.format("[REDUX] dispatching action: %s", action.toString())); // // dispatcher.dispatch(action); // logger.finer(String.format("[REDUX] reduced state: %s", getState().toString())); // return getState(); // } // // public S getState() { // return typedStateBuilder.apply(currentState); // } // // public UUID subscribe(Consumer<Map<String, Object>> subscriber) { // UUID uuid = UUID.randomUUID(); // this.consumers.put(uuid, subscriber); // // return uuid; // } // // public void unsubscribe(UUID uuid) { // // this.consumers.remove(uuid); // } // }
import com.conversationkit.redux.Action; import com.conversationkit.redux.Middleware; import com.conversationkit.redux.Store; import java.util.concurrent.Future; import java.util.logging.Level; import java.util.logging.Logger;
/* * The MIT License * * Copyright 2019 Synclab Consulting LLC. * * 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.conversationkit.redux.impl; /** * Redux middleware that handles an async {@link Action} of type {@link Future} * @author pdtyreus */ public class CompletableFutureMiddleware implements Middleware { private static final Logger logger = Logger.getLogger(CompletableFutureMiddleware.class.getName()); @Override
// Path: redux/src/main/java/com/conversationkit/redux/Action.java // @FunctionalInterface // public interface Action { // public String getType(); // } // // Path: redux/src/main/java/com/conversationkit/redux/Middleware.java // @FunctionalInterface // /** // * A middleware is a higher-order function that composes a {@link Dispatcher} function to return a new dispatch function. It often turns async actions into actions. // * @see <a href="https://redux.js.org/glossary#middleware">https://redux.js.org/glossary#middleware</a> // */ // public interface Middleware<S> { // // void dispatch(Store<S> store, Object action, Middleware<S> next); // } // // Path: redux/src/main/java/com/conversationkit/redux/Store.java // public final class Store<S> implements Dispatcher { // // private static final Logger logger = Logger.getLogger(Store.class.getName()); // // private Map currentState; // // private final Reducer reducer; // private ActionDispatcher dispatcher; // private final Function<Map,S> typedStateBuilder; // private final Map<UUID, Consumer<Map<String, Object>>> consumers = new HashMap<>(); // // @FunctionalInterface // public interface ActionDispatcher { // // public void dispatch(Object action); // // } // // protected Store(Reducer reducer, Map initialState, Function<Map,S> stateBuilder, Middleware... middlewares) { // this.reducer = reducer; // this.currentState = initialState; // this.typedStateBuilder = stateBuilder; // // List<Middleware> allMiddlewares = new ArrayList(); // // for (Middleware mw : middlewares) { // allMiddlewares.add(mw); // } // //native middleware, last middleware in chain // allMiddlewares.add((store, action, next) -> { // Map nextState; // synchronized (Store.this) { // logger.fine(String.format("[REDUX] reducing action: %s", action.toString())); // if (!(action instanceof Action)) { // throw new RuntimeException("The action must be an instance of Action by the time it is received by the reducer. Action is " + action.getClass().getName()); // } // Action a = (Action) action; // nextState = store.reducer.reduce(a, currentState); // } // if (!nextState.equals(currentState)) { // logger.fine(String.format("[REDUX] state has changed after %s", action.toString())); // currentState = nextState; // consumers.values().parallelStream().forEach(e -> e.accept(currentState)); // } else { // logger.fine(String.format("[REDUX] state has not changed after %s", action.toString())); // } // }); // // logger.info(String.format("[REDUX] initializing redux store with %d middleware(s).", (allMiddlewares.size() - 1))); // // for (int i = allMiddlewares.size() - 1; i >= 0; i--) { // final Middleware mw = allMiddlewares.get(i); // logger.fine(String.format("[REDUX] chaining middleware (%d)", i)); // //this will be null for the native middleware only, which is last // final Middleware next = (i == allMiddlewares.size() - 1 ? null : allMiddlewares.get(i + 1)); // this.dispatcher = (action) -> { // mw.dispatch(Store.this, action, next); // }; // // } // } // // @Override // public S dispatch(Object action) { // logger.fine(String.format("[REDUX] dispatching action: %s", action.toString())); // // dispatcher.dispatch(action); // logger.finer(String.format("[REDUX] reduced state: %s", getState().toString())); // return getState(); // } // // public S getState() { // return typedStateBuilder.apply(currentState); // } // // public UUID subscribe(Consumer<Map<String, Object>> subscriber) { // UUID uuid = UUID.randomUUID(); // this.consumers.put(uuid, subscriber); // // return uuid; // } // // public void unsubscribe(UUID uuid) { // // this.consumers.remove(uuid); // } // } // Path: redux/src/main/java/com/conversationkit/redux/impl/CompletableFutureMiddleware.java import com.conversationkit.redux.Action; import com.conversationkit.redux.Middleware; import com.conversationkit.redux.Store; import java.util.concurrent.Future; import java.util.logging.Level; import java.util.logging.Logger; /* * The MIT License * * Copyright 2019 Synclab Consulting LLC. * * 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.conversationkit.redux.impl; /** * Redux middleware that handles an async {@link Action} of type {@link Future} * @author pdtyreus */ public class CompletableFutureMiddleware implements Middleware { private static final Logger logger = Logger.getLogger(CompletableFutureMiddleware.class.getName()); @Override
public void dispatch(Store store, Object action, Middleware next) {
pdtyreus/conversation-kit
conversation-kit/src/main/java/com/conversationkit/impl/ConversationReducer.java
// Path: nlu-core/src/main/java/com/conversationkit/model/IConversationIntent.java // public interface IConversationIntent { // /** // * @return unique ID for the intent. // */ // public String getIntentId(); // /** // * Slots are parameters collected from the user's input while detecting intent. As an example, a // * a slot might be a color. So in the user input, "Press the red button" the intent // * might be <code>PRESS_BUTTON</code> with a slot of <code>color</code> set to <code>red</code>. // * @return map of slot keys to slot values // */ // public Map<String,Object> getSlots(); // // public boolean getAllRequiredSlotsFilled(); // } // // Path: conversation-kit/src/main/java/com/conversationkit/model/IConversationNode.java // public interface IConversationNode<E extends IConversationEdge> { // // /** // * Returns a list of outbound edges from the current node. One matching // * edge may be chosen to continue the conversation to the next node. // * @return outbound edges // */ // public Iterable<E> getEdges(); // // /** // * Adds an edge to the list of possible outbound edges. // * @param edge edge to add // */ // public void addEdge(E edge); // // /** // * Returns the unique identifier for this node. // * @return the node id // */ // public int getId(); // // /** // * Node metadata is any additional information the node may // * need to build platform-specific implementations of itself. The values stored // * in the metadata will be highly dependent on the final use case and is // * designed to be highly flexible. // * @return JSON metadata // */ // public JsonObject getMetadata(); // // } // // Path: redux/src/main/java/com/conversationkit/redux/Action.java // @FunctionalInterface // public interface Action { // public String getType(); // } // // Path: redux/src/main/java/com/conversationkit/redux/Reducer.java // @FunctionalInterface // /** // * Reducers calculate a new state given the previous state and an action. // * @see <a href="https://redux.js.org/glossary#reducer">https://redux.js.org/glossary#reducer</a> // */ // public interface Reducer { // // Map reduce(Action action, Map currentState); // }
import java.util.Map; import java.util.Optional; import java.util.Set; import java.util.logging.Level; import java.util.logging.Logger; import com.conversationkit.model.IConversationIntent; import com.conversationkit.model.IConversationNode; import com.conversationkit.redux.Action; import com.conversationkit.redux.Reducer; import java.util.Arrays; import java.util.HashMap; import java.util.HashSet;
/* * The MIT License * * Copyright 2019 Synclab Consulting LLC. * * 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.conversationkit.impl; /** * Redux reducer function to handle conversation-scoped actions. * * @author pdtyreus */ public class ConversationReducer implements Reducer { private static final Set<String> reservedKeys = new HashSet(Arrays.asList("intentId", "edgeId", "misunderstoodCount", "nodeId")); private static Logger logger = Logger.getLogger(ConversationReducer.class.getName()); @Override
// Path: nlu-core/src/main/java/com/conversationkit/model/IConversationIntent.java // public interface IConversationIntent { // /** // * @return unique ID for the intent. // */ // public String getIntentId(); // /** // * Slots are parameters collected from the user's input while detecting intent. As an example, a // * a slot might be a color. So in the user input, "Press the red button" the intent // * might be <code>PRESS_BUTTON</code> with a slot of <code>color</code> set to <code>red</code>. // * @return map of slot keys to slot values // */ // public Map<String,Object> getSlots(); // // public boolean getAllRequiredSlotsFilled(); // } // // Path: conversation-kit/src/main/java/com/conversationkit/model/IConversationNode.java // public interface IConversationNode<E extends IConversationEdge> { // // /** // * Returns a list of outbound edges from the current node. One matching // * edge may be chosen to continue the conversation to the next node. // * @return outbound edges // */ // public Iterable<E> getEdges(); // // /** // * Adds an edge to the list of possible outbound edges. // * @param edge edge to add // */ // public void addEdge(E edge); // // /** // * Returns the unique identifier for this node. // * @return the node id // */ // public int getId(); // // /** // * Node metadata is any additional information the node may // * need to build platform-specific implementations of itself. The values stored // * in the metadata will be highly dependent on the final use case and is // * designed to be highly flexible. // * @return JSON metadata // */ // public JsonObject getMetadata(); // // } // // Path: redux/src/main/java/com/conversationkit/redux/Action.java // @FunctionalInterface // public interface Action { // public String getType(); // } // // Path: redux/src/main/java/com/conversationkit/redux/Reducer.java // @FunctionalInterface // /** // * Reducers calculate a new state given the previous state and an action. // * @see <a href="https://redux.js.org/glossary#reducer">https://redux.js.org/glossary#reducer</a> // */ // public interface Reducer { // // Map reduce(Action action, Map currentState); // } // Path: conversation-kit/src/main/java/com/conversationkit/impl/ConversationReducer.java import java.util.Map; import java.util.Optional; import java.util.Set; import java.util.logging.Level; import java.util.logging.Logger; import com.conversationkit.model.IConversationIntent; import com.conversationkit.model.IConversationNode; import com.conversationkit.redux.Action; import com.conversationkit.redux.Reducer; import java.util.Arrays; import java.util.HashMap; import java.util.HashSet; /* * The MIT License * * Copyright 2019 Synclab Consulting LLC. * * 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.conversationkit.impl; /** * Redux reducer function to handle conversation-scoped actions. * * @author pdtyreus */ public class ConversationReducer implements Reducer { private static final Set<String> reservedKeys = new HashSet(Arrays.asList("intentId", "edgeId", "misunderstoodCount", "nodeId")); private static Logger logger = Logger.getLogger(ConversationReducer.class.getName()); @Override
public Map reduce(Action action, Map currentState) {
pdtyreus/conversation-kit
conversation-kit/src/main/java/com/conversationkit/impl/ConversationReducer.java
// Path: nlu-core/src/main/java/com/conversationkit/model/IConversationIntent.java // public interface IConversationIntent { // /** // * @return unique ID for the intent. // */ // public String getIntentId(); // /** // * Slots are parameters collected from the user's input while detecting intent. As an example, a // * a slot might be a color. So in the user input, "Press the red button" the intent // * might be <code>PRESS_BUTTON</code> with a slot of <code>color</code> set to <code>red</code>. // * @return map of slot keys to slot values // */ // public Map<String,Object> getSlots(); // // public boolean getAllRequiredSlotsFilled(); // } // // Path: conversation-kit/src/main/java/com/conversationkit/model/IConversationNode.java // public interface IConversationNode<E extends IConversationEdge> { // // /** // * Returns a list of outbound edges from the current node. One matching // * edge may be chosen to continue the conversation to the next node. // * @return outbound edges // */ // public Iterable<E> getEdges(); // // /** // * Adds an edge to the list of possible outbound edges. // * @param edge edge to add // */ // public void addEdge(E edge); // // /** // * Returns the unique identifier for this node. // * @return the node id // */ // public int getId(); // // /** // * Node metadata is any additional information the node may // * need to build platform-specific implementations of itself. The values stored // * in the metadata will be highly dependent on the final use case and is // * designed to be highly flexible. // * @return JSON metadata // */ // public JsonObject getMetadata(); // // } // // Path: redux/src/main/java/com/conversationkit/redux/Action.java // @FunctionalInterface // public interface Action { // public String getType(); // } // // Path: redux/src/main/java/com/conversationkit/redux/Reducer.java // @FunctionalInterface // /** // * Reducers calculate a new state given the previous state and an action. // * @see <a href="https://redux.js.org/glossary#reducer">https://redux.js.org/glossary#reducer</a> // */ // public interface Reducer { // // Map reduce(Action action, Map currentState); // }
import java.util.Map; import java.util.Optional; import java.util.Set; import java.util.logging.Level; import java.util.logging.Logger; import com.conversationkit.model.IConversationIntent; import com.conversationkit.model.IConversationNode; import com.conversationkit.redux.Action; import com.conversationkit.redux.Reducer; import java.util.Arrays; import java.util.HashMap; import java.util.HashSet;
/* * The MIT License * * Copyright 2019 Synclab Consulting LLC. * * 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.conversationkit.impl; /** * Redux reducer function to handle conversation-scoped actions. * * @author pdtyreus */ public class ConversationReducer implements Reducer { private static final Set<String> reservedKeys = new HashSet(Arrays.asList("intentId", "edgeId", "misunderstoodCount", "nodeId")); private static Logger logger = Logger.getLogger(ConversationReducer.class.getName()); @Override public Map reduce(Action action, Map currentState) { Map<String, Object> nextState = new HashMap(currentState); if (action instanceof ConversationAction) { ConversationAction conversationAction = (ConversationAction) action; switch (conversationAction.getActionType()) { case MESSAGE_RECEIVED: nextState.remove("intentId"); nextState.remove("edgeId"); return nextState; case SET_NODE_ID: nextState.remove("intentId"); nextState.remove("edgeId"); nextState.remove("misunderstoodCount"); nextState.put("nodeId", ((ConversationAction<String>) action).getPayload().get()); return nextState; case INTENT_UNDERSTANDING_SUCCEEDED: nextState.remove("misunderstoodCount");
// Path: nlu-core/src/main/java/com/conversationkit/model/IConversationIntent.java // public interface IConversationIntent { // /** // * @return unique ID for the intent. // */ // public String getIntentId(); // /** // * Slots are parameters collected from the user's input while detecting intent. As an example, a // * a slot might be a color. So in the user input, "Press the red button" the intent // * might be <code>PRESS_BUTTON</code> with a slot of <code>color</code> set to <code>red</code>. // * @return map of slot keys to slot values // */ // public Map<String,Object> getSlots(); // // public boolean getAllRequiredSlotsFilled(); // } // // Path: conversation-kit/src/main/java/com/conversationkit/model/IConversationNode.java // public interface IConversationNode<E extends IConversationEdge> { // // /** // * Returns a list of outbound edges from the current node. One matching // * edge may be chosen to continue the conversation to the next node. // * @return outbound edges // */ // public Iterable<E> getEdges(); // // /** // * Adds an edge to the list of possible outbound edges. // * @param edge edge to add // */ // public void addEdge(E edge); // // /** // * Returns the unique identifier for this node. // * @return the node id // */ // public int getId(); // // /** // * Node metadata is any additional information the node may // * need to build platform-specific implementations of itself. The values stored // * in the metadata will be highly dependent on the final use case and is // * designed to be highly flexible. // * @return JSON metadata // */ // public JsonObject getMetadata(); // // } // // Path: redux/src/main/java/com/conversationkit/redux/Action.java // @FunctionalInterface // public interface Action { // public String getType(); // } // // Path: redux/src/main/java/com/conversationkit/redux/Reducer.java // @FunctionalInterface // /** // * Reducers calculate a new state given the previous state and an action. // * @see <a href="https://redux.js.org/glossary#reducer">https://redux.js.org/glossary#reducer</a> // */ // public interface Reducer { // // Map reduce(Action action, Map currentState); // } // Path: conversation-kit/src/main/java/com/conversationkit/impl/ConversationReducer.java import java.util.Map; import java.util.Optional; import java.util.Set; import java.util.logging.Level; import java.util.logging.Logger; import com.conversationkit.model.IConversationIntent; import com.conversationkit.model.IConversationNode; import com.conversationkit.redux.Action; import com.conversationkit.redux.Reducer; import java.util.Arrays; import java.util.HashMap; import java.util.HashSet; /* * The MIT License * * Copyright 2019 Synclab Consulting LLC. * * 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.conversationkit.impl; /** * Redux reducer function to handle conversation-scoped actions. * * @author pdtyreus */ public class ConversationReducer implements Reducer { private static final Set<String> reservedKeys = new HashSet(Arrays.asList("intentId", "edgeId", "misunderstoodCount", "nodeId")); private static Logger logger = Logger.getLogger(ConversationReducer.class.getName()); @Override public Map reduce(Action action, Map currentState) { Map<String, Object> nextState = new HashMap(currentState); if (action instanceof ConversationAction) { ConversationAction conversationAction = (ConversationAction) action; switch (conversationAction.getActionType()) { case MESSAGE_RECEIVED: nextState.remove("intentId"); nextState.remove("edgeId"); return nextState; case SET_NODE_ID: nextState.remove("intentId"); nextState.remove("edgeId"); nextState.remove("misunderstoodCount"); nextState.put("nodeId", ((ConversationAction<String>) action).getPayload().get()); return nextState; case INTENT_UNDERSTANDING_SUCCEEDED: nextState.remove("misunderstoodCount");
IConversationIntent successfulIntent = ((ConversationAction<IConversationIntent>) action).getPayload().get();
pdtyreus/conversation-kit
conversation-kit/src/main/java/com/conversationkit/impl/ConversationReducer.java
// Path: nlu-core/src/main/java/com/conversationkit/model/IConversationIntent.java // public interface IConversationIntent { // /** // * @return unique ID for the intent. // */ // public String getIntentId(); // /** // * Slots are parameters collected from the user's input while detecting intent. As an example, a // * a slot might be a color. So in the user input, "Press the red button" the intent // * might be <code>PRESS_BUTTON</code> with a slot of <code>color</code> set to <code>red</code>. // * @return map of slot keys to slot values // */ // public Map<String,Object> getSlots(); // // public boolean getAllRequiredSlotsFilled(); // } // // Path: conversation-kit/src/main/java/com/conversationkit/model/IConversationNode.java // public interface IConversationNode<E extends IConversationEdge> { // // /** // * Returns a list of outbound edges from the current node. One matching // * edge may be chosen to continue the conversation to the next node. // * @return outbound edges // */ // public Iterable<E> getEdges(); // // /** // * Adds an edge to the list of possible outbound edges. // * @param edge edge to add // */ // public void addEdge(E edge); // // /** // * Returns the unique identifier for this node. // * @return the node id // */ // public int getId(); // // /** // * Node metadata is any additional information the node may // * need to build platform-specific implementations of itself. The values stored // * in the metadata will be highly dependent on the final use case and is // * designed to be highly flexible. // * @return JSON metadata // */ // public JsonObject getMetadata(); // // } // // Path: redux/src/main/java/com/conversationkit/redux/Action.java // @FunctionalInterface // public interface Action { // public String getType(); // } // // Path: redux/src/main/java/com/conversationkit/redux/Reducer.java // @FunctionalInterface // /** // * Reducers calculate a new state given the previous state and an action. // * @see <a href="https://redux.js.org/glossary#reducer">https://redux.js.org/glossary#reducer</a> // */ // public interface Reducer { // // Map reduce(Action action, Map currentState); // }
import java.util.Map; import java.util.Optional; import java.util.Set; import java.util.logging.Level; import java.util.logging.Logger; import com.conversationkit.model.IConversationIntent; import com.conversationkit.model.IConversationNode; import com.conversationkit.redux.Action; import com.conversationkit.redux.Reducer; import java.util.Arrays; import java.util.HashMap; import java.util.HashSet;
IConversationIntent successfulIntent = ((ConversationAction<IConversationIntent>) action).getPayload().get(); nextState.put("intentId", successfulIntent.getIntentId()); for (Map.Entry<String, Object> entry : successfulIntent.getSlots().entrySet()) { if (reservedKeys.contains(entry.getKey())) { logger.log(Level.WARNING, "Slot name {0} is reserved for conversation-kit internal functionality and may have unexpected consequences.", entry.getKey()); } nextState.put(entry.getKey(), entry.getValue()); } return nextState; case INTENT_UNDERSTANDING_PARTIAL: nextState.remove("misunderstoodCount"); IConversationIntent partialIntent = ((ConversationAction<IConversationIntent>) action).getPayload().get(); nextState.put("intentId", partialIntent.getIntentId()); for (Map.Entry<String, Object> entry : partialIntent.getSlots().entrySet()) { if (reservedKeys.contains(entry.getKey())) { logger.log(Level.WARNING, "Slot name {0} is reserved for conversation-kit internal functionality and may have unexpected consequences.", entry.getKey()); } nextState.put(entry.getKey(), entry.getValue()); } return nextState; case INTENT_UNDERSTANDING_FAILED: nextState.remove("intentId"); Integer misunderstoodCount = (Integer) nextState.get("misunderstoodCount"); if (misunderstoodCount == null) { misunderstoodCount = 0; } misunderstoodCount++; nextState.put("misunderstoodCount", misunderstoodCount); return nextState; case EDGE_MATCH_SUCCEEDED:
// Path: nlu-core/src/main/java/com/conversationkit/model/IConversationIntent.java // public interface IConversationIntent { // /** // * @return unique ID for the intent. // */ // public String getIntentId(); // /** // * Slots are parameters collected from the user's input while detecting intent. As an example, a // * a slot might be a color. So in the user input, "Press the red button" the intent // * might be <code>PRESS_BUTTON</code> with a slot of <code>color</code> set to <code>red</code>. // * @return map of slot keys to slot values // */ // public Map<String,Object> getSlots(); // // public boolean getAllRequiredSlotsFilled(); // } // // Path: conversation-kit/src/main/java/com/conversationkit/model/IConversationNode.java // public interface IConversationNode<E extends IConversationEdge> { // // /** // * Returns a list of outbound edges from the current node. One matching // * edge may be chosen to continue the conversation to the next node. // * @return outbound edges // */ // public Iterable<E> getEdges(); // // /** // * Adds an edge to the list of possible outbound edges. // * @param edge edge to add // */ // public void addEdge(E edge); // // /** // * Returns the unique identifier for this node. // * @return the node id // */ // public int getId(); // // /** // * Node metadata is any additional information the node may // * need to build platform-specific implementations of itself. The values stored // * in the metadata will be highly dependent on the final use case and is // * designed to be highly flexible. // * @return JSON metadata // */ // public JsonObject getMetadata(); // // } // // Path: redux/src/main/java/com/conversationkit/redux/Action.java // @FunctionalInterface // public interface Action { // public String getType(); // } // // Path: redux/src/main/java/com/conversationkit/redux/Reducer.java // @FunctionalInterface // /** // * Reducers calculate a new state given the previous state and an action. // * @see <a href="https://redux.js.org/glossary#reducer">https://redux.js.org/glossary#reducer</a> // */ // public interface Reducer { // // Map reduce(Action action, Map currentState); // } // Path: conversation-kit/src/main/java/com/conversationkit/impl/ConversationReducer.java import java.util.Map; import java.util.Optional; import java.util.Set; import java.util.logging.Level; import java.util.logging.Logger; import com.conversationkit.model.IConversationIntent; import com.conversationkit.model.IConversationNode; import com.conversationkit.redux.Action; import com.conversationkit.redux.Reducer; import java.util.Arrays; import java.util.HashMap; import java.util.HashSet; IConversationIntent successfulIntent = ((ConversationAction<IConversationIntent>) action).getPayload().get(); nextState.put("intentId", successfulIntent.getIntentId()); for (Map.Entry<String, Object> entry : successfulIntent.getSlots().entrySet()) { if (reservedKeys.contains(entry.getKey())) { logger.log(Level.WARNING, "Slot name {0} is reserved for conversation-kit internal functionality and may have unexpected consequences.", entry.getKey()); } nextState.put(entry.getKey(), entry.getValue()); } return nextState; case INTENT_UNDERSTANDING_PARTIAL: nextState.remove("misunderstoodCount"); IConversationIntent partialIntent = ((ConversationAction<IConversationIntent>) action).getPayload().get(); nextState.put("intentId", partialIntent.getIntentId()); for (Map.Entry<String, Object> entry : partialIntent.getSlots().entrySet()) { if (reservedKeys.contains(entry.getKey())) { logger.log(Level.WARNING, "Slot name {0} is reserved for conversation-kit internal functionality and may have unexpected consequences.", entry.getKey()); } nextState.put(entry.getKey(), entry.getValue()); } return nextState; case INTENT_UNDERSTANDING_FAILED: nextState.remove("intentId"); Integer misunderstoodCount = (Integer) nextState.get("misunderstoodCount"); if (misunderstoodCount == null) { misunderstoodCount = 0; } misunderstoodCount++; nextState.put("misunderstoodCount", misunderstoodCount); return nextState; case EDGE_MATCH_SUCCEEDED:
ConversationAction<IConversationNode> npsa = (ConversationAction<IConversationNode>) action;
b0noI/AIF2
src/main/java/io/aif/language/word/dict/WordPlaceHolderMapper.java
// Path: src/main/java/io/aif/language/common/IMapper.java // @FunctionalInterface // public interface IMapper<T, S> extends Function<T, S> { // // public S map(final T nestedList); // // @Override // default S apply(final T t) { // return map(t); // } // // default List<S> mapAll(final List<T> elements) { // return elements // .parallelStream() // .map(this) // .collect(Collectors.toList()); // } // // } // // Path: src/main/java/io/aif/language/common/ISearchable.java // public interface ISearchable<T, R> { // // public Optional<R> search(final T subject); // // } // // Path: src/main/java/io/aif/language/word/IWord.java // public interface IWord { // // public String getRootToken(); // // public Set<String> getAllTokens(); // // public Long getCount(); // // public int getTokenCount(String token); // // public static interface IWordPlaceholder { // // public IWord getWord(); // // public String getToken(); // // } // // }
import java.util.Collection; import java.util.List; import java.util.Optional; import java.util.stream.Collectors; import io.aif.language.common.IMapper; import io.aif.language.common.ISearchable; import io.aif.language.word.IWord;
package io.aif.language.word.dict; public class WordPlaceHolderMapper implements IMapper<Collection<String>, List<IWord.IWordPlaceholder>> {
// Path: src/main/java/io/aif/language/common/IMapper.java // @FunctionalInterface // public interface IMapper<T, S> extends Function<T, S> { // // public S map(final T nestedList); // // @Override // default S apply(final T t) { // return map(t); // } // // default List<S> mapAll(final List<T> elements) { // return elements // .parallelStream() // .map(this) // .collect(Collectors.toList()); // } // // } // // Path: src/main/java/io/aif/language/common/ISearchable.java // public interface ISearchable<T, R> { // // public Optional<R> search(final T subject); // // } // // Path: src/main/java/io/aif/language/word/IWord.java // public interface IWord { // // public String getRootToken(); // // public Set<String> getAllTokens(); // // public Long getCount(); // // public int getTokenCount(String token); // // public static interface IWordPlaceholder { // // public IWord getWord(); // // public String getToken(); // // } // // } // Path: src/main/java/io/aif/language/word/dict/WordPlaceHolderMapper.java import java.util.Collection; import java.util.List; import java.util.Optional; import java.util.stream.Collectors; import io.aif.language.common.IMapper; import io.aif.language.common.ISearchable; import io.aif.language.word.IWord; package io.aif.language.word.dict; public class WordPlaceHolderMapper implements IMapper<Collection<String>, List<IWord.IWordPlaceholder>> {
private final ISearchable<String, IWord> searchable;
b0noI/AIF2
src/test/unit/java/io/aif/language/word/dict/WordTest.java
// Path: src/main/java/io/aif/language/word/IWord.java // public interface IWord { // // public String getRootToken(); // // public Set<String> getAllTokens(); // // public Long getCount(); // // public int getTokenCount(String token); // // public static interface IWordPlaceholder { // // public IWord getWord(); // // public String getToken(); // // } // // }
import org.testng.annotations.Test; import java.util.Arrays; import java.util.Collection; import io.aif.language.word.IWord; import static org.testng.Assert.assertEquals;
package io.aif.language.word.dict; public class WordTest { private final String ROOT_TOKEN = "hey"; private Collection<String> TOKENS = Arrays.asList("hey", "hey", "hey", "heya", "freya.", "freya"); @Test(groups = "unit-tests") public void testGetRootToken() throws Exception {
// Path: src/main/java/io/aif/language/word/IWord.java // public interface IWord { // // public String getRootToken(); // // public Set<String> getAllTokens(); // // public Long getCount(); // // public int getTokenCount(String token); // // public static interface IWordPlaceholder { // // public IWord getWord(); // // public String getToken(); // // } // // } // Path: src/test/unit/java/io/aif/language/word/dict/WordTest.java import org.testng.annotations.Test; import java.util.Arrays; import java.util.Collection; import io.aif.language.word.IWord; import static org.testng.Assert.assertEquals; package io.aif.language.word.dict; public class WordTest { private final String ROOT_TOKEN = "hey"; private Collection<String> TOKENS = Arrays.asList("hey", "hey", "hey", "heya", "freya.", "freya"); @Test(groups = "unit-tests") public void testGetRootToken() throws Exception {
IWord word = new Word(ROOT_TOKEN, TOKENS, (long) TOKENS.size());
b0noI/AIF2
src/test/unit/java/io/aif/language/word/dict/WordPlaceHolderMapperTest.java
// Path: src/main/java/io/aif/language/word/IWord.java // public interface IWord { // // public String getRootToken(); // // public Set<String> getAllTokens(); // // public Long getCount(); // // public int getTokenCount(String token); // // public static interface IWordPlaceholder { // // public IWord getWord(); // // public String getToken(); // // } // // }
import org.testng.annotations.Test; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.HashSet; import java.util.List; import java.util.Set; import java.util.stream.Collectors; import io.aif.language.word.IWord; import static org.testng.Assert.assertNotSame;
package io.aif.language.word.dict; public class WordPlaceHolderMapperTest { @Test(groups = "unit-tests") public void testMap() throws Exception { Collection<String> inputTokens = Arrays.asList("I", "am", "from", "kandy", "land.", "And", "you?");
// Path: src/main/java/io/aif/language/word/IWord.java // public interface IWord { // // public String getRootToken(); // // public Set<String> getAllTokens(); // // public Long getCount(); // // public int getTokenCount(String token); // // public static interface IWordPlaceholder { // // public IWord getWord(); // // public String getToken(); // // } // // } // Path: src/test/unit/java/io/aif/language/word/dict/WordPlaceHolderMapperTest.java import org.testng.annotations.Test; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.HashSet; import java.util.List; import java.util.Set; import java.util.stream.Collectors; import io.aif.language.word.IWord; import static org.testng.Assert.assertNotSame; package io.aif.language.word.dict; public class WordPlaceHolderMapperTest { @Test(groups = "unit-tests") public void testMap() throws Exception { Collection<String> inputTokens = Arrays.asList("I", "am", "from", "kandy", "land.", "And", "you?");
Set<IWord> words = new HashSet<>();
b0noI/AIF2
src/test/unit/java/io/aif/language/token/separator/PredefinedTokenSeparatorExtractorTest.java
// Path: src/main/java/io/aif/language/common/settings/ISettings.java // public interface ISettings { // // @Deprecated // public ISettings SETTINGS = Guice.createInjector(new SettingsModule()).getInstance(ISettings.class); // // public String getVersion(); // // public int recommendedMinimumTokensInputCount(); // // public boolean useIsAlphabeticMethod(); // // public double thresholdPForSeparatorCharacterInSecondFilter(); // // public int minimalValuableTokenSizeForSentenceSplit(); // // public int minimumCharacterObservationsCountForMakingCharacterValuableDuringSentenceSplitting(); // // public double thresholdPFirstFilterForSeparatorCharacter(); // // public double splitterCharactersGrouperSearchStep(); // // public double splitterCharactersGrouperInitSearchPValue(); // // public double wordSetDictComparatorThreshold(); // // public double recursiveSubstringComparatorWeight(); // // public double simpleTokenComparatorWeight(); // // public double characterDensityComparatorWeight(); // // public String predefinedSeparators(); // }
import org.testng.annotations.Test; import java.util.Arrays; import java.util.List; import java.util.Optional; import io.aif.language.common.settings.ISettings; import static junit.framework.Assert.assertEquals; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when;
package io.aif.language.token.separator; public class PredefinedTokenSeparatorExtractorTest { @Test(groups = "unit-tests") public void testExtract() throws Exception { // input parameter final String inputText = null; // mocks
// Path: src/main/java/io/aif/language/common/settings/ISettings.java // public interface ISettings { // // @Deprecated // public ISettings SETTINGS = Guice.createInjector(new SettingsModule()).getInstance(ISettings.class); // // public String getVersion(); // // public int recommendedMinimumTokensInputCount(); // // public boolean useIsAlphabeticMethod(); // // public double thresholdPForSeparatorCharacterInSecondFilter(); // // public int minimalValuableTokenSizeForSentenceSplit(); // // public int minimumCharacterObservationsCountForMakingCharacterValuableDuringSentenceSplitting(); // // public double thresholdPFirstFilterForSeparatorCharacter(); // // public double splitterCharactersGrouperSearchStep(); // // public double splitterCharactersGrouperInitSearchPValue(); // // public double wordSetDictComparatorThreshold(); // // public double recursiveSubstringComparatorWeight(); // // public double simpleTokenComparatorWeight(); // // public double characterDensityComparatorWeight(); // // public String predefinedSeparators(); // } // Path: src/test/unit/java/io/aif/language/token/separator/PredefinedTokenSeparatorExtractorTest.java import org.testng.annotations.Test; import java.util.Arrays; import java.util.List; import java.util.Optional; import io.aif.language.common.settings.ISettings; import static junit.framework.Assert.assertEquals; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; package io.aif.language.token.separator; public class PredefinedTokenSeparatorExtractorTest { @Test(groups = "unit-tests") public void testExtract() throws Exception { // input parameter final String inputText = null; // mocks
ISettings settings = mock(ISettings.class);
b0noI/AIF2
src/main/java/io/aif/language/semantic/SemanticGraphBuilder.java
// Path: src/main/java/io/aif/language/semantic/weights/node/word/TokensCountBasedWeightCalculator.java // public class TokensCountBasedWeightCalculator implements IVertexWeightCalculator<IWord> { // // @Override // public Map<IWord, Double> calculate( // final Map<IWord, Map<IWord, Double>> vertex, final Map<IWord, Long> count) { // // return vertex.keySet() // .stream().collect(Collectors.toMap(node -> node, node -> calculate(node))); // } // // private Double calculate(final IWord node) { // final Set<String> mergedTokens = // node.getAllTokens().stream().map(String::toLowerCase).collect(Collectors.toSet()); // return 1.0 - 1.0 / (double) mergedTokens.size(); // } // // } // // Path: src/main/java/io/aif/language/word/IWord.java // public interface IWord { // // public String getRootToken(); // // public Set<String> getAllTokens(); // // public Long getCount(); // // public int getTokenCount(String token); // // public static interface IWordPlaceholder { // // public IWord getWord(); // // public String getToken(); // // } // // }
import java.util.Collection; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.stream.Collectors; import io.aif.associations.builder.AssociationGraph; import io.aif.associations.builder.AssociationsGraphBuilder; import io.aif.associations.calculators.vertex.IVertexWeightCalculator; import io.aif.language.semantic.weights.node.word.TokensCountBasedWeightCalculator; import io.aif.language.word.IWord;
package io.aif.language.semantic; public class SemanticGraphBuilder { private final AssociationsGraphBuilder<IWord> associationsGraphBuilder; public SemanticGraphBuilder() { associationsGraphBuilder = new AssociationsGraphBuilder<>(generateWeightCalculator()); } public AssociationGraph<IWord> build(final Collection<IWord.IWordPlaceholder> placeholders) { final List<IWord> words = placeholders.stream().map(IWord.IWordPlaceholder::getWord).collect(Collectors.toList()); return associationsGraphBuilder.buildGraph(words); } private Map<IVertexWeightCalculator<IWord>, Double> generateWeightCalculator() { final Map<IVertexWeightCalculator<IWord>, Double> calculators = new HashMap<>();
// Path: src/main/java/io/aif/language/semantic/weights/node/word/TokensCountBasedWeightCalculator.java // public class TokensCountBasedWeightCalculator implements IVertexWeightCalculator<IWord> { // // @Override // public Map<IWord, Double> calculate( // final Map<IWord, Map<IWord, Double>> vertex, final Map<IWord, Long> count) { // // return vertex.keySet() // .stream().collect(Collectors.toMap(node -> node, node -> calculate(node))); // } // // private Double calculate(final IWord node) { // final Set<String> mergedTokens = // node.getAllTokens().stream().map(String::toLowerCase).collect(Collectors.toSet()); // return 1.0 - 1.0 / (double) mergedTokens.size(); // } // // } // // Path: src/main/java/io/aif/language/word/IWord.java // public interface IWord { // // public String getRootToken(); // // public Set<String> getAllTokens(); // // public Long getCount(); // // public int getTokenCount(String token); // // public static interface IWordPlaceholder { // // public IWord getWord(); // // public String getToken(); // // } // // } // Path: src/main/java/io/aif/language/semantic/SemanticGraphBuilder.java import java.util.Collection; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.stream.Collectors; import io.aif.associations.builder.AssociationGraph; import io.aif.associations.builder.AssociationsGraphBuilder; import io.aif.associations.calculators.vertex.IVertexWeightCalculator; import io.aif.language.semantic.weights.node.word.TokensCountBasedWeightCalculator; import io.aif.language.word.IWord; package io.aif.language.semantic; public class SemanticGraphBuilder { private final AssociationsGraphBuilder<IWord> associationsGraphBuilder; public SemanticGraphBuilder() { associationsGraphBuilder = new AssociationsGraphBuilder<>(generateWeightCalculator()); } public AssociationGraph<IWord> build(final Collection<IWord.IWordPlaceholder> placeholders) { final List<IWord> words = placeholders.stream().map(IWord.IWordPlaceholder::getWord).collect(Collectors.toList()); return associationsGraphBuilder.buildGraph(words); } private Map<IVertexWeightCalculator<IWord>, Double> generateWeightCalculator() { final Map<IVertexWeightCalculator<IWord>, Double> calculators = new HashMap<>();
calculators.put(new TokensCountBasedWeightCalculator(), .85);
b0noI/AIF2
src/main/java/io/aif/language/sentence/splitters/HeuristicSentenceSplitter.java
// Path: src/main/java/io/aif/language/sentence/separators/extractors/ISeparatorExtractor.java // public interface ISeparatorExtractor extends IExtractor<List<String>, List<Character>> { // // public static enum Type { // PREDEFINED(new PredefinedSeparatorExtractor()), // PROBABILITY(new StatSeparatorExtractor()), // NON_ALPHABETIC_CHARACTERS_EXTRACTOR(new NonAlphabeticCharactersExtractor()); // // private final ISeparatorExtractor instance; // // private Type(final ISeparatorExtractor instance) { // this.instance = instance; // } // // public static ISeparatorExtractor getDefault() { // final ISettings settings = Guice.createInjector(new SettingsModule()).getInstance(ISettings.class); // return settings.useIsAlphabeticMethod() ? // Type.NON_ALPHABETIC_CHARACTERS_EXTRACTOR.getInstance() : // Type.PROBABILITY.getInstance(); // } // // public ISeparatorExtractor getInstance() { // return instance; // } // // } // // // } // // Path: src/main/java/io/aif/language/sentence/separators/groupers/ISeparatorsGrouper.java // public interface ISeparatorsGrouper { // // public List<Set<Character>> group(final List<String> tokens, final List<Character> splitters); // // public enum Type { // // PREDEFINED(new PredefinedGrouper()), // PROBABILITY(new StatGrouper()); // // private final ISeparatorsGrouper instance; // // Type(ISeparatorsGrouper instance) { // this.instance = instance; // } // // public ISeparatorsGrouper getInstance() { // return instance; // } // // } // // }
import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Set; import io.aif.language.sentence.separators.classificators.ISeparatorGroupsClassifier; import io.aif.language.sentence.separators.extractors.ISeparatorExtractor; import io.aif.language.sentence.separators.groupers.ISeparatorsGrouper;
package io.aif.language.sentence.splitters; class HeuristicSentenceSplitter extends AbstractSentenceSplitter { public HeuristicSentenceSplitter(final ISeparatorExtractor sentenceSeparatorExtractor,
// Path: src/main/java/io/aif/language/sentence/separators/extractors/ISeparatorExtractor.java // public interface ISeparatorExtractor extends IExtractor<List<String>, List<Character>> { // // public static enum Type { // PREDEFINED(new PredefinedSeparatorExtractor()), // PROBABILITY(new StatSeparatorExtractor()), // NON_ALPHABETIC_CHARACTERS_EXTRACTOR(new NonAlphabeticCharactersExtractor()); // // private final ISeparatorExtractor instance; // // private Type(final ISeparatorExtractor instance) { // this.instance = instance; // } // // public static ISeparatorExtractor getDefault() { // final ISettings settings = Guice.createInjector(new SettingsModule()).getInstance(ISettings.class); // return settings.useIsAlphabeticMethod() ? // Type.NON_ALPHABETIC_CHARACTERS_EXTRACTOR.getInstance() : // Type.PROBABILITY.getInstance(); // } // // public ISeparatorExtractor getInstance() { // return instance; // } // // } // // // } // // Path: src/main/java/io/aif/language/sentence/separators/groupers/ISeparatorsGrouper.java // public interface ISeparatorsGrouper { // // public List<Set<Character>> group(final List<String> tokens, final List<Character> splitters); // // public enum Type { // // PREDEFINED(new PredefinedGrouper()), // PROBABILITY(new StatGrouper()); // // private final ISeparatorsGrouper instance; // // Type(ISeparatorsGrouper instance) { // this.instance = instance; // } // // public ISeparatorsGrouper getInstance() { // return instance; // } // // } // // } // Path: src/main/java/io/aif/language/sentence/splitters/HeuristicSentenceSplitter.java import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Set; import io.aif.language.sentence.separators.classificators.ISeparatorGroupsClassifier; import io.aif.language.sentence.separators.extractors.ISeparatorExtractor; import io.aif.language.sentence.separators.groupers.ISeparatorsGrouper; package io.aif.language.sentence.splitters; class HeuristicSentenceSplitter extends AbstractSentenceSplitter { public HeuristicSentenceSplitter(final ISeparatorExtractor sentenceSeparatorExtractor,
final ISeparatorsGrouper sentenceSeparatorsGrouper,
b0noI/AIF2
src/main/java/io/aif/language/sentence/splitters/SimpleSentenceSplitter.java
// Path: src/main/java/io/aif/language/sentence/separators/extractors/ISeparatorExtractor.java // public interface ISeparatorExtractor extends IExtractor<List<String>, List<Character>> { // // public static enum Type { // PREDEFINED(new PredefinedSeparatorExtractor()), // PROBABILITY(new StatSeparatorExtractor()), // NON_ALPHABETIC_CHARACTERS_EXTRACTOR(new NonAlphabeticCharactersExtractor()); // // private final ISeparatorExtractor instance; // // private Type(final ISeparatorExtractor instance) { // this.instance = instance; // } // // public static ISeparatorExtractor getDefault() { // final ISettings settings = Guice.createInjector(new SettingsModule()).getInstance(ISettings.class); // return settings.useIsAlphabeticMethod() ? // Type.NON_ALPHABETIC_CHARACTERS_EXTRACTOR.getInstance() : // Type.PROBABILITY.getInstance(); // } // // public ISeparatorExtractor getInstance() { // return instance; // } // // } // // // } // // Path: src/main/java/io/aif/language/sentence/separators/groupers/ISeparatorsGrouper.java // public interface ISeparatorsGrouper { // // public List<Set<Character>> group(final List<String> tokens, final List<Character> splitters); // // public enum Type { // // PREDEFINED(new PredefinedGrouper()), // PROBABILITY(new StatGrouper()); // // private final ISeparatorsGrouper instance; // // Type(ISeparatorsGrouper instance) { // this.instance = instance; // } // // public ISeparatorsGrouper getInstance() { // return instance; // } // // } // // }
import com.google.common.annotations.VisibleForTesting; import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.Set; import io.aif.language.sentence.separators.classificators.ISeparatorGroupsClassifier; import io.aif.language.sentence.separators.extractors.ISeparatorExtractor; import io.aif.language.sentence.separators.groupers.ISeparatorsGrouper;
package io.aif.language.sentence.splitters; class SimpleSentenceSplitter extends AbstractSentenceSplitter { public SimpleSentenceSplitter(final ISeparatorExtractor sentenceSeparatorExtractor,
// Path: src/main/java/io/aif/language/sentence/separators/extractors/ISeparatorExtractor.java // public interface ISeparatorExtractor extends IExtractor<List<String>, List<Character>> { // // public static enum Type { // PREDEFINED(new PredefinedSeparatorExtractor()), // PROBABILITY(new StatSeparatorExtractor()), // NON_ALPHABETIC_CHARACTERS_EXTRACTOR(new NonAlphabeticCharactersExtractor()); // // private final ISeparatorExtractor instance; // // private Type(final ISeparatorExtractor instance) { // this.instance = instance; // } // // public static ISeparatorExtractor getDefault() { // final ISettings settings = Guice.createInjector(new SettingsModule()).getInstance(ISettings.class); // return settings.useIsAlphabeticMethod() ? // Type.NON_ALPHABETIC_CHARACTERS_EXTRACTOR.getInstance() : // Type.PROBABILITY.getInstance(); // } // // public ISeparatorExtractor getInstance() { // return instance; // } // // } // // // } // // Path: src/main/java/io/aif/language/sentence/separators/groupers/ISeparatorsGrouper.java // public interface ISeparatorsGrouper { // // public List<Set<Character>> group(final List<String> tokens, final List<Character> splitters); // // public enum Type { // // PREDEFINED(new PredefinedGrouper()), // PROBABILITY(new StatGrouper()); // // private final ISeparatorsGrouper instance; // // Type(ISeparatorsGrouper instance) { // this.instance = instance; // } // // public ISeparatorsGrouper getInstance() { // return instance; // } // // } // // } // Path: src/main/java/io/aif/language/sentence/splitters/SimpleSentenceSplitter.java import com.google.common.annotations.VisibleForTesting; import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.Set; import io.aif.language.sentence.separators.classificators.ISeparatorGroupsClassifier; import io.aif.language.sentence.separators.extractors.ISeparatorExtractor; import io.aif.language.sentence.separators.groupers.ISeparatorsGrouper; package io.aif.language.sentence.splitters; class SimpleSentenceSplitter extends AbstractSentenceSplitter { public SimpleSentenceSplitter(final ISeparatorExtractor sentenceSeparatorExtractor,
final ISeparatorsGrouper sentenceSeparatorsGrouper,
b0noI/AIF2
src/main/java/io/aif/language/sentence/separators/extractors/StatSeparatorExtractor.java
// Path: src/main/java/io/aif/language/common/IExtractor.java // @FunctionalInterface // public interface IExtractor<T1, T2> extends Function<T1, Optional<T2>> { // // public Optional<T2> extract(final T1 from); // // @Override // public default Optional<T2> apply(final T1 t1) { // return extract(t1); // } // // } // // Path: src/main/java/io/aif/language/common/settings/ISettings.java // public interface ISettings { // // @Deprecated // public ISettings SETTINGS = Guice.createInjector(new SettingsModule()).getInstance(ISettings.class); // // public String getVersion(); // // public int recommendedMinimumTokensInputCount(); // // public boolean useIsAlphabeticMethod(); // // public double thresholdPForSeparatorCharacterInSecondFilter(); // // public int minimalValuableTokenSizeForSentenceSplit(); // // public int minimumCharacterObservationsCountForMakingCharacterValuableDuringSentenceSplitting(); // // public double thresholdPFirstFilterForSeparatorCharacter(); // // public double splitterCharactersGrouperSearchStep(); // // public double splitterCharactersGrouperInitSearchPValue(); // // public double wordSetDictComparatorThreshold(); // // public double recursiveSubstringComparatorWeight(); // // public double simpleTokenComparatorWeight(); // // public double characterDensityComparatorWeight(); // // public String predefinedSeparators(); // } // // Path: src/main/java/io/aif/language/common/settings/SettingsModule.java // public class SettingsModule extends AbstractModule { // // @Override // protected void configure() { // bind(ISettings.class).toProvider(new PropertyBasedSettings.Provider()); // } // // }
import com.google.common.annotations.VisibleForTesting; import com.google.inject.Guice; import java.util.HashSet; import java.util.List; import java.util.Optional; import java.util.Set; import io.aif.language.common.IExtractor; import io.aif.language.common.VisibilityReducedForCLI; import io.aif.language.common.settings.ISettings; import io.aif.language.common.settings.SettingsModule; import io.aif.language.token.TokenMappers; import static java.lang.Character.isAlphabetic; import static java.util.Collections.emptyList; import static java.util.stream.Collectors.toList;
package io.aif.language.sentence.separators.extractors; // TODO(#263): StatSeparatorExtractor should be documented. // TODO(#265): Publish article about the algorithm of separators extractors. class StatSeparatorExtractor implements ISeparatorExtractor { private static final IExtractor<String, Character> END_CHARACTER_EXTRACTOR = token -> Optional.of(token.charAt(token.length() - 1)); private static final IExtractor<String, Character> CHARACTER_BEFORE_END_CHARACTER_EXTRACTOR = token -> Optional.of(token.charAt(token.length() - 2)); private static final IExtractor<String, Character> START_CHARACTER_EXTRACTOR = token -> Optional.of(token.charAt(0)); private static final IExtractor<String, Character> CHARACTER_AFTER_START_CHARACTER_EXTRACTOR = token -> Optional.of(token.charAt(1)); private static final StatDataExtractor END_CHARACTER_STAT_DATA_EXTRACTOR = new StatDataExtractor(END_CHARACTER_EXTRACTOR, CHARACTER_BEFORE_END_CHARACTER_EXTRACTOR); private static final StatDataExtractor START_CHARACTER_STAT_DATA_EXTRACTOR = new StatDataExtractor(START_CHARACTER_EXTRACTOR, CHARACTER_AFTER_START_CHARACTER_EXTRACTOR);
// Path: src/main/java/io/aif/language/common/IExtractor.java // @FunctionalInterface // public interface IExtractor<T1, T2> extends Function<T1, Optional<T2>> { // // public Optional<T2> extract(final T1 from); // // @Override // public default Optional<T2> apply(final T1 t1) { // return extract(t1); // } // // } // // Path: src/main/java/io/aif/language/common/settings/ISettings.java // public interface ISettings { // // @Deprecated // public ISettings SETTINGS = Guice.createInjector(new SettingsModule()).getInstance(ISettings.class); // // public String getVersion(); // // public int recommendedMinimumTokensInputCount(); // // public boolean useIsAlphabeticMethod(); // // public double thresholdPForSeparatorCharacterInSecondFilter(); // // public int minimalValuableTokenSizeForSentenceSplit(); // // public int minimumCharacterObservationsCountForMakingCharacterValuableDuringSentenceSplitting(); // // public double thresholdPFirstFilterForSeparatorCharacter(); // // public double splitterCharactersGrouperSearchStep(); // // public double splitterCharactersGrouperInitSearchPValue(); // // public double wordSetDictComparatorThreshold(); // // public double recursiveSubstringComparatorWeight(); // // public double simpleTokenComparatorWeight(); // // public double characterDensityComparatorWeight(); // // public String predefinedSeparators(); // } // // Path: src/main/java/io/aif/language/common/settings/SettingsModule.java // public class SettingsModule extends AbstractModule { // // @Override // protected void configure() { // bind(ISettings.class).toProvider(new PropertyBasedSettings.Provider()); // } // // } // Path: src/main/java/io/aif/language/sentence/separators/extractors/StatSeparatorExtractor.java import com.google.common.annotations.VisibleForTesting; import com.google.inject.Guice; import java.util.HashSet; import java.util.List; import java.util.Optional; import java.util.Set; import io.aif.language.common.IExtractor; import io.aif.language.common.VisibilityReducedForCLI; import io.aif.language.common.settings.ISettings; import io.aif.language.common.settings.SettingsModule; import io.aif.language.token.TokenMappers; import static java.lang.Character.isAlphabetic; import static java.util.Collections.emptyList; import static java.util.stream.Collectors.toList; package io.aif.language.sentence.separators.extractors; // TODO(#263): StatSeparatorExtractor should be documented. // TODO(#265): Publish article about the algorithm of separators extractors. class StatSeparatorExtractor implements ISeparatorExtractor { private static final IExtractor<String, Character> END_CHARACTER_EXTRACTOR = token -> Optional.of(token.charAt(token.length() - 1)); private static final IExtractor<String, Character> CHARACTER_BEFORE_END_CHARACTER_EXTRACTOR = token -> Optional.of(token.charAt(token.length() - 2)); private static final IExtractor<String, Character> START_CHARACTER_EXTRACTOR = token -> Optional.of(token.charAt(0)); private static final IExtractor<String, Character> CHARACTER_AFTER_START_CHARACTER_EXTRACTOR = token -> Optional.of(token.charAt(1)); private static final StatDataExtractor END_CHARACTER_STAT_DATA_EXTRACTOR = new StatDataExtractor(END_CHARACTER_EXTRACTOR, CHARACTER_BEFORE_END_CHARACTER_EXTRACTOR); private static final StatDataExtractor START_CHARACTER_STAT_DATA_EXTRACTOR = new StatDataExtractor(START_CHARACTER_EXTRACTOR, CHARACTER_AFTER_START_CHARACTER_EXTRACTOR);
private static final ISettings SETTINGS = Guice.createInjector(new SettingsModule()).getInstance(ISettings.class);
b0noI/AIF2
src/main/java/io/aif/language/sentence/separators/extractors/StatSeparatorExtractor.java
// Path: src/main/java/io/aif/language/common/IExtractor.java // @FunctionalInterface // public interface IExtractor<T1, T2> extends Function<T1, Optional<T2>> { // // public Optional<T2> extract(final T1 from); // // @Override // public default Optional<T2> apply(final T1 t1) { // return extract(t1); // } // // } // // Path: src/main/java/io/aif/language/common/settings/ISettings.java // public interface ISettings { // // @Deprecated // public ISettings SETTINGS = Guice.createInjector(new SettingsModule()).getInstance(ISettings.class); // // public String getVersion(); // // public int recommendedMinimumTokensInputCount(); // // public boolean useIsAlphabeticMethod(); // // public double thresholdPForSeparatorCharacterInSecondFilter(); // // public int minimalValuableTokenSizeForSentenceSplit(); // // public int minimumCharacterObservationsCountForMakingCharacterValuableDuringSentenceSplitting(); // // public double thresholdPFirstFilterForSeparatorCharacter(); // // public double splitterCharactersGrouperSearchStep(); // // public double splitterCharactersGrouperInitSearchPValue(); // // public double wordSetDictComparatorThreshold(); // // public double recursiveSubstringComparatorWeight(); // // public double simpleTokenComparatorWeight(); // // public double characterDensityComparatorWeight(); // // public String predefinedSeparators(); // } // // Path: src/main/java/io/aif/language/common/settings/SettingsModule.java // public class SettingsModule extends AbstractModule { // // @Override // protected void configure() { // bind(ISettings.class).toProvider(new PropertyBasedSettings.Provider()); // } // // }
import com.google.common.annotations.VisibleForTesting; import com.google.inject.Guice; import java.util.HashSet; import java.util.List; import java.util.Optional; import java.util.Set; import io.aif.language.common.IExtractor; import io.aif.language.common.VisibilityReducedForCLI; import io.aif.language.common.settings.ISettings; import io.aif.language.common.settings.SettingsModule; import io.aif.language.token.TokenMappers; import static java.lang.Character.isAlphabetic; import static java.util.Collections.emptyList; import static java.util.stream.Collectors.toList;
package io.aif.language.sentence.separators.extractors; // TODO(#263): StatSeparatorExtractor should be documented. // TODO(#265): Publish article about the algorithm of separators extractors. class StatSeparatorExtractor implements ISeparatorExtractor { private static final IExtractor<String, Character> END_CHARACTER_EXTRACTOR = token -> Optional.of(token.charAt(token.length() - 1)); private static final IExtractor<String, Character> CHARACTER_BEFORE_END_CHARACTER_EXTRACTOR = token -> Optional.of(token.charAt(token.length() - 2)); private static final IExtractor<String, Character> START_CHARACTER_EXTRACTOR = token -> Optional.of(token.charAt(0)); private static final IExtractor<String, Character> CHARACTER_AFTER_START_CHARACTER_EXTRACTOR = token -> Optional.of(token.charAt(1)); private static final StatDataExtractor END_CHARACTER_STAT_DATA_EXTRACTOR = new StatDataExtractor(END_CHARACTER_EXTRACTOR, CHARACTER_BEFORE_END_CHARACTER_EXTRACTOR); private static final StatDataExtractor START_CHARACTER_STAT_DATA_EXTRACTOR = new StatDataExtractor(START_CHARACTER_EXTRACTOR, CHARACTER_AFTER_START_CHARACTER_EXTRACTOR);
// Path: src/main/java/io/aif/language/common/IExtractor.java // @FunctionalInterface // public interface IExtractor<T1, T2> extends Function<T1, Optional<T2>> { // // public Optional<T2> extract(final T1 from); // // @Override // public default Optional<T2> apply(final T1 t1) { // return extract(t1); // } // // } // // Path: src/main/java/io/aif/language/common/settings/ISettings.java // public interface ISettings { // // @Deprecated // public ISettings SETTINGS = Guice.createInjector(new SettingsModule()).getInstance(ISettings.class); // // public String getVersion(); // // public int recommendedMinimumTokensInputCount(); // // public boolean useIsAlphabeticMethod(); // // public double thresholdPForSeparatorCharacterInSecondFilter(); // // public int minimalValuableTokenSizeForSentenceSplit(); // // public int minimumCharacterObservationsCountForMakingCharacterValuableDuringSentenceSplitting(); // // public double thresholdPFirstFilterForSeparatorCharacter(); // // public double splitterCharactersGrouperSearchStep(); // // public double splitterCharactersGrouperInitSearchPValue(); // // public double wordSetDictComparatorThreshold(); // // public double recursiveSubstringComparatorWeight(); // // public double simpleTokenComparatorWeight(); // // public double characterDensityComparatorWeight(); // // public String predefinedSeparators(); // } // // Path: src/main/java/io/aif/language/common/settings/SettingsModule.java // public class SettingsModule extends AbstractModule { // // @Override // protected void configure() { // bind(ISettings.class).toProvider(new PropertyBasedSettings.Provider()); // } // // } // Path: src/main/java/io/aif/language/sentence/separators/extractors/StatSeparatorExtractor.java import com.google.common.annotations.VisibleForTesting; import com.google.inject.Guice; import java.util.HashSet; import java.util.List; import java.util.Optional; import java.util.Set; import io.aif.language.common.IExtractor; import io.aif.language.common.VisibilityReducedForCLI; import io.aif.language.common.settings.ISettings; import io.aif.language.common.settings.SettingsModule; import io.aif.language.token.TokenMappers; import static java.lang.Character.isAlphabetic; import static java.util.Collections.emptyList; import static java.util.stream.Collectors.toList; package io.aif.language.sentence.separators.extractors; // TODO(#263): StatSeparatorExtractor should be documented. // TODO(#265): Publish article about the algorithm of separators extractors. class StatSeparatorExtractor implements ISeparatorExtractor { private static final IExtractor<String, Character> END_CHARACTER_EXTRACTOR = token -> Optional.of(token.charAt(token.length() - 1)); private static final IExtractor<String, Character> CHARACTER_BEFORE_END_CHARACTER_EXTRACTOR = token -> Optional.of(token.charAt(token.length() - 2)); private static final IExtractor<String, Character> START_CHARACTER_EXTRACTOR = token -> Optional.of(token.charAt(0)); private static final IExtractor<String, Character> CHARACTER_AFTER_START_CHARACTER_EXTRACTOR = token -> Optional.of(token.charAt(1)); private static final StatDataExtractor END_CHARACTER_STAT_DATA_EXTRACTOR = new StatDataExtractor(END_CHARACTER_EXTRACTOR, CHARACTER_BEFORE_END_CHARACTER_EXTRACTOR); private static final StatDataExtractor START_CHARACTER_STAT_DATA_EXTRACTOR = new StatDataExtractor(START_CHARACTER_EXTRACTOR, CHARACTER_AFTER_START_CHARACTER_EXTRACTOR);
private static final ISettings SETTINGS = Guice.createInjector(new SettingsModule()).getInstance(ISettings.class);
b0noI/AIF2
src/test/unit/java/io/aif/language/token/TokenizerTest.java
// Path: src/main/java/io/aif/language/common/IRegexpCooker.java // public interface IRegexpCooker { // // String prepareRegexp(final List<Character> characters); // } // // Path: src/main/java/io/aif/language/common/ISplitter.java // @FunctionalInterface // public interface ISplitter<T1, T2> extends Function<T1, List<T2>> { // // public List<T2> split(final T1 target); // // @Override // public default List<T2> apply(final T1 t1) { // return split(t1); // } // } // // Path: src/main/java/io/aif/language/token/separator/ITokenSeparatorExtractor.java // public interface ITokenSeparatorExtractor extends IExtractor<String, List<Character>> { // final ISettings settings = Guice.createInjector(new SettingsModule()).getInstance(ISettings.class); // public static enum Type { // // PREDEFINED(new PredefinedTokenSeparatorExtractor(settings)), // PROBABILITY(new ProbabilityBasedTokenSeparatorExtractor()); // // private final ITokenSeparatorExtractor instance; // // private Type(final ITokenSeparatorExtractor instance) { // this.instance = instance; // } // // public ITokenSeparatorExtractor getInstance() { // return instance; // } // // } // // }
import org.testng.annotations.Test; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.Optional; import io.aif.language.common.IRegexpCooker; import io.aif.language.common.ISplitter; import io.aif.language.token.separator.ITokenSeparatorExtractor; import static junit.framework.Assert.assertEquals; import static org.mockito.Matchers.eq; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when;
package io.aif.language.token; public class TokenizerTest { @Test(groups = "unit-tests") public void testExtract() throws Exception { final String inputText = "test1 test2\ntest3"; final List<String> expectedResult = new ArrayList<>(); expectedResult.add("test1"); expectedResult.add("test2"); expectedResult.add("test3");
// Path: src/main/java/io/aif/language/common/IRegexpCooker.java // public interface IRegexpCooker { // // String prepareRegexp(final List<Character> characters); // } // // Path: src/main/java/io/aif/language/common/ISplitter.java // @FunctionalInterface // public interface ISplitter<T1, T2> extends Function<T1, List<T2>> { // // public List<T2> split(final T1 target); // // @Override // public default List<T2> apply(final T1 t1) { // return split(t1); // } // } // // Path: src/main/java/io/aif/language/token/separator/ITokenSeparatorExtractor.java // public interface ITokenSeparatorExtractor extends IExtractor<String, List<Character>> { // final ISettings settings = Guice.createInjector(new SettingsModule()).getInstance(ISettings.class); // public static enum Type { // // PREDEFINED(new PredefinedTokenSeparatorExtractor(settings)), // PROBABILITY(new ProbabilityBasedTokenSeparatorExtractor()); // // private final ITokenSeparatorExtractor instance; // // private Type(final ITokenSeparatorExtractor instance) { // this.instance = instance; // } // // public ITokenSeparatorExtractor getInstance() { // return instance; // } // // } // // } // Path: src/test/unit/java/io/aif/language/token/TokenizerTest.java import org.testng.annotations.Test; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.Optional; import io.aif.language.common.IRegexpCooker; import io.aif.language.common.ISplitter; import io.aif.language.token.separator.ITokenSeparatorExtractor; import static junit.framework.Assert.assertEquals; import static org.mockito.Matchers.eq; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; package io.aif.language.token; public class TokenizerTest { @Test(groups = "unit-tests") public void testExtract() throws Exception { final String inputText = "test1 test2\ntest3"; final List<String> expectedResult = new ArrayList<>(); expectedResult.add("test1"); expectedResult.add("test2"); expectedResult.add("test3");
final ISplitter<String, String> tokenSeparatorExtractor = new Tokenizer();
b0noI/AIF2
src/test/unit/java/io/aif/language/token/TokenizerTest.java
// Path: src/main/java/io/aif/language/common/IRegexpCooker.java // public interface IRegexpCooker { // // String prepareRegexp(final List<Character> characters); // } // // Path: src/main/java/io/aif/language/common/ISplitter.java // @FunctionalInterface // public interface ISplitter<T1, T2> extends Function<T1, List<T2>> { // // public List<T2> split(final T1 target); // // @Override // public default List<T2> apply(final T1 t1) { // return split(t1); // } // } // // Path: src/main/java/io/aif/language/token/separator/ITokenSeparatorExtractor.java // public interface ITokenSeparatorExtractor extends IExtractor<String, List<Character>> { // final ISettings settings = Guice.createInjector(new SettingsModule()).getInstance(ISettings.class); // public static enum Type { // // PREDEFINED(new PredefinedTokenSeparatorExtractor(settings)), // PROBABILITY(new ProbabilityBasedTokenSeparatorExtractor()); // // private final ITokenSeparatorExtractor instance; // // private Type(final ITokenSeparatorExtractor instance) { // this.instance = instance; // } // // public ITokenSeparatorExtractor getInstance() { // return instance; // } // // } // // }
import org.testng.annotations.Test; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.Optional; import io.aif.language.common.IRegexpCooker; import io.aif.language.common.ISplitter; import io.aif.language.token.separator.ITokenSeparatorExtractor; import static junit.framework.Assert.assertEquals; import static org.mockito.Matchers.eq; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when;
package io.aif.language.token; public class TokenizerTest { @Test(groups = "unit-tests") public void testExtract() throws Exception { final String inputText = "test1 test2\ntest3"; final List<String> expectedResult = new ArrayList<>(); expectedResult.add("test1"); expectedResult.add("test2"); expectedResult.add("test3"); final ISplitter<String, String> tokenSeparatorExtractor = new Tokenizer(); final List<String> actualResult = tokenSeparatorExtractor.split(inputText); assertEquals(expectedResult, actualResult); } @Test(groups = "unit-tests") public void testConstructor() throws Exception {
// Path: src/main/java/io/aif/language/common/IRegexpCooker.java // public interface IRegexpCooker { // // String prepareRegexp(final List<Character> characters); // } // // Path: src/main/java/io/aif/language/common/ISplitter.java // @FunctionalInterface // public interface ISplitter<T1, T2> extends Function<T1, List<T2>> { // // public List<T2> split(final T1 target); // // @Override // public default List<T2> apply(final T1 t1) { // return split(t1); // } // } // // Path: src/main/java/io/aif/language/token/separator/ITokenSeparatorExtractor.java // public interface ITokenSeparatorExtractor extends IExtractor<String, List<Character>> { // final ISettings settings = Guice.createInjector(new SettingsModule()).getInstance(ISettings.class); // public static enum Type { // // PREDEFINED(new PredefinedTokenSeparatorExtractor(settings)), // PROBABILITY(new ProbabilityBasedTokenSeparatorExtractor()); // // private final ITokenSeparatorExtractor instance; // // private Type(final ITokenSeparatorExtractor instance) { // this.instance = instance; // } // // public ITokenSeparatorExtractor getInstance() { // return instance; // } // // } // // } // Path: src/test/unit/java/io/aif/language/token/TokenizerTest.java import org.testng.annotations.Test; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.Optional; import io.aif.language.common.IRegexpCooker; import io.aif.language.common.ISplitter; import io.aif.language.token.separator.ITokenSeparatorExtractor; import static junit.framework.Assert.assertEquals; import static org.mockito.Matchers.eq; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; package io.aif.language.token; public class TokenizerTest { @Test(groups = "unit-tests") public void testExtract() throws Exception { final String inputText = "test1 test2\ntest3"; final List<String> expectedResult = new ArrayList<>(); expectedResult.add("test1"); expectedResult.add("test2"); expectedResult.add("test3"); final ISplitter<String, String> tokenSeparatorExtractor = new Tokenizer(); final List<String> actualResult = tokenSeparatorExtractor.split(inputText); assertEquals(expectedResult, actualResult); } @Test(groups = "unit-tests") public void testConstructor() throws Exception {
final ITokenSeparatorExtractor mockTokenSeparatorExtractor =
b0noI/AIF2
src/test/unit/java/io/aif/language/token/TokenizerTest.java
// Path: src/main/java/io/aif/language/common/IRegexpCooker.java // public interface IRegexpCooker { // // String prepareRegexp(final List<Character> characters); // } // // Path: src/main/java/io/aif/language/common/ISplitter.java // @FunctionalInterface // public interface ISplitter<T1, T2> extends Function<T1, List<T2>> { // // public List<T2> split(final T1 target); // // @Override // public default List<T2> apply(final T1 t1) { // return split(t1); // } // } // // Path: src/main/java/io/aif/language/token/separator/ITokenSeparatorExtractor.java // public interface ITokenSeparatorExtractor extends IExtractor<String, List<Character>> { // final ISettings settings = Guice.createInjector(new SettingsModule()).getInstance(ISettings.class); // public static enum Type { // // PREDEFINED(new PredefinedTokenSeparatorExtractor(settings)), // PROBABILITY(new ProbabilityBasedTokenSeparatorExtractor()); // // private final ITokenSeparatorExtractor instance; // // private Type(final ITokenSeparatorExtractor instance) { // this.instance = instance; // } // // public ITokenSeparatorExtractor getInstance() { // return instance; // } // // } // // }
import org.testng.annotations.Test; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.Optional; import io.aif.language.common.IRegexpCooker; import io.aif.language.common.ISplitter; import io.aif.language.token.separator.ITokenSeparatorExtractor; import static junit.framework.Assert.assertEquals; import static org.mockito.Matchers.eq; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when;
final List<String> expectedResult = Arrays.asList(inputText); // creating instances final ISplitter<String, String> tokenSplitter = new Tokenizer(mockTokenSeparatorExtractor); // execution test final List<String> actualResult = tokenSplitter.split(inputText); // asserts assertEquals(expectedResult, actualResult); // verify verify(mockTokenSeparatorExtractor, times(1)).extract(inputText); } @Test(groups = "unit-tests") public void testSplitWhenSplittersFound() throws Exception { // input parameter final String inputText = "token1 token2"; // mocks final Optional<List<Character>> mockOptionalsSplitCharacters = Optional.of(Arrays.asList(' ', '\n')); final ITokenSeparatorExtractor mockTokenSeparatorExtractor = mock(ITokenSeparatorExtractor.class); when(mockTokenSeparatorExtractor.extract(eq(inputText))) .thenReturn(mockOptionalsSplitCharacters);
// Path: src/main/java/io/aif/language/common/IRegexpCooker.java // public interface IRegexpCooker { // // String prepareRegexp(final List<Character> characters); // } // // Path: src/main/java/io/aif/language/common/ISplitter.java // @FunctionalInterface // public interface ISplitter<T1, T2> extends Function<T1, List<T2>> { // // public List<T2> split(final T1 target); // // @Override // public default List<T2> apply(final T1 t1) { // return split(t1); // } // } // // Path: src/main/java/io/aif/language/token/separator/ITokenSeparatorExtractor.java // public interface ITokenSeparatorExtractor extends IExtractor<String, List<Character>> { // final ISettings settings = Guice.createInjector(new SettingsModule()).getInstance(ISettings.class); // public static enum Type { // // PREDEFINED(new PredefinedTokenSeparatorExtractor(settings)), // PROBABILITY(new ProbabilityBasedTokenSeparatorExtractor()); // // private final ITokenSeparatorExtractor instance; // // private Type(final ITokenSeparatorExtractor instance) { // this.instance = instance; // } // // public ITokenSeparatorExtractor getInstance() { // return instance; // } // // } // // } // Path: src/test/unit/java/io/aif/language/token/TokenizerTest.java import org.testng.annotations.Test; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.Optional; import io.aif.language.common.IRegexpCooker; import io.aif.language.common.ISplitter; import io.aif.language.token.separator.ITokenSeparatorExtractor; import static junit.framework.Assert.assertEquals; import static org.mockito.Matchers.eq; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; final List<String> expectedResult = Arrays.asList(inputText); // creating instances final ISplitter<String, String> tokenSplitter = new Tokenizer(mockTokenSeparatorExtractor); // execution test final List<String> actualResult = tokenSplitter.split(inputText); // asserts assertEquals(expectedResult, actualResult); // verify verify(mockTokenSeparatorExtractor, times(1)).extract(inputText); } @Test(groups = "unit-tests") public void testSplitWhenSplittersFound() throws Exception { // input parameter final String inputText = "token1 token2"; // mocks final Optional<List<Character>> mockOptionalsSplitCharacters = Optional.of(Arrays.asList(' ', '\n')); final ITokenSeparatorExtractor mockTokenSeparatorExtractor = mock(ITokenSeparatorExtractor.class); when(mockTokenSeparatorExtractor.extract(eq(inputText))) .thenReturn(mockOptionalsSplitCharacters);
final IRegexpCooker mockRegexpCooker = mock(IRegexpCooker.class);
b0noI/AIF2
src/main/java/io/aif/language/word/comparator/OptimisedMeshComparator.java
// Path: src/main/java/io/aif/language/token/comparator/ITokenComparator.java // public interface ITokenComparator { // // public static ITokenComparator createComposite(final Map<ITokenComparator, Double> comparators) { // return new CompositeTokenComparator(comparators); // } // // public static ITokenComparator defaultComparator() { // return Type.CHARACTER_DENSITY_COMPARATOR.getInstance(); // } // // public Double compare(String left, String right); // // public static enum Type { // SIMPLE_TOKEN_COMPARATOR(new SimpleTokenComparator()), // RECURSIVE_SUBSTRING_COMPARATOR(new RecursiveSubstringComparator()), // CHARACTER_DENSITY_COMPARATOR(new CharacterDensityTokenComparator()), // LEVENSHTEIN_COMPARATOR(new LevenshteinDistanceComparator()); // // private final ITokenComparator instance; // // private Type(final ITokenComparator instance) { // this.instance = instance; // } // // public ITokenComparator getInstance() { // return instance; // } // } // }
import java.util.Collection; import io.aif.language.token.comparator.ITokenComparator;
package io.aif.language.word.comparator; class OptimisedMeshComparator implements IGroupComparator { private static final double MAX_AVERAGE_LENGTH_DISTANCE = .5; private final IGroupComparator meshComparator;
// Path: src/main/java/io/aif/language/token/comparator/ITokenComparator.java // public interface ITokenComparator { // // public static ITokenComparator createComposite(final Map<ITokenComparator, Double> comparators) { // return new CompositeTokenComparator(comparators); // } // // public static ITokenComparator defaultComparator() { // return Type.CHARACTER_DENSITY_COMPARATOR.getInstance(); // } // // public Double compare(String left, String right); // // public static enum Type { // SIMPLE_TOKEN_COMPARATOR(new SimpleTokenComparator()), // RECURSIVE_SUBSTRING_COMPARATOR(new RecursiveSubstringComparator()), // CHARACTER_DENSITY_COMPARATOR(new CharacterDensityTokenComparator()), // LEVENSHTEIN_COMPARATOR(new LevenshteinDistanceComparator()); // // private final ITokenComparator instance; // // private Type(final ITokenComparator instance) { // this.instance = instance; // } // // public ITokenComparator getInstance() { // return instance; // } // } // } // Path: src/main/java/io/aif/language/word/comparator/OptimisedMeshComparator.java import java.util.Collection; import io.aif.language.token.comparator.ITokenComparator; package io.aif.language.word.comparator; class OptimisedMeshComparator implements IGroupComparator { private static final double MAX_AVERAGE_LENGTH_DISTANCE = .5; private final IGroupComparator meshComparator;
OptimisedMeshComparator(final ITokenComparator tokenComparator) {
b0noI/AIF2
src/main/java/io/aif/language/sentence/separators/extractors/ISeparatorExtractor.java
// Path: src/main/java/io/aif/language/common/IExtractor.java // @FunctionalInterface // public interface IExtractor<T1, T2> extends Function<T1, Optional<T2>> { // // public Optional<T2> extract(final T1 from); // // @Override // public default Optional<T2> apply(final T1 t1) { // return extract(t1); // } // // } // // Path: src/main/java/io/aif/language/common/settings/ISettings.java // public interface ISettings { // // @Deprecated // public ISettings SETTINGS = Guice.createInjector(new SettingsModule()).getInstance(ISettings.class); // // public String getVersion(); // // public int recommendedMinimumTokensInputCount(); // // public boolean useIsAlphabeticMethod(); // // public double thresholdPForSeparatorCharacterInSecondFilter(); // // public int minimalValuableTokenSizeForSentenceSplit(); // // public int minimumCharacterObservationsCountForMakingCharacterValuableDuringSentenceSplitting(); // // public double thresholdPFirstFilterForSeparatorCharacter(); // // public double splitterCharactersGrouperSearchStep(); // // public double splitterCharactersGrouperInitSearchPValue(); // // public double wordSetDictComparatorThreshold(); // // public double recursiveSubstringComparatorWeight(); // // public double simpleTokenComparatorWeight(); // // public double characterDensityComparatorWeight(); // // public String predefinedSeparators(); // } // // Path: src/main/java/io/aif/language/common/settings/SettingsModule.java // public class SettingsModule extends AbstractModule { // // @Override // protected void configure() { // bind(ISettings.class).toProvider(new PropertyBasedSettings.Provider()); // } // // }
import com.google.inject.Guice; import java.util.List; import io.aif.language.common.IExtractor; import io.aif.language.common.settings.ISettings; import io.aif.language.common.settings.SettingsModule;
package io.aif.language.sentence.separators.extractors; public interface ISeparatorExtractor extends IExtractor<List<String>, List<Character>> { public static enum Type { PREDEFINED(new PredefinedSeparatorExtractor()), PROBABILITY(new StatSeparatorExtractor()), NON_ALPHABETIC_CHARACTERS_EXTRACTOR(new NonAlphabeticCharactersExtractor()); private final ISeparatorExtractor instance; private Type(final ISeparatorExtractor instance) { this.instance = instance; } public static ISeparatorExtractor getDefault() {
// Path: src/main/java/io/aif/language/common/IExtractor.java // @FunctionalInterface // public interface IExtractor<T1, T2> extends Function<T1, Optional<T2>> { // // public Optional<T2> extract(final T1 from); // // @Override // public default Optional<T2> apply(final T1 t1) { // return extract(t1); // } // // } // // Path: src/main/java/io/aif/language/common/settings/ISettings.java // public interface ISettings { // // @Deprecated // public ISettings SETTINGS = Guice.createInjector(new SettingsModule()).getInstance(ISettings.class); // // public String getVersion(); // // public int recommendedMinimumTokensInputCount(); // // public boolean useIsAlphabeticMethod(); // // public double thresholdPForSeparatorCharacterInSecondFilter(); // // public int minimalValuableTokenSizeForSentenceSplit(); // // public int minimumCharacterObservationsCountForMakingCharacterValuableDuringSentenceSplitting(); // // public double thresholdPFirstFilterForSeparatorCharacter(); // // public double splitterCharactersGrouperSearchStep(); // // public double splitterCharactersGrouperInitSearchPValue(); // // public double wordSetDictComparatorThreshold(); // // public double recursiveSubstringComparatorWeight(); // // public double simpleTokenComparatorWeight(); // // public double characterDensityComparatorWeight(); // // public String predefinedSeparators(); // } // // Path: src/main/java/io/aif/language/common/settings/SettingsModule.java // public class SettingsModule extends AbstractModule { // // @Override // protected void configure() { // bind(ISettings.class).toProvider(new PropertyBasedSettings.Provider()); // } // // } // Path: src/main/java/io/aif/language/sentence/separators/extractors/ISeparatorExtractor.java import com.google.inject.Guice; import java.util.List; import io.aif.language.common.IExtractor; import io.aif.language.common.settings.ISettings; import io.aif.language.common.settings.SettingsModule; package io.aif.language.sentence.separators.extractors; public interface ISeparatorExtractor extends IExtractor<List<String>, List<Character>> { public static enum Type { PREDEFINED(new PredefinedSeparatorExtractor()), PROBABILITY(new StatSeparatorExtractor()), NON_ALPHABETIC_CHARACTERS_EXTRACTOR(new NonAlphabeticCharactersExtractor()); private final ISeparatorExtractor instance; private Type(final ISeparatorExtractor instance) { this.instance = instance; } public static ISeparatorExtractor getDefault() {
final ISettings settings = Guice.createInjector(new SettingsModule()).getInstance(ISettings.class);
b0noI/AIF2
src/main/java/io/aif/language/sentence/separators/extractors/ISeparatorExtractor.java
// Path: src/main/java/io/aif/language/common/IExtractor.java // @FunctionalInterface // public interface IExtractor<T1, T2> extends Function<T1, Optional<T2>> { // // public Optional<T2> extract(final T1 from); // // @Override // public default Optional<T2> apply(final T1 t1) { // return extract(t1); // } // // } // // Path: src/main/java/io/aif/language/common/settings/ISettings.java // public interface ISettings { // // @Deprecated // public ISettings SETTINGS = Guice.createInjector(new SettingsModule()).getInstance(ISettings.class); // // public String getVersion(); // // public int recommendedMinimumTokensInputCount(); // // public boolean useIsAlphabeticMethod(); // // public double thresholdPForSeparatorCharacterInSecondFilter(); // // public int minimalValuableTokenSizeForSentenceSplit(); // // public int minimumCharacterObservationsCountForMakingCharacterValuableDuringSentenceSplitting(); // // public double thresholdPFirstFilterForSeparatorCharacter(); // // public double splitterCharactersGrouperSearchStep(); // // public double splitterCharactersGrouperInitSearchPValue(); // // public double wordSetDictComparatorThreshold(); // // public double recursiveSubstringComparatorWeight(); // // public double simpleTokenComparatorWeight(); // // public double characterDensityComparatorWeight(); // // public String predefinedSeparators(); // } // // Path: src/main/java/io/aif/language/common/settings/SettingsModule.java // public class SettingsModule extends AbstractModule { // // @Override // protected void configure() { // bind(ISettings.class).toProvider(new PropertyBasedSettings.Provider()); // } // // }
import com.google.inject.Guice; import java.util.List; import io.aif.language.common.IExtractor; import io.aif.language.common.settings.ISettings; import io.aif.language.common.settings.SettingsModule;
package io.aif.language.sentence.separators.extractors; public interface ISeparatorExtractor extends IExtractor<List<String>, List<Character>> { public static enum Type { PREDEFINED(new PredefinedSeparatorExtractor()), PROBABILITY(new StatSeparatorExtractor()), NON_ALPHABETIC_CHARACTERS_EXTRACTOR(new NonAlphabeticCharactersExtractor()); private final ISeparatorExtractor instance; private Type(final ISeparatorExtractor instance) { this.instance = instance; } public static ISeparatorExtractor getDefault() {
// Path: src/main/java/io/aif/language/common/IExtractor.java // @FunctionalInterface // public interface IExtractor<T1, T2> extends Function<T1, Optional<T2>> { // // public Optional<T2> extract(final T1 from); // // @Override // public default Optional<T2> apply(final T1 t1) { // return extract(t1); // } // // } // // Path: src/main/java/io/aif/language/common/settings/ISettings.java // public interface ISettings { // // @Deprecated // public ISettings SETTINGS = Guice.createInjector(new SettingsModule()).getInstance(ISettings.class); // // public String getVersion(); // // public int recommendedMinimumTokensInputCount(); // // public boolean useIsAlphabeticMethod(); // // public double thresholdPForSeparatorCharacterInSecondFilter(); // // public int minimalValuableTokenSizeForSentenceSplit(); // // public int minimumCharacterObservationsCountForMakingCharacterValuableDuringSentenceSplitting(); // // public double thresholdPFirstFilterForSeparatorCharacter(); // // public double splitterCharactersGrouperSearchStep(); // // public double splitterCharactersGrouperInitSearchPValue(); // // public double wordSetDictComparatorThreshold(); // // public double recursiveSubstringComparatorWeight(); // // public double simpleTokenComparatorWeight(); // // public double characterDensityComparatorWeight(); // // public String predefinedSeparators(); // } // // Path: src/main/java/io/aif/language/common/settings/SettingsModule.java // public class SettingsModule extends AbstractModule { // // @Override // protected void configure() { // bind(ISettings.class).toProvider(new PropertyBasedSettings.Provider()); // } // // } // Path: src/main/java/io/aif/language/sentence/separators/extractors/ISeparatorExtractor.java import com.google.inject.Guice; import java.util.List; import io.aif.language.common.IExtractor; import io.aif.language.common.settings.ISettings; import io.aif.language.common.settings.SettingsModule; package io.aif.language.sentence.separators.extractors; public interface ISeparatorExtractor extends IExtractor<List<String>, List<Character>> { public static enum Type { PREDEFINED(new PredefinedSeparatorExtractor()), PROBABILITY(new StatSeparatorExtractor()), NON_ALPHABETIC_CHARACTERS_EXTRACTOR(new NonAlphabeticCharactersExtractor()); private final ISeparatorExtractor instance; private Type(final ISeparatorExtractor instance) { this.instance = instance; } public static ISeparatorExtractor getDefault() {
final ISettings settings = Guice.createInjector(new SettingsModule()).getInstance(ISettings.class);
b0noI/AIF2
src/test/unit/java/io/aif/language/semantic/weights/node/word/TokensCountBasedWeightCalculatorTest.java
// Path: src/main/java/io/aif/language/word/IWord.java // public interface IWord { // // public String getRootToken(); // // public Set<String> getAllTokens(); // // public Long getCount(); // // public int getTokenCount(String token); // // public static interface IWordPlaceholder { // // public IWord getWord(); // // public String getToken(); // // } // // }
import org.testng.annotations.Test; import java.util.Arrays; import java.util.HashSet; import io.aif.associations.calculators.vertex.IVertexWeightCalculator; import io.aif.language.word.IWord; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when;
package io.aif.language.semantic.weights.node.word; public class TokensCountBasedWeightCalculatorTest { @Test(groups = "unit-tests", enabled = false) public void testCalculateWeight() throws Exception { // input arguments
// Path: src/main/java/io/aif/language/word/IWord.java // public interface IWord { // // public String getRootToken(); // // public Set<String> getAllTokens(); // // public Long getCount(); // // public int getTokenCount(String token); // // public static interface IWordPlaceholder { // // public IWord getWord(); // // public String getToken(); // // } // // } // Path: src/test/unit/java/io/aif/language/semantic/weights/node/word/TokensCountBasedWeightCalculatorTest.java import org.testng.annotations.Test; import java.util.Arrays; import java.util.HashSet; import io.aif.associations.calculators.vertex.IVertexWeightCalculator; import io.aif.language.word.IWord; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; package io.aif.language.semantic.weights.node.word; public class TokensCountBasedWeightCalculatorTest { @Test(groups = "unit-tests", enabled = false) public void testCalculateWeight() throws Exception { // input arguments
final IWord inputWord = mock(IWord.class);
b0noI/AIF2
src/test/unit/java/io/aif/language/ner/noun/TitleCaseProperNounCalculatorTest.java
// Path: src/main/java/io/aif/language/word/IWord.java // public interface IWord { // // public String getRootToken(); // // public Set<String> getAllTokens(); // // public Long getCount(); // // public int getTokenCount(String token); // // public static interface IWordPlaceholder { // // public IWord getWord(); // // public String getToken(); // // } // // }
import org.testng.annotations.Test; import java.util.Arrays; import java.util.HashSet; import java.util.List; import io.aif.language.word.IWord; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; import static org.testng.Assert.assertEquals;
package io.aif.language.ner.noun; public class TitleCaseProperNounCalculatorTest { @Test(groups = "unit-tests") public void testCalculate() throws Exception { final List<String> tokens = Arrays.asList("Heya", "Hiya", "Hola", "deela"); final String rootToken = "Heya"; final double expected = .75d;
// Path: src/main/java/io/aif/language/word/IWord.java // public interface IWord { // // public String getRootToken(); // // public Set<String> getAllTokens(); // // public Long getCount(); // // public int getTokenCount(String token); // // public static interface IWordPlaceholder { // // public IWord getWord(); // // public String getToken(); // // } // // } // Path: src/test/unit/java/io/aif/language/ner/noun/TitleCaseProperNounCalculatorTest.java import org.testng.annotations.Test; import java.util.Arrays; import java.util.HashSet; import java.util.List; import io.aif.language.word.IWord; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; import static org.testng.Assert.assertEquals; package io.aif.language.ner.noun; public class TitleCaseProperNounCalculatorTest { @Test(groups = "unit-tests") public void testCalculate() throws Exception { final List<String> tokens = Arrays.asList("Heya", "Hiya", "Hola", "deela"); final String rootToken = "Heya"; final double expected = .75d;
final IWord mockWord = mock(IWord.class);
b0noI/AIF2
src/test/unit/java/io/aif/language/word/dict/RootTokenExtractorTest.java
// Path: src/main/java/io/aif/language/token/comparator/ITokenComparator.java // public interface ITokenComparator { // // public static ITokenComparator createComposite(final Map<ITokenComparator, Double> comparators) { // return new CompositeTokenComparator(comparators); // } // // public static ITokenComparator defaultComparator() { // return Type.CHARACTER_DENSITY_COMPARATOR.getInstance(); // } // // public Double compare(String left, String right); // // public static enum Type { // SIMPLE_TOKEN_COMPARATOR(new SimpleTokenComparator()), // RECURSIVE_SUBSTRING_COMPARATOR(new RecursiveSubstringComparator()), // CHARACTER_DENSITY_COMPARATOR(new CharacterDensityTokenComparator()), // LEVENSHTEIN_COMPARATOR(new LevenshteinDistanceComparator()); // // private final ITokenComparator instance; // // private Type(final ITokenComparator instance) { // this.instance = instance; // } // // public ITokenComparator getInstance() { // return instance; // } // } // }
import org.testng.annotations.Test; import java.util.Arrays; import java.util.List; import java.util.Optional; import io.aif.language.token.comparator.ITokenComparator; import static org.mockito.Mockito.any; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; import static org.testng.Assert.assertEquals; import static org.testng.Assert.assertTrue;
package io.aif.language.word.dict; public class RootTokenExtractorTest { @Test(groups = "unit-tests", enabled = false) public void testExtractEmptyInput() throws Exception { List<String> input = Arrays.asList(); Optional expected = Optional.empty();
// Path: src/main/java/io/aif/language/token/comparator/ITokenComparator.java // public interface ITokenComparator { // // public static ITokenComparator createComposite(final Map<ITokenComparator, Double> comparators) { // return new CompositeTokenComparator(comparators); // } // // public static ITokenComparator defaultComparator() { // return Type.CHARACTER_DENSITY_COMPARATOR.getInstance(); // } // // public Double compare(String left, String right); // // public static enum Type { // SIMPLE_TOKEN_COMPARATOR(new SimpleTokenComparator()), // RECURSIVE_SUBSTRING_COMPARATOR(new RecursiveSubstringComparator()), // CHARACTER_DENSITY_COMPARATOR(new CharacterDensityTokenComparator()), // LEVENSHTEIN_COMPARATOR(new LevenshteinDistanceComparator()); // // private final ITokenComparator instance; // // private Type(final ITokenComparator instance) { // this.instance = instance; // } // // public ITokenComparator getInstance() { // return instance; // } // } // } // Path: src/test/unit/java/io/aif/language/word/dict/RootTokenExtractorTest.java import org.testng.annotations.Test; import java.util.Arrays; import java.util.List; import java.util.Optional; import io.aif.language.token.comparator.ITokenComparator; import static org.mockito.Mockito.any; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; import static org.testng.Assert.assertEquals; import static org.testng.Assert.assertTrue; package io.aif.language.word.dict; public class RootTokenExtractorTest { @Test(groups = "unit-tests", enabled = false) public void testExtractEmptyInput() throws Exception { List<String> input = Arrays.asList(); Optional expected = Optional.empty();
ITokenComparator mockTokenComparator = mock(ITokenComparator.class);
b0noI/AIF2
src/test/unit/java/io/aif/language/fact/FactTest.java
// Path: src/main/java/io/aif/language/word/IWord.java // public interface IWord { // // public String getRootToken(); // // public Set<String> getAllTokens(); // // public Long getCount(); // // public int getTokenCount(String token); // // public static interface IWordPlaceholder { // // public IWord getWord(); // // public String getToken(); // // } // // }
import org.testng.annotations.Test; import java.util.Arrays; import java.util.Collections; import java.util.List; import io.aif.language.word.IWord; import static org.mockito.Mockito.mock; import static org.testng.Assert.assertEquals;
package io.aif.language.fact; public class FactTest { @Test(groups = "unit-tests") public void testFactConstruction() throws Exception { final IFact fact = new Fact(Collections.EMPTY_LIST, Collections.EMPTY_SET); assert true; } @Test(groups = "unit-tests") public void testGetSemanticSentence() throws Exception {
// Path: src/main/java/io/aif/language/word/IWord.java // public interface IWord { // // public String getRootToken(); // // public Set<String> getAllTokens(); // // public Long getCount(); // // public int getTokenCount(String token); // // public static interface IWordPlaceholder { // // public IWord getWord(); // // public String getToken(); // // } // // } // Path: src/test/unit/java/io/aif/language/fact/FactTest.java import org.testng.annotations.Test; import java.util.Arrays; import java.util.Collections; import java.util.List; import io.aif.language.word.IWord; import static org.mockito.Mockito.mock; import static org.testng.Assert.assertEquals; package io.aif.language.fact; public class FactTest { @Test(groups = "unit-tests") public void testFactConstruction() throws Exception { final IFact fact = new Fact(Collections.EMPTY_LIST, Collections.EMPTY_SET); assert true; } @Test(groups = "unit-tests") public void testGetSemanticSentence() throws Exception {
IWord semanticNodeMock1 = mock(IWord.class);
b0noI/AIF2
src/main/java/io/aif/language/fact/Factr.java
// Path: src/main/java/io/aif/language/ner/NERExtractor.java // public class NERExtractor { // // public Optional<Type> getNerType(final IWord word) { // return Arrays.stream(Type.values()) // .filter(nerType -> nerType.contains(word).isTrue()) // .findAny(); // } // } // // Path: src/main/java/io/aif/language/word/IWord.java // public interface IWord { // // public String getRootToken(); // // public Set<String> getAllTokens(); // // public Long getCount(); // // public int getTokenCount(String token); // // public static interface IWordPlaceholder { // // public IWord getWord(); // // public String getToken(); // // } // // }
import java.util.List; import java.util.Set; import java.util.stream.Collectors; import io.aif.graph.simple.ISimpleGraph; import io.aif.graph.simple.ISimpleGraphBuilder; import io.aif.language.ner.NERExtractor; import io.aif.language.word.IWord;
package io.aif.language.fact; public class Factr { private final IFactDefiner factDefiner;
// Path: src/main/java/io/aif/language/ner/NERExtractor.java // public class NERExtractor { // // public Optional<Type> getNerType(final IWord word) { // return Arrays.stream(Type.values()) // .filter(nerType -> nerType.contains(word).isTrue()) // .findAny(); // } // } // // Path: src/main/java/io/aif/language/word/IWord.java // public interface IWord { // // public String getRootToken(); // // public Set<String> getAllTokens(); // // public Long getCount(); // // public int getTokenCount(String token); // // public static interface IWordPlaceholder { // // public IWord getWord(); // // public String getToken(); // // } // // } // Path: src/main/java/io/aif/language/fact/Factr.java import java.util.List; import java.util.Set; import java.util.stream.Collectors; import io.aif.graph.simple.ISimpleGraph; import io.aif.graph.simple.ISimpleGraphBuilder; import io.aif.language.ner.NERExtractor; import io.aif.language.word.IWord; package io.aif.language.fact; public class Factr { private final IFactDefiner factDefiner;
private final NERExtractor nerExtractor;
b0noI/AIF2
src/main/java/io/aif/language/fact/Factr.java
// Path: src/main/java/io/aif/language/ner/NERExtractor.java // public class NERExtractor { // // public Optional<Type> getNerType(final IWord word) { // return Arrays.stream(Type.values()) // .filter(nerType -> nerType.contains(word).isTrue()) // .findAny(); // } // } // // Path: src/main/java/io/aif/language/word/IWord.java // public interface IWord { // // public String getRootToken(); // // public Set<String> getAllTokens(); // // public Long getCount(); // // public int getTokenCount(String token); // // public static interface IWordPlaceholder { // // public IWord getWord(); // // public String getToken(); // // } // // }
import java.util.List; import java.util.Set; import java.util.stream.Collectors; import io.aif.graph.simple.ISimpleGraph; import io.aif.graph.simple.ISimpleGraphBuilder; import io.aif.language.ner.NERExtractor; import io.aif.language.word.IWord;
package io.aif.language.fact; public class Factr { private final IFactDefiner factDefiner; private final NERExtractor nerExtractor; public Factr(final IFactDefiner definer, final NERExtractor nerExtractor) { this.factDefiner = definer; this.nerExtractor = nerExtractor; } public Factr() { this(IFactDefiner.Type.SIMPLE_FACT.getInstance(), new NERExtractor()); } // TODO Move this to the graph class. Should take a lambda to build graph private static ISimpleGraph<IFact> buildGraph(final List<IFact> facts) { final ISimpleGraphBuilder<IFact> g = ISimpleGraphBuilder.defaultBuilder(); for (int i = 0; i < facts.size(); i++) { IFact from = facts.get(i); for (int j = i + 1; j < facts.size(); j++) { IFact to = facts.get(j); if (hasCommonProperNoun(from, to)) g.connect(from, to); } } return g.build(); } // TODO move this as a method to fact class private static boolean hasCommonProperNoun(IFact sf1, IFact sf2) {
// Path: src/main/java/io/aif/language/ner/NERExtractor.java // public class NERExtractor { // // public Optional<Type> getNerType(final IWord word) { // return Arrays.stream(Type.values()) // .filter(nerType -> nerType.contains(word).isTrue()) // .findAny(); // } // } // // Path: src/main/java/io/aif/language/word/IWord.java // public interface IWord { // // public String getRootToken(); // // public Set<String> getAllTokens(); // // public Long getCount(); // // public int getTokenCount(String token); // // public static interface IWordPlaceholder { // // public IWord getWord(); // // public String getToken(); // // } // // } // Path: src/main/java/io/aif/language/fact/Factr.java import java.util.List; import java.util.Set; import java.util.stream.Collectors; import io.aif.graph.simple.ISimpleGraph; import io.aif.graph.simple.ISimpleGraphBuilder; import io.aif.language.ner.NERExtractor; import io.aif.language.word.IWord; package io.aif.language.fact; public class Factr { private final IFactDefiner factDefiner; private final NERExtractor nerExtractor; public Factr(final IFactDefiner definer, final NERExtractor nerExtractor) { this.factDefiner = definer; this.nerExtractor = nerExtractor; } public Factr() { this(IFactDefiner.Type.SIMPLE_FACT.getInstance(), new NERExtractor()); } // TODO Move this to the graph class. Should take a lambda to build graph private static ISimpleGraph<IFact> buildGraph(final List<IFact> facts) { final ISimpleGraphBuilder<IFact> g = ISimpleGraphBuilder.defaultBuilder(); for (int i = 0; i < facts.size(); i++) { IFact from = facts.get(i); for (int j = i + 1; j < facts.size(); j++) { IFact to = facts.get(j); if (hasCommonProperNoun(from, to)) g.connect(from, to); } } return g.build(); } // TODO move this as a method to fact class private static boolean hasCommonProperNoun(IFact sf1, IFact sf2) {
for (IWord node : sf1.getNamedEntities()) {
b0noI/AIF2
src/test/unit/java/io/aif/language/word/dict/DictTest.java
// Path: src/main/java/io/aif/language/common/ISearchable.java // public interface ISearchable<T, R> { // // public Optional<R> search(final T subject); // // } // // Path: src/main/java/io/aif/language/word/IWord.java // public interface IWord { // // public String getRootToken(); // // public Set<String> getAllTokens(); // // public Long getCount(); // // public int getTokenCount(String token); // // public static interface IWordPlaceholder { // // public IWord getWord(); // // public String getToken(); // // } // // }
import org.testng.annotations.BeforeTest; import org.testng.annotations.Test; import java.util.Arrays; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Optional; import java.util.Set; import java.util.stream.Collectors; import io.aif.language.common.IDict; import io.aif.language.common.ISearchable; import io.aif.language.word.IWord; import static org.testng.Assert.assertEquals; import static org.testng.Assert.assertFalse;
package io.aif.language.word.dict; public class DictTest { private Map<String, List<String>> fixture; @BeforeTest public void setUp() { fixture = new HashMap<>(); fixture.put("hey", Arrays.asList("hey", "heya", "freya")); fixture.put("see", Arrays.asList("see", "unseen", "foreseen", "seen", "seered")); fixture.put("back", Arrays.asList("back", "backward", "backer", "backpack")); } @Test(groups = "unit-tests", enabled = false) public void getWords() throws Exception {
// Path: src/main/java/io/aif/language/common/ISearchable.java // public interface ISearchable<T, R> { // // public Optional<R> search(final T subject); // // } // // Path: src/main/java/io/aif/language/word/IWord.java // public interface IWord { // // public String getRootToken(); // // public Set<String> getAllTokens(); // // public Long getCount(); // // public int getTokenCount(String token); // // public static interface IWordPlaceholder { // // public IWord getWord(); // // public String getToken(); // // } // // } // Path: src/test/unit/java/io/aif/language/word/dict/DictTest.java import org.testng.annotations.BeforeTest; import org.testng.annotations.Test; import java.util.Arrays; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Optional; import java.util.Set; import java.util.stream.Collectors; import io.aif.language.common.IDict; import io.aif.language.common.ISearchable; import io.aif.language.word.IWord; import static org.testng.Assert.assertEquals; import static org.testng.Assert.assertFalse; package io.aif.language.word.dict; public class DictTest { private Map<String, List<String>> fixture; @BeforeTest public void setUp() { fixture = new HashMap<>(); fixture.put("hey", Arrays.asList("hey", "heya", "freya")); fixture.put("see", Arrays.asList("see", "unseen", "foreseen", "seen", "seered")); fixture.put("back", Arrays.asList("back", "backward", "backer", "backpack")); } @Test(groups = "unit-tests", enabled = false) public void getWords() throws Exception {
Set<IWord> words = fixture
b0noI/AIF2
src/test/unit/java/io/aif/language/word/dict/DictTest.java
// Path: src/main/java/io/aif/language/common/ISearchable.java // public interface ISearchable<T, R> { // // public Optional<R> search(final T subject); // // } // // Path: src/main/java/io/aif/language/word/IWord.java // public interface IWord { // // public String getRootToken(); // // public Set<String> getAllTokens(); // // public Long getCount(); // // public int getTokenCount(String token); // // public static interface IWordPlaceholder { // // public IWord getWord(); // // public String getToken(); // // } // // }
import org.testng.annotations.BeforeTest; import org.testng.annotations.Test; import java.util.Arrays; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Optional; import java.util.Set; import java.util.stream.Collectors; import io.aif.language.common.IDict; import io.aif.language.common.ISearchable; import io.aif.language.word.IWord; import static org.testng.Assert.assertEquals; import static org.testng.Assert.assertFalse;
} @Test(groups = "unit-tests", enabled = false) public void getWords() throws Exception { Set<IWord> words = fixture .entrySet() .stream() .map(pair -> new Word( pair.getKey(), new HashSet<String>(pair.getValue()), (long) pair.getValue().size() ) ).collect(Collectors.toSet()); IDict dict = Dict.create(words); assertEquals(dict.getWords(), words); } @Test(groups = "unit-tests", enabled = false) public void testSearch() throws Exception { IWord expectedIWord = new Word("see", fixture.remove("see"), 0l); Set<IWord> words = fixture .entrySet() .stream() .map(pair -> new Word( pair.getKey(), new HashSet<String>(pair.getValue()), (long) pair.getValue().size() ) ).collect(Collectors.toSet()); words.add(expectedIWord);
// Path: src/main/java/io/aif/language/common/ISearchable.java // public interface ISearchable<T, R> { // // public Optional<R> search(final T subject); // // } // // Path: src/main/java/io/aif/language/word/IWord.java // public interface IWord { // // public String getRootToken(); // // public Set<String> getAllTokens(); // // public Long getCount(); // // public int getTokenCount(String token); // // public static interface IWordPlaceholder { // // public IWord getWord(); // // public String getToken(); // // } // // } // Path: src/test/unit/java/io/aif/language/word/dict/DictTest.java import org.testng.annotations.BeforeTest; import org.testng.annotations.Test; import java.util.Arrays; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Optional; import java.util.Set; import java.util.stream.Collectors; import io.aif.language.common.IDict; import io.aif.language.common.ISearchable; import io.aif.language.word.IWord; import static org.testng.Assert.assertEquals; import static org.testng.Assert.assertFalse; } @Test(groups = "unit-tests", enabled = false) public void getWords() throws Exception { Set<IWord> words = fixture .entrySet() .stream() .map(pair -> new Word( pair.getKey(), new HashSet<String>(pair.getValue()), (long) pair.getValue().size() ) ).collect(Collectors.toSet()); IDict dict = Dict.create(words); assertEquals(dict.getWords(), words); } @Test(groups = "unit-tests", enabled = false) public void testSearch() throws Exception { IWord expectedIWord = new Word("see", fixture.remove("see"), 0l); Set<IWord> words = fixture .entrySet() .stream() .map(pair -> new Word( pair.getKey(), new HashSet<String>(pair.getValue()), (long) pair.getValue().size() ) ).collect(Collectors.toSet()); words.add(expectedIWord);
ISearchable dict = Dict.create(words);
b0noI/AIF2
src/main/java/io/aif/language/word/dict/DictBuilder.java
// Path: src/main/java/io/aif/language/common/IDictBuilder.java // public interface IDictBuilder<T, R> { // // public IDict<R> build(final T tokens); // // } // // Path: src/main/java/io/aif/language/common/IGrouper.java // public interface IGrouper { // // public List<Set<String>> group(final Collection<String> tokens); // } // // Path: src/main/java/io/aif/language/common/IMapper.java // @FunctionalInterface // public interface IMapper<T, S> extends Function<T, S> { // // public S map(final T nestedList); // // @Override // default S apply(final T t) { // return map(t); // } // // default List<S> mapAll(final List<T> elements) { // return elements // .parallelStream() // .map(this) // .collect(Collectors.toList()); // } // // } // // Path: src/main/java/io/aif/language/token/comparator/ITokenComparator.java // public interface ITokenComparator { // // public static ITokenComparator createComposite(final Map<ITokenComparator, Double> comparators) { // return new CompositeTokenComparator(comparators); // } // // public static ITokenComparator defaultComparator() { // return Type.CHARACTER_DENSITY_COMPARATOR.getInstance(); // } // // public Double compare(String left, String right); // // public static enum Type { // SIMPLE_TOKEN_COMPARATOR(new SimpleTokenComparator()), // RECURSIVE_SUBSTRING_COMPARATOR(new RecursiveSubstringComparator()), // CHARACTER_DENSITY_COMPARATOR(new CharacterDensityTokenComparator()), // LEVENSHTEIN_COMPARATOR(new LevenshteinDistanceComparator()); // // private final ITokenComparator instance; // // private Type(final ITokenComparator instance) { // this.instance = instance; // } // // public ITokenComparator getInstance() { // return instance; // } // } // } // // Path: src/main/java/io/aif/language/word/IWord.java // public interface IWord { // // public String getRootToken(); // // public Set<String> getAllTokens(); // // public Long getCount(); // // public int getTokenCount(String token); // // public static interface IWordPlaceholder { // // public IWord getWord(); // // public String getToken(); // // } // // } // // Path: src/main/java/io/aif/language/word/comparator/IGroupComparator.java // public interface IGroupComparator { // // public static IGroupComparator createDefaultInstance(final ITokenComparator tokenComparator) { // return new OptimisedMeshComparator(tokenComparator); // } // // public double compare(final Collection<String> t1, final Collection<String> t2); // // public enum Type { // PRIMITIVE(new PrimitiveComparator()); // // private final IGroupComparator setComparator; // // Type(IGroupComparator setComparator) { // this.setComparator = setComparator; // } // // public IGroupComparator getComparator() { // return setComparator; // } // // } // // }
import org.apache.log4j.Logger; import java.util.Collection; import java.util.HashSet; import java.util.List; import java.util.Set; import java.util.stream.Collectors; import io.aif.language.common.IDict; import io.aif.language.common.IDictBuilder; import io.aif.language.common.IGrouper; import io.aif.language.common.IMapper; import io.aif.language.token.comparator.ITokenComparator; import io.aif.language.word.IWord; import io.aif.language.word.comparator.IGroupComparator;
package io.aif.language.word.dict; public class DictBuilder implements IDictBuilder<Collection<String>, IWord> { private static final Logger logger = Logger.getLogger(DictBuilder.class);
// Path: src/main/java/io/aif/language/common/IDictBuilder.java // public interface IDictBuilder<T, R> { // // public IDict<R> build(final T tokens); // // } // // Path: src/main/java/io/aif/language/common/IGrouper.java // public interface IGrouper { // // public List<Set<String>> group(final Collection<String> tokens); // } // // Path: src/main/java/io/aif/language/common/IMapper.java // @FunctionalInterface // public interface IMapper<T, S> extends Function<T, S> { // // public S map(final T nestedList); // // @Override // default S apply(final T t) { // return map(t); // } // // default List<S> mapAll(final List<T> elements) { // return elements // .parallelStream() // .map(this) // .collect(Collectors.toList()); // } // // } // // Path: src/main/java/io/aif/language/token/comparator/ITokenComparator.java // public interface ITokenComparator { // // public static ITokenComparator createComposite(final Map<ITokenComparator, Double> comparators) { // return new CompositeTokenComparator(comparators); // } // // public static ITokenComparator defaultComparator() { // return Type.CHARACTER_DENSITY_COMPARATOR.getInstance(); // } // // public Double compare(String left, String right); // // public static enum Type { // SIMPLE_TOKEN_COMPARATOR(new SimpleTokenComparator()), // RECURSIVE_SUBSTRING_COMPARATOR(new RecursiveSubstringComparator()), // CHARACTER_DENSITY_COMPARATOR(new CharacterDensityTokenComparator()), // LEVENSHTEIN_COMPARATOR(new LevenshteinDistanceComparator()); // // private final ITokenComparator instance; // // private Type(final ITokenComparator instance) { // this.instance = instance; // } // // public ITokenComparator getInstance() { // return instance; // } // } // } // // Path: src/main/java/io/aif/language/word/IWord.java // public interface IWord { // // public String getRootToken(); // // public Set<String> getAllTokens(); // // public Long getCount(); // // public int getTokenCount(String token); // // public static interface IWordPlaceholder { // // public IWord getWord(); // // public String getToken(); // // } // // } // // Path: src/main/java/io/aif/language/word/comparator/IGroupComparator.java // public interface IGroupComparator { // // public static IGroupComparator createDefaultInstance(final ITokenComparator tokenComparator) { // return new OptimisedMeshComparator(tokenComparator); // } // // public double compare(final Collection<String> t1, final Collection<String> t2); // // public enum Type { // PRIMITIVE(new PrimitiveComparator()); // // private final IGroupComparator setComparator; // // Type(IGroupComparator setComparator) { // this.setComparator = setComparator; // } // // public IGroupComparator getComparator() { // return setComparator; // } // // } // // } // Path: src/main/java/io/aif/language/word/dict/DictBuilder.java import org.apache.log4j.Logger; import java.util.Collection; import java.util.HashSet; import java.util.List; import java.util.Set; import java.util.stream.Collectors; import io.aif.language.common.IDict; import io.aif.language.common.IDictBuilder; import io.aif.language.common.IGrouper; import io.aif.language.common.IMapper; import io.aif.language.token.comparator.ITokenComparator; import io.aif.language.word.IWord; import io.aif.language.word.comparator.IGroupComparator; package io.aif.language.word.dict; public class DictBuilder implements IDictBuilder<Collection<String>, IWord> { private static final Logger logger = Logger.getLogger(DictBuilder.class);
private final IGrouper grouper;